Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Coordinate cloud and self-hosted ownership handovers (#8001)

ConnorYohf71331db3e1f
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
index 51c644caad..0d7bf3630e 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
@@ -62,15 +62,25 @@ public class AccountLinkClient {
/** A non-2xx reply from the SaaS account-link API. */
public static class UpstreamException extends IOException {
private final int status;
+ private final String reason;
public UpstreamException(int status, String body) {
+ this(status, body, null);
+ }
+
+ public UpstreamException(int status, String body, String reason) {
super("SaaS account-link returned HTTP " + status + ": " + body);
this.status = status;
+ this.reason = reason;
}
public int status() {
return status;
}
+
+ public String reason() {
+ return reason;
+ }
}
/** Authoritative deny (401/403) — the device credential is revoked or invalid. */
@@ -221,9 +231,71 @@ public class AccountLinkClient {
}
}
- /**
- * Revokes this instance's own credential on the SaaS side, authenticated by that credential.
- */
+ /** Status uses the device identity; invite and transfer additionally require a human bearer. */
+ public CloudOwnershipStatus ownership(
+ DeviceCredential credential, String email, String token, String action, Long leaderId)
+ throws IOException {
+ return ownership(credential, email, token, action, leaderId, null);
+ }
+
+ /** Pins the cloud recipient as well as the expected leader when a member has been selected. */
+ public CloudOwnershipStatus ownership(
+ DeviceCredential credential,
+ String email,
+ String token,
+ String action,
+ Long leaderId,
+ Long targetUserId)
+ throws IOException {
+ ObjectNode body = mapper.createObjectNode();
+ body.put("email", email);
+ if (leaderId != null) body.put("expectedLeaderId", leaderId);
+ if (targetUserId != null) body.put("expectedTargetId", targetUserId);
+ String path =
+ "status".equals(action)
+ ? "/api/v1/instance/ownership/status"
+ : "/api/v1/account-link/ownership/" + action;
+ HttpRequest.Builder request =
+ HttpRequest.newBuilder()
+ .uri(uri(path))
+ .header(HEADER_DEVICE_ID, credential.getDeviceId())
+ .header(HEADER_DEVICE_SECRET, credential.getDeviceSecret())
+ .header("Content-Type", "application/json")
+ .timeout(timeout())
+ .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body)));
+ if (token != null && !token.isBlank()) request.header("Authorization", token);
+ HttpResponse<String> response = send(request.build());
+ if (response.statusCode() / 100 != 2) {
+ String reason = null;
+ try {
+ reason = text(mapper.readTree(response.body()), "detail");
+ } catch (RuntimeException ignored) {
+ // An HTML gateway error has no structured ownership reason.
+ }
+ throw new UpstreamException(response.statusCode(), response.body(), reason);
+ }
+ return mapper.readValue(response.body(), CloudOwnershipStatus.class);
+ }
+
+ /** Reads only the linked team's eligible members; device credentials stay on the server. */
+ public CloudOwnershipCandidates ownershipCandidates(DeviceCredential credential)
+ throws IOException {
+ HttpRequest request =
+ HttpRequest.newBuilder()
+ .uri(uri("/api/v1/instance/ownership/members"))
+ .header(HEADER_DEVICE_ID, credential.getDeviceId())
+ .header(HEADER_DEVICE_SECRET, credential.getDeviceSecret())
+ .timeout(timeout())
+ .GET()
+ .build();
+ HttpResponse<String> response = send(request);
+ if (response.statusCode() / 100 != 2) {
+ throw new UpstreamException(response.statusCode(), response.body());
+ }
+ return mapper.readValue(response.body(), CloudOwnershipCandidates.class);
+ }
+
+ /** Revokes only the instance presenting this device credential. */
public boolean revokeSelf(String deviceId, String deviceSecret) {
try {
HttpRequest request =
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java
index 9383f945ba..6069377024 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
@@ -26,6 +26,7 @@ import lombok.extern.slf4j.Slf4j;
*
* <p>Owner-only class-wide except {@link #linked()}: everything else is server-scoped, the
* free-tier meter included. Other users learn of the wall from the {@code reason} on the 402.
+ * Linking and unlinking recheck ownership under the service's lock.
*/
@Slf4j
@Hidden
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.java
index c1f00cc54c..5b3c4789fd 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
@@ -4,10 +4,13 @@ import java.util.Optional;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Profile;
+import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.proprietary.service.OrgOwnerService;
+
/** Linking orchestrator (self-hosted side of combined billing). */
@Slf4j
@Service
@@ -21,14 +24,17 @@ public class AccountLinkService {
private final AccountLinkClient client;
private final DeviceCredentialStore credentialStore;
private final EntitlementCache entitlementCache;
+ private final OrgOwnerService owners;
public AccountLinkService(
AccountLinkClient client,
DeviceCredentialStore credentialStore,
- EntitlementCache entitlementCache) {
+ EntitlementCache entitlementCache,
+ OrgOwnerService owners) {
this.client = client;
this.credentialStore = credentialStore;
this.entitlementCache = entitlementCache;
+ this.owners = owners;
}
/** Status of this instance's link, for the portal's "Account link" card. */
@@ -47,7 +53,10 @@ public class AccountLinkService {
* Unlinks this instance — best-effort tells SaaS to revoke first (so the row gets {@code
* revoked_at} set), then clears locally regardless.
*/
+ @org.springframework.transaction.annotation.Transactional
public void unlink() {
+ owners.requireCurrentOwner(SecurityContextHolder.getContext().getAuthentication());
+ credentialStore.assertNoHandover();
credentialStore
.get()
.ifPresent(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/CloudOwnershipCandidates.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/CloudOwnershipCandidates.java
new file mode 100644
index 0000000000..5d4a23bc25
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/CloudOwnershipCandidates.java
@@ -0,0 +1,8 @@
+package stirling.software.proprietary.accountlink;
+
+import java.util.List;
+
+/** Eligible successors in the team authenticated by the server's device credential. */
+public record CloudOwnershipCandidates(Long teamId, String teamName, List<Member> members) {
+ public record Member(Long id, String name, String email) {}
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/CloudOwnershipStatus.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/CloudOwnershipStatus.java
new file mode 100644
index 0000000000..d885339214
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/CloudOwnershipStatus.java
@@ -0,0 +1,17 @@
+package stirling.software.proprietary.accountlink;
+
+/** Live team membership, scoped to the authenticated linked instance or SaaS team. */
+public record CloudOwnershipStatus(
+ Long teamId,
+ String teamName,
+ Long leaderUserId,
+ Long targetUserId,
+ long linkedInstances,
+ boolean subscribed,
+ State state) {
+ public enum State {
+ NEEDS_MEMBERSHIP,
+ READY,
+ TRANSFERRED
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java
index 8720a781e9..be72cc8497 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java
@@ -10,16 +10,22 @@ import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Locale;
+import java.util.Objects;
import java.util.Optional;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.server.ResponseStatusException;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.model.OrgOwner;
+import stirling.software.proprietary.service.OrgOwnerService;
/** Browser-mediated account linking, instance side. */
@Slf4j
@@ -41,6 +47,7 @@ public class ConnectService {
private final DeviceCredentialStore credentialStore;
private final EntitlementCache entitlementCache;
private final ApplicationProperties applicationProperties;
+ private final OrgOwnerService owners;
private final SecureRandom random = new SecureRandom();
public ConnectService(
@@ -48,12 +55,14 @@ public class ConnectService {
ConnectStateRepository stateRepo,
DeviceCredentialStore credentialStore,
EntitlementCache entitlementCache,
- ApplicationProperties applicationProperties) {
+ ApplicationProperties applicationProperties,
+ OrgOwnerService owners) {
this.client = client;
this.stateRepo = stateRepo;
this.credentialStore = credentialStore;
this.entitlementCache = entitlementCache;
this.applicationProperties = applicationProperties;
+ this.owners = owners;
}
public enum Phase {
@@ -88,10 +97,13 @@ public class ConnectService {
/** Opens a handshake and returns where to send the admin. */
@Transactional
public ConnectStatus start(String name, CallbackHint hint) throws IOException {
+ OrgOwner owner =
+ owners.requireCurrentOwner(SecurityContextHolder.getContext().getAuthentication());
+ credentialStore.assertNoHandover();
if (credentialStore.isLinked()) {
return status();
}
- return open(name, hint, null);
+ return open(name, hint, null, owner);
}
/**
@@ -108,10 +120,11 @@ public class ConnectService {
new IOException(
"This server is not linked, so there is no session"
+ " to re-establish"));
- return open(credential.getDeviceId(), hint, credential);
+ return open(credential.getDeviceId(), hint, credential, null);
}
- private ConnectStatus open(String name, CallbackHint hint, DeviceCredential credential)
+ private ConnectStatus open(
+ String name, CallbackHint hint, DeviceCredential credential, OrgOwner owner)
throws IOException {
String callbackUrl = resolveCallbackUrl(hint);
if (callbackUrl == null) {
@@ -137,6 +150,11 @@ public class ConnectService {
state.setCallbackUrl(callbackUrl);
state.setAuthorizeUrl(created.authorizeUrl());
state.setCreatedAt(now);
+ state.setReauth(credential != null);
+ if (owner != null) {
+ state.setOwnerUserId(owner.getOwnerUserId());
+ state.setOwnerAssignedAt(owner.getAssignedAt());
+ }
state.setExpiresAt(
now.plusSeconds(created.expiresInSeconds() > 0 ? created.expiresInSeconds() : 900));
stateRepo.save(state);
@@ -165,10 +183,23 @@ public class ConnectService {
return ConnectStatus.of(Phase.REJECTED);
}
+ boolean reauth = Boolean.TRUE.equals(state.getReauth());
+ if (!reauth) {
+ OrgOwner owner =
+ owners.requireCurrentOwner(
+ SecurityContextHolder.getContext().getAuthentication());
+ if (state.getOwnerUserId() == null
+ || !Objects.equals(state.getOwnerUserId(), owner.getOwnerUserId())
+ || !Objects.equals(state.getOwnerAssignedAt(), owner.getAssignedAt())) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "LINK_OWNER_CHANGED");
+ }
+ credentialStore.assertNoHandover();
+ }
AccountLinkClient.ConnectClaimResult claim =
client.connectClaim(state.getRequestId(), state.getClaimSecret());
return switch (claim.outcome()) {
case GRANTED -> {
+ if (reauth) yield ConnectStatus.of(Phase.REJECTED);
credentialStore.save(claim.deviceId(), claim.deviceSecret(), claim.teamId());
entitlementCache.invalidate();
stateRepo.delete(state);
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectState.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectState.java
index c0dcea032e..e18eb1985a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectState.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectState.java
@@ -54,6 +54,14 @@ public class ConnectState implements Serializable {
@Column(name = "expires_at", nullable = false)
private LocalDateTime expiresAt;
+ /** Null on older handshakes, which cannot establish a new link. */
+ private Long ownerUserId;
+
+ private LocalDateTime ownerAssignedAt;
+
+ /** Only session confirmation is accepted for a reauth handshake. */
+ private Boolean reauth;
+
public boolean isExpired(LocalDateTime now) {
return expiresAt != null && expiresAt.isBefore(now);
}
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.java
index ec0451769e..b1342d40ad 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
@@ -26,6 +26,9 @@ public class DeviceCredentialStore {
private final DeviceCredentialRepository repo;
+ @org.springframework.beans.factory.annotation.Autowired(required = false)
+ private stirling.software.proprietary.security.repository.OrgOwnerRepository owners;
+
public DeviceCredentialStore(DeviceCredentialRepository repo) {
this.repo = repo;
}
@@ -43,6 +46,7 @@ public class DeviceCredentialStore {
/** Persists (or replaces) the credential returned by a SaaS register call. */
@Transactional
public void save(String deviceId, String deviceSecret, Long teamId) {
+ assertNoHandover();
DeviceCredential cred = repo.findCredential().orElseGet(DeviceCredential::new);
cred.setId(DeviceCredential.SINGLETON_ID);
cred.setDeviceId(deviceId);
@@ -65,6 +69,24 @@ public class DeviceCredentialStore {
/** Unlinks this instance locally (idempotent). */
@Transactional
public void clear() {
+ assertNoHandover();
repo.findCredential().ifPresent(repo::delete);
}
+
+ /**
+ * Holds the ownership lock until the caller's transaction ends, including upstream revocation.
+ */
+ @Transactional
+ public void assertNoHandover() {
+ if (owners == null) return;
+ owners.lockOwner()
+ .ifPresent(
+ owner -> {
+ if (owner.getHandoverTargetId() != null) {
+ throw new org.springframework.web.server.ResponseStatusException(
+ org.springframework.http.HttpStatus.CONFLICT,
+ "Finish or cancel the ownership transfer before changing the account link.");
+ }
+ });
+ }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/LocalOwnershipHandoverController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/LocalOwnershipHandoverController.java
new file mode 100644
index 0000000000..63b5f4b593
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/LocalOwnershipHandoverController.java
@@ -0,0 +1,53 @@
+package stirling.software.proprietary.accountlink;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.*;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.service.OwnershipHandoverService;
+import stirling.software.proprietary.service.OwnershipHandoverService.Status;
+
+/** Only the local owner may prepare, resume or advance this server's ownership handover. */
+@RestController
+@Profile("!saas")
+@RequestMapping("/api/v1/ownership/handover")
+@PreAuthorize("hasRole('ADMIN')")
+@RequiredArgsConstructor
+public class LocalOwnershipHandoverController {
+ private final OwnershipHandoverService handovers;
+
+ @GetMapping
+ public Status current(Authentication auth) {
+ return handovers.current(auth);
+ }
+
+ @GetMapping("/members")
+ public CloudOwnershipCandidates members(Authentication auth) {
+ return handovers.members(auth);
+ }
+
+ @PostMapping("/{targetId}")
+ public Status prepare(
+ @PathVariable Long targetId,
+ @jakarta.validation.Valid @RequestBody(required = false)
+ OwnershipHandoverService.Selection selection,
+ Authentication auth) {
+ return handovers.prepare(targetId, selection, auth);
+ }
+
+ @PostMapping("/cloud/{action:invite|transfer}")
+ public Status cloud(
+ @PathVariable String action,
+ @RequestHeader(value = "X-SaaS-Authorization", required = false) String bearer,
+ Authentication auth) {
+ return handovers.changeCloud(auth, bearer, action);
+ }
+
+ @DeleteMapping
+ public void cancel(Authentication auth) {
+ handovers.cancel(auth);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/OrgOwner.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/OrgOwner.java
index e7341d2024..f2ae42a33a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/OrgOwner.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/OrgOwner.java
@@ -19,4 +19,12 @@ public class OrgOwner {
private String ownerUsername;
private LocalDateTime assignedAt;
private String assignedReason;
+ private Long handoverTargetId;
+ private String handoverTargetUsername;
+ private String handoverTargetEmail;
+ private String handoverCloudEmail;
+ private Long handoverCloudUserId;
+ private String handoverDeviceId;
+ private Long handoverTeamId;
+ private Long handoverLeaderId;
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/OrgOwnerService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/OrgOwnerService.java
index 982374a2fe..fa57a6eb05 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/OrgOwnerService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/OrgOwnerService.java
@@ -45,6 +45,9 @@ public class OrgOwnerService {
private final ObjectProvider<DatabaseServiceInterface> database;
private final ObjectProvider<AuditService> audit;
+ @org.springframework.beans.factory.annotation.Autowired(required = false)
+ private OwnershipHandoverService handovers;
+
private boolean saas() {
return environment.acceptsProfiles(Profiles.of("saas"));
}
@@ -64,9 +67,42 @@ public class OrgOwnerService {
public boolean isCurrentUser(Authentication authentication) {
if (saas() || authentication == null || !authentication.isAuthenticated()) return false;
- return users.findByUsernameIgnoreCase(authentication.getName())
- .filter(u -> isOwner(u.getId()))
- .isPresent();
+ return authenticatedUserId(authentication).filter(this::isOwner).isPresent();
+ }
+
+ /**
+ * Holds the ownership lock through the caller's mutation; stale admin sessions grant no
+ * ownership.
+ */
+ @Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY)
+ public OrgOwner requireCurrentOwner(Authentication authentication) {
+ OrgOwner row =
+ lockedOwner()
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.FORBIDDEN, "orgOwnerRequired"));
+ User owner =
+ validOwner(row)
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.FORBIDDEN, "orgOwnerRequired"));
+ if (saas()
+ || authentication == null
+ || !authentication.isAuthenticated()
+ || !authenticatedUserId(authentication).filter(owner.getId()::equals).isPresent()) {
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN, "orgOwnerRequired");
+ }
+ return row;
+ }
+
+ private Optional<Long> authenticatedUserId(Authentication authentication) {
+ if (authentication == null || !authentication.isAuthenticated()) return Optional.empty();
+ if (authentication.getPrincipal() instanceof User principal)
+ return Optional.ofNullable(principal.getId());
+ if (authentication.getName() == null) return Optional.empty();
+ return users.findByUsername(authentication.getName()).map(User::getId);
}
private Optional<OrgOwner> lockedOwner() {
@@ -242,6 +278,7 @@ public class OrgOwnerService {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST,
"Choose an enabled user who has completed first login.");
+ if (handovers != null) handovers.validateCompletion(row, targetId);
promote(target);
assign(row, target, "TRANSFER", authentication.getName());
}
@@ -264,6 +301,7 @@ public class OrgOwnerService {
row.setOwnerUsername(target.getUsername());
row.setAssignedAt(LocalDateTime.now());
row.setAssignedReason(reason);
+ OwnershipHandoverService.clear(row);
audit.getObject().audit(actor, AuditEventType.ORG_OWNERSHIP_CHANGE, data, AuditLevel.BASIC);
log.info("Organization owner is {} ({})", target.getUsername(), reason);
if (target.isFirstLogin())
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/OwnershipHandoverService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/OwnershipHandoverService.java
new file mode 100644
index 0000000000..43aacbc71b
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/OwnershipHandoverService.java
@@ -0,0 +1,407 @@
+package stirling.software.proprietary.service;
+
+import java.io.IOException;
+import java.util.Objects;
+
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.core.Authentication;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.server.ResponseStatusException;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.common.model.enumeration.Role;
+import stirling.software.proprietary.accountlink.*;
+import stirling.software.proprietary.model.OrgOwner;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.OrgOwnerRepository;
+
+/**
+ * Pins the local successor and server link until live cloud leadership permits local completion.
+ */
+@Service
+@Profile("!saas")
+@RequiredArgsConstructor
+public class OwnershipHandoverService {
+ private final OrgOwnerRepository owners;
+ private final UserRepository users;
+ private final DeviceCredentialRepository credentials;
+ private final ObjectProvider<AccountLinkClient> client;
+
+ public record Status(
+ Long targetId,
+ String targetName,
+ String targetEmail,
+ CloudOwnershipStatus cloud,
+ CloudOwnershipCandidates candidates,
+ String cloudEmail) {
+ public Status(
+ Long targetId, String targetName, String targetEmail, CloudOwnershipStatus cloud) {
+ this(targetId, targetName, targetEmail, cloud, null, targetEmail);
+ }
+ }
+
+ public record Selection(
+ Long cloudUserId, @jakarta.validation.constraints.Email String cloudEmail) {}
+
+ /** Persists one successor per owner; retries cannot replace the recipient or cloud team. */
+ @Transactional
+ public Status prepare(Long targetId, Authentication auth) {
+ return prepare(targetId, null, auth);
+ }
+
+ /**
+ * No intent is persisted for a linked server until the owner explicitly chooses a cloud
+ * account.
+ */
+ @Transactional
+ public Status prepare(Long targetId, Selection selection, Authentication auth) {
+ OrgOwner owner = requireOwner(auth);
+ if (owner.getHandoverTargetId() != null
+ && !Objects.equals(owner.getHandoverTargetId(), targetId)) {
+ throw conflict("HANDOVER_IN_PROGRESS");
+ }
+ User target = target(targetId);
+ if (Objects.equals(targetId, owner.getOwnerUserId())) throw conflict("CHOOSE_ANOTHER_USER");
+ if (owner.getHandoverTargetId() == null) {
+ var credential = credentials.findCredential();
+ String cloudEmail = null;
+ Long cloudUserId = null;
+ CloudOwnershipStatus cloud = null;
+ if (credential.isPresent()) {
+ CloudOwnershipCandidates candidates = candidates(credential.get());
+ if (!Objects.equals(candidates.teamId(), credential.get().getTeamId()))
+ throw conflict("LINK_CHANGED");
+ if (selection == null
+ || (selection.cloudUserId() == null
+ && (selection.cloudEmail() == null
+ || selection.cloudEmail().isBlank()))) {
+ return new Status(
+ targetId,
+ target.getUsername(),
+ target.getEmail(),
+ null,
+ candidates,
+ null);
+ }
+ if (selection.cloudUserId() != null) {
+ var member =
+ candidates.members().stream()
+ .filter(m -> Objects.equals(m.id(), selection.cloudUserId()))
+ .findFirst()
+ .orElseThrow(() -> conflict("CLOUD_TARGET_CHANGED"));
+ cloudEmail = member.email();
+ cloudUserId = member.id();
+ } else {
+ cloudEmail = selection.cloudEmail().strip().toLowerCase(java.util.Locale.ROOT);
+ if (!cloudEmail.matches("[^\\s@]+@[^\\s@]+\\.[^\\s@]+"))
+ throw conflict("CLOUD_EMAIL_REQUIRED");
+ }
+ cloud = remote(credential.get(), cloudEmail, null, "status", null, cloudUserId);
+ if (!Objects.equals(cloud.teamId(), credential.get().getTeamId()))
+ throw conflict("LINK_CHANGED");
+ if (cloud.state() == CloudOwnershipStatus.State.TRANSFERRED)
+ throw conflict("CHOOSE_ANOTHER_CLOUD_USER");
+ cloudUserId = cloud.targetUserId();
+ }
+ owner.setHandoverTargetId(targetId);
+ owner.setHandoverTargetUsername(target.getUsername());
+ owner.setHandoverTargetEmail(target.getEmail());
+ owner.setHandoverCloudEmail(cloudEmail);
+ owner.setHandoverCloudUserId(cloudUserId);
+ if (credential.isPresent()) {
+ owner.setHandoverDeviceId(credential.get().getDeviceId());
+ owner.setHandoverTeamId(credential.get().getTeamId());
+ verifyTeam(owner, cloud);
+ owner.setHandoverLeaderId(cloud.leaderUserId());
+ }
+ } else if (selection != null
+ && ((selection.cloudUserId() != null
+ && !Objects.equals(
+ selection.cloudUserId(), owner.getHandoverCloudUserId()))
+ || (selection.cloudEmail() != null
+ && !selection.cloudEmail().equalsIgnoreCase(cloudEmail(owner))))) {
+ throw conflict("HANDOVER_IN_PROGRESS");
+ }
+ return status(owner);
+ }
+
+ /** Returns the durable intent without contacting SaaS, including during an upstream outage. */
+ @Transactional
+ public Status current(Authentication auth) {
+ OrgOwner owner = requireOwner(auth);
+ return owner.getHandoverTargetId() == null
+ ? null
+ : new Status(
+ owner.getHandoverTargetId(),
+ owner.getHandoverTargetUsername(),
+ owner.getHandoverTargetEmail(),
+ null,
+ null,
+ cloudEmail(owner));
+ }
+
+ /** Reading alternative cloud accounts never cancels or replaces a saved handover. */
+ @Transactional
+ public CloudOwnershipCandidates members(Authentication auth) {
+ OrgOwner owner = requireOwner(auth);
+ DeviceCredential credential =
+ owner.getHandoverTargetId() == null
+ ? credentials.findCredential().orElseThrow(() -> conflict("NOT_LINKED"))
+ : credential(owner);
+ if (credential == null) throw conflict("NOT_LINKED");
+ return candidates(credential);
+ }
+
+ /**
+ * The bearer is forwarded for this request only; SaaS must authorize its current team owner.
+ */
+ @Transactional
+ public Status changeCloud(Authentication auth, String bearer, String action) {
+ OrgOwner owner = requireOwner(auth);
+ Status current = status(owner);
+ if (current.cloud() == null) throw conflict("NOT_LINKED");
+ if (current.cloud().state() == CloudOwnershipStatus.State.TRANSFERRED) return current;
+ if (bearer == null || !bearer.startsWith("Bearer ")) {
+ throw conflict("CLOUD_SIGN_IN_REQUIRED");
+ }
+ remote(
+ credential(owner),
+ cloudEmail(owner),
+ bearer,
+ action,
+ owner.getHandoverLeaderId(),
+ owner.getHandoverCloudUserId());
+ return status(owner);
+ }
+
+ /**
+ * Cancellation preserves a completed cloud transfer or an unknown outcome. An authoritative
+ * denial of the pinned device link permits abandoning the now-disconnected handover.
+ */
+ @Transactional
+ public void cancel(Authentication auth) {
+ OrgOwner owner = requireOwner(auth);
+ if (owner.getHandoverTargetId() == null) return;
+ DeviceCredential credential = credential(owner);
+ CloudOwnershipStatus cloud;
+ try {
+ cloud =
+ credential == null
+ ? null
+ : remote(credential, cloudEmail(owner), null, "status", null, null);
+ } catch (ResponseStatusException e) {
+ if (!"LINK_REVOKED".equals(e.getReason())) throw e;
+ clear(owner);
+ return;
+ }
+ if (cloud != null
+ && (owner.getHandoverCloudUserId() == null
+ ? cloud.state() == CloudOwnershipStatus.State.TRANSFERRED
+ : Objects.equals(owner.getHandoverCloudUserId(), cloud.leaderUserId()))) {
+ throw conflict("FINISH_LOCAL_TRANSFER");
+ }
+ clear(owner);
+ }
+
+ /**
+ * Also called by the original transfer endpoint, so bypassing the wizard cannot skip cloud
+ * ownership.
+ */
+ public void validateCompletion(OrgOwner owner, Long targetId) {
+ boolean linked = credentials.findCredential().isPresent();
+ if (linked) requireClient();
+ if (!linked && owner.getHandoverTargetId() == null) return;
+ if (!Objects.equals(owner.getHandoverTargetId(), targetId))
+ throw conflict("PREPARE_HANDOVER_FIRST");
+ Status state = status(owner);
+ if (state.cloud() != null
+ && state.cloud().state() != CloudOwnershipStatus.State.TRANSFERRED) {
+ throw conflict("CLOUD_TRANSFER_REQUIRED");
+ }
+ }
+
+ /**
+ * Clears only the local handover record; licenses, credentials and cloud membership are
+ * untouched.
+ */
+ public static void clear(OrgOwner owner) {
+ owner.setHandoverTargetId(null);
+ owner.setHandoverTargetUsername(null);
+ owner.setHandoverTargetEmail(null);
+ owner.setHandoverCloudEmail(null);
+ owner.setHandoverCloudUserId(null);
+ owner.setHandoverDeviceId(null);
+ owner.setHandoverTeamId(null);
+ owner.setHandoverLeaderId(null);
+ }
+
+ private Status status(OrgOwner owner) {
+ User target = target(owner.getHandoverTargetId());
+ if (!Objects.equals(owner.getHandoverTargetUsername(), target.getUsername())
+ || !Objects.equals(owner.getHandoverTargetEmail(), target.getEmail())) {
+ throw conflict("TARGET_CHANGED");
+ }
+ DeviceCredential credential = credential(owner);
+ CloudOwnershipStatus cloud =
+ credential == null
+ ? null
+ : remote(
+ credential,
+ cloudEmail(owner),
+ null,
+ "status",
+ null,
+ owner.getHandoverCloudUserId());
+ if (cloud != null) {
+ verifyTeam(owner, cloud);
+ if (owner.getHandoverCloudUserId() == null && cloud.targetUserId() != null) {
+ owner.setHandoverCloudUserId(cloud.targetUserId());
+ }
+ }
+ return new Status(
+ target.getId(),
+ target.getUsername(),
+ target.getEmail(),
+ cloud,
+ null,
+ cloudEmail(owner));
+ }
+
+ private String cloudEmail(OrgOwner owner) {
+ return owner.getHandoverCloudEmail() != null
+ ? owner.getHandoverCloudEmail()
+ : owner.getHandoverTargetEmail();
+ }
+
+ private CloudOwnershipCandidates candidates(DeviceCredential credential) {
+ AccountLinkClient upstream = requireClient();
+ try {
+ return upstream.ownershipCandidates(credential);
+ } catch (IOException e) {
+ throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "CLOUD_UNAVAILABLE");
+ }
+ }
+
+ private DeviceCredential credential(OrgOwner owner) {
+ DeviceCredential credential = credentials.findCredential().orElse(null);
+ if (!Objects.equals(
+ owner.getHandoverDeviceId(),
+ credential == null ? null : credential.getDeviceId())
+ || !Objects.equals(
+ owner.getHandoverTeamId(),
+ credential == null ? null : credential.getTeamId())) {
+ throw conflict("LINK_CHANGED");
+ }
+ return credential;
+ }
+
+ private void verifyTeam(OrgOwner owner, CloudOwnershipStatus cloud) {
+ if (!Objects.equals(owner.getHandoverTeamId(), cloud.teamId()))
+ throw conflict("LINK_CHANGED");
+ }
+
+ private OrgOwner requireOwner(Authentication auth) {
+ OrgOwner owner = owners.lockOwner().orElseThrow(() -> conflict("OWNER_UNAVAILABLE"));
+ if (auth == null || !auth.isAuthenticated() || auth.getName() == null) {
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN, "ORG_OWNER_REQUIRED");
+ }
+ Long authenticatedId =
+ auth.getPrincipal() instanceof User principal
+ ? principal.getId()
+ : users.findByUsername(auth.getName()).map(User::getId).orElse(null);
+ if (authenticatedId == null || !Objects.equals(authenticatedId, owner.getOwnerUserId())) {
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN, "ORG_OWNER_REQUIRED");
+ }
+ users.findById(authenticatedId)
+ .filter(
+ u ->
+ u.isEnabled()
+ && !u.isFirstLogin()
+ && u.getAuthorities().stream()
+ .anyMatch(
+ a ->
+ Role.ADMIN
+ .getRoleId()
+ .equals(a.getAuthority())))
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.FORBIDDEN, "ORG_OWNER_REQUIRED"));
+ return owner;
+ }
+
+ private User target(Long id) {
+ if (id == null) throw conflict("PREPARE_HANDOVER_FIRST");
+ return users.findById(id)
+ .filter(
+ u ->
+ u.isEnabled()
+ && !u.isFirstLogin()
+ && u.getAuthorities().stream()
+ .noneMatch(
+ a ->
+ Role.INTERNAL_API_USER
+ .getRoleId()
+ .equals(a.getAuthority())))
+ .orElseThrow(() -> conflict("TARGET_UNAVAILABLE"));
+ }
+
+ private CloudOwnershipStatus remote(
+ DeviceCredential credential,
+ String email,
+ String bearer,
+ String action,
+ Long leader,
+ Long targetUserId) {
+ if (email == null || email.isBlank()) throw conflict("EMAIL_REQUIRED");
+ AccountLinkClient upstream = requireClient();
+ try {
+ CloudOwnershipStatus status =
+ upstream.ownership(credential, email, bearer, action, leader, targetUserId);
+ if (targetUserId != null && !Objects.equals(targetUserId, status.targetUserId()))
+ throw conflict("CLOUD_TARGET_CHANGED");
+ return status;
+ } catch (AccountLinkClient.UpstreamException e) {
+ String reason =
+ switch (e.status()) {
+ case 401 ->
+ "status".equals(action) ? "LINK_REVOKED" : "CLOUD_SIGN_IN_REQUIRED";
+ case 403 ->
+ "status".equals(action) ? "LINK_REVOKED" : "CLOUD_OWNER_REQUIRED";
+ case 404 ->
+ "status".equals(action) && "CLOUD_TEAM_MISSING".equals(e.reason())
+ ? "LINK_REVOKED"
+ : "CLOUD_UNAVAILABLE";
+ case 400 ->
+ "PERSONAL_TEAM".equals(e.reason())
+ ? "PERSONAL_TEAM"
+ : "INVITATION_BLOCKED";
+ case 409 ->
+ switch (String.valueOf(e.reason())) {
+ case "CLOUD_TARGET_CHANGED", "MEMBERSHIP_REQUIRED" ->
+ e.reason();
+ default -> "CLOUD_OWNER_CHANGED";
+ };
+ default -> "CLOUD_UNAVAILABLE";
+ };
+ throw new ResponseStatusException(HttpStatus.CONFLICT, reason);
+ } catch (IOException e) {
+ throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "CLOUD_UNAVAILABLE");
+ }
+ }
+
+ private AccountLinkClient requireClient() {
+ AccountLinkClient upstream = client.getIfAvailable();
+ if (upstream == null) throw conflict("ACCOUNT_LINK_DISABLED");
+ return upstream;
+ }
+
+ private ResponseStatusException conflict(String reason) {
+ return new ResponseStatusException(HttpStatus.CONFLICT, reason);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
index 06d03f9546..cf5a5e2819 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
@@ -51,8 +51,125 @@ class AccountLinkClientTest {
return resp;
}
- // register() is gone with the JWT relay, and with it the two tests that asserted this client
- // sends an Authorization: Bearer header. Nothing here carries a user token any more.
+ @Test
+ @SuppressWarnings("unchecked")
+ void candidateReadUsesOnlyDeviceCredentials() throws Exception {
+ var requests = ArgumentCaptor.forClass(HttpRequest.class);
+ var reply =
+ response(
+ 200,
+ "{\"teamId\":9,\"teamName\":\"Team\",\"members\":[{\"id\":42,\"name\":\"Jamie\",\"email\":\"[email protected]\"}]}");
+ when(httpClient.send(requests.capture(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(reply);
+ DeviceCredential device = new DeviceCredential();
+ device.setDeviceId("device");
+ device.setDeviceSecret("secret");
+ var result = client.ownershipCandidates(device);
+ assertEquals(42L, result.members().getFirst().id());
+ assertEquals("[email protected]", result.members().getFirst().email());
+ var request = requests.getValue();
+ assertEquals("GET", request.method());
+ assertEquals("/api/v1/instance/ownership/members", request.uri().getPath());
+ assertEquals("secret", request.headers().firstValue("X-Device-Secret").orElseThrow());
+ assertEquals(java.util.Optional.empty(), request.headers().firstValue("Authorization"));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void pinnedIdentityIsSentAndStructuredTargetFailureIsPreserved() throws Exception {
+ var requests = ArgumentCaptor.forClass(HttpRequest.class);
+ var reply = response(409, "{\"detail\":\"CLOUD_TARGET_CHANGED\"}");
+ when(httpClient.send(requests.capture(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(reply);
+ DeviceCredential device = new DeviceCredential();
+ device.setDeviceId("device");
+ device.setDeviceSecret("secret");
+ var error =
+ assertThrows(
+ AccountLinkClient.UpstreamException.class,
+ () ->
+ client.ownership(
+ device,
+ "Bearer owner",
+ "transfer",
+ 1L,
+ 42L));
+ assertEquals("CLOUD_TARGET_CHANGED", error.reason());
+ var body = HttpResponse.BodySubscribers.ofString(java.nio.charset.StandardCharsets.UTF_8);
+ requests.getValue()
+ .bodyPublisher()
+ .orElseThrow()
+ .subscribe(
+ new java.util.concurrent.Flow.Subscriber<java.nio.ByteBuffer>() {
+ public void onSubscribe(
+ java.util.concurrent.Flow.Subscription subscription) {
+ body.onSubscribe(subscription);
+ }
+
+ public void onNext(java.nio.ByteBuffer item) {
+ body.onNext(java.util.List.of(item));
+ }
+
+ public void onError(Throwable error) {
+ body.onError(error);
+ }
+
+ public void onComplete() {
+ body.onComplete();
+ }
+ });
+ var json = new ObjectMapper().readTree(body.getBody().toCompletableFuture().join());
+ assertEquals(42L, json.path("expectedTargetId").asLong());
+ assertEquals(1L, json.path("expectedLeaderId").asLong());
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void ownershipReadsUseDeviceIdentityAndMutationsAlsoCarryHumanAuthorization() throws Exception {
+ HttpResponse<String> resp =
+ response(
+ 200,
+ "{\"teamId\":9,\"teamName\":\"Team\",\"leaderUserId\":1,\"targetUserId\":2,\"linkedInstances\":3,\"subscribed\":true,\"state\":\"READY\"}");
+ ArgumentCaptor<HttpRequest> requests = ArgumentCaptor.forClass(HttpRequest.class);
+ when(httpClient.send(requests.capture(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(resp);
+ DeviceCredential device = new DeviceCredential();
+ device.setDeviceId("device");
+ device.setDeviceSecret("secret");
+ device.setTeamId(9L);
+ assertEquals(
+ CloudOwnershipStatus.State.READY,
+ client.ownership(device, "[email protected]", null, "status", null).state());
+ assertEquals("/api/v1/instance/ownership/status", requests.getValue().uri().getPath());
+ assertEquals(
+ java.util.Optional.empty(),
+ requests.getValue().headers().firstValue("Authorization"));
+ client.ownership(device, "[email protected]", "Bearer human", "transfer", 1L);
+ HttpRequest transfer = requests.getValue();
+ assertEquals("/api/v1/account-link/ownership/transfer", transfer.uri().getPath());
+ assertEquals("Bearer human", transfer.headers().firstValue("Authorization").orElseThrow());
+ assertEquals("device", transfer.headers().firstValue("X-Device-Id").orElseThrow());
+ assertEquals("secret", transfer.headers().firstValue("X-Device-Secret").orElseThrow());
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void ownershipRejectsUpstreamFailureInsteadOfAssumingSuccess() throws Exception {
+ HttpResponse<String> resp = response(503, "unavailable");
+ when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(resp);
+ DeviceCredential device = new DeviceCredential();
+ device.setDeviceId("device");
+ device.setDeviceSecret("secret");
+ assertEquals(
+ 503,
+ assertThrows(
+ AccountLinkClient.UpstreamException.class,
+ () ->
+ client.ownership(
+ device, "[email protected]", null, "status", null))
+ .status());
+ }
@Test
@SuppressWarnings("unchecked")
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.java
index b396712daa..e9e945e0c2 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
@@ -14,6 +14,8 @@ import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import stirling.software.proprietary.service.OrgOwnerService;
+
class AccountLinkServiceTest {
private AccountLinkClient client;
@@ -26,7 +28,7 @@ class AccountLinkServiceTest {
client = mock(AccountLinkClient.class);
store = mock(DeviceCredentialStore.class);
cache = mock(EntitlementCache.class);
- service = new AccountLinkService(client, store, cache);
+ service = new AccountLinkService(client, store, cache, mock(OrgOwnerService.class));
}
// The two link() tests here are gone with the JWT relay. Storing a credential and invalidating
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.java
index 30ce1d5884..ac4365844f 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/ConnectServiceTest.java
@@ -27,6 +27,8 @@ import stirling.software.proprietary.accountlink.AccountLinkClient.ConnectClaimO
import stirling.software.proprietary.accountlink.AccountLinkClient.ConnectClaimResult;
import stirling.software.proprietary.accountlink.AccountLinkClient.ConnectRequestResult;
import stirling.software.proprietary.accountlink.ConnectService.Phase;
+import stirling.software.proprietary.model.OrgOwner;
+import stirling.software.proprietary.service.OrgOwnerService;
/** Unit tests for the instance half of the connect handshake. */
@ExtendWith(MockitoExtension.class)
@@ -41,6 +43,7 @@ class ConnectServiceTest {
@Mock private ConnectStateRepository stateRepo;
@Mock private DeviceCredentialStore credentialStore;
@Mock private EntitlementCache entitlementCache;
+ @Mock private OrgOwnerService owners;
private ApplicationProperties applicationProperties;
private ConnectService service;
@@ -48,13 +51,18 @@ class ConnectServiceTest {
@BeforeEach
void setUp() {
applicationProperties = new ApplicationProperties();
+ OrgOwner owner = new OrgOwner();
+ owner.setOwnerUserId(1L);
+ owner.setAssignedAt(LocalDateTime.of(2026, 9, 1, 0, 0));
+ when(owners.requireCurrentOwner(any())).thenReturn(owner);
service =
new ConnectService(
client,
stateRepo,
credentialStore,
entitlementCache,
- applicationProperties);
+ applicationProperties,
+ owners);
}
private void configureFrontendUrl(String url) {
@@ -357,7 +365,7 @@ class ConnectServiceTest {
assertThat(service.complete(NONCE).phase()).isEqualTo(Phase.UNAVAILABLE);
verify(stateRepo, never()).delete(any());
- verifyNoInteractions(credentialStore);
+ verify(credentialStore, never()).save(anyString(), anyString(), any());
}
@Test
@@ -369,7 +377,7 @@ class ConnectServiceTest {
assertThat(service.complete(NONCE).phase()).isEqualTo(Phase.REJECTED);
verify(stateRepo).delete(state);
- verifyNoInteractions(credentialStore);
+ verify(credentialStore, never()).save(anyString(), anyString(), any());
}
@Test
@@ -413,6 +421,7 @@ class ConnectServiceTest {
@Test
void complete_onAConfirmedReauthKeepsTheExistingCredential() {
ConnectState state = openHandshake();
+ state.setReauth(true);
when(stateRepo.findById(ConnectState.SINGLETON_ID)).thenReturn(Optional.of(state));
when(client.connectClaim(anyString(), anyString()))
.thenReturn(new ConnectClaimResult(ConnectClaimOutcome.CONFIRMED, null, null, 7L));
@@ -424,6 +433,18 @@ class ConnectServiceTest {
// Nothing to store: a second credential would orphan the one we already hold.
verify(credentialStore, never()).save(anyString(), anyString(), any());
verify(stateRepo).delete(state);
+ verifyNoInteractions(owners);
+ }
+
+ @Test
+ void reauthCannotStoreANewCredentialEvenIfUpstreamGrantsOne() {
+ ConnectState state = openHandshake();
+ state.setReauth(true);
+ when(stateRepo.findById(ConnectState.SINGLETON_ID)).thenReturn(Optional.of(state));
+ when(client.connectClaim(anyString(), anyString()))
+ .thenReturn(new ConnectClaimResult(ConnectClaimOutcome.GRANTED, "dev", "sec", 7L));
+ assertThat(service.complete(NONCE).phase()).isEqualTo(Phase.REJECTED);
+ verifyNoInteractions(owners, credentialStore);
}
@Test
@@ -476,6 +497,8 @@ class ConnectServiceTest {
state.setAuthorizeUrl("https://app.example.com/link?request=req-1");
state.setCreatedAt(LocalDateTime.now());
state.setExpiresAt(LocalDateTime.now().plusMinutes(10));
+ state.setOwnerUserId(1L);
+ state.setOwnerAssignedAt(LocalDateTime.of(2026, 9, 1, 0, 0));
return state;
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
index df7039ff57..949c1ccbb8 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
@@ -1021,10 +1021,12 @@ class ProcessingFolderControllerTest {
@Test
void cancelStopsTheFoldersRuns() {
+ // Saving starts a background sweep on this mock; finish stubbing before it runs.
+ when(policyRunner.cancelRuns(anyString())).thenReturn(3);
var view = controller.save(request(null, "new_version")).getBody();
- when(policyRunner.cancelRuns(view.id())).thenReturn(3);
assertThat(controller.cancelRuns(view.id()).cancelled()).isEqualTo(3);
+ verify(policyRunner).cancelRuns(view.id());
}
/** A stored file double with just what the listing reads. */
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/OrgOwnerServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/OrgOwnerServiceTest.java
index 001df6f3f3..69c5a0d661 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/OrgOwnerServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/OrgOwnerServiceTest.java
@@ -1,7 +1,7 @@
package stirling.software.proprietary.service;
import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.*;
import java.util.*;
import java.util.concurrent.*;
@@ -21,22 +21,36 @@ import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.server.ResponseStatusException;
import stirling.software.common.model.enumeration.Role;
+import stirling.software.proprietary.accountlink.*;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.*;
import stirling.software.proprietary.security.repository.OrgOwnerRepository;
import stirling.software.proprietary.security.service.DatabaseServiceInterface;
@DataJpaTest(properties = "spring.jpa.show-sql=false")
-@Import(OrgOwnerService.class)
+@Import({
+ OrgOwnerService.class,
+ OwnershipHandoverService.class,
+ ConnectService.class,
+ AccountLinkService.class,
+ DeviceCredentialStore.class
+})
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class OrgOwnerServiceTest {
@Autowired OrgOwnerService owners;
@Autowired OrgOwnerRepository ownerRepository;
@Autowired UserRepository users;
@Autowired PlatformTransactionManager transactions;
+ @Autowired OwnershipHandoverService handovers;
+ @Autowired DeviceCredentialRepository credentials;
+ @Autowired AccountLinkClient cloud;
+ @Autowired ConnectService connect;
+ @Autowired AccountLinkService accountLink;
+ @Autowired ConnectStateRepository connectStates;
@BeforeEach
void clear() {
+ reset(credentials, cloud, connectStates);
new TransactionTemplate(transactions)
.executeWithoutResult(
s -> {
@@ -195,6 +209,229 @@ class OrgOwnerServiceTest {
assertEquals(Optional.of(target.getId()), owners.ownerId());
}
+ @Test
+ void linkedHandoverPersistsAndOriginalEndpointEnforcesCloudFirst() throws Exception {
+ User first = user("first", Role.ADMIN.getRoleId(), false, true);
+ User second = user("second", Role.USER.getRoleId(), false, true);
+ second.setEmail("[email protected]");
+ users.saveAndFlush(second);
+ owners.resolveOwner();
+ DeviceCredential device = new DeviceCredential();
+ device.setDeviceId("device");
+ device.setTeamId(9L);
+ when(credentials.findCredential()).thenReturn(Optional.of(device));
+ when(cloud.ownershipCandidates(device))
+ .thenReturn(
+ new stirling.software.proprietary.accountlink.CloudOwnershipCandidates(
+ 9L,
+ "Cloud team",
+ java.util.List.of(
+ new stirling.software.proprietary.accountlink
+ .CloudOwnershipCandidates.Member(
+ 20L,
+ "Second cloud account",
+ when(cloud.ownership(
+ any(),
+ isNull(),
+ eq("status"),
+ isNull(),
+ nullable(Long.class)))
+ .thenReturn(
+ new CloudOwnershipStatus(
+ 9L,
+ "Cloud team",
+ 10L,
+ 20L,
+ 2L,
+ true,
+ CloudOwnershipStatus.State.READY));
+ assertThrows(
+ ResponseStatusException.class, () -> owners.transfer(second.getId(), auth(first)));
+ handovers.prepare(
+ second.getId(), new OwnershipHandoverService.Selection(20L, null), auth(first));
+ assertEquals(
+ second.getId(), ownerRepository.findById(1L).orElseThrow().getHandoverTargetId());
+ assertEquals(20L, ownerRepository.findById(1L).orElseThrow().getHandoverCloudUserId());
+ assertEquals(
+ ownerRepository.findById(1L).orElseThrow().getHandoverCloudEmail());
+ assertThrows(
+ ResponseStatusException.class, () -> owners.transfer(second.getId(), auth(first)));
+ assertEquals(Optional.of(first.getId()), owners.ownerId());
+ when(cloud.ownership(
+ any(),
+ isNull(),
+ eq("status"),
+ isNull(),
+ nullable(Long.class)))
+ .thenReturn(
+ new CloudOwnershipStatus(
+ 9L,
+ "Cloud team",
+ 20L,
+ 20L,
+ 2L,
+ true,
+ CloudOwnershipStatus.State.TRANSFERRED));
+ owners.transfer(second.getId(), auth(first));
+ assertEquals(Optional.of(second.getId()), owners.ownerId());
+ assertNull(ownerRepository.findById(1L).orElseThrow().getHandoverTargetId());
+ assertEquals(
+ Role.ADMIN.getRoleId(),
+ users.findById(first.getId()).orElseThrow().getRolesAsString());
+ assertEquals(
+ Role.ADMIN.getRoleId(),
+ users.findById(second.getId()).orElseThrow().getRolesAsString());
+ }
+
+ @Test
+ void caseVariantAdminCannotLinkUnlinkOrAppearAsOwner() {
+ User owner = user("alice", Role.ADMIN.getRoleId(), false, true);
+ User other = user("Alice", Role.ADMIN.getRoleId(), false, true);
+ owners.resolveOwner();
+ var hint = new ConnectService.CallbackHint(null, null, "https://pdf.example.com");
+ for (var authentication :
+ List.of(
+ auth(other),
+ new UsernamePasswordAuthenticationToken(
+ other, "", other.getAuthorities()))) {
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+ assertFalse(owners.isCurrentUser(authentication));
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> connect.start("server", hint))
+ .getStatusCode()
+ .value());
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> accountLink.unlink())
+ .getStatusCode()
+ .value());
+ }
+ assertTrue(owners.isCurrentUser(auth(owner)));
+ User principal = new User();
+ principal.setId(owner.getId());
+ principal.setUsername("ALICE");
+ var authentication =
+ new UsernamePasswordAuthenticationToken(principal, "", owner.getAuthorities());
+ assertTrue(owners.isCurrentUser(authentication));
+ new TransactionTemplate(transactions)
+ .executeWithoutResult(
+ s ->
+ assertEquals(
+ owner.getId(),
+ owners.requireCurrentOwner(authentication)
+ .getOwnerUserId()));
+ verifyNoInteractions(cloud);
+ }
+
+ @Test
+ void linkAuthorityMovesWithOwnershipAndOldHandshakesCannotComplete() throws Exception {
+ User first = user("first", Role.ADMIN.getRoleId(), false, true);
+ User second = user("second", Role.USER.getRoleId(), false, true);
+ User admin = user("admin", Role.ADMIN.getRoleId(), false, true);
+ owners.resolveOwner();
+ var hint = new ConnectService.CallbackHint(null, null, "https://pdf.example.com");
+ when(cloud.connectRequest(any(), any(), any(), any(), any()))
+ .thenReturn(
+ new AccountLinkClient.ConnectRequestResult(
+ "request", 900, "https://cloud.example.com/link"));
+
+ SecurityContextHolder.getContext().setAuthentication(auth(admin));
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> connect.start("server", hint))
+ .getStatusCode()
+ .value());
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> accountLink.unlink())
+ .getStatusCode()
+ .value());
+ verifyNoInteractions(cloud);
+
+ SecurityContextHolder.getContext().setAuthentication(auth(first));
+ connect.start("server", hint);
+ var saved = org.mockito.ArgumentCaptor.forClass(ConnectState.class);
+ verify(connectStates).save(saved.capture());
+ ConnectState pending = saved.getValue();
+ when(connectStates.findById(1L)).thenReturn(Optional.of(pending));
+ owners.transfer(second.getId(), auth(first));
+ clearInvocations(cloud, credentials);
+
+ assertEquals(
+ 403,
+ assertThrows(
+ ResponseStatusException.class,
+ () -> connect.complete(pending.getNonce()))
+ .getStatusCode()
+ .value());
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> connect.start("server", hint))
+ .getStatusCode()
+ .value());
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> accountLink.unlink())
+ .getStatusCode()
+ .value());
+ verifyNoInteractions(cloud);
+
+ SecurityContextHolder.getContext()
+ .setAuthentication(auth(users.findById(second.getId()).orElseThrow()));
+ assertEquals(
+ "LINK_OWNER_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> connect.complete(pending.getNonce()))
+ .getReason());
+ verifyNoInteractions(cloud);
+ connect.start("server", hint);
+ verify(connectStates, times(2)).save(saved.capture());
+ ConnectState fresh = saved.getValue();
+ when(connectStates.findById(1L)).thenReturn(Optional.of(fresh));
+ when(cloud.connectClaim(fresh.getRequestId(), fresh.getClaimSecret()))
+ .thenReturn(
+ new AccountLinkClient.ConnectClaimResult(
+ AccountLinkClient.ConnectClaimOutcome.GRANTED,
+ "device",
+ "secret",
+ 9L));
+ assertEquals(ConnectService.Phase.LINKED, connect.complete(fresh.getNonce()).phase());
+ verify(credentials).save(any(DeviceCredential.class));
+ assertDoesNotThrow(() -> accountLink.unlink());
+ }
+
+ @Test
+ void pendingHandoverBlocksLinkingBeforeContactingCloud() {
+ User first = user("first", Role.ADMIN.getRoleId(), false, true);
+ User second = user("second", Role.USER.getRoleId(), false, true);
+ owners.resolveOwner();
+ handovers.prepare(second.getId(), auth(first));
+ SecurityContextHolder.getContext().setAuthentication(auth(first));
+ assertEquals(
+ 409,
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ connect.start(
+ "server",
+ new ConnectService.CallbackHint(
+ null, null, "https://pdf.example.com")))
+ .getStatusCode()
+ .value());
+ assertEquals(
+ 409,
+ assertThrows(ResponseStatusException.class, () -> accountLink.unlink())
+ .getStatusCode()
+ .value());
+ verifyNoInteractions(cloud);
+ }
+
@SpringBootConfiguration
@EntityScan(
basePackages = {
@@ -207,6 +444,31 @@ class OrgOwnerServiceTest {
"stirling.software.proprietary.security.repository"
})
static class TestApp {
+ @Bean
+ ConnectStateRepository connectStates() {
+ return mock(ConnectStateRepository.class);
+ }
+
+ @Bean
+ EntitlementCache entitlementCache() {
+ return mock(EntitlementCache.class);
+ }
+
+ @Bean
+ stirling.software.common.model.ApplicationProperties applicationProperties() {
+ return new stirling.software.common.model.ApplicationProperties();
+ }
+
+ @Bean
+ DeviceCredentialRepository credentials() {
+ return mock(DeviceCredentialRepository.class);
+ }
+
+ @Bean
+ AccountLinkClient cloud() {
+ return mock(AccountLinkClient.class);
+ }
+
@Bean
AuditService auditService() {
return mock(AuditService.class);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/OwnershipHandoverServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/OwnershipHandoverServiceTest.java
new file mode 100644
index 0000000000..8fc87a0d30
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/OwnershipHandoverServiceTest.java
@@ -0,0 +1,553 @@
+package stirling.software.proprietary.service;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+import java.util.Optional;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.enumeration.Role;
+import stirling.software.proprietary.accountlink.*;
+import stirling.software.proprietary.accountlink.CloudOwnershipStatus.State;
+import stirling.software.proprietary.model.OrgOwner;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.*;
+import stirling.software.proprietary.security.repository.OrgOwnerRepository;
+
+class OwnershipHandoverServiceTest {
+ private final OrgOwnerRepository owners = mock(OrgOwnerRepository.class);
+ private final UserRepository users = mock(UserRepository.class);
+ private final DeviceCredentialRepository credentials = mock(DeviceCredentialRepository.class);
+ private final AccountLinkClient cloud = mock(AccountLinkClient.class);
+ private ObjectProvider<AccountLinkClient> provider;
+ private OwnershipHandoverService service;
+ private OrgOwner owner;
+ private User successor;
+ private DeviceCredential credential;
+ private UsernamePasswordAuthenticationToken auth;
+
+ @BeforeEach
+ @SuppressWarnings("unchecked")
+ void setup() {
+ provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(cloud);
+ service = new OwnershipHandoverService(owners, users, credentials, provider);
+ owner = new OrgOwner();
+ owner.setOwnerUserId(1L);
+ owner.setOwnerUsername("owner");
+ when(owners.lockOwner()).thenReturn(Optional.of(owner));
+ User current = new User();
+ current.setId(1L);
+ current.setUsername("owner");
+ current.setEnabled(true);
+ current.setFirstLogin(false);
+ current.addAuthority(new Authority(Role.ADMIN.getRoleId(), current));
+ when(users.findById(1L)).thenReturn(Optional.of(current));
+ auth = new UsernamePasswordAuthenticationToken(current, "", current.getAuthorities());
+ successor = new User();
+ successor.setId(2L);
+ successor.setUsername("new-owner");
+ successor.setEmail("[email protected]");
+ successor.setEnabled(true);
+ successor.setFirstLogin(false);
+ when(users.findById(2L)).thenReturn(Optional.of(successor));
+ credential = new DeviceCredential();
+ credential.setDeviceId("device");
+ credential.setDeviceSecret("secret");
+ credential.setTeamId(9L);
+ }
+
+ @Test
+ void disabledLinkingWithCredentialHasAnExplicitRecoveryReason() throws IOException {
+ when(credentials.findCredential()).thenReturn(Optional.of(credential));
+ when(provider.getIfAvailable()).thenReturn(null);
+ assertEquals(
+ "ACCOUNT_LINK_DISABLED",
+ assertThrows(ResponseStatusException.class, () -> service.prepare(2L, auth))
+ .getReason());
+ assertEquals(
+ "ACCOUNT_LINK_DISABLED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.validateCompletion(owner, 2L))
+ .getReason());
+ assertNull(owner.getHandoverTargetId());
+ verifyNoInteractions(cloud);
+ verify(credentials, never()).deleteAll();
+ when(provider.getIfAvailable()).thenReturn(cloud);
+ linked(State.READY, false);
+ assertNotNull(service.prepare(2L, auth).candidates());
+ }
+
+ @Test
+ void disabledLinkingWithoutCredentialStillAllowsLocalTransfer() {
+ when(provider.getIfAvailable()).thenReturn(null);
+ assertDoesNotThrow(() -> service.validateCompletion(owner, 2L));
+ assertNull(service.prepare(2L, auth).cloud());
+ assertDoesNotThrow(() -> service.validateCompletion(owner, 2L));
+ service.cancel(auth);
+ assertNull(owner.getHandoverTargetId());
+ }
+
+ @Test
+ void anotherPendingRecipientIsReportedBeforeValidatingAMissingTarget() {
+ owner.setHandoverTargetId(2L);
+ assertEquals(
+ "HANDOVER_IN_PROGRESS",
+ assertThrows(ResponseStatusException.class, () -> service.prepare(99L, auth))
+ .getReason());
+ verify(users, never()).findById(99L);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "deleted,TARGET_UNAVAILABLE",
+ "disabled,TARGET_UNAVAILABLE",
+ "renamed,TARGET_CHANGED",
+ "email,TARGET_CHANGED"
+ })
+ void changedRecipientCanStillBeCancelledBeforeCloudCommit(String change, String reason)
+ throws IOException {
+ linked(State.READY, false);
+ prepareSelected();
+ switch (change) {
+ case "deleted" -> when(users.findById(2L)).thenReturn(Optional.empty());
+ case "disabled" -> successor.setEnabled(false);
+ case "renamed" -> successor.setUsername("changed");
+ case "email" -> successor.setEmail("[email protected]");
+ default -> throw new AssertionError(change);
+ }
+ assertEquals(
+ reason,
+ assertThrows(ResponseStatusException.class, () -> service.prepare(2L, auth))
+ .getReason());
+ service.cancel(auth);
+ assertNull(owner.getHandoverTargetId());
+ assertEquals(1L, owner.getOwnerUserId());
+ }
+
+ private CloudOwnershipStatus state(State state, boolean paid) {
+ return new CloudOwnershipStatus(
+ 9L,
+ "Team",
+ state == State.TRANSFERRED ? 2L : 1L,
+ state == State.NEEDS_MEMBERSHIP ? null : 2L,
+ 2,
+ paid,
+ state);
+ }
+
+ private void linked(State state, boolean paid) throws IOException {
+ when(credentials.findCredential()).thenReturn(Optional.of(credential));
+ when(cloud.ownershipCandidates(credential))
+ .thenReturn(
+ new CloudOwnershipCandidates(
+ 9L,
+ "Team",
+ java.util.List.of(
+ new CloudOwnershipCandidates.Member(
+ 2L, "Cloud member", "[email protected]"))));
+ when(cloud.ownership(
+ eq(credential),
+ isNull(),
+ eq("status"),
+ isNull(),
+ nullable(Long.class)))
+ .thenReturn(state(state, paid));
+ when(cloud.ownership(
+ eq(credential),
+ anyString(),
+ eq("transfer"),
+ anyLong(),
+ nullable(Long.class)))
+ .thenReturn(state(State.TRANSFERRED, paid));
+ }
+
+ private OwnershipHandoverService.Status prepareSelected() {
+ return service.prepare(
+ 2L, new OwnershipHandoverService.Selection(null, "[email protected]"), auth);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "400,PERSONAL_TEAM,PERSONAL_TEAM",
+ "400,other,INVITATION_BLOCKED",
+ "409,MEMBERSHIP_REQUIRED,MEMBERSHIP_REQUIRED",
+ "409,CLOUD_TARGET_CHANGED,CLOUD_TARGET_CHANGED",
+ "409,other,CLOUD_OWNER_CHANGED"
+ })
+ void cloudRejectionPreservesSpecificGuidanceAndPendingHandover(
+ int code, String upstreamReason, String expectedReason) throws IOException {
+ linked(State.READY, false);
+ prepareSelected();
+ when(cloud.ownership(credential, "[email protected]", "Bearer owner", "transfer", 1L, 2L))
+ .thenThrow(
+ new AccountLinkClient.UpstreamException(code, "rejected", upstreamReason));
+ assertEquals(
+ expectedReason,
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.changeCloud(auth, "Bearer owner", "transfer"))
+ .getReason());
+ assertEquals(1L, owner.getOwnerUserId());
+ assertEquals(2L, owner.getHandoverTargetId());
+ }
+
+ @Test
+ void changedCloudAccountCanBeCancelledWithoutAbandoningACompletedTransfer() throws IOException {
+ linked(State.READY, false);
+ prepareSelected();
+ when(cloud.ownership(credential, "[email protected]", null, "status", null, null))
+ .thenReturn(
+ new CloudOwnershipStatus(
+ 9L, "Team", 1L, null, 2, false, State.NEEDS_MEMBERSHIP));
+ service.cancel(auth);
+ assertNull(owner.getHandoverTargetId());
+ when(cloud.ownership(credential, "[email protected]", null, "status", null, null))
+ .thenReturn(state(State.READY, false));
+ prepareSelected();
+ when(cloud.ownership(credential, "[email protected]", null, "status", null, null))
+ .thenReturn(
+ new CloudOwnershipStatus(
+ 9L, "Team", 2L, null, 2, false, State.NEEDS_MEMBERSHIP));
+ assertEquals(
+ "FINISH_LOCAL_TRANSFER",
+ assertThrows(ResponseStatusException.class, () -> service.cancel(auth))
+ .getReason());
+ assertEquals(2L, owner.getHandoverTargetId());
+ }
+
+ @Test
+ void linkedUserWithoutEmailCanBrowseWithoutStartingAHandover() throws IOException {
+ linked(State.READY, false);
+ successor.setEmail(null);
+ var result = service.prepare(2L, auth);
+ assertEquals(2L, result.candidates().members().getFirst().id());
+ assertNull(result.cloud());
+ assertNull(owner.getHandoverTargetId());
+ assertNull(service.current(auth));
+ }
+
+ @Test
+ void selectedCloudMemberIsPinnedIndependentlyOfTheLocalEmail() throws IOException {
+ linked(State.READY, false);
+ successor.setEmail(null);
+ var result = service.prepare(2L, new OwnershipHandoverService.Selection(2L, null), auth);
+ assertNull(result.targetEmail());
+ assertEquals("[email protected]", result.cloudEmail());
+ assertNull(successor.getEmail());
+ assertEquals(2L, owner.getHandoverCloudUserId());
+ service.changeCloud(auth, "Bearer human", "transfer");
+ verify(cloud).ownership(credential, "[email protected]", "Bearer human", "transfer", 1L, 2L);
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.prepare(2L, new OwnershipHandoverService.Selection(3L, null), auth));
+ }
+
+ @Test
+ void rejectsMemberNotInLinkedTeamWithoutPersistingIntent() throws IOException {
+ linked(State.READY, false);
+ assertEquals(
+ "CLOUD_TARGET_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.prepare(
+ 2L,
+ new OwnershipHandoverService.Selection(123L, null),
+ auth))
+ .getReason());
+ assertNull(owner.getHandoverTargetId());
+ }
+
+ @Test
+ void cannotPairTheLocalSuccessorWithTheCurrentCloudOwner() throws IOException {
+ linked(State.TRANSFERRED, false);
+ assertEquals(
+ "CHOOSE_ANOTHER_CLOUD_USER",
+ assertThrows(ResponseStatusException.class, this::prepareSelected).getReason());
+ assertNull(owner.getHandoverTargetId());
+ }
+
+ @Test
+ void invitationPinsTheAcceptedAccountBeforeTransfer() throws IOException {
+ linked(State.NEEDS_MEMBERSHIP, true);
+ successor.setEmail(null);
+ prepareSelected();
+ assertNull(owner.getHandoverCloudUserId());
+ linked(State.READY, true);
+ prepareSelected();
+ assertEquals(2L, owner.getHandoverCloudUserId());
+ service.changeCloud(auth, "Bearer human", "transfer");
+ verify(cloud).ownership(credential, "[email protected]", "Bearer human", "transfer", 1L, 2L);
+ }
+
+ @Test
+ void unlinkedNeedsNoCloudAccountAndPreservesOwnerUntilCompletion() {
+ successor.setEmail(null);
+ assertNull(service.prepare(2L, auth).cloud());
+ service.validateCompletion(owner, 2L);
+ assertEquals(1L, owner.getOwnerUserId());
+ verifyNoInteractions(cloud);
+ }
+
+ @ParameterizedTest(name = "paid={0}, recipient={1}")
+ @CsvSource({
+ "false, no-account",
+ "false, same-team",
+ "false, different-team",
+ "true, no-account",
+ "true, same-team",
+ "true, different-team"
+ })
+ void sixLinkedScenariosCannotCompleteBeforeCloudOwnership(boolean paid, String account)
+ throws IOException {
+ State readiness = account.equals("same-team") ? State.READY : State.NEEDS_MEMBERSHIP;
+ linked(readiness, paid);
+ assertEquals(readiness, prepareSelected().cloud().state());
+ assertEquals(
+ "CLOUD_TRANSFER_REQUIRED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.validateCompletion(owner, 2L))
+ .getReason());
+ assertEquals(1L, owner.getOwnerUserId());
+ linked(State.TRANSFERRED, paid);
+ service.validateCompletion(owner, 2L);
+ assertEquals("device", owner.getHandoverDeviceId());
+ assertEquals("secret", credential.getDeviceSecret());
+ }
+
+ @Test
+ void directLocalEndpointCannotBypassPreparation() throws IOException {
+ linked(State.READY, true);
+ assertEquals(
+ "PREPARE_HANDOVER_FIRST",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.validateCompletion(owner, 2L))
+ .getReason());
+ }
+
+ @Test
+ void deviceCredentialAloneCannotTransferCloudOwnership() throws IOException {
+ linked(State.READY, false);
+ prepareSelected();
+ assertEquals(
+ "CLOUD_SIGN_IN_REQUIRED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.changeCloud(auth, null, "transfer"))
+ .getReason());
+ verify(cloud, never()).ownership(any(), any(), any(), eq("transfer"), any(), any());
+ }
+
+ @Test
+ void humanBearerIsForwardedWithPinnedLeaderButNeverPersisted() throws IOException {
+ linked(State.READY, true);
+ prepareSelected();
+ service.changeCloud(auth, "Bearer human", "transfer");
+ verify(cloud).ownership(credential, "[email protected]", "Bearer human", "transfer", 1L, 2L);
+ assertEquals(1L, owner.getHandoverLeaderId());
+ }
+
+ @Test
+ void lostCloudResponseCanResumeWithoutOldLeadersBearer() throws IOException {
+ linked(State.READY, true);
+ prepareSelected();
+ when(cloud.ownership(credential, "[email protected]", "Bearer human", "transfer", 1L, 2L))
+ .thenThrow(new IOException("lost response"));
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.changeCloud(auth, "Bearer human", "transfer"));
+ linked(State.TRANSFERRED, true);
+ assertEquals(State.TRANSFERRED, service.prepare(2L, auth).cloud().state());
+ service.validateCompletion(owner, 2L);
+ assertEquals(
+ "FINISH_LOCAL_TRANSFER",
+ assertThrows(ResponseStatusException.class, () -> service.cancel(auth))
+ .getReason());
+ }
+
+ @Test
+ void changedRecipientOrLinkCannotComplete() throws IOException {
+ linked(State.READY, true);
+ prepareSelected();
+ successor.setEmail("[email protected]");
+ assertEquals(
+ "TARGET_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.validateCompletion(owner, 2L))
+ .getReason());
+ successor.setEmail("[email protected]");
+ credential.setDeviceId("replacement");
+ assertEquals(
+ "LINK_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.validateCompletion(owner, 2L))
+ .getReason());
+ }
+
+ @Test
+ void outageFailsClosedButPendingRecordCanStillBeDiscovered() throws IOException {
+ linked(State.READY, false);
+ prepareSelected();
+ when(cloud.ownership(credential, "[email protected]", null, "status", null, 2L))
+ .thenThrow(new IOException());
+ assertThrows(ResponseStatusException.class, () -> service.validateCompletion(owner, 2L));
+ assertEquals(2L, service.current(auth).targetId());
+ }
+
+ @Test
+ void nonOwnerAndDisabledRecipientAreRejected() {
+ var stranger = new UsernamePasswordAuthenticationToken("stranger", "", java.util.List.of());
+ assertEquals(
+ "ORG_OWNER_REQUIRED",
+ assertThrows(ResponseStatusException.class, () -> service.prepare(2L, stranger))
+ .getReason());
+ successor.setEnabled(false);
+ assertEquals(
+ "TARGET_UNAVAILABLE",
+ assertThrows(ResponseStatusException.class, () -> service.prepare(2L, auth))
+ .getReason());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"401, invalid", "403, revoked", "404, CLOUD_TEAM_MISSING"})
+ void authoritativeLostLinkAllowsCancellationButNeverCompletion(int code, String reason)
+ throws IOException {
+ linked(State.READY, true);
+ prepareSelected();
+ when(cloud.ownership(
+ eq(credential),
+ anyString(),
+ isNull(),
+ eq("status"),
+ isNull(),
+ nullable(Long.class)))
+ .thenThrow(new AccountLinkClient.UpstreamException(code, "denied", reason));
+ assertEquals(
+ "LINK_REVOKED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.validateCompletion(owner, 2L))
+ .getReason());
+ service.cancel(auth);
+ assertNull(owner.getHandoverTargetId());
+ assertNull(owner.getHandoverCloudUserId());
+ assertEquals(1L, owner.getOwnerUserId());
+ verify(credentials, never()).delete(any());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"404, route_missing", "500, error", "503, outage", "409, CLOUD_TARGET_CHANGED"})
+ void ambiguousFailureCannotAbandonHandover(int code, String reason) throws IOException {
+ linked(State.READY, true);
+ prepareSelected();
+ when(cloud.ownership(credential, "[email protected]", null, "status", null, null))
+ .thenThrow(new AccountLinkClient.UpstreamException(code, "unavailable", reason));
+ assertThrows(ResponseStatusException.class, () -> service.cancel(auth));
+ assertEquals(2L, owner.getHandoverTargetId());
+ }
+
+ @Test
+ void cancelledRequestCannotDiscardHandoverDuringNetworkOutage() throws IOException {
+ linked(State.READY, true);
+ prepareSelected();
+ when(cloud.ownership(credential, "[email protected]", null, "status", null, null))
+ .thenThrow(new IOException("timeout"));
+ assertThrows(ResponseStatusException.class, () -> service.cancel(auth));
+ assertEquals(2L, owner.getHandoverTargetId());
+ }
+
+ @Test
+ void browsingResumedCandidatesPreservesPinnedRecipient() throws IOException {
+ linked(State.READY, false);
+ prepareSelected();
+ assertEquals(2L, service.members(auth).members().getFirst().id());
+ assertEquals(2L, owner.getHandoverTargetId());
+ assertEquals(2L, owner.getHandoverCloudUserId());
+ assertEquals(1L, owner.getHandoverLeaderId());
+ }
+
+ @Test
+ void mixedCaseOwnerCanPrepareReadAdvanceAndCancel() throws IOException {
+ linked(State.READY, false);
+ User principal = new User();
+ principal.setId(1L);
+ principal.setUsername("OwNeR");
+ auth = new UsernamePasswordAuthenticationToken(principal, "", java.util.List.of());
+ prepareSelected();
+ assertEquals(2L, service.current(auth).targetId());
+ assertEquals(1, service.members(auth).members().size());
+ when(cloud.ownership(credential, "[email protected]", "Bearer human", "invite", 1L, 2L))
+ .thenReturn(state(State.READY, false));
+ service.changeCloud(auth, "Bearer human", "invite");
+ service.cancel(auth);
+ assertNull(owner.getHandoverTargetId());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true", "false"})
+ void caseVariantAdministratorCannotActAsOwner(boolean userPrincipal) {
+ successor.setUsername("OWNER");
+ successor.addAuthority(new Authority(Role.ADMIN.getRoleId(), successor));
+ if (!userPrincipal) when(users.findByUsername("OWNER")).thenReturn(Optional.of(successor));
+ var impersonator =
+ new UsernamePasswordAuthenticationToken(
+ userPrincipal ? successor : "OWNER", "", successor.getAuthorities());
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> service.prepare(2L, impersonator))
+ .getStatusCode()
+ .value());
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> service.cancel(impersonator))
+ .getStatusCode()
+ .value());
+ verifyNoInteractions(cloud, credentials);
+ assertNull(owner.getHandoverTargetId());
+ }
+
+ @Test
+ void namedPrincipalResolvesTheAuthenticatedAccountBeforeCheckingOwnership() {
+ var current = users.findById(1L);
+ when(users.findByUsername("owner")).thenReturn(current);
+ var named = new UsernamePasswordAuthenticationToken("owner", "", java.util.List.of());
+ assertNotNull(service.prepare(2L, named));
+ }
+
+ @Test
+ void staleOwnerPrincipalCannotBypassCurrentAccountRestrictions() {
+ users.findById(1L).orElseThrow().setEnabled(false);
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> service.prepare(2L, auth))
+ .getStatusCode()
+ .value());
+ }
+
+ @Test
+ void cancelBeforeCloudTransferClearsOnlyHandover() throws IOException {
+ linked(State.READY, true);
+ prepareSelected();
+ successor.setEmail("[email protected]");
+ service.cancel(auth);
+ assertNull(owner.getHandoverTargetId());
+ assertEquals(1L, owner.getOwnerUserId());
+ assertEquals("secret", credential.getDeviceSecret());
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java
index 2a751c8120..a3bd413ce2 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectController.java
@@ -106,8 +106,7 @@ public class ConnectController {
body.nonce(),
body.claimSecret(),
clientIp(http),
- instance.map(LinkedInstance::getTeamId).orElse(null),
- instance.map(LinkedInstance::getCreatedByUserId).orElse(null));
+ instance.map(LinkedInstance::getTeamId).orElse(null));
} else {
result =
service.create(
@@ -191,9 +190,7 @@ public class ConnectController {
boolean reauth = v.mode() == ConnectRequest.Mode.REAUTH;
boolean canApprove =
!caller.isError()
- && (!reauth
- || v.isLinkedAccount(
- caller.teamId(), caller.userId()));
+ && (!reauth || v.isLinkedTeam(caller.teamId()));
boolean canDeny = !reauth && !caller.isError();
return ResponseEntity.ok(
new ViewResponse(
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.java b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.java
index 833e8f5571..6e5f0a1548 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequest.java
@@ -78,7 +78,7 @@ public class ConnectRequest {
@Column(name = "team_id")
private Long teamId;
- /** LINK: set on approval. REAUTH: pinned to the original linking user at creation. */
+ /** The current cloud owner who approved this handshake; populated on approval. */
@Column(name = "approved_by_user_id")
private Long approvedByUserId;
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.java b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.java
index 7d7ad48b35..cb706ee274 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/ConnectRequestService.java
@@ -84,13 +84,9 @@ public class ConnectRequestService {
boolean insecureTransport,
ConnectRequest.Mode mode,
ConnectRequest.Status status,
- Long teamId,
- Long linkedUserId) {
- boolean isLinkedAccount(Long callerTeamId, Long callerUserId) {
- return teamId != null
- && linkedUserId != null
- && teamId.equals(callerTeamId)
- && linkedUserId.equals(callerUserId);
+ Long teamId) {
+ boolean isLinkedTeam(Long callerTeamId) {
+ return teamId != null && teamId.equals(callerTeamId);
}
}
@@ -119,7 +115,7 @@ public class ConnectRequestService {
@Transactional
public CreateResult create(
String name, String callbackUrl, String nonce, String claimSecret, String requesterIp) {
- return create(name, callbackUrl, nonce, claimSecret, requesterIp, null, null);
+ return create(name, callbackUrl, nonce, claimSecret, requesterIp, null);
}
/**
@@ -133,13 +129,11 @@ public class ConnectRequestService {
String nonce,
String claimSecret,
String requesterIp,
- Long pinnedTeamId,
- Long pinnedUserId) {
- if (pinnedTeamId == null || pinnedUserId == null) {
+ Long pinnedTeamId) {
+ if (pinnedTeamId == null) {
return CreateResult.rejected(CreateRejection.NOT_LINKED);
}
- return create(
- name, callbackUrl, nonce, claimSecret, requesterIp, pinnedTeamId, pinnedUserId);
+ return create(name, callbackUrl, nonce, claimSecret, requesterIp, pinnedTeamId);
}
private CreateResult create(
@@ -148,8 +142,7 @@ public class ConnectRequestService {
String nonce,
String claimSecret,
String requesterIp,
- Long pinnedTeamId,
- Long pinnedUserId) {
+ Long pinnedTeamId) {
if (nonce == null || nonce.isBlank() || nonce.length() > MAX_NONCE_LENGTH) {
return CreateResult.rejected(CreateRejection.BAD_NONCE);
}
@@ -179,7 +172,6 @@ public class ConnectRequestService {
request.setMode(
pinnedTeamId == null ? ConnectRequest.Mode.LINK : ConnectRequest.Mode.REAUTH);
request.setTeamId(pinnedTeamId);
- request.setApprovedByUserId(pinnedUserId);
request.setRequesterIp(requesterIp);
request.setExpiresAt(now.plusMinutes(LIFETIME_MINUTES));
repo.save(request);
@@ -209,15 +201,14 @@ public class ConnectRequestService {
!"https".equals(schemeOf(request.getCallbackOrigin())),
request.getMode(),
request.getStatus(),
- request.getTeamId(),
- request.getApprovedByUserId());
+ request.getTeamId());
}
/** Why an approval was refused, so the page can say something useful. */
public enum ApproveRejection {
/** Unknown, expired, or already settled. */
UNAVAILABLE,
- /** The approver is not the account and team this server was linked with. */
+ /** The authenticated owner belongs to a different team from the linked server. */
WRONG_ACCOUNT
}
@@ -227,7 +218,10 @@ public class ConnectRequestService {
}
}
- /** Binds a pending handshake to the approver's team and returns where to send them next. */
+ /**
+ * The caller must resolve the current team owner before approval. Renewal confirms the pinned
+ * team without rebinding the server or requiring its original linking user.
+ */
@Transactional
public ApproveResult approve(String requestId, Long teamId, Long userId) {
Optional<ConnectRequest> found = repo.findByRequestIdForUpdate(requestId);
@@ -240,7 +234,7 @@ public class ConnectRequestService {
return new ApproveResult(null, ApproveRejection.UNAVAILABLE);
}
if (request.getMode() == ConnectRequest.Mode.REAUTH
- && !viewOf(request).isLinkedAccount(teamId, userId)) {
+ && (userId == null || !viewOf(request).isLinkedTeam(teamId))) {
return new ApproveResult(null, ApproveRejection.WRONG_ACCOUNT);
}
request.setStatus(ConnectRequest.Status.APPROVED);
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/OwnershipHandoverController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/OwnershipHandoverController.java
new file mode 100644
index 0000000000..b263803505
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/OwnershipHandoverController.java
@@ -0,0 +1,75 @@
+package stirling.software.saas.accountlink;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.server.ResponseStatusException;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.accountlink.CloudOwnershipCandidates;
+import stirling.software.proprietary.accountlink.CloudOwnershipStatus;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.saas.service.SaasOwnershipHandoverService;
+import stirling.software.saas.util.AuthenticationUtils;
+
+/** Device reads cannot grant cloud ownership; mutations require the current human cloud leader. */
+@RestController
+@Profile("saas")
+@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@RequiredArgsConstructor
+public class OwnershipHandoverController {
+ private final AccountLinkService links;
+ private final SaasOwnershipHandoverService handovers;
+ private final UserRepository users;
+
+ public record Request(String email, Long expectedLeaderId, Long expectedTargetId) {
+ public Request(String email, Long expectedLeaderId) {
+ this(email, expectedLeaderId, null);
+ }
+ }
+
+ @GetMapping("/api/v1/instance/ownership/members")
+ @PreAuthorize("hasRole('LINKED_INSTANCE')")
+ public CloudOwnershipCandidates candidates(Authentication auth) {
+ if (!(auth instanceof LinkedInstanceAuthenticationToken token)) {
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN);
+ }
+ return handovers.candidates(token.getTeamId());
+ }
+
+ @PostMapping("/api/v1/instance/ownership/status")
+ @PreAuthorize("hasRole('LINKED_INSTANCE')")
+ public CloudOwnershipStatus status(@RequestBody Request request, Authentication auth) {
+ if (!(auth instanceof LinkedInstanceAuthenticationToken token)) {
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN);
+ }
+ return handovers.status(token.getTeamId(), request.email(), request.expectedTargetId());
+ }
+
+ @PostMapping("/api/v1/account-link/ownership/{action:invite|transfer}")
+ @PreAuthorize("isAuthenticated()")
+ public CloudOwnershipStatus change(
+ @PathVariable String action,
+ @RequestHeader("X-Device-Id") String deviceId,
+ @RequestHeader("X-Device-Secret") String secret,
+ @RequestBody Request request,
+ Authentication auth) {
+ LinkedInstance instance =
+ links.resolveActiveInstance(deviceId, secret)
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.FORBIDDEN, "LINK_CHANGED"));
+ return handovers.changeFromInstance(
+ instance,
+ request.email(),
+ request.expectedLeaderId(),
+ AuthenticationUtils.getCurrentUser(auth, users),
+ action,
+ request.expectedTargetId());
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/controller/TeamOwnershipHandoverController.java b/app/saas/src/main/java/stirling/software/saas/controller/TeamOwnershipHandoverController.java
new file mode 100644
index 0000000000..1e50e009f6
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/controller/TeamOwnershipHandoverController.java
@@ -0,0 +1,43 @@
+package stirling.software.saas.controller;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.*;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.accountlink.CloudOwnershipStatus;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.saas.service.SaasOwnershipHandoverService;
+import stirling.software.saas.util.AuthenticationUtils;
+
+/** Uses the same team-scoped handover checks as a linked server, with human authentication. */
+@RestController
+@Profile("saas")
+@RequestMapping("/api/v1/team/{teamId}/ownership")
+@RequiredArgsConstructor
+public class TeamOwnershipHandoverController {
+ private final SaasOwnershipHandoverService handovers;
+ private final UserRepository users;
+
+ public record Request(String email, Long expectedLeaderId) {}
+
+ @PostMapping("/status")
+ @PreAuthorize("@teamSecurity.isTeamMember(#teamId)")
+ public CloudOwnershipStatus status(@PathVariable Long teamId, @RequestBody Request request) {
+ return handovers.status(teamId, request.email());
+ }
+
+ @PostMapping("/transfer")
+ @PreAuthorize("@teamSecurity.isTeamMember(#teamId)")
+ public CloudOwnershipStatus transfer(
+ @PathVariable Long teamId, @RequestBody Request request, Authentication auth) {
+ return handovers.change(
+ teamId,
+ request.email(),
+ request.expectedLeaderId(),
+ AuthenticationUtils.getCurrentUser(auth, users),
+ "transfer");
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/service/SaasOwnershipHandoverService.java b/app/saas/src/main/java/stirling/software/saas/service/SaasOwnershipHandoverService.java
new file mode 100644
index 0000000000..f181034b0c
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/service/SaasOwnershipHandoverService.java
@@ -0,0 +1,224 @@
+package stirling.software.saas.service;
+
+import java.util.List;
+import java.util.Objects;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.server.ResponseStatusException;
+
+import jakarta.persistence.EntityManager;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.accountlink.CloudOwnershipCandidates;
+import stirling.software.proprietary.accountlink.CloudOwnershipStatus;
+import stirling.software.proprietary.accountlink.CloudOwnershipStatus.State;
+import stirling.software.proprietary.model.TeamMembership;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
+import stirling.software.proprietary.security.repository.TeamRepository;
+import stirling.software.saas.accountlink.LinkedInstance;
+import stirling.software.saas.accountlink.LinkedInstanceRepository;
+import stirling.software.saas.payg.billing.TeamBillingService;
+import stirling.software.saas.repository.TeamInvitationRepository;
+
+/**
+ * Resolves successors inside one team; a device never supplies the human authorization to transfer.
+ */
+@Service
+@Profile("saas")
+@RequiredArgsConstructor
+public class SaasOwnershipHandoverService {
+ private final TeamRepository teams;
+ private final TeamMembershipRepository memberships;
+ private final LinkedInstanceRepository instances;
+ private final TeamBillingService billing;
+ private final SaasTeamService invitations;
+ private final SaasOwnershipService ownership;
+ private final SaasTeamExtensionService extensions;
+ private final EntityManager entities;
+ private final TeamInvitationRepository pendingInvitations;
+
+ /**
+ * Excludes the current owner, unaccepted invitations, disabled accounts and departed members.
+ */
+ @Transactional(readOnly = true)
+ public CloudOwnershipCandidates candidates(Long teamId) {
+ var team =
+ teams.findById(teamId)
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.NOT_FOUND, "CLOUD_TEAM_MISSING"));
+ var members =
+ memberships.findByTeamId(teamId).stream()
+ .filter(m -> !m.isLeader() && eligible(m, teamId, m.getUser().getEmail()))
+ .map(
+ m ->
+ new CloudOwnershipCandidates.Member(
+ m.getUser().getId(),
+ m.getUser().getUsername(),
+ m.getUser().getEmail()))
+ .sorted(
+ java.util.Comparator.comparing(
+ CloudOwnershipCandidates.Member::email,
+ String.CASE_INSENSITIVE_ORDER))
+ .toList();
+ return new CloudOwnershipCandidates(teamId, team.getName(), members);
+ }
+
+ /** Rejects email reassignment or membership changes after the local server pins an account. */
+ @Transactional(readOnly = true)
+ public CloudOwnershipStatus status(Long teamId, String email, Long expectedTargetId) {
+ var result = status(teamId, email);
+ if (expectedTargetId != null && !Objects.equals(result.targetUserId(), expectedTargetId)) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "CLOUD_TARGET_CHANGED");
+ }
+ return result;
+ }
+
+ /** Resolves only accepted, enabled recipients currently attached to the specified team. */
+ @Transactional(readOnly = true)
+ public CloudOwnershipStatus status(Long teamId, String email) {
+ if (email == null || email.isBlank()) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "EMAIL_REQUIRED");
+ }
+ var team =
+ teams.findById(teamId)
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.NOT_FOUND, "CLOUD_TEAM_MISSING"));
+ List<TeamMembership> rows = memberships.findByTeamId(teamId);
+ Long leader =
+ rows.stream()
+ .filter(TeamMembership::isLeader)
+ .map(m -> m.getUser().getId())
+ .min(Long::compareTo)
+ .orElse(null);
+ var target = rows.stream().filter(m -> eligible(m, teamId, email)).findFirst();
+ long leaderCount = rows.stream().filter(TeamMembership::isLeader).count();
+ State state =
+ target.map(m -> m.isLeader() && leaderCount == 1 ? State.TRANSFERRED : State.READY)
+ .orElse(State.NEEDS_MEMBERSHIP);
+ return new CloudOwnershipStatus(
+ teamId,
+ team.getName(),
+ leader,
+ target.map(m -> m.getUser().getId()).orElse(null),
+ instances.countByTeamIdAndRevokedAtIsNull(teamId),
+ billing.forTeam(teamId).subscribed(),
+ state);
+ }
+
+ /** Serializes with other ownership changes and rejects a confirmation of a stale leader. */
+ @Transactional
+ public CloudOwnershipStatus change(
+ Long teamId, String email, Long expectedLeaderId, User caller, String action) {
+ return change(teamId, email, expectedLeaderId, caller, action, null, null);
+ }
+
+ /**
+ * Only the device-authenticated endpoint may supply an instance; the human owner is rechecked.
+ */
+ @Transactional
+ public CloudOwnershipStatus changeFromInstance(
+ LinkedInstance instance,
+ String email,
+ Long expectedLeaderId,
+ User caller,
+ String action) {
+ return changeFromInstance(instance, email, expectedLeaderId, caller, action, null);
+ }
+
+ /** Revalidates the selected account under the same team lock used for ownership changes. */
+ @Transactional
+ public CloudOwnershipStatus changeFromInstance(
+ LinkedInstance instance,
+ String email,
+ Long expectedLeaderId,
+ User caller,
+ String action,
+ Long expectedTargetId) {
+ return change(
+ instance.getTeamId(),
+ email,
+ expectedLeaderId,
+ caller,
+ action,
+ instance,
+ expectedTargetId);
+ }
+
+ private CloudOwnershipStatus change(
+ Long teamId,
+ String email,
+ Long expectedLeaderId,
+ User caller,
+ String action,
+ LinkedInstance instance,
+ Long expectedTargetId) {
+ var team =
+ teams.lockById(teamId)
+ .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
+ memberships.findByTeamId(teamId).forEach(entities::refresh);
+ var actor =
+ memberships
+ .findByTeamIdAndUserId(teamId, caller.getId())
+ .filter(
+ m ->
+ m.isLeader()
+ && m.getAcceptedAt() != null
+ && caller.isEnabled())
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.FORBIDDEN, "CLOUD_OWNER_REQUIRED"));
+ CloudOwnershipStatus before = status(teamId, email, expectedTargetId);
+ if (!Objects.equals(before.leaderUserId(), expectedLeaderId)) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "CLOUD_OWNER_CHANGED");
+ }
+ if ("invite".equals(action)) {
+ if (before.state() == State.NEEDS_MEMBERSHIP) {
+ String address = email.strip().toLowerCase(java.util.Locale.ROOT);
+ pendingInvitations.markExpiredInvitations(java.time.LocalDateTime.now());
+ if (!pendingInvitations.existsPendingInvitationByTeamIdAndEmail(teamId, address)) {
+ try {
+ invitations.inviteUserToTeam(teamId, address, actor.getUser());
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "INVITATION_BLOCKED");
+ }
+ }
+ }
+ } else if ("transfer".equals(action)) {
+ if (extensions.isPersonal(team))
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "PERSONAL_TEAM");
+ if (before.state() == State.NEEDS_MEMBERSHIP)
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "MEMBERSHIP_REQUIRED");
+ if (before.state() != State.TRANSFERRED) {
+ if (instance == null) ownership.transfer(teamId, before.targetUserId(), caller);
+ else
+ ownership.transferFromInstance(teamId, before.targetUserId(), caller, instance);
+ }
+ } else {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
+ }
+ return status(teamId, email);
+ }
+
+ private boolean eligible(TeamMembership membership, Long teamId, String email) {
+ User user = membership.getUser();
+ return membership.getAcceptedAt() != null
+ && email != null
+ && !email.isBlank()
+ && user.isEnabled()
+ && user.getEmail() != null
+ && user.getEmail().equalsIgnoreCase(email.strip())
+ && user.getTeam() != null
+ && (membership.isLeader() || Objects.equals(user.getTeam().getId(), teamId));
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/service/SaasOwnershipService.java b/app/saas/src/main/java/stirling/software/saas/service/SaasOwnershipService.java
index cbfbaeea0e..b968db6d7d 100644
--- a/app/saas/src/main/java/stirling/software/saas/service/SaasOwnershipService.java
+++ b/app/saas/src/main/java/stirling/software/saas/service/SaasOwnershipService.java
@@ -18,6 +18,8 @@ import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.*;
import stirling.software.proprietary.service.AuditService;
+import stirling.software.saas.accountlink.LinkedInstance;
+import stirling.software.saas.accountlink.LinkedInstanceRepository;
/** Transfers an existing team's leadership without moving wallets, subscriptions or identities. */
@Service
@@ -29,9 +31,25 @@ public class SaasOwnershipService {
private final SaasTeamExtensionService extensions;
private final EntityManager entityManager;
private final AuditService audit;
+ private final LinkedInstanceRepository instances;
+ /**
+ * Linked teams must transfer through an authenticated instance; ownerless recovery remains
+ * available.
+ */
@Transactional
public void transfer(Long teamId, Long targetId, User caller) {
+ transfer(teamId, targetId, caller, null);
+ }
+
+ /** The caller must have authenticated this instance's device secret and the human owner. */
+ @Transactional
+ void transferFromInstance(Long teamId, Long targetId, User caller, LinkedInstance instance) {
+ Objects.requireNonNull(instance);
+ transfer(teamId, targetId, caller, instance);
+ }
+
+ private void transfer(Long teamId, Long targetId, User caller, LinkedInstance instance) {
var team =
teams.lockById(teamId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
@@ -55,6 +73,15 @@ public class SaasOwnershipService {
HttpStatus.FORBIDDEN, "Only the current leader can transfer ownership.");
if (!unowned && caller.getId().equals(targetId))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Choose another member.");
+ if (instance != null) {
+ instances
+ .findByDeviceIdAndRevokedAtIsNull(instance.getDeviceId())
+ .filter(link -> Objects.equals(link.getTeamId(), teamId))
+ .orElseThrow(
+ () -> new ResponseStatusException(HttpStatus.CONFLICT, "LINK_CHANGED"));
+ } else if (!unowned && instances.countByTeamIdAndRevokedAtIsNull(teamId) > 0) {
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "START_TRANSFER_FROM_INSTANCE");
+ }
TeamMembership target =
rows.stream()
.filter(
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.java
index 764c78332c..6800618064 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
@@ -428,10 +428,9 @@ public class SaasTeamService {
|| oldTeam.getId().equals(team.getId())) {
continue; // keep the durable home; skip the team being joined
}
- // Keep any team the user leads that still has other members: leaving it would orphan
- // them (members, zero leaders). Solo/empty led teams and plain memberships still leave.
- if (existingMembership.isLeader()
- && membershipRepository.countByTeamId(oldTeam.getId()) > 1) {
+ // A transferred team can be non-home and have only its successor left. Retain its
+ // owner even when it is unpaid: content and wallet value outlive subscriptions.
+ if (existingMembership.isLeader()) {
continue;
}
membershipRepository.delete(existingMembership);
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java
index 7e76c49e47..e705e563db 100644
--- a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectControllerTest.java
@@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
@@ -132,14 +133,7 @@ class ConnectControllerTest {
// createReauth is the credentialled path; a first link must not reach it.
org.mockito.Mockito.verify(service, org.mockito.Mockito.never())
- .createReauth(
- anyString(),
- anyString(),
- anyString(),
- anyString(),
- any(),
- isNull(),
- isNull());
+ .createReauth(anyString(), anyString(), anyString(), anyString(), any(), isNull());
}
@Test
@@ -171,7 +165,7 @@ class ConnectControllerTest {
}
@Test
- void reauthLookupAllowsOnlyTheLinkedOwnerToRenew() {
+ void reauthLookupAllowsTheCurrentTeamOwnerToRenew() {
pendingRequest(ConnectRequest.Mode.REAUTH);
when(leaderTeams.resolve(auth)).thenReturn(new LeaderTeam(1L, 2L, null));
@@ -183,8 +177,8 @@ class ConnectControllerTest {
}
@ParameterizedTest
- @CsvSource({"1,3", "99,2", "99,3"})
- void reauthLookupOffersNoActionsToAnotherAccountOrTeam(Long teamId, Long userId) {
+ @CsvSource({"99,2", "99,3"})
+ void reauthLookupOffersNoActionsToAnotherTeamOwner(Long teamId, Long userId) {
pendingRequest(ConnectRequest.Mode.REAUTH);
when(leaderTeams.resolve(auth)).thenReturn(new LeaderTeam(teamId, userId, null));
@@ -196,7 +190,7 @@ class ConnectControllerTest {
}
@Test
- void reauthRequiresTheLinkedAccountToStillOwnItsTeam() {
+ void reauthRejectsTheFormerOwnerAfterHandover() {
pendingRequest(ConnectRequest.Mode.REAUTH);
when(leaderTeams.resolve(auth))
.thenReturn(new LeaderTeam(null, null, HttpStatus.FORBIDDEN));
@@ -211,25 +205,24 @@ class ConnectControllerTest {
}
@Test
- void reauthCreationUsesTheAuthenticatedInstancesOriginalAccount() {
+ void reauthCreationUsesTheAuthenticatedInstancesTeamWithoutItsOriginalAccount() {
LinkedInstance instance = new LinkedInstance();
instance.setTeamId(1L);
- instance.setCreatedByUserId(2L);
when(accountLinkService.resolveActiveInstance("device", "secret"))
.thenReturn(Optional.of(instance));
- when(service.createReauth("prod-1", BODY.callbackUrl(), "n", "s", "127.0.0.1", 1L, 2L))
+ when(service.createReauth("prod-1", BODY.callbackUrl(), "n", "s", "127.0.0.1", 1L))
.thenReturn(ConnectRequestService.CreateResult.ok("req-1", 1800));
MockHttpServletRequest request = request("https", "api.example.com", 443);
request.addHeader(ConnectController.HEADER_DEVICE_ID, "device");
request.addHeader(ConnectController.HEADER_DEVICE_SECRET, "secret");
assertThat(controller.request(BODY, request).getStatusCode()).isEqualTo(HttpStatus.CREATED);
- verify(service).createReauth("prod-1", BODY.callbackUrl(), "n", "s", "127.0.0.1", 1L, 2L);
+ verify(service).createReauth("prod-1", BODY.callbackUrl(), "n", "s", "127.0.0.1", 1L);
}
@ParameterizedTest
- @CsvSource({"1,3", "99,2", "99,3"})
- void directRenewalPostsCannotApproveOrDenyForAnotherAccount(Long teamId, Long userId) {
+ @CsvSource({"99,2", "99,3"})
+ void directRenewalPostsCannotApproveOrDenyForAnotherTeam(Long teamId, Long userId) {
ConnectRequestRepository repo = mock(ConnectRequestRepository.class);
ConnectRequest row = new ConnectRequest();
row.setRequestId("req-1");
@@ -268,7 +261,39 @@ class ConnectControllerTest {
false,
mode,
ConnectRequest.Status.PENDING,
- 1L,
- 2L)));
+ 1L)));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void newOwnerCanRenewFreshAndLegacyRequestsWithoutReplacingTheLink(boolean legacy) {
+ var repo = mock(ConnectRequestRepository.class);
+ var row = new ConnectRequest();
+ row.setRequestId("req-1");
+ row.setMode(ConnectRequest.Mode.REAUTH);
+ row.setTeamId(1L);
+ row.setApprovedByUserId(legacy ? 2L : null);
+ row.setCallbackOrigin("https://pdf.example.com");
+ row.setCallbackUrl("https://pdf.example.com/account-link/callback");
+ row.setNonce("nonce");
+ row.setClaimSecretHash(AccountLinkService.sha256Hex("claim-secret"));
+ row.setExpiresAt(LocalDateTime.now().plusMinutes(10));
+ when(repo.findByRequestId("req-1")).thenReturn(Optional.of(row));
+ when(repo.findByRequestIdForUpdate("req-1")).thenReturn(Optional.of(row));
+ when(leaderTeams.resolve(auth)).thenReturn(new LeaderTeam(1L, 3L, null));
+ var realService = new ConnectRequestService(repo, accountLinkService);
+ var realController =
+ new ConnectController(
+ realService, leaderTeams, accountLinkService, applicationProperties);
+
+ assertThat(realController.view("req-1", auth).getBody().canApprove()).isTrue();
+ assertThat(realController.approve("req-1", auth).getStatusCode()).isEqualTo(HttpStatus.OK);
+ assertThat(row.getApprovedByUserId()).isEqualTo(3L);
+ var claimed = realService.claim("req-1", "claim-secret");
+ assertThat(claimed.outcome()).isEqualTo(ConnectRequestService.ClaimOutcome.CONFIRMED);
+ assertThat(claimed.teamId()).isEqualTo(1L);
+ assertThat(claimed.deviceId()).isNull();
+ assertThat(claimed.deviceSecret()).isNull();
+ org.mockito.Mockito.verifyNoInteractions(accountLinkService);
}
}
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.java
index 2db21bfb6c..a64eb897cb 100644
--- a/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/ConnectRequestServiceTest.java
@@ -179,16 +179,16 @@ class ConnectRequestServiceTest {
}
@Test
- void createReauth_pinsTheAccountAndTeamFromTheCredential() {
+ void createReauth_pinsTheTeamFromTheCredentialUntilItsCurrentOwnerApproves() {
ConnectRequestService.CreateResult result =
- service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, 7L, 42L);
+ service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, 7L);
assertThat(result.isRejected()).isFalse();
ArgumentCaptor<ConnectRequest> saved = ArgumentCaptor.forClass(ConnectRequest.class);
verify(repo).save(saved.capture());
assertThat(saved.getValue().getMode()).isEqualTo(ConnectRequest.Mode.REAUTH);
assertThat(saved.getValue().getTeamId()).isEqualTo(7L);
- assertThat(saved.getValue().getApprovedByUserId()).isEqualTo(42L);
+ assertThat(saved.getValue().getApprovedByUserId()).isNull();
assertThat(saved.getValue().getApprovedAt()).isNull();
}
@@ -196,7 +196,7 @@ class ConnectRequestServiceTest {
void createReauth_withoutAnAuthenticatedInstanceIsRefused() {
// The controller passes null when the offered device credential did not authenticate.
assertThat(
- service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, null, null)
+ service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, null)
.rejection())
.isEqualTo(CreateRejection.NOT_LINKED);
verify(repo, never()).save(any());
@@ -228,7 +228,7 @@ class ConnectRequestServiceTest {
}
@Test
- void approve_acceptsTheOriginalAccountInTheLinkedTeam() {
+ void approve_acceptsTheAuthenticatedOwnerInTheLinkedTeam() {
ConnectRequest row = reauthPinnedTo(7L);
when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));
@@ -236,20 +236,11 @@ class ConnectRequestServiceTest {
assertThat(row.getStatus()).isEqualTo(ConnectRequest.Status.APPROVED);
}
- @Test
- void createReauth_withoutAnOriginalLinkingUserFailsClosed() {
- assertThat(
- service.createReauth(null, CALLBACK, NONCE, CLAIM_SECRET, null, 7L, null)
- .rejection())
- .isEqualTo(CreateRejection.NOT_LINKED);
- verify(repo, never()).save(any());
- }
-
@ParameterizedTest
@CsvSource(
- value = {"7,43", "99,43", "NULL,42", "7,NULL"},
+ value = {"99,43", "NULL,42", "7,NULL"},
nullValues = "NULL")
- void approve_rejectsAnotherAccountOrMissingIdentity(Long teamId, Long userId) {
+ void approve_rejectsAnotherTeamOrMissingIdentity(Long teamId, Long userId) {
ConnectRequest row = reauthPinnedTo(7L);
when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));
@@ -263,12 +254,10 @@ class ConnectRequestServiceTest {
verifyNoInteractions(accountLinkService);
}
- @ParameterizedTest
- @ValueSource(booleans = {true, false})
- void approve_rejectsLegacyRenewalRequestsWithoutBothPins(boolean missingUser) {
+ @Test
+ void approve_rejectsRenewalRequestsWithoutAPinnedTeam() {
ConnectRequest row = reauthPinnedTo(7L);
- if (missingUser) row.setApprovedByUserId(null);
- else row.setTeamId(null);
+ row.setTeamId(null);
when(repo.findByRequestIdForUpdate("req")).thenReturn(Optional.of(row));
assertThat(service.approve("req", 7L, 42L).rejection())
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/OwnershipHandoverControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/OwnershipHandoverControllerTest.java
new file mode 100644
index 0000000000..bb174b2f33
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/OwnershipHandoverControllerTest.java
@@ -0,0 +1,74 @@
+package stirling.software.saas.accountlink;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.Optional;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.saas.service.SaasOwnershipHandoverService;
+import stirling.software.saas.util.AuthenticationUtils;
+
+class OwnershipHandoverControllerTest {
+ private final AccountLinkService links = mock(AccountLinkService.class);
+ private final SaasOwnershipHandoverService handovers = mock(SaasOwnershipHandoverService.class);
+ private final UserRepository users = mock(UserRepository.class);
+ private final Authentication auth = mock(Authentication.class);
+ private final OwnershipHandoverController controller =
+ new OwnershipHandoverController(links, handovers, users);
+ private final OwnershipHandoverController.Request request =
+ new OwnershipHandoverController.Request("[email protected]", 1L);
+
+ @Test
+ void candidateReadIsScopedToTheDeviceTeam() {
+ controller.candidates(new LinkedInstanceAuthenticationToken(4L, 9L));
+ verify(handovers).candidates(9L);
+ verifyNoInteractions(links, users);
+ }
+
+ @Test
+ void humanSessionCannotReadCandidatesThroughTheDeviceEndpoint() {
+ assertEquals(
+ 403,
+ assertThrows(ResponseStatusException.class, () -> controller.candidates(auth))
+ .getStatusCode()
+ .value());
+ verifyNoInteractions(handovers, links, users);
+ }
+
+ @Test
+ void humanSessionWithoutValidDeviceCredentialsCannotUseInstanceTransfer() {
+ when(links.resolveActiveInstance("device", "wrong-secret")).thenReturn(Optional.empty());
+ var error =
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ controller.change(
+ "transfer", "device", "wrong-secret", request, auth));
+ assertEquals(403, error.getStatusCode().value());
+ verifyNoInteractions(handovers, users);
+ }
+
+ @Test
+ void authenticatedDeviceSuppliesTeamAndStillRequiresTheHumanOwner() {
+ LinkedInstance instance = new LinkedInstance();
+ instance.setTeamId(9L);
+ User owner = new User();
+ owner.setId(1L);
+ when(links.resolveActiveInstance("device", "secret")).thenReturn(Optional.of(instance));
+ try (var authentication = mockStatic(AuthenticationUtils.class)) {
+ authentication
+ .when(() -> AuthenticationUtils.getCurrentUser(auth, users))
+ .thenReturn(owner);
+ controller.change("transfer", "device", "secret", request, auth);
+ }
+ verify(handovers)
+ .changeFromInstance(instance, "[email protected]", 1L, owner, "transfer", null);
+ verify(handovers, never()).change(anyLong(), anyString(), anyLong(), any(), anyString());
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/service/SaasOwnershipHandoverServiceTest.java b/app/saas/src/test/java/stirling/software/saas/service/SaasOwnershipHandoverServiceTest.java
new file mode 100644
index 0000000000..06d6cfab59
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/service/SaasOwnershipHandoverServiceTest.java
@@ -0,0 +1,396 @@
+package stirling.software.saas.service;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.time.LocalDateTime;
+import java.util.*;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.web.server.ResponseStatusException;
+
+import jakarta.persistence.EntityManager;
+
+import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.accountlink.CloudOwnershipStatus.State;
+import stirling.software.proprietary.model.*;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.*;
+import stirling.software.saas.accountlink.LinkedInstance;
+import stirling.software.saas.accountlink.LinkedInstanceRepository;
+import stirling.software.saas.payg.billing.*;
+import stirling.software.saas.repository.TeamInvitationRepository;
+
+class SaasOwnershipHandoverServiceTest {
+ private final TeamRepository teams = mock(TeamRepository.class);
+ private final TeamMembershipRepository memberships = mock(TeamMembershipRepository.class);
+ private final LinkedInstanceRepository instances = mock(LinkedInstanceRepository.class);
+ private final TeamBillingService billing = mock(TeamBillingService.class);
+ private final SaasTeamService invitations = mock(SaasTeamService.class);
+ private final SaasOwnershipService ownership = mock(SaasOwnershipService.class);
+ private final SaasTeamExtensionService extensions = mock(SaasTeamExtensionService.class);
+ private final EntityManager entities = mock(EntityManager.class);
+ private final TeamInvitationRepository pending = mock(TeamInvitationRepository.class);
+ private final SaasOwnershipHandoverService service =
+ new SaasOwnershipHandoverService(
+ teams,
+ memberships,
+ instances,
+ billing,
+ invitations,
+ ownership,
+ extensions,
+ entities,
+ pending);
+ private Team team;
+ private TeamMembership leader;
+ private TeamMembership target;
+
+ @Test
+ void missingCloudTeamHasAnAuthoritativeRecoveryReason() {
+ when(teams.findById(9L)).thenReturn(Optional.empty());
+ assertEquals(
+ "CLOUD_TEAM_MISSING",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.status(9L, "[email protected]"))
+ .getReason());
+ }
+
+ @BeforeEach
+ void setup() {
+ team = new Team();
+ team.setId(9L);
+ team.setName("Acme");
+ when(teams.findById(9L)).thenReturn(Optional.of(team));
+ when(teams.lockById(9L)).thenReturn(Optional.of(team));
+ leader = member(1L, "[email protected]", TeamRole.LEADER);
+ target = member(2L, "[email protected]", TeamRole.MEMBER);
+ when(memberships.findByTeamId(9L)).thenReturn(List.of(leader, target));
+ when(memberships.findByTeamIdAndUserId(9L, 1L)).thenReturn(Optional.of(leader));
+ when(instances.countByTeamIdAndRevokedAtIsNull(9L)).thenReturn(3L);
+ paid(false);
+ }
+
+ private TeamMembership member(Long id, String email, TeamRole role) {
+ User user = new User();
+ user.setId(id);
+ user.setEmail(email);
+ user.setTeam(team);
+ user.setEnabled(true);
+ TeamMembership row = new TeamMembership();
+ row.setTeam(team);
+ row.setUser(user);
+ row.setRole(role);
+ row.setAcceptedAt(LocalDateTime.now());
+ return row;
+ }
+
+ private void paid(boolean subscribed) {
+ when(billing.forTeam(9L))
+ .thenReturn(
+ new TeamBillingContext(
+ subscribed,
+ subscribed ? "sub_existing" : null,
+ null,
+ null,
+ 10,
+ 5,
+ null,
+ "usd",
+ null,
+ null,
+ null,
+ null));
+ }
+
+ @Test
+ void candidatesExcludeOwnerUnacceptedDisabledAndDepartedAccounts() {
+ var invited = member(3L, "[email protected]", TeamRole.MEMBER);
+ invited.setAcceptedAt(null);
+ var disabled = member(4L, "[email protected]", TeamRole.MEMBER);
+ disabled.getUser().setEnabled(false);
+ var departed = member(5L, "[email protected]", TeamRole.MEMBER);
+ departed.getUser().setTeam(null);
+ var missingEmail = member(6L, null, TeamRole.MEMBER);
+ when(memberships.findByTeamId(9L))
+ .thenReturn(List.of(leader, target, invited, disabled, departed, missingEmail));
+ var result = service.candidates(9L);
+ assertEquals(9L, result.teamId());
+ assertEquals(List.of(2L), result.members().stream().map(m -> m.id()).toList());
+ verifyNoInteractions(invitations, ownership);
+ }
+
+ @Test
+ void pinnedCloudIdentityRejectsReassignedEmail() {
+ assertEquals(
+ "CLOUD_TARGET_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () -> service.status(9L, "[email protected]", 99L))
+ .getReason());
+ assertEquals(2L, service.status(9L, "[email protected]", 2L).targetUserId());
+ var instance = new LinkedInstance();
+ instance.setTeamId(9L);
+ assertEquals(
+ "CLOUD_TARGET_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.changeFromInstance(
+ instance,
+ 1L,
+ leader.getUser(),
+ "transfer",
+ 99L))
+ .getReason());
+ verifyNoInteractions(ownership, invitations);
+ }
+
+ @ParameterizedTest(name = "paid={0}, account={1}, state={2}")
+ @CsvSource({
+ "false,no-account,NEEDS_MEMBERSHIP",
+ "false,same-team,READY",
+ "false,different-team,NEEDS_MEMBERSHIP",
+ "true,no-account,NEEDS_MEMBERSHIP",
+ "true,same-team,READY",
+ "true,different-team,NEEDS_MEMBERSHIP"
+ })
+ void readinessForAllSixLinkedScenarios(boolean subscribed, String account, State expected) {
+ paid(subscribed);
+ if (account.equals("no-account"))
+ when(memberships.findByTeamId(9L)).thenReturn(List.of(leader));
+ if (account.equals("different-team")) {
+ Team other = new Team();
+ other.setId(99L);
+ target.getUser().setTeam(other);
+ }
+ var result = service.status(9L, " [email protected] ");
+ assertEquals(expected, result.state());
+ assertEquals(subscribed, result.subscribed());
+ assertEquals(3L, result.linkedInstances());
+ verifyNoInteractions(ownership, invitations);
+ }
+
+ @Test
+ void transferUsesExistingTeamAndDoesNotMutateBillingOrLinks() {
+ LinkedInstance instance = new LinkedInstance();
+ instance.setTeamId(9L);
+ doAnswer(
+ invocation -> {
+ leader.setRole(TeamRole.MEMBER);
+ target.setRole(TeamRole.LEADER);
+ return null;
+ })
+ .when(ownership)
+ .transferFromInstance(9L, 2L, leader.getUser(), instance);
+ assertEquals(
+ State.TRANSFERRED,
+ service.changeFromInstance(
+ instance, "[email protected]", 1L, leader.getUser(), "transfer")
+ .state());
+ verify(ownership).transferFromInstance(9L, 2L, leader.getUser(), instance);
+ verify(ownership, never()).transfer(anyLong(), anyLong(), any());
+ verify(billing, atLeastOnce()).forTeam(9L);
+ verify(instances, atLeastOnce()).countByTeamIdAndRevokedAtIsNull(9L);
+ verifyNoMoreInteractions(billing, instances);
+ verifyNoInteractions(invitations);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void coLeaderTransferMustDemoteOtherLeadersBeforeReportingCompletion(boolean fromInstance) {
+ target.setRole(TeamRole.LEADER);
+ var otherLeader = member(3L, "[email protected]", TeamRole.LEADER);
+ when(memberships.findByTeamId(9L)).thenReturn(List.of(leader, target, otherLeader));
+ assertEquals(State.READY, service.status(9L, "[email protected]", 2L).state());
+ LinkedInstance instance = new LinkedInstance();
+ instance.setTeamId(9L);
+ var transfer =
+ doAnswer(
+ invocation -> {
+ leader.setRole(TeamRole.MEMBER);
+ otherLeader.setRole(TeamRole.MEMBER);
+ return null;
+ })
+ .when(ownership);
+ if (fromInstance) transfer.transferFromInstance(9L, 2L, leader.getUser(), instance);
+ else transfer.transfer(9L, 2L, leader.getUser());
+
+ var result =
+ fromInstance
+ ? service.changeFromInstance(
+ instance, "[email protected]", 1L, leader.getUser(), "transfer", 2L)
+ : service.change(9L, "[email protected]", 1L, leader.getUser(), "transfer");
+
+ assertEquals(State.TRANSFERRED, result.state());
+ assertEquals(2L, result.leaderUserId());
+ if (fromInstance)
+ verify(ownership).transferFromInstance(9L, 2L, leader.getUser(), instance);
+ else verify(ownership).transfer(9L, 2L, leader.getUser());
+ verifyNoMoreInteractions(ownership);
+ }
+
+ @Test
+ void cloudEntryPointCannotOptIntoInstanceTransfer() {
+ doThrow(
+ new ResponseStatusException(
+ org.springframework.http.HttpStatus.CONFLICT,
+ "START_TRANSFER_FROM_INSTANCE"))
+ .when(ownership)
+ .transfer(9L, 2L, leader.getUser());
+ assertEquals(
+ "START_TRANSFER_FROM_INSTANCE",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.change(
+ 9L,
+ 1L,
+ leader.getUser(),
+ "transfer"))
+ .getReason());
+ verify(ownership, never()).transferFromInstance(anyLong(), anyLong(), any(), any());
+ }
+
+ @Test
+ void memberCannotTransferAndStaleLeaderCannotConfirm() {
+ when(memberships.findByTeamIdAndUserId(9L, 2L)).thenReturn(Optional.of(target));
+ assertEquals(
+ "CLOUD_OWNER_REQUIRED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.change(
+ 9L,
+ 1L,
+ target.getUser(),
+ "transfer"))
+ .getReason());
+ assertEquals(
+ "CLOUD_OWNER_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.change(
+ 9L,
+ 99L,
+ leader.getUser(),
+ "transfer"))
+ .getReason());
+ verifyNoInteractions(ownership);
+ }
+
+ @Test
+ void disabledOrUnacceptedRecipientCannotTakeOwnership() {
+ target.getUser().setEnabled(false);
+ assertEquals(State.NEEDS_MEMBERSHIP, service.status(9L, "[email protected]").state());
+ target.getUser().setEnabled(true);
+ target.setAcceptedAt(null);
+ assertEquals(
+ "MEMBERSHIP_REQUIRED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.change(
+ 9L,
+ 1L,
+ leader.getUser(),
+ "transfer"))
+ .getReason());
+ verifyNoInteractions(ownership);
+ }
+
+ @Test
+ void retainedLeaderRemainsTransferredAfterSwitchingActiveTeams() {
+ Team other = new Team();
+ other.setId(10L);
+ target.getUser().setTeam(other);
+ assertEquals(State.NEEDS_MEMBERSHIP, service.status(9L, "[email protected]").state());
+ target.setRole(TeamRole.LEADER);
+ leader.setRole(TeamRole.MEMBER);
+ when(memberships.findByTeamIdAndUserId(9L, 2L)).thenReturn(Optional.of(target));
+ assertEquals(State.TRANSFERRED, service.status(9L, "[email protected]", 2L).state());
+ assertEquals(
+ State.TRANSFERRED,
+ service.change(9L, "[email protected]", 2L, target.getUser(), "transfer").state());
+ verifyNoInteractions(ownership, invitations);
+ target.getUser().setTeam(null);
+ assertEquals(State.NEEDS_MEMBERSHIP, service.status(9L, "[email protected]").state());
+ }
+
+ @Test
+ void retainedLeaderStillRequiresAcceptedEnabledMembership() {
+ target.setRole(TeamRole.LEADER);
+ target.getUser().setEnabled(false);
+ assertEquals(State.NEEDS_MEMBERSHIP, service.status(9L, "[email protected]").state());
+ target.getUser().setEnabled(true);
+ target.setAcceptedAt(null);
+ assertEquals(State.NEEDS_MEMBERSHIP, service.status(9L, "[email protected]").state());
+ }
+
+ @Test
+ void personalTeamCannotTransfer() {
+ when(extensions.isPersonal(team)).thenReturn(true);
+ assertEquals(
+ "PERSONAL_TEAM",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.change(
+ 9L,
+ 1L,
+ leader.getUser(),
+ "transfer"))
+ .getReason());
+ verifyNoInteractions(ownership);
+ }
+
+ @Test
+ void invitationUsesExistingAcceptanceRulesAndDoesNotTransfer() {
+ when(memberships.findByTeamId(9L)).thenReturn(List.of(leader));
+ service.change(9L, "[email protected]", 1L, leader.getUser(), "invite");
+ verify(invitations).inviteUserToTeam(9L, "[email protected]", leader.getUser());
+ verifyNoInteractions(ownership);
+ }
+
+ @Test
+ void pendingInvitationCanBeRetriedWithoutSendingDuplicate() {
+ when(memberships.findByTeamId(9L)).thenReturn(List.of(leader));
+ when(pending.existsPendingInvitationByTeamIdAndEmail(9L, "[email protected]"))
+ .thenReturn(true);
+ service.change(9L, "[email protected]", 1L, leader.getUser(), "invite");
+ verifyNoInteractions(invitations, ownership);
+ }
+
+ @Test
+ void paidAccountOrSeatRejectionKeepsCurrentOwner() {
+ when(memberships.findByTeamId(9L)).thenReturn(List.of(leader));
+ when(invitations.inviteUserToTeam(9L, "[email protected]", leader.getUser()))
+ .thenThrow(new IllegalArgumentException("paid account"));
+ assertEquals(
+ "INVITATION_BLOCKED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ service.change(
+ 9L,
+ 1L,
+ leader.getUser(),
+ "invite"))
+ .getReason());
+ assertTrue(leader.isLeader());
+ verifyNoInteractions(ownership);
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/service/SaasOwnershipServiceTest.java b/app/saas/src/test/java/stirling/software/saas/service/SaasOwnershipServiceTest.java
index 37627e6d9e..a79a5d3d37 100644
--- a/app/saas/src/test/java/stirling/software/saas/service/SaasOwnershipServiceTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/service/SaasOwnershipServiceTest.java
@@ -24,6 +24,8 @@ import stirling.software.proprietary.security.database.repository.UserRepository
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.*;
import stirling.software.proprietary.service.AuditService;
+import stirling.software.saas.accountlink.LinkedInstance;
+import stirling.software.saas.accountlink.LinkedInstanceRepository;
@DataJpaTest(
properties = {
@@ -40,12 +42,13 @@ class SaasOwnershipServiceTest {
@Autowired TeamRepository teams;
@Autowired TeamMembershipRepository memberships;
@Autowired SaasTeamExtensionService extensions;
+ @Autowired LinkedInstanceRepository instances;
private Team team;
@BeforeEach
void setup() {
- reset(extensions);
+ reset(extensions, instances);
memberships.deleteAll();
users.deleteAll();
teams.deleteAll();
@@ -102,6 +105,96 @@ class SaasOwnershipServiceTest {
assertEquals(1, memberships.countByTeamIdAndRole(team.getId(), TeamRole.LEADER));
}
+ @Test
+ void linkedTeamCannotTransferThroughCloudOrLegacyEntryPoint() {
+ User first = member("first", TeamRole.LEADER);
+ User target = member("successor", TeamRole.MEMBER);
+ when(instances.countByTeamIdAndRevokedAtIsNull(team.getId())).thenReturn(1L);
+ var error =
+ assertThrows(
+ ResponseStatusException.class,
+ () -> ownership.transfer(team.getId(), target.getId(), first));
+ assertEquals(409, error.getStatusCode().value());
+ assertEquals("START_TRANSFER_FROM_INSTANCE", error.getReason());
+ assertTrue(
+ memberships
+ .findByTeamIdAndUserId(team.getId(), first.getId())
+ .orElseThrow()
+ .isLeader());
+ assertFalse(
+ memberships
+ .findByTeamIdAndUserId(team.getId(), target.getId())
+ .orElseThrow()
+ .isLeader());
+ }
+
+ @Test
+ void authenticatedInstanceCanTransferItsLinkedTeam() {
+ User first = member("first", TeamRole.LEADER);
+ User target = member("successor", TeamRole.MEMBER);
+ LinkedInstance instance = new LinkedInstance();
+ instance.setDeviceId("device");
+ instance.setTeamId(team.getId());
+ when(instances.findByDeviceIdAndRevokedAtIsNull("device"))
+ .thenReturn(Optional.of(instance));
+ ownership.transferFromInstance(team.getId(), target.getId(), first, instance);
+ assertFalse(
+ memberships
+ .findByTeamIdAndUserId(team.getId(), first.getId())
+ .orElseThrow()
+ .isLeader());
+ assertTrue(
+ memberships
+ .findByTeamIdAndUserId(team.getId(), target.getId())
+ .orElseThrow()
+ .isLeader());
+ }
+
+ @Test
+ void revokedOrDifferentTeamInstanceCannotAuthorizeTransfer() {
+ User first = member("first", TeamRole.LEADER);
+ User target = member("successor", TeamRole.MEMBER);
+ LinkedInstance instance = new LinkedInstance();
+ instance.setDeviceId("device");
+ instance.setTeamId(team.getId());
+ assertEquals(
+ "LINK_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ ownership.transferFromInstance(
+ team.getId(), target.getId(), first, instance))
+ .getReason());
+ instance.setTeamId(-1L);
+ when(instances.findByDeviceIdAndRevokedAtIsNull("device"))
+ .thenReturn(Optional.of(instance));
+ assertEquals(
+ "LINK_CHANGED",
+ assertThrows(
+ ResponseStatusException.class,
+ () ->
+ ownership.transferFromInstance(
+ team.getId(), target.getId(), first, instance))
+ .getReason());
+ assertTrue(
+ memberships
+ .findByTeamIdAndUserId(team.getId(), first.getId())
+ .orElseThrow()
+ .isLeader());
+ }
+
+ @Test
+ void linkedOwnerlessTeamCanStillRecoverOwnership() {
+ User target = member("successor", TeamRole.MEMBER);
+ when(instances.countByTeamIdAndRevokedAtIsNull(team.getId())).thenReturn(1L);
+ ownership.transfer(team.getId(), target.getId(), target);
+ assertTrue(
+ memberships
+ .findByTeamIdAndUserId(team.getId(), target.getId())
+ .orElseThrow()
+ .isLeader());
+ }
+
@Test
void rejectsPersonalTeamAndNonMember() {
User first = member("first", TeamRole.LEADER);
@@ -175,6 +268,11 @@ class SaasOwnershipServiceTest {
"stirling.software.proprietary.security.repository"
})
static class TestApp {
+ @Bean
+ LinkedInstanceRepository instances() {
+ return mock(LinkedInstanceRepository.class);
+ }
+
@Bean
SaasTeamExtensionService extensions() {
return mock(SaasTeamExtensionService.class);
diff --git a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java
index f2c2019ccc..4267901cae 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
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -742,6 +743,34 @@ class SaasTeamServiceTest {
verify(userRepository).updateUserTeamId(5L, 100L);
}
+ @Test
+ @DisplayName("successor joining another team keeps a solo transferred team's ownership")
+ void successorKeepsTransferredTeamAfterFounderRemoved() {
+ User bob = user(5L, "[email protected]", "bob");
+ Team transferred = team(300L, "Transferred organisation");
+ Team next = team(100L, "Next organisation");
+ TeamMembership ownership = membership(transferred, bob, TeamRole.LEADER);
+ TeamInvitation invite =
+ pendingInvitation(next, user(1L, "[email protected]", "alice"), "[email protected]");
+ when(userRepository.findById(5L)).thenReturn(Optional.of(bob));
+ when(invitationRepository.findByInvitationToken("tok-123"))
+ .thenReturn(Optional.of(invite));
+ when(saasTeamExtensionService.hasAvailableSeats(next)).thenReturn(true);
+ when(saasUserExtensionService.getHomeTeamId(bob)).thenReturn(200L);
+ when(membershipRepository.findByUserId(5L)).thenReturn(List.of(ownership));
+ when(membershipRepository.countByTeamIdAndRole(300L, TeamRole.LEADER)).thenReturn(1L);
+ when(saasTeamExtensionsRepository.incrementSeatsUsed(100L)).thenReturn(1);
+
+ service.acceptInvitation("tok-123", bob);
+
+ verify(membershipRepository, never()).delete(ownership);
+ verify(saasTeamExtensionsRepository, never()).decrementSeatsUsed(300L);
+ verify(teamRepository, never()).delete(any());
+ verify(userRepository).updateUserTeamId(5L, 100L);
+ assertThat(ownership.getRole()).isEqualTo(TeamRole.LEADER);
+ assertThat(invite.getStatus()).isEqualTo(InvitationStatus.ACCEPTED);
+ }
+
@Test
@DisplayName("parks the home team (keeps it) and joins the new team, incrementing seats")
void success_parksHomeTeamAndJoins() {
@@ -835,7 +864,6 @@ class SaasTeamServiceTest {
when(saasTeamExtensionService.hasAvailableSeats(newTeam)).thenReturn(true);
when(membershipRepository.findByUserId(5L)).thenReturn(List.of(sharedMembership));
// Shared team: sole leader, but >1 member - leaving would orphan the other member.
- when(membershipRepository.countByTeamId(300L)).thenReturn(2L);
when(membershipRepository.countByTeamIdAndRole(300L, TeamRole.LEADER)).thenReturn(1L);
when(saasTeamExtensionsRepository.incrementSeatsUsed(100L)).thenReturn(1);
@@ -1048,6 +1076,33 @@ class SaasTeamServiceTest {
verify(teamRepository, never()).delete(any());
}
+ @Test
+ void removingFormerFounderCreatesFreshHomeWithoutRestoringMembership() {
+ User bob = user(1L, "[email protected]", "bob");
+ User alice = user(2L, "[email protected]", "alice");
+ Team transferred = team(teamId, "Transferred team");
+ TeamMembership bobOwner = membership(transferred, bob, TeamRole.LEADER);
+ TeamMembership aliceMember = membership(transferred, alice, TeamRole.MEMBER);
+ when(membershipRepository.findByTeamIdAndUserId(teamId, 1L))
+ .thenReturn(Optional.of(bobOwner));
+ when(membershipRepository.findByTeamIdAndRole(teamId, TeamRole.LEADER))
+ .thenReturn(List.of(bobOwner));
+ when(membershipRepository.findByTeamIdAndUserId(teamId, 2L))
+ .thenReturn(Optional.of(aliceMember))
+ .thenReturn(Optional.empty());
+ when(saasUserExtensionService.getHomeTeamId(alice)).thenReturn(teamId);
+ stubCreatePersonalTeam(alice, 500L);
+
+ service.removeTeamMember(teamId, 2L, bob);
+
+ verify(membershipRepository).delete(aliceMember);
+ verify(saasUserExtensionService).setHomeTeamId(alice, 500L);
+ verify(membershipRepository, never())
+ .save(argThat(m -> m.getTeam().getId().equals(teamId)));
+ assertThat(alice.getTeam().getId()).isEqualTo(500L);
+ assertThat(bobOwner.getRole()).isEqualTo(TeamRole.LEADER);
+ }
+
@Test
@DisplayName("keeps a non-empty team after removing a member")
void success_keepsNonEmptyTeam() {
@@ -1460,8 +1515,8 @@ class SaasTeamServiceTest {
service.acceptInvitation(TOKEN, joiner);
- // Guard let the move through: the old membership was left and the user re-pointed.
- verify(membershipRepository).delete(oldMembership);
+ // Joining changes the active team while retaining ownership of the previous team.
+ verify(membershipRepository, never()).delete(oldMembership);
verify(userRepository).updateUserTeamId(USER_ID, NEW_TEAM_ID);
verify(invitationRepository).save(invitation);
assertThat(invitation.getStatus()).isEqualTo(InvitationStatus.ACCEPTED);
diff --git a/frontend/editor/.env.desktop b/frontend/editor/.env.desktop
index 1cddad78e9..62bf6dece5 100644
--- a/frontend/editor/.env.desktop
+++ b/frontend/editor/.env.desktop
@@ -11,6 +11,7 @@ VITE_DESKTOP_BACKEND_URL=
# Desktop auth integration
VITE_SAAS_SERVER_URL=https://auth.stirling.com
VITE_SAAS_BACKEND_API_URL=https://api2.stirling.com
+VITE_SAAS_FRONTEND_URL=https://stirling.com/app
# Dev only: set to true to mimic an expired access token (no valid JWT for API/auth checks).
# Production builds ignore this. Restart tauri-dev after changing.
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index dfe655eba9..83ded88d38 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -3959,10 +3959,10 @@ title = "Request not valid"
[connect.renewal]
approve = "Renew sign-in"
+currentOwnerRequired = "Sign in as the current owner of the linked cloud team to renew this server's sign-in. If ownership was transferred, use the new owner's account."
failed = "Your sign-in could not be renewed. Try again, or dismiss this page and start again from your server."
lead = "This server is already linked to your account. Renew your sign-in to return to billing and usage on your server."
title = "Renew your server sign-in"
-wrongAccount = "This account cannot renew this server's sign-in. Switch to the account originally used to link the server. That account must still own the linked team."
[convert]
autoRotate = "Auto Rotate"
@@ -4202,6 +4202,12 @@ title = "Settings Opened"
message = "Stirling PDF is now your default PDF editor"
title = "Default App Set"
+[desktopBilling]
+description = "Manage usage and billing in your browser. Sign in with the same Stirling account you use here."
+open = "Open Usage & Billing in browser"
+openFailed = "Could not open Usage & Billing. Check your connection and try again."
+selfHostedDescription = "Manage usage and billing on your connected server in your browser. Sign in with your server owner account."
+
[desktopFileLink]
saveAs = "Save as…"
useDiskVersion = "Use disk version"
@@ -6276,6 +6282,66 @@ title = "Overlay Files"
text = "Foreground places the overlay on top of the page. Background places it behind."
title = "Overlay Position"
+[ownership]
+acceptInvite = "They can create an account or sign in, then accept the invitation."
+accessUpdated = "Their owner access is ready."
+accountLinkDisabled = "This server still has a cloud link, but account linking is turned off. Ask the server operator to enable account linking, then resume this transfer or unlink the server in settings."
+anotherTeam = "Already on another team?"
+billing = "The subscription, wallet, payment method and existing licenses stay in place. Billing contact details do not change automatically."
+billingDetails = "Billing details"
+billingUnchanged = "Subscription and billing stay in place"
+bothDone = "Server and cloud ownership are now aligned."
+cancel = "Cancel transfer"
+check = "Check again"
+checkAccount = "Check account"
+chooseEmail = "Choose their account in {{team}}, or enter an email to invite them."
+close = "Close transfer dialog"
+cloudAccount = "Stirling account"
+cloudScopeStyled = "<user>{{name}}</user> will manage {{team}}, its members and billing."
+cloudTargetChanged = "Choose another cloud member. This account is no longer eligible for the handover."
+confirm = "I understand the access and ownership changes."
+done = "Ownership transferred"
+error = "We couldn't complete this step. Check the recipient is active and the server is connected, then check again. A pending transfer can be resumed here."
+finish = "Finish server transfer"
+inProgress = "Another recipient already has a pending transfer. Close this dialog and resume it from Users."
+instances = "This team has {{count}} linked servers. Their cloud billing stays with this team; other servers' local owners do not change."
+invitationSent = "Invitation sent"
+invite = "Send invitation"
+inviteAddress = "Invite <account>{{email}}</account> to {{team}}."
+inviteBlocked = "The invitation could not be sent. Check available team seats and whether the recipient already has a paid subscription."
+linkChanged = "The server's cloud link changed. Ask the server operator to restore the original link before resuming."
+linkedServerCount = "{{count}} linked servers"
+linkRevoked = "This server's cloud link is no longer valid. Cancel the transfer, then reconnect your Stirling account in settings. Ownership will not change."
+localScope = "They will own this server and manage billing and cloud connections. You keep administrator access, but lose access to those settings."
+membershipDetails = "Team membership details"
+membershipFirst = "They must join the team before you can confirm the transfer."
+membershipRequired = "The recipient must join this cloud team before ownership can transfer. Ask them to accept their invitation, then check again."
+newOwnerLabel = "New owner"
+newOwnerStyled = "<user>{{name}}</user> is now the owner."
+noEmailMatches = "No matching members. Enter an email to invite."
+otherTeam = "If they belong to another team, accepting may move their account. A paid account or ownership of another team may need resolving first. We won't move their subscription or merge teams."
+ownerChanged = "Cloud ownership changed after this transfer started. Cancel this transfer and start again with the current cloud owner."
+ownerRequired = "Sign in as the current cloud team owner, then try this step again."
+partialError = "Cloud ownership has transferred. Finish the server transfer to keep both owners aligned."
+partialTargetChanged = "Restore the selected server user's access and original account details, then finish the server transfer. Cloud ownership has already transferred."
+pending = "An ownership transfer to {{name}} is pending."
+personalTeam = "Personal teams cannot transfer ownership."
+prepareHelp = "The recipient must have completed their first server login. You can retry here, or return to Users to choose someone else."
+resume = "Resume transfer"
+searchEmail = "Search or enter an email"
+serverAccount = "Server account"
+serverDetails = "Linked server details"
+signIn = "Sign in to cloud"
+startFromInstanceBody = "This team has linked servers. On the self-hosted server, open Settings → Users and change the recipient's role to Org Owner. That flow transfers cloud ownership before completing the server transfer."
+startFromInstanceTitle = "Start from your self-hosted server"
+stayOwner = "You stay the owner until transfer."
+targetChanged = "The recipient's account changed. Restore their access or cancel this transfer and choose them again."
+title = "Transfer ownership"
+transfer = "Transfer ownership"
+waitingForEmail = "Waiting for {{email}} to join {{team}}."
+working = "Checking and updating ownership..."
+yourCloudAccess = "You'll become a team member and lose owner access."
+
[pageEdit]
deselectAll = "None"
selectAll = "Check All"
@@ -7304,12 +7370,6 @@ upToFiveUsers = "Up to 5 users"
usageTrackingPrometheus = "Usage tracking & Prometheus"
usersIncluded = "100 users included"
-[plan.licenseWarning]
-body = "You have {{total}} users but the free tier only supports {{limit}}. Upgrade to keep Stirling PDF running smoothly."
-cta = "See plans"
-overLimit = "more than {{limit}}"
-title = "Free self-hosted limit reached"
-
[plan.period]
month = "month"
@@ -7437,6 +7497,9 @@ pdfa-1 = "PDF/A-1b"
pdfa-2b = "PDF/A-2b"
pdfa-3b = "PDF/A-3b"
+[portal.accountLink]
+ownerRequired = "Only the org owner can link or unlink this server."
+
[portal.accountLink.card]
billingNote = "This server shares your team’s processing allowance in Stirling Cloud."
connectDescription = "Connect this server to use your team’s processing allowance in Stirling Cloud."
@@ -7558,6 +7621,7 @@ identity = "Stirling account"
linkTitle = "Connect your Stirling account"
noAuthorizeUrl = "Stirling did not return somewhere to continue. Try again in a moment."
startFailed = "Could not reach Stirling to start the connection. Check this server's outbound network access, then try again."
+transferPending = "An ownership transfer is pending. Go to Settings → Users to finish or cancel it, then try linking again."
[portal.accountLink.modal.loginNotConfigured]
after = "so this server can finish the connection when you come back."
@@ -12252,6 +12316,7 @@ confirmCancelInvite = "Are you sure you want to cancel this invitation?"
confirmLeave = "Are you sure you want to leave this team?"
confirmLeaveLeader = "As a team leader, leaving will remove you from the team. Are you sure?"
confirmRemove = "Are you sure you want to remove this member?"
+currentUnavailable = "We couldn't identify your current team. Try again, or contact support if this continues."
editName = "Edit team name"
inviteCancelled = "Invitation canceled"
inviteError = "Failed to send invitation"
@@ -12277,10 +12342,8 @@ renameCancel = "Cancel rename"
renameError = "Failed to rename team"
renameSubmit = "Save team name"
renameSuccess = "Team renamed successfully"
-transferBody = "Make {{email}} the team owner? They will control team membership and organization billing settings. You will become a member. The team’s subscription and wallet stay with the team."
transferError = "Ownership could not be transferred. Refresh the team and try again."
transferSuccess = "Team ownership transferred. Your role is now member."
-transferTitle = "Transfer team ownership"
[team.invitationBanner]
acceptButton = "Accept"
@@ -12576,7 +12639,6 @@ removeTeam = "Remove from team"
rename = "Rename team"
resetPw = "Reset password"
suspend = "Suspend"
-transferOwnership = "Transfer ownership"
unlock = "Unlock account"
[users.activity]
@@ -12616,8 +12678,6 @@ disableMfaTitle = "Reset MFA"
removeBody = "Permanently remove {{name}} from the organization? This cannot be undone."
removeTeamBody = "Remove {{name}} from the team? They keep their account but lose access to this team's resources."
removeTitle = "Remove member"
-transferOwnershipBody = "Make {{name}} the organization owner? They will become an admin. You will remain an admin but lose ownership. Only the new owner or the server operator can transfer it back."
-transferOwnershipTitle = "Transfer organization ownership"
[users.empty]
description = "Invite your team to start collaborating."
diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx
index bf6c56793d..d5684f3c39 100644
--- a/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx
+++ b/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx
@@ -8,68 +8,27 @@ import {
Table,
Badge,
Menu,
- Modal,
} from "@mantine/core";
import { Button } from "@app/ui/Button";
import { ActionIcon } from "@app/ui/ActionIcon";
import { StatusBadge } from "@app/ui/StatusBadge";
import { useTranslation } from "react-i18next";
+import { useTeamAuth } from "@app/auth/teamSession";
import {
useSaaSTeam,
type TeamInvitation,
type TeamMember,
} from "@app/contexts/SaaSTeamContext";
import { Icon } from "@app/ui/Icon";
-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
+import {
+ OwnershipTransferModal,
+ type CloudOwnershipStatus,
+} from "@app/components/shared/ownership/OwnershipTransferModal";
import apiClient from "@app/services/apiClient";
+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
-interface TransferOwnershipModalProps {
- targetEmail: string | null;
- error: string | null;
- transferring: boolean;
- onCancel: () => void;
- onConfirm: () => void;
-}
-
-function TransferOwnershipModal({
- targetEmail,
- error,
- transferring,
- onCancel,
- onConfirm,
-}: TransferOwnershipModalProps) {
- const { t } = useTranslation();
- return (
- <Modal
- opened={targetEmail !== null}
- onClose={onCancel}
- title={t("team.transferTitle", "Transfer team ownership")}
- zIndex={Z_INDEX_OVER_CONFIG_MODAL + 1}
- >
- <Stack>
- {error && <Alert color="red">{error}</Alert>}
- <Text>
- {t(
- "team.transferBody",
- "Make {{email}} the team owner? They will control team membership and organization billing settings. You will become a member. The team's subscription and wallet stay with the team.",
- { email: targetEmail ?? undefined },
- )}
- </Text>
- <Group justify="flex-end">
- <Button variant="tertiary" disabled={transferring} onClick={onCancel}>
- {t("common.cancel", "Cancel")}
- </Button>
- <Button accent="danger" disabled={transferring} onClick={onConfirm}>
- {t("team.makeOwner", "Make owner")}
- </Button>
- </Group>
- </Stack>
- </Modal>
- );
-}
-
interface NoOwnerAlertProps {
show: boolean;
busy: boolean;
@@ -581,8 +540,10 @@ function TeamMembersTable(props: TeamMembersTableProps) {
const TeamSection: React.FC = () => {
const { t } = useTranslation();
+ const { refreshAfterMembershipChange } = useTeamAuth();
const {
currentTeam,
+ loading,
teamMembers,
teamInvitations,
isTeamLeader,
@@ -590,7 +551,6 @@ const TeamSection: React.FC = () => {
inviteUser,
cancelInvitation,
removeMember,
- transferLeadership,
claimLeadership,
leaveTeam,
refreshTeams,
@@ -775,31 +735,6 @@ const TeamSection: React.FC = () => {
}
};
- const handleConfirmTransfer = async () => {
- if (!transferTarget) return;
- setTransferring(true);
- setError(null);
- try {
- await transferLeadership(transferTarget.id);
- setTransferTarget(null);
- setSuccess(
- t(
- "team.transferSuccess",
- "Team ownership transferred. Your role is now member.",
- ),
- );
- } catch {
- setError(
- t(
- "team.transferError",
- "Ownership could not be transferred. Refresh the team and try again.",
- ),
- );
- } finally {
- setTransferring(false);
- }
- };
-
const handleClaimOwnership = async () => {
setTransferring(true);
try {
@@ -820,7 +755,21 @@ const TeamSection: React.FC = () => {
if (!currentTeam) {
return (
<Alert color="gray">
- <Text>{t("team.loading", "Loading team information...")}</Text>
+ {loading ? (
+ <Text>{t("team.loading", "Loading team information...")}</Text>
+ ) : (
+ <>
+ <Text>
+ {t(
+ "team.currentUnavailable",
+ "We couldn't identify your current team. Try again, or contact support if this continues.",
+ )}
+ </Text>
+ <Button onClick={() => void refreshTeams()}>
+ {t("common.retry", "Try again")}
+ </Button>
+ </>
+ )}
</Alert>
);
}
@@ -829,13 +778,49 @@ const TeamSection: React.FC = () => {
return (
<Stack gap="lg">
- <TransferOwnershipModal
- targetEmail={transferTarget?.email ?? null}
- error={error}
- transferring={transferring}
- onCancel={() => !transferring && setTransferTarget(null)}
- onConfirm={handleConfirmTransfer}
- />
+ {transferTarget && (
+ <OwnershipTransferModal
+ key={transferTarget.id}
+ adapter={{
+ local: false,
+ prepare: async () => ({
+ targetId: transferTarget.id,
+ targetName: transferTarget.email,
+ targetEmail: transferTarget.email,
+ cloud: (
+ await apiClient.post<CloudOwnershipStatus>(
+ `/api/v1/team/${currentTeam.teamId}/ownership/status`,
+ { email: transferTarget.email },
+ )
+ ).data,
+ }),
+ transferCloud: async (state) => {
+ await apiClient.post(
+ `/api/v1/team/${state.cloud!.teamId}/ownership/transfer`,
+ {
+ email: transferTarget.email,
+ expectedLeaderId: state.cloud!.leaderUserId,
+ },
+ );
+ return {
+ ...state,
+ cloud: { ...state.cloud!, state: "TRANSFERRED" },
+ };
+ },
+ }}
+ onClose={() => setTransferTarget(null)}
+ onTransferred={() => {
+ setSuccess(
+ t(
+ "team.transferSuccess",
+ "Team ownership transferred. Your role is now member.",
+ ),
+ );
+ void refreshTeams();
+ void refreshAfterMembershipChange();
+ }}
+ />
+ )}
<NoOwnerAlert
show={
diff --git a/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx b/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx
index c50d0bcee9..9f01eebcb1 100644
--- a/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx
+++ b/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx
@@ -20,6 +20,7 @@ import { useTeamAuth } from "@app/auth/teamSession";
*/
interface Team {
+ current?: boolean;
teamId: number;
name: string;
teamType: string;
@@ -64,7 +65,10 @@ interface SaaSTeamContextType {
rejectInvitation: (token: string) => Promise<void>;
cancelInvitation: (invitationId: number) => Promise<void>;
removeMember: (memberId: number) => Promise<void>;
- transferLeadership: (memberId: number) => Promise<void>;
+ transferLeadership: (
+ email: string,
+ expectedLeaderId: number | null,
+ ) => Promise<void>;
claimLeadership: () => Promise<void>;
leaveTeam: () => Promise<void>;
refreshTeams: () => Promise<void>;
@@ -104,19 +108,22 @@ export function SaaSTeamProvider({ children }: { children: ReactNode }) {
const fetchMyTeams = useCallback(async () => {
if (!canUseTeams) return null;
-
+ setLoading(true);
try {
const response = await apiClient.get<Team[]>("/api/v1/team/my", {
suppressErrorToast: true,
});
setTeams(response.data);
- const activeTeam = response.data[0];
+ const activeTeam = response.data.find((team) => team.current);
setCurrentTeam(activeTeam || null);
return activeTeam || null;
} catch (error) {
console.error("[SaaSTeamContext] Failed to fetch teams:", error);
+ // A failed background poll must not unmount an in-progress transfer or its receipt.
return null;
+ } finally {
+ setLoading(false);
}
}, [canUseTeams]);
@@ -196,7 +203,6 @@ export function SaaSTeamProvider({ children }: { children: ReactNode }) {
setTeamMembers([]);
setTeamInvitations([]);
}
- setLoading(false);
}, [currentTeam, fetchTeamMembers, fetchTeamInvitations]);
const inviteUser = async (email: string) => {
@@ -264,10 +270,14 @@ export function SaaSTeamProvider({ children }: { children: ReactNode }) {
await refreshAfterMembershipChange();
};
- const transferLeadership = async (memberId: number) => {
+ const transferLeadership = async (
+ email: string,
+ expectedLeaderId: number | null,
+ ) => {
if (!currentTeam) throw new Error("No current team");
await apiClient.post(
- `/api/v1/team/${currentTeam.teamId}/members/${memberId}/transfer-leadership`,
+ `/api/v1/team/${currentTeam.teamId}/ownership/transfer`,
+ { email, expectedLeaderId },
);
await refreshTeams();
await fetchTeamMembers(currentTeam.teamId);
diff --git a/frontend/editor/src/proprietary/components/shared/FlowModal.css b/frontend/editor/src/core/components/shared/FlowModal.css
similarity index 100%
rename from frontend/editor/src/proprietary/components/shared/FlowModal.css
rename to frontend/editor/src/core/components/shared/FlowModal.css
diff --git a/frontend/editor/src/proprietary/components/shared/FlowModal.tsx b/frontend/editor/src/core/components/shared/FlowModal.tsx
similarity index 80%
rename from frontend/editor/src/proprietary/components/shared/FlowModal.tsx
rename to frontend/editor/src/core/components/shared/FlowModal.tsx
index 3e7e56eab5..7110650b8c 100644
--- a/frontend/editor/src/proprietary/components/shared/FlowModal.tsx
+++ b/frontend/editor/src/core/components/shared/FlowModal.tsx
@@ -14,6 +14,9 @@ export function FlowModal({
header,
footer,
size = "md",
+ zIndex,
+ disableBackdropClose,
+ disableEscapeClose,
children,
}: {
open: boolean;
@@ -24,6 +27,9 @@ export function FlowModal({
footer?: ReactNode;
/** `md` for the task dialogs, `lg` for the procurement takeover and Calendly. */
size?: "md" | "lg";
+ zIndex?: number;
+ disableBackdropClose?: boolean;
+ disableEscapeClose?: boolean;
children: ReactNode;
}) {
return (
@@ -35,6 +41,9 @@ export function FlowModal({
className={`portal-flowmodal portal-flowmodal--${size}`}
title={header}
footer={footer}
+ zIndex={zIndex}
+ disableBackdropClose={disableBackdropClose}
+ disableEscapeClose={disableEscapeClose}
>
{children}
</Modal>
diff --git a/frontend/editor/src/proprietary/components/shared/StepModalHeader.css b/frontend/editor/src/core/components/shared/StepModalHeader.css
similarity index 100%
rename from frontend/editor/src/proprietary/components/shared/StepModalHeader.css
rename to frontend/editor/src/core/components/shared/StepModalHeader.css
diff --git a/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx b/frontend/editor/src/core/components/shared/StepModalHeader.tsx
similarity index 84%
rename from frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx
rename to frontend/editor/src/core/components/shared/StepModalHeader.tsx
index 16ef47ae18..58a0966ca7 100644
--- a/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx
+++ b/frontend/editor/src/core/components/shared/StepModalHeader.tsx
@@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@app/ui";
+import { Icon } from "@app/ui/Icon";
// No brand webfont is loaded, so the wordmark must be this SVG rather than styled text.
import wordmarkLight from "@app/assets/brand/modern-logo/StirlingProcessorLogoBlackText.svg";
import wordmarkDark from "@app/assets/brand/modern-logo/StirlingProcessorLogoWhiteText.svg";
@@ -56,8 +57,6 @@ export function StepModalHeader({
</div>
) : brand ? (
<div className="portal-stepmodal__brand">
- {/* `wordmark`, not `wordmark-light-only`: theme.css hides the former in dark mode and
- has no rule for the latter, so both used to render at once. */}
<img
src={wordmarkLight}
alt="Stirling"
@@ -93,22 +92,7 @@ export function StepModalHeader({
shape="circle"
onClick={onClose}
aria-label={closeLabel ?? t("portal.stepModal.close", "Close")}
- leftSection={
- <svg
- viewBox="0 0 24 24"
- width="16"
- height="16"
- fill="none"
- stroke="currentColor"
- strokeWidth={1.75}
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden
- >
- <line x1="18" y1="6" x2="6" y2="18" />
- <line x1="6" y1="6" x2="18" y2="18" />
- </svg>
- }
+ leftSection={<Icon name="x" size={16} />}
/>
)}
</div>
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferAccounts.tsx b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferAccounts.tsx
new file mode 100644
index 0000000000..e1cea976a5
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferAccounts.tsx
@@ -0,0 +1,114 @@
+import { useTranslation } from "react-i18next";
+import type { OwnershipTransferFlow } from "@app/components/shared/ownership/useOwnershipTransfer";
+import { Combobox } from "@mantine/core";
+import { Icon } from "@app/ui/Icon";
+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
+
+/** Keeps local identity separate from the editable cloud account; focusing only loads candidates. */
+export function OwnershipTransferAccounts({
+ flow,
+}: {
+ flow: OwnershipTransferFlow;
+}) {
+ const { t } = useTranslation();
+ const {
+ status,
+ local,
+ ownerAccount,
+ linked,
+ canSelectCloud,
+ partial,
+ picker,
+ search,
+ busy,
+ editEmail,
+ members,
+ cloudEmail,
+ } = flow;
+ return (
+ <>
+ {status && (
+ <div className="ownership-flow__accounts">
+ <div>
+ <span>
+ {local
+ ? t("ownership.serverAccount", "Server account")
+ : t("ownership.newOwnerLabel", "New owner")}
+ </span>
+ <strong title={ownerAccount}>{ownerAccount}</strong>
+ </div>
+ {local && linked && (
+ <div>
+ <label
+ className="ownership-flow__account-label"
+ htmlFor="ownership-cloud-email"
+ >
+ {t("ownership.cloudAccount", "Stirling account")}
+ </label>
+ {canSelectCloud && !partial ? (
+ <Combobox
+ store={picker}
+ zIndex={Z_INDEX_OVER_CONFIG_MODAL + 2}
+ onOptionSubmit={(value) => flow.selectMember(Number(value))}
+ >
+ <div className="ownership-flow__picker">
+ <Combobox.Target withExpandedAttribute>
+ <input
+ id="ownership-cloud-email"
+ role="combobox"
+ className="ownership-flow__search"
+ value={search}
+ readOnly={busy}
+ autoComplete="off"
+ placeholder={t(
+ "ownership.searchEmail",
+ "Search or enter an email",
+ )}
+ onChange={(event) => editEmail(event.target.value)}
+ onFocus={flow.focusAccount}
+ onClick={() => picker.openDropdown()}
+ onBlur={() => picker.closeDropdown()}
+ onKeyDown={(event) => {
+ if (event.key === "Escape" && picker.dropdownOpened)
+ event.stopPropagation();
+ }}
+ />
+ </Combobox.Target>
+ <span className="ownership-flow__chevron">
+ <Icon name="chevron-down" size={16} />
+ </span>
+ <Combobox.Dropdown className="ownership-flow__dropdown">
+ <Combobox.Options className="ownership-flow__options">
+ {members.map((member) => (
+ <Combobox.Option
+ key={member.id}
+ value={String(member.id)}
+ title={member.email}
+ disabled={busy}
+ className="ownership-flow__option"
+ >
+ {member.email}
+ </Combobox.Option>
+ ))}
+ {!members.length && (
+ <Combobox.Empty>
+ {t(
+ "ownership.noEmailMatches",
+ "No matching members. Enter an email to invite.",
+ )}
+ </Combobox.Empty>
+ )}
+ </Combobox.Options>
+ </Combobox.Dropdown>
+ </div>
+ </Combobox>
+ ) : (
+ <strong title={cloudEmail ?? undefined}>{cloudEmail}</strong>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferActions.tsx b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferActions.tsx
new file mode 100644
index 0000000000..65c6e2001b
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferActions.tsx
@@ -0,0 +1,72 @@
+import { useTranslation } from "react-i18next";
+import type { OwnershipTransferFlow } from "@app/components/shared/ownership/useOwnershipTransfer";
+import { Button } from "@app/ui/Button";
+
+/** Selects the next action from confirmed handover state; the hook serializes its execution. */
+export function OwnershipTransferActions({
+ flow,
+}: {
+ flow: OwnershipTransferFlow;
+}) {
+ const { t } = useTranslation();
+ const {
+ done,
+ startFromInstance,
+ error,
+ busy,
+ editing,
+ emailValid,
+ matchingMember,
+ status,
+ partial,
+ needsMember,
+ invited,
+ accepted,
+ } = flow;
+ if (done)
+ return <Button onClick={flow.close}>{t("common.done", "Done")}</Button>;
+ if (startFromInstance) return null;
+ if (flow.canCancelRecovery)
+ return (
+ <Button disabled={busy} onClick={flow.cancel}>
+ {t("ownership.cancel", "Cancel transfer")}
+ </Button>
+ );
+ if (editing && !error)
+ return (
+ <Button
+ disabled={
+ busy ||
+ !emailValid ||
+ !flow.canSelectCloud ||
+ (!matchingMember && !flow.canInvite)
+ }
+ onClick={flow.checkAccount}
+ >
+ {emailValid
+ ? matchingMember
+ ? t("ownership.checkAccount", "Check account")
+ : t("ownership.invite", "Send invitation")
+ : t("ownership.transfer", "Transfer ownership")}
+ </Button>
+ );
+ if (!status || (error && !partial) || (needsMember && invited))
+ return (
+ <Button disabled={busy} onClick={flow.refresh}>
+ {t("ownership.check", "Check again")}
+ </Button>
+ );
+ if (needsMember)
+ return (
+ <Button disabled={busy || !flow.canInvite} onClick={flow.invite}>
+ {t("ownership.invite", "Send invitation")}
+ </Button>
+ );
+ return (
+ <Button disabled={busy || (!accepted && !partial)} onClick={flow.transfer}>
+ {partial
+ ? t("ownership.finish", "Finish server transfer")
+ : t("ownership.transfer", "Transfer ownership")}
+ </Button>
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferMembership.tsx b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferMembership.tsx
new file mode 100644
index 0000000000..b9f14d2b8c
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferMembership.tsx
@@ -0,0 +1,122 @@
+import { Trans, useTranslation } from "react-i18next";
+import type { OwnershipTransferFlow } from "@app/components/shared/ownership/useOwnershipTransfer";
+import { Tooltip } from "@mantine/core";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon } from "@app/ui/Icon";
+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
+
+/** Describes invitation readiness without implying that entering an email sends an invitation. */
+export function OwnershipTransferMembership({
+ flow,
+}: {
+ flow: OwnershipTransferFlow;
+}) {
+ const { t } = useTranslation();
+ const {
+ editing,
+ emailValid,
+ matchingMember,
+ email,
+ teamName,
+ needsMember,
+ invited,
+ cloudEmail,
+ } = flow;
+ return (
+ <>
+ {editing && (
+ <>
+ {emailValid && !matchingMember ? (
+ <p>
+ <Trans
+ t={t}
+ i18nKey="ownership.inviteAddress"
+ defaults="Invite <account>{{email}}</account> to {{team}}."
+ values={{ email, team: teamName }}
+ components={{
+ account: <strong className="ownership-flow__username" />,
+ }}
+ />
+ </p>
+ ) : (
+ <p>
+ {t(
+ "ownership.chooseEmail",
+ "Choose their account in {{team}}, or enter an email to invite them.",
+ { team: teamName },
+ )}
+ </p>
+ )}
+ <p className="ownership-flow__muted">
+ {t(
+ "ownership.membershipFirst",
+ "They must join the team before you can confirm the transfer.",
+ )}
+ </p>
+ </>
+ )}
+ {needsMember && !editing && (
+ <>
+ {invited ? (
+ <div role="status">
+ <strong>
+ {t("ownership.invitationSent", "Invitation sent")}
+ </strong>
+ <p>
+ {t(
+ "ownership.waitingForEmail",
+ "Waiting for {{email}} to join {{team}}.",
+ { email: cloudEmail, team: teamName },
+ )}
+ </p>
+ </div>
+ ) : (
+ <p>
+ <Trans
+ t={t}
+ i18nKey="ownership.inviteAddress"
+ defaults="Invite <account>{{email}}</account> to {{team}}."
+ values={{ email: cloudEmail, team: teamName }}
+ components={{
+ account: <strong className="ownership-flow__username" />,
+ }}
+ />
+ </p>
+ )}
+ <p className="ownership-flow__muted">
+ {t(
+ "ownership.acceptInvite",
+ "They can create an account or sign in, then accept the invitation.",
+ )}
+ </p>
+ </>
+ )}
+ {(needsMember || (editing && emailValid && !matchingMember)) && (
+ <div className="ownership-flow__detail">
+ <span>{t("ownership.anotherTeam", "Already on another team?")}</span>
+ <Tooltip
+ multiline
+ w={300}
+ zIndex={Z_INDEX_OVER_CONFIG_MODAL + 2}
+ events={{ hover: true, focus: true, touch: true }}
+ label={t(
+ "ownership.otherTeam",
+ "If they belong to another team, accepting may move their account. A paid account or ownership of another team may need resolving first. We won't move their subscription or merge teams.",
+ )}
+ >
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ aria-label={t(
+ "ownership.membershipDetails",
+ "Team membership details",
+ )}
+ >
+ <Icon name="info" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.css b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.css
new file mode 100644
index 0000000000..9d5239d4c3
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.css
@@ -0,0 +1,143 @@
+.ownership-flow {
+ display: flex;
+ flex-direction: column;
+ gap: 0.85rem;
+ font-size: 0.875rem;
+ line-height: 1.55;
+}
+
+.ownership-flow p {
+ margin: 0;
+}
+.ownership-flow__muted {
+ color: var(--c-text-muted);
+ font-size: 0.8125rem;
+}
+.ownership-flow__accounts {
+ min-width: 0;
+}
+.ownership-flow__accounts > div {
+ display: flex;
+ align-items: center;
+ gap: 0.65rem;
+ padding: 0.65rem 0;
+}
+.ownership-flow__accounts > div + div {
+ border-top: 1px solid var(--c-border-subtle);
+}
+.ownership-flow__accounts > div > span,
+.ownership-flow__account-label {
+ flex: 0 0 7rem;
+ color: var(--c-text-muted);
+ font-size: 0.75rem;
+}
+.ownership-flow__accounts strong {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ownership-flow__accounts button {
+ flex-shrink: 0;
+}
+.ownership-flow__username {
+ color: var(--c-text);
+ background: var(--c-primary-subtle);
+ border-radius: 0.25rem;
+ padding: 0.05rem 0.3rem;
+ overflow-wrap: anywhere;
+}
+.ownership-flow__picker {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+}
+.ownership-flow__search {
+ width: 100%;
+ box-sizing: border-box;
+ background: var(--c-input-bg);
+ color: var(--c-text);
+ border: 1px solid var(--c-border);
+ border-radius: 0.5rem;
+ padding: 0.55rem 2rem 0.55rem 0.65rem;
+ font: inherit;
+}
+.ownership-flow__search:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: 2px;
+}
+.ownership-flow__chevron {
+ position: absolute;
+ right: 0.6rem;
+ top: 50%;
+ transform: translateY(-50%);
+ pointer-events: none;
+ color: var(--c-text-muted);
+}
+.ownership-flow__dropdown {
+ background: var(--c-surface-raised);
+ color: var(--c-text);
+ border-color: var(--c-border);
+ z-index: 1;
+}
+.ownership-flow__options {
+ max-height: calc(5 * 2.5rem);
+ overflow-y: auto;
+ overscroll-behavior: contain;
+}
+.ownership-flow__option {
+ height: 2.5rem;
+ box-sizing: border-box;
+ display: block;
+ padding: 0.55rem 0.65rem;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ownership-flow__option[data-combobox-selected],
+.ownership-flow__option:hover {
+ background: var(--c-primary-subtle);
+ color: var(--c-text);
+}
+.ownership-flow__success {
+ display: flex;
+ align-items: center;
+ flex-direction: column;
+ gap: 0.7rem;
+ padding: 1.25rem 1rem;
+ text-align: center;
+}
+.ownership-flow__success svg {
+ color: var(--c-success);
+}
+.ownership-flow__summary {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+.ownership-flow__detail {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ color: var(--c-text-muted);
+ font-size: 0.8125rem;
+}
+.ownership-flow__notice {
+ padding: 0.85rem 1rem;
+ border: 1px solid var(--c-border);
+ background: var(--c-surface-sunken);
+ border-radius: 0.65rem;
+}
+.ownership-flow__notice--error {
+ border-color: var(--c-danger);
+}
+
+@media (max-width: 420px) {
+ .ownership-flow__accounts > div {
+ flex-wrap: wrap;
+ }
+ .ownership-flow__picker {
+ flex-basis: 100%;
+ }
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.stories.tsx b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.stories.tsx
new file mode 100644
index 0000000000..e049350cc6
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.stories.tsx
@@ -0,0 +1,156 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import {
+ OwnershipTransferModal,
+ type OwnershipStatus,
+ type OwnershipTransferAdapter,
+} from "@app/components/shared/ownership/OwnershipTransferModal";
+
+const ready: OwnershipStatus = {
+ targetId: 2,
+ targetName: "Jamie Chen",
+ targetEmail: "[email protected]",
+ cloud: {
+ teamId: 9,
+ teamName: "Acme",
+ leaderUserId: 1,
+ targetUserId: 2,
+ linkedInstances: 2,
+ subscribed: true,
+ state: "READY",
+ },
+};
+
+function adapter(
+ state: OwnershipStatus,
+ local = true,
+): OwnershipTransferAdapter {
+ return {
+ local,
+ prepare: async () => state,
+ transferCloud: async () => ({
+ ...state,
+ cloud: state.cloud ? { ...state.cloud, state: "TRANSFERRED" } : null,
+ }),
+ completeLocal: async () => {},
+ invite: async () => state,
+ cancel: async () => {},
+ };
+}
+
+const meta = {
+ title: "Ownership/Transfer",
+ component: OwnershipTransferModal,
+ args: { adapter: adapter(ready), onClose: () => {}, onTransferred: () => {} },
+} satisfies Meta<typeof OwnershipTransferModal>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const LinkedPaid: Story = {};
+function pickerAdapter(
+ members: NonNullable<OwnershipStatus["candidates"]>["members"],
+): OwnershipTransferAdapter {
+ const initial: OwnershipStatus = {
+ ...ready,
+ targetName: "jamie-local",
+ targetEmail: null,
+ cloud: null,
+ candidates: { teamId: 9, teamName: "Acme", members },
+ };
+ let current = initial;
+ return {
+ ...adapter(initial),
+ prepare: async () => current,
+ selectCloud: async (choice) => {
+ const member = members.find((entry) =>
+ choice.cloudUserId !== undefined
+ ? entry.id === choice.cloudUserId
+ : entry.email === choice.cloudEmail,
+ );
+ current = {
+ ...initial,
+ candidates: null,
+ cloudEmail: member?.email ?? choice.cloudEmail,
+ cloud: {
+ ...ready.cloud!,
+ targetUserId: member?.id ?? null,
+ state: member ? "READY" : "NEEDS_MEMBERSHIP",
+ },
+ };
+ return current;
+ },
+ invite: async () => current,
+ transferCloud: async () => {
+ current = {
+ ...current,
+ cloud: { ...current.cloud!, state: "TRANSFERRED" },
+ };
+ return current;
+ },
+ cancel: async () => {
+ current = initial;
+ },
+ };
+}
+
+export const ChooseCloudMember: Story = {
+ args: {
+ adapter: pickerAdapter([
+ { id: 42, name: "Jamie Chen", email: "[email protected]" },
+ { id: 43, name: "Alex Morgan", email: "[email protected]" },
+ ]),
+ },
+};
+export const NoOtherCloudMembers: Story = {
+ args: { adapter: pickerAdapter([]) },
+};
+export const ScrollableCloudMembers: Story = {
+ args: {
+ adapter: pickerAdapter(
+ Array.from({ length: 8 }, (_, index) => ({
+ id: index + 42,
+ name: `Member ${index + 1}`,
+ email: `member${index + 1}@acme.com`,
+ })),
+ ),
+ },
+};
+export const ReviewSeparateAccounts: Story = {
+ args: {
+ adapter: adapter({
+ ...ready,
+ targetName: "jamie-local",
+ targetEmail: null,
+ cloudEmail: "[email protected]",
+ }),
+ },
+};
+export const Unlinked: Story = {
+ args: { adapter: adapter({ ...ready, cloud: null }) },
+};
+export const CloudTeam: Story = {
+ args: {
+ adapter: adapter(
+ { ...ready, cloud: { ...ready.cloud!, linkedInstances: 0 } },
+ false,
+ ),
+ },
+};
+export const CloudTeamWithLinkedServers: Story = {
+ args: { adapter: adapter(ready, false) },
+};
+export const Invitation: Story = {
+ args: {
+ adapter: adapter({
+ ...ready,
+ cloud: { ...ready.cloud!, targetUserId: null, state: "NEEDS_MEMBERSHIP" },
+ }),
+ },
+};
+export const FinishServer: Story = {
+ args: {
+ adapter: adapter({
+ ...ready,
+ cloud: { ...ready.cloud!, state: "TRANSFERRED" },
+ }),
+ },
+};
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.test.tsx b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.test.tsx
new file mode 100644
index 0000000000..280e78bbaf
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.test.tsx
@@ -0,0 +1,753 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import {
+ OwnershipTransferModal,
+ type OwnershipStatus,
+ type OwnershipTransferAdapter,
+} from "@app/components/shared/ownership/OwnershipTransferModal";
+
+vi.mock("react-i18next", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-i18next")>();
+ const { createInstance } = await import("i18next");
+ const i18n = createInstance();
+ await i18n.use(actual.initReactI18next).init({
+ lng: "en",
+ resources: {},
+ interpolation: { escapeValue: false },
+ });
+ return { ...actual, useTranslation: () => ({ t: i18n.t, i18n }) };
+});
+
+async function click(element: HTMLElement) {
+ await act(async () => {
+ fireEvent.click(element);
+ });
+}
+
+function status(
+ state: "READY" | "NEEDS_MEMBERSHIP" | "TRANSFERRED" | null,
+ paid = false,
+): OwnershipStatus {
+ return {
+ targetId: 2,
+ targetName: "Jamie",
+ targetEmail: "[email protected]",
+ cloud: state
+ ? {
+ teamId: 9,
+ teamName: "Acme",
+ leaderUserId: 1,
+ targetUserId: state === "NEEDS_MEMBERSHIP" ? null : 2,
+ linkedInstances: 3,
+ subscribed: paid,
+ state,
+ }
+ : null,
+ };
+}
+
+describe("ownership handover", () => {
+ let adapter: OwnershipTransferAdapter;
+ const onTransferred = vi.fn();
+ const onClose = vi.fn();
+ beforeEach(() => {
+ vi.clearAllMocks();
+ adapter = {
+ local: true,
+ prepare: vi.fn().mockResolvedValue(status("READY")),
+ invite: vi.fn().mockResolvedValue(status("NEEDS_MEMBERSHIP")),
+ transferCloud: vi.fn().mockResolvedValue(status("TRANSFERRED")),
+ completeLocal: vi.fn().mockResolvedValue(undefined),
+ cancel: vi.fn().mockResolvedValue(undefined),
+ signIn: vi.fn(),
+ };
+ });
+ function show() {
+ return render(
+ <MantineProvider env="test">
+ <OwnershipTransferModal
+ adapter={adapter}
+ onClose={onClose}
+ onTransferred={onTransferred}
+ />
+ </MantineProvider>,
+ );
+ }
+ async function confirm() {
+ await click(await screen.findByRole("checkbox"));
+ await click(screen.getByRole("button", { name: "Transfer ownership" }));
+ }
+
+ function choosing(
+ members: NonNullable<OwnershipStatus["candidates"]>["members"] = [
+ { id: 42, name: "Jamie Cloud", email: "[email protected]" },
+ ],
+ ): OwnershipStatus {
+ return {
+ ...status(null),
+ targetEmail: null,
+ candidates: { teamId: 9, teamName: "Acme", members },
+ };
+ }
+
+ it("selects a team member for a local user without an email and reviews both accounts", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(choosing());
+ adapter.selectCloud = vi.fn().mockResolvedValue({
+ ...status("READY"),
+ targetEmail: null,
+ cloudEmail: "[email protected]",
+ });
+ show();
+ const input = await screen.findByRole("combobox", {
+ name: "Stirling account",
+ });
+ expect(
+ screen.getByRole("button", { name: "Transfer ownership" }),
+ ).toBeDisabled();
+ fireEvent.focus(input);
+ await click(
+ await screen.findByRole("option", { name: "[email protected]" }),
+ );
+ await screen.findByRole("checkbox");
+ expect(adapter.selectCloud).toHaveBeenCalledWith({ cloudUserId: 42 });
+ expect(screen.getByText("Server account")).toBeVisible();
+ expect(screen.getAllByText("Jamie")[0]).toBeVisible();
+ expect(
+ screen.getByRole("combobox", { name: "Stirling account" }),
+ ).toHaveValue("[email protected]");
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ await confirm();
+ expect(screen.getByText("Ownership transferred")).toBeVisible();
+ });
+
+ it("Escape closes the email dropdown before dismissing the transfer", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(choosing());
+ adapter.selectCloud = vi.fn();
+ show();
+ const input = await screen.findByRole("combobox", {
+ name: "Stirling account",
+ });
+ fireEvent.focus(input);
+ await screen.findByRole("option", { name: "[email protected]" });
+ fireEvent.keyDown(input, { key: "Escape", code: "Escape" });
+ expect(input).toHaveAttribute("aria-expanded", "false");
+ expect(onClose).not.toHaveBeenCalled();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ fireEvent.keyDown(input, { key: "Escape", code: "Escape" });
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it("closing a member picker does not create or cancel an intent", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(choosing());
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Close transfer dialog" }),
+ );
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ });
+
+ it("guides an empty team through invitation and acceptance before offering transfer", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(choosing([]));
+ const awaiting = {
+ ...status("NEEDS_MEMBERSHIP"),
+ targetEmail: null,
+ cloudEmail: "[email protected]",
+ };
+ adapter.selectCloud = vi.fn().mockResolvedValue(awaiting);
+ vi.mocked(adapter.invite!).mockResolvedValue(awaiting);
+ show();
+ await screen.findByRole("combobox", { name: "Stirling account" });
+ expect(screen.queryByRole("alert")).toBeNull();
+ fireEvent.change(
+ screen.getByRole("combobox", { name: "Stirling account" }),
+ { target: { value: "invalid" } },
+ );
+ expect(
+ screen.getByRole("button", { name: "Transfer ownership" }),
+ ).toBeDisabled();
+ fireEvent.change(
+ screen.getByRole("combobox", { name: "Stirling account" }),
+ { target: { value: "[email protected]" } },
+ );
+ expect(adapter.invite).not.toHaveBeenCalled();
+ await click(await screen.findByRole("button", { name: "Send invitation" }));
+ expect(adapter.selectCloud).toHaveBeenCalledWith({
+ cloudEmail: "[email protected]",
+ });
+ expect(await screen.findByText("Invitation sent")).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Transfer ownership" }),
+ ).toBeNull();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ vi.mocked(adapter.prepare).mockResolvedValue({
+ ...status("READY"),
+ cloudEmail: "[email protected]",
+ });
+ await click(screen.getByRole("button", { name: "Check again" }));
+ await confirm();
+ expect(screen.getByText("Ownership transferred")).toBeVisible();
+ });
+
+ it("keeps the picker open when a chosen member is no longer eligible", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(choosing());
+ const awaiting = {
+ ...status("NEEDS_MEMBERSHIP"),
+ cloudEmail: "[email protected]",
+ };
+ adapter.selectCloud = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("CLOUD_TARGET_CHANGED"))
+ .mockResolvedValue(awaiting);
+ vi.mocked(adapter.invite!).mockResolvedValue(awaiting);
+ show();
+ fireEvent.focus(
+ await screen.findByRole("combobox", { name: "Stirling account" }),
+ );
+ await click(
+ await screen.findByRole("option", { name: "[email protected]" }),
+ );
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Choose another cloud member",
+ );
+ fireEvent.change(
+ screen.getByRole("combobox", { name: "Stirling account" }),
+ { target: { value: "[email protected]" } },
+ );
+ await click(await screen.findByRole("button", { name: "Send invitation" }));
+ expect(adapter.selectCloud).toHaveBeenLastCalledWith({
+ cloudEmail: "[email protected]",
+ });
+ expect(await screen.findByText("Invitation sent")).toBeVisible();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ });
+
+ it("focusing and reselecting a resumed account preserves the saved handover", async () => {
+ adapter.selectCloud = vi.fn();
+ adapter.loadCandidates = vi
+ .fn()
+ .mockResolvedValue(
+ choosing([{ id: 2, name: null, email: "[email protected]" }])
+ .candidates,
+ );
+ show();
+ const input = await screen.findByRole("combobox", {
+ name: "Stirling account",
+ });
+ fireEvent.focus(input);
+ await click(
+ await screen.findByRole("option", { name: "[email protected]" }),
+ );
+ fireEvent.blur(input);
+ fireEvent.focus(input);
+ expect(adapter.loadCandidates).toHaveBeenCalledOnce();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ expect(adapter.selectCloud).not.toHaveBeenCalled();
+ expect(adapter.prepare).toHaveBeenCalledOnce();
+ expect(input).toHaveValue("[email protected]");
+ fireEvent.blur(input);
+ await confirm();
+ expect(adapter.completeLocal).toHaveBeenCalledOnce();
+ });
+
+ it.each(["TARGET_CHANGED", "TARGET_UNAVAILABLE"])(
+ "offers checked cancellation when a saved recipient cannot be loaded: %s",
+ async (reason) => {
+ vi.mocked(adapter.prepare).mockRejectedValue(new Error(reason));
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Cancel transfer" }),
+ );
+ expect(adapter.cancel).toHaveBeenCalledOnce();
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps checked cancellation blocked after cloud completion even without recipient status", async () => {
+ vi.mocked(adapter.prepare).mockRejectedValue(
+ new Error("TARGET_UNAVAILABLE"),
+ );
+ vi.mocked(adapter.cancel!).mockRejectedValue(
+ new Error("FINISH_LOCAL_TRANSFER"),
+ );
+ show();
+ await click(await screen.findByRole("button", { name: "Cancel transfer" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Cloud ownership has transferred",
+ );
+ expect(onClose).not.toHaveBeenCalled();
+ await click(screen.getByRole("button", { name: "Close transfer dialog" }));
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.cancel).toHaveBeenCalledOnce();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["PERSONAL_TEAM", "Personal teams cannot transfer ownership."],
+ ["MEMBERSHIP_REQUIRED", "The recipient must join this cloud team"],
+ ])("explains a cloud transfer rejection: %s", async (reason, message) => {
+ vi.mocked(adapter.transferCloud).mockRejectedValue(new Error(reason));
+ show();
+ await confirm();
+ expect(await screen.findByRole("alert")).toHaveTextContent(message);
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ expect(onTransferred).not.toHaveBeenCalled();
+ });
+
+ it("explains how to recover a retained link when linking is disabled", async () => {
+ vi.mocked(adapter.prepare).mockRejectedValue(
+ new Error("ACCOUNT_LINK_DISABLED"),
+ );
+ show();
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Ask the server operator to enable account linking",
+ );
+ await click(screen.getByRole("button", { name: "Close transfer dialog" }));
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ });
+
+ it("offers checked cancellation when a resumed link is revoked", async () => {
+ vi.mocked(adapter.prepare).mockRejectedValue(new Error("LINK_REVOKED"));
+ show();
+ await click(await screen.findByRole("button", { name: "Cancel transfer" }));
+ expect(adapter.cancel).toHaveBeenCalledOnce();
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ });
+
+ it("keeps a revoked-link recovery open if cancellation cannot be verified", async () => {
+ vi.mocked(adapter.prepare).mockRejectedValue(new Error("LINK_REVOKED"));
+ vi.mocked(adapter.cancel!).mockRejectedValue(
+ new Error("CLOUD_UNAVAILABLE"),
+ );
+ show();
+ await click(await screen.findByRole("button", { name: "Cancel transfer" }));
+ expect(onClose).not.toHaveBeenCalled();
+ expect(
+ await screen.findByRole("button", { name: "Check again" }),
+ ).toBeVisible();
+ });
+
+ it("changing the selected account cancels its draft before loading the member picker", async () => {
+ adapter.selectCloud = vi.fn();
+ show();
+ await screen.findByRole("checkbox");
+ vi.mocked(adapter.prepare).mockResolvedValue(choosing());
+ fireEvent.change(
+ screen.getByRole("combobox", { name: "Stirling account" }),
+ { target: { value: "[email protected]" } },
+ );
+ await waitFor(() => expect(adapter.cancel).toHaveBeenCalledOnce());
+ expect(
+ screen.getByRole("combobox", { name: "Stirling account" }),
+ ).toHaveValue("[email protected]");
+ expect(adapter.cancel).toHaveBeenCalledOnce();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ });
+
+ it("unlinked transfer needs no cloud account", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(status(null));
+ show();
+ await confirm();
+ await screen.findByText("Ownership transferred");
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ expect(adapter.completeLocal).toHaveBeenCalledOnce();
+ });
+
+ it.each([null, "READY", "NEEDS_MEMBERSHIP"] as const)(
+ "closing the dialog cancels an unfinished transfer in state %s",
+ async (state) => {
+ vi.mocked(adapter.prepare).mockResolvedValue(status(state));
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Close transfer dialog" }),
+ );
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(adapter.cancel).toHaveBeenCalledOnce();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ },
+ );
+
+ it("Escape uses the same cancellation as the close button", async () => {
+ show();
+ await screen.findByRole("checkbox");
+ await act(async () => {
+ fireEvent.keyDown(screen.getByRole("dialog"), {
+ key: "Escape",
+ code: "Escape",
+ });
+ });
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(adapter.cancel).toHaveBeenCalledOnce();
+ });
+
+ it("waits for cancellation before dismissing", async () => {
+ let resolveCancel!: () => void;
+ vi.mocked(adapter.cancel!).mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveCancel = resolve;
+ }),
+ );
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Close transfer dialog" }),
+ );
+ expect(adapter.cancel).toHaveBeenCalledOnce();
+ expect(onClose).not.toHaveBeenCalled();
+ await act(async () => {
+ resolveCancel();
+ });
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it("closes the dialog after cancellation fails without completing the saved handover", async () => {
+ vi.mocked(adapter.cancel!).mockRejectedValue(
+ new Error("Cloud state unknown"),
+ );
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Close transfer dialog" }),
+ );
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ expect(onTransferred).not.toHaveBeenCalled();
+ });
+
+ it("preserves the pending transfer when cloud ownership has already moved", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(status("TRANSFERRED"));
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Close transfer dialog" }),
+ );
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ });
+
+ it.each([true, false])(
+ "keeps success visible until Done before refreshing its host (local=%s)",
+ async (local) => {
+ adapter.local = local;
+ const ready = status("READY");
+ if (!local) ready.cloud!.linkedInstances = 0;
+ vi.mocked(adapter.prepare).mockResolvedValue(ready);
+ vi.mocked(adapter.transferCloud).mockResolvedValue({
+ ...ready,
+ cloud: { ...ready.cloud!, state: "TRANSFERRED" },
+ });
+ const view = show();
+ onTransferred.mockImplementationOnce(() => view.unmount());
+ await confirm();
+ expect(await screen.findByText("Ownership transferred")).toBeVisible();
+ expect(screen.queryByText(/Step \d of/)).toBeNull();
+ expect(screen.getByRole("status")).toHaveTextContent(
+ local
+ ? "Jamie is now the owner."
+ : "[email protected] is now the owner.",
+ );
+ expect(onTransferred).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ await click(screen.getByRole("button", { name: "Done" }));
+ expect(onTransferred).toHaveBeenCalledOnce();
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(adapter.transferCloud).toHaveBeenCalledOnce();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ },
+ );
+
+ it("searches by email only and uses the typed invitation address without sending on entry", async () => {
+ adapter.selectCloud = vi.fn();
+ vi.mocked(adapter.prepare).mockResolvedValue(
+ choosing(
+ Array.from({ length: 8 }, (_, index) => ({
+ id: index + 10,
+ name: "Display " + index,
+ email: "member" + index + "@example.com",
+ })),
+ ),
+ );
+ show();
+ const input = await screen.findByRole("combobox", {
+ name: "Stirling account",
+ });
+ fireEvent.focus(input);
+ expect(await screen.findAllByRole("option")).toHaveLength(8);
+ fireEvent.change(input, { target: { value: "member7@" } });
+ expect(screen.getAllByRole("option")).toHaveLength(1);
+ expect(
+ screen.getByRole("option", { name: "[email protected]" }),
+ ).toBeVisible();
+ fireEvent.change(input, { target: { value: "Display" } });
+ expect(screen.queryByRole("option")).toBeNull();
+ fireEvent.change(input, { target: { value: "[email protected]" } });
+ expect(
+ screen.getByRole("button", { name: "Send invitation" }),
+ ).toBeEnabled();
+ expect(screen.getByText("[email protected]")).toBeVisible();
+ expect(adapter.selectCloud).not.toHaveBeenCalled();
+ expect(adapter.invite).not.toHaveBeenCalled();
+ });
+
+ it("does not send an invitation if the entered address is already a member when checked", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(choosing([]));
+ adapter.selectCloud = vi.fn().mockResolvedValue({
+ ...status("READY"),
+ cloudEmail: "[email protected]",
+ });
+ show();
+ fireEvent.change(
+ await screen.findByRole("combobox", { name: "Stirling account" }),
+ {
+ target: { value: "[email protected]" },
+ },
+ );
+ await click(screen.getByRole("button", { name: "Send invitation" }));
+ expect(await screen.findByRole("checkbox")).not.toBeChecked();
+ expect(adapter.invite).not.toHaveBeenCalled();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ });
+
+ it("does not advance a changed email if cancelling the previous selection fails", async () => {
+ adapter.selectCloud = vi.fn();
+ vi.mocked(adapter.cancel!).mockRejectedValue(new Error("network"));
+ show();
+ const input = await screen.findByRole("combobox", {
+ name: "Stirling account",
+ });
+ fireEvent.change(input, { target: { value: "[email protected]" } });
+ expect(await screen.findByRole("alert")).toBeVisible();
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "Send invitation" }),
+ ).toBeNull();
+ expect(adapter.selectCloud).not.toHaveBeenCalled();
+ expect(adapter.invite).not.toHaveBeenCalled();
+ await click(screen.getByRole("button", { name: "Check again" }));
+ expect(input).toHaveValue("[email protected]");
+ });
+
+ it("makes billing details available on keyboard focus", async () => {
+ show();
+ const details = await screen.findByRole("button", {
+ name: "Billing details",
+ });
+ fireEvent.focus(details);
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(
+ "Billing contact details do not change automatically.",
+ );
+ expect(screen.getByText(/You keep administrator access/)).toBeVisible();
+ });
+
+ it("closing a completed transfer does not cancel it", async () => {
+ show();
+ await confirm();
+ await screen.findByText("Ownership transferred");
+ await click(
+ await screen.findByRole("button", { name: "Close transfer dialog" }),
+ );
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ });
+
+ it("does not cancel another recipient's transfer when preparation fails", async () => {
+ vi.mocked(adapter.prepare).mockRejectedValue(
+ new Error("HANDOVER_IN_PROGRESS"),
+ );
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Close transfer dialog" }),
+ );
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])(
+ "same-team recipient transfers cloud before server (paid=%s)",
+ async (paid) => {
+ vi.mocked(adapter.prepare).mockResolvedValue(status("READY", paid));
+ const order: string[] = [];
+ vi.mocked(adapter.transferCloud).mockImplementation(async () => {
+ order.push("cloud");
+ return status("TRANSFERRED", paid);
+ });
+ vi.mocked(adapter.completeLocal!).mockImplementation(async () => {
+ order.push("server");
+ });
+ show();
+ expect(await screen.findByRole("checkbox")).not.toBeChecked();
+ expect(
+ screen.getByRole("button", { name: "Transfer ownership" }),
+ ).toBeDisabled();
+ await confirm();
+ await screen.findByText("Ownership transferred");
+ expect(order).toEqual(["cloud", "server"]);
+ expect(screen.getByText("Ownership transferred")).toBeInTheDocument();
+ },
+ );
+
+ it.each([
+ [false, "no account"],
+ [false, "another team"],
+ [true, "no account"],
+ [true, "another team"],
+ ])("requires acceptance: paid=%s, recipient=%s", async (paid) => {
+ vi.mocked(adapter.prepare).mockResolvedValue(
+ status("NEEDS_MEMBERSHIP", Boolean(paid)),
+ );
+ show();
+ await click(await screen.findByRole("button", { name: "Send invitation" }));
+ await screen.findByText("Invitation sent");
+ expect(
+ screen.queryByRole("button", { name: "Transfer ownership" }),
+ ).not.toBeInTheDocument();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ vi.mocked(adapter.prepare).mockResolvedValue(
+ status("READY", Boolean(paid)),
+ );
+ await click(screen.getByRole("button", { name: "Check again" }));
+ await confirm();
+ await screen.findByText("Ownership transferred");
+ });
+
+ it("cloud failure leaves server ownership untouched", async () => {
+ vi.mocked(adapter.transferCloud).mockRejectedValue({
+ body: { detail: "CLOUD_OWNER_REQUIRED" },
+ });
+ show();
+ await confirm();
+ await screen.findByText(
+ "Sign in as the current cloud team owner, then try this step again.",
+ );
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ expect(onTransferred).not.toHaveBeenCalled();
+ });
+
+ it("resumes a cloud commit after a lost response without transferring cloud twice", async () => {
+ vi.mocked(adapter.transferCloud).mockRejectedValue(new Error("network"));
+ vi.mocked(adapter.prepare)
+ .mockResolvedValueOnce(status("READY"))
+ .mockResolvedValue(status("TRANSFERRED"));
+ show();
+ await confirm();
+ await click(
+ await screen.findByRole("button", { name: "Finish server transfer" }),
+ );
+ await screen.findByText("Ownership transferred");
+ expect(adapter.transferCloud).toHaveBeenCalledOnce();
+ expect(adapter.completeLocal).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ ["TARGET_UNAVAILABLE", "Restore the selected server user's access"],
+ ["TARGET_CHANGED", "Restore the selected server user's access"],
+ ["LINK_CHANGED", "The server's cloud link changed"],
+ ])(
+ "shows the repair needed after the cloud step: %s",
+ async (code, message) => {
+ vi.mocked(adapter.prepare).mockResolvedValue(status("TRANSFERRED"));
+ vi.mocked(adapter.completeLocal!).mockRejectedValue(new Error(code));
+ show();
+ await click(
+ await screen.findByRole("button", { name: "Finish server transfer" }),
+ );
+ expect(await screen.findByRole("alert")).toHaveTextContent(message);
+ expect(adapter.cancel).not.toHaveBeenCalled();
+ expect(
+ screen.queryByRole("button", { name: "Cancel transfer" }),
+ ).toBeNull();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ },
+ );
+
+ it("reopening a partial handover offers completion and prevents cancellation", async () => {
+ vi.mocked(adapter.prepare).mockResolvedValue(status("TRANSFERRED"));
+ show();
+ const finish = await screen.findByRole("button", {
+ name: "Finish server transfer",
+ });
+ expect(
+ screen.queryByRole("button", { name: "Cancel transfer" }),
+ ).not.toBeInTheDocument();
+ await click(finish);
+ await screen.findByText("Ownership transferred");
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ });
+
+ it("native SaaS uses the same review without a server mutation", async () => {
+ adapter.local = false;
+ const unlinked = status("READY");
+ unlinked.cloud!.linkedInstances = 0;
+ vi.mocked(adapter.prepare).mockResolvedValue(unlinked);
+ show();
+ expect(await screen.findByText("New owner")).toBeVisible();
+ expect(screen.getAllByText("[email protected]")[0]).toBeVisible();
+ expect(screen.queryByText("Stirling account")).toBeNull();
+ expect(
+ screen.getByText("You'll become a team member and lose owner access."),
+ ).toBeVisible();
+ await confirm();
+ await screen.findByText("Ownership transferred");
+ expect(adapter.transferCloud).toHaveBeenCalledOnce();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ });
+
+ it.each([1, 3])(
+ "directs SaaS owners with %s linked servers to self-hosted",
+ async (count) => {
+ adapter.local = false;
+ const linked = status("READY");
+ linked.cloud!.linkedInstances = count;
+ vi.mocked(adapter.prepare).mockResolvedValue(linked);
+ show();
+ expect(
+ await screen.findByText("Start from your self-hosted server"),
+ ).toBeVisible();
+ expect(screen.getByText(/open Settings → Users/)).toBeVisible();
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "Transfer ownership" }),
+ ).toBeNull();
+ await click(
+ screen.getByRole("button", { name: "Close transfer dialog" }),
+ );
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(adapter.transferCloud).not.toHaveBeenCalled();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ },
+ );
+
+ it("shows the same guidance if an instance is linked after the review loads", async () => {
+ adapter.local = false;
+ const unlinked = status("READY");
+ unlinked.cloud!.linkedInstances = 0;
+ vi.mocked(adapter.prepare).mockResolvedValue(unlinked);
+ vi.mocked(adapter.transferCloud).mockRejectedValue({
+ response: { data: { detail: "START_TRANSFER_FROM_INSTANCE" } },
+ });
+ show();
+ await confirm();
+ expect(
+ await screen.findByText("Start from your self-hosted server"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Transfer ownership" }),
+ ).toBeNull();
+ expect(onTransferred).not.toHaveBeenCalled();
+ expect(adapter.completeLocal).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.tsx b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.tsx
new file mode 100644
index 0000000000..1b2e808546
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferModal.tsx
@@ -0,0 +1,142 @@
+import { Trans, useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
+import { FlowModal } from "@app/components/shared/FlowModal";
+import { StepModalHeader } from "@app/components/shared/StepModalHeader";
+import { Icon } from "@app/ui/Icon";
+import { useOwnershipTransfer } from "@app/components/shared/ownership/useOwnershipTransfer";
+import { ownershipErrorText } from "@app/components/shared/ownership/ownershipTransferErrors";
+import { OwnershipTransferAccounts } from "@app/components/shared/ownership/OwnershipTransferAccounts";
+import { OwnershipTransferMembership } from "@app/components/shared/ownership/OwnershipTransferMembership";
+import { OwnershipTransferReview } from "@app/components/shared/ownership/OwnershipTransferReview";
+import { OwnershipTransferActions } from "@app/components/shared/ownership/OwnershipTransferActions";
+import type { OwnershipTransferProps } from "@app/components/shared/ownership/ownershipTransfer.types";
+import "@app/components/shared/ownership/OwnershipTransferModal.css";
+
+export type {
+ CloudOwnershipStatus,
+ OwnershipStatus,
+ OwnershipTransferAdapter,
+} from "@app/components/shared/ownership/ownershipTransfer.types";
+
+/** Mounted for one recipient. Dismissal cancels preparation but preserves a committed cloud step. */
+export function OwnershipTransferModal(props: OwnershipTransferProps) {
+ const { t } = useTranslation();
+ const flow = useOwnershipTransfer(props);
+ const {
+ close,
+ busy,
+ picker,
+ done,
+ partial,
+ startFromInstance,
+ error,
+ ownerAccount,
+ local,
+ linked,
+ status,
+ canSignIn,
+ cloudDone,
+ } = flow;
+ return (
+ <FlowModal
+ open
+ onClose={close}
+ label={t("ownership.title", "Transfer ownership")}
+ disableBackdropClose
+ disableEscapeClose={busy || picker.dropdownOpened}
+ zIndex={Z_INDEX_OVER_CONFIG_MODAL + 1}
+ footer={
+ <>
+ <span className="ownership-flow__muted">
+ {!done &&
+ !partial &&
+ !startFromInstance &&
+ t("ownership.stayOwner", "You stay the owner until transfer.")}
+ </span>
+ <OwnershipTransferActions flow={flow} />
+ </>
+ }
+ >
+ <StepModalHeader
+ brand={t("ownership.title", "Transfer ownership")}
+ closeLabel={t("ownership.close", "Close transfer dialog")}
+ onClose={busy ? undefined : close}
+ />
+ <div className="ownership-flow" aria-busy={busy}>
+ {busy && (
+ <p className="ownership-flow__muted" role="status">
+ {t("ownership.working", "Checking and updating ownership…")}
+ </p>
+ )}
+ {error && !startFromInstance && (
+ <div
+ className="ownership-flow__notice ownership-flow__notice--error"
+ role="alert"
+ >
+ {ownershipErrorText(t, error, partial)}
+ </div>
+ )}
+ {done ? (
+ <div className="ownership-flow__success" role="status">
+ <Icon name="circle-check" size={32} />
+ <strong>{t("ownership.done", "Ownership transferred")}</strong>
+ <p>
+ <Trans
+ t={t}
+ i18nKey="ownership.newOwnerStyled"
+ defaults="<user>{{name}}</user> is now the owner."
+ values={{ name: ownerAccount }}
+ components={{
+ user: <strong className="ownership-flow__username" />,
+ }}
+ />
+ </p>
+ <p className="ownership-flow__muted">
+ {local && linked
+ ? t(
+ "ownership.bothDone",
+ "Server and cloud ownership are now aligned.",
+ )
+ : t("ownership.accessUpdated", "Their owner access is ready.")}
+ </p>
+ </div>
+ ) : startFromInstance ? (
+ <div role="alert">
+ <strong>
+ {t(
+ "ownership.startFromInstanceTitle",
+ "Start from your self-hosted server",
+ )}
+ </strong>
+ <p>
+ {t(
+ "ownership.startFromInstanceBody",
+ "This team has linked servers. On the self-hosted server, open Settings → Users and change the recipient's role to Org Owner. That flow transfers cloud ownership before completing the server transfer.",
+ )}
+ </p>
+ </div>
+ ) : (
+ <>
+ <OwnershipTransferAccounts flow={flow} />
+ <OwnershipTransferMembership flow={flow} />
+ <OwnershipTransferReview flow={flow} />
+ {status?.cloud && canSignIn && !cloudDone && error && (
+ <Button variant="secondary" disabled={busy} onClick={flow.signIn}>
+ {t("ownership.signIn", "Sign in to cloud")}
+ </Button>
+ )}
+ {!status && !busy && (
+ <p className="ownership-flow__muted">
+ {t(
+ "ownership.prepareHelp",
+ "The recipient must have completed their first server login. You can retry here, or return to Users to choose someone else.",
+ )}
+ </p>
+ )}
+ </>
+ )}
+ </div>
+ </FlowModal>
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/OwnershipTransferReview.tsx b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferReview.tsx
new file mode 100644
index 0000000000..b1a2a8d8ee
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/OwnershipTransferReview.tsx
@@ -0,0 +1,152 @@
+import { Trans, useTranslation } from "react-i18next";
+import type { OwnershipTransferFlow } from "@app/components/shared/ownership/useOwnershipTransfer";
+import { Checkbox, Tooltip } from "@mantine/core";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon } from "@app/ui/Icon";
+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
+
+/** Shows the scope before consent, or the remaining local step after cloud ownership commits. */
+export function OwnershipTransferReview({
+ flow,
+}: {
+ flow: OwnershipTransferFlow;
+}) {
+ const { t } = useTranslation();
+ const {
+ status,
+ editing,
+ needsMember,
+ partial,
+ ownerAccount,
+ local,
+ accepted,
+ setAccepted,
+ } = flow;
+ return (
+ <>
+ {status && !editing && !needsMember && (
+ <>
+ {partial ? (
+ <div className="ownership-flow__notice" role="status">
+ {t(
+ "ownership.partialError",
+ "Cloud ownership has transferred. Finish the server transfer to keep both owners aligned.",
+ )}
+ </div>
+ ) : (
+ <>
+ <div className="ownership-flow__summary">
+ {status.cloud && (
+ <>
+ <p>
+ <Trans
+ t={t}
+ i18nKey="ownership.cloudScopeStyled"
+ defaults="<user>{{name}}</user> will manage {{team}}, its members and billing."
+ values={{
+ name: ownerAccount,
+ team: status.cloud.teamName,
+ }}
+ components={{
+ user: <strong className="ownership-flow__username" />,
+ }}
+ />
+ </p>
+ <div className="ownership-flow__detail">
+ <span>
+ {t(
+ "ownership.billingUnchanged",
+ "Subscription and billing stay in place",
+ )}
+ </span>
+ <Tooltip
+ multiline
+ w={300}
+ zIndex={Z_INDEX_OVER_CONFIG_MODAL + 2}
+ events={{ hover: true, focus: true, touch: true }}
+ label={t(
+ "ownership.billing",
+ "The subscription, wallet, payment method and existing licenses stay in place. Billing contact details do not change automatically.",
+ )}
+ >
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ aria-label={t(
+ "ownership.billingDetails",
+ "Billing details",
+ )}
+ >
+ <Icon name="info" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ {status.cloud.linkedInstances > 1 && (
+ <div className="ownership-flow__detail">
+ <span>
+ {t(
+ "ownership.linkedServerCount",
+ "{{count}} linked servers",
+ { count: status.cloud.linkedInstances },
+ )}
+ </span>
+ <Tooltip
+ multiline
+ w={300}
+ zIndex={Z_INDEX_OVER_CONFIG_MODAL + 2}
+ events={{
+ hover: true,
+ focus: true,
+ touch: true,
+ }}
+ label={t(
+ "ownership.instances",
+ "This team has {{count}} linked servers. Their cloud billing stays with this team; other servers' local owners do not change.",
+ { count: status.cloud.linkedInstances },
+ )}
+ >
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ aria-label={t(
+ "ownership.serverDetails",
+ "Linked server details",
+ )}
+ >
+ <Icon name="info" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ )}
+ <p className="ownership-flow__muted">
+ {t(
+ "ownership.yourCloudAccess",
+ "You'll become a team member and lose owner access.",
+ )}
+ </p>
+ </>
+ )}
+ {local && (
+ <p>
+ {t(
+ "ownership.localScope",
+ "They will own this server and manage billing and cloud connections. You keep administrator access, but lose access to those settings.",
+ )}
+ </p>
+ )}
+ </div>
+ <Checkbox
+ checked={accepted}
+ onChange={(event) => setAccepted(event.currentTarget.checked)}
+ label={t(
+ "ownership.confirm",
+ "I understand the access and ownership changes.",
+ )}
+ />
+ </>
+ )}
+ </>
+ )}
+ </>
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/ownershipTransfer.types.ts b/frontend/editor/src/core/components/shared/ownership/ownershipTransfer.types.ts
new file mode 100644
index 0000000000..7dd721d7a0
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/ownershipTransfer.types.ts
@@ -0,0 +1,45 @@
+export interface CloudOwnershipStatus {
+ teamId: number;
+ teamName: string;
+ leaderUserId: number | null;
+ targetUserId: number | null;
+ linkedInstances: number;
+ subscribed: boolean;
+ state: "NEEDS_MEMBERSHIP" | "READY" | "TRANSFERRED";
+}
+
+export interface OwnershipStatus {
+ targetId: number;
+ targetName: string;
+ targetEmail: string | null;
+ cloud: CloudOwnershipStatus | null;
+ cloudEmail?: string | null;
+ candidates?: {
+ teamId: number;
+ teamName: string;
+ members: { id: number; name: string | null; email: string }[];
+ } | null;
+}
+
+/** Callbacks reject on failure; completion must enforce cloud readiness on the server. */
+export interface OwnershipTransferAdapter {
+ local: boolean;
+ prepare: () => Promise<OwnershipStatus>;
+ loadCandidates?: () => Promise<NonNullable<OwnershipStatus["candidates"]>>;
+ selectCloud?: (selection: {
+ cloudUserId?: number;
+ cloudEmail?: string;
+ }) => Promise<OwnershipStatus>;
+ invite?: () => Promise<OwnershipStatus>;
+ transferCloud: (status: OwnershipStatus) => Promise<OwnershipStatus>;
+ completeLocal?: (status: OwnershipStatus) => Promise<void>;
+ cancel?: () => Promise<void>;
+ signIn?: () => void;
+}
+
+export interface OwnershipTransferProps {
+ adapter: OwnershipTransferAdapter;
+ onClose: () => void;
+ /** Runs when the success screen is dismissed, so session refresh cannot hide the result. */
+ onTransferred: () => void;
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/ownershipTransferErrors.ts b/frontend/editor/src/core/components/shared/ownership/ownershipTransferErrors.ts
new file mode 100644
index 0000000000..4dbea95327
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/ownershipTransferErrors.ts
@@ -0,0 +1,92 @@
+import type { TFunction } from "i18next";
+
+/** Resolves recovery guidance without hiding a specific failure after cloud completion. */
+export function ownershipErrorText(
+ t: TFunction,
+ error: string | null,
+ partial: boolean,
+) {
+ if (error?.includes("ACCOUNT_LINK_DISABLED"))
+ return t(
+ "ownership.accountLinkDisabled",
+ "This server still has a cloud link, but account linking is turned off. Ask the server operator to enable account linking, then resume this transfer or unlink the server in settings.",
+ );
+ if (error?.includes("LINK_REVOKED"))
+ return t(
+ "ownership.linkRevoked",
+ "This server's cloud link is no longer valid. Cancel the transfer, then reconnect your Stirling account in settings. Ownership will not change.",
+ );
+ if (error?.includes("FINISH_LOCAL_TRANSFER"))
+ return t(
+ "ownership.partialError",
+ "Cloud ownership has transferred. Finish the server transfer to keep both owners aligned.",
+ );
+ if (
+ error?.includes("CLOUD_SIGN_IN_REQUIRED") ||
+ error?.includes("CLOUD_OWNER_REQUIRED")
+ )
+ return t(
+ "ownership.ownerRequired",
+ "Sign in as the current cloud team owner, then try this step again.",
+ );
+ if (error?.includes("PERSONAL_TEAM"))
+ return t(
+ "ownership.personalTeam",
+ "Personal teams cannot transfer ownership.",
+ );
+ if (error?.includes("MEMBERSHIP_REQUIRED"))
+ return t(
+ "ownership.membershipRequired",
+ "The recipient must join this cloud team before ownership can transfer. Ask them to accept their invitation, then check again.",
+ );
+ if (error?.includes("INVITATION_BLOCKED"))
+ return t(
+ "ownership.inviteBlocked",
+ "The invitation could not be sent. Check available team seats and whether the recipient already has a paid subscription.",
+ );
+ if (error?.includes("CLOUD_OWNER_CHANGED"))
+ return t(
+ "ownership.ownerChanged",
+ "Cloud ownership changed after this transfer started. Cancel this transfer and start again with the current cloud owner.",
+ );
+ if (
+ error?.includes("CLOUD_TARGET_CHANGED") ||
+ error?.includes("CHOOSE_ANOTHER_CLOUD_USER")
+ )
+ return t(
+ "ownership.cloudTargetChanged",
+ "Choose another cloud member. This account is no longer eligible for the handover.",
+ );
+ if (
+ error?.includes("TARGET_CHANGED") ||
+ error?.includes("TARGET_UNAVAILABLE")
+ )
+ return partial
+ ? t(
+ "ownership.partialTargetChanged",
+ "Restore the selected server user's access and original account details, then finish the server transfer. Cloud ownership has already transferred.",
+ )
+ : t(
+ "ownership.targetChanged",
+ "The recipient's account changed. Restore their access or cancel this transfer and choose them again.",
+ );
+ if (error?.includes("HANDOVER_IN_PROGRESS"))
+ return t(
+ "ownership.inProgress",
+ "Another recipient already has a pending transfer. Close this dialog and resume it from Users.",
+ );
+ if (error?.includes("LINK_CHANGED"))
+ return t(
+ "ownership.linkChanged",
+ "The server's cloud link changed. Ask the server operator to restore the original link before resuming.",
+ );
+ if (partial)
+ return t(
+ "ownership.partialError",
+ "Cloud ownership has transferred. Finish the server transfer to keep both owners aligned.",
+ );
+ return t(
+ "ownership.error",
+ "We couldn't complete this step. Check the recipient is active and the server is connected, then check again. A pending transfer can be resumed here.",
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/ownership/useOwnershipTransfer.ts b/frontend/editor/src/core/components/shared/ownership/useOwnershipTransfer.ts
new file mode 100644
index 0000000000..97d41036db
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/ownership/useOwnershipTransfer.ts
@@ -0,0 +1,318 @@
+import { useEffect, useRef, useState } from "react";
+import { useCombobox } from "@mantine/core";
+import type {
+ OwnershipStatus,
+ OwnershipTransferProps,
+} from "@app/components/shared/ownership/ownershipTransfer.types";
+
+function ownershipError(cause: unknown): string {
+ if (!cause || typeof cause !== "object") return "UNKNOWN";
+ const error = cause as {
+ body?: { detail?: string };
+ response?: { data?: { detail?: string } };
+ message?: string;
+ };
+ return (
+ error.body?.detail ??
+ error.response?.data?.detail ??
+ error.message ??
+ "UNKNOWN"
+ );
+}
+
+/** One recipient per mount; serializes mutations and reconciles uncertain cloud completion before retry. */
+export function useOwnershipTransfer({
+ adapter,
+ onClose,
+ onTransferred,
+}: OwnershipTransferProps) {
+ const [status, setStatus] = useState<OwnershipStatus | null>(null);
+ const [busy, setBusy] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [invited, setInvited] = useState(false);
+ const [accepted, setAccepted] = useState(false);
+ const [done, setDone] = useState(false);
+ const [search, setSearch] = useState("");
+ const [candidates, setCandidates] =
+ useState<OwnershipStatus["candidates"]>(null);
+ const picker = useCombobox({
+ onDropdownClose: () => picker.resetSelectedOption(),
+ });
+ const working = useRef(false);
+ const dismissed = useRef(false);
+ const initialAdapter = useRef(adapter);
+
+ useEffect(() => {
+ let active = true;
+ initialAdapter.current
+ .prepare()
+ .then(
+ (value) => {
+ if (active) {
+ setStatus(value);
+ setCandidates(value.candidates);
+ setSearch(
+ value.cloud ? (value.cloudEmail ?? value.targetEmail ?? "") : "",
+ );
+ }
+ },
+ (cause) => {
+ if (active) setError(ownershipError(cause));
+ },
+ )
+ .finally(() => {
+ if (active) setBusy(false);
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ const needsMember = status?.cloud?.state === "NEEDS_MEMBERSHIP";
+ const cloudDone = status?.cloud?.state === "TRANSFERRED";
+ const partial = adapter.local && cloudDone && !done;
+ const canCancel = Boolean(
+ adapter.local &&
+ adapter.cancel &&
+ status &&
+ !status.candidates &&
+ !partial &&
+ !done,
+ );
+ const startFromInstance =
+ !adapter.local &&
+ ((status?.cloud?.linkedInstances ?? 0) > 0 ||
+ Boolean(error?.includes("START_TRANSFER_FROM_INSTANCE")));
+
+ async function run(action: () => Promise<void>) {
+ if (working.current) return;
+ working.current = true;
+ setBusy(true);
+ setError(null);
+ try {
+ await action();
+ } catch (cause) {
+ setError(ownershipError(cause));
+ } finally {
+ working.current = false;
+ setBusy(false);
+ }
+ }
+
+ async function transfer() {
+ if (!status || status.candidates || startFromInstance) return;
+ let next = status;
+ try {
+ if (next.cloud && next.cloud.state !== "TRANSFERRED") {
+ next = await adapter.transferCloud(next);
+ setStatus(next);
+ }
+ if (adapter.local) await adapter.completeLocal!(next);
+ setDone(true);
+ } catch (cause) {
+ // A lost cloud response may have committed. Read its state before offering any retry.
+ try {
+ setStatus(await adapter.prepare());
+ } catch {
+ /* Keep the last confirmed state. */
+ }
+ throw cause;
+ }
+ }
+
+ function close() {
+ if (busy || working.current || dismissed.current) return;
+ if (done) {
+ dismissed.current = true;
+ onTransferred();
+ onClose();
+ return;
+ }
+ if (canCancel) {
+ void run(async () => {
+ try {
+ await adapter.cancel!();
+ } finally {
+ onClose();
+ }
+ });
+ } else {
+ onClose();
+ }
+ }
+
+ const choosing = Boolean(status?.candidates);
+ const linked = Boolean(status?.cloud || choosing);
+ const cloudEmail = status?.cloudEmail ?? status?.targetEmail;
+ const ownerAccount = adapter.local
+ ? status?.targetName
+ : (cloudEmail ?? status?.targetName);
+ const email = search.trim();
+ const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
+ const members = (candidates?.members ?? []).filter((member) =>
+ member.email.toLowerCase().includes(email.toLowerCase()),
+ );
+ const matchingMember = candidates?.members.find(
+ (member) => member.email.toLowerCase() === email.toLowerCase(),
+ );
+ const editing =
+ choosing ||
+ Boolean(
+ adapter.selectCloud &&
+ status?.cloud &&
+ email.toLowerCase() !== (cloudEmail ?? "").toLowerCase(),
+ );
+ const teamName = status?.cloud?.teamName ?? candidates?.teamName;
+
+ async function refresh() {
+ const next = await adapter.prepare();
+ setStatus(next);
+ if (next.candidates) setCandidates(next.candidates);
+ setSearch(next.cloud ? (next.cloudEmail ?? next.targetEmail ?? "") : "");
+ setAccepted(false);
+ }
+
+ async function resetSelection() {
+ await adapter.cancel!();
+ const next = await adapter.prepare();
+ setStatus(next);
+ if (next.candidates) setCandidates(next.candidates);
+ setAccepted(false);
+ setInvited(false);
+ if (!next.candidates) throw new Error("CLOUD_TARGET_CHANGED");
+ }
+
+ function editEmail(value: string) {
+ setSearch(value);
+ if (status?.candidates) setError(null);
+ setAccepted(false);
+ setInvited(false);
+ picker.resetSelectedOption();
+ picker.openDropdown();
+ if (status?.cloud && !working.current) void run(resetSelection);
+ }
+
+ async function selectAccount(selection: {
+ cloudUserId?: number;
+ cloudEmail?: string;
+ }) {
+ if (!adapter.selectCloud) return null;
+ if (
+ status?.cloud &&
+ ((selection.cloudUserId != null &&
+ selection.cloudUserId === status.cloud.targetUserId) ||
+ (selection.cloudEmail != null &&
+ selection.cloudEmail.toLowerCase() === cloudEmail?.toLowerCase()))
+ )
+ return status;
+ if (status?.cloud) await resetSelection();
+ const next = await adapter.selectCloud(selection);
+ setStatus(next);
+ setSearch(next.cloudEmail ?? next.targetEmail ?? "");
+ setAccepted(false);
+ setInvited(false);
+ return next;
+ }
+
+ function focusAccount() {
+ picker.openDropdown();
+ if (
+ status?.cloud &&
+ !candidates &&
+ adapter.loadCandidates &&
+ !working.current
+ )
+ void run(async () => {
+ setCandidates(await adapter.loadCandidates!());
+ });
+ }
+
+ function selectMember(id: number) {
+ picker.closeDropdown();
+ void run(async () => {
+ await selectAccount({ cloudUserId: id });
+ });
+ }
+
+ function checkAccount() {
+ picker.closeDropdown();
+ void run(async () => {
+ const next = await selectAccount(
+ matchingMember
+ ? { cloudUserId: matchingMember.id }
+ : { cloudEmail: email },
+ );
+ if (next?.cloud?.state === "NEEDS_MEMBERSHIP" && !matchingMember) {
+ setStatus(await adapter.invite!());
+ setInvited(true);
+ }
+ });
+ }
+
+ function invite() {
+ void run(async () => {
+ setStatus(await adapter.invite!());
+ setInvited(true);
+ });
+ }
+
+ function cancel() {
+ void run(async () => {
+ await adapter.cancel!();
+ onClose();
+ });
+ }
+
+ function signIn() {
+ onClose();
+ adapter.signIn?.();
+ }
+
+ return {
+ status,
+ busy,
+ error,
+ invited,
+ accepted,
+ done,
+ search,
+ picker,
+ needsMember,
+ cloudDone,
+ partial,
+ startFromInstance,
+ linked,
+ cloudEmail,
+ ownerAccount,
+ email,
+ emailValid,
+ members,
+ matchingMember,
+ editing,
+ teamName,
+ local: adapter.local,
+ canSelectCloud: Boolean(adapter.selectCloud),
+ canInvite: Boolean(adapter.invite),
+ canCancelRecovery: Boolean(
+ adapter.local &&
+ adapter.cancel &&
+ !partial &&
+ !done &&
+ /\b(LINK_REVOKED|TARGET_CHANGED|TARGET_UNAVAILABLE)\b/.test(error ?? ""),
+ ),
+ canSignIn: Boolean(adapter.signIn),
+ close,
+ editEmail,
+ setAccepted,
+ focusAccount,
+ selectMember,
+ checkAccount,
+ invite,
+ cancel,
+ signIn,
+ refresh: () => void run(refresh),
+ transfer: () => void run(transfer),
+ };
+}
+
+export type OwnershipTransferFlow = ReturnType<typeof useOwnershipTransfer>;
diff --git a/frontend/editor/src/core/ui/Modal.tsx b/frontend/editor/src/core/ui/Modal.tsx
index 3c31acc6be..21c1b58c18 100644
--- a/frontend/editor/src/core/ui/Modal.tsx
+++ b/frontend/editor/src/core/ui/Modal.tsx
@@ -24,6 +24,7 @@ export interface ModalProps {
/** Accessible name when no visible title is provided. */
ariaLabel?: string;
className?: string;
+ zIndex?: number;
children?: ReactNode;
}
@@ -41,6 +42,7 @@ export function Modal({
disableEscapeClose = false,
ariaLabel,
className,
+ zIndex,
children,
}: ModalProps) {
const titleId = useId();
@@ -79,6 +81,7 @@ export function Modal({
return createPortal(
<div
className="sui-modal__backdrop"
+ style={zIndex === undefined ? undefined : { zIndex }}
onClick={onBackdropClick}
role="presentation"
>
diff --git a/frontend/editor/src/desktop/auth/selfHostedSession.test.tsx b/frontend/editor/src/desktop/auth/selfHostedSession.test.tsx
new file mode 100644
index 0000000000..a3646488ea
--- /dev/null
+++ b/frontend/editor/src/desktop/auth/selfHostedSession.test.tsx
@@ -0,0 +1,132 @@
+import { beforeEach, expect, it, vi } from "vitest";
+import { renderHook, waitFor } from "@testing-library/react";
+import axios, { AxiosError, type InternalAxiosRequestConfig } from "axios";
+import { configureSpringAuth } from "@app/auth/config";
+import { defaultPlatformBridge } from "@app/auth/spring/platformBridge";
+import * as desktopBridge from "@app/extensions/platformSessionBridge";
+import { springAuth } from "@app/auth/spring/springAuthClient";
+import { SpringAuthProvider } from "@app/auth/spring/UseSession";
+import { useAuth } from "@app/auth/context";
+import { authService } from "@app/services/authService";
+
+const state = vi.hoisted(() => ({ mode: "selfhosted" }));
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: { getCurrentMode: async () => state.mode },
+}));
+vi.mock("@app/services/authService", () => ({
+ authService: {
+ getUserInfo: vi.fn(),
+ saveToken: vi.fn(),
+ refreshSupabaseToken: vi.fn(),
+ },
+}));
+const http = axios.create();
+const get = vi.spyOn(http, "get");
+const post = vi.spyOn(http, "post");
+const token =
+ btoa(JSON.stringify({ alg: "HS256" })) +
+ "." +
+ btoa(
+ JSON.stringify({ iat: Math.floor(Date.now() / 1000), exp: 4102444800 }),
+ ) +
+ ".test";
+const serverUser = {
+ id: "42",
+ username: "ConnorYoh",
+ email: "[email protected]",
+ role: "ROLE_ADMIN",
+ orgOwner: true,
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ state.mode = "selfhosted";
+ localStorage.clear();
+ localStorage.setItem("stirling_jwt", token);
+ configureSpringAuth({
+ http,
+ platform: { ...defaultPlatformBridge, ...desktopBridge },
+ });
+ vi.mocked(authService.getUserInfo).mockResolvedValue({
+ username: "cached-name",
+ });
+ vi.mocked(authService.saveToken).mockResolvedValue(undefined);
+});
+
+it.each([true, false])(
+ "loads server role and ownership into the desktop auth context: owner=%s",
+ async (orgOwner) => {
+ get.mockResolvedValue({ data: { user: { ...serverUser, orgOwner } } });
+ const { result } = renderHook(() => useAuth(), {
+ wrapper: SpringAuthProvider,
+ });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(get).toHaveBeenCalledWith(
+ "/api/v1/auth/me",
+ expect.objectContaining({
+ headers: { Authorization: "Bearer " + token },
+ }),
+ );
+ expect(result.current.isAdmin).toBe(true);
+ expect(result.current.user?.orgOwner).toBe(orgOwner);
+ expect(result.current.user?.username).toBe("ConnorYoh");
+ expect(authService.getUserInfo).not.toHaveBeenCalled();
+ },
+);
+
+it("does not use a cached identity when the server rejects the session", async () => {
+ const denied = new AxiosError(
+ "Unauthorized",
+ "ERR_BAD_REQUEST",
+ undefined,
+ undefined,
+ {
+ status: 401,
+ statusText: "Unauthorized",
+ data: {},
+ headers: {},
+ config: {} as InternalAxiosRequestConfig,
+ },
+ );
+ get.mockRejectedValue(denied);
+ post.mockRejectedValue(denied);
+ const { result } = renderHook(() => useAuth(), {
+ wrapper: SpringAuthProvider,
+ });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.user).toBeNull();
+ expect(result.current.isAdmin).toBe(false);
+ expect(authService.getUserInfo).not.toHaveBeenCalled();
+});
+
+it("keeps SaaS on its platform session path", async () => {
+ state.mode = "saas";
+ const { result } = renderHook(() => useAuth(), {
+ wrapper: SpringAuthProvider,
+ });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.user?.username).toBe("cached-name");
+ expect(result.current.user?.role).toBe("USER");
+ expect(result.current.user?.orgOwner).toBeUndefined();
+ expect(get).not.toHaveBeenCalled();
+ expect(post).not.toHaveBeenCalled();
+});
+
+it("persists a refreshed self-hosted token and the server's updated ownership", async () => {
+ post.mockResolvedValue({
+ data: {
+ user: { ...serverUser, orgOwner: false },
+ session: { access_token: token, expires_in: 3600 },
+ },
+ });
+ const response = await springAuth.refreshSession();
+ expect(response.error).toBeNull();
+ expect(response.data.session?.user.orgOwner).toBe(false);
+ expect(post).toHaveBeenCalledWith(
+ "/api/v1/auth/refresh",
+ null,
+ expect.any(Object),
+ );
+ expect(authService.saveToken).toHaveBeenCalledWith(token);
+ expect(authService.refreshSupabaseToken).not.toHaveBeenCalled();
+});
diff --git a/frontend/editor/src/desktop/components/settings/BillingSettingsSection.test.tsx b/frontend/editor/src/desktop/components/settings/BillingSettingsSection.test.tsx
new file mode 100644
index 0000000000..2191365ec4
--- /dev/null
+++ b/frontend/editor/src/desktop/components/settings/BillingSettingsSection.test.tsx
@@ -0,0 +1,154 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { BillingSettingsSection } from "@app/components/settings/BillingSettingsSection";
+import { connectionModeService } from "@app/services/connectionModeService";
+import { openExternal } from "@app/platform/openExternal";
+
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ }),
+}));
+vi.mock("@app/platform/openExternal", () => ({ openExternal: vi.fn() }));
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: { getCurrentConfig: vi.fn() },
+}));
+beforeEach(() => {
+ vi.mocked(connectionModeService.getCurrentConfig).mockResolvedValue({
+ mode: "saas",
+ server_config: null,
+ lock_connection_mode: false,
+ });
+ vi.mocked(openExternal).mockReset();
+});
+afterEach(() => vi.unstubAllEnvs());
+
+function show(mode: "saas" | "selfhosted" = "saas") {
+ render(
+ <MantineProvider>
+ <BillingSettingsSection mode={mode} />
+ </MantineProvider>,
+ );
+}
+
+it.each(["https://cloud.example/app", "https://cloud.example/app/"])(
+ "opens current billing under the configured web path: %s",
+ async (base) => {
+ vi.stubEnv("VITE_SAAS_FRONTEND_URL", base);
+ vi.mocked(openExternal).mockResolvedValue(undefined);
+ show();
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(
+ screen.getByText(/Sign in with the same Stirling account/),
+ ).toBeVisible();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open Usage & Billing in browser" }),
+ );
+ await waitFor(() =>
+ expect(openExternal).toHaveBeenCalledWith(
+ "https://cloud.example/app/settings/billing",
+ ),
+ );
+ },
+);
+
+it("lets the user retry when the system browser cannot open", async () => {
+ vi.stubEnv("VITE_SAAS_FRONTEND_URL", "https://cloud.example/app");
+ vi.mocked(openExternal)
+ .mockRejectedValueOnce(new Error("Shell unavailable"))
+ .mockResolvedValueOnce(undefined);
+ show();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open Usage & Billing in browser" }),
+ );
+ expect(
+ await screen.findByText(/Could not open Usage & Billing/),
+ ).toBeVisible();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open Usage & Billing in browser" }),
+ );
+ await waitFor(() => expect(openExternal).toHaveBeenCalledTimes(2));
+ expect(screen.queryByText(/Could not open Usage & Billing/)).toBeNull();
+});
+
+it.each([
+ [
+ "https://server.example/stirling/",
+ "https://server.example/stirling/settings/billing",
+ ],
+ ["http://localhost:8080", "http://localhost:8080/settings/billing"],
+ [
+ "https://user:[email protected]/stirling?token=private#section",
+ "https://server.example/stirling/settings/billing",
+ ],
+])("opens the connected server's billing page: %s", async (base, expected) => {
+ vi.mocked(connectionModeService.getCurrentConfig).mockResolvedValue({
+ mode: "selfhosted",
+ server_config: { url: base },
+ lock_connection_mode: false,
+ });
+ vi.mocked(openExternal).mockResolvedValue(undefined);
+ show("selfhosted");
+ expect(
+ screen.getByText(/Sign in with your server owner account/),
+ ).toBeVisible();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open Usage & Billing in browser" }),
+ );
+ await waitFor(() => expect(openExternal).toHaveBeenCalledWith(expected));
+});
+
+it.each([null, "not-a-url", "javascript:alert(1)", "file:///tmp/server"])(
+ "does not fall back to SaaS for an invalid server URL: %s",
+ async (base) => {
+ vi.mocked(connectionModeService.getCurrentConfig).mockResolvedValue({
+ mode: "selfhosted",
+ server_config: base ? { url: base } : null,
+ lock_connection_mode: false,
+ });
+ show("selfhosted");
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open Usage & Billing in browser" }),
+ );
+ expect(
+ await screen.findByText(/Could not open Usage & Billing/),
+ ).toBeVisible();
+ expect(openExternal).not.toHaveBeenCalled();
+ },
+);
+
+it("reads the current server when opening billing", async () => {
+ show("selfhosted");
+ vi.mocked(connectionModeService.getCurrentConfig).mockResolvedValue({
+ mode: "selfhosted",
+ server_config: { url: "https://new-server.example" },
+ lock_connection_mode: false,
+ });
+ vi.mocked(openExternal).mockResolvedValue(undefined);
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open Usage & Billing in browser" }),
+ );
+ await waitFor(() =>
+ expect(openExternal).toHaveBeenCalledWith(
+ "https://new-server.example/settings/billing",
+ ),
+ );
+});
+
+it("does not open a stale billing destination after switching to local mode", async () => {
+ show();
+ vi.mocked(connectionModeService.getCurrentConfig).mockResolvedValue({
+ mode: "local",
+ server_config: null,
+ lock_connection_mode: false,
+ });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open Usage & Billing in browser" }),
+ );
+ expect(
+ await screen.findByText(/Could not open Usage & Billing/),
+ ).toBeVisible();
+ expect(openExternal).not.toHaveBeenCalled();
+});
diff --git a/frontend/editor/src/desktop/components/settings/BillingSettingsSection.tsx b/frontend/editor/src/desktop/components/settings/BillingSettingsSection.tsx
new file mode 100644
index 0000000000..1340e4f567
--- /dev/null
+++ b/frontend/editor/src/desktop/components/settings/BillingSettingsSection.tsx
@@ -0,0 +1,72 @@
+import { useState } from "react";
+import { Stack, Text } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import { Banner } from "@app/ui/Banner";
+import { openExternal } from "@app/platform/openExternal";
+import { connectionModeService } from "@app/services/connectionModeService";
+
+/** Billing runs on the web because desktop does not ship the processor's billing UI. */
+export function BillingSettingsSection({
+ mode,
+}: {
+ mode: "saas" | "selfhosted";
+}) {
+ const { t } = useTranslation();
+ const [opening, setOpening] = useState(false);
+ const [failed, setFailed] = useState(false);
+
+ async function openBilling() {
+ setOpening(true);
+ setFailed(false);
+ try {
+ const connection = await connectionModeService.getCurrentConfig();
+ if (connection.mode !== mode) throw new Error("Connection changed");
+ const base =
+ mode === "saas"
+ ? import.meta.env.VITE_SAAS_FRONTEND_URL
+ : connection.server_config?.url;
+ if (!base) throw new Error("Billing destination unavailable");
+ const url = new URL(base);
+ if (url.protocol !== "https:" && url.protocol !== "http:")
+ throw new Error("Invalid billing destination");
+ url.pathname = `${url.pathname.replace(/\/+$/, "")}/settings/billing`;
+ url.search = "";
+ url.hash = "";
+ url.username = "";
+ url.password = "";
+ await openExternal(url.href);
+ } catch {
+ setFailed(true);
+ } finally {
+ setOpening(false);
+ }
+ }
+
+ return (
+ <Stack align="flex-start">
+ <Text>
+ {mode === "selfhosted"
+ ? t(
+ "desktopBilling.selfHostedDescription",
+ "Manage usage and billing on your connected server in your browser. Sign in with your server owner account.",
+ )
+ : t(
+ "desktopBilling.description",
+ "Manage usage and billing in your browser. Sign in with the same Stirling account you use here.",
+ )}
+ </Text>
+ {failed && (
+ <Banner tone="danger">
+ {t(
+ "desktopBilling.openFailed",
+ "Could not open Usage & Billing. Check your connection and try again.",
+ )}
+ </Banner>
+ )}
+ <Button loading={opening} onClick={() => void openBilling()}>
+ {t("desktopBilling.open", "Open Usage & Billing in browser")}
+ </Button>
+ </Stack>
+ );
+}
diff --git a/frontend/editor/src/desktop/components/settings/useSettingsNav.test.tsx b/frontend/editor/src/desktop/components/settings/useSettingsNav.test.tsx
new file mode 100644
index 0000000000..834a71c048
--- /dev/null
+++ b/frontend/editor/src/desktop/components/settings/useSettingsNav.test.tsx
@@ -0,0 +1,230 @@
+import { beforeEach, it, expect, vi } from "vitest";
+import { renderHook, waitFor } from "@testing-library/react";
+import { useSettingsNav } from "@app/components/settings/useSettingsNav";
+
+const state = vi.hoisted(() => ({
+ mode: "saas",
+ authenticated: true,
+ roster: false,
+ owner: false,
+ loading: false,
+ connectionFails: false,
+ workspace: true,
+}));
+vi.mock("@proprietary/components/shared/config/configNavSections", () => ({
+ useConfigNavSections: () => [
+ {
+ id: "preferences",
+ title: "Preferences",
+ items: [{ key: "general", label: "Preferences", component: null }],
+ },
+ ...(state.workspace
+ ? [
+ {
+ id: "workspace",
+ title: "Workspace",
+ items: [
+ { key: "users", label: "Users", component: null },
+ { key: "plan", label: "Old plan", component: null },
+ { key: "adminPlan", label: "Old admin plan", component: null },
+ ],
+ },
+ ]
+ : []),
+ ],
+}));
+vi.mock("@app/components/shared/config/configSections/GeneralSection", () => ({
+ default: () => null,
+}));
+vi.mock("@app/components/ConnectionSettings", () => ({
+ ConnectionSettings: () => null,
+}));
+vi.mock("@app/components/shared/config/cloudConfigNavSections", () => ({
+ createCloudTeamNavItem: () => ({
+ key: "users",
+ label: "Users",
+ component: null,
+ }),
+}));
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCurrentMode: async () => {
+ if (state.connectionFails)
+ throw new Error("Connection config unavailable");
+ return state.mode;
+ },
+ subscribeToModeChanges: () => () => {},
+ },
+}));
+vi.mock("@app/services/authService", () => ({
+ authService: {
+ subscribeToAuth: (listener: (status: string) => void) => {
+ listener(state.authenticated ? "authenticated" : "unauthenticated");
+ return () => {};
+ },
+ },
+}));
+vi.mock("@app/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { isAdmin: true } }),
+}));
+vi.mock("@app/auth/context", () => ({
+ useAuth: () => ({
+ isAdmin: true,
+ user: { orgOwner: state.owner },
+ loading: state.loading,
+ }),
+}));
+vi.mock("@app/hooks/usePortalAccess", () => ({
+ usePortalAccessState: () => ({ granted: false, settled: true }),
+}));
+vi.mock("@app/hooks/useRosterAvailable", () => ({
+ useRosterAvailable: () => state.roster,
+}));
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ }),
+}));
+vi.mock("@app/platform/openExternal", () => ({ openExternal: vi.fn() }));
+
+beforeEach(() => {
+ state.mode = "saas";
+ state.authenticated = true;
+ state.roster = false;
+ state.owner = false;
+ state.loading = false;
+ state.connectionFails = false;
+ state.workspace = true;
+});
+
+it("finishes loading without billing when the connection lookup fails", async () => {
+ state.connectionFails = true;
+ state.owner = true;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ await waitFor(() => expect(result.current.pending).toBe(false));
+ const keys = result.current.sections.flatMap((group) =>
+ group.items.map((item) => item.key),
+ );
+ expect(keys).toContain("general");
+ expect(keys).toContain("connectionMode");
+ expect(keys).not.toContain("billing");
+ expect(result.current.aliases?.plan).toBeUndefined();
+});
+
+it.each([false, true])(
+ "keeps one Workspace group for a self-hosted owner with roster=%s",
+ async (roster) => {
+ state.mode = "selfhosted";
+ state.owner = true;
+ state.roster = roster;
+ const { result, rerender } = renderHook(() => useSettingsNav(vi.fn()));
+ await waitFor(() => expect(result.current.pending).toBe(false));
+ rerender();
+ const workspaces = result.current.sections.filter(
+ (group) => group.id === "workspace",
+ );
+ expect(workspaces).toHaveLength(1);
+ const keys = workspaces[0].items.map((item) => item.key);
+ expect(keys).toContain("users");
+ expect(keys.filter((key) => key === "billing")).toHaveLength(1);
+ },
+);
+
+it("creates a Workspace group when the self-hosted owner has none", async () => {
+ state.mode = "selfhosted";
+ state.owner = true;
+ state.workspace = false;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ await waitFor(() => expect(result.current.pending).toBe(false));
+ const workspaces = result.current.sections.filter(
+ (group) => group.id === "workspace",
+ );
+ expect(workspaces).toHaveLength(1);
+ expect(workspaces[0].items.map((item) => item.key)).toEqual(["billing"]);
+});
+
+it("waits for the connection before resolving an old billing bookmark", async () => {
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ expect(result.current.pending).toBe(true);
+ await waitFor(() => expect(result.current.pending).toBe(false));
+ expect(result.current.aliases?.plan).toBe("billing");
+});
+
+it.each([false, true])(
+ "routes old Plan links to web billing with roster=%s",
+ async (roster) => {
+ state.roster = roster;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ await waitFor(() => expect(result.current.aliases?.plan).toBe("billing"));
+ const items = result.current.sections.flatMap((group) => group.items);
+ expect(items.find((item) => item.key === "billing")?.label).toBe(
+ "Usage & Billing",
+ );
+ expect(items.some((item) => ["plan", "adminPlan"].includes(item.key))).toBe(
+ false,
+ );
+ expect(result.current.aliases?.adminPlan).toBe("billing");
+ expect(result.current.aliases?.help).toBe("about");
+ },
+);
+
+it.each([
+ ["local", true],
+ ["selfhosted", true],
+ ["saas", false],
+])(
+ "does not offer cloud billing for mode=%s authenticated=%s",
+ async (mode, authenticated) => {
+ state.mode = mode;
+ state.authenticated = authenticated;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ await waitFor(() =>
+ expect(
+ result.current.sections.some((group) =>
+ group.items.some((item) => item.key === "connectionMode"),
+ ),
+ ).toBe(true),
+ );
+ const keys = result.current.sections.flatMap((group) =>
+ group.items.map((item) => item.key),
+ );
+ expect(keys).not.toContain("billing");
+ expect(keys).not.toContain("plan");
+ expect(keys).not.toContain("adminPlan");
+ expect(result.current.aliases?.plan).toBeUndefined();
+ },
+);
+
+it("offers self-hosted billing only to the current organisation owner", async () => {
+ state.mode = "selfhosted";
+ state.owner = true;
+ const { result, rerender } = renderHook(() => useSettingsNav(vi.fn()));
+ await waitFor(() => expect(result.current.pending).toBe(false));
+ const billing = () =>
+ result.current.sections
+ .flatMap((group) => group.items)
+ .some((item) => item.key === "billing");
+ expect(billing()).toBe(true);
+ expect(result.current.aliases?.plan).toBe("billing");
+ state.loading = true;
+ rerender();
+ expect(billing()).toBe(false);
+ state.loading = false;
+ state.owner = false;
+ rerender();
+ expect(billing()).toBe(false);
+ expect(result.current.aliases?.plan).toBeUndefined();
+});
+
+it("does not offer billing to a local-mode owner", async () => {
+ state.mode = "local";
+ state.owner = true;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ await waitFor(() => expect(result.current.pending).toBe(false));
+ expect(
+ result.current.sections
+ .flatMap((group) => group.items)
+ .some((item) => item.key === "billing"),
+ ).toBe(false);
+});
diff --git a/frontend/editor/src/desktop/components/settings/useSettingsNav.tsx b/frontend/editor/src/desktop/components/settings/useSettingsNav.tsx
index 7975a2ce80..6a091f6180 100644
--- a/frontend/editor/src/desktop/components/settings/useSettingsNav.tsx
+++ b/frontend/editor/src/desktop/components/settings/useSettingsNav.tsx
@@ -1,4 +1,34 @@
-/** Takes proprietary's seam for the roster, a portal module desktop does ship;
- * the processor's own sections resolve to null here (HAS_PORTAL is false). */
-export { useSettingsNav } from "@proprietary/components/settings/useSettingsNav";
-export type { SettingsNav } from "@app/components/settings/settingsNavTypes";
+import { useEffect, useState } from "react";
+import { useSettingsNav as useProprietarySettingsNav } from "@proprietary/components/settings/useSettingsNav";
+import type { SettingsNav } from "@app/components/settings/settingsNavTypes";
+import { connectionModeService } from "@app/services/connectionModeService";
+
+export type { SettingsNav };
+
+/** Desktop billing opens on the web; existing Plan links land on its browser handoff. */
+export function useSettingsNav(onLeave: () => void): SettingsNav {
+ const nav = useProprietarySettingsNav(onLeave);
+ const [connectionReady, setConnectionReady] = useState(false);
+ useEffect(() => {
+ let active = true;
+ void connectionModeService
+ .getCurrentMode()
+ .catch(() => undefined)
+ .finally(() => {
+ if (active) setConnectionReady(true);
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+ const hasBilling = nav.sections.some((group) =>
+ group.items.some((item) => item.key === "billing"),
+ );
+ return {
+ ...nav,
+ pending: nav.pending || !connectionReady,
+ aliases: hasBilling
+ ? { ...nav.aliases, plan: "billing", adminPlan: "billing" }
+ : nav.aliases,
+ };
+}
diff --git a/frontend/editor/src/desktop/components/shared/config/configNavSections.tsx b/frontend/editor/src/desktop/components/shared/config/configNavSections.tsx
index 9da55492dc..0a619dbf6a 100644
--- a/frontend/editor/src/desktop/components/shared/config/configNavSections.tsx
+++ b/frontend/editor/src/desktop/components/shared/config/configNavSections.tsx
@@ -4,12 +4,11 @@ import { useConfigNavSections as useProprietaryConfigNavSections } from "@propri
import { ConfigNavSection } from "@core/components/shared/config/configNavSections";
import { ConnectionSettings } from "@app/components/ConnectionSettings";
import DesktopGeneralSection from "@app/components/shared/config/configSections/GeneralSection";
-import {
- createCloudPlanNavItem,
- createCloudTeamNavItem,
-} from "@app/components/shared/config/cloudConfigNavSections";
+import { createCloudTeamNavItem } from "@app/components/shared/config/cloudConfigNavSections";
+import { BillingSettingsSection } from "@app/components/settings/BillingSettingsSection";
import { connectionModeService } from "@app/services/connectionModeService";
import { authService } from "@app/services/authService";
+import { useAuth } from "@app/auth/context";
export type {
ConfigNavSection,
@@ -27,15 +26,27 @@ export const useConfigNavSections = (
showSettingsWhenNoLogin: boolean = true,
): ConfigNavSection[] => {
const { t } = useTranslation();
+ const { isAdmin: authenticatedAdmin, user, loading } = useAuth();
+ const isOwner = authenticatedAdmin && !loading && user?.orgOwner === true;
const [connectionMode, setConnectionMode] = useState<string | null>(null);
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
useEffect(() => {
- void connectionModeService.getCurrentMode().then(setConnectionMode);
- return connectionModeService.subscribeToModeChanges((config) =>
+ let active = true;
+ void connectionModeService.getCurrentMode().then(
+ (mode) => {
+ if (active) setConnectionMode(mode);
+ },
+ () => undefined,
+ );
+ const unsubscribe = connectionModeService.subscribeToModeChanges((config) =>
setConnectionMode(config.mode),
);
+ return () => {
+ active = false;
+ unsubscribe();
+ };
}, []);
// Subscribe to auth changes
@@ -56,7 +67,7 @@ export const useConfigNavSections = (
loginEnabled,
onRequestClose,
showSettingsWhenNoLogin,
- );
+ ).slice();
// Desktop adds file-association defaults and its own update controls to the
// Preferences page; core builds the page, desktop supplies its extras.
@@ -116,15 +127,38 @@ export const useConfigNavSections = (
// Connection Mode always sits immediately after Preferences
result.push(connectionModeSection);
- // Plan & Billing and Team sections only when authenticated in SaaS mode.
- // These are the SHARED cloud sections — the wallet-driven PAYG Plan
- // (dashboard + spend cap) and the team management UI — so a desktop SaaS
- // user sees the same Plan / billing / team experience as the web app.
+ if (
+ isAuthenticated &&
+ (isSaasMode || (connectionMode === "selfhosted" && isOwner))
+ ) {
+ const billingSection: ConfigNavSection = {
+ id: "workspace",
+ title: t("settings.workspace.title", "Workspace"),
+ items: [
+ {
+ key: "billing",
+ label: t("portal.nav.usage", "Usage & Billing"),
+ icon: "credit-card",
+ component: (
+ <BillingSettingsSection mode={isSaasMode ? "saas" : "selfhosted"} />
+ ),
+ },
+ ],
+ };
+ const workspace = isSaasMode
+ ? undefined
+ : sections.find((section) => section.id === "workspace");
+ if (workspace) {
+ const index = sections.indexOf(workspace);
+ sections[index] = {
+ ...workspace,
+ items: [...workspace.items, ...billingSection.items],
+ };
+ } else {
+ result.push(billingSection);
+ }
+ }
if (isSaasMode && isAuthenticated) {
- result.push({
- title: t("settings.planBilling.title", "Plan & Billing"),
- items: [createCloudPlanNavItem(t)],
- });
result.push({
title: t("settings.team.title", "Team"),
items: [createCloudTeamNavItem(t)],
diff --git a/frontend/editor/src/desktop/extensions/platformSessionBridge.ts b/frontend/editor/src/desktop/extensions/platformSessionBridge.ts
index a01f0eeb42..58909d95aa 100644
--- a/frontend/editor/src/desktop/extensions/platformSessionBridge.ts
+++ b/frontend/editor/src/desktop/extensions/platformSessionBridge.ts
@@ -6,10 +6,8 @@ import type { PlatformSessionUser } from "@proprietary/extensions/platformSessio
export async function isDesktopSaaSAuthMode(): Promise<boolean> {
try {
const mode = await connectionModeService.getCurrentMode();
- // Return true for ANY desktop auth mode (SaaS or self-hosted with desktop authService)
- // This skips redundant backend validation in springAuthClient since desktop authService
- // already manages the token lifecycle
- return mode === "saas" || mode === "selfhosted";
+ // Self-hosted sessions need the server profile for roles and organisation ownership.
+ return mode === "saas";
} catch {
return false;
}
diff --git a/frontend/editor/src/portal/api/ownership.ts b/frontend/editor/src/portal/api/ownership.ts
new file mode 100644
index 0000000000..c4ab8dc695
--- /dev/null
+++ b/frontend/editor/src/portal/api/ownership.ts
@@ -0,0 +1,84 @@
+import { apiClient } from "@app/portal/api/http";
+import { getPortalSaasToken } from "@app/portal/auth/portalSaasSession";
+import type { Member } from "@app/portal/api/users";
+import type {
+ CloudOwnershipStatus,
+ OwnershipStatus,
+ OwnershipTransferAdapter,
+} from "@app/components/shared/ownership/OwnershipTransferModal";
+
+const path = "/api/v1/ownership/handover";
+
+/** Only the local owner can read a pending transfer. No cloud bearer is stored in the handover. */
+export const pendingOwnership = () =>
+ apiClient.local.json<OwnershipStatus | null>(path);
+
+/** The local server supplies its own device credential and rechecks cloud ownership on completion. */
+export function ownershipAdapter(
+ member: Pick<Member, "id" | "name" | "email" | "teamId">,
+ local: boolean,
+ signIn: () => void,
+): OwnershipTransferAdapter {
+ async function cloudAction(action: "invite" | "transfer") {
+ const token = await getPortalSaasToken();
+ return apiClient.local.json<OwnershipStatus>(`${path}/cloud/${action}`, {
+ method: "POST",
+ headers: token ? { "X-SaaS-Authorization": `Bearer ${token}` } : {},
+ });
+ }
+ if (local)
+ return {
+ local,
+ signIn,
+ loadCandidates: () =>
+ apiClient.local.json<NonNullable<OwnershipStatus["candidates"]>>(
+ `${path}/members`,
+ ),
+ prepare: () =>
+ apiClient.local.json<OwnershipStatus>(`${path}/${member.id}`, {
+ method: "POST",
+ }),
+ selectCloud: (selection) =>
+ apiClient.local.json<OwnershipStatus>(`${path}/${member.id}`, {
+ method: "POST",
+ body: selection,
+ }),
+ invite: () => cloudAction("invite"),
+ transferCloud: () => cloudAction("transfer"),
+ completeLocal: () =>
+ apiClient.local.json<void>("/api/v1/user/admin/transferOwnership", {
+ method: "POST",
+ body: { userId: Number(member.id) },
+ }),
+ cancel: () => apiClient.local.json<void>(path, { method: "DELETE" }),
+ };
+ const wrap = (cloud: CloudOwnershipStatus): OwnershipStatus => ({
+ targetId: Number(member.id),
+ targetName: member.name,
+ targetEmail: member.email ?? null,
+ cloud,
+ });
+ return {
+ local,
+ prepare: async () =>
+ wrap(
+ await apiClient.local.json<CloudOwnershipStatus>(
+ `/api/v1/team/${member.teamId}/ownership/status`,
+ { method: "POST", body: { email: member.email } },
+ ),
+ ),
+ transferCloud: async (state) =>
+ wrap(
+ await apiClient.local.json<CloudOwnershipStatus>(
+ `/api/v1/team/${member.teamId}/ownership/transfer`,
+ {
+ method: "POST",
+ body: {
+ email: member.email,
+ expectedLeaderId: state.cloud?.leaderUserId,
+ },
+ },
+ ),
+ ),
+ };
+}
diff --git a/frontend/editor/src/portal/components/LinkAccountFooterItem.stories.tsx b/frontend/editor/src/portal/components/LinkAccountFooterItem.stories.tsx
index b65041164a..6a41d05ba0 100644
--- a/frontend/editor/src/portal/components/LinkAccountFooterItem.stories.tsx
+++ b/frontend/editor/src/portal/components/LinkAccountFooterItem.stories.tsx
@@ -1,9 +1,11 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
+import { WithOrgOwner } from "@portal/test/WithOrgOwner";
import { LinkAccountFooterItem } from "@portal/components/LinkAccountFooterItem";
const meta: Meta<typeof LinkAccountFooterItem> = {
title: "Portal/LinkAccountFooterItem",
component: LinkAccountFooterItem,
+ decorators: [WithOrgOwner],
parameters: { layout: "padded" },
};
export default meta;
diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.stories.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.stories.tsx
index 99735e657f..aa3ea43e3e 100644
--- a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.stories.tsx
+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.stories.tsx
@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
+import { WithOrgOwner } from "@portal/test/WithOrgOwner";
import { http, HttpResponse } from "msw";
import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";
import { AccountLinkPanel } from "@portal/components/account-link/AccountLinkPanel";
@@ -12,6 +13,7 @@ const meta: Meta<typeof AccountLinkPanel> = {
component: AccountLinkPanel,
parameters: { layout: "padded" },
decorators: [
+ WithOrgOwner,
(Story) => (
<AccountLinkProvider>
<Story />
diff --git a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx
index 5f87ca06f3..95edaab546 100644
--- a/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx
+++ b/frontend/editor/src/portal/components/account-link/AccountLinkPanel.test.tsx
@@ -21,6 +21,9 @@ const state = vi.hoisted(() => ({
email: "[email protected]" as string | null,
isOwner: true,
}));
+vi.mock("@app/auth/context", () => ({
+ useAuth: () => ({ user: { orgOwner: state.isOwner } }),
+}));
vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({
useAccountLinkOwner: () => state.isOwner,
}));
diff --git a/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx b/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx
index 5ae67d784f..6482926f18 100644
--- a/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx
+++ b/frontend/editor/src/portal/components/account-link/ConnectCallbackHost.tsx
@@ -1,4 +1,5 @@
import { useEffect, useRef } from "react";
+import { HttpError } from "@app/portal/api/http";
import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";
import { clearAccountLinkBlock } from "@app/services/accountLinkBlock";
import { useLocation, useNavigate } from "react-router-dom";
@@ -154,7 +155,12 @@ export function ConnectCallbackHost() {
discardTokens();
publishRef.current({ ...metadata, state: "linked", sessionRestored });
} catch (error) {
- if (current() && isTerminalSaasAuthError(error)) {
+ if (
+ current() &&
+ (isTerminalSaasAuthError(error) ||
+ (error instanceof HttpError &&
+ (error.status === 403 || error.status === 409)))
+ ) {
discardTokens();
publishRef.current({
...metadata,
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsx
index 04992e30df..14cdebe069 100644
--- a/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountCard.stories.tsx
@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
+import { WithOrgOwner } from "@portal/test/WithOrgOwner";
import type { UseAccountLink } from "@portal/hooks/useAccountLink";
import { LinkAccountCard } from "@portal/components/account-link/LinkAccountCard";
import "@portal/views/AccountLink.css";
@@ -18,6 +19,7 @@ const base: UseAccountLink = {
const meta: Meta<typeof LinkAccountCard> = {
title: "Portal/AccountLink/LinkAccountCard",
component: LinkAccountCard,
+ decorators: [WithOrgOwner],
parameters: { layout: "padded" },
};
export default meta;
@@ -28,6 +30,11 @@ export const NotLinked: Story = {
args: { link: base },
};
+export const OtherAdministrator: Story = {
+ args: { link: base },
+ parameters: { orgOwner: false },
+};
+
/** Linking — login completed, button shows progress while registering. */
export const Linking: Story = {
args: { link: { ...base, phase: "linking" } },
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountCard.test.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountCard.test.tsx
new file mode 100644
index 0000000000..538c358b24
--- /dev/null
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountCard.test.tsx
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { PortalTestProviders } from "@portal/test/TestQueryProvider";
+import { LinkAccountCard } from "@portal/components/account-link/LinkAccountCard";
+import type { UseAccountLink } from "@portal/hooks/useAccountLink";
+
+const { auth, openLinkModal, unlink } = vi.hoisted(() => ({
+ auth: { user: { orgOwner: false } },
+ openLinkModal: vi.fn(),
+ unlink: vi.fn(),
+}));
+vi.mock("@app/auth/context", () => ({ useAuth: () => auth }));
+vi.mock("@portal/contexts/UIContext", () => ({
+ useUI: () => ({ openLinkModal }),
+}));
+
+vi.mock("@portal/hooks/useLinkedAccountEmail", () => ({
+ useLinkedAccountEmail: () => null,
+}));
+
+const link: UseAccountLink = {
+ loginConfigured: true,
+ status: { linked: false, name: null },
+ statusError: null,
+ phase: "idle",
+ error: null,
+ unlink,
+ refresh: async () => {},
+};
+
+describe("account-link ownership", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ auth.user.orgOwner = false;
+ });
+
+ it.each([false, true])(
+ "keeps link changes unavailable to another admin when linked=%s",
+ (linked) => {
+ render(
+ <PortalTestProviders>
+ <LinkAccountCard link={{ ...link, status: { linked, name: null } }} />
+ </PortalTestProviders>,
+ );
+ const action = screen.getByRole("button", {
+ name: linked
+ ? "Disconnect this instance"
+ : "Connect your Stirling account",
+ });
+ expect(action).toBeDisabled();
+ fireEvent.click(action);
+ expect(unlink).not.toHaveBeenCalled();
+ expect(openLinkModal).not.toHaveBeenCalled();
+ expect(
+ screen.getByText("Only the org owner can link or unlink this server."),
+ ).toBeInTheDocument();
+ },
+ );
+
+ it.each([false, true])(
+ "gives the new owner link control when linked=%s",
+ (linked) => {
+ auth.user.orgOwner = true;
+ render(
+ <PortalTestProviders>
+ <LinkAccountCard link={{ ...link, status: { linked, name: null } }} />
+ </PortalTestProviders>,
+ );
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: linked
+ ? "Disconnect this instance"
+ : "Connect your Stirling account",
+ }),
+ );
+ if (linked) {
+ expect(unlink).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "Disconnect this instance",
+ }),
+ );
+ }
+ expect(linked ? unlink : openLinkModal).toHaveBeenCalledTimes(1);
+ },
+ );
+});
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx
index eb6a88d911..42020472e7 100644
--- a/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountCard.tsx
@@ -1,4 +1,5 @@
import { useState } from "react";
+import { useAuth } from "@app/auth/context";
import { Icon } from "@app/ui/Icon";
import { useTranslation } from "react-i18next";
import { Banner, Button, InfoTooltip, Modal, Skeleton } from "@app/ui";
@@ -17,6 +18,8 @@ export function LinkAccountCard({ link, instanceName }: Props) {
const { t } = useTranslation();
const { openLinkModal } = useUI();
const email = useLinkedAccountEmail();
+ const { user } = useAuth();
+ const canLink = user?.orgOwner === true;
const linking = link.phase === "linking";
const linked = link.status?.linked ?? false;
const [confirmDisconnect, setConfirmDisconnect] = useState(false);
@@ -83,6 +86,7 @@ export function LinkAccountCard({ link, instanceName }: Props) {
)}
</div>
</div>
+
{!linked && (
<span className="portal-link__status">
<Icon name="unlink" size={20} />
@@ -108,6 +112,7 @@ export function LinkAccountCard({ link, instanceName }: Props) {
accent="neutral"
leftSection={<Icon name="unlink" size={20} />}
loading={linking}
+ disabled={!canLink}
onClick={() => setConfirmDisconnect(true)}
>
{t("portal.accountLink.card.unlink", "Disconnect this instance")}
@@ -143,6 +148,14 @@ export function LinkAccountCard({ link, instanceName }: Props) {
</Banner>
)}
+ {!canLink && (
+ <p>
+ {t(
+ "portal.accountLink.ownerRequired",
+ "Only the org owner can link or unlink this server.",
+ )}
+ </p>
+ )}
{!linked && (
<div className="portal-link__connect">
<p>
@@ -151,7 +164,11 @@ export function LinkAccountCard({ link, instanceName }: Props) {
"Connect this server to use your team’s processing allowance in Stirling Cloud.",
)}
</p>
- <Button loading={linking} onClick={() => openLinkModal()}>
+ <Button
+ loading={linking}
+ disabled={!canLink}
+ onClick={() => openLinkModal()}
+ >
{t(
"portal.accountLink.card.linkButton",
"Connect your Stirling account",
@@ -178,6 +195,7 @@ export function LinkAccountCard({ link, instanceName }: Props) {
</Button>
<Button
accent="danger"
+ disabled={!canLink}
onClick={() => {
setConfirmDisconnect(false);
void link.unlink();
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsx
index fe97f69a4c..72404a3b8e 100644
--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.stories.tsx
@@ -16,6 +16,15 @@ const meta: Meta<typeof LinkAccountModal> = {
value={{
...auth,
isAdmin: context.parameters.accountLinkAdmin !== false,
+ user: {
+ id: "1",
+ email: "[email protected]",
+ username: "owner",
+ role: "ROLE_ADMIN",
+ orgOwner:
+ context.parameters.accountLinkAdmin !== false &&
+ context.parameters.orgOwner !== false,
+ },
loading: false,
}}
>
@@ -39,6 +48,10 @@ type Story = StoryObj<typeof LinkAccountModal>;
*/
export const Default: Story = {};
+export const OtherAdministrator: Story = {
+ parameters: { orgOwner: false },
+};
+
/** "reauth" mode — the server stays linked; only the browser session is renewed. */
export const Reauth: Story = {
args: { mode: "reauth" },
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx
index 853998647c..b388020bcd 100644
--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.test.tsx
@@ -7,6 +7,7 @@ import {
type LinkModalMode,
} from "@app/portal/contexts/UIContext";
import { PortalTestProviders } from "@app/portal/test/TestQueryProvider";
+import { HttpError } from "@app/portal/api/http";
/** The step machine: what drives each step, and what must not skip or repeat one. */
const { startConnect, startReauth, fetchWallet, EMAIL } = vi.hoisted(() => ({
@@ -370,6 +371,24 @@ describe("LinkAccountModal", () => {
expect(filledSteps()).toBe(1);
});
+ it("explains a pending ownership transfer and allows linking after it is resolved", async () => {
+ startConnect.mockRejectedValueOnce(new HttpError(409, "Conflict", {}));
+
+ renderModal();
+ click(CONNECT);
+
+ expect(
+ await screen.findByText(/Settings → Users to finish or cancel/),
+ ).toBeTruthy();
+ expect(screen.queryByText(/outbound network access/)).toBeNull();
+ expect(assign).not.toHaveBeenCalled();
+ expect(sessionStorage.getItem("stirling.portalConnect")).toBeNull();
+ expect(filledSteps()).toBe(1);
+
+ click(CONNECT);
+ await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
+ });
+
it.each(["link", "reauth"] as const)(
"explains a callback address mismatch during %s and allows retry after correction",
async (mode) => {
diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
index 97eec5c0b1..0e77ed522a 100644
--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
@@ -14,8 +14,15 @@ import { MantineProvider } from "@mantine/core";
* with no link to this server, so loading a wallet there would flip the whole portal to linked.
*/
const gate = { gated: false, loading: false, available: true };
-// Administrator by default: the page is theirs, and one case below is the member.
const admin = { is: true };
+const owner = { is: true, loading: false };
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({
+ isAdmin: admin.is,
+ user: { orgOwner: owner.is },
+ loading: owner.loading,
+ }),
+}));
const link = { is: false };
const connect = vi.fn();
const applyLinkFacts = vi.fn();
@@ -57,7 +64,7 @@ vi.mock("@app/portal/contexts/UIContext", () => ({
useUI: () => ({ openLinkModal: vi.fn() }),
}));
vi.mock("@app/portal/hooks/useAccountLinkOwner", () => ({
- useAccountLinkOwner: () => admin.is,
+ useAccountLinkOwner: () => admin.is && owner.is && !owner.loading,
}));
vi.mock("@app/portal/views/Usage", () => ({
Usage: ({
@@ -113,6 +120,8 @@ const renderGate = () => render(<GateTree />);
describe("PortalBillingGate — self-hosted", () => {
beforeEach(() => {
admin.is = true;
+ owner.is = true;
+ owner.loading = false;
link.is = false;
connect.mockReset();
applyLinkFacts.mockReset();
@@ -136,6 +145,39 @@ describe("PortalBillingGate — self-hosted", () => {
expect(screen.queryByTestId("usage")).toBeNull();
});
+ it.each([false, true])(
+ "blocks direct billing access for another admin with linked=%s",
+ (linked) => {
+ owner.is = false;
+ link.is = linked;
+ renderGate();
+ expect(screen.queryByTestId("usage")).toBeNull();
+ expect(screen.queryByTestId("free-tier")).toBeNull();
+ expect(applyLinkFacts).not.toHaveBeenCalled();
+ expect(connect).not.toHaveBeenCalled();
+ },
+ );
+
+ it("removes billing on transfer and allows the successor after the session refresh", () => {
+ link.is = true;
+ const view = renderGate();
+ expect(screen.getByTestId("usage")).toBeInTheDocument();
+ owner.is = false;
+ view.rerender(<GateTree />);
+ expect(screen.queryByTestId("usage")).toBeNull();
+ owner.is = true;
+ view.rerender(<GateTree />);
+ expect(screen.getByTestId("usage")).toBeInTheDocument();
+ });
+
+ it("does not load billing while ownership is being refreshed", () => {
+ owner.loading = true;
+ link.is = true;
+ renderGate();
+ expect(screen.queryByTestId("usage")).toBeNull();
+ expect(applyLinkFacts).not.toHaveBeenCalled();
+ });
+
it("asks for nothing on the way in", () => {
gate.gated = true;
renderGate();
diff --git a/frontend/editor/src/portal/components/settings/PortalRosterHost.tsx b/frontend/editor/src/portal/components/settings/PortalRosterHost.tsx
index 84e9b3642b..4ba7301c8d 100644
--- a/frontend/editor/src/portal/components/settings/PortalRosterHost.tsx
+++ b/frontend/editor/src/portal/components/settings/PortalRosterHost.tsx
@@ -1,21 +1,48 @@
-import { type ReactNode } from "react";
+import { lazy, Suspense, useEffect, useState, type ReactNode } from "react";
+import { useLocation } from "react-router-dom";
import { QueryClientProvider } from "@tanstack/react-query";
import { getPortalQueryClient } from "@portal/queryClient";
import { LinkProvider } from "@portal/contexts/LinkContext";
import { TierProvider } from "@portal/contexts/TierContext";
import { ErrorBoundary } from "@portal/components/ErrorBoundary";
+import { UIProvider, useUI } from "@portal/contexts/UIContext";
import "@portal/theme/base.css";
import "@portal/components/settings/PortalSettingsSectionHost.css";
-/** Runs the roster in settings with only the contexts it reads. Deliberately not
- * PortalSettingsSectionHost: desktop has no account-link flow to mount. */
+const PortalRosterLinkFlow = lazy(
+ () => import("@portal/components/settings/PortalRosterLinkFlow"),
+);
+
+function RequestedLinkFlow() {
+ const { linkModalOpen } = useUI();
+ const location = useLocation();
+ const hasCallback = Boolean(location.state?.accountLinkReturn);
+ const [requested, setRequested] = useState(false);
+ useEffect(() => {
+ if (linkModalOpen || hasCallback) setRequested(true);
+ }, [linkModalOpen, hasCallback]);
+ // The callback clears router state before its asynchronous claim finishes.
+ return requested || linkModalOpen || hasCallback ? (
+ <Suspense fallback={null}>
+ <PortalRosterLinkFlow />
+ </Suspense>
+ ) : null;
+}
+
+/** The roster can renew cloud sign-in on demand; listing users must not mount
+ * instance-link endpoints, which are absent on SaaS and desktop cloud mode. */
export function PortalRosterHost({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={getPortalQueryClient()}>
<div className="portal-settings-section portal-scope">
<LinkProvider initialState="unlinked">
<TierProvider>
- <ErrorBoundary>{children}</ErrorBoundary>
+ <UIProvider>
+ <ErrorBoundary>
+ {children}
+ <RequestedLinkFlow />
+ </ErrorBoundary>
+ </UIProvider>
</TierProvider>
</LinkProvider>
</div>
diff --git a/frontend/editor/src/portal/components/settings/PortalRosterLinkFlow.tsx b/frontend/editor/src/portal/components/settings/PortalRosterLinkFlow.tsx
new file mode 100644
index 0000000000..30b584c4d4
--- /dev/null
+++ b/frontend/editor/src/portal/components/settings/PortalRosterLinkFlow.tsx
@@ -0,0 +1,16 @@
+import { AccountLinkProvider } from "@app/portal/contexts/AccountLinkContext";
+import { AccountLinkSessionBoundary } from "@app/portal/components/account-link/AccountLinkSessionBoundary";
+import { ConnectCallbackHost } from "@app/portal/components/account-link/ConnectCallbackHost";
+import { LinkAccountModalHost } from "@app/portal/components/account-link/LinkAccountModal";
+
+/** Handles an explicit roster sign-in request or its return from cloud authentication. */
+export default function PortalRosterLinkFlow() {
+ return (
+ <AccountLinkSessionBoundary>
+ <AccountLinkProvider>
+ <LinkAccountModalHost />
+ <ConnectCallbackHost />
+ </AccountLinkProvider>
+ </AccountLinkSessionBoundary>
+ );
+}
diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx
index be0d5c124d..53ed9fd0d7 100644
--- a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx
+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { PortalSettingsSectionHost } from "@portal/components/settings/PortalSettingsSectionHost";
+import { PortalRosterHost } from "@portal/components/settings/PortalRosterHost";
import { useLinkOptional } from "@portal/contexts/LinkContext";
import {
clearAccountLinkBlock,
@@ -53,6 +54,13 @@ function LinkState() {
);
}
+function RosterTransferSignIn() {
+ const { openLinkModal } = useUI();
+ return (
+ <button onClick={() => openLinkModal("reauth")}>Renew cloud sign-in</button>
+ );
+}
+
function renderHost(path = "/settings/billing") {
return render(
<MemoryRouter initialEntries={[path]}>
@@ -70,6 +78,25 @@ describe("settings link status", () => {
clearAccountLinkBlock();
});
+ it("supports transfer sign-in in the shared roster without mounting linking on entry", async () => {
+ fetchStatus.mockResolvedValue({ linked: true });
+ render(
+ <MemoryRouter initialEntries={["/settings/users"]}>
+ <PortalRosterHost>
+ <RosterTransferSignIn />
+ </PortalRosterHost>
+ </MemoryRouter>,
+ );
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(fetchStatus).not.toHaveBeenCalled();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Renew cloud sign-in" }),
+ );
+ expect(await screen.findByRole("dialog", { name: "reauth" })).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Not now" }));
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
it("does not claim an unlinked server while its status is still loading", async () => {
let resolve!: (value: { linked: boolean }) => void;
fetchStatus.mockReturnValue(
diff --git a/frontend/editor/src/portal/components/settings/portalSettingsSections.tsx b/frontend/editor/src/portal/components/settings/portalSettingsSections.tsx
index 973e08c827..0e45fe9732 100644
--- a/frontend/editor/src/portal/components/settings/portalSettingsSections.tsx
+++ b/frontend/editor/src/portal/components/settings/portalSettingsSections.tsx
@@ -41,7 +41,7 @@ const Billing = lazy(async () => {
return { default: m.BillingSettingsSection };
});
-/** The roster's own host: it reads the tier and nothing else (see PortalRosterHost). */
+/** The roster host loads cloud sign-in only when a handover requests it. */
function rosterHosted(View: ComponentType) {
return function HostedRosterSection() {
return (
diff --git a/frontend/editor/src/portal/hooks/useConnectHandoff.ts b/frontend/editor/src/portal/hooks/useConnectHandoff.ts
index 7bf0900775..b0f64f7d53 100644
--- a/frontend/editor/src/portal/hooks/useConnectHandoff.ts
+++ b/frontend/editor/src/portal/hooks/useConnectHandoff.ts
@@ -1,5 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
+import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";
+import { HttpError } from "@app/portal/api/http";
import { useLocation } from "react-router-dom";
import { withBasePath } from "@app/constants/app";
import { startConnect, startReauth } from "@app/portal/api/link";
@@ -14,6 +16,7 @@ interface ConnectHandoff {
export function useConnectHandoff(reauth: boolean): ConnectHandoff {
const { t } = useTranslation();
+ const isOwner = useAccountLinkOwner();
const location = useLocation();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -36,6 +39,15 @@ export function useConnectHandoff(reauth: boolean): ConnectHandoff {
}, []);
const begin = useCallback(() => {
+ if (!isOwner) {
+ setError(
+ t(
+ "portal.accountLink.ownerRequired",
+ "Only the org owner can link or unlink this server.",
+ ),
+ );
+ return;
+ }
if (inFlight.current) return;
inFlight.current = true;
setBusy(true);
@@ -94,19 +106,39 @@ export function useConnectHandoff(reauth: boolean): ConnectHandoff {
);
setBusy(false);
inFlight.current = false;
- } catch {
+ } catch (error) {
if (!mounted.current) return;
- setError(
- t(
- "portal.accountLink.modal.startFailed",
- "Could not reach Stirling to start the connection. Check this server's outbound network access, then try again.",
- ),
- );
+ if (error instanceof HttpError && error.status === 403) {
+ setError(
+ t(
+ "portal.accountLink.ownerRequired",
+ "Only the org owner can link or unlink this server.",
+ ),
+ );
+ } else if (
+ !reauth &&
+ error instanceof HttpError &&
+ error.status === 409
+ ) {
+ setError(
+ t(
+ "portal.accountLink.modal.transferPending",
+ "An ownership transfer is pending. Go to Settings → Users to finish or cancel it, then try linking again.",
+ ),
+ );
+ } else {
+ setError(
+ t(
+ "portal.accountLink.modal.startFailed",
+ "Could not reach Stirling to start the connection. Check this server's outbound network access, then try again.",
+ ),
+ );
+ }
setBusy(false);
inFlight.current = false;
}
})();
- }, [reauth, t, location.pathname, location.search]);
+ }, [reauth, t, location.pathname, location.search, isOwner]);
return { busy, error, begin };
}
diff --git a/frontend/editor/src/portal/test/WithOrgOwner.tsx b/frontend/editor/src/portal/test/WithOrgOwner.tsx
new file mode 100644
index 0000000000..a73ae48c4f
--- /dev/null
+++ b/frontend/editor/src/portal/test/WithOrgOwner.tsx
@@ -0,0 +1,25 @@
+import type { Decorator } from "@storybook/react-vite";
+import { AuthContext, useAuth } from "@app/auth/context";
+
+/** Account-link stories default to the owner; orgOwner: false previews another administrator. */
+export const WithOrgOwner: Decorator = (Story, context) => {
+ const auth = useAuth();
+ return (
+ <AuthContext.Provider
+ value={{
+ ...auth,
+ loading: false,
+ isAdmin: true,
+ user: {
+ id: "1",
+ email: "[email protected]",
+ username: "owner",
+ role: "ROLE_ADMIN",
+ orgOwner: context.parameters.orgOwner !== false,
+ },
+ }}
+ >
+ <Story />
+ </AuthContext.Provider>
+ );
+};
diff --git a/frontend/editor/src/portal/views/ConnectCallback.test.tsx b/frontend/editor/src/portal/views/ConnectCallback.test.tsx
index 0182a48f28..0238c397f4 100644
--- a/frontend/editor/src/portal/views/ConnectCallback.test.tsx
+++ b/frontend/editor/src/portal/views/ConnectCallback.test.tsx
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HttpError } from "@app/portal/api/http";
import type { ReactNode } from "react";
+import { PortalRosterHost } from "@app/portal/components/settings/PortalRosterHost";
import { PortalSettingsSectionHost } from "@app/portal/components/settings/PortalSettingsSectionHost";
import { act, render, waitFor } from "@testing-library/react";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
@@ -138,9 +140,13 @@ describe("account-link callback", () => {
setSession.mockResolvedValue({ error: null });
});
- it.each(["/settings/billing", "/settings/account-link"])(
+ it.each(["/settings/billing", "/settings/account-link", "/settings/users"])(
"restores renewal through the settings host at %s",
async (returnTo) => {
+ const Host =
+ returnTo === "/settings/users"
+ ? PortalRosterHost
+ : PortalSettingsSectionHost;
rememberConnect({
ownerId: "owner",
mode: "reauth",
@@ -159,10 +165,10 @@ describe("account-link callback", () => {
<Route
path={returnTo}
element={
- <PortalSettingsSectionHost>
+ <Host>
<OutcomeSpy />
<div data-testid="settings-destination" />
- </PortalSettingsSectionHost>
+ </Host>
}
/>
</Routes>
@@ -176,7 +182,7 @@ describe("account-link callback", () => {
access_token: "at",
refresh_token: "rt",
});
- expect(routeState).toBeNull();
+ await waitFor(() => expect(routeState).toBeNull());
},
);
@@ -361,6 +367,18 @@ describe("account-link callback", () => {
expect(lastOutcome()?.reclaim).toBeUndefined();
});
+ it.each([403, 409])(
+ "does not retry a link rejected after ownership changes (%s)",
+ async (status) => {
+ landOn(`#type=link&nonce=${NONCE}`);
+ completeConnect.mockRejectedValue(new HttpError(status, "Rejected", {}));
+ renderFlow();
+ await waitFor(() => expect(lastOutcome()?.state).toBe("rejected"));
+ expect(lastOutcome()?.reclaim).toBeUndefined();
+ expect(refresh).not.toHaveBeenCalled();
+ },
+ );
+
it.each(["REJECTED", "EXPIRED", "PENDING", "UNAVAILABLE"])(
"does not install tokens for a %s handshake",
async (phase) => {
diff --git a/frontend/editor/src/portal/views/Users.caching.test.tsx b/frontend/editor/src/portal/views/Users.caching.test.tsx
index a619d883b7..498e8064ce 100644
--- a/frontend/editor/src/portal/views/Users.caching.test.tsx
+++ b/frontend/editor/src/portal/views/Users.caching.test.tsx
@@ -1,3 +1,4 @@
+import { UIProvider } from "@portal/contexts/UIContext";
import {
afterAll,
afterEach,
@@ -94,7 +95,9 @@ function renderUsers(client: QueryClient): RenderResult {
<MantineProvider>
<QueryClientProvider client={client}>
<MemoryRouter>
- <Users />
+ <UIProvider>
+ <Users />
+ </UIProvider>
</MemoryRouter>
</QueryClientProvider>
</MantineProvider>,
diff --git a/frontend/editor/src/portal/views/Users.saas.test.tsx b/frontend/editor/src/portal/views/Users.saas.test.tsx
index 75538aa361..de491dedde 100644
--- a/frontend/editor/src/portal/views/Users.saas.test.tsx
+++ b/frontend/editor/src/portal/views/Users.saas.test.tsx
@@ -1,3 +1,4 @@
+import { UIProvider } from "@portal/contexts/UIContext";
import {
afterAll,
afterEach,
@@ -59,17 +60,17 @@ vi.mock("@portal/contexts/TierContext", () => ({
useTier: () => ({ tier: "pro" }),
}));
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string, fallback?: string, opts?: Record<string, unknown>) => {
- const base = fallback ?? key;
- return opts
- ? base.replace(/\{\{(\w+)\}\}/g, (_, k) => String(opts[k] ?? ""))
- : base;
- },
- i18n: { changeLanguage: vi.fn() },
- }),
-}));
+vi.mock("react-i18next", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-i18next")>();
+ const { createInstance } = await import("i18next");
+ const i18n = createInstance();
+ await i18n.use(actual.initReactI18next).init({
+ lng: "en",
+ resources: {},
+ interpolation: { escapeValue: false },
+ });
+ return { ...actual, useTranslation: () => ({ t: i18n.t, i18n }) };
+});
import { Users } from "@portal/views/Users";
@@ -90,7 +91,9 @@ function renderUsers() {
return render(
<PortalTestProviders>
<MemoryRouter>
- <Users />
+ <UIProvider>
+ <Users />
+ </UIProvider>
</MemoryRouter>
</PortalTestProviders>,
);
@@ -162,7 +165,11 @@ describe("Users page (SaaS flavor, end-to-end via SaasTeamController mocks)", ()
});
});
-function ownershipScenario(ownerless = false, fail = false) {
+function ownershipScenario(
+ ownerless = false,
+ fail = false,
+ linkedInstances = 0,
+) {
let ownerId = ownerless ? 0 : 1;
server.use(
http.get("/api/v1/team/my", () =>
@@ -203,14 +210,37 @@ function ownershipScenario(ownerless = false, fail = false) {
},
]),
),
- http.post("/api/v1/team/1/members/2/transfer-leadership", () => {
+ http.post("/api/v1/team/1/ownership/status", () =>
+ HttpResponse.json({
+ teamId: 1,
+ teamName: "Acme",
+ leaderUserId: ownerId,
+ targetUserId: 2,
+ linkedInstances,
+ subscribed: true,
+ state: ownerId === 2 ? "TRANSFERRED" : "READY",
+ }),
+ ),
+ http.post("/api/v1/team/1/ownership/transfer", async ({ request }) => {
+ expect(await request.json()).toEqual({
+ email: "[email protected]",
+ expectedLeaderId: 1,
+ });
if (fail)
return HttpResponse.json(
{ message: "Ownership changed; refresh and retry." },
{ status: 409 },
);
ownerId = 2;
- return HttpResponse.json({});
+ return HttpResponse.json({
+ teamId: 1,
+ teamName: "Acme",
+ leaderUserId: 2,
+ targetUserId: 2,
+ linkedInstances,
+ subscribed: true,
+ state: "TRANSFERRED",
+ });
}),
http.post("/api/v1/team/1/claim-leadership", () => {
ownerId = 1;
@@ -221,8 +251,8 @@ function ownershipScenario(ownerless = false, fail = false) {
}
describe("SaaS ownership through the current Users page", () => {
- it("transfers through the role menu and keeps the former owner's shared roster visible", async () => {
- const owner = ownershipScenario();
+ it("directs a linked team's owner to the self-hosted Users page without transferring", async () => {
+ const owner = ownershipScenario(false, false, 1);
renderUsers();
fireEvent.click(
await screen.findByRole("textbox", { name: "Role for Blair" }),
@@ -235,9 +265,32 @@ describe("SaaS ownership through the current Users page", () => {
}),
).getByRole("option", { name: "Org Owner", hidden: true }),
);
+ expect(
+ await screen.findByText("Start from your self-hosted server"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Transfer ownership" }),
+ ).toBeNull();
+ expect(owner()).toBe(1);
+ });
+
+ it("transfers through the role menu and keeps the former owner's shared roster visible", async () => {
+ const owner = ownershipScenario();
+ renderUsers();
fireEvent.click(
- await screen.findByRole("button", { name: "Transfer ownership" }),
+ await screen.findByRole("textbox", { name: "Role for Blair" }),
+ );
+ fireEvent.click(
+ within(
+ await screen.findByRole("listbox", {
+ name: "Role for Blair",
+ hidden: true,
+ }),
+ ).getByRole("option", { name: "Org Owner", hidden: true }),
);
+ fireEvent.click(await screen.findByRole("checkbox"));
+ fireEvent.click(screen.getByRole("button", { name: "Transfer ownership" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Done" }));
await waitFor(
() =>
expect(
@@ -285,13 +338,12 @@ describe("SaaS ownership through the current Users page", () => {
}),
).getByRole("option", { name: "Org Owner", hidden: true }),
);
- fireEvent.click(
- await screen.findByRole("button", { name: "Transfer ownership" }),
- );
+ fireEvent.click(await screen.findByRole("checkbox"));
+ fireEvent.click(screen.getByRole("button", { name: "Transfer ownership" }));
expect(await screen.findByRole("alert")).toBeInTheDocument();
expect(owner()).toBe(1);
- expect(screen.getByRole("textbox", { name: "Role for Alex" })).toHaveValue(
- "Org Owner",
- );
+ expect(
+ screen.getByRole("textbox", { name: "Role for Alex", hidden: true }),
+ ).toHaveValue("Org Owner");
});
});
diff --git a/frontend/editor/src/portal/views/Users.tsx b/frontend/editor/src/portal/views/Users.tsx
index 584ef793fc..0d1be0f704 100644
--- a/frontend/editor/src/portal/views/Users.tsx
+++ b/frontend/editor/src/portal/views/Users.tsx
@@ -4,8 +4,6 @@ import { useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Button, EmptyState, Skeleton, StatusBadge, Tooltip } from "@app/ui";
import {
- transferOwnership,
- transferTeamOwnership,
claimTeamOwnership,
changeMemberRole,
disableMemberMfa,
@@ -37,6 +35,12 @@ import { RenameTeamModal } from "@portal/components/users/RenameTeamModal";
import { ConfirmModal } from "@portal/components/users/ConfirmModal";
import { seatsLabel } from "@portal/components/users/format";
import { useUsersData } from "@portal/views/usersData";
+import {
+ OwnershipTransferModal,
+ type OwnershipStatus,
+} from "@app/components/shared/ownership/OwnershipTransferModal";
+import { ownershipAdapter, pendingOwnership } from "@portal/api/ownership";
+import { useUI } from "@portal/contexts/UIContext";
interface Confirm {
title: string;
@@ -53,6 +57,13 @@ interface Confirm {
export function Users() {
const { t } = useTranslation();
const { refreshSession } = useAuth();
+ const { openLinkModal } = useUI();
+ const [ownershipTarget, setOwnershipTarget] = useState<Pick<
+ Member,
+ "id" | "name" | "email" | "teamId"
+ > | null>(null);
+ const [pendingTransfer, setPendingTransfer] =
+ useState<OwnershipStatus | null>(null);
const [actionBusy, setActionBusy] = useState(false);
const { usersState, grantsState, teamsState, authState, refresh } =
useUsersData();
@@ -105,6 +116,19 @@ export function Users() {
} | null>(null);
const [confirm, setConfirm] = useState<Confirm | null>(null);
+ useEffect(() => {
+ if (!buildCaps.adminRole || !viewer?.orgOwner || ownershipTarget) return;
+ let active = true;
+ pendingOwnership()
+ .then((value) => {
+ if (active) setPendingTransfer(value);
+ })
+ .catch(() => {});
+ return () => {
+ active = false;
+ };
+ }, [viewer?.orgOwner, ownershipTarget]);
+
const [searchParams, setSearchParams] = useSearchParams();
useEffect(() => {
@@ -295,30 +319,7 @@ export function Users() {
});
}
function transferOwner(member: Member) {
- setConfirm({
- title: t(
- "users.confirm.transferOwnershipTitle",
- "Transfer organization ownership",
- ),
- body: !buildCaps.adminRole
- ? t(
- "team.transferBody",
- "Make {{email}} the team owner? They will control team membership and organization billing settings. You will become a member. The team’s subscription and wallet stay with the team.",
- { email: member.email ?? member.name },
- )
- : t(
- "users.confirm.transferOwnershipBody",
- "Make {{name}} the organization owner? They will become an admin. You will remain an admin but lose ownership. Only the new owner or the server operator can transfer it back.",
- { name: member.name },
- ),
- confirmLabel: t("users.action.transferOwnership", "Transfer ownership"),
- danger: true,
- action: async () => {
- if (buildCaps.adminRole) await transferOwnership(member);
- else await transferTeamOwnership(member);
- await refreshSession();
- },
- });
+ setOwnershipTarget(member);
}
function removeUser(member: Member) {
@@ -416,6 +417,29 @@ export function Users() {
</div>
</header>
+ {pendingTransfer && viewer?.orgOwner && (
+ <div role="status">
+ <p>
+ {t(
+ "ownership.pending",
+ "An ownership transfer to {{name}} is pending.",
+ { name: pendingTransfer.targetName },
+ )}
+ </p>
+ <Button
+ onClick={() =>
+ setOwnershipTarget({
+ id: String(pendingTransfer.targetId),
+ name: pendingTransfer.targetName,
+ email: pendingTransfer.targetEmail ?? "",
+ })
+ }
+ >
+ {t("ownership.resume", "Resume transfer")}
+ </Button>
+ </div>
+ )}
+
{members.some((member) => member.orgOwner && member.isFirstLogin) && (
<p role="status">
{t(
@@ -546,6 +570,20 @@ export function Users() {
manageGrants={caps.manageGrants}
onNotice={setActionError}
/>
+ {ownershipTarget && (
+ <OwnershipTransferModal
+ key={ownershipTarget.id}
+ adapter={ownershipAdapter(ownershipTarget, buildCaps.adminRole, () =>
+ openLinkModal("reauth"),
+ )}
+ onClose={() => setOwnershipTarget(null)}
+ onTransferred={() => {
+ setPendingTransfer(null);
+ refresh();
+ void refreshSession();
+ }}
+ />
+ )}
<NewTeamModal
open={newTeamOpen}
onClose={() => setNewTeamOpen(false)}
diff --git a/frontend/editor/src/portal/views/usersData.ts b/frontend/editor/src/portal/views/usersData.ts
index d6e965d714..e8e66758d0 100644
--- a/frontend/editor/src/portal/views/usersData.ts
+++ b/frontend/editor/src/portal/views/usersData.ts
@@ -51,6 +51,7 @@ export function useUsersData(): UsersData {
queryClient.invalidateQueries({ queryKey: qk.usersGrants(tier) });
queryClient.invalidateQueries({ queryKey: qk.usersTeams(tier) });
queryClient.invalidateQueries({ queryKey: qk.teamMy() });
+ queryClient.invalidateQueries({ queryKey: qk.wallet(true) });
}, [queryClient, tier]);
return {
diff --git a/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx
index afd1a62f33..c27f1e28f9 100644
--- a/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx
+++ b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx
@@ -46,10 +46,11 @@ const EncryptionSection = portalSection((m) => m.PortalEncryptionSection);
const BillingSection = portalSection((m) => m.PortalBillingSection);
const AccountLinkSection = portalSection((m) => m.PortalAccountLinkSection);
-/** The processor's deployment-administration views as settings sections; empty
- * without the portal. The include* flags only decide what is offered - the
- * endpoints enforce the same rules server-side. includeRoster is the one that
- * does not need the processor, being the build's only roster. */
+/**
+ * Deployment-administration sections; endpoints enforce the same access rules.
+ * The roster is shared across builds and does not require the processor.
+ * Self-hosted billing and account linking require org ownership; SaaS has no server to link.
+ */
export function buildPortalSettingsSections(
t: TFunction<"translation", undefined>,
{
diff --git a/frontend/editor/src/proprietary/components/settings/useSettingsNav.test.tsx b/frontend/editor/src/proprietary/components/settings/useSettingsNav.test.tsx
new file mode 100644
index 0000000000..d84598a87a
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/settings/useSettingsNav.test.tsx
@@ -0,0 +1,129 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+const state = vi.hoisted(() => ({
+ owner: true,
+ loading: false,
+ portal: true,
+ roster: true,
+}));
+vi.mock("@app/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { isAdmin: true } }),
+}));
+vi.mock("@app/auth/context", () => ({
+ useAuth: () => ({
+ isAdmin: true,
+ user: { orgOwner: state.owner },
+ loading: state.loading,
+ }),
+}));
+vi.mock("@app/hooks/usePortalAccess", () => ({
+ usePortalAccessState: () => ({ granted: state.portal, settled: true }),
+}));
+vi.mock("@app/hooks/useRosterAvailable", () => ({
+ useRosterAvailable: () => state.roster,
+}));
+vi.mock("@core/components/settings/useSettingsNav", () => ({
+ useSettingsNav: () => ({
+ sections: [
+ {
+ id: "workspace",
+ title: "Workspace",
+ items: [
+ { key: "plan", label: "Plan", component: null },
+ { key: "adminPlan", label: "Legacy plan", component: null },
+ ],
+ },
+ {
+ id: "monitoring",
+ title: "Monitoring",
+ items: [
+ { key: "adminUsage", label: "Usage Analytics", component: null },
+ ],
+ },
+ ],
+ aliases: {},
+ }),
+}));
+vi.mock("@app/routes/hasPortal", () => ({ HAS_PORTAL: true }));
+
+import { useSettingsNav } from "@app/components/settings/useSettingsNav";
+
+describe("self-hosted owner settings", () => {
+ beforeEach(() => {
+ state.owner = true;
+ state.loading = false;
+ state.portal = true;
+ state.roster = true;
+ });
+
+ it.each([false, true])(
+ "keeps operational analytics for admins with ownership=%s",
+ (owner) => {
+ state.owner = owner;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ const keys = result.current.sections.flatMap((section) =>
+ section.items.map((item) => item.key),
+ );
+ expect(keys).toContain("adminUsage");
+ expect(keys).toContain("users");
+ expect(keys.includes("billing")).toBe(owner);
+ expect(keys.includes("account-link")).toBe(owner);
+ expect(keys).not.toContain("adminPlan");
+ expect(keys).not.toContain("plan");
+ expect(result.current.aliases?.plan).toBe(owner ? "billing" : undefined);
+ expect(result.current.aliases?.adminPlan).toBe(
+ owner ? "billing" : undefined,
+ );
+ },
+ );
+
+ it("updates the available URL targets when ownership transfers", () => {
+ const { result, rerender } = renderHook(() => useSettingsNav(vi.fn()));
+ const keys = () =>
+ result.current.sections.flatMap((section) =>
+ section.items.map((item) => item.key),
+ );
+ expect(keys()).toContain("billing");
+ expect(result.current.aliases?.plan).toBe("billing");
+ state.owner = false;
+ rerender();
+ expect(result.current.aliases?.plan).toBeUndefined();
+ expect(result.current.aliases?.adminPlan).toBeUndefined();
+ expect(keys()).not.toContain("billing");
+ expect(keys()).not.toContain("account-link");
+ expect(keys()).not.toContain("adminPlan");
+ expect(keys()).toContain("adminUsage");
+ state.owner = true;
+ rerender();
+ expect(keys()).toContain("billing");
+ expect(keys()).toContain("account-link");
+ });
+
+ it.each([false, true])(
+ "retires the legacy Plan URL without processor sections for ownership=%s",
+ (owner) => {
+ state.owner = owner;
+ state.portal = false;
+ state.roster = false;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ const keys = result.current.sections.flatMap((section) =>
+ section.items.map((item) => item.key),
+ );
+ expect(keys).not.toContain("adminPlan");
+ expect(keys).toContain("adminUsage");
+ expect(keys).not.toContain("billing");
+ },
+ );
+
+ it("waits for ownership to settle before resolving a settings bookmark", () => {
+ state.loading = true;
+ const { result } = renderHook(() => useSettingsNav(vi.fn()));
+ expect(result.current.pending).toBe(true);
+ expect(
+ result.current.sections
+ .flatMap((section) => section.items)
+ .some((item) => ["billing", "adminPlan", "plan"].includes(item.key)),
+ ).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx b/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx
index 2661097009..609df47b16 100644
--- a/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx
+++ b/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx
@@ -30,8 +30,8 @@ export function useSettingsNav(onLeave: () => void): SettingsNav {
const base = useCoreSettingsNav(onLeave);
const { granted: portalAccess, settled: accessSettled } =
usePortalAccessState();
- const { isAdmin, user } = useAuth();
- const isOwner = isAdmin && user?.orgOwner === true;
+ const { isAdmin, user, loading } = useAuth();
+ const isOwner = isAdmin && !loading && user?.orgOwner === true;
// Answers to the same admin flag the rest of the nav is built from, not the
// session's - the two disagree while /me is still in flight.
const { config } = useAppConfig();
@@ -54,23 +54,31 @@ export function useSettingsNav(onLeave: () => void): SettingsNav {
const sections = useMemo(
() =>
- portalSections.length === 0
- ? base.sections
- : mergeSettingsGroups(
- base.sections,
- portalSections,
- portalSupersededSectionKeys(portalSections),
- ),
+ mergeSettingsGroups(base.sections, portalSections, [
+ "plan",
+ "adminPlan",
+ ...portalSupersededSectionKeys(portalSections),
+ ]),
[base.sections, portalSections],
);
+ const portalAliases = { ...PORTAL_SECTION_ALIASES };
+ if (
+ !portalSections.some((group) =>
+ group.items.some((item) => item.key === "billing"),
+ )
+ ) {
+ delete portalAliases.plan;
+ delete portalAliases.adminPlan;
+ }
+
return {
...base,
sections,
- pending: !accessSettled,
+ pending: !accessSettled || loading,
aliases:
portalSections.length > 0
- ? { ...base.aliases, ...PORTAL_SECTION_ALIASES }
+ ? { ...base.aliases, ...portalAliases }
: base.aliases,
};
}
diff --git a/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsx b/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsx
index c808ecb8db..fc2a5e0f02 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsx
+++ b/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsx
@@ -5,7 +5,6 @@ import {
useConfigNavSections as useCoreConfigNavSections,
ConfigNavSection,
} from "@core/components/shared/config/configNavSections";
-import AdminPlanSection from "@app/components/shared/config/configSections/AdminPlanSection";
import { LoadingFallback } from "@app/components/shared/LoadingFallback";
import PreferencesSection from "@core/components/shared/config/configSections/preferences/PreferencesSection";
@@ -113,26 +112,6 @@ export const useConfigNavSections = (
disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,
};
- if (showAdmin) {
- sections.push({
- id: "workspace",
- title: t("settings.workspace.title", "Workspace"),
- items: [
- {
- key: "adminPlan",
- label: t("settings.licensingAnalytics.plan", "Plan"),
- description: t(
- "settings.licensingAnalytics.planDescription",
- "Your licence, seats and what the current plan unlocks.",
- ),
- icon: "star",
- component: <AdminPlanSection />,
- ...gated,
- },
- ],
- });
- }
-
if (showAdmin) {
sections.push(
{
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx
deleted file mode 100644
index 068791b36b..0000000000
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx
+++ /dev/null
@@ -1,237 +0,0 @@
-import React, { useState, useCallback, useEffect, useMemo } from "react";
-import { SettingsEmptyState } from "@app/components/shared/config/SettingsEmptyState";
-import { Divider, Loader } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { usePlans } from "@app/hooks/usePlans";
-import licenseService, {
- PlanTierGroup,
- mapLicenseToTier,
-} from "@app/services/licenseService";
-import { useCheckout } from "@app/contexts/CheckoutContext";
-import { useLicense } from "@app/contexts/LicenseContext";
-import AvailablePlansSection from "@app/components/shared/config/configSections/plan/AvailablePlansSection";
-import StaticPlanSection from "@app/components/shared/config/configSections/plan/StaticPlanSection";
-import LicenseKeySection from "@app/components/shared/config/configSections/plan/LicenseKeySection";
-import { alert } from "@app/components/toast";
-import { AppBanner } from "@app/components/shared/AppBanner";
-import { useLicenseAlert } from "@app/hooks/useLicenseAlert";
-import {
- getPreferredCurrency,
- setCachedCurrency,
-} from "@app/utils/currencyDetection";
-import { useLoginRequired } from "@app/hooks/useLoginRequired";
-import { isSupabaseConfigured } from "@app/services/supabaseClient";
-
-const AdminPlanSection: React.FC = () => {
- const { t } = useTranslation();
- const { loginEnabled, validateLoginEnabled } = useLoginRequired();
- const { openCheckout } = useCheckout();
- const { licenseInfo } = useLicense();
- const [currency, setCurrency] = useState<string>(() => {
- return getPreferredCurrency();
- });
- const [useStaticVersion, setUseStaticVersion] = useState(false);
- const { plans, loading, error, refetch } = usePlans(currency);
- const licenseAlert = useLicenseAlert();
-
- // Check if we should use static version
- useEffect(() => {
- // Only use static version if Supabase is not configured or there's an error
- // Stripe key is not required - hosted checkout works without it
- if (!isSupabaseConfigured || error) {
- setUseStaticVersion(true);
- }
- }, [error]);
-
- const currencyOptions = [
- { value: "gbp", label: "British pound (GBP, £)" },
- { value: "usd", label: "US dollar (USD, $)" },
- { value: "eur", label: "Euro (EUR, €)" },
- { value: "cny", label: "Chinese yuan (CNY, ¥)" },
- { value: "inr", label: "Indian rupee (INR, ₹)" },
- { value: "brl", label: "Brazilian real (BRL, R$)" },
- { value: "idr", label: "Indonesian rupiah (IDR, Rp)" },
- ];
-
- const handleManageClick = useCallback(async () => {
- // Block access if login is disabled
- if (!validateLoginEnabled()) {
- return;
- }
-
- try {
- // Only allow PRO or ENTERPRISE licenses to access billing portal
- if (!licenseInfo?.licenseType || licenseInfo.licenseType === "NORMAL") {
- throw new Error(
- "No valid license found. Please purchase a license before accessing the billing portal.",
- );
- }
-
- if (!licenseInfo?.licenseKey) {
- throw new Error("License key missing. Please contact support.");
- }
-
- // Create billing portal session with license key
- const response = await licenseService.createBillingPortalSession(
- window.location.href,
- licenseInfo.licenseKey,
- );
-
- // Open billing portal in new tab
- window.open(response.url, "_blank");
- } catch (error: unknown) {
- console.error("Failed to open billing portal:", error);
- alert({
- alertType: "error",
- title: t("billing.portal.error", "Failed to open billing portal"),
- body:
- (error instanceof Error ? error.message : undefined) ||
- "Please try again or contact support.",
- });
- }
- }, [licenseInfo, t, validateLoginEnabled]);
-
- const handleCurrencyChange = useCallback((newCurrency: string) => {
- setCurrency(newCurrency);
- // Persist user's manual selection to localStorage
- setCachedCurrency(newCurrency);
- }, []);
-
- const handleUpgradeClick = useCallback(
- (planGroup: PlanTierGroup) => {
- // Block access if login is disabled
- if (!validateLoginEnabled()) {
- return;
- }
-
- // Only allow upgrades for server and enterprise tiers
- if (planGroup.tier === "free") {
- return;
- }
-
- // Prevent free tier users from directly accessing enterprise (must have server first)
- const currentTier = mapLicenseToTier(licenseInfo);
- if (currentTier === "free" && planGroup.tier === "enterprise") {
- alert({
- alertType: "warning",
- title: t("plan.enterprise.requiresServer", "Requires Team plan"),
- body: t(
- "plan.enterprise.requiresServerMessage",
- "Please upgrade to the Team plan first before upgrading to Enterprise.",
- ),
- });
- return;
- }
-
- // Use checkout context to open checkout modal
- openCheckout(planGroup.tier, {
- currency,
- onSuccess: () => {
- // Refetch plans after successful payment
- // License context will auto-update
- refetch();
- },
- });
- },
- [openCheckout, currency, refetch, licenseInfo, t, validateLoginEnabled],
- );
-
- const shouldShowLicenseWarning =
- licenseAlert.active && licenseAlert.audience === "admin";
- const formattedUserCount = useMemo(() => {
- if (licenseAlert.totalUsers == null) {
- return t("plan.licenseWarning.overLimit", "more than {{limit}}", {
- limit: licenseAlert.freeTierLimit,
- });
- }
- return licenseAlert.totalUsers.toLocaleString();
- }, [licenseAlert.totalUsers, licenseAlert.freeTierLimit, t]);
-
- const scrollToPlans = useCallback(() => {
- const el = document.getElementById("available-plans-section");
- if (el) {
- el.scrollIntoView({ behavior: "smooth", block: "start" });
- }
- }, []);
-
- // Show static version if Stripe is not configured or there's an error
- if (useStaticVersion) {
- return <StaticPlanSection currentLicenseInfo={licenseInfo ?? undefined} />;
- }
-
- // Early returns after all hooks are called
- if (loading) {
- return (
- <div
- style={{
- display: "flex",
- justifyContent: "center",
- alignItems: "center",
- padding: "2rem 0",
- }}
- >
- <Loader size="lg" />
- </div>
- );
- }
-
- if (error) {
- // Fallback to static version on error
- return <StaticPlanSection currentLicenseInfo={licenseInfo ?? undefined} />;
- }
-
- if (!plans || plans.length === 0) {
- return (
- <SettingsEmptyState
- icon="star"
- title={t("admin.settings.plan.noData.title", "No plan data")}
- >
- {t(
- "admin.settings.plan.noData.message",
- "This server could not reach the licence service. Retry, or check the licence key.",
- )}
- </SettingsEmptyState>
- );
- }
-
- return (
- <div style={{ display: "flex", flexDirection: "column", gap: "2rem" }}>
- {shouldShowLicenseWarning && (
- <AppBanner
- icon="triangle-alert"
- tone="warning"
- title={t(
- "plan.licenseWarning.title",
- "Free self-hosted limit reached",
- )}
- message={t("plan.licenseWarning.body", {
- total: formattedUserCount,
- limit: licenseAlert.freeTierLimit,
- })}
- buttonText={t("plan.licenseWarning.cta", "See plans")}
- buttonIcon="circle-arrow-up"
- onButtonClick={scrollToPlans}
- dismissible={false}
- />
- )}
-
- <AvailablePlansSection
- plans={plans}
- currentLicenseInfo={licenseInfo}
- onUpgradeClick={handleUpgradeClick}
- onManageClick={handleManageClick}
- currency={currency}
- onCurrencyChange={handleCurrencyChange}
- currencyOptions={currencyOptions}
- loginEnabled={loginEnabled}
- />
-
- <Divider />
-
- {/* License Key Section */}
- <LicenseKeySection currentLicenseInfo={licenseInfo ?? undefined} />
- </div>
- );
-};
-
-export default AdminPlanSection;
diff --git a/frontend/editor/src/proprietary/data/settingsSectionRegistry.ts b/frontend/editor/src/proprietary/data/settingsSectionRegistry.ts
index 51f7df893e..3aa99978b3 100644
--- a/frontend/editor/src/proprietary/data/settingsSectionRegistry.ts
+++ b/frontend/editor/src/proprietary/data/settingsSectionRegistry.ts
@@ -155,15 +155,6 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [
groupLabelFallback: "Server",
},
// --- Licensing & Analytics ---
- {
- key: "adminPlan",
- labelKey: "settings.licensingAnalytics.plan",
- labelFallback: "Plan",
- keywords: ["plan", "license", "billing", "subscription", "enterprise"],
- adminArea: true,
- groupLabelKey: "settings.workspace.title",
- groupLabelFallback: "Workspace",
- },
{
key: "adminAudit",
labelKey: "settings.licensingAnalytics.audit",
diff --git a/frontend/editor/src/proprietary/routes/Login.test.tsx b/frontend/editor/src/proprietary/routes/Login.test.tsx
index 5553f202fb..22ddbc649e 100644
--- a/frontend/editor/src/proprietary/routes/Login.test.tsx
+++ b/frontend/editor/src/proprietary/routes/Login.test.tsx
@@ -756,20 +756,15 @@ describe("Login", () => {
it("should disable submit button while signing in", async () => {
const user = userEvent.setup();
- vi.mocked(springAuth.signInWithPassword).mockImplementationOnce(
- () =>
- new Promise((resolve) =>
- setTimeout(
- () =>
- resolve({
- user: null,
- session: null,
- error: { message: "Error" },
- }),
- 100,
- ),
- ),
- );
+ let finishSignIn!: (
+ result: Awaited<ReturnType<typeof springAuth.signInWithPassword>>,
+ ) => void;
+ const signIn = new Promise<
+ Awaited<ReturnType<typeof springAuth.signInWithPassword>>
+ >((resolve) => {
+ finishSignIn = resolve;
+ });
+ vi.mocked(springAuth.signInWithPassword).mockReturnValueOnce(signIn);
render(
<TestWrapper>
@@ -815,7 +810,13 @@ describe("Login", () => {
// Button should be disabled while signing in
expect(submitButton).toBeDisabled();
- // Wait for completion
+ await act(async () => {
+ finishSignIn({
+ user: null,
+ session: null,
+ error: { message: "Error" },
+ });
+ });
await waitFor(() => {
expect(submitButton).not.toBeDisabled();
});
diff --git a/frontend/editor/src/saas/components/TeamSection.ownership.test.tsx b/frontend/editor/src/saas/components/TeamSection.ownership.test.tsx
new file mode 100644
index 0000000000..4364624a1c
--- /dev/null
+++ b/frontend/editor/src/saas/components/TeamSection.ownership.test.tsx
@@ -0,0 +1,103 @@
+import { beforeEach, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import TeamSection from "@app/components/shared/config/configSections/TeamSection";
+
+const { post, refreshTeams, refreshSession, teamState } = vi.hoisted(() => ({
+ teamState: { available: true, loading: false },
+ post: vi.fn(),
+ refreshTeams: vi.fn().mockResolvedValue(undefined),
+ refreshSession: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("@app/services/apiClient", () => ({ default: { post } }));
+vi.mock("@app/auth/teamSession", () => ({
+ useTeamAuth: () => ({ refreshAfterMembershipChange: refreshSession }),
+}));
+vi.mock("@app/contexts/SaaSTeamContext", () => ({
+ useSaaSTeam: () => ({
+ currentTeam: teamState.available
+ ? { teamId: 9, name: "Acme", seatsUsed: 2 }
+ : null,
+ loading: teamState.loading,
+ teamMembers: [
+ { id: 1, username: "Alex", email: "[email protected]", role: "LEADER" },
+ { id: 2, username: "Jamie", email: "[email protected]", role: "MEMBER" },
+ ],
+ teamInvitations: [],
+ isTeamLeader: true,
+ isPersonalTeam: false,
+ refreshTeams,
+ }),
+}));
+vi.mock("react-i18next", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-i18next")>();
+ const { createInstance } = await import("i18next");
+ const i18n = createInstance();
+ await i18n.use(actual.initReactI18next).init({
+ lng: "en",
+ resources: {},
+ interpolation: { escapeValue: false },
+ });
+ return { ...actual, useTranslation: () => ({ t: i18n.t, i18n }) };
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ teamState.available = true;
+ teamState.loading = false;
+ post.mockResolvedValue({
+ data: {
+ teamId: 9,
+ teamName: "Acme",
+ leaderUserId: 1,
+ targetUserId: 2,
+ linkedInstances: 0,
+ subscribed: true,
+ state: "READY",
+ },
+ });
+});
+
+it("keeps the SaaS team settings receipt open until the owner acknowledges it", async () => {
+ const view = render(
+ <MantineProvider>
+ <TeamSection />
+ </MantineProvider>,
+ );
+ refreshSession.mockImplementationOnce(async () => view.unmount());
+ fireEvent.click(screen.getByRole("button", { name: "Member actions" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Make owner" }));
+ fireEvent.click(await screen.findByRole("checkbox"));
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Transfer ownership" }));
+ });
+ expect(post).toHaveBeenCalledWith("/api/v1/team/9/ownership/transfer", {
+ email: "[email protected]",
+ expectedLeaderId: 1,
+ });
+ expect(screen.getByText("Ownership transferred")).toBeVisible();
+ expect(refreshSession).not.toHaveBeenCalled();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Done" }));
+ });
+ expect(refreshSession).toHaveBeenCalledOnce();
+ expect(screen.queryByRole("dialog")).toBeNull();
+});
+
+it("shows a retry instead of endless loading when no current team is identified", async () => {
+ teamState.available = false;
+ render(
+ <MantineProvider>
+ <TeamSection />
+ </MantineProvider>,
+ );
+ expect(screen.getByText(/couldn't identify your current team/)).toBeVisible();
+ expect(screen.queryByText("Loading team information...")).toBeNull();
+ refreshTeams.mockClear();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ });
+ expect(refreshTeams).toHaveBeenCalledOnce();
+ expect(post).not.toHaveBeenCalled();
+});
diff --git a/frontend/editor/src/saas/contexts/SaaSTeamContext.test.tsx b/frontend/editor/src/saas/contexts/SaaSTeamContext.test.tsx
new file mode 100644
index 0000000000..802fd2fed7
--- /dev/null
+++ b/frontend/editor/src/saas/contexts/SaaSTeamContext.test.tsx
@@ -0,0 +1,60 @@
+import { it, expect, vi } from "vitest";
+import { expectConsole } from "@app/tests/failOnConsole";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { SaaSTeamProvider, useSaaSTeam } from "@app/contexts/SaaSTeamContext";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@app/services/apiClient", () => ({ default: { get } }));
+vi.mock("@app/auth/teamSession", () => ({
+ useTeamAuth: () => ({
+ canUseTeams: true,
+ refreshAfterMembershipChange: vi.fn(),
+ }),
+}));
+
+it("uses the server's current team and never guesses a parked team when that marker is missing", async () => {
+ const parked = {
+ teamId: 1,
+ name: "Parked home",
+ current: false,
+ isPersonal: false,
+ isLeader: true,
+ };
+ const active = {
+ teamId: 2,
+ name: "Organisation",
+ current: true,
+ isPersonal: false,
+ isLeader: false,
+ };
+ let teams = [parked, active];
+ get.mockImplementation(async (url: string) => ({
+ data: url === "/api/v1/team/my" ? teams : [],
+ }));
+ const { result } = renderHook(() => useSaaSTeam(), {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <SaaSTeamProvider>{children}</SaaSTeamProvider>
+ ),
+ });
+ await waitFor(() => expect(result.current.currentTeam?.teamId).toBe(2));
+ expectConsole.error(/Failed to fetch teams.*Network unavailable/s);
+ get.mockRejectedValueOnce(new Error("Network unavailable"));
+ await act(() => result.current.refreshTeams());
+ expect(result.current.currentTeam?.teamId).toBe(2);
+ expect(result.current.teams).toEqual([parked, active]);
+ expect(result.current.loading).toBe(false);
+ teams = [parked];
+ await act(() => result.current.refreshTeams());
+ expect(result.current.currentTeam).toBeNull();
+ expect(result.current.loading).toBe(false);
+ expect(result.current.isTeamLeader).toBe(false);
+ expect(get).not.toHaveBeenCalledWith(
+ "/api/v1/team/1/members",
+ expect.anything(),
+ );
+ expect(get).not.toHaveBeenCalledWith(
+ "/api/v1/team/1/invitations",
+ expect.anything(),
+ );
+});
diff --git a/frontend/editor/src/saas/routes/ConnectApprove.test.tsx b/frontend/editor/src/saas/routes/ConnectApprove.test.tsx
index e14d55f61f..8131975d9c 100644
--- a/frontend/editor/src/saas/routes/ConnectApprove.test.tsx
+++ b/frontend/editor/src/saas/routes/ConnectApprove.test.tsx
@@ -228,7 +228,7 @@ describe("connect approval permissions", () => {
});
arrive();
expect(
- await screen.findByText("connect.renewal.wrongAccount"),
+ await screen.findByText("connect.renewal.currentOwnerRequired"),
).toBeInTheDocument();
expect(screen.getByText("[email protected]")).toBeInTheDocument();
expect(screen.queryByRole("checkbox")).toBeNull();
@@ -276,7 +276,7 @@ describe("connect approval permissions", () => {
await screen.findByRole("button", { name: "connect.renewal.approve" }),
);
expect(
- await screen.findByText("connect.renewal.wrongAccount"),
+ await screen.findByText("connect.renewal.currentOwnerRequired"),
).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "connect.renewal.approve" }),
@@ -319,7 +319,7 @@ describe("connect approval permissions", () => {
session.user.id = "different-owner";
view.rerender(<TestApp />);
expect(
- await screen.findByText("connect.renewal.wrongAccount"),
+ await screen.findByText("connect.renewal.currentOwnerRequired"),
).toBeInTheDocument();
await act(async () =>
resolveOld({ data: { ...pending, mode: "REAUTH", canApprove: true } }),
diff --git a/frontend/editor/src/saas/routes/ConnectApproveView.tsx b/frontend/editor/src/saas/routes/ConnectApproveView.tsx
index c0208f5daf..709bc5ba44 100644
--- a/frontend/editor/src/saas/routes/ConnectApproveView.tsx
+++ b/frontend/editor/src/saas/routes/ConnectApproveView.tsx
@@ -165,8 +165,8 @@ export function ConnectApproveView({
"This server is already linked to your account. Renew your sign-in to return to billing and usage on your server.",
)
: t(
- "connect.renewal.wrongAccount",
- "This account cannot renew this server's sign-in. Switch to the account originally used to link the server. That account must still own the linked team.",
+ "connect.renewal.currentOwnerRequired",
+ "Sign in as the current owner of the linked cloud team to renew this server's sign-in. If ownership was transferred, use the new owner's account.",
)
: pending?.canApprove
? t(