#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
Buy Team as the SaaS account, and let that grant the Team tier (#7945)
ConnorYohb51e1e3e406f
diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.javaindex 6653b5ed08..de96ad7b36 100644--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java@@ -8,12 +8,14 @@ import java.util.concurrent.ConcurrentHashMap;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;+import org.springframework.context.annotation.Lazy;import org.springframework.stereotype.Service;import lombok.Getter;import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.LicenseServiceInterface;import stirling.software.common.service.PdfaLevelAServiceInterface;@Service@@ -53,6 +55,7 @@ public class EndpointConfiguration {private Map<String, DisableReason> groupDisableReasons = new ConcurrentHashMap<>();private Map<String, Set<String>> endpointAlternatives = new ConcurrentHashMap<>();private final boolean runningProOrHigher;+ @Autowired @Lazy private LicenseServiceInterface licenseService;private final boolean pdfUaAvailable;public EndpointConfiguration(@@ -129,6 +132,10 @@ public class EndpointConfiguration {if (endpoint.startsWith("/")) {endpoint = endpoint.substring(1);}+ if (endpointGroups.getOrDefault("enterprise", Set.of()).contains(endpoint)+ && !hasPaidPlan()) {+ return false;+ }// Rule 1: Explicit flag wins - if disabled via disableEndpoint(), stay disabledBoolean explicitStatus = endpointStatuses.get(endpoint);@@ -188,6 +195,7 @@ public class EndpointConfiguration {}public boolean isGroupEnabled(String group) {+ if ("enterprise".equals(group) && !hasPaidPlan()) return false;// Rule 1: If group is explicitly disabled, it stays disabledif (disabledGroups.contains(group)) {log.debug("isGroupEnabled('{}') -> false (explicitly disabled)", group);@@ -642,9 +650,6 @@ public class EndpointConfiguration {}}}- if (!runningProOrHigher) {- disableGroup("enterprise");- }if (!pdfUaAvailable) {disableEndpoint("pdf-to-ua");@@ -670,6 +675,10 @@ public class EndpointConfiguration {.collect(java.util.stream.Collectors.toSet());}+ private boolean hasPaidPlan() {+ return licenseService == null ? runningProOrHigher : licenseService.isRunningProOrHigher();+ }+private boolean isToolGroup(String group) {return "qpdf".equals(group)|| "OCRmyPDF".equals(group)diff --git a/app/common/src/main/java/stirling/software/common/service/PdfMetadataService.java b/app/common/src/main/java/stirling/software/common/service/PdfMetadataService.javaindex aa521bf942..cbf63d143a 100644--- a/app/common/src/main/java/stirling/software/common/service/PdfMetadataService.java+++ b/app/common/src/main/java/stirling/software/common/service/PdfMetadataService.java@@ -26,6 +26,9 @@ public class PdfMetadataService {private final UserServiceInterface userService;private final boolean runningProOrHigher;+ @Autowired(required = false)+ private LicenseServiceInterface licenseService;+public PdfMetadataService(ApplicationProperties applicationProperties,@Qualifier("StirlingPDFLabel") String stirlingPDFLabel,@@ -114,6 +117,10 @@ public class PdfMetadataService {.build();}+ private boolean hasPaidPlan() {+ return licenseService == null ? runningProOrHigher : licenseService.isRunningProOrHigher();+ }+private void setNewDocumentMetadata(PDDocument pdf, PdfMetadata pdfMetadata) {String creator = stirlingPDFLabel;@@ -123,7 +130,7 @@ public class PdfMetadataService {.getProFeatures().getCustomMetadata().isAutoUpdateMetadata()- && runningProOrHigher) {+ && hasPaidPlan()) {creator =applicationProperties@@ -164,7 +171,7 @@ public class PdfMetadataService {.getProFeatures().getCustomMetadata().isAutoUpdateMetadata()- && runningProOrHigher) {+ && hasPaidPlan()) {author =applicationProperties.getPremium()diff --git a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.javaindex 7064c7695d..be9f1cb149 100644--- a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java+++ b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java@@ -478,7 +478,7 @@ class EndpointConfigurationGapTest {@DisplayName("non-pro build disables the enterprise group")void nonProDisablesEnterprise() {EndpointConfiguration config = build(false);- assertTrue(config.getDisabledGroups().contains("enterprise"));+ assertFalse(config.isGroupEnabled("enterprise"));}@Testdiff --git a/app/common/src/test/java/stirling/software/common/service/PdfMetadataServiceTest.java b/app/common/src/test/java/stirling/software/common/service/PdfMetadataServiceTest.javaindex 6519d667a0..e01fd8ab80 100644--- a/app/common/src/test/java/stirling/software/common/service/PdfMetadataServiceTest.java+++ b/app/common/src/test/java/stirling/software/common/service/PdfMetadataServiceTest.java@@ -27,6 +27,32 @@ import stirling.software.common.model.PdfMetadata;class PdfMetadataServiceTest {+ @Test+ void teamPromotionAndRevocationChangeWrittenMetadataWithoutRestart() throws Exception {+ ApplicationProperties properties = new ApplicationProperties();+ CustomMetadata metadata = properties.getPremium().getProFeatures().getCustomMetadata();+ metadata.setAutoUpdateMetadata(true);+ metadata.setAuthor("Our organisation");+ metadata.setCreator("Our editor");+ PdfMetadataService service = new PdfMetadataService(properties, "Stirling", false, null);+ LicenseServiceInterface licence = mock(LicenseServiceInterface.class);+ org.springframework.test.util.ReflectionTestUtils.setField(+ service, "licenseService", licence);+ for (boolean paid : new boolean[] {false, true, false}) {+ when(licence.isRunningProOrHigher()).thenReturn(paid);+ try (PDDocument pdf = new PDDocument()) {+ service.setMetadataToPdf(+ pdf, PdfMetadata.builder().author("Original").build(), true);+ assertEquals(+ paid ? "Our organisation" : "Original",+ pdf.getDocumentInformation().getAuthor());+ assertEquals(+ paid ? "Our editor" : "Stirling",+ pdf.getDocumentInformation().getCreator());+ }+ }+ }+private static final String LABEL = "Stirling-PDF v1.0.0";/**diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.javaindex c57856877b..1310dbb1fa 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java@@ -338,7 +338,7 @@ public class ConfigController {"enableEasterEggs", applicationProperties.getSystem().isEnableEasterEggs());// Premium/Enterprise settings- configData.put("premiumEnabled", applicationProperties.getPremium().isEnabled());+ configData.put("premiumEnabled", Boolean.TRUE.equals(isRunningProOrHigher()));// Whether this instance can link a Stirling (SaaS) account at all. The account-link// beans live in :proprietary and are @ConditionalOnProperty on this same key, so when@@ -423,7 +423,8 @@ public class ConfigController {if (applicationContext.containsBean("SSOAutoLogin")) {configData.put("SSOAutoLogin",- applicationContext.getBean("SSOAutoLogin", Boolean.class));+ Boolean.TRUE.equals(isRunningProOrHigher())+ && applicationContext.getBean("SSOAutoLogin", Boolean.class));}} catch (Exception e) {// EE features not available, continue without themdiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.javaindex bac0e7d39b..9294d816fa 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java@@ -151,6 +151,12 @@ public class AccountLinkController {return ResponseEntity.ok(service.status());}+ /** Refreshes cloud entitlement without changing the linked account. */+ @PostMapping("/recheck")+ public ResponseEntity<AccountLinkService.LinkStatus> recheck() {+ return ResponseEntity.ok(service.recheck());+ }+@PostMapping("/unlink")public ResponseEntity<Void> unlink() {service.unlink();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.javaindex ca27d94920..6f26e3cc40 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java@@ -60,7 +60,8 @@ public class AccountLinkProperties {private int syncIntervalHours = 24;/**- * Block billable work after this many days with no successful sync (fail-open → closed).+ * Suspend cloud-backed Team features and processing after this many days without confirmed+ * entitlement.*/private int graceDays = 3;diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.javaindex a4746cf034..5acce9c744 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java@@ -32,7 +32,16 @@ public class AccountLinkService {}/** Status of this instance's link, for the portal's "Account link" card. */- public record LinkStatus(boolean linked, String deviceId, Long teamId, String linkedAt) {}+ public record LinkStatus(+ boolean linked,+ String deviceId,+ Long teamId,+ String linkedAt,+ EntitlementCache.ConnectionStatus connection) {+ public LinkStatus(boolean linked, String deviceId, Long teamId, String linkedAt) {+ this(linked, deviceId, teamId, linkedAt, null);+ }+ }/*** Unlinks this instance — best-effort tells SaaS to revoke first (so the row gets {@code@@ -57,17 +66,23 @@ public class AccountLinkService {log.info("Account-link: instance unlinked");}+ /** Forces a cloud check for an administrator retrying a restored connection. */+ public LinkStatus recheck() {+ entitlementCache.invalidate();+ return status();+ }+public LinkStatus status() {Optional<DeviceCredential> cred = credentialStore.get();+ if (cred.isPresent()) entitlementCache.current();return cred.map(c ->new LinkStatus(true,c.getDeviceId(),c.getTeamId(),- c.getLinkedAt() != null- ? c.getLinkedAt().toString()- : null))+ c.getLinkedAt() != null ? c.getLinkedAt().toString() : null,+ entitlementCache.connectionStatus())).orElseGet(() -> new LinkStatus(false, null, null, null));}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.javaindex 7da486b741..a14b812df7 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java@@ -48,6 +48,16 @@ public class DeviceCredential implements Serializable {@Column(name = "team_id")private Long teamId;+ /** Last confirmed SaaS entitlement for this device; failed attempts never advance it. */+ @Column(name = "last_entitlement_success_at")+ private java.time.Instant lastEntitlementSuccessAt;++ @Column(+ name = "entitlement_revoked",+ nullable = false,+ columnDefinition = "boolean not null default false")+ private boolean entitlementRevoked;+@Column(name = "linked_at", nullable = false)private LocalDateTime linkedAt;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.javaindex bbeddd3781..9c3261b6c1 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java@@ -1,11 +1,20 @@package stirling.software.proprietary.accountlink;+import java.time.Instant;import java.util.Optional;import org.springframework.data.jpa.repository.JpaRepository;+import org.springframework.data.jpa.repository.Modifying;+import org.springframework.data.jpa.repository.Query;public interface DeviceCredentialRepository extends JpaRepository<DeviceCredential, Long> {+ /** Updates only the current device, so an old response cannot refresh a replacement link. */+ @Modifying(clearAutomatically = true)+ @Query(+ "update DeviceCredential c set c.lastEntitlementSuccessAt = :at, c.entitlementRevoked = :revoked where c.deviceId = :deviceId and (c.lastEntitlementSuccessAt is null or c.lastEntitlementSuccessAt <= :at)")+ int recordEntitlementContact(String deviceId, Instant at, boolean revoked);+/** The singleton credential, if this instance has linked. */default Optional<DeviceCredential> findCredential() {return findById(DeviceCredential.SINGLETON_ID);diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.javaindex 981554b699..d5a12a59e1 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java@@ -1,11 +1,13 @@package stirling.software.proprietary.accountlink;+import java.time.Instant;import java.time.LocalDateTime;import java.util.Optional;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Service;+import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;/**@@ -47,9 +49,17 @@ public class DeviceCredentialStore {cred.setDeviceSecret(deviceSecret);cred.setTeamId(teamId);cred.setLinkedAt(LocalDateTime.now());+ cred.setLastEntitlementSuccessAt(null);+ cred.setEntitlementRevoked(false);repo.save(cred);}+ /** Commits successful contact independently of the caller's work or transaction rollback. */+ @Transactional(propagation = Propagation.REQUIRES_NEW)+ public void recordEntitlementContact(String deviceId, Instant at, boolean revoked) {+ repo.recordEntitlementContact(deviceId, at, revoked);+ }+/** Unlinks this instance locally (idempotent). */@Transactionalpublic void clear() {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.javaindex ef459e8248..777c91df8f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java@@ -1,25 +1,20 @@package stirling.software.proprietary.accountlink;+import java.time.Clock;import java.time.Duration;import java.time.Instant;+import java.util.Objects;import java.util.Optional;import java.util.concurrent.atomic.AtomicBoolean;+import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Service;import lombok.extern.slf4j.Slf4j;-/**- * Caches the linked team's entitlement so the request-time gate needn't call SaaS on every billable- * request. Single-slot (one instance = one linked team), TTL-based.- *- * <p>A transport failure fails open — {@link #current()} keeps serving the freshest snapshot it has- * and returns {@link Optional#empty()} ("unknown → allow") only when nothing was ever fetched. An- * authoritative deny ({@link AccountLinkClient.RevokedException}) does not: the snapshot is- * replaced with a {@link EntitlementState#REVOKED} entitlement so the gate blocks immediately.- */+/** Caches cloud entitlement; callers must also enforce the persisted offline deadline. */@Slf4j@Service@Profile("!saas")@@ -32,28 +27,50 @@ public class EntitlementCache {private final DeviceCredentialStore credentialStore;private final AccountLinkClient client;private final Duration ttl;+ private final Duration grace;+ private final Clock clock;/** Entitlement + fetch time, swapped atomically as one value so readers never tear. */- private record Snapshot(InstanceEntitlement entitlement, Instant fetchedAt) {}+ private record Snapshot(+ InstanceEntitlement entitlement,+ Instant fetchedAt,+ Instant lastSuccess,+ boolean offline) {}- private static final Snapshot EMPTY = new Snapshot(null, Instant.EPOCH);+ private static final Snapshot EMPTY = new Snapshot(null, Instant.EPOCH, null, false);/** Blocked entitlement synthesised on an authoritative deny (revoked/invalid credential). */private static final InstanceEntitlement REVOKED =new InstanceEntitlement(false, 0, 0, null, EntitlementState.REVOKED);private volatile Snapshot snapshot = EMPTY;+ private volatile String snapshotDeviceId;/** Single-flight guard: one thread refreshes while others serve the current snapshot. */private final AtomicBoolean refreshing = new AtomicBoolean(false);+ @Autowiredpublic EntitlementCache(DeviceCredentialStore credentialStore,AccountLinkClient client,AccountLinkProperties properties) {+ this(credentialStore, client, properties, Clock.systemDefaultZone());+ }++ EntitlementCache(+ DeviceCredentialStore credentialStore,+ AccountLinkClient client,+ AccountLinkProperties properties,+ Clock clock) {this.credentialStore = credentialStore;this.client = client;this.ttl = Duration.ofSeconds(properties.getEntitlementCacheSeconds());+ this.grace =+ Duration.ofDays(+ properties.getMetering().getGraceDays() > 0+ ? properties.getMetering().getGraceDays()+ : 3);+ this.clock = clock;}/**@@ -61,6 +78,11 @@ public class EntitlementCache {* not linked or the SaaS side is unreachable and we have no prior snapshot.*/public Optional<InstanceEntitlement> current() {+ String linked = linkedDeviceId();+ if (!Objects.equals(linked, snapshotDeviceId)) {+ snapshot = EMPTY;+ snapshotDeviceId = linked;+ }// Single-flight: when stale, exactly one thread refreshes while concurrent callers serve// the last snapshot — no thundering herd of round-trips on the billable hot path.if (isStale(snapshot) && refreshing.compareAndSet(false, true)) {@@ -70,13 +92,25 @@ public class EntitlementCache {refreshing.set(false);}}+ if (snapshot.entitlement() == null+ && credentialStore+ .get()+ .map(DeviceCredential::isEntitlementRevoked)+ .orElse(false)) {+ return Optional.of(REVOKED);+ }return Optional.ofNullable(snapshot.entitlement());}+ /** Identity owning the cached allowance; absent after an explicit unlink. */+ public String linkedDeviceId() {+ return credentialStore.get().map(DeviceCredential::getDeviceId).orElse(null);+ }+private boolean isStale(Snapshot snap) {// fetchedAt is the last *attempt* time (stamped on success and failure), so a failed fetch// backs off a full TTL instead of every request re-triggering a round-trip to a dead SaaS.- return Duration.between(snap.fetchedAt(), Instant.now()).compareTo(ttl) >= 0;+ return Duration.between(snap.fetchedAt(), clock.instant()).compareTo(ttl) >= 0;}/**@@ -88,43 +122,110 @@ public class EntitlementCache {Optional<DeviceCredential> cred = credentialStore.get();if (cred.isEmpty()) {// Unlinked: clear any stale snapshot so the gate sees "not linked".- snapshot = new Snapshot(null, Instant.now());+ snapshot = new Snapshot(null, clock.instant(), null, false);return;}try {InstanceEntitlement fresh =client.fetchEntitlement(cred.get().getDeviceId(), cred.get().getDeviceSecret());+ if (!Objects.equals(cred.get().getDeviceId(), linkedDeviceId())) return;if (fresh != null) {- snapshot = new Snapshot(fresh, Instant.now());+ snapshot = successfulSnapshot(cred.get().getDeviceId(), fresh);} else {// Unreachable / server error: keep the last known entitlement but stamp the attempt- // so we don't hammer SaaS; the gate fails open meanwhile.+ // so requests back off; the persisted offline deadline still applies.log.debug("Entitlement refresh failed; reusing last known snapshot, backing off a TTL");- snapshot = new Snapshot(snapshot.entitlement(), Instant.now());+ snapshot =+ new Snapshot(+ snapshot.entitlement(),+ clock.instant(),+ snapshot.lastSuccess(),+ true);}} catch (AccountLinkClient.RevokedException e) {+ if (!Objects.equals(cred.get().getDeviceId(), linkedDeviceId())) return;// Authoritative deny — block immediately rather than serving the stale entitled// snapshot.log.info("Entitlement denied (HTTP {}); blocking billable work for the revoked credential",e.status());- snapshot = new Snapshot(REVOKED, Instant.now());+ snapshot = successfulSnapshot(cred.get().getDeviceId(), REVOKED);}}+ private Snapshot successfulSnapshot(String deviceId, InstanceEntitlement entitlement) {+ Instant now = clock.instant();+ credentialStore.recordEntitlementContact(+ deviceId, now, entitlement.state() == EntitlementState.REVOKED);+ return new Snapshot(entitlement, now, now, false);+ }++ /** Applies across restarts and independently of metering or the presence of cached data. */+ public boolean isGraceExpired() {+ ConnectionStatus status = connectionStatus();+ return "expired".equals(status.state());+ }++ /** The caller refreshes with current() first; this method performs no network request. */+ public ConnectionStatus connectionStatus() {+ Optional<DeviceCredential> credential = credentialStore.get();+ if (credential.isEmpty()) return new ConnectionStatus("unlinked", null, null);+ DeviceCredential device = credential.get();+ Instant last = device.getLastEntitlementSuccessAt();+ Snapshot current =+ Objects.equals(device.getDeviceId(), snapshotDeviceId) ? snapshot : EMPTY;+ if (current.lastSuccess() != null+ && (last == null || current.lastSuccess().isAfter(last))) {+ last = current.lastSuccess();+ }+ Instant reference =+ last != null+ ? last+ : device.getLinkedAt() == null+ ? Instant.EPOCH+ : device.getLinkedAt().atZone(clock.getZone()).toInstant();+ Instant deadline = reference.plus(grace);+ boolean currentIsNewer =+ current.lastSuccess() != null+ && (device.getLastEntitlementSuccessAt() == null+ || !current.lastSuccess()+ .isBefore(device.getLastEntitlementSuccessAt()));+ boolean revoked =+ currentIsNewer+ ? current.entitlement() != null+ && current.entitlement().state() == EntitlementState.REVOKED+ : device.isEntitlementRevoked();+ String state =+ revoked+ ? "revoked"+ : !clock.instant().isBefore(deadline)+ ? "expired"+ : current.offline() ? "offline" : "connected";+ return new ConnectionStatus(state, last, deadline);+ }++ public record ConnectionStatus(+ String state, Instant lastSuccessAt, Instant offlineAccessUntil) {}+/** Forces a refresh on the next {@link #current()} (e.g. right after linking). */public void invalidate() {- snapshot = new Snapshot(snapshot.entitlement(), Instant.EPOCH);+ snapshot =+ new Snapshot(+ snapshot.entitlement(),+ Instant.EPOCH,+ snapshot.lastSuccess(),+ snapshot.offline());}/*** Seeds the cache with an entitlement obtained out-of-band (the sync reply carries a fresh- * one), saving a redundant fetch. No-op on null.+ * one), saving a redundant fetch. Ignores null and replies for a different linked device.*/- public void accept(InstanceEntitlement fresh) {- if (fresh != null) {- snapshot = new Snapshot(fresh, Instant.now());+ public void accept(String deviceId, InstanceEntitlement fresh) {+ if (fresh != null && deviceId != null && Objects.equals(deviceId, linkedDeviceId())) {+ snapshotDeviceId = deviceId;+ snapshot = successfulSnapshot(deviceId, fresh);}}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementRefreshedEvent.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementRefreshedEvent.javanew file mode 100644index 0000000000..f43ce1d51c--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementRefreshedEvent.java@@ -0,0 +1,14 @@+package stirling.software.proprietary.accountlink;++/**+ * The cached entitlement has just been re-read from SaaS.+ *+ * <p>Published by whoever did the read rather than by a timer, so nothing here adds traffic: the+ * instance speaks to SaaS on the daily sync, on the return from a checkout, and at startup, and+ * those are the moments a plan change can be noticed without phoning home more often than the+ * design intends.+ *+ * <p>An event rather than a direct call because the listener is the licence tier, which already+ * reads this package. Calling the other way would point the dependency both ways.+ */+public record EntitlementRefreshedEvent() {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.javaindex eaf166056e..a2d3367633 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java@@ -1,6 +1,5 @@package stirling.software.proprietary.accountlink;-import java.time.LocalDateTime;import java.util.Optional;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;@@ -10,29 +9,7 @@ import org.springframework.stereotype.Service;import stirling.software.common.service.LicenseServiceInterface;/**- * Decides whether a request may proceed under combined billing on a self-hosted instance.- *- * <p>Rules (in order):- *- * <ol>- * <li>Flag off → always allow (feature inert).- * <li>Manual tool → always allow (manual tools are free, never metered).- * <li>Enterprise license → always allow, with local-only metering.- * <li>Billable + not linked → {@code FREE_TIER} while units remain, else {@code- * FREE_TIER_EXHAUSTED}. Linking buys a further grant, it does not activate the feature.- * <li>Billable + linked + entitlement unknown (unreachable) → <b>fail open</b>, allow — unless- * metering is on and SaaS has been unreachable past the grace window, then block with {@code- * GRACE_EXPIRED} so the fail-open can't grant unbounded free/unbilled work forever.- * <li>Billable + linked + entitled → allow.- * <li>Billable + linked + credential revoked → block with {@code REVOKED}.- * <li>Billable + linked + over limit → block with {@code OVER_LIMIT}.- * </ol>- *- * <p>The local grant is read only when unlinked; a linked instance's pre-link counters sit- * untouched, and are what it resumes on if it unlinks.- *- * <p>The decision logic is the pure static {@link #decide}; the Spring wrapper supplies the live- * flag / linked-state / entitlement / balances and resolves the grace window.+ * Enforces cloud processing allowance and the shared offline deadline; manual tools remain free.*/@Service@Profile("!saas")@@ -46,7 +23,6 @@ public class InstanceEntitlementGate {private final AccountLinkProperties properties;private final DeviceCredentialStore credentialStore;private final EntitlementCache entitlementCache;- private final AccountLinkSyncStateRepository syncStateRepository;private final LocalUsageService localUsageService;private final FreeTierUsageService freeTierUsageService;@@ -54,7 +30,6 @@ public class InstanceEntitlementGate {AccountLinkProperties properties,DeviceCredentialStore credentialStore,EntitlementCache entitlementCache,- AccountLinkSyncStateRepository syncStateRepository,LocalUsageService localUsageService,FreeTierUsageService freeTierUsageService,LicenseServiceInterface licenseService) {@@ -62,7 +37,6 @@ public class InstanceEntitlementGate {this.properties = properties;this.credentialStore = credentialStore;this.entitlementCache = entitlementCache;- this.syncStateRepository = syncStateRepository;this.localUsageService = localUsageService;this.freeTierUsageService = freeTierUsageService;}@@ -82,7 +56,11 @@ public class InstanceEntitlementGate {long freeTierRemaining = linked ? 0L : freeTierUsageService.balance().remainingUnits();Optional<InstanceEntitlement> entitlement =linked ? entitlementCache.current() : Optional.empty();- boolean graceExpired = linked && entitlement.isEmpty() && isGraceExpired();+ boolean graceExpired = linked && entitlementCache.isGraceExpired();+ if (entitlement.isPresent() && entitlement.get().state() == EntitlementState.REVOKED) {+ return GateDecision.block(GateDecision.Reason.REVOKED);+ }+ if (graceExpired) return GateDecision.block(GateDecision.Reason.GRACE_EXPIRED);// Deplete the applicable ceiling — free grant (unsubscribed) or spend cap (capped// subscription) — by local usage not yet synced, so the gate stops in real time instead of// overshooting until the next sync. An uncapped subscription has no ceiling to deplete → 0.@@ -130,14 +108,11 @@ public class InstanceEntitlementGate {? GateDecision.allow(GateDecision.Reason.FREE_TIER): GateDecision.block(GateDecision.Reason.FREE_TIER_EXHAUSTED);}- if (entitlement.isEmpty()) {- // Linked but entitlement unreachable: fail open, unless the grace window has expired- // (so- // the fail-open can't grant unbounded unbilled work forever).- return graceExpired- ? GateDecision.block(GateDecision.Reason.GRACE_EXPIRED)- : GateDecision.allow(GateDecision.Reason.FAIL_OPEN);+ if (entitlement.isPresent() && entitlement.get().state() == EntitlementState.REVOKED) {+ return GateDecision.block(GateDecision.Reason.REVOKED);}+ if (graceExpired) return GateDecision.block(GateDecision.Reason.GRACE_EXPIRED);+ if (entitlement.isEmpty()) return GateDecision.allow(GateDecision.Reason.FAIL_OPEN);InstanceEntitlement e = entitlement.get();if (e.state() == EntitlementState.REVOKED) {// Credential revoked/invalid (authoritative deny) — block, distinct from over-limit.@@ -148,35 +123,6 @@ public class InstanceEntitlementGate {: GateDecision.block(GateDecision.Reason.OVER_LIMIT);}- /**- * True when metering is on and it's been {@code graceDays} since the last authoritative contact- * (last successful sync, or link time if never synced). {@code graceDays <= 0} or metering off- * disables the backstop.- */- private boolean isGraceExpired() {- AccountLinkProperties.Metering metering = properties.getMetering();- if (!metering.isEnabled() || metering.getGraceDays() <= 0) {- return false;- }- LocalDateTime reference = lastAuthoritativeContact();- if (reference == null) {- return false; // can't determine elapsed time → fail open- }- return reference.plusDays(metering.getGraceDays()).isBefore(LocalDateTime.now());- }-- private LocalDateTime lastAuthoritativeContact() {- LocalDateTime lastSuccess =- syncStateRepository- .findById(AccountLinkSyncState.SINGLETON_ID)- .map(AccountLinkSyncState::getLastSuccessAt)- .orElse(null);- if (lastSuccess != null) {- return lastSuccess;- }- return credentialStore.get().map(DeviceCredential::getLinkedAt).orElse(null);- }-/** True when the snapshot permits billable work (subscribed, free pool left, or within cap). */private static boolean entitled(InstanceEntitlement e, long pendingUnsyncedUnits) {if (e.state() == EntitlementState.OVER_LIMIT || e.state() == EntitlementState.REVOKED) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.javaindex 73804a705a..8f7b569a4a 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java@@ -123,7 +123,11 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {.write("{\"error\":\"ACCOUNT_LINK_REQUIRED\",\"reason\":\""+ decision.reason().name()- + "\"}");+ + "\""+ + (decision.reason() == GateDecision.Reason.GRACE_EXPIRED+ ? ",\"message\":\"Cloud processing is paused because this server's offline allowance expired. Ask an administrator to restore its Stirling Cloud connection.\""+ : "")+ + "}");return false;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.javaindex a12a26eb8a..a8e3a921ac 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.java@@ -7,6 +7,7 @@ import java.util.List;import java.util.Optional;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.context.annotation.Profile;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.config.FixedDelayTask;@@ -44,6 +45,7 @@ public class UsageSyncService implements SchedulingConfigurer {private final AccountLinkClient client;private final EntitlementCache entitlementCache;private final AccountLinkProperties properties;+ private final ApplicationEventPublisher events;public UsageSyncService(UsageCounterRepository counters,@@ -51,13 +53,15 @@ public class UsageSyncService implements SchedulingConfigurer {DeviceCredentialStore credentialStore,AccountLinkClient client,EntitlementCache entitlementCache,- AccountLinkProperties properties) {+ AccountLinkProperties properties,+ ApplicationEventPublisher events) {this.counters = counters;this.syncState = syncState;this.credentialStore = credentialStore;this.client = client;this.entitlementCache = entitlementCache;this.properties = properties;+ this.events = events;}/**@@ -97,6 +101,7 @@ public class UsageSyncService implements SchedulingConfigurer {// cache TTL lapses. Force an immediate refresh so the gate reflects the new plan now.entitlementCache.invalidate();entitlementCache.current();+ events.publishEvent(new EntitlementRefreshedEvent());return;}InstanceEntitlement latest = null;@@ -118,7 +123,12 @@ public class UsageSyncService implements SchedulingConfigurer {return;}// Adopt the freshest entitlement the sync returned, saving the cache a redundant fetch.- entitlementCache.accept(latest);+ entitlementCache.accept(cred.get().getDeviceId(), latest);+ if (latest != null) {+ // Only when a reply actually arrived. accept() no-ops on null, so announcing a refresh+ // here would tell listeners the plan had been re-read when every period had failed.+ events.publishEvent(new EntitlementRefreshedEvent());+ }}/** Reports one period; returns the fresh entitlement, or null on a transport/server failure. */diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/cluster/ClusterLicenseGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/cluster/ClusterLicenseGate.javaindex cc67354fec..78755b75df 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/cluster/ClusterLicenseGate.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/cluster/ClusterLicenseGate.java@@ -23,12 +23,16 @@ public class ClusterLicenseGate {@Qualifier("runningProOrHigher")private Boolean runningProOrHigher;+ @Autowired+ private stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker+ licenseChecker;+@PostConstructvoid verifyLicense() {if (runningProOrHigher == null) {return; // saas flavor - licensed via Stripe elsewhere}- if (!runningProOrHigher) {+ if (!runningProOrHigher && !licenseChecker.isTeamOfflineExpired()) {throw new IllegalStateException("Cluster mode (cluster.enabled=true) requires a SERVER or"+ " ENTERPRISE license. Configure stirling.premium.key with a valid"diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.javaindex de423f03a1..ab71cf1152 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java@@ -231,7 +231,7 @@ public class ProprietaryUIDataController {SAML2 saml2 = securityProps.getSaml2();// Only add SAML2 providers if loginMethod allows it- if (securityProps.isSaml2Active() && applicationProperties.getPremium().isEnabled()) {+ if (securityProps.isSaml2Active() && licenseSettingsService.hasPaidLicense()) {String samlIdp = saml2.getProvider();String saml2AuthenticationPath = "/saml2/authenticate/" + saml2.getRegistrationId();@@ -351,7 +351,7 @@ public class ProprietaryUIDataController {long availableSlots = licenseSettingsService.getAvailableUserSlots();int grandfatheredCount = licenseSettingsService.getDisplayGrandfatheredCount();int licenseMaxUsers = licenseSettingsService.getSettings().getLicenseMaxUsers();- boolean premiumEnabled = applicationProperties.getPremium().isEnabled();+ boolean premiumEnabled = licenseSettingsService.hasPaidLicense();long pendingInvites = inviteTokenRepository.countActiveInvites(LocalDateTime.now());// Resolve portal access for the whole roster. The teamLead display flag counts adiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.javaindex 1683ad9134..41dac6cc7f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.java@@ -50,6 +50,20 @@ public class UserLicenseSettings implements Serializable {@Column(name = "license_max_users", nullable = false)private int licenseMaxUsers = 0;+ /**+ * Users the linked cloud team has bought a Team plan for; null when it has bought none.+ *+ * <p>Mirrored here from the SaaS entitlement, which lives only in memory: an instance that+ * boots offline, or before the first entitlement round trip finishes, would otherwise not know+ * it is entitled at all. Rewritten on every licence sync, so SaaS stays the authority and a+ * lapsed plan clears it.+ */+ @Column(name = "linked_team_users")+ private Integer linkedTeamUsers;++ @Column(name = "linked_team_device_id")+ private String linkedTeamDeviceId;+/*** Random salt used when generating signatures. Makes it harder to recompute the signature when* manually editing the table.diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.javaindex 56df2b5981..9bc8bc1e2c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java@@ -29,6 +29,7 @@ import stirling.software.proprietary.policy.source.EditorSource;import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.policy.source.SourceDocCounter;import stirling.software.proprietary.policy.source.SourceStore;+import stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard;/*** Turns a policy's referenced sources into runs: each {@code sourceId} is resolved live to its@@ -48,6 +49,7 @@ public class PolicyRunner {private final ProcessedLedger processedLedger;private final ApplicationProperties applicationProperties;private final PolicyAccessGuard policyAccessGuard;+ private final DatabaseLicenseGuard databaseLicenseGuard;/*** One admission gate per sweep: every run is visible immediately, but only this many execute at@@ -103,6 +105,9 @@ public class PolicyRunner {*/private SweepOutcome run(Policy policy, List<PipelineInput> inputs, SweepKind sweep, String target) {+ if (databaseLicenseGuard.requiresActivation()) {+ return new SweepOutcome(List.of(), 0, 0, 0, 0, 0);+ }if (policyAccessGuard.isOrphaned(policy)) {// Reachable by nobody, so nobody could stop it: running would replace files in place// in a folder no user can list, pause, revert, or delete.@@ -178,6 +183,7 @@ public class PolicyRunner {PolicyInputs inputs,PolicyProgressListener listener,String documentReference) {+ requireDatabaseAccess();PolicyRunHandle handle =policyEngine.runPolicy(policy, inputs, listener, null, documentReference);docCounter.record(EditorSource.counterKey(policy.teamId()), inputs.primary().size());@@ -187,9 +193,17 @@ public class PolicyRunner {/** Run an ad-hoc pipeline with no stored policy (AI/Automate one-offs). */public PolicyRunHandle runAdHoc(PipelineDefinition definition, PolicyInputs inputs, PolicyProgressListener listener) {+ requireDatabaseAccess();return policyEngine.submit(definition, inputs, listener);}+ private void requireDatabaseAccess() {+ if (databaseLicenseGuard.requiresActivation()) {+ throw new IllegalStateException(+ "Link a paid Team account or install a Server licence before processing");+ }+ }+/** Whether nothing of the policy is running or mid-settle — safe to move its files. */public boolean quiesced(String policyId) {return !policyEngine.hasActiveRuns(policyId) && !processedLedger.anyInFlight(policyId);@@ -278,6 +292,7 @@ public class PolicyRunner {Consumer<Boolean> onComplete,Semaphore admission) {log.info("Running policy {} ({})", policy.id(), policy.name());+ requireDatabaseAccess();PolicyRunHandle handle =policyEngine.runPolicy(policy,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/config/PremiumEndpointAspect.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/config/PremiumEndpointAspect.javaindex 9b26e5b55c..04c44e0acd 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/config/PremiumEndpointAspect.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/config/PremiumEndpointAspect.java@@ -3,25 +3,35 @@ package stirling.software.proprietary.security.config;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;-import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Component;import org.springframework.web.server.ResponseStatusException;+import stirling.software.common.service.LicenseServiceInterface;++/**+ * Refuses {@code @PremiumEndpoint} work below Server.+ *+ * <p>Asks per request rather than holding the {@code runningProOrHigher} bean, which is a value+ * copied once at startup. The tier is not fixed for the life of the process: an admin can enter a+ * licence key, the scheduled recheck can find one lapsed, and a linked instance can have a Team+ * plan bought or cancelled under it. A snapshot grants a cancelled plan until someone restarts, and+ * the customer who stopped paying has no reason to.+ */@Aspect@Componentpublic class PremiumEndpointAspect {- private final boolean runningProOrHigher;+ private final LicenseServiceInterface licenseService;- public PremiumEndpointAspect(@Qualifier("runningProOrHigher") boolean runningProOrHigher) {- this.runningProOrHigher = runningProOrHigher;+ public PremiumEndpointAspect(LicenseServiceInterface licenseService) {+ this.licenseService = licenseService;}@Around("@annotation(stirling.software.proprietary.security.config.PremiumEndpoint) || @within(stirling.software.proprietary.security.config.PremiumEndpoint)")public Object checkPremiumAccess(ProceedingJoinPoint joinPoint) throws Throwable {- if (!runningProOrHigher) {+ if (!licenseService.isRunningProOrHigher()) {throw new ResponseStatusException(HttpStatus.FORBIDDEN, "This endpoint requires a Server or Enterprise license");}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.javaindex 389ffa535e..a176176d47 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java@@ -5,7 +5,6 @@ import java.util.Locale;import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Qualifier;-import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;import org.springframework.boot.jdbc.DataSourceBuilder;import org.springframework.boot.jdbc.DatabaseDriver;import org.springframework.boot.persistence.autoconfigure.EntityScan;@@ -65,28 +64,18 @@ public class DatabaseConfig {public static final String DEFAULT_USERNAME = "sa";private final ApplicationProperties.Datasource datasource;- private final boolean runningProOrHigher;- public DatabaseConfig(- ApplicationProperties.Datasource datasource,- @Qualifier("runningProOrHigher") boolean runningProOrHigher) {+ /** Opens the configured database; entitlement checks must read this same database. */+ public DatabaseConfig(ApplicationProperties.Datasource datasource) {DATASOURCE_DEFAULT_URL ="jdbc:h2:file:"+ InstallationPathConfig.getConfigPath()+ "stirling-pdf-DB-2.3.232;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL";log.debug("Database URL: {}", DATASOURCE_DEFAULT_URL);this.datasource = datasource;- this.runningProOrHigher = runningProOrHigher;}- /**- * Creates the <code>DataSource</code> for the connection to the DB. If <code>useDefault</code>- * is set to <code>true</code>, it will use the default H2 DB. If it is set to <code>false- * </code>, it will use the user's custom configuration set in the settings.yml.- *- * @return a <code>DataSource</code> using the configuration settings in the settings.yml- * @throws UnsupportedProviderException if the type of database selected is not supported- */+ /** Uses the configured database without falling back on an entitlement failure. */@Bean@Qualifier("dataSource")@Primary@@ -94,7 +83,7 @@ public class DatabaseConfig {public DataSource dataSource() throws UnsupportedProviderException {DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();- if (!runningProOrHigher || !datasource.isEnableCustomDatabase()) {+ if (!datasource.isEnableCustomDatabase()) {return useDefaultDataSource(dataSourceBuilder);}@@ -120,7 +109,6 @@ public class DatabaseConfig {return dataSourceBuilder.build();}- @ConditionalOnBooleanProperty(name = "premium.enabled")private DataSource useCustomDataSource(DataSourceBuilder<?> dataSourceBuilder)throws UnsupportedProviderException {log.info("Using custom database configuration");diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.javaindex 9923e3aa81..d49e365474 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java@@ -236,7 +236,7 @@ public class SecurityConfiguration {http.securityMatcher("/saml2/**", "/login/saml2/**");SessionCreationPolicy sessionPolicy =- (securityProperties.isSaml2Active() && runningProOrHigher)+ securityProperties.isSaml2Active()? SessionCreationPolicy.IF_REQUIRED: SessionCreationPolicy.STATELESS;@@ -429,7 +429,7 @@ public class SecurityConfiguration {.permitAll());}// Handle SAML- if (securityProperties.isSaml2Active() && runningProOrHigher) {+ if (securityProperties.isSaml2Active()) {OpenSaml5AuthenticationProvider authenticationProvider =new OpenSaml5AuthenticationProvider();authenticationProvider.setResponseAuthenticationConverter(diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/DatabaseLicenseGuard.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/DatabaseLicenseGuard.javanew file mode 100644index 0000000000..0e0906ef57--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/DatabaseLicenseGuard.java@@ -0,0 +1,26 @@+package stirling.software.proprietary.security.configuration.ee;++import org.springframework.core.env.Environment;+import org.springframework.stereotype.Component;++import lombok.RequiredArgsConstructor;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.LicenseServiceInterface;++/** Keeps the configured database available for recovery without granting unlicensed processing. */+@Component+@RequiredArgsConstructor+public class DatabaseLicenseGuard {+ private final ApplicationProperties properties;+ private final LicenseServiceInterface licenseService;+ private final Environment environment;++ /** Setup and licence recovery remain available while this is true. */+ public boolean requiresActivation() {+ return !environment.matchesProfiles("saas")+ && properties.getSystem().getDatasource() != null+ && properties.getSystem().getDatasource().isEnableCustomDatabase()+ && !licenseService.isRunningProOrHigher();+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/DynamicLicenseService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/DynamicLicenseService.javaindex 849c15c889..e227a0685b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/DynamicLicenseService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/DynamicLicenseService.java@@ -12,11 +12,8 @@ import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVeri* admins update the license key, the changes are immediately reflected in the UI and config* endpoints without requiring a restart.*- * <p>Note: Some components (EnterpriseEndpointAspect, PremiumEndpointAspect, filters) still inject- * cached beans at startup for performance. These will require a restart to reflect license changes.- * This is acceptable because: 1. Most deployments add licenses during initial setup 2. License- * changes in production typically warrant a restart anyway 3. UI reflects changes immediately- * (banner disappears, license status updates)+ * <p>Linked Team entitlement is evaluated on access, including unlink and revocation; installed+ * licences retain their own validation lifecycle.*/@Service@RequiredArgsConstructor@@ -30,7 +27,7 @@ public class DynamicLicenseService implements LicenseServiceInterface {* @return Current license: NORMAL, SERVER, or ENTERPRISE*/public License getCurrentLicense() {- return licenseKeyChecker.getPremiumLicenseEnabledResult();+ return licenseKeyChecker.premiumTier();}@Overridediff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/EEAppConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/EEAppConfig.javaindex 4fb6a0de36..2d7b8b1d9f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/EEAppConfig.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/EEAppConfig.java@@ -4,6 +4,7 @@ import static stirling.software.proprietary.security.configuration.ee.KeygenLiceimport org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;+import org.springframework.context.annotation.DependsOn;import org.springframework.context.annotation.Profile;import org.springframework.core.Ordered;import org.springframework.core.annotation.Order;@@ -27,27 +28,33 @@ public class EEAppConfig {migrateEnterpriseSettingsToPremium(this.applicationProperties);}+ /** Team entitlement is stored in the configured database. */@Profile("security & !saas")@Bean(name = "runningProOrHigher")+ @DependsOn("entityManagerFactory")public boolean runningProOrHigher() {- License license = licenseKeyChecker.getPremiumLicenseEnabledResult();+ License license = licenseKeyChecker.premiumTier();return license == License.SERVER || license == License.ENTERPRISE;}@Profile("security & !saas")@Bean(name = "license")+ @DependsOn("entityManagerFactory")public String licenseType() {- return licenseKeyChecker.getPremiumLicenseEnabledResult().name();+ return licenseKeyChecker.premiumTier().name();}+ /** Never promoted: Enterprise is contracted, so this stays what the licence key itself says. */@Profile("security & !saas")@Bean(name = "runningEE")+ @DependsOn("entityManagerFactory")public boolean runningEnterprise() {- return licenseKeyChecker.getPremiumLicenseEnabledResult() == License.ENTERPRISE;+ return licenseKeyChecker.premiumTier() == License.ENTERPRISE;}@Profile("security & !saas")@Bean(name = "SSOAutoLogin")+ @DependsOn("runningProOrHigher")public boolean ssoAutoLogin() {boolean enabled = applicationProperties.getPremium().getProFeatures().isSsoAutoLogin();if (enabled) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.javaindex d8dbfc0e08..e4e59e5d37 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyChecker.java@@ -16,6 +16,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.util.GeneralUtils;+import stirling.software.proprietary.accountlink.EntitlementRefreshedEvent;import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;import stirling.software.proprietary.service.UserLicenseSettingsService;@@ -31,11 +32,12 @@ public class LicenseKeyChecker {private final UserLicenseSettingsService licenseSettingsService;- // volatile: written by evaluateLicense() on the @Scheduled refresh thread, read by request- // threads via getPremiumLicenseEnabledResult() / requireProOrEnterprise(). Ensures readers see- // the latest tier rather than a stale cached value.+ // Licence refreshes and request threads share these snapshots.private volatile License premiumEnabledResult = License.NORMAL;+ /** The licence key's own tier, before any Team-plan promotion. Same volatile contract. */+ private volatile License licenseKeyResult = License.NORMAL;+public LicenseKeyChecker(KeygenLicenseVerifier licenseService,ApplicationProperties applicationProperties,@@ -50,11 +52,23 @@ public class LicenseKeyChecker {evaluateLicense();}+ /** Refreshes persisted entitlement without repeating Keygen verification. */@EventListener(ApplicationReadyEvent.class)public void onApplicationReady() {+ applyTeamPlanPromotion();synchronizeLicenseSettings();}+ /** Applies a newly synced Team entitlement. */+ @EventListener(EntitlementRefreshedEvent.class)+ public void onEntitlementRefreshed() {+ try {+ applyTeamPlanPromotion();+ } catch (RuntimeException e) {+ log.debug("Team plan check failed; keeping the current tier: {}", e.getMessage());+ }+ }+@Scheduled(initialDelay = 604800000, fixedRate = 604800000) // 7 days in millisecondspublic void checkLicensePeriodically() {try {@@ -69,24 +83,54 @@ public class LicenseKeyChecker {}private void evaluateLicense() {+ licenseKeyResult = verifyLicenseKey();+ applyTeamPlanPromotion();+ }++ private License verifyLicenseKey() {if (!applicationProperties.getPremium().isEnabled()) {- premiumEnabledResult = License.NORMAL;+ return License.NORMAL;+ }+ String licenseKey = getLicenseKeyContent(applicationProperties.getPremium().getKey());+ if (licenseKey == null) {+ log.error("Failed to obtain license key content.");+ return License.NORMAL;+ }+ License verified = licenseService.verifyLicense(licenseKey);+ if (License.ENTERPRISE == verified) {+ log.info("License key is Enterprise.");+ } else if (License.SERVER == verified) {+ log.info("License key is Server.");} else {- String licenseKey = getLicenseKeyContent(applicationProperties.getPremium().getKey());- if (licenseKey != null) {- premiumEnabledResult = licenseService.verifyLicense(licenseKey);- if (License.ENTERPRISE == premiumEnabledResult) {- log.info("License key is Enterprise.");- } else if (License.SERVER == premiumEnabledResult) {- log.info("License key is Server.");- } else {- log.info("License key is invalid, defaulting to non pro license.");- }- } else {- log.error("Failed to obtain license key content.");- premiumEnabledResult = License.NORMAL;- }+ log.info("License key is invalid, defaulting to non pro license.");+ }+ return verified;+ }++ /** Team grants Server features independently of the installed-key settings. */+ private void applyTeamPlanPromotion() {+ if (licenseKeyResult != License.NORMAL) {+ premiumEnabledResult = licenseKeyResult;+ return;+ }+ Integer users;+ try {+ users = purchasedTeamUsers();+ } catch (RuntimeException e) {+ // A failed read must not revoke a known entitlement.+ log.debug("Linked team allowance unreadable; keeping the current tier", e);+ return;}+ boolean entitled = users != null && users > 0;+ if (entitled) {+ log.info("Linked cloud team holds a Team plan for {} users; running as Server.", users);+ }+ premiumEnabledResult = entitled ? License.SERVER : License.NORMAL;+ }++ /** Throws when entitlement cannot be read; null means no purchased Team capacity. */+ private Integer purchasedTeamUsers() {+ return licenseSettingsService.refreshLinkedTeamUsers();}private void synchronizeLicenseSettings() {@@ -127,23 +171,50 @@ public class LicenseKeyChecker {synchronizeLicenseSettings();}+ /** Refreshes the linked entitlement and installed licence after a purchase. */public void resyncLicense() {+ licenseSettingsService.forgetEntitlement();evaluateLicense();synchronizeLicenseSettings();}+ /** Resolves the effective tier after the datasource is available. */+ public License premiumTier() {+ applyTeamPlanPromotion();+ return premiumEnabledResult;+ }+public License getPremiumLicenseEnabledResult() {return premiumEnabledResult;}+ /** Purchased Team capacity, excluding grandfathered and installed-key allowances. */+ public Integer linkedTeamUsers() {+ return licenseSettingsService.refreshLinkedTeamUsers();+ }++ /** Effective admission limit enforced on this instance. */+ public int maxAllowedUsers() {+ return licenseSettingsService.calculateMaxAllowedUsers();+ }++ /** Installed-key tier only; use it for seat arithmetic, not feature gates. */+ public License getLicenseKeyResult() {+ return licenseKeyResult;+ }++ /** Keeps configured infrastructure available for recovery after an offline Team expiry. */+ public boolean isTeamOfflineExpired() {+ return licenseKeyResult == License.NORMAL && licenseSettingsService.isTeamOfflineExpired();+ }+/**- * Throws {@link IllegalStateException} if the current license is not Pro or Enterprise. Used by- * boot-time gates to fail fast when an operator enables a premium-only setting without a valid- * license. {@code configuredAs} is the human-readable property path (e.g. {@code- * "storage.provider=s3"}) and appears in the exception message.+ * Validates paid startup configuration, allowing expired Team infrastructure to boot for+ * recovery.*/public void requireProOrEnterprise(String configuredAs) {- if (premiumEnabledResult != License.SERVER && premiumEnabledResult != License.ENTERPRISE) {+ License tier = premiumTier();+ if (tier != License.SERVER && tier != License.ENTERPRISE && !isTeamOfflineExpired()) {throw new IllegalStateException(configuredAs + " requires a Pro or Enterprise license");}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminLicenseController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminLicenseController.javaindex 04fbd9d3b2..c95a1be45b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminLicenseController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminLicenseController.java@@ -152,18 +152,23 @@ public class AdminLicenseController {}/**- * Resync the current license with Keygen. This endpoint re-validates the existing license key- * and updates the max users setting. Used after subscription upgrades to sync the new license- * limits.+ * Re-reads everything that decides this instance's tier: the linked cloud team's plan, fetched+ * fresh rather than from cache, and the licence key if one is installed.+ *+ * <p>Deliberately does not require a licence key. A Team plan is bought on a SaaS account and+ * issues no key, so a key check here would reject the one customer this path exists for and+ * leave their purchase waiting for the next daily sync.** @return Response with updated license information*/@PostMapping("/license/resync")@Operation(- summary = "Resync license with Keygen",+ summary = "Resync entitlements",description =- "Re-validates the existing license key with Keygen and updates local settings."- + " Used after subscription upgrades.")+ "Re-reads what decides this instance's tier: the linked cloud team's plan,"+ + " fetched fresh rather than from cache, and the licence key if one is"+ + " installed. Used after a purchase, and as the recovery when the"+ + " automatic check has not caught up.")public ResponseEntity<Map<String, Object>> resyncLicense() {try {if (licenseKeyChecker == null) {@@ -171,15 +176,8 @@ public class AdminLicenseController {.body(Map.of("success", false, "error", "License checker not available"));}- String currentKey = applicationProperties.getPremium().getKey();- if (currentKey == null || currentKey.trim().isEmpty()) {- return ResponseEntity.badRequest()- .body(Map.of("success", false, "error", "No license key configured"));- }-- log.info("Resyncing license with Keygen");+ log.info("Resyncing entitlements");- // Re-validate license and sync settingslicenseKeyChecker.resyncLicense();// Get updated license status@@ -190,6 +188,12 @@ public class AdminLicenseController {response.put("success", true);response.put("licenseType", license.name());response.put("enabled", premium.isEnabled());+ response.put(+ "linkedTeamUsers",+ licenseKeyChecker == null ? null : licenseKeyChecker.linkedTeamUsers());+ response.put(+ "maxAllowedUsers",+ licenseKeyChecker == null ? null : licenseKeyChecker.maxAllowedUsers());response.put("maxUsers", premium.getMaxUsers());response.put("message", "License resynced successfully");@@ -236,6 +240,12 @@ public class AdminLicenseController {ApplicationProperties.Premium premium = applicationProperties.getPremium();response.put("enabled", premium.isEnabled());+ response.put(+ "linkedTeamUsers",+ licenseKeyChecker == null ? null : licenseKeyChecker.linkedTeamUsers());+ response.put(+ "maxAllowedUsers",+ licenseKeyChecker == null ? null : licenseKeyChecker.maxAllowedUsers());response.put("maxUsers", premium.getMaxUsers());// Presentation only, so the plan page can say "2 servers, 100 users each" rather than a// bare 200. Both are 0 on a licence issued before the cap.diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.javaindex d1b494583c..b23f294705 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/InviteLinkController.java@@ -108,24 +108,21 @@ public class InviteLinkController {}}- // Check license limits- if (applicationProperties.getPremium().isEnabled()) {- long currentUserCount = userService.getTotalUsersCount();- long activeInvites = inviteTokenRepository.countActiveInvites(LocalDateTime.now());- int maxUsers = userLicenseSettingsService.calculateMaxAllowedUsers();+ long currentUserCount = userService.getTotalUsersCount();+ long activeInvites = inviteTokenRepository.countActiveInvites(LocalDateTime.now());+ int maxUsers = userLicenseSettingsService.calculateMaxAllowedUsers();- if (currentUserCount + activeInvites >= maxUsers) {- return ResponseEntity.status(HttpStatus.BAD_REQUEST)- .body(- Map.of(- "error",- "License limit reached ("- + (currentUserCount + activeInvites)- + "/"- + maxUsers- + " users). Contact your administrator to"- + " upgrade your license."));- }+ if (currentUserCount + activeInvites >= maxUsers) {+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)+ .body(+ Map.of(+ "error",+ "License limit reached ("+ + (currentUserCount + activeInvites)+ + "/"+ + maxUsers+ + " users). Contact your administrator to"+ + " upgrade your license."));}// Validate rolediff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/DatabaseLicenseFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/DatabaseLicenseFilter.javanew file mode 100644index 0000000000..aa3efd266b--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/DatabaseLicenseFilter.java@@ -0,0 +1,56 @@+package stirling.software.proprietary.security.filter;++import java.io.IOException;+import java.util.Set;++import org.springframework.core.Ordered;+import org.springframework.core.annotation.Order;+import org.springframework.stereotype.Component;+import org.springframework.web.filter.OncePerRequestFilter;++import jakarta.servlet.FilterChain;+import jakarta.servlet.ServletException;+import jakarta.servlet.http.HttpServletRequest;+import jakarta.servlet.http.HttpServletResponse;++import lombok.RequiredArgsConstructor;++import stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard;++/** Restricts an unlicensed external database to reading, setup and account/licence recovery. */+@Component+@Order(Ordered.HIGHEST_PRECEDENCE + 21)+@RequiredArgsConstructor+public class DatabaseLicenseFilter extends OncePerRequestFilter {+ private static final Set<String> LICENCE_PATHS =+ Set.of(+ "/api/v1/admin/license-key",+ "/api/v1/admin/license/resync",+ "/api/v1/admin/license-file",+ "/api/v1/user/change-password",+ "/api/v1/user/change-password-on-login",+ "/api/v1/user/change-username");+ private final DatabaseLicenseGuard guard;++ @Override+ protected void doFilterInternal(+ HttpServletRequest request, HttpServletResponse response, FilterChain chain)+ throws ServletException, IOException {+ String path = request.getRequestURI().substring(request.getContextPath().length());+ if (!path.startsWith("/api/")+ || Set.of("GET", "HEAD", "OPTIONS").contains(request.getMethod())+ || path.startsWith("/api/v1/auth/")+ || path.startsWith("/api/v1/account-link/")+ || path.startsWith("/api/v1/admin/settings/")+ || LICENCE_PATHS.contains(path)+ || !guard.requiresActivation()) {+ chain.doFilter(request, response);+ return;+ }+ response.setStatus(HttpServletResponse.SC_PAYMENT_REQUIRED);+ response.setContentType("application/json");+ response.getWriter()+ .write(+ "{\"error\":\"SERVER_PLAN_REQUIRED\",\"message\":\"Link a paid Team account or install a Server or Enterprise licence to use this database.\"}");+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.javaindex 2d34032cff..4e9112edcb 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.java@@ -2,7 +2,8 @@ package stirling.software.proprietary.security.filter;import java.io.IOException;-import org.springframework.beans.factory.annotation.Qualifier;+import org.springframework.core.Ordered;+import org.springframework.core.annotation.Order;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Component;import org.springframework.web.filter.OncePerRequestFilter;@@ -12,12 +13,15 @@ import jakarta.servlet.ServletException;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;+import stirling.software.common.service.LicenseServiceInterface;+@Component+@Order(Ordered.HIGHEST_PRECEDENCE + 20)public class EnterpriseEndpointFilter extends OncePerRequestFilter {- private final boolean runningProOrHigher;+ private final LicenseServiceInterface licenseService;- public EnterpriseEndpointFilter(@Qualifier("runningProOrHigher") boolean runningProOrHigher) {- this.runningProOrHigher = runningProOrHigher;+ public EnterpriseEndpointFilter(LicenseServiceInterface licenseService) {+ this.licenseService = licenseService;}@Override@@ -25,7 +29,7 @@ public class EnterpriseEndpointFilter extends OncePerRequestFilter {HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {- if (!runningProOrHigher && isPrometheusEndpointRequest(request)) {+ if (isPrometheusEndpointRequest(request) && !licenseService.isRunningProOrHigher()) {// Allow only health checks to pass through for non-pro usersString uri = request.getRequestURI();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.javaindex f790cbac36..fc3fe311a0 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.java@@ -14,6 +14,7 @@ import org.springframework.http.HttpHeaders;import org.springframework.http.ResponseCookie;import org.springframework.security.authentication.LockedException;import org.springframework.security.core.Authentication;+import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;import org.springframework.security.web.savedrequest.SavedRequest;@@ -70,27 +71,12 @@ public class CustomSaml2AuthenticationSuccessHandlerboolean userExists = userService.usernameExistsIgnoreCase(username);- // Check if user is eligible for SAML (grandfathered or system has ENTERPRISE license)- if (userExists) {- stirling.software.proprietary.security.model.User user =- userService.findByUsernameIgnoreCase(username).orElse(null);-- if (user != null && !licenseSettingsService.isSamlEligible(user)) {- // User is not grandfathered and no ENTERPRISE license - block SAML login- log.warn(- "SAML2 login blocked for existing user '{}' - not eligible (not grandfathered and no ENTERPRISE license)",- username);- String origin = resolveOrigin(request);- response.sendRedirect(origin + "/logout?saml2RequiresLicense=true");- return;- }- } else if (!licenseSettingsService.isSamlEligible(null)) {- // No existing user and no ENTERPRISE license -> block auto creation- log.warn(- "SAML2 login blocked for new user '{}' - not eligible (no ENTERPRISE license for auto-creation)",- username);- String origin = resolveOrigin(request);- response.sendRedirect(origin + "/logout?saml2RequiresLicense=true");+ var user = userService.findByUsernameIgnoreCase(username).orElse(null);+ if (!licenseSettingsService.isSamlEligible(user)) {+ SecurityContextHolder.clearContext();+ HttpSession deniedSession = request.getSession(false);+ if (deniedSession != null) deniedSession.invalidate();+ response.sendRedirect(resolveOrigin() + "/logout?saml2RequiresLicense=true");return;}@@ -147,7 +133,7 @@ public class CustomSaml2AuthenticationSuccessHandlerlog.debug("User {} exists with password but is not an SSO user, redirecting to logout",username);- String origin = resolveOrigin(request);+ String origin = resolveOrigin();response.sendRedirect(origin + "/logout?oAuth2AuthenticationErrorWeb=true");return;}@@ -162,12 +148,12 @@ public class CustomSaml2AuthenticationSuccessHandlerusername,saml2Properties.getBlockRegistration(),saml2Properties.getAutoCreateUser());- String origin = resolveOrigin(request);+ String origin = resolveOrigin();response.sendRedirect(origin + "/login?errorOAuth=oAuth2AdminBlockedUser");return;}if (!userExists && licenseSettingsService.wouldExceedLimit(1)) {- String origin = resolveOrigin(request);+ String origin = resolveOrigin();response.sendRedirect(origin + "/logout?maxUsersReached=true");return;}@@ -250,7 +236,7 @@ public class CustomSaml2AuthenticationSuccessHandlerString contextPath,String jwt) {String redirectPath = resolveRedirectPath(request, contextPath);- String origin = resolveOrigin(request);+ String origin = resolveOrigin();clearRedirectCookie(response);String url = origin + redirectPath + "#access_token=" + jwt;@@ -264,23 +250,12 @@ public class CustomSaml2AuthenticationSuccessHandlerreturn url;}- /**- * Resolve the origin (frontend URL) for redirects. First checks system.frontendUrl from config,- * then falls back to detecting from request headers.- */- private String resolveOrigin(HttpServletRequest request) {- // First check if frontendUrl is configured- String configuredFrontendUrl = applicationProperties.getSystem().getFrontendUrl();- if (configuredFrontendUrl != null && !configuredFrontendUrl.trim().isEmpty()) {- return configuredFrontendUrl.trim();- }-- // Fall back to auto-detection from request headers- return resolveForwardedOrigin(request)- .orElseGet(- () ->- resolveOriginFromReferer(request)- .orElseGet(() -> buildOriginFromRequest(request)));+ // Relative redirects preserve the browser's origin without trusting proxy or Referer headers.+ private String resolveOrigin() {+ String configured = applicationProperties.getSystem().getFrontendUrl();+ return configured == null || configured.isBlank()+ ? ""+ : configured.trim().replaceAll("/+$", "");}private String resolveRedirectPath(HttpServletRequest request, String contextPath) {@@ -288,7 +263,7 @@ public class CustomSaml2AuthenticationSuccessHandlerreturn TauriOAuthUtils.defaultTauriCallbackPath(contextPath);}return extractRedirectPathFromCookie(request)- .filter(path -> path.startsWith("/"))+ .filter(CustomSaml2AuthenticationSuccessHandler::isLocalRedirectPath).orElseGet(() -> defaultCallbackPath(contextPath));}@@ -299,9 +274,12 @@ public class CustomSaml2AuthenticationSuccessHandler}for (Cookie cookie : cookies) {if (SPA_REDIRECT_COOKIE.equals(cookie.getName())) {- String value = URLDecoder.decode(cookie.getValue(), StandardCharsets.UTF_8).trim();- if (!value.isEmpty()) {- return Optional.of(value);+ try {+ String value =+ URLDecoder.decode(cookie.getValue(), StandardCharsets.UTF_8).trim();+ if (!value.isEmpty()) return Optional.of(value);+ } catch (IllegalArgumentException e) {+ return Optional.empty();}}}@@ -318,81 +296,19 @@ public class CustomSaml2AuthenticationSuccessHandlerreturn contextPath + DEFAULT_CALLBACK_PATH;}- private Optional<String> resolveForwardedOrigin(HttpServletRequest request) {- String forwardedHostHeader = request.getHeader("X-Forwarded-Host");- if (forwardedHostHeader == null || forwardedHostHeader.isBlank()) {- return Optional.empty();- }- String host = forwardedHostHeader.split(",")[0].trim();- if (host.isEmpty()) {- return Optional.empty();- }-- String forwardedProtoHeader = request.getHeader("X-Forwarded-Proto");- String proto =- (forwardedProtoHeader == null || forwardedProtoHeader.isBlank())- ? request.getScheme()- : forwardedProtoHeader.split(",")[0].trim();-- if (!host.contains(":")) {- String forwardedPort = request.getHeader("X-Forwarded-Port");- if (forwardedPort != null- && !forwardedPort.isBlank()- && !isDefaultPort(proto, forwardedPort.trim())) {- host = host + ":" + forwardedPort.trim();- }- }- return Optional.of(proto + "://" + host);- }-- private Optional<String> resolveOriginFromReferer(HttpServletRequest request) {- String referer = request.getHeader("Referer");- if (referer != null && !referer.isEmpty()) {- try {- URI refererUri = URI.create(referer);- String host = refererUri.getHost();- if (host == null) {- return Optional.empty();- }- String origin = refererUri.getScheme() + "://" + host;- int port = refererUri.getPort();- if (port != -1 && port != 80 && port != 443) {- origin += ":" + port;- }- return Optional.of(origin);- } catch (IllegalArgumentException e) {- log.debug(- "Malformed referer URL: {}, falling back to request-based origin", referer);- }- }- return Optional.empty();- }-- private String buildOriginFromRequest(HttpServletRequest request) {- String scheme = request.getScheme();- String serverName = request.getServerName();- int serverPort = request.getServerPort();-- StringBuilder origin = new StringBuilder();- origin.append(scheme).append("://").append(serverName);-- if ((!"http".equalsIgnoreCase(scheme) || serverPort != 80)- && (!"https".equalsIgnoreCase(scheme) || serverPort != 443)) {- origin.append(":").append(serverPort);- }-- return origin.toString();- }-- private boolean isDefaultPort(String scheme, String port) {- if (port == null) {- return true;- }+ private static boolean isLocalRedirectPath(String path) {try {- int parsedPort = Integer.parseInt(port);- return ("http".equalsIgnoreCase(scheme) && parsedPort == 80)- || ("https".equalsIgnoreCase(scheme) && parsedPort == 443);- } catch (NumberFormatException e) {+ URI uri = URI.create(path);+ String decoded = uri.getPath();+ return !uri.isAbsolute()+ && uri.getRawAuthority() == null+ && uri.getRawFragment() == null+ && decoded != null+ && decoded.startsWith("/")+ && !decoded.startsWith("//")+ && !decoded.contains("\\")+ && decoded.chars().noneMatch(c -> c < 32 || c == 127);+ } catch (IllegalArgumentException e) {return false;}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.javaindex 09b767a6d1..d73550510f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.java@@ -67,7 +67,7 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa}private boolean hasProOrEnterpriseAccess() {- License license = licenseKeyChecker.getPremiumLicenseEnabledResult();+ License license = licenseKeyChecker.premiumTier();return license == License.SERVER || license == License.ENTERPRISE;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.javaindex fa83432639..7b18312dfe 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java@@ -4,6 +4,7 @@ import java.nio.charset.StandardCharsets;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.util.Base64;+import java.util.Objects;import java.util.Optional;import java.util.UUID;@@ -162,13 +163,18 @@ public class UserLicenseSettingsService {/*** Updates the license max users from the application properties. This should be called when the* license is validated.+ *+ * <p>Keyed on the licence <i>key</i>'s tier, not on the effective one: {@code premium.maxUsers}+ * is a figure only a licence carries, and a Team plan bought in the cloud leaves it unset.+ * Reading the effective tier would store 0 for such an instance, which {@link+ * #calculateMaxAllowedUsers()} reads as "SERVER licence, unlimited users".*/@Transactionalpublic void updateLicenseMaxUsers() {UserLicenseSettings settings = getOrCreateSettings();int licenseMaxUsers = 0;- if (hasPaidLicense()) {+ if (hasLicenseKeyPaidTier()) {licenseMaxUsers = applicationProperties.getPremium().getMaxUsers();}@@ -317,6 +323,11 @@ public class UserLicenseSettingsService {* <p>IMPORTANT: Paid licenses REPLACE the limit, they don't add to grandfathering. A linked* team's allowance does not: linking is monotonic, so it can only raise the ceiling.*+ * <p>The branch is chosen by whether a licence <i>key</i> is installed, never by the effective+ * tier. A Team plan bought in the cloud promotes the effective tier to SERVER without carrying+ * a {@code premium.maxUsers}, so branching on the effective tier would read the stored 0 as+ * "SERVER licence, unlimited" and hand a customer who bought 100 users no limit at all.+ ** @return Maximum number of users allowed (Integer.MAX_VALUE for unlimited)*/public int calculateMaxAllowedUsers() {@@ -334,7 +345,7 @@ public class UserLicenseSettingsService {// all, so in the end state only Enterprise holds one, and Enterprise should outrank SaaS:// it is contracted and has to keep working offline. Until then a legacy licence keeps// whatever it granted, and a customer worse off under it can simply remove it.- if (!hasPaidLicense()) {+ if (!hasLicenseKeyPaidTier()) {Integer fromSaas = linkedTeamAllowance();if (fromSaas != null) {// Floored at the grandfathered limit, so linking can only raise the ceiling.@@ -368,23 +379,77 @@ public class UserLicenseSettingsService {return licenseMaxUsers;}+ /** Paid capacity for the current linked device, retaining its last allowance while offline. */+ private Integer linkedTeamAllowance() {+ return refreshLinkedTeamUsers();+ }++ /** Only a previously purchased Team grant permits infrastructure to boot in recovery mode. */+ public boolean isTeamOfflineExpired() {+ EntitlementCache cache = entitlementCache.getIfAvailable();+ if (cache == null) return false;+ cache.current();+ var settings = getOrCreateSettings();+ return cache.isGraceExpired()+ && settings.getLinkedTeamUsers() != null+ && settings.getLinkedTeamUsers() > 0+ && Objects.equals(cache.linkedDeviceId(), settings.getLinkedTeamDeviceId());+ }++ /**+ * Drops the cached entitlement so the next read goes to SaaS. For a caller with reason to+ * believe the plan just changed; the ordinary path waits out the cache's own TTL.+ */+ public void forgetEntitlement() {+ EntitlementCache cache = entitlementCache.getIfAvailable();+ if (cache != null) {+ cache.invalidate();+ }+ }++ private Optional<InstanceEntitlement> currentEntitlement() {+ EntitlementCache cache = entitlementCache.getIfAvailable();+ return cache == null ? Optional.empty() : cache.current();+ }+/**- * Users this instance's linked team is entitled to, or null when SaaS is not the authority- * here.+ * Records the linked team's purchased user allowance on the licence row and returns it, or+ * returns the stored value when SaaS has said nothing.*- * <p>Only consulted when no licence is installed. Null covers three indistinguishable cases- * that all fall through to the grandfathered limit: the instance is not linked, SaaS has never- * answered, or it answered with no user limit — which is also what an older SaaS sends.+ * <p>Called from the licence sync, which is what makes the stored value SaaS-derived rather+ * than a local claim: a plan that lapses comes back as no allowance and clears the column. An+ * unreachable SaaS preserves the allowance only for the same linked device. Unlinking or+ * replacing that identity clears it; a new link must obtain its own entitlement.*- * <p>When SaaS is merely unreachable, {@link EntitlementCache} keeps serving the freshest- * snapshot it has, so a linked instance holds its last known allowance rather than losing it.+ * <p>Not transactional: asking the cache can mean an HTTP round trip to SaaS, and there is no+ * invariant here worth holding a database connection across one. The single conditional write+ * carries its own transaction.+ *+ * @return users the linked team has bought, or null when it has bought none*/- private Integer linkedTeamAllowance() {+ public Integer refreshLinkedTeamUsers() {+ UserLicenseSettings settings = getOrCreateSettings();EntitlementCache cache = entitlementCache.getIfAvailable();- if (cache == null) {- return null;+ String deviceId = cache == null ? null : cache.linkedDeviceId();+ if (!Objects.equals(deviceId, settings.getLinkedTeamDeviceId())+ || (deviceId == null && settings.getLinkedTeamUsers() != null)) {+ settings.setLinkedTeamUsers(null);+ settings.setLinkedTeamDeviceId(deviceId);+ settingsRepository.save(settings);}- return cache.current().map(InstanceEntitlement::licensedUsers).orElse(null);+ if (deviceId == null) return null;+ Optional<InstanceEntitlement> answer = currentEntitlement();+ if (cache.isGraceExpired()) return null;+ if (answer.isEmpty()) {+ return settings.getLinkedTeamUsers();+ }+ Integer purchased = answer.get().licensedUsers();+ if (!Objects.equals(settings.getLinkedTeamUsers(), purchased)) {+ settings.setLinkedTeamUsers(purchased);+ settingsRepository.save(settings);+ log.info("Linked team user allowance is now {}", purchased);+ }+ return purchased;}/**@@ -610,19 +675,36 @@ public class UserLicenseSettingsService {}}- private boolean hasPaidLicense() {+ /** Whether the effective tier includes Server features. */+ public boolean hasPaidLicense() {LicenseKeyChecker checker = licenseKeyChecker.getIfAvailable();if (checker == null) {return false;}- License license = checker.getPremiumLicenseEnabledResult();+ License license = checker.premiumTier();boolean hasPaid = (license == License.SERVER || license == License.ENTERPRISE);log.info("License check result: type={}, requiresPaid=true, hasPaid={}", license, hasPaid);return hasPaid;}+ /**+ * Whether an installed licence key alone grants a paid tier.+ *+ * <p>The seat arithmetic needs this rather than {@link #hasPaidLicense()}: the effective tier+ * is also SERVER when the promotion comes from a cloud Team plan, and that plan states its+ * capacity in the entitlement, not in {@code premium.maxUsers}.+ */+ private boolean hasLicenseKeyPaidTier() {+ LicenseKeyChecker checker = licenseKeyChecker.getIfAvailable();+ if (checker == null) {+ return false;+ }+ License license = checker.getLicenseKeyResult();+ return license == License.SERVER || license == License.ENTERPRISE;+ }+/*** Checks if the system has an ENTERPRISE license. Used for enterprise-only features like SSO* (OAuth/SAML).@@ -635,7 +717,7 @@ public class UserLicenseSettingsService {return false;}- License license = checker.getPremiumLicenseEnabledResult();+ License license = checker.premiumTier();log.info("License check result: type={}, requiresEnterprise=true, hasEnterprise={}",license,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/ClusterStorageGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/ClusterStorageGate.javaindex 07320a9ce7..1720800b68 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/ClusterStorageGate.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/ClusterStorageGate.java@@ -5,6 +5,7 @@ import java.util.Optional;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Configuration;+import org.springframework.context.annotation.DependsOn;import jakarta.annotation.PostConstruct;@@ -22,6 +23,7 @@ import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker* cluster.artifactStore=s3}) is accompanied by a valid Pro / Enterprise license.*/@Configuration+@DependsOn("runningProOrHigher")@RequiredArgsConstructor@Slf4jpublic class ClusterStorageGate {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/StorageProviderConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/StorageProviderConfig.javaindex 1217d81cc8..4a6dade758 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/StorageProviderConfig.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/config/StorageProviderConfig.java@@ -9,6 +9,7 @@ import java.util.Optional;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;+import org.springframework.context.annotation.DependsOn;import org.springframework.transaction.PlatformTransactionManager;import org.springframework.transaction.TransactionDefinition;import org.springframework.transaction.support.TransactionOperations;@@ -31,6 +32,7 @@ import stirling.software.proprietary.storage.crypto.FileEncryptionMasterKey;import stirling.software.proprietary.storage.crypto.StorageEncryptionAuditListener;import stirling.software.proprietary.storage.crypto.StorageEncryptionState;import stirling.software.proprietary.storage.provider.DatabaseStorageProvider;+import stirling.software.proprietary.storage.provider.LicensedStorageProvider;import stirling.software.proprietary.storage.provider.LocalStorageProvider;import stirling.software.proprietary.storage.provider.S3StorageProvider;import stirling.software.proprietary.storage.provider.StorageProvider;@@ -38,6 +40,7 @@ import stirling.software.proprietary.storage.repository.FileEncryptionKeyRepositimport stirling.software.proprietary.storage.repository.StoredFileBlobRepository;@Configuration+@DependsOn("runningProOrHigher")@RequiredArgsConstructor@Slf4jpublic class StorageProviderConfig {@@ -137,8 +140,25 @@ public class StorageProviderConfig {@Bean(destroyMethod = "close")public StorageProvider storageProvider(StorageEncryptionState encryptionState, Optional<TempFileManager> tempFileManager) {- return new EncryptingStorageProvider(- innerStorageProvider(), encryptionState, tempFileManager.orElse(null));+ StorageProvider provider =+ new EncryptingStorageProvider(+ innerStorageProvider(), encryptionState, tempFileManager.orElse(null));+ String providerName =+ Optional.ofNullable(applicationProperties.getStorage().getProvider())+ .orElse("local")+ .trim();+ boolean paidStorage =+ encryptionState.isWriteEnabled()+ || "s3".equalsIgnoreCase(providerName)+ || "database".equalsIgnoreCase(providerName);+ return paidStorage+ ? new LicensedStorageProvider(+ provider,+ () -> {+ License tier = licenseKeyChecker.premiumTier();+ return tier == License.SERVER || tier == License.ENTERPRISE;+ })+ : provider;}private StorageProvider innerStorageProvider() {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/provider/LicensedStorageProvider.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/provider/LicensedStorageProvider.javanew file mode 100644index 0000000000..b713a8e970--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/provider/LicensedStorageProvider.java@@ -0,0 +1,45 @@+package stirling.software.proprietary.storage.provider;++import java.io.IOException;+import java.net.URI;+import java.time.Duration;+import java.util.Optional;+import java.util.function.BooleanSupplier;++import org.springframework.core.io.Resource;+import org.springframework.web.multipart.MultipartFile;++import stirling.software.proprietary.security.model.User;++/** Stops new paid storage writes while keeping existing content readable after entitlement loss. */+public record LicensedStorageProvider(StorageProvider delegate, BooleanSupplier licensed)+ implements StorageProvider {+ @Override+ public StoredObject store(User owner, MultipartFile file) throws IOException {+ if (!licensed.getAsBoolean())+ throw new IOException(+ "Paid storage is paused. Restore the Stirling account connection or a valid licence.");+ return delegate.store(owner, file);+ }++ @Override+ public Resource load(String key) throws IOException {+ return delegate.load(key);+ }++ @Override+ public void delete(String key) throws IOException {+ delegate.delete(key);+ }++ @Override+ public Optional<URI> signedDownloadUrl(String key, Duration ttl, boolean inline, String name)+ throws IOException {+ return delegate.signedDownloadUrl(key, ttl, inline, name);+ }++ @Override+ public void close() {+ delegate.close();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkServiceTest.javaindex 410ef8a8c7..b396712daa 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkServiceTest.java@@ -7,6 +7,7 @@ import static org.mockito.Mockito.mock;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.time.Instant;import java.time.LocalDateTime;import java.util.Optional;@@ -40,8 +41,15 @@ class AccountLinkServiceTest {stored.setLinkedAt(LocalDateTime.now());when(store.get()).thenReturn(Optional.of(stored));- AccountLinkService.LinkStatus status = service.status();+ var connection =+ new EntitlementCache.ConnectionStatus(+ "expired", Instant.EPOCH, Instant.EPOCH.plusSeconds(259200));+ when(cache.connectionStatus()).thenReturn(connection);+ AccountLinkService.LinkStatus status = service.recheck();+ assertEquals(connection, status.connection());+ verify(cache).invalidate();+ verify(cache).current();assertTrue(status.linked());assertEquals("dev-1", status.deviceId());assertEquals(7L, status.teamId());diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/DeviceEntitlementContactDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/DeviceEntitlementContactDbTest.javanew file mode 100644index 0000000000..4e9a18faaa--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/DeviceEntitlementContactDbTest.java@@ -0,0 +1,45 @@+package stirling.software.proprietary.accountlink;++import static org.assertj.core.api.Assertions.assertThat;++import java.time.Instant;+import java.time.LocalDateTime;++import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.boot.SpringBootConfiguration;+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;++@DataJpaTest+class DeviceEntitlementContactDbTest {+ @Autowired DeviceCredentialRepository repository;++ @Test+ void successfulContactIsDurableAndOlderOrWrongDeviceResponsesCannotExtendIt() {+ var device = new DeviceCredential();+ device.setDeviceId("current");+ device.setDeviceSecret("secret");+ device.setLinkedAt(LocalDateTime.of(2026, 9, 15, 0, 0));+ repository.saveAndFlush(device);+ Instant contact = Instant.parse("2026-09-15T10:00:00Z");+ assertThat(repository.recordEntitlementContact("current", contact, true)).isEqualTo(1);+ var restored = repository.findCredential().orElseThrow();+ assertThat(restored.getLastEntitlementSuccessAt()).isEqualTo(contact);+ assertThat(restored.isEntitlementRevoked()).isTrue();+ assertThat(+ repository.recordEntitlementContact(+ "old-device", contact.plusSeconds(20), false))+ .isZero();+ assertThat(repository.recordEntitlementContact("current", contact.minusSeconds(1), false))+ .isZero();+ assertThat(repository.findCredential().orElseThrow().isEntitlementRevoked()).isTrue();+ assertThat(repository.recordEntitlementContact("current", contact.plusSeconds(1), false))+ .isEqualTo(1);+ assertThat(repository.findCredential().orElseThrow().isEntitlementRevoked()).isFalse();+ }++ @SpringBootConfiguration+ @AutoConfigurationPackage+ static class TestApp {}+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.javaindex 7bd6491887..c008d67470 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java@@ -118,7 +118,7 @@ class EnterpriseProcessingHttpIntegrationTest {signatures.deleteAll();cloudCounters.deleteAll();syncState.deleteAll();- when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseChecker.premiumTier()).thenReturn(License.ENTERPRISE);localUsage.accrue(BillingCategory.AUTOMATION, SPENT_GRANT, null);assertThat(localUsage.balance().remainingUnits()).isZero();}@@ -201,7 +201,7 @@ class EnterpriseProcessingHttpIntegrationTest {assertConvertedPdf(convert(input));assertLocalUsage(SPENT_GRANT + PDF_UNITS);- when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(nextLicense);+ when(licenseChecker.premiumTier()).thenReturn(nextLicense);HttpResponse<byte[]> response = convert(input);assertThat(response.statusCode()).isEqualTo(402);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementCacheTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementCacheTest.javaindex 3dbeb1ef5c..516f3fd17b 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementCacheTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementCacheTest.java@@ -40,6 +40,19 @@ class EntitlementCacheTest {return c;}+ @Test+ void relinkingDoesNotReuseAnotherDevicesEntitlement() {+ when(store.get()).thenReturn(Optional.of(cred()));+ when(client.fetchEntitlement(anyString(), anyString()))+ .thenReturn(new InstanceEntitlement(true, 0, 1, 100L, EntitlementState.OK));+ assertTrue(cache.current().isPresent());+ DeviceCredential other = cred();+ other.setDeviceId("dev-2");+ when(store.get()).thenReturn(Optional.of(other));+ when(client.fetchEntitlement(anyString(), anyString())).thenReturn(null);+ assertTrue(cache.current().isEmpty());+ }+@Testvoid unlinked_returnsEmpty() {when(store.get()).thenReturn(Optional.empty());@@ -111,4 +124,12 @@ class EntitlementCacheTest {cache.current();verify(client, times(2)).fetchEntitlement(any(), any());}++ @Test+ void syncReplyFromPreviousDeviceDoesNotRestoreItsAllowance() {+ when(store.get()).thenReturn(Optional.of(cred()));+ cache.accept(+ "previous-device", new InstanceEntitlement(true, 0, 1, 100L, EntitlementState.OK));+ assertTrue(cache.current().isEmpty());+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementOfflineTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementOfflineTest.javanew file mode 100644index 0000000000..2b175c8551--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementOfflineTest.java@@ -0,0 +1,123 @@+package stirling.software.proprietary.accountlink;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.*;+import static org.mockito.Mockito.*;++import java.time.*;+import java.util.Optional;+import java.util.concurrent.atomic.AtomicReference;++import org.junit.jupiter.api.Test;++class EntitlementOfflineTest {+ @Test+ void authoritativeRevocationSurvivesRestartWithoutACloudConnection() {+ Instant now = Instant.parse("2026-09-15T10:00:00Z");+ var device = new DeviceCredential();+ device.setDeviceId("device");+ device.setDeviceSecret("secret");+ device.setLinkedAt(LocalDateTime.ofInstant(now, ZoneOffset.UTC));+ var store = mock(DeviceCredentialStore.class);+ when(store.get()).thenReturn(Optional.of(device));+ doAnswer(+ inv -> {+ device.setLastEntitlementSuccessAt(inv.getArgument(1));+ device.setEntitlementRevoked(inv.getArgument(2));+ return null;+ })+ .when(store)+ .recordEntitlementContact(eq("device"), any(), anyBoolean());+ var client = mock(AccountLinkClient.class);+ when(client.fetchEntitlement("device", "secret"))+ .thenThrow(new AccountLinkClient.RevokedException(401));+ var properties = new AccountLinkProperties();+ var clock = Clock.fixed(now, ZoneOffset.UTC);+ var cache = new EntitlementCache(store, client, properties, clock);+ assertThat(cache.current().orElseThrow().state()).isEqualTo(EntitlementState.REVOKED);+ var offlineClient = mock(AccountLinkClient.class);+ var restarted = new EntitlementCache(store, offlineClient, properties, clock);+ assertThat(restarted.current().orElseThrow().state()).isEqualTo(EntitlementState.REVOKED);+ assertThat(restarted.connectionStatus().state()).isEqualTo("revoked");+ when(offlineClient.fetchEntitlement("device", "secret"))+ .thenReturn(+ new InstanceEntitlement(+ true, 0, 0, null, EntitlementState.OK, null, null, null, 300));+ restarted.invalidate();+ assertThat(restarted.current().orElseThrow().state()).isEqualTo(EntitlementState.OK);+ assertThat(restarted.connectionStatus().state()).isEqualTo("connected");+ }++ @Test+ void staleCacheAndRestartCannotExtendDeadlineAndReconnectionRestoresAccess() {+ Instant start = Instant.parse("2026-09-15T10:00:00Z");+ AtomicReference<Instant> now = new AtomicReference<>(start);+ Clock clock = mock(Clock.class);+ when(clock.instant()).thenAnswer(inv -> now.get());+ when(clock.getZone()).thenReturn(ZoneOffset.UTC);+ DeviceCredential device = new DeviceCredential();+ device.setDeviceId("device");+ device.setDeviceSecret("secret");+ device.setLinkedAt(+ LocalDateTime.ofInstant(start.minus(Duration.ofDays(10)), ZoneOffset.UTC));+ DeviceCredentialStore store = mock(DeviceCredentialStore.class);+ when(store.get()).thenReturn(Optional.of(device));+ doAnswer(+ inv -> {+ device.setLastEntitlementSuccessAt(inv.getArgument(1));+ return null;+ })+ .when(store)+ .recordEntitlementContact(eq("device"), any(), anyBoolean());+ AccountLinkClient client = mock(AccountLinkClient.class);+ AccountLinkProperties properties = new AccountLinkProperties();+ InstanceEntitlement paid =+ new InstanceEntitlement(+ true, 0, 0, null, EntitlementState.OK, null, null, null, 300);+ when(client.fetchEntitlement("device", "secret")).thenReturn(paid);+ EntitlementCache cache = new EntitlementCache(store, client, properties, clock);+ assertThat(cache.current()).contains(paid);+ now.set(start.plus(Duration.ofDays(3)).minusMillis(1));+ when(client.fetchEntitlement("device", "secret")).thenReturn(null);+ assertThat(cache.current()).contains(paid);+ assertThat(cache.isGraceExpired()).isFalse();+ now.set(start.plus(Duration.ofDays(3)));+ assertThat(cache.current()).contains(paid);+ assertThat(cache.isGraceExpired()).isTrue();+ assertThat(device.getLastEntitlementSuccessAt()).isEqualTo(start);+ EntitlementCache restarted = new EntitlementCache(store, client, properties, clock);+ assertThat(restarted.current()).isEmpty();+ assertThat(restarted.isGraceExpired()).isTrue();+ when(client.fetchEntitlement("device", "secret")).thenReturn(paid);+ restarted.invalidate();+ assertThat(restarted.current()).contains(paid);+ assertThat(restarted.isGraceExpired()).isFalse();+ assertThat(restarted.connectionStatus().state()).isEqualTo("connected");+ }++ @Test+ void aReplacementDeviceCannotUseThePreviousDevicesSuccessfulContact() {+ Instant now = Instant.parse("2026-09-15T10:00:00Z");+ DeviceCredential device = new DeviceCredential();+ device.setDeviceId("old");+ device.setDeviceSecret("secret");+ device.setLinkedAt(LocalDateTime.ofInstant(now.minus(Duration.ofDays(4)), ZoneOffset.UTC));+ DeviceCredentialStore store = mock(DeviceCredentialStore.class);+ when(store.get()).thenReturn(Optional.of(device));+ AccountLinkClient client = mock(AccountLinkClient.class);+ when(client.fetchEntitlement("old", "secret"))+ .thenReturn(+ new InstanceEntitlement(+ true, 0, 0, null, EntitlementState.OK, null, null, null, 300));+ EntitlementCache cache =+ new EntitlementCache(+ store,+ client,+ new AccountLinkProperties(),+ Clock.fixed(now, ZoneOffset.UTC));+ cache.current();+ device.setDeviceId("replacement");+ assertThat(cache.current()).isEmpty();+ assertThat(cache.isGraceExpired()).isTrue();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.javaindex 016c308551..edfe8c2068 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java@@ -266,7 +266,6 @@ class InstanceEntitlementGateTest {props,credentialStore,entitlementCache,- syncStateRepository,localUsageService,freeTierUsageService,licenseService);@@ -281,46 +280,16 @@ class InstanceEntitlementGateTest {}@Test- void evaluate_meteringOff_unreachable_failsOpen_neverGraceBlocks() {+ void cachedPaidEntitlementExpiresEvenWithMeteringDisabledAndRecovers() {when(credentialStore.isLinked()).thenReturn(true);- when(entitlementCache.current()).thenReturn(Optional.empty());-- GateDecision d = gate(props(false, 3)).evaluate(true);-- // Metering off → grace never applies, even if a sync is ancient.- assertTrue(d.allowed());- assertEquals(Reason.FAIL_OPEN, d.reason());- }-- @Test- void evaluate_neverSynced_pastGraceSinceLink_blocks() {- when(credentialStore.isLinked()).thenReturn(true);- when(entitlementCache.current()).thenReturn(Optional.empty());- when(syncStateRepository.findById(AccountLinkSyncState.SINGLETON_ID))- .thenReturn(Optional.empty());- DeviceCredential cred = new DeviceCredential();- cred.setLinkedAt(LocalDateTime.now().minusDays(5));- when(credentialStore.get()).thenReturn(Optional.of(cred));-- GateDecision d = gate(props(true, 3)).evaluate(true);-- assertFalse(d.allowed());- assertEquals(Reason.GRACE_EXPIRED, d.reason());- }-- @Test- void evaluate_recentSync_withinGrace_failsOpen() {- when(credentialStore.isLinked()).thenReturn(true);- when(entitlementCache.current()).thenReturn(Optional.empty());- AccountLinkSyncState state = new AccountLinkSyncState();- state.setLastSuccessAt(LocalDateTime.now().minusDays(1));- when(syncStateRepository.findById(AccountLinkSyncState.SINGLETON_ID))- .thenReturn(Optional.of(state));-- GateDecision d = gate(props(true, 3)).evaluate(true);-- assertTrue(d.allowed());- assertEquals(Reason.FAIL_OPEN, d.reason());+ when(entitlementCache.current())+ .thenReturn(+ Optional.of(+ new InstanceEntitlement(true, 0, 0, null, EntitlementState.OK)));+ when(entitlementCache.isGraceExpired()).thenReturn(true, false);+ InstanceEntitlementGate gate = gate(props(false, 3));+ assertEquals(Reason.GRACE_EXPIRED, gate.evaluate(true).reason());+ assertTrue(gate.evaluate(true).allowed());}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.javaindex c48f216967..b8c10629ab 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java@@ -68,7 +68,7 @@ class InstanceEntitlementGateWiringTest {@Testvoid enterpriseBypassesExhaustedLocalCredits() {- when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseChecker.premiumTier()).thenReturn(License.ENTERPRISE);when(freeTier.balance()).thenReturn(grant(0));assertEquals(@@ -80,7 +80,7 @@ class InstanceEntitlementGateWiringTest {@ParameterizedTest@EnumSource(EntitlementState.class)void enterpriseBypassesLinkedBillingRestrictions(EntitlementState state) {- when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseChecker.premiumTier()).thenReturn(License.ENTERPRISE);when(store.isLinked()).thenReturn(true);when(cache.current()).thenReturn(Optional.of(new InstanceEntitlement(true, 0, 100, 100L, state)));@@ -95,7 +95,7 @@ class InstanceEntitlementGateWiringTest {@Testvoid enterpriseBypassesExpiredCloudSyncGrace() {- when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseChecker.premiumTier()).thenReturn(License.ENTERPRISE);properties.getMetering().setEnabled(true);when(store.isLinked()).thenReturn(true);when(cache.current()).thenReturn(Optional.empty());@@ -114,7 +114,7 @@ class InstanceEntitlementGateWiringTest {value = License.class,names = {"NORMAL", "SERVER"})void nonEnterpriseLicensesStillEnforceCredits(License license) {- when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(license);+ when(licenseChecker.premiumTier()).thenReturn(license);when(freeTier.balance()).thenReturn(grant(0));assertFalse(gate.evaluate(true).allowed());@@ -122,7 +122,7 @@ class InstanceEntitlementGateWiringTest {@Testvoid licenseChangesTakeEffectOnTheSameGate() {- when(licenseChecker.getPremiumLicenseEnabledResult())+ when(licenseChecker.premiumTier()).thenReturn(License.NORMAL, License.ENTERPRISE, License.NORMAL);when(freeTier.balance()).thenReturn(grant(0));@@ -175,7 +175,7 @@ class InstanceEntitlementGateWiringTest {@Testvoid enterpriseProcessingDoesNotConsultLinkStatusOrCreditBalances() {- when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseChecker.premiumTier()).thenReturn(License.ENTERPRISE);GateDecision decision = gate.evaluate(true);assertTrue(decision.allowed());assertEquals(GateDecision.Reason.ENTERPRISE_LICENSE, decision.reason());@@ -184,8 +184,7 @@ class InstanceEntitlementGateWiringTest {@Testvoid removingEnterpriseLicenseRestoresCreditEnforcementWithoutRestart() {- when(licenseChecker.getPremiumLicenseEnabledResult())- .thenReturn(License.ENTERPRISE, License.NORMAL);+ when(licenseChecker.premiumTier()).thenReturn(License.ENTERPRISE, License.NORMAL);assertTrue(gate.evaluate(true).allowed());when(store.isLinked()).thenReturn(false);when(freeTier.balance()).thenReturn(grant(0));diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.javaindex 1b1ade7e80..374008db71 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.java@@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.scheduling.config.ScheduledTaskRegistrar;@ExtendWith(MockitoExtension.class)@@ -31,6 +32,8 @@ class UsageSyncServiceTest {@Mock private AccountLinkClient client;@Mock private EntitlementCache entitlementCache;+ @Mock private ApplicationEventPublisher events;+private UsageSyncService service;private final LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);@@ -43,7 +46,8 @@ class UsageSyncServiceTest {credentialStore,client,entitlementCache,- new AccountLinkProperties());+ new AccountLinkProperties(),+ events);}@Test@@ -52,7 +56,13 @@ class UsageSyncServiceTest {props.getMetering().setSyncIntervalHours(6);UsageSyncService svc =new UsageSyncService(- counters, syncState, credentialStore, client, entitlementCache, props);+ counters,+ syncState,+ credentialStore,+ client,+ entitlementCache,+ props,+ events);ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();svc.configureTasks(registrar);@@ -84,7 +94,7 @@ class UsageSyncServiceTest {service.syncNow();- verifyNoInteractions(client, entitlementCache);+ verifyNoInteractions(client, entitlementCache, events);verify(counters, never()).findPeriodsWithUnsyncedUsage();}@@ -100,9 +110,10 @@ class UsageSyncServiceTest {// surfaces on the gate immediately instead of waiting out the entitlement-cache TTL.verifyNoInteractions(client);verify(syncState, never()).save(any());- verify(entitlementCache, never()).accept(any());+ verify(entitlementCache, never()).accept(any(), any());verify(entitlementCache).invalidate();verify(entitlementCache).current();+ verify(events).publishEvent(any(EntitlementRefreshedEvent.class));}@Test@@ -131,7 +142,8 @@ class UsageSyncServiceTest {verify(counters, never()).markSynced(eq(period), eq("AUTOMATION"), anyLong());// Two saves: the pre-report seq reservation + the post-success timestamp.verify(syncState, times(2)).save(state);- verify(entitlementCache).accept(fresh);+ verify(entitlementCache).accept("dev-1", fresh);+ verify(events).publishEvent(any(EntitlementRefreshedEvent.class));}@Test@@ -149,7 +161,10 @@ class UsageSyncServiceTest {verify(counters, never()).markSynced(any(), any(), anyLong());verify(syncState, times(1)).save(state); // seq reserved, success not recorded- verify(entitlementCache).accept(null); // nothing fresh adopted+ verify(entitlementCache).accept("dev-1", null); // nothing fresh adopted+ // accept() no-ops on null, so saying the entitlement was refreshed would be a lie: the+ // licence tier listens to this and would re-read a plan nobody fetched.+ verify(events, never()).publishEvent(any(EntitlementRefreshedEvent.class));}@Test@@ -166,6 +181,6 @@ class UsageSyncServiceTest {service.syncNow();verify(counters, never()).markSynced(any(), any(), anyLong());- verify(entitlementCache, never()).accept(any());+ verify(entitlementCache, never()).accept(any(), any());}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/cluster/ClusterLicenseGateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/cluster/ClusterLicenseGateTest.javaindex 49920076d1..210542204c 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/cluster/ClusterLicenseGateTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/cluster/ClusterLicenseGateTest.java@@ -16,6 +16,12 @@ class ClusterLicenseGateTest {Field f = ClusterLicenseGate.class.getDeclaredField("runningProOrHigher");f.setAccessible(true);f.set(gate, value);+ org.springframework.test.util.ReflectionTestUtils.setField(+ gate,+ "licenseChecker",+ org.mockito.Mockito.mock(+ stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker+ .class));}private void invokeVerify(ClusterLicenseGate gate) throws Throwable {@@ -28,6 +34,19 @@ class ClusterLicenseGateTest {}}+ @Test+ void offlineTeamCanBootForRecovery() throws Exception {+ var gate = new ClusterLicenseGate();+ injectRunningProOrHigher(gate, false);+ var checker =+ org.mockito.Mockito.mock(+ stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker+ .class);+ org.mockito.Mockito.when(checker.isTeamOfflineExpired()).thenReturn(true);+ org.springframework.test.util.ReflectionTestUtils.setField(gate, "licenseChecker", checker);+ assertDoesNotThrow(() -> invokeVerify(gate));+ }+@Testvoid serverOrEnterpriseLicense_allowsClusterMode() throws Throwable {ClusterLicenseGate gate = new ClusterLicenseGate();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.javaindex 7bb6f04770..aac2ae1193 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java@@ -287,7 +287,10 @@ class PolicyEngineTest {new InProcessSourceDocCounter(),ledger,properties,- mock(PolicyAccessGuard.class));+ mock(PolicyAccessGuard.class),+ org.mockito.Mockito.mock(+ stirling.software.proprietary.security.configuration.ee+ .DatabaseLicenseGuard.class));SweepOutcome outcome = runner.run(policy);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.javaindex 18d2d1857c..f9571d44fe 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java@@ -62,6 +62,11 @@ import stirling.software.proprietary.policy.source.SourceStore;class PolicyRunnerTest {@Mock private PolicyEngine policyEngine;++ @Mock+ private stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard+ databaseLicenseGuard;+@Mock private FolderInputSource folderSource;@Mock private ProcessedLedger processedLedger;@@ -80,7 +85,15 @@ class PolicyRunnerTest {docCounter,processedLedger,new ApplicationProperties(),- reachableOwners());+ reachableOwners(),+ databaseLicenseGuard);+ }++ @Test+ void unlicensedDatabaseDoesNotClaimOrProcessSourceFiles() {+ when(databaseLicenseGuard.requiresActivation()).thenReturn(true);+ runner.run(policy(List.of(InputSpec.folder("/in"))));+ verifyNoInteractions(folderSource, policyEngine, processedLedger);}@Test@@ -110,7 +123,10 @@ class PolicyRunnerTest {new InProcessSourceDocCounter(),ledger,new ApplicationProperties(),- reachableOwners());+ reachableOwners(),+ org.mockito.Mockito.mock(+ stirling.software.proprietary.security.configuration.ee+ .DatabaseLicenseGuard.class));InputSpec spec = InputSpec.folder("/in");Policy policy = policy(List.of(spec));// One file already processed at its current version, one parked by a failed run.@@ -394,7 +410,10 @@ class PolicyRunnerTest {docCounter,processedLedger,loginOn,- guardOver(loginOn, noUsers()));+ guardOver(loginOn, noUsers()),+ org.mockito.Mockito.mock(+ stirling.software.proprietary.security.configuration.ee+ .DatabaseLicenseGuard.class));for (String owner : new String[] {null, "", "deleted-user"}) {Source source =sourceStore.save(@@ -439,7 +458,10 @@ class PolicyRunnerTest {docCounter,processedLedger,loginOn,- guardOver(loginOn, noUsers()));+ guardOver(loginOn, noUsers()),+ org.mockito.Mockito.mock(+ stirling.software.proprietary.security.configuration.ee+ .DatabaseLicenseGuard.class));SweepOutcome outcome = enforced.run(stranded.withSurface(Policy.SURFACE_PROCESSING_FOLDER));diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.javaindex 4cace860e5..dd14646b75 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java@@ -52,6 +52,7 @@ import stirling.software.proprietary.policy.source.SourceController;import stirling.software.proprietary.policy.source.SourceOverviewService;import stirling.software.proprietary.policy.store.InProcessPolicyStore;import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;+import stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard;import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.security.service.UserService;import stirling.software.proprietary.storage.model.FilePurpose;@@ -155,7 +156,8 @@ class StorageFolderAuthorizationTest {new InProcessSourceDocCounter(),new InProcessProcessedLedger(),properties,- policies);+ policies,+ mock(DatabaseLicenseGuard.class));}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/config/PremiumEndpointAspectTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/config/PremiumEndpointAspectTest.javanew file mode 100644index 0000000000..2c3904e77d--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/config/PremiumEndpointAspectTest.java@@ -0,0 +1,63 @@+package stirling.software.proprietary.security.config;++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.when;++import org.aspectj.lang.ProceedingJoinPoint;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import org.springframework.http.HttpStatus;+import org.springframework.web.server.ResponseStatusException;++import stirling.software.common.service.LicenseServiceInterface;++/**+ * The tier is not fixed for the life of the process, so this gate must not answer from a copy of+ * it. A snapshot is how a Team plan bought after boot stayed refused, and how a cancelled one would+ * stay granted.+ */+class PremiumEndpointAspectTest {++ private final LicenseServiceInterface licenseService = mock(LicenseServiceInterface.class);+ private final PremiumEndpointAspect aspect = new PremiumEndpointAspect(licenseService);++ private ProceedingJoinPoint joinPointReturning(String value) throws Throwable {+ ProceedingJoinPoint point = mock(ProceedingJoinPoint.class);+ when(point.proceed()).thenReturn(value);+ return point;+ }++ @Test+ @DisplayName("refuses below Server")+ void refusesBelowServer() throws Throwable {+ when(licenseService.isRunningProOrHigher()).thenReturn(false);++ assertThatThrownBy(() -> aspect.checkPremiumAccess(joinPointReturning("teams")))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ }++ @Test+ @DisplayName("a plan bought after boot is honoured without a restart")+ void honoursAPlanBoughtAfterBoot() throws Throwable {+ // What a purchase looks like from here: the same aspect, asked twice, answered differently.+ when(licenseService.isRunningProOrHigher()).thenReturn(false, true);++ assertThatThrownBy(() -> aspect.checkPremiumAccess(joinPointReturning("teams")))+ .isInstanceOf(ResponseStatusException.class);+ assertThat(aspect.checkPremiumAccess(joinPointReturning("teams"))).isEqualTo("teams");+ }++ @Test+ @DisplayName("a cancelled plan stops working without a restart")+ void refusesOnceCancelled() throws Throwable {+ when(licenseService.isRunningProOrHigher()).thenReturn(true, false);++ assertThat(aspect.checkPremiumAccess(joinPointReturning("teams"))).isEqualTo("teams");+ assertThatThrownBy(() -> aspect.checkPremiumAccess(joinPointReturning("teams")))+ .isInstanceOf(ResponseStatusException.class);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/DatabaseConfigTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/DatabaseConfigTest.javaindex e74c5c56c4..f8d07e4988 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/DatabaseConfigTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/DatabaseConfigTest.java@@ -25,16 +25,28 @@ class DatabaseConfigTest {@BeforeEachvoid setUp() {- databaseConfig = new DatabaseConfig(datasource, true);+ databaseConfig = new DatabaseConfig(datasource);}@Test- void testDataSource_whenRunningEEIsFalse() throws UnsupportedProviderException {- databaseConfig = new DatabaseConfig(datasource, false);-- var result = databaseConfig.dataSource();-- assertInstanceOf(DataSource.class, result);+ void configuredDatabaseRetainsExistingDataWithoutAnInstalledKey() throws Exception {+ String url = "jdbc:h2:mem:team-parity;DB_CLOSE_DELAY=-1";+ try (var connection = java.sql.DriverManager.getConnection(url, "sa", "");+ var statement = connection.createStatement()) {+ statement.execute("CREATE TABLE existing_users (name VARCHAR(40))");+ statement.execute("INSERT INTO existing_users VALUES ('existing-admin')");+ }+ when(datasource.isEnableCustomDatabase()).thenReturn(true);+ when(datasource.getCustomDatabaseUrl()).thenReturn(url);+ when(datasource.getUsername()).thenReturn("sa");+ when(datasource.getPassword()).thenReturn("");+ try (var pool = (com.zaxxer.hikari.HikariDataSource) databaseConfig.dataSource();+ var connection = pool.getConnection();+ var statement = connection.createStatement();+ var rows = statement.executeQuery("SELECT name FROM existing_users")) {+ assertTrue(rows.next());+ assertEquals("existing-admin", rows.getString(1));+ }}@Test@@ -55,7 +67,9 @@ class DatabaseConfigTest {var result = databaseConfig.dataSource();- assertInstanceOf(DataSource.class, result);+ assertEquals(+ "jdbc:postgresql://mockUrl",+ ((com.zaxxer.hikari.HikariDataSource) result).getJdbcUrl());}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.javaindex ae4fa2162d..2085f43d99 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/ee/LicenseKeyCheckerTest.java@@ -3,6 +3,8 @@ package stirling.software.proprietary.security.configuration.ee;import static org.assertj.core.api.Assertions.assertThatCode;import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.reset;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;@@ -27,6 +29,22 @@ class LicenseKeyCheckerTest {@Mock private KeygenLicenseVerifier verifier;@Mock private UserLicenseSettingsService userLicenseSettingsService;+ @Test+ void bootGateRefreshesTeamBeforeRejectingPaidConfiguration() {+ ApplicationProperties properties = new ApplicationProperties();+ when(userLicenseSettingsService.refreshLinkedTeamUsers())+ .thenThrow(new IllegalStateException("Database not initialized"))+ .thenReturn(300);+ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, properties, userLicenseSettingsService);+ checker.init();+ assertEquals(License.NORMAL, checker.getPremiumLicenseEnabledResult());+ assertThatCode(() -> checker.requireProOrEnterprise("storage.provider=s3"))+ .doesNotThrowAnyException();+ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());+ verifyNoInteractions(verifier);+ }+@Testvoid premiumDisabled_skipsVerification() {ApplicationProperties props = new ApplicationProperties();@@ -113,6 +131,197 @@ class LicenseKeyCheckerTest {.doesNotThrowAnyException();}+ /**+ * The single injection point for cloud-sold Team, which issues no licence key. Every licence+ * consumer reads getPremiumLicenseEnabledResult(), so promoting that one field is what lights+ * them up; the tests below pin the boundaries the promotion must not cross.+ */+ @Test+ void teamPlan_promotesToServerWithNoLicenceKey() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(100);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();++ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());+ // The key granted nothing, which is what keeps the seat arithmetic off premium.maxUsers.+ assertEquals(License.NORMAL, checker.getLicenseKeyResult());+ verifyNoInteractions(verifier);+ }++ /**+ * premium.enabled is how an operator declares they hold a licence. A Team buyer has none to+ * declare and never edits settings.yml, so the promotion sits outside that gate.+ */+ @Test+ void teamPlan_promotesEvenWhenPremiumIsDisabled() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ props.getPremium().setKey("dummy");+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(100);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();++ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());+ }++ /**+ * Enterprise is contracted and stays licence-only, so runningEE and every @EnterpriseEndpoint+ * keep requiring a real key however much capacity the cloud team bought.+ */+ @Test+ void teamPlan_neverPromotesToEnterprise() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(100000);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();++ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());+ }++ /** Precedence is an OR: a licence that already grants more is not lowered to SERVER. */+ @Test+ void enterpriseLicence_outranksTheTeamPlan() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(true);+ props.getPremium().setKey("ent");+ when(verifier.verifyLicense("ent")).thenReturn(License.ENTERPRISE);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();++ assertEquals(License.ENTERPRISE, checker.getPremiumLicenseEnabledResult());+ // The holding is not even consulted once the key already grants more.+ verify(userLicenseSettingsService, never()).refreshLinkedTeamUsers();+ }++ @Test+ void noTeamPlan_staysNormal() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(null);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();++ assertEquals(License.NORMAL, checker.getPremiumLicenseEnabledResult());+ }++ /**+ * init() is a @PostConstruct, so it runs long before the datasource exists. The row read+ * therefore throws rather than answering, and boot has to survive it -- the promotion is the+ * tier beans' job, not this one's.+ */+ @Test+ void unreadableHolding_doesNotBreakBoot() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ when(userLicenseSettingsService.refreshLinkedTeamUsers())+ .thenThrow(new IllegalStateException("no datasource yet"));++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);++ assertThatCode(checker::init).doesNotThrowAnyException();+ assertEquals(License.NORMAL, checker.getPremiumLicenseEnabledResult());+ }++ /** ApplicationReadyEvent is the backstop for an instance whose row was unreadable earlier. */+ @Test+ void applicationReady_appliesThePromotionTheBootReadCouldNotSee() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ when(userLicenseSettingsService.refreshLinkedTeamUsers())+ .thenThrow(new IllegalStateException("no datasource yet"))+ .thenReturn(100);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();+ assertEquals(License.NORMAL, checker.getPremiumLicenseEnabledResult());++ checker.onApplicationReady();++ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());+ verify(userLicenseSettingsService).updateLicenseMaxUsers();+ }++ /**+ * The seam between the daily sync and the tier. The sync refreshes the entitlement for its own+ * reasons and says so; nothing re-read the plan on the back of it, which is how a purchase+ * could sit unnoticed until the weekly Keygen recheck.+ */+ @Test+ void entitlementRefresh_promotesWithoutWaitingForTheLicenceRecheck() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ // Unreadable at boot, as it is on a real start: no datasource yet.+ when(userLicenseSettingsService.refreshLinkedTeamUsers())+ .thenThrow(new IllegalStateException("no datasource"));++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();+ assertEquals(License.NORMAL, checker.getPremiumLicenseEnabledResult());++ // What the sync's event stands for: the plan is now readable and says 100 users.+ reset(userLicenseSettingsService);+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(100);+ checker.onEntitlementRefreshed();++ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());+ // Still no Keygen round trip: the whole point is that this is the cheap path.+ verifyNoInteractions(verifier);+ }++ /** A cancellation travels the same seam, and must not need a restart either. */+ @Test+ void entitlementRefresh_demotesWhenThePlanIsGone() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(100);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();+ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());++ reset(userLicenseSettingsService);+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(null);+ checker.onEntitlementRefreshed();++ assertEquals(License.NORMAL, checker.getPremiumLicenseEnabledResult());+ }++ /** A read that throws leaves the tier where it was rather than silently demoting a payer. */+ @Test+ void entitlementRefresh_keepsTheTierWhenTheReadFails() {+ ApplicationProperties props = new ApplicationProperties();+ props.getPremium().setEnabled(false);+ when(userLicenseSettingsService.refreshLinkedTeamUsers()).thenReturn(100);++ LicenseKeyChecker checker =+ new LicenseKeyChecker(verifier, props, userLicenseSettingsService);+ checker.init();++ reset(userLicenseSettingsService);+ when(userLicenseSettingsService.refreshLinkedTeamUsers())+ .thenThrow(new IllegalStateException("SaaS unreachable"));+ checker.onEntitlementRefreshed();++ assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());+ }+private LicenseKeyChecker checkerWithLicense(License level) {ApplicationProperties props = new ApplicationProperties();if (level == License.NORMAL) {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminLicenseControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminLicenseControllerTest.javaindex 5dca00ff6d..4aa35d332d 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminLicenseControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminLicenseControllerTest.java@@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import java.io.IOException;@@ -189,15 +190,23 @@ class AdminLicenseControllerTest {assertThat(body(response)).containsEntry("success", false);}+ /**+ * A Team buyer has no licence key, and this endpoint is how their purchase reaches the tier+ * in seconds instead of waiting for the next daily sync. Rejecting them on a missing key+ * would break the whole path.+ */@Test- @DisplayName("returns 400 when no license key is configured")- void noKey_returnsBadRequest() {+ @DisplayName("resyncs with no license key, for a Team plan bought on a SaaS account")+ void noKey_stillResyncs() {applicationProperties.getPremium().setKey(" ");+ when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);ResponseEntity<Map<String, Object>> response = controller.resyncLicense();- assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);- assertThat(body(response)).containsEntry("success", false);+ verify(licenseKeyChecker).resyncLicense();+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);+ assertThat(body(response)).containsEntry("success", true);+ assertThat(body(response)).containsEntry("licenseType", "SERVER");}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.javaindex d2e0341c9c..6952f98223 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerMoreTest.java@@ -130,6 +130,7 @@ class InviteLinkControllerMoreTest {@Test@DisplayName("rejects assigning the INTERNAL_API_USER role")void rejectsInternalApiRole() throws Exception {+ when(userLicenseSettingsService.calculateMaxAllowedUsers()).thenReturn(5);mockMvc.perform(post("/api/v1/invite/generate").principal(adminPrincipal)diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerTest.javaindex 80e06f4d80..30ea3a08f9 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/InviteLinkControllerTest.java@@ -104,6 +104,19 @@ class InviteLinkControllerTest {.andExpect(jsonPath("$.error").value(startsWith("License limit reached")));}+ @Test+ void keylessTeamCountsPendingInvitesAgainstCapacity() throws Exception {+ applicationProperties.getPremium().setEnabled(false);+ when(userService.getTotalUsersCount()).thenReturn(299L);+ when(inviteTokenRepository.countActiveInvites(any(LocalDateTime.class))).thenReturn(1L);+ when(userLicenseSettingsService.calculateMaxAllowedUsers()).thenReturn(300);++ mockMvc.perform(post("/api/v1/invite/generate").principal(adminPrincipal))+ .andExpect(status().isBadRequest())+ .andExpect(jsonPath("$.error").value(startsWith("License limit reached (300/300")));+ verify(inviteTokenRepository, never()).save(any());+ }+@Testvoid generateInviteLinkAllowedOnServerLicense() throws Exception {// SERVER license has raw maxUsers=0, but calculateMaxAllowedUsers() returns@@ -129,6 +142,7 @@ class InviteLinkControllerTest {@Testvoid generateInviteLinkBuildsFrontendUrl() throws Exception {+ when(userLicenseSettingsService.calculateMaxAllowedUsers()).thenReturn(5);Team defaultTeam = new Team();defaultTeam.setId(5L);defaultTeam.setName(TeamService.DEFAULT_TEAM_NAME);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilterTest.javanew file mode 100644index 0000000000..b270fce3b7--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilterTest.java@@ -0,0 +1,35 @@+package stirling.software.proprietary.security.filter;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import org.junit.jupiter.api.Test;+import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.mock.web.MockHttpServletResponse;++import stirling.software.common.service.LicenseServiceInterface;++class EnterpriseEndpointFilterTest {+ @Test+ void purchaseAndRevocationChangeAccessWithoutRestart() throws Exception {+ LicenseServiceInterface license = mock(LicenseServiceInterface.class);+ EnterpriseEndpointFilter filter = new EnterpriseEndpointFilter(license);+ for (String path : new String[] {"/actuator/prometheus"}) {+ when(license.isRunningProOrHigher()).thenReturn(true);+ MockHttpServletResponse paid = new MockHttpServletResponse();+ filter.doFilter(+ new MockHttpServletRequest("GET", path),+ paid,+ (req, res) -> res.setContentType("passed"));+ assertEquals("passed", paid.getContentType());+ when(license.isRunningProOrHigher()).thenReturn(false);+ MockHttpServletResponse revoked = new MockHttpServletResponse();+ filter.doFilter(+ new MockHttpServletRequest("GET", path),+ revoked,+ (req, res) -> res.setContentType("passed"));+ assertEquals(404, revoked.getStatus());+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/LicenseFilterHttpTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/LicenseFilterHttpTest.javanew file mode 100644index 0000000000..c4d7d09969--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/LicenseFilterHttpTest.java@@ -0,0 +1,141 @@+package stirling.software.proprietary.security.filter;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.net.CookieManager;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.boot.SpringBootConfiguration;+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;+import org.springframework.boot.test.context.SpringBootTest;+import org.springframework.boot.test.web.server.LocalServerPort;+import org.springframework.context.annotation.Bean;+import org.springframework.context.annotation.Import;+import org.springframework.security.config.annotation.web.builders.HttpSecurity;+import org.springframework.security.web.SecurityFilterChain;+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;+import org.springframework.security.web.csrf.CsrfToken;+import org.springframework.web.filter.OncePerRequestFilter;++import jakarta.servlet.FilterChain;+import jakarta.servlet.http.HttpServletRequest;+import jakarta.servlet.http.HttpServletResponse;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.LicenseServiceInterface;+import stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard;++/** Exercises servlet registration order against a security chain that terminates SAML requests. */+@SpringBootTest(+ classes = LicenseFilterHttpTest.TestApp.class,+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,+ properties = "spring.datasource.url=jdbc:h2:mem:license-filter")+class LicenseFilterHttpTest {+ @LocalServerPort int port;+ @Autowired LicenseServiceInterface license;+ @Autowired ApplicationProperties properties;+ private final HttpClient client =+ HttpClient.newBuilder().cookieHandler(new CookieManager()).build();++ @BeforeEach+ void reset() {+ when(license.isRunningProOrHigher()).thenReturn(false);+ properties.getSystem().setDatasource(new ApplicationProperties.Datasource());+ }++ private int request(String method, String path) throws Exception {+ var builder = HttpRequest.newBuilder(URI.create("http://localhost:" + port + path));+ if (!"GET".equals(method)) {+ var tokenResponse =+ client.send(+ HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/csrf"))+ .GET()+ .build(),+ HttpResponse.BodyHandlers.discarding());+ builder.header(+ "X-CSRF-TOKEN",+ tokenResponse.headers().firstValue("X-CSRF-TOKEN").orElseThrow());+ }+ return client.send(+ builder.method(method, HttpRequest.BodyPublishers.noBody()).build(),+ HttpResponse.BodyHandlers.discarding())+ .statusCode();+ }++ @Test+ void samlHandshakeCanIdentifyGrandfatheredUsersWithoutAPaidPlan() throws Exception {+ for (String path :+ new String[] {+ "/saml2/authenticate/company",+ "/saml2/metadata/company",+ "/login/saml2/sso/company"+ }) {+ assertThat(request("GET", path)).isEqualTo(302);+ when(license.isRunningProOrHigher()).thenReturn(true);+ assertThat(request("GET", path)).isEqualTo(302);+ when(license.isRunningProOrHigher()).thenReturn(false);+ }+ }++ @Test+ void externalDatabaseAllowsRecoveryThenUnlocksAfterTeamActivation() throws Exception {+ properties.getSystem().getDatasource().setEnableCustomDatabase(true);+ assertThat(request("POST", "/api/v1/misc/compress-pdf")).isEqualTo(402);+ assertThat(request("POST", "/api/v1/account-link/connect/start")).isEqualTo(204);+ assertThat(request("POST", "/api/v1/user/change-password-on-login")).isEqualTo(204);+ assertThat(request("POST", "/api/v1/admin/license/resync")).isEqualTo(204);+ assertThat(request("GET", "/api/v1/files/existing")).isEqualTo(204);+ when(license.isRunningProOrHigher()).thenReturn(true);+ assertThat(request("POST", "/api/v1/misc/compress-pdf")).isEqualTo(204);+ when(license.isRunningProOrHigher()).thenReturn(false);+ assertThat(request("POST", "/api/v1/misc/compress-pdf")).isEqualTo(402);+ }++ @SpringBootConfiguration+ @EnableAutoConfiguration+ @Import({+ EnterpriseEndpointFilter.class,+ DatabaseLicenseFilter.class,+ DatabaseLicenseGuard.class+ })+ static class TestApp {+ @Bean+ ApplicationProperties properties() {+ return new ApplicationProperties();+ }++ @Bean+ LicenseServiceInterface license() {+ return mock(LicenseServiceInterface.class);+ }++ @Bean+ SecurityFilterChain security(HttpSecurity http) throws Exception {+ http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());+ http.addFilterBefore(+ new OncePerRequestFilter() {+ @Override+ protected void doFilterInternal(+ HttpServletRequest request,+ HttpServletResponse response,+ FilterChain chain) {+ CsrfToken token =+ (CsrfToken) request.getAttribute(CsrfToken.class.getName());+ response.setHeader("X-CSRF-TOKEN", token.getToken());+ response.setStatus(+ request.getRequestURI().contains("saml2") ? 302 : 204);+ }+ },+ UsernamePasswordAuthenticationFilter.class);+ return http.build();+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/saml2/SamlEligibilityTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/saml2/SamlEligibilityTest.javanew file mode 100644index 0000000000..ab49386147--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/saml2/SamlEligibilityTest.java@@ -0,0 +1,85 @@+package stirling.software.proprietary.security.saml2;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.Mockito.*;++import java.util.List;+import java.util.Map;+import java.util.Optional;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.beans.factory.ObjectProvider;+import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.mock.web.MockHttpServletResponse;+import org.springframework.mock.web.MockHttpSession;+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;+import org.springframework.security.core.context.SecurityContextHolder;+import org.springframework.security.web.savedrequest.SavedRequest;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;+import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.JwtServiceInterface;+import stirling.software.proprietary.security.service.LoginAttemptService;+import stirling.software.proprietary.security.service.UserService;+import stirling.software.proprietary.service.UserLicenseSettingsService;++class SamlEligibilityTest {+ @AfterEach+ void clear() {+ SecurityContextHolder.clearContext();+ }++ @ParameterizedTest+ @ValueSource(booleans = {true, false})+ @SuppressWarnings("unchecked")+ void verifiedIdentityDeterminesEligibilityAndDenialClearsTheSession(boolean grandfathered)+ throws Exception {+ User user = new User();+ user.setUsername("verified-user");+ user.setOauthGrandfathered(grandfathered);+ UserService users = mock(UserService.class);+ when(users.usernameExistsIgnoreCase("verified-user")).thenReturn(true);+ when(users.findByUsernameIgnoreCase("verified-user")).thenReturn(Optional.of(user));+ LicenseKeyChecker checker = mock(LicenseKeyChecker.class);+ when(checker.premiumTier()).thenReturn(License.NORMAL);+ ObjectProvider<LicenseKeyChecker> provider = mock(ObjectProvider.class);+ when(provider.getIfAvailable()).thenReturn(checker);+ ApplicationProperties properties = new ApplicationProperties();+ var eligibility = new UserLicenseSettingsService(null, users, properties, provider, null);+ var handler =+ new CustomSaml2AuthenticationSuccessHandler(+ mock(LoginAttemptService.class),+ properties.getSecurity().getSaml2(),+ users,+ mock(JwtServiceInterface.class),+ eligibility,+ properties);+ var principal =+ new CustomSaml2AuthenticatedPrincipal(+ "verified-user", Map.of(), "name", List.of(), "signed-response");+ var authentication =+ UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of());+ SecurityContextHolder.getContext().setAuthentication(authentication);+ var request = new MockHttpServletRequest();+ request.setParameter("username", "someone-grandfathered");+ var session = (MockHttpSession) request.getSession();+ SavedRequest saved = mock(SavedRequest.class);+ when(saved.getRedirectUrl()).thenReturn("http://localhost/protected");+ session.setAttribute("SPRING_SECURITY_SAVED_REQUEST", saved);+ var response = new MockHttpServletResponse();+ handler.onAuthenticationSuccess(request, response, authentication);+ if (grandfathered) {+ assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/protected");+ assertThat(session.isInvalid()).isFalse();+ } else {+ assertThat(response.getRedirectedUrl()).contains("saml2RequiresLicense=true");+ assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();+ assertThat(session.isInvalid()).isTrue();+ }+ verify(users, never()).findByUsernameIgnoreCase("someone-grandfathered");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/saml2/SamlRedirectTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/saml2/SamlRedirectTest.javanew file mode 100644index 0000000000..146241c3e0--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/saml2/SamlRedirectTest.java@@ -0,0 +1,91 @@+package stirling.software.proprietary.security.saml2;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.Mockito.*;++import java.net.URLEncoder;+import java.nio.charset.StandardCharsets;+import java.util.List;+import java.util.Map;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.mock.web.MockHttpServletResponse;+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;+import org.springframework.security.core.Authentication;++import jakarta.servlet.http.Cookie;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.service.JwtServiceInterface;+import stirling.software.proprietary.security.service.LoginAttemptService;+import stirling.software.proprietary.security.service.UserService;+import stirling.software.proprietary.service.UserLicenseSettingsService;++class SamlRedirectTest {+ @ParameterizedTest+ @ValueSource(+ strings = {+ "//attacker.example/callback",+ "/\\attacker.example/callback",+ "/%2f%2fattacker.example/callback",+ "/auth/callback#redirect",+ "/%0d%0aLocation:evil",+ "%"+ })+ void untrustedHeadersAndCookiesCannotReceiveTheToken(String path) throws Exception {+ assertThat(login(null, path, false)).isEqualTo("/auth/callback#access_token=test-token");+ }++ @Test+ void configuredFrontendAndLocalCallbackRemainSupported() throws Exception {+ assertThat(login("https://app.example", "/app/auth/callback", false))+ .isEqualTo("https://app.example/app/auth/callback#access_token=test-token");+ assertThat(login(null, "/app/auth/callback", false))+ .isEqualTo("/app/auth/callback#access_token=test-token");+ }++ @Test+ void deniedUsersStayOnTheApplicationOrigin() throws Exception {+ assertThat(login(null, "//attacker.example", true))+ .isEqualTo("/logout?saml2RequiresLicense=true");+ }++ private String login(String frontend, String path, boolean denied) throws Exception {+ var properties = new ApplicationProperties();+ properties.getSystem().setFrontendUrl(frontend);+ var eligibility = mock(UserLicenseSettingsService.class);+ when(eligibility.isSamlEligible(any())).thenReturn(!denied);+ var jwt = mock(JwtServiceInterface.class);+ when(jwt.isJwtEnabled()).thenReturn(true);+ when(jwt.generateToken(any(Authentication.class), anyMap())).thenReturn("test-token");+ var users = mock(UserService.class);+ when(users.usernameExistsIgnoreCase("verified-user")).thenReturn(true);+ var handler =+ new CustomSaml2AuthenticationSuccessHandler(+ mock(LoginAttemptService.class),+ properties.getSecurity().getSaml2(),+ users,+ jwt,+ eligibility,+ properties);+ var principal =+ new CustomSaml2AuthenticatedPrincipal(+ "verified-user", Map.of(), "name", List.of(), "signed-response");+ var authentication =+ UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of());+ var request = new MockHttpServletRequest();+ request.addHeader("Referer", "https://attacker.example/");+ request.addHeader("X-Forwarded-Host", "attacker.example");+ request.addHeader("X-Forwarded-Proto", "https");+ request.setServerName("attacker.example");+ request.setCookies(+ new Cookie(+ "stirling_redirect_path", URLEncoder.encode(path, StandardCharsets.UTF_8)));+ var response = new MockHttpServletResponse();+ handler.onAuthenticationSuccess(request, response, authentication);+ return response.getRedirectedUrl();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.javaindex e13bc7b0b4..acd0b8563b 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.java@@ -65,15 +65,11 @@ class ServerCertificateServiceTest {}private void grantProLicense() {- lenient()- .when(licenseKeyChecker.getPremiumLicenseEnabledResult())- .thenReturn(License.SERVER);+ lenient().when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);}private void denyLicense() {- lenient()- .when(licenseKeyChecker.getPremiumLicenseEnabledResult())- .thenReturn(License.NORMAL);+ lenient().when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);}// -------------------------------------------------------------------------@@ -91,7 +87,7 @@ class ServerCertificateServiceTest {@Test@DisplayName("true when feature flag on and license is ENTERPRISE")void enabledWithEnterpriseLicense() {- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);assertThat(service.isEnabled()).isTrue();}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.javaindex 420f54e95d..9a0ffd94d8 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.java@@ -57,7 +57,8 @@ class UserLicenseSettingsServiceMoreTest {when(settingsRepository.save(any(UserLicenseSettings.class))).thenAnswer(inv -> inv.getArgument(0));when(licenseKeyCheckerProvider.getIfAvailable()).thenReturn(licenseKeyChecker);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);service =new UserLicenseSettingsService(@@ -96,6 +97,7 @@ class UserLicenseSettingsServiceMoreTest {private void cacheReturns(InstanceEntitlement entitlement) {EntitlementCache cache = org.mockito.Mockito.mock(EntitlementCache.class);when(cache.current()).thenReturn(Optional.ofNullable(entitlement));+ when(cache.linkedDeviceId()).thenReturn("device-1");when(entitlementCacheProvider.getIfAvailable()).thenReturn(cache);}@@ -122,7 +124,8 @@ class UserLicenseSettingsServiceMoreTest {@DisplayName("a valid licence outranks the SaaS allowance")void licenceOutranksSaas() {lockedSettings(7);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);cacheReturns(withAllowance(100));// A SERVER licence with licenseMaxUsers = 0 is unlimited; it is not lowered to 100.@@ -173,6 +176,110 @@ class UserLicenseSettingsServiceMoreTest {assertThat(service.calculateMaxAllowedUsers()).isEqualTo(7);}+ /**+ * The failure that looks like success. Buying Team promotes the effective tier to SERVER,+ * and a SERVER licence with no {@code premium.maxUsers} means unlimited users -- so+ * branching on the effective tier hands a customer who paid for 100 users no cap at all.+ * The branch must read the licence key's own tier.+ */+ @Test+ @DisplayName("a Team plan grants the users it bought, not unlimited")+ void teamPlanIsNotAnUnlimitedLicence() {+ lockedSettings(7);+ // What buying Team does: SERVER effective, NORMAL from the key, maxUsers never set.+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);+ cacheReturns(withAllowance(100));++ assertThat(service.calculateMaxAllowedUsers()).isEqualTo(100);+ }++ /**+ * The other half of the same trap: the stored figure is what {@code licenseMaxUsers == 0}+ * is read against, so a promoted tier must not be allowed to stamp it.+ */+ @Test+ @DisplayName("a Team plan leaves licenseMaxUsers alone")+ void teamPlanDoesNotStampLicenseMaxUsers() {+ applicationProperties.getPremium().setMaxUsers(15);+ UserLicenseSettings s = new UserLicenseSettings();+ s.setIntegritySalt("salt");+ s.setLicenseMaxUsers(0);+ when(settingsRepository.findSettings()).thenReturn(Optional.of(s));+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);++ service.updateLicenseMaxUsers();++ assertThat(s.getLicenseMaxUsers()).isZero();+ }++ @Test+ @DisplayName("the stored allowance answers when SaaS has not been reached this boot")+ void storedAllowanceSurvivesABootWithNoAnswer() {+ UserLicenseSettings s = lockedSettings(7);+ s.setLinkedTeamUsers(300);+ s.setLinkedTeamDeviceId("device-1");+ cacheReturns(null);++ assertThat(service.calculateMaxAllowedUsers()).isEqualTo(300);+ }++ @Test+ @DisplayName("refresh records the purchased allowance on the licence row")+ void refreshRecordsTheAllowance() {+ UserLicenseSettings s = lockedSettings(7);+ cacheReturns(withAllowance(200));++ assertThat(service.refreshLinkedTeamUsers()).isEqualTo(200);+ assertThat(s.getLinkedTeamUsers()).isEqualTo(200);+ }++ /** A cancelled plan comes back as no allowance, and the stored figure has to follow. */+ @Test+ @DisplayName("refresh clears the allowance when SaaS says there is none")+ void refreshClearsALapsedAllowance() {+ UserLicenseSettings s = lockedSettings(7);+ s.setLinkedTeamUsers(200);+ cacheReturns(withAllowance(null));++ assertThat(service.refreshLinkedTeamUsers()).isNull();+ assertThat(s.getLinkedTeamUsers()).isNull();+ }++ @Test+ @DisplayName("refresh keeps the stored allowance when SaaS says nothing")+ void refreshKeepsTheAllowanceWhenUnanswered() {+ UserLicenseSettings s = lockedSettings(7);+ s.setLinkedTeamUsers(200);+ s.setLinkedTeamDeviceId("device-1");+ cacheReturns(null);++ assertThat(service.refreshLinkedTeamUsers()).isEqualTo(200);+ assertThat(s.getLinkedTeamUsers()).isEqualTo(200);+ }++ @Test+ void unlinkClearsPersistedAllowance() {+ UserLicenseSettings settings = lockedSettings(7);+ settings.setLinkedTeamUsers(200);+ settings.setLinkedTeamDeviceId("device-1");+ assertThat(service.refreshLinkedTeamUsers()).isNull();+ assertThat(settings.getLinkedTeamUsers()).isNull();+ assertThat(settings.getLinkedTeamDeviceId()).isNull();+ assertThat(service.calculateMaxAllowedUsers()).isEqualTo(7);+ }++ @Test+ void anotherLinkCannotInheritOfflineAllowance() {+ UserLicenseSettings settings = lockedSettings(7);+ settings.setLinkedTeamUsers(200);+ settings.setLinkedTeamDeviceId("old-device");+ cacheReturns(null);+ assertThat(service.refreshLinkedTeamUsers()).isNull();+ assertThat(settings.getLinkedTeamUsers()).isNull();+ }+@Test@DisplayName("a SaaS allowance above the grandfathered limit raises it")void higherAllowanceRaisesTheCeiling() {@@ -305,7 +412,8 @@ class UserLicenseSettingsServiceMoreTest {s.setIntegritySalt("salt");s.setLicenseMaxUsers(0);when(settingsRepository.findSettings()).thenReturn(Optional.of(s));- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);service.updateLicenseMaxUsers();@@ -320,7 +428,8 @@ class UserLicenseSettingsServiceMoreTest {s.setIntegritySalt("salt");s.setLicenseMaxUsers(0);when(settingsRepository.findSettings()).thenReturn(Optional.of(s));- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);service.updateLicenseMaxUsers();@@ -335,7 +444,8 @@ class UserLicenseSettingsServiceMoreTest {s.setIntegritySalt("salt");s.setLicenseMaxUsers(8);when(settingsRepository.findSettings()).thenReturn(Optional.of(s));- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);service.updateLicenseMaxUsers();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.javaindex fe25862aac..2a778c845c 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.java@@ -59,7 +59,8 @@ class UserLicenseSettingsServiceTest {when(userService.getTotalUsersCount()).thenReturn(80L);when(settingsRepository.save(any(UserLicenseSettings.class))).thenAnswer(invocation -> invocation.getArgument(0));- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);when(licenseKeyCheckerProvider.getIfAvailable()).thenReturn(licenseKeyChecker);// Create service with overridden validateSettingsIntegrity to bypass signature validation@@ -78,11 +79,42 @@ class UserLicenseSettingsServiceTest {};}+ @Test+ void offlineExpirySuspendsTeamAllowanceWithoutDestroyingItAndReconnectRestoresIt() {+ EntitlementCache cache = org.mockito.Mockito.mock(EntitlementCache.class);+ when(entitlementCacheProvider.getIfAvailable()).thenReturn(cache);+ when(cache.linkedDeviceId()).thenReturn("device");+ mockSettings.setLinkedTeamDeviceId("device");+ mockSettings.setLinkedTeamUsers(300);+ when(cache.current()).thenReturn(Optional.empty());+ when(cache.isGraceExpired()).thenReturn(true);+ assertEquals(null, service.refreshLinkedTeamUsers());+ assertEquals(300, mockSettings.getLinkedTeamUsers());+ assertEquals(80, service.calculateMaxAllowedUsers());+ when(cache.isGraceExpired()).thenReturn(false);+ when(cache.current())+ .thenReturn(+ Optional.of(+ new stirling.software.proprietary.accountlink.InstanceEntitlement(+ true,+ 0,+ 0,+ null,+ stirling.software.proprietary.accountlink.EntitlementState+ .OK,+ null,+ null,+ null,+ 300)));+ assertEquals(300, service.calculateMaxAllowedUsers());+ }+@Testvoid noLicense_returnsGrandfatheredLimit() {// No license activewhen(premium.isEnabled()).thenReturn(false);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);int result = service.calculateMaxAllowedUsers();@@ -93,7 +125,8 @@ class UserLicenseSettingsServiceTest {void serverLicense_returnsUnlimited() {// SERVER license with users=0when(premium.isEnabled()).thenReturn(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);mockSettings.setLicenseMaxUsers(0);int result = service.calculateMaxAllowedUsers();@@ -105,7 +138,8 @@ class UserLicenseSettingsServiceTest {void enterpriseLicense_returnsLicenseSeatsOnly() {// ENTERPRISE license with 5 seatswhen(premium.isEnabled()).thenReturn(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);mockSettings.setLicenseMaxUsers(5);int result = service.calculateMaxAllowedUsers();@@ -120,7 +154,8 @@ class UserLicenseSettingsServiceTest {void enterpriseLicense_ignoresGrandfathering() {// ENTERPRISE with 20 seats, grandfathered was 80when(premium.isEnabled()).thenReturn(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);mockSettings.setLicenseMaxUsers(20);mockSettings.setGrandfatheredUserCount(80); // This should be ignored@@ -148,7 +183,8 @@ class UserLicenseSettingsServiceTest {// Fresh install with SERVER licensemockSettings.setGrandfatheredUserCount(5);when(premium.isEnabled()).thenReturn(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);mockSettings.setLicenseMaxUsers(0);int result = service.calculateMaxAllowedUsers();@@ -164,7 +200,8 @@ class UserLicenseSettingsServiceTest {// Fresh install with ENTERPRISE 10 seatsmockSettings.setGrandfatheredUserCount(5);when(premium.isEnabled()).thenReturn(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);mockSettings.setLicenseMaxUsers(10);int result = service.calculateMaxAllowedUsers();@@ -189,7 +226,8 @@ class UserLicenseSettingsServiceTest {// V1→V2 with 80 users, then buy ENTERPRISE 5 seatsmockSettings.setGrandfatheredUserCount(80);when(premium.isEnabled()).thenReturn(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);mockSettings.setLicenseMaxUsers(5);int result = service.calculateMaxAllowedUsers();@@ -285,7 +323,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("grandfathered-user");user.setOauthGrandfathered(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);boolean result = service.isOAuthEligible(user);@@ -300,7 +339,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("test-user");user.setOauthGrandfathered(false);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);boolean result = service.isOAuthEligible(user);@@ -315,7 +355,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("test-user");user.setOauthGrandfathered(false);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);boolean result = service.isOAuthEligible(user);@@ -331,7 +372,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("test-user");user.setOauthGrandfathered(false);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);boolean result = service.isOAuthEligible(user);@@ -344,7 +386,8 @@ class UserLicenseSettingsServiceTest {@Testvoid isOAuthEligible_newUserWithServerLicense_returnsTrue() {// New user (null) with SERVER license should be eligible for auto-creation- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);boolean result = service.isOAuthEligible(null);@@ -355,7 +398,8 @@ class UserLicenseSettingsServiceTest {@Testvoid isOAuthEligible_newUserWithNoLicense_returnsFalse() {// New user (null) without license should NOT be eligible- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);boolean result = service.isOAuthEligible(null);@@ -391,7 +435,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("grandfathered-user");user.setOauthGrandfathered(true);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);boolean result = service.isSamlEligible(user);@@ -406,7 +451,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("test-user");user.setOauthGrandfathered(false);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);boolean result = service.isSamlEligible(user);@@ -424,7 +470,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("test-user");user.setOauthGrandfathered(false);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);boolean result = service.isSamlEligible(user);@@ -442,7 +489,8 @@ class UserLicenseSettingsServiceTest {user.setUsername("test-user");user.setOauthGrandfathered(false);- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.NORMAL);boolean result = service.isSamlEligible(user);@@ -455,7 +503,8 @@ class UserLicenseSettingsServiceTest {@Testvoid isSamlEligible_newUserWithEnterpriseLicense_returnsTrue() {// New user (null) with ENTERPRISE license should be eligible for auto-creation- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);boolean result = service.isSamlEligible(null);@@ -468,7 +517,8 @@ class UserLicenseSettingsServiceTest {@Testvoid isSamlEligible_newUserWithServerLicense_returnsFalse() {// New user (null) with SERVER license should NOT be eligible for SAML- when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);+ when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);+ when(licenseKeyChecker.getLicenseKeyResult()).thenReturn(License.SERVER);boolean result = service.isSamlEligible(null);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/config/StorageProviderConfigTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/config/StorageProviderConfigTest.javaindex 4098d6ab19..846d94b985 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/storage/config/StorageProviderConfigTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/config/StorageProviderConfigTest.java@@ -70,7 +70,15 @@ class StorageProviderConfigTest {StorageEncryptionState state = newState(cfg);StorageProvider provider = cfg.storageProvider(state, Optional.empty());- assertThat(provider).isInstanceOf(EncryptingStorageProvider.class);+ assertThat(provider)+ .isInstanceOf(+ stirling.software.proprietary.storage.provider.LicensedStorageProvider+ .class);+ assertThat(+ ((stirling.software.proprietary.storage.provider.LicensedStorageProvider)+ provider)+ .delegate())+ .isInstanceOf(EncryptingStorageProvider.class);assertThat(state.isWriteEnabled()).isTrue();assertThat(state.suppressDirectDownloads()).isTrue();}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/provider/LicensedStorageProviderTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/provider/LicensedStorageProviderTest.javanew file mode 100644index 0000000000..900fa6a06b--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/provider/LicensedStorageProviderTest.java@@ -0,0 +1,26 @@+package stirling.software.proprietary.storage.provider;++import static org.assertj.core.api.Assertions.*;+import static org.mockito.Mockito.*;++import java.io.IOException;+import java.util.concurrent.atomic.AtomicBoolean;++import org.junit.jupiter.api.Test;++class LicensedStorageProviderTest {+ @Test+ void expiryBlocksNewWritesButPreservesReadingAndReconnectRestoresWrites() throws Exception {+ StorageProvider delegate = mock(StorageProvider.class);+ AtomicBoolean paid = new AtomicBoolean(true);+ var provider = new LicensedStorageProvider(delegate, paid::get);+ provider.store(null, null);+ paid.set(false);+ assertThatThrownBy(() -> provider.store(null, null)).isInstanceOf(IOException.class);+ provider.load("existing");+ verify(delegate).load("existing");+ paid.set(true);+ provider.store(null, null);+ verify(delegate, times(2)).store(null, null);+ }+}diff --git a/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateController.java b/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateController.javaindex 77a87a27bb..d56849ff7b 100644--- a/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateController.java+++ b/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateController.java@@ -26,9 +26,6 @@ import org.springframework.web.bind.annotation.RestController;import org.springframework.web.server.ResponseStatusException;import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;-import tools.jackson.core.JacksonException;-import tools.jackson.databind.ObjectMapper;-import io.swagger.v3.oas.annotations.Hidden;import io.swagger.v3.oas.annotations.tags.Tag;@@ -53,6 +50,9 @@ import stirling.software.saas.payg.model.JobSource;import stirling.software.saas.payg.model.ProcessType;import stirling.software.saas.util.AuthenticationUtils;+import tools.jackson.core.JacksonException;+import tools.jackson.databind.ObjectMapper;+@RestController@Profile("saas")@RequestMapping("/api/v1/ai/create")diff --git a/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateInternalController.java b/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateInternalController.javaindex 04b8302e7e..ea9ee64145 100644--- a/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateInternalController.java+++ b/app/saas/src/main/java/stirling/software/saas/ai/controller/AiCreateInternalController.java@@ -14,9 +14,6 @@ import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.server.ResponseStatusException;-import tools.jackson.core.JacksonException;-import tools.jackson.databind.ObjectMapper;-import io.swagger.v3.oas.annotations.Hidden;import io.swagger.v3.oas.annotations.tags.Tag;@@ -29,6 +26,9 @@ import stirling.software.saas.ai.service.AiCreateSessionService;import stirling.software.saas.payg.cap.RequiresFeature;import stirling.software.saas.payg.model.FeatureGate;+import tools.jackson.core.JacksonException;+import tools.jackson.databind.ObjectMapper;+@RestController@Profile("saas")@RequestMapping("/api/v1/ai/create/internal")diff --git a/app/saas/src/main/java/stirling/software/saas/billing/service/StripeUsageReportingService.java b/app/saas/src/main/java/stirling/software/saas/billing/service/StripeUsageReportingService.javaindex ae5d3d943a..f1870bb715 100644--- a/app/saas/src/main/java/stirling/software/saas/billing/service/StripeUsageReportingService.java+++ b/app/saas/src/main/java/stirling/software/saas/billing/service/StripeUsageReportingService.java@@ -12,12 +12,12 @@ import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Service;-import tools.jackson.databind.ObjectMapper;-import lombok.extern.slf4j.Slf4j;import stirling.software.saas.config.SupabaseConfigurationProperties;+import tools.jackson.databind.ObjectMapper;+/*** Reports per-tenant overage to Stripe Billing Meters via the Supabase {@code meter-usage} Edge* Function. Only credits consumed above the free tier flow through {@link #reportUsageToStripe}.diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasLicenseOverride.java b/app/saas/src/main/java/stirling/software/saas/config/SaasLicenseOverride.javaindex 779c1ac54b..ff7f6b9633 100644--- a/app/saas/src/main/java/stirling/software/saas/config/SaasLicenseOverride.java+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasLicenseOverride.java@@ -2,12 +2,33 @@ package stirling.software.saas.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;+import org.springframework.context.annotation.Primary;import org.springframework.context.annotation.Profile;-/** Saas mode is unconditionally ENTERPRISE (every tenant is a paying Stripe customer). */+import stirling.software.common.service.LicenseServiceInterface;++/**+ * SaaS infrastructure is licensed; tenant purchases are enforced by the billing entitlement gate.+ */@Configuration@Profile("saas")-public class SaasLicenseOverride {+@Primary+public class SaasLicenseOverride implements LicenseServiceInterface {++ @Override+ public boolean isRunningProOrHigher() {+ return true;+ }++ @Override+ public boolean isRunningEE() {+ return true;+ }++ @Override+ public String getLicenseTypeName() {+ return "ENTERPRISE";+ }@Bean(name = "runningProOrHigher")public boolean runningProOrHigherSaas() {diff --git a/app/saas/src/main/java/stirling/software/saas/model/SaasTeamExtensions.java b/app/saas/src/main/java/stirling/software/saas/model/SaasTeamExtensions.javaindex ca6ed81006..75ccda831a 100644--- a/app/saas/src/main/java/stirling/software/saas/model/SaasTeamExtensions.java+++ b/app/saas/src/main/java/stirling/software/saas/model/SaasTeamExtensions.java@@ -101,15 +101,9 @@ public class SaasTeamExtensions implements Serializable {return Boolean.TRUE.equals(isPersonal);}- /**- * Whether this team has unused seats. Personal teams are bound by {@code max_seats}; standard- * teams are unlimited, because cloud capacity is not enforced yet.- */+ /** Whether this team has unused seats. Membership acceptance also claims a seat atomically. */public boolean hasAvailableSeats() {- if (isPersonal()) {- return seatsUsed != null && maxSeats != null && seatsUsed < maxSeats;- }- return true;+ return seatsUsed != null && maxSeats != null && seatsUsed < maxSeats;}/**@@ -118,7 +112,7 @@ public class SaasTeamExtensions implements Serializable {* refused — see {@code SaasTeamService.inviteUserToTeam}.*/public boolean canInviteMembers() {- return !isPersonal();+ return !isPersonal() && hasAvailableSeats();}/**diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygBillingDetailsController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygBillingDetailsController.javaindex 1ca2a9ff81..8fa455d656 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygBillingDetailsController.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygBillingDetailsController.java@@ -1,5 +1,6 @@package stirling.software.saas.payg.api;+import java.util.List;import java.util.Objects;import java.util.Optional;@@ -30,8 +31,8 @@ import stirling.software.saas.util.AuthenticationUtils;* The team is resolved from the authenticated principal, never from the request, as {@link* PaygPaymentMethodController} and {@link PaygInvoicesController} also do.*- * <p>Read-only by design; Stripe's hosted portal is the one writer. Next-invoice timing is not- * served here either, since the wallet already carries the period end.+ * <p>Read-only by design; Stripe's hosted portal is the one writer. Each subscription's renewal+ * date is independent of the wallet's usage and free-grant window.** <p>No team, no {@code stripe_customer_id}, or a customer absent from the mirror all degrade to* {@code 200 present=false}, so the section loses rows rather than failing the page.@@ -44,9 +45,13 @@ import stirling.software.saas.util.AuthenticationUtils;public class PaygBillingDetailsController {/** {@code present=false} carries no detail fields; either field may be null when present. */- public record BillingDetailsResponse(boolean present, String companyName, String invoiceEmail) {+ public record BillingDetailsResponse(+ boolean present,+ String companyName,+ String invoiceEmail,+ List<StripeCustomerDetailsDao.UpcomingInvoice> upcomingInvoices) {static BillingDetailsResponse absent() {- return new BillingDetailsResponse(false, null, null);+ return new BillingDetailsResponse(false, null, null, List.of());}}@@ -93,7 +98,11 @@ public class PaygBillingDetailsController {.map(d ->new BillingDetailsResponse(- true, d.companyName(), d.invoiceEmail()))+ true,+ d.companyName(),+ d.invoiceEmail(),+ customerDetailsDao.findUpcomingInvoices(+ ext.get().getStripeCustomerId()))).orElseGet(BillingDetailsResponse::absent));}}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.javaindex 441ebf1220..b9856a17b5 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java@@ -20,8 +20,6 @@ import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;-import tools.jackson.databind.ObjectMapper;-import io.micrometer.core.instrument.Counter;import io.micrometer.core.instrument.MeterRegistry;@@ -40,6 +38,8 @@ import stirling.software.saas.payg.cap.RequiresFeature;import stirling.software.saas.payg.model.FeatureGate;import stirling.software.saas.util.AuthenticationUtils;+import tools.jackson.databind.ObjectMapper;+/*** Hot-path entitlement check. Runs after {@code PaygChargeInterceptor} in the MVC chain and short-* circuits the request before any handler work happens when the team's snapshot is missing one ofdiff --git a/app/saas/src/main/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDao.java b/app/saas/src/main/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDao.javaindex d604e89e59..a6be90acfc 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDao.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDao.java@@ -1,5 +1,6 @@package stirling.software.saas.payg.stripe;+import java.time.Instant;import java.util.List;import java.util.Objects;import java.util.Optional;@@ -27,6 +28,40 @@ public class StripeCustomerDetailsDao {/** Either field may be null. */public record CustomerDetails(String companyName, String invoiceEmail) {}+ /** The next renewal for one subscription, independent of the wallet's usage window. */+ public record UpcomingInvoice(String subscriptionId, String description, Instant date) {}++ /** Empty when subscription dates have not synced; never substitutes a grant reset date. */+ public List<UpcomingInvoice> findUpcomingInvoices(String customerId) {+ if (customerId == null || customerId.isBlank()) return List.of();+ try {+ return jdbcTemplate.query(+ """+ SELECT s.id, string_agg(DISTINCT product.name, ' + ') AS description,+ COALESCE(MIN(si.current_period_end), s.current_period_end) AS period_end+ FROM stripe.subscriptions s+ LEFT JOIN stripe.subscription_items si ON si.subscription = s.id+ AND COALESCE(si.deleted, false) = false+ LEFT JOIN stripe.prices p ON p.id = si.price+ LEFT JOIN stripe.products product ON product.id = p.product+ WHERE s.customer = ? AND s.status IN ('active', 'trialing')+ AND COALESCE(s.cancel_at_period_end, false) = false+ GROUP BY s.id, s.current_period_end+ HAVING COALESCE(MIN(si.current_period_end), s.current_period_end) IS NOT NULL+ ORDER BY period_end, s.id+ """,+ (rs, i) ->+ new UpcomingInvoice(+ rs.getString("id"),+ rs.getString("description"),+ Instant.ofEpochSecond(rs.getLong("period_end"))),+ customerId);+ } catch (DataAccessException e) {+ log.warn("Stripe renewal dates unavailable for customer {}", customerId);+ return List.of();+ }+ }+private static final String QUERY ="SELECT c.name AS name, c.email AS email FROM stripe.customers c WHERE c.id = ?";diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.javaindex e75f3cbb32..2555a82079 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java@@ -10,8 +10,6 @@ import java.util.Map;import org.springframework.stereotype.Service;-import tools.jackson.databind.ObjectMapper;-import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;@@ -22,6 +20,8 @@ import stirling.software.saas.procurement.pricing.ProcurementPricingService;import stirling.software.saas.procurement.pricing.QuoteConfig;import stirling.software.saas.procurement.pricing.QuoteLineItem;+import tools.jackson.databind.ObjectMapper;+/*** Builds the full Stirling Enterprise Agreement for a specific quote: the static MSA (Part A) and* DPA (Part C) from the {@link LegalDocumentRegistry}, with the dynamic Order Form (Part B)diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.java b/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.javaindex a1c09a9cb9..22252d892b 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.java@@ -16,13 +16,13 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Service;-import tools.jackson.databind.JsonNode;-import tools.jackson.databind.ObjectMapper;-import lombok.extern.slf4j.Slf4j;import stirling.software.saas.procurement.config.KeygenConfigurationProperties;+import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;+/*** Real {@link EnterpriseLicenseService}: manages the team's enterprise licence directly against the* Keygen API (the "call Keygen from Java" direction), rather than via the Supabase edge functionsdiff --git a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.javaindex 26bfb733dd..388b95eef3 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java@@ -10,9 +10,6 @@ import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;-import tools.jackson.core.JacksonException;-import tools.jackson.databind.ObjectMapper;-import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.enumeration.TeamRole;@@ -38,6 +35,9 @@ import stirling.software.saas.procurement.repository.ProcurementQuoteRepository;import stirling.software.saas.service.SaasTeamService;import stirling.software.saas.util.LogRedactionUtils;+import tools.jackson.core.JacksonException;+import tools.jackson.databind.ObjectMapper;+/*** Orchestrates a linked team's procurement journey: start a (mock-licensed) trial, build a* server-priced quote, and accept it. Stripe checkout itself lives in a Supabase edge function thediff --git a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.javaindex 36c8bcef17..f2ed734c9d 100644--- a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java+++ b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java@@ -14,15 +14,13 @@ public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExteOptional<SaasTeamExtensions> findByTeamId(Long teamId);/**- * Atomic seat increment. Personal teams enforce a strict {@code seatsUsed < maxSeats}- * ceiling; standard (non-personal) teams have no cap (mirrors {@link- * SaasTeamExtensions#hasAvailableSeats()}). Returns 1 on success, 0 if the cap was hit.+ * Atomic seat claim for every team type. Returns 1 on success, 0 when capacity is exhausted.*/@Modifying@Query("UPDATE SaasTeamExtensions e SET e.seatsUsed = e.seatsUsed + 1 "+ "WHERE e.teamId = :teamId AND "- + "(e.isPersonal = TRUE AND e.seatsUsed < e.maxSeats OR e.isPersonal = FALSE)")+ + "e.seatsUsed < e.maxSeats")int incrementSeatsUsed(@Param("teamId") Long teamId);/** Atomic seat decrement. Floor at 0. Returns 1 on a real decrement, 0 if already at 0. */diff --git a/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.java b/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.javaindex 658f3df85d..840cf77b5a 100644--- a/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.java+++ b/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.java@@ -258,11 +258,11 @@ public class SaasTeamService {team.getName(),inviter.getUsername());saasTeamExtensionService.setPersonal(team, false);- // Still the unlimited sentinel, which is what a standard team is until it buys: nothing- // enforces capacity for one. Writing the free allowance here instead would state a- // ceiling nothing honours, and SaasTeamController's availableSeats would go negative as- // the team grew past it. The sentinel goes when enforcement arrives.- saasTeamExtensionService.setSeats(team, Integer.MAX_VALUE, Integer.MAX_VALUE);+ int capacity =+ Math.max(+ UserLicenseSettingsService.DEFAULT_USER_LIMIT,+ saasTeamExtensionService.getMaxSeats(team));+ saasTeamExtensionService.setSeats(team, capacity, capacity);}// Validate: team can invite (not personal, has available seats)diff --git a/app/saas/src/test/java/stirling/software/saas/config/SaasLicenseBeanCoverageTest.java b/app/saas/src/test/java/stirling/software/saas/config/SaasLicenseBeanCoverageTest.javanew file mode 100644index 0000000000..098f3d66db--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/config/SaasLicenseBeanCoverageTest.java@@ -0,0 +1,24 @@+package stirling.software.saas.config;++import static org.assertj.core.api.Assertions.assertThat;++import org.junit.jupiter.api.Test;+import org.springframework.context.annotation.AnnotationConfigApplicationContext;++import stirling.software.common.service.LicenseServiceInterface;++class SaasLicenseBeanCoverageTest {+ @Test+ void saasResolvesBothDynamicAndStartupInfrastructureEntitlements() {+ try (var context = new AnnotationConfigApplicationContext()) {+ context.getEnvironment().setActiveProfiles("saas");+ context.register(SaasLicenseOverride.class);+ context.refresh();+ LicenseServiceInterface license = context.getBean(LicenseServiceInterface.class);+ assertThat(license.isRunningProOrHigher()).isTrue();+ assertThat(license.isRunningEE()).isTrue();+ assertThat(context.getBean("runningProOrHigher")).isEqualTo(true);+ assertThat(context.getBean("runningEE")).isEqualTo(true);+ }+ }+}diff --git a/app/saas/src/test/java/stirling/software/saas/model/SaasTeamExtensionsTest.java b/app/saas/src/test/java/stirling/software/saas/model/SaasTeamExtensionsTest.javaindex 3d7109efdc..81f13b541e 100644--- a/app/saas/src/test/java/stirling/software/saas/model/SaasTeamExtensionsTest.java+++ b/app/saas/src/test/java/stirling/software/saas/model/SaasTeamExtensionsTest.java@@ -89,11 +89,13 @@ class SaasTeamExtensionsTest {class HasAvailableSeats {@Test- @DisplayName("standard teams are always unlimited")- void standardUnlimited() {+ @DisplayName("standard teams enforce purchased capacity")+ void standardCapacity() {SaasTeamExtensions ext = new SaasTeamExtensions();ext.setSeatsUsed(100);ext.setMaxSeats(1);+ assertThat(ext.hasAvailableSeats()).isFalse();+ ext.setMaxSeats(101);assertThat(ext.hasAvailableSeats()).isTrue();}diff --git a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.javaindex a9ca7642a6..dad953d61e 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java@@ -28,9 +28,6 @@ import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.oauth2.jwt.Jwt;import org.springframework.web.method.HandlerMethod;-import tools.jackson.databind.JsonNode;-import tools.jackson.databind.ObjectMapper;-import io.micrometer.core.instrument.MeterRegistry;import io.micrometer.core.instrument.simple.SimpleMeterRegistry;@@ -45,6 +42,9 @@ import stirling.software.saas.payg.model.FeatureGate;import stirling.software.saas.payg.model.FeatureSet;import stirling.software.saas.security.EnhancedJwtAuthenticationToken;+import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;+/*** Pure-Mockito tests for {@link EntitlementGuard}. Covers the four decision-matrix cells: anonymous* billable → 401, anonymous manual → pass, authenticated FULL → pass, authenticated DEGRADED for adiff --git a/app/saas/src/test/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDaoTest.java b/app/saas/src/test/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDaoTest.javanew file mode 100644index 0000000000..d32ab045f7--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDaoTest.java@@ -0,0 +1,47 @@+package stirling.software.saas.payg.stripe;++import static org.assertj.core.api.Assertions.assertThat;++import java.time.Instant;+import java.util.UUID;++import org.junit.jupiter.api.Test;+import org.springframework.jdbc.core.JdbcTemplate;+import org.springframework.jdbc.datasource.DriverManagerDataSource;++class StripeCustomerDetailsDaoTest {+ @Test+ void renewalsUseEachSubscriptionsItemsAndStayWithinTheCustomer() {+ JdbcTemplate jdbc =+ new JdbcTemplate(+ new DriverManagerDataSource(+ "jdbc:h2:mem:"+ + UUID.randomUUID()+ + ";MODE=PostgreSQL;DB_CLOSE_DELAY=-1",+ "sa",+ ""));+ jdbc.execute("CREATE SCHEMA stripe");+ jdbc.execute(+ "CREATE TABLE stripe.subscriptions (id text, customer text, status text, current_period_end bigint, cancel_at_period_end boolean)");+ jdbc.execute(+ "CREATE TABLE stripe.subscription_items (subscription text, price text, current_period_end bigint, deleted boolean)");+ jdbc.execute("CREATE TABLE stripe.prices (id text, product text)");+ jdbc.execute("CREATE TABLE stripe.products (id text, name text)");+ jdbc.execute(+ "INSERT INTO stripe.products VALUES ('team', 'Team'), ('processor', 'Processor')");+ jdbc.execute(+ "INSERT INTO stripe.prices VALUES ('team_price', 'team'), ('processor_price', 'processor')");+ jdbc.execute(+ "INSERT INTO stripe.subscriptions VALUES ('team_sub', 'buyer', 'active', null, false), ('processor_sub', 'buyer', 'active', 1792071850, false), ('other_sub', 'other', 'active', 1792071850, false), ('cancelled_sub', 'buyer', 'active', 1792071850, true), ('unsynced_sub', 'buyer', 'active', null, false)");+ jdbc.execute(+ "INSERT INTO stripe.subscription_items VALUES ('team_sub', 'team_price', 1792071502, false), ('processor_sub', 'processor_price', 1792071850, false), ('team_sub', 'team_price', 1789479502, true)");++ var renewals = new StripeCustomerDetailsDao(jdbc).findUpcomingInvoices("buyer");++ assertThat(renewals).hasSize(2);+ assertThat(renewals.getFirst().subscriptionId()).isEqualTo("team_sub");+ assertThat(renewals.getFirst().description()).isEqualTo("Team");+ assertThat(renewals.getFirst().date()).isEqualTo(Instant.ofEpochSecond(1792071502));+ assertThat(renewals.getLast().date()).isEqualTo(Instant.ofEpochSecond(1792071850));+ }+}diff --git a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.java b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.javaindex 4626244762..8bb5bd7984 100644--- a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.java@@ -283,8 +283,8 @@ class SaasTeamExtensionServiceTest {}@Test- @DisplayName("standard team always has seats regardless of usage")- void standardTeam_alwaysTrue() {+ @DisplayName("standard team cannot exceed purchased capacity")+ void standardTeam_overCap_false() {Team team = team();SaasTeamExtensions row = ext(team);row.setIsPersonal(false);@@ -292,7 +292,7 @@ class SaasTeamExtensionServiceTest {row.setMaxSeats(1);when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.of(row));- assertThat(service.hasAvailableSeats(team)).isTrue();+ assertThat(service.hasAvailableSeats(team)).isFalse();}@Testdiff --git a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.javaindex 9c11ed90d9..2da28f1111 100644--- a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java@@ -323,10 +323,7 @@ class SaasTeamServiceTest {service.inviteUserToTeam(teamId, "[email protected]", inviter);verify(saasTeamExtensionService).setPersonal(t, false);- // Still the sentinel. A standard team has no user limit until it buys one, and nothing- // enforces capacity for one, so stating the free allowance here would announce a- // ceiling nothing honours.- verify(saasTeamExtensionService).setSeats(t, Integer.MAX_VALUE, Integer.MAX_VALUE);+ verify(saasTeamExtensionService).setSeats(t, 5, 5);}@Testdiff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 9f459a4184..ca54168878 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -6607,6 +6607,7 @@ licenseKey = "Your License Key"licensePollingError = "Payment successful but we couldn't retrieve your license key automatically. Please check your email or contact support with your payment confirmation."licenseRetrievalError = "Payment successful but license retrieval failed. You will receive your license key via email. Please contact support if you don't receive it within 10 minutes."licenseSaveError = "Failed to save license key. Please contact support with your license key to complete activation."+manageSubscription = "Manage subscription"monthly = "Monthly"paymentCanceled = "Payment was canceled. No charges were made."perMonth = "/month"@@ -6617,6 +6618,10 @@ success = "Payment Successful!"successMessage = "Your subscription has been activated successfully. You will receive a confirmation email shortly."syncError = "Payment successful but license sync failed. Your license will be updated shortly. Please contact support if issues persist."syncingLicense = "Syncing your upgraded license..."+teamActivated = "Your Team capacity is active"+teamActivating = "Confirming your Team capacity..."+teamPending = "Your Team purchase is still processing. Refresh this page shortly."+teamProcessing = "Team purchase processing"upgradeComplete = "Upgrade Complete"upgradeCompleteMessage = "Your subscription has been upgraded successfully. Your existing license key has been updated."upgradeSuccess = "Payment successful! Your subscription has been upgraded. The license has been updated on your server. You will receive a confirmation email shortly."@@ -6628,6 +6633,7 @@ currently = "Currently up to {{users}} users"title = "Add capacity"[payment.capacityStage]+adjustmentNote = "Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available."continue = "Continue to payment"customHint = "Rounded up to the next block of {{users}}."customLabel = "Number of users"@@ -6636,10 +6642,12 @@ enterpriseQuote = "Get an enterprise quote"lineItem = "Team · {{price}}{{period}} per {{block}} users"minimumForCurrentUsers = "You have {{users}} users, so the plan must cover at least {{minimum}}."modalTitle = "Upgrade to {{planName}}"+newPlanTotal = "New plan total"other = "Other"perMonth = "/mo"perYear = "/yr"renewalNote = "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing."+reviewChange = "Review change in Stripe"subheading = "Covers everyone you invite, in blocks of {{users}} users."subheadingAdd = "Your plan covers {{current}} users today. Choose the new total."userDelta = "+{{users}} users"@@ -6651,7 +6659,6 @@ continue = "Continue"description = "We'll use this to send your license key and receipts."emailLabel = "Email Address"emailPlaceholder = "[email protected]"-modalTitle = "Get Started - {{planName}}"[payment.paymentStage]modalTitle = "Complete Payment - {{planName}}"@@ -7390,6 +7397,15 @@ going = "Taking you to stirling.com"reauthLede = "Your Stirling session expired. Signing in again keeps usage and billing visible. This server stays connected either way."title = "Connecting"+[portal.accountLink.connectionNotice]+expiredBody = "This server has not reached Stirling Cloud within its offline allowance. Cloud-backed Team features and Processor work are paused. Existing data and installed licence rights are preserved. Access returns automatically after a successful connection confirms your plan."+expiredTitle = "Cloud access paused"+offlineBody = "Your last confirmed plan remains available until {{deadline}}. Restore this server’s connection before then to avoid pausing cloud-backed features and processing."+offlineTitle = "Stirling Cloud is unreachable"+retry = "Check connection"+revokedBody = "Stirling Cloud rejected this account connection. Reconnect the account in Settings to restore eligible cloud-backed features."+revokedTitle = "Account connection revoked"+[portal.accountLink.gate]retry = "Try again"@@ -7579,11 +7595,10 @@ view = "View"billedTo = "Billed to"card = "{{brand}} ending {{last4}}"cardWithExpiry = "{{brand}} ending {{last4}} · expires {{month}} / {{year}}"+dateUnavailable = "Billing date not available yet"invoicesTo = "Invoices go to"method = "Payment method"nextInvoice = "Next invoice"-nextInvoiceNote = "from this cycle's pace"-nextInvoiceValue = "{{date}} · {{amount}}"noCard = "No card on file"update = "Update"diff --git a/frontend/editor/src/desktop/services/teamPlanActivation.ts b/frontend/editor/src/desktop/services/teamPlanActivation.tsnew file mode 100644index 0000000000..4744d9e875--- /dev/null+++ b/frontend/editor/src/desktop/services/teamPlanActivation.ts@@ -0,0 +1,6 @@+import { connectionModeService } from "@app/services/connectionModeService";++/** Cloud purchases need no local activation when the desktop is connected directly to SaaS. */+export async function requiresLocalTeamActivation(): Promise<boolean> {+ return (await connectionModeService.getCurrentMode()) !== "saas";+}diff --git a/frontend/editor/src/portal/api/billing.ts b/frontend/editor/src/portal/api/billing.tsindex 92eab21ee7..7a3694233f 100644--- a/frontend/editor/src/portal/api/billing.ts+++ b/frontend/editor/src/portal/api/billing.ts@@ -99,6 +99,12 @@ export interface BillingDetails {present: boolean;companyName: string | null;invoiceEmail: string | null;+ /** Per-subscription renewal dates; absent until supported by the hosted backend. */+ upcomingInvoices?: Array<{+ subscriptionId: string;+ description: string | null;+ date: string;+ }>;}export async function fetchBillingDetails(): Promise<BillingDetails> {diff --git a/frontend/editor/src/portal/api/link.ts b/frontend/editor/src/portal/api/link.tsindex 12b903c71a..7dd2bcd3dc 100644--- a/frontend/editor/src/portal/api/link.ts+++ b/frontend/editor/src/portal/api/link.ts@@ -6,6 +6,11 @@ export type { LinkedInstanceRow };/** Link status for this instance (GET /api/v1/account-link/status). */export interface LinkStatus {linked: boolean;+ connection?: {+ state: "connected" | "offline" | "expired" | "revoked" | "unlinked";+ lastSuccessAt: string | null;+ offlineAccessUntil: string | null;+ } | null;/** Matches the cloud instance row; older status responses may omit it. */deviceId?: string | null;name?: string | null;@@ -39,8 +44,11 @@ export interface FreeTierBalance {const BASE = "/api/v1/account-link";/** Linked / Not-linked for this instance. */-export async function fetchStatus(): Promise<LinkStatus> {- return apiClient.local.json<LinkStatus>(`${BASE}/status`);+export async function fetchStatus(force = false): Promise<LinkStatus> {+ return apiClient.local.json<LinkStatus>(+ `${BASE}/${force ? "recheck" : "status"}`,+ { method: force ? "POST" : "GET" },+ );}/**diff --git a/frontend/editor/src/portal/components/PortalChrome.tsx b/frontend/editor/src/portal/components/PortalChrome.tsxindex f77efab719..3350623525 100644--- a/frontend/editor/src/portal/components/PortalChrome.tsx+++ b/frontend/editor/src/portal/components/PortalChrome.tsx@@ -1,3 +1,4 @@+import { AccountConnectionNotice } from "@portal/components/account-link/AccountConnectionNotice";import { useLocation } from "react-router-dom";import { AppConfigProvider } from "@app/contexts/AppConfigContext";import { ToolRegistryProvider } from "@app/contexts/ToolRegistryProvider";@@ -27,6 +28,7 @@ function RoutedContent() {* PortalProviders, not here.*/export function PortalChrome() {+ const { pathname } = useLocation();return (// One app-config instance for every portal consumer (the search gates, the// sidebar) so they can't fetch twice or disagree.@@ -34,6 +36,7 @@ export function PortalChrome() {{/* The pipeline builder reads the tool registry to list and configure operations. */}<ToolRegistryProvider><AppShell>+ {!pathname.endsWith("/account-link") && <AccountConnectionNotice />}<RoutedContent /></AppShell></ToolRegistryProvider>diff --git a/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.test.tsx b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.test.tsxnew file mode 100644index 0000000000..0dcfc20c52--- /dev/null+++ b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.test.tsx@@ -0,0 +1,71 @@+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { describe, it, expect, vi } from "vitest";+import { AccountConnectionNotice } from "@portal/components/account-link/AccountConnectionNotice";++const mocks = vi.hoisted(() => ({+ link: {+ status: {+ connection: {+ state: "expired",+ offlineAccessUntil: "2026-09-18T10:00:00Z",+ },+ },+ refresh: vi.fn().mockResolvedValue(undefined),+ },+ refetch: vi.fn(),+}));+vi.mock("@portal/contexts/AccountLinkContext", () => ({+ useAccountLinkOptional: () => mocks.link,+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ refetch: mocks.refetch }),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));+vi.mock("@app/ui", () => ({+ Banner: ({+ title,+ children,+ action,+ }: {+ title: string;+ children: React.ReactNode;+ action: React.ReactNode;+ }) => (+ <div role="alert">+ {title}+ {children}+ {action}+ </div>+ ),+ Button: (props: React.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props} />+ ),+}));++describe("offline account notice", () => {+ it("explains paused features, retries and removes the warning on recovery", async () => {+ mocks.link.status.connection.state = "expired";+ const view = render(<AccountConnectionNotice />);+ expect(screen.getByRole("alert").textContent).toContain(+ "Cloud-backed Team features and Processor work are paused",+ );+ fireEvent.click(screen.getByRole("button", { name: "Check connection" }));+ await waitFor(() => expect(mocks.link.refresh).toHaveBeenCalledWith(true));+ mocks.link.status.connection.state = "connected";+ view.rerender(<AccountConnectionNotice />);+ expect(screen.queryByRole("alert")).toBeNull();+ expect(mocks.refetch).toHaveBeenCalled();+ });+ it("warns before the deadline without claiming features are paused", () => {+ mocks.link.status.connection.state = "offline";+ render(<AccountConnectionNotice />);+ expect(screen.getByRole("alert").textContent).toContain(+ "last confirmed plan remains available",+ );+ expect(screen.getByRole("alert").textContent).not.toContain(+ "features and Processor work are paused",+ );+ });+});diff --git a/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.tsx b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.tsxnew file mode 100644index 0000000000..c9a58dbcc3--- /dev/null+++ b/frontend/editor/src/portal/components/account-link/AccountConnectionNotice.tsx@@ -0,0 +1,80 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Banner, Button } from "@app/ui";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import { useAccountLinkOptional } from "@portal/contexts/AccountLinkContext";++/** Shows the server's cloud-access deadline and refreshes feature visibility when it changes. */+export function AccountConnectionNotice() {+ const { t } = useTranslation();+ const link = useAccountLinkOptional();+ const { refetch } = useAppConfig();+ const state = link?.status?.connection?.state;+ const previous = useRef(state);+ const [checking, setChecking] = useState(false);+ useEffect(() => {+ if (previous.current && previous.current !== state) {+ void refetch();+ window.dispatchEvent(new Event("stirling:billing-updated"));+ }+ previous.current = state;+ }, [state, refetch]);+ if (!link || !state || state === "connected" || state === "unlinked")+ return null;+ const expired = state === "expired";+ const revoked = state === "revoked";+ const deadline = link.status?.connection?.offlineAccessUntil;+ return (+ <Banner+ tone={expired || revoked ? "danger" : "warning"}+ title={+ expired+ ? t(+ "portal.accountLink.connectionNotice.expiredTitle",+ "Cloud access paused",+ )+ : revoked+ ? t(+ "portal.accountLink.connectionNotice.revokedTitle",+ "Account connection revoked",+ )+ : t(+ "portal.accountLink.connectionNotice.offlineTitle",+ "Stirling Cloud is unreachable",+ )+ }+ action={+ <Button+ size="sm"+ disabled={checking}+ onClick={async () => {+ setChecking(true);+ try {+ await link.refresh(true);+ } finally {+ setChecking(false);+ }+ }}+ >+ {t("portal.accountLink.connectionNotice.retry", "Check connection")}+ </Button>+ }+ >+ {expired+ ? t(+ "portal.accountLink.connectionNotice.expiredBody",+ "This server has not reached Stirling Cloud within its offline allowance. Cloud-backed Team features and Processor work are paused. Existing data and installed licence rights are preserved. Access returns automatically after a successful connection confirms your plan.",+ )+ : revoked+ ? t(+ "portal.accountLink.connectionNotice.revokedBody",+ "Stirling Cloud rejected this account connection. Reconnect the account in Settings to restore eligible cloud-backed features.",+ )+ : t(+ "portal.accountLink.connectionNotice.offlineBody",+ "Your last confirmed plan remains available until {{deadline}}. Restore this server’s connection before then to avoid pausing cloud-backed features and processing.",+ { deadline: deadline ? new Date(deadline).toLocaleString() : "" },+ )}+ </Banner>+ );+}diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsxindex 9e1a5a6914..4843222a8b 100644--- a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx@@ -24,6 +24,7 @@ vi.mock("@portal/hooks/useLinkedAccountEmail", () => ({useLinkedAccountEmail: () => state.email,}));vi.mock("@portal/contexts/AccountLinkContext", () => ({+ useAccountLinkOptional: () => null,useAccountLinkContext: () => ({loginConfigured: true,status: state.status,diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsxindex 60eb7cfe4a..0fe8182255 100644--- a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.tsx@@ -1,3 +1,4 @@+import { AccountConnectionNotice } from "@portal/components/account-link/AccountConnectionNotice";import { useCallback, useState } from "react";import { useTranslation } from "react-i18next";import { Banner, Button, InfoTooltip, Skeleton } from "@app/ui";@@ -86,6 +87,7 @@ export function AccountLinkPanel() {)}>+ <AccountConnectionNotice /><LinkAccountCard link={link} instanceName={currentInstance?.name} />{linked && (diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsxindex 71eb94c75e..7637b52977 100644--- a/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx@@ -134,6 +134,7 @@ export function FreeTierPlanView({serverPlan={serverPlan}serverPlanAction={serverPlanAction}editorsDeployed={editorsDeployed}+ pdfsProcessed={fleetStats?.pdfsProcessed ?? null}onAddCapacity={() => openLinkModal()}onActivateProcessor={() => openLinkModal()}notices={diff --git a/frontend/editor/src/portal/components/billing/PaymentSection.test.tsx b/frontend/editor/src/portal/components/billing/PaymentSection.test.tsxnew file mode 100644index 0000000000..babcd10d44--- /dev/null+++ b/frontend/editor/src/portal/components/billing/PaymentSection.test.tsx@@ -0,0 +1,44 @@+import { render, screen } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import { PaymentSection } from "@portal/components/billing/PaymentSection";+import { formatPeriodDate } from "@app/billing";+import { freeWallet } from "@app/billing/walletFixtures";++vi.mock("@portal/api/billing", () => ({+ fetchPaymentMethod: async () => ({ present: false }),+ fetchBillingDetails: async () => ({+ present: true,+ upcomingInvoices: [+ {+ subscriptionId: "team",+ description: "Team",+ date: "2026-10-15T12:00:00Z",+ },+ {+ subscriptionId: "processor",+ description: "Processor",+ date: "2026-10-20T12:00:00Z",+ },+ ],+ }),+}));++it("shows each Stripe renewal date instead of the wallet grant reset", async () => {+ render(+ <PaymentSection+ wallet={{ ...freeWallet, billingPeriodEnd: "2026-10-01" }}+ />,+ );+ expect(+ await screen.findByText(+ formatPeriodDate("2026-10-15T12:00:00Z", { year: true }),+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByText(formatPeriodDate("2026-10-20T12:00:00Z", { year: true })),+ ).toBeInTheDocument();+ expect(screen.getByText("Team")).toBeInTheDocument();+ expect(+ screen.queryByText(formatPeriodDate("2026-10-01", { year: true })),+ ).not.toBeInTheDocument();+});diff --git a/frontend/editor/src/portal/components/billing/PaymentSection.tsx b/frontend/editor/src/portal/components/billing/PaymentSection.tsxindex 3c2481ce18..edf3e277ca 100644--- a/frontend/editor/src/portal/components/billing/PaymentSection.tsx+++ b/frontend/editor/src/portal/components/billing/PaymentSection.tsx@@ -1,7 +1,6 @@-import { estimatedBillWithPending } from "@app/billing/pendingUsage";import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import { KvRow, formatMinor, formatPeriodDate } from "@app/billing";+import { KvRow, formatPeriodDate } from "@app/billing";import {fetchBillingDetails,fetchPaymentMethod,@@ -18,11 +17,10 @@ import {*/export function PaymentSection({wallet,- pendingUnits = 0,onManage,managing = false,}: {- /** Supplies the next-invoice date and estimate. */+ /** Identifies the account and refreshes details after subscription changes. */wallet: Wallet;pendingUnits?: number;/** Opens the Stripe customer portal, which is where all of these are edited. */@@ -30,7 +28,6 @@ export function PaymentSection({managing?: boolean;}) {const { t } = useTranslation();- const estimatedMinor = estimatedBillWithPending(wallet, pendingUnits);const [pm, setPm] = useState<PaymentMethod | null>(null);const [details, setDetails] = useState<BillingDetails | null>(null);@@ -54,7 +51,7 @@ export function PaymentSection({return () => {cancelled = true;};- }, []);+ }, [wallet]);const card =pm?.present && pm.brand && pm.last4@@ -89,31 +86,24 @@ export function PaymentSection({value={card}door={update}/>- <KvRow- label={t("portal.billing.payment.nextInvoice", "Next invoice")}- note={- wallet.processor.active- ? t(- "portal.billing.payment.nextInvoiceNote",- "from this cycle's pace",- )- : undefined- }- value={- estimatedMinor != null- ? t(- "portal.billing.payment.nextInvoiceValue",- "{{date}} · {{amount}}",- {- date: formatPeriodDate(wallet.billingPeriodEnd, {- year: true,- }),- amount: formatMinor(estimatedMinor, wallet.currency),- },- )- : formatPeriodDate(wallet.billingPeriodEnd, { year: true })- }- />+ {details?.upcomingInvoices?.length ? (+ details.upcomingInvoices.map((invoice) => (+ <KvRow+ key={invoice.subscriptionId}+ label={t("portal.billing.payment.nextInvoice", "Next invoice")}+ note={invoice.description ?? undefined}+ value={formatPeriodDate(invoice.date, { year: true })}+ />+ ))+ ) : (+ <KvRow+ label={t("portal.billing.payment.nextInvoice", "Next invoice")}+ value={t(+ "portal.billing.payment.dateUnavailable",+ "Billing date not available yet",+ )}+ />+ )}{details?.companyName && (<KvRowlabel={t("portal.billing.payment.billedTo", "Billed to")}diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsxindex f82adc9c1c..e2c75ffcf5 100644--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx@@ -26,7 +26,11 @@ export function PortalBillingGate() {const { openLinkModal, trialSetupRequested } = useUI();const { loading, gated, connect } = useConnectGate();const isAdmin = usePortalAdmin();- const { serverPlan, loading: licenseLoading } = useServerPlan(isAdmin);+ const {+ serverPlan,+ usersInUse,+ loading: licenseLoading,+ } = useServerPlan(isAdmin);const serverPlanAction = serverPlan ? <ManageBillingButton /> : undefined;const link = useLinkOptional();const [searchParams] = useSearchParams();@@ -66,6 +70,7 @@ export function PortalBillingGate() {);return (<Usage+ localUsersInUse={usersInUse}serverPlan={serverPlan}serverPlanAction={serverPlanAction}onWalletLoaded={onWalletLoaded}diff --git a/frontend/editor/src/portal/hooks/useAccountLink.ts b/frontend/editor/src/portal/hooks/useAccountLink.tsindex 781c23ef34..917f6fec20 100644--- a/frontend/editor/src/portal/hooks/useAccountLink.ts+++ b/frontend/editor/src/portal/hooks/useAccountLink.ts@@ -1,4 +1,4 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useState, useRef } from "react";import { errorMessage } from "@portal/api/http";import { isSaasSupabaseConfigured } from "@portal/auth/saasSupabase";import { fetchStatus, unlinkInstance, type LinkStatus } from "@portal/api/link";@@ -20,7 +20,7 @@ export interface UseAccountLink {/** Unlink this instance. */unlink: () => Promise<void>;/** Re-read the status, for when something outside this hook changed it. */- refresh: () => Promise<void>;+ refresh: (force?: boolean) => Promise<void>;}export function useAccountLink(): UseAccountLink {@@ -31,22 +31,30 @@ export function useAccountLink(): UseAccountLink {const [phase, setPhase] = useState<LinkPhase>("idle");const [error, setError] = useState<string | null>(null);- const refresh = useCallback(async () => {- setStatusError(null);- try {- const s = await fetchStatus();- setStatus(s);- // A linked instance is at least linked-free; subscription comes from the wallet.- if (s.linked) applyLinkFacts(true, false);- // Success only: marking this in the catch would read "could not ask" as "not linked".- markStatusKnown();- } catch (e) {- setStatusError(errorMessage(e));- }- }, [applyLinkFacts, markStatusKnown]);+ const previousLinked = useRef<boolean | null>(null);+ const refresh = useCallback(+ async (force = false) => {+ setStatusError(null);+ try {+ const s = await fetchStatus(force);+ setStatus(s);+ // A linked instance is at least linked-free; subscription comes from the wallet.+ if (s.linked && previousLinked.current !== true)+ applyLinkFacts(true, false);+ previousLinked.current = s.linked;+ // Success only: marking this in the catch would read "could not ask" as "not linked".+ markStatusKnown();+ } catch (e) {+ setStatusError(errorMessage(e));+ }+ },+ [applyLinkFacts, markStatusKnown],+ );useEffect(() => {void refresh();+ const timer = window.setInterval(() => void refresh(), 60_000);+ return () => window.clearInterval(timer);}, [refresh]);const unlink = useCallback(async () => {@@ -55,6 +63,7 @@ export function useAccountLink(): UseAccountLink {try {await unlinkInstance();setStatus({ linked: false, name: null });+ previousLinked.current = false;setPhase("idle");applyLinkFacts(false, false);} catch (e) {diff --git a/frontend/editor/src/portal/hooks/useServerPlan.test.tsx b/frontend/editor/src/portal/hooks/useServerPlan.test.tsxindex 2a4a600677..13cd470dc5 100644--- a/frontend/editor/src/portal/hooks/useServerPlan.test.tsx+++ b/frontend/editor/src/portal/hooks/useServerPlan.test.tsx@@ -1,6 +1,22 @@-import { renderHook, waitFor } from "@testing-library/react";+import {+ fireEvent,+ render,+ renderHook,+ screen,+ waitFor,+} from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import type { LicenseInfo } from "@app/types/license";+import { BillingScreen } from "@app/billing/BillingScreen";+import { freeWallet } from "@app/billing/walletFixtures";+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback?: string, vars?: Record<string, unknown>) =>+ (fallback ?? _key).replace(/\{\{(\w+)\}\}/g, (_match, key) =>+ String(vars?.[key] ?? ""),+ ),+ }),+}));const state = vi.hoisted(() => ({licenseInfo: null as LicenseInfo | null,fetchUsers: vi.fn(),@@ -20,6 +36,7 @@ describe("local licence entitlements", () => {enabled: true,maxUsers: 250,hasKey: true,+ licenseKey: "installed-enterprise-key",};state.fetchUsers.mockReset()@@ -39,8 +56,66 @@ describe("local licence entitlements", () => {state.licenseInfo!.enabled = false;const { result } = renderHook(() => useServerPlan(true));expect(result.current.serverPlan).toBeUndefined();- expect(state.fetchUsers).not.toHaveBeenCalled();+ expect(state.fetchUsers).toHaveBeenCalled();});+ it.each([undefined, "", "00000000-0000-0000-0000-000000000000"])(+ "keeps keyless SERVER features on Team billing with key %s",+ async (licenseKey) => {+ state.licenseInfo = {+ licenseType: "SERVER",+ enabled: true,+ maxUsers: 200,+ hasKey: Boolean(licenseKey),+ licenseKey,+ };+ const addCapacity = vi.fn();+ function LinkedTeamBilling() {+ const { serverPlan, usersInUse } = useServerPlan(true);+ return (+ <BillingScreen+ selfHosted+ serverPlan={serverPlan}+ usersInUse={usersInUse}+ wallet={{+ ...freeWallet,+ team: { held: true, licensedUsers: 200, usersInUse: 40 },+ }}+ onAddCapacity={addCapacity}+ />+ );+ }+ render(<LinkedTeamBilling />);+ expect(screen.getByText("Team")).toBeInTheDocument();+ await waitFor(() =>+ expect(screen.getByText("37 of 200 users")).toBeInTheDocument(),+ );+ expect(screen.queryByText("Server")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));+ expect(addCapacity).toHaveBeenCalledOnce();+ expect(state.licenseInfo.licenseType).toBe("SERVER");+ expect(state.fetchUsers).toHaveBeenCalled();+ },+ );+ it.each(["installed-server-key", "file:/licenses/server.cert"])(+ "keeps installed Server billing for %s",+ async (licenseKey) => {+ state.licenseInfo = {+ licenseType: "SERVER",+ enabled: true,+ maxUsers: 9999,+ hasKey: true,+ licenseKey,+ };+ const { result } = renderHook(() => useServerPlan(true));+ await waitFor(() =>+ expect(result.current.serverPlan).toEqual({+ licenseType: "SERVER",+ maxUsers: 9999,+ usersInUse: 37,+ }),+ );+ },+ );it("does not read licence seats for a non-admin", () => {const { result } = renderHook(() => useServerPlan(false));expect(result.current.serverPlan).toBeUndefined();diff --git a/frontend/editor/src/portal/hooks/useServerPlan.ts b/frontend/editor/src/portal/hooks/useServerPlan.tsindex 53aa698a8e..807c2a95dd 100644--- a/frontend/editor/src/portal/hooks/useServerPlan.ts+++ b/frontend/editor/src/portal/hooks/useServerPlan.ts@@ -3,32 +3,44 @@ import { useLicense } from "@app/contexts/LicenseContext";import { usersBackend } from "@app/portal/usersBackend";import type { ServerPlan } from "@app/billing/serverPlan";-/** Read local entitlements only in the self-hosted administrator's billing gate. */+/** Reads installed-plan details and the local roster; keyless Team also needs the roster for seat usage. */export function useServerPlan(enabled: boolean) {const { licenseInfo, loading } = useLicense();const [usersInUse, setUsersInUse] = useState<number | null>(null);+ const installedKey = licenseInfo?.licenseKey?.trim();const licenseType =- enabled && licenseInfo?.enabled && licenseInfo.licenseType !== "NORMAL"+ enabled &&+ licenseInfo?.enabled &&+ licenseInfo.hasKey &&+ installedKey &&+ installedKey !== "00000000-0000-0000-0000-000000000000" &&+ licenseInfo.licenseType !== "NORMAL"? licenseInfo.licenseType: null;useEffect(() => {let cancelled = false;setUsersInUse(null);- if (licenseType) {+ const refreshUsers = () => {+ if (!enabled) return;usersBackend.fetchUsers(licenseType === "ENTERPRISE" ? "enterprise" : "pro").then(({ summary }) => {if (!cancelled) setUsersInUse(summary.seatsUsed);})- .catch(() => {});- }+ .catch(() => {+ if (!cancelled) setUsersInUse(null);+ });+ };+ refreshUsers();+ window.addEventListener("focus", refreshUsers);return () => {cancelled = true;+ window.removeEventListener("focus", refreshUsers);};- }, [licenseType, licenseInfo]);+ }, [enabled, licenseType, licenseInfo]);const serverPlan: ServerPlan | undefined =licenseType && licenseInfo? { licenseType, maxUsers: licenseInfo.maxUsers, usersInUse }: undefined;- return { serverPlan, loading: loading && !licenseInfo };+ return { serverPlan, usersInUse, loading: loading && !licenseInfo };}diff --git a/frontend/editor/src/portal/hooks/useStripePortal.ts b/frontend/editor/src/portal/hooks/useStripePortal.tsindex c438dabcca..5f5bce064d 100644--- a/frontend/editor/src/portal/hooks/useStripePortal.ts+++ b/frontend/editor/src/portal/hooks/useStripePortal.ts@@ -3,7 +3,7 @@ import type { Wallet } from "@portal/api/billing";import { createPortalSession } from "@portal/billing/stripe";/**- * Opens the Stripe customer portal for the wallet's team in a new tab. Card,+ * Opens the Stripe customer portal for the wallet's team. Card,* invoice, and cancellation changes all live in Stripe's hosted portal — both* the header "Manage Payment" action and the payment-method card's "Update"* button route through here.@@ -22,7 +22,7 @@ export function useStripePortal(wallet: Wallet | null) {teamId,returnUrl: window.location.href,});- window.open(url, "_blank", "noopener,noreferrer");+ window.location.assign(url);} catch (e) {setError(e instanceof Error ? e.message : String(e));} finally {diff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsxindex 603a9dc18f..f10f5b24b9 100644--- a/frontend/editor/src/portal/views/Usage.test.tsx+++ b/frontend/editor/src/portal/views/Usage.test.tsx@@ -90,8 +90,9 @@ vi.mock("@portal/api/billing", () => ({fetchWallet: () => fetchWallet(),refreshWalletCache: () => refreshWalletCache(),}));+const fetchLocalUsage = vi.fn().mockResolvedValue(null);vi.mock("@portal/api/link", () => ({- fetchLocalUsage: () => Promise.resolve(null),+ fetchLocalUsage: () => fetchLocalUsage(),triggerLocalSync: () => Promise.resolve(),}));vi.mock("@portal/hooks/useStripePortal", () => ({@@ -368,3 +369,18 @@ describe("Usage — link-free wallet renderer", () => {).not.toBeInTheDocument();});});++it("does not request instance-local usage on SaaS", async () => {+ fetchWallet.mockResolvedValue(freeWallet);+ fetchLocalUsage.mockClear();+ renderUsage(<Usage />);+ await waitFor(() => expect(screen.getByText("Free")).toBeInTheDocument());+ expect(fetchLocalUsage).not.toHaveBeenCalled();+});++it("requests pending usage for a self-hosted instance", async () => {+ fetchWallet.mockResolvedValue(freeWallet);+ fetchLocalUsage.mockClear();+ renderUsage(<Usage localUsersInUse={null} />);+ await waitFor(() => expect(fetchLocalUsage).toHaveBeenCalled());+});diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsxindex bc1b7f9668..e6631011dc 100644--- a/frontend/editor/src/portal/views/Usage.tsx+++ b/frontend/editor/src/portal/views/Usage.tsx@@ -41,6 +41,8 @@ import "@portal/views/Usage.css";import "@portal/components/billing/billing.css";export interface UsageProps {+ /** Local occupied seats for self-hosted; undefined keeps the SaaS membership count. */+ localUsersInUse?: number | null;serverPlan?: ServerPlan;serverPlanAction?: ReactNode;/**@@ -70,6 +72,7 @@ export interface UsageProps {* products render from their own holdings, which that axis cannot express.*/export function Usage({+ localUsersInUse,serverPlan,serverPlanAction,onWalletLoaded,@@ -125,6 +128,7 @@ export function Usage({]);// Locally-accrued usage SaaS hasn't billed yet; added to the synced figure so// "current usage" reflects work since the last daily sync. Best-effort.+ const hasLocalInstance = localUsersInUse !== undefined;const [localUsage, setLocalUsage] = useState<LocalUsage | null>(null);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);@@ -175,13 +179,14 @@ export function Usage({setSessionExpired(false);// Independent of the wallet load — a local-usage failure must not break the// page; it just means no unsynced delta is shown.- fetchLocalUsage()- .then((u) => {- if (!cancelled) setLocalUsage(u);- })- .catch(() => {- if (!cancelled) setLocalUsage(null);- });+ if (hasLocalInstance)+ fetchLocalUsage()+ .then((u) => {+ if (!cancelled) setLocalUsage(u);+ })+ .catch(() => {+ if (!cancelled) setLocalUsage(null);+ });fetchWallet().then((w) => {if (cancelled) return;@@ -216,9 +221,30 @@ export function Usage({return () => {cancelled = true;};- }, [refreshKey, onWalletLoaded, t]);+ }, [refreshKey, onWalletLoaded, t, hasLocalInstance]);const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);+ useEffect(() => {+ const refreshVisible = () => {+ if (document.visibilityState === "visible") refresh();+ };+ window.addEventListener("focus", refreshVisible);+ const interval = window.setInterval(refreshVisible, 30_000);+ return () => {+ window.removeEventListener("focus", refreshVisible);+ window.clearInterval(interval);+ };+ }, [refresh]);+ useEffect(() => {+ const onBillingUpdated = () => {+ void refreshWalletCache()+ .catch(() => {})+ .finally(refresh);+ };+ window.addEventListener("stirling:billing-updated", onBillingUpdated);+ return () =>+ window.removeEventListener("stirling:billing-updated", onBillingUpdated);+ }, [refresh]);const refreshAfterLicense = useCallback(() => {void refreshWalletCache().catch(() => {})@@ -232,14 +258,15 @@ export function Usage({// Optional on purpose: a build that mounts no provider must lose the door, not the page.const checkout = useCheckoutOptional();const heldLimit = wallet?.team?.held ? wallet.team.licensedUsers : null;- const usersInUse = wallet?.team?.usersInUse;+ const usersInUse =+ localUsersInUse === undefined ? wallet?.team?.usersInUse : localUsersInUse;const addCapacity = useCallback(() => {// No email: the only one this instance holds is its local admin record, which is a Spring// username and not an address the buyer owns. The checkout asks for one instead.void checkout?.openCheckout("server", {combinedChoose: true,currentLimit: heldLimit,- minimumSeats: usersInUse,+ minimumSeats: usersInUse ?? undefined,onSuccess: () => setRefreshKey((k) => k + 1),});}, [checkout, heldLimit, usersInUse]);@@ -263,7 +290,7 @@ export function Usage({// Nudge the local instance to refresh its gate now so billable work// unblocks immediately rather than on its next poll. Fire-and-forget;// a no-op on SaaS (no local instance to sync).- triggerLocalSync().catch(() => {});+ if (hasLocalInstance) triggerLocalSync().catch(() => {});return true;}} catch {@@ -276,13 +303,26 @@ export function Usage({// shows its "almost there" notice rather than the page silently self-healing.setRefreshKey((k) => k + 1);return false;- }, [onWalletLoaded]);+ }, [onWalletLoaded, hasLocalInstance]);const enterpriseProcessor = serverPlan?.licenseType === "ENTERPRISE";const paying = Boolean(wallet?.processor?.active || wallet?.team?.held);return (<BillingScreen+ usersInUse={localUsersInUse}+ headerAction={+ paying && wallet?.role === "leader" ? (+ <Button+ fat+ variant="secondary"+ onClick={portal.open}+ disabled={portal.opening}+ >+ {t("payment.manageSubscription", "Manage subscription")}+ </Button>+ ) : undefined+ }wallet={wallet}serverPlan={serverPlan}serverPlanAction={serverPlanAction}@@ -354,6 +394,7 @@ export function Usage({</>}editorsDeployed={editorsDeployed}+ pdfsProcessed={fleetStats?.pdfsProcessed ?? null}licenseSection={renderLicenseSection?.(refreshAfterLicense)}onAddCapacity={checkout && wallet?.role === "leader" ? addCapacity : undefined@@ -404,7 +445,7 @@ export function Usage({<PaymentSectionpendingUnits={localUsage?.totalUnsyncedUnits ?? 0}wallet={wallet}- onManage={portal.open}+ onManage={wallet.role === "leader" ? portal.open : undefined}managing={portal.opening}/>) : undefineddiff --git a/frontend/editor/src/proprietary/auth/session.ts b/frontend/editor/src/proprietary/auth/session.tsnew file mode 100644index 0000000000..f86e3f0516--- /dev/null+++ b/frontend/editor/src/proprietary/auth/session.ts@@ -0,0 +1,8 @@+import { supabase } from "@app/services/supabaseClient";++/** The Stirling account token used for checkout, independent of the local server login. */+export async function getAccessToken(): Promise<string | null> {+ if (!supabase) return null;+ const { data } = await supabase.auth.getSession();+ return data.session?.access_token ?? null;+}diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsxindex ccdfbdc9fa..49cc9b5a0d 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx@@ -12,6 +12,10 @@ import type { Wallet } from "@app/billing/types";import "@app/billing/billing-screen.css";export interface BillingScreenProps {+ /** Host-specific occupied seats; null means unavailable, undefined uses the wallet. */+ usersInUse?: number | null;+ /** Host-authorized account actions beside the page title. */+ headerAction?: ReactNode;/*** Null while loading, or when the host could not read one. A non-null wallet must be complete:* the sections dereference its fields without guards, so a hand-built partial object throws@@ -49,6 +53,8 @@ export interface BillingScreenProps {invoicesSection?: ReactNode;/** Null when the backend cannot compute it, which omits the row rather than showing a zero. */editorsDeployed?: number | null;+ /** Overrides wallet analytics when supplied; null omits an unavailable activity count. */+ pdfsProcessed?: number | null;/** The enterprise door. Omitted for a team already on an agreement. */onEnterpriseQuote?: () => void;/** Host-owned surfaces that are not sections of this card: modals, upsells, detail cards. */@@ -80,6 +86,8 @@ function cycleDay(* <p>A chip exists only where its section does, so an omitted slot removes both.*/export function BillingScreen({+ usersInUse,+ headerAction,wallet,loading = false,selfHosted = false,@@ -95,6 +103,7 @@ export function BillingScreen({procurementSection,licenseSection,editorsDeployed,+ pdfsProcessed,paymentSection,invoicesSection,onEnterpriseQuote,@@ -111,6 +120,10 @@ export function BillingScreen({const enterpriseProcessor = serverPlan?.licenseType === "ENTERPRISE";const paying = Boolean(wallet?.processor?.active) && !enterpriseProcessor;const teamHeld = Boolean(wallet?.team?.held);+ const processedCount =+ pdfsProcessed === undefined+ ? wallet?.docsProcessedThisPeriod+ : pdfsProcessed;const chips = useMemo(() => {const out: Array<[string, string]> = [];@@ -221,6 +234,11 @@ export function BillingScreen({}, [wallet, paying, teamHeld, serverPlan, t]);const creditUnits = (wallet?.spendUnitsThisPeriod ?? 0) + pendingUnits;+ const occupiedSeats = serverPlan+ ? serverPlan.usersInUse+ : usersInUse === undefined+ ? wallet?.team.usersInUse+ : usersInUse;const showTeam = Boolean(wallet &&(wallet.team.held ||@@ -238,15 +256,18 @@ export function BillingScreen({return (<div className="billing-page"><header className="billing-page__head">- <h1 className="billing-page__title">- {t("portal.usage.title", "Usage & Billing")}- </h1>- <p className="billing-page__subtitle">- {t(- "portal.usage.subtitle",- "Your plan, your usage, and every invoice.",- )}- </p>+ <div>+ <h1 className="billing-page__title">+ {t("portal.usage.title", "Usage & Billing")}+ </h1>+ <p className="billing-page__subtitle">+ {t(+ "portal.usage.subtitle",+ "Your plan, your usage, and every invoice.",+ )}+ </p>+ </div>+ {headerAction}</header><div className="billing-page__body">@@ -311,6 +332,7 @@ export function BillingScreen({<div className="billing-meters">{(showTeam || serverPlan) && (<TeamPlanRow+ usersInUse={usersInUse}wallet={wallet}selfHosted={selfHosted}serverPlan={serverPlan}@@ -374,18 +396,19 @@ export function BillingScreen({</div>)}- <KvRow- label={t("portal.billing.cycle.pdfs", "PDFs processed")}- value={wallet.docsProcessedThisPeriod.toLocaleString()}- />- {(serverPlan- ? serverPlan.usersInUse != null- : showTeam) && (+ {processedCount != null && (+ <KvRow+ label={t(+ "portal.billing.cycle.pdfs",+ "PDFs processed",+ )}+ value={processedCount.toLocaleString()}+ />+ )}+ {(serverPlan || showTeam) && occupiedSeats != null && (<KvRowlabel={t("portal.billing.cycle.users", "Users")}- value={(- serverPlan?.usersInUse ?? wallet.team.usersInUse- ).toLocaleString()}+ value={occupiedSeats.toLocaleString()}/>)}{editorsDeployed != null && (diff --git a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsxindex e5d187d927..c63d4ced02 100644--- a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx+++ b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx@@ -17,6 +17,7 @@ export function TeamPlanRow({selfHosted = false,serverPlan,onAddCapacity,+ usersInUse: occupiedSeats,}: {wallet: Wallet | null;serverPlan?: ServerPlan;@@ -24,6 +25,8 @@ export function TeamPlanRow({selfHosted?: boolean;/** Leader-only: the door that sells Team capacity. Omit for members. */onAddCapacity?: () => void;+ /** Undefined uses cloud membership; null hides an unavailable local count. */+ usersInUse?: number | null;}) {const { t } = useTranslation();if (serverPlan) {@@ -67,7 +70,9 @@ export function TeamPlanRow({);}if (!wallet) return null;- const { held, licensedUsers, usersInUse } = wallet.team;+ const { held, licensedUsers } = wallet.team;+ const usersInUse =+ occupiedSeats === undefined ? wallet.team.usersInUse : occupiedSeats;const processorActive = Boolean(wallet.processor?.active);const mid = !held@@ -92,6 +97,26 @@ export function TeamPlanRow({? licensedUsers: (licensedUsers ?? wallet.freeUserAllowance ?? null);+ if (usersInUse == null) {+ return (+ <MeterRow+ name={name}+ mid={mid}+ showTrack={false}+ tone={held ? "paid" : "free"}+ fact={+ limit != null+ ? t("portal.billing.serverPlan.seats", "{{seats}} licensed seats", {+ seats: limit.toLocaleString(),+ })+ : "—"+ }+ door={door}+ onDoor={onAddCapacity}+ />+ );+ }+// A non-positive limit is an absent one, not a full meter: nothing to divide by either way.if (limit == null || limit <= 0) {return (diff --git a/frontend/editor/src/proprietary/billing/billing-screen.css b/frontend/editor/src/proprietary/billing/billing-screen.cssindex 96992ebb66..ac5eb0c05b 100644--- a/frontend/editor/src/proprietary/billing/billing-screen.css+++ b/frontend/editor/src/proprietary/billing/billing-screen.css@@ -12,6 +12,11 @@}.billing-page__head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 1rem;flex-shrink: 0;padding: 1.75rem 2.5rem 0.75rem;}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminDatabasePage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminDatabasePage.tsxindex 3c7584833c..788e7b741c 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminDatabasePage.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminDatabasePage.tsx@@ -127,7 +127,7 @@ export default function AdminDatabasePage() {"admin.settings.database.connectionDescription","Point Stirling at an external database instead of the embedded one.",)}- badge={<TierBadge tier="ENTERPRISE" />}+ badge={<TierBadge tier="PRO" />}><DatabaseConfigCardsettings={settings}diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsxindex ae230ed43b..abe8337064 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx@@ -150,7 +150,9 @@ describe("capacity checkout entry", () => {expect(screen.queryByText("Buyer email")).not.toBeInTheDocument();},);- it("still asks a free user for their billing email", async () => {+ // The free user is the case that changed: this lane mints the checkout as their Stirling+ // account, so the address comes from the team's billing owner and nobody is asked for one.+ it("does not ask a free user for a billing email either", async () => {service.getLicenseInfo.mockResolvedValue({ licenseType: "NORMAL" });render(<StripeCheckout@@ -158,18 +160,6 @@ describe("capacity checkout entry", () => {onClose={() => {}}planGroup={planGroup}combinedChoose- />,- );- expect(await screen.findByText("Buyer email")).toBeInTheDocument();- });- it("seeds required capacity when the caller supplies an email", async () => {- render(- <StripeCheckout- opened- onClose={() => {}}- planGroup={planGroup}- combinedChoose- initialEmail="[email protected]"minimumSeats={250}currentLimit={300}/>,@@ -177,12 +167,15 @@ describe("capacity checkout entry", () => {expect(await screen.findByText("Capacity: 3 blocks; current: 300"),).toBeInTheDocument();- expect(service.getLicenseInfo).not.toHaveBeenCalled();+ expect(screen.getByText("Billing period")).toBeInTheDocument();+ expect(screen.queryByText("Buyer email")).not.toBeInTheDocument();});});describe("combined checkout for plans without capacity", () => {- it.each(["supplied email", "existing license", "email entry"])(+ // Two entry paths now, not three: the licence only decides whether an upgrade key travels with+ // the purchase, never whether an address is collected first.+ it.each(["existing license", "no license"])("reaches payment from %s",async (entry) => {service.getLicenseInfo.mockResolvedValue(@@ -196,18 +189,8 @@ describe("combined checkout for plans without capacity", () => {onClose={() => {}}planGroup={{ ...planGroup, tier: "enterprise" }}combinedChoose- initialEmail={- entry === "supplied email" ? "[email protected]" : undefined- }/>,);- if (entry === "email entry") {- await screen.findByText("Buyer email");- fireEvent.change(screen.getByLabelText("Email"), {- target: { value: "[email protected]" },- });- fireEvent.click(screen.getByRole("button", { name: "Continue" }));- }fireEvent.click(await screen.findByRole("button", { name: "Monthly" }));expect(await screen.findByText("Payment details")).toBeInTheDocument();expect(screen.queryByText(/Capacity:/)).not.toBeInTheDocument();@@ -222,7 +205,6 @@ it("starts at held capacity and lets payment return to those choices", async ()onClose={() => {}}planGroup={planGroup}combinedChoose- initialEmail="[email protected]"minimumSeats={40}currentLimit={300}/>,diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsxindex 857b0258f9..f45ed2e734 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx@@ -11,16 +11,12 @@ import {StripeCheckoutProps,} from "@app/components/shared/stripeCheckout/types/checkout";import { StepModalHeader } from "@app/components/shared/StepModalHeader";-import {- validateEmail,- getModalTitle,-} from "@app/components/shared/stripeCheckout/utils/checkoutUtils";+import { getModalTitle } from "@app/components/shared/stripeCheckout/utils/checkoutUtils";import { calculateSavings } from "@app/components/shared/stripeCheckout/utils/savingsCalculator";import { useCheckoutState } from "@app/components/shared/stripeCheckout/hooks/useCheckoutState";import { useCheckoutNavigation } from "@app/components/shared/stripeCheckout/hooks/useCheckoutNavigation";import { useLicensePolling } from "@app/components/shared/stripeCheckout/hooks/useLicensePolling";import { useCheckoutSession } from "@app/components/shared/stripeCheckout/hooks/useCheckoutSession";-import { EmailStage } from "@app/components/shared/stripeCheckout/stages/EmailStage";import { PlanSelectionStage } from "@app/components/shared/stripeCheckout/stages/PlanSelectionStage";import { CapacityStage } from "@app/components/shared/stripeCheckout/stages/CapacityStage";import { blocksForUsers } from "@app/components/shared/stripeCheckout/utils/capacity";@@ -51,7 +47,6 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({onClose,planGroup,minimumSeats = 1,- initialEmail,combinedChoose: requestedCombinedChoose = false,currentLimit = null,onSuccess,@@ -100,34 +95,13 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({onSuccess,onError,onLicenseActivated,+ undefined,+ () => checkoutState.isMountedRef.current,);// Calculate savingsconst savings = calculateSavings(planGroup, minimumSeats);- // Email submission handler- const handleEmailSubmit = () => {- const validation = validateEmail(checkoutState.emailInput);- if (validation.valid) {- checkoutState.setState((prev) => ({- ...prev,- email: checkoutState.emailInput,- }));- if (combinedChoose) {- // Arrive on the capacity an installation already needs rather than on a blocked minimum,- // the same seeding the separate walk does when a period is picked.- if (sellsCapacity) {- checkoutState.setServerQuantity(blocksForUsers(minimumCapacity));- }- navigation.goToStage("choose");- } else {- navigation.goToStage("plan-selection");- }- } else {- checkoutState.setEmailError(validation.error);- }- };-// Plan selection handlerconst handlePlanSelect = (period: "monthly" | "yearly") => {checkoutState.setSelectedPeriod(period);@@ -142,6 +116,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({// Close handlerconst handleClose = () => {+ checkoutState.isMountedRef.current = false;// Clear any active pollingif (checkoutState.pollingTimeoutRef.current) {clearTimeout(checkoutState.pollingTimeoutRef.current);@@ -168,6 +143,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({// Initialize stage based on existing licenseuseEffect(() => {if (!opened) return;+ checkoutState.isMountedRef.current = true;// Handle hosted checkout success - open directly to success stateif (hostedCheckoutSuccess) {@@ -187,50 +163,29 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({return;}- // Check for existing license to skip email stage- const checkExistingLicense = async () => {+ // Only installed licence upgrades need the previous key; Team belongs to the cloud account.+ const openOnFirstChoice = async () => {+ const landing = combinedChoose ? "choose" : "plan-selection";try {- // A caller that already holds the email (a linked instance does, from the account link)- // never needs to be asked for it, whatever the licence says.if (combinedChoose && sellsCapacity)checkoutState.setServerQuantity(blocksForUsers(minimumCapacity));- if (initialEmail) {- checkoutState.setEmailInput(initialEmail);- checkoutState.setState((prev) => ({- ...prev,- email: initialEmail,- currentStage: combinedChoose ? "choose" : "plan-selection",- loading: false,- }));- return;- }-- const licenseInfo = await licenseService.getLicenseInfo();- // Only skip email if license is PRO or ENTERPRISE (not NORMAL/free tier)+ const licenseInfo = sellsCapacity+ ? null+ : await licenseService.getLicenseInfo();if (licenseInfo?.licenseType && licenseInfo.licenseType !== "NORMAL") {- // Has valid premium license - skip email stage- console.log("Valid premium license detected - skipping email stage");checkoutState.setCurrentLicenseKey(licenseInfo.licenseKey || null);- checkoutState.setState({- currentStage: combinedChoose ? "choose" : "plan-selection",- loading: false,- });- } else {- // No valid premium license - start at email stage- checkoutState.setState({ currentStage: "email", loading: false });}} catch (error) {+ // An unreadable licence only costs the upgrade metadata, so the purchase still proceeds.console.warn("Could not check for existing license:", error);- // Default to email stage if check fails- checkoutState.setState({ currentStage: "email", loading: false });}+ checkoutState.setState({ currentStage: landing, loading: false });};- checkExistingLicense();+ openOnFirstChoice();}, [opened,hostedCheckoutSuccess,- initialEmail,combinedChoose,sellsCapacity,minimumCapacity,@@ -263,16 +218,6 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({// Don't block checkout - hosted mode works without publishable key// The checkout will automatically redirect to Stripe hosted page if key is missingswitch (checkoutState.state.currentStage) {- case "email":- return (- <EmailStage- emailInput={checkoutState.emailInput}- setEmailInput={checkoutState.setEmailInput}- emailError={checkoutState.emailError}- onSubmit={handleEmailSubmit}- />- );-// Page 1 of 2: both choices at once, which is how the design puts them in front of a buyer.// The period cards select rather than navigate, and capacity supplies the single continue.case "choose":@@ -342,6 +287,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({case "success":return (<SuccessStage+ isTeam={sellsCapacity}pollingStatus={checkoutState.pollingStatus}currentLicenseKey={checkoutState.currentLicenseKey}licenseKey={checkoutState.licenseKey}@@ -363,17 +309,10 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({};const canGoBack = checkoutState.stageHistory.length > 0;- // The combined flow wears the stepped chrome, counting the pages it actually walks: the email- // page only when the caller supplied no address. The separate walk keeps its own title, because- // a step count would be a lie about how many pages it has.+ // The combined flow wears the stepped chrome, counting the pages it actually walks. The separate+ // walk keeps its own title, because a step count would be a lie about how many pages it has.const steppedPath: CheckoutStage[] | null = combinedChoose- ? [- ...(initialEmail || checkoutState.currentLicenseKey- ? []- : (["email"] as CheckoutStage[])),- "choose",- "payment",- ]+ ? ["choose", "payment"]: null;const steppedIndex = steppedPath? steppedPath.indexOf(checkoutState.state.currentStage)diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutSession.test.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutSession.test.tsxnew file mode 100644index 0000000000..379b7ad309--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutSession.test.tsx@@ -0,0 +1,186 @@+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++/**+ * The Team purchase mints its Stripe session as the buyer's SaaS account, so what the hook sends+ * is the contract worth pinning: the sized capacity, and no email (the edge function reads that+ * from the JWT). Both are asserted through an injected session creator, which is also what keeps+ * the test off a Supabase client.+ */+const getLicenseInfo = vi.fn();+const getInstallationId = vi.fn();++vi.mock("@app/services/licenseService", () => ({+ default: {+ getLicenseInfo: () => getLicenseInfo(),+ getInstallationId: () => getInstallationId(),+ },+}));+vi.mock("@app/utils/licenseCheckoutUtils", () => ({+ resyncExistingLicense: vi.fn(),+ pollTeamCheckout: vi.fn(),+}));+vi.mock("@app/utils/protocolDetection", () => ({+ getCheckoutMode: () => "embedded",+}));+vi.mock("@app/services/serverPlanCheckout", () => ({+ createServerPlanCheckoutSession: vi.fn(),+}));++import { useCheckoutSession } from "@app/components/shared/stripeCheckout/hooks/useCheckoutSession";+import { pollTeamCheckout } from "@app/utils/licenseCheckoutUtils";+import type { CheckoutState } from "@app/components/shared/stripeCheckout/types/checkout";++const plan = {+ id: "selfhosted:server:yearly",+ name: "Team",+ price: 0,+ currency: "usd",+ period: "yearly",+ features: [],+ highlights: [],+ lookupKey: "selfhosted:server:yearly",+ requiresSeats: false,+};++function mount(+ createSession: ReturnType<typeof vi.fn>,+ state: CheckoutState = { currentStage: "payment" },+ selectedPlan = plan,+ installationId: string | null = "install-abc",+) {+ const setState = vi.fn();+ const hook = renderHook(() =>+ useCheckoutSession(+ selectedPlan,+ state,+ setState,+ installationId,+ vi.fn(),+ null,+ vi.fn(),+ vi.fn(),+ 7,+ 3,+ vi.fn(),+ undefined,+ undefined,+ undefined,+ createSession as never,+ ),+ );+ return { hook, setState };+}++beforeEach(() => {+ getLicenseInfo.mockReset().mockResolvedValue({ licenseType: "NORMAL" });+ getInstallationId.mockReset();+});++describe("useCheckoutSession", () => {+ it("confirms Team entitlement instead of polling for a licence key", async () => {+ vi.mocked(pollTeamCheckout).mockResolvedValue({ success: true });+ const { hook } = mount(vi.fn(), {+ currentStage: "payment",+ sessionId: "cs_team",+ });+ await hook.result.current.handlePaymentComplete();+ expect(pollTeamCheckout).toHaveBeenCalledWith(+ "cs_team",+ 3,+ expect.any(Object),+ );+ });+ it("sends the sized capacity and never an email", async () => {+ const createSession = vi.fn().mockResolvedValue({+ clientSecret: "cs_1",+ url: null,+ sessionId: "sess_1",+ });+ const { hook } = mount(createSession, {+ currentStage: "payment",+ email: "[email protected]",+ });++ await hook.result.current.createCheckoutSession();++ await waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));+ const request = createSession.mock.calls[0][0];+ expect(request).not.toHaveProperty("email");+ expect(request).toMatchObject({+ lookupKey: "selfhosted:server:yearly",+ serverQuantity: 3,+ seatCount: 7,+ installationId: "install-abc",+ uiMode: "embedded",+ });+ expect(request.successUrl).toContain("payment_status=success");+ });++ it("carries a premium licence key through as upgrade metadata", async () => {+ getLicenseInfo.mockResolvedValue({+ licenseType: "SERVER",+ licenseKey: "key-1",+ });+ const createSession = vi+ .fn()+ .mockResolvedValue({ clientSecret: "cs", url: null, sessionId: "s" });+ const { hook } = mount(createSession, undefined, {+ ...plan,+ requiresSeats: true,+ });++ await hook.result.current.createCheckoutSession();++ expect(createSession.mock.calls[0][0].currentLicenseKey).toBe("key-1");+ });++ it("surfaces a transport failure as the error stage", async () => {+ const createSession = vi.fn().mockRejectedValue(new Error("Unauthorized"));+ const onError = vi.fn();+ const setState = vi.fn();+ const hook = renderHook(() =>+ useCheckoutSession(+ plan,+ { currentStage: "payment" },+ setState,+ "install-abc",+ vi.fn(),+ null,+ vi.fn(),+ vi.fn(),+ 1,+ 1,+ vi.fn(),+ undefined,+ onError,+ undefined,+ createSession as never,+ ),+ );++ await hook.result.current.createCheckoutSession();++ expect(onError).toHaveBeenCalledWith("Unauthorized");+ expect(setState).toHaveBeenCalledWith(+ expect.objectContaining({ currentStage: "error", error: "Unauthorized" }),+ );+ });+});++it("creates Team checkout without accessing installation admin endpoints", async () => {+ const createSession = vi+ .fn()+ .mockResolvedValue({ clientSecret: "cs", sessionId: "s" });+ const { hook } = mount(createSession, undefined, plan, null);+ await hook.result.current.createCheckoutSession();+ expect(createSession).toHaveBeenCalledWith(+ expect.objectContaining({+ serverQuantity: 3,+ installationId: undefined,+ currentLicenseKey: undefined,+ }),+ );+ expect(getInstallationId).not.toHaveBeenCalled();+ expect(getLicenseInfo).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutSession.ts b/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutSession.tsindex 474406adc3..757f455344 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutSession.ts+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutSession.ts@@ -1,11 +1,29 @@import { useCallback } from "react";import licenseService, { PlanTier } from "@app/services/licenseService";-import { resyncExistingLicense } from "@app/utils/licenseCheckoutUtils";+import {+ resyncExistingLicense,+ pollTeamCheckout,+} from "@app/utils/licenseCheckoutUtils";+import {+ createServerPlanCheckoutSession,+ type ServerPlanCheckoutRequest,+ type ServerPlanCheckoutSession,+} from "@app/services/serverPlanCheckout";+import { getCheckoutMode } from "@app/utils/protocolDetection";import {CheckoutState,PollingStatus,} from "@app/components/shared/stripeCheckout/types/checkout";+/**+ * Mints the Stripe session a plan purchase is paid through. Injectable so a test can drive the+ * stages without a Supabase client, and so the transport stays one named thing rather than a+ * hard-coded import in the middle of the stage machine.+ */+export type CheckoutSessionCreator = (+ request: ServerPlanCheckoutRequest,+) => Promise<ServerPlanCheckoutSession>;+/*** Checkout session creation and payment handling hook*/@@ -29,6 +47,8 @@ export const useCheckoutSession = (maxUsers: number;hasKey: boolean;}) => void,+ createSession: CheckoutSessionCreator = createServerPlanCheckoutSession,+ isMounted?: () => boolean,) => {const createCheckoutSession = useCallback(async () => {if (!selectedPlan) {@@ -45,7 +65,7 @@ export const useCheckoutSession = (// Fetch installation ID from backendlet fetchedInstallationId = installationId;- if (!fetchedInstallationId) {+ if (selectedPlan.requiresSeats && !fetchedInstallationId) {fetchedInstallationId = await licenseService.getInstallationId();setInstallationId(fetchedInstallationId);}@@ -54,7 +74,9 @@ export const useCheckoutSession = (// Only include if it's a valid PRO/ENTERPRISE license (not NORMAL/free tier)let existingLicenseKey: string | undefined;try {- const licenseInfo = await licenseService.getLicenseInfo();+ const licenseInfo = selectedPlan.requiresSeats+ ? await licenseService.getLicenseInfo()+ : null;if (licenseInfo?.licenseType &&licenseInfo.licenseType !== "NORMAL" &&@@ -71,29 +93,35 @@ export const useCheckoutSession = ();}- const response = await licenseService.createCheckoutSession({- lookup_key: selectedPlan.lookupKey,- installation_id: fetchedInstallationId,- current_license_key: existingLicenseKey,- requires_seats: selectedPlan.requiresSeats,- seat_count: Math.max(1, Math.min(minimumSeats || 1, 10000)),- server_quantity: Math.max(1, serverQuantity || 1),- email: state.email, // Pass collected email from Stage 1+ // Stripe's embedded iframe needs a secure context, so a plain-HTTP instance sends the buyer+ // to Stripe's own page and needs the two return URLs up front.+ const uiMode = getCheckoutMode();+ // Back to the page the buyer left, whichever it was: this modal opens from the settings+ // plan section and from the portal's billing screen, and a fixed path lands half of them+ // somewhere they were not. CheckoutProvider reads the return params wherever it is mounted,+ // and both hosts mount it. The current pathname already carries any base path.+ const returnTo = window.location.origin + window.location.pathname;+ const response = await createSession({+ lookupKey: selectedPlan.lookupKey,+ serverQuantity: Math.max(1, serverQuantity || 1),+ requiresSeats: selectedPlan.requiresSeats,+ seatCount: Math.max(1, Math.min(minimumSeats || 1, 10000)),+ installationId: fetchedInstallationId ?? undefined,+ currentLicenseKey: existingLicenseKey,+ uiMode,+ successUrl: `${returnTo}?session_id={CHECKOUT_SESSION_ID}&payment_status=success`,+ cancelUrl: `${returnTo}?payment_status=canceled`,});- // Check if we got a redirect URL (hosted checkout for HTTP)if (response.url) {- console.log("Redirecting to Stripe hosted checkout:", response.url);- // Redirect to Stripe's hosted checkout pagewindow.location.href = response.url;return;}- // Otherwise, use embedded checkout (HTTPS)setState((prev) => ({...prev,- clientSecret: response.clientSecret,- sessionId: response.sessionId,+ clientSecret: response.clientSecret ?? undefined,+ sessionId: response.sessionId ?? undefined,loading: false,}));} catch (err) {@@ -110,10 +138,10 @@ export const useCheckoutSession = (}}, [selectedPlan,- state.email,installationId,minimumSeats,serverQuantity,+ createSession,setState,setInstallationId,setCurrentLicenseKey,@@ -124,6 +152,20 @@ export const useCheckoutSession = (// Preserve state when changing stagesetState((prev) => ({ ...prev, currentStage: "success" }));+ if (!selectedPlan?.requiresSeats) {+ const result = await pollTeamCheckout(+ state.sessionId || "",+ serverQuantity,+ {+ isMounted,+ onStatusChange: setPollingStatus,+ onActivated: onLicenseActivated,+ },+ );+ if (result.success) onSuccess?.(state.sessionId || "");+ return;+ }+// Check if this is an upgrade (existing license key) or new planif (currentLicenseKey) {// UPGRADE FLOW: Resync existing license with Keygen@@ -160,6 +202,9 @@ export const useCheckoutSession = (}}}, [+ selectedPlan,+ serverQuantity,+ isMounted,currentLicenseKey,installationId,state.sessionId,diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutState.ts b/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutState.tsindex 3529566edb..551af681f7 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutState.ts+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/hooks/useCheckoutState.ts@@ -11,7 +11,7 @@ import {*/export const useCheckoutState = (planGroup: PlanTierGroup) => {const [state, setState] = useState<CheckoutState>({- currentStage: "email",+ currentStage: "plan-selection",loading: false,});const [stageHistory, setStageHistory] = useState<CheckoutStage[]>([]);@@ -39,7 +39,7 @@ export const useCheckoutState = (planGroup: PlanTierGroup) => {const resetState = useCallback(() => {setState({- currentStage: "email",+ currentStage: "plan-selection",loading: false,clientSecret: undefined,sessionId: undefined,diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsxindex bcec8e3ab9..1207768541 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx@@ -20,6 +20,45 @@ it("blocks purchasing less than the existing allowance even when usage is lower");expect(screen.getByRole("button", { name: "100" })).toBeDisabled();expect(- screen.getByRole("button", { name: "Continue to payment" }),+ screen.getByRole("button", { name: "Review change in Stripe" }),).toBeDisabled();});++it("shows the new recurring total without inventing the adjustment charge", () => {+ render(+ <MantineProvider>+ <CapacityStage+ selectedPlan={null}+ serverQuantity={3}+ setServerQuantity={() => {}}+ currentUsers={40}+ currentLimit={300}+ onContinue={() => {}}+ />+ </MantineProvider>,+ );+ expect(screen.getByText("New plan total")).toBeInTheDocument();+ expect(screen.queryByText("Due today")).not.toBeInTheDocument();+ expect(+ screen.getByText(/Stripe will show the exact charge/),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Review change in Stripe" }),+ ).toBeEnabled();+});+it("keeps payment language for a first purchase", () => {+ render(+ <MantineProvider>+ <CapacityStage+ selectedPlan={null}+ serverQuantity={1}+ setServerQuantity={() => {}}+ onContinue={() => {}}+ />+ </MantineProvider>,+ );+ expect(screen.getByText("Due today")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Continue to payment" }),+ ).toBeEnabled();+});diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsxindex 8de942229e..01b55f1eaf 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx@@ -175,24 +175,33 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({</Group><Group justify="space-between" align="baseline"><Text fw={600}>- {t("payment.capacityStage.dueToday", "Due today")}+ {currentLimit != null+ ? t("payment.capacityStage.newPlanTotal", "New plan total")+ : t("payment.capacityStage.dueToday", "Due today")}</Text><Text size="xl" fw={700}>{formatPrice(total, currency)}</Text></Group><Text size="xs" c="dimmed">- {t(- "payment.capacityStage.renewalNote",- "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing.",- { total: formatPrice(total, currency, 0), period },- )}+ {currentLimit != null+ ? t(+ "payment.capacityStage.adjustmentNote",+ "Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available.",+ )+ : t(+ "payment.capacityStage.renewalNote",+ "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing.",+ { total: formatPrice(total, currency, 0), period },+ )}</Text></Stack><Stack gap="sm"><Button onClick={onContinue} disabled={belowMinimumCapacity} fullWidth>- {t("payment.capacityStage.continue", "Continue to payment")}+ {currentLimit != null+ ? t("payment.capacityStage.reviewChange", "Review change in Stripe")+ : t("payment.capacityStage.continue", "Continue to payment")}</Button>{offerEnterprise && onContactSales && (diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/SuccessStage.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/SuccessStage.tsxindex a25f2d9705..a2e0605b94 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/SuccessStage.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/SuccessStage.tsx@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";import { PollingStatus } from "@app/components/shared/stripeCheckout/types/checkout";interface SuccessStageProps {+ isTeam?: boolean;pollingStatus: PollingStatus;currentLicenseKey: string | null;licenseKey: string | null;@@ -12,6 +13,7 @@ interface SuccessStageProps {}export const SuccessStage: React.FC<SuccessStageProps> = ({+ isTeam = false,pollingStatus,currentLicenseKey,licenseKey,@@ -23,10 +25,14 @@ export const SuccessStage: React.FC<SuccessStageProps> = ({<Alert color="green" title={t("payment.success", "Payment Successful!")}><Stack gap="md"><Text size="sm">- {t(- "payment.successMessage",- "Your subscription has been activated successfully.",- )}+ {isTeam+ ? pollingStatus === "ready"+ ? t("payment.teamActivated", "Your Team capacity is active")+ : t("payment.teamActivating", "Confirming your Team capacity...")+ : t(+ "payment.successMessage",+ "Your subscription has been activated successfully.",+ )}</Text>{/* License Key Polling Status */}@@ -34,44 +40,52 @@ export const SuccessStage: React.FC<SuccessStageProps> = ({<Group gap="xs"><Loader size="sm" /><Text size="sm" c="dimmed">- {currentLicenseKey+ {isTeam? t(- "payment.syncingLicense",- "Syncing your upgraded license...",+ "payment.teamActivating",+ "Confirming your Team capacity...",)- : t(- "payment.generatingLicense",- "Generating your license key...",- )}+ : currentLicenseKey+ ? t(+ "payment.syncingLicense",+ "Syncing your upgraded license...",+ )+ : t(+ "payment.generatingLicense",+ "Generating your license key...",+ )}</Text></Group>)}- {pollingStatus === "ready" && !currentLicenseKey && licenseKey && (- <Paper withBorder p="md" radius="md" bg="gray.1">- <Stack gap="sm">- <Text size="sm" fw={600}>- {t("payment.licenseKey", "Your License Key")}- </Text>- <Code block>{licenseKey}</Code>- <Button- variant="secondary"- size="sm"- onClick={() => navigator.clipboard.writeText(licenseKey)}- >- {t("common.copy", "Copy to Clipboard")}- </Button>- <Text size="xs" c="dimmed">- {t(- "payment.licenseInstructions",- "This has been added to your installation. You will receive a copy in your email as well.",- )}- </Text>- </Stack>- </Paper>- )}+ {!isTeam &&+ pollingStatus === "ready" &&+ !currentLicenseKey &&+ licenseKey && (+ <Paper withBorder p="md" radius="md" bg="gray.1">+ <Stack gap="sm">+ <Text size="sm" fw={600}>+ {t("payment.licenseKey", "Your License Key")}+ </Text>+ <Code block>{licenseKey}</Code>+ <Button+ variant="secondary"+ size="sm"+ onClick={() => navigator.clipboard.writeText(licenseKey)}+ >+ {t("common.copy", "Copy to Clipboard")}+ </Button>+ <Text size="xs" c="dimmed">+ {t(+ "payment.licenseInstructions",+ "This has been added to your installation. You will receive a copy in your email as well.",+ )}+ </Text>+ </Stack>+ </Paper>+ )}- {pollingStatus === "ready" && currentLicenseKey && (+ {!isTeam && pollingStatus === "ready" && currentLicenseKey && (<Alertcolor="green"title={t("payment.upgradeComplete", "Upgrade Complete")}@@ -88,13 +102,22 @@ export const SuccessStage: React.FC<SuccessStageProps> = ({{pollingStatus === "timeout" && (<Alertcolor="yellow"- title={t("payment.licenseDelayed", "License Key Processing")}+ title={+ isTeam+ ? t("payment.teamProcessing", "Team purchase processing")+ : t("payment.licenseDelayed", "License Key Processing")+ }><Text size="sm">- {t(- "payment.licenseDelayedMessage",- "Your license key is being generated. Please check your email shortly or contact support.",- )}+ {isTeam+ ? t(+ "payment.teamPending",+ "Your Team purchase is still processing. Refresh this page shortly.",+ )+ : t(+ "payment.licenseDelayedMessage",+ "Your license key is being generated. Please check your email shortly or contact support.",+ )}</Text></Alert>)}diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts b/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.tsindex f6bd2ec480..cf4f5fae6e 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts@@ -1,12 +1,10 @@import { PlanTierGroup } from "@app/services/licenseService";export interface StripeCheckoutProps {- /** Supplying it skips the email step. */- initialEmail?: string;/**- * Put the period and capacity choices on one page instead of walking them separately. Independent- * of {@link initialEmail}: a buyer who still has to type an address gets the email page in front- * of the combined one rather than the long walk behind it. Ignored for tiers that do not sell capacity.+ * Put the period and capacity choices on one page instead of walking them separately. Nothing+ * precedes it: the buyer is never asked for an address, so the combined page is the first thing+ * the flow opens on. Ignored for tiers that do not sell capacity.*/combinedChoose?: boolean;/** Users the current plan covers, or null when there is none. Drives the add-capacity face. */@@ -30,17 +28,11 @@ export interface StripeCheckoutProps {}export type CheckoutStage =- | "email"/*** Billing period and capacity on one page. The separate {@code plan-selection} and {@code* capacity} stages remain for the flows that still walk them one at a time.*/- | "choose"- | "plan-selection"- | "capacity"- | "payment"- | "success"- | "error";+ "choose" | "plan-selection" | "capacity" | "payment" | "success" | "error";export type CheckoutState = {currentStage: CheckoutStage;diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/utils/checkoutUtils.ts b/frontend/editor/src/proprietary/components/shared/stripeCheckout/utils/checkoutUtils.tsindex 6b021ff962..1045dbcd38 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/utils/checkoutUtils.ts+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/utils/checkoutUtils.ts@@ -26,10 +26,6 @@ export const getModalTitle = (t: TFunction,): string => {switch (stage) {- case "email":- return t("payment.emailStage.modalTitle", "Get Started - {{planName}}", {- planName,- });case "plan-selection":return t("payment.planStage.modalTitle",diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsxnew file mode 100644index 0000000000..81c2268d5e--- /dev/null+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.test.tsx@@ -0,0 +1,102 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import { CheckoutProvider, useCheckout } from "@app/contexts/CheckoutContext";+import { expectConsole } from "@app/tests/failOnConsole";++const mocks = vi.hoisted(() => ({+ getPlans: vi.fn(),+ getLicenseInfo: vi.fn(),+ getUsers: vi.fn(),+ alert: vi.fn(),+ features: [],+ highlights: [],+ refetch: vi.fn(),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { language: "en-US" },+ }),+}));+vi.mock("@app/constants/planConstants", () => ({+ usePlanFeatures: () => mocks.features,+ usePlanHighlights: () => mocks.highlights,+}));+vi.mock("@app/contexts/LicenseContext", () => ({+ useLicense: () => ({ refetchLicense: mocks.refetch }),+}));+vi.mock("@app/services/supabaseClient", () => ({ isSupabaseConfigured: true }));+vi.mock("@app/utils/currencyDetection", () => ({+ getPreferredCurrency: () => "usd",+}));+vi.mock("@app/components/toast", () => ({ alert: mocks.alert }));+vi.mock("@app/services/userManagementService", () => ({+ userManagementService: { getUsers: mocks.getUsers },+}));+vi.mock("@app/services/licenseService", () => ({+ default: {+ getPlans: mocks.getPlans,+ getLicenseInfo: mocks.getLicenseInfo,+ groupPlansByTier: (plans: unknown[]) =>+ plans.length ? [{ tier: "server" }] : [],+ },+ mapLicenseToTier: () => "free",+}));+vi.mock("@app/components/shared/stripeCheckout", () => ({+ StripeCheckout: () => <div role="dialog">Checkout</div>,+}));++function Buyer() {+ const checkout = useCheckout();+ return (+ <button onClick={() => void checkout.openCheckout("server")}>+ Add capacity+ </button>+ );+}++beforeEach(() => {+ vi.clearAllMocks();+});++it("opens on the first click using asynchronously fetched plans", async () => {+ let resolvePlans!: (value: { plans: unknown[] }) => void;+ mocks.getPlans.mockReturnValue(+ new Promise((resolve) => {+ resolvePlans = resolve;+ }),+ );+ render(+ <CheckoutProvider>+ <Buyer />+ </CheckoutProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));+ expect(mocks.getPlans).toHaveBeenCalledTimes(1);+ resolvePlans({ plans: [{ id: "server-monthly" }] });+ expect(await screen.findByRole("dialog")).toBeInTheDocument();+ expect(mocks.alert).not.toHaveBeenCalled();+ expect(mocks.getLicenseInfo).not.toHaveBeenCalled();+ expect(mocks.getUsers).not.toHaveBeenCalled();+});++it("reports failed price loading visibly and allows a retry", async () => {+ expectConsole.error(/Failed to fetch plans/);+ expectConsole.error(/Error opening checkout/);+ mocks.getPlans.mockRejectedValueOnce(new Error("offline"));+ render(+ <CheckoutProvider>+ <Buyer />+ </CheckoutProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));+ await waitFor(() =>+ expect(mocks.alert).toHaveBeenCalledWith(+ expect.objectContaining({ alertType: "error" }),+ ),+ );+ mocks.getPlans.mockResolvedValue({ plans: [{ id: "server-monthly" }] });+ fireEvent.click(screen.getByRole("button", { name: "Add capacity" }));+ expect(await screen.findByRole("dialog")).toBeInTheDocument();+});diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsxindex d489d48797..e070c9fed4 100644--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx@@ -4,6 +4,7 @@ import React, {useState,useCallback,useEffect,+ useRef,lazy,Suspense,ReactNode,@@ -27,6 +28,7 @@ import {pollLicenseKeyWithBackoff,activateLicenseKey,resyncExistingLicense,+ pollTeamCheckout,} from "@app/utils/licenseCheckoutUtils";import { useLicense } from "@app/contexts/LicenseContext";import { isSupabaseConfigured } from "@app/services/supabaseClient";@@ -41,12 +43,6 @@ export interface CheckoutOptions {currency?: string; // Optional currency override (auto-detected from locale)onSuccess?: (sessionId: string) => void; // Callback after successful paymentonError?: (error: string) => void; // Callback on error- /**- * Supplying it skips the email step. No caller does today: the only address a self-hosted- * instance holds is its Spring username. #7945 removes the step instead, by buying as the- * signed-in account.- */- email?: string;/** Put the period and capacity choices on one page rather than walking them separately. */combinedChoose?: boolean;/** Users the current plan covers. Its presence is what makes this "add capacity", not a first@@ -99,16 +95,12 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({// Lazy-loaded plans state (no fetch on mount)const [plans, setPlans] = useState<PlanTier[]>([]);const [plansLoaded, setPlansLoaded] = useState(false);- const [plansLoading, setPlansLoading] = useState(false);+ const openingCheckout = useRef(false);// Lazy fetch plans only when neededconst fetchPlansIfNeeded = useCallback(async (currency: string) => {- // Don't fetch if already loading- if (plansLoading) return;-try {- setPlansLoading(true);const response = await licenseService.getPlans(planFeatures,planHighlights,@@ -116,14 +108,14 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({);setPlans(response.plans);setPlansLoaded(true);+ return response.plans;} catch (error) {console.error("Failed to fetch plans:", error);- // Don't block - let components handle the error- } finally {- setPlansLoading(false);+ setPlansLoaded(false);+ return [];}},- [plansLoading, planFeatures, planHighlights],+ [planFeatures, planHighlights],);const refetchPlans = useCallback(() => {@@ -144,6 +136,26 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({// Clear URL parameterswindow.history.replaceState({}, "", window.location.pathname);+ if (urlParams.get("checkout_kind") === "team") {+ const result = await pollTeamCheckout(+ sessionId,+ Number(urlParams.get("team_quantity")) || 1,+ );+ await refetchLicense();+ refetchPlans();+ window.dispatchEvent(new Event("stirling:billing-updated"));+ alert({+ alertType: result.success ? "success" : "warning",+ title: result.success+ ? t("payment.teamActivated", "Your Team capacity is active")+ : t(+ "payment.teamPending",+ "Your Team purchase is still processing. Refresh this page shortly.",+ ),+ });+ return;+ }+// Fetch current license info to determine upgrade vs newlet licenseInfo: LicenseInfo | null = null;try {@@ -152,14 +164,18 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({console.warn("Could not fetch license info:", err);}+ // Always resync, whichever branch follows. A cloud Team purchase mints no licence key,+ // so the upgrade branch never runs for one and the new-subscription branch polls for a key+ // that will not arrive. This is what moves the tier in seconds: it drops the cached+ // entitlement and re-reads the linked team's plan, instead of leaving the purchase to be+ // noticed on the next daily sync.+ const activation = await resyncExistingLicense();+// Check if this is an upgrade or new subscription// Only treat as upgrade if there's a valid PRO/ENTERPRISE license (not NORMAL/free tier)if (licenseInfo?.licenseType && licenseInfo.licenseType !== "NORMAL") {- // UPGRADE: Resync existing license with Keygenconsole.log("Upgrade detected - resyncing existing license");- const activation = await resyncExistingLicense();-if (activation.success) {console.log("License synced successfully, refreshing license context",@@ -309,6 +325,8 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({const openCheckout = useCallback(async (tier: "server" | "enterprise", options: CheckoutOptions = {}) => {+ if (openingCheckout.current) return;+ openingCheckout.current = true;try {setIsLoading(true);@@ -326,22 +344,25 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({}// Fetch plans if not already loaded- if (!plansLoaded) {- await fetchPlansIfNeeded(currency);- }+ const availablePlans =+ !plansLoaded || currency !== currentCurrency+ ? await fetchPlansIfNeeded(currency)+ : plans;// Fetch license info and user data for seat calculationslet licenseInfo: LicenseInfo | null = null;let totalUsers = 0;try {- const [licenseData, userData] = await Promise.all([- licenseService.getLicenseInfo(),- userManagementService.getUsers(),- ]);-- licenseInfo = licenseData;- totalUsers = userData.totalUsers || 0;+ if (tier === "enterprise" && !options.minimumSeats) {+ const [licenseData, userData] = await Promise.all([+ licenseService.getLicenseInfo(),+ userManagementService.getUsers(),+ ]);++ licenseInfo = licenseData;+ totalUsers = userData.totalUsers || 0;+ }} catch (err) {console.warn("Could not fetch license/user info, proceeding with defaults:",@@ -373,7 +394,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({}// Find the plan group for the requested tier- const planGroups = licenseService.groupPlansByTier(plans);+ const planGroups = licenseService.groupPlansByTier(availablePlans);const planGroup = planGroups.find((pg) => pg.tier === tier);if (!planGroup) {@@ -389,8 +410,10 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({const errorMessage =err instanceof Error ? err.message : "Failed to open checkout";console.error("Error opening checkout:", errorMessage);+ alert({ alertType: "error", title: errorMessage });options.onError?.(errorMessage);} finally {+ openingCheckout.current = false;setIsLoading(false);}},@@ -457,7 +480,6 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({onClose={closeCheckout}planGroup={selectedPlanGroup}minimumSeats={minimumSeats}- initialEmail={currentOptions.email}combinedChoose={currentOptions.combinedChoose}currentLimit={currentOptions.currentLimit ?? null}onSuccess={handlePaymentSuccess}diff --git a/frontend/editor/src/proprietary/contexts/LicenseContext.tsx b/frontend/editor/src/proprietary/contexts/LicenseContext.tsxindex 50feea580a..9cef8f865c 100644--- a/frontend/editor/src/proprietary/contexts/LicenseContext.tsx+++ b/frontend/editor/src/proprietary/contexts/LicenseContext.tsx@@ -26,10 +26,13 @@ const LicenseContext = createContext<LicenseContextValue | undefined>(interface LicenseProviderProps {children: ReactNode;+ /** Hosted billing has no installation licence to read or refresh. */+ enabled?: boolean;}export const LicenseProvider: React.FC<LicenseProviderProps> = ({children,+ enabled = true,}) => {const { config } = useAppConfig();const location = useLocation();@@ -44,6 +47,12 @@ export const LicenseProvider: React.FC<LicenseProviderProps> = ({}, [config]);const refetchLicense = useCallback(async () => {+ if (!enabled) {+ setLicenseInfo(null);+ setError(null);+ setLoading(false);+ return;+ }// Wait for config to load if it's not available yetlet currentConfig = configRef.current;if (!currentConfig) {@@ -96,7 +105,7 @@ export const LicenseProvider: React.FC<LicenseProviderProps> = ({} finally {setLoading(false);}- }, []);+ }, [enabled]);// Fetch license info when config changes (only if user is admin)useEffect(() => {diff --git a/frontend/editor/src/proprietary/services/licenseService.ts b/frontend/editor/src/proprietary/services/licenseService.tsindex 63320ba6ba..c2c81ef51e 100644--- a/frontend/editor/src/proprietary/services/licenseService.ts+++ b/frontend/editor/src/proprietary/services/licenseService.ts@@ -1,6 +1,5 @@import apiClient from "@app/services/apiClient";import { supabase, isSupabaseConfigured } from "@app/services/supabaseClient";-import { getCheckoutMode } from "@app/utils/protocolDetection";import type {PlanFeaturesMap,PlanHighlightsMap,@@ -36,24 +35,6 @@ export interface PlansResponse {plans: PlanTier[];}-export interface CheckoutSessionRequest {- lookup_key: string; // Stripe lookup key (e.g., 'selfhosted:server:monthly')- installation_id?: string; // Installation ID from backend (MAC-based fingerprint)- current_license_key?: string; // Current license key for upgrades- requires_seats?: boolean; // Whether to add adjustable seat pricing- seat_count?: number; // Initial number of seats for enterprise plans (user can adjust in Stripe UI)- server_quantity?: number; // Blocks of users to buy; the Stripe line item counts these- email?: string; // Customer email for checkout pre-fill- successUrl?: string;- cancelUrl?: string;-}--export interface CheckoutSessionResponse {- clientSecret: string;- sessionId: string;- url?: string; // URL for hosted checkout (when not using HTTPS)-}-export interface BillingPortalResponse {url: string;}@@ -329,53 +310,6 @@ const licenseService = {return groups;},- /**- * Create a Stripe checkout session for upgrading- */- async createCheckoutSession(- request: CheckoutSessionRequest,- ): Promise<CheckoutSessionResponse> {- // Check if Supabase is configured- if (!isSupabaseConfigured || !supabase) {- throw new Error("Supabase is not configured. Checkout is not available.");- }-- // Detect if HTTPS is available to determine checkout mode- const checkoutMode = getCheckoutMode();- const baseUrl = window.location.origin;- const settingsUrl = `${baseUrl}/settings/adminPlan`;-- const { data, error } = await supabase.functions.invoke("create-checkout", {- body: {- self_hosted: true,- lookup_key: request.lookup_key,- installation_id: request.installation_id,- current_license_key: request.current_license_key,- requires_seats: request.requires_seats,- seat_count: request.seat_count || 1,- server_quantity: request.server_quantity || 1,- email: request.email,- callback_base_url: baseUrl,- ui_mode: checkoutMode,- // For hosted checkout, provide success/cancel URLs- success_url:- checkoutMode === "hosted"- ? `${settingsUrl}?session_id={CHECKOUT_SESSION_ID}&payment_status=success`- : undefined,- cancel_url:- checkoutMode === "hosted"- ? `${settingsUrl}?payment_status=canceled`- : undefined,- },- });-- if (error) {- throw new Error(`Failed to create checkout session: ${error.message}`);- }-- return data as CheckoutSessionResponse;- },-/*** Create a Stripe billing portal session for managing subscription* Uses license key for self-hosted authenticationdiff --git a/frontend/editor/src/proprietary/services/serverPlanCheckout.test.ts b/frontend/editor/src/proprietary/services/serverPlanCheckout.test.tsnew file mode 100644index 0000000000..1f53520db0--- /dev/null+++ b/frontend/editor/src/proprietary/services/serverPlanCheckout.test.ts@@ -0,0 +1,155 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++/**+ * What this pins is the lane the request lands on. `self_hosted` is what selects the Keygen+ * licence lane, and a client-supplied email is what lets it bill the wrong customer, so both+ * absences are the contract — not incidental.+ */+const { invoke, getAccessToken } = vi.hoisted(() => ({+ invoke: vi.fn(),+ getAccessToken: vi.fn(),+}));++vi.mock("@app/services/supabaseClient", () => ({+ isSupabaseConfigured: true,+ supabase: { functions: { invoke } },+}));++vi.mock("@app/auth/session", () => ({ getAccessToken }));++import {+ createServerPlanCheckoutSession,+ verifyTeamCheckout,+} from "@app/services/serverPlanCheckout";++const plan = {+ lookupKey: "selfhosted:server:yearly",+ serverQuantity: 2,+ installationId: "inst-1",+ uiMode: "embedded",+} as const;++beforeEach(() => {+ invoke.mockReset();+ getAccessToken.mockReset().mockResolvedValue("native-token");+});++describe("createServerPlanCheckoutSession", () => {+ it("preserves the server's subscription failure reason", async () => {+ invoke.mockResolvedValue({+ data: null,+ error: {+ message: "Edge Function returned a non-2xx status code",+ context: new Response(+ JSON.stringify({+ error: "Resolve the pending payment in Manage billing first.",+ }),+ { status: 400 },+ ),+ },+ });+ await expect(createServerPlanCheckoutSession(plan)).rejects.toThrow(+ "Resolve the pending payment in Manage billing first.",+ );+ });+ it("keeps Enterprise on the licence-issuing path", async () => {+ getAccessToken.mockResolvedValue(null);+ invoke.mockResolvedValue({+ data: { clientSecret: "cs", sessionId: "cs_enterprise" },+ error: null,+ });+ await createServerPlanCheckoutSession({+ ...plan,+ requiresSeats: true,+ currentLicenseKey: "key-1",+ });+ expect(invoke.mock.calls[0][1].body).toMatchObject({+ self_hosted: true,+ requires_seats: true,+ current_license_key: "key-1",+ });+ });+ it("buys as the signed-in account: no self_hosted lane, no client-supplied email", async () => {+ invoke.mockResolvedValue({+ data: { clientSecret: "cs_1", sessionId: "cs_sess" },+ error: null,+ });++ const session = await createServerPlanCheckoutSession(plan);++ expect(session).toEqual({+ clientSecret: "cs_1",+ url: null,+ sessionId: "cs_sess",+ });+ const [fn, options] = invoke.mock.calls[0];+ expect(fn).toBe("create-checkout");+ expect(options.body).not.toHaveProperty("self_hosted");+ expect(options.body).not.toHaveProperty("email");+ expect(options.body).toMatchObject({+ lookup_key: "selfhosted:server:yearly",+ server_quantity: 2,+ installation_id: "inst-1",+ ui_mode: "embedded",+ requires_seats: false,+ seat_count: 1,+ });+ });++ it("passes the hosted-mode return URLs through", async () => {+ invoke.mockResolvedValue({+ data: { url: "https://checkout.stripe.com/x", sessionId: "s" },+ error: null,+ });++ const session = await createServerPlanCheckoutSession({+ ...plan,+ uiMode: "hosted",+ successUrl: "https://host/ok",+ cancelUrl: "https://host/no",+ });++ expect(session.url).toBe("https://checkout.stripe.com/x");+ expect(session.clientSecret).toBeNull();+ expect(invoke.mock.calls[0][1].body).toMatchObject({+ success_url: "https://host/ok",+ cancel_url: "https://host/no",+ });+ });++ it("refuses before invoking when no Stirling account is signed in", async () => {+ getAccessToken.mockResolvedValue(null);++ await expect(createServerPlanCheckoutSession(plan)).rejects.toThrow(+ /Sign in to the Stirling account/,+ );+ expect(invoke).not.toHaveBeenCalled();+ });++ it("throws the edge function's own error", async () => {+ invoke.mockResolvedValue({ data: { error: "Unauthorized" }, error: null });++ await expect(createServerPlanCheckoutSession(plan)).rejects.toThrow(+ /Unauthorized/,+ );+ });++ it("throws when the session carries neither a secret nor a URL", async () => {+ invoke.mockResolvedValue({ data: { sessionId: "s" }, error: null });++ await expect(createServerPlanCheckoutSession(plan)).rejects.toThrow(+ /neither/,+ );+ });+});++it("attaches the platform token to checkout and completion without a browser session", async () => {+ invoke+ .mockResolvedValueOnce({ data: { clientSecret: "cs" } })+ .mockResolvedValueOnce({ data: { ready: true, licensedUsers: 300 } });+ await createServerPlanCheckoutSession(plan);+ expect(await verifyTeamCheckout("cs", 3)).toBe(300);+ for (const [, options] of invoke.mock.calls) {+ expect(options.headers).toEqual({ Authorization: "Bearer native-token" });+ }+});diff --git a/frontend/editor/src/proprietary/services/serverPlanCheckout.ts b/frontend/editor/src/proprietary/services/serverPlanCheckout.tsnew file mode 100644index 0000000000..255e973b01--- /dev/null+++ b/frontend/editor/src/proprietary/services/serverPlanCheckout.ts@@ -0,0 +1,133 @@+/** Account-owned Team checkout and the separate installed Enterprise licence checkout. */+import { supabase, isSupabaseConfigured } from "@app/services/supabaseClient";+import { getAccessToken } from "@app/auth/session";++/**+ * A Team-plan checkout, sized in user blocks rather than seats.+ *+ * {@link uiMode} follows the instance's own protocol: Stripe's embedded iframe needs a secure+ * context, so a plain-HTTP instance asks for `"hosted"` and supplies the two return URLs.+ */+export interface ServerPlanCheckoutRequest {+ /** Stripe price lookup key for the chosen period, e.g. `selfhosted:server:yearly`. */+ lookupKey: string;+ /** User blocks being bought. One block is the Team plan's user allowance. */+ serverQuantity: number;+ /** Adds the adjustable per-seat line Enterprise is priced on; Team leaves it off. */+ requiresSeats?: boolean;+ seatCount?: number;+ /** This instance's fingerprint, carried as Stripe metadata so a purchase can be traced to it. */+ installationId?: string;+ /** Installed licence being upgraded; Enterprise uses it to resolve the billing owner. */+ currentLicenseKey?: string;+ uiMode: "embedded" | "hosted";+ /** Required for hosted checkout and existing-subscription portal updates. */+ successUrl?: string;+ cancelUrl?: string;+}++/**+ * Result of {@link createServerPlanCheckoutSession}. `clientSecret` drives embedded Checkout;+ * `url` is Stripe's own page, returned for `uiMode: "hosted"`.+ */+export interface ServerPlanCheckoutSession {+ clientSecret: string | null;+ url: string | null;+ sessionId: string | null;+}++interface CheckoutResponse {+ clientSecret?: string | null;+ sessionId?: string | null;+ url?: string | null;+ error?: string;+}++/** Team requires a signed-in account; Enterprise uses the licence-issuing self-hosted flow. */+export async function createServerPlanCheckoutSession(+ request: ServerPlanCheckoutRequest,+): Promise<ServerPlanCheckoutSession> {+ if (!isSupabaseConfigured || !supabase) {+ throw new Error("Supabase is not configured. Checkout is not available.");+ }++ const token = await getAccessToken();+ if (!request.requiresSeats && !token) {+ throw new Error(+ "Sign in to the Stirling account you want to buy Team for, then try again.",+ );+ }++ const { data, error } = await supabase.functions.invoke<CheckoutResponse>(+ "create-checkout",+ {+ headers: token ? { Authorization: `Bearer ${token}` } : undefined,+ body: {+ lookup_key: request.lookupKey,+ server_quantity: request.serverQuantity,+ requires_seats: Boolean(request.requiresSeats),+ ...(request.requiresSeats ? { self_hosted: true } : {}),+ seat_count: request.seatCount ?? 1,+ ui_mode: request.uiMode,+ installation_id: request.installationId,+ current_license_key: request.currentLicenseKey,+ success_url: request.successUrl,+ cancel_url: request.cancelUrl,+ },+ },+ );++ if (error) {+ let message = error.message;+ if (error.context instanceof Response) {+ try {+ const details: unknown = await error.context.clone().json();+ if (+ details &&+ typeof details === "object" &&+ "error" in details &&+ typeof details.error === "string"+ ) {+ message = details.error;+ }+ } catch {+ // A gateway response may have no JSON body; keep the transport error.+ }+ }+ throw new Error(`Failed to create checkout session: ${message}`);+ }+ if (data?.error) {+ throw new Error(data.error);+ }+ const clientSecret = data?.clientSecret ?? null;+ const url = data?.url ?? null;+ if (!clientSecret && !url) {+ throw new Error("create-checkout returned neither clientSecret nor URL");+ }+ return { clientSecret, url, sessionId: data?.sessionId ?? null };+}++/** Returns confirmed purchased seats, or null while fulfilment is pending. */+export async function verifyTeamCheckout(+ sessionId: string,+ quantity: number,+): Promise<number | null> {+ if (!supabase) throw new Error("Checkout is not configured");+ const token = await getAccessToken();+ if (!token) throw new Error("Sign in to verify the Team purchase");+ const { data, error } = await supabase.functions.invoke<{+ ready: boolean;+ licensedUsers?: number;+ }>("complete-team-checkout", {+ headers: { Authorization: `Bearer ${token}` },+ body: { session_id: sessionId, quantity },+ });+ if (error) throw error;+ const users = data?.licensedUsers;+ return data?.ready &&+ typeof users === "number" &&+ Number.isInteger(users) &&+ users > 0+ ? users+ : null;+}diff --git a/frontend/editor/src/proprietary/services/teamPlanActivation.ts b/frontend/editor/src/proprietary/services/teamPlanActivation.tsnew file mode 100644index 0000000000..ebd884da49--- /dev/null+++ b/frontend/editor/src/proprietary/services/teamPlanActivation.ts@@ -0,0 +1,4 @@+/** Whether Team fulfilment must also refresh an independently licensed local server. */+export async function requiresLocalTeamActivation(): Promise<boolean> {+ return true;+}diff --git a/frontend/editor/src/proprietary/types/license.ts b/frontend/editor/src/proprietary/types/license.tsindex e2755646aa..6df72789cf 100644--- a/frontend/editor/src/proprietary/types/license.ts+++ b/frontend/editor/src/proprietary/types/license.ts@@ -7,6 +7,8 @@ export interface LicenseInfo {licenseType: "NORMAL" | "SERVER" | "ENTERPRISE";enabled: boolean;maxUsers: number;+ linkedTeamUsers?: number | null;+ maxAllowedUsers?: number;hasKey: boolean;licenseKey?: string;}diff --git a/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.ts b/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.tsindex cfa590d548..3be63d5828 100644--- a/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.ts+++ b/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.ts@@ -4,6 +4,49 @@*/import licenseService, { LicenseInfo } from "@app/services/licenseService";+import { verifyTeamCheckout } from "@app/services/serverPlanCheckout";+import { requiresLocalTeamActivation } from "@app/services/teamPlanActivation";++/** Waits for account capacity, then refreshes the linked server without requesting a licence key. */+export async function pollTeamCheckout(+ sessionId: string,+ quantity: number,+ config: PollConfig & { onActivated?: (info: LicenseInfo) => void } = {},+): Promise<LicenseActivationResult> {+ const delays = config.backoffMs ?? [0, 1000, 2000, 4000, 8000, 16000];+ config.onStatusChange?.("polling");+ for (const delay of delays) {+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));+ if (config.isMounted && !config.isMounted()) return { success: false };+ try {+ const purchasedUsers = await verifyTeamCheckout(sessionId, quantity);+ if (purchasedUsers != null) {+ if (!(await requiresLocalTeamActivation())) {+ config.onStatusChange?.("ready");+ return { success: true };+ }+ const result = await resyncExistingLicense({+ isMounted: config.isMounted,+ });+ if (+ result.success &&+ (result.licenseInfo?.linkedTeamUsers ?? 0) >= purchasedUsers &&+ (result.licenseInfo?.maxAllowedUsers ?? 0) >= purchasedUsers &&+ (result.licenseType === "SERVER" ||+ result.licenseType === "ENTERPRISE")+ ) {+ config.onActivated?.(result.licenseInfo!);+ config.onStatusChange?.("ready");+ return result;+ }+ }+ } catch {+ // A delayed webhook or transient transport error can recover on the next attempt.+ }+ }+ config.onStatusChange?.("timeout");+ return { success: false, error: "Team activation is still pending" };+}/*** Result of license key pollingdiff --git a/frontend/editor/src/proprietary/utils/teamCheckout.test.ts b/frontend/editor/src/proprietary/utils/teamCheckout.test.tsnew file mode 100644index 0000000000..3b4132be74--- /dev/null+++ b/frontend/editor/src/proprietary/utils/teamCheckout.test.ts@@ -0,0 +1,124 @@+import { beforeEach, expect, it, vi } from "vitest";+const { verify, resync, info, requiresLocal } = vi.hoisted(() => ({+ verify: vi.fn(),+ resync: vi.fn(),+ info: vi.fn(),+ requiresLocal: vi.fn(),+}));+vi.mock("@app/services/teamPlanActivation", () => ({+ requiresLocalTeamActivation: requiresLocal,+}));+vi.mock("@app/services/serverPlanCheckout", () => ({+ verifyTeamCheckout: verify,+}));+vi.mock("@app/services/licenseService", () => ({+ default: { resyncLicense: resync, getLicenseInfo: info },+}));+import { pollTeamCheckout } from "@app/utils/licenseCheckoutUtils";++beforeEach(() => {+ requiresLocal.mockReset().mockResolvedValue(true);+ verify.mockReset();+ resync+ .mockReset()+ .mockResolvedValue({ success: true, licenseType: "SERVER" });+ info.mockReset().mockResolvedValue({+ licenseType: "SERVER",+ hasKey: false,+ linkedTeamUsers: 200,+ maxAllowedUsers: 200,+ });+});++it("activates hosted Team capacity without calling the server administrator licence endpoint", async () => {+ requiresLocal.mockResolvedValue(false);+ verify.mockResolvedValue(200);+ expect(+ (await pollTeamCheckout("cs_team", 2, { backoffMs: [0] })).success,+ ).toBe(true);+ expect(resync).not.toHaveBeenCalled();+});++it("keeps waiting when the linked server has not received paid capacity", async () => {+ verify.mockResolvedValue(200);+ resync.mockResolvedValue({ success: true, licenseType: "NORMAL" });+ info.mockResolvedValue({ licenseType: "NORMAL", hasKey: false });+ expect(+ (await pollTeamCheckout("cs_team", 2, { backoffMs: [0] })).success,+ ).toBe(false);+});++it("waits for purchased capacity before refreshing the server and announcing activation", async () => {+ verify.mockResolvedValueOnce(null).mockResolvedValueOnce(200);+ const onActivated = vi.fn();+ const onStatusChange = vi.fn();+ const result = await pollTeamCheckout("cs_team", 2, {+ backoffMs: [0, 0],+ onActivated,+ onStatusChange,+ });+ expect(result.success).toBe(true);+ expect(verify).toHaveBeenCalledTimes(2);+ expect(resync).toHaveBeenCalledTimes(1);+ expect(onActivated).toHaveBeenCalledWith({+ licenseType: "SERVER",+ hasKey: false,+ linkedTeamUsers: 200,+ maxAllowedUsers: 200,+ });+ expect(onStatusChange.mock.calls.map(([status]) => status)).toEqual([+ "polling",+ "ready",+ ]);+});++it("does not announce activation when fulfilment is delayed", async () => {+ verify.mockResolvedValue(null);+ const result = await pollTeamCheckout("cs_team", 2, { backoffMs: [0, 0] });+ expect(result.success).toBe(false);+ expect(resync).not.toHaveBeenCalled();+});++it("retries a transient verification error", async () => {+ verify+ .mockRejectedValueOnce(new Error("temporary outage"))+ .mockResolvedValueOnce(200);+ expect(+ (await pollTeamCheckout("cs_team", 2, { backoffMs: [0, 0] })).success,+ ).toBe(true);+});++it("does not activate from an existing Server tier or a grandfathered seat limit", async () => {+ verify.mockResolvedValue(300);+ info.mockResolvedValue({+ licenseType: "SERVER",+ linkedTeamUsers: 100,+ maxAllowedUsers: 500,+ });+ const onActivated = vi.fn();+ expect(+ (await pollTeamCheckout("cs", 3, { backoffMs: [0], onActivated })).success,+ ).toBe(false);+ expect(onActivated).not.toHaveBeenCalled();+});++it("retries until the local purchased allowance catches up", async () => {+ verify.mockResolvedValue(300);+ info+ .mockResolvedValueOnce({+ licenseType: "SERVER",+ linkedTeamUsers: 100,+ maxAllowedUsers: 100,+ })+ .mockResolvedValueOnce({+ licenseType: "SERVER",+ linkedTeamUsers: 300,+ maxAllowedUsers: 300,+ });+ const onActivated = vi.fn();+ expect(+ (await pollTeamCheckout("cs", 3, { backoffMs: [0, 0], onActivated }))+ .success,+ ).toBe(true);+ expect(onActivated).toHaveBeenCalledTimes(1);+});diff --git a/frontend/editor/src/saas/contexts/LicenseContext.test.tsx b/frontend/editor/src/saas/contexts/LicenseContext.test.tsxnew file mode 100644index 0000000000..e2901f010a--- /dev/null+++ b/frontend/editor/src/saas/contexts/LicenseContext.test.tsx@@ -0,0 +1,30 @@+import { act, renderHook } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import { MemoryRouter } from "react-router-dom";+import type { ReactNode } from "react";+import { LicenseProvider, useLicense } from "@app/contexts/LicenseContext";++const getLicenseInfo = vi.hoisted(() => vi.fn());+vi.mock("@app/services/licenseService", () => ({+ default: { getLicenseInfo },+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config: { isAdmin: true } }),+}));+vi.mock("@app/testing/serverExperienceSimulations", () => ({+ getSimulatedLicenseInfo: () => null,+}));++it("does not read an installation licence on SaaS, including after checkout refresh", async () => {+ const { result } = renderHook(() => useLicense(), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <MemoryRouter>+ <LicenseProvider>{children}</LicenseProvider>+ </MemoryRouter>+ ),+ });+ await act(() => result.current.refetchLicense());+ expect(result.current.loading).toBe(false);+ expect(result.current.licenseInfo).toBeNull();+ expect(getLicenseInfo).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/saas/contexts/LicenseContext.tsx b/frontend/editor/src/saas/contexts/LicenseContext.tsxnew file mode 100644index 0000000000..46d13f6b6f--- /dev/null+++ b/frontend/editor/src/saas/contexts/LicenseContext.tsx@@ -0,0 +1,15 @@+import type { ReactNode } from "react";+import { LicenseProvider as InstalledLicenseProvider } from "@proprietary/contexts/LicenseContext";+export {+ useLicense,+ useOptionalLicense,+} from "@proprietary/contexts/LicenseContext";++/** SaaS checkout shares the context contract without accessing the host's installation licence. */+export function LicenseProvider({ children }: { children: ReactNode }) {+ return (+ <InstalledLicenseProvider enabled={false}>+ {children}+ </InstalledLicenseProvider>+ );+}diff --git a/frontend/editor/src/saas/services/teamPlanActivation.ts b/frontend/editor/src/saas/services/teamPlanActivation.tsnew file mode 100644index 0000000000..2763e4a8df--- /dev/null+++ b/frontend/editor/src/saas/services/teamPlanActivation.ts@@ -0,0 +1,4 @@+/** Hosted Team capacity is fulfilled in SaaS; members cannot resync the host's installation licence. */+export async function requiresLocalTeamActivation(): Promise<boolean> {+ return false;+}