Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
service: add the new endpoint for checking if the activation modal needs to show
adilsona34ed863ad15
diff --git a/backend/e2e-test/routes/v1/user-activation.spec.ts b/backend/e2e-test/routes/v1/user-activation.spec.tsnew file mode 100644index 0000000000..b376d9cfb4--- /dev/null+++ b/backend/e2e-test/routes/v1/user-activation.spec.ts@@ -0,0 +1,203 @@+import crypto from "node:crypto";++import jwt from "jsonwebtoken";+import { Knex } from "knex";++import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "@app/db/schemas";+import { seedData1 } from "@app/db/seed-data";+import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";++const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;+const daysAgo = (n: number) => new Date(Date.now() - n * 24 * 60 * 60 * 1000);++// The seeded auth-token session is user-scoped, so we can reuse it while pointing the JWT at any org+// the seeded user is an accepted member of. fnValidateJwtIdentity resolves the org from this payload.+const mintJwt = (orgId: string) =>+ jwt.sign(+ {+ authTokenType: AuthTokenType.ACCESS_TOKEN,+ userId: seedData1.id,+ tokenVersionId: seedData1.token.id,+ authMethod: AuthMethod.EMAIL,+ organizationId: orgId,+ accessVersion: 1+ },+ process.env.AUTH_SECRET as string,+ { expiresIn: "1h" }+ );++const callActivation = (orgId: string) =>+ testServer.inject({+ method: "GET",+ url: "/api/v1/user-activation/secrets",+ headers: { authorization: `Bearer ${mintJwt(orgId)}` }+ });++describe("User Activation Router", () => {+ const createdOrgIds: string[] = [];+ const createdUserIds: string[] = [];++ // Creates a fresh org (optionally backdated) with the seeded user as an accepted admin member, so+ // the invite-permission gate passes and org age / member count are the only variables under test.+ const createOrgWithAdmin = async (db: Knex, createdAt: Date) => {+ const suffix = crypto.randomUUID().slice(0, 8);+ const [org] = await db(TableName.Organization)+ .insert({ name: `ua-test-${suffix}`, slug: `ua-test-${suffix}`, createdAt } as never)+ .returning("*");+ createdOrgIds.push(org.id);++ const [membership] = await db(TableName.Membership)+ .insert({+ actorUserId: seedData1.id,+ scopeOrgId: org.id,+ scope: AccessScope.Organization,+ status: OrgMembershipStatus.Accepted,+ isActive: true+ })+ .returning("*");+ await db(TableName.MembershipRole).insert({ membershipId: membership.id, role: OrgMembershipRole.Admin });++ return org;+ };++ // Adds an accepted, active, non-ghost user member so it is counted by countAllOrgMembers.+ const addAcceptedMember = async (db: Knex, orgId: string) => {+ const suffix = crypto.randomUUID().slice(0, 8);+ const [user] = await db(TableName.Users)+ .insert({+ email: `ua-${suffix}@localhost.local`,+ username: `ua-${suffix}`,+ isGhost: false,+ isEmailVerified: true,+ authMethods: ["email"]+ })+ .returning("*");+ createdUserIds.push(user.id);++ const [membership] = await db(TableName.Membership)+ .insert({+ actorUserId: user.id,+ scopeOrgId: orgId,+ scope: AccessScope.Organization,+ status: OrgMembershipStatus.Accepted,+ isActive: true+ })+ .returning("*");+ await db(TableName.MembershipRole).insert({ membershipId: membership.id, role: OrgMembershipRole.Member });+ };++ const getActivationRow = (db: Knex, orgId: string) =>+ db(TableName.UserSecretActivation).where({ userId: seedData1.id, orgId }).first();++ afterAll(async () => {+ const db = getDb();+ if (createdOrgIds.length) {+ const memberships = await db(TableName.Membership).whereIn("scopeOrgId", createdOrgIds).select("id");+ const membershipIds = memberships.map((m) => m.id);+ if (membershipIds.length) await db(TableName.MembershipRole).whereIn("membershipId", membershipIds).del();+ await db(TableName.UserSecretActivation).whereIn("orgId", createdOrgIds).del();+ await db(TableName.Membership).whereIn("scopeOrgId", createdOrgIds).del();+ await db(TableName.Organization).whereIn("id", createdOrgIds).del();+ }+ if (createdUserIds.length) await db(TableName.Users).whereIn("id", createdUserIds).del();+ });++ test("old org (62 days) → no activation and no row created", async () => {+ const db = getDb();+ const org = await createOrgWithAdmin(db, daysAgo(62));++ const res = await callActivation(org.id);+ expect(res.statusCode).toBe(200);+ expect(res.json().shouldShowActivation).toBe(false);++ const row = await getActivationRow(db, org.id);+ expect(row).toBeUndefined();+ });++ test("new org (60 days) with more than 5 users → no activation and no row created", async () => {+ const db = getDb();+ const org = await createOrgWithAdmin(db, daysAgo(60));+ // admin member + 5 more = 6 users (> 5)+ for (let i = 0; i < 5; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await addAcceptedMember(db, org.id);+ }++ const res = await callActivation(org.id);+ expect(res.statusCode).toBe(200);+ expect(res.json().shouldShowActivation).toBe(false);++ const row = await getActivationRow(db, org.id);+ expect(row).toBeUndefined();+ });++ test("new org, < 5 users, first interaction → firstSecretCreatedAt is set", async () => {+ const db = getDb();+ const org = await createOrgWithAdmin(db, daysAgo(1));++ const res = await callActivation(org.id);+ expect(res.statusCode).toBe(200);+ const body = res.json();+ expect(body.shouldShowActivation).toBe(true);+ expect(body.stage).toBe("FIRST_SECRET");++ const row = await getActivationRow(db, org.id);+ expect(row).toBeDefined();+ expect(row?.firstSecretCreatedAt).not.toBeNull();+ });++ test("returning after 3 days → returnedAfterThreeDaysAt is set", async () => {+ const db = getDb();+ const org = await createOrgWithAdmin(db, daysAgo(5));+ await db(TableName.UserSecretActivation).insert({+ userId: seedData1.id,+ orgId: org.id,+ firstSecretCreatedAt: daysAgo(4)+ });++ const res = await callActivation(org.id);+ expect(res.statusCode).toBe(200);+ expect(res.json().stage).toBe("THREE_DAYS");++ const row = await getActivationRow(db, org.id);+ expect(row).toBeDefined();+ expect(row?.returnedAfterThreeDaysAt).not.toBeNull();+ });++ test("returning after 7 days → returnedAfterSevenDaysAt is set", async () => {+ const db = getDb();+ const org = await createOrgWithAdmin(db, daysAgo(10));+ await db(TableName.UserSecretActivation).insert({+ userId: seedData1.id,+ orgId: org.id,+ firstSecretCreatedAt: daysAgo(8),+ returnedAfterThreeDaysAt: daysAgo(5)+ });++ const res = await callActivation(org.id);+ expect(res.statusCode).toBe(200);+ expect(res.json().stage).toBe("SEVEN_DAYS");++ const row = await getActivationRow(db, org.id);+ expect(row).toBeDefined();+ expect(row?.returnedAfterSevenDaysAt).not.toBeNull();+ });++ test("all activation stages already recorded → no activation shown", async () => {+ const db = getDb();+ const org = await createOrgWithAdmin(db, daysAgo(10));+ await db(TableName.UserSecretActivation).insert({+ userId: seedData1.id,+ orgId: org.id,+ firstSecretCreatedAt: daysAgo(8),+ returnedAfterThreeDaysAt: daysAgo(5),+ returnedAfterSevenDaysAt: daysAgo(1)+ });++ const res = await callActivation(org.id);+ expect(res.statusCode).toBe(200);+ const body = res.json();+ expect(body.shouldShowActivation).toBe(false);+ expect(body.stage).toBeNull();+ });+});diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 366e43381b..d517122a50 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -684,6 +684,9 @@ import {TUserGroupMembershipInsert,TUserGroupMembershipUpdate,TUsers,+ TUserSecretActivation,+ TUserSecretActivationInsert,+ TUserSecretActivationUpdate,TUsersInsert,TUsersUpdate,TVaultExternalMigrationConfigs,@@ -839,6 +842,11 @@ declare module "knex" {declare module "knex/types/tables" {interface Tables {[TableName.Users]: KnexOriginal.CompositeTableType<TUsers, TUsersInsert, TUsersUpdate>;+ [TableName.UserSecretActivation]: KnexOriginal.CompositeTableType<+ TUserSecretActivation,+ TUserSecretActivationInsert,+ TUserSecretActivationUpdate+ >;[TableName.Groups]: KnexOriginal.CompositeTableType<TGroups, TGroupsInsert, TGroupsUpdate>;[TableName.SshHostGroup]: KnexOriginal.CompositeTableType<TSshHostGroups,diff --git a/backend/src/db/migrations/20260702120000_create-user-secret-activation.ts b/backend/src/db/migrations/20260702120000_create-user-secret-activation.tsindex 7808f1085d..d0ea192fad 100644--- a/backend/src/db/migrations/20260702120000_create-user-secret-activation.ts+++ b/backend/src/db/migrations/20260702120000_create-user-secret-activation.ts@@ -11,6 +11,7 @@ export async function up(knex: Knex): Promise<void> {t.datetime("firstSecretCreatedAt");t.datetime("returnedAfterThreeDaysAt");t.datetime("returnedAfterSevenDaysAt");+t.datetime("createdAt").notNullable().defaultTo(knex.fn.now());t.datetime("updatedAt").notNullable().defaultTo(knex.fn.now());diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex f113fc7569..291d3ca6f7 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -262,6 +262,7 @@ export * from "./user-actions";export * from "./user-aliases";export * from "./user-encryption-keys";export * from "./user-group-membership";+export * from "./user-secret-activation";export * from "./users";export * from "./vault-external-migration-configs";export * from "./webauthn-credentials";diff --git a/backend/src/db/schemas/user-secret-activation.ts b/backend/src/db/schemas/user-secret-activation.tsnew file mode 100644index 0000000000..9e1e5b9258--- /dev/null+++ b/backend/src/db/schemas/user-secret-activation.ts@@ -0,0 +1,23 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const UserSecretActivationSchema = z.object({+ id: z.string().uuid(),+ firstSecretCreatedAt: z.date().nullable().optional(),+ returnedAfterThreeDaysAt: z.date().nullable().optional(),+ returnedAfterSevenDaysAt: z.date().nullable().optional(),+ userId: z.string().uuid(),+ orgId: z.string().uuid(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TUserSecretActivation = z.infer<typeof UserSecretActivationSchema>;+export type TUserSecretActivationInsert = Omit<z.input<typeof UserSecretActivationSchema>, TImmutableDBKeys>;+export type TUserSecretActivationUpdate = Partial<Omit<z.input<typeof UserSecretActivationSchema>, TImmutableDBKeys>>;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex ad86aa850b..b748e49452 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -525,6 +525,7 @@ import { totpConfigDALFactory } from "@app/services/totp/totp-config-dal";import { totpServiceFactory } from "@app/services/totp/totp-service";import { userDALFactory } from "@app/services/user/user-dal";import { userServiceFactory } from "@app/services/user/user-service";+import { userActivationDALFactory } from "@app/services/user-activation/user-activation-dal";import { userActivationServiceFactory } from "@app/services/user-activation/user-activation-service";import { userAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { userEngagementServiceFactory } from "@app/services/user-engagement/user-engagement-service";@@ -598,6 +599,7 @@ export const registerRoutes = async (const authTokenDAL = tokenDALFactory(db);const orgDAL = orgDALFactory(db);const orgMembershipDAL = orgMembershipDALFactory(db);+ const userActivationDAL = userActivationDALFactory(db);const incidentContactDAL = incidentContactDALFactory(db);const rateLimitDAL = rateLimitDALFactory(db);@@ -2597,7 +2599,11 @@ export const registerRoutes = async (telemetryService});- const userActivationService = userActivationServiceFactory();+ const userActivationService = userActivationServiceFactory({+ userActivationDAL,+ permissionService,+ orgDAL+ });const userEngagementService = userEngagementServiceFactory({userDAL,diff --git a/backend/src/server/routes/v1/user-activation-router.ts b/backend/src/server/routes/v1/user-activation-router.tsindex 762aeb0ac7..819c84d985 100644--- a/backend/src/server/routes/v1/user-activation-router.ts+++ b/backend/src/server/routes/v1/user-activation-router.ts@@ -7,22 +7,34 @@ import { AuthMode } from "@app/services/auth/auth-type";export const registerUserActivationRouter = async (server: FastifyZodProvider) => {server.route({url: "/secrets",- method: "GET",+ method: "POST",config: {rateLimit: readLimit},schema: {- operationId: "getSecretsActivationStatus",+ operationId: "checkSecretsActivation",response: {200: z.object({- userId: z.string(),- orgId: z.string()+ shouldShowActivation: z.boolean(),+ stage: z.enum(["FIRST_SECRET", "THREE_DAYS", "SEVEN_DAYS"]).nullable(),+ activation: z+ .object({+ firstSecretCreatedAt: z.date().nullable(),+ returnedAfterThreeDaysAt: z.date().nullable(),+ returnedAfterSevenDaysAt: z.date().nullable()+ })+ .nullable()})}},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- return server.services.userActivation.getSecretsActivationStatus(req.permission.id, req.permission.orgId);+ return server.services.userActivation.getSecretsActivationStatus({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });}});};diff --git a/backend/src/services/user-activation/user-activation-dal.ts b/backend/src/services/user-activation/user-activation-dal.tsindex f9c35e25ba..6dcd3ff3d3 100644--- a/backend/src/services/user-activation/user-activation-dal.ts+++ b/backend/src/services/user-activation/user-activation-dal.ts@@ -1,5 +1,11 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";+export type TUserActivationDALFactory = ReturnType<typeof userActivationDALFactory>;-export const userActivationDALFactory = () => {- return {};+export const userActivationDALFactory = (db: TDbClient) => {+ const userActivationOrm = ormify(db, TableName.UserSecretActivation);++ return userActivationOrm;};diff --git a/backend/src/services/user-activation/user-activation-service.ts b/backend/src/services/user-activation/user-activation-service.tsindex cac25329ec..c36fb866ae 100644--- a/backend/src/services/user-activation/user-activation-service.ts+++ b/backend/src/services/user-activation/user-activation-service.ts@@ -1,8 +1,123 @@+import { OrganizationActionScope } from "@app/db/schemas";+import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { TOrgDALFactory } from "@app/services/org/org-dal";++import { TUserActivationDALFactory } from "./user-activation-dal";+import { TGetSecretsActivationStatusDTO } from "./user-activation-types";++const DAY_IN_MS = 24 * 60 * 60 * 1000;+const ORG_MAX_AGE_MONTHS = 2;+const ORG_MAX_MEMBERS = 5;+const RETURNED_AFTER_THREE_DAYS_MS = 3 * DAY_IN_MS;+const RETURNED_AFTER_SEVEN_DAYS_MS = 7 * DAY_IN_MS;++type TUserActivationServiceFactoryDep = {+ userActivationDAL: TUserActivationDALFactory;+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;+ orgDAL: Pick<TOrgDALFactory, "findById" | "countAllOrgMembers">;+};+export type TUserActivationServiceFactory = ReturnType<typeof userActivationServiceFactory>;-export const userActivationServiceFactory = () => {- const getSecretsActivationStatus = async (userId: string, orgId: string) => {- return { userId, orgId };+type TActivationRecord = {+ firstSecretCreatedAt?: Date | null;+ returnedAfterThreeDaysAt?: Date | null;+ returnedAfterSevenDaysAt?: Date | null;+};++type TSecretsActivationStatus = {+ shouldShowActivation: boolean;+ stage: "FIRST_SECRET" | "THREE_DAYS" | "SEVEN_DAYS" | null;+ activation: {+ firstSecretCreatedAt: Date | null;+ returnedAfterThreeDaysAt: Date | null;+ returnedAfterSevenDaysAt: Date | null;+ } | null;+};++export const userActivationServiceFactory = ({+ userActivationDAL,+ permissionService,+ orgDAL+}: TUserActivationServiceFactoryDep) => {+ const toActivation = (record: TActivationRecord) => ({+ firstSecretCreatedAt: record.firstSecretCreatedAt ?? null,+ returnedAfterThreeDaysAt: record.returnedAfterThreeDaysAt ?? null,+ returnedAfterSevenDaysAt: record.returnedAfterSevenDaysAt ?? null+ });++ // Decides whether the UI should surface the member-invite activation banner and, if so, which+ // message. Gated on the org being young, small, and the caller being able to invite members.+ const getSecretsActivationStatus = async ({+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod+ }: TGetSecretsActivationStatusDTO): Promise<TSecretsActivationStatus> => {+ const noActivation: TSecretsActivationStatus = { shouldShowActivation: false, stage: null, activation: null };++ // 1. The caller must be able to invite other members to the org.+ const { permission } = await permissionService.getOrgPermission({+ actor,+ actorId,+ orgId: actorOrgId,+ actorOrgId,+ actorAuthMethod,+ scope: OrganizationActionScope.Any+ });+ if (!permission.can(OrgPermissionActions.Create, OrgPermissionSubjects.Member)) return noActivation;++ // 2. The org must be younger than 2 months.+ const org = await orgDAL.findById(actorOrgId);+ if (!org) return noActivation;+ const orgAgeCutoff = new Date();+ orgAgeCutoff.setMonth(orgAgeCutoff.getMonth() - ORG_MAX_AGE_MONTHS);+ if (org.createdAt.getTime() < orgAgeCutoff.getTime()) return noActivation;++ // 3. The org must have fewer than 5 users.+ const memberCount = await orgDAL.countAllOrgMembers(actorOrgId);+ if (memberCount >= ORG_MAX_MEMBERS) return noActivation;++ const existingActivation = await userActivationDAL.findOne({ userId: actorId, orgId: actorOrgId });+ const now = new Date();++ // First interaction: creating the row is itself the signal that this is the user's first action,+ // so we stamp firstSecretCreatedAt. This also covers orgs that predate the feature.+ if (!existingActivation) {+ const createdActivation = await userActivationDAL.create({+ userId: actorId,+ orgId: actorOrgId,+ firstSecretCreatedAt: now+ });+ return { shouldShowActivation: true, stage: "FIRST_SECRET", activation: toActivation(createdActivation) };+ }++ // if the row was created and the firstSecretCreatedAt is not set, it means the user has not created a secret yet+ if (!existingActivation.firstSecretCreatedAt) {+ existingActivation.firstSecretCreatedAt = now;+ await userActivationDAL.updateById(existingActivation.id, existingActivation);++ return { shouldShowActivation: true, stage: "FIRST_SECRET", activation: toActivation(existingActivation) };+ }++ const elapsedMs = now.getTime() - existingActivation.firstSecretCreatedAt.getTime();++ if (!existingActivation.returnedAfterThreeDaysAt && elapsedMs >= RETURNED_AFTER_THREE_DAYS_MS) {+ const updatedActivation = await userActivationDAL.updateById(existingActivation.id, {+ returnedAfterThreeDaysAt: now+ });+ return { shouldShowActivation: true, stage: "THREE_DAYS", activation: toActivation(updatedActivation) };+ }++ if (!existingActivation.returnedAfterSevenDaysAt && elapsedMs >= RETURNED_AFTER_SEVEN_DAYS_MS) {+ const updatedActivation = await userActivationDAL.updateById(existingActivation.id, {+ returnedAfterSevenDaysAt: now+ });+ return { shouldShowActivation: true, stage: "SEVEN_DAYS", activation: toActivation(updatedActivation) };+ }++ return { shouldShowActivation: false, stage: null, activation: toActivation(existingActivation) };};return {diff --git a/backend/src/services/user-activation/user-activation-types.ts b/backend/src/services/user-activation/user-activation-types.tsindex e69de29bb2..a54a2a4a68 100644--- a/backend/src/services/user-activation/user-activation-types.ts+++ b/backend/src/services/user-activation/user-activation-types.ts@@ -0,0 +1,8 @@+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";++export type TGetSecretsActivationStatusDTO = {+ actor: ActorType;+ actorId: string;+ actorOrgId: string;+ actorAuthMethod: ActorAuthMethod;+};diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/InviteMembersModal.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/InviteMembersModal.tsxnew file mode 100644index 0000000000..cca426dce7--- /dev/null+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/InviteMembersModal.tsx@@ -0,0 +1,240 @@+import { useMemo } from "react";+import { Controller, useFieldArray, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { InfoIcon, SendHorizontalIcon } from "lucide-react";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ CreatableSelect,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldError,+ FieldLabel,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { useOrganization, useProject } from "@app/context";+import { useGetOrgUsers, useGetWorkspaceUsers } from "@app/hooks/api";+import { UsePopUpState } from "@app/hooks/usePopUp";++const inviteMembersFormSchema = z.object({+ members: z+ .array(+ z.object({+ label: z.string().trim(),+ value: z.string().trim(),+ isNewInvitee: z.boolean().optional()+ })+ )+ .min(1)+});++type TInviteMembersForm = z.infer<typeof inviteMembersFormSchema>;++type Props = {+ popUp: UsePopUpState<["inviteMembers"]>;+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["inviteMembers"]>, state?: boolean) => void;+};++const getInitials = (user: {+ firstName?: string;+ lastName?: string;+ email?: string;+ username?: string;+}) => {+ const first = user.firstName?.trim();+ const last = user.lastName?.trim();+ if (first || last) {+ return `${first?.[0] ?? ""}${last?.[0] ?? ""}`.toUpperCase();+ }+ return (user.email || user.username || "?").charAt(0).toUpperCase();+};++export const InviteMembersModal = ({ popUp, handlePopUpToggle }: Props) => {+ const { currentOrg } = useOrganization();+ const { currentProject } = useProject();++ const orgId = currentOrg?.id || "";+ const projectId = currentProject?.id || "";++ const { data: members } = useGetWorkspaceUsers(projectId);+ const { data: orgUsers } = useGetOrgUsers(orgId);++ const {+ control,+ handleSubmit,+ reset,+ watch,+ formState: { isSubmitting, errors }+ } = useForm<TInviteMembersForm>({+ resolver: zodResolver(inviteMembersFormSchema),+ defaultValues: { members: [] }+ });++ const { append } = useFieldArray<TInviteMembersForm>({ control, name: "members" });++ // Org members that are not already part of this project, shown as suggestions.+ const suggestionList = useMemo(() => {+ const wsUserUsernames = new Map();+ members?.forEach((member) => {+ wsUserUsernames.set(member.user.username, true);+ });+ return (orgUsers || [])+ .filter(({ user: u }) => !wsUserUsernames.has(u.username))+ .map(({ id, inviteEmail, user: { firstName, lastName, email } }) => ({+ value: id,+ label:+ firstName && lastName+ ? `${firstName} ${lastName}`+ : firstName || lastName || email || inviteEmail+ }));+ }, [orgUsers, members]);++ const teammates = useMemo(() => (members ?? []).slice(0, 3), [members]);+ const teammateCount = members?.length ?? 0;++ const selectedMembers = watch("members");++ const onInvite = () => {+ // Submit is intentionally UI only for now. The triggering action and the real+ // invite request are wired later (see the modal plan for how to reuse+ // useAddUserToWsNonE2EE with the default Member role).+ createNotification({+ type: "success",+ text: "Invites sent. Your teammates will get an email to join."+ });+ handlePopUpToggle("inviteMembers", false);+ reset();+ };++ return (+ <Dialog+ open={popUp?.inviteMembers?.isOpen}+ onOpenChange={(isOpen) => {+ handlePopUpToggle("inviteMembers", isOpen);+ if (!isOpen) reset();+ }}+ >+ <DialogContent className="overflow-visible sm:max-w-md">+ <DialogHeader>+ {teammateCount > 0 && (+ <div className="flex items-center gap-3">+ <div className="flex">+ {teammates.map((member, idx) => (+ <span+ key={member.id}+ className={`flex size-7 items-center justify-center rounded-full border-2 border-popover bg-project/15 text-[11px] font-semibold text-project ${+ idx > 0 ? "-ml-2" : ""+ }`}+ >+ {getInitials(member.user)}+ </span>+ ))}+ </div>+ <span className="text-xs text-muted">+ {teammateCount} {teammateCount === 1 ? "teammate" : "teammates"} already on this+ project+ </span>+ </div>+ )}+ <DialogTitle>Invite your team</DialogTitle>+ <DialogDescription>+ Everyone has secrets, even your colleagues. Bring your team in to review, rotate, and+ manage them together.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit(onInvite)} className="flex flex-col gap-4">+ <Controller+ control={control}+ name="members"+ render={({ field }) => (+ <Field>+ <FieldLabel>+ People+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label="Role information"+ className="text-muted transition-colors hover:text-foreground"+ >+ <InfoIcon className="size-3" />+ </button>+ </TooltipTrigger>+ <TooltipContent>New members join with the Member role.</TooltipContent>+ </Tooltip>+ </FieldLabel>+ <FieldContent>+ <CreatableSelect+ /* eslint-disable-next-line react/no-unstable-nested-components */+ noOptionsMessage={() => (+ <p>Type an email address to invite someone new to your organization.</p>+ )}+ onCreateOption={(inputValue) =>+ append({ label: inputValue, value: inputValue, isNewInvitee: true })+ }+ formatCreateLabel={(inputValue) => `Invite "${inputValue}"`}+ isValidNewOption={(input) =>+ Boolean(input) &&+ z.string().email().safeParse(input).success &&+ !orgUsers+ ?.flatMap(({ user }) => {+ const emails: string[] = [];++ if (user.email) {+ emails.push(user.email);+ }++ if (user.username) {+ emails.push(user.username);+ }++ return emails;+ })+ .includes(input)+ }+ placeholder="[email protected]"+ isMulti+ name="members"+ options={suggestionList}+ value={field.value}+ onChange={field.onChange}+ isError={!!errors.members?.length}+ />+ </FieldContent>+ <FieldError>{errors.members?.[0]?.message}</FieldError>+ </Field>+ )}+ />+ <DialogFooter>+ <Button+ variant="ghost"+ type="button"+ onClick={() => handlePopUpToggle("inviteMembers", false)}+ >+ Maybe later+ </Button>+ <Button+ type="submit"+ variant="project"+ isPending={isSubmitting}+ isDisabled={isSubmitting || selectedMembers.length === 0}+ >+ <SendHorizontalIcon />+ Send invites+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsxindex 7afc7b366b..62b4cbd7eb 100644--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx@@ -26,6 +26,7 @@ import { ActorType } from "@app/hooks/api/auditLogs/enums";import { ProjectType } from "@app/hooks/api/projects/types";import { AddMemberModal } from "./AddMemberModal";+import { InviteMembersModal } from "./InviteMembersModal";import { MembersTable } from "./MembersTable";export const MembersSection = () => {@@ -38,6 +39,7 @@ export const MembersSection = () => {const { handlePopUpToggle, popUp, handlePopUpOpen, handlePopUpClose } = usePopUp(["addMember",+ "inviteMembers","removeMember","assumePrivileges"] as const);@@ -72,21 +74,38 @@ export const MembersSection = () => {{`Invite and manage ${productLabel.toLowerCase()} users`}</CardDescription><CardAction>- <ProjectPermissionCan- I={ProjectPermissionActions.Create}- a={ProjectPermissionSub.Member}- >- {(isAllowed) => (- <Button- variant="project"- onClick={() => handlePopUpOpen("addMember")}- isDisabled={!isAllowed}- >- <UserPlusIcon />- {isCertManager ? "Add Users" : `Add Users to ${productLabel}`}- </Button>- )}- </ProjectPermissionCan>+ <div className="flex items-center gap-2">+ {/* TEMP: preview trigger for the Invite Members modal. Replace with the real action later. */}+ <ProjectPermissionCan+ I={ProjectPermissionActions.Create}+ a={ProjectPermissionSub.Member}+ >+ {(isAllowed) => (+ <Button+ variant="outline"+ onClick={() => handlePopUpOpen("inviteMembers")}+ isDisabled={!isAllowed}+ >+ Invite team (preview)+ </Button>+ )}+ </ProjectPermissionCan>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Create}+ a={ProjectPermissionSub.Member}+ >+ {(isAllowed) => (+ <Button+ variant="project"+ onClick={() => handlePopUpOpen("addMember")}+ isDisabled={!isAllowed}+ >+ <UserPlusIcon />+ {isCertManager ? "Add Users" : `Add Users to ${productLabel}`}+ </Button>+ )}+ </ProjectPermissionCan>+ </div></CardAction></CardHeader><CardContent>@@ -94,6 +113,7 @@ export const MembersSection = () => {</CardContent></Card><AddMemberModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />+ <InviteMembersModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} /><DeleteActionModalisOpen={popUp.removeMember.isOpen}deleteKey="remove"