Skip to content

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

Add portal user management and access control (#6913)

Anthony Stirling8d2bb14f9969
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/config/AccessConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/config/AccessConfig.java
index b2d6d3d12d..d763c146ee 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/config/AccessConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/config/AccessConfig.java
@@ -4,7 +4,9 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import stirling.software.proprietary.access.service.DefaultPrincipalResolver;
import stirling.software.proprietary.access.service.DefaultTeamLeadLookup;
+import stirling.software.proprietary.access.service.PrincipalResolver;
import stirling.software.proprietary.access.service.TeamLeadLookup;
/** Access-layer bean wiring. */
@@ -17,4 +19,11 @@ public class AccessConfig {
TeamLeadLookup defaultTeamLeadLookup() {
return new DefaultTeamLeadLookup();
}
+
+ /** USER/TEAM projection unless another bean is defined (e.g. the saas resolver). */
+ @Bean
+ @ConditionalOnMissingBean(PrincipalResolver.class)
+ PrincipalResolver defaultPrincipalResolver() {
+ return new DefaultPrincipalResolver();
+ }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/controller/ResourceGrantController.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/controller/ResourceGrantController.java
index 5b69c6878e..cc66020670 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/controller/ResourceGrantController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/controller/ResourceGrantController.java
@@ -25,7 +25,9 @@ import stirling.software.proprietary.access.model.PrincipalType;
import stirling.software.proprietary.access.model.ResourceGrant;
import stirling.software.proprietary.access.model.ResourceType;
import stirling.software.proprietary.access.service.ResourceAccessService;
+import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamRepository;
/** Admin endpoints to grant/revoke access to gated resources (the portal, integration configs). */
@RestController
@@ -36,6 +38,8 @@ import stirling.software.proprietary.security.model.User;
public class ResourceGrantController {
private final ResourceAccessService accessService;
+ private final UserRepository userRepository;
+ private final TeamRepository teamRepository;
@GetMapping("/grants")
public ResponseEntity<?> list(
@@ -45,6 +49,14 @@ public class ResourceGrantController {
return ResponseEntity.ok(grants.stream().map(this::toDto).toList());
}
+ @GetMapping("/grants/by-principal")
+ public ResponseEntity<?> listByPrincipal(
+ @RequestParam PrincipalType principalType, @RequestParam Long principalId) {
+ List<ResourceGrant> grants =
+ accessService.listGrantsForPrincipal(principalType, principalId);
+ return ResponseEntity.ok(grants.stream().map(this::toDto).toList());
+ }
+
@PostMapping("/grants")
public ResponseEntity<?> create(
@RequestBody GrantRequest request, @AuthenticationPrincipal User admin) {
@@ -57,17 +69,26 @@ public class ResourceGrantController {
"error",
"resourceType, principalType and principalId are required"));
}
+ // PORTAL is a singleton (empty resourceId); every other type must name a resource.
+ boolean portal = request.resourceType() == ResourceType.PORTAL;
+ if (!portal && (request.resourceId() == null || request.resourceId().isBlank())) {
+ return ResponseEntity.badRequest()
+ .body(Map.of("error", "resourceId is required for " + request.resourceType()));
+ }
+ Long principalId = request.principalId();
+ String principalError = validatePrincipalExists(request.principalType(), principalId);
+ if (principalError != null) {
+ return ResponseEntity.badRequest().body(Map.of("error", principalError));
+ }
AccessPermission permission =
request.permission() == null ? AccessPermission.USE : request.permission();
- // PORTAL is a singleton resource; its grants always target the whole type.
- String resourceId =
- request.resourceType() == ResourceType.PORTAL ? "" : request.resourceId();
+ String resourceId = portal ? "" : request.resourceId();
ResourceGrant grant =
accessService.grant(
request.resourceType(),
resourceId,
request.principalType(),
- request.principalId(),
+ principalId,
permission,
admin);
return ResponseEntity.ok(toDto(grant));
@@ -79,6 +100,14 @@ public class ResourceGrantController {
return ResponseEntity.ok(Map.of("message", "Grant revoked"));
}
+ // Rejects grants to nonexistent principals (dead rows otherwise).
+ private String validatePrincipalExists(PrincipalType type, Long id) {
+ return switch (type) {
+ case USER -> userRepository.existsById(id) ? null : "User " + id + " does not exist";
+ case TEAM -> teamRepository.existsById(id) ? null : "Team " + id + " does not exist";
+ };
+ }
+
private Map<String, Object> toDto(ResourceGrant g) {
Map<String, Object> m = new HashMap<>();
m.put("id", g.getId());
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/model/OwnedResource.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/model/OwnedResource.java
index 1bca14a420..46d6e17602 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/model/OwnedResource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/model/OwnedResource.java
@@ -54,4 +54,15 @@ public abstract class OwnedResource {
public Long getOwnerTeamId() {
return ownerTeam != null ? ownerTeam.getId() : null;
}
+
+ /** Owner as a principal ref; null when server-owned (admin-only ownership). */
+ public PrincipalRef getOwnerRef() {
+ if (getOwnerUserId() != null) {
+ return PrincipalRef.user(getOwnerUserId());
+ }
+ if (getOwnerTeamId() != null) {
+ return PrincipalRef.team(getOwnerTeamId());
+ }
+ return null;
+ }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/model/PrincipalRef.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/model/PrincipalRef.java
new file mode 100644
index 0000000000..e66da7a435
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/model/PrincipalRef.java
@@ -0,0 +1,20 @@
+package stirling.software.proprietary.access.model;
+
+import java.util.Locale;
+
+/** A (type, id) principal pair; the atom grants and ownership are expressed in. */
+public record PrincipalRef(PrincipalType type, Long id) {
+
+ public static PrincipalRef user(Long id) {
+ return new PrincipalRef(PrincipalType.USER, id);
+ }
+
+ public static PrincipalRef team(Long id) {
+ return new PrincipalRef(PrincipalType.TEAM, id);
+ }
+
+ /** Canonical engine wire form, e.g. "user:12". */
+ public String token() {
+ return type.name().toLowerCase(Locale.ROOT) + ":" + id;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/model/PrincipalType.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/model/PrincipalType.java
index 9019b32845..b29b1df4c4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/model/PrincipalType.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/model/PrincipalType.java
@@ -1,6 +1,6 @@
package stirling.software.proprietary.access.model;
-/** Who a {@link ResourceGrant} is granted to. Org-wide access is expressed via default policy. */
+/** Who a {@link ResourceGrant} is granted to. */
public enum PrincipalType {
USER,
TEAM
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/repository/ResourceGrantRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/repository/ResourceGrantRepository.java
index 76209c1abe..654a8e0854 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/repository/ResourceGrantRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/repository/ResourceGrantRepository.java
@@ -3,11 +3,15 @@ package stirling.software.proprietary.access.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import stirling.software.proprietary.access.model.PrincipalType;
import stirling.software.proprietary.access.model.ResourceGrant;
import stirling.software.proprietary.access.model.ResourceType;
+import stirling.software.proprietary.security.model.User;
@Repository
public interface ResourceGrantRepository extends JpaRepository<ResourceGrant, Long> {
@@ -18,8 +22,20 @@ public interface ResourceGrantRepository extends JpaRepository<ResourceGrant, Lo
List<ResourceGrant> findByResourceTypeAndPrincipalTypeAndPrincipalId(
ResourceType resourceType, PrincipalType principalType, Long principalId);
+ /** All grants held by a principal, across resource types (for the manage-access view). */
+ List<ResourceGrant> findByPrincipalTypeAndPrincipalId(
+ PrincipalType principalType, Long principalId);
+
void deleteByResourceTypeAndResourceId(ResourceType resourceType, String resourceId);
+ /** Removes every grant held by a principal; used when the user/team behind it is deleted. */
+ void deleteByPrincipalTypeAndPrincipalId(PrincipalType principalType, Long principalId);
+
+ // Detach issued grants so deleting the granting user does not hit the FK.
+ @Modifying
+ @Query("update ResourceGrant g set g.grantedBy = null where g.grantedBy = :user")
+ void clearGrantedBy(@Param("user") User user);
+
boolean existsByResourceTypeAndResourceIdAndPrincipalTypeAndPrincipalId(
ResourceType resourceType,
String resourceId,
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/security/ResourceAccessSecurity.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/security/ResourceAccessSecurity.java
index 5189b703a1..0f35965ad4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/security/ResourceAccessSecurity.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/security/ResourceAccessSecurity.java
@@ -11,7 +11,12 @@ import stirling.software.proprietary.access.service.ResourceAccessService;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.UserService;
-/** {@code @PreAuthorize} bean for portal-access checks. Active in self-hosted and saas. */
+/**
+ * {@code @PreAuthorize} bean for portal-access checks. Active in self-hosted and saas. Convention:
+ * every portal-exclusive endpoint is gated with
+ * {@code @PreAuthorize("@resourceAccess.canUsePortal()")}; endpoints shared with the editor (e.g.
+ * the policies API) must NOT be.
+ */
@Component("resourceAccess")
@RequiredArgsConstructor
public class ResourceAccessSecurity {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/DefaultPrincipalResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/DefaultPrincipalResolver.java
new file mode 100644
index 0000000000..61a70a7336
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/DefaultPrincipalResolver.java
@@ -0,0 +1,32 @@
+package stirling.software.proprietary.access.service;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import stirling.software.proprietary.access.model.PrincipalRef;
+import stirling.software.proprietary.security.model.User;
+
+/**
+ * Self-hosted projection: the user and their team. One deployment = one org, so ORG_ALL is open.
+ */
+public class DefaultPrincipalResolver implements PrincipalResolver {
+
+ @Override
+ public Set<PrincipalRef> principalsOf(User user) {
+ if (user == null) {
+ return Set.of();
+ }
+ Set<PrincipalRef> principals = new HashSet<>();
+ principals.add(PrincipalRef.user(user.getId()));
+ if (user.getTeam() != null) {
+ principals.add(PrincipalRef.team(user.getTeam().getId()));
+ }
+ return principals;
+ }
+
+ // Self-hosted is a single deployment-wide org, so ORG_ALL admits every authenticated user.
+ @Override
+ public boolean allowsDeploymentWideAccess() {
+ return true;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/MembershipTeamLeadLookup.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/MembershipTeamLeadLookup.java
new file mode 100644
index 0000000000..9a5bece4ca
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/MembershipTeamLeadLookup.java
@@ -0,0 +1,33 @@
+package stirling.software.proprietary.access.service;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
+
+/** Real lookup backed by team_memberships LEADER rows; wins over the no-op default bean. */
+@Component
+@RequiredArgsConstructor
+public class MembershipTeamLeadLookup implements TeamLeadLookup {
+
+ private final TeamMembershipRepository memberships;
+
+ @Override
+ public boolean isAnyTeamLeader(User user) {
+ return user != null
+ && user.getId() != null
+ && memberships.existsByUserIdAndRole(user.getId(), TeamRole.LEADER);
+ }
+
+ @Override
+ public boolean isLeaderOfTeam(User user, Long teamId) {
+ return user != null
+ && user.getId() != null
+ && teamId != null
+ && memberships.existsByTeamIdAndUserIdAndRole(
+ teamId, user.getId(), TeamRole.LEADER);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/OwnershipService.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/OwnershipService.java
index 8db87f2c0e..5b62d8e890 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/OwnershipService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/OwnershipService.java
@@ -36,15 +36,19 @@ public class OwnershipService {
return accessService.canUseResource(
type,
String.valueOf(resource.getId()),
- resource.getOwnerUserId(),
+ resource.getOwnerRef(),
resource.getDefaultAccess(),
user);
}
/** Whether the user may manage the resource. */
public boolean canManage(ResourceType type, OwnedResource resource, User user) {
+ // Disabled resources bypass grants for MANAGE too: admin/owner only.
+ if (!resource.isEnabled()) {
+ return isAdmin(user) || isOwner(resource, user);
+ }
return accessService.canManageResource(
- type, String.valueOf(resource.getId()), resource.getOwnerUserId(), user);
+ type, String.valueOf(resource.getId()), resource.getOwnerRef(), user);
}
/**
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/PrincipalResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/PrincipalResolver.java
new file mode 100644
index 0000000000..94fdd990da
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/PrincipalResolver.java
@@ -0,0 +1,28 @@
+package stirling.software.proprietary.access.service;
+
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import stirling.software.proprietary.access.model.PrincipalRef;
+import stirling.software.proprietary.security.model.User;
+
+/** Projects a user onto the set of principals they act as. */
+public interface PrincipalResolver {
+
+ /** Every principal the user acts as; empty for a null user. */
+ Set<PrincipalRef> principalsOf(User user);
+
+ /**
+ * Whether this deployment treats every authenticated user as one org, so the {@code ORG_ALL}
+ * default policy admits anyone. Self-hosted: true. Multi-tenant saas: false, so an {@code
+ * ORG_ALL} resource can't leak across tenants. Defaults to false (deny) for safety.
+ */
+ default boolean allowsDeploymentWideAccess() {
+ return false;
+ }
+
+ /** Canonical wire tokens for the engine, e.g. "user:12". */
+ default Set<String> principalTokens(User user) {
+ return principalsOf(user).stream().map(PrincipalRef::token).collect(Collectors.toSet());
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/ResourceAccessService.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/ResourceAccessService.java
index ada4c95290..72159829a4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/ResourceAccessService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/ResourceAccessService.java
@@ -14,6 +14,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.enumeration.Role;
import stirling.software.proprietary.access.model.AccessPermission;
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
+import stirling.software.proprietary.access.model.PrincipalRef;
import stirling.software.proprietary.access.model.PrincipalType;
import stirling.software.proprietary.access.model.ResourceGrant;
import stirling.software.proprietary.access.model.ResourceType;
@@ -29,6 +30,7 @@ public class ResourceAccessService {
private final ResourceGrantRepository grantRepository;
private final TeamLeadLookup teamLeadLookup;
+ private final PrincipalResolver principalResolver;
@Value("${security.portal.defaultAccess:ADMINS_AND_TEAM_LEADS}")
private DefaultAccessPolicy portalDefaultPolicy;
@@ -44,28 +46,28 @@ public class ResourceAccessService {
public boolean canUseResource(
ResourceType type,
String resourceId,
- Long ownerUserId,
+ PrincipalRef owner,
DefaultAccessPolicy defaultPolicy,
User user) {
if (user == null) {
return false;
}
- if (isOwner(ownerUserId, user) || isAdmin(user)) {
+ if (isOwner(owner, user) || isAdmin(user)) {
return true;
}
if (hasGrant(type, normalize(resourceId), user, AccessPermission.USE)) {
return true;
}
- return matchesDefault(defaultPolicy, user);
+ return matchesDefault(defaultPolicy, owner, user);
}
/** Whether the user may manage (edit/delete/share) a resource. No default-policy fallback. */
public boolean canManageResource(
- ResourceType type, String resourceId, Long ownerUserId, User user) {
+ ResourceType type, String resourceId, PrincipalRef owner, User user) {
if (user == null) {
return false;
}
- if (isOwner(ownerUserId, user) || isAdmin(user)) {
+ if (isOwner(owner, user) || isAdmin(user)) {
return true;
}
return hasGrant(type, normalize(resourceId), user, AccessPermission.MANAGE);
@@ -110,21 +112,22 @@ public class ResourceAccessService {
return grantRepository.findByResourceTypeAndResourceId(type, normalize(resourceId));
}
- /** Resource ids of the given type that this user (or their team) holds any grant on. */
+ /** Every grant a principal holds, for the per-user/per-team manage-access view. */
+ public List<ResourceGrant> listGrantsForPrincipal(
+ PrincipalType principalType, Long principalId) {
+ return grantRepository.findByPrincipalTypeAndPrincipalId(principalType, principalId);
+ }
+
+ /** Resource ids of the given type that any of the user's principals holds a grant on. */
public Set<String> grantedResourceIds(ResourceType type, User user) {
if (user == null) {
return Set.of();
}
Set<String> ids = new HashSet<>();
- for (ResourceGrant g :
- grantRepository.findByResourceTypeAndPrincipalTypeAndPrincipalId(
- type, PrincipalType.USER, user.getId())) {
- ids.add(g.getResourceId());
- }
- if (user.getTeam() != null) {
+ for (PrincipalRef principal : principalResolver.principalsOf(user)) {
for (ResourceGrant g :
grantRepository.findByResourceTypeAndPrincipalTypeAndPrincipalId(
- type, PrincipalType.TEAM, user.getTeam().getId())) {
+ type, principal.type(), principal.id())) {
ids.add(g.getResourceId());
}
}
@@ -135,18 +138,12 @@ public class ResourceAccessService {
private boolean hasGrant(
ResourceType type, String resourceId, User user, AccessPermission required) {
- Long teamId = user.getTeam() != null ? user.getTeam().getId() : null;
+ Set<PrincipalRef> principals = principalResolver.principalsOf(user);
for (ResourceGrant g : grantRepository.findByResourceTypeAndResourceId(type, resourceId)) {
if (!permissionSatisfies(g.getPermission(), required)) {
continue;
}
- if (g.getPrincipalType() == PrincipalType.USER
- && g.getPrincipalId().equals(user.getId())) {
- return true;
- }
- if (g.getPrincipalType() == PrincipalType.TEAM
- && teamId != null
- && g.getPrincipalId().equals(teamId)) {
+ if (principals.contains(new PrincipalRef(g.getPrincipalType(), g.getPrincipalId()))) {
return true;
}
}
@@ -161,20 +158,40 @@ public class ResourceAccessService {
return held == AccessPermission.MANAGE;
}
- private boolean matchesDefault(DefaultAccessPolicy policy, User user) {
+ private boolean matchesDefault(DefaultAccessPolicy policy, PrincipalRef owner, User user) {
if (policy == null) {
return false;
}
return switch (policy) {
- case ORG_ALL -> true;
- // Admins already pass above; only team leads here.
- case ADMINS_AND_TEAM_LEADS -> teamLeadLookup.isAnyTeamLeader(user);
+ // Deployment-wide only where the resolver treats everyone as one org; saas resolvers
+ // return false, so ORG_ALL cannot leak a tenant's resource to another tenant's users.
+ case ORG_ALL -> principalResolver.allowsDeploymentWideAccess();
+ // Admins already pass above; only team leads here, scoped to the owning team.
+ case ADMINS_AND_TEAM_LEADS -> matchesTeamLeadDefault(owner, user);
case EXPLICIT_ONLY -> false;
};
}
- private boolean isOwner(Long ownerUserId, User user) {
- return ownerUserId != null && ownerUserId.equals(user.getId());
+ // Portal (no owner) admits any team lead; a team-owned resource admits only that team's
+ // leads; a user-owned resource admits no extra leads.
+ private boolean matchesTeamLeadDefault(PrincipalRef owner, User user) {
+ if (owner == null) {
+ return teamLeadLookup.isAnyTeamLeader(user);
+ }
+ return owner.type() == PrincipalType.TEAM
+ && owner.id() != null
+ && teamLeadLookup.isLeaderOfTeam(user, owner.id());
+ }
+
+ // Team owners are the owning team's leaders; plain members are not.
+ private boolean isOwner(PrincipalRef owner, User user) {
+ if (owner == null || owner.id() == null) {
+ return false;
+ }
+ return switch (owner.type()) {
+ case USER -> owner.id().equals(user.getId());
+ case TEAM -> teamLeadLookup.isLeaderOfTeam(user, owner.id());
+ };
}
private boolean isAdmin(User user) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.java
index 917c180116..f160b92759 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.java
@@ -18,15 +18,26 @@ public class SecretMasker {
// Cap recursion so a pathologically nested payload cannot overflow the stack.
private static final int MAX_DEPTH = 32;
+ // Key-name substrings that mark a value sensitive. Over-masking a non-secret is
+ // safe; leaking a secret is not, so this errs broad - but a per-type schema
+ // whitelist would be a stronger boundary for free-form config (follow-up).
private static final Set<String> SENSITIVE_HINTS =
Set.of(
"secret",
"password",
+ "passphrase",
+ "pwd",
"token",
"apikey",
"accesskey",
"credential",
- "privatekey");
+ "privatekey",
+ "authorization",
+ "cookie",
+ "session",
+ "connectionstring",
+ "bearer",
+ "signature");
/** Replace sensitive values with the mask (recursively) for safe display. */
public Map<String, Object> mask(Map<String, Object> config) {
@@ -73,18 +84,24 @@ public class SecretMasker {
private Map<String, Object> merge(
Map<String, Object> stored, Map<String, Object> incoming, int depth) {
- Map<String, Object> out = new LinkedHashMap<>(stored);
+ // Replace semantics (PUT): the result is the incoming document, except a redacted secret
+ // keeps its stored value. Keys absent from incoming are dropped, so edits can remove them.
+ Map<String, Object> out = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : incoming.entrySet()) {
String key = e.getKey();
Object value = e.getValue();
if (isSensitive(key)) {
- if (!isRedacted(value, depth)) {
+ if (isRedacted(value, depth)) {
+ if (stored.containsKey(key)) {
+ out.put(key, stored.get(key)); // keep the stored secret
+ }
+ } else {
out.put(key, value); // a real new secret replaces the stored one
}
- continue; // redacted (blank / mask) -> keep stored
+ continue;
}
if (depth < MAX_DEPTH
- && out.get(key) instanceof Map<?, ?> s
+ && stored.get(key) instanceof Map<?, ?> s
&& value instanceof Map<?, ?> i) {
out.put(key, merge(castMap(s), castMap(i), depth + 1));
} else {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
index 161c1d7055..8db5f48174 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
@@ -5,6 +5,7 @@ import static stirling.software.common.util.ProviderUtils.validateProvider;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
+import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
@@ -28,13 +29,16 @@ import stirling.software.common.model.ApplicationProperties.Security.OAUTH2.Clie
import stirling.software.common.model.ApplicationProperties.Security.SAML2;
import stirling.software.common.model.FileInfo;
import stirling.software.common.model.enumeration.Role;
+import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.common.model.oauth2.GitHubProvider;
import stirling.software.common.model.oauth2.GoogleProvider;
import stirling.software.common.model.oauth2.KeycloakProvider;
+import stirling.software.proprietary.access.service.ResourceAccessService;
import stirling.software.proprietary.audit.AuditEventType;
import stirling.software.proprietary.audit.AuditLevel;
import stirling.software.proprietary.config.AuditConfigurationProperties;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.model.dto.TeamWithUserCountDTO;
import stirling.software.proprietary.repository.PersistentAuditEventRepository;
import stirling.software.proprietary.security.config.EnterpriseEndpoint;
@@ -44,6 +48,7 @@ import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.SessionEntity;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.dto.AdminUserSummary;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.DatabaseServiceInterface;
@@ -65,6 +70,7 @@ public class ProprietaryUIDataController {
private final SessionPersistentRegistry sessionPersistentRegistry;
private final UserRepository userRepository;
private final TeamRepository teamRepository;
+ private final TeamMembershipRepository teamMembershipRepository;
private final SessionRepository sessionRepository;
private final DatabaseServiceInterface databaseService;
private final boolean runningEE;
@@ -73,6 +79,7 @@ public class ProprietaryUIDataController {
private final PersistentAuditEventRepository auditRepository;
private final MfaService mfaService;
private final LoginAttemptService loginAttemptService;
+ private final ResourceAccessService resourceAccessService;
public ProprietaryUIDataController(
ApplicationProperties applicationProperties,
@@ -80,6 +87,7 @@ public class ProprietaryUIDataController {
SessionPersistentRegistry sessionPersistentRegistry,
UserRepository userRepository,
TeamRepository teamRepository,
+ TeamMembershipRepository teamMembershipRepository,
SessionRepository sessionRepository,
DatabaseServiceInterface databaseService,
ObjectMapper objectMapper,
@@ -87,12 +95,14 @@ public class ProprietaryUIDataController {
UserLicenseSettingsService licenseSettingsService,
PersistentAuditEventRepository auditRepository,
MfaService mfaService,
- LoginAttemptService loginAttemptService) {
+ LoginAttemptService loginAttemptService,
+ ResourceAccessService resourceAccessService) {
this.applicationProperties = applicationProperties;
this.auditConfig = auditConfig;
this.sessionPersistentRegistry = sessionPersistentRegistry;
this.userRepository = userRepository;
this.teamRepository = teamRepository;
+ this.teamMembershipRepository = teamMembershipRepository;
this.sessionRepository = sessionRepository;
this.databaseService = databaseService;
this.objectMapper = objectMapper;
@@ -101,6 +111,7 @@ public class ProprietaryUIDataController {
this.auditRepository = auditRepository;
this.mfaService = mfaService;
this.loginAttemptService = loginAttemptService;
+ this.resourceAccessService = resourceAccessService;
}
/**
@@ -370,8 +381,11 @@ public class ProprietaryUIDataController {
boolean premiumEnabled = applicationProperties.getPremium().isEnabled();
// Convert User entities to AdminUserSummary DTOs to exclude sensitive fields
+ Set<Long> leaderUserIds = leaderUserIds();
List<AdminUserSummary> userSummaries =
- sortedUsers.stream().map(this::convertUserToSummary).toList();
+ sortedUsers.stream()
+ .map(user -> convertUserToSummary(user, leaderUserIds))
+ .toList();
AdminSettingsData data = new AdminSettingsData();
data.setUsers(userSummaries);
@@ -390,6 +404,10 @@ public class ProprietaryUIDataController {
data.setLicenseMaxUsers(licenseMaxUsers);
data.setPremiumEnabled(premiumEnabled);
data.setMailEnabled(applicationProperties.getMail().isEnabled());
+ // Email invites need the invites toggle AND SMTP on; matches the inviteUsers precondition.
+ data.setEmailInvitesEnabled(
+ applicationProperties.getMail().isEnableInvites()
+ && applicationProperties.getMail().isEnabled());
data.setUserSettings(userSettings);
data.setLockedUsers(loginAttemptService.getAllBlockedUsers());
@@ -468,9 +486,18 @@ public class ProprietaryUIDataController {
teamLastRequest.put(teamId, lastActivity);
}
+ Map<Long, List<String>> teamOwners = new HashMap<>();
+ for (TeamMembership row :
+ teamMembershipRepository.findByRoleFetchingUserAndTeam(TeamRole.LEADER)) {
+ teamOwners
+ .computeIfAbsent(row.getTeam().getId(), id -> new ArrayList<>())
+ .add(row.getUser().getUsername());
+ }
+
TeamsData data = new TeamsData();
data.setTeamsWithCounts(teamsWithCounts);
data.setTeamLastRequest(teamLastRequest);
+ data.setTeamOwners(teamOwners);
return ResponseEntity.ok(data);
}
@@ -510,11 +537,17 @@ public class ProprietaryUIDataController {
userLastRequest.put(username, lastRequest);
}
+ Set<Long> ownerUserIds =
+ teamMembershipRepository.findByTeamIdAndRole(id, TeamRole.LEADER).stream()
+ .map(row -> row.getUser().getId())
+ .collect(Collectors.toSet());
+
TeamDetailsData data = new TeamDetailsData();
data.setTeam(team);
data.setTeamUsers(teamUsers);
data.setAvailableUsers(availableUsers);
data.setUserLastRequest(userLastRequest);
+ data.setOwnerUserIds(ownerUserIds);
return ResponseEntity.ok(data);
}
@@ -535,13 +568,24 @@ public class ProprietaryUIDataController {
return ResponseEntity.ok(data);
}
+ /** User ids holding a LEADER membership on any team. */
+ private Set<Long> leaderUserIds() {
+ return teamMembershipRepository.findByRoleFetchingUserAndTeam(TeamRole.LEADER).stream()
+ .map(row -> row.getUser().getId())
+ .collect(Collectors.toSet());
+ }
+
/**
* Convert User entity to AdminUserSummary DTO, excluding sensitive fields like password and
* apiKey.
*/
- private AdminUserSummary convertUserToSummary(User user) {
+ private AdminUserSummary convertUserToSummary(User user, Set<Long> leaderUserIds) {
AdminUserSummary summary = new AdminUserSummary();
summary.setId(user.getId());
+ summary.setTeamLead(leaderUserIds.contains(user.getId()));
+ // Authoritative portal access, same call /me uses, so the roster honors the configured
+ // policy instead of the frontend guessing from role/team-leadership.
+ summary.setPortalAccess(resourceAccessService.canAccessPortal(user));
summary.setUsername(user.getUsername());
summary.setEmail(user.getUsername()); // Use username as email for consistency
summary.setRoleName(user.getRoleName());
@@ -609,6 +653,7 @@ public class ProprietaryUIDataController {
private int licenseMaxUsers;
private boolean premiumEnabled;
private boolean mailEnabled;
+ private boolean emailInvitesEnabled;
private Map<String, Map<String, String>> userSettings;
private List<String> lockedUsers;
}
@@ -629,6 +674,7 @@ public class ProprietaryUIDataController {
public static class TeamsData {
private List<TeamWithUserCountDTO> teamsWithCounts;
private Map<Long, Date> teamLastRequest;
+ private Map<Long, List<String>> teamOwners;
}
@Data
@@ -637,6 +683,7 @@ public class ProprietaryUIDataController {
private List<User> teamUsers;
private List<User> availableUsers;
private Map<String, Date> userLastRequest;
+ private Set<Long> ownerUserIds;
}
@Data
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.java
index 220c4e8d65..4e79fc5e7a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.java
@@ -29,7 +29,9 @@ import stirling.software.proprietary.security.model.User;
@RestController
@RequestMapping("/api/v1/integrations")
@RequiredArgsConstructor
-@PreAuthorize("isAuthenticated()")
+// Portal-exclusive: server-side portal-access boundary, not just isAuthenticated. Per-config
+// ownership is still enforced in the service layer.
+@PreAuthorize("@resourceAccess.canUsePortal()")
@Tag(name = "Integrations", description = "Manage S3/MCP/API integration configurations")
public class IntegrationConfigController {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/crypto/CredentialEncryption.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/crypto/CredentialEncryption.java
index 1fff2dd321..96e20f55cb 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/crypto/CredentialEncryption.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/crypto/CredentialEncryption.java
@@ -1,12 +1,16 @@
package stirling.software.proprietary.integration.crypto;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
+import java.util.EnumSet;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
@@ -74,7 +78,7 @@ public class CredentialEncryption {
generator.init(256);
SecretKey generated = generator.generateKey();
Files.createDirectories(path.getParent());
- Files.writeString(path, Base64.getEncoder().encodeToString(generated.getEncoded()));
+ writeOwnerOnly(path, Base64.getEncoder().encodeToString(generated.getEncoded()));
log.warn(
"Generated a new credential encryption key at {}. Back this file up: losing it"
+ " makes stored integration secrets unrecoverable.",
@@ -85,6 +89,25 @@ public class CredentialEncryption {
}
}
+ // The master key decrypts every stored integration secret, so create it 0600
+ // (owner-only) atomically. On non-POSIX filesystems (Windows) the config-dir
+ // ACL is the protection; we still create the file, just without POSIX perms.
+ private static void writeOwnerOnly(Path path, String content) throws IOException {
+ EnumSet<PosixFilePermission> ownerOnly =
+ EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);
+ try {
+ Files.createFile(path, PosixFilePermissions.asFileAttribute(ownerOnly));
+ } catch (UnsupportedOperationException e) {
+ Files.createFile(path);
+ }
+ Files.writeString(path, content);
+ try {
+ Files.setPosixFilePermissions(path, ownerOnly);
+ } catch (UnsupportedOperationException ignored) {
+ // Non-POSIX filesystem: nothing to tighten here.
+ }
+ }
+
public static String encrypt(String plaintext) {
if (plaintext == null) {
return null;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/repository/IntegrationConfigRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/repository/IntegrationConfigRepository.java
index 6efb45d745..30556060d4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/repository/IntegrationConfigRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/repository/IntegrationConfigRepository.java
@@ -18,4 +18,13 @@ public interface IntegrationConfigRepository extends JpaRepository<IntegrationCo
List<IntegrationConfig> findByOwnerTeam(Team ownerTeam);
List<IntegrationConfig> findByScope(OwnerScope scope);
+
+ // Nested path: OwnedResource has a getOwnerTeamId() convenience getter but no such persistent
+ // attribute, so the plain "...OwnerTeamId" derivation resolves to a phantom property and throws
+ // UnknownPathException. The underscore forces the real ownerTeam.id association path.
+ boolean existsByOwnerTeam_Id(Long teamId);
+
+ void deleteByOwnerUser(User ownerUser);
+
+ void deleteByOwnerTeam_Id(Long teamId);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java
index b384cc48e6..9e44b35523 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java
@@ -16,6 +16,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
import stirling.software.proprietary.access.model.OwnerScope;
import stirling.software.proprietary.access.model.ResourceType;
+import stirling.software.proprietary.access.repository.ResourceGrantRepository;
import stirling.software.proprietary.access.service.OwnershipService;
import stirling.software.proprietary.access.service.SecretMasker;
import stirling.software.proprietary.integration.dto.IntegrationConfigRequest;
@@ -41,6 +42,7 @@ public class IntegrationConfigService {
private final IntegrationConfigRepository repository;
private final OwnershipService ownership;
private final SecretMasker secretMasker;
+ private final ResourceGrantRepository grantRepository;
// ---- commands ----
@@ -49,6 +51,13 @@ public class IntegrationConfigService {
OwnerScope scope = request.scope() == null ? OwnerScope.USER : request.scope();
IntegrationConfig cfg = new IntegrationConfig();
cfg.setIntegrationType(require(request.integrationType(), "integrationType"));
+ // S3 is infrastructure, not self-serve: no personal S3 for regular users. TEAM/SERVER
+ // scopes are already restricted to admins/team owners by assignOwnership.
+ if (cfg.getIntegrationType() == IntegrationType.S3
+ && scope == OwnerScope.USER
+ && !ownership.isAdmin(currentUser)) {
+ throw forbidden("S3 connections can only be created by administrators or team owners");
+ }
cfg.setName(require(request.name(), "name"));
cfg.setEnabled(request.enabled() == null || request.enabled());
cfg.setLocked(request.locked() != null && request.locked());
@@ -104,6 +113,8 @@ public class IntegrationConfigService {
if (!ownership.canManage(TYPE, cfg, currentUser)) {
throw forbidden("You cannot manage this integration");
}
+ // Drop grants sharing this config so they do not dangle as dead rows.
+ grantRepository.deleteByResourceTypeAndResourceId(TYPE, String.valueOf(cfg.getId()));
repository.delete(cfg);
}
diff --git a/app/saas/src/main/java/stirling/software/saas/model/TeamMembership.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/TeamMembership.java
similarity index 96%
rename from app/saas/src/main/java/stirling/software/saas/model/TeamMembership.java
rename to app/proprietary/src/main/java/stirling/software/proprietary/model/TeamMembership.java
index 4221643432..de121939bb 100644
--- a/app/saas/src/main/java/stirling/software/saas/model/TeamMembership.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/TeamMembership.java
@@ -1,4 +1,4 @@
-package stirling.software.saas.model;
+package stirling.software.proprietary.model;
import java.io.Serializable;
import java.time.LocalDateTime;
@@ -15,7 +15,6 @@ import lombok.Setter;
import lombok.ToString;
import stirling.software.common.model.enumeration.TeamRole;
-import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.User;
/**
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.java
index 94dc41a231..5d68bc99e0 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/InitialSecuritySetup.java
@@ -22,6 +22,7 @@ import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.DatabaseServiceInterface;
import stirling.software.proprietary.security.service.SaveUserRequest;
+import stirling.software.proprietary.security.service.TeamMembershipService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@@ -40,6 +41,7 @@ public class InitialSecuritySetup {
private final DatabaseServiceInterface databaseService;
private final UserLicenseSettingsService licenseSettingsService;
private final Environment environment;
+ private final TeamMembershipService teamMembershipService;
/**
* SaaS manages identity in Supabase and billing via PAYG, so the self-host bootstrap steps that
@@ -114,6 +116,7 @@ public class InitialSecuritySetup {
}
userService.saveAll(usersWithoutTeam); // batch save
+ usersWithoutTeam.forEach(teamMembershipService::syncMembership);
if (usersWithoutTeam != null && !usersWithoutTeam.isEmpty()) {
log.info(
"Assigned {} user(s) without a team to the default team.",
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java
index dcea7807b1..86a1c5fe0c 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AuthController.java
@@ -29,6 +29,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.constants.JwtConstants;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.access.service.ResourceAccessService;
+import stirling.software.proprietary.access.service.TeamLeadLookup;
import stirling.software.proprietary.audit.AuditEventType;
import stirling.software.proprietary.audit.AuditLevel;
import stirling.software.proprietary.audit.Audited;
@@ -66,6 +67,7 @@ public class AuthController {
private final ApplicationProperties applicationProperties;
private final AiUserDataService aiUserDataService;
private final ResourceAccessService resourceAccessService;
+ private final TeamLeadLookup teamLeadLookup;
/**
* Login endpoint - replaces Supabase signInWithPassword
@@ -265,8 +267,11 @@ public class AuthController {
.body(Map.of("error", "Not authenticated"));
}
- UserDetails userDetails = (UserDetails) auth.getPrincipal();
- User user = (User) userDetails;
+ // Anonymous SaaS sessions carry a raw Jwt principal; treat them as unauthenticated
+ if (!(auth.getPrincipal() instanceof User user)) {
+ return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
+ .body(Map.of("error", "Not authenticated"));
+ }
return ResponseEntity.ok(Map.of("user", buildUserResponse(user)));
@@ -631,6 +636,12 @@ public class AuthController {
userMap.put("role", user.getRolesAsString());
userMap.put("enabled", user.isEnabled());
userMap.put("portalAccess", resourceAccessService.canAccessPortal(user));
+ userMap.put("teamLead", teamLeadLookup.isAnyTeamLeader(user));
+ // Expose the caller's team so non-admin team owners can scope their own team's resources.
+ if (user.getTeam() != null) {
+ userMap.put(
+ "team", Map.of("id", user.getTeam().getId(), "name", user.getTeam().getName()));
+ }
userMap.put(
"authenticationType",
user.getAuthenticationType()); // Expose authentication type for SSO detection
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java
index d9e43fa848..32a429ea72 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/TeamController.java
@@ -14,11 +14,15 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.TeamApi;
+import stirling.software.proprietary.access.model.PrincipalType;
+import stirling.software.proprietary.access.repository.ResourceGrantRepository;
+import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.config.PremiumEndpoint;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.TeamRepository;
+import stirling.software.proprietary.security.service.TeamMembershipService;
import stirling.software.proprietary.security.service.TeamService;
@TeamApi
@@ -29,6 +33,9 @@ public class TeamController {
private final TeamRepository teamRepository;
private final UserRepository userRepository;
+ private final ResourceGrantRepository resourceGrantRepository;
+ private final IntegrationConfigRepository integrationConfigRepository;
+ private final TeamMembershipService teamMembershipService;
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/create")
@@ -96,10 +103,72 @@ public class TeamController {
"Team must be empty before deletion. Please remove all members first."));
}
+ if (integrationConfigRepository.existsByOwnerTeam_Id(teamId)) {
+ return ResponseEntity.status(HttpStatus.CONFLICT)
+ .body(
+ Map.of(
+ "error",
+ "Team still owns integration configurations. Delete or reassign them first."));
+ }
+
+ // Team grants and membership rows would dangle once the team row is gone
+ resourceGrantRepository.deleteByPrincipalTypeAndPrincipalId(PrincipalType.TEAM, teamId);
+ teamMembershipService.deleteAllForTeam(teamId);
teamRepository.delete(team);
return ResponseEntity.ok(Map.of("message", "Team deleted successfully"));
}
+ @PreAuthorize("hasRole('ADMIN')")
+ @PostMapping("/setOwner")
+ @Transactional
+ public ResponseEntity<?> setTeamOwner(
+ @RequestParam("teamId") Long teamId, @RequestParam("userId") Long userId) {
+ return mutateOwner(teamId, userId, true);
+ }
+
+ @PreAuthorize("hasRole('ADMIN')")
+ @PostMapping("/removeOwner")
+ @Transactional
+ public ResponseEntity<?> removeTeamOwner(
+ @RequestParam("teamId") Long teamId, @RequestParam("userId") Long userId) {
+ return mutateOwner(teamId, userId, false);
+ }
+
+ private ResponseEntity<?> mutateOwner(Long teamId, Long userId, boolean owner) {
+ Optional<Team> teamOpt = teamRepository.findById(teamId);
+ if (teamOpt.isEmpty()) {
+ return ResponseEntity.status(HttpStatus.NOT_FOUND)
+ .body(Map.of("error", "Team not found."));
+ }
+ Team team = teamOpt.get();
+
+ // System teams have no owners
+ if (TeamService.INTERNAL_TEAM_NAME.equals(team.getName())
+ || TeamService.DEFAULT_TEAM_NAME.equals(team.getName())) {
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Map.of("error", "System teams cannot have owners."));
+ }
+
+ Optional<User> userOpt = userRepository.findById(userId);
+ if (userOpt.isEmpty()) {
+ return ResponseEntity.status(HttpStatus.NOT_FOUND)
+ .body(Map.of("error", "User not found."));
+ }
+ User user = userOpt.get();
+
+ if (user.getTeam() == null || !user.getTeam().getId().equals(teamId)) {
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Map.of("error", "User must be a member of the team."));
+ }
+
+ if (owner) {
+ teamMembershipService.setOwner(team, user);
+ return ResponseEntity.ok(Map.of("message", "Team owner assigned successfully"));
+ }
+ teamMembershipService.removeOwner(team, user);
+ return ResponseEntity.ok(Map.of("message", "Team owner removed successfully"));
+ }
+
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/addUser")
@Transactional
@@ -138,6 +207,7 @@ public class TeamController {
// Assign user to team
user.setTeam(team);
userRepository.save(user);
+ teamMembershipService.syncMembership(user);
return ResponseEntity.ok(Map.of("message", "User added to team successfully"));
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java
index d8500e475f..b19c052ff1 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/UserController.java
@@ -50,6 +50,7 @@ import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrin
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.SaveUserRequest;
+import stirling.software.proprietary.security.service.TeamMembershipService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -69,6 +70,7 @@ public class UserController {
private final Optional<EmailService> emailService;
private final UserLicenseSettingsService licenseSettingsService;
private final LoginAttemptService loginAttemptService;
+ private final TeamMembershipService teamMembershipService;
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@PostMapping("/register")
@@ -644,6 +646,7 @@ public class UserController {
user.setTeam(team);
userRepository.save(user);
+ teamMembershipService.syncMembership(user);
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java
index 2a3e7d2af6..5a503e9436 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java
@@ -50,6 +50,14 @@ public class AdminUserSummary {
@Schema(description = "Team membership (if any)")
private TeamSummary team;
+ @Schema(description = "Whether the user owns (leads) any team")
+ private boolean teamLead;
+
+ @Schema(
+ description =
+ "Whether the user may access the portal, per the server-side access policy")
+ private boolean portalAccess;
+
@Schema(description = "User account creation timestamp")
private LocalDateTime createdAt;
diff --git a/app/saas/src/main/java/stirling/software/saas/repository/TeamMembershipRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/TeamMembershipRepository.java
similarity index 77%
rename from app/saas/src/main/java/stirling/software/saas/repository/TeamMembershipRepository.java
rename to app/proprietary/src/main/java/stirling/software/proprietary/security/repository/TeamMembershipRepository.java
index 36c04f09c3..0662edd67b 100644
--- a/app/saas/src/main/java/stirling/software/saas/repository/TeamMembershipRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/TeamMembershipRepository.java
@@ -1,15 +1,17 @@
-package stirling.software.saas.repository;
+package stirling.software.proprietary.security.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import stirling.software.common.model.enumeration.TeamRole;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.model.TeamMembership;
+import stirling.software.proprietary.security.model.User;
@Repository
public interface TeamMembershipRepository extends JpaRepository<TeamMembership, Long> {
@@ -106,4 +108,24 @@ public interface TeamMembershipRepository extends JpaRepository<TeamMembership,
* @param userId the user ID
*/
void deleteByTeamIdAndUserId(Long teamId, Long userId);
+
+ /** Leadership checks for TeamLeadLookup. */
+ boolean existsByTeamIdAndUserIdAndRole(Long teamId, Long userId, TeamRole role);
+
+ boolean existsByUserIdAndRole(Long userId, TeamRole role);
+
+ /** All rows holding a role, users and teams pre-fetched for out-of-session mapping. */
+ @Query(
+ "SELECT tm FROM TeamMembership tm JOIN FETCH tm.user JOIN FETCH tm.team"
+ + " WHERE tm.role = :role")
+ List<TeamMembership> findByRoleFetchingUserAndTeam(@Param("role") TeamRole role);
+
+ void deleteByTeamId(Long teamId);
+
+ void deleteByUserId(Long userId);
+
+ // Detach invitation references so deleting the inviting user does not hit the FK.
+ @Modifying
+ @Query("update TeamMembership tm set tm.invitedBy = null where tm.invitedBy = :user")
+ void clearInvitedBy(@Param("user") User user);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/TeamMembershipService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/TeamMembershipService.java
new file mode 100644
index 0000000000..e8fca904b6
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/TeamMembershipService.java
@@ -0,0 +1,117 @@
+package stirling.software.proprietary.security.service;
+
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
+
+/**
+ * Keeps team_memberships in step with users.team_id on self-hosted admin flows and holds the
+ * team-owner (LEADER role) mutations. SaaS owns membership lifecycle (seats, personal teams,
+ * last-leader guards) via SaasTeamService, so these mutations no-op on the saas profile to avoid
+ * corrupting its accounting.
+ */
+@Service
+@RequiredArgsConstructor
+public class TeamMembershipService {
+
+ private final TeamMembershipRepository membershipRepository;
+ private final Environment environment;
+
+ private boolean isSaas() {
+ return Arrays.asList(environment.getActiveProfiles()).contains("saas");
+ }
+
+ /** Reflects users.team_id into membership rows, preserving an existing role on the team. */
+ @Transactional
+ public void syncMembership(User user) {
+ if (isSaas() || user == null || user.getId() == null) {
+ return;
+ }
+ Long teamId = user.getTeam() != null ? user.getTeam().getId() : null;
+ boolean present = false;
+ for (TeamMembership row : membershipRepository.findByUserId(user.getId())) {
+ if (teamId != null && teamId.equals(row.getTeam().getId())) {
+ present = true;
+ } else {
+ membershipRepository.delete(row);
+ }
+ }
+ if (teamId != null && !present) {
+ membershipRepository.save(newRow(user.getTeam(), user, TeamRole.MEMBER));
+ }
+ }
+
+ /** Promotes a member to team owner, creating the membership row if it is missing. */
+ @Transactional
+ public void setOwner(Team team, User user) {
+ if (isSaas()) {
+ return;
+ }
+ Optional<TeamMembership> existing =
+ membershipRepository.findByTeamIdAndUserId(team.getId(), user.getId());
+ if (existing.isPresent()) {
+ existing.get().setRole(TeamRole.LEADER);
+ membershipRepository.save(existing.get());
+ } else {
+ membershipRepository.save(newRow(team, user, TeamRole.LEADER));
+ }
+ }
+
+ /** Demotes a team owner back to member; keeps the membership row. */
+ @Transactional
+ public void removeOwner(Team team, User user) {
+ if (isSaas()) {
+ return;
+ }
+ membershipRepository
+ .findByTeamIdAndUserId(team.getId(), user.getId())
+ .ifPresent(
+ row -> {
+ row.setRole(TeamRole.MEMBER);
+ membershipRepository.save(row);
+ });
+ }
+
+ /** Owner user ids for a team. */
+ @Transactional(readOnly = true)
+ public List<Long> ownerUserIds(Long teamId) {
+ return membershipRepository.findByTeamIdAndRole(teamId, TeamRole.LEADER).stream()
+ .map(row -> row.getUser().getId())
+ .toList();
+ }
+
+ @Transactional
+ public void deleteAllForTeam(Long teamId) {
+ membershipRepository.deleteByTeamId(teamId);
+ }
+
+ @Transactional
+ public void deleteAllForUser(User user) {
+ membershipRepository.deleteByUserId(user.getId());
+ membershipRepository.clearInvitedBy(user);
+ }
+
+ private TeamMembership newRow(Team team, User user, TeamRole role) {
+ TeamMembership row = new TeamMembership();
+ row.setTeam(team);
+ row.setUser(user);
+ row.setRole(role);
+ // Self-hosted rows are admin-assigned, not invitation-driven.
+ row.setInvitedAt(LocalDateTime.now());
+ row.setAcceptedAt(LocalDateTime.now());
+ return row;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
index a7aaa573fd..45532978f3 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
@@ -39,6 +39,11 @@ import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.exception.UnsupportedProviderException;
import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.RegexPatternUtils;
+import stirling.software.proprietary.access.model.PrincipalType;
+import stirling.software.proprietary.access.model.ResourceType;
+import stirling.software.proprietary.access.repository.ResourceGrantRepository;
+import stirling.software.proprietary.integration.model.IntegrationConfig;
+import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.database.repository.AuthorityRepository;
import stirling.software.proprietary.security.database.repository.PersistentLoginRepository;
@@ -87,6 +92,9 @@ public class UserService implements UserServiceInterface {
private final StorageCleanupEntryRepository storageCleanupEntryRepository;
private final FileShareRepository fileShareRepository;
private final FileShareAccessRepository fileShareAccessRepository;
+ private final ResourceGrantRepository resourceGrantRepository;
+ private final IntegrationConfigRepository integrationConfigRepository;
+ private final TeamMembershipService teamMembershipService;
@Transactional
public void processSSOPostLogin(
@@ -249,6 +257,21 @@ public class UserService implements UserServiceInterface {
private void deleteUserRelatedData(User user) {
log.info("Deleting all associated data for user: {}", user.getUsername());
+ // Drop ACL grants held by this user and detach grants they issued
+ resourceGrantRepository.deleteByPrincipalTypeAndPrincipalId(
+ PrincipalType.USER, user.getId());
+ resourceGrantRepository.clearGrantedBy(user);
+
+ // Integration configs owned by this user FK the users row; drop them and their grants
+ for (IntegrationConfig cfg : integrationConfigRepository.findByOwnerUser(user)) {
+ resourceGrantRepository.deleteByResourceTypeAndResourceId(
+ ResourceType.INTEGRATION_CONFIG, String.valueOf(cfg.getId()));
+ }
+ integrationConfigRepository.deleteByOwnerUser(user);
+
+ // Membership rows and invitation references would dangle once the user row is gone
+ teamMembershipService.deleteAllForUser(user);
+
// Delete server certificate (non-nullable OneToOne → User)
userServerCertificateService.deleteUserCertificate(user.getId());
@@ -412,6 +435,7 @@ public class UserService implements UserServiceInterface {
}
user.setTeam(team);
userRepository.save(user);
+ teamMembershipService.syncMembership(user);
databaseService.exportDatabase();
}
@@ -523,6 +547,7 @@ public class UserService implements UserServiceInterface {
// Save user
userRepository.save(user);
+ teamMembershipService.syncMembership(user);
// Export database
databaseService.exportDatabase();
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/access/security/ResourceAccessSecurityTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/access/security/ResourceAccessSecurityTest.java
new file mode 100644
index 0000000000..09c0fbf1f7
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/access/security/ResourceAccessSecurityTest.java
@@ -0,0 +1,61 @@
+package stirling.software.proprietary.access.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.proprietary.access.service.ResourceAccessService;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.service.UserService;
+
+@ExtendWith(MockitoExtension.class)
+class ResourceAccessSecurityTest {
+
+ @Mock private ResourceAccessService accessService;
+ @Mock private UserService userService;
+
+ @InjectMocks private ResourceAccessSecurity security;
+
+ @AfterEach
+ void clearContext() {
+ SecurityContextHolder.clearContext();
+ }
+
+ @Test
+ void userPrincipalDelegatesToPortalCheck() {
+ User user = new User();
+ user.setId(5L);
+ authenticate(user);
+ when(accessService.canAccessPortal(user)).thenReturn(true);
+
+ assertThat(security.canUsePortal()).isTrue();
+ }
+
+ @Test
+ void deniedWithoutAuthentication() {
+ assertThat(security.canUsePortal()).isFalse();
+ }
+
+ @Test
+ void nonUserPrincipalWithoutBackingRowIsDenied() {
+ // Mirrors an anonymous SaaS session: principal is not a User and resolves to nothing.
+ authenticate("anonymousUser");
+
+ assertThat(security.canUsePortal()).isFalse();
+ }
+
+ private void authenticate(Object principal) {
+ SecurityContextHolder.getContext()
+ .setAuthentication(
+ new UsernamePasswordAuthenticationToken(
+ principal, null, java.util.List.of()));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/DefaultPrincipalResolverTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/DefaultPrincipalResolverTest.java
new file mode 100644
index 0000000000..94e99bdbc9
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/DefaultPrincipalResolverTest.java
@@ -0,0 +1,54 @@
+package stirling.software.proprietary.access.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.proprietary.access.model.PrincipalRef;
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.security.model.User;
+
+class DefaultPrincipalResolverTest {
+
+ private final DefaultPrincipalResolver resolver = new DefaultPrincipalResolver();
+
+ @Test
+ void userWithoutTeamProjectsUser() {
+ assertThat(resolver.principalsOf(user(5, null)))
+ .containsExactlyInAnyOrder(PrincipalRef.user(5L));
+ }
+
+ @Test
+ void userWithTeamProjectsUserAndTeam() {
+ assertThat(resolver.principalsOf(user(5, 7L)))
+ .containsExactlyInAnyOrder(PrincipalRef.user(5L), PrincipalRef.team(7L));
+ }
+
+ @Test
+ void nullUserProjectsNothing() {
+ assertThat(resolver.principalsOf(null)).isEmpty();
+ assertThat(resolver.principalTokens(null)).isEmpty();
+ }
+
+ @Test
+ void tokensUseTheCanonicalWireForm() {
+ assertThat(resolver.principalTokens(user(5, 7L)))
+ .containsExactlyInAnyOrder("user:5", "team:7");
+ }
+
+ @Test
+ void selfHostedAllowsDeploymentWideAccess() {
+ assertThat(resolver.allowsDeploymentWideAccess()).isTrue();
+ }
+
+ private User user(long id, Long teamId) {
+ User u = new User();
+ u.setId(id);
+ if (teamId != null) {
+ Team t = new Team();
+ t.setId(teamId);
+ u.setTeam(t);
+ }
+ return u;
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/MembershipTeamLeadLookupTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/MembershipTeamLeadLookupTest.java
new file mode 100644
index 0000000000..f485bcec52
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/MembershipTeamLeadLookupTest.java
@@ -0,0 +1,55 @@
+package stirling.software.proprietary.access.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
+
+@ExtendWith(MockitoExtension.class)
+class MembershipTeamLeadLookupTest {
+
+ @Mock private TeamMembershipRepository memberships;
+
+ @InjectMocks private MembershipTeamLeadLookup lookup;
+
+ @Test
+ void leaderMembershipMakesTeamLeader() {
+ when(memberships.existsByTeamIdAndUserIdAndRole(7L, 5L, TeamRole.LEADER)).thenReturn(true);
+ assertThat(lookup.isLeaderOfTeam(user(5), 7L)).isTrue();
+ }
+
+ @Test
+ void memberOnlyIsNotTeamLeader() {
+ when(memberships.existsByTeamIdAndUserIdAndRole(7L, 5L, TeamRole.LEADER)).thenReturn(false);
+ assertThat(lookup.isLeaderOfTeam(user(5), 7L)).isFalse();
+ }
+
+ @Test
+ void anyLeadershipDetectedAcrossTeams() {
+ when(memberships.existsByUserIdAndRole(5L, TeamRole.LEADER)).thenReturn(true);
+ assertThat(lookup.isAnyTeamLeader(user(5))).isTrue();
+ }
+
+ @Test
+ void nullInputsNeverQueryAndDeny() {
+ assertThat(lookup.isAnyTeamLeader(null)).isFalse();
+ assertThat(lookup.isLeaderOfTeam(null, 7L)).isFalse();
+ assertThat(lookup.isLeaderOfTeam(user(5), null)).isFalse();
+ verifyNoInteractions(memberships);
+ }
+
+ private User user(long id) {
+ User u = new User();
+ u.setId(id);
+ return u;
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/OwnershipServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/OwnershipServiceTest.java
index 3f70058d0b..f2d86e783d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/OwnershipServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/OwnershipServiceTest.java
@@ -3,6 +3,7 @@ package stirling.software.proprietary.access.service;
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.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.util.Optional;
@@ -150,6 +151,27 @@ class OwnershipServiceTest {
assertThat(ownership.canUse(TYPE, r, user(8))).isFalse(); // not a lead
}
+ @Test
+ void disabledResourceManageableOnlyByOwnerOrAdmin() {
+ TestResource r = new TestResource(1L);
+ r.setEnabled(false);
+ r.setOwnerUser(user(7));
+
+ assertThat(ownership.canManage(TYPE, r, user(7))).isTrue(); // owner
+ assertThat(ownership.canManage(TYPE, r, user(8))).isFalse(); // would-be MANAGE grantee
+ assertThat(ownership.canManage(TYPE, r, admin(2))).isTrue(); // admin
+ // Grants are bypassed entirely while disabled.
+ verifyNoInteractions(accessService);
+ }
+
+ @Test
+ void enabledResourceManageDelegatesToTheAcl() {
+ TestResource r = new TestResource(1L);
+ when(accessService.canManageResource(any(), any(), any(), any())).thenReturn(true);
+
+ assertThat(ownership.canManage(TYPE, r, user(7))).isTrue();
+ }
+
// ---- helpers ----
private void assertForbidden(org.assertj.core.api.ThrowableAssert.ThrowingCallable call) {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/ResourceAccessServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/ResourceAccessServiceTest.java
index 230c207eb0..baa6755493 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/ResourceAccessServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/ResourceAccessServiceTest.java
@@ -1,20 +1,22 @@
package stirling.software.proprietary.access.service;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.util.List;
+import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import stirling.software.proprietary.access.model.AccessPermission;
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
+import stirling.software.proprietary.access.model.PrincipalRef;
import stirling.software.proprietary.access.model.PrincipalType;
import stirling.software.proprietary.access.model.ResourceGrant;
import stirling.software.proprietary.access.model.ResourceType;
@@ -32,13 +34,20 @@ class ResourceAccessServiceTest {
@Mock private ResourceGrantRepository grantRepository;
@Mock private TeamLeadLookup teamLeadLookup;
- @InjectMocks private ResourceAccessService service;
+ private ResourceAccessService service;
@BeforeEach
- void setPortalDefault() throws Exception {
+ void setUp() throws Exception {
+ service = newService(new DefaultPrincipalResolver());
+ }
+
+ private ResourceAccessService newService(PrincipalResolver resolver) throws Exception {
+ ResourceAccessService s =
+ new ResourceAccessService(grantRepository, teamLeadLookup, resolver);
Field f = ResourceAccessService.class.getDeclaredField("portalDefaultPolicy");
f.setAccessible(true);
- f.set(service, DefaultAccessPolicy.ADMINS_AND_TEAM_LEADS);
+ f.set(s, DefaultAccessPolicy.ADMINS_AND_TEAM_LEADS);
+ return s;
}
// ---- owner / admin short-circuits ----
@@ -55,15 +64,56 @@ class ResourceAccessServiceTest {
void ownerMayUseEvenWithExplicitOnly() {
assertThat(
service.canUseResource(
- TYPE, RID, 5L, DefaultAccessPolicy.EXPLICIT_ONLY, user(5)))
+ TYPE,
+ RID,
+ PrincipalRef.user(5L),
+ DefaultAccessPolicy.EXPLICIT_ONLY,
+ user(5)))
.isTrue();
}
@Test
void nullUserIsAlwaysDenied() {
- assertThat(service.canUseResource(TYPE, RID, 5L, DefaultAccessPolicy.ORG_ALL, null))
+ assertThat(
+ service.canUseResource(
+ TYPE,
+ RID,
+ PrincipalRef.user(5L),
+ DefaultAccessPolicy.ORG_ALL,
+ null))
+ .isFalse();
+ assertThat(service.canManageResource(TYPE, RID, PrincipalRef.user(5L), null)).isFalse();
+ }
+
+ // ---- owner refs ----
+
+ @Test
+ void teamOwnerRefAllowsLeaderOfThatTeam() {
+ User leader = userInTeam(5, 7);
+ when(teamLeadLookup.isLeaderOfTeam(leader, 7L)).thenReturn(true);
+ assertThat(
+ service.canUseResource(
+ TYPE,
+ RID,
+ PrincipalRef.team(7L),
+ DefaultAccessPolicy.EXPLICIT_ONLY,
+ leader))
+ .isTrue();
+ assertThat(service.canManageResource(TYPE, RID, PrincipalRef.team(7L), leader)).isTrue();
+ }
+
+ @Test
+ void teamOwnerRefDeniesPlainTeamMember() {
+ stubGrants();
+ User member = userInTeam(5, 7);
+ assertThat(
+ service.canUseResource(
+ TYPE,
+ RID,
+ PrincipalRef.team(7L),
+ DefaultAccessPolicy.EXPLICIT_ONLY,
+ member))
.isFalse();
- assertThat(service.canManageResource(TYPE, RID, 5L, null)).isFalse();
}
// ---- explicit grants ----
@@ -124,15 +174,60 @@ class ResourceAccessServiceTest {
assertThat(service.canManageResource(TYPE, RID, null, user(5))).isTrue();
}
+ // ---- upsert semantics ----
+
+ @Test
+ void grantOverwritesPermissionEvenDowngrading() {
+ // Upsert key is (type, resourceId, principalType, principalId); permission is overwritten.
+ ResourceGrant existing = grant(PrincipalType.USER, 5L, AccessPermission.MANAGE);
+ stubGrants(existing);
+ when(grantRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
+
+ ResourceGrant saved =
+ service.grant(TYPE, RID, PrincipalType.USER, 5L, AccessPermission.USE, null);
+
+ assertThat(saved).isSameAs(existing);
+ assertThat(saved.getPermission()).isEqualTo(AccessPermission.USE);
+ }
+
+ // ---- granted resource ids ----
+
+ @Test
+ void grantedResourceIdsCollectsAcrossAllPrincipals() {
+ when(grantRepository.findByResourceTypeAndPrincipalTypeAndPrincipalId(
+ TYPE, PrincipalType.USER, 5L))
+ .thenReturn(List.of(grantOn("a")));
+ when(grantRepository.findByResourceTypeAndPrincipalTypeAndPrincipalId(
+ TYPE, PrincipalType.TEAM, 7L))
+ .thenReturn(List.of(grantOn("b")));
+
+ assertThat(service.grantedResourceIds(TYPE, userInTeam(5, 7)))
+ .containsExactlyInAnyOrder("a", "b");
+ }
+
// ---- default policies ----
@Test
- void orgAllDefaultAllowsAnyUser() {
+ void orgAllDefaultAllowsAnyUserWhenDeploymentWide() {
+ // Self-hosted resolver allows deployment-wide access, so ORG_ALL admits anyone.
stubGrants();
assertThat(service.canUseResource(TYPE, RID, null, DefaultAccessPolicy.ORG_ALL, user(5)))
.isTrue();
}
+ @Test
+ void orgAllDefaultDeniedWhenNotDeploymentWide() throws Exception {
+ // Mirrors the saas resolver (USER/TEAM only, no deployment-wide access): ORG_ALL must not
+ // leak a resource to a tenant's users, so an ungranted user is denied.
+ ResourceAccessService tenantScoped =
+ newService(u -> u == null ? Set.of() : Set.of(PrincipalRef.user(u.getId())));
+ stubGrants();
+ assertThat(
+ tenantScoped.canUseResource(
+ TYPE, RID, null, DefaultAccessPolicy.ORG_ALL, user(5)))
+ .isFalse();
+ }
+
@Test
void explicitOnlyDefaultDeniesUngrantedUser() {
stubGrants();
@@ -194,6 +289,12 @@ class ResourceAccessServiceTest {
return g;
}
+ private ResourceGrant grantOn(String resourceId) {
+ ResourceGrant g = grant(PrincipalType.USER, 5L, AccessPermission.USE);
+ g.setResourceId(resourceId);
+ return g;
+ }
+
private User user(long id) {
User u = new User();
u.setId(id);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.java
index ea5597cb12..4f76b06b5c 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.java
@@ -49,6 +49,23 @@ class SecretMaskerTest {
assertThat(merged.get("secretKey")).isEqualTo("NEW");
}
+ @Test
+ void mergeDropsKeysAbsentFromIncoming() {
+ // PUT/replace semantics: a key removed in the edit is removed from storage.
+ Map<String, Object> stored = new java.util.LinkedHashMap<>();
+ stored.put("bucket", "b");
+ stored.put("endpoint", "https://old");
+ stored.put("secretKey", "REAL");
+ Map<String, Object> incoming = new java.util.LinkedHashMap<>();
+ incoming.put("bucket", "b");
+ incoming.put("secretKey", SecretMasker.MASK);
+
+ Map<String, Object> merged = masker.merge(stored, incoming);
+
+ assertThat(merged).doesNotContainKey("endpoint");
+ assertThat(merged.get("secretKey")).isEqualTo("REAL"); // masked secret retained
+ }
+
@Test
void sanitizeDropsBlankSecretsOnCreate() {
Map<String, Object> incoming = new LinkedHashMap<>();
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.java
index 3ddd9e9a1e..585edc6e66 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerMoreTest.java
@@ -24,6 +24,7 @@ import org.springframework.security.oauth2.core.user.OAuth2User;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
+import stirling.software.proprietary.access.service.ResourceAccessService;
import stirling.software.proprietary.config.AuditConfigurationProperties;
import stirling.software.proprietary.controller.api.ProprietaryUIDataController.AccountData;
import stirling.software.proprietary.controller.api.ProprietaryUIDataController.AdminSettingsData;
@@ -39,6 +40,7 @@ import stirling.software.proprietary.security.database.repository.SessionReposit
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.DatabaseServiceInterface;
@@ -57,12 +59,14 @@ class ProprietaryUIDataControllerMoreTest {
@Mock private SessionPersistentRegistry sessionPersistentRegistry;
@Mock private UserRepository userRepository;
@Mock private TeamRepository teamRepository;
+ @Mock private TeamMembershipRepository teamMembershipRepository;
@Mock private SessionRepository sessionRepository;
@Mock private DatabaseServiceInterface databaseService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private PersistentAuditEventRepository auditRepository;
@Mock private MfaService mfaService;
@Mock private LoginAttemptService loginAttemptService;
+ @Mock private ResourceAccessService resourceAccessService;
private ApplicationProperties applicationProperties;
private AuditConfigurationProperties auditConfig;
@@ -87,6 +91,7 @@ class ProprietaryUIDataControllerMoreTest {
sessionPersistentRegistry,
userRepository,
teamRepository,
+ teamMembershipRepository,
sessionRepository,
databaseService,
objectMapper,
@@ -94,7 +99,8 @@ class ProprietaryUIDataControllerMoreTest {
licenseSettingsService,
auditRepository,
mfaService,
- loginAttemptService);
+ loginAttemptService,
+ resourceAccessService);
}
private static User normalUser(Long id, String username) {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerTest.java
index b8552e274c..0b01c9bcf5 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ProprietaryUIDataControllerTest.java
@@ -18,6 +18,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
+import stirling.software.proprietary.access.service.ResourceAccessService;
import stirling.software.proprietary.config.AuditConfigurationProperties;
import stirling.software.proprietary.controller.api.ProprietaryUIDataController.AccountData;
import stirling.software.proprietary.controller.api.ProprietaryUIDataController.DatabaseData;
@@ -27,6 +28,7 @@ import stirling.software.proprietary.security.database.repository.SessionReposit
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.DatabaseService;
import stirling.software.proprietary.security.service.LoginAttemptService;
@@ -43,12 +45,14 @@ class ProprietaryUIDataControllerTest {
@Mock private SessionPersistentRegistry sessionPersistentRegistry;
@Mock private UserRepository userRepository;
@Mock private TeamRepository teamRepository;
+ @Mock private TeamMembershipRepository teamMembershipRepository;
@Mock private SessionRepository sessionRepository;
@Mock private DatabaseService databaseService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private PersistentAuditEventRepository auditRepository;
@Mock private MfaService mfaService;
@Mock private LoginAttemptService loginAttemptService;
+ @Mock private ResourceAccessService resourceAccessService;
private ApplicationProperties applicationProperties;
private AuditConfigurationProperties auditConfig;
@@ -75,6 +79,7 @@ class ProprietaryUIDataControllerTest {
sessionPersistentRegistry,
userRepository,
teamRepository,
+ teamMembershipRepository,
sessionRepository,
databaseService,
objectMapper,
@@ -82,7 +87,8 @@ class ProprietaryUIDataControllerTest {
licenseSettingsService,
auditRepository,
mfaService,
- loginAttemptService);
+ loginAttemptService,
+ resourceAccessService);
}
@Test
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.java
index 9f3b2d84af..8e0ef200bb 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.java
@@ -49,6 +49,9 @@ class IntegrationConfigServiceTest {
@Mock private OwnershipService ownership;
@Mock private SecretMasker secretMasker;
+ @Mock
+ private stirling.software.proprietary.access.repository.ResourceGrantRepository grantRepository;
+
@InjectMocks private IntegrationConfigService service;
@Test
@@ -58,9 +61,9 @@ class IntegrationConfigServiceTest {
User user = user(7);
IntegrationConfig created =
- service.create(request(IntegrationType.S3, OwnerScope.USER, null), user);
+ service.create(request(IntegrationType.API, OwnerScope.USER, null), user);
- assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.S3);
+ assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.API);
assertThat(created.getName()).isEqualTo("name");
verify(ownership)
.assignOwnership(eq(created), eq(OwnerScope.USER), isNull(), eq(user), any());
@@ -156,6 +159,60 @@ class IntegrationConfigServiceTest {
.isEqualTo(HttpStatus.FORBIDDEN);
}
+ // ---- S3 type policy ----
+
+ @Test
+ void s3PersonalCreateForbiddenForRegularUser() {
+ User user = user(7);
+ when(ownership.isAdmin(user)).thenReturn(false);
+
+ assertThatThrownBy(
+ () ->
+ service.create(
+ request(IntegrationType.S3, OwnerScope.USER, null), user))
+ .isInstanceOf(ResponseStatusException.class)
+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())
+ .isEqualTo(HttpStatus.FORBIDDEN);
+ }
+
+ @Test
+ void s3PersonalCreateAllowedForAdmin() {
+ when(secretMasker.sanitize(any())).thenReturn(Map.of("bucket", "b"));
+ when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
+ User admin = user(1);
+ when(ownership.isAdmin(admin)).thenReturn(true);
+
+ IntegrationConfig created =
+ service.create(request(IntegrationType.S3, OwnerScope.USER, null), admin);
+
+ assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.S3);
+ }
+
+ @Test
+ void s3TeamScopeCreateDelegatesLeadershipToOwnership() {
+ // TEAM scope skips the personal-S3 gate; assignOwnership enforces admin/team-owner.
+ when(secretMasker.sanitize(any())).thenReturn(Map.of("bucket", "b"));
+ when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
+ User leader = user(7);
+
+ IntegrationConfig created =
+ service.create(request(IntegrationType.S3, OwnerScope.TEAM, 3L), leader);
+
+ verify(ownership)
+ .assignOwnership(eq(created), eq(OwnerScope.TEAM), eq(3L), eq(leader), any());
+ }
+
+ @Test
+ void mcpPersonalCreateAllowedForRegularUser() {
+ when(secretMasker.sanitize(any())).thenReturn(Map.of("token", "t"));
+ when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
+
+ IntegrationConfig created =
+ service.create(request(IntegrationType.MCP, OwnerScope.USER, null), user(7));
+
+ assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.MCP);
+ }
+
// ---- helpers ----
private IntegrationConfig config(long id) {
diff --git a/app/saas/src/test/java/stirling/software/saas/model/TeamMembershipTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/model/TeamMembershipTest.java
similarity index 98%
rename from app/saas/src/test/java/stirling/software/saas/model/TeamMembershipTest.java
rename to app/proprietary/src/test/java/stirling/software/proprietary/model/TeamMembershipTest.java
index a94e8b9373..653fcd0ef1 100644
--- a/app/saas/src/test/java/stirling/software/saas/model/TeamMembershipTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/model/TeamMembershipTest.java
@@ -1,4 +1,4 @@
-package stirling.software.saas.model;
+package stirling.software.proprietary.model;
import static org.assertj.core.api.Assertions.assertThat;
@@ -9,7 +9,6 @@ import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import stirling.software.common.model.enumeration.TeamRole;
-import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.User;
/** Constructor, accessor, equals/hashCode/toString, and role-helper tests for TeamMembership. */
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.java
index adf9486094..3e4c75f645 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/InitialSecuritySetupTest.java
@@ -26,6 +26,7 @@ import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.DatabaseServiceInterface;
import stirling.software.proprietary.security.service.SaveUserRequest;
+import stirling.software.proprietary.security.service.TeamMembershipService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@@ -38,6 +39,7 @@ class InitialSecuritySetupTest {
@Mock private DatabaseServiceInterface databaseService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private Environment environment;
+ @Mock private TeamMembershipService teamMembershipService;
private ApplicationProperties applicationProperties;
private InitialSecuritySetup initialSecuritySetup;
@@ -63,7 +65,8 @@ class InitialSecuritySetupTest {
applicationProperties,
databaseService,
licenseSettingsService,
- environment);
+ environment,
+ teamMembershipService);
}
@Test
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerLoginTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerLoginTest.java
index 6a27b4d578..6586fc11b6 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerLoginTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerLoginTest.java
@@ -29,6 +29,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
import stirling.software.proprietary.access.service.ResourceAccessService;
+import stirling.software.proprietary.access.service.TeamLeadLookup;
import stirling.software.proprietary.security.model.AuthenticationType;
import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.User;
@@ -60,6 +61,7 @@ class AuthControllerLoginTest {
@Mock private TotpService totpService;
@Mock private RefreshRateLimitService refreshRateLimitService;
@Mock private ResourceAccessService resourceAccessService;
+ @Mock private TeamLeadLookup teamLeadLookup;
@BeforeEach
void setUp() {
@@ -83,7 +85,8 @@ class AuthControllerLoginTest {
securityProperties,
applicationProperties,
new stirling.software.proprietary.service.AiUserDataService(null),
- resourceAccessService);
+ resourceAccessService,
+ teamLeadLookup);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java
index 611929b5b9..aaf931f597 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AuthControllerMoreTest.java
@@ -29,6 +29,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
import stirling.software.proprietary.access.service.ResourceAccessService;
+import stirling.software.proprietary.access.service.TeamLeadLookup;
import stirling.software.proprietary.security.model.AuthenticationType;
import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.User;
@@ -61,6 +62,7 @@ class AuthControllerMoreTest {
@Mock private TotpService totpService;
@Mock private RefreshRateLimitService refreshRateLimitService;
@Mock private ResourceAccessService resourceAccessService;
+ @Mock private TeamLeadLookup teamLeadLookup;
@BeforeEach
void setUp() {
@@ -84,7 +86,8 @@ class AuthControllerMoreTest {
securityProperties,
applicationProperties,
new stirling.software.proprietary.service.AiUserDataService(null),
- resourceAccessService);
+ resourceAccessService,
+ teamLeadLookup);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java
index 75c23b4630..ac2219efa3 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerMoreTest.java
@@ -30,6 +30,7 @@ import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.LoginAttemptService;
+import stirling.software.proprietary.security.service.TeamMembershipService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -46,6 +47,7 @@ class UserControllerMoreTest {
@Mock private EmailService emailService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private LoginAttemptService loginAttemptService;
+ @Mock private TeamMembershipService teamMembershipService;
private ApplicationProperties applicationProperties;
private MockMvc mockMvc;
@@ -64,7 +66,8 @@ class UserControllerMoreTest {
userRepository,
Optional.of(emailService),
licenseSettingsService,
- loginAttemptService);
+ loginAttemptService,
+ teamMembershipService);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java
index 7bcc0da9f4..b3a1e8de93 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/UserControllerTest.java
@@ -33,6 +33,7 @@ import stirling.software.proprietary.security.model.api.user.UsernameAndPass;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.LoginAttemptService;
+import stirling.software.proprietary.security.service.TeamMembershipService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -53,6 +54,7 @@ class UserControllerTest {
@Mock private EmailService emailService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private LoginAttemptService loginAttemptService;
+ @Mock private TeamMembershipService teamMembershipService;
private ApplicationProperties applicationProperties;
private MockMvc mockMvc;
@@ -72,7 +74,8 @@ class UserControllerTest {
userRepository,
Optional.of(emailService),
licenseSettingsService,
- loginAttemptService);
+ loginAttemptService,
+ teamMembershipService);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/TeamMembershipServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/TeamMembershipServiceTest.java
new file mode 100644
index 0000000000..68bd2d1727
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/TeamMembershipServiceTest.java
@@ -0,0 +1,159 @@
+package stirling.software.proprietary.security.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
+
+@ExtendWith(MockitoExtension.class)
+class TeamMembershipServiceTest {
+
+ @Mock private TeamMembershipRepository membershipRepository;
+ @Mock private org.springframework.core.env.Environment environment;
+
+ @InjectMocks private TeamMembershipService service;
+
+ @org.junit.jupiter.api.BeforeEach
+ void notSaas() {
+ org.mockito.Mockito.lenient()
+ .when(environment.getActiveProfiles())
+ .thenReturn(new String[] {});
+ }
+
+ @Test
+ void syncCreatesMemberRowForUsersTeam() {
+ User user = userInTeam(5, 7);
+ when(membershipRepository.findByUserId(5L)).thenReturn(List.of());
+
+ service.syncMembership(user);
+
+ ArgumentCaptor<TeamMembership> captor = ArgumentCaptor.forClass(TeamMembership.class);
+ verify(membershipRepository).save(captor.capture());
+ assertThat(captor.getValue().getTeam().getId()).isEqualTo(7L);
+ assertThat(captor.getValue().getRole()).isEqualTo(TeamRole.MEMBER);
+ assertThat(captor.getValue().getInvitedAt()).isNotNull();
+ }
+
+ @Test
+ void syncMovesRowsWhenUserChangedTeam() {
+ User user = userInTeam(5, 8);
+ TeamMembership oldRow = row(7, user, TeamRole.LEADER);
+ when(membershipRepository.findByUserId(5L)).thenReturn(List.of(oldRow));
+
+ service.syncMembership(user);
+
+ verify(membershipRepository).delete(oldRow);
+ ArgumentCaptor<TeamMembership> captor = ArgumentCaptor.forClass(TeamMembership.class);
+ verify(membershipRepository).save(captor.capture());
+ assertThat(captor.getValue().getTeam().getId()).isEqualTo(8L);
+ assertThat(captor.getValue().getRole()).isEqualTo(TeamRole.MEMBER);
+ }
+
+ @Test
+ void syncPreservesLeaderRoleOnSameTeam() {
+ User user = userInTeam(5, 7);
+ TeamMembership existing = row(7, user, TeamRole.LEADER);
+ when(membershipRepository.findByUserId(5L)).thenReturn(List.of(existing));
+
+ service.syncMembership(user);
+
+ verify(membershipRepository, never()).delete(any());
+ verify(membershipRepository, never()).save(any());
+ }
+
+ @Test
+ void syncRemovesAllRowsWhenUserHasNoTeam() {
+ User user = new User();
+ user.setId(5L);
+ TeamMembership stale = row(7, user, TeamRole.MEMBER);
+ when(membershipRepository.findByUserId(5L)).thenReturn(List.of(stale));
+
+ service.syncMembership(user);
+
+ verify(membershipRepository).delete(stale);
+ verify(membershipRepository, never()).save(any());
+ }
+
+ @Test
+ void setOwnerPromotesExistingRow() {
+ User user = userInTeam(5, 7);
+ TeamMembership existing = row(7, user, TeamRole.MEMBER);
+ when(membershipRepository.findByTeamIdAndUserId(7L, 5L)).thenReturn(Optional.of(existing));
+
+ service.setOwner(user.getTeam(), user);
+
+ assertThat(existing.getRole()).isEqualTo(TeamRole.LEADER);
+ verify(membershipRepository).save(existing);
+ }
+
+ @Test
+ void setOwnerCreatesLeaderRowWhenMissing() {
+ User user = userInTeam(5, 7);
+ when(membershipRepository.findByTeamIdAndUserId(7L, 5L)).thenReturn(Optional.empty());
+
+ service.setOwner(user.getTeam(), user);
+
+ ArgumentCaptor<TeamMembership> captor = ArgumentCaptor.forClass(TeamMembership.class);
+ verify(membershipRepository).save(captor.capture());
+ assertThat(captor.getValue().getRole()).isEqualTo(TeamRole.LEADER);
+ }
+
+ @Test
+ void removeOwnerDemotesToMemberAndKeepsRow() {
+ User user = userInTeam(5, 7);
+ TeamMembership existing = row(7, user, TeamRole.LEADER);
+ when(membershipRepository.findByTeamIdAndUserId(7L, 5L)).thenReturn(Optional.of(existing));
+
+ service.removeOwner(user.getTeam(), user);
+
+ assertThat(existing.getRole()).isEqualTo(TeamRole.MEMBER);
+ verify(membershipRepository).save(existing);
+ verify(membershipRepository, never()).delete(any());
+ }
+
+ @Test
+ void deleteAllForUserDropsRowsAndInvitationRefs() {
+ User user = userInTeam(5, 7);
+
+ service.deleteAllForUser(user);
+
+ verify(membershipRepository).deleteByUserId(5L);
+ verify(membershipRepository).clearInvitedBy(user);
+ }
+
+ private User userInTeam(long userId, long teamId) {
+ User u = new User();
+ u.setId(userId);
+ Team t = new Team();
+ t.setId(teamId);
+ u.setTeam(t);
+ return u;
+ }
+
+ private TeamMembership row(long teamId, User user, TeamRole role) {
+ Team t = new Team();
+ t.setId(teamId);
+ TeamMembership m = new TeamMembership();
+ m.setTeam(t);
+ m.setUser(user);
+ m.setRole(role);
+ return m;
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java
index cfb0f2e885..bc516172a6 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java
@@ -71,6 +71,12 @@ class UserServiceMoreTest {
@Mock private FileShareRepository fileShareRepository;
@Mock private FileShareAccessRepository fileShareAccessRepository;
+ @Mock
+ private stirling.software.proprietary.integration.repository.IntegrationConfigRepository
+ integrationConfigRepository;
+
+ @Mock private TeamMembershipService teamMembershipService;
+
@InjectMocks private UserService userService;
@AfterEach
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
index 713fd4b9c3..95ec72d962 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
@@ -24,6 +24,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.exception.UnsupportedProviderException;
+import stirling.software.proprietary.access.repository.ResourceGrantRepository;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.database.repository.AuthorityRepository;
import stirling.software.proprietary.security.database.repository.PersistentLoginRepository;
@@ -63,6 +64,13 @@ class UserServiceTest {
@Mock private StorageCleanupEntryRepository storageCleanupEntryRepository;
@Mock private FileShareRepository fileShareRepository;
@Mock private FileShareAccessRepository fileShareAccessRepository;
+ @Mock private ResourceGrantRepository resourceGrantRepository;
+
+ @Mock
+ private stirling.software.proprietary.integration.repository.IntegrationConfigRepository
+ integrationConfigRepository;
+
+ @Mock private TeamMembershipService teamMembershipService;
@Spy @InjectMocks private UserService userService;
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
index 91974a6d04..490b3d5db1 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
@@ -20,10 +20,10 @@ import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
-import stirling.software.saas.repository.TeamMembershipRepository;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
diff --git a/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java b/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java
index 6253d64651..9346e18b4b 100644
--- a/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java
+++ b/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java
@@ -20,15 +20,15 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.TeamApi;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.saas.model.TeamInvitation;
-import stirling.software.saas.model.TeamMembership;
import stirling.software.saas.repository.TeamInvitationRepository;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.security.TeamSecurityExpressions;
import stirling.software.saas.service.SaasTeamExtensionService;
import stirling.software.saas.service.SaasTeamService;
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygInvoicesController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygInvoicesController.java
index 6b8bb2c883..80c20902ce 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygInvoicesController.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygInvoicesController.java
@@ -20,13 +20,13 @@ import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.stripe.StripeInvoiceDao;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygPaymentMethodController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygPaymentMethodController.java
index 724d6715d3..89ab18230f 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygPaymentMethodController.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygPaymentMethodController.java
@@ -18,13 +18,13 @@ import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.stripe.StripePaymentMethodDao;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java
index b79d57117e..90616bea55 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java
@@ -32,9 +32,10 @@ import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.payg.api.WalletSnapshotResponse.ActivityRow;
import stirling.software.saas.payg.api.WalletSnapshotResponse.CategoryBreakdown;
import stirling.software.saas.payg.api.WalletSnapshotResponse.MemberRow;
@@ -51,7 +52,6 @@ import stirling.software.saas.payg.repository.WalletLedgerRepository;
import stirling.software.saas.payg.repository.WalletPolicyRepository;
import stirling.software.saas.payg.wallet.WalletLedgerEntry;
import stirling.software.saas.payg.wallet.WalletPolicy;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java b/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java
index f92267da33..57f7e6a3a3 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java
@@ -25,16 +25,16 @@ import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.enumeration.TeamRole;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.procurement.config.ProcurementConfigurationProperties;
import stirling.software.saas.procurement.model.ProcurementDeal;
import stirling.software.saas.procurement.model.ProcurementQuote;
import stirling.software.saas.procurement.pricing.QuoteConfig;
import stirling.software.saas.procurement.pricing.QuoteLineItem;
import stirling.software.saas.procurement.service.ProcurementService;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java
index 57f530cc9a..225e0327e8 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java
@@ -17,7 +17,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.enumeration.TeamRole;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.procurement.config.ProcurementConfigurationProperties;
import stirling.software.saas.procurement.license.EnterpriseLicenseService;
import stirling.software.saas.procurement.license.LicenseEntitlements;
@@ -28,7 +29,6 @@ import stirling.software.saas.procurement.pricing.QuoteBreakdown;
import stirling.software.saas.procurement.pricing.QuoteConfig;
import stirling.software.saas.procurement.repository.ProcurementDealRepository;
import stirling.software.saas.procurement.repository.ProcurementQuoteRepository;
-import stirling.software.saas.repository.TeamMembershipRepository;
/**
* Orchestrates a linked team's procurement journey: start a (mock-licensed) trial, build a
diff --git a/app/saas/src/main/java/stirling/software/saas/security/SaasPortalAuditScopeResolver.java b/app/saas/src/main/java/stirling/software/saas/security/SaasPortalAuditScopeResolver.java
index 00c7c42757..0d0df35688 100644
--- a/app/saas/src/main/java/stirling/software/saas/security/SaasPortalAuditScopeResolver.java
+++ b/app/saas/src/main/java/stirling/software/saas/security/SaasPortalAuditScopeResolver.java
@@ -11,7 +11,7 @@ import lombok.RequiredArgsConstructor;
import stirling.software.proprietary.audit.PortalAuditScope;
import stirling.software.proprietary.audit.PortalAuditScopeResolver;
-import stirling.software.saas.repository.TeamMembershipRepository;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
/** SaaS audit visibility: admins see the server; team LEADERs see their team (by member email). */
@Component
diff --git a/app/saas/src/main/java/stirling/software/saas/security/SaasPrincipalResolver.java b/app/saas/src/main/java/stirling/software/saas/security/SaasPrincipalResolver.java
new file mode 100644
index 0000000000..d064c7b59d
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/security/SaasPrincipalResolver.java
@@ -0,0 +1,30 @@
+package stirling.software.saas.security;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Component;
+
+import stirling.software.proprietary.access.model.PrincipalRef;
+import stirling.software.proprietary.access.service.PrincipalResolver;
+import stirling.software.proprietary.security.model.User;
+
+/** USER/TEAM only: SaaS has no org concept, so an ORG grant must never match across tenants. */
+@Component
+@Profile("saas")
+public class SaasPrincipalResolver implements PrincipalResolver {
+
+ @Override
+ public Set<PrincipalRef> principalsOf(User user) {
+ if (user == null) {
+ return Set.of();
+ }
+ Set<PrincipalRef> principals = new HashSet<>();
+ principals.add(PrincipalRef.user(user.getId()));
+ if (user.getTeam() != null) {
+ principals.add(PrincipalRef.team(user.getTeam().getId()));
+ }
+ return principals;
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java b/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java
index 3dfdf541cc..d93eacbafa 100644
--- a/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java
+++ b/app/saas/src/main/java/stirling/software/saas/security/TeamSecurityExpressions.java
@@ -12,8 +12,8 @@ import lombok.RequiredArgsConstructor;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.security.service.UserService;
-import stirling.software.saas.repository.TeamMembershipRepository;
/**
* Security expressions for team-based authorization in saas mode. Wired into
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 6d3e42e806..94996ca01c 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
@@ -16,17 +16,17 @@ import stirling.software.common.model.enumeration.InvitationStatus;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
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.LinkedInstanceRepository;
import stirling.software.saas.billing.repository.BillingSubscriptionRepository;
import stirling.software.saas.config.SupabaseConfigurationProperties;
import stirling.software.saas.model.TeamInvitation;
-import stirling.software.saas.model.TeamMembership;
import stirling.software.saas.repository.SaasTeamExtensionsRepository;
import stirling.software.saas.repository.TeamInvitationRepository;
-import stirling.software.saas.repository.TeamMembershipRepository;
/** SaaS-only team management: invitations, personal teams, seat caps, paid-subscription gating. */
@Service
@@ -48,6 +48,17 @@ public class SaasTeamService {
private final SaasTeamExtensionsRepository saasTeamExtensionsRepository;
private final LinkedInstanceRepository linkedInstanceRepository;
private final stirling.software.proprietary.security.service.UserService userService;
+ private final stirling.software.proprietary.access.repository.ResourceGrantRepository
+ resourceGrantRepository;
+ private final stirling.software.proprietary.integration.repository.IntegrationConfigRepository
+ integrationConfigRepository;
+
+ // Team-owned integration configs + team grants FK the teams row; purge before deleting a team.
+ private void purgeTeamOwnedResources(Long teamId) {
+ integrationConfigRepository.deleteByOwnerTeam_Id(teamId);
+ resourceGrantRepository.deleteByPrincipalTypeAndPrincipalId(
+ stirling.software.proprietary.access.model.PrincipalType.TEAM, teamId);
+ }
public static final String DEFAULT_TEAM_NAME = "Default";
public static final String INTERNAL_TEAM_NAME = "Internal";
@@ -347,6 +358,7 @@ public class SaasTeamService {
"Deleting empty personal team {} after user {} joined another team",
teamToDelete.getId(),
acceptingUser.getUsername());
+ purgeTeamOwnedResources(teamToDelete.getId());
teamRepository.delete(teamToDelete);
}
@@ -437,6 +449,7 @@ public class SaasTeamService {
if (!saasTeamExtensionService.isPersonal(team)
&& membershipRepository.countByTeamId(teamId) == 0) {
log.info("Deleting empty non-personal team {} after last member removed", teamId);
+ purgeTeamOwnedResources(team.getId());
teamRepository.delete(team);
}
@@ -551,6 +564,7 @@ public class SaasTeamService {
if (!saasTeamExtensionService.isPersonal(team)
&& membershipRepository.countByTeamId(teamId) == 0) {
log.info("Deleting empty non-personal team {} after last member left", teamId);
+ purgeTeamOwnedResources(team.getId());
teamRepository.delete(team);
}
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java
index 0de790cac0..e12888edb3 100644
--- a/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/AccountLinkControllerTest.java
@@ -19,12 +19,12 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.accountlink.AccountLinkController.RegisterRequest;
import stirling.software.saas.accountlink.AccountLinkController.RegisterResponse;
-import stirling.software.saas.model.TeamMembership;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
diff --git a/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java b/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java
index ea8721a4c3..4dd8a9670d 100644
--- a/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java
@@ -36,8 +36,10 @@ import stirling.software.common.model.enumeration.InvitationStatus;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
@@ -45,9 +47,7 @@ import stirling.software.saas.controller.SaasTeamController.InviteUserRequest;
import stirling.software.saas.controller.SaasTeamController.RenameTeamRequest;
import stirling.software.saas.controller.SaasTeamController.UpdateSeatsRequest;
import stirling.software.saas.model.TeamInvitation;
-import stirling.software.saas.model.TeamMembership;
import stirling.software.saas.repository.TeamInvitationRepository;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.security.TeamSecurityExpressions;
import stirling.software.saas.service.SaasTeamExtensionService;
import stirling.software.saas.service.SaasTeamService;
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygInvoicesControllerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygInvoicesControllerTest.java
index 9266b02336..dc29ceb22d 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygInvoicesControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygInvoicesControllerTest.java
@@ -23,14 +23,14 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.payg.api.PaygInvoicesController.InvoiceResponse;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.stripe.StripeInvoiceDao;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygPaymentMethodControllerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygPaymentMethodControllerTest.java
index c4c0780b86..b7b7561a88 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygPaymentMethodControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygPaymentMethodControllerTest.java
@@ -24,15 +24,15 @@ import org.springframework.security.oauth2.jwt.Jwt;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.payg.api.PaygPaymentMethodController.PaymentMethodResponse;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.stripe.StripePaymentMethodDao;
import stirling.software.saas.payg.stripe.StripePaymentMethodDao.CardSummary;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.security.EnhancedJwtAuthenticationToken;
/**
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java
index 6cc97d916b..0e02c0ce50 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java
@@ -31,9 +31,10 @@ import org.springframework.security.oauth2.jwt.Jwt;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
-import stirling.software.saas.model.TeamMembership;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.payg.api.PaygWalletController.UpdateCapRequest;
import stirling.software.saas.payg.api.WalletSnapshotResponse.MemberRow;
import stirling.software.saas.payg.billing.TeamBillingContext;
@@ -50,7 +51,6 @@ import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.repository.WalletLedgerRepository;
import stirling.software.saas.payg.repository.WalletPolicyRepository;
import stirling.software.saas.payg.wallet.WalletPolicy;
-import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.security.EnhancedJwtAuthenticationToken;
/**
diff --git a/app/saas/src/test/java/stirling/software/saas/security/SaasPrincipalResolverTest.java b/app/saas/src/test/java/stirling/software/saas/security/SaasPrincipalResolverTest.java
new file mode 100644
index 0000000000..20acc83e5b
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/security/SaasPrincipalResolverTest.java
@@ -0,0 +1,39 @@
+package stirling.software.saas.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.proprietary.access.model.PrincipalRef;
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.security.model.User;
+
+class SaasPrincipalResolverTest {
+
+ private final SaasPrincipalResolver resolver = new SaasPrincipalResolver();
+
+ @Test
+ void projectsUserAndTeamOnlyNeverOrg() {
+ User u = new User();
+ u.setId(5L);
+ Team t = new Team();
+ t.setId(7L);
+ u.setTeam(t);
+
+ assertThat(resolver.principalsOf(u))
+ .containsExactlyInAnyOrder(PrincipalRef.user(5L), PrincipalRef.team(7L));
+ }
+
+ @Test
+ void userWithoutTeamProjectsUserOnly() {
+ User u = new User();
+ u.setId(5L);
+
+ assertThat(resolver.principalsOf(u)).containsExactly(PrincipalRef.user(5L));
+ }
+
+ @Test
+ void nullUserProjectsNothing() {
+ assertThat(resolver.principalsOf(null)).isEmpty();
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsMoreTest.java b/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsMoreTest.java
index 580623c878..364db2855d 100644
--- a/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsMoreTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsMoreTest.java
@@ -25,10 +25,10 @@ import org.springframework.security.oauth2.jwt.Jwt;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+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.service.UserService;
-import stirling.software.saas.model.TeamMembership;
-import stirling.software.saas.repository.TeamMembershipRepository;
/**
* Additional branch coverage for {@link TeamSecurityExpressions}: the JWT resolution path, the
diff --git a/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsTest.java b/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsTest.java
index 23226e4467..c698daccca 100644
--- a/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/security/TeamSecurityExpressionsTest.java
@@ -20,10 +20,10 @@ import org.springframework.security.core.context.SecurityContextHolder;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+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.service.UserService;
-import stirling.software.saas.model.TeamMembership;
-import stirling.software.saas.repository.TeamMembershipRepository;
/**
* {@link TeamSecurityExpressions#isCurrentUserTeamLeader()} — used to gate policy editing on SaaS.
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 ac2a4cecba..5f1083cb3f 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
@@ -30,18 +30,18 @@ import stirling.software.common.model.enumeration.InvitationStatus;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.Authority;
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.LinkedInstanceRepository;
import stirling.software.saas.billing.repository.BillingSubscriptionRepository;
import stirling.software.saas.config.SupabaseConfigurationProperties;
import stirling.software.saas.model.TeamInvitation;
-import stirling.software.saas.model.TeamMembership;
import stirling.software.saas.repository.SaasTeamExtensionsRepository;
import stirling.software.saas.repository.TeamInvitationRepository;
-import stirling.software.saas.repository.TeamMembershipRepository;
/**
* Unit tests for {@link SaasTeamService}.
@@ -68,6 +68,14 @@ class SaasTeamServiceTest {
@Mock private LinkedInstanceRepository linkedInstanceRepository;
@Mock private stirling.software.proprietary.security.service.UserService userService;
+ @Mock
+ private stirling.software.proprietary.access.repository.ResourceGrantRepository
+ resourceGrantRepository;
+
+ @Mock
+ private stirling.software.proprietary.integration.repository.IntegrationConfigRepository
+ integrationConfigRepository;
+
@InjectMocks private SaasTeamService service;
private static final UUID SUPABASE_ID = UUID.fromString("11111111-2222-3333-4444-555555555555");
diff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsx
index 76463001fe..5ec17efb9a 100644
--- a/frontend/.storybook/preview.tsx
+++ b/frontend/.storybook/preview.tsx
@@ -19,11 +19,26 @@ import { UIProvider } from "@portal/contexts/UIContext";
import { SuiProvider } from "@portal/theme/SuiProvider";
import { handlers } from "@portal/mocks/handlers";
import { configureSupabase } from "@proprietary/auth/supabase/supabaseClient";
+import i18next from "i18next";
+import { initReactI18next } from "react-i18next";
import "@mantine/core/styles.css";
import "@core/tokens/tokens.css";
import "@core/tokens/base.css";
+// Storybook-only: init react-i18next so t(key, fallback, vars) interpolates its
+// English fallback (there's no backend here to load locale files). Without this,
+// the default t() returns raw templates like "{{count}} people · led by {{owner}}".
+if (!i18next.isInitialized) {
+ void i18next.use(initReactI18next).init({
+ lng: "en",
+ fallbackLng: "en",
+ resources: { en: { translation: {} } },
+ interpolation: { escapeValue: false },
+ react: { useSuspense: false },
+ });
+}
+
// Start MSW once. Storybook runs in a browser so this uses the service worker.
initialize({ onUnhandledRequest: "bypass" }, handlers);
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index e81f5eaebb..242c3885e3 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -2812,6 +2812,7 @@ back = "Back"
cancel = "Cancel"
close = "Close"
collapse = "Collapse"
+confirm = "Confirm"
continue = "Continue"
copied = "Copied!"
copy = "Copy"
@@ -6462,9 +6463,6 @@ componentSpendMtd = "Component spend (MTD)"
embedsThisMonth = "Embeds this month"
inBeta = "In beta"
-[portal.common]
-inviteMember = "Invite member"
-
[portal.componentsView]
subtitle = "Embeddable SDK widgets you drop into your own app — a viewer, an e-sign flow, an AI review panel. Each is metered per action. Click a card for install, usage and props."
title = "Components"
@@ -8027,83 +8025,8 @@ eyebrow = "TRAINING DATA"
title = "Turn PDFs into training data"
[portal.users]
-subtitle = "The people in your organization and the access they hold — roles, status and security controls."
title = "Users"
-[portal.users.access]
-subtitle = "Seats, authentication and provisioning for your organization."
-title = "Access & security"
-
-[portal.users.access.auth]
-title = "Authentication"
-
-[portal.users.access.auth.requireMfa]
-description = "Members must set up a second factor to sign in."
-enforced = "Enforced org-wide on this plan."
-label = "Require MFA"
-
-[portal.users.access.auth.shortSessions]
-description = "Sign members out after inactivity (currently {{timeout}})."
-label = "Short-lived sessions"
-
-[portal.users.access.scim]
-active = "Active"
-directory = "Directory"
-lastSync = "Last sync"
-note = "Members are created, updated and deactivated automatically from your identity provider."
-off = "Off"
-title = "SCIM provisioning"
-
-[portal.users.access.seats]
-title = "Seats"
-unlimited = "Your plan includes unlimited seats."
-usedLabel = "{{used}} of {{limit}} seats used"
-
-[portal.users.access.sso]
-connected = "Connected"
-domains = "Domains"
-manage = "Manage connection"
-notConfigured = "Not configured"
-provider = "Provider"
-title = "SSO / SAML"
-
-[portal.users.access.upgrade]
-action = "Upgrade plan"
-title = "Unlock team access controls"
-
-[portal.users.empty]
-description = "Invite your team to start collaborating on documents and pipelines."
-title = "No members yet"
-
-[portal.users.invite]
-cancel = "Cancel"
-email = "Email"
-emailError = "Enter a valid email address"
-emailPlaceholder = "[email protected]"
-role = "Role"
-roleHelper = "Determines what the member can do once they join."
-send = "Send invite"
-subtitle = "They'll receive an email to join your organization."
-
-[portal.users.roles]
-subtitle = "Every role exists on every plan — what each one can do is fixed across the org."
-title = "Roles"
-
-[portal.users.summary]
-members = "Members"
-pendingInvites = "Pending invites"
-seatsUsed = "Seats used"
-
-[portal.users.table]
-actionsFor = "Actions for {{name}}"
-changeRole = "Change role"
-lastActive = "Last active"
-member = "Member"
-remove = "Remove from org"
-role = "Role"
-status = "Status"
-suspend = "Suspend"
-
[portal.welcome]
ariaLabel = "Welcome to Stirling PDF"
badge = "Open-source"
@@ -10017,6 +9940,146 @@ title = "Detailed Statistics"
unknownEndpoint = "Unknown endpoint"
visits = "Visits"
+[users]
+lastActive = "Last active"
+learnMore = "Learn more about roles and access."
+locked = "Locked"
+roleFor = "Role for {{name}}"
+rowActions = "Actions for {{name}}"
+showAll = "Show all {{count}}"
+showLess = "Show less"
+subtitle2 = "Your people, teams, and access levels."
+suspended = "Suspended"
+teamActions = "Team actions"
+title = "Users"
+you = "(you)"
+
+[users.action]
+deleteTeam = "Delete team"
+disableMfa = "Reset MFA"
+move = "Move to team"
+reinstate = "Reinstate"
+remove = "Remove from org"
+rename = "Rename team"
+resetPw = "Reset password"
+suspend = "Suspend"
+unlock = "Unlock account"
+
+[users.cap]
+addProcessor = "+ Processor"
+approver = "Approves policy"
+editor = "Editor"
+processor = "Processor"
+
+[users.confirm]
+deleteTeamBody = "Delete the {{name}} team? The team must be empty first - move its members to another team, and it can't still own any integration configs."
+deleteTeamTitle = "Delete team"
+disableMfaBody = "Remove {{name}}'s MFA enrolment? They'll set it up again on next login if required."
+disableMfaTitle = "Reset MFA"
+removeBody = "Permanently remove {{name}} from the organization? This cannot be undone."
+removeTitle = "Remove member"
+
+[users.empty]
+description = "Invite your team to start collaborating."
+title = "No members yet"
+
+[users.group]
+addToTeam = "Add to team"
+guestCount = "{{count}} guest"
+guests = "Guests"
+guestsDesc = "External collaborators, scoped to what you shared. Editor only."
+ledBy = "led by {{owner}}"
+org = "Organization"
+orgDesc = "Owners with org-wide authority and policy approval"
+owners = "{{count}} owner"
+team = "{{name}} team"
+teamMeta = "{{count}} people"
+
+[users.invite]
+access = "Access"
+action = "Invite people"
+authOauth = "OAuth2 / SSO"
+authSaml = "SAML 2.0"
+authType = "Sign-in method"
+authWeb = "Password"
+create = "Create account"
+createSubtitle = "Create a self-hosted account with a password or SSO."
+createTitle = "Create account"
+editorDesc = "Edit PDFs in the Stirling PDF Editor. Everyone gets this."
+email = "Email address"
+emailError = "Enter a valid email address"
+emailPlaceholder2 = "[email protected]"
+forceChange = "Require a password change on first login"
+forceMfa = "Require MFA setup on first login"
+method = "How to add them"
+methodDirect = "Create account directly"
+methodEmail = "Invite by email"
+password = "Password"
+passwordError = "Password must be at least 8 characters"
+processorDeferred = "Invite sent, but Processor access couldn't be granted yet - set it from the roster once they've joined."
+processorDesc = "The governance surface, run pipelines, agents, and the API."
+role = "Role"
+send2 = "Send invite"
+subtitle2 = "They'll get an email to join your Stirling workspace."
+team = "Team"
+title = "Invite people"
+username = "Username"
+usernameError = "Username must be at least 3 characters"
+usernamePlaceholder = "jsmith"
+
+[users.loadError]
+description = "Something went wrong reaching the backend, or you don't have access. Try again."
+title = "Couldn't load members"
+
+[users.moveTeam]
+apply = "Move"
+team = "Team"
+title = "Move to team"
+
+[users.newTeam]
+action = "+ New team"
+create = "Create team"
+emailError = "Enter a valid email address"
+name = "Team name"
+namePlaceholder = "e.g. Finance"
+nameRequired = "Team name is required"
+owner = "Team Owner"
+ownerFailed = "Team created, but the owner couldn't be invited. Assign one from the roster."
+ownerHelper = "Every team has a leader. They'll be invited as Team Owner, with the Processor on, and can add the rest. You can reassign later."
+ownerPlaceholder = "[email protected]"
+subtitle = "Group people under a Team Owner who manages their access."
+title = "New team"
+
+[users.renameTeam]
+apply = "Rename"
+name = "Team name"
+title = "Rename team"
+
+[users.resetPw]
+apply = "Reset password"
+confirm = "Confirm password"
+copied = "Copied to clipboard"
+copyHint = "Copy this now - it won't be shown again."
+email = "Email the user about the reset"
+forceChange = "Require a password change on next login"
+generate = "Generate a secure password"
+includePw = "Include the new password in the email"
+mismatch = "Passwords do not match"
+newPassword = "New password"
+regen = "Regenerate"
+title = "Reset password"
+tooShort = "Password must be at least 8 characters"
+
+[users.role]
+guest = "Guest"
+member = "Member"
+orgOwner = "Org Owner"
+teamOwner = "Team Owner"
+
+[users.team]
+grantProcessor = "Grant Processor to team"
+revokeProcessor = "Revoke Processor from team"
+
[validateSignature]
date = "Date"
downloadCsv = "Download CSV"
diff --git a/frontend/editor/src/core/ui/Avatar.css b/frontend/editor/src/core/ui/Avatar.css
index 07187c439a..21089db8f0 100644
--- a/frontend/editor/src/core/ui/Avatar.css
+++ b/frontend/editor/src/core/ui/Avatar.css
@@ -3,14 +3,21 @@
align-items: center;
justify-content: center;
border-radius: 50%;
- font-weight: 600;
+ font-weight: 700;
color: var(--color-text-on-accent);
font-family: var(--font-sans);
- letter-spacing: 0.01em;
overflow: hidden;
flex-shrink: 0;
}
+/* line-height:1 + centred tracking keeps initials optically centred at small sizes. */
+.sui-avatar__initials {
+ display: block;
+ line-height: 1;
+ letter-spacing: 0.02em;
+ text-indent: 0.02em;
+}
+
.sui-avatar--interactive {
cursor: pointer;
transition: transform var(--motion-fast);
diff --git a/frontend/editor/src/core/ui/Avatar.tsx b/frontend/editor/src/core/ui/Avatar.tsx
index e848217e88..c7cfac501b 100644
--- a/frontend/editor/src/core/ui/Avatar.tsx
+++ b/frontend/editor/src/core/ui/Avatar.tsx
@@ -56,7 +56,9 @@ export function Avatar({
const content = src ? (
<img src={src} alt={ariaLabel ?? name} className="sui-avatar__img" />
) : (
- <span aria-hidden>{initialsOf(name)}</span>
+ <span className="sui-avatar__initials" aria-hidden>
+ {initialsOf(name)}
+ </span>
);
if (onClick) {
diff --git a/frontend/editor/src/core/ui/Chip.css b/frontend/editor/src/core/ui/Chip.css
index c341bb8e5c..f4b83cb853 100644
--- a/frontend/editor/src/core/ui/Chip.css
+++ b/frontend/editor/src/core/ui/Chip.css
@@ -21,6 +21,15 @@
.sui-chip--interactive {
cursor: pointer;
}
+/* "box-cut" add/placeholder affordance: no fill, dashed outline. */
+.sui-chip--dashed.mantine-Pill-root {
+ background: transparent;
+ border-style: dashed;
+ border-color: var(--_bd);
+}
+.sui-chip--dashed.sui-chip--interactive:hover {
+ background: var(--_tint);
+}
.sui-chip--loading {
opacity: 0.6;
pointer-events: none;
diff --git a/frontend/editor/src/core/ui/Chip.stories.tsx b/frontend/editor/src/core/ui/Chip.stories.tsx
index 0d54da3891..22a9f554c8 100644
--- a/frontend/editor/src/core/ui/Chip.stories.tsx
+++ b/frontend/editor/src/core/ui/Chip.stories.tsx
@@ -29,6 +29,7 @@ const meta: Meta<typeof Chip> = {
variant: { control: "inline-radio", options: ["primary", "secondary"] },
size: { control: "inline-radio", options: ["xs", "sm", "md", "lg"] },
showDot: { control: "boolean" },
+ dashed: { control: "boolean" },
onClick: { action: "clicked" },
onRemove: { action: "removed" },
},
@@ -55,6 +56,13 @@ export const Accents: Story = {
),
};
+/** "box-cut" add affordance: dashed outline, no fill, clickable. */
+export const DashedAdd: Story = {
+ args: { children: "+ Processor", dashed: true, accent: "neutral" },
+ argTypes: { onClick: { action: "clicked" } },
+ render: (args) => <Chip {...args} onClick={() => {}} />,
+};
+
export const InContext_OpChain: Story = {
render: () => (
<div
diff --git a/frontend/editor/src/core/ui/Chip.tsx b/frontend/editor/src/core/ui/Chip.tsx
index 49478d84c6..b92b534c2b 100644
--- a/frontend/editor/src/core/ui/Chip.tsx
+++ b/frontend/editor/src/core/ui/Chip.tsx
@@ -36,6 +36,8 @@ export interface ChipProps extends Omit<
onClick?: () => void;
/** Leading status dot. Use for status-style chips. */
showDot?: boolean;
+ /** Dashed "box-cut" outline with no fill - for add/placeholder affordances. */
+ dashed?: boolean;
style?: CSSProperties;
children?: ReactNode;
className?: string;
@@ -52,6 +54,7 @@ export function Chip({
onRemove,
onClick,
showDot,
+ dashed,
style,
children,
className,
@@ -63,6 +66,7 @@ export function Chip({
`sui-chip--${variant}`,
onClick ? "sui-chip--interactive" : "",
loading ? "sui-chip--loading" : "",
+ dashed ? "sui-chip--dashed" : "",
className ?? "",
]
.filter(Boolean)
diff --git a/frontend/editor/src/portal/api/access.ts b/frontend/editor/src/portal/api/access.ts
new file mode 100644
index 0000000000..cec165d68f
--- /dev/null
+++ b/frontend/editor/src/portal/api/access.ts
@@ -0,0 +1,61 @@
+import { apiClient } from "@portal/api/http";
+
+/**
+ * Access-control service layer: the ResourceGrant ACL the portal admin drives.
+ *
+ * Grants sit on top of the default policy (admins + team leads may enter the
+ * portal; owners/admins may use their configs). A grant widens that: a PORTAL
+ * grant lets a specific user/team into the processor; an INTEGRATION_CONFIG
+ * grant shares one stored config with a user/team at USE or MANAGE.
+ *
+ * Backend: /api/v1/admin/access/grants (admin only).
+ */
+
+export type PrincipalType = "USER" | "TEAM";
+export type ResourceType = "PORTAL" | "INTEGRATION_CONFIG";
+export type AccessPermission = "USE" | "MANAGE";
+
+/** One ACL row. `resourceId` is "" for the singleton PORTAL resource. */
+export interface ResourceGrant {
+ id: number;
+ resourceType: ResourceType;
+ resourceId: string;
+ principalType: PrincipalType;
+ principalId: number;
+ permission: AccessPermission;
+ createdAt?: string;
+}
+
+/** Create body; `permission` defaults to USE, `resourceId` empty for PORTAL. */
+export interface GrantRequest {
+ resourceType: ResourceType;
+ resourceId?: string;
+ principalType: PrincipalType;
+ principalId: number;
+ permission?: AccessPermission;
+}
+
+const BASE = "/api/v1/admin/access/grants";
+
+/** GET /grants: every grant on one resource (PORTAL, or one config by id). */
+export async function fetchGrants(
+ resourceType: ResourceType,
+ resourceId = "",
+): Promise<ResourceGrant[]> {
+ const q = new URLSearchParams({ resourceType });
+ if (resourceId) q.set("resourceId", resourceId);
+ return apiClient.local.json<ResourceGrant[]>(`${BASE}?${q.toString()}`);
+}
+
+/** POST /grants: grant (or, for a new permission, re-grant) access. */
+export async function createGrant(req: GrantRequest): Promise<ResourceGrant> {
+ return apiClient.local.json<ResourceGrant>(BASE, {
+ method: "POST",
+ body: req,
+ });
+}
+
+/** DELETE /grants/{id}: revoke a single grant row. */
+export async function revokeGrant(id: number): Promise<void> {
+ await apiClient.local.json(`${BASE}/${id}`, { method: "DELETE" });
+}
diff --git a/frontend/editor/src/portal/api/http.ts b/frontend/editor/src/portal/api/http.ts
index d0398470eb..b479a226c7 100644
--- a/frontend/editor/src/portal/api/http.ts
+++ b/frontend/editor/src/portal/api/http.ts
@@ -188,6 +188,24 @@ async function localBlob(
return res.blob();
}
+/** POST an application/x-www-form-urlencoded body (Spring @RequestParam endpoints),
+ * via the localBackend seam — same base + auth as localJson. */
+async function localForm<T>(
+ path: string,
+ params: Record<string, string>,
+ method: "POST" | "PUT" | "DELETE" = "POST",
+): Promise<T> {
+ const res = await fetch(`${localBaseUrl()}${path}`, {
+ method,
+ headers: { Accept: "application/json", ...(await localAuthHeader()) },
+ body: new URLSearchParams(params),
+ });
+ if (res.status === 401) {
+ onLocalUnauthorized();
+ }
+ return unwrap<T>(res);
+}
+
// ────────────────────────────────────────────────────────────────────────────
// saas — hosted SaaS Java, admin's Supabase JWT
// ────────────────────────────────────────────────────────────────────────────
@@ -269,6 +287,7 @@ export const apiClient = {
/** Local backend (this instance). Spring admin bearer auto-attached. */
local: {
json: localJson,
+ form: localForm,
blob: localBlob,
},
/** Hosted SaaS Java. Admin's Supabase JWT auto-attached. */
diff --git a/frontend/editor/src/portal/api/teams.ts b/frontend/editor/src/portal/api/teams.ts
new file mode 100644
index 0000000000..8ce2e36d30
--- /dev/null
+++ b/frontend/editor/src/portal/api/teams.ts
@@ -0,0 +1,76 @@
+import { apiClient } from "@portal/api/http";
+
+/**
+ * Teams service layer. The roster groups people under teams, each with a Team
+ * Owner (a LEADER membership). Backed by the proprietary team endpoints
+ * (/api/v1/team/*) plus the admin ui-data teams summary.
+ */
+
+export interface Team {
+ id: number;
+ name: string;
+ userCount: number;
+ /** Usernames of the team's owners (LEADER memberships). */
+ owners: string[];
+}
+
+interface TeamsDto {
+ teamsWithCounts: { id: number; name: string; userCount: number }[];
+ teamOwners: Record<string, string[]>;
+}
+
+/** GET the teams summary and fold the owners map onto each team. */
+export async function fetchTeams(): Promise<Team[]> {
+ const data = await apiClient.local.json<TeamsDto>(
+ "/api/v1/proprietary/ui-data/teams",
+ );
+ return (data.teamsWithCounts ?? []).map((t) => ({
+ id: t.id,
+ name: t.name,
+ userCount: t.userCount,
+ owners: data.teamOwners?.[String(t.id)] ?? [],
+ }));
+}
+
+/** POST /api/v1/team/create. */
+export async function createTeam(name: string): Promise<void> {
+ await apiClient.local.form("/api/v1/team/create", { name });
+}
+
+/** POST /api/v1/team/addUser. */
+export async function addUserToTeam(
+ teamId: number,
+ userId: string,
+): Promise<void> {
+ await apiClient.local.form("/api/v1/team/addUser", {
+ teamId: String(teamId),
+ userId,
+ });
+}
+
+/** POST /api/v1/team/setOwner. */
+export async function setTeamOwner(
+ teamId: number,
+ userId: string,
+): Promise<void> {
+ await apiClient.local.form("/api/v1/team/setOwner", {
+ teamId: String(teamId),
+ userId,
+ });
+}
+
+/** POST /api/v1/team/rename. */
+export async function renameTeam(
+ teamId: number,
+ newName: string,
+): Promise<void> {
+ await apiClient.local.form("/api/v1/team/rename", {
+ teamId: String(teamId),
+ newName,
+ });
+}
+
+/** POST /api/v1/team/delete (blocked by the backend if the team still has members/configs). */
+export async function deleteTeam(teamId: number): Promise<void> {
+ await apiClient.local.form("/api/v1/team/delete", { teamId: String(teamId) });
+}
diff --git a/frontend/editor/src/portal/api/users.ts b/frontend/editor/src/portal/api/users.ts
index 4c0fa5dcb6..0987f659ec 100644
--- a/frontend/editor/src/portal/api/users.ts
+++ b/frontend/editor/src/portal/api/users.ts
@@ -1,11 +1,13 @@
import { apiClient } from "@portal/api/http";
-import type { UsersResponse } from "@portal/mocks/users";
+import { ROLES } from "@portal/mocks/users";
+import type { Member, RoleId, UsersResponse } from "@portal/mocks/users";
import type { Tier } from "@portal/contexts/TierContext";
export type {
AccessControls,
Member,
MemberStatus,
+ PortalAccessState,
Role,
RoleId,
UsersResponse,
@@ -13,14 +15,373 @@ export type {
} from "@portal/mocks/users";
export {
MEMBER_STATUS_TONE,
+ PORTAL_ACCESS_TONE,
ROLES,
ROLE_LABEL,
ROLE_TONE,
} from "@portal/mocks/users";
-/** GET /v1/users?tier=… — summary strip, members table, role catalogue, access. */
+/** Roles an admin can assign from the portal; guest is derived, not assigned. */
+export const ASSIGNABLE_ROLES: RoleId[] = ["admin", "team_owner", "member"];
+
+/* ── backend payload (subset of AdminSettingsData) ─────────────────────── */
+
+interface AdminUserSummaryDto {
+ id: number;
+ username: string;
+ email?: string;
+ rolesAsString?: string;
+ enabled: boolean;
+ teamLead?: boolean;
+ team?: { id: number; name: string };
+ authenticationType?: string;
+ /** Authoritative server-side portal access (honors the configured default policy). */
+ portalAccess?: boolean;
+}
+
+interface AdminSettingsDto {
+ users: AdminUserSummaryDto[];
+ userLastRequest?: Record<string, number | string>;
+ userSettings?: Record<string, Record<string, string>>;
+ lockedUsers?: string[];
+ mailEnabled?: boolean;
+ emailInvitesEnabled?: boolean;
+ totalUsers?: number;
+ maxAllowedUsers?: number;
+ currentUsername?: string;
+}
+
+function roleIdFor(u: AdminUserSummaryDto): RoleId {
+ const role = u.rolesAsString ?? "";
+ if (role.includes("ROLE_ADMIN")) return "admin";
+ if (u.teamLead) return "team_owner";
+ // Guest (web-only/demo) is hidden from the UI for now; surface as a member.
+ return "member";
+}
+
+/** A member's last-seen time as plain language; "Never" when no session is tracked. */
+function relativeTime(value: number | string | undefined): string {
+ if (value === undefined || value === null) return "Never";
+ const ts = typeof value === "string" ? Date.parse(value) : value;
+ if (!Number.isFinite(ts) || ts <= 0) return "Never";
+ const mins = Math.max(0, Math.round((Date.now() - ts) / 60000));
+ if (mins < 1) return "Just now";
+ if (mins < 60) return `${mins}m ago`;
+ const hours = Math.round(mins / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.round(hours / 24);
+ if (days < 7) return `${days}d ago`;
+ const weeks = Math.round(days / 7);
+ if (weeks < 5) return weeks === 1 ? "1 week ago" : `${weeks} weeks ago`;
+ const months = Math.round(days / 30);
+ if (months < 12) return months <= 1 ? "1 month ago" : `${months} months ago`;
+ const years = Math.round(days / 365);
+ return years <= 1 ? "1 year ago" : `${years} years ago`;
+}
+
+/** 0 / huge sentinel license values mean "no seat limit". */
+function normalizeSeatLimit(max: number | undefined): number | null {
+ if (!max || max <= 0 || max >= 100000) return null;
+ return max;
+}
+
+/**
+ * GET /api/v1/proprietary/ui-data/admin-settings adapted onto the portal's
+ * UsersResponse. Role = stored authority + team leadership; the role
+ * catalogue is client copy. `tier` shapes only the access card.
+ */
export async function fetchUsers(tier: Tier): Promise<UsersResponse> {
- return apiClient.local.json<UsersResponse>(
- `/v1/users?tier=${encodeURIComponent(tier)}`,
+ const data = await apiClient.local.json<AdminSettingsDto>(
+ "/api/v1/proprietary/ui-data/admin-settings",
+ );
+ const locked = new Set(data.lockedUsers ?? []);
+ const members: Member[] = (data.users ?? []).map((u) => ({
+ id: String(u.id),
+ name: u.username,
+ email: u.email ?? u.username,
+ username: u.username,
+ teamId: u.team?.id,
+ teamName: u.team?.name,
+ role: roleIdFor(u),
+ teamLead: u.teamLead === true,
+ canAccessPortal: u.portalAccess === true,
+ isSelf: !!data.currentUsername && data.currentUsername === u.username,
+ status: u.enabled ? "active" : "suspended",
+ lastActive: relativeTime(data.userLastRequest?.[u.username]),
+ locked: locked.has(u.username),
+ mfaEnabled: data.userSettings?.[u.username]?.mfaEnabled === "true",
+ authType: u.authenticationType,
+ authority: u.rolesAsString,
+ }));
+ const seatLimit = normalizeSeatLimit(data.maxAllowedUsers);
+ const seatsUsed = data.totalUsers ?? members.length;
+ return {
+ summary: {
+ totalMembers: members.length,
+ pendingInvites: 0,
+ seatsUsed,
+ seatLimit,
+ },
+ members,
+ roles: ROLES,
+ access: { tier, seatsUsed, seatLimit },
+ mailEnabled: data.mailEnabled === true,
+ emailInvitesEnabled: data.emailInvitesEnabled === true,
+ };
+}
+
+/* ── row actions (Spring @RequestParam endpoints) ──────────────────────── */
+
+async function setAuthority(username: string, role: string): Promise<void> {
+ await apiClient.local.form("/api/v1/user/admin/changeRole", {
+ username,
+ role,
+ });
+}
+
+/**
+ * Reassign a member's canonical role. Admin/member map onto the stored ROLE_*
+ * authority; team owner is a LEADER membership on the user's team. Leadership is
+ * assigned/removed on `teamLead` (independent of the displayed role), and for
+ * team_owner the ownership call runs FIRST so a rejection can't strand a demote.
+ */
+export async function changeMemberRole(
+ member: Member,
+ target: RoleId,
+): Promise<void> {
+ if (!member.username) throw new Error("Member has no backend identity");
+ if (target === member.role) return;
+
+ const holdsAdmin = member.role === "admin";
+ const holdsLeader = member.teamLead === true;
+ // A stored web-only/demo authority must be lifted to ROLE_USER for member/team_owner.
+ // roleIdFor() surfaces a web-only account as "member", so read the raw authority.
+ const holdsWebOnly = (member.authority ?? "").includes("ROLE_WEB_ONLY_USER");
+
+ if (target === "guest") {
+ // Demote to web-only; drop any leadership first so no team is left ownerless-by-a-guest.
+ if (holdsLeader && member.teamId) {
+ await apiClient.local.form("/api/v1/team/removeOwner", {
+ teamId: String(member.teamId),
+ userId: member.id,
+ });
+ }
+ await setAuthority(member.username, "ROLE_WEB_ONLY_USER");
+ return;
+ }
+
+ if (target === "admin") {
+ if (!holdsAdmin) await setAuthority(member.username, "ROLE_ADMIN");
+ return; // any LEADER membership is harmless; an admin owns everything anyway
+ }
+
+ if (target === "team_owner") {
+ if (!member.teamId) {
+ throw new Error("Member must belong to a team to become its owner");
+ }
+ // Assign ownership first so a 400 (e.g. system team) leaves the user unchanged.
+ await apiClient.local.form("/api/v1/team/setOwner", {
+ teamId: String(member.teamId),
+ userId: member.id,
+ });
+ if (holdsAdmin || holdsWebOnly)
+ await setAuthority(member.username, "ROLE_USER");
+ return;
+ }
+
+ // target === "member": drop any leadership, and normalise a non-ROLE_USER authority.
+ if (holdsLeader && member.teamId) {
+ await apiClient.local.form("/api/v1/team/removeOwner", {
+ teamId: String(member.teamId),
+ userId: member.id,
+ });
+ }
+ if (holdsAdmin || holdsWebOnly)
+ await setAuthority(member.username, "ROLE_USER");
+}
+
+export async function setMemberSuspended(
+ member: Member,
+ suspended: boolean,
+): Promise<void> {
+ if (!member.username) throw new Error("Member has no backend identity");
+ await apiClient.local.form(
+ `/api/v1/user/admin/changeUserEnabled/${encodeURIComponent(member.username)}`,
+ { enabled: String(!suspended) },
+ );
+}
+
+export async function removeMember(member: Member): Promise<void> {
+ if (!member.username) throw new Error("Member has no backend identity");
+ await apiClient.local.json(
+ `/api/v1/user/admin/deleteUser/${encodeURIComponent(member.username)}`,
+ { method: "POST" },
+ );
+}
+
+export interface ResetPasswordOptions {
+ /** The new password (client-generated or admin-typed). */
+ newPassword: string;
+ forcePasswordChange?: boolean;
+ sendEmail?: boolean;
+ includePassword?: boolean;
+}
+
+/** Admin reset of a member's password (cannot target yourself). */
+export async function resetMemberPassword(
+ member: Member,
+ opts: ResetPasswordOptions,
+): Promise<void> {
+ if (!member.username) throw new Error("Member has no backend identity");
+ const params: Record<string, string> = {
+ username: member.username,
+ newPassword: opts.newPassword,
+ };
+ if (opts.forcePasswordChange) params.forcePasswordChange = "true";
+ if (opts.sendEmail) params.sendEmail = "true";
+ if (opts.includePassword) params.includePassword = "true";
+ await apiClient.local.form(
+ "/api/v1/user/admin/changePasswordForUser",
+ params,
+ );
+}
+
+/** Unlock an account locked after failed logins. */
+export async function unlockMember(member: Member): Promise<void> {
+ if (!member.username) throw new Error("Member has no backend identity");
+ await apiClient.local.json(
+ `/api/v1/user/admin/unlockUser/${encodeURIComponent(member.username)}`,
+ { method: "POST" },
+ );
+}
+
+/** Reset (disable) a member's MFA enrolment. */
+export async function disableMemberMfa(member: Member): Promise<void> {
+ if (!member.username) throw new Error("Member has no backend identity");
+ await apiClient.local.json(
+ `/api/v1/auth/mfa/disable/admin/${encodeURIComponent(member.username)}`,
+ { method: "POST" },
+ );
+}
+
+/**
+ * Move a member to a different team, keeping their role. The backend changeRole
+ * endpoint requires a single role, so we resolve one canonical authority from the
+ * member's stored roles (which may be a CSV) - preserving a web-only account and
+ * never silently promoting one to ROLE_USER.
+ */
+export async function moveMemberToTeam(
+ member: Member,
+ teamId: number,
+): Promise<void> {
+ if (!member.username) throw new Error("Member has no backend identity");
+ const role = canonicalAuthority(member);
+ await apiClient.local.form("/api/v1/user/admin/changeRole", {
+ username: member.username,
+ role,
+ teamId: String(teamId),
+ });
+}
+
+/**
+ * The member's single canonical ROLE_* authority. `authority` is the raw stored
+ * rolesAsString, which may be a CSV; match on substrings so a compound value maps
+ * to one role. Web-only is preserved; team_owner/member both store as ROLE_USER
+ * (leadership is a separate membership, not an authority).
+ */
+function canonicalAuthority(member: Member): string {
+ const stored = member.authority ?? "";
+ if (stored.includes("ROLE_ADMIN")) return "ROLE_ADMIN";
+ if (stored.includes("ROLE_WEB_ONLY_USER")) return "ROLE_WEB_ONLY_USER";
+ if (stored.includes("ROLE_USER")) return "ROLE_USER";
+ // Authority absent/unrecognized: fall back to the displayed role, never upgrading.
+ return member.role === "admin" ? "ROLE_ADMIN" : "ROLE_USER";
+}
+
+/* ── direct account creation (self-hosted / password auth only) ────────── */
+
+interface LoginConfigDto {
+ enableLogin?: boolean;
+ loginMethod?: string;
+ providerList?: Record<string, string>;
+}
+
+export interface AdminAuthConfig {
+ /**
+ * True only on a self-hosted instance with username/password login (loginMethod
+ * all|normal). SaaS (Supabase-authed) has no password accounts, so direct
+ * create is hidden there - and the portal can only reach a self-hosted backend
+ * anyway (it logs in via /api/v1/auth/login, which SaaS doesn't expose).
+ */
+ canDirectCreate: boolean;
+ hasOauth: boolean;
+ hasSaml: boolean;
+}
+
+/** Probe the login config to decide whether direct account creation is offered. */
+export async function fetchAuthConfig(): Promise<AdminAuthConfig> {
+ const d = await apiClient.local.json<LoginConfigDto>(
+ "/api/v1/proprietary/ui-data/login",
+ );
+ const method = (d.loginMethod ?? "all").toLowerCase();
+ const keys = Object.keys(d.providerList ?? {});
+ return {
+ canDirectCreate:
+ d.enableLogin === true && (method === "all" || method === "normal"),
+ hasOauth: keys.some((k) => k.includes("oauth2")),
+ hasSaml: keys.some((k) => k.includes("saml")),
+ };
+}
+
+export type AuthType = "WEB" | "OAUTH2" | "SAML2";
+
+export interface CreateMemberParams {
+ username: string;
+ /** Required for WEB (password) accounts; omitted for OAUTH2/SAML2. */
+ password?: string;
+ role: Extract<RoleId, "admin" | "member">;
+ teamId?: number;
+ authType: AuthType;
+ forceChange?: boolean;
+ forceMFA?: boolean;
+}
+
+/** Create an account directly (self-hosted). Returns the created username. */
+export async function createMember(p: CreateMemberParams): Promise<string> {
+ const params: Record<string, string> = {
+ username: p.username,
+ role: p.role === "admin" ? "ROLE_ADMIN" : "ROLE_USER",
+ authType: p.authType,
+ };
+ if (p.password) params.password = p.password;
+ if (p.teamId != null) params.teamId = String(p.teamId);
+ if (p.forceChange) params.forceChange = "true";
+ if (p.forceMFA) params.forceMFA = "true";
+ await apiClient.local.form("/api/v1/user/admin/saveUser", params);
+ return p.username;
+}
+
+export interface InviteResult {
+ successCount?: number;
+ failureCount?: number;
+ message?: string;
+ errors?: string;
+ error?: string;
+}
+
+/** Email invite; creates the account and mails a join link (mail required). */
+export async function inviteMember(
+ email: string,
+ role: Extract<RoleId, "admin" | "member">,
+ teamId?: number,
+): Promise<InviteResult> {
+ const params: Record<string, string> = {
+ emails: email,
+ role: role === "admin" ? "ROLE_ADMIN" : "ROLE_USER",
+ };
+ if (teamId != null) params.teamId = String(teamId);
+ return apiClient.local.form<InviteResult>(
+ "/api/v1/user/admin/inviteUsers",
+ params,
);
}
diff --git a/frontend/editor/src/portal/api/usersCapabilities.ts b/frontend/editor/src/portal/api/usersCapabilities.ts
new file mode 100644
index 0000000000..151c4c1df4
--- /dev/null
+++ b/frontend/editor/src/portal/api/usersCapabilities.ts
@@ -0,0 +1,53 @@
+/**
+ * Which user/team admin actions the current build's backend supports.
+ *
+ * The Users page UI and its data endpoints are shared across flavors; only this
+ * capability set differs. The endpoints are identical - the build flavor just
+ * selects the client + credential (`apiClient.local` in @portal/api/http, via the
+ * localBackend seam: self-hosted -> local Spring bearer, SaaS -> SaaS-backend
+ * Supabase bearer). Resolved at build time via the `@app/*` alias - see
+ * `src/proprietary/portal/usersCapabilities.ts`
+ * (self-hosted, org-admin: everything) and `src/saas/portal/usersCapabilities.ts`
+ * (SaaS, team-leader scoped: invite / rename / remove / seats only).
+ */
+export interface UsersCapabilities {
+ /** Show the "Organization" owners group (a single-org deployment). */
+ orgGroup: boolean;
+ /** Let an admin reassign roles at all (the role Select). */
+ changeRole: boolean;
+ /**
+ * Whether the "Org Owner" (ROLE_ADMIN) role can be held/assigned. Always false
+ * on SaaS - no SaaS user is ever ROLE_ADMIN, so it's dropped from the picker.
+ */
+ adminRole: boolean;
+ /** Create a team from the roster ("+ New team"). */
+ createTeam: boolean;
+ /** Delete a team. */
+ deleteTeam: boolean;
+ /** Rename a team. */
+ renameTeam: boolean;
+ /** Invite by email. */
+ emailInvite: boolean;
+ /** Create an account directly with a password (self-hosted password login). */
+ directCreate: boolean;
+ /** Admin password reset. */
+ resetPassword: boolean;
+ /** Unlock a locked account. */
+ unlock: boolean;
+ /** Reset (disable) a member's MFA. */
+ resetMfa: boolean;
+ /** Suspend / reinstate an account. */
+ suspend: boolean;
+ /** Move a member between teams. */
+ moveTeam: boolean;
+ /** Per-team seat usage / limits (SaaS billing). */
+ seats: boolean;
+ /**
+ * Manage Processor (portal) access grants. The grant endpoints are ADMIN-only,
+ * so this is off on SaaS (team leaders aren't admins) - the +Processor / grant
+ * controls are hidden there rather than shown as permanently-403 dead controls.
+ */
+ manageGrants: boolean;
+ /** Whether "remove" takes the member out of the whole org or just the team. */
+ removeScope: "org" | "team";
+}
diff --git a/frontend/editor/src/portal/components/users/AccessControls.stories.tsx b/frontend/editor/src/portal/components/users/AccessControls.stories.tsx
deleted file mode 100644
index 45f69ec8a3..0000000000
--- a/frontend/editor/src/portal/components/users/AccessControls.stories.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import { accessFor } from "@portal/mocks/users";
-import { AccessControls } from "@portal/components/users/AccessControls";
-
-const meta: Meta<typeof AccessControls> = {
- title: "Portal/Users/AccessControls",
- component: AccessControls,
- parameters: { layout: "padded" },
-};
-export default meta;
-type Story = StoryObj<typeof AccessControls>;
-
-/** Free: seat limit + upgrade nudge only. */
-export const Free: Story = {
- args: { access: accessFor("free") },
-};
-
-/** Pro: adds self-service MFA + session toggles. */
-export const Pro: Story = {
- args: { access: accessFor("pro") },
-};
-
-/** Enterprise: SSO/SAML, SCIM provisioning and enforced MFA. */
-export const Enterprise: Story = {
- args: { access: accessFor("enterprise") },
-};
diff --git a/frontend/editor/src/portal/components/users/AccessControls.tsx b/frontend/editor/src/portal/components/users/AccessControls.tsx
deleted file mode 100644
index 9744e13141..0000000000
--- a/frontend/editor/src/portal/components/users/AccessControls.tsx
+++ /dev/null
@@ -1,199 +0,0 @@
-import { useState } from "react";
-import { useTranslation } from "react-i18next";
-import {
- Banner,
- Button,
- Card,
- ProgressBar,
- StatTile,
- StatusBadge,
- ToggleSwitch,
-} from "@app/ui";
-import type { AccessControls as Access } from "@portal/api/users";
-import { seatsLabel } from "@portal/components/users/format";
-import "@portal/views/Users.css";
-
-interface AccessControlsProps {
- access: Access;
-}
-
-/**
- * Access posture for the org, scaling by tier:
- * free — seat limit + upgrade nudge only
- * pro — adds self-service MFA + session timeout toggles
- * enterprise — adds SSO/SAML, SCIM provisioning and enforced MFA
- *
- * Toggles hold local state only; persisting them is a backend wiring task.
- */
-export function AccessControls({ access }: AccessControlsProps) {
- const { t } = useTranslation();
- const [mfaEnforced, setMfaEnforced] = useState(access.mfaEnforced ?? false);
- const [shortSessions, setShortSessions] = useState(false);
-
- const seatPct =
- access.seatLimit === null
- ? 0
- : Math.min(1, access.seatsUsed / access.seatLimit);
-
- return (
- <section className="portal-users__access">
- <header className="portal-users__section-head">
- <h2 className="portal-users__section-title">
- {t("portal.users.access.title")}
- </h2>
- <p className="portal-users__section-sub">
- {t("portal.users.access.subtitle")}
- </p>
- </header>
-
- <div className="portal-users__access-grid">
- {/* Seats — shown on every tier. */}
- <Card padding="default">
- <div className="portal-users__access-card-head">
- <h3 className="portal-users__access-card-title">
- {t("portal.users.access.seats.title")}
- </h3>
- <span className="portal-users__muted">
- {seatsLabel(access.seatsUsed, access.seatLimit)}
- </span>
- </div>
- {access.seatLimit === null ? (
- <p className="portal-users__access-note">
- {t("portal.users.access.seats.unlimited")}
- </p>
- ) : (
- <ProgressBar
- value={seatPct}
- thresholded
- label={t("portal.users.access.seats.usedLabel", {
- used: access.seatsUsed,
- limit: access.seatLimit,
- })}
- />
- )}
- </Card>
-
- {/* Pro+: MFA + sessions self-service. */}
- {access.mfaAvailable && (
- <Card padding="default">
- <h3 className="portal-users__access-card-title">
- {t("portal.users.access.auth.title")}
- </h3>
- <div className="portal-users__toggle-rows">
- <div className="portal-users__toggle-row">
- <ToggleSwitch
- checked={mfaEnforced}
- onChange={(v) => {
- setMfaEnforced(v);
- // TODO(backend): PATCH /v1/users/access { mfaEnforced }
- }}
- label={t("portal.users.access.auth.requireMfa.label")}
- description={
- access.mfaEnforced
- ? t("portal.users.access.auth.requireMfa.enforced")
- : t("portal.users.access.auth.requireMfa.description")
- }
- disabled={access.mfaEnforced}
- />
- </div>
- <div className="portal-users__toggle-row">
- <ToggleSwitch
- checked={shortSessions}
- onChange={(v) => {
- setShortSessions(v);
- // TODO(backend): PATCH /v1/users/access { sessionTimeout }
- }}
- label={t("portal.users.access.auth.shortSessions.label")}
- description={t(
- "portal.users.access.auth.shortSessions.description",
- {
- timeout: access.sessionTimeout,
- },
- )}
- />
- </div>
- </div>
- </Card>
- )}
-
- {/* Enterprise: SSO. */}
- {access.sso && (
- <Card padding="default">
- <div className="portal-users__access-card-head">
- <h3 className="portal-users__access-card-title">
- {t("portal.users.access.sso.title")}
- </h3>
- <StatusBadge
- tone={access.sso.status === "connected" ? "success" : "neutral"}
- size="sm"
- >
- {access.sso.status === "connected"
- ? t("portal.users.access.sso.connected")
- : t("portal.users.access.sso.notConfigured")}
- </StatusBadge>
- </div>
- <div className="portal-users__access-stats">
- <StatTile
- label={t("portal.users.access.sso.provider")}
- value={access.sso.provider}
- />
- <StatTile
- label={t("portal.users.access.sso.domains")}
- value={access.sso.domains.join(", ") || "—"}
- />
- </div>
- <Button variant="tertiary" size="sm">
- {t("portal.users.access.sso.manage")}
- </Button>
- </Card>
- )}
-
- {/* Enterprise: SCIM provisioning. */}
- {access.scim && (
- <Card padding="default">
- <div className="portal-users__access-card-head">
- <h3 className="portal-users__access-card-title">
- {t("portal.users.access.scim.title")}
- </h3>
- <StatusBadge
- tone={access.scim.enabled ? "success" : "neutral"}
- size="sm"
- >
- {access.scim.enabled
- ? t("portal.users.access.scim.active")
- : t("portal.users.access.scim.off")}
- </StatusBadge>
- </div>
- <div className="portal-users__access-stats">
- <StatTile
- label={t("portal.users.access.scim.directory")}
- value={access.scim.directory}
- />
- <StatTile
- label={t("portal.users.access.scim.lastSync")}
- value={access.scim.lastSync}
- />
- </div>
- <p className="portal-users__access-note">
- {t("portal.users.access.scim.note")}
- </p>
- </Card>
- )}
- </div>
-
- {/* Free: upgrade nudge spans the section. */}
- {access.upgradeHint && (
- <Banner
- tone="info"
- title={t("portal.users.access.upgrade.title")}
- description={access.upgradeHint}
- action={
- <Button size="sm" accent="premium">
- {t("portal.users.access.upgrade.action")}
- </Button>
- }
- />
- )}
- </section>
- );
-}
diff --git a/frontend/editor/src/portal/components/users/ConfirmModal.stories.tsx b/frontend/editor/src/portal/components/users/ConfirmModal.stories.tsx
new file mode 100644
index 0000000000..92eeca3f42
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/ConfirmModal.stories.tsx
@@ -0,0 +1,32 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ConfirmModal } from "@portal/components/users/ConfirmModal";
+
+const meta: Meta<typeof ConfirmModal> = {
+ title: "Portal/Users/ConfirmModal",
+ component: ConfirmModal,
+ parameters: { layout: "fullscreen" },
+ args: {
+ open: true,
+ title: "Remove member",
+ body: "Permanently remove Sarah Kowalski from the organization? This cannot be undone.",
+ confirmLabel: "Remove from org",
+ danger: true,
+ onConfirm: () => {},
+ onCancel: () => {},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof ConfirmModal>;
+
+/** Destructive confirm (red button). */
+export const Danger: Story = {};
+
+/** Neutral confirm. */
+export const Neutral: Story = {
+ args: {
+ title: "Reset MFA",
+ body: "Remove this member's MFA enrolment?",
+ confirmLabel: "Reset MFA",
+ danger: false,
+ },
+};
diff --git a/frontend/editor/src/portal/components/users/ConfirmModal.tsx b/frontend/editor/src/portal/components/users/ConfirmModal.tsx
new file mode 100644
index 0000000000..183b61bde3
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/ConfirmModal.tsx
@@ -0,0 +1,54 @@
+import { useTranslation } from "react-i18next";
+import { Button, Modal } from "@app/ui";
+import "@portal/views/Users.css";
+
+interface ConfirmModalProps {
+ open: boolean;
+ title: string;
+ body: string;
+ confirmLabel: string;
+ /** Red confirm button for destructive actions. */
+ danger?: boolean;
+ busy?: boolean;
+ onConfirm: () => void;
+ onCancel: () => void;
+}
+
+/** Small reusable confirm dialog for destructive/irreversible actions. */
+export function ConfirmModal({
+ open,
+ title,
+ body,
+ confirmLabel,
+ danger,
+ busy,
+ onConfirm,
+ onCancel,
+}: ConfirmModalProps) {
+ const { t } = useTranslation();
+ return (
+ <Modal
+ open={open}
+ onClose={onCancel}
+ width="sm"
+ title={title}
+ footer={
+ <div className="portal-users__modal-footer">
+ <Button variant="tertiary" size="sm" onClick={onCancel}>
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ size="sm"
+ accent={danger ? "danger" : undefined}
+ onClick={onConfirm}
+ disabled={busy}
+ >
+ {confirmLabel}
+ </Button>
+ </div>
+ }
+ >
+ <p className="portal-users__confirm-body">{body}</p>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/portal/components/users/InviteMemberModal.stories.tsx b/frontend/editor/src/portal/components/users/InviteMemberModal.stories.tsx
index cffa89d54d..9d1127d8a5 100644
--- a/frontend/editor/src/portal/components/users/InviteMemberModal.stories.tsx
+++ b/frontend/editor/src/portal/components/users/InviteMemberModal.stories.tsx
@@ -1,16 +1,72 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";
+import type { Team } from "@portal/api/teams";
+
+const TEAMS: Team[] = [
+ { id: 1, name: "Default", userCount: 4, owners: [] },
+ { id: 2, name: "Engineering", userCount: 3, owners: ["tom"] },
+ { id: 3, name: "Compliance", userCount: 2, owners: ["dana"] },
+];
const meta: Meta<typeof InviteMemberModal> = {
title: "Portal/Users/InviteMemberModal",
component: InviteMemberModal,
parameters: { layout: "fullscreen" },
- args: { open: true, onClose: () => {} },
+ args: {
+ open: true,
+ onClose: () => {},
+ onInvited: () => {},
+ teams: TEAMS,
+ // Admin build: the Processor access option is offered (gated on grant management).
+ manageGrants: true,
+ },
};
export default meta;
type Story = StoryObj<typeof InviteMemberModal>;
-/** Email + role; Send invite validates locally then closes (demo shell). */
+/** Invite by email with a role, team, and starting access level. */
export const Open: Story = {};
+/** Opened from a team's "Add to team" — the team is preselected. */
+export const ScopedToTeam: Story = {
+ args: { defaultTeamId: 2 },
+};
+
+/** Self-hosted with mail configured: the email/create toggle is offered; opens in
+ * create mode (the default when account creation is available). */
+export const SelfHostedDirectCreate: Story = {
+ args: {
+ canDirectCreate: true,
+ canEmailInvite: true,
+ hasOauth: true,
+ hasSaml: true,
+ },
+};
+
+/** Self-hosted without SMTP/invites: no "Invite by email" option at all - just the
+ * create-account form. */
+export const SelfHostedNoMail: Story = {
+ args: {
+ canDirectCreate: true,
+ canEmailInvite: false,
+ hasOauth: true,
+ hasSaml: true,
+ },
+};
+
+/** The direct "Create account" form: username, password, sign-in method, force-MFA. */
+export const CreateAccountForm: Story = {
+ args: {
+ canDirectCreate: true,
+ hasOauth: true,
+ hasSaml: true,
+ initialMode: "direct",
+ },
+};
+
+/** SaaS: no "admin" (Org Owner) option and no Processor grant (both admin-only). */
+export const NoAdminRole: Story = {
+ args: { adminRole: false, manageGrants: false },
+};
+
export const Closed: Story = { args: { open: false } };
diff --git a/frontend/editor/src/portal/components/users/InviteMemberModal.test.tsx b/frontend/editor/src/portal/components/users/InviteMemberModal.test.tsx
new file mode 100644
index 0000000000..cf43743817
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/InviteMemberModal.test.tsx
@@ -0,0 +1,72 @@
+import type { ComponentProps } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+
+// Deterministic i18n: render the English fallback so assertions read naturally.
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ i18n: { changeLanguage: vi.fn() },
+ }),
+}));
+
+vi.mock("@portal/contexts/TierContext", () => ({
+ useTier: () => ({ tier: "pro" }),
+}));
+
+// The modal only calls these on submit; stub so imports resolve and no fetch fires.
+vi.mock("@portal/api/users", () => ({
+ createMember: vi.fn(),
+ fetchUsers: vi.fn().mockResolvedValue({ members: [] }),
+ inviteMember: vi.fn(),
+ ROLE_LABEL: { member: "Member", admin: "Admin" },
+}));
+vi.mock("@portal/api/access", () => ({ createGrant: vi.fn() }));
+
+import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";
+import type { Team } from "@portal/api/teams";
+
+const TEAMS: Team[] = [{ id: 1, name: "Default", userCount: 1, owners: [] }];
+
+function renderModal(props: Partial<ComponentProps<typeof InviteMemberModal>>) {
+ return render(
+ <MantineProvider>
+ <InviteMemberModal open onClose={() => {}} teams={TEAMS} {...props} />
+ </MantineProvider>,
+ );
+}
+
+describe("InviteMemberModal — add-user method gating", () => {
+ it("SaaS (email only): no method toggle, opens to the email field", () => {
+ renderModal({ canDirectCreate: false, canEmailInvite: true });
+ expect(screen.queryByText("How to add them")).not.toBeInTheDocument();
+ expect(screen.getByText("Email address")).toBeInTheDocument();
+ expect(screen.queryByText("Username")).not.toBeInTheDocument();
+ });
+
+ it("self-hosted with mail: offers the toggle and defaults to create-account", () => {
+ renderModal({ canDirectCreate: true, canEmailInvite: true });
+ expect(screen.getByText("How to add them")).toBeInTheDocument();
+ // Default mode is create-account (username field, not email).
+ expect(screen.getByText("Username")).toBeInTheDocument();
+ expect(screen.queryByText("Email address")).not.toBeInTheDocument();
+ });
+
+ it("self-hosted without SMTP: no email option at all, create-account only", () => {
+ renderModal({ canDirectCreate: true, canEmailInvite: false });
+ expect(screen.queryByText("How to add them")).not.toBeInTheDocument();
+ expect(screen.getByText("Username")).toBeInTheDocument();
+ expect(screen.queryByText("Email address")).not.toBeInTheDocument();
+ });
+
+ it("clamps initialMode=email to create-account when email is unavailable", () => {
+ renderModal({
+ canDirectCreate: true,
+ canEmailInvite: false,
+ initialMode: "email",
+ });
+ expect(screen.getByText("Username")).toBeInTheDocument();
+ expect(screen.queryByText("Email address")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/portal/components/users/InviteMemberModal.tsx b/frontend/editor/src/portal/components/users/InviteMemberModal.tsx
index fe90105cf5..305bcc622d 100644
--- a/frontend/editor/src/portal/components/users/InviteMemberModal.tsx
+++ b/frontend/editor/src/portal/components/users/InviteMemberModal.tsx
@@ -1,54 +1,253 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { Button, FormField, Input, Modal, Select } from "@app/ui";
-import { type RoleId, ROLES } from "@portal/api/users";
+import { Button, Checkbox, FormField, Input, Modal, Select } from "@app/ui";
+import {
+ createMember,
+ fetchUsers,
+ inviteMember,
+ ROLE_LABEL,
+ type AuthType,
+} from "@portal/api/users";
+import { createGrant } from "@portal/api/access";
+import { errorMessage } from "@portal/api/http";
+import type { Team } from "@portal/api/teams";
+import { useTier } from "@portal/contexts/TierContext";
import "@portal/views/Users.css";
interface InviteMemberModalProps {
open: boolean;
onClose: () => void;
+ onInvited?: () => void;
+ teams: Team[];
+ defaultTeamId?: number | null;
+ /** Self-hosted with password login: enables the "Create account" mode. */
+ canDirectCreate?: boolean;
+ /** Whether "Invite by email" is offered. Off when SMTP/invites aren't configured
+ * (self-hosted); always on for SaaS. */
+ canEmailInvite?: boolean;
+ hasOauth?: boolean;
+ hasSaml?: boolean;
+ /** Whether the "admin" (Org Owner) role can be assigned. Off on SaaS. */
+ adminRole?: boolean;
+ /** Whether portal-access grants can be created (ADMIN-only). Gates the Processor option. */
+ manageGrants?: boolean;
+ /** Non-blocking notice back to the parent (e.g. a deferred Processor grant). */
+ onNotice?: (message: string) => void;
+ /** Force the initial mode (mainly for Storybook). Defaults to "direct" when account
+ * creation is available, else "email". */
+ initialMode?: "email" | "direct";
}
-const ROLE_SELECT_OPTIONS = ROLES.map((r) => ({
- value: r.id,
- label: r.label,
-}));
+type InviteRole = "member" | "admin";
+type Mode = "email" | "direct";
-/** Org Owner is reserved for transfer flows — invites default to Developer. */
-const DEFAULT_ROLE: RoleId = "developer";
+const ROLE_SELECT_OPTIONS: { value: InviteRole; label: string }[] = [
+ { value: "member", label: ROLE_LABEL.member },
+ { value: "admin", label: ROLE_LABEL.admin },
+];
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
-/**
- * Invite-by-email shell. Submitting validates locally then closes without
- * sending — wiring the submit to the backend dispatches the invitation.
- */
-export function InviteMemberModal({ open, onClose }: InviteMemberModalProps) {
+export function InviteMemberModal({
+ open,
+ onClose,
+ onInvited,
+ teams,
+ defaultTeamId,
+ canDirectCreate = false,
+ canEmailInvite = true,
+ hasOauth = false,
+ hasSaml = false,
+ adminRole = true,
+ manageGrants = false,
+ onNotice,
+ initialMode,
+}: InviteMemberModalProps) {
const { t } = useTranslation();
+ const { tier } = useTier();
+ const [mode, setMode] = useState<Mode>("email");
const [email, setEmail] = useState("");
- const [role, setRole] = useState<RoleId>(DEFAULT_ROLE);
+ const [username, setUsername] = useState("");
+ const [password, setPassword] = useState("");
+ const [authType, setAuthType] = useState<AuthType>("WEB");
+ const [forceChange, setForceChange] = useState(true);
+ const [forceMFA, setForceMFA] = useState(false);
+ const [role, setRole] = useState<InviteRole>("member");
+ const [teamId, setTeamId] = useState<string>("");
+ const [processor, setProcessor] = useState(false);
const [touched, setTouched] = useState(false);
+ const [sending, setSending] = useState(false);
+ const [submitError, setSubmitError] = useState<string | null>(null);
+
+ // Which add-user modes this flavor/config offers. Self-hosted offers direct create;
+ // SaaS offers email; self-hosted also offers email once SMTP + invites are configured.
+ const directAvailable = canDirectCreate;
+ const emailAvailable = canEmailInvite;
+ const preferredMode: Mode = directAvailable ? "direct" : "email";
+
+ useEffect(() => {
+ if (!open) return;
+ // Honor an explicit initialMode only when that mode is actually available.
+ const requested: Mode =
+ initialMode &&
+ (initialMode === "email" ? emailAvailable : directAvailable)
+ ? initialMode
+ : preferredMode;
+ setMode(requested);
+ setTeamId(
+ defaultTeamId != null
+ ? String(defaultTeamId)
+ : teams.length > 0
+ ? String(teams[0].id)
+ : "",
+ );
+ }, [
+ open,
+ defaultTeamId,
+ teams,
+ directAvailable,
+ emailAvailable,
+ preferredMode,
+ initialMode,
+ ]);
+
+ // A server-side submit error must not outlive the input that caused it.
+ useEffect(() => {
+ setSubmitError(null);
+ }, [email, username, password]);
+
+ // Drop the "admin" (Org Owner) option where it can't be assigned (SaaS).
+ const roleOptions = adminRole
+ ? ROLE_SELECT_OPTIONS
+ : ROLE_SELECT_OPTIONS.filter((o) => o.value !== "admin");
+
+ const authTypeOptions: { value: AuthType; label: string }[] = [
+ { value: "WEB", label: t("users.invite.authWeb", "Password") },
+ ...(hasOauth
+ ? [
+ {
+ value: "OAUTH2" as AuthType,
+ label: t("users.invite.authOauth", "OAuth2 / SSO"),
+ },
+ ]
+ : []),
+ ...(hasSaml
+ ? [
+ {
+ value: "SAML2" as AuthType,
+ label: t("users.invite.authSaml", "SAML 2.0"),
+ },
+ ]
+ : []),
+ ];
const emailValid = EMAIL_RE.test(email.trim());
+ const usernameValid = username.trim().length >= 3;
+ const needsPassword = mode === "direct" && authType === "WEB";
+ const passwordValid = !needsPassword || password.length >= 8;
+
const error =
- touched && !emailValid ? t("portal.users.invite.emailError") : undefined;
+ (touched && mode === "email" && !emailValid
+ ? t("users.invite.emailError", "Enter a valid email address")
+ : undefined) ??
+ (touched && mode === "direct" && !usernameValid
+ ? t(
+ "users.invite.usernameError",
+ "Username must be at least 3 characters",
+ )
+ : undefined) ??
+ (touched && mode === "direct" && !passwordValid
+ ? t(
+ "users.invite.passwordError",
+ "Password must be at least 8 characters",
+ )
+ : undefined) ??
+ submitError ??
+ undefined;
function close() {
onClose();
- // Reset for the next open, after the close transition has finished.
setTimeout(() => {
setEmail("");
- setRole(DEFAULT_ROLE);
+ setUsername("");
+ setPassword("");
+ setAuthType("WEB");
+ setForceChange(true);
+ setForceMFA(false);
+ setRole("member");
+ setProcessor(false);
setTouched(false);
+ setSubmitError(null);
}, 200);
}
- function submit() {
+ // Grant Processor to the just-added user. Returns false when it couldn't be applied
+ // (an email invitee usually isn't a resolvable user yet, or the grant call is denied).
+ async function grantProcessor(
+ match: (m: { email: string; username?: string }) => boolean,
+ ): Promise<boolean> {
+ const { members } = await fetchUsers(tier);
+ const user = members.find(match);
+ if (!user) return false;
+ await createGrant({
+ resourceType: "PORTAL",
+ resourceId: "",
+ principalType: "USER",
+ principalId: Number(user.id),
+ permission: "USE",
+ });
+ return true;
+ }
+
+ async function submit() {
setTouched(true);
- if (!emailValid) return;
- // TODO(backend): POST /v1/users/invitations { email, role } — send the
- // invite, then close on success and refetch the members list.
- close();
+ setSubmitError(null);
+ if (sending) return;
+ const teamNum = teamId ? Number(teamId) : undefined;
+ setSending(true);
+ try {
+ let processorApplied = true;
+ if (mode === "email") {
+ if (!emailValid) return;
+ const result = await inviteMember(email.trim(), role, teamNum);
+ if (result?.error || result?.errors) {
+ setSubmitError(result.error ?? result.errors ?? null);
+ return;
+ }
+ if (processor)
+ processorApplied = await grantProcessor(
+ (m) => m.email === email.trim() || m.username === email.trim(),
+ ).catch(() => false);
+ } else {
+ if (!usernameValid || !passwordValid) return;
+ const created = await createMember({
+ username: username.trim(),
+ password: authType === "WEB" ? password : undefined,
+ role,
+ teamId: teamNum,
+ authType,
+ forceChange,
+ forceMFA,
+ });
+ if (processor)
+ processorApplied = await grantProcessor(
+ (m) => m.username === created,
+ ).catch(() => false);
+ }
+ if (processor && !processorApplied)
+ onNotice?.(
+ t(
+ "users.invite.processorDeferred",
+ "Invite sent, but Processor access couldn't be granted yet - set it from the roster once they've joined.",
+ ),
+ );
+ onInvited?.();
+ close();
+ } catch (e) {
+ setSubmitError(errorMessage(e));
+ } finally {
+ setSending(false);
+ }
}
return (
@@ -56,44 +255,184 @@ export function InviteMemberModal({ open, onClose }: InviteMemberModalProps) {
open={open}
onClose={close}
width="sm"
- title={t("portal.common.inviteMember")}
- subtitle={t("portal.users.invite.subtitle")}
+ title={
+ mode === "direct"
+ ? t("users.invite.createTitle", "Create account")
+ : t("users.invite.title", "Invite people")
+ }
+ subtitle={
+ mode === "direct"
+ ? t(
+ "users.invite.createSubtitle",
+ "Create a self-hosted account with a password or SSO.",
+ )
+ : t(
+ "users.invite.subtitle2",
+ "They'll get an email to join your Stirling workspace.",
+ )
+ }
footer={
<div className="portal-users__modal-footer">
<Button variant="tertiary" size="sm" onClick={close}>
- {t("portal.users.invite.cancel")}
+ {t("common.cancel", "Cancel")}
</Button>
- <Button size="sm" onClick={submit} disabled={touched && !emailValid}>
- {t("portal.users.invite.send")}
+ <Button size="sm" onClick={() => void submit()} disabled={sending}>
+ {mode === "direct"
+ ? t("users.invite.create", "Create account")
+ : t("users.invite.send2", "Send invite")}
</Button>
</div>
}
>
<div className="portal-users__invite-body">
- <FormField
- label={t("portal.users.invite.email")}
- error={error}
- required
- >
- <Input
- type="email"
- placeholder={t("portal.users.invite.emailPlaceholder")}
- value={email}
- invalid={!!error}
- onChange={(e) => setEmail(e.target.value)}
- onBlur={() => setTouched(true)}
- />
- </FormField>
- <FormField
- label={t("portal.users.invite.role")}
- helperText={t("portal.users.invite.roleHelper")}
- >
- <Select
- options={ROLE_SELECT_OPTIONS}
- value={role}
- onChange={(value) => setRole((value ?? "") as RoleId)}
+ {directAvailable && emailAvailable && (
+ <FormField label={t("users.invite.method", "How to add them")}>
+ <Select
+ options={[
+ {
+ value: "email",
+ label: t("users.invite.methodEmail", "Invite by email"),
+ },
+ {
+ value: "direct",
+ label: t(
+ "users.invite.methodDirect",
+ "Create account directly",
+ ),
+ },
+ ]}
+ value={mode}
+ onChange={(value) => setMode((value ?? "email") as Mode)}
+ />
+ </FormField>
+ )}
+
+ {mode === "email" ? (
+ <FormField
+ label={t("users.invite.email", "Email address")}
+ error={error}
+ required
+ >
+ <Input
+ type="email"
+ placeholder={t(
+ "users.invite.emailPlaceholder2",
+ )}
+ value={email}
+ invalid={!!error}
+ onChange={(e) => setEmail(e.target.value)}
+ onBlur={() => setTouched(true)}
+ />
+ </FormField>
+ ) : (
+ <>
+ <FormField
+ label={t("users.invite.username", "Username")}
+ error={error}
+ required
+ >
+ <Input
+ placeholder={t("users.invite.usernamePlaceholder", "jsmith")}
+ value={username}
+ invalid={!!error}
+ onChange={(e) => setUsername(e.target.value)}
+ onBlur={() => setTouched(true)}
+ />
+ </FormField>
+ {authTypeOptions.length > 1 && (
+ <FormField label={t("users.invite.authType", "Sign-in method")}>
+ <Select
+ options={authTypeOptions}
+ value={authType}
+ onChange={(value) =>
+ setAuthType((value ?? "WEB") as AuthType)
+ }
+ />
+ </FormField>
+ )}
+ {authType === "WEB" && (
+ <FormField
+ label={t("users.invite.password", "Password")}
+ required
+ >
+ <Input
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </FormField>
+ )}
+ </>
+ )}
+
+ <div className="portal-users__invite-grid">
+ <FormField label={t("users.invite.role", "Role")}>
+ <Select
+ options={roleOptions}
+ value={role}
+ onChange={(value) => setRole((value ?? "member") as InviteRole)}
+ />
+ </FormField>
+ <FormField label={t("users.invite.team", "Team")}>
+ <Select
+ options={teams.map((tm) => ({
+ value: String(tm.id),
+ label: tm.name,
+ }))}
+ value={teamId}
+ onChange={(value) => setTeamId(value ?? "")}
+ />
+ </FormField>
+ </div>
+
+ {mode === "direct" && (
+ <div className="portal-users__invite-access">
+ <Checkbox
+ checked={forceChange}
+ onChange={(e) => setForceChange(e.target.checked)}
+ label={t(
+ "users.invite.forceChange",
+ "Require a password change on first login",
+ )}
+ disabled={authType !== "WEB"}
+ />
+ <Checkbox
+ checked={forceMFA}
+ onChange={(e) => setForceMFA(e.target.checked)}
+ label={t(
+ "users.invite.forceMfa",
+ "Require MFA setup on first login",
+ )}
+ />
+ </div>
+ )}
+
+ <div className="portal-users__invite-access">
+ <span className="portal-users__invite-access-label">
+ {t("users.invite.access", "Access")}
+ </span>
+ <Checkbox
+ checked
+ disabled
+ label={t("users.cap.editor", "Editor")}
+ description={t(
+ "users.invite.editorDesc",
+ "Edit PDFs in the Stirling PDF Editor. Everyone gets this.",
+ )}
/>
- </FormField>
+ {manageGrants && (
+ <Checkbox
+ checked={processor}
+ onChange={(e) => setProcessor(e.target.checked)}
+ label={t("users.cap.processor", "Processor")}
+ description={t(
+ "users.invite.processorDesc",
+ "The governance surface, run pipelines, agents, and the API.",
+ )}
+ />
+ )}
+ </div>
</div>
</Modal>
);
diff --git a/frontend/editor/src/portal/components/users/MembersTable.stories.tsx b/frontend/editor/src/portal/components/users/MembersTable.stories.tsx
deleted file mode 100644
index 2420622609..0000000000
--- a/frontend/editor/src/portal/components/users/MembersTable.stories.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import { membersFor } from "@portal/mocks/users";
-import { MembersTable } from "@portal/components/users/MembersTable";
-
-const meta: Meta<typeof MembersTable> = {
- title: "Portal/Users/MembersTable",
- component: MembersTable,
- parameters: { layout: "padded" },
- args: {
- members: membersFor("pro"),
- onChangeRole: () => {},
- onSuspend: () => {},
- onRemove: () => {},
- },
-};
-export default meta;
-type Story = StoryObj<typeof MembersTable>;
-
-/** Pro roster: active members plus an invited and a suspended account. */
-export const Default: Story = {};
-
-/** Enterprise adds a Team Owner and a second pending invite. */
-export const Enterprise: Story = {
- args: { members: membersFor("enterprise") },
-};
-
-export const Free: Story = {
- args: { members: membersFor("free") },
-};
diff --git a/frontend/editor/src/portal/components/users/MembersTable.tsx b/frontend/editor/src/portal/components/users/MembersTable.tsx
deleted file mode 100644
index 6a918813b5..0000000000
--- a/frontend/editor/src/portal/components/users/MembersTable.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-import { useMemo } from "react";
-import { useTranslation } from "react-i18next";
-import { Menu } from "@mantine/core";
-import {
- ActionIcon,
- Avatar,
- Chip,
- StatusBadge,
- Table,
- type TableColumn,
-} from "@app/ui";
-import {
- type Member,
- type RoleId,
- MEMBER_STATUS_TONE,
- ROLE_LABEL,
-} from "@portal/api/users";
-import {
- avatarToneForRole,
- chipAccentForRole,
-} from "@portal/components/users/format";
-import "@portal/views/Users.css";
-
-interface MembersTableProps {
- members: Member[];
- /** Row actions. Each submits to the backend via the view's handlers. */
- onChangeRole: (member: Member, role: RoleId) => void;
- onSuspend: (member: Member) => void;
- onRemove: (member: Member) => void;
-}
-
-/** Roles a member can be reassigned to, in catalogue order. */
-const ROLE_OPTIONS = Object.keys(ROLE_LABEL) as RoleId[];
-
-export function MembersTable({
- members,
- onChangeRole,
- onSuspend,
- onRemove,
-}: MembersTableProps) {
- const { t } = useTranslation();
- const columns = useMemo<TableColumn<Member>[]>(
- () => [
- {
- key: "name",
- header: t("portal.users.table.member"),
- render: (m) => (
- <div className="portal-users__member-cell">
- <Avatar
- name={m.name}
- src={m.avatarUrl}
- size="sm"
- tone={avatarToneForRole(m.role)}
- />
- <div className="portal-users__member-text">
- <strong>{m.name}</strong>
- {/* Invited rows seed the name with the email, so don't repeat it. */}
- {m.email !== m.name && (
- <span className="portal-users__muted">{m.email}</span>
- )}
- </div>
- </div>
- ),
- },
- {
- key: "role",
- header: t("portal.users.table.role"),
- render: (m) => (
- <Chip accent={chipAccentForRole(m.role)} size="sm">
- {ROLE_LABEL[m.role]}
- </Chip>
- ),
- },
- {
- key: "status",
- header: t("portal.users.table.status"),
- render: (m) => (
- <StatusBadge
- tone={MEMBER_STATUS_TONE[m.status]}
- size="sm"
- pulse={m.status === "active"}
- >
- {m.status}
- </StatusBadge>
- ),
- },
- {
- key: "lastActive",
- header: t("portal.users.table.lastActive"),
- render: (m) => (
- <span className="portal-users__muted">{m.lastActive}</span>
- ),
- },
- {
- key: "actions",
- header: "",
- align: "right",
- width: "3rem",
- render: (m) => (
- // Mantine Menu owns the focus trap + roving arrow-key navigation that
- // a row-action menu needs; SUI has no equivalent.
- <Menu position="bottom-end" withinPortal shadow="md" width={200}>
- <Menu.Target>
- <ActionIcon
- className="portal-users__row-action"
- aria-label={t("portal.users.table.actionsFor", {
- name: m.name,
- })}
- onClick={(e) => e.stopPropagation()}
- variant="tertiary"
- >
- ⋯
- </ActionIcon>
- </Menu.Target>
- <Menu.Dropdown>
- <Menu.Label>{t("portal.users.table.changeRole")}</Menu.Label>
- {ROLE_OPTIONS.map((role) => (
- <Menu.Item
- key={role}
- disabled={role === m.role}
- onClick={() => onChangeRole(m, role)}
- >
- {ROLE_LABEL[role]}
- </Menu.Item>
- ))}
- <Menu.Divider />
- {m.status !== "suspended" && (
- <Menu.Item onClick={() => onSuspend(m)}>
- {t("portal.users.table.suspend")}
- </Menu.Item>
- )}
- <Menu.Item color="red" onClick={() => onRemove(m)}>
- {t("portal.users.table.remove")}
- </Menu.Item>
- </Menu.Dropdown>
- </Menu>
- ),
- },
- ],
- [t, onChangeRole, onSuspend, onRemove],
- );
-
- return (
- <Table<Member>
- className="portal-users__table"
- columns={columns}
- rows={members}
- rowKey={(m) => m.id}
- />
- );
-}
diff --git a/frontend/editor/src/portal/components/users/MoveToTeamModal.stories.tsx b/frontend/editor/src/portal/components/users/MoveToTeamModal.stories.tsx
new file mode 100644
index 0000000000..eb38c32c4c
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/MoveToTeamModal.stories.tsx
@@ -0,0 +1,38 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { MoveToTeamModal } from "@portal/components/users/MoveToTeamModal";
+import type { Member } from "@portal/api/users";
+import type { Team } from "@portal/api/teams";
+
+const MEMBER: Member = {
+ id: "3",
+ name: "Sarah Kowalski",
+ email: "[email protected]",
+ role: "member",
+ status: "active",
+ lastActive: "30m ago",
+ username: "sarah",
+ teamId: 2,
+};
+
+const TEAMS: Team[] = [
+ { id: 1, name: "Default", userCount: 4, owners: [] },
+ { id: 2, name: "Engineering", userCount: 3, owners: ["tom"] },
+ { id: 3, name: "Compliance", userCount: 2, owners: ["dana"] },
+];
+
+const meta: Meta<typeof MoveToTeamModal> = {
+ title: "Portal/Users/MoveToTeamModal",
+ component: MoveToTeamModal,
+ parameters: { layout: "fullscreen" },
+ args: {
+ open: true,
+ member: MEMBER,
+ teams: TEAMS,
+ onClose: () => {},
+ onDone: () => {},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof MoveToTeamModal>;
+
+export const Default: Story = {};
diff --git a/frontend/editor/src/portal/components/users/MoveToTeamModal.tsx b/frontend/editor/src/portal/components/users/MoveToTeamModal.tsx
new file mode 100644
index 0000000000..b9a56ab9c5
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/MoveToTeamModal.tsx
@@ -0,0 +1,94 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button, FormField, Modal, Select } from "@app/ui";
+import { moveMemberToTeam, type Member } from "@portal/api/users";
+import type { Team } from "@portal/api/teams";
+import { errorMessage } from "@portal/api/http";
+import "@portal/views/Users.css";
+
+interface MoveToTeamModalProps {
+ open: boolean;
+ member: Member | null;
+ teams: Team[];
+ onClose: () => void;
+ onDone: () => void;
+}
+
+/** Move a member to a different team (keeps their role). */
+export function MoveToTeamModal({
+ open,
+ member,
+ teams,
+ onClose,
+ onDone,
+}: MoveToTeamModalProps) {
+ const { t } = useTranslation();
+ const [teamId, setTeamId] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const options = teams
+ .filter((tm) => tm.id !== member?.teamId)
+ .map((tm) => ({ value: String(tm.id), label: tm.name }));
+
+ useEffect(() => {
+ if (!open) return;
+ const first = teams.find((tm) => tm.id !== member?.teamId);
+ setTeamId(first ? String(first.id) : "");
+ setError(null);
+ }, [open, teams, member]);
+
+ async function submit() {
+ if (!member || !teamId) return;
+ setSaving(true);
+ setError(null);
+ try {
+ await moveMemberToTeam(member, Number(teamId));
+ onDone();
+ onClose();
+ } catch (e) {
+ setError(errorMessage(e));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ width="sm"
+ title={t("users.moveTeam.title", "Move to team")}
+ subtitle={member?.name}
+ footer={
+ <div className="portal-users__modal-footer">
+ <Button variant="tertiary" size="sm" onClick={onClose}>
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => void submit()}
+ disabled={saving || !teamId}
+ >
+ {t("users.moveTeam.apply", "Move")}
+ </Button>
+ </div>
+ }
+ >
+ <div className="portal-users__invite-body">
+ <FormField label={t("users.moveTeam.team", "Team")}>
+ <Select
+ options={options}
+ value={teamId}
+ onChange={(value) => setTeamId(value ?? "")}
+ />
+ </FormField>
+ {error && (
+ <p className="portal-users__error" role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/portal/components/users/NewTeamModal.stories.tsx b/frontend/editor/src/portal/components/users/NewTeamModal.stories.tsx
new file mode 100644
index 0000000000..ce0b5409ce
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/NewTeamModal.stories.tsx
@@ -0,0 +1,18 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { NewTeamModal } from "@portal/components/users/NewTeamModal";
+
+const meta: Meta<typeof NewTeamModal> = {
+ title: "Portal/Users/NewTeamModal",
+ component: NewTeamModal,
+ parameters: { layout: "fullscreen" },
+ args: {
+ open: true,
+ onClose: () => {},
+ onCreated: () => {},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof NewTeamModal>;
+
+/** Create a team and (optionally) invite its owner. */
+export const Default: Story = {};
diff --git a/frontend/editor/src/portal/components/users/NewTeamModal.tsx b/frontend/editor/src/portal/components/users/NewTeamModal.tsx
new file mode 100644
index 0000000000..cc7cf26e81
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/NewTeamModal.tsx
@@ -0,0 +1,158 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button, FormField, Input, Modal } from "@app/ui";
+import { errorMessage } from "@portal/api/http";
+import { createTeam, fetchTeams, setTeamOwner } from "@portal/api/teams";
+import { fetchUsers, inviteMember } from "@portal/api/users";
+import { useTier } from "@portal/contexts/TierContext";
+import "@portal/views/Users.css";
+
+interface NewTeamModalProps {
+ open: boolean;
+ onClose: () => void;
+ /** Called after a team is created so the roster refetches. */
+ onCreated: () => void;
+}
+
+const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+/**
+ * Create a team and optionally invite its owner. The team is created first, so
+ * even if the owner invite needs mail (unavailable) the team still lands and an
+ * owner can be assigned from the roster.
+ */
+export function NewTeamModal({ open, onClose, onCreated }: NewTeamModalProps) {
+ const { t } = useTranslation();
+ const { tier } = useTier();
+ const [name, setName] = useState("");
+ const [ownerEmail, setOwnerEmail] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [note, setNote] = useState<string | null>(null);
+
+ function close() {
+ onClose();
+ setTimeout(() => {
+ setName("");
+ setOwnerEmail("");
+ setError(null);
+ setNote(null);
+ }, 200);
+ }
+
+ async function inviteOwner(teamName: string, email: string) {
+ const teams = await fetchTeams();
+ const team = teams.find((tm) => tm.name === teamName);
+ if (!team) return;
+ await inviteMember(email, "member", team.id);
+ const { members } = await fetchUsers(tier);
+ const owner = members.find(
+ (m) => m.email === email || m.username === email,
+ );
+ if (owner) await setTeamOwner(team.id, owner.id);
+ }
+
+ async function submit() {
+ setError(null);
+ setNote(null);
+ if (!name.trim()) {
+ setError(t("users.newTeam.nameRequired", "Team name is required"));
+ return;
+ }
+ const email = ownerEmail.trim();
+ if (email && !EMAIL_RE.test(email)) {
+ setError(t("users.newTeam.emailError", "Enter a valid email address"));
+ return;
+ }
+ setSaving(true);
+ try {
+ await createTeam(name.trim());
+ let ownerFailed = false;
+ if (email) {
+ try {
+ await inviteOwner(name.trim(), email);
+ } catch {
+ // Team is created; keep the modal open so this recovery note stays
+ // readable (owner invite needs mail, can be redone from the roster).
+ ownerFailed = true;
+ setNote(
+ t(
+ "users.newTeam.ownerFailed",
+ "Team created, but the owner couldn't be invited. Assign one from the roster.",
+ ),
+ );
+ }
+ }
+ onCreated();
+ if (!ownerFailed) close();
+ } catch (e) {
+ setError(errorMessage(e));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Modal
+ open={open}
+ onClose={close}
+ width="sm"
+ title={t("users.newTeam.title", "New team")}
+ subtitle={t(
+ "users.newTeam.subtitle",
+ "Group people under a Team Owner who manages their access.",
+ )}
+ footer={
+ <div className="portal-users__modal-footer">
+ <Button variant="tertiary" size="sm" onClick={close}>
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => void submit()}
+ disabled={saving || !name.trim()}
+ >
+ {t("users.newTeam.create", "Create team")}
+ </Button>
+ </div>
+ }
+ >
+ <div className="portal-users__invite-body">
+ <FormField label={t("users.newTeam.name", "Team name")} required>
+ <Input
+ placeholder={t("users.newTeam.namePlaceholder", "e.g. Finance")}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </FormField>
+ <FormField
+ label={t("users.newTeam.owner", "Team Owner")}
+ helperText={t(
+ "users.newTeam.ownerHelper",
+ "Every team has a leader. They'll be invited as Team Owner, with the Processor on, and can add the rest. You can reassign later.",
+ )}
+ >
+ <Input
+ type="email"
+ placeholder={t(
+ "users.newTeam.ownerPlaceholder",
+ )}
+ value={ownerEmail}
+ onChange={(e) => setOwnerEmail(e.target.value)}
+ />
+ </FormField>
+ {note && (
+ <p className="portal-users__form-note" role="status">
+ {note}
+ </p>
+ )}
+ {error && (
+ <p className="portal-users__error" role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/portal/components/users/RenameTeamModal.stories.tsx b/frontend/editor/src/portal/components/users/RenameTeamModal.stories.tsx
new file mode 100644
index 0000000000..6e8cba5aea
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/RenameTeamModal.stories.tsx
@@ -0,0 +1,19 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { RenameTeamModal } from "@portal/components/users/RenameTeamModal";
+
+const meta: Meta<typeof RenameTeamModal> = {
+ title: "Portal/Users/RenameTeamModal",
+ component: RenameTeamModal,
+ parameters: { layout: "fullscreen" },
+ args: {
+ open: true,
+ teamId: 2,
+ currentName: "Engineering",
+ onClose: () => {},
+ onDone: () => {},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof RenameTeamModal>;
+
+export const Default: Story = {};
diff --git a/frontend/editor/src/portal/components/users/RenameTeamModal.tsx b/frontend/editor/src/portal/components/users/RenameTeamModal.tsx
new file mode 100644
index 0000000000..d9f1f4b66c
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/RenameTeamModal.tsx
@@ -0,0 +1,83 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button, FormField, Input, Modal } from "@app/ui";
+import { renameTeam } from "@portal/api/teams";
+import { errorMessage } from "@portal/api/http";
+import "@portal/views/Users.css";
+
+interface RenameTeamModalProps {
+ open: boolean;
+ teamId: number | null;
+ currentName: string;
+ onClose: () => void;
+ onDone: () => void;
+}
+
+/** Rename a team. */
+export function RenameTeamModal({
+ open,
+ teamId,
+ currentName,
+ onClose,
+ onDone,
+}: RenameTeamModalProps) {
+ const { t } = useTranslation();
+ const [name, setName] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setName(currentName);
+ setError(null);
+ }, [open, currentName]);
+
+ async function submit() {
+ if (teamId == null || !name.trim()) return;
+ setSaving(true);
+ setError(null);
+ try {
+ await renameTeam(teamId, name.trim());
+ onDone();
+ onClose();
+ } catch (e) {
+ setError(errorMessage(e));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ width="sm"
+ title={t("users.renameTeam.title", "Rename team")}
+ footer={
+ <div className="portal-users__modal-footer">
+ <Button variant="tertiary" size="sm" onClick={onClose}>
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => void submit()}
+ disabled={saving || !name.trim()}
+ >
+ {t("users.renameTeam.apply", "Rename")}
+ </Button>
+ </div>
+ }
+ >
+ <div className="portal-users__invite-body">
+ <FormField label={t("users.renameTeam.name", "Team name")} required>
+ <Input value={name} onChange={(e) => setName(e.target.value)} />
+ </FormField>
+ {error && (
+ <p className="portal-users__error" role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/portal/components/users/ResetPasswordModal.stories.tsx b/frontend/editor/src/portal/components/users/ResetPasswordModal.stories.tsx
new file mode 100644
index 0000000000..24a6f58308
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/ResetPasswordModal.stories.tsx
@@ -0,0 +1,34 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ResetPasswordModal } from "@portal/components/users/ResetPasswordModal";
+import type { Member } from "@portal/api/users";
+
+const MEMBER: Member = {
+ id: "3",
+ name: "Sarah Kowalski",
+ email: "[email protected]",
+ role: "member",
+ status: "active",
+ lastActive: "30m ago",
+ username: "sarah",
+};
+
+const meta: Meta<typeof ResetPasswordModal> = {
+ title: "Portal/Users/ResetPasswordModal",
+ component: ResetPasswordModal,
+ parameters: { layout: "fullscreen" },
+ args: {
+ open: true,
+ member: MEMBER,
+ mailEnabled: false,
+ onClose: () => {},
+ onDone: () => {},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof ResetPasswordModal>;
+
+/** Auto-generate a secure password (copy + regenerate). */
+export const Default: Story = {};
+
+/** With SMTP configured, the admin can email the reset. */
+export const WithEmail: Story = { args: { mailEnabled: true } };
diff --git a/frontend/editor/src/portal/components/users/ResetPasswordModal.tsx b/frontend/editor/src/portal/components/users/ResetPasswordModal.tsx
new file mode 100644
index 0000000000..d1cfe9e739
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/ResetPasswordModal.tsx
@@ -0,0 +1,211 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button, Checkbox, FormField, Input, Modal } from "@app/ui";
+import { resetMemberPassword, type Member } from "@portal/api/users";
+import { errorMessage } from "@portal/api/http";
+import "@portal/views/Users.css";
+
+interface ResetPasswordModalProps {
+ open: boolean;
+ member: Member | null;
+ /** SMTP configured - gates the "email the password" options. */
+ mailEnabled: boolean;
+ onClose: () => void;
+ onDone: () => void;
+}
+
+const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+/** Cryptographically secure password with rejection sampling (no modulo bias). */
+function generatePassword(len = 16): string {
+ const chars =
+ "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789!@#$%^&*";
+ const max = Math.floor(256 / chars.length) * chars.length;
+ const out: string[] = [];
+ const buf = new Uint8Array(1);
+ while (out.length < len) {
+ crypto.getRandomValues(buf);
+ if (buf[0] < max) out.push(chars[buf[0] % chars.length]);
+ }
+ return out.join("");
+}
+
+/** Admin reset of a member's password: auto-generate (with copy) or set manually. */
+export function ResetPasswordModal({
+ open,
+ member,
+ mailEnabled,
+ onClose,
+ onDone,
+}: ResetPasswordModalProps) {
+ const { t } = useTranslation();
+ const [autoGenerate, setAutoGenerate] = useState(true);
+ const [generated, setGenerated] = useState("");
+ const [password, setPassword] = useState("");
+ const [confirm, setConfirm] = useState("");
+ const [forceChange, setForceChange] = useState(true);
+ const [sendEmail, setSendEmail] = useState(false);
+ const [includePassword, setIncludePassword] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const canEmail = mailEnabled && EMAIL_RE.test(member?.email ?? "");
+
+ useEffect(() => {
+ if (!open) return;
+ setAutoGenerate(true);
+ setGenerated(generatePassword());
+ setPassword("");
+ setConfirm("");
+ setForceChange(true);
+ setSendEmail(false);
+ setIncludePassword(false);
+ setCopied(false);
+ setError(null);
+ }, [open]);
+
+ function copy() {
+ void navigator.clipboard?.writeText(generated)?.then(() => setCopied(true));
+ }
+
+ async function submit() {
+ if (!member) return;
+ setError(null);
+ const newPassword = autoGenerate ? generated : password;
+ if (!autoGenerate) {
+ if (newPassword.length < 8) {
+ setError(
+ t("users.resetPw.tooShort", "Password must be at least 8 characters"),
+ );
+ return;
+ }
+ if (newPassword !== confirm) {
+ setError(t("users.resetPw.mismatch", "Passwords do not match"));
+ return;
+ }
+ }
+ setSaving(true);
+ try {
+ await resetMemberPassword(member, {
+ newPassword,
+ forcePasswordChange: forceChange,
+ sendEmail: canEmail && sendEmail,
+ includePassword: canEmail && sendEmail && includePassword,
+ });
+ onDone();
+ onClose();
+ } catch (e) {
+ setError(errorMessage(e));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ width="sm"
+ title={t("users.resetPw.title", "Reset password")}
+ subtitle={member?.name}
+ footer={
+ <div className="portal-users__modal-footer">
+ <Button variant="tertiary" size="sm" onClick={onClose}>
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button size="sm" onClick={() => void submit()} disabled={saving}>
+ {t("users.resetPw.apply", "Reset password")}
+ </Button>
+ </div>
+ }
+ >
+ <div className="portal-users__invite-body">
+ <Checkbox
+ checked={autoGenerate}
+ onChange={(e) => setAutoGenerate(e.target.checked)}
+ label={t("users.resetPw.generate", "Generate a secure password")}
+ />
+
+ {autoGenerate ? (
+ <FormField
+ label={t("users.resetPw.newPassword", "New password")}
+ helperText={
+ copied
+ ? t("users.resetPw.copied", "Copied to clipboard")
+ : t(
+ "users.resetPw.copyHint",
+ "Copy this now - it won't be shown again.",
+ )
+ }
+ >
+ <div className="portal-users__pw-row">
+ <Input value={generated} readOnly />
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => setGenerated(generatePassword())}
+ >
+ {t("users.resetPw.regen", "Regenerate")}
+ </Button>
+ <Button variant="secondary" size="sm" onClick={copy}>
+ {t("common.copy", "Copy")}
+ </Button>
+ </div>
+ </FormField>
+ ) : (
+ <>
+ <FormField label={t("users.resetPw.newPassword", "New password")}>
+ <Input
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </FormField>
+ <FormField label={t("users.resetPw.confirm", "Confirm password")}>
+ <Input
+ type="password"
+ value={confirm}
+ onChange={(e) => setConfirm(e.target.value)}
+ />
+ </FormField>
+ </>
+ )}
+
+ <Checkbox
+ checked={forceChange}
+ onChange={(e) => setForceChange(e.target.checked)}
+ label={t(
+ "users.resetPw.forceChange",
+ "Require a password change on next login",
+ )}
+ />
+
+ {canEmail && (
+ <>
+ <Checkbox
+ checked={sendEmail}
+ onChange={(e) => setSendEmail(e.target.checked)}
+ label={t("users.resetPw.email", "Email the user about the reset")}
+ />
+ <Checkbox
+ checked={includePassword}
+ disabled={!sendEmail}
+ onChange={(e) => setIncludePassword(e.target.checked)}
+ label={t(
+ "users.resetPw.includePw",
+ "Include the new password in the email",
+ )}
+ />
+ </>
+ )}
+
+ {error && (
+ <p className="portal-users__error" role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/portal/components/users/RolesGrid.stories.tsx b/frontend/editor/src/portal/components/users/RolesGrid.stories.tsx
deleted file mode 100644
index 386e61fc99..0000000000
--- a/frontend/editor/src/portal/components/users/RolesGrid.stories.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import { ROLES } from "@portal/mocks/users";
-import { RolesGrid } from "@portal/components/users/RolesGrid";
-
-const meta: Meta<typeof RolesGrid> = {
- title: "Portal/Users/RolesGrid",
- component: RolesGrid,
- parameters: { layout: "padded" },
- args: { roles: ROLES },
-};
-export default meta;
-type Story = StoryObj<typeof RolesGrid>;
-
-/** The five org roles, most → least privileged. */
-export const Default: Story = {};
diff --git a/frontend/editor/src/portal/components/users/RolesGrid.tsx b/frontend/editor/src/portal/components/users/RolesGrid.tsx
deleted file mode 100644
index 24527f35be..0000000000
--- a/frontend/editor/src/portal/components/users/RolesGrid.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { Card, Chip } from "@app/ui";
-import type { Role } from "@portal/api/users";
-import { chipAccentForRole } from "@portal/components/users/format";
-import "@portal/views/Users.css";
-
-interface RolesGridProps {
- roles: Role[];
-}
-
-/** Reference catalogue of the org roles and what each one can do. */
-export function RolesGrid({ roles }: RolesGridProps) {
- const { t } = useTranslation();
- return (
- <section className="portal-users__roles">
- <header className="portal-users__section-head">
- <h2 className="portal-users__section-title">
- {t("portal.users.roles.title")}
- </h2>
- <p className="portal-users__section-sub">
- {t("portal.users.roles.subtitle")}
- </p>
- </header>
- <div className="portal-users__roles-grid">
- {roles.map((role) => (
- <Card key={role.id} padding="default" className="portal-users__role">
- <div className="portal-users__role-head">
- <Chip accent={chipAccentForRole(role.id)} size="sm">
- {role.label}
- </Chip>
- </div>
- <p className="portal-users__role-summary">{role.summary}</p>
- <ul className="portal-users__role-perms">
- {role.permissions.map((perm) => (
- <li key={perm}>{perm}</li>
- ))}
- </ul>
- </Card>
- ))}
- </div>
- </section>
- );
-}
diff --git a/frontend/editor/src/portal/components/users/UsersDirectory.stories.tsx b/frontend/editor/src/portal/components/users/UsersDirectory.stories.tsx
new file mode 100644
index 0000000000..b7fb277854
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/UsersDirectory.stories.tsx
@@ -0,0 +1,324 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { UsersDirectory } from "@portal/components/users/UsersDirectory";
+import type { Member } from "@portal/api/users";
+import type { Team } from "@portal/api/teams";
+import type { UsersCapabilities } from "@portal/api/usersCapabilities";
+
+/** Self-hosted org-admin: the full action set. */
+const FULL_CAPS: UsersCapabilities = {
+ orgGroup: true,
+ changeRole: true,
+ adminRole: true,
+ createTeam: true,
+ deleteTeam: true,
+ renameTeam: true,
+ emailInvite: true,
+ directCreate: true,
+ resetPassword: true,
+ unlock: true,
+ resetMfa: true,
+ suspend: true,
+ moveTeam: true,
+ seats: false,
+ manageGrants: true,
+ removeScope: "org",
+};
+
+/** SaaS team-leader: invite / rename / remove-member only, no org group. */
+const SAAS_CAPS: UsersCapabilities = {
+ orgGroup: false,
+ changeRole: false,
+ adminRole: false,
+ createTeam: false,
+ deleteTeam: false,
+ renameTeam: true,
+ emailInvite: true,
+ directCreate: false,
+ resetPassword: false,
+ unlock: false,
+ resetMfa: false,
+ suspend: false,
+ moveTeam: false,
+ seats: true,
+ manageGrants: false,
+ removeScope: "team",
+};
+
+/** A full org: one org owner and two teams, each with a leader. */
+const MEMBERS: Member[] = [
+ {
+ id: "1",
+ name: "Matt Joseph",
+ email: "[email protected]",
+ role: "admin",
+ status: "active",
+ lastActive: "Now",
+ username: "matt",
+ teamId: 1,
+ teamName: "Default",
+ isSelf: true,
+ portalAccess: "admin",
+ },
+ {
+ id: "2",
+ name: "Tom Reilly",
+ email: "[email protected]",
+ role: "team_owner",
+ status: "active",
+ lastActive: "12m ago",
+ username: "tom",
+ teamId: 2,
+ teamName: "Engineering",
+ teamLead: true,
+ portalAccess: "role",
+ },
+ {
+ id: "3",
+ name: "Sarah Kowalski",
+ email: "[email protected]",
+ role: "member",
+ status: "active",
+ lastActive: "30m ago",
+ username: "sarah",
+ teamId: 2,
+ teamName: "Engineering",
+ portalAccess: "granted",
+ portalGrantId: 10,
+ },
+ {
+ id: "4",
+ name: "Priya Patel",
+ email: "[email protected]",
+ role: "member",
+ status: "active",
+ lastActive: "Never",
+ username: "priya",
+ teamId: 2,
+ teamName: "Engineering",
+ portalAccess: "none",
+ },
+ {
+ id: "5",
+ name: "Dana Okafor",
+ email: "[email protected]",
+ role: "team_owner",
+ status: "active",
+ lastActive: "1h ago",
+ username: "dana",
+ teamId: 3,
+ teamName: "Compliance",
+ teamLead: true,
+ portalAccess: "role",
+ },
+ {
+ id: "6",
+ name: "Lars Eriksson",
+ email: "[email protected]",
+ role: "member",
+ status: "active",
+ lastActive: "3h ago",
+ username: "lars",
+ teamId: 3,
+ teamName: "Compliance",
+ portalAccess: "granted",
+ portalGrantId: 11,
+ },
+];
+
+/** An external guest (parked concept, shown via showGuests). */
+const GUEST: Member = {
+ id: "7",
+ name: "Meridian Legal",
+ email: "[email protected]",
+ role: "guest",
+ status: "active",
+ lastActive: "2d ago",
+ username: "legal",
+ teamId: 1,
+ teamName: "Default",
+ portalAccess: "none",
+};
+
+/** Members exercising the status states: suspended, locked, and MFA-enrolled. */
+const STATE_MEMBERS: Member[] = [
+ {
+ id: "1",
+ name: "Matt Joseph",
+ email: "[email protected]",
+ role: "admin",
+ status: "active",
+ lastActive: "Now",
+ username: "matt",
+ teamId: 1,
+ teamName: "Default",
+ isSelf: true,
+ portalAccess: "admin",
+ },
+ {
+ id: "s1",
+ name: "Nadia Costa",
+ email: "[email protected]",
+ role: "member",
+ status: "suspended",
+ lastActive: "12 days ago",
+ username: "nadia",
+ teamId: 2,
+ teamName: "Engineering",
+ portalAccess: "none",
+ },
+ {
+ id: "s2",
+ name: "Leo Fischer",
+ email: "[email protected]",
+ role: "member",
+ status: "active",
+ lastActive: "1h ago",
+ username: "leo",
+ teamId: 2,
+ teamName: "Engineering",
+ portalAccess: "granted",
+ portalGrantId: 20,
+ locked: true,
+ },
+ {
+ id: "s3",
+ name: "Aisha Rahman",
+ email: "[email protected]",
+ role: "team_owner",
+ status: "active",
+ lastActive: "3m ago",
+ username: "aisha",
+ teamId: 2,
+ teamName: "Engineering",
+ teamLead: true,
+ portalAccess: "role",
+ mfaEnabled: true,
+ },
+];
+
+/** A big team (>8) to exercise the "Show all" / "Show less" expander. */
+const BIG_MEMBERS: Member[] = [
+ {
+ id: "b0",
+ name: "Matt Joseph",
+ email: "[email protected]",
+ role: "admin",
+ status: "active",
+ lastActive: "Now",
+ username: "matt",
+ teamId: 1,
+ isSelf: true,
+ portalAccess: "admin",
+ },
+ ...Array.from(
+ { length: 11 },
+ (_, i): Member => ({
+ id: `big-${i}`,
+ name: `Teammate ${i + 1}`,
+ email: `teammate${i + 1}@acme.com`,
+ role: i === 0 ? "team_owner" : "member",
+ status: "active",
+ lastActive: `${i + 1}h ago`,
+ username: `tm${i + 1}`,
+ teamId: 9,
+ teamName: "Platform",
+ teamLead: i === 0,
+ portalAccess: i === 0 ? "role" : "none",
+ }),
+ ),
+];
+
+const TEAMS: Team[] = [
+ { id: 2, name: "Engineering", userCount: 3, owners: ["tom"] },
+ { id: 3, name: "Compliance", userCount: 2, owners: ["dana"] },
+];
+
+const meta: Meta<typeof UsersDirectory> = {
+ title: "Portal/Users/UsersDirectory",
+ component: UsersDirectory,
+ parameters: { layout: "padded" },
+ args: {
+ members: MEMBERS,
+ teams: TEAMS,
+ capabilities: FULL_CAPS,
+ onChangeRole: () => {},
+ onGrantProcessor: () => {},
+ onRevokeProcessor: () => {},
+ processorTeamIds: new Set<number>(),
+ onGrantTeamProcessor: () => {},
+ onRevokeTeamProcessor: () => {},
+ onAddToTeam: () => {},
+ onResetPassword: () => {},
+ onMoveToTeam: () => {},
+ onToggleEnabled: () => {},
+ onUnlock: () => {},
+ onDisableMfa: () => {},
+ onRemove: () => {},
+ onRenameTeam: () => {},
+ onDeleteTeam: () => {},
+ // Documents the intended "Approves policy" chip; hidden in the live app.
+ showApprover: true,
+ },
+};
+export default meta;
+type Story = StoryObj<typeof UsersDirectory>;
+
+/** Organization owner plus two teams, each with a leader. */
+export const Default: Story = {};
+
+/**
+ * SaaS build (team-leader scope): no Organization group, no role select, no
+ * password/suspend actions - just invite / rename / remove-from-team.
+ */
+export const SaasTeamLeader: Story = {
+ args: {
+ members: MEMBERS.filter((m) => m.role !== "admin"),
+ capabilities: SAAS_CAPS,
+ },
+};
+
+/** A solo workspace: just the org owner, no teams yet. */
+export const OrgOnly: Story = {
+ args: { members: MEMBERS.filter((m) => m.role === "admin"), teams: [] },
+};
+
+/** A team with a team-wide Processor grant: every member inherits it (solid, non-removable). */
+export const TeamWideProcessor: Story = {
+ args: {
+ members: MEMBERS.map((m) =>
+ m.teamId === 2 && m.role === "member"
+ ? { ...m, portalAccess: "team" as const, portalGrantId: undefined }
+ : m,
+ ),
+ processorTeamIds: new Set<number>([2]),
+ },
+};
+
+/** One team, mixed Processor access (implicit, granted, and not granted). */
+export const SingleTeam: Story = {
+ args: {
+ members: MEMBERS.filter((m) => m.teamId === 2 || m.role === "admin"),
+ teams: TEAMS.filter((t) => t.id === 2),
+ },
+};
+
+/** Guests group + "Guest" role option (parked in the live app; behind showGuests). */
+export const WithGuests: Story = {
+ args: { members: [...MEMBERS, GUEST], showGuests: true },
+};
+
+/** Suspended / locked / MFA-enrolled members show inline tags and gated kebab actions. */
+export const MemberStates: Story = {
+ args: {
+ members: STATE_MEMBERS,
+ teams: TEAMS.filter((t) => t.id === 2),
+ },
+};
+
+/** A team past the collapse limit surfaces the "Show all" expander. */
+export const LargeTeam: Story = {
+ args: {
+ members: BIG_MEMBERS,
+ teams: [{ id: 9, name: "Platform", userCount: 11, owners: ["tm1"] }],
+ },
+};
diff --git a/frontend/editor/src/portal/components/users/UsersDirectory.tsx b/frontend/editor/src/portal/components/users/UsersDirectory.tsx
new file mode 100644
index 0000000000..1419026453
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/UsersDirectory.tsx
@@ -0,0 +1,478 @@
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Menu } from "@mantine/core";
+import PersonAddAltRounded from "@mui/icons-material/PersonAddAltRounded";
+import { Avatar, Chip, Select } from "@app/ui";
+import { type Member, type RoleId } from "@portal/api/users";
+import type { Team } from "@portal/api/teams";
+import type { UsersCapabilities } from "@portal/api/usersCapabilities";
+import { avatarToneForMember } from "@portal/components/users/format";
+import {
+ buildDirectory,
+ type TeamGroup,
+} from "@portal/components/users/directory";
+import "@portal/views/Users.css";
+
+/** Collapse a group's rows past this many, behind a "Show all" expander. */
+const COLLAPSED_LIMIT = 8;
+
+/** Teams that can't be renamed/deleted (system-managed). */
+const SYSTEM_TEAMS = new Set(["Default", "Internal"]);
+
+interface UsersDirectoryProps {
+ members: Member[];
+ teams: Team[];
+ /** Flavor-specific action set (self-hosted org-admin vs SaaS team-leader). */
+ capabilities: UsersCapabilities;
+ onChangeRole: (member: Member, role: RoleId) => void;
+ onGrantProcessor: (member: Member) => void;
+ onRevokeProcessor: (member: Member) => void;
+ /** Team ids holding a team-wide Processor grant; members inherit it. */
+ processorTeamIds: Set<number>;
+ onGrantTeamProcessor: (team: TeamGroup) => void;
+ onRevokeTeamProcessor: (team: TeamGroup) => void;
+ onAddToTeam: (team: TeamGroup) => void;
+ // Per-member admin actions (the row kebab).
+ onResetPassword: (member: Member) => void;
+ onMoveToTeam: (member: Member) => void;
+ onToggleEnabled: (member: Member) => void;
+ onUnlock: (member: Member) => void;
+ onDisableMfa: (member: Member) => void;
+ onRemove: (member: Member) => void;
+ // Team actions (the team-header kebab).
+ onRenameTeam: (team: TeamGroup) => void;
+ onDeleteTeam: (team: TeamGroup) => void;
+ /**
+ * Show the "Approves policy" capability chip on org owners. Off in the live
+ * app (no backend for it yet); on in Storybook to document the intended design.
+ */
+ showApprover?: boolean;
+ /**
+ * Show the Guests group + the "Guest" role option. Off in the live app (the
+ * Guest concept is parked); on in Storybook to document the intended design.
+ */
+ showGuests?: boolean;
+}
+
+/**
+ * The people roster, grouped like the org chart: Organization owners, then each
+ * team (with its leader), each row carrying capability chips, a role selector,
+ * and a kebab of admin actions. Long groups collapse behind a "Show all" so big
+ * orgs stay scannable.
+ */
+export function UsersDirectory({
+ members,
+ teams,
+ capabilities,
+ onChangeRole,
+ onGrantProcessor,
+ onRevokeProcessor,
+ processorTeamIds,
+ onGrantTeamProcessor,
+ onRevokeTeamProcessor,
+ onAddToTeam,
+ onResetPassword,
+ onMoveToTeam,
+ onToggleEnabled,
+ onUnlock,
+ onDisableMfa,
+ onRemove,
+ onRenameTeam,
+ onDeleteTeam,
+ showApprover = false,
+ showGuests = false,
+}: UsersDirectoryProps) {
+ const { t } = useTranslation();
+ const dir = useMemo(() => buildDirectory(members, teams), [members, teams]);
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
+
+ const nameByUsername = useMemo(() => {
+ const m = new Map<string, string>();
+ for (const member of members) {
+ if (member.username) m.set(member.username, member.name);
+ }
+ return m;
+ }, [members]);
+
+ const roleOptions: { value: RoleId; label: string }[] = [
+ // No SaaS user is ever ROLE_ADMIN, so the Org Owner option is dropped there.
+ ...(capabilities.adminRole
+ ? [
+ {
+ value: "admin" as RoleId,
+ label: t("users.role.orgOwner", "Org Owner"),
+ },
+ ]
+ : []),
+ { value: "team_owner", label: t("users.role.teamOwner", "Team Owner") },
+ { value: "member", label: t("users.role.member", "Member") },
+ ...(showGuests
+ ? [{ value: "guest" as RoleId, label: t("users.role.guest", "Guest") }]
+ : []),
+ ];
+
+ function toggleExpand(key: string) {
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ }
+
+ function ownerNames(owners: string[]): string {
+ return owners.map((u) => nameByUsername.get(u) ?? u).join(", ");
+ }
+
+ // Whether the team-header kebab has any actions (else it isn't rendered).
+ function teamKebabHasItems(team: TeamGroup): boolean {
+ return (
+ capabilities.manageGrants ||
+ (!SYSTEM_TEAMS.has(team.name) &&
+ (capabilities.renameTeam || capabilities.deleteTeam))
+ );
+ }
+
+ // Whether any action sits above the "Remove" item (so we render a divider).
+ function rowKebabHasUpperActions(m: Member): boolean {
+ return (
+ capabilities.resetPassword ||
+ capabilities.moveTeam ||
+ capabilities.suspend ||
+ (capabilities.unlock && !!m.locked) ||
+ (capabilities.resetMfa && !!m.mfaEnabled)
+ );
+ }
+
+ function rowKebab(m: Member) {
+ // Removal is org-delete (admin-only) - the only backed path. SaaS "remove from
+ // team" has no endpoint, so don't offer a control that would 403 or org-delete.
+ const canRemove = capabilities.removeScope === "org";
+ if (!rowKebabHasUpperActions(m) && !canRemove) return null;
+ return (
+ <Menu position="bottom-end" withinPortal shadow="md" width={210}>
+ <Menu.Target>
+ <button
+ type="button"
+ className="portal-users__row-kebab"
+ aria-label={t("users.rowActions", "Actions for {{name}}", {
+ name: m.name,
+ })}
+ >
+ ⋯
+ </button>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {capabilities.resetPassword && (
+ <Menu.Item disabled={m.isSelf} onClick={() => onResetPassword(m)}>
+ {t("users.action.resetPw", "Reset password")}
+ </Menu.Item>
+ )}
+ {capabilities.moveTeam && (
+ <Menu.Item onClick={() => onMoveToTeam(m)}>
+ {t("users.action.move", "Move to team")}
+ </Menu.Item>
+ )}
+ {capabilities.suspend && (
+ <Menu.Item disabled={m.isSelf} onClick={() => onToggleEnabled(m)}>
+ {m.status === "suspended"
+ ? t("users.action.reinstate", "Reinstate")
+ : t("users.action.suspend", "Suspend")}
+ </Menu.Item>
+ )}
+ {capabilities.unlock && m.locked && (
+ <Menu.Item onClick={() => onUnlock(m)}>
+ {t("users.action.unlock", "Unlock account")}
+ </Menu.Item>
+ )}
+ {capabilities.resetMfa && m.mfaEnabled && (
+ <Menu.Item disabled={m.isSelf} onClick={() => onDisableMfa(m)}>
+ {t("users.action.disableMfa", "Reset MFA")}
+ </Menu.Item>
+ )}
+ {canRemove && rowKebabHasUpperActions(m) && <Menu.Divider />}
+ {canRemove && (
+ <Menu.Item
+ color="red"
+ disabled={m.isSelf}
+ onClick={() => onRemove(m)}
+ >
+ {t("users.action.remove", "Remove from org")}
+ </Menu.Item>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ );
+ }
+
+ function renderRow(m: Member) {
+ const access = m.portalAccess ?? "none";
+ return (
+ <div className="portal-users__row" key={m.id}>
+ <div className="portal-users__row-main">
+ <Avatar name={m.name} size="sm" tone={avatarToneForMember(m)} />
+ <div className="portal-users__row-id">
+ <span className="portal-users__row-name">
+ {m.name}
+ {m.isSelf && (
+ <span className="portal-users__row-you">
+ {" "}
+ {t("users.you", "(you)")}
+ </span>
+ )}
+ {m.status === "suspended" && (
+ <Chip
+ accent="danger"
+ size="sm"
+ className="portal-users__row-tag"
+ >
+ {t("users.suspended", "Suspended")}
+ </Chip>
+ )}
+ {m.locked && (
+ <Chip
+ accent="warning"
+ size="sm"
+ className="portal-users__row-tag"
+ >
+ {t("users.locked", "Locked")}
+ </Chip>
+ )}
+ </span>
+ {m.email !== m.name && (
+ <span className="portal-users__row-email">{m.email}</span>
+ )}
+ </div>
+ </div>
+
+ <div className="portal-users__caps">
+ <Chip accent="neutral" size="sm">
+ {t("users.cap.editor", "Editor")}
+ </Chip>
+ {access === "granted" ? (
+ <Chip
+ accent="default"
+ size="sm"
+ onRemove={
+ capabilities.manageGrants
+ ? () => onRevokeProcessor(m)
+ : undefined
+ }
+ >
+ {t("users.cap.processor", "Processor")}
+ </Chip>
+ ) : access !== "none" ? (
+ // admin / team-owner role / inherited from a team-wide grant
+ <Chip accent="default" size="sm">
+ {t("users.cap.processor", "Processor")}
+ </Chip>
+ ) : capabilities.manageGrants ? (
+ <Chip
+ accent="neutral"
+ size="sm"
+ dashed
+ onClick={() => onGrantProcessor(m)}
+ >
+ {t("users.cap.addProcessor", "+ Processor")}
+ </Chip>
+ ) : null}
+ {showApprover && m.role === "admin" && (
+ <Chip
+ accent="success"
+ size="sm"
+ leadingIcon={<span aria-hidden>✓</span>}
+ >
+ {t("users.cap.approver", "Approves policy")}
+ </Chip>
+ )}
+ </div>
+
+ <span
+ className="portal-users__row-active"
+ title={t("users.lastActive", "Last active")}
+ >
+ {m.lastActive}
+ </span>
+
+ {capabilities.changeRole && (
+ <div className="portal-users__row-role">
+ <Select
+ aria-label={t("users.roleFor", "Role for {{name}}", {
+ name: m.name,
+ })}
+ options={roleOptions}
+ value={m.role}
+ disabled={m.isSelf}
+ onChange={(value) => onChangeRole(m, (value ?? m.role) as RoleId)}
+ />
+ </div>
+ )}
+
+ {rowKebab(m)}
+ </div>
+ );
+ }
+
+ /** Rows for a group, collapsing past COLLAPSED_LIMIT behind a toggle. */
+ function renderMembers(list: Member[], key: string) {
+ const isOpen = expanded.has(key);
+ const overflow = list.length > COLLAPSED_LIMIT;
+ const shown = overflow && !isOpen ? list.slice(0, COLLAPSED_LIMIT) : list;
+ return (
+ <>
+ {shown.map(renderRow)}
+ {overflow && (
+ <button
+ type="button"
+ className="portal-users__show-more"
+ onClick={() => toggleExpand(key)}
+ >
+ {isOpen
+ ? t("users.showLess", "Show less")
+ : t("users.showAll", "Show all {{count}}", {
+ count: list.length,
+ })}
+ </button>
+ )}
+ </>
+ );
+ }
+
+ return (
+ <div className="portal-users__directory">
+ {/* Organization (a single-org deployment only; SaaS has no org). */}
+ {capabilities.orgGroup && dir.organization.length > 0 && (
+ <section className="portal-users__group">
+ <header className="portal-users__group-head">
+ <div className="portal-users__group-title">
+ <strong>{t("users.group.org", "Organization")}</strong>
+ <span className="portal-users__group-desc">
+ {t(
+ "users.group.orgDesc",
+ "Owners with org-wide authority and policy approval",
+ )}
+ </span>
+ </div>
+ <span className="portal-users__group-count">
+ {t("users.group.owners", "{{count}} owner", {
+ count: dir.organization.length,
+ })}
+ </span>
+ </header>
+ {renderMembers(dir.organization, "org")}
+ </section>
+ )}
+
+ {/* Teams */}
+ {dir.teams.map((team) => (
+ <section className="portal-users__group" key={team.id}>
+ <header className="portal-users__group-head">
+ <div className="portal-users__group-title">
+ <strong>
+ {t("users.group.team", "{{name}} team", { name: team.name })}
+ </strong>
+ <span className="portal-users__group-desc">
+ {t("users.group.teamMeta", "{{count}} people", {
+ count: team.members.length,
+ })}
+ {team.owners.length > 0 &&
+ ` · ${t("users.group.ledBy", "led by {{owner}}", {
+ owner: ownerNames(team.owners),
+ })}`}
+ </span>
+ </div>
+ <div className="portal-users__group-actions">
+ <button
+ type="button"
+ className="portal-users__group-action"
+ onClick={() => onAddToTeam(team)}
+ >
+ <PersonAddAltRounded sx={{ fontSize: 15 }} />
+ {t("users.group.addToTeam", "Add to team")}
+ </button>
+ {teamKebabHasItems(team) && (
+ <Menu
+ position="bottom-end"
+ withinPortal
+ shadow="md"
+ width={210}
+ >
+ <Menu.Target>
+ <button
+ type="button"
+ className="portal-users__row-kebab"
+ aria-label={t("users.teamActions", "Team actions")}
+ >
+ ⋯
+ </button>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {capabilities.manageGrants &&
+ (processorTeamIds.has(team.id) ? (
+ <Menu.Item onClick={() => onRevokeTeamProcessor(team)}>
+ {t(
+ "users.team.revokeProcessor",
+ "Revoke Processor from team",
+ )}
+ </Menu.Item>
+ ) : (
+ <Menu.Item onClick={() => onGrantTeamProcessor(team)}>
+ {t(
+ "users.team.grantProcessor",
+ "Grant Processor to team",
+ )}
+ </Menu.Item>
+ ))}
+ {!SYSTEM_TEAMS.has(team.name) &&
+ (capabilities.renameTeam || capabilities.deleteTeam) && (
+ <>
+ {capabilities.manageGrants && <Menu.Divider />}
+ {capabilities.renameTeam && (
+ <Menu.Item onClick={() => onRenameTeam(team)}>
+ {t("users.action.rename", "Rename team")}
+ </Menu.Item>
+ )}
+ {capabilities.deleteTeam && (
+ <Menu.Item
+ color="red"
+ onClick={() => onDeleteTeam(team)}
+ >
+ {t("users.action.deleteTeam", "Delete team")}
+ </Menu.Item>
+ )}
+ </>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ )}
+ </div>
+ </header>
+ {renderMembers(team.members, `team-${team.id}`)}
+ </section>
+ ))}
+
+ {/* Guests (parked in the live app; shown when showGuests is set). */}
+ {showGuests && dir.guests.length > 0 && (
+ <section className="portal-users__group">
+ <header className="portal-users__group-head">
+ <div className="portal-users__group-title">
+ <strong>{t("users.group.guests", "Guests")}</strong>
+ <span className="portal-users__group-desc">
+ {t(
+ "users.group.guestsDesc",
+ "External collaborators, scoped to what you shared. Editor only.",
+ )}
+ </span>
+ </div>
+ <span className="portal-users__group-count">
+ {t("users.group.guestCount", "{{count}} guest", {
+ count: dir.guests.length,
+ })}
+ </span>
+ </header>
+ {renderMembers(dir.guests, "guests")}
+ </section>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/portal/components/users/UsersSummaryStrip.stories.tsx b/frontend/editor/src/portal/components/users/UsersSummaryStrip.stories.tsx
deleted file mode 100644
index d1e44ff72b..0000000000
--- a/frontend/editor/src/portal/components/users/UsersSummaryStrip.stories.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import { buildUsersResponse } from "@portal/mocks/users";
-import { UsersSummaryStrip } from "@portal/components/users/UsersSummaryStrip";
-
-const meta: Meta<typeof UsersSummaryStrip> = {
- title: "Portal/Users/UsersSummaryStrip",
- component: UsersSummaryStrip,
- parameters: { layout: "padded" },
-};
-export default meta;
-type Story = StoryObj<typeof UsersSummaryStrip>;
-
-export const Pro: Story = {
- args: { data: buildUsersResponse("pro"), loading: false },
-};
-
-/** Enterprise shows unlimited seats. */
-export const Enterprise: Story = {
- args: { data: buildUsersResponse("enterprise"), loading: false },
-};
-
-/** Free sits near its seat ceiling. */
-export const Free: Story = {
- args: { data: buildUsersResponse("free"), loading: false },
-};
-
-/** Loading collapses every card to the placeholder dash. */
-export const Loading: Story = {
- args: { data: null, loading: true },
-};
diff --git a/frontend/editor/src/portal/components/users/UsersSummaryStrip.tsx b/frontend/editor/src/portal/components/users/UsersSummaryStrip.tsx
deleted file mode 100644
index 981b1fca52..0000000000
--- a/frontend/editor/src/portal/components/users/UsersSummaryStrip.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { MetricCard, MetricStrip } from "@app/ui";
-import type { UsersResponse } from "@portal/api/users";
-import { seatsLabel } from "@portal/components/users/format";
-
-/**
- * Stable identifiers for the KPI tiles. They keep the strip's structure
- * constant across loading / empty / ready states; only the values flow from
- * the API and the displayed labels come from the locale.
- */
-const KPI_KEYS = ["members", "pendingInvites", "seatsUsed"] as const;
-
-interface UsersSummaryStripProps {
- data: UsersResponse | null;
- loading: boolean;
-}
-
-export function UsersSummaryStrip({ data, loading }: UsersSummaryStripProps) {
- const { t } = useTranslation();
- const summary = loading ? undefined : data?.summary;
-
- const values: Record<(typeof KPI_KEYS)[number], string | number> = {
- members: summary?.totalMembers ?? "—",
- pendingInvites: summary?.pendingInvites ?? "—",
- seatsUsed: summary ? seatsLabel(summary.seatsUsed, summary.seatLimit) : "—",
- };
-
- return (
- <MetricStrip>
- {KPI_KEYS.map((key) => (
- <MetricCard
- key={key}
- label={t(`portal.users.summary.${key}`)}
- value={values[key]}
- />
- ))}
- </MetricStrip>
- );
-}
diff --git a/frontend/editor/src/portal/components/users/directory.ts b/frontend/editor/src/portal/components/users/directory.ts
new file mode 100644
index 0000000000..a2663a681a
--- /dev/null
+++ b/frontend/editor/src/portal/components/users/directory.ts
@@ -0,0 +1,50 @@
+import type { Member } from "@portal/api/users";
+import type { Team } from "@portal/api/teams";
+
+/** One team section in the roster: the team, its owners, and its members. */
+export interface TeamGroup {
+ id: number;
+ name: string;
+ /** Usernames of the team owners (resolved to display names by the UI). */
+ owners: string[];
+ members: Member[];
+}
+
+/** The roster split into Organization owners, teams, and guests. */
+export interface Directory {
+ organization: Member[];
+ teams: TeamGroup[];
+ guests: Member[];
+}
+
+/**
+ * Group the flat roster into the directory shape the Users page renders:
+ * admins are the Organization owners, web-only users are Guests, and everyone
+ * else sits under their team. Empty teams are omitted from the roster (they're
+ * still creatable / visible via team management).
+ */
+export function buildDirectory(members: Member[], teams: Team[]): Directory {
+ const organization = members.filter((m) => m.role === "admin");
+ const guests = members.filter((m) => m.role === "guest");
+
+ const byTeam = new Map<number, Member[]>();
+ for (const m of members) {
+ if (m.role === "admin" || m.role === "guest") continue;
+ if (m.teamId == null) continue;
+ const list = byTeam.get(m.teamId) ?? [];
+ list.push(m);
+ byTeam.set(m.teamId, list);
+ }
+
+ const teamGroups: TeamGroup[] = teams
+ .map((t) => ({
+ id: t.id,
+ name: t.name,
+ owners: t.owners,
+ members: byTeam.get(t.id) ?? [],
+ }))
+ .filter((g) => g.members.length > 0)
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ return { organization, teams: teamGroups, guests };
+}
diff --git a/frontend/editor/src/portal/components/users/format.ts b/frontend/editor/src/portal/components/users/format.ts
index 3308a6441d..f17abe85e0 100644
--- a/frontend/editor/src/portal/components/users/format.ts
+++ b/frontend/editor/src/portal/components/users/format.ts
@@ -1,7 +1,10 @@
import type { AvatarTone, ChipAccent } from "@app/ui";
-import type { RoleId } from "@portal/api/users";
+import type { Member, RoleId } from "@portal/api/users";
import { ROLE_TONE } from "@portal/api/users";
+/** Vivid tones cycled per-person so a big roster reads as distinct people. */
+const AVATAR_TONES: AvatarTone[] = ["blue", "purple", "green", "amber", "red"];
+
/** Map the role palette onto the shared Chip accent set. */
const ROLE_CHIP_ACCENT: Record<
"purple" | "blue" | "green" | "amber" | "neutral",
@@ -25,9 +28,13 @@ export function seatsLabel(used: number, limit: number | null): string {
}
/**
- * Avatar tone for a member, keyed off their role so the roster reads as a
- * legend for the role catalogue. Falls back to neutral for unknown roles.
+ * A stable avatar tone for a member, hashed from their identity so everyone
+ * gets a distinct, consistent colour (role is conveyed by the row's controls,
+ * not the avatar).
*/
-export function avatarToneForRole(role: RoleId): AvatarTone {
- return (ROLE_TONE[role] ?? "neutral") as AvatarTone;
+export function avatarToneForMember(m: Member): AvatarTone {
+ const key = m.username || m.name || m.id || "";
+ let h = 0;
+ for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) | 0;
+ return AVATAR_TONES[Math.abs(h) % AVATAR_TONES.length];
}
diff --git a/frontend/editor/src/portal/mocks/handlers/users.ts b/frontend/editor/src/portal/mocks/handlers/users.ts
index 76a5e7796b..577dfc29bb 100644
--- a/frontend/editor/src/portal/mocks/handlers/users.ts
+++ b/frontend/editor/src/portal/mocks/handlers/users.ts
@@ -1,12 +1,29 @@
import { http, HttpResponse, delay } from "msw";
-import type { Tier } from "@portal/contexts/TierContext";
-import { buildUsersResponse } from "@portal/mocks/users";
+import { buildAdminSettingsData } from "@portal/mocks/users";
+/** Mock mode serves the REAL routes the users view reads and mutates. */
export const usersHandlers = [
- http.get("/v1/users", async ({ request }) => {
+ http.get("/api/v1/proprietary/ui-data/admin-settings", async () => {
await delay(120);
- const url = new URL(request.url);
- const tier = (url.searchParams.get("tier") ?? "pro") as Tier;
- return HttpResponse.json(buildUsersResponse(tier));
+ return HttpResponse.json(buildAdminSettingsData("pro"));
}),
+ // Row-action mutations: acknowledge so mock mode doesn't fall through to a real backend.
+ http.post("/api/v1/user/admin/changeRole", () =>
+ HttpResponse.json({ message: "Role updated" }),
+ ),
+ http.post("/api/v1/user/admin/inviteUsers", () =>
+ HttpResponse.json({ successCount: 1, failureCount: 0 }),
+ ),
+ http.post("/api/v1/user/admin/changeUserEnabled/:username", () =>
+ HttpResponse.json({ message: "Updated" }),
+ ),
+ http.post("/api/v1/user/admin/deleteUser/:username", () =>
+ HttpResponse.json({ message: "Deleted" }),
+ ),
+ http.post("/api/v1/team/setOwner", () =>
+ HttpResponse.json({ message: "Owner assigned" }),
+ ),
+ http.post("/api/v1/team/removeOwner", () =>
+ HttpResponse.json({ message: "Owner removed" }),
+ ),
];
diff --git a/frontend/editor/src/portal/mocks/users.ts b/frontend/editor/src/portal/mocks/users.ts
index 136a9b07bb..95b2e2f25c 100644
--- a/frontend/editor/src/portal/mocks/users.ts
+++ b/frontend/editor/src/portal/mocks/users.ts
@@ -18,27 +18,65 @@ import type { Tier } from "@portal/contexts/TierContext";
/* Roles & members */
/* ──────────────────────────────────────────────────────────────────────── */
-/** The five org roles, most → least privileged. Order is meaningful: it drives
- * the role select and the reference grid. */
-export type RoleId =
- | "org_owner"
- | "team_owner"
- | "developer"
- | "reviewer"
- | "viewer";
+/** The four org roles, most → least privileged, mapped onto the backend's
+ * authorities + team leadership. Order drives the role select and grid. */
+export type RoleId = "admin" | "team_owner" | "member" | "guest";
export type MemberStatus = "active" | "invited" | "suspended";
+/**
+ * Effective portal (processor) access for a member:
+ * admin — implicit, admins always have it
+ * role — implicit via team-owner leadership (default policy)
+ * team — inherited from a PORTAL grant on the member's whole team
+ * granted — explicit per-user PORTAL grant
+ * none — no access
+ */
+export type PortalAccessState = "admin" | "role" | "team" | "granted" | "none";
+
+export const PORTAL_ACCESS_TONE: Record<
+ PortalAccessState,
+ "success" | "info" | "neutral" | "warning"
+> = {
+ admin: "info",
+ role: "info",
+ team: "info",
+ granted: "success",
+ none: "neutral",
+};
+
export interface Member {
id: string;
name: string;
email: string;
role: RoleId;
status: MemberStatus;
+ /** Effective portal access; set by the view from the grant list. */
+ portalAccess?: PortalAccessState;
+ /** Authoritative server-side portal access (roster DTO); drives whether a chip shows at all. */
+ canAccessPortal?: boolean;
+ /** The explicit PORTAL grant's id, for revoke (present when access = granted). */
+ portalGrantId?: number;
/** Relative-time string, e.g. "4m ago". Invited members read "—". */
lastActive: string;
/** Optional avatar image; falls back to initials when absent. */
avatarUrl?: string;
+ /** Backend linkage for row actions (absent on pure fixtures). */
+ username?: string;
+ teamId?: number;
+ teamName?: string;
+ /** Holds a LEADER membership on their team (independent of displayed role). */
+ teamLead?: boolean;
+ /** The signed-in admin's own row; self-directed actions are disabled. */
+ isSelf?: boolean;
+ /** Account locked after failed logins (admin can unlock). */
+ locked?: boolean;
+ /** MFA enrolled (admin can reset it). */
+ mfaEnabled?: boolean;
+ /** Auth provider: "web" (password), "oauth2", "saml2", etc. */
+ authType?: string;
+ /** Raw stored authority (e.g. ROLE_USER, ROLE_WEB_ONLY_USER); preserved on team moves. */
+ authority?: string;
}
export interface Role {
@@ -104,6 +142,11 @@ export interface UsersResponse {
members: Member[];
roles: Role[];
access: AccessControls;
+ /** Whether SMTP is configured (gates emailing passwords/invites). */
+ mailEnabled: boolean;
+ /** Whether email invites will work: SMTP on AND mail.enableInvites=true. Gates the
+ * "Invite by email" option on self-hosted. */
+ emailInvitesEnabled: boolean;
}
/* ──────────────────────────────────────────────────────────────────────── */
@@ -127,62 +170,51 @@ export const MEMBER_STATUS_TONE: Record<
export const ROLES: Role[] = [
{
- id: "org_owner",
- label: "Org Owner",
- summary: "Full governance over the organization, billing and members.",
+ id: "admin",
+ label: "Admin (Org owner)",
+ summary: "Full governance over the workspace, settings and members.",
permissions: [
- "Manage billing & plan",
- "Add, suspend and remove members",
- "Configure SSO, SCIM and security policy",
+ "Manage users, teams and roles",
+ "Manage all integrations incl. S3 connections",
+ "Grant or revoke portal access",
"Everything Team Owner can do",
],
tone: "purple",
},
{
id: "team_owner",
- label: "Team Owner",
- summary: "Team-scoped admin — manage members and pipelines for a team.",
+ label: "Team owner",
+ summary: "Owns a team — manages its members' resources and shared configs.",
permissions: [
- "Invite & manage team members",
- "Create and deploy pipelines",
- "View team usage & audit log",
- "No org billing or SSO access",
+ "Create & manage the team's S3 connections",
+ "Manage team-owned integration configs",
+ "Portal access via the default policy",
+ "Everything Member can do",
],
tone: "blue",
},
{
- id: "developer",
- label: "Developer",
- summary: "Build and operate pipelines, agents and integrations.",
+ id: "member",
+ label: "Member",
+ summary:
+ "Regular user — works with shared resources and their own configs.",
permissions: [
- "Create & edit pipelines",
- "Manage API keys, agents and webhooks",
- "Run and debug document jobs",
- "Read team audit log",
+ "Use the editor and shared integrations",
+ "Create personal API & MCP configs",
+ "See team configs shared with them",
+ "No S3 or workspace management",
],
tone: "green",
},
{
- id: "reviewer",
- label: "Reviewer",
- summary: "Approve or reject documents routed for human review.",
- permissions: [
- "Approve / reject review tasks",
- "Annotate and redact documents",
- "Read assigned pipelines",
- "No pipeline or key management",
- ],
- tone: "amber",
- },
- {
- id: "viewer",
- label: "Viewer",
- summary: "Read-only access to documents and dashboards.",
+ id: "guest",
+ label: "Guest",
+ summary: "Limited or web-only access; cannot hold personal configs.",
permissions: [
- "View documents & results",
- "View dashboards & usage",
- "Export permitted reports",
- "No write access",
+ "Web-only / demo usage",
+ "No API keys or integrations",
+ "No portal access",
+ "Read-only where shared",
],
tone: "neutral",
},
@@ -206,7 +238,7 @@ const PRO_MEMBERS: Member[] = [
id: "usr-you",
name: "You",
- role: "org_owner",
+ role: "admin",
status: "active",
lastActive: "just now",
},
@@ -214,7 +246,7 @@ const PRO_MEMBERS: Member[] = [
id: "usr-priya",
name: "Priya Nair",
- role: "developer",
+ role: "member",
status: "active",
lastActive: "8m ago",
},
@@ -222,7 +254,7 @@ const PRO_MEMBERS: Member[] = [
id: "usr-marcus",
name: "Marcus Webb",
- role: "developer",
+ role: "member",
status: "active",
lastActive: "1h ago",
},
@@ -230,7 +262,7 @@ const PRO_MEMBERS: Member[] = [
id: "usr-dana",
name: "Dana Osei",
- role: "reviewer",
+ role: "member",
status: "active",
lastActive: "yesterday",
},
@@ -239,16 +271,16 @@ const PRO_MEMBERS: Member[] = [
id: "usr-invite-1",
- role: "viewer",
+ role: "guest",
status: "invited",
- lastActive: "—",
+ lastActive: "Never",
},
{
// Suspended: retains the seat but cannot sign in until reinstated.
id: "usr-leo",
name: "Leo Fischer",
- role: "developer",
+ role: "member",
status: "suspended",
lastActive: "12 days ago",
},
@@ -268,7 +300,7 @@ const ENTERPRISE_EXTRA: Member[] = [
id: "usr-tom",
name: "Tom Becker",
- role: "reviewer",
+ role: "member",
status: "active",
lastActive: "26m ago",
},
@@ -276,7 +308,7 @@ const ENTERPRISE_EXTRA: Member[] = [
id: "usr-nadia",
name: "Nadia Costa",
- role: "viewer",
+ role: "guest",
status: "active",
lastActive: "2h ago",
},
@@ -284,9 +316,9 @@ const ENTERPRISE_EXTRA: Member[] = [
id: "usr-invite-2",
- role: "reviewer",
+ role: "member",
status: "invited",
- lastActive: "—",
+ lastActive: "Never",
},
];
@@ -296,7 +328,7 @@ const FREE_MEMBERS: Member[] = [
id: "usr-you",
name: "You",
- role: "org_owner",
+ role: "admin",
status: "active",
lastActive: "just now",
},
@@ -304,7 +336,7 @@ const FREE_MEMBERS: Member[] = [
id: "usr-jess",
name: "Jess Allen",
- role: "developer",
+ role: "member",
status: "active",
lastActive: "3h ago",
},
@@ -395,5 +427,52 @@ export function buildUsersResponse(tier: Tier): UsersResponse {
members: membersFor(tier),
roles: ROLES,
access: accessFor(tier),
+ mailEnabled: false,
+ emailInvitesEnabled: false,
+ };
+}
+
+/* ──────────────────────────────────────────────────────────────────────── */
+/* Backend-shaped fixtures */
+/* api/users.ts now reads the real admin-settings endpoint; mock mode */
+/* serves this AdminSettingsData-shaped payload on the same route so the */
+/* real adapter is exercised end to end. */
+/* ──────────────────────────────────────────────────────────────────────── */
+
+export function buildAdminSettingsData(tier: Tier) {
+ const members = membersFor(tier);
+ const users = members.map((m, i) => ({
+ id: i + 1,
+ username: m.email,
+ email: m.email,
+ rolesAsString:
+ m.role === "admin"
+ ? "ROLE_ADMIN"
+ : m.role === "guest"
+ ? "ROLE_WEB_ONLY_USER"
+ : "ROLE_USER",
+ teamLead: m.role === "team_owner",
+ // Authoritative portal access as the backend computes it under the default policy
+ // (admins + team leads), plus the seeded PORTAL grant on user id 2 (see mock grantStore).
+ portalAccess: m.role === "admin" || m.role === "team_owner" || i + 1 === 2,
+ enabled: m.status !== "suspended",
+ team: { id: 1, name: "Default" },
+ }));
+ const userLastRequest = Object.fromEntries(
+ members
+ .filter((m) => m.status === "active")
+ .map((m, i) => [m.email, Date.now() - i * 45 * 60 * 1000]),
+ );
+ const seatLimit = seatLimitFor(tier);
+ return {
+ users,
+ userLastRequest,
+ totalUsers: users.length,
+ activeUsers: users.filter((u) => u.enabled).length,
+ disabledUsers: users.filter((u) => !u.enabled).length,
+ maxAllowedUsers: seatLimit ?? 0,
+ currentUsername: users[0]?.username,
+ mailEnabled: false,
+ emailInvitesEnabled: false,
};
}
diff --git a/frontend/editor/src/portal/views/Users.css b/frontend/editor/src/portal/views/Users.css
index e33bbfa794..a29a8aafab 100644
--- a/frontend/editor/src/portal/views/Users.css
+++ b/frontend/editor/src/portal/views/Users.css
@@ -253,3 +253,266 @@
gap: 0.5rem;
width: 100%;
}
+
+.portal-users__error {
+ margin: 0.75rem 0 0;
+ padding: 0.5rem 0.75rem;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--sui-danger, #dc2626) 12%, transparent);
+ color: var(--sui-danger, #dc2626);
+ font-size: 0.85rem;
+}
+
+/* ──────────────────────────────────────────────────────────────────────── */
+/* Directory (grouped roster) — Organization / teams / guests */
+/* ──────────────────────────────────────────────────────────────────────── */
+.portal-users__head-actions {
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+}
+
+.portal-users__link {
+ color: var(--color-blue);
+ text-decoration: none;
+}
+.portal-users__link:hover {
+ text-decoration: underline;
+}
+
+.portal-users__directory {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.portal-users__group {
+ background: var(--color-surface);
+ border: 1px solid var(--color-border);
+ border-radius: var(--radius-lg);
+ overflow: hidden;
+}
+
+.portal-users__group-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ padding: 0.75rem 1.25rem;
+ border-bottom: 1px solid var(--color-border-light);
+ background: var(--color-bg-subtle);
+}
+
+.portal-users__group-title {
+ display: flex;
+ align-items: baseline;
+ gap: 0.6rem;
+ min-width: 0;
+ flex-wrap: wrap;
+}
+.portal-users__group-title > strong {
+ font-size: 0.9rem;
+ font-weight: 650;
+ color: var(--color-text-1);
+}
+.portal-users__group-desc {
+ font-size: 0.8rem;
+ color: var(--color-text-4);
+}
+.portal-users__group-count {
+ font-size: 0.78rem;
+ color: var(--color-text-4);
+ white-space: nowrap;
+}
+.portal-users__group-action {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3rem;
+ background: none;
+ border: none;
+ cursor: pointer;
+ color: var(--color-blue);
+ font-size: 0.8rem;
+ font-weight: 500;
+ white-space: nowrap;
+}
+.portal-users__group-action:hover {
+ text-decoration: underline;
+}
+
+.portal-users__row {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ padding: 0.7rem 1.25rem;
+}
+.portal-users__row + .portal-users__row {
+ border-top: 1px solid var(--color-border-light);
+}
+.portal-users__row-main {
+ display: flex;
+ align-items: center;
+ gap: 0.7rem;
+ width: 250px;
+ flex-shrink: 0;
+ min-width: 0;
+}
+.portal-users__row-id {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+.portal-users__row-name {
+ font-size: 0.875rem;
+ font-weight: 600;
+ color: var(--color-text-1);
+}
+.portal-users__row-you {
+ font-weight: 400;
+ color: var(--color-text-4);
+}
+.portal-users__row-email {
+ font-size: 0.78rem;
+ color: var(--color-text-4);
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.portal-users__caps {
+ display: flex;
+ align-items: center;
+ gap: 0.4rem;
+ flex: 1;
+ flex-wrap: wrap;
+}
+/* Solid capability/status tags read cleaner without an outline; the dashed
+ "+ Processor" add-chip keeps its box-cut border. */
+.portal-users__caps .sui-chip:not(.sui-chip--dashed),
+.portal-users__row-tag {
+ border-color: transparent;
+}
+.portal-users__row-active {
+ font-size: 0.78rem;
+ color: var(--color-text-4);
+ white-space: nowrap;
+}
+.portal-users__row-role {
+ width: 148px;
+ flex-shrink: 0;
+}
+
+/* Invite modal extras */
+.portal-users__invite-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.75rem;
+}
+.portal-users__invite-hint {
+ margin: 0;
+ font-size: 0.78rem;
+ color: var(--color-text-4);
+}
+.portal-users__invite-access {
+ display: flex;
+ flex-direction: column;
+ gap: 0.6rem;
+ padding-top: 0.75rem;
+ border-top: 1px solid var(--color-border-light);
+}
+.portal-users__invite-access-label {
+ font-size: 0.78rem;
+ font-weight: 600;
+ color: var(--color-text-2);
+}
+.portal-users__form-note {
+ margin: 0;
+ font-size: 0.8rem;
+ color: var(--color-text-3);
+}
+
+@media (max-width: 720px) {
+ .portal-users__row {
+ flex-wrap: wrap;
+ }
+ .portal-users__row-main {
+ width: 100%;
+ }
+ .portal-users__invite-grid {
+ grid-template-columns: 1fr;
+ }
+}
+
+/* ── Row kebab + team-header actions + expander + tags ─────────────────── */
+.portal-users__group-actions {
+ display: flex;
+ align-items: center;
+ gap: 0.4rem;
+}
+
+.portal-users__row-kebab {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 1.75rem;
+ height: 1.75rem;
+ flex-shrink: 0;
+ border-radius: var(--radius-md);
+ border: 1px solid transparent;
+ background: transparent;
+ color: var(--color-text-4);
+ font-size: 1.125rem;
+ line-height: 1;
+ cursor: pointer;
+ transition:
+ background var(--motion-fast),
+ color var(--motion-fast),
+ border-color var(--motion-fast);
+}
+.portal-users__row-kebab:hover {
+ background: var(--color-bg-hover);
+ border-color: var(--color-border);
+ color: var(--color-text-1);
+}
+
+.portal-users__show-more {
+ display: block;
+ width: 100%;
+ padding: 0.6rem 1.25rem;
+ text-align: center;
+ background: none;
+ border: none;
+ border-top: 1px solid var(--color-border-light);
+ color: var(--color-blue);
+ font-size: 0.8rem;
+ font-weight: 500;
+ cursor: pointer;
+}
+.portal-users__show-more:hover {
+ background: var(--color-bg-hover);
+}
+
+.portal-users__row-tag {
+ margin-left: 0.4rem;
+ vertical-align: middle;
+}
+
+.portal-users__pw-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+/* The password field flexes; the Regenerate/Copy buttons keep their full label
+ (flex-shrink:0) so they don't truncate in the narrow modal. */
+.portal-users__pw-row > *:first-child {
+ flex: 1;
+ min-width: 0;
+}
+.portal-users__pw-row > *:not(:first-child) {
+ flex-shrink: 0;
+}
+
+.portal-users__confirm-body {
+ margin: 0;
+ font-size: 0.875rem;
+ line-height: 1.5;
+ color: var(--color-text-3);
+}
diff --git a/frontend/editor/src/portal/views/Users.tsx b/frontend/editor/src/portal/views/Users.tsx
index 7d210e9831..26670198d5 100644
--- a/frontend/editor/src/portal/views/Users.tsx
+++ b/frontend/editor/src/portal/views/Users.tsx
@@ -1,33 +1,82 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Button, EmptyState, Skeleton } from "@app/ui";
import { useTier } from "@portal/contexts/TierContext";
-import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";
+import { useAsync } from "@portal/hooks/useAsync";
import {
+ changeMemberRole,
+ disableMemberMfa,
+ fetchAuthConfig,
fetchUsers,
+ removeMember,
+ setMemberSuspended,
+ unlockMember,
+ type AdminAuthConfig,
type Member,
+ type PortalAccessState,
type RoleId,
type UsersResponse,
} from "@portal/api/users";
-import { UsersSummaryStrip } from "@portal/components/users/UsersSummaryStrip";
-import { MembersTable } from "@portal/components/users/MembersTable";
-import { RolesGrid } from "@portal/components/users/RolesGrid";
-import { AccessControls } from "@portal/components/users/AccessControls";
+import {
+ createGrant,
+ fetchGrants,
+ revokeGrant,
+ type ResourceGrant,
+} from "@portal/api/access";
+import {
+ deleteTeam as apiDeleteTeam,
+ fetchTeams,
+ type Team,
+} from "@portal/api/teams";
+import { errorMessage } from "@portal/api/http";
+import { usersCapabilities as caps } from "@app/portal/usersCapabilities";
+import { UsersDirectory } from "@portal/components/users/UsersDirectory";
import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";
-import "@portal/views/Users.css";
+import { NewTeamModal } from "@portal/components/users/NewTeamModal";
+import { ResetPasswordModal } from "@portal/components/users/ResetPasswordModal";
+import { MoveToTeamModal } from "@portal/components/users/MoveToTeamModal";
+import { RenameTeamModal } from "@portal/components/users/RenameTeamModal";
+import { ConfirmModal } from "@portal/components/users/ConfirmModal";
+import type { TeamGroup } from "@portal/components/users/directory";
+
+interface Confirm {
+ title: string;
+ body: string;
+ confirmLabel: string;
+ danger?: boolean;
+ action: () => Promise<unknown>;
+}
export function Users() {
const { t } = useTranslation();
const { tier } = useTier();
- const state = useAsync<UsersResponse>(() => fetchUsers(tier), [tier]);
- const { data, loading } = state;
- const { isLoading, isEmpty } = useSectionFlags(state);
+ const [refreshKey, setRefreshKey] = useState(0);
+
+ const usersState = useAsync<UsersResponse>(
+ () => fetchUsers(tier),
+ [tier, refreshKey],
+ );
+ // Grants are ADMIN-only; skip the fetch entirely on flavors that can't manage them.
+ const grantsState = useAsync<ResourceGrant[]>(
+ () => (caps.manageGrants ? fetchGrants("PORTAL") : Promise.resolve([])),
+ [tier, refreshKey],
+ );
+ const teamsState = useAsync<Team[]>(() => fetchTeams(), [tier, refreshKey]);
+ const authState = useAsync<AdminAuthConfig>(() => fetchAuthConfig(), []);
+ const [actionError, setActionError] = useState<string | null>(null);
const [inviteOpen, setInviteOpen] = useState(false);
+ const [inviteTeamId, setInviteTeamId] = useState<number | null>(null);
+ const [newTeamOpen, setNewTeamOpen] = useState(false);
+ const [resetPwMember, setResetPwMember] = useState<Member | null>(null);
+ const [moveMember, setMoveMember] = useState<Member | null>(null);
+ const [renameTarget, setRenameTarget] = useState<{
+ id: number;
+ name: string;
+ } | null>(null);
+ const [confirm, setConfirm] = useState<Confirm | null>(null);
- // Deep-link from elsewhere (e.g. billing's "Invite teammates"): ?invite opens
- // the modal, then the param is cleared so a refresh/back doesn't re-open it.
const [searchParams, setSearchParams] = useSearchParams();
useEffect(() => {
if (searchParams.get("invite") === null) return;
@@ -37,76 +86,301 @@ export function Users() {
setSearchParams(next, { replace: true });
}, [searchParams, setSearchParams]);
- const members = data?.members ?? [];
+ // PORTAL grants held by a whole team (principalId = teamId); members inherit these.
+ const grantByTeam = useMemo(() => {
+ const m = new Map<number, ResourceGrant>();
+ for (const g of grantsState.data ?? []) {
+ if (g.principalType === "TEAM") m.set(g.principalId, g);
+ }
+ return m;
+ }, [grantsState.data]);
+
+ const members = useMemo<Member[]>(() => {
+ const grantByUser = new Map<string, ResourceGrant>();
+ for (const g of grantsState.data ?? []) {
+ if (g.principalType === "USER") grantByUser.set(String(g.principalId), g);
+ }
+ return (usersState.data?.members ?? []).map((raw) => {
+ // Enforce the no-ROLE_ADMIN-on-SaaS rule: clamp any stray admin to member.
+ const m: Member =
+ !caps.adminRole && raw.role === "admin"
+ ? { ...raw, role: "member" }
+ : raw;
+ // Presence is the server's authoritative decision (roster DTO's portalAccess, the same
+ // canAccessPortal /me uses), so a stricter/looser default policy can't drift. The grant
+ // maps only pick the display sub-state: which source, and whether the chip is removable.
+ let portalAccess: PortalAccessState;
+ let portalGrantId: number | undefined;
+ if (!m.canAccessPortal) portalAccess = "none";
+ else if (m.role === "admin") portalAccess = "admin";
+ else if (grantByUser.has(m.id)) {
+ portalAccess = "granted"; // a per-user grant is the removable source
+ portalGrantId = grantByUser.get(m.id)!.id;
+ } else if (m.teamId != null && grantByTeam.has(m.teamId))
+ portalAccess = "team";
+ else portalAccess = "role"; // access via the default policy (e.g. team lead)
+ return { ...m, portalAccess, portalGrantId };
+ });
+ }, [usersState.data?.members, grantsState.data, grantByTeam]);
+
+ const processorTeamIds = useMemo(
+ () => new Set(grantByTeam.keys()),
+ [grantByTeam],
+ );
+
+ const teams = teamsState.data ?? [];
+ const mailEnabled = usersState.data?.mailEnabled ?? false;
+ // Email invites need SMTP + mail.enableInvites on self-hosted; SaaS (no directCreate path)
+ // always has email via Supabase, so it isn't gated on a self-hosted mail config.
+ const canEmailInvite =
+ caps.emailInvite &&
+ (caps.directCreate
+ ? (usersState.data?.emailInvitesEnabled ?? false)
+ : true);
+ const loading = usersState.loading && usersState.data === null;
+ const loadError = !usersState.loading && usersState.error !== null;
+ const isEmpty = !usersState.loading && !loadError && members.length === 0;
+
+ function run(action: () => Promise<unknown>) {
+ setActionError(null);
+ action()
+ .catch((error) => setActionError(errorMessage(error)))
+ // Refetch on success AND failure: a multi-step mutation (e.g. changeMemberRole)
+ // has no rollback, so a mid-sequence failure must resync the roster to real state.
+ .finally(() => setRefreshKey((k) => k + 1));
+ }
+ const refresh = () => setRefreshKey((k) => k + 1);
- // Row actions are non-functional shells until the backend exists; each logs
- // the intended request so the wiring point is obvious.
function changeRole(member: Member, role: RoleId) {
- // TODO(backend): PATCH /v1/users/{id} { role }
- void member;
- void role;
+ run(() => changeMemberRole(member, role));
+ }
+ function grantProcessor(member: Member) {
+ run(() =>
+ createGrant({
+ resourceType: "PORTAL",
+ resourceId: "",
+ principalType: "USER",
+ principalId: Number(member.id),
+ permission: "USE",
+ }),
+ );
+ }
+ function revokeProcessor(member: Member) {
+ if (!member.portalGrantId) return;
+ run(() => revokeGrant(member.portalGrantId!));
+ }
+ // Grant/revoke Processor for a whole team (a TEAM-principal PORTAL grant).
+ function grantTeamProcessor(team: TeamGroup) {
+ run(() =>
+ createGrant({
+ resourceType: "PORTAL",
+ resourceId: "",
+ principalType: "TEAM",
+ principalId: team.id,
+ permission: "USE",
+ }),
+ );
+ }
+ function revokeTeamProcessor(team: TeamGroup) {
+ const grant = grantByTeam.get(team.id);
+ if (!grant) return;
+ run(() => revokeGrant(grant.id));
+ }
+ function openInvite(teamId: number | null) {
+ setInviteTeamId(teamId);
+ setInviteOpen(true);
+ }
+
+ // Kebab actions
+ function toggleEnabled(member: Member) {
+ run(() => setMemberSuspended(member, member.status !== "suspended"));
+ }
+ function unlock(member: Member) {
+ run(() => unlockMember(member));
+ }
+ function disableMfa(member: Member) {
+ setConfirm({
+ title: t("users.confirm.disableMfaTitle", "Reset MFA"),
+ body: t(
+ "users.confirm.disableMfaBody",
+ "Remove {{name}}'s MFA enrolment? They'll set it up again on next login if required.",
+ { name: member.name },
+ ),
+ confirmLabel: t("users.action.disableMfa", "Reset MFA"),
+ action: () => disableMemberMfa(member),
+ });
}
- function suspend(member: Member) {
- // TODO(backend): PATCH /v1/users/{id} { status: "suspended" }
- void member;
+ function removeUser(member: Member) {
+ setConfirm({
+ title: t("users.confirm.removeTitle", "Remove member"),
+ body: t(
+ "users.confirm.removeBody",
+ "Permanently remove {{name}} from the organization? This cannot be undone.",
+ { name: member.name },
+ ),
+ confirmLabel: t("users.action.remove", "Remove from org"),
+ danger: true,
+ action: () => removeMember(member),
+ });
}
- function remove(member: Member) {
- // TODO(backend): DELETE /v1/users/{id}
- void member;
+ function deleteTeamAction(team: TeamGroup) {
+ setConfirm({
+ title: t("users.confirm.deleteTeamTitle", "Delete team"),
+ body: t(
+ "users.confirm.deleteTeamBody",
+ "Delete the {{name}} team? The team must be empty first - move its members to another team, and it can't still own any integration configs.",
+ { name: team.name },
+ ),
+ confirmLabel: t("users.action.deleteTeam", "Delete team"),
+ danger: true,
+ action: () => apiDeleteTeam(team.id),
+ });
}
return (
<div className="portal-users">
<header className="portal-users__head">
<div>
- <h1 className="portal-users__title">{t("portal.users.title")}</h1>
- <p className="portal-users__sub">{t("portal.users.subtitle")}</p>
+ <h1 className="portal-users__title">{t("users.title", "Users")}</h1>
+ <p className="portal-users__sub">
+ {t("users.subtitle2", "Your people, teams, and access levels.")}{" "}
+ <a className="portal-users__link" href="/docs">
+ {t("users.learnMore", "Learn more about roles and access.")}
+ </a>
+ </p>
+ </div>
+ <div className="portal-users__head-actions">
+ {caps.createTeam && (
+ <Button variant="secondary" onClick={() => setNewTeamOpen(true)}>
+ {t("users.newTeam.action", "+ New team")}
+ </Button>
+ )}
+ <Button onClick={() => openInvite(null)}>
+ {t("users.invite.action", "Invite people")}
+ </Button>
</div>
- <Button
- onClick={() => setInviteOpen(true)}
- leftSection={<span aria-hidden>+</span>}
- >
- {t("portal.common.inviteMember")}
- </Button>
</header>
- <UsersSummaryStrip data={data} loading={loading} />
+ {actionError && (
+ <p className="portal-users__error" role="alert">
+ {actionError}
+ </p>
+ )}
- {isLoading && (
+ {loading && (
<div className="portal-users__table-skeleton" aria-hidden>
{Array.from({ length: 5 }).map((_, i) => (
- <Skeleton key={i} height="3rem" />
+ <Skeleton key={i} height="3.25rem" />
))}
</div>
)}
+ {loadError && (
+ <EmptyState
+ title={t("users.loadError.title", "Couldn't load members")}
+ description={t(
+ "users.loadError.description",
+ "Something went wrong reaching the backend, or you don't have access. Try again.",
+ )}
+ actions={
+ <Button variant="secondary" onClick={refresh}>
+ {t("common.retry", "Retry")}
+ </Button>
+ }
+ />
+ )}
+
{isEmpty && (
<EmptyState
- title={t("portal.users.empty.title")}
- description={t("portal.users.empty.description")}
+ title={t("users.empty.title", "No members yet")}
+ description={t(
+ "users.empty.description",
+ "Invite your team to start collaborating.",
+ )}
actions={
- <Button onClick={() => setInviteOpen(true)}>
- {t("portal.common.inviteMember")}
+ <Button onClick={() => openInvite(null)}>
+ {t("users.invite.action", "Invite people")}
</Button>
}
/>
)}
- {!isLoading && !isEmpty && members.length > 0 && (
- <MembersTable
+ {!loading && members.length > 0 && (
+ <UsersDirectory
members={members}
+ teams={teams}
+ capabilities={caps}
onChangeRole={changeRole}
- onSuspend={suspend}
- onRemove={remove}
+ onGrantProcessor={grantProcessor}
+ onRevokeProcessor={revokeProcessor}
+ processorTeamIds={processorTeamIds}
+ onGrantTeamProcessor={grantTeamProcessor}
+ onRevokeTeamProcessor={revokeTeamProcessor}
+ onAddToTeam={(team) => openInvite(team.id)}
+ onResetPassword={setResetPwMember}
+ onMoveToTeam={setMoveMember}
+ onToggleEnabled={toggleEnabled}
+ onUnlock={unlock}
+ onDisableMfa={disableMfa}
+ onRemove={removeUser}
+ onRenameTeam={(team) =>
+ setRenameTarget({ id: team.id, name: team.name })
+ }
+ onDeleteTeam={deleteTeamAction}
/>
)}
- {data && <RolesGrid roles={data.roles} />}
- {data && <AccessControls access={data.access} />}
-
<InviteMemberModal
open={inviteOpen}
onClose={() => setInviteOpen(false)}
+ onInvited={refresh}
+ teams={teams}
+ defaultTeamId={inviteTeamId}
+ canDirectCreate={caps.directCreate && authState.data?.canDirectCreate}
+ canEmailInvite={canEmailInvite}
+ hasOauth={authState.data?.hasOauth}
+ hasSaml={authState.data?.hasSaml}
+ adminRole={caps.adminRole}
+ manageGrants={caps.manageGrants}
+ onNotice={setActionError}
+ />
+ <NewTeamModal
+ open={newTeamOpen}
+ onClose={() => setNewTeamOpen(false)}
+ onCreated={refresh}
+ />
+ <ResetPasswordModal
+ open={resetPwMember !== null}
+ member={resetPwMember}
+ mailEnabled={mailEnabled}
+ onClose={() => setResetPwMember(null)}
+ onDone={refresh}
+ />
+ <MoveToTeamModal
+ open={moveMember !== null}
+ member={moveMember}
+ teams={teams}
+ onClose={() => setMoveMember(null)}
+ onDone={refresh}
+ />
+ <RenameTeamModal
+ open={renameTarget !== null}
+ teamId={renameTarget?.id ?? null}
+ currentName={renameTarget?.name ?? ""}
+ onClose={() => setRenameTarget(null)}
+ onDone={refresh}
+ />
+ <ConfirmModal
+ open={confirm !== null}
+ title={confirm?.title ?? ""}
+ body={confirm?.body ?? ""}
+ confirmLabel={confirm?.confirmLabel ?? t("common.confirm", "Confirm")}
+ danger={confirm?.danger}
+ onConfirm={() => {
+ if (confirm) run(confirm.action);
+ setConfirm(null);
+ }}
+ onCancel={() => setConfirm(null)}
/>
</div>
);
diff --git a/frontend/editor/src/proprietary/auth/supabase/UseSession.tsx b/frontend/editor/src/proprietary/auth/supabase/UseSession.tsx
index c541ec5f24..9d2b3f2682 100644
--- a/frontend/editor/src/proprietary/auth/supabase/UseSession.tsx
+++ b/frontend/editor/src/proprietary/auth/supabase/UseSession.tsx
@@ -141,6 +141,57 @@ export function SupabaseAuthProvider({
};
}, []);
+ // Enrich with backend truth: grant-based portal access and team leadership
+ // come from /api/v1/auth/me, not Supabase claims. Best-effort; the
+ // isAdminRole fallback below covers failures and anonymous sessions.
+ useEffect(() => {
+ const token = session?.access_token;
+ const sessionUser = session?.user;
+ if (
+ !token ||
+ !sessionUser ||
+ sessionUser.is_anonymous ||
+ sessionUser.portalAccess !== undefined
+ ) {
+ return;
+ }
+ let cancelled = false;
+ void fetch("/api/v1/auth/me", {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: "application/json",
+ },
+ })
+ .then((res) => (res.ok ? res.json() : null))
+ .then(
+ (
+ data: {
+ user?: { portalAccess?: boolean; teamLead?: boolean };
+ } | null,
+ ) => {
+ if (cancelled || !data?.user) return;
+ setSession((prev) =>
+ prev
+ ? {
+ ...prev,
+ user: {
+ ...prev.user,
+ portalAccess: data.user?.portalAccess,
+ teamLead: data.user?.teamLead,
+ },
+ }
+ : prev,
+ );
+ },
+ )
+ .catch(() => {
+ // Backend unreachable or /me unsupported: keep the claim fallback.
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [session?.access_token, session?.user?.id, session?.user?.portalAccess]);
+
const user = session?.user ?? null;
const value: AuthContextValue = {
session,
diff --git a/frontend/editor/src/proprietary/auth/types.ts b/frontend/editor/src/proprietary/auth/types.ts
index c69adb033b..891bf64779 100644
--- a/frontend/editor/src/proprietary/auth/types.ts
+++ b/frontend/editor/src/proprietary/auth/types.ts
@@ -18,6 +18,10 @@ export interface AuthUser {
authenticationType?: string;
/** Whether the backend grants this user portal/processor access. */
portalAccess?: boolean;
+ /** Whether the user owns (leads) any team; drives elevated self-serve UI. */
+ teamLead?: boolean;
+ /** The user's team (self-hosted single-team model), when they have one. */
+ team?: { id: number; name: string };
app_metadata?: Record<string, unknown>;
}
diff --git a/frontend/editor/src/proprietary/portal/usersCapabilities.ts b/frontend/editor/src/proprietary/portal/usersCapabilities.ts
new file mode 100644
index 0000000000..f8efefc810
--- /dev/null
+++ b/frontend/editor/src/proprietary/portal/usersCapabilities.ts
@@ -0,0 +1,24 @@
+import type { UsersCapabilities } from "@portal/api/usersCapabilities";
+
+/**
+ * Self-hosted (proprietary) build: org-admin scope - the full set. Matches the
+ * behaviour the Users page had before the flavor seam existed.
+ */
+export const usersCapabilities: UsersCapabilities = {
+ orgGroup: true,
+ changeRole: true,
+ adminRole: true,
+ createTeam: true,
+ deleteTeam: true,
+ renameTeam: true,
+ emailInvite: true,
+ directCreate: true,
+ resetPassword: true,
+ unlock: true,
+ resetMfa: true,
+ suspend: true,
+ moveTeam: true,
+ seats: false,
+ manageGrants: true,
+ removeScope: "org",
+};
diff --git a/frontend/editor/src/saas/portal/usersCapabilities.ts b/frontend/editor/src/saas/portal/usersCapabilities.ts
new file mode 100644
index 0000000000..e24ee29745
--- /dev/null
+++ b/frontend/editor/src/saas/portal/usersCapabilities.ts
@@ -0,0 +1,25 @@
+import type { UsersCapabilities } from "@portal/api/usersCapabilities";
+
+/**
+ * SaaS build: team-leader scope. No org-wide roster, no create-team, and no
+ * password/role administration (Supabase-authed users); leaders invite, rename,
+ * remove members, and manage seats. Mirrors what SaasTeamController exposes.
+ */
+export const usersCapabilities: UsersCapabilities = {
+ orgGroup: false,
+ changeRole: false,
+ adminRole: false,
+ createTeam: false,
+ deleteTeam: false,
+ renameTeam: true,
+ emailInvite: true,
+ directCreate: false,
+ resetPassword: false,
+ unlock: false,
+ resetMfa: false,
+ suspend: false,
+ moveTeam: false,
+ seats: true,
+ manageGrants: false,
+ removeScope: "team",
+};
diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjs
index d954ca4006..5c3d20b94a 100644
--- a/frontend/eslint.config.mjs
+++ b/frontend/eslint.config.mjs
@@ -240,6 +240,17 @@ export default defineConfig(
"no-restricted-syntax": ["error", ...mantineComponentImportRestrictions],
},
},
+ // TEMPORARY: the portal user-management / integrations surface predates the
+ // button consolidation and uses bespoke CSS-styled raw <button>s (kebab
+ // triggers, inline text-link actions) that the shared Button can't represent
+ // without heavy overrides. Exempt ONLY the raw-<button> rule — the Mantine
+ // import bans stay in force — and migrate these in a follow-up PR.
+ {
+ files: ["editor/src/portal/components/users/UsersDirectory.tsx"],
+ rules: {
+ "no-restricted-syntax": ["error", ...mantineComponentImportRestrictions],
+ },
+ },
// TEMPORARY (same rationale as procurement above): the portal home hero
// reuses the same bespoke CSS-styled raw <button> controls as the procurement
// deal hero — status/invite chips and full-width checklist rows that the