Skip to content

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

new accounts and account templates ui + some template backend tweaks

x03220559cda12ede03
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
index ab223803a9..10ea0b6076 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-template-router.ts
@@ -43,7 +43,9 @@ export const registerPamAccountTemplateRouter = async (server: FastifyZodProvide
type: z.nativeEnum(PamAccountType).optional().describe("Filter by account type")
}),
response: {
- 200: z.object({ templates: z.array(SanitizedTemplateSchema) })
+ 200: z.object({
+ templates: z.array(SanitizedTemplateSchema.extend({ accountCount: z.number() }))
+ })
}
},
config: { rateLimit: readLimit },
diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts b/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
index e9dca5abb5..5b5be9a926 100644
--- a/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
+++ b/backend/src/ee/services/pam-account-template/pam-account-template-dal.ts
@@ -1,12 +1,14 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
+import { TableName, TPamAccountTemplates } from "@app/db/schemas";
import { sanitizeSqlLikeString } from "@app/lib/fn";
import { ormify } from "@app/lib/knex";
import { PamAccountType } from "../pam/pam-enums";
+export type TPamAccountTemplateWithCount = TPamAccountTemplates & { accountCount: number };
+
export type TPamAccountTemplateDALFactory = ReturnType<typeof pamAccountTemplateDALFactory>;
export const pamAccountTemplateDALFactory = (db: TDbClient) => {
@@ -16,20 +18,36 @@ export const pamAccountTemplateDALFactory = (db: TDbClient) => {
projectId: string,
filters?: { search?: string; type?: PamAccountType },
tx?: Knex
- ) => {
- const qb = (tx || db.replicaNode())(TableName.PamAccountTemplate).where({ projectId });
+ ): Promise<TPamAccountTemplateWithCount[]> => {
+ const qb = (tx || db.replicaNode())(TableName.PamAccountTemplate)
+ .leftJoin(
+ TableName.PamAccount,
+ `${TableName.PamAccount}.templateId`,
+ `${TableName.PamAccountTemplate}.id`
+ )
+ .where(`${TableName.PamAccountTemplate}.projectId`, projectId);
if (filters?.search) {
const sanitized = sanitizeSqlLikeString(filters.search);
void qb.where((inner) => {
- void inner.whereILike("name", `%${sanitized}%`).orWhereILike("type", `%${sanitized}%`);
+ void inner
+ .whereILike(`${TableName.PamAccountTemplate}.name`, `%${sanitized}%`)
+ .orWhereILike(`${TableName.PamAccountTemplate}.type`, `%${sanitized}%`);
});
}
if (filters?.type) {
- void qb.where("type", filters.type);
+ void qb.where(`${TableName.PamAccountTemplate}.type`, filters.type);
}
- return qb.orderBy("name", "asc");
+ return qb
+ .groupBy(`${TableName.PamAccountTemplate}.id`)
+ .select(
+ `${TableName.PamAccountTemplate}.*`,
+ db.raw(`COUNT(${TableName.PamAccount}.id)::int as "accountCount"`)
+ )
+ .orderBy(`${TableName.PamAccountTemplate}.name`, "asc") as unknown as Promise<
+ TPamAccountTemplateWithCount[]
+ >;
};
const countAccountsByTemplateId = async (templateId: string, tx?: Knex) => {
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index b26ad86c78..870feba073 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -19,8 +19,8 @@ import {
TListAccessiblePamAccountsDTO,
TListPamAccountTemplatesDTO,
TPamAccount,
- TPamAccountTemplate,
TPamAccountTemplateDetail,
+ TPamAccountTemplateWithCount,
TPamAccountTypeMetadata,
TPamFolderWithCount,
TPamMember,
@@ -210,7 +210,7 @@ export const useListPamAccountTemplates = (params?: TListPamAccountTemplatesDTO)
return useQuery({
queryKey: pamKeys.listTemplates(params),
queryFn: async () => {
- const { data } = await apiRequest.get<{ templates: TPamAccountTemplate[] }>(
+ const { data } = await apiRequest.get<{ templates: TPamAccountTemplateWithCount[] }>(
"/api/v1/pam/account-templates",
{ params }
);
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index 6acc25229f..d2e0e9f7ac 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -246,6 +246,8 @@ export type TDeletePamAccountDTO = {
accountType: PamAccountType;
};
+export type TPamAccountTemplateWithCount = TPamAccountTemplate & { accountCount: number };
+
export type TPamAccountTemplateDetail = TPamAccountTemplate & { accountCount: number };
export type TListPamAccountTemplatesDTO = {
diff --git a/frontend/src/hooks/usePamSheetState.ts b/frontend/src/hooks/usePamSheetState.ts
index 16dbf3e359..8ee8503c46 100644
--- a/frontend/src/hooks/usePamSheetState.ts
+++ b/frontend/src/hooks/usePamSheetState.ts
@@ -1,11 +1,19 @@
import { useNavigate, useSearch } from "@tanstack/react-router";
import { z } from "zod";
+export enum PamSheetTab {
+ Launch = "launch",
+ Permissions = "permissions",
+ Configuration = "configuration",
+ Overrides = "overrides",
+ AccessPolicy = "access-policy"
+}
+
export const pamSheetSearchParams = z.object({
accountId: z.string().optional().catch(undefined),
folderId: z.string().optional().catch(undefined),
templateId: z.string().optional().catch(undefined),
- tab: z.string().optional().catch(undefined)
+ tab: z.nativeEnum(PamSheetTab).optional().catch(undefined)
});
export type PamSheetKey = "accountId" | "folderId" | "templateId";
@@ -14,13 +22,13 @@ export const usePamSheetState = (key: PamSheetKey) => {
const navigate = useNavigate();
const search = useSearch({ strict: false }) as Record<string, unknown>;
const selectedId = search[key] as string | undefined;
- const tab = search.tab as string | undefined;
+ const tab = search.tab as PamSheetTab | undefined;
return {
selectedId,
isOpen: Boolean(selectedId),
tab,
- openSheet: (id: string, initialTab?: string) => {
+ openSheet: (id: string, initialTab?: PamSheetTab) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
navigate({ search: { ...search, [key]: id, tab: initialTab } as any });
},
diff --git a/frontend/src/pages/pam/PamAccessPage/components/FolderAccountGroup.tsx b/frontend/src/pages/pam/PamAccessPage/components/FolderAccountGroup.tsx
new file mode 100644
index 0000000000..5797e76f82
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccessPage/components/FolderAccountGroup.tsx
@@ -0,0 +1,143 @@
+import { useEffect, useMemo, useRef } from "react";
+import { ChevronRight, Folder, FolderOpen, Loader2 } from "lucide-react";
+
+import { HighlightText } from "@app/components/v2/HighlightText";
+import { TableCell, TableRow } from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import {
+ TAccessiblePamAccount,
+ TAccessiblePamFolder,
+ useListAccessiblePamAccounts
+} from "@app/hooks/api/pam";
+
+import { AccountRow } from "./AccountRow";
+
+type Props = {
+ folder: TAccessiblePamFolder;
+ isOpen: boolean;
+ onToggle: () => void;
+ search: string;
+ accountType: string;
+ filterActive: boolean;
+ onLaunch: (account: TAccessiblePamAccount) => void;
+ onResultCount: (folderId: string, count: number) => void;
+};
+
+const SKELETON_KEYS = ["a", "b", "c"];
+
+export const FolderAccountGroup = ({
+ folder,
+ isOpen,
+ onToggle,
+ search,
+ accountType,
+ filterActive,
+ onLaunch,
+ onResultCount
+}: Props) => {
+ // Only fetch this folder's accounts once it's open (lazy load per folder)
+ const { data, isLoading, hasNextPage, isFetchingNextPage, fetchNextPage } =
+ useListAccessiblePamAccounts({ folderId: folder.id }, { enabled: isOpen });
+
+ const accounts = data?.pages.flatMap((p) => p.accounts) ?? [];
+ const totalCount = data?.pages[0]?.totalCount ?? 0;
+
+ const q = search.trim().toLowerCase();
+ const hasQuery = q.length > 0;
+ const folderNameMatches = hasQuery && folder.name.toLowerCase().includes(q);
+
+ // Client-side filtering keeps search/type instant once a folder's accounts are loaded
+ const accountsToShow = useMemo(() => {
+ let list = accounts;
+ if (accountType) list = list.filter((a) => a.accountType === accountType);
+ if (hasQuery && !folderNameMatches) {
+ list = list.filter((a) => `${a.name} ${a.description ?? ""}`.toLowerCase().includes(q));
+ }
+ return list;
+ }, [accounts, accountType, q, hasQuery, folderNameMatches]);
+
+ const effectiveCount = folderNameMatches
+ ? Math.max(accountsToShow.length, 1)
+ : accountsToShow.length;
+
+ const sentinelRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const el = sentinelRef.current;
+ if (!el || !hasNextPage) return undefined;
+ const observer = new IntersectionObserver(([entry]) => {
+ if (entry.isIntersecting && !isFetchingNextPage) fetchNextPage();
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [hasNextPage, isFetchingNextPage, fetchNextPage]);
+
+ useEffect(() => {
+ if (isOpen && !isLoading) onResultCount(folder.id, effectiveCount);
+ }, [isOpen, isLoading, effectiveCount, folder.id, onResultCount]);
+
+ // While filtering, hide folders with no name match and no matching accounts
+ if (filterActive && isOpen && !isLoading && !folderNameMatches && accountsToShow.length === 0) {
+ return null;
+ }
+
+ let count = folder.accountCount;
+ if (isOpen && !isLoading) count = filterActive ? accountsToShow.length : totalCount;
+
+ return (
+ <>
+ <TableRow className="cursor-pointer select-none" onClick={onToggle}>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <ChevronRight
+ className={`size-4 shrink-0 text-muted transition-transform ${isOpen ? "rotate-90" : ""}`}
+ />
+ {isOpen ? (
+ <FolderOpen className="size-5 shrink-0 text-product-pam" />
+ ) : (
+ <Folder className="size-5 shrink-0 text-product-pam" />
+ )}
+ <span className="font-medium text-foreground">
+ <HighlightText text={folder.name} highlight={search} />
+ </span>
+ <span className="text-xs text-muted">({count})</span>
+ </div>
+ </TableCell>
+ <TableCell className="w-20" />
+ </TableRow>
+
+ {isOpen && isLoading && (
+ <TableRow>
+ <TableCell colSpan={2}>
+ <div className="flex flex-col gap-2 pl-[26px]">
+ {SKELETON_KEYS.map((key) => (
+ <Skeleton key={key} className="h-8 w-full rounded-md" />
+ ))}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+
+ {isOpen &&
+ !isLoading &&
+ accountsToShow.map((account) => (
+ <AccountRow
+ key={account.id}
+ account={account}
+ search={search}
+ onLaunch={onLaunch}
+ indented
+ />
+ ))}
+
+ {isOpen && hasNextPage && (
+ <TableRow>
+ <TableCell colSpan={2}>
+ <div ref={sentinelRef} className="flex justify-center py-2">
+ {isFetchingNextPage && <Loader2 className="size-4 animate-spin text-muted" />}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsx b/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsx
index 1b2bdf3168..dfd47d6d59 100644
--- a/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsx
+++ b/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsx
@@ -17,6 +17,7 @@ import {
} from "@app/components/v3";
import { useOrganization } from "@app/context";
import { TAccessiblePamAccount, usePamAccountTypeMap } from "@app/hooks/api/pam";
+import { PamSheetTab } from "@app/hooks/usePamSheetState";
import { PamDetailSheet } from "../../components/PamDetailSheet";
@@ -121,7 +122,7 @@ export const LaunchSessionSheet = ({ account, isOpen, onOpenChange }: Props) =>
metadata={metadata}
tabs={[
{
- value: "launch",
+ value: PamSheetTab.Launch,
label: "Launch",
icon: <Rocket className="mr-1.5 size-4" />,
content: <LaunchTab account={account} />
diff --git a/frontend/src/pages/pam/PamAccountsPage/PamAccountsPage.tsx b/frontend/src/pages/pam/PamAccountsPage/PamAccountsPage.tsx
new file mode 100644
index 0000000000..470d8e8245
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/PamAccountsPage.tsx
@@ -0,0 +1,368 @@
+import { useCallback, useEffect, useState } from "react";
+import { ChevronDown, FolderOpen, FolderPlus, Layers, Plus, Search } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { PageHeader } from "@app/components/v2";
+import {
+ Button,
+ ButtonGroup,
+ Card,
+ CardContent,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Table,
+ TableBody,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import {
+ PamAccountType,
+ useDeletePamAccount,
+ useDeletePamFolder,
+ useListPamAccountTemplates,
+ useListPamFoldersAdmin
+} from "@app/hooks/api/pam";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { PamSheetTab, usePamSheetState } from "@app/hooks/usePamSheetState";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+import { AccountPlatformIcon } from "../PamAccessPage/components/AccountPlatformIcon";
+import { AccountDetailSheet } from "./components/AccountDetailSheet";
+import { CreateAccountSheet } from "./components/CreateAccountSheet";
+import { CreateFolderModal } from "./components/CreateFolderModal";
+import { DeleteAccountModal } from "./components/DeleteAccountModal";
+import { DeleteFolderModal } from "./components/DeleteFolderModal";
+import { FolderAccountRows } from "./components/FolderAccountRows";
+import { FolderDetailSheet } from "./components/FolderDetailSheet";
+
+const SKELETON_KEYS = ["s1", "s2", "s3", "s4", "s5"];
+
+export const PamAccountsPage = () => {
+ const [searchInput, setSearchInput] = useState("");
+ const [selectedFolderId, setSelectedFolderId] = useState<string>("");
+ const [selectedTemplateId, setSelectedTemplateId] = useState<string>("");
+ const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
+ const [resultCounts, setResultCounts] = useState<Record<string, number>>({});
+
+ const { data: folders = [], isLoading: isLoadingFolders } = useListPamFoldersAdmin();
+ const { data: templates = [] } = useListPamAccountTemplates();
+
+ const deleteAccount = useDeletePamAccount();
+ const deleteFolder = useDeletePamFolder();
+
+ const { popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([
+ "createAccount",
+ "deleteAccount",
+ "createFolder",
+ "deleteFolder"
+ ] as const);
+
+ const accountSheet = usePamSheetState("accountId");
+ const folderSheet = usePamSheetState("folderId");
+
+ const query = searchInput.trim();
+ // Active filters force-open every folder so matches surface; otherwise folders load lazily on open
+ const filterActive = Boolean(query || selectedTemplateId);
+ const hasActiveFilters = Boolean(query || selectedFolderId || selectedTemplateId);
+
+ useEffect(() => {
+ setResultCounts({});
+ }, [query, selectedTemplateId]);
+
+ const toggleFolder = useCallback((folderId: string) => {
+ setExpandedFolders((prev) => {
+ const next = new Set(prev);
+ if (next.has(folderId)) next.delete(folderId);
+ else next.add(folderId);
+ return next;
+ });
+ }, []);
+
+ const handleResultCount = useCallback((folderId: string, count: number) => {
+ setResultCounts((prev) => (prev[folderId] === count ? prev : { ...prev, [folderId]: count }));
+ }, []);
+
+ const visibleFolders = selectedFolderId
+ ? folders.filter((folder) => folder.id === selectedFolderId)
+ : folders;
+
+ const isFolderOpen = (folderId: string) =>
+ filterActive || folderId === selectedFolderId || expandedFolders.has(folderId);
+
+ const filterSettled = visibleFolders.every((f) => resultCounts[f.id] !== undefined);
+ const filterHasMatches = visibleFolders.some((f) => (resultCounts[f.id] ?? 0) > 0);
+ const showNoMatches = filterActive && filterSettled && !filterHasMatches;
+ const showEmpty = !isLoadingFolders && (visibleFolders.length === 0 || showNoMatches);
+
+ const handleDelete = () => {
+ const { accountId, accountType } = popUp.deleteAccount.data as {
+ accountId: string;
+ accountType: PamAccountType;
+ };
+
+ deleteAccount.mutate(
+ { accountId, accountType },
+ {
+ onSuccess: () => {
+ createNotification({ text: "Account deleted", type: "success" });
+ handlePopUpClose("deleteAccount");
+ }
+ }
+ );
+ };
+
+ const handleDeleteFolder = () => {
+ const { folderId } = popUp.deleteFolder.data as { folderId: string };
+
+ deleteFolder.mutate(
+ { folderId },
+ {
+ onSuccess: () => {
+ createNotification({ text: "Folder deleted", type: "success" });
+ handlePopUpClose("deleteFolder");
+ }
+ }
+ );
+ };
+
+ return (
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ title="Accounts"
+ description="Privileged accounts grouped by folder."
+ scope={ProjectType.PAM}
+ />
+
+ <Card className="mt-4">
+ <CardContent className="flex items-center gap-3">
+ <InputGroup className="flex-1">
+ <InputGroupAddon align="inline-start">
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search folders and accounts..."
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
+ />
+ </InputGroup>
+
+ <Select
+ value={selectedFolderId}
+ onValueChange={(val) => setSelectedFolderId(val === "all" ? "" : val)}
+ >
+ <SelectTrigger>
+ <FolderOpen className="mr-1.5 size-4 text-muted" />
+ <SelectValue placeholder="All folders" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value="all">All folders</SelectItem>
+ {folders.map((folder) => (
+ <SelectItem key={folder.id} value={folder.id}>
+ {folder.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <Select
+ value={selectedTemplateId}
+ onValueChange={(val) => setSelectedTemplateId(val === "all" ? "" : val)}
+ >
+ <SelectTrigger>
+ {!selectedTemplateId && <Layers className="mr-1.5 size-4 text-muted" />}
+ <SelectValue placeholder="All templates" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value="all">All templates</SelectItem>
+ {templates.map((tpl) => (
+ <SelectItem key={tpl.id} value={tpl.id}>
+ <span className="flex items-center gap-1.5">
+ <AccountPlatformIcon accountType={tpl.type} size={16} />
+ {tpl.name}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <ButtonGroup>
+ <Button
+ variant="pam"
+ className="rounded-r-none"
+ onClick={() => handlePopUpOpen("createAccount")}
+ >
+ <Plus />
+ Add Account
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="pam"
+ aria-label="More create options"
+ className="border-l-transparent"
+ >
+ <ChevronDown />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4} onClick={(e) => e.stopPropagation()}>
+ <DropdownMenuItem onClick={() => handlePopUpOpen("createFolder")}>
+ <FolderPlus />
+ Add Folder
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </ButtonGroup>
+ </CardContent>
+
+ {isLoadingFolders && (
+ <CardContent>
+ <div className="flex flex-col gap-3">
+ {SKELETON_KEYS.map((key) => (
+ <Skeleton key={key} className="h-10 w-full rounded-md" />
+ ))}
+ </div>
+ </CardContent>
+ )}
+
+ {showEmpty && (
+ <CardContent>
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>
+ {hasActiveFilters ? "No results match your filters" : "No accounts yet"}
+ </EmptyTitle>
+ <EmptyDescription>
+ {hasActiveFilters
+ ? "Try adjusting your search or filters."
+ : "Create your first account to get started."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ )}
+
+ {!isLoadingFolders && !showEmpty && (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead className="w-20" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {visibleFolders.map((folder) => (
+ <FolderAccountRows
+ key={folder.id}
+ folder={folder}
+ isOpen={isFolderOpen(folder.id)}
+ onToggle={() => toggleFolder(folder.id)}
+ search={searchInput}
+ templateId={selectedTemplateId}
+ filterActive={filterActive}
+ onOpenAccount={(id) => accountSheet.openSheet(id)}
+ onConfigureAccount={(id) => accountSheet.openSheet(id, PamSheetTab.Configuration)}
+ onDeleteAccount={(target) => handlePopUpOpen("deleteAccount", target)}
+ onFolderDetails={() => folderSheet.openSheet(folder.id)}
+ onFolderConfigure={() =>
+ folderSheet.openSheet(folder.id, PamSheetTab.Configuration)
+ }
+ onFolderAddAccount={() =>
+ handlePopUpOpen("createAccount", { folderId: folder.id })
+ }
+ onFolderDelete={() =>
+ handlePopUpOpen("deleteFolder", {
+ folderId: folder.id,
+ folderName: folder.name,
+ accountCount: folder.accountCount
+ })
+ }
+ onResultCount={handleResultCount}
+ />
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </Card>
+
+ <CreateAccountSheet
+ isOpen={popUp.createAccount.isOpen}
+ defaultFolderId={(popUp.createAccount.data as { folderId?: string } | undefined)?.folderId}
+ onOpenChange={(open) => {
+ if (!open) handlePopUpClose("createAccount");
+ }}
+ />
+
+ <CreateFolderModal
+ isOpen={popUp.createFolder.isOpen}
+ onOpenChange={(open) => {
+ if (!open) handlePopUpClose("createFolder");
+ }}
+ />
+
+ <AccountDetailSheet
+ isOpen={accountSheet.isOpen}
+ accountId={accountSheet.selectedId}
+ onOpenChange={(open) => {
+ if (!open) accountSheet.closeSheet();
+ }}
+ />
+
+ <FolderDetailSheet
+ isOpen={folderSheet.isOpen}
+ folder={folders.find((f) => f.id === folderSheet.selectedId)}
+ activeTab={folderSheet.tab}
+ onTabChange={folderSheet.setTab}
+ onOpenChange={(open) => {
+ if (!open) folderSheet.closeSheet();
+ }}
+ />
+
+ <DeleteAccountModal
+ isOpen={popUp.deleteAccount.isOpen}
+ accountName={
+ (popUp.deleteAccount.data as { accountName: string } | undefined)?.accountName ?? ""
+ }
+ accountType={
+ (popUp.deleteAccount.data as { accountType: PamAccountType } | undefined)?.accountType
+ }
+ isLoading={deleteAccount.isPending}
+ onConfirm={handleDelete}
+ onOpenChange={(open) => {
+ if (!open) handlePopUpClose("deleteAccount");
+ }}
+ />
+
+ <DeleteFolderModal
+ isOpen={popUp.deleteFolder.isOpen}
+ folderName={
+ (popUp.deleteFolder.data as { folderName: string } | undefined)?.folderName ?? ""
+ }
+ accountCount={
+ (popUp.deleteFolder.data as { accountCount: number } | undefined)?.accountCount
+ }
+ isLoading={deleteFolder.isPending}
+ onConfirm={handleDeleteFolder}
+ onOpenChange={(open) => {
+ if (!open) handlePopUpClose("deleteFolder");
+ }}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountActionsMenu.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountActionsMenu.tsx
new file mode 100644
index 0000000000..b8c5c06730
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountActionsMenu.tsx
@@ -0,0 +1,73 @@
+import { useState } from "react";
+import { Eye, MoreHorizontal, Settings, Trash2 } from "lucide-react";
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ IconButton
+} from "@app/components/v3";
+import { PamResourcePermissionActions, usePamAccountActions } from "@app/hooks/api/pam";
+
+type Props = {
+ accountId: string;
+ onDetails: () => void;
+ onConfigure: () => void;
+ onDelete: () => void;
+};
+
+export const AccountActionsMenu = ({ accountId, onDetails, onConfigure, onDelete }: Props) => {
+ // Defer the permission fetch until the menu is first opened to avoid a request per row
+ const [hasOpened, setHasOpened] = useState(false);
+ const { can, isLoading } = usePamAccountActions(accountId, hasOpened);
+
+ const canRead = can(PamResourcePermissionActions.ReadAccounts);
+ const canEdit = can(PamResourcePermissionActions.EditAccounts);
+ const canDelete = can(PamResourcePermissionActions.DeleteAccounts);
+ const hasAnyAction = canRead || canEdit || canDelete;
+
+ return (
+ <DropdownMenu onOpenChange={(open) => open && setHasOpened(true)}>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Account actions"
+ className="text-muted"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <MoreHorizontal className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
+ {isLoading && <DropdownMenuItem isDisabled>Checking access&hellip;</DropdownMenuItem>}
+ {!isLoading && !hasAnyAction && (
+ <DropdownMenuItem isDisabled>No actions available</DropdownMenuItem>
+ )}
+ {canRead && (
+ <DropdownMenuItem onClick={onDetails}>
+ <Eye />
+ View Details
+ </DropdownMenuItem>
+ )}
+ {canEdit && (
+ <DropdownMenuItem onClick={onConfigure}>
+ <Settings />
+ Configure
+ </DropdownMenuItem>
+ )}
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="danger" onClick={onDelete}>
+ <Trash2 />
+ Delete Account
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
new file mode 100644
index 0000000000..8c11a8ed6b
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountDetailSheet.tsx
@@ -0,0 +1,737 @@
+import { type ReactNode, useEffect, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { useNavigate } from "@tanstack/react-router";
+import {
+ FolderInput,
+ FolderOpen,
+ Layers2,
+ MoreHorizontal,
+ Network,
+ Pencil,
+ Settings,
+ SquarePen,
+ Trash2,
+ UserPlus,
+ Users
+} from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ GatewayPicker,
+ IconButton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import { useOrganization, useUser } from "@app/context";
+import { useGetOrganizationGroups } from "@app/hooks/api/organization/queries";
+import {
+ PamAccountType,
+ PamResourcePermissionActions,
+ TPamMember,
+ useDeletePamAccount,
+ useGetPamAccountById,
+ useListAccountMembers,
+ useListFolderMembers,
+ useListPamResourceRoles,
+ usePamAccountActions,
+ usePamAccountTypeMap,
+ useRemoveAccountGroupMember,
+ useRemoveAccountMember,
+ useUpdatePamAccount
+} from "@app/hooks/api/pam";
+import { useGetOrgUsers } from "@app/hooks/api/users/queries";
+import { PamSheetTab, usePamSheetState } from "@app/hooks/usePamSheetState";
+
+import { PamMemberKind, PamMembershipScope, PamMemberSource } from "../../components/memberEnums";
+import {
+ formatDetailDate,
+ isMembershipExpired,
+ MemberExpiry,
+ PamDetailSheet
+} from "../../components/PamDetailSheet";
+import { RemoveMemberConfirm } from "../../components/RemoveMemberConfirm";
+import { SheetSaveBar } from "../../components/SheetSaveBar";
+import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
+import { AssignAccessModal, EditMemberTarget } from "./AssignAccessModal";
+import { DeleteAccountModal } from "./DeleteAccountModal";
+import { EditAccountForm } from "./EditAccountForm";
+
+type Props = {
+ isOpen: boolean;
+ accountId?: string;
+ onOpenChange: (open: boolean) => void;
+};
+
+type ResolvedMember = {
+ member: TPamMember;
+ displayName: string;
+ subtitle: string;
+ source: PamMemberSource;
+ kind: PamMemberKind;
+};
+
+const PermissionsTab = ({
+ accountId,
+ folderId,
+ folderName
+}: {
+ accountId: string;
+ folderId: string;
+ folderName: string | null;
+}) => {
+ const { currentOrg } = useOrganization();
+ const { user } = useUser();
+ const navigate = useNavigate();
+ const { data: accountMembers, isLoading: isLoadingAccount } = useListAccountMembers(accountId);
+ const { data: folderMembers, isLoading: isLoadingFolder } = useListFolderMembers(folderId);
+
+ const goToFolderPermissions = () => {
+ navigate({ search: { folderId, tab: PamSheetTab.Permissions } as any });
+ };
+ const { data: resourceRoles } = useListPamResourceRoles();
+ const { data: orgUsers } = useGetOrgUsers(currentOrg.id);
+ const { data: orgGroups } = useGetOrganizationGroups(currentOrg.id);
+ const groupMap = useMemo(
+ () => new Map((orgGroups ?? []).map((g) => [g.id, g.name] as const)),
+ [orgGroups]
+ );
+
+ const removeUser = useRemoveAccountMember();
+ const removeGroup = useRemoveAccountGroupMember();
+
+ const [isAssignOpen, setIsAssignOpen] = useState(false);
+ const [editTarget, setEditTarget] = useState<EditMemberTarget | null>(null);
+ const [removeTarget, setRemoveTarget] = useState<ResolvedMember | null>(null);
+
+ const directUserIdSet = useMemo(
+ () =>
+ new Set(
+ (accountMembers?.users ?? [])
+ .filter((m) => m.userId && !isMembershipExpired(m.expiresAt))
+ .map((m) => m.userId) as string[]
+ ),
+ [accountMembers]
+ );
+ const directGroupIdSet = useMemo(
+ () =>
+ new Set(
+ (accountMembers?.groups ?? [])
+ .filter((m) => m.groupId && !isMembershipExpired(m.expiresAt))
+ .map((m) => m.groupId) as string[]
+ ),
+ [accountMembers]
+ );
+
+ const userMap = useMemo(
+ () =>
+ new Map(
+ (orgUsers ?? []).map((ou) => {
+ const name =
+ [ou.user.firstName, ou.user.lastName].filter(Boolean).join(" ") || ou.user.username;
+ return [
+ ou.user.id,
+ { name, email: ou.user.email ?? ou.inviteEmail ?? ou.user.username }
+ ] as const;
+ })
+ ),
+ [orgUsers]
+ );
+
+ const directMembers = useMemo<ResolvedMember[]>(() => {
+ const users = (accountMembers?.users ?? []).map((m) => {
+ const info = m.userId ? userMap.get(m.userId) : undefined;
+ return {
+ member: m,
+ displayName: info?.name ?? m.userId ?? "Unknown",
+ subtitle: info?.email ?? "",
+ source: PamMemberSource.Direct,
+ kind: PamMemberKind.User
+ };
+ });
+ const groups = (accountMembers?.groups ?? []).map((m) => ({
+ member: m,
+ displayName:
+ (m.groupId ? groupMap.get(m.groupId) : undefined) ?? m.groupId ?? "Unknown group",
+ subtitle: "Group",
+ source: PamMemberSource.Direct,
+ kind: PamMemberKind.Group
+ }));
+ return [...users, ...groups];
+ }, [accountMembers, userMap, groupMap]);
+
+ const inheritedMembers = useMemo<ResolvedMember[]>(() => {
+ const users = (folderMembers?.users ?? []).map((m) => {
+ const info = m.userId ? userMap.get(m.userId) : undefined;
+ return {
+ member: m,
+ displayName: info?.name ?? m.userId ?? "Unknown",
+ subtitle: info?.email ?? "",
+ source: PamMemberSource.Inherited,
+ kind: PamMemberKind.User
+ };
+ });
+ const groups = (folderMembers?.groups ?? []).map((m) => ({
+ member: m,
+ displayName:
+ (m.groupId ? groupMap.get(m.groupId) : undefined) ?? m.groupId ?? "Unknown group",
+ subtitle: "Group",
+ source: PamMemberSource.Inherited,
+ kind: PamMemberKind.Group
+ }));
+ return [...users, ...groups];
+ }, [folderMembers, userMap, groupMap]);
+
+ const isLoading = isLoadingAccount || isLoadingFolder;
+
+ const roleNameFor = (role: string) =>
+ (resourceRoles ?? []).find((r) => r.slug === role)?.name ?? role;
+
+ const handleRemove = (rm: ResolvedMember) => {
+ const opts = {
+ onSuccess: () => createNotification({ type: "success", text: "Member removed" })
+ };
+ if (rm.kind === PamMemberKind.User && rm.member.userId) {
+ removeUser.mutate({ accountId, userId: rm.member.userId }, opts);
+ } else if (rm.kind === PamMemberKind.Group && rm.member.groupId) {
+ removeGroup.mutate({ accountId, groupId: rm.member.groupId }, opts);
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <Skeleton className="h-8 w-48" />
+ <Skeleton className="h-32 w-full" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <AssignAccessModal
+ isOpen={isAssignOpen || Boolean(editTarget)}
+ onOpenChange={(open) => {
+ if (!open) {
+ setIsAssignOpen(false);
+ setEditTarget(null);
+ }
+ }}
+ scope={PamMembershipScope.Account}
+ resourceId={accountId}
+ existingUserIds={directUserIdSet}
+ existingGroupIds={directGroupIdSet}
+ editMember={editTarget}
+ />
+ <RemoveMemberConfirm
+ isOpen={Boolean(removeTarget)}
+ onOpenChange={(open) => {
+ if (!open) setRemoveTarget(null);
+ }}
+ memberName={removeTarget?.displayName}
+ onConfirm={() => {
+ if (removeTarget) handleRemove(removeTarget);
+ setRemoveTarget(null);
+ }}
+ />
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Direct Permissions</CardTitle>
+ <CardDescription>
+ Users and groups granted access directly on this account.
+ </CardDescription>
+ <CardAction>
+ <Button size="sm" variant="pam" onClick={() => setIsAssignOpen(true)}>
+ <UserPlus className="mr-1.5 size-4" />
+ Assign Access
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {directMembers.length === 0 ? (
+ <div className="rounded-md border border-border p-8 text-center text-sm text-muted">
+ No members assigned to this account yet.
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Assignee</TableHead>
+ <TableHead>Role</TableHead>
+ <TableHead>Expiry</TableHead>
+ <TableHead className="w-12" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {directMembers.map((rm) => {
+ const isOwnMembership =
+ rm.kind === PamMemberKind.User && rm.member.userId === user.id;
+
+ return (
+ <TableRow key={`direct-${rm.member.membershipId}`} className="[&>td]:h-12">
+ <TableCell>
+ <div className="flex flex-col">
+ <span className="font-medium text-foreground">{rm.displayName}</span>
+ {rm.subtitle && <span className="text-xs text-muted">{rm.subtitle}</span>}
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant="neutral">{roleNameFor(rm.member.role)}</Badge>
+ </TableCell>
+ <TableCell>
+ <MemberExpiry expiresAt={rm.member.expiresAt} />
+ </TableCell>
+ <TableCell>
+ {!isOwnMembership && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Member actions"
+ className="text-muted"
+ >
+ <MoreHorizontal className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
+ <DropdownMenuItem
+ onClick={() =>
+ setEditTarget({
+ kind: rm.kind,
+ id:
+ (rm.kind === PamMemberKind.User
+ ? rm.member.userId
+ : rm.member.groupId) ?? "",
+ label: rm.displayName,
+ role: rm.member.role
+ })
+ }
+ >
+ <Pencil />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setRemoveTarget(rm)}
+ >
+ <Trash2 />
+ Remove
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+
+ {inheritedMembers.length > 0 && (
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Inherited Permissions</CardTitle>
+ <CardDescription>
+ Access inherited from the{" "}
+ <button
+ type="button"
+ className="font-medium text-foreground hover:underline"
+ onClick={goToFolderPermissions}
+ >
+ {folderName ?? "parent"} folder
+ </button>
+ . Manage these on the folder.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Assignee</TableHead>
+ <TableHead>Role</TableHead>
+ <TableHead>Expiry</TableHead>
+ <TableHead>Source</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {inheritedMembers.map((rm) => (
+ <TableRow key={`inherited-${rm.member.membershipId}`} className="[&>td]:h-12">
+ <TableCell>
+ <div className="flex flex-col">
+ <span className="font-medium text-foreground">{rm.displayName}</span>
+ {rm.subtitle && <span className="text-xs text-muted">{rm.subtitle}</span>}
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant="neutral">{roleNameFor(rm.member.role)}</Badge>
+ </TableCell>
+ <TableCell>
+ <MemberExpiry expiresAt={rm.member.expiresAt} />
+ </TableCell>
+ <TableCell>
+ <button
+ type="button"
+ className="flex items-center gap-1.5 text-sm text-muted hover:text-foreground hover:underline"
+ onClick={goToFolderPermissions}
+ >
+ <FolderInput className="size-3.5" />
+ from {folderName ?? "Folder"} folder
+ </button>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ );
+};
+
+type OverridesForm = { gatewayId: string | null; gatewayPoolId: string | null };
+
+const SettingsTab = ({
+ accountId,
+ onDirtyChange
+}: {
+ accountId: string;
+ onDirtyChange?: (isDirty: boolean) => void;
+}) => {
+ const { data: account, isLoading } = useGetPamAccountById(accountId);
+ const updateAccount = useUpdatePamAccount();
+ const [showGatewayPicker, setShowGatewayPicker] = useState(false);
+
+ const {
+ handleSubmit,
+ reset,
+ setValue,
+ watch,
+ formState: { isDirty }
+ } = useForm<OverridesForm>({
+ defaultValues: { gatewayId: null, gatewayPoolId: null }
+ });
+
+ useEffect(() => {
+ onDirtyChange?.(isDirty);
+ return () => onDirtyChange?.(false);
+ }, [isDirty, onDirtyChange]);
+
+ useEffect(() => {
+ if (account) {
+ reset({ gatewayId: account.gatewayId, gatewayPoolId: account.gatewayPoolId });
+ setShowGatewayPicker(false);
+ }
+ }, [account, reset]);
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <Skeleton className="h-8 w-48" />
+ <Skeleton className="h-32 w-full" />
+ </div>
+ );
+ }
+
+ if (!account) return null;
+
+ const gatewayId = watch("gatewayId");
+ const gatewayPoolId = watch("gatewayPoolId");
+ const isOverriding = Boolean(gatewayId || gatewayPoolId) || showGatewayPicker;
+
+ const setGateway = (value: OverridesForm) => {
+ setValue("gatewayId", value.gatewayId, { shouldDirty: true });
+ setValue("gatewayPoolId", value.gatewayPoolId, { shouldDirty: true });
+ };
+
+ const removeOverride = () => {
+ setGateway({ gatewayId: null, gatewayPoolId: null });
+ setShowGatewayPicker(false);
+ };
+
+ const discard = () => {
+ reset();
+ setShowGatewayPicker(false);
+ };
+
+ const onSubmit = (values: OverridesForm) => {
+ updateAccount.mutate(
+ {
+ accountId,
+ accountType: account.accountType,
+ gatewayId: values.gatewayId,
+ gatewayPoolId: values.gatewayPoolId
+ },
+ {
+ onSuccess: () => createNotification({ type: "success", text: "Overrides updated" })
+ }
+ );
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Settings</CardTitle>
+ <CardDescription>System configuration overrides.</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div
+ className={`rounded-md border p-4 ${isOverriding ? "border-product-pam/50" : "border-border"}`}
+ >
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex items-start gap-3">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-container">
+ <Network className="size-4 text-muted" />
+ </div>
+ <div>
+ <p className="font-medium text-foreground">
+ Gateway
+ {isOverriding && (
+ <span className="ml-2 text-xs font-normal text-product-pam">(override)</span>
+ )}
+ </p>
+ <p className="text-sm text-muted">
+ {isOverriding
+ ? "Overriding the template default for this account."
+ : `Inherited from ${account.templateName}`}
+ </p>
+ </div>
+ </div>
+ {isOverriding ? (
+ <Button type="button" size="sm" variant="ghost" onClick={removeOverride}>
+ Remove Override
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => setShowGatewayPicker(true)}
+ >
+ <SquarePen className="mr-1.5 size-3.5" />
+ Override
+ </Button>
+ )}
+ </div>
+
+ {isOverriding && (
+ <div className="mt-4">
+ <GatewayPicker value={{ gatewayId, gatewayPoolId }} onChange={setGateway} />
+ </div>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+
+ <div aria-hidden className="h-8 shrink-0" />
+ {isDirty && <SheetSaveBar isPending={updateAccount.isPending} onDiscard={discard} />}
+ </form>
+ );
+};
+
+const CONNECTION_FIELD_LABELS: Record<string, string> = {
+ host: "Host",
+ port: "Port",
+ database: "Database",
+ sslEnabled: "SSL",
+ sslRejectUnauthorized: "Reject Unauthorized SSL",
+ sslCertificate: "SSL Certificate"
+};
+
+const humanizeFieldKey = (key: string) =>
+ key
+ .replace(/([A-Z])/g, " $1")
+ .replace(/^./, (c) => c.toUpperCase())
+ .trim();
+
+const formatConnectionValue = (value: unknown): ReactNode => {
+ if (typeof value === "boolean") return value ? "Enabled" : "Disabled";
+ const str = String(value);
+ if (str.length > 48) return "Provided";
+ return <span className="font-mono">{str}</span>;
+};
+
+const buildConnectionMetadata = (connectionDetails: Record<string, unknown>) =>
+ Object.entries(connectionDetails)
+ .filter(([, value]) => value !== null && value !== undefined && value !== "")
+ .map(([key, value]) => ({
+ label: CONNECTION_FIELD_LABELS[key] ?? humanizeFieldKey(key),
+ value: formatConnectionValue(value)
+ }));
+
+export const AccountDetailSheet = ({ isOpen, accountId, onOpenChange }: Props) => {
+ const { data: account, isLoading } = useGetPamAccountById(isOpen ? accountId : undefined);
+ const { tab, setTab } = usePamSheetState("accountId");
+ const deleteAccount = useDeletePamAccount();
+
+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);
+ const [isFormDirty, setIsFormDirty] = useState(false);
+
+ const { map: accountTypeMap } = usePamAccountTypeMap();
+ const accountType = account?.accountType as PamAccountType | undefined;
+ const typeInfo = accountType ? accountTypeMap[accountType] : undefined;
+
+ const { can } = usePamAccountActions(accountId ?? "", isOpen && Boolean(accountId));
+ const canManageMembers = can(PamResourcePermissionActions.ManageMembers);
+ const canEdit = can(PamResourcePermissionActions.EditAccounts);
+ const canDelete = can(PamResourcePermissionActions.DeleteAccounts);
+
+ const handleDelete = () => {
+ if (!accountId || !accountType) return;
+ deleteAccount.mutate(
+ { accountId, accountType },
+ {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Account deleted" });
+ setIsDeleteOpen(false);
+ onOpenChange(false);
+ }
+ }
+ );
+ };
+
+ const actions =
+ account && (canEdit || canDelete) ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="sm" aria-label="Account actions" className="text-muted">
+ <MoreHorizontal className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
+ {canEdit && (
+ <DropdownMenuItem onClick={() => setTab(PamSheetTab.Configuration)}>
+ <Settings />
+ Configure
+ </DropdownMenuItem>
+ )}
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="danger" onClick={() => setIsDeleteOpen(true)}>
+ <Trash2 />
+ Delete
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : undefined;
+
+ const conn = (account?.connectionDetails ?? {}) as Record<string, unknown>;
+
+ const metadata = account
+ ? [
+ ...(account.description ? [{ label: "Description", value: account.description }] : []),
+ {
+ label: "Template",
+ value: <Badge variant="neutral">{account.templateName ?? "None"}</Badge>
+ },
+ ...buildConnectionMetadata(conn),
+ { label: "Created", value: formatDetailDate(account.createdAt) }
+ ]
+ : [];
+
+ const folderSubtitle = account?.folderName ? (
+ <span className="flex items-center gap-1.5">
+ <FolderOpen className="size-3.5" />
+ {account.folderName}
+ </span>
+ ) : undefined;
+
+ return (
+ <>
+ <PamDetailSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ isLoading={isLoading}
+ accountType={accountType}
+ title={account?.name}
+ subtitle={folderSubtitle}
+ typeBadge={typeInfo?.name}
+ icon={
+ accountType ? (
+ <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
+ <AccountPlatformIcon accountType={accountType} size={40} />
+ </div>
+ ) : undefined
+ }
+ metadata={metadata}
+ actions={actions}
+ activeTab={tab}
+ onTabChange={setTab}
+ tabs={
+ [
+ canManageMembers && {
+ value: PamSheetTab.Permissions,
+ label: "Permissions",
+ icon: <Users className="mr-1.5 size-4" />,
+ content:
+ accountId && account ? (
+ <PermissionsTab
+ accountId={accountId}
+ folderId={account.folderId}
+ folderName={account.folderName}
+ />
+ ) : null
+ },
+ canEdit && {
+ value: PamSheetTab.Configuration,
+ label: "Configuration",
+ icon: <Settings className="mr-1.5 size-4" />,
+ content: accountId ? (
+ <EditAccountForm accountId={accountId} onDirtyChange={setIsFormDirty} />
+ ) : null
+ },
+ canEdit && {
+ value: PamSheetTab.Overrides,
+ label: "Overrides",
+ icon: <Layers2 className="mr-1.5 size-4" />,
+ content: accountId ? (
+ <SettingsTab accountId={accountId} onDirtyChange={setIsFormDirty} />
+ ) : null
+ }
+ ].filter(Boolean) as {
+ value: string;
+ label: string;
+ icon: JSX.Element;
+ content: JSX.Element | null;
+ }[]
+ }
+ isDirty={isFormDirty}
+ />
+
+ <DeleteAccountModal
+ isOpen={isDeleteOpen}
+ accountName={account?.name ?? ""}
+ accountType={accountType}
+ isLoading={deleteAccount.isPending}
+ onConfirm={handleDelete}
+ onOpenChange={setIsDeleteOpen}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AssignAccessModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AssignAccessModal.tsx
new file mode 100644
index 0000000000..24a69141f7
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/AssignAccessModal.tsx
@@ -0,0 +1,363 @@
+import { useMemo, useState } from "react";
+import { components, OptionProps } from "react-select";
+import { User as UserIcon, Users as UsersIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { RoleOption } from "@app/components/roles";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel,
+ FilterableSelect,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { useOrganization } from "@app/context";
+import { useGetOrganizationGroups } from "@app/hooks/api/organization/queries";
+import {
+ TPamResourceRole,
+ useAddAccountGroupMember,
+ useAddAccountMember,
+ useAddFolderGroupMember,
+ useAddFolderMember,
+ useListPamResourceRoles,
+ useUpdateAccountGroupMemberRole,
+ useUpdateAccountMemberRole,
+ useUpdateFolderGroupMemberRole,
+ useUpdateFolderMemberRole
+} from "@app/hooks/api/pam";
+import { useGetOrgUsers } from "@app/hooks/api/users/queries";
+
+import { PamMemberKind, PamMembershipScope } from "../../components/memberEnums";
+
+type AssigneeOption = {
+ value: string;
+ label: string;
+ kind: PamMemberKind;
+ subtitle: string;
+};
+
+export type EditMemberTarget = {
+ kind: PamMemberKind;
+ id: string;
+ label: string;
+ role: string;
+};
+
+const EXPIRY_OPTIONS = [
+ { value: "none", label: "No expiry" },
+ { value: "15m", label: "15 minutes" },
+ { value: "1h", label: "1 hour" },
+ { value: "4h", label: "4 hours" },
+ { value: "1d", label: "1 day" },
+ { value: "3d", label: "3 days" },
+ { value: "7d", label: "1 week" },
+ { value: "14d", label: "2 weeks" },
+ { value: "30d", label: "1 month" }
+];
+
+const AssigneeSelectOption = ({ children, ...props }: OptionProps<AssigneeOption>) => (
+ <components.Option {...props}>
+ <div className="flex items-center gap-2.5">
+ {props.data.kind === PamMemberKind.Group ? (
+ <UsersIcon className="size-4 shrink-0 text-muted" />
+ ) : (
+ <UserIcon className="size-4 shrink-0 text-muted" />
+ )}
+ <div className="min-w-0">
+ <p className="truncate">{children}</p>
+ {props.data.subtitle && (
+ <p className="truncate text-xs leading-4 text-muted">{props.data.subtitle}</p>
+ )}
+ </div>
+ </div>
+ </components.Option>
+);
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ scope: PamMembershipScope;
+ resourceId: string;
+ existingUserIds: Set<string>;
+ existingGroupIds: Set<string>;
+ editMember?: EditMemberTarget | null;
+};
+
+export const AssignAccessModal = ({
+ isOpen,
+ onOpenChange,
+ scope,
+ resourceId,
+ existingUserIds,
+ existingGroupIds,
+ editMember
+}: Props) => {
+ const { currentOrg } = useOrganization();
+ const { data: orgUsers } = useGetOrgUsers(currentOrg.id);
+ const { data: orgGroups } = useGetOrganizationGroups(currentOrg.id);
+ const { data: resourceRoles } = useListPamResourceRoles();
+
+ const addAccountUser = useAddAccountMember();
+ const addAccountGroup = useAddAccountGroupMember();
+ const addFolderUser = useAddFolderMember();
+ const addFolderGroup = useAddFolderGroupMember();
+ const updateAccountUser = useUpdateAccountMemberRole();
+ const updateAccountGroup = useUpdateAccountGroupMemberRole();
+ const updateFolderUser = useUpdateFolderMemberRole();
+ const updateFolderGroup = useUpdateFolderGroupMemberRole();
+
+ const isEdit = Boolean(editMember);
+
+ const [selectedActor, setSelectedActor] = useState<AssigneeOption | null>(null);
+ const [roleSlug, setRoleSlug] = useState<string>("");
+ const [expiry, setExpiry] = useState<string>("none");
+
+ // Roles come ordered most-to-least privileged, so the last one is the safe default
+ const defaultRoleSlug = useMemo(
+ () => (resourceRoles?.length ? resourceRoles[resourceRoles.length - 1].slug : ""),
+ [resourceRoles]
+ );
+ const effectiveRoleSlug = roleSlug || editMember?.role || defaultRoleSlug;
+
+ const lockedActor = useMemo<AssigneeOption | null>(
+ () =>
+ editMember
+ ? {
+ value: editMember.id,
+ label: editMember.label,
+ kind: editMember.kind,
+ subtitle: editMember.kind === PamMemberKind.Group ? "Group" : ""
+ }
+ : null,
+ [editMember]
+ );
+
+ const assigneeOptions = useMemo<AssigneeOption[]>(() => {
+ const groups: AssigneeOption[] = (orgGroups ?? [])
+ .filter((g) => !existingGroupIds.has(g.id))
+ .map((g) => ({ value: g.id, label: g.name, kind: PamMemberKind.Group, subtitle: "Group" }));
+
+ const users: AssigneeOption[] = (orgUsers ?? [])
+ .filter((ou) => ou.user.id && !existingUserIds.has(ou.user.id))
+ .map((ou) => {
+ const name = [ou.user.firstName, ou.user.lastName].filter(Boolean).join(" ");
+ return {
+ value: ou.user.id,
+ label: name || ou.user.email || ou.inviteEmail || ou.user.username,
+ kind: PamMemberKind.User,
+ subtitle: ou.user.email ?? ou.inviteEmail ?? ""
+ };
+ });
+
+ return [...groups, ...users];
+ }, [orgGroups, orgUsers, existingGroupIds, existingUserIds]);
+
+ const selectedRole = (resourceRoles ?? []).find((r) => r.slug === effectiveRoleSlug) ?? null;
+
+ const isPending =
+ addAccountUser.isPending ||
+ addAccountGroup.isPending ||
+ addFolderUser.isPending ||
+ addFolderGroup.isPending ||
+ updateAccountUser.isPending ||
+ updateAccountGroup.isPending ||
+ updateFolderUser.isPending ||
+ updateFolderGroup.isPending;
+
+ const reset = () => {
+ setSelectedActor(null);
+ setRoleSlug("");
+ setExpiry("none");
+ };
+
+ const handleEdit = () => {
+ if (!editMember || !effectiveRoleSlug) return;
+ const isUser = editMember.kind === PamMemberKind.User;
+
+ const opts = {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Role updated" });
+ reset();
+ onOpenChange(false);
+ }
+ };
+
+ if (scope === PamMembershipScope.Account && isUser) {
+ updateAccountUser.mutate(
+ { accountId: resourceId, userId: editMember.id, role: effectiveRoleSlug },
+ opts
+ );
+ } else if (scope === PamMembershipScope.Account) {
+ updateAccountGroup.mutate(
+ { accountId: resourceId, groupId: editMember.id, role: effectiveRoleSlug },
+ opts
+ );
+ } else if (isUser) {
+ updateFolderUser.mutate(
+ { folderId: resourceId, userId: editMember.id, role: effectiveRoleSlug },
+ opts
+ );
+ } else {
+ updateFolderGroup.mutate(
+ { folderId: resourceId, groupId: editMember.id, role: effectiveRoleSlug },
+ opts
+ );
+ }
+ };
+
+ const handleAssign = () => {
+ if (!selectedActor || !effectiveRoleSlug) return;
+ const expiryValue = expiry === "none" ? null : expiry;
+ const isUser = selectedActor.kind === PamMemberKind.User;
+
+ const opts = {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Access assigned" });
+ reset();
+ onOpenChange(false);
+ }
+ };
+
+ if (scope === PamMembershipScope.Account && isUser) {
+ addAccountUser.mutate(
+ {
+ accountId: resourceId,
+ userId: selectedActor.value,
+ role: effectiveRoleSlug,
+ expiry: expiryValue
+ },
+ opts
+ );
+ } else if (scope === PamMembershipScope.Account) {
+ addAccountGroup.mutate(
+ {
+ accountId: resourceId,
+ groupId: selectedActor.value,
+ role: effectiveRoleSlug,
+ expiry: expiryValue
+ },
+ opts
+ );
+ } else if (isUser) {
+ addFolderUser.mutate(
+ {
+ folderId: resourceId,
+ userId: selectedActor.value,
+ role: effectiveRoleSlug,
+ expiry: expiryValue
+ },
+ opts
+ );
+ } else {
+ addFolderGroup.mutate(
+ {
+ folderId: resourceId,
+ groupId: selectedActor.value,
+ role: effectiveRoleSlug,
+ expiry: expiryValue
+ },
+ opts
+ );
+ }
+ };
+
+ return (
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) reset();
+ onOpenChange(open);
+ }}
+ >
+ <DialogContent className="overflow-visible sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{isEdit ? "Edit Access" : "Assign Access"}</DialogTitle>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4">
+ <Field>
+ <FieldLabel>Assignee</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ value={isEdit ? lockedActor : selectedActor}
+ options={assigneeOptions}
+ isDisabled={isEdit}
+ onChange={(opt) => setSelectedActor((opt as AssigneeOption | null) ?? null)}
+ getOptionValue={(opt) => `${opt.kind}:${opt.value}`}
+ getOptionLabel={(opt) => opt.label}
+ components={{ Option: AssigneeSelectOption }}
+ placeholder="Pick a user or a group..."
+ noOptionsMessage={() => "No users or groups available to assign."}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Role</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ value={selectedRole}
+ options={resourceRoles ?? []}
+ onChange={(opt) => setRoleSlug((opt as TPamResourceRole | null)?.slug ?? "")}
+ getOptionValue={(opt) => opt.slug}
+ getOptionLabel={(opt) => opt.name}
+ components={{ Option: RoleOption }}
+ placeholder="Select a role..."
+ />
+ </FieldContent>
+ </Field>
+
+ {!isEdit && (
+ <Field>
+ <FieldLabel>Expiry</FieldLabel>
+ <FieldContent>
+ <Select value={expiry} onValueChange={setExpiry}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {EXPIRY_OPTIONS.map((opt) => (
+ <SelectItem key={opt.value} value={opt.value}>
+ {opt.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ </Field>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ {isEdit ? (
+ <Button variant="pam" isPending={isPending} onClick={handleEdit}>
+ Save
+ </Button>
+ ) : (
+ <Button
+ variant="pam"
+ isPending={isPending}
+ isDisabled={!selectedActor}
+ onClick={handleAssign}
+ >
+ Assign
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
new file mode 100644
index 0000000000..234ed5961f
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
@@ -0,0 +1,26 @@
+import { Control, useWatch } from "react-hook-form";
+
+import { useListPamAccountTypes } from "@app/hooks/api/pam";
+
+import { TAccountFormValues } from "./accountFormSchema";
+import { PamSchemaFields } from "./PamSchemaFields";
+
+type Props = {
+ control: Control<TAccountFormValues>;
+};
+
+export const ConnectionDetailsForm = ({ control }: Props) => {
+ const accountType = useWatch({ control, name: "accountType" });
+ const { data: accountTypes } = useListPamAccountTypes();
+
+ const metadata = accountTypes?.find((t) => t.type === accountType);
+ if (!metadata) return null;
+
+ return (
+ <PamSchemaFields
+ control={control}
+ namePrefix="connectionDetails"
+ fields={metadata.connectionFields}
+ />
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx
new file mode 100644
index 0000000000..dd148eb2d9
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx
@@ -0,0 +1,392 @@
+import { useEffect, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangle, Search } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { HighlightText } from "@app/components/v2/HighlightText";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ RadioGroup,
+ RadioGroupItem
+} from "@app/components/v3";
+import { Button } from "@app/components/v3/generic/Button";
+import { Field, FieldContent, FieldError, FieldLabel } from "@app/components/v3/generic/Field";
+import { Input } from "@app/components/v3/generic/Input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3/generic/Select";
+import {
+ Sheet,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle
+} from "@app/components/v3/generic/Sheet";
+import { TextArea } from "@app/components/v3/generic/TextArea";
+import {
+ PamAccountType,
+ useCreatePamAccount,
+ useListPamAccountTemplates,
+ useListPamAccountTypes,
+ useListPamFoldersAdmin,
+ usePamAccountTypeMap
+} from "@app/hooks/api/pam";
+
+import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
+import {
+ accountFormSchema,
+ areRequiredFieldsFilled,
+ buildDefaultFieldValues,
+ TAccountFormValues
+} from "./accountFormSchema";
+import { ConnectionDetailsForm } from "./ConnectionDetailsForm";
+import { CredentialsForm } from "./CredentialsForm";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ defaultFolderId?: string;
+};
+
+export const CreateAccountSheet = ({ isOpen, onOpenChange, defaultFolderId }: Props) => {
+ const createAccount = useCreatePamAccount();
+
+ const [step, setStep] = useState<1 | 2>(1);
+ const [templateSearch, setTemplateSearch] = useState("");
+ const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ setValue,
+ formState: { isDirty }
+ } = useForm<TAccountFormValues>({
+ resolver: zodResolver(accountFormSchema),
+ defaultValues: {
+ accountType: PamAccountType.Postgres,
+ name: "",
+ description: "",
+ folderId: "",
+ templateId: "",
+ connectionDetails: {},
+ credentials: {}
+ }
+ });
+
+ const selectedFolderId = watch("folderId");
+ const selectedTemplateId = watch("templateId");
+
+ const { data: accountTypes = [] } = useListPamAccountTypes();
+ const { data: folders = [] } = useListPamFoldersAdmin();
+ const { data: templates = [] } = useListPamAccountTemplates();
+ const { map: accountTypeMap } = usePamAccountTypeMap();
+
+ const selectedTemplate = templates.find((t) => t.id === selectedTemplateId);
+ const selectedMetadata = accountTypes.find((t) => t.type === selectedTemplate?.type);
+
+ const templateQuery = templateSearch.trim().toLowerCase();
+ const filteredTemplates = templates.filter((tpl) => {
+ if (!templateQuery) return true;
+ const typeName = accountTypeMap[tpl.type]?.name ?? tpl.type;
+ return `${tpl.name} ${tpl.description ?? ""} ${tpl.type} ${typeName}`
+ .toLowerCase()
+ .includes(templateQuery);
+ });
+
+ // Reset everything to a fresh state when the sheet (re)opens, honoring a pre-filled folder
+ useEffect(() => {
+ if (isOpen) {
+ reset({
+ accountType: PamAccountType.Postgres,
+ name: "",
+ description: "",
+ folderId: defaultFolderId ?? "",
+ templateId: "",
+ connectionDetails: {},
+ credentials: {}
+ });
+ setStep(1);
+ setTemplateSearch("");
+ }
+ }, [isOpen, defaultFolderId, reset]);
+
+ // The chosen template fixes the account type; seed the type + its field defaults from metadata
+ useEffect(() => {
+ if (!selectedMetadata) return;
+ setValue("accountType", selectedMetadata.type);
+ setValue("connectionDetails", buildDefaultFieldValues(selectedMetadata.connectionFields));
+ setValue("credentials", buildDefaultFieldValues(selectedMetadata.credentialFields));
+ }, [selectedMetadata?.type, setValue]);
+
+ const canProceed = Boolean(selectedFolderId && selectedTemplateId);
+
+ const onSubmit = (values: TAccountFormValues) => {
+ if (!selectedMetadata) return;
+
+ if (!areRequiredFieldsFilled(selectedMetadata.connectionFields, values.connectionDetails)) {
+ createNotification({ text: "Check connection details fields", type: "error" });
+ return;
+ }
+ if (!areRequiredFieldsFilled(selectedMetadata.credentialFields, values.credentials)) {
+ createNotification({ text: "Check credentials fields", type: "error" });
+ return;
+ }
+
+ createAccount.mutate(
+ {
+ accountType: values.accountType,
+ name: values.name,
+ description: values.description || undefined,
+ folderId: values.folderId,
+ templateId: values.templateId,
+ connectionDetails: values.connectionDetails,
+ credentials: values.credentials
+ },
+ {
+ onSuccess: () => {
+ createNotification({ text: "Account created", type: "success" });
+ onOpenChange(false);
+ }
+ }
+ );
+ };
+
+ // Warn before discarding a partially filled form
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen && isDirty) {
+ setConfirmDiscardOpen(true);
+ return;
+ }
+ onOpenChange(nextOpen);
+ };
+
+ return (
+ <>
+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>Add Account</SheetTitle>
+ </SheetHeader>
+
+ {step === 1 ? (
+ <>
+ <div className="flex min-h-0 flex-1 flex-col gap-5 px-4">
+ <Controller
+ control={control}
+ name="folderId"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>
+ Folder<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select folder" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {folders.map((folder) => (
+ <SelectItem key={folder.id} value={folder.id}>
+ {folder.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="templateId"
+ render={({ field }) => (
+ <Field className="min-h-0 flex-1">
+ <FieldLabel>
+ Account Template<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent className="min-h-0 flex-1">
+ <InputGroup>
+ <InputGroupAddon align="inline-start">
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search templates..."
+ value={templateSearch}
+ onChange={(e) => setTemplateSearch(e.target.value)}
+ />
+ </InputGroup>
+ <RadioGroup
+ value={field.value}
+ onValueChange={field.onChange}
+ className="mt-2 flex thin-scrollbar flex-1 flex-col gap-2 overflow-y-auto"
+ >
+ {filteredTemplates.map((tpl) => {
+ const typeName = accountTypeMap[tpl.type]?.name ?? tpl.type;
+ const subtitle = tpl.description
+ ? `${typeName} • ${tpl.description}`
+ : typeName;
+ return (
+ <FieldLabel key={tpl.id} htmlFor={`tpl-${tpl.id}`} variant="pam">
+ <Field orientation="horizontal" className="items-center gap-3">
+ <AccountPlatformIcon accountType={tpl.type} size={28} />
+ <div className="min-w-0 flex-1 text-left">
+ <p className="truncate text-sm font-medium text-foreground">
+ <HighlightText text={tpl.name} highlight={templateSearch} />
+ </p>
+ <p className="truncate text-xs text-muted">
+ <HighlightText text={subtitle} highlight={templateSearch} />
+ </p>
+ </div>
+ <RadioGroupItem
+ id={`tpl-${tpl.id}`}
+ value={tpl.id}
+ className="sr-only"
+ />
+ </Field>
+ </FieldLabel>
+ );
+ })}
+ {filteredTemplates.length === 0 && (
+ <div className="rounded-md border border-border p-8 text-center text-sm text-muted">
+ {templates.length === 0
+ ? "No templates yet. Create one from the Account Templates page."
+ : "No templates match your search."}
+ </div>
+ )}
+ </RadioGroup>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </div>
+
+ <SheetFooter className="justify-end border-t">
+ <Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ variant="pam"
+ isDisabled={!canProceed}
+ onClick={() => setStep(2)}
+ >
+ Next
+ </Button>
+ </SheetFooter>
+ </>
+ ) : (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto px-4">
+ {selectedTemplate && (
+ <div className="flex items-center gap-3 rounded-md border border-border bg-container p-3">
+ <AccountPlatformIcon accountType={selectedTemplate.type} size={28} />
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-foreground">{selectedTemplate.name}</p>
+ <p className="truncate text-xs text-muted">
+ {accountTypeMap[selectedTemplate.type]?.name ?? selectedTemplate.type}
+ {selectedTemplate.description ? ` • ${selectedTemplate.description}` : ""}
+ </p>
+ </div>
+ </div>
+ )}
+
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ Name<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="My account" isError={!!fieldState.error} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea {...field} placeholder="Optional description" rows={2} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <div className="mt-2">
+ <h3 className="mb-3 text-sm font-medium text-foreground">Connection Details</h3>
+ <ConnectionDetailsForm control={control} />
+ </div>
+
+ <div className="mt-2">
+ <h3 className="mb-3 text-sm font-medium text-foreground">Credentials</h3>
+ <CredentialsForm control={control} />
+ </div>
+ </div>
+
+ <SheetFooter className="justify-end border-t">
+ <Button type="button" variant="ghost" onClick={() => setStep(1)}>
+ Back
+ </Button>
+ <Button type="submit" variant="pam" isPending={createAccount.isPending}>
+ Create
+ </Button>
+ </SheetFooter>
+ </form>
+ )}
+ </SheetContent>
+ </Sheet>
+
+ <AlertDialog open={confirmDiscardOpen} onOpenChange={setConfirmDiscardOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <AlertTriangle />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Discard account setup?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Your progress creating this account will be lost.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep Editing</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ onClick={() => {
+ setConfirmDiscardOpen(false);
+ onOpenChange(false);
+ }}
+ >
+ Discard
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/CreateFolderModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/CreateFolderModal.tsx
new file mode 100644
index 0000000000..3fc320c03a
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CreateFolderModal.tsx
@@ -0,0 +1,110 @@
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldError,
+ FieldLabel,
+ Input,
+ TextArea
+} from "@app/components/v3";
+import { useCreatePamFolder } from "@app/hooks/api/pam";
+
+const formSchema = z.object({
+ name: z.string().min(1, "Name is required").max(64),
+ description: z.string().max(256).optional()
+});
+
+type FormData = z.infer<typeof formSchema>;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+export const CreateFolderModal = ({ isOpen, onOpenChange }: Props) => {
+ const createFolder = useCreatePamFolder();
+
+ const {
+ register,
+ handleSubmit,
+ reset,
+ formState: { errors }
+ } = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: { name: "", description: "" }
+ });
+
+ const onSubmit = (data: FormData) => {
+ createFolder.mutate(
+ { name: data.name, description: data.description || undefined },
+ {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Folder created" });
+ reset();
+ onOpenChange(false);
+ }
+ }
+ );
+ };
+
+ return (
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) reset();
+ onOpenChange(open);
+ }}
+ >
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Add Folder</DialogTitle>
+ </DialogHeader>
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <Field>
+ <FieldLabel htmlFor="folder-name">Name</FieldLabel>
+ <FieldContent>
+ <Input
+ id="folder-name"
+ placeholder="e.g. production-databases"
+ isError={!!errors.name}
+ {...register("name")}
+ />
+ <FieldError>{errors.name?.message}</FieldError>
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="folder-description">Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ id="folder-description"
+ placeholder="What lives in this folder?"
+ rows={3}
+ {...register("description")}
+ />
+ </FieldContent>
+ </Field>
+
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="pam" isPending={createFolder.isPending}>
+ Add Folder
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/CredentialsForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/CredentialsForm.tsx
new file mode 100644
index 0000000000..c8dc060ca3
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CredentialsForm.tsx
@@ -0,0 +1,26 @@
+import { Control, useWatch } from "react-hook-form";
+
+import { useListPamAccountTypes } from "@app/hooks/api/pam";
+
+import { TAccountFormValues } from "./accountFormSchema";
+import { PamSchemaFields } from "./PamSchemaFields";
+
+type Props = {
+ control: Control<TAccountFormValues>;
+};
+
+export const CredentialsForm = ({ control }: Props) => {
+ const accountType = useWatch({ control, name: "accountType" });
+ const { data: accountTypes } = useListPamAccountTypes();
+
+ const metadata = accountTypes?.find((t) => t.type === accountType);
+ if (!metadata) return null;
+
+ return (
+ <PamSchemaFields
+ control={control}
+ namePrefix="credentials"
+ fields={metadata.credentialFields}
+ />
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/DeleteAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/DeleteAccountModal.tsx
new file mode 100644
index 0000000000..322a4aa737
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/DeleteAccountModal.tsx
@@ -0,0 +1,84 @@
+import { useEffect, useState } from "react";
+
+import { Button } from "@app/components/v3/generic/Button";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from "@app/components/v3/generic/Dialog";
+import { Field, FieldContent, FieldLabel } from "@app/components/v3/generic/Field";
+import { Input } from "@app/components/v3/generic/Input";
+import { PamAccountType, usePamAccountTypeMap } from "@app/hooks/api/pam";
+
+type Props = {
+ isOpen: boolean;
+ accountName: string;
+ accountType?: PamAccountType;
+ isLoading: boolean;
+ onConfirm: () => void;
+ onOpenChange: (open: boolean) => void;
+};
+
+export const DeleteAccountModal = ({
+ isOpen,
+ accountName,
+ accountType,
+ isLoading,
+ onConfirm,
+ onOpenChange
+}: Props) => {
+ const { map } = usePamAccountTypeMap();
+ const typeName = accountType ? map[accountType]?.name : "";
+
+ const [confirmInput, setConfirmInput] = useState("");
+ const canDelete = confirmInput === accountName && accountName.length > 0;
+
+ useEffect(() => {
+ setConfirmInput("");
+ }, [isOpen]);
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Delete Account</DialogTitle>
+ </DialogHeader>
+ <form
+ className="grid gap-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (canDelete && !isLoading) onConfirm();
+ }}
+ >
+ <p className="text-sm text-muted">
+ Are you sure you want to delete{" "}
+ <span className="font-medium text-foreground">{accountName}</span>
+ {typeName ? ` (${typeName})` : ""}? This action cannot be undone.
+ </p>
+ <Field>
+ <FieldLabel>
+ Type <span className="font-medium text-foreground">{accountName}</span> to confirm
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ value={confirmInput}
+ onChange={(e) => setConfirmInput(e.target.value)}
+ placeholder={accountName}
+ />
+ </FieldContent>
+ </Field>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="danger" isPending={isLoading} isDisabled={!canDelete}>
+ Delete
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/DeleteFolderModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/DeleteFolderModal.tsx
new file mode 100644
index 0000000000..4d371c1450
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/DeleteFolderModal.tsx
@@ -0,0 +1,99 @@
+import { useEffect, useState } from "react";
+
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel,
+ Input
+} from "@app/components/v3";
+
+type Props = {
+ isOpen: boolean;
+ folderName: string;
+ accountCount?: number;
+ isLoading: boolean;
+ onConfirm: () => void;
+ onOpenChange: (open: boolean) => void;
+};
+
+export const DeleteFolderModal = ({
+ isOpen,
+ folderName,
+ accountCount = 0,
+ isLoading,
+ onConfirm,
+ onOpenChange
+}: Props) => {
+ const [confirmInput, setConfirmInput] = useState("");
+ const canDelete = confirmInput === folderName && folderName.length > 0;
+ const hasAccounts = accountCount > 0;
+
+ useEffect(() => {
+ setConfirmInput("");
+ }, [isOpen]);
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Delete Folder</DialogTitle>
+ </DialogHeader>
+
+ {hasAccounts ? (
+ <div className="grid gap-4">
+ <p className="text-sm text-muted">
+ <span className="font-medium text-foreground">{folderName}</span> contains{" "}
+ {accountCount} account{accountCount === 1 ? "" : "s"}. Move or delete{" "}
+ {accountCount === 1 ? "it" : "them"} before this folder can be deleted.
+ </p>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Close
+ </Button>
+ </DialogFooter>
+ </div>
+ ) : (
+ <form
+ className="grid gap-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (canDelete && !isLoading) onConfirm();
+ }}
+ >
+ <p className="text-sm text-muted">
+ Are you sure you want to delete{" "}
+ <span className="font-medium text-foreground">{folderName}</span>? This action cannot
+ be undone.
+ </p>
+ <Field>
+ <FieldLabel>
+ Type <span className="font-medium text-foreground">{folderName}</span> to confirm
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ value={confirmInput}
+ onChange={(e) => setConfirmInput(e.target.value)}
+ placeholder={folderName}
+ />
+ </FieldContent>
+ </Field>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="danger" isPending={isLoading} isDisabled={!canDelete}>
+ Delete
+ </Button>
+ </DialogFooter>
+ </form>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
new file mode 100644
index 0000000000..df40d9a826
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
@@ -0,0 +1,275 @@
+import { useEffect, useMemo } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+
+import { createNotification } from "@app/components/notifications";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@app/components/v3";
+import { Field, FieldContent, FieldError, FieldLabel } from "@app/components/v3/generic/Field";
+import { Input } from "@app/components/v3/generic/Input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3/generic/Select";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import { TextArea } from "@app/components/v3/generic/TextArea";
+import {
+ useGetPamAccountById,
+ useListPamAccountTemplates,
+ useListPamAccountTypes,
+ useListPamFoldersAdmin,
+ useUpdatePamAccount
+} from "@app/hooks/api/pam";
+import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";
+
+import { SheetSaveBar } from "../../components/SheetSaveBar";
+import {
+ accountFormSchema,
+ areRequiredFieldsFilled,
+ buildDefaultFieldValues,
+ buildEditCredentialValues,
+ TAccountFormValues
+} from "./accountFormSchema";
+import { ConnectionDetailsForm } from "./ConnectionDetailsForm";
+import { CredentialsForm } from "./CredentialsForm";
+
+function filterUnchangedCredentials(
+ credentials: Record<string, unknown>
+): Record<string, unknown> | null {
+ const entries = Object.entries(credentials);
+ const changed = entries.filter(([, v]) => v !== UNCHANGED_PASSWORD_SENTINEL);
+
+ if (changed.length === entries.length) {
+ return credentials;
+ }
+
+ const hasRealChanges = changed.some(([key]) => key !== "authMethod");
+
+ if (!hasRealChanges) return null;
+
+ return Object.fromEntries(changed);
+}
+
+const SKELETON_ROWS = ["s1", "s2", "s3", "s4", "s5", "s6"];
+
+type Props = {
+ accountId?: string;
+ onDirtyChange?: (isDirty: boolean) => void;
+};
+
+export const EditAccountForm = ({ accountId, onDirtyChange }: Props) => {
+ const { data: account, isLoading: isLoadingAccount } = useGetPamAccountById(accountId);
+ const updateAccount = useUpdatePamAccount();
+ const { data: accountTypes = [] } = useListPamAccountTypes();
+ const { data: folders = [] } = useListPamFoldersAdmin();
+ const { data: templates = [] } = useListPamAccountTemplates(
+ account ? { type: account.accountType } : undefined
+ );
+
+ const metadata = useMemo(
+ () => accountTypes.find((t) => t.type === account?.accountType),
+ [accountTypes, account?.accountType]
+ );
+
+ // Keep the current template selectable before the type-filtered list loads
+ const templateOptions = useMemo(() => {
+ const options = templates.map((t) => ({ id: t.id, name: t.name }));
+ if (account && !options.some((o) => o.id === account.templateId)) {
+ options.unshift({ id: account.templateId, name: account.templateName });
+ }
+ return options;
+ }, [templates, account]);
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isDirty }
+ } = useForm<TAccountFormValues>({
+ resolver: zodResolver(accountFormSchema)
+ });
+
+ useEffect(() => {
+ onDirtyChange?.(isDirty);
+ return () => onDirtyChange?.(false);
+ }, [isDirty, onDirtyChange]);
+
+ useEffect(() => {
+ if (account && metadata) {
+ reset({
+ accountType: account.accountType,
+ name: account.name,
+ description: account.description ?? "",
+ folderId: account.folderId,
+ templateId: account.templateId,
+ connectionDetails: {
+ ...buildDefaultFieldValues(metadata.connectionFields),
+ ...account.connectionDetails
+ },
+ credentials: buildEditCredentialValues(metadata.credentialFields, account.credentials)
+ });
+ }
+ }, [account, metadata, reset]);
+
+ const onSubmit = (values: TAccountFormValues) => {
+ if (!accountId || !account || !metadata) return;
+
+ if (!areRequiredFieldsFilled(metadata.connectionFields, values.connectionDetails)) {
+ createNotification({ text: "Check connection details fields", type: "error" });
+ return;
+ }
+ if (!areRequiredFieldsFilled(metadata.credentialFields, values.credentials)) {
+ createNotification({ text: "Check credentials fields", type: "error" });
+ return;
+ }
+
+ // Drop unchanged secrets (sentinel) so they're preserved server-side; send the rest
+ const filteredCredentials = filterUnchangedCredentials(values.credentials);
+
+ updateAccount.mutate(
+ {
+ accountId,
+ accountType: values.accountType,
+ name: values.name,
+ description: values.description || null,
+ folderId: values.folderId,
+ templateId: values.templateId,
+ connectionDetails: values.connectionDetails,
+ ...(filteredCredentials ? { credentials: filteredCredentials } : {})
+ },
+ {
+ onSuccess: () => createNotification({ text: "Account updated", type: "success" })
+ }
+ );
+ };
+
+ if (isLoadingAccount) {
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ {SKELETON_ROWS.map((key) => (
+ <Skeleton key={key} className="h-9 w-full" />
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">General</CardTitle>
+ <CardDescription>Name, location, and template for this account.</CardDescription>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ Name<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} isError={!!fieldState.error} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea {...field} rows={2} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="folderId"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ Folder<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full" isError={!!fieldState.error}>
+ <SelectValue placeholder="Select folder" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {folders.map((folder) => (
+ <SelectItem key={folder.id} value={folder.id}>
+ {folder.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="templateId"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ Template<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full" isError={!!fieldState.error}>
+ <SelectValue placeholder="Select template" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {templateOptions.map((tpl) => (
+ <SelectItem key={tpl.id} value={tpl.id}>
+ {tpl.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Connection Details</CardTitle>
+ <CardDescription>How Infisical reaches this account.</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <ConnectionDetailsForm control={control} />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Credentials</CardTitle>
+ <CardDescription>Authentication used to connect to this account.</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <CredentialsForm control={control} />
+ </CardContent>
+ </Card>
+
+ <div aria-hidden className="h-8 shrink-0" />
+ {isDirty && <SheetSaveBar isPending={updateAccount.isPending} onDiscard={() => reset()} />}
+ </form>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRows.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRows.tsx
new file mode 100644
index 0000000000..ebc18fb350
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRows.tsx
@@ -0,0 +1,176 @@
+import { useEffect, useMemo } from "react";
+import { ChevronRight, Folder, FolderOpen } from "lucide-react";
+
+import { HighlightText } from "@app/components/v2/HighlightText";
+import { Badge, TableCell, TableRow } from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import {
+ PamAccountType,
+ TPamFolderWithCount,
+ useListPamAccountsAdmin,
+ usePamAccountTypeMap
+} from "@app/hooks/api/pam";
+
+import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
+import { AccountActionsMenu } from "./AccountActionsMenu";
+import { FolderActionsMenu } from "./FolderActionsMenu";
+
+type DeleteTarget = { accountId: string; accountName: string; accountType: PamAccountType };
+
+type Props = {
+ folder: TPamFolderWithCount;
+ isOpen: boolean;
+ onToggle: () => void;
+ search: string;
+ templateId: string;
+ filterActive: boolean;
+ onOpenAccount: (accountId: string) => void;
+ onConfigureAccount: (accountId: string) => void;
+ onDeleteAccount: (target: DeleteTarget) => void;
+ onFolderDetails: () => void;
+ onFolderConfigure: () => void;
+ onFolderAddAccount: () => void;
+ onFolderDelete: () => void;
+ onResultCount: (folderId: string, count: number) => void;
+};
+
+const SKELETON_KEYS = ["a", "b", "c"];
+
+export const FolderAccountRows = ({
+ folder,
+ isOpen,
+ onToggle,
+ search,
+ templateId,
+ filterActive,
+ onOpenAccount,
+ onConfigureAccount,
+ onDeleteAccount,
+ onFolderDetails,
+ onFolderConfigure,
+ onFolderAddAccount,
+ onFolderDelete,
+ onResultCount
+}: Props) => {
+ const { map } = usePamAccountTypeMap();
+ // Only fetch this folder's accounts once it's open (lazy load per folder)
+ const { data, isLoading } = useListPamAccountsAdmin({ folderId: folder.id }, { enabled: isOpen });
+ const accounts = data ?? [];
+
+ const q = search.trim().toLowerCase();
+ const hasQuery = q.length > 0;
+ const folderNameMatches =
+ hasQuery && `${folder.name} ${folder.description ?? ""}`.toLowerCase().includes(q);
+
+ // Client-side filtering keeps search/template instant once a folder's accounts are loaded
+ const accountsToShow = useMemo(() => {
+ let list = accounts;
+ if (templateId) list = list.filter((a) => a.templateId === templateId);
+ if (hasQuery && !folderNameMatches) {
+ list = list.filter((a) => `${a.name} ${a.description ?? ""}`.toLowerCase().includes(q));
+ }
+ return list;
+ }, [accounts, templateId, q, hasQuery, folderNameMatches]);
+
+ const effectiveCount = folderNameMatches
+ ? Math.max(accountsToShow.length, 1)
+ : accountsToShow.length;
+
+ useEffect(() => {
+ if (isOpen && !isLoading) onResultCount(folder.id, effectiveCount);
+ }, [isOpen, isLoading, effectiveCount, folder.id, onResultCount]);
+
+ // While filtering, hide folders with no name match and no matching accounts
+ if (filterActive && isOpen && !isLoading && !folderNameMatches && accountsToShow.length === 0) {
+ return null;
+ }
+
+ return (
+ <>
+ <TableRow className="cursor-pointer select-none" onClick={onToggle}>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <ChevronRight
+ className={`size-4 shrink-0 text-muted transition-transform ${isOpen ? "rotate-90" : ""}`}
+ />
+ {isOpen ? (
+ <FolderOpen className="size-5 shrink-0 text-product-pam" />
+ ) : (
+ <Folder className="size-5 shrink-0 text-product-pam" />
+ )}
+ <span className="font-medium text-foreground">
+ <HighlightText text={folder.name} highlight={search} />
+ </span>
+ {folder.description && (
+ <span className="text-muted">
+ <HighlightText text={folder.description} highlight={search} />
+ </span>
+ )}
+ </div>
+ </TableCell>
+ <TableCell className="w-20">
+ <div className="flex items-center justify-end gap-1">
+ <FolderActionsMenu
+ folder={folder}
+ onDetails={onFolderDetails}
+ onConfigure={onFolderConfigure}
+ onAddAccount={onFolderAddAccount}
+ onDelete={onFolderDelete}
+ />
+ </div>
+ </TableCell>
+ </TableRow>
+
+ {isOpen && isLoading && (
+ <TableRow>
+ <TableCell colSpan={2}>
+ <div className="flex flex-col gap-2 pl-[26px]">
+ {SKELETON_KEYS.map((key) => (
+ <Skeleton key={key} className="h-8 w-full rounded-md" />
+ ))}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+
+ {isOpen &&
+ !isLoading &&
+ accountsToShow.map((account) => {
+ const accountType = account.accountType as PamAccountType;
+ return (
+ <TableRow
+ key={account.id}
+ className="cursor-pointer"
+ onClick={() => onOpenAccount(account.id)}
+ >
+ <TableCell>
+ <div className="flex items-center gap-2.5 pl-[26px]">
+ <AccountPlatformIcon accountType={accountType} size={20} />
+ <span className="font-medium text-foreground">
+ <HighlightText text={account.name} highlight={search} />
+ </span>
+ <Badge variant="neutral">{map[accountType]?.name ?? account.accountType}</Badge>
+ </div>
+ </TableCell>
+ <TableCell className="w-20">
+ <div className="flex items-center justify-end gap-1">
+ <AccountActionsMenu
+ accountId={account.id}
+ onDetails={() => onOpenAccount(account.id)}
+ onConfigure={() => onConfigureAccount(account.id)}
+ onDelete={() =>
+ onDeleteAccount({
+ accountId: account.id,
+ accountName: account.name,
+ accountType
+ })
+ }
+ />
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderActionsMenu.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderActionsMenu.tsx
new file mode 100644
index 0000000000..1104791cba
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderActionsMenu.tsx
@@ -0,0 +1,91 @@
+import { useState } from "react";
+import { Eye, MoreHorizontal, Plus, Settings, Trash2 } from "lucide-react";
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ IconButton
+} from "@app/components/v3";
+import {
+ PamResourcePermissionActions,
+ TPamFolderWithCount,
+ usePamFolderActions
+} from "@app/hooks/api/pam";
+
+type Props = {
+ folder: TPamFolderWithCount;
+ onDetails: () => void;
+ onConfigure: () => void;
+ onAddAccount: () => void;
+ onDelete: () => void;
+};
+
+export const FolderActionsMenu = ({
+ folder,
+ onDetails,
+ onConfigure,
+ onAddAccount,
+ onDelete
+}: Props) => {
+ // Defer the permission fetch until the menu is first opened to avoid a request per row
+ const [hasOpened, setHasOpened] = useState(false);
+ const { can, isLoading } = usePamFolderActions(folder.id, hasOpened);
+
+ const canRead = can(PamResourcePermissionActions.ReadFolder);
+ const canEdit = can(PamResourcePermissionActions.EditFolder);
+ const canCreateAccounts = can(PamResourcePermissionActions.CreateAccounts);
+ const canDelete = can(PamResourcePermissionActions.DeleteFolder);
+ const hasAnyAction = canRead || canEdit || canCreateAccounts || canDelete;
+
+ return (
+ <DropdownMenu onOpenChange={(open) => open && setHasOpened(true)}>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Folder actions"
+ className="text-muted"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <MoreHorizontal className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
+ {isLoading && <DropdownMenuItem isDisabled>Checking access&hellip;</DropdownMenuItem>}
+ {!isLoading && !hasAnyAction && (
+ <DropdownMenuItem isDisabled>No actions available</DropdownMenuItem>
+ )}
+ {canRead && (
+ <DropdownMenuItem onClick={onDetails}>
+ <Eye />
+ Details
+ </DropdownMenuItem>
+ )}
+ {canEdit && (
+ <DropdownMenuItem onClick={onConfigure}>
+ <Settings />
+ Configure
+ </DropdownMenuItem>
+ )}
+ {canCreateAccounts && (
+ <DropdownMenuItem onClick={onAddAccount}>
+ <Plus />
+ Add Account
+ </DropdownMenuItem>
+ )}
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="danger" onClick={onDelete}>
+ <Trash2 />
+ Delete Folder
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderDetailSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderDetailSheet.tsx
new file mode 100644
index 0000000000..52a36d82dc
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderDetailSheet.tsx
@@ -0,0 +1,467 @@
+import { useEffect, useMemo, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ FolderOpen,
+ MoreHorizontal,
+ Pencil,
+ Settings,
+ SquarePen,
+ Trash2,
+ UserPlus,
+ Users
+} from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Field,
+ FieldContent,
+ FieldError,
+ FieldLabel,
+ IconButton,
+ Input,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ TextArea
+} from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import { useOrganization, useUser } from "@app/context";
+import { useGetOrganizationGroups } from "@app/hooks/api/organization/queries";
+import {
+ PamResourcePermissionActions,
+ TPamFolderWithCount,
+ TPamMember,
+ useListFolderMembers,
+ useListPamResourceRoles,
+ usePamFolderActions,
+ useRemoveFolderGroupMember,
+ useRemoveFolderMember,
+ useUpdatePamFolder
+} from "@app/hooks/api/pam";
+import { useGetOrgUsers } from "@app/hooks/api/users/queries";
+import { PamSheetTab } from "@app/hooks/usePamSheetState";
+
+import { PamMemberKind, PamMembershipScope } from "../../components/memberEnums";
+import {
+ formatDetailDate,
+ isMembershipExpired,
+ MemberExpiry,
+ PamDetailSheet
+} from "../../components/PamDetailSheet";
+import { RemoveMemberConfirm } from "../../components/RemoveMemberConfirm";
+import { SheetSaveBar } from "../../components/SheetSaveBar";
+import { AssignAccessModal, EditMemberTarget } from "./AssignAccessModal";
+
+type Props = {
+ isOpen: boolean;
+ folder?: TPamFolderWithCount;
+ activeTab?: string;
+ onTabChange?: (tab: string) => void;
+ onOpenChange: (open: boolean) => void;
+};
+
+const folderFormSchema = z.object({
+ name: z.string().min(1, "Name is required").max(64),
+ description: z.string().max(256).optional()
+});
+
+type FolderFormData = z.infer<typeof folderFormSchema>;
+
+const GeneralTab = ({
+ folder,
+ onDirtyChange
+}: {
+ folder: TPamFolderWithCount;
+ onDirtyChange?: (isDirty: boolean) => void;
+}) => {
+ const updateFolder = useUpdatePamFolder();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isDirty }
+ } = useForm<FolderFormData>({
+ resolver: zodResolver(folderFormSchema),
+ defaultValues: { name: folder.name, description: folder.description ?? "" }
+ });
+
+ useEffect(() => {
+ onDirtyChange?.(isDirty);
+ return () => onDirtyChange?.(false);
+ }, [isDirty, onDirtyChange]);
+
+ useEffect(() => {
+ reset({ name: folder.name, description: folder.description ?? "" });
+ }, [folder.id, folder.name, folder.description, reset]);
+
+ const onSubmit = (data: FolderFormData) => {
+ updateFolder.mutate(
+ { folderId: folder.id, name: data.name, description: data.description || null },
+ {
+ onSuccess: () => createNotification({ type: "success", text: "Folder updated" })
+ }
+ );
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">General</CardTitle>
+ <CardDescription>Edit the folder name and description.</CardDescription>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ Name<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} isError={!!fieldState.error} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea {...field} rows={3} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </CardContent>
+ </Card>
+
+ <div aria-hidden className="h-8 shrink-0" />
+ {isDirty && <SheetSaveBar isPending={updateFolder.isPending} onDiscard={() => reset()} />}
+ </form>
+ );
+};
+
+type ResolvedMember = {
+ member: TPamMember;
+ displayName: string;
+ subtitle: string;
+ kind: PamMemberKind;
+};
+
+const PermissionsTab = ({ folderId }: { folderId: string }) => {
+ const { currentOrg } = useOrganization();
+ const { user } = useUser();
+ const { data: folderMembers, isLoading } = useListFolderMembers(folderId);
+ const { data: resourceRoles } = useListPamResourceRoles();
+ const { data: orgUsers } = useGetOrgUsers(currentOrg.id);
+ const { data: orgGroups } = useGetOrganizationGroups(currentOrg.id);
+ const groupMap = useMemo(
+ () => new Map((orgGroups ?? []).map((g) => [g.id, g.name] as const)),
+ [orgGroups]
+ );
+
+ const removeUser = useRemoveFolderMember();
+ const removeGroup = useRemoveFolderGroupMember();
+
+ const [isAssignOpen, setIsAssignOpen] = useState(false);
+ const [editTarget, setEditTarget] = useState<EditMemberTarget | null>(null);
+ const [removeTarget, setRemoveTarget] = useState<ResolvedMember | null>(null);
+
+ const existingUserIdSet = useMemo(
+ () =>
+ new Set(
+ (folderMembers?.users ?? [])
+ .filter((m) => m.userId && !isMembershipExpired(m.expiresAt))
+ .map((m) => m.userId) as string[]
+ ),
+ [folderMembers]
+ );
+ const existingGroupIdSet = useMemo(
+ () =>
+ new Set(
+ (folderMembers?.groups ?? [])
+ .filter((m) => m.groupId && !isMembershipExpired(m.expiresAt))
+ .map((m) => m.groupId) as string[]
+ ),
+ [folderMembers]
+ );
+
+ const userMap = useMemo(
+ () =>
+ new Map(
+ (orgUsers ?? []).map((ou) => {
+ const name =
+ [ou.user.firstName, ou.user.lastName].filter(Boolean).join(" ") || ou.user.username;
+ return [
+ ou.user.id,
+ { name, email: ou.user.email ?? ou.inviteEmail ?? ou.user.username }
+ ] as const;
+ })
+ ),
+ [orgUsers]
+ );
+
+ const resolvedMembers = useMemo(() => {
+ const users: ResolvedMember[] = (folderMembers?.users ?? []).map((m) => {
+ const info = m.userId ? userMap.get(m.userId) : undefined;
+ return {
+ member: m,
+ displayName: info?.name ?? m.userId ?? "Unknown",
+ subtitle: info?.email ?? "",
+ kind: PamMemberKind.User
+ };
+ });
+ const groups: ResolvedMember[] = (folderMembers?.groups ?? []).map((m) => ({
+ member: m,
+ displayName:
+ (m.groupId ? groupMap.get(m.groupId) : undefined) ?? m.groupId ?? "Unknown group",
+ subtitle: "Group",
+ kind: PamMemberKind.Group
+ }));
+ return [...users, ...groups];
+ }, [folderMembers, userMap, groupMap]);
+
+ const handleRemove = (rm: ResolvedMember) => {
+ const opts = {
+ onSuccess: () => createNotification({ type: "success", text: "Member removed" })
+ };
+ if (rm.kind === PamMemberKind.User && rm.member.userId) {
+ removeUser.mutate({ folderId, userId: rm.member.userId }, opts);
+ } else if (rm.kind === PamMemberKind.Group && rm.member.groupId) {
+ removeGroup.mutate({ folderId, groupId: rm.member.groupId }, opts);
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <Skeleton className="h-8 w-48" />
+ <Skeleton className="h-32 w-full" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <AssignAccessModal
+ isOpen={isAssignOpen || Boolean(editTarget)}
+ onOpenChange={(open) => {
+ if (!open) {
+ setIsAssignOpen(false);
+ setEditTarget(null);
+ }
+ }}
+ scope={PamMembershipScope.Folder}
+ resourceId={folderId}
+ existingUserIds={existingUserIdSet}
+ existingGroupIds={existingGroupIdSet}
+ editMember={editTarget}
+ />
+ <RemoveMemberConfirm
+ isOpen={Boolean(removeTarget)}
+ onOpenChange={(open) => {
+ if (!open) setRemoveTarget(null);
+ }}
+ memberName={removeTarget?.displayName}
+ onConfirm={() => {
+ if (removeTarget) handleRemove(removeTarget);
+ setRemoveTarget(null);
+ }}
+ />
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Permissions</CardTitle>
+ <CardDescription>
+ Users and groups with access to this folder and its accounts.
+ </CardDescription>
+ <CardAction>
+ <Button size="sm" variant="pam" onClick={() => setIsAssignOpen(true)}>
+ <UserPlus className="mr-1.5 size-4" />
+ Assign Access
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {resolvedMembers.length === 0 ? (
+ <div className="rounded-md border border-border p-8 text-center text-sm text-muted">
+ No members assigned to this folder yet.
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Assignee</TableHead>
+ <TableHead>Role</TableHead>
+ <TableHead>Expiry</TableHead>
+ <TableHead>Source</TableHead>
+ <TableHead className="w-12" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {resolvedMembers.map((rm) => {
+ const roleName =
+ (resourceRoles ?? []).find((r) => r.slug === rm.member.role)?.name ??
+ rm.member.role;
+ const isOwnMembership =
+ rm.kind === PamMemberKind.User && rm.member.userId === user.id;
+
+ return (
+ <TableRow key={rm.member.membershipId} className="[&>td]:h-12">
+ <TableCell>
+ <div className="flex flex-col">
+ <span className="font-medium text-foreground">{rm.displayName}</span>
+ {rm.subtitle && <span className="text-xs text-muted">{rm.subtitle}</span>}
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant="neutral">{roleName}</Badge>
+ </TableCell>
+ <TableCell>
+ <MemberExpiry expiresAt={rm.member.expiresAt} />
+ </TableCell>
+ <TableCell>
+ <span className="flex items-center gap-1.5 text-sm text-muted">
+ <SquarePen className="size-3.5" />
+ Manual
+ </span>
+ </TableCell>
+ <TableCell>
+ {!isOwnMembership && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Member actions"
+ className="text-muted"
+ >
+ <MoreHorizontal className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
+ <DropdownMenuItem
+ onClick={() =>
+ setEditTarget({
+ kind: rm.kind,
+ id:
+ (rm.kind === PamMemberKind.User
+ ? rm.member.userId
+ : rm.member.groupId) ?? "",
+ label: rm.displayName,
+ role: rm.member.role
+ })
+ }
+ >
+ <Pencil />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setRemoveTarget(rm)}
+ >
+ <Trash2 />
+ Remove
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+};
+
+export const FolderDetailSheet = ({
+ isOpen,
+ folder,
+ activeTab,
+ onTabChange,
+ onOpenChange
+}: Props) => {
+ const { can } = usePamFolderActions(folder?.id ?? "", isOpen && Boolean(folder));
+ const canManageMembers = can(PamResourcePermissionActions.ManageMembers);
+ const canEdit = can(PamResourcePermissionActions.EditFolder);
+
+ const [isFormDirty, setIsFormDirty] = useState(false);
+
+ const metadata = folder
+ ? [
+ ...(folder.description ? [{ label: "Description", value: folder.description }] : []),
+ { label: "Accounts", value: String(folder.accountCount) },
+ { label: "Created", value: formatDetailDate(folder.createdAt) }
+ ]
+ : [];
+
+ const tabs = [
+ canManageMembers && {
+ value: PamSheetTab.Permissions,
+ label: "Permissions",
+ icon: <Users className="mr-1.5 size-4" />,
+ content: folder ? <PermissionsTab folderId={folder.id} /> : null
+ },
+ canEdit && {
+ value: PamSheetTab.Configuration,
+ label: "Configuration",
+ icon: <Settings className="mr-1.5 size-4" />,
+ content: folder ? <GeneralTab folder={folder} onDirtyChange={setIsFormDirty} /> : null
+ }
+ ].filter(Boolean) as {
+ value: string;
+ label: string;
+ icon: JSX.Element;
+ content: JSX.Element | null;
+ }[];
+
+ return (
+ <PamDetailSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ title={folder?.name}
+ typeBadge={undefined}
+ activeTab={activeTab}
+ onTabChange={onTabChange}
+ icon={
+ <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
+ <FolderOpen className="size-10 text-product-pam" />
+ </div>
+ }
+ metadata={metadata}
+ tabs={tabs}
+ isDirty={isFormDirty}
+ />
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamPasswordInput.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamPasswordInput.tsx
new file mode 100644
index 0000000000..a4fda5b867
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamPasswordInput.tsx
@@ -0,0 +1,45 @@
+import { Input } from "@app/components/v3/generic/Input";
+import { TextArea } from "@app/components/v3/generic/TextArea";
+import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";
+
+type Props = {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ isError?: boolean;
+ multiline?: boolean;
+};
+
+// Write-only secret input: seeded with the "unchanged" sentinel; focusing clears it to ""
+export const PamPasswordInput = ({ value, onChange, placeholder, isError, multiline }: Props) => {
+ const isUnchanged = value === UNCHANGED_PASSWORD_SENTINEL;
+
+ const handleFocus = () => {
+ if (isUnchanged) onChange("");
+ };
+
+ if (multiline) {
+ return (
+ <TextArea
+ value={isUnchanged ? "" : value}
+ onFocus={handleFocus}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={isUnchanged ? "Unchanged, click to replace" : placeholder}
+ rows={4}
+ className="font-mono text-xs"
+ isError={isError}
+ />
+ );
+ }
+
+ return (
+ <Input
+ type="password"
+ value={value}
+ onFocus={handleFocus}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ isError={isError}
+ />
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
new file mode 100644
index 0000000000..3d17382f49
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
@@ -0,0 +1,131 @@
+import { Control, Controller, ControllerRenderProps, useWatch } from "react-hook-form";
+
+import { Field, FieldContent, FieldError, FieldLabel } from "@app/components/v3/generic/Field";
+import { Input } from "@app/components/v3/generic/Input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3/generic/Select";
+import { Switch } from "@app/components/v3/generic/Switch";
+import { TextArea } from "@app/components/v3/generic/TextArea";
+import { PamFieldWidget, TPamFieldDescriptor } from "@app/hooks/api/pam";
+
+import { TAccountFormValues } from "./accountFormSchema";
+import { PamPasswordInput } from "./PamPasswordInput";
+
+type NamePrefix = "connectionDetails" | "credentials";
+
+type Props = {
+ control: Control<TAccountFormValues>;
+ namePrefix: NamePrefix;
+ fields: TPamFieldDescriptor[];
+};
+
+const RequiredMark = () => <span className="text-product-pam">*</span>;
+
+type FieldProps = {
+ field: ControllerRenderProps<TAccountFormValues>;
+ descriptor: TPamFieldDescriptor;
+ isError: boolean;
+};
+
+const FieldWidget = ({ field, descriptor, isError }: FieldProps) => {
+ if (descriptor.secret) {
+ return (
+ <PamPasswordInput
+ value={(field.value as string) ?? ""}
+ onChange={field.onChange}
+ multiline={descriptor.widget === PamFieldWidget.Textarea}
+ isError={isError}
+ />
+ );
+ }
+
+ if (descriptor.widget === PamFieldWidget.Textarea) {
+ return (
+ <TextArea
+ value={(field.value as string) ?? ""}
+ onChange={field.onChange}
+ rows={4}
+ isError={isError}
+ />
+ );
+ }
+
+ if (descriptor.widget === PamFieldWidget.Select) {
+ return (
+ <Select value={(field.value as string) ?? ""} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full" isError={isError}>
+ <SelectValue placeholder={`Select ${descriptor.label.toLowerCase()}`} />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {(descriptor.options ?? []).map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+ }
+
+ if (descriptor.widget === PamFieldWidget.Number) {
+ return (
+ <Input
+ type="number"
+ value={(field.value as number | string) ?? ""}
+ onChange={(e) => field.onChange(e.target.value === "" ? "" : Number(e.target.value))}
+ isError={isError}
+ />
+ );
+ }
+
+ return (
+ <Input value={(field.value as string) ?? ""} onChange={field.onChange} isError={isError} />
+ );
+};
+
+// Renders connection/credential fields from backend-supplied metadata
+export const PamSchemaFields = ({ control, namePrefix, fields }: Props) => {
+ const values = (useWatch({ control, name: namePrefix }) ?? {}) as Record<string, unknown>;
+ const visibleFields = fields.filter(
+ (field) => !field.showWhen || values[field.showWhen.field] === field.showWhen.equals
+ );
+
+ return (
+ <div className="flex flex-col gap-4">
+ {visibleFields.map((descriptor) => (
+ <Controller
+ key={descriptor.key}
+ control={control}
+ name={`${namePrefix}.${descriptor.key}` as const}
+ render={({ field, fieldState }) =>
+ descriptor.widget === PamFieldWidget.Boolean ? (
+ <Field orientation="horizontal">
+ <FieldLabel>
+ {descriptor.label}
+ {descriptor.required && <RequiredMark />}
+ </FieldLabel>
+ <Switch checked={Boolean(field.value)} onCheckedChange={field.onChange} />
+ </Field>
+ ) : (
+ <Field>
+ <FieldLabel>
+ {descriptor.label}
+ {descriptor.required && <RequiredMark />}
+ </FieldLabel>
+ <FieldContent>
+ <FieldWidget field={field} descriptor={descriptor} isError={!!fieldState.error} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )
+ }
+ />
+ ))}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/accountFormSchema.ts b/frontend/src/pages/pam/PamAccountsPage/components/accountFormSchema.ts
new file mode 100644
index 0000000000..3be941539a
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/accountFormSchema.ts
@@ -0,0 +1,56 @@
+import { z } from "zod";
+
+import { PamAccountType, PamFieldWidget, TPamFieldDescriptor } from "@app/hooks/api/pam";
+import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";
+
+// Shared shape only; per-type connection/credential fields are validated server-side
+export const accountFormSchema = z.object({
+ accountType: z.nativeEnum(PamAccountType),
+ name: z.string().min(1, "Name is required"),
+ description: z.string().optional(),
+ folderId: z.string().min(1, "Folder is required"),
+ templateId: z.string().min(1, "Template is required"),
+ connectionDetails: z.record(z.unknown()),
+ credentials: z.record(z.unknown())
+});
+
+export type TAccountFormValues = z.infer<typeof accountFormSchema>;
+
+const defaultForField = (field: TPamFieldDescriptor): unknown => {
+ if (field.widget === PamFieldWidget.Boolean) return false;
+ if (field.widget === PamFieldWidget.Select) return field.options?.[0]?.value ?? "";
+ return "";
+};
+
+export const buildDefaultFieldValues = (fields: TPamFieldDescriptor[]): Record<string, unknown> =>
+ Object.fromEntries(fields.map((field) => [field.key, defaultForField(field)]));
+
+export const buildEditCredentialValues = (
+ fields: TPamFieldDescriptor[],
+ existing: Record<string, unknown> = {}
+): Record<string, unknown> =>
+ Object.fromEntries(
+ fields.map((field) => {
+ if (field.secret) return [field.key, UNCHANGED_PASSWORD_SENTINEL];
+ return [field.key, existing[field.key] ?? defaultForField(field)];
+ })
+ );
+
+const isFieldVisible = (field: TPamFieldDescriptor, values: Record<string, unknown>) =>
+ !field.showWhen || values[field.showWhen.field] === field.showWhen.equals;
+
+// Lightweight required-field check; the backend performs full schema validation
+export const areRequiredFieldsFilled = (
+ fields: TPamFieldDescriptor[],
+ values: Record<string, unknown>
+): boolean =>
+ fields.every((field) => {
+ if (
+ !field.required ||
+ field.widget === PamFieldWidget.Boolean ||
+ !isFieldVisible(field, values)
+ )
+ return true;
+ const value = values[field.key];
+ return value !== undefined && value !== null && String(value).trim() !== "";
+ });
diff --git a/frontend/src/pages/pam/PamTemplatesPage/PamTemplatesPage.tsx b/frontend/src/pages/pam/PamTemplatesPage/PamTemplatesPage.tsx
new file mode 100644
index 0000000000..ff83a8ac0c
--- /dev/null
+++ b/frontend/src/pages/pam/PamTemplatesPage/PamTemplatesPage.tsx
@@ -0,0 +1,310 @@
+import { useMemo, useState } from "react";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { Eye, Layers, MoreHorizontal, Plus, Search, Settings, Trash2 } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { PageHeader } from "@app/components/v2";
+import { HighlightText } from "@app/components/v2/HighlightText";
+import {
+ Button,
+ Card,
+ CardContent,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import {
+ TPamAccountTemplateWithCount,
+ useDeletePamAccountTemplate,
+ useListPamAccountTemplates,
+ useListPamAccountTypes
+} from "@app/hooks/api/pam";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { PamSheetTab, usePamSheetState } from "@app/hooks/usePamSheetState";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+import { AccountPlatformIcon } from "../PamAccessPage/components/AccountPlatformIcon";
+import { CreateTemplateModal } from "./components/CreateTemplateModal";
+import { DeleteTemplateModal } from "./components/DeleteTemplateModal";
+import { TemplateDetailSheet } from "./components/TemplateDetailSheet";
+
+const TemplateRow = ({
+ template,
+ search,
+ onOpen,
+ onDelete
+}: {
+ template: TPamAccountTemplateWithCount;
+ search: string;
+ onOpen: (tab?: PamSheetTab) => void;
+ onDelete: () => void;
+}) => {
+ return (
+ <TableRow className="cursor-pointer" onClick={() => onOpen()}>
+ <TableCell>
+ <div className="flex items-center gap-2.5">
+ <AccountPlatformIcon accountType={template.type} size={20} />
+ <span className="font-medium text-foreground">
+ <HighlightText text={template.name} highlight={search} />
+ </span>
+ {template.description && (
+ <span className="text-sm text-muted">
+ <HighlightText text={template.description} highlight={search} />
+ </span>
+ )}
+ </div>
+ </TableCell>
+ <TableCell className="w-32 text-muted">
+ {template.accountCount} account{template.accountCount === 1 ? "" : "s"}
+ </TableCell>
+ <TableCell className="w-12">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Template actions"
+ className="text-muted"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <MoreHorizontal className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4} onClick={(e) => e.stopPropagation()}>
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpen();
+ }}
+ >
+ <Eye />
+ Details
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpen(PamSheetTab.Configuration);
+ }}
+ >
+ <Settings />
+ Configure
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="danger"
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete();
+ }}
+ >
+ <Trash2 />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+};
+
+export const PamTemplatesPage = () => {
+ const { t } = useTranslation();
+
+ const [searchInput, setSearchInput] = useState("");
+ const [selectedType, setSelectedType] = useState<string>("");
+
+ const { data: templates, isLoading } = useListPamAccountTemplates();
+ const { data: accountTypes = [] } = useListPamAccountTypes();
+
+ const deleteTemplate = useDeletePamAccountTemplate();
+
+ const { popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([
+ "createTemplate",
+ "deleteTemplate"
+ ] as const);
+
+ const templateSheet = usePamSheetState("templateId");
+
+ // Instant client-side filter: templates by name and description (type via the dropdown only)
+ const filteredTemplates = useMemo(() => {
+ let list = templates ?? [];
+ if (selectedType) list = list.filter((tpl) => tpl.type === selectedType);
+ const q = searchInput.trim().toLowerCase();
+ if (q) {
+ list = list.filter((tpl) => `${tpl.name} ${tpl.description ?? ""}`.toLowerCase().includes(q));
+ }
+ return list;
+ }, [templates, searchInput, selectedType]);
+
+ const hasActiveFilters = searchInput.trim() || selectedType;
+
+ const handleDelete = (templateId: string) => {
+ deleteTemplate.mutate(
+ { templateId },
+ {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Template deleted" });
+ handlePopUpClose("deleteTemplate");
+ }
+ }
+ );
+ };
+
+ return (
+ <>
+ <Helmet>
+ <title>{t("common.head-title", { title: "Account Templates" })}</title>
+ </Helmet>
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.PAM}
+ title="Account Templates"
+ description="Templates define the policies, rotation behavior, and settings for a type of account."
+ />
+
+ <Card className="mt-4">
+ <CardContent className="flex items-center gap-3">
+ <InputGroup className="flex-1">
+ <InputGroupAddon align="inline-start">
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search by name or type..."
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
+ />
+ </InputGroup>
+ <Select
+ value={selectedType}
+ onValueChange={(val) => {
+ setSelectedType(val === "all" ? "" : val);
+ }}
+ >
+ <SelectTrigger>
+ {!selectedType && <Layers className="mr-1.5 size-4 text-muted" />}
+ <SelectValue placeholder="All types" />
+ </SelectTrigger>
+ <SelectContent position="popper" align="end" sideOffset={4}>
+ <SelectItem value="all">All types</SelectItem>
+ {accountTypes.map((meta) => (
+ <SelectItem key={meta.type} value={meta.type}>
+ <img
+ src={`/images/integrations/${meta.icon}`}
+ alt={meta.name}
+ className="mr-1.5 inline-block size-4 rounded-sm"
+ />
+ {meta.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <Button variant="pam" onClick={() => handlePopUpOpen("createTemplate")}>
+ <Plus />
+ Create Template
+ </Button>
+ </CardContent>
+
+ {isLoading && (
+ <CardContent>
+ <div className="flex flex-col gap-3">
+ <Skeleton className="h-10 w-full rounded-md" />
+ <Skeleton className="h-10 w-full rounded-md" />
+ <Skeleton className="h-10 w-full rounded-md" />
+ </div>
+ </CardContent>
+ )}
+
+ {!isLoading && filteredTemplates.length === 0 && (
+ <CardContent>
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>
+ {hasActiveFilters ? "No templates match your filters" : "No templates yet"}
+ </EmptyTitle>
+ <EmptyDescription>
+ {hasActiveFilters
+ ? "Try adjusting your search or type filter."
+ : "Create your first account template to get started."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ )}
+
+ {!isLoading && filteredTemplates.length > 0 && (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Template</TableHead>
+ <TableHead className="w-32">Accounts</TableHead>
+ <TableHead className="w-12" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filteredTemplates.map((template) => (
+ <TemplateRow
+ key={template.id}
+ template={template}
+ search={searchInput}
+ onOpen={(tab) => templateSheet.openSheet(template.id, tab)}
+ onDelete={() => handlePopUpOpen("deleteTemplate", template)}
+ />
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </Card>
+ </div>
+
+ <CreateTemplateModal
+ isOpen={popUp.createTemplate.isOpen}
+ onOpenChange={(open) => {
+ if (!open) handlePopUpClose("createTemplate");
+ }}
+ onCreated={(templateId) => templateSheet.openSheet(templateId)}
+ />
+
+ <TemplateDetailSheet
+ isOpen={templateSheet.isOpen}
+ templateId={templateSheet.selectedId}
+ onOpenChange={(open) => {
+ if (!open) templateSheet.closeSheet();
+ }}
+ />
+
+ <DeleteTemplateModal
+ template={popUp.deleteTemplate.data as TPamAccountTemplateWithCount | undefined}
+ isOpen={popUp.deleteTemplate.isOpen}
+ onOpenChange={(open) => {
+ if (!open) handlePopUpClose("deleteTemplate");
+ }}
+ onConfirm={handleDelete}
+ isDeleting={deleteTemplate.isPending}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/CreateTemplateModal.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/CreateTemplateModal.tsx
new file mode 100644
index 0000000000..cb63574386
--- /dev/null
+++ b/frontend/src/pages/pam/PamTemplatesPage/components/CreateTemplateModal.tsx
@@ -0,0 +1,161 @@
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldError,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ TextArea
+} from "@app/components/v3";
+import {
+ PamAccountType,
+ useCreatePamAccountTemplate,
+ useListPamAccountTypes
+} from "@app/hooks/api/pam";
+import { slugSchema } from "@app/lib/schemas";
+
+const formSchema = z.object({
+ name: slugSchema({ field: "Name" }),
+ type: z.nativeEnum(PamAccountType, { required_error: "Type is required" }),
+ description: z.string().max(256).optional()
+});
+
+type FormData = z.infer<typeof formSchema>;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ onCreated?: (templateId: string) => void;
+};
+
+export const CreateTemplateModal = ({ isOpen, onOpenChange, onCreated }: Props) => {
+ const createTemplate = useCreatePamAccountTemplate();
+ const { data: accountTypes = [] } = useListPamAccountTypes();
+
+ const {
+ register,
+ handleSubmit,
+ setValue,
+ watch,
+ reset,
+ formState: { errors }
+ } = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: "",
+ type: undefined,
+ description: ""
+ }
+ });
+
+ const selectedType = watch("type");
+
+ const onSubmit = (data: FormData) => {
+ createTemplate.mutate(
+ { name: data.name, type: data.type, description: data.description || undefined },
+ {
+ onSuccess: (template) => {
+ createNotification({ type: "success", text: "Template created" });
+ reset();
+ onOpenChange(false);
+ onCreated?.(template.id);
+ }
+ }
+ );
+ };
+
+ return (
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) reset();
+ onOpenChange(open);
+ }}
+ >
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Create Account Template</DialogTitle>
+ </DialogHeader>
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <Field>
+ <FieldLabel htmlFor="template-name">Name</FieldLabel>
+ <FieldContent>
+ <Input
+ id="template-name"
+ placeholder="e.g. production-postgresql"
+ isError={!!errors.name}
+ {...register("name")}
+ />
+ <FieldError>{errors.name?.message}</FieldError>
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Type</FieldLabel>
+ <FieldContent>
+ <Select
+ value={selectedType}
+ onValueChange={(val) =>
+ setValue("type", val as PamAccountType, { shouldValidate: true })
+ }
+ >
+ <SelectTrigger className="w-full" isError={!!errors.type}>
+ <SelectValue placeholder="Select a platform type" />
+ </SelectTrigger>
+ <SelectContent position="popper" sideOffset={4}>
+ {accountTypes.map((meta) => (
+ <SelectItem key={meta.type} value={meta.type}>
+ <img
+ src={`/images/integrations/${meta.icon}`}
+ alt={meta.name}
+ className="mr-1.5 inline-block size-4 rounded-sm"
+ />
+ {meta.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldError>{errors.type?.message}</FieldError>
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="template-description">Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ id="template-description"
+ placeholder="What is this template for?"
+ rows={3}
+ {...register("description")}
+ />
+ </FieldContent>
+ </Field>
+
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="pam" isPending={createTemplate.isPending}>
+ Create Template
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/DeleteTemplateModal.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/DeleteTemplateModal.tsx
new file mode 100644
index 0000000000..5f7ce2a7de
--- /dev/null
+++ b/frontend/src/pages/pam/PamTemplatesPage/components/DeleteTemplateModal.tsx
@@ -0,0 +1,108 @@
+import { useEffect, useState } from "react";
+
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel,
+ Input
+} from "@app/components/v3";
+import { TPamAccountTemplateWithCount } from "@app/hooks/api/pam";
+
+type Props = {
+ template?: TPamAccountTemplateWithCount;
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ onConfirm: (templateId: string) => void;
+ isDeleting: boolean;
+};
+
+export const DeleteTemplateModal = ({
+ template,
+ isOpen,
+ onOpenChange,
+ onConfirm,
+ isDeleting
+}: Props) => {
+ const templateName = template?.name ?? "";
+ const accountCount = template?.accountCount ?? 0;
+ const hasAccounts = accountCount > 0;
+
+ const [confirmInput, setConfirmInput] = useState("");
+ const canDelete = confirmInput === templateName && templateName.length > 0;
+
+ useEffect(() => {
+ setConfirmInput("");
+ }, [isOpen]);
+
+ const renderBody = () => {
+ if (hasAccounts) {
+ return (
+ <div className="grid gap-4">
+ <p className="text-sm text-muted">
+ <span className="font-medium text-foreground">{templateName}</span> is used by{" "}
+ {accountCount} account{accountCount === 1 ? "" : "s"}. Move or delete{" "}
+ {accountCount === 1 ? "it" : "them"} before this template can be deleted.
+ </p>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Close
+ </Button>
+ </DialogFooter>
+ </div>
+ );
+ }
+
+ return (
+ <form
+ className="grid gap-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (canDelete && !isDeleting && template) onConfirm(template.id);
+ }}
+ >
+ <p className="text-sm text-muted">
+ Are you sure you want to delete{" "}
+ <span className="font-medium text-foreground">{templateName}</span>? This action cannot be
+ undone.
+ </p>
+ <Field>
+ <FieldLabel>
+ Type <span className="font-medium text-foreground">{templateName}</span> to confirm
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ value={confirmInput}
+ onChange={(e) => setConfirmInput(e.target.value)}
+ placeholder={templateName}
+ />
+ </FieldContent>
+ </Field>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="danger" isPending={isDeleting} isDisabled={!canDelete}>
+ Delete
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Delete Template</DialogTitle>
+ </DialogHeader>
+ {renderBody()}
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
new file mode 100644
index 0000000000..c81b237ee2
--- /dev/null
+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx
@@ -0,0 +1,410 @@
+import { useEffect, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { MoreHorizontal, Settings, ShieldCheck, Trash2 } from "lucide-react";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldTitle,
+ IconButton,
+ Input,
+ Switch,
+ TextArea
+} from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import {
+ PamAccountType,
+ useDeletePamAccountTemplate,
+ useGetPamAccountTemplate,
+ usePamAccountTypeMap,
+ useUpdatePamAccountTemplate
+} from "@app/hooks/api/pam";
+import { PamSheetTab, usePamSheetState } from "@app/hooks/usePamSheetState";
+
+import { formatDetailDate, PamDetailSheet } from "../../components/PamDetailSheet";
+import { SheetSaveBar } from "../../components/SheetSaveBar";
+import { AccountPlatformIcon } from "../../PamAccessPage/components/AccountPlatformIcon";
+import { DeleteTemplateModal } from "./DeleteTemplateModal";
+
+const configSchema = z.object({
+ name: z.string().min(1, "Name is required").max(64),
+ description: z.string().max(256).optional()
+});
+
+type ConfigForm = z.infer<typeof configSchema>;
+
+const accessPolicySchema = z.object({
+ requireReason: z.boolean(),
+ requireMfa: z.boolean(),
+ maxSessionDurationSeconds: z
+ .number({ invalid_type_error: "Must be a number" })
+ .int()
+ .min(60, "Minimum 60 seconds")
+ .max(86400, "Maximum 24 hours")
+ .optional()
+ .nullable()
+});
+
+type AccessPolicyForm = z.infer<typeof accessPolicySchema>;
+
+type Props = {
+ isOpen: boolean;
+ templateId?: string;
+ onOpenChange: (open: boolean) => void;
+};
+
+const ConfigurationTab = ({
+ templateId,
+ onDirtyChange
+}: {
+ templateId: string;
+ onDirtyChange?: (isDirty: boolean) => void;
+}) => {
+ const { data: template, isLoading } = useGetPamAccountTemplate(templateId);
+ const updateTemplate = useUpdatePamAccountTemplate();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isDirty }
+ } = useForm<ConfigForm>({
+ resolver: zodResolver(configSchema),
+ defaultValues: { name: "", description: "" }
+ });
+
+ useEffect(() => {
+ onDirtyChange?.(isDirty);
+ return () => onDirtyChange?.(false);
+ }, [isDirty, onDirtyChange]);
+
+ useEffect(() => {
+ if (template) {
+ reset({ name: template.name, description: template.description ?? "" });
+ }
+ }, [template, reset]);
+
+ const onSubmit = (data: ConfigForm) => {
+ updateTemplate.mutate(
+ { templateId, name: data.name, description: data.description || null },
+ {
+ onSuccess: () => createNotification({ type: "success", text: "Template updated" })
+ }
+ );
+ };
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <Skeleton className="h-8 w-48" />
+ <Skeleton className="h-16 w-full" />
+ </div>
+ );
+ }
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Configuration</CardTitle>
+ <CardDescription>Edit the template name and description.</CardDescription>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ Name<span className="text-product-pam">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input {...field} isError={!!fieldState.error} />
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea {...field} rows={3} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </CardContent>
+ </Card>
+
+ <div aria-hidden className="h-8 shrink-0" />
+ {isDirty && <SheetSaveBar isPending={updateTemplate.isPending} onDiscard={() => reset()} />}
+ </form>
+ );
+};
+
+const AccessPolicyTab = ({
+ templateId,
+ onDirtyChange
+}: {
+ templateId: string;
+ onDirtyChange?: (isDirty: boolean) => void;
+}) => {
+ const { data: template, isLoading } = useGetPamAccountTemplate(templateId);
+ const updateTemplate = useUpdatePamAccountTemplate();
+
+ const {
+ register,
+ control,
+ handleSubmit,
+ reset,
+ formState: { errors, isDirty }
+ } = useForm<AccessPolicyForm>({
+ resolver: zodResolver(accessPolicySchema),
+ defaultValues: {
+ requireReason: false,
+ requireMfa: false,
+ maxSessionDurationSeconds: null
+ }
+ });
+
+ useEffect(() => {
+ onDirtyChange?.(isDirty);
+ return () => onDirtyChange?.(false);
+ }, [isDirty, onDirtyChange]);
+
+ useEffect(() => {
+ if (template) {
+ const policy = (template.accessPolicy ?? {}) as Record<string, unknown>;
+ reset({
+ requireReason: Boolean(policy.requireReason),
+ requireMfa: Boolean(policy.requireMfa),
+ maxSessionDurationSeconds:
+ typeof policy.maxSessionDurationSeconds === "number"
+ ? policy.maxSessionDurationSeconds
+ : null
+ });
+ }
+ }, [template, reset]);
+
+ const onSubmit = (data: AccessPolicyForm) => {
+ updateTemplate.mutate(
+ {
+ templateId,
+ accessPolicy: {
+ requireReason: data.requireReason,
+ requireMfa: data.requireMfa,
+ maxSessionDurationSeconds: data.maxSessionDurationSeconds ?? undefined
+ }
+ },
+ {
+ onSuccess: () => createNotification({ type: "success", text: "Template updated" })
+ }
+ );
+ };
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ <Skeleton className="h-8 w-48" />
+ <Skeleton className="h-16 w-full" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ );
+ }
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle className="text-base">Access Policy</CardTitle>
+ <CardDescription>
+ Governance rules applied to all accounts using this template.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-6">
+ <Field>
+ <FieldLabel>Max session duration (seconds)</FieldLabel>
+ <FieldContent>
+ <Input
+ type="number"
+ placeholder="e.g. 3600"
+ isError={!!errors.maxSessionDurationSeconds}
+ {...register("maxSessionDurationSeconds", {
+ setValueAs: (v: string) => {
+ if (v === "" || v === null || v === undefined) return null;
+ const n = Number(v);
+ return Number.isNaN(n) ? null : n;
+ }
+ })}
+ />
+ <FieldDescription>Between 60 and 86400. Leave empty for no limit.</FieldDescription>
+ <FieldError>{errors.maxSessionDurationSeconds?.message}</FieldError>
+ </FieldContent>
+ </Field>
+
+ <Field orientation="horizontal" className="items-center!">
+ <FieldContent>
+ <FieldTitle>Require reason</FieldTitle>
+ <FieldDescription>Users must provide a reason before accessing.</FieldDescription>
+ </FieldContent>
+ <Controller
+ name="requireReason"
+ control={control}
+ render={({ field }) => (
+ <Switch checked={field.value} variant="pam" onCheckedChange={field.onChange} />
+ )}
+ />
+ </Field>
+
+ <Field orientation="horizontal" className="items-center!">
+ <FieldContent>
+ <FieldTitle>Require MFA</FieldTitle>
+ <FieldDescription>
+ Users must re-authenticate with MFA before accessing.
+ </FieldDescription>
+ </FieldContent>
+ <Controller
+ name="requireMfa"
+ control={control}
+ render={({ field }) => (
+ <Switch checked={field.value} variant="pam" onCheckedChange={field.onChange} />
+ )}
+ />
+ </Field>
+ </CardContent>
+ </Card>
+
+ <div aria-hidden className="h-8 shrink-0" />
+ {isDirty && <SheetSaveBar isPending={updateTemplate.isPending} onDiscard={() => reset()} />}
+ </form>
+ );
+};
+
+export const TemplateDetailSheet = ({ isOpen, templateId, onOpenChange }: Props) => {
+ const { data: template, isLoading } = useGetPamAccountTemplate(isOpen ? templateId : undefined);
+ const { tab, setTab } = usePamSheetState("templateId");
+ const deleteTemplate = useDeletePamAccountTemplate();
+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);
+ const [isFormDirty, setIsFormDirty] = useState(false);
+
+ const { map: accountTypeMap } = usePamAccountTypeMap();
+ const accountType = template?.type as PamAccountType | undefined;
+ const typeInfo = accountType ? accountTypeMap[accountType] : undefined;
+
+ const handleDelete = (id: string) => {
+ deleteTemplate.mutate(
+ { templateId: id },
+ {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Template deleted" });
+ setIsDeleteOpen(false);
+ onOpenChange(false);
+ }
+ }
+ );
+ };
+
+ const metadata = template
+ ? [
+ ...(template.description ? [{ label: "Description", value: template.description }] : []),
+ {
+ label: "Accounts",
+ value: `${template.accountCount ?? 0} using this template`
+ },
+ { label: "Created", value: formatDetailDate(template.createdAt) }
+ ]
+ : [];
+
+ const actions = template ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="sm" aria-label="Template actions" className="text-muted">
+ <MoreHorizontal className="size-4" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
+ <DropdownMenuItem onClick={() => setTab(PamSheetTab.Configuration)}>
+ <Settings />
+ Configure
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="danger" onClick={() => setIsDeleteOpen(true)}>
+ <Trash2 />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : undefined;
+
+ return (
+ <>
+ <PamDetailSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ isLoading={isLoading}
+ accountType={accountType}
+ title={template?.name}
+ typeBadge={typeInfo?.name}
+ activeTab={tab}
+ onTabChange={setTab}
+ actions={actions}
+ icon={
+ accountType ? (
+ <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
+ <AccountPlatformIcon accountType={accountType} size={40} />
+ </div>
+ ) : undefined
+ }
+ metadata={metadata}
+ tabs={[
+ {
+ value: PamSheetTab.AccessPolicy,
+ label: "Access Policy",
+ icon: <ShieldCheck className="mr-1.5 size-4" />,
+ content: templateId ? (
+ <AccessPolicyTab templateId={templateId} onDirtyChange={setIsFormDirty} />
+ ) : null
+ },
+ {
+ value: PamSheetTab.Configuration,
+ label: "Configuration",
+ icon: <Settings className="mr-1.5 size-4" />,
+ content: templateId ? (
+ <ConfigurationTab templateId={templateId} onDirtyChange={setIsFormDirty} />
+ ) : null
+ }
+ ]}
+ isDirty={isFormDirty}
+ />
+
+ <DeleteTemplateModal
+ template={template}
+ isOpen={isDeleteOpen}
+ onOpenChange={setIsDeleteOpen}
+ onConfirm={handleDelete}
+ isDeleting={deleteTemplate.isPending}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/components/PamDetailSheet.tsx b/frontend/src/pages/pam/components/PamDetailSheet.tsx
new file mode 100644
index 0000000000..e41c73e3ec
--- /dev/null
+++ b/frontend/src/pages/pam/components/PamDetailSheet.tsx
@@ -0,0 +1,251 @@
+import { type ReactNode, useState } from "react";
+import { format, formatDistanceToNow } from "date-fns";
+import { AlertTriangle, Clock } from "lucide-react";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+ Badge,
+ Sheet,
+ SheetContent,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { Skeleton } from "@app/components/v3/generic/Skeleton";
+import { PamAccountType } from "@app/hooks/api/pam";
+
+import { AccountPlatformIcon } from "../PamAccessPage/components/AccountPlatformIcon";
+
+type MetadataField = {
+ label: string;
+ value: ReactNode;
+};
+
+export type PamDetailSheetTab = {
+ value: string;
+ label: string;
+ icon?: ReactNode;
+ content: ReactNode;
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ isLoading?: boolean;
+ icon?: ReactNode;
+ accountType?: PamAccountType;
+ title?: string;
+ subtitle?: ReactNode;
+ typeBadge?: string;
+ metadata?: MetadataField[];
+ actions?: ReactNode;
+ tabs?: PamDetailSheetTab[];
+ activeTab?: string;
+ onTabChange?: (tab: string) => void;
+ isDirty?: boolean;
+ children?: ReactNode;
+};
+
+const TabbedContent = ({
+ tabs,
+ activeTab,
+ onTabChange
+}: {
+ tabs: PamDetailSheetTab[];
+ activeTab?: string;
+ onTabChange?: (tab: string) => void;
+}) => {
+ const defaultTab = tabs[0]?.value;
+ const showTabBar = tabs.length > 1;
+
+ return (
+ <Tabs
+ {...(onTabChange
+ ? { value: activeTab ?? defaultTab, onValueChange: onTabChange }
+ : { defaultValue: defaultTab })}
+ className={`flex min-h-full flex-col ${showTabBar ? "" : "pt-3"}`}
+ >
+ {showTabBar && (
+ <TabsList variant="pam" className="sticky top-0 z-10 shrink-0 bg-popover">
+ {tabs.map((tab) => (
+ <TabsTrigger key={tab.value} value={tab.value}>
+ {tab.icon}
+ {tab.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ )}
+ {tabs.map((tab) => (
+ <TabsContent key={tab.value} value={tab.value} className="m-0 flex flex-1 flex-col">
+ {tab.content}
+ </TabsContent>
+ ))}
+ </Tabs>
+ );
+};
+
+export const PamDetailSheet = ({
+ isOpen,
+ onOpenChange,
+ isLoading,
+ icon,
+ accountType,
+ title,
+ subtitle,
+ typeBadge,
+ metadata = [],
+ actions,
+ tabs,
+ activeTab,
+ onTabChange,
+ isDirty,
+ children
+}: Props) => {
+ const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);
+
+ // Warn before closing while a tab form has unsaved changes
+ const handleOpenChange = (open: boolean) => {
+ if (!open && isDirty) {
+ setConfirmDiscardOpen(true);
+ return;
+ }
+ onOpenChange(open);
+ };
+
+ return (
+ <>
+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>
+ <SheetContent className="w-full !max-w-5xl overflow-y-auto">
+ {isLoading ? (
+ <div className="flex gap-6 p-6">
+ <div className="flex w-80 shrink-0 flex-col gap-4">
+ <Skeleton className="size-16 rounded-lg" />
+ <Skeleton className="h-6 w-48" />
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="mt-4 h-4 w-24" />
+ <Skeleton className="h-4 w-48" />
+ <Skeleton className="mt-2 h-4 w-24" />
+ <Skeleton className="h-4 w-36" />
+ </div>
+ <div className="flex-1">
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="mt-4 h-64 w-full" />
+ </div>
+ </div>
+ ) : (
+ <div className="flex h-full">
+ <div className="flex w-80 shrink-0 flex-col border-r border-border p-6">
+ <div className="flex items-start justify-between">
+ {icon ||
+ (accountType && (
+ <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">
+ <AccountPlatformIcon accountType={accountType} size={40} />
+ </div>
+ ))}
+ {actions}
+ </div>
+
+ {title && <h2 className="text-lg font-semibold text-foreground">{title}</h2>}
+ {subtitle && <p className="mt-0.5 text-sm text-muted">{subtitle}</p>}
+ {typeBadge && (
+ <div className="mt-2">
+ <Badge variant="neutral">{typeBadge}</Badge>
+ </div>
+ )}
+
+ {metadata.length > 0 && (
+ <div className="mt-6 flex flex-col gap-4 border-t border-border pt-4">
+ {metadata.map((field) => (
+ <div key={field.label}>
+ <p className="text-xs font-medium text-muted">{field.label}</p>
+ <div className="mt-1 text-sm text-foreground">{field.value}</div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div className="flex flex-1 flex-col overflow-y-auto">
+ {tabs ? (
+ <TabbedContent tabs={tabs} activeTab={activeTab} onTabChange={onTabChange} />
+ ) : (
+ children
+ )}
+ </div>
+ </div>
+ )}
+ </SheetContent>
+ </Sheet>
+
+ <AlertDialog open={confirmDiscardOpen} onOpenChange={setConfirmDiscardOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <AlertTriangle />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Discard changes?</AlertDialogTitle>
+ <AlertDialogDescription>Your unsaved changes will be lost.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep Editing</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ onClick={() => {
+ setConfirmDiscardOpen(false);
+ onOpenChange(false);
+ }}
+ >
+ Discard
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+};
+
+export const formatDetailDate = (dateStr: string) => format(new Date(dateStr), "MMMM do, yyyy");
+
+export const formatRelativeExpiry = (dateStr: string) =>
+ formatDistanceToNow(new Date(dateStr), { addSuffix: true });
+
+const ONE_DAY_MS = 24 * 60 * 60 * 1000;
+
+// A temporary membership whose end time has passed grants no access and can be re-granted
+export const isMembershipExpired = (expiresAt?: string | null) =>
+ Boolean(expiresAt) && new Date(expiresAt as string).getTime() <= Date.now();
+
+// Expiry cell: danger once elapsed, warning under a day left, dash when permanent
+export const MemberExpiry = ({ expiresAt }: { expiresAt?: string | null }) => {
+ if (!expiresAt) return <span className="text-sm text-muted">&mdash;</span>;
+
+ const remainingMs = new Date(expiresAt).getTime() - Date.now();
+ const isExpired = remainingMs <= 0;
+ let variant: "danger" | "warning" | "neutral" = "neutral";
+ if (isExpired) variant = "danger";
+ else if (remainingMs < ONE_DAY_MS) variant = "warning";
+
+ return (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant={variant}>
+ <Clock className="mr-1 size-3" />
+ {isExpired ? "Expired" : formatRelativeExpiry(expiresAt)}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{format(new Date(expiresAt), "MMMM do, yyyy 'at' h:mm a")}</TooltipContent>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/pages/pam/components/RemoveMemberConfirm.tsx b/frontend/src/pages/pam/components/RemoveMemberConfirm.tsx
new file mode 100644
index 0000000000..8840e6b906
--- /dev/null
+++ b/frontend/src/pages/pam/components/RemoveMemberConfirm.tsx
@@ -0,0 +1,49 @@
+import { AlertTriangle } from "lucide-react";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle
+} from "@app/components/v3";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ memberName?: string;
+ onConfirm: () => void;
+};
+
+export const RemoveMemberConfirm = ({ isOpen, onOpenChange, memberName, onConfirm }: Props) => (
+ <AlertDialog open={isOpen} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <AlertTriangle />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Remove access?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {memberName ? (
+ <>
+ <span className="font-medium text-foreground">{memberName}</span> will lose this
+ access.
+ </>
+ ) : (
+ "This member will lose this access."
+ )}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" onClick={onConfirm}>
+ Remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+);
diff --git a/frontend/src/pages/pam/components/SheetSaveBar.tsx b/frontend/src/pages/pam/components/SheetSaveBar.tsx
new file mode 100644
index 0000000000..4fa65079e3
--- /dev/null
+++ b/frontend/src/pages/pam/components/SheetSaveBar.tsx
@@ -0,0 +1,17 @@
+import { Button } from "@app/components/v3";
+
+type Props = {
+ isPending?: boolean;
+ onDiscard: () => void;
+};
+
+export const SheetSaveBar = ({ isPending, onDiscard }: Props) => (
+ <div className="sticky bottom-0 -mx-4 mt-auto -mb-4 flex items-center justify-end gap-2 border-t border-border bg-popover px-4 py-3">
+ <Button type="button" variant="ghost" onClick={onDiscard}>
+ Discard
+ </Button>
+ <Button type="submit" variant="pam" isPending={isPending}>
+ Save Changes
+ </Button>
+ </div>
+);
diff --git a/frontend/src/pages/pam/components/memberEnums.ts b/frontend/src/pages/pam/components/memberEnums.ts
new file mode 100644
index 0000000000..30251d96d0
--- /dev/null
+++ b/frontend/src/pages/pam/components/memberEnums.ts
@@ -0,0 +1,14 @@
+export enum PamMemberKind {
+ User = "user",
+ Group = "group"
+}
+
+export enum PamMemberSource {
+ Direct = "direct",
+ Inherited = "inherited"
+}
+
+export enum PamMembershipScope {
+ Account = "account",
+ Folder = "folder"
+}