Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: re-vamp create secret form

Scott Wilson17b351870b0f
diff --git a/frontend/src/components/v3/generic/Field/Field.tsx b/frontend/src/components/v3/generic/Field/Field.tsx
index 5deb07ef79..42b45ef010 100644
--- a/frontend/src/components/v3/generic/Field/Field.tsx
+++ b/frontend/src/components/v3/generic/Field/Field.tsx
@@ -95,7 +95,7 @@ function FieldLabel({ className, ...props }: React.ComponentProps<typeof Label>)
<Label
data-slot="field-label"
className={cn(
- "group/field-label peer/field-label flex w-fit items-center gap-1.5 text-xs leading-snug text-accent group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10 [&>*]:data-[slot=field]:p-2.5",
+ "group/field-label peer/field-label flex w-fit items-center gap-1.5 text-xs leading-snug text-accent group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10 [&>*]:data-[slot=field]:p-2.5 [&>svg]:size-3",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
className
)}
diff --git a/frontend/src/components/v3/generic/Input/Input.tsx b/frontend/src/components/v3/generic/Input/Input.tsx
index e52109a369..603865298d 100644
--- a/frontend/src/components/v3/generic/Input/Input.tsx
+++ b/frontend/src/components/v3/generic/Input/Input.tsx
@@ -1,20 +1,29 @@
+import { forwardRef } from "react";
+
import { cn } from "../../utils";
-function UnstableInput({ className, type, ...props }: React.ComponentProps<"input">) {
+const UnstableInput = forwardRef<
+ HTMLInputElement,
+ React.ComponentProps<"input"> & { isError?: boolean }
+>(({ className, type, isError, ...props }, ref) => {
return (
<input
+ ref={ref}
type={type}
data-slot="input"
className={cn(
"h-9 w-full min-w-0 rounded-md border border-border bg-transparent px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
- "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
+ "aria-invalid:border-danger aria-invalid:ring-danger/20 dark:aria-invalid:ring-danger/40",
"selection:bg-foreground selection:text-background",
className
)}
+ aria-invalid={isError}
{...props}
/>
);
-}
+});
+
+UnstableInput.displayName = "UnstableInput";
export { UnstableInput };
diff --git a/frontend/src/components/v3/generic/PasswordGenerator/PasswordGenerator.tsx b/frontend/src/components/v3/generic/PasswordGenerator/PasswordGenerator.tsx
new file mode 100644
index 0000000000..6426f4bef2
--- /dev/null
+++ b/frontend/src/components/v3/generic/PasswordGenerator/PasswordGenerator.tsx
@@ -0,0 +1,188 @@
+import { useMemo, useState } from "react";
+import { CheckIcon, CopyIcon, KeyRoundIcon, RefreshCwIcon } from "lucide-react";
+
+import { useTimedReset } from "@app/hooks";
+
+import { Button } from "../Button";
+import { Checkbox } from "../Checkbox";
+import { UnstableIconButton } from "../IconButton";
+import { Label } from "../Label";
+import { Popover, PopoverContent, PopoverTrigger } from "../Popover";
+
+type PasswordOptionsType = {
+ length: number;
+ useUppercase: boolean;
+ useLowercase: boolean;
+ useNumbers: boolean;
+ useSpecialChars: boolean;
+};
+
+export type PasswordGeneratorProps = {
+ onUsePassword?: (password: string) => void;
+ isDisabled?: boolean;
+ minLength?: number;
+ maxLength?: number;
+};
+
+export const PasswordGenerator = ({
+ onUsePassword,
+ isDisabled = false,
+ minLength = 12,
+ maxLength = 64
+}: PasswordGeneratorProps) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [, isCopying, setCopyText] = useTimedReset<string>({
+ initialState: "Copy"
+ });
+ const [refresh, setRefresh] = useState(false);
+ const [passwordOptions, setPasswordOptions] = useState<PasswordOptionsType>({
+ length: minLength,
+ useUppercase: true,
+ useLowercase: true,
+ useNumbers: true,
+ useSpecialChars: true
+ });
+
+ const password = useMemo(() => {
+ const charset = {
+ uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
+ lowercase: "abcdefghijklmnopqrstuvwxyz",
+ numbers: "0123456789",
+ specialChars: "-_.~!*"
+ };
+
+ let availableChars = "";
+ if (passwordOptions.useUppercase) availableChars += charset.uppercase;
+ if (passwordOptions.useLowercase) availableChars += charset.lowercase;
+ if (passwordOptions.useNumbers) availableChars += charset.numbers;
+ if (passwordOptions.useSpecialChars) availableChars += charset.specialChars;
+
+ if (availableChars === "") availableChars = charset.lowercase + charset.numbers;
+
+ let newPassword = "";
+ for (let i = 0; i < passwordOptions.length; i += 1) {
+ const randomIndex = Math.floor(Math.random() * availableChars.length);
+ newPassword += availableChars[randomIndex];
+ }
+
+ return newPassword;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [passwordOptions, refresh]);
+
+ const copyToClipboard = () => {
+ navigator.clipboard
+ .writeText(password)
+ .then(() => {
+ setCopyText("Copied");
+ })
+ .catch(() => {
+ setCopyText("Copy failed");
+ });
+ };
+
+ const usePassword = () => {
+ onUsePassword?.(password);
+ setIsOpen(false);
+ };
+
+ return (
+ <Popover open={isOpen} onOpenChange={setIsOpen}>
+ <PopoverTrigger asChild>
+ <UnstableIconButton variant="outline" size="md" isDisabled={isDisabled}>
+ <KeyRoundIcon />
+ </UnstableIconButton>
+ </PopoverTrigger>
+ <PopoverContent className="w-[30rem]" align="end">
+ <div className="flex flex-col gap-4">
+ <div>
+ <p className="text-sm font-medium">Generate Random Value</p>
+ <p className="mt-0.5 text-xs text-muted">Generate strong unique values</p>
+ </div>
+
+ <div className="rounded-md border border-border bg-container/50 p-3">
+ <div className="flex items-center justify-between gap-2">
+ <p className="flex-1 font-mono text-sm break-all select-all">{password}</p>
+ <div className="flex shrink-0 gap-1">
+ <UnstableIconButton
+ variant="ghost"
+ size="xs"
+ onClick={() => setRefresh((prev) => !prev)}
+ >
+ <RefreshCwIcon />
+ </UnstableIconButton>
+ <UnstableIconButton variant="ghost" size="xs" onClick={copyToClipboard}>
+ {isCopying ? <CheckIcon /> : <CopyIcon />}
+ </UnstableIconButton>
+ </div>
+ </div>
+ </div>
+
+ <div>
+ <div className="mb-2 flex items-center justify-between">
+ <Label className="text-xs text-accent">Length: {passwordOptions.length}</Label>
+ </div>
+ <input
+ type="range"
+ min={minLength}
+ max={maxLength}
+ value={passwordOptions.length}
+ onChange={(e) =>
+ setPasswordOptions({ ...passwordOptions, length: Number(e.target.value) })
+ }
+ className="h-1.5 w-full cursor-pointer appearance-none rounded-full bg-foreground/10 accent-project [&::-webkit-slider-thumb]:size-3.5 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-foreground [&::-webkit-slider-thumb]:shadow-sm"
+ />
+ </div>
+
+ <div className="flex flex-wrap gap-6">
+ <Label className="flex cursor-pointer items-center gap-1.5 text-xs">
+ <Checkbox
+ variant="project"
+ isChecked={passwordOptions.useUppercase}
+ onCheckedChange={(checked) =>
+ setPasswordOptions({ ...passwordOptions, useUppercase: checked as boolean })
+ }
+ />
+ A-Z
+ </Label>
+ <Label className="flex cursor-pointer items-center gap-1.5 text-xs">
+ <Checkbox
+ variant="project"
+ isChecked={passwordOptions.useLowercase}
+ onCheckedChange={(checked) =>
+ setPasswordOptions({ ...passwordOptions, useLowercase: checked as boolean })
+ }
+ />
+ a-z
+ </Label>
+ <Label className="flex cursor-pointer items-center gap-1.5 text-xs">
+ <Checkbox
+ variant="project"
+ isChecked={passwordOptions.useNumbers}
+ onCheckedChange={(checked) =>
+ setPasswordOptions({ ...passwordOptions, useNumbers: checked as boolean })
+ }
+ />
+ 0-9
+ </Label>
+ <Label className="flex cursor-pointer items-center gap-1.5 text-xs">
+ <Checkbox
+ variant="project"
+ isChecked={passwordOptions.useSpecialChars}
+ onCheckedChange={(checked) =>
+ setPasswordOptions({ ...passwordOptions, useSpecialChars: checked as boolean })
+ }
+ />
+ -_.~!*
+ </Label>
+ </div>
+
+ {onUsePassword && (
+ <Button variant="project" size="xs" onClick={usePassword} className="w-full">
+ Use Value
+ </Button>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+};
diff --git a/frontend/src/components/v3/generic/PasswordGenerator/index.ts b/frontend/src/components/v3/generic/PasswordGenerator/index.ts
new file mode 100644
index 0000000000..f834fcf6f0
--- /dev/null
+++ b/frontend/src/components/v3/generic/PasswordGenerator/index.ts
@@ -0,0 +1 @@
+export { PasswordGenerator, type PasswordGeneratorProps } from "./PasswordGenerator";
diff --git a/frontend/src/components/v3/generic/SecretInput/InfisicalSecretInput.tsx b/frontend/src/components/v3/generic/SecretInput/InfisicalSecretInput.tsx
new file mode 100644
index 0000000000..5fb756c625
--- /dev/null
+++ b/frontend/src/components/v3/generic/SecretInput/InfisicalSecretInput.tsx
@@ -0,0 +1,531 @@
+import { forwardRef, TextareaHTMLAttributes, useCallback, useMemo, useRef, useState } from "react";
+import * as PopoverPrimitive from "@radix-ui/react-popover";
+import { useNavigate } from "@tanstack/react-router";
+import { FolderIcon, KeyRoundIcon, LayersIcon, SearchIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { ROUTE_PATHS } from "@app/const/routes";
+import { useProject, useProjectPermission } from "@app/context";
+import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
+import { useDebounce, useToggle } from "@app/hooks";
+import { useGetProjectFolders, useGetProjectSecrets } from "@app/hooks/api";
+import { hasSecretReadValueOrDescribePermission } from "@app/lib/fn/permission";
+
+import { cn } from "../../utils";
+import { SecretInput } from "./SecretInput";
+
+const getIndexOfUnclosedRefToTheLeft = (value: string, pos: number) => {
+ for (let i = pos; i >= 1; i -= 1) {
+ if (value[i] === "}") return -1;
+ if (value[i - 1] === "$" && value[i] === "{") {
+ return i;
+ }
+ }
+ return -1;
+};
+
+const getIndexOfUnclosedRefToTheRight = (value: string, pos: number) => {
+ for (let i = pos; i < value.length; i += 1) {
+ if (value[i] === "}") return i - 1;
+ }
+ return -1;
+};
+
+const getClosingSymbol = (isSelectedSecret: boolean, isClosed: boolean) => {
+ if (!isClosed) {
+ return isSelectedSecret ? "}" : ".";
+ }
+ if (!isSelectedSecret) return ".";
+ return "";
+};
+
+const mod = (n: number, m: number) => ((n % m) + m) % m;
+
+export enum ReferenceType {
+ ENVIRONMENT = "environment",
+ FOLDER = "folder",
+ SECRET = "secret"
+}
+
+type Props = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "onChange" | "value"> & {
+ value?: string;
+ onChange: (val: string) => void;
+ isImport?: boolean;
+ isVisible?: boolean;
+ isReadOnly?: boolean;
+ isDisabled?: boolean;
+ canEditButNotView?: boolean;
+ secretPath?: string;
+ environment?: string;
+ containerClassName?: string;
+ isLoadingValue?: boolean;
+ isErrorLoadingValue?: boolean;
+};
+
+type ReferenceItem = {
+ label: string;
+ type: ReferenceType;
+ slug: string;
+};
+
+export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
+ (
+ {
+ value = "",
+ onChange,
+ containerClassName,
+ secretPath: propSecretPath,
+ environment: propEnvironment,
+ canEditButNotView,
+ ...props
+ },
+ ref
+ ) => {
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
+ const navigate = useNavigate({ from: ROUTE_PATHS.SecretManager.SecretDashboardPage.path });
+ const { permission } = useProjectPermission();
+
+ const [debouncedValue] = useDebounce(value, 100);
+
+ const [highlightedIndex, setHighlightedIndex] = useState(-1);
+
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const popoverContentRef = useRef<HTMLDivElement>(null);
+ const [isFocused, setIsFocused] = useToggle(false);
+ const currentCursorPosition = inputRef.current?.selectionStart || 0;
+
+ const suggestionSource = useMemo(() => {
+ const left = getIndexOfUnclosedRefToTheLeft(debouncedValue, currentCursorPosition - 1);
+ if (left === -1) return { left, value: "", predicate: "", isDeep: false };
+
+ const suggestionSourceValue = debouncedValue.slice(left + 1, currentCursorPosition);
+ let suggestionSourceEnv: string | undefined = propEnvironment;
+ let suggestionSourceSecretPath: string | undefined = propSecretPath || "/";
+
+ const isDeep = suggestionSourceValue.includes(".");
+ let predicate = suggestionSourceValue;
+ if (isDeep) {
+ const [envSlug, ...folderPaths] = suggestionSourceValue.split(".");
+ const isValidEnvSlug = currentProject?.environments.find((e) => e.slug === envSlug);
+ suggestionSourceEnv = isValidEnvSlug ? envSlug : undefined;
+ suggestionSourceSecretPath = `/${folderPaths.slice(0, -1)?.join("/")}`;
+ predicate = folderPaths[folderPaths.length - 1];
+ }
+
+ return {
+ left: left + 1,
+ value: suggestionSourceValue,
+ predicate,
+ isOpen: left !== -1,
+ isDeep,
+ environment: suggestionSourceEnv,
+ secretPath: suggestionSourceSecretPath
+ };
+ }, [debouncedValue]);
+
+ const isPopupOpen = Boolean(suggestionSource.isOpen) && isFocused;
+ const { data: secrets } = useGetProjectSecrets({
+ viewSecretValue: false,
+ environment: suggestionSource.environment || "",
+ secretPath: suggestionSource.secretPath || "",
+ projectId,
+ options: {
+ enabled: isPopupOpen
+ }
+ });
+ const { data: folders } = useGetProjectFolders({
+ environment: suggestionSource.environment || "",
+ path: suggestionSource.secretPath || "",
+ projectId,
+ options: {
+ enabled: isPopupOpen
+ }
+ });
+
+ const suggestions = useMemo(() => {
+ if (!isPopupOpen) return [];
+ setHighlightedIndex(0);
+ const suggestionsArr: ReferenceItem[] = [];
+ const predicate = suggestionSource.predicate.toLowerCase();
+
+ if (!suggestionSource.isDeep) {
+ (currentProject?.environments || []).forEach(({ name, slug }) => {
+ if (name.toLowerCase().startsWith(predicate))
+ suggestionsArr.push({
+ label: name,
+ slug,
+ type: ReferenceType.ENVIRONMENT
+ });
+ });
+ } else {
+ (folders || []).forEach(({ name }) => {
+ if (name.toLowerCase().startsWith(predicate))
+ suggestionsArr.push({
+ label: name,
+ slug: name,
+ type: ReferenceType.FOLDER
+ });
+ });
+ }
+ (secrets || []).forEach(({ key }) => {
+ if (key.toLowerCase().startsWith(predicate))
+ suggestionsArr.push({
+ label: key,
+ slug: key,
+ type: ReferenceType.SECRET
+ });
+ });
+
+ if (suggestionsArr.length === 0 && suggestionSource.predicate.trim()) {
+ suggestionsArr.push({
+ label: "No matches found",
+ slug: "__no_match__",
+ type: ReferenceType.SECRET
+ });
+ }
+
+ return suggestionsArr;
+ }, [
+ secrets,
+ folders,
+ currentProject?.environments,
+ isPopupOpen,
+ suggestionSource.value,
+ suggestionSource.predicate
+ ]);
+
+ const handleSuggestionSelect = (selectIndex?: number) => {
+ const selectedSuggestion =
+ suggestions[typeof selectIndex !== "undefined" ? selectIndex : highlightedIndex];
+ if (!selectedSuggestion || selectedSuggestion.slug === "__no_match__") {
+ return;
+ }
+
+ const rightBracketIndex = getIndexOfUnclosedRefToTheRight(value, suggestionSource.left);
+ const isEnclosed = rightBracketIndex !== -1;
+ const lhsValue = value.slice(0, suggestionSource.left);
+ const rhsValue = value.slice(
+ rightBracketIndex !== -1 ? rightBracketIndex + 1 : currentCursorPosition
+ );
+ const mid = suggestionSource.isDeep
+ ? `${suggestionSource.value.slice(0, -suggestionSource.predicate.length || undefined)}${
+ selectedSuggestion.slug
+ }`
+ : selectedSuggestion.slug;
+ const closingSymbol = getClosingSymbol(
+ selectedSuggestion.type === ReferenceType.SECRET,
+ isEnclosed
+ );
+
+ const newValue = `${lhsValue}${mid}${closingSymbol}${rhsValue}`;
+ onChange?.(newValue);
+ const delay = setTimeout(() => {
+ clearTimeout(delay);
+ if (inputRef.current)
+ inputRef.current.selectionEnd =
+ lhsValue.length +
+ mid.length +
+ closingSymbol.length +
+ (isEnclosed && selectedSuggestion.type === ReferenceType.SECRET ? 1 : 0);
+ }, 10);
+ setHighlightedIndex(-1);
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (isPopupOpen) {
+ if (e.key === "ArrowDown" || (e.key === "Tab" && !e.shiftKey)) {
+ setHighlightedIndex((prevIndex) => {
+ let nextIndex = mod(prevIndex + 1, suggestions.length);
+ while (
+ nextIndex < suggestions.length &&
+ suggestions[nextIndex].slug === "__no_match__"
+ ) {
+ nextIndex = mod(nextIndex + 1, suggestions.length);
+ }
+ if (suggestions[nextIndex]?.slug === "__no_match__") {
+ return -1;
+ }
+ popoverContentRef.current?.children?.[nextIndex]?.scrollIntoView({
+ block: "nearest",
+ behavior: "smooth"
+ });
+ return nextIndex;
+ });
+ } else if (e.key === "ArrowUp" || (e.key === "Tab" && e.shiftKey)) {
+ setHighlightedIndex((prevIndex) => {
+ let prevIdx = mod(prevIndex - 1, suggestions.length);
+ while (prevIdx >= 0 && suggestions[prevIdx].slug === "__no_match__") {
+ prevIdx = mod(prevIdx - 1, suggestions.length);
+ }
+ if (suggestions[prevIdx]?.slug === "__no_match__") {
+ return -1;
+ }
+ popoverContentRef.current?.children?.[prevIdx]?.scrollIntoView({
+ block: "nearest",
+ behavior: "smooth"
+ });
+ return prevIdx;
+ });
+ } else if (e.key === "Enter" && highlightedIndex >= 0) {
+ e.preventDefault();
+ handleSuggestionSelect();
+ }
+ if (["ArrowDown", "ArrowUp", "Tab"].includes(e.key)) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ const handlePopUpOpen = () => {
+ setHighlightedIndex(-1);
+ };
+
+ const handleRef = useCallback((el: HTMLTextAreaElement) => {
+ // @ts-expect-error this is for multiple ref single component
+ inputRef.current = el;
+ if (ref) {
+ if (typeof ref === "function") {
+ ref(el);
+ } else {
+ // eslint-disable-next-line
+ ref.current = el;
+ }
+ }
+ }, []);
+
+ const handleClickSegment = useCallback(
+ (segment: string, allSegments: string[]) => {
+ if (!projectId) {
+ createNotification({
+ text: "Project ID is not set",
+ type: "error"
+ });
+ return;
+ }
+
+ if (allSegments.length === 0) {
+ createNotification({
+ text: "Invalid secret reference",
+ type: "error"
+ });
+ return;
+ }
+
+ if (allSegments.length === 1) {
+ const canReadSecretValue = hasSecretReadValueOrDescribePermission(
+ permission,
+ ProjectPermissionSecretActions.ReadValue,
+ {
+ environment: propEnvironment ?? "*",
+ secretPath: propSecretPath ?? "/",
+ secretName: segment,
+ secretTags: ["*"]
+ }
+ );
+
+ if (!canReadSecretValue) {
+ createNotification({
+ text: "You do not have permission to access this secret",
+ type: "error"
+ });
+ return;
+ }
+
+ navigate({
+ search: (prev) => ({
+ ...prev,
+ search: segment,
+ filterBy: "secret",
+ tags: ""
+ })
+ });
+ return;
+ }
+
+ const environmentSlug = allSegments[0];
+ const secretName = allSegments[allSegments.length - 1];
+ let folderPath = "/";
+
+ if (allSegments.length > 2) {
+ const pathSegments = allSegments.slice(1, -1);
+ for (let i = 0; i < pathSegments.length; i += 1) {
+ if (!pathSegments[i]) {
+ createNotification({
+ text: "Invalid secret reference",
+ type: "error"
+ });
+ return;
+ }
+
+ const pathSegment = pathSegments[i];
+ folderPath += `${pathSegment}`;
+ if (pathSegment === segment) {
+ folderPath += "/";
+ break;
+ }
+ folderPath += "/";
+ }
+ }
+
+ if (segment === secretName) {
+ const canReadSecretValue = hasSecretReadValueOrDescribePermission(
+ permission,
+ ProjectPermissionSecretActions.ReadValue,
+ {
+ environment: environmentSlug,
+ secretPath: folderPath,
+ secretName,
+ secretTags: ["*"]
+ }
+ );
+
+ if (!canReadSecretValue) {
+ createNotification({
+ text: "You do not have permission to access this secret",
+ type: "error"
+ });
+ return;
+ }
+ }
+
+ navigate({
+ to: ROUTE_PATHS.SecretManager.SecretDashboardPage.path,
+ params: {
+ projectId,
+ envSlug: environmentSlug
+ },
+ search: (prev) => ({
+ ...prev,
+ secretPath: segment === environmentSlug ? "/" : folderPath,
+ search: segment === secretName ? secretName : prev.search,
+ filterBy: segment === secretName ? "secret" : prev.filterBy,
+ tags: ""
+ })
+ });
+ },
+ [navigate, projectId, permission, propEnvironment, propSecretPath]
+ );
+
+ const getEntryIcon = (item: ReferenceItem) => {
+ if (item.slug === "__no_match__") {
+ return <SearchIcon className="size-4 text-muted" />;
+ }
+ if (item.type === ReferenceType.SECRET) {
+ return <KeyRoundIcon className="size-4 text-muted" />;
+ }
+ if (item.type === ReferenceType.ENVIRONMENT) {
+ return <LayersIcon className="size-4 text-success" />;
+ }
+ return <FolderIcon className="size-4 text-warning" />;
+ };
+
+ const getSubText = (item: ReferenceItem) => {
+ if (item.slug === "__no_match__") return "No results";
+ if (item.type === ReferenceType.SECRET) return "Secret";
+ if (item.type === ReferenceType.ENVIRONMENT) return "Environment";
+ return "Folder";
+ };
+
+ return (
+ <PopoverPrimitive.Root open={isPopupOpen} onOpenChange={handlePopUpOpen}>
+ <PopoverPrimitive.Trigger asChild>
+ <SecretInput
+ {...props}
+ canEditButNotView={canEditButNotView}
+ ref={handleRef}
+ onKeyDown={handleKeyDown}
+ value={value}
+ onFocus={(evt) => {
+ if (props.onFocus) props.onFocus(evt);
+ setIsFocused.on();
+ }}
+ onBlur={(evt) => {
+ if (!(evt.relatedTarget?.getAttribute("aria-label") === "suggestion-item"))
+ setIsFocused.off();
+
+ if (props.onBlur) props.onBlur(evt);
+ }}
+ onChange={(e) => onChange?.(e.target.value)}
+ containerClassName={containerClassName}
+ onClickSegment={handleClickSegment}
+ />
+ </PopoverPrimitive.Trigger>
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ align="start"
+ onOpenAutoFocus={(e) => e.preventDefault()}
+ className="relative top-2 z-[100] max-h-64 thin-scrollbar overflow-auto rounded-md border border-border bg-popover text-foreground shadow-md"
+ style={{
+ width: "var(--radix-popover-trigger-width)"
+ }}
+ >
+ <div
+ className="flex h-full w-full flex-col items-center justify-center rounded-md"
+ ref={popoverContentRef}
+ >
+ {suggestions.map((item, i) => {
+ const isNoMatchMessage = item.slug === "__no_match__";
+ const entryIcon = getEntryIcon(item);
+ const subText = getSubText(item);
+
+ return isNoMatchMessage ? (
+ <div
+ role="status"
+ aria-label="no-match-message"
+ className="flex w-full items-center justify-between text-left"
+ key={`secret-reference-secret-${i + 1}`}
+ >
+ <div className="relative flex w-full cursor-default items-center justify-between px-2 py-2 text-sm opacity-75 outline-hidden transition-all select-none">
+ <div className="flex w-full items-start gap-2">
+ <div className="mt-0.5 flex items-center">{entryIcon}</div>
+ <div className="w-10/12 truncate text-left">
+ <span className="text-muted">{item.label}</span>
+ <div className="mb-[0.1rem] text-xs leading-3 text-muted">{subText}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <button
+ type="button"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") handleSuggestionSelect(i);
+ }}
+ aria-label="suggestion-item"
+ onClick={(e) => {
+ inputRef.current?.focus();
+ e.preventDefault();
+ e.stopPropagation();
+ handleSuggestionSelect(i);
+ }}
+ onMouseEnter={() => setHighlightedIndex(i)}
+ className="flex w-full items-center justify-between border-none bg-transparent p-0 text-left"
+ key={`secret-reference-secret-${i + 1}`}
+ >
+ <div
+ className={cn(
+ "relative flex w-full cursor-pointer items-center justify-between px-2 py-2 text-sm outline-hidden transition-all select-none hover:bg-foreground/10",
+ highlightedIndex === i && "bg-foreground/5"
+ )}
+ >
+ <div className="flex w-full items-start gap-2">
+ <div className="mt-0.5 flex items-center">{entryIcon}</div>
+ <div className="w-10/12 truncate text-left">
+ <span>{item.label}</span>
+ <div className="mb-[0.1rem] text-xs leading-3 text-muted">{subText}</div>
+ </div>
+ </div>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ </PopoverPrimitive.Content>
+ </PopoverPrimitive.Portal>
+ </PopoverPrimitive.Root>
+ );
+ }
+);
+
+InfisicalSecretInput.displayName = "InfisicalSecretInput";
diff --git a/frontend/src/components/v3/generic/SecretInput/SecretInput.tsx b/frontend/src/components/v3/generic/SecretInput/SecretInput.tsx
new file mode 100644
index 0000000000..d261d181f5
--- /dev/null
+++ b/frontend/src/components/v3/generic/SecretInput/SecretInput.tsx
@@ -0,0 +1,249 @@
+/* eslint-disable react/no-danger */
+import { forwardRef, TextareaHTMLAttributes, useEffect, useState } from "react";
+
+import { useToggle } from "@app/hooks";
+import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
+
+import { cn } from "../../utils";
+
+const REGEX = /(\${([a-zA-Z0-9-_. ]+)})/g;
+
+const syntaxHighlight = (
+ content?: string | null,
+ isVisible?: boolean,
+ isImport?: boolean,
+ isLoadingValue?: boolean,
+ isErrorLoadingValue?: boolean,
+ onHoverPart?: (part: string) => void,
+ hoveredPart?: string,
+ isCmdOrCtrlPressed?: boolean,
+ onClickSegment?: (segment: string, allSegments: string[]) => void,
+ placeholder?: string
+) => {
+ if (isLoadingValue) return HIDDEN_SECRET_VALUE;
+ if (isErrorLoadingValue)
+ return <span className="ph-no-capture text-danger/75">Error loading secret value.</span>;
+ if (isImport && !content) return "EMPTY";
+ if (placeholder && (content === "" || !content)) return placeholder;
+ if (content === "") return "EMPTY";
+ if (!content) return "EMPTY";
+ if (!isVisible) return HIDDEN_SECRET_VALUE;
+
+ let skipNext = false;
+ const formattedContent = content.split(REGEX).flatMap((el, i) => {
+ const isInterpolationSyntax = el.startsWith("${") && el.endsWith("}");
+ if (isInterpolationSyntax) {
+ skipNext = true;
+ const part = el;
+ const innerContent = el.slice(2, -1);
+ const parts = innerContent.split(".");
+
+ return (
+ <span className="ph-no-capture relative z-10 text-yellow" key={`secret-value-${i + 1}`}>
+ &#36;&#123;
+ {parts.map((segment, segmentIndex) => {
+ const segmentKey = `${part}-segment-${segmentIndex}`;
+ const isHovered = hoveredPart === segmentKey;
+ const shouldShowHoverStyle = isHovered && isCmdOrCtrlPressed;
+
+ return (
+ <span key={segmentKey}>
+ <span
+ role="button"
+ tabIndex={isCmdOrCtrlPressed ? 0 : -1}
+ className={cn(
+ "ph-no-capture text-yellow-200/80",
+ isCmdOrCtrlPressed ? "pointer-events-auto" : "pointer-events-none",
+ shouldShowHoverStyle && "cursor-pointer underline decoration-yellow-400"
+ )}
+ onMouseEnter={() => onHoverPart?.(segmentKey)}
+ onMouseLeave={() => onHoverPart?.("")}
+ onMouseDown={(e) => {
+ if (isCmdOrCtrlPressed) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (isCmdOrCtrlPressed) {
+ e.preventDefault();
+ onClickSegment?.(segment, parts);
+ }
+ }}
+ onKeyDown={(e) => {
+ if (isCmdOrCtrlPressed && (e.key === "Enter" || e.key === " ")) {
+ e.preventDefault();
+ e.stopPropagation();
+ onClickSegment?.(segment, parts);
+ }
+ }}
+ >
+ {segment}
+ </span>
+ {segmentIndex < parts.length - 1 && (
+ <span className="ph-no-capture pointer-events-none text-yellow-200/80">.</span>
+ )}
+ </span>
+ );
+ })}
+ &#125;
+ </span>
+ );
+ }
+ if (skipNext) {
+ skipNext = false;
+ return [];
+ }
+ return el;
+ });
+
+ // akhilmhdh: Dont remove this br. I am still clueless how this works but weirdly enough
+ // when break is added a line break works properly
+ return formattedContent.concat(
+ <br key={`secret-value-linebreak-${formattedContent.length + 1}`} />
+ );
+};
+
+type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
+ value?: string | null;
+ isVisible?: boolean;
+ valueAlwaysHidden?: boolean;
+ isImport?: boolean;
+ isReadOnly?: boolean;
+ isDisabled?: boolean;
+ containerClassName?: string;
+ canEditButNotView?: boolean;
+ isLoadingValue?: boolean;
+ isErrorLoadingValue?: boolean;
+ onClickSegment?: (segment: string, allSegments: string[]) => void;
+};
+
+const commonClassName =
+ "text-sm leading-[1.85rem] caret-white border-none outline-hidden w-full break-all";
+
+export const SecretInput = forwardRef<HTMLTextAreaElement, Props>(
+ (
+ {
+ value,
+ isVisible,
+ isImport,
+ valueAlwaysHidden,
+ containerClassName,
+ onBlur,
+ isDisabled,
+ isReadOnly,
+ onFocus,
+ canEditButNotView,
+ isLoadingValue,
+ isErrorLoadingValue,
+ onClickSegment,
+ placeholder,
+ ...props
+ },
+ ref
+ ) => {
+ const [isSecretFocused, setIsSecretFocused] = useToggle();
+ const [hoveredPart, setHoveredPart] = useState<string | undefined>();
+ const [isCmdOrCtrlPressed, setIsCmdOrCtrlPressed] = useState(false);
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.metaKey || e.ctrlKey) {
+ setIsCmdOrCtrlPressed(true);
+ }
+ };
+
+ const handleKeyUp = (e: KeyboardEvent) => {
+ if (!e.metaKey && !e.ctrlKey) {
+ setIsCmdOrCtrlPressed(false);
+ }
+ };
+
+ const handleBlur = () => {
+ setIsCmdOrCtrlPressed(false);
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+ window.addEventListener("keyup", handleKeyUp);
+ window.addEventListener("blur", handleBlur);
+
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown);
+ window.removeEventListener("keyup", handleKeyUp);
+ window.removeEventListener("blur", handleBlur);
+ };
+ }, []);
+
+ return (
+ <div
+ className={cn(
+ "no-scrollbar min-h-9 w-full overflow-auto rounded-md border border-border bg-transparent transition-[color,box-shadow]",
+ "focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50",
+ containerClassName
+ )}
+ style={{ maxHeight: `${21 * 7}px` }}
+ >
+ <div className="relative overflow-hidden px-3 py-1">
+ <pre aria-hidden className="pointer-events-none relative z-10 m-0 font-sans">
+ <code className={cn("inline-block w-full font-sans", commonClassName)}>
+ <span className={cn("whitespace-break-spaces", !value && "text-muted")}>
+ {syntaxHighlight(
+ value,
+ isVisible || (isSecretFocused && !valueAlwaysHidden),
+ isImport,
+ isLoadingValue,
+ isErrorLoadingValue,
+ (part) => {
+ setHoveredPart(part);
+ },
+ hoveredPart,
+ isCmdOrCtrlPressed,
+ onClickSegment,
+ placeholder
+ )}
+ </span>
+ </code>
+ </pre>
+ <textarea
+ placeholder={placeholder}
+ style={{ whiteSpace: "break-spaces" }}
+ aria-label="secret value"
+ ref={ref}
+ className={cn(
+ "no-scrollbar absolute inset-0 block h-full resize-none overflow-hidden bg-transparent px-3 py-1 text-transparent focus:border-0",
+ commonClassName
+ )}
+ onFocus={(evt) => {
+ onFocus?.(evt);
+ setIsSecretFocused.on();
+ if (canEditButNotView && value === HIDDEN_SECRET_VALUE) {
+ evt.currentTarget.select();
+ }
+ }}
+ onMouseDown={(e) => {
+ if (canEditButNotView && value === HIDDEN_SECRET_VALUE) {
+ e.preventDefault();
+ e.currentTarget.select();
+ }
+ }}
+ disabled={isDisabled}
+ spellCheck={false}
+ onBlur={(evt) => {
+ onBlur?.(evt);
+ setIsSecretFocused.off();
+ }}
+ onMouseLeave={() => {
+ setHoveredPart(undefined);
+ }}
+ value={value || ""}
+ {...props}
+ readOnly={isReadOnly || isLoadingValue || isErrorLoadingValue}
+ />
+ </div>
+ </div>
+ );
+ }
+);
+
+SecretInput.displayName = "SecretInput";
diff --git a/frontend/src/components/v3/generic/SecretInput/index.ts b/frontend/src/components/v3/generic/SecretInput/index.ts
new file mode 100644
index 0000000000..ae87d23a29
--- /dev/null
+++ b/frontend/src/components/v3/generic/SecretInput/index.ts
@@ -0,0 +1,2 @@
+export { InfisicalSecretInput } from "./InfisicalSecretInput";
+export { SecretInput } from "./SecretInput";
diff --git a/frontend/src/components/v3/generic/Sheet/Sheet.tsx b/frontend/src/components/v3/generic/Sheet/Sheet.tsx
index 9e72bde214..e99cac943c 100644
--- a/frontend/src/components/v3/generic/Sheet/Sheet.tsx
+++ b/frontend/src/components/v3/generic/Sheet/Sheet.tsx
@@ -54,7 +54,7 @@ function SheetContent({
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
- "fixed z-50 flex thin-scrollbar flex-col gap-4 border-border bg-popover shadow-lg outline-0 transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
+ "fixed z-50 flex thin-scrollbar flex-col gap-4 border-border bg-popover text-foreground shadow-lg outline-0 transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",
side === "right" &&
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-md",
side === "left" &&
@@ -84,7 +84,7 @@ function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
- className={cn("flex flex-col gap-1.5 p-4", className)}
+ className={cn("flex flex-col gap-1.5 border-border p-4", className)}
{...props}
/>
);
@@ -94,7 +94,7 @@ function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
- className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ className={cn("mt-auto flex gap-2 border-border p-4", className)}
{...props}
/>
);
diff --git a/frontend/src/components/v3/generic/index.ts b/frontend/src/components/v3/generic/index.ts
index 6ac4fd5ca2..985cfd0b04 100644
--- a/frontend/src/components/v3/generic/index.ts
+++ b/frontend/src/components/v3/generic/index.ts
@@ -21,8 +21,10 @@ export * from "./Item";
export * from "./Label";
export * from "./PageLoader";
export * from "./Pagination";
+export * from "./PasswordGenerator";
export * from "./Popover";
export * from "./ReactSelect";
+export * from "./SecretInput";
export * from "./Select";
export * from "./Separator";
export * from "./Sheet";
diff --git a/frontend/src/hooks/api/secrets/mutations.tsx b/frontend/src/hooks/api/secrets/mutations.tsx
index 48b18a0676..d4c0e88a4a 100644
--- a/frontend/src/hooks/api/secrets/mutations.tsx
+++ b/frontend/src/hooks/api/secrets/mutations.tsx
@@ -38,7 +38,8 @@ export const useCreateSecretV3 = ({
secretValue,
secretComment,
skipMultilineEncoding,
- tagIds
+ tagIds,
+ secretMetadata
}) => {
const { data } = await apiRequest.post(`/api/v4/secrets/${secretKey}`, {
secretPath,
@@ -48,7 +49,8 @@ export const useCreateSecretV3 = ({
secretValue,
secretComment,
skipMultilineEncoding,
- tagIds
+ tagIds,
+ secretMetadata
});
return data;
},
diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.ts
index b2e28f4b94..93b71db214 100644
--- a/frontend/src/hooks/api/secrets/types.ts
+++ b/frontend/src/hooks/api/secrets/types.ts
@@ -175,6 +175,7 @@ export type TCreateSecretsV3DTO = {
environment: string;
type: SecretType;
tagIds?: string[];
+ secretMetadata?: { key: string; value: string; isEncrypted?: boolean }[];
};
export type TUpdateSecretsV3DTO = {
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index cbda9f1d47..b3f3558316 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -52,6 +52,11 @@ import {
Badge,
Button,
Checkbox,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
Skeleton,
Tooltip,
TooltipContent,
@@ -2309,23 +2314,22 @@ export const OverviewPage = () => {
</UnstableCardContent>
</UnstableCard>
</div>
- <Modal
- isOpen={popUp.addSecretsInAllEnvs.isOpen}
+ <Sheet
+ open={popUp.addSecretsInAllEnvs.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("addSecretsInAllEnvs", isOpen)}
>
- <ModalContent
- className="max-h-[80vh]"
- bodyClassName="overflow-visible"
- title="Create Secrets"
- subTitle="Create a secret across multiple environments"
- onPointerDownOutside={(e) => e.preventDefault()}
- >
+ <SheetContent className="flex h-full flex-col gap-y-0 overflow-y-auto sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>Create Secret</SheetTitle>
+ <SheetDescription>Create a secret across multiple environments</SheetDescription>
+ </SheetHeader>
<CreateSecretForm
secretPath={secretPath}
+ defaultSelectedEnvs={filteredEnvs}
onClose={() => handlePopUpClose("addSecretsInAllEnvs")}
/>
- </ModalContent>
- </Modal>
+ </SheetContent>
+ </Sheet>
<Modal
isOpen={popUp.addFolder.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("addFolder", isOpen)}
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx
index a821a029d5..7a00cfb289 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx
@@ -1,22 +1,33 @@
-import { ClipboardEvent, useRef } from "react";
-import { Controller, useForm } from "react-hook-form";
+import { ClipboardEvent, useMemo, useRef, useState } from "react";
+import { Controller, useFieldArray, useForm } from "react-hook-form";
import { subject } from "@casl/ability";
-import { faTriangleExclamation, faWarning } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangleIcon, InfoIcon, PlusIcon, TrashIcon, TriangleAlertIcon } from "lucide-react";
+import { twMerge } from "tailwind-merge";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
Button,
- FilterableSelect,
- FormControl,
- Input,
+ InfisicalSecretInput,
PasswordGenerator,
- Tooltip
-} from "@app/components/v2";
-import { CreatableSelect } from "@app/components/v2/CreatableSelect";
-import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
+ SheetFooter,
+ Switch,
+ TextArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ UnstableIconButton,
+ UnstableInput
+} from "@app/components/v3";
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel
+} from "@app/components/v3/generic/Field";
+import { CreatableSelect, FilterableSelect } from "@app/components/v3/generic/ReactSelect";
import {
ProjectPermissionActions,
ProjectPermissionSub,
@@ -33,35 +44,60 @@ import {
} from "@app/hooks/api";
import { SecretType } from "@app/hooks/api/types";
-const typeSchema = z
+const formSchema = z
.object({
key: z.string().trim().min(1, "Key is required"),
value: z.string().optional(),
+ comment: z.string().optional(),
+ skipMultilineEncoding: z.boolean().optional(),
environments: z.object({ name: z.string(), slug: z.string() }).array(),
- tags: z.array(z.object({ label: z.string().trim(), value: z.string().trim() })).optional()
+ tags: z.array(z.object({ label: z.string().trim(), value: z.string().trim() })).optional(),
+ metadata: z
+ .array(
+ z.object({
+ key: z.string().min(1, "Key is required"),
+ value: z.string(),
+ isEncrypted: z.boolean().default(false)
+ })
+ )
+ .optional()
})
.refine((data) => data.key !== undefined, {
message: "Please enter secret name"
});
-type TFormSchema = z.infer<typeof typeSchema>;
+type TFormSchema = z.infer<typeof formSchema>;
type Props = {
secretPath?: string;
- // modal props
+ defaultSelectedEnvs?: { name: string; slug: string }[];
onClose: () => void;
};
-export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
+export const CreateSecretForm = ({ secretPath = "/", defaultSelectedEnvs, onClose }: Props) => {
const {
- register,
handleSubmit,
control,
reset,
setValue,
+ getValues,
+ setFocus,
watch,
formState: { isSubmitting, errors }
- } = useForm<TFormSchema>({ resolver: zodResolver(typeSchema) });
+ } = useForm<TFormSchema>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ environments: defaultSelectedEnvs ?? [],
+ skipMultilineEncoding: false,
+ metadata: []
+ }
+ });
+
+ const {
+ fields: metadataFields,
+ append: appendMetadata,
+ remove: removeMetadata
+ } = useFieldArray({ control, name: "metadata" });
const { currentProject, projectId } = useProject();
const { permission } = useProjectPermission();
@@ -74,17 +110,29 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
canReadTags ? projectId : ""
);
- const secretKeyInputRef = useRef<HTMLInputElement>(null);
- const { ref: setSecretKeyHookRef, ...secretKeyRegisterRest } = register("key");
+ const tagOptions = useMemo(
+ () => projectTags?.map((el) => ({ label: el.slug, value: el.id })),
+ [projectTags]
+ );
+ const [createMore, setCreateMore] = useState(false);
+ const secretKeyInputRef = useRef<HTMLInputElement>(null);
const secretKey = watch("key");
- const handleFormSubmit = async ({ key, value, environments: selectedEnv, tags }: TFormSchema) => {
+ const handleFormSubmit = async ({
+ key,
+ value,
+ comment,
+ skipMultilineEncoding,
+ environments: selectedEnv,
+ tags,
+ metadata
+ }: TFormSchema) => {
+ const filteredMetadata = metadata?.filter((m) => m.key && m.value);
+
const promises = selectedEnv.map(async (env) => {
const environment = env.slug;
- // create folder if not existing
if (secretPath !== "/") {
- // /hello/world -> [hello","world"]
const pathSegment = secretPath.split("/").filter(Boolean);
const parentPath = `/${pathSegment.slice(0, -1).join("/")}`;
const folderName = pathSegment.at(-1);
@@ -106,8 +154,6 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
}
}
- // TODO: add back ability to overwrite - need to fetch secrets by key to check for conflicts as previous method broke with pagination
-
return {
...(await createSecretV3({
environment,
@@ -115,9 +161,11 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
secretPath,
secretKey: key,
secretValue: value || "",
- secretComment: "",
+ secretComment: comment || "",
+ skipMultilineEncoding: skipMultilineEncoding || undefined,
type: SecretType.Shared,
- tagIds: tags?.map((el) => el.value)
+ tagIds: tags?.map((el) => el.value),
+ secretMetadata: filteredMetadata?.length ? filteredMetadata : undefined
})),
environment
};
@@ -163,6 +211,11 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
type: "error",
text: "Failed to create secrets"
});
+ } else if (createMore) {
+ setValue("key", "");
+ setValue("value", "");
+ setValue("comment", "");
+ setTimeout(() => secretKeyInputRef.current?.focus(), 150);
} else {
onClose();
reset();
@@ -192,173 +245,318 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
const createWsTag = useCreateWsTag();
const slugSchema = z.string().trim().toLowerCase().min(1);
const createNewTag = async (slug: string) => {
- // TODO: Replace with slugSchema generic
const parsedSlug = slugSchema.parse(slug);
- await createWsTag.mutateAsync({
+ const newTag = await createWsTag.mutateAsync({
projectId,
tagSlug: parsedSlug,
tagColor: ""
});
+ const currentTags = getValues("tags") ?? [];
+ setValue("tags", [...currentTags, { label: newTag.slug, value: newTag.id }], {
+ shouldDirty: true
+ });
};
return (
- <form onSubmit={handleSubmit(handleFormSubmit)} noValidate>
- <FormControl
- label="Key"
- isRequired
- isError={Boolean(errors?.key)}
- errorText={errors?.key?.message}
- >
- <Input
- {...secretKeyRegisterRest}
- ref={(e) => {
- setSecretKeyHookRef(e);
- // @ts-expect-error this is for multiple ref single component
- secretKeyInputRef.current = e;
- }}
- warning={
- secretKey?.includes(" ") ? (
- <Tooltip
- className="w-full max-w-72"
- content={
- <div>
- Secret key contains whitespaces.
- <br />
- <br /> If this is the desired format, you need to provide it as{" "}
- <code className="rounded-md bg-mineshaft-500 px-1 py-0.5">
- {encodeURIComponent(secretKey.trim())}
- </code>{" "}
- when making API requests.
- </div>
- }
- >
- <FontAwesomeIcon
- icon={faWarning}
- className="absolute right-0 mr-3 text-yellow-600"
+ <form
+ onSubmit={handleSubmit(handleFormSubmit)}
+ noValidate
+ className="flex flex-1 flex-col gap-4 overflow-hidden"
+ >
+ <div className="flex thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <Controller
+ control={control}
+ name="environments"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Environments</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ isMulti
+ options={environments.filter((environment) =>
+ permission.can(
+ ProjectPermissionSecretActions.Create,
+ subject(ProjectPermissionSub.Secrets, {
+ environment: environment.slug,
+ secretPath,
+ secretName: "*",
+ secretTags: ["*"]
+ })
+ )
+ )}
+ value={value}
+ onChange={onChange}
+ placeholder="Select environments to create secret in..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.slug}
/>
- </Tooltip>
- ) : undefined
- }
- placeholder="Type your secret name"
- onPaste={handlePaste}
- autoCapitalization={currentProject?.autoCapitalization}
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
/>
- </FormControl>
- <Controller
- control={control}
- name="value"
- render={({ field }) => (
- <FormControl
- tooltipText={
- <div>
- You can add references to other secrets using the format{" "}
- <code className="rounded-sm bg-mineshaft-600 px-1 py-0.5">
- &#36;{"{"}secret_name{"}"}
- </code>
- <br />
- <br />
- You can go to the referenced secret by holding the{" "}
- <code className="rounded-sm bg-mineshaft-600 px-1 py-0.5">Cmd</code> (Mac) or{" "}
- <code className="rounded-sm bg-mineshaft-600 px-1 py-0.5">Ctrl</code>{" "}
- (Windows/Linux) key and clicking on the secret name.
- </div>
- }
- tooltipClassName="max-w-md"
- label="Value"
- isError={Boolean(errors?.value)}
- errorText={errors?.value?.message}
- >
- <div className="flex items-center gap-2">
- <InfisicalSecretInput
- {...field}
- containerClassName="text-bunker-300 hover:border-primary-400/50 border border-mineshaft-600 bg-mineshaft-900 px-2 py-1.5"
- />
- <PasswordGenerator onUsePassword={field.onChange} />
- </div>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="tags"
- render={({ field }) => (
- <FormControl
- label="Tags"
- isError={Boolean(errors?.value)}
- errorText={errors?.value?.message}
- helperText={
- !canReadTags ? (
- <div className="flex items-center space-x-2">
- <FontAwesomeIcon icon={faTriangleExclamation} className="text-yellow-400" />
- <span>You do not have permission to read tags.</span>
+
+ <Controller
+ control={control}
+ name="key"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Key</FieldLabel>
+ <FieldContent>
+ <div className="relative">
+ <UnstableInput
+ ref={secretKeyInputRef}
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const val = currentProject?.autoCapitalization
+ ? e.target.value.toUpperCase()
+ : e.target.value;
+ field.onChange(val);
+ }}
+ onBlur={field.onBlur}
+ placeholder="Type your secret name"
+ onPaste={handlePaste}
+ autoComplete="off"
+ isError={Boolean(error)}
+ className={currentProject?.autoCapitalization ? "uppercase" : undefined}
+ />
+ {secretKey?.includes(" ") && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <AlertTriangleIcon className="absolute top-1/2 right-3 size-4 -translate-y-1/2 text-warning" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-72">
+ Secret key contains whitespaces. If this is the desired format, you need to
+ provide it as{" "}
+ <code className="rounded-md bg-container px-1 py-0.5">
+ {encodeURIComponent(secretKey.trim())}
+ </code>{" "}
+ when making API requests.
+ </TooltipContent>
+ </Tooltip>
+ )}
</div>
- ) : (
- ""
- )
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="value"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>
+ Value
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon />
+ </TooltipTrigger>
+ <TooltipContent>
+ You can add references to other secrets using the format{" "}
+ <code className="rounded-sm bg-accent px-1 py-0.5 text-background">
+ &#36;{"{"}secret_name{"}"}
+ </code>
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <div className="flex items-start gap-2">
+ <InfisicalSecretInput
+ value={field.value ?? ""}
+ onChange={field.onChange}
+ placeholder="Enter secret value..."
+ />
+ <PasswordGenerator onUsePassword={field.onChange} />
+ </div>
+ <FieldError errors={[errors.value]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="comment"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Comment</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ placeholder="Add a comment for this secret..."
+ className="max-h-32 min-h-[60px] resize-y"
+ />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="tags"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Tags</FieldLabel>
+ <FieldContent>
+ {!canReadTags ? (
+ <FieldDescription>
+ <span className="flex items-center gap-1.5 text-warning">
+ <TriangleAlertIcon className="size-3" />
+ You do not have permission to read tags.
+ </span>
+ </FieldDescription>
+ ) : (
+ <CreatableSelect
+ isMulti
+ className="w-full"
+ placeholder="Select tags to assign to secret..."
+ isValidNewOption={(v) => slugSchema.safeParse(v).success}
+ name="tagIds"
+ isDisabled={!canReadTags}
+ isLoading={isTagsLoading && canReadTags}
+ options={tagOptions}
+ value={field.value}
+ onChange={field.onChange}
+ onCreateOption={createNewTag}
+ />
+ )}
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="skipMultilineEncoding"
+ render={({ field }) => (
+ <Field orientation="horizontal">
+ <FieldLabel className="cursor-pointer">Enable Multiline Encoding</FieldLabel>
+ <Switch variant="project" checked={field.value} onCheckedChange={field.onChange} />
+ </Field>
+ )}
+ />
+
+ <div>
+ <div className="mb-1">
+ <p className="text-sm font-medium">Metadata</p>
+ <p className="mt-1 text-xs text-accent">
+ Encrypted Metadata will not be searchable via the UI or API.
+ </p>
+ </div>
+ <div className="flex max-h-64 thin-scrollbar flex-col gap-3 overflow-y-auto rounded-md border border-border bg-container/50 p-4">
+ {metadataFields.length === 0 && (
+ <p className="text-center text-sm text-muted">
+ No metadata entries. Click below to add.
+ </p>
+ )}
+ {metadataFields.map((metaField, index) => (
+ <div key={metaField.id} className="flex items-start gap-3">
+ <Field className="flex-1">
+ {index === 0 && <FieldLabel className="text-xs">Key</FieldLabel>}
+ <FieldContent>
+ <Controller
+ control={control}
+ name={`metadata.${index}.key`}
+ render={({ field: inputField, fieldState: { error } }) => (
+ <>
+ <UnstableInput {...inputField} placeholder="Enter key" className="h-8" />
+ <FieldError errors={[error]} />
+ </>
+ )}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field className="flex-1">
+ {index === 0 && <FieldLabel className="text-xs">Value</FieldLabel>}
+ <FieldContent>
+ <Controller
+ control={control}
+ name={`metadata.${index}.value`}
+ render={({ field: inputField, fieldState: { error } }) => (
+ <>
+ <UnstableInput
+ {...inputField}
+ placeholder="Enter value"
+ className="h-8"
+ />
+ <FieldError errors={[error]} />
+ </>
+ )}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field className="w-10">
+ {index === 0 && <FieldLabel className="text-xs">Encrypt</FieldLabel>}
+ <Controller
+ control={control}
+ name={`metadata.${index}.isEncrypted`}
+ render={({ field: switchField }) => (
+ <Switch
+ className="mt-2"
+ variant="project"
+ size="default"
+ checked={switchField.value}
+ onCheckedChange={switchField.onChange}
+ />
+ )}
+ />
+ </Field>
+
+ <UnstableIconButton
+ variant="ghost"
+ size="xs"
+ type="button"
+ className={twMerge(
+ index === 0 ? "mt-6.5" : "mt-0.5",
+ "transition-transform hover:text-danger"
+ )}
+ onClick={() => removeMetadata(index)}
+ >
+ <TrashIcon className="size-4" />
+ </UnstableIconButton>
+ </div>
+ ))}
+ </div>
+
+ <Button
+ variant="ghost"
+ size="xs"
+ type="button"
+ className="mt-2"
+ onClick={() =>
+ appendMetadata({
+ key: "",
+ value: "",
+ isEncrypted: currentProject?.enforceEncryptedSecretManagerSecretMetadata ?? false
+ })
}
>
- <CreatableSelect
- isMulti
- className="w-full"
- placeholder="Select tags to assign to secret..."
- isValidNewOption={(v) => slugSchema.safeParse(v).success}
- name="tagIds"
- isDisabled={!canReadTags}
- isLoading={isTagsLoading && canReadTags}
- options={projectTags?.map((el) => ({ label: el.slug, value: el.id }))}
- value={field.value}
- onChange={field.onChange}
- onCreateOption={createNewTag}
- />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl label="Environments" isError={Boolean(error)} errorText={error?.message}>
- <FilterableSelect
- isMulti
- options={environments.filter((environment) =>
- permission.can(
- ProjectPermissionSecretActions.Create,
- subject(ProjectPermissionSub.Secrets, {
- environment: environment.slug,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- })
- )
- )}
- value={value}
- onChange={onChange}
- placeholder="Select environments to create secret in..."
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.slug}
- />
- </FormControl>
- )}
- name="environments"
- />
- <div className="mt-7 flex items-center">
- <Button
- isDisabled={isSubmitting}
- isLoading={isSubmitting}
- key="layout-create-project-submit"
- className="mr-4"
- type="submit"
- >
+ <PlusIcon className="mr-1 size-4" />
+ Add Entry
+ </Button>
+ </div>
+ </div>
+ <SheetFooter className="border-t">
+ <Button isPending={isSubmitting} isDisabled={isSubmitting} variant="project" type="submit">
Create Secret
</Button>
- <Button
- key="layout-cancel-create-project"
- onClick={onClose}
- variant="plain"
- colorSchema="secondary"
- >
+ <Button onClick={onClose} variant="outline" className="mr-auto" type="button">
Cancel
</Button>
- </div>
+ <Field orientation="horizontal" className="my-auto ml-auto w-fit">
+ <FieldLabel>Create More</FieldLabel>
+ <Switch
+ id="create-more"
+ variant="project"
+ checked={createMore}
+ onCheckedChange={setCreateMore}
+ />
+ </Field>
+ </SheetFooter>
</form>
);
};