Skip to content

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

12.3 KB
Raw Blame
import { forwardRef, ReactNode, TextareaHTMLAttributes, useEffect, useMemo, useState } from "react";
import { TriangleAlertIcon } from "lucide-react";

import { HIDDEN_SECRET_VALUE } from "@app/const/secrets";
import { useToggle } from "@app/hooks";

import { IconButton } from "../../generic/IconButton";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../generic/Tooltip";
import { cn } from "../../utils";
import { getInvisibleCharacterSummary, splitSuspiciousCharacters } from "./invisibleCharacters";

const REGEX = /(\${([@a-zA-Z0-9-_. ]+)})/g;

const markInvisibleChars = (text: string, chunkKey: number) => {
  const nodes: ReactNode[] = [];
  let offset = 0;

  splitSuspiciousCharacters(text).forEach(({ text: part, isSuspicious }) => {
    if (isSuspicious) {
      nodes.push(
        <span
          key={`secret-value-invisible-${chunkKey}-${offset}`}
          className="rounded-xs bg-warning/25 outline outline-1 outline-warning/70"
        >
          {part}
        </span>
      );
    } else {
      nodes.push(part);
    }
    offset += part.length;
  });

  return nodes;
};

// One dot per character, keeping line breaks, so a value being typed shows its length and shape the
// way a password field does.
const maskPerCharacter = (content: string) => [
  Array.from(content, (char) => (char === "\n" ? "\n" : "\u2022")).join(""),
  <br key="secret-value-mask-linebreak" />
];

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,
  isMaskedPerCharacter?: boolean
) => {
  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 isMaskedPerCharacter ? maskPerCharacter(content) : 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(".");
      const isCrossProjectRef = parts[0]?.startsWith("@");

      return (
        <span className="ph-no-capture relative z-10 text-secret" key={`secret-value-${i + 1}`}>
          &#36;&#123;
          {parts.map((segment, segmentIndex) => {
            const segmentKey = `${part}-segment-${segmentIndex}`;
            const isHovered = hoveredPart === segmentKey;
            const isInteractive = isCmdOrCtrlPressed && !isCrossProjectRef;
            const shouldShowHoverStyle = isHovered && isInteractive;

            return (
              <span key={segmentKey}>
                <span
                  role="button"
                  tabIndex={isInteractive ? 0 : -1}
                  className={cn(
                    "ph-no-capture text-secret/80",
                    isInteractive ? "pointer-events-auto" : "pointer-events-none",
                    shouldShowHoverStyle && "cursor-pointer underline decoration-secret"
                  )}
                  onMouseEnter={() => onHoverPart?.(segmentKey)}
                  onMouseLeave={() => onHoverPart?.("")}
                  onMouseDown={(e) => {
                    if (isInteractive) {
                      e.preventDefault();
                      e.stopPropagation();
                    }
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    if (isInteractive) {
                      e.preventDefault();
                      onClickSegment?.(segment, parts);
                    }
                  }}
                  onKeyDown={(e) => {
                    if (isInteractive && (e.key === "Enter" || e.key === " ")) {
                      e.preventDefault();
                      e.stopPropagation();
                      onClickSegment?.(segment, parts);
                    }
                  }}
                >
                  {markInvisibleChars(segment, i)}
                </span>
                {segmentIndex < parts.length - 1 && (
                  <span className="ph-no-capture pointer-events-none text-secret/80">.</span>
                )}
              </span>
            );
          })}
          &#125;
        </span>
      );
    }
    if (skipNext) {
      skipNext = false;
      return [];
    }
    return markInvisibleChars(el, i);
  });

  // 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}`} />
  );
};

export type SecretInputVariant = "default" | "plain";

type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
  value?: string | null;
  variant?: SecretInputVariant;
  isVisible?: boolean;
  valueAlwaysHidden?: boolean;
  // Masks with one dot per character instead of a fixed-length mask, which reveals the value's
  // length. Meant for a value the user is typing, not a stored one.
  maskEachCharacter?: boolean;
  isImport?: boolean;
  isReadOnly?: boolean;
  isDisabled?: boolean;
  containerClassName?: string;
  // Grows from a textarea-height box with the value top-aligned, for standalone form fields.
  isMultiline?: boolean;
  canEditButNotView?: boolean;
  isLoadingValue?: boolean;
  isErrorLoadingValue?: boolean;
  isError?: boolean;
  onClickSegment?: (segment: string, allSegments: string[]) => void;
};

const commonClassName =
  "w-full border-none text-sm leading-5 break-all caret-foreground outline-hidden";

export const SecretInput = forwardRef<HTMLTextAreaElement, Props>(
  (
    {
      value,
      variant = "default",
      isVisible,
      isImport,
      valueAlwaysHidden,
      maskEachCharacter,
      containerClassName,
      isMultiline,
      onBlur,
      isDisabled,
      isReadOnly,
      readOnly,
      onFocus,
      canEditButNotView,
      isLoadingValue,
      isErrorLoadingValue,
      isError,
      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);
      };
    }, []);

    const shouldRevealValue = isVisible || (isSecretFocused && !valueAlwaysHidden);
    const shouldBindRealValue = isVisible || isSecretFocused;
    const shouldShowMask =
      !isErrorLoadingValue && (isLoadingValue || (Boolean(value) && !shouldRevealValue));

    const invisibleChars = useMemo(
      () =>
        value && !isLoadingValue && !isErrorLoadingValue ? getInvisibleCharacterSummary(value) : [],
      [value, isLoadingValue, isErrorLoadingValue]
    );

    return (
      <div
        data-slot="secret-input"
        data-variant={variant}
        data-invalid={isError}
        className={cn(
          "no-scrollbar w-full overflow-auto bg-transparent text-foreground",
          variant === "default" &&
            "flex min-h-9 items-center-safe rounded-md border border-border shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 data-[invalid=true]:border-danger data-[invalid=true]:ring-danger/40",
          variant === "plain" && invisibleChars.length > 0 && "flex",
          variant === "default" && isMultiline && "min-h-16 items-start py-1",
          containerClassName
        )}
        style={{ maxHeight: `${21 * 7}px` }}
      >
        <div
          className={cn(
            "relative w-full min-w-0 overflow-hidden",
            variant === "default" && "px-2.5 py-1"
          )}
        >
          <div
            aria-hidden
            className={cn(
              "pointer-events-none whitespace-break-spaces",
              commonClassName,
              maskEachCharacter && "font-mono",
              !value && "text-muted",
              shouldShowMask && "tracking-normal"
            )}
          >
            {syntaxHighlight(
              value,
              shouldRevealValue,
              isImport,
              isLoadingValue,
              isErrorLoadingValue,
              (part) => {
                setHoveredPart(part);
              },
              hoveredPart,
              isCmdOrCtrlPressed,
              onClickSegment,
              placeholder,
              maskEachCharacter
            )}
          </div>
          <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 text-transparent focus:border-0",
              variant === "default" && "px-2.5 py-1",
              commonClassName,
              // Monospaced in both layers, so each dot sits over the character it hides and the caret
              // in the transparent textarea lines up with them.
              maskEachCharacter && "font-mono"
            )}
            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 && !shouldBindRealValue ? HIDDEN_SECRET_VALUE : (value ?? "")}
            {...props}
            aria-invalid={isError || props["aria-invalid"]}
            readOnly={readOnly || isReadOnly || isLoadingValue || isErrorLoadingValue}
          />
        </div>
        {invisibleChars.length > 0 && (
          <Tooltip>
            <TooltipTrigger asChild>
              <IconButton
                aria-label="Value contains invisible characters"
                variant="ghost"
                size="xs"
                className={cn(
                  "border-transparent bg-transparent text-warning hover:bg-transparent hover:text-warning data-[state=open]:bg-transparent",
                  "sticky top-0 self-start",
                  variant === "default" && "mt-1 mr-2.5"
                )}
              >
                <TriangleAlertIcon />
              </IconButton>
            </TooltipTrigger>
            <TooltipContent className="max-w-72">
              <p>This value contains invisible characters that can break it when used:</p>
              <ul className="mt-1 list-disc pl-4">
                {invisibleChars.map(({ codePoint, label, count }) => (
                  <li key={codePoint}>
                    {count}x {label} ({codePoint})
                  </li>
                ))}
              </ul>
            </TooltipContent>
          </Tooltip>
        )}
      </div>
    );
  }
);

SecretInput.displayName = "SecretInput";