Skip to content

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

11.9 KB
Raw Blame
import {
  FileKeyIcon,
  KeyIcon,
  LockIcon,
  LucideIcon,
  RadarIcon,
  UsersIcon,
  VaultIcon
} from "lucide-react";

import { apiRequest } from "@app/config/request";
import { setCertManagerActiveProjectCookie } from "@app/helpers/certManagerActiveProject";
import { setSecretScanningActiveProjectCookie } from "@app/helpers/secretScanningActiveProject";
import { createWorkspace } from "@app/hooks/api/projects/queries";
import { Project, ProjectEnv, ProjectType } from "@app/hooks/api/projects/types";
import { fetchProjectSecrets } from "@app/hooks/api/secrets/queries";

const secretsToBeAdded = [
  {
    secretKey: "DATABASE_URL",
    // eslint-disable-next-line no-template-curly-in-string
    secretValue: "mongodb+srv://${DB_USERNAME}:${DB_PASSWORD}@mongodb.net",
    secretComment: "Secret referencing example"
  },
  {
    secretKey: "DB_USERNAME",
    secretValue: "OVERRIDE_THIS",
    secretComment: "Override secrets with personal value"
  },
  {
    secretKey: "DB_PASSWORD",
    secretValue: "example_password"
  },
  {
    secretKey: "TWILIO_AUTH_TOKEN",
    secretValue: "example_twillio_token"
  },
  {
    secretKey: "WEBSITE_URL",
    secretValue: "http://localhost:3000"
  }
];

const seedExampleSecrets = async (projectId: string) => {
  await apiRequest.post("/api/v4/secrets/batch", {
    projectId,
    environment: "dev",
    secretPath: "/",
    secrets: secretsToBeAdded
  });
};

/**
 * Seed the example secrets into a project that may already have them: a prior attempt can
 * have created the project but failed before seeding finished. Seeding is all-or-nothing
 * server-side, so any existing secret means the project is already seeded.
 */
export const ensureExampleSecrets = async (projectId: string) => {
  const { secrets } = await fetchProjectSecrets({
    projectId,
    environment: "dev",
    secretPath: "/",
    viewSecretValue: false
  });

  if (secrets.length === 0) {
    await seedExampleSecrets(projectId);
  }
};

/**
 * Create and initialize a new project in organization with id [organizationId]
 * Note: current user should be a member of the organization
 */
export const initProjectHelper = async ({ projectName }: { projectName: string }) => {
  // create new project
  const {
    data: { project }
  } = await createWorkspace({
    projectName,
    type: ProjectType.SecretManager
  });

  // A seeding failure must propagate; swallowing it here would report the project as
  // fully initialized and the example secrets would never be retried.
  await seedExampleSecrets(project.id);

  return project;
};

export const projectTypeToUrlSlug = (type: ProjectType): string => {
  if (type === ProjectType.SecretManager) return "secret-management";
  return type;
};

const VALID_PROJECT_SLUGS = new Set<string>([
  "secret-management",
  ProjectType.CertificateManager,
  ProjectType.KMS,
  ProjectType.SecretScanning,
  ProjectType.PAM,
  ProjectType.AgentVault
]);

export const urlSlugToProjectType = (slug: string): ProjectType | null => {
  if (!VALID_PROJECT_SLUGS.has(slug)) return null;
  if (slug === "secret-management") return ProjectType.SecretManager;
  return slug as ProjectType;
};

// Org-wide resource pages (KMIP servers, Secret Sharing, Product Settings, Insights) live at
// literal /projects/<slug>/<resource> paths with no $type route param. Parse the product slug out
// of the pathname so the sidebar can resolve the active product when the route param is absent.
const ORG_RESOURCE_PROJECT_SLUG_RE =
  /\/projects\/([^/]+)\/(?:kmip-servers|secret-sharing|product-settings|insights)/;

export const parseProjectSlugFromPath = (pathname: string): string | undefined =>
  pathname.match(ORG_RESOURCE_PROJECT_SLUG_RE)?.[1];

const PROJECT_TYPES_WITH_INTERMEDIATE_VIEW = new Set<ProjectType>([
  ProjectType.SecretManager,
  ProjectType.KMS
]);

export const hasIntermediateProjectsView = (type: ProjectType) =>
  PROJECT_TYPES_WITH_INTERMEDIATE_VIEW.has(type);

const PROJECT_TYPES_WITH_PROJECT_TEMPLATES = new Set<ProjectType>([
  ProjectType.SecretManager,
  ProjectType.KMS
]);

export const hasProjectTemplates = (type: ProjectType) =>
  PROJECT_TYPES_WITH_PROJECT_TEMPLATES.has(type);

// Products that live at /organizations/$orgId/<slug> over a single implicit project, with no $projectId
// in the URL.
const ORG_SCOPED_PRODUCT_TYPES = new Set<ProjectType>([
  ProjectType.CertificateManager,
  ProjectType.SecretScanning,
  ProjectType.PAM,
  ProjectType.AgentVault
]);

export const isOrgScopedProduct = (type: ProjectType) => ORG_SCOPED_PRODUCT_TYPES.has(type);

// This does not include PAM and Agent Vault because they use different
// components for each type of project. They don't reuse the shared components
const PROJECTLESS_PRODUCT_NAMES: Partial<Record<ProjectType, string>> = {
  [ProjectType.CertificateManager]: "Certificate Manager",
  [ProjectType.SecretScanning]: "Secret Scanning"
};

export const hidesProjects = (type?: ProjectType) =>
  Boolean(type && PROJECTLESS_PRODUCT_NAMES[type]);

export const getProjectLabel = (type?: ProjectType) =>
  (type && PROJECTLESS_PRODUCT_NAMES[type]) || "Project";

const PRODUCTS_WITHOUT_ASSUME_PRIVILEGES = new Set<ProjectType>([ProjectType.AgentVault]);

export const supportsAssumePrivileges = (type: ProjectType) =>
  !PRODUCTS_WITHOUT_ASSUME_PRIVILEGES.has(type);

const ORG_SCOPED_PRODUCT_PATH_RE =
  /^\/organizations\/[^/]+\/(cert-manager|secret-scanning|pam|agent-vault)(?:\/|$)/;

export const getOrgScopedProductFromPath = (pathname: string): ProjectType | null => {
  const slug = pathname.match(ORG_SCOPED_PRODUCT_PATH_RE)?.[1];
  return slug ? urlSlugToProjectType(slug) : null;
};

// Certificate Manager and Secret Scanning URLs name no project, so a link into one specific project
// (an earlier one, in legacy orgs that have several) pins it for their layout to open.
export const pinProjectForNavigation = (orgId: string, project: Pick<Project, "id" | "type">) => {
  if (project.type === ProjectType.CertificateManager) {
    setCertManagerActiveProjectCookie(orgId, project.id);
  } else if (project.type === ProjectType.SecretScanning) {
    setSecretScanningActiveProjectCookie(orgId, project.id);
  }
};

// Certificate Manager and Secret Scanning URLs carry no project id, so a link that may open in a
// new tab goes through the legacy project URL, whose redirect pins the instance in that tab.
export const getInstancePinningLink = (
  orgId: string,
  project: Pick<Project, "id" | "type">,
  path: string
) => {
  const params = { orgId, projectId: project.id, _splat: path };
  if (project.type === ProjectType.CertificateManager) {
    return { to: "/organizations/$orgId/projects/cert-manager/$projectId/$", params } as const;
  }
  if (project.type === ProjectType.SecretScanning) {
    return { to: "/organizations/$orgId/projects/secret-scanning/$projectId/$", params } as const;
  }
  return null;
};

export const getProjectBaseURL = (type: ProjectType) => {
  switch (type) {
    case ProjectType.SecretManager:
      return "/organizations/$orgId/projects/secret-management/$projectId";
    case ProjectType.CertificateManager:
      return "/organizations/$orgId/cert-manager" as const;
    case ProjectType.SecretScanning:
      return "/organizations/$orgId/secret-scanning" as const;
    case ProjectType.PAM:
      return "/organizations/$orgId/pam" as const;
    case ProjectType.AgentVault:
      return "/organizations/$orgId/agent-vault" as const;
    default:
      return `/organizations/$orgId/projects/${type}/$projectId` as const;
  }
};

// @ts-expect-error akhilmhdh: will remove this later
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const getProjectHomePage = (type: ProjectType, environments: ProjectEnv[]) => {
  switch (type) {
    case ProjectType.SecretManager:
      return "/organizations/$orgId/projects/secret-management/$projectId/overview" as const;
    case ProjectType.CertificateManager:
      return "/organizations/$orgId/cert-manager/overview" as const;
    case ProjectType.SecretScanning:
      return "/organizations/$orgId/secret-scanning/data-sources" as const;
    case ProjectType.PAM:
      return "/organizations/$orgId/pam/access" as const;
    case ProjectType.AgentVault:
      return "/organizations/$orgId/agent-vault" as const;
    default:
      return `/organizations/$orgId/projects/${type}/$projectId/overview` as const;
  }
};

export const getProjectTitle = (type: ProjectType) => {
  const titleConvert: Partial<Record<ProjectType, string>> = {
    [ProjectType.SecretManager]: "Secrets Management",
    [ProjectType.KMS]: "KMS",
    [ProjectType.CertificateManager]: "Certificate Manager",
    [ProjectType.SecretScanning]: "Secret Scanning",
    [ProjectType.PAM]: "Privileged Access Manager",
    [ProjectType.AgentVault]: "Agent Vault"
  };
  return titleConvert[type] || type;
};

// Certificate Manager is named after the product, except in legacy orgs that still have several
// instances, where the instance name is the only thing telling them apart.
export const getProjectDisplayName = (
  project: Pick<Project, "name" | "type">,
  isCertManagerMultiInstance: boolean
) =>
  project.type === ProjectType.CertificateManager && !isCertManagerMultiInstance
    ? getProjectTitle(project.type)
    : project.name;

export const getProjectDescription = (type: ProjectType) => {
  const descriptions: Partial<Record<ProjectType, string>> = {
    [ProjectType.SecretManager]:
      "Centralize secrets across environments with automatic secret syncs, secret rotations, short-lived dynamic credentials, and lifecycle policies.",
    [ProjectType.CertificateManager]:
      "Issue, rotate, and govern X.509 certificates for TLS, mTLS, code signing, and device identity.",
    [ProjectType.KMS]:
      "Generate, store, and use cryptographic keys to encrypt, decrypt, sign, and verify against managed CMKs.",
    [ProjectType.SecretScanning]:
      "Continuously scan repositories, builds, and runtime artifacts for leaked secrets and misconfigurations.",
    [ProjectType.PAM]:
      "Connect to databases and servers securely with session brokering, recording, and credential vaulting.",
    [ProjectType.AgentVault]:
      "Run AI agents with the access, context, and capabilities they need to do work, wherever they operate."
  };
  return descriptions[type] ?? "";
};

export const collapseCertManagerProjects = (
  projects: Project[],
  activeCertManagerProjectId: string | null
): Project[] => {
  const certManagerProjects = projects.filter((p) => p.type === ProjectType.CertificateManager);
  if (certManagerProjects.length <= 1) return projects;

  const others = projects.filter((p) => p.type !== ProjectType.CertificateManager);
  const display =
    certManagerProjects.find((p) => p.id === activeCertManagerProjectId) ?? certManagerProjects[0];
  const otherCount = certManagerProjects.length - 1;

  return [
    ...others,
    {
      ...display,
      name: "Certificate Manager",
      description:
        otherCount > 0
          ? `Active: ${display.name} · ${otherCount} other instance${otherCount === 1 ? "" : "s"}`
          : display.name
    }
  ];
};

export const getProjectLucideIcon = (type: ProjectType): LucideIcon => {
  const iconConvert: Partial<Record<ProjectType, LucideIcon>> = {
    [ProjectType.SecretManager]: KeyIcon,
    [ProjectType.KMS]: LockIcon,
    [ProjectType.CertificateManager]: FileKeyIcon,
    [ProjectType.SecretScanning]: RadarIcon,
    [ProjectType.PAM]: UsersIcon,
    [ProjectType.AgentVault]: VaultIcon
  };
  return iconConvert[type] || KeyIcon;
};

export type ProjectTileStyle = {
  iconClassName: string;
  containerClassName: string;
  cardHoverClassName: string;
  titleUnderlineClassName: string;
};

export const PROJECT_TILE_STYLE: ProjectTileStyle = {
  iconClassName: "text-project",
  containerClassName:
    "border-project/30 bg-gradient-to-br from-project/20 to-project/5 group-hover:border-project/50 group-hover:from-project/25 group-hover:to-project/10",
  cardHoverClassName: "hover:bg-gradient-to-br hover:from-project/[0.04] hover:to-transparent",
  titleUnderlineClassName: "decoration-project/60"
};