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
feat(secret-sharing): Specify Emails
x03220592bebf7d84e4
diff --git a/backend/src/db/migrations/20250517002223_secret-share-to-specific-emails.ts b/backend/src/db/migrations/20250517002223_secret-share-to-specific-emails.tsnew file mode 100644index 0000000000..6a02ae4ebd--- /dev/null+++ b/backend/src/db/migrations/20250517002223_secret-share-to-specific-emails.ts@@ -0,0 +1,43 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.SecretSharing)) {+ const hasEncryptedSalt = await knex.schema.hasColumn(TableName.SecretSharing, "encryptedSalt");+ const hasAuthorizedEmails = await knex.schema.hasColumn(TableName.SecretSharing, "authorizedEmails");++ if (!hasEncryptedSalt || !hasAuthorizedEmails) {+ await knex.schema.alterTable(TableName.SecretSharing, (t) => {+ // These two columns are only needed when secrets are shared with a specific list of emails++ if (!hasEncryptedSalt) {+ t.binary("encryptedSalt").nullable();+ }++ if (!hasAuthorizedEmails) {+ t.json("authorizedEmails").nullable();+ }+ });+ }+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.SecretSharing)) {+ const hasEncryptedSalt = await knex.schema.hasColumn(TableName.SecretSharing, "encryptedSalt");+ const hasAuthorizedEmails = await knex.schema.hasColumn(TableName.SecretSharing, "authorizedEmails");++ if (hasEncryptedSalt || hasAuthorizedEmails) {+ await knex.schema.alterTable(TableName.SecretSharing, (t) => {+ if (hasEncryptedSalt) {+ t.dropColumn("encryptedSalt");+ }++ if (hasAuthorizedEmails) {+ t.dropColumn("authorizedEmails");+ }+ });+ }+ }+}diff --git a/backend/src/db/schemas/secret-sharing.ts b/backend/src/db/schemas/secret-sharing.tsindex 24ea266772..7de34708c5 100644--- a/backend/src/db/schemas/secret-sharing.ts+++ b/backend/src/db/schemas/secret-sharing.ts@@ -27,7 +27,9 @@ export const SecretSharingSchema = z.object({password: z.string().nullable().optional(),encryptedSecret: zodBuffer.nullable().optional(),identifier: z.string().nullable().optional(),- type: z.string().default("share")+ type: z.string().default("share"),+ encryptedSalt: zodBuffer.nullable().optional(),+ authorizedEmails: z.unknown().nullable().optional()});export type TSecretSharing = z.infer<typeof SecretSharingSchema>;diff --git a/backend/src/server/routes/v1/secret-sharing-router.ts b/backend/src/server/routes/v1/secret-sharing-router.tsindex 37c8a052f6..f191e4deb5 100644--- a/backend/src/server/routes/v1/secret-sharing-router.ts+++ b/backend/src/server/routes/v1/secret-sharing-router.ts@@ -62,7 +62,9 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>}),body: z.object({hashedHex: z.string().min(1).optional(),- password: z.string().optional()+ password: z.string().optional(),+ email: z.string().optional(),+ token: z.string().optional()}),response: {200: z.object({@@ -88,7 +90,9 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>sharedSecretId: req.params.id,hashedHex: req.body.hashedHex,password: req.body.password,- orgId: req.permission?.orgId+ orgId: req.permission?.orgId,+ email: req.body.email,+ token: req.body.token});if (sharedSecret.secret?.orgId) {@@ -151,7 +155,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>secretValue: z.string(),expiresAt: z.string(),expiresAfterViews: z.number().min(1).optional(),- accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization)+ accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization),+ emails: z.string().email().array().optional()}),response: {200: z.object({diff --git a/backend/src/services/secret-sharing/secret-sharing-service.ts b/backend/src/services/secret-sharing/secret-sharing-service.tsindex 9649be7228..ec7fa287ab 100644--- a/backend/src/services/secret-sharing/secret-sharing-service.ts+++ b/backend/src/services/secret-sharing/secret-sharing-service.ts@@ -6,6 +6,7 @@ import { TSecretSharing } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";import { getConfig } from "@app/lib/config/env";import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { SecretSharingAccessType } from "@app/lib/types";import { isUuidV4 } from "@app/lib/validator";@@ -76,8 +77,11 @@ export const secretSharingServiceFactory = ({password,accessType,expiresAt,- expiresAfterViews+ expiresAfterViews,+ emails}: TCreateSharedSecretDTO) => {+ const appCfg = getConfig();+const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);if (!permission) throw new ForbiddenRequestError({ name: "User is not a part of the specified organization" });$validateSharedSecretExpiry(expiresAt);@@ -94,6 +98,31 @@ export const secretSharingServiceFactory = ({}const encryptWithRoot = kmsService.encryptWithRootKey();++ let salt: string | undefined;+ let encryptedSalt: Buffer | undefined;+ const orgEmails = [];++ if (emails && emails.length > 0) {+ const allOrgMembers = await orgDAL.findAllOrgMembers(orgId);++ // Check to see that all emails are a part of the organization (if enforced) while also collecting a list of emails which are in the org+ for (const email of emails) {+ if (allOrgMembers.some((v) => v.user.email === email)) {+ orgEmails.push(email);+ // If the email is not part of the org, but access type / org settings require it+ } else if (!org.allowSecretSharingOutsideOrganization || accessType === SecretSharingAccessType.Organization) {+ throw new BadRequestError({+ message: "Organization does not allow sharing secrets to members outside of this organization"+ });+ }+ }++ // Generate salt for signing email tokens (if emails are provided)+ salt = crypto.randomBytes(32).toString("hex");+ encryptedSalt = encryptWithRoot(Buffer.from(salt));+ }+const encryptedSecret = encryptWithRoot(Buffer.from(secretValue));const id = crypto.randomBytes(32).toString("hex");@@ -112,11 +141,45 @@ export const secretSharingServiceFactory = ({expiresAfterViews,userId: actorId,orgId,- accessType+ accessType,+ authorizedEmails: emails && emails.length > 0 ? JSON.stringify(emails) : undefined,+ encryptedSalt});const idToReturn = `${Buffer.from(newSharedSecret.identifier!, "hex").toString("base64url")}`;+ // Loop through recipients and send out emails with unique access links+ if (emails && salt) {+ const user = await userDAL.findById(actorId);++ if (!user) {+ throw new NotFoundError({ message: `User with ID '${actorId}' not found` });+ }++ for await (const email of emails) {+ try {+ const hmac = crypto.createHmac("sha256", salt).update(email);+ const token = hmac.digest("base64");++ // Only show the username to emails which are part of the organization+ const respondentUsername = orgEmails.includes(email) ? user.username : undefined;++ await smtpService.sendMail({+ recipients: [email],+ subjectLine: "A secret has been shared with you",+ substitutions: {+ name,+ respondentUsername,+ secretRequestUrl: `${appCfg.SITE_URL}/shared/secret/${idToReturn}?email=${encodeURIComponent(email)}&token=${token}`+ },+ template: SmtpTemplates.SecretRequestCompleted+ });+ } catch (e) {+ logger.error(e, "Failed to send shared secret URL to a recipient's email.");+ }+ }+ }+return { id: idToReturn };};@@ -390,8 +453,15 @@ export const secretSharingServiceFactory = ({});};- /** Get's password-less secret. validates all secret's requested (must be fresh). */- const getSharedSecretById = async ({ sharedSecretId, hashedHex, orgId, password }: TGetActiveSharedSecretByIdDTO) => {+ /** Gets password-less secret. validates all secret's requested (must be fresh). */+ const getSharedSecretById = async ({+ sharedSecretId,+ hashedHex,+ orgId,+ password,+ email,+ token+ }: TGetActiveSharedSecretByIdDTO) => {const sharedSecret = isUuidV4(sharedSecretId)? await secretSharingDAL.findOne({id: sharedSecretId,@@ -438,6 +508,32 @@ export const secretSharingServiceFactory = ({});}+ const decryptWithRoot = kmsService.decryptWithRootKey();++ if (sharedSecret.authorizedEmails && sharedSecret.encryptedSalt) {+ // Verify both params were passed+ if (!email || !token) {+ throw new BadRequestError({+ message: "This secret is email protected. Parameters must include email and token."+ });++ // Verify that email is authorized to view shared secret+ } else if (!(sharedSecret.authorizedEmails as string[]).includes(email)) {+ throw new UnauthorizedError({ message: "Email not authorized to view secret" });++ // Verify that token matches+ } else {+ const salt = decryptWithRoot(sharedSecret.encryptedSalt).toString();+ const hmac = crypto.createHmac("sha256", salt).update(email);+ const rebuiltToken = hmac.digest("base64");++ if (rebuiltToken !== token) {+ throw new UnauthorizedError({ message: "Email not authorized to view secret" });+ }+ }+ }++ // Password checksconst isPasswordProtected = Boolean(sharedSecret.password);const hasProvidedPassword = Boolean(password);if (isPasswordProtected) {@@ -452,7 +548,6 @@ export const secretSharingServiceFactory = ({// If encryptedSecret is set, we know that this secret has been encrypted using KMS, and we can therefore do server-side decryption.let decryptedSecretValue: Buffer | undefined;if (sharedSecret.encryptedSecret) {- const decryptWithRoot = kmsService.decryptWithRootKey();decryptedSecretValue = decryptWithRoot(sharedSecret.encryptedSecret);}diff --git a/backend/src/services/secret-sharing/secret-sharing-types.ts b/backend/src/services/secret-sharing/secret-sharing-types.tsindex 835d70eff0..eae6a48fa1 100644--- a/backend/src/services/secret-sharing/secret-sharing-types.ts+++ b/backend/src/services/secret-sharing/secret-sharing-types.ts@@ -22,6 +22,7 @@ export type TSharedSecretPermission = {accessType?: SecretSharingAccessType;name?: string;password?: string;+ emails?: string[];};export type TCreatePublicSharedSecretDTO = {@@ -37,6 +38,10 @@ export type TGetActiveSharedSecretByIdDTO = {hashedHex?: string;orgId?: string;password?: string;++ // For secrets shared with specific emails+ email?: string;+ token?: string;};export type TValidateActiveSharedSecretDTO = TGetActiveSharedSecretByIdDTO & {diff --git a/frontend/src/hooks/api/secretSharing/queries.ts b/frontend/src/hooks/api/secretSharing/queries.tsindex ace45526a7..28448b7517 100644--- a/frontend/src/hooks/api/secretSharing/queries.ts+++ b/frontend/src/hooks/api/secretSharing/queries.ts@@ -70,11 +70,17 @@ export const useGetSecretRequests = ({export const useGetActiveSharedSecretById = ({sharedSecretId,hashedHex,- password+ password,+ email,+ token}: {sharedSecretId: string;hashedHex: string | null;password?: string;++ // For secrets shared to specific emails (optional)+ email?: string;+ token?: string;}) => {return useQuery({queryKey: secretSharingKeys.getSecretById({ id: sharedSecretId, hashedHex, password }),@@ -83,7 +89,9 @@ export const useGetActiveSharedSecretById = ({`/api/v1/secret-sharing/shared/public/${sharedSecretId}`,{...(hashedHex && { hashedHex }),- password+ password,+ email,+ token});diff --git a/frontend/src/hooks/api/secretSharing/types.ts b/frontend/src/hooks/api/secretSharing/types.tsindex ab819cfb6b..c35228fab3 100644--- a/frontend/src/hooks/api/secretSharing/types.ts+++ b/frontend/src/hooks/api/secretSharing/types.ts@@ -32,6 +32,7 @@ export type TCreateSharedSecretRequest = {expiresAt: Date;expiresAfterViews?: number;accessType?: SecretSharingAccessType;+ emails?: string[];};export type TCreateSecretRequestRequestDTO = {diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsxindex b9991d0e56..2697aeb7d5 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgProductSelectSection/OrgProductSelectSection.tsx@@ -1,10 +1,10 @@import { useEffect, useState } from "react";+import axios from "axios";+import { createNotification } from "@app/components/notifications";import { Switch } from "@app/components/v2";import { useOrganization } from "@app/context";import { useUpdateOrg } from "@app/hooks/api";-import axios from "axios";-import { createNotification } from "@app/components/notifications";export const OrgProductSelectSection = () => {const [toggledProducts, setToggledProducts] = useState<{diff --git a/frontend/src/pages/public/ShareSecretPage/ShareSecretPage.tsx b/frontend/src/pages/public/ShareSecretPage/ShareSecretPage.tsxindex 1869497220..53cd09f65d 100644--- a/frontend/src/pages/public/ShareSecretPage/ShareSecretPage.tsx+++ b/frontend/src/pages/public/ShareSecretPage/ShareSecretPage.tsx@@ -91,7 +91,7 @@ export const ShareSecretPage = () => {Infisical</a><br />- 156 2nd st, 3rd Floor, San Francisco, California, 94105, United States. ๐บ๐ธ+ 235 2nd st, San Francisco, California, 94105, United States. ๐บ๐ธ</p></div></div>diff --git a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsxindex a2228e46b7..35536831e5 100644--- a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx+++ b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx@@ -6,7 +6,19 @@ import { zodResolver } from "@hookform/resolvers/zod";import { z } from "zod";import { createNotification } from "@app/components/notifications";-import { Button, FormControl, IconButton, Input, Select, SelectItem } from "@app/components/v2";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ Button,+ FormControl,+ IconButton,+ Input,+ Select,+ SelectItem,+ Switch+} from "@app/components/v2";import { useTimedReset } from "@app/hooks";import { useCreatePublicSharedSecret, useCreateSharedSecret } from "@app/hooks/api";import { SecretSharingAccessType } from "@app/hooks/api/secretSharing";@@ -33,7 +45,19 @@ const schema = z.object({secret: z.string().min(1),expiresIn: z.string(),viewLimit: z.string(),- accessType: z.nativeEnum(SecretSharingAccessType).optional()+ accessType: z.nativeEnum(SecretSharingAccessType).optional(),+ emails: z+ .string()+ .optional()+ .refine(+ (val) => {+ if (!val) return true;+ return val.split(",").every((email) => z.string().email().safeParse(email.trim()).success);+ },+ {+ message: "Must be a comma-separated list of valid emails or empty."+ }+ )});export type FormData = z.infer<typeof schema>;@@ -49,7 +73,7 @@ export const ShareSecretForm = ({value,allowSecretSharingOutsideOrganization = true}: Props) => {- const [secretLink, setSecretLink] = useState("");+ const [secretLink, setSecretLink] = useState<string | null>(null);const [, isCopyingSecret, setCopyTextSecret] = useTimedReset<string>({initialState: "Copy to clipboard"});@@ -66,7 +90,9 @@ export const ShareSecretForm = ({} = useForm<FormData>({resolver: zodResolver(schema),defaultValues: {- secret: value || ""+ secret: value || "",+ viewLimit: "-1",+ expiresIn: "3600000"}});@@ -76,32 +102,45 @@ export const ShareSecretForm = ({secret,expiresIn,viewLimit,- accessType+ accessType,+ emails}: FormData) => {try {const expiresAt = new Date(new Date().getTime() + Number(expiresIn));+ const processedEmails = emails ? emails.split(",").map((e) => e.trim()) : undefined;+const { id } = await createSharedSecret.mutateAsync({name,password,secretValue: secret,expiresAt,expiresAfterViews: viewLimit === "-1" ? undefined : Number(viewLimit),- accessType+ accessType,+ emails: processedEmails});- const link = `${window.location.origin}/shared/secret/${id}`;+ if (processedEmails && processedEmails.length > 0) {+ setSecretLink("");+ createNotification({+ text: `Shared secret link emailed to ${processedEmails.length} user(s).`,+ type: "success"+ });+ } else {+ const link = `${window.location.origin}/shared/secret/${id}`;- setSecretLink(link);- reset();+ setSecretLink(link);- navigator.clipboard.writeText(link);- setCopyTextSecret("secret");+ navigator.clipboard.writeText(link);+ setCopyTextSecret("secret");- createNotification({- text: "Shared secret link copied to clipboard.",- type: "success"- });+ createNotification({+ text: "Shared secret link copied to clipboard.",+ type: "success"+ });+ }++ reset();} catch (error) {console.error(error);createNotification({@@ -111,152 +150,230 @@ export const ShareSecretForm = ({}};- const hasSecretLink = Boolean(secretLink);-- return !hasSecretLink ? (- <form onSubmit={handleSubmit(onFormSubmit)}>- {!isPublic && (+ if (secretLink === null)+ return (+ <form onSubmit={handleSubmit(onFormSubmit)}>+ {!isPublic && (+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Name"+ isOptional+ isError={Boolean(error)}+ errorText={error?.message}+ >+ <Input+ {...field}+ placeholder="API Key"+ type="text"+ autoComplete="off"+ autoCorrect="off"+ spellCheck="false"+ />+ </FormControl>+ )}+ />+ )}<Controllercontrol={control}- name="name"+ name="secret"render={({ field, fieldState: { error } }) => (<FormControl- label="Name (Optional)"+ label="Your Secret"isError={Boolean(error)}errorText={error?.message}+ className="mb-2"+ isRequired>- <Input+ <textarea+ placeholder="Enter sensitive data to share via an encrypted link..."{...field}- placeholder="API Key"- type="text"- autoComplete="off"- autoCorrect="off"- spellCheck="false"+ className="h-40 min-h-[70px] w-full rounded-md border border-mineshaft-600 bg-mineshaft-900 px-2 py-1.5 text-bunker-300 outline-none transition-all placeholder:text-mineshaft-400 hover:border-primary-400/30 focus:border-primary-400/50 group-hover:mr-2"+ disabled={value !== undefined}/></FormControl>)}/>- )}- <Controller- control={control}- name="secret"- render={({ field, fieldState: { error } }) => (- <FormControl- label="Your Secret"- isError={Boolean(error)}- errorText={error?.message}- className="mb-2"- isRequired- >- <textarea- placeholder="Enter sensitive data to share via an encrypted link..."- {...field}- className="h-40 min-h-[70px] w-full rounded-md border border-mineshaft-600 bg-mineshaft-900 px-2 py-1.5 text-bunker-300 outline-none transition-all placeholder:text-mineshaft-400 hover:border-primary-400/30 focus:border-primary-400/50 group-hover:mr-2"- disabled={value !== undefined}- />- </FormControl>- )}- />- <Controller- control={control}- name="password"- render={({ field, fieldState: { error } }) => (- <FormControl- label="Password"- isError={Boolean(error)}- errorText={error?.message}- isOptional- >- <Input- {...field}- placeholder="Password"- type="password"- autoComplete="new-password"- autoCorrect="off"- spellCheck="false"- aria-autocomplete="none"- data-form-type="other"- />- </FormControl>- )}- />- <Controller- control={control}- name="expiresIn"- defaultValue="3600000"- render={({ field: { onChange, ...field }, fieldState: { error } }) => (- <FormControl label="Expires In" errorText={error?.message} isError={Boolean(error)}>- <Select- defaultValue={field.value}- {...field}- onValueChange={(e) => onChange(e)}- className="w-full"- >- {expiresInOptions.map(({ label, value: expiresInValue }) => (- <SelectItem value={String(expiresInValue || "")} key={label}>- {label}- </SelectItem>- ))}- </Select>- </FormControl>- )}- />- <Controller- control={control}- name="viewLimit"- defaultValue="-1"- render={({ field: { onChange, ...field }, fieldState: { error } }) => (- <FormControl label="Max Views" errorText={error?.message} isError={Boolean(error)}>- <Select- defaultValue={field.value}- {...field}- onValueChange={(e) => onChange(e)}- className="w-full"- >- {viewLimitOptions.map(({ label, value: viewLimitValue }) => (- <SelectItem value={String(viewLimitValue || "")} key={label}>- {label}- </SelectItem>- ))}- </Select>- </FormControl>- )}- />- {!isPublic && (<Controllercontrol={control}- name="accessType"- defaultValue={SecretSharingAccessType.Organization}- render={({ field: { onChange, ...field }, fieldState: { error } }) => (- <FormControl label="General Access" errorText={error?.message} isError={Boolean(error)}>- <Select- defaultValue={field.value}+ name="password"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Password"+ isError={Boolean(error)}+ errorText={error?.message}+ isOptional+ >+ <Input{...field}- onValueChange={(e) => onChange(e)}- className="w-full"- >- {allowSecretSharingOutsideOrganization && (- <SelectItem value={SecretSharingAccessType.Anyone}>Anyone</SelectItem>- )}- <SelectItem value={SecretSharingAccessType.Organization}>- People within your organization- </SelectItem>- </Select>+ placeholder="Password"+ type="password"+ autoComplete="new-password"+ autoCorrect="off"+ spellCheck="false"+ aria-autocomplete="none"+ data-form-type="other"+ /></FormControl>)}/>- )}- <Button- className="mt-4"- size="sm"- type="submit"- isLoading={isSubmitting}- isDisabled={isSubmitting}- >- Create Secret Link- </Button>- </form>- ) : (++ {!isPublic && (+ <Controller+ control={control}+ name="accessType"+ defaultValue={SecretSharingAccessType.Organization}+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (+ <FormControl+ helperText={+ allowSecretSharingOutsideOrganization ? undefined : (+ <span className="text-red-500">Feature enforced by organization</span>+ )+ }+ errorText={error?.message}+ isError={Boolean(error)}+ >+ <Switch+ className={`ml-0 mr-2 bg-mineshaft-400/50 shadow-inner data-[state=checked]:bg-primary ${!allowSecretSharingOutsideOrganization ? "opacity-50" : ""}`}+ thumbClassName="bg-mineshaft-800"+ containerClassName="flex-row-reverse w-fit"+ isChecked={+ field.value === SecretSharingAccessType.Organization ||+ !allowSecretSharingOutsideOrganization+ }+ isDisabled={!allowSecretSharingOutsideOrganization}+ onCheckedChange={(v) =>+ onChange(+ v ? SecretSharingAccessType.Organization : SecretSharingAccessType.Anyone+ )+ }+ id="delete-secrets"+ >+ Limit access to people within organization+ </Switch>+ </FormControl>+ )}+ />+ )}++ <Accordion type="single" collapsible className="w-full">+ <AccordionItem value="advance-settings" className="data-[state=open]:border-none">+ <AccordionTrigger className="h-fit flex-none pl-1 text-sm">+ <div className="order-1 ml-3">Advanced Settings</div>+ </AccordionTrigger>+ <AccordionContent childrenClassName="p-0">+ <Controller+ control={control}+ name="expiresIn"+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (+ <FormControl+ label="Expires In"+ errorText={error?.message}+ isError={Boolean(error)}+ >+ <Select+ defaultValue={field.value}+ {...field}+ onValueChange={(e) => onChange(e)}+ className="w-full"+ >+ {expiresInOptions.map(({ label, value: expiresInValue }) => (+ <SelectItem value={String(expiresInValue || "")} key={label}>+ {label}+ </SelectItem>+ ))}+ </Select>+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="viewLimit"+ render={({ field: { onChange, ...field }, fieldState: { error } }) => (+ <FormControl+ label="Max Views"+ errorText={error?.message}+ isError={Boolean(error)}+ >+ <Select+ defaultValue={field.value}+ {...field}+ onValueChange={(e) => onChange(e)}+ className="w-full"+ >+ {viewLimitOptions.map(({ label, value: viewLimitValue }) => (+ <SelectItem value={String(viewLimitValue || "")} key={label}>+ {label}+ </SelectItem>+ ))}+ </Select>+ </FormControl>+ )}+ />++ {!isPublic && (+ <Controller+ control={control}+ name="emails"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Authorized Emails"+ isOptional+ tooltipText="Unique secret links will be emailed to each individual. The secret will only be accessible to those links."+ tooltipClassName="max-w-sm"+ isError={Boolean(error)}+ errorText={error?.message}+ >+ <Input+ {...field}+ placeholder="[email protected], [email protected]"+ autoComplete="off"+ />+ </FormControl>+ )}+ />+ )}+ </AccordionContent>+ </AccordionItem>+ </Accordion>++ <div className="flex w-full justify-end">+ <Button+ className="mt-4"+ size="sm"+ type="submit"+ isLoading={isSubmitting}+ isDisabled={isSubmitting}+ >+ Create Secret Link+ </Button>+ </div>+ </form>+ );++ if (secretLink === "")+ return (+ <>+ <div className="mt-1 flex w-full items-center justify-center gap-2">+ <FontAwesomeIcon icon={faCheck} className="text-green-500" />+ <span>Shared secret link has been emailed to select users.</span>+ </div>+ <Button+ className="mt-6 w-full bg-mineshaft-700 py-3 text-bunker-200"+ colorSchema="primary"+ variant="outline_bg"+ size="sm"+ onClick={() => setSecretLink(null)}+ rightIcon={<FontAwesomeIcon icon={faRedo} className="pl-2" />}+ >+ Share Another Secret+ </Button>+ </>+ );++ return (<><div className="mr-2 flex items-center justify-end rounded-md bg-white/[0.05] p-2 text-base text-gray-400"><p className="mr-4 break-all">{secretLink}</p>@@ -265,7 +382,7 @@ export const ShareSecretForm = ({colorSchema="secondary"className="group relative ml-2"onClick={() => {- navigator.clipboard.writeText(secretLink);+ navigator.clipboard.writeText(secretLink || "");setCopyTextSecret("Copied");}}>@@ -277,7 +394,7 @@ export const ShareSecretForm = ({colorSchema="primary"variant="outline_bg"size="sm"- onClick={() => setSecretLink("")}+ onClick={() => setSecretLink(null)}rightIcon={<FontAwesomeIcon icon={faRedo} className="pl-2" />}>Share Another Secretdiff --git a/frontend/src/pages/public/ViewSecretRequestByIDPage/ViewSecretRequestByIDPage.tsx b/frontend/src/pages/public/ViewSecretRequestByIDPage/ViewSecretRequestByIDPage.tsxindex bce742358a..2bb5c7b0ff 100644--- a/frontend/src/pages/public/ViewSecretRequestByIDPage/ViewSecretRequestByIDPage.tsx+++ b/frontend/src/pages/public/ViewSecretRequestByIDPage/ViewSecretRequestByIDPage.tsx@@ -175,7 +175,7 @@ export const ViewSecretRequestByIDPage = () => {Infisical</a><br />- 156 2nd st, 3rd Floor, San Francisco, California, 94105, United States. ๐บ๐ธ+ 235 2nd st, San Francisco, California, 94105, United States. ๐บ๐ธ</p></div></div>diff --git a/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx b/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsxindex 5112bd47ed..4c83b03570 100644--- a/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx+++ b/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx@@ -38,6 +38,14 @@ export const ViewSharedSecretByIDPage = () => {from: ROUTE_PATHS.Public.ViewSharedSecretByIDPage.id,select: (el) => el.key});+ const email = useSearch({+ from: ROUTE_PATHS.Public.ViewSharedSecretByIDPage.id,+ select: (el) => el.email+ });+ const token = useSearch({+ from: ROUTE_PATHS.Public.ViewSharedSecretByIDPage.id,+ select: (el) => el.token+ });const [password, setPassword] = useState<string>();const { hashedHex, key } = extractDetailsFromUrl(urlEncodedKey);@@ -49,7 +57,9 @@ export const ViewSharedSecretByIDPage = () => {} = useGetActiveSharedSecretById({sharedSecretId: id,hashedHex,- password+ password,+ email,+ token});const navigate = useNavigate();@@ -57,15 +67,16 @@ export const ViewSharedSecretByIDPage = () => {const isUnauthorized =((error as AxiosError)?.response?.data as { statusCode: number })?.statusCode === 401;- const isForbidden =- ((error as AxiosError)?.response?.data as { statusCode: number })?.statusCode === 403;-const isInvalidCredential =((error as AxiosError)?.response?.data as { message: string })?.message ==="Invalid credentials";+ const isEmailUnauthorized =+ ((error as AxiosError)?.response?.data as { message: string })?.message ===+ "Email not authorized to view secret";+useEffect(() => {- if (isUnauthorized && !isInvalidCredential) {+ if (isUnauthorized && !isInvalidCredential && !isEmailUnauthorized) {// persist current URL in session storage so that we can come back to this after successful loginsessionStorage.setItem(SessionStorageKeys.ORG_LOGIN_SUCCESS_REDIRECT_URL,@@ -85,10 +96,10 @@ export const ViewSharedSecretByIDPage = () => {});}- if (isForbidden) {+ if (error) {createNotification({type: "error",- text: "You do not have access to this shared secret."+ text: ((error as AxiosError)?.response?.data as { message: string })?.message});}}, [error]);@@ -195,7 +206,7 @@ export const ViewSharedSecretByIDPage = () => {Infisical</a><br />- 156 2nd st, 3rd Floor, San Francisco, California, 94105, United States. ๐บ๐ธ+ 235 2nd st, San Francisco, California, 94105, United States. ๐บ๐ธ</p></div></div>diff --git a/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsx b/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsxindex 7b98dded34..a1bc4009ce 100644--- a/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsx+++ b/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsx@@ -7,7 +7,9 @@ import { authKeys, fetchAuthToken } from "@app/hooks/api/auth/queries";import { ViewSharedSecretByIDPage } from "./ViewSharedSecretByIDPage";const SharedSecretByIDPageQuerySchema = z.object({- key: z.string().catch("")+ key: z.string().catch(""),+ email: z.string().optional(),+ token: z.string().optional()});export const Route = createFileRoute("/shared/secret/$secretId")({diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsxindex 1113816924..8ada43347f 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsx@@ -4,13 +4,13 @@ import { ProjectType, ProjectVersion } from "@app/hooks/api/workspace/types";import { AuditLogsRetentionSection } from "../AuditLogsRetentionSection";import { AutoCapitalizationSection } from "../AutoCapitalizationSection";-import { SecretSharingSection } from "../SecretSharingSection";import { BackfillSecretReferenceSecretion } from "../BackfillSecretReferenceSection";import { DeleteProjectProtection } from "../DeleteProjectProtection";import { DeleteProjectSection } from "../DeleteProjectSection";import { EnvironmentSection } from "../EnvironmentSection";import { PointInTimeVersionLimitSection } from "../PointInTimeVersionLimitSection";import { RebuildSecretIndicesSection } from "../RebuildSecretIndicesSection/RebuildSecretIndicesSection";+import { SecretSharingSection } from "../SecretSharingSection";import { SecretTagsSection } from "../SecretTagsSection";export const ProjectGeneralTab = () => {diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsxindex 3daa7dad2e..837f32d3e5 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx@@ -1,9 +1,10 @@+import { useState } from "react";+import { createNotification } from "@app/components/notifications";import { ProjectPermissionCan } from "@app/components/permissions";import { Checkbox } from "@app/components/v2";import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";import { useUpdateProject } from "@app/hooks/api/workspace/queries";-import { useState } from "react";export const SecretSharingSection = () => {const { currentWorkspace } = useWorkspace();