Skip to content

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

9.0 KB
Raw Blame
import { useEffect, useState } from "react";
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import { ChevronLeft, SlidersHorizontal } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";

import {
  SidebarGroup,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem
} from "@app/components/v3";
import {
  OrgPermissionActions,
  OrgPermissionSubjects,
  useOrganization,
  useOrgPermission,
  useProject
} from "@app/context";
import {
  hasIntermediateProjectsView,
  hasProjectTemplates,
  isOrgScopedProduct,
  projectTypeToUrlSlug
} from "@app/helpers/project";
import { ProjectType } from "@app/hooks/api/projects/types";
import { useGetSecretScanningInstanceState } from "@app/hooks/api/secretScanningV2";

import { AgentVaultNav } from "./AgentVaultNav";
import { CertManagerNav } from "./CertManagerNav";
import { KmsNav } from "./KmsNav";
import { PamNav } from "./PamNav";
import { SecretManagerNav } from "./SecretManagerNav";
import { SecretScanningNav } from "./SecretScanningNav";
import {
  CERT_APPROVALS_SUBMENU,
  CERT_CERTIFICATES_SUBMENU,
  CERT_INTEGRATIONS_SUBMENU,
  getSecretScanningSettingsSubmenu,
  PROJECT_ACCESS_CONTROL_SUBMENU,
  SM_SETTINGS_SUBMENU
} from "./submenus";
import { ProjectSubmenuView } from "./SubmenuViews";
import type { Submenu } from "./types";
import { PROJECT_TYPE_PATH } from "./types";

const PROJECT_NAV_COMPONENT: Record<
  ProjectType,
  React.ComponentType<{ onSubmenuOpen: (submenu: Submenu) => void }>
> = {
  [ProjectType.SecretManager]: SecretManagerNav,
  [ProjectType.KMS]: KmsNav,
  [ProjectType.CertificateManager]: CertManagerNav,
  [ProjectType.PAM]: PamNav,
  [ProjectType.SecretScanning]: SecretScanningNav,
  [ProjectType.AgentVault]: AgentVaultNav
};

// --- Project nav wrapper ---

export const ProjectNav = () => {
  const { currentProject } = useProject();
  const { currentOrg, isSubOrganization } = useOrganization();
  const { pathname, search: locationSearch } = useLocation();
  const navigate = useNavigate();
  const { permission } = useOrgPermission();
  const isLegacyView = (locationSearch as { legacy?: string })?.legacy === "true";
  const hasApplicationContext = Boolean(
    (locationSearch as { applicationName?: string })?.applicationName
  );
  const isFromRootRequests = (locationSearch as { from?: string })?.from === "root-requests";
  const hasSignerContext = Boolean((locationSearch as { signerId?: string })?.signerId);
  const intermediateAvailable = hasIntermediateProjectsView(currentProject.type);
  const { data: secretScanningInstance } = useGetSecretScanningInstanceState(currentOrg.id, {
    enabled: currentProject.type === ProjectType.SecretScanning
  });
  const hasMultipleSecretScanningProjects = Boolean(secretScanningInstance?.isMultiInstance);
  let projectLabel: string;
  if (intermediateAvailable) projectLabel = "Projects";
  else if (isSubOrganization) projectLabel = "Sub-Organization";
  else projectLabel = "Organization";
  const NavComponent = PROJECT_NAV_COMPONENT[currentProject.type];
  // Products with a projects listing link Product Settings from there; the rest link it here.
  const showProductSettings =
    !intermediateAvailable &&
    hasProjectTemplates(currentProject.type) &&
    permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.ProjectTemplates);

  // scott: we currently have to use this flaky inclusion for routes/nested routes because we haven't
  // been consistent in using a route structure that reflects nested pages; once we refactor we can switch
  // to using tanstack `isActive` link property
  const isOnAccessControl =
    pathname.includes("/access-management") ||
    Boolean(pathname.match(/\/groups\/|\/identities\/|\/members\/|\/roles\//));
  const isOnIntegrations = pathname.includes("/integrations");
  const isOnProjectSettings = /\/settings(\/|\?|$)/.test(pathname);
  const isCertManager = currentProject.type === ProjectType.CertificateManager;
  const isOnCertPolicies = isCertManager && pathname.includes("/policies");
  const isOnCertApprovals = isCertManager && pathname.includes("/approvals");

  const getInitialProjectSubmenu = (): Submenu | null => {
    if (isLegacyView || hasApplicationContext || isFromRootRequests || hasSignerContext)
      return null;
    if (isCertManager && (isOnAccessControl || pathname.includes("/discovery"))) return null;
    if (isOnAccessControl && currentProject.type === ProjectType.AgentVault) return null;
    // PAM navigation is handled separately by PamNav.
    if (currentProject.type === ProjectType.PAM) return null;
    // Secret manager renders access control as in-page tabs (no secondary submenu).
    if (isOnAccessControl && currentProject.type !== ProjectType.SecretManager)
      return PROJECT_ACCESS_CONTROL_SUBMENU;
    if (isOnIntegrations && isCertManager) return CERT_INTEGRATIONS_SUBMENU;
    if (isOnProjectSettings && currentProject.type === ProjectType.SecretManager)
      return SM_SETTINGS_SUBMENU;
    if (isOnProjectSettings && currentProject.type === ProjectType.SecretScanning)
      return getSecretScanningSettingsSubmenu(hasMultipleSecretScanningProjects);
    if (isOnCertPolicies) return CERT_CERTIFICATES_SUBMENU;
    if (isOnCertApprovals) return CERT_APPROVALS_SUBMENU;
    return null;
  };

  const [activeSubmenu, setActiveSubmenu] = useState<Submenu | null>(getInitialProjectSubmenu);

  useEffect(() => {
    setActiveSubmenu(getInitialProjectSubmenu());
  }, [pathname, hasMultipleSecretScanningProjects]);

  const handleSubmenuOpen = (submenu: Submenu) => {
    setActiveSubmenu(submenu);
    const typePath = PROJECT_TYPE_PATH[currentProject.type];
    const isOrgScoped = isOrgScopedProduct(currentProject.type);
    // Already on this submenu's page (e.g. after collapsing via the "< back" button):
    // re-navigating to the same URL would push a duplicate history entry, so just re-expand.
    const submenuPath = isOrgScoped
      ? `/organizations/${currentOrg.id}/${typePath}/${submenu.pathSuffix}`
      : `/organizations/${currentOrg.id}/projects/${typePath}/${currentProject.id}/${submenu.pathSuffix}`;
    if (pathname === submenuPath || pathname.startsWith(`${submenuPath}/`)) return;
    navigate({
      to: isOrgScoped
        ? (`/organizations/$orgId/${typePath}/${submenu.pathSuffix}` as any)
        : (`/organizations/$orgId/projects/${typePath}/$projectId/${submenu.pathSuffix}` as any),
      params: { orgId: currentOrg.id, projectId: currentProject.id } as any,
      search: { selectedTab: submenu.defaultTab } as any
    });
  };

  return (
    <AnimatePresence mode="wait" initial={false}>
      {activeSubmenu ? (
        <motion.div
          key="submenu"
          initial={{ x: 30, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          exit={{ x: 30, opacity: 0 }}
          transition={{ duration: 0.11, ease: "easeOut" }}
        >
          <ProjectSubmenuView submenu={activeSubmenu} onBack={() => setActiveSubmenu(null)} />
        </motion.div>
      ) : (
        <motion.div
          key="main"
          className="flex flex-1 flex-col"
          initial={{ x: -30, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          exit={{ x: -30, opacity: 0 }}
          transition={{ duration: 0.11, ease: "easeOut" }}
        >
          <SidebarGroup className="flex-1">
            <SidebarGroupLabel asChild>
              {intermediateAvailable ? (
                <Link
                  className="cursor-pointer hover:bg-foreground/[0.025]"
                  to="/organizations/$orgId/projects/$type"
                  params={{
                    orgId: currentOrg.id,
                    type: projectTypeToUrlSlug(currentProject.type)
                  }}
                >
                  <ChevronLeft />
                  <span>{projectLabel}</span>
                </Link>
              ) : (
                <Link
                  className="cursor-pointer hover:bg-foreground/[0.025]"
                  to="/organizations/$orgId/projects"
                  params={{ orgId: currentOrg.id }}
                >
                  <ChevronLeft />
                  <span>{projectLabel}</span>
                </Link>
              )}
            </SidebarGroupLabel>
            <NavComponent onSubmenuOpen={handleSubmenuOpen} />
            {showProductSettings && (
              <SidebarMenu>
                <SidebarMenuItem>
                  <SidebarMenuButton size="lg" asChild closeOnMobile tooltip="Product Settings">
                    <Link
                      to="/organizations/$orgId/projects/product-settings/$type"
                      params={{
                        orgId: currentOrg.id,
                        type: projectTypeToUrlSlug(currentProject.type)
                      }}
                    >
                      <SlidersHorizontal className="size-4" />
                      <span>Product Settings</span>
                    </Link>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              </SidebarMenu>
            )}
          </SidebarGroup>
        </motion.div>
      )}
    </AnimatePresence>
  );
};