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
apply review recommendations
adilsone9b76bfe340d
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex dbfdb0a0ea..f5ef3622db 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -239,21 +239,10 @@ const envSchema = z// GitHub API token for upgrade path toolGITHUB_API_TOKEN: zpStr(z.string().optional()),// Secrets activation nudge tuning. Gates whether the member-invite activation banner shows and- // how long after the first secret the follow-up nudges appear.+ // the org size/age window in which it appears.+ SECRETS_ACTIVATION_ENABLED: zodStrBool.default("false"),SECRETS_ACTIVATION_ORG_MAX_AGE_MONTHS: z.coerce.number().default(2),SECRETS_ACTIVATION_ORG_MAX_MEMBERS: z.coerce.number().default(5),- SECRETS_ACTIVATION_FIRST_NUDGE_DELAY: zpStr(- z- .string()- .default("3d")- .transform((val) => ms(val))- ),- SECRETS_ACTIVATION_SECOND_NUDGE_DELAY: zpStr(- z- .string()- .default("7d")- .transform((val) => ms(val))- ),// jwt optionsAUTH_SECRET: zpStr(z.string()).default(process.env.JWT_AUTH_SECRET), // for those still using old JWT_AUTH_SECRETJWT_AUTH_LIFETIME: zpStr(z.string().default("10d")),diff --git a/backend/src/services/user-activation/user-activation-service.ts b/backend/src/services/user-activation/user-activation-service.tsindex 14a26775e3..df5f904db9 100644--- a/backend/src/services/user-activation/user-activation-service.ts+++ b/backend/src/services/user-activation/user-activation-service.ts@@ -2,11 +2,17 @@ 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 { getConfig } from "@app/lib/config/env";+import { ms } from "@app/lib/ms";import { TOrgDALFactory } from "@app/services/org/org-dal";import { TUserActivationDALFactory } from "./user-activation-dal";import { TActivationRecord, TGetSecretsActivationStatusDTO, TSecretsActivationStatus } from "./user-activation-types";+// How long after the first secret the follow-up activation nudges appear. These are product-defined+// constants rather than deployment config — they don't vary per environment.+const FIRST_NUDGE_DELAY = ms("3d");+const SECOND_NUDGE_DELAY = ms("7d");+type TUserActivationServiceFactoryDep = {userActivationDAL: TUserActivationDALFactory;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;@@ -37,6 +43,8 @@ export const userActivationServiceFactory = ({const noActivation: TSecretsActivationStatus = { shouldShowActivation: false, stage: null, activation: null };const appCfg = getConfig();+ if (!appCfg.SECRETS_ACTIVATION_ENABLED) return noActivation;+// 1. The caller must be able to invite other members to the org.const { permission } = await permissionService.getOrgPermission({actor,@@ -86,7 +94,7 @@ export const userActivationServiceFactory = ({const elapsedMs = now.getTime() - existingActivation.firstSecretCreatedAt.getTime();- if (!existingActivation.returnedAfterThreeDaysAt && elapsedMs >= appCfg.SECRETS_ACTIVATION_FIRST_NUDGE_DELAY) {+ if (!existingActivation.returnedAfterThreeDaysAt && elapsedMs >= FIRST_NUDGE_DELAY) {const updatedActivation = await userActivationDAL.updateById(existingActivation.id,{ returnedAfterThreeDaysAt: now },@@ -95,13 +103,18 @@ export const userActivationServiceFactory = ({return { shouldShowActivation: true, stage: "THREE_DAYS", activation: toActivation(updatedActivation) };}- if (!existingActivation.returnedAfterSevenDaysAt && elapsedMs >= appCfg.SECRETS_ACTIVATION_SECOND_NUDGE_DELAY) {- const updatedActivation = await userActivationDAL.updateById(- existingActivation.id,- { returnedAfterSevenDaysAt: now },- tx- );- return { shouldShowActivation: true, stage: "SEVEN_DAYS", activation: toActivation(updatedActivation) };+ // The seven-day nudge only follows the three-day nudge, so it's gated on that timestamp being set.+ if (existingActivation.returnedAfterThreeDaysAt && !existingActivation.returnedAfterSevenDaysAt) {+ const secondWindowElapsedMs = now.getTime() - existingActivation.returnedAfterThreeDaysAt.getTime();++ if (secondWindowElapsedMs >= SECOND_NUDGE_DELAY) {+ const updatedActivation = await userActivationDAL.updateById(+ existingActivation.id,+ { returnedAfterSevenDaysAt: now },+ tx+ );+ return { shouldShowActivation: true, stage: "SEVEN_DAYS", activation: toActivation(updatedActivation) };+ }}return { shouldShowActivation: false, stage: null, activation: toActivation(existingActivation) };diff --git a/frontend/src/helpers/email.ts b/frontend/src/helpers/email.tsnew file mode 100644index 0000000000..771b82e29f--- /dev/null+++ b/frontend/src/helpers/email.ts@@ -0,0 +1,85 @@+import { z } from "zod";++const EmailSchema = z.string().email().min(1).trim().toLowerCase();++// Zod's .email() accepts addresses the backend/DB reject: domain labels over 63 chars+// (backend/src/lib/validator/validate-email.ts) and emails longer than the users table's+// varchar(255) email/username columns. Mirror both here so oversized/malformed addresses are+// caught inline instead of failing with a 400 (bad domain) or 500 (too long) from the API.+const MAX_EMAIL_LENGTH = 255;+const MAX_DOMAIN_LABEL_LENGTH = 63;+const DOMAIN_LABEL_REGEX = /^[a-zA-Z0-9-]+$/;+const TLD_REGEX = /^[a-zA-Z0-9]+$/;++const isValidEmailDomain = (domain: string) => {+ const labels = domain.split(".");+ if (labels.length < 2) return false;++ const tld = labels[labels.length - 1];+ if (tld.length < 2 || !TLD_REGEX.test(tld)) return false;++ return labels.every(+ (label) =>+ label.length > 0 &&+ label.length <= MAX_DOMAIN_LABEL_LENGTH &&+ !label.startsWith("-") &&+ !label.endsWith("-") &&+ DOMAIN_LABEL_REGEX.test(label)+ );+};++export const isValidEmail = (email: string) =>+ email.length <= MAX_EMAIL_LENGTH &&+ EmailSchema.safeParse(email).success &&+ isValidEmailDomain(email.slice(email.indexOf("@") + 1));++// Mirror the backend cap (inviteeEmails.array().max(100)) so oversized invites are rejected inline+// before hitting the API.+export const MAX_INVITE_EMAILS = 100;++export const parseEmailList = (value: string) =>+ value+ .split(",")+ .map((email) => email.trim())+ .filter(Boolean);++// Shared validation for a comma-separated email list entered in a textarea. Embed it directly as an+// object field in a react-hook-form schema: z.object({ emails: emailListSchema, ... }).+export const emailListSchema = z+ .string()+ .trim()+ .toLowerCase()+ .superRefine((value, ctx) => {+ const emails = parseEmailList(value);++ if (!emails.length) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Please enter at least one email address."+ });+ return;+ }++ if (emails.length > MAX_INVITE_EMAILS) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `You can invite up to ${MAX_INVITE_EMAILS} users at a time.`+ });+ }++ const invalidEmails = emails.filter((email) => !isValidEmail(email));++ if (invalidEmails.length) {+ const preview = invalidEmails+ .slice(0, 3)+ .map((email) => (email.length > 40 ? `${email.slice(0, 40)}...` : email))+ .join(", ");+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ invalidEmails.length > 3+ ? `${invalidEmails.length} invalid email addresses (e.g. ${preview}).`+ : `Invalid email address${invalidEmails.length > 1 ? "es" : ""}: ${preview}.`+ });+ }+ });diff --git a/frontend/src/hooks/useSecretsActivationNudge.tsx b/frontend/src/hooks/useSecretsActivationNudge.tsxindex b93852cb13..1d7ba1aef2 100644--- a/frontend/src/hooks/useSecretsActivationNudge.tsx+++ b/frontend/src/hooks/useSecretsActivationNudge.tsx@@ -47,6 +47,7 @@ export const useSecretsActivationNudge = () => {if (!isRootOrganization || !canInviteMembers || !currentOrg?.id) return;const queryKey = userActivationKeys.secretsStatus(currentOrg.id, user.id);+ console.log("queryKey", queryKey);// Already checked this session (cached): don't call again and don't re-open the modal.if (queryClient.getQueryData(queryKey) !== undefined) return;diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsxindex 49dfc7b99b..df18e0c335 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx@@ -26,6 +26,7 @@ import {TooltipTrigger} from "@app/components/v3";import { useOrganization } from "@app/context";+import { emailListSchema, parseEmailList } from "@app/helpers/email";import { getProjectLucideIcon, getProjectTitle } from "@app/helpers/project";import { findOrgMembershipRole } from "@app/helpers/roles";import {@@ -119,88 +120,8 @@ const ProductSingleValue = ({ children, ...props }: SingleValueProps<ProductDefi);};-const EmailSchema = z.string().email().min(1).trim().toLowerCase();--// Zod's .email() accepts addresses the backend/DB reject: domain labels over 63 chars-// (backend/src/lib/validator/validate-email.ts) and emails longer than the users table's-// varchar(255) email/username columns. Mirror both here so oversized/malformed addresses are-// caught inline instead of failing with a 400 (bad domain) or 500 (too long) from the API.-const MAX_EMAIL_LENGTH = 255;-const MAX_DOMAIN_LABEL_LENGTH = 63;-const DOMAIN_LABEL_REGEX = /^[a-zA-Z0-9-]+$/;-const TLD_REGEX = /^[a-zA-Z0-9]+$/;--const isValidEmailDomain = (domain: string) => {- const labels = domain.split(".");- if (labels.length < 2) return false;-- const tld = labels[labels.length - 1];- if (tld.length < 2 || !TLD_REGEX.test(tld)) return false;-- return labels.every(- (label) =>- label.length > 0 &&- label.length <= MAX_DOMAIN_LABEL_LENGTH &&- !label.startsWith("-") &&- !label.endsWith("-") &&- DOMAIN_LABEL_REGEX.test(label)- );-};--const isValidEmail = (email: string) =>- email.length <= MAX_EMAIL_LENGTH &&- EmailSchema.safeParse(email).success &&- isValidEmailDomain(email.slice(email.indexOf("@") + 1));--// Mirror the backend cap (inviteeEmails.array().max(100)) so oversized invites are rejected inline-// before hitting the API.-const MAX_INVITE_EMAILS = 100;--const parseEmailList = (value: string) =>- value- .split(",")- .map((email) => email.trim())- .filter(Boolean);-const addMemberFormSchema = z.object({- emails: z- .string()- .trim()- .toLowerCase()- .superRefine((value, ctx) => {- const emails = parseEmailList(value);-- if (!emails.length) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "Please enter at least one email address."- });- return;- }-- if (emails.length > MAX_INVITE_EMAILS) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `You can invite up to ${MAX_INVITE_EMAILS} users at a time.`- });- }-- const invalidEmails = emails.filter((email) => !isValidEmail(email));-- if (invalidEmails.length) {- const preview = invalidEmails- .slice(0, 3)- .map((email) => (email.length > 40 ? `${email.slice(0, 40)}...` : email))- .join(", ");- ctx.addIssue({- code: z.ZodIssueCode.custom,- message:- invalidEmails.length > 3- ? `${invalidEmails.length} invalid email addresses (e.g. ${preview}).`- : `Invalid email address${invalidEmails.length > 1 ? "es" : ""}: ${preview}.`- });- }- }),+ emails: emailListSchema,product: z.object({type: z.nativeEnum(ProjectType),diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsxindex 83d9cdbd9e..2b7353078f 100644--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx@@ -705,7 +705,7 @@ const OverviewPageContent = () => {const hasSecrets = !isPlaceholderData && Boolean(totalSecretCount);useEffect(() => {if (hasSecrets) {- checkSecretsActivation(4000);+ checkSecretsActivation();}}, [hasSecrets, checkSecretsActivation]);@@ -2134,7 +2134,6 @@ const OverviewPageContent = () => {// surface the activation nudge.const createdSecret = changes.secrets.some((s) => s.type === PendingAction.Create);if (createdSecret && !requiresApproval) {- console.log("createdSecret", createdSecret);checkSecretsActivation();}},diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsxindex 4deab4de98..4e23982223 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsx@@ -1,14 +1,14 @@-import { useEffect } from "react";-import { Controller, useFieldArray, useForm } from "react-hook-form";+import { useEffect, useMemo } from "react";+import { Controller, 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 { RoleOption } from "@app/components/roles";import Telemetry from "@app/components/utilities/telemetry/Telemetry";import {Button,- CreatableSelect,Dialog,DialogContent,DialogDescription,@@ -16,18 +16,20 @@ import {DialogHeader,DialogTitle,Field,- FieldContent,FieldError,FieldLabel,+ FilterableSelect,+ TextArea,Tooltip,TooltipContent,TooltipTrigger} from "@app/components/v3";-import { useOrganization, useProject } from "@app/context";-import { useAddUserToWsNonE2EE, useGetOrgUsers } from "@app/hooks/api";+import { useOrganization, useProject, useProjectPermission } from "@app/context";+import { emailListSchema, parseEmailList } from "@app/helpers/email";+import { useAddUserToWsNonE2EE, useGetProjectRoles } from "@app/hooks/api";import { ProjectVersion } from "@app/hooks/api/projects/types";-import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { UsePopUpState } from "@app/hooks/usePopUp";+import { filterByGrantConditions, getMemberAssignRoleConditions } from "@app/lib/fn/permission";// PostHog event names for the secrets activation nudge, so we can measure the// shown -> invited/dismissed conversion funnel of this modal.@@ -37,15 +39,16 @@ const ACTIVATION_EVENTS = {Dismissed: "Secrets Activation Modal Dismissed"} as const;+const DEFAULT_PROJECT_ROLE = { slug: "member", name: "Member" };+const inviteMembersFormSchema = z.object({- members: z- .array(- z.object({- label: z.string().trim(),- value: z.string().trim()- })- )- .min(1)+ emails: emailListSchema,+ projectRole: z+ .object({+ slug: z.string().min(1),+ name: z.string().min(1)+ })+ .default(DEFAULT_PROJECT_ROLE)});type TInviteMembersForm = z.infer<typeof inviteMembersFormSchema>;@@ -58,25 +61,41 @@ type Props = {export const InviteMembersModal = ({ popUp, handlePopUpToggle }: Props) => {const { currentOrg } = useOrganization();const { currentProject } = useProject();+ const { permission: projectPermission } = useProjectPermission();const orgId = currentOrg?.id || "";const projectId = currentProject?.id || "";- const { data: orgUsers } = useGetOrgUsers(orgId);+ const { data: roles, isPending: isProjectRolesLoading } = useGetProjectRoles(+ projectId,+ currentProject?.type+ );++ const assignRoleConditions = useMemo(+ () => getMemberAssignRoleConditions(projectPermission),+ [projectPermission]+ );++ const filteredRoles = useMemo(+ () =>+ filterByGrantConditions(roles ?? [], {+ getKey: (role) => role.slug,+ allowed: assignRoleConditions?.roles,+ forbidden: assignRoleConditions?.forbiddenRoles+ }),+ [roles, assignRoleConditions]+ );const {control,handleSubmit,reset,- watch,- formState: { isSubmitting, errors }+ formState: { isSubmitting }} = useForm<TInviteMembersForm>({resolver: zodResolver(inviteMembersFormSchema),- defaultValues: { members: [] }+ defaultValues: { emails: "", projectRole: DEFAULT_PROJECT_ROLE }});- const { append } = useFieldArray<TInviteMembersForm>({ control, name: "members" });-const { mutateAsync: addUserToProject } = useAddUserToWsNonE2EE();const telemetry = new Telemetry().getInstance();@@ -90,9 +109,7 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle }: Props) => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [isOpen]);- const selectedMembers = watch("members");-- const onInvite = async ({ members: selectedPeople }: TInviteMembersForm) => {+ const onInvite = async ({ emails, projectRole }: TInviteMembersForm) => {if (!currentProject) return;if (!currentOrg?.id) return;@@ -104,15 +121,15 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle }: Props) => {return;}- // Every entry is a brand-new invitee typed in as an email address.- const usernames = selectedPeople.map((person) => person.value.toLowerCase());+ // emails is already trimmed + lowercased by the schema; parseEmailList splits the entries.+ const usernames = parseEmailList(emails);if (usernames.length) {await addUserToProject({usernames,orgId: currentOrg.id,projectId: currentProject.id,projectType: currentProject.type,- roleSlugs: [ProjectMembershipRole.Member]+ roleSlugs: [projectRole.slug]});}@@ -153,49 +170,55 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle }: Props) => {<form onSubmit={handleSubmit(onInvite)} className="flex flex-col gap-4"><Controllercontrol={control}- name="members"- render={({ field }) => (+ name="emails"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor="invite-members-emails">Emails</FieldLabel>+ <TextArea+ id="invite-members-emails"+ className="h-24"+ isError={Boolean(error)}+ placeholder="[email protected], [email protected]..."+ {...field}+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="projectRole"+ render={({ field: { value, onChange }, fieldState: { error } }) => (<Field>- <FieldLabel>- People+ <FieldLabel+ htmlFor="invite-members-project-role"+ className="flex items-center gap-1.5"+ >+ Project role<Tooltip>- <TooltipTrigger asChild>- <button- type="button"- aria-label="Role information"- className="text-muted transition-colors hover:text-foreground"- >- <InfoIcon className="size-3" />- </button>+ <TooltipTrigger tabIndex={-1} asChild>+ <span>+ <InfoIcon className="size-3 text-muted" />+ </span></TooltipTrigger>- <TooltipContent>New members join with the Member role.</TooltipContent>+ <TooltipContent className="max-w-md">+ Select which role to assign to the invited members in this project.+ </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 })- }- formatCreateLabel={(inputValue) => `Invite "${inputValue}"`}- isValidNewOption={(input) =>- Boolean(input) &&- z.string().email().safeParse(input).success &&- !orgUsers?.some(({ user }) => user.email === input || user.username === input)- }- placeholder="[email protected]"- isMulti- name="members"- components={{ DropdownIndicator: null, IndicatorSeparator: null }}- value={field.value}- onChange={field.onChange}- isError={!!errors.members?.length}- />- </FieldContent>- <FieldError>{errors.members?.[0]?.message}</FieldError>+ <FilterableSelect+ inputId="invite-members-project-role"+ isLoading={Boolean(projectId) && isProjectRolesLoading}+ value={value}+ onChange={onChange}+ options={filteredRoles}+ getOptionValue={(option) => option.slug}+ getOptionLabel={(option) => option.name}+ placeholder="Select role..."+ isError={Boolean(error)}+ components={{ Option: RoleOption }}+ />+ <FieldError>{error?.message}</FieldError></Field>)}/>@@ -215,7 +238,7 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle }: Props) => {type="submit"variant="project"isPending={isSubmitting}- isDisabled={isSubmitting || selectedMembers.length === 0}+ isDisabled={isSubmitting}><SendHorizontalIcon />Send invites