Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: revamp pam insights based on review feedback
bernie-g33b95c85808f
diff --git a/backend/src/ee/routes/v1/pam-insights-router.ts b/backend/src/ee/routes/v1/pam-insights-router.tsindex c5bb21f65b..29dd6e00f3 100644--- a/backend/src/ee/routes/v1/pam-insights-router.ts+++ b/backend/src/ee/routes/v1/pam-insights-router.ts@@ -23,6 +23,16 @@ export const registerPamInsightsRouter = async (server: FastifyZodProvider) => {resourcesWithRotation: z.number(),totalAccounts: z.number(),failedRotations: z.number(),+ failedRotationAccounts: z.array(+ z.object({+ accountId: z.string(),+ accountName: z.string(),+ resourceId: z.string(),+ resourceName: z.string(),+ resourceType: z.string(),+ lastRotatedAt: z.date().nullable()+ })+ ),activeSessions: z.number(),resourceTypeCount: z.number()})@@ -147,19 +157,22 @@ export const registerPamInsightsRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",- url: "/upcoming-rotations",+ url: "/rotation-calendar",config: { rateLimit: readLimit },schema: {- operationId: "getPamInsightsUpcomingRotations",- description: "Get accounts with a configured rotation schedule, ordered by next rotation time (capped at 100)",+ operationId: "getPamInsightsRotationCalendar",+ description: "Get rotation events for a calendar month, expanded across the visible grid",security: [{ bearerAuth: [] }],querystring: z.object({- projectId: z.string().trim()+ projectId: z.string().trim(),+ month: z.coerce.number().int().min(1).max(12),+ year: z.coerce.number().int().min(1970).max(9999)}),response: {200: z.object({rotations: z.array(z.object({+ id: z.string(),accountId: z.string(),accountName: z.string(),resourceId: z.string(),@@ -168,18 +181,20 @@ export const registerPamInsightsRouter = async (server: FastifyZodProvider) => {intervalSeconds: z.number(),nextRotationAt: z.date()})- ),- totalScheduled: z.number()+ )})}},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const { projectId } = req.query;- const result = await server.services.pamInsights.getUpcomingRotations(projectId, req.permission);+ const { projectId, month, year } = req.query;+ const result = await server.services.pamInsights.getRotationCalendar(projectId, month, year, req.permission);await server.services.auditLog.createAuditLog({projectId,- event: { type: EventType.VIEW_INSIGHTS_PAM_UPCOMING_ROTATIONS, metadata: { projectId } },+ event: {+ type: EventType.VIEW_INSIGHTS_PAM_ROTATION_CALENDAR,+ metadata: { projectId, month, year }+ },...req.auditLogInfo});return result;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 8634aedb7f..5004f90296 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -613,7 +613,7 @@ export enum EventType {VIEW_INSIGHTS_PAM_SESSION_ACTIVITY = "view-insights-pam-session-activity",VIEW_INSIGHTS_PAM_TOP_ACTORS = "view-insights-pam-top-actors",VIEW_INSIGHTS_PAM_RESOURCE_BREAKDOWN = "view-insights-pam-resource-breakdown",- VIEW_INSIGHTS_PAM_UPCOMING_ROTATIONS = "view-insights-pam-upcoming-rotations",+ VIEW_INSIGHTS_PAM_ROTATION_CALENDAR = "view-insights-pam-rotation-calendar",PAM_SESSION_CREDENTIALS_GET = "pam-session-credentials-get",PAM_SESSION_START = "pam-session-start",@@ -4817,10 +4817,12 @@ interface ViewPamInsightsResourceBreakdownEvent {};}-interface ViewPamInsightsUpcomingRotationsEvent {- type: EventType.VIEW_INSIGHTS_PAM_UPCOMING_ROTATIONS;+interface ViewPamInsightsRotationCalendarEvent {+ type: EventType.VIEW_INSIGHTS_PAM_ROTATION_CALENDAR;metadata: {projectId: string;+ month: number;+ year: number;};}@@ -6641,7 +6643,7 @@ export type Event =| ViewPamInsightsSessionActivityEvent| ViewPamInsightsTopActorsEvent| ViewPamInsightsResourceBreakdownEvent- | ViewPamInsightsUpcomingRotationsEvent+ | ViewPamInsightsRotationCalendarEvent| ProjectRoleCreateEvent| ProjectRoleUpdateEvent| ProjectRoleDeleteEventdiff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.tsindex bca7b64da5..8cccec515c 100644--- a/backend/src/ee/services/pam-account/pam-account-dal.ts+++ b/backend/src/ee/services/pam-account/pam-account-dal.ts@@ -303,6 +303,45 @@ export const pamAccountDALFactory = (db: TDbClient) => {return Number((result as { count?: string | number })?.count ?? 0);};+ const findFailedRotationsByProject = async (+ projectId: string,+ limit: number,+ tx?: Knex+ ): Promise<+ {+ id: string;+ name: string;+ resourceId: string;+ resourceName: string;+ resourceType: string;+ lastRotatedAt: Date | null;+ }[]+ > => {+ const rows = await (tx || db.replicaNode())(TableName.PamAccount)+ .innerJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)+ .select(+ `${TableName.PamAccount}.id as id`,+ `${TableName.PamAccount}.name as name`,+ `${TableName.PamAccount}.resourceId as resourceId`,+ `${TableName.PamAccount}.lastRotatedAt as lastRotatedAt`,+ `${TableName.PamResource}.name as resourceName`,+ `${TableName.PamResource}.resourceType as resourceType`+ )+ .where(`${TableName.PamAccount}.projectId`, projectId)+ .where(`${TableName.PamAccount}.rotationStatus`, "failed")+ .orderBy(`${TableName.PamAccount}.lastRotatedAt`, "desc")+ .limit(limit);++ return rows as {+ id: string;+ name: string;+ resourceId: string;+ resourceName: string;+ resourceType: string;+ lastRotatedAt: Date | null;+ }[];+ };+const countByProjectGroupedByResourceType = async (projectId: string,tx?: Knex@@ -370,6 +409,7 @@ export const pamAccountDALFactory = (db: TDbClient) => {findRotationCandidatesByProject,countByProject,countFailedRotationsByProject,+ findFailedRotationsByProject,countByProjectGroupedByResourceType};};diff --git a/backend/src/ee/services/pam-insights/pam-insights-service.ts b/backend/src/ee/services/pam-insights/pam-insights-service.tsindex 2d4f25e762..2f78b785da 100644--- a/backend/src/ee/services/pam-insights/pam-insights-service.ts+++ b/backend/src/ee/services/pam-insights/pam-insights-service.ts@@ -18,7 +18,7 @@ import { OrgServiceActor } from "@app/lib/types";const SESSION_ACTIVITY_DAYS = 30;const TOP_ACTORS_DAYS = 30;const TOP_ACTORS_LIMIT = 10;-const UPCOMING_ROTATIONS_LIMIT = 100;+const FAILED_ROTATIONS_LIMIT = 25;type TPamInsightsServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;@@ -31,6 +31,7 @@ type TPamInsightsServiceFactoryDep = {TPamAccountDALFactory,| "countByProject"| "countFailedRotationsByProject"+ | "findFailedRotationsByProject"| "countByProjectGroupedByResourceType"| "findRotationCandidatesByProject">;@@ -87,6 +88,7 @@ export const pamInsightsServiceFactory = ({resourcesWithRotation,totalAccounts,failedRotations,+ failedRotationAccounts,activeSessions,resourceTypeCount] = await Promise.all([@@ -94,6 +96,7 @@ export const pamInsightsServiceFactory = ({pamResourceDAL.countWithRotationByProject(projectId),pamAccountDAL.countByProject(projectId),pamAccountDAL.countFailedRotationsByProject(projectId),+ pamAccountDAL.findFailedRotationsByProject(projectId, FAILED_ROTATIONS_LIMIT),pamSessionDAL.countActiveByProject(projectId),pamResourceDAL.countByProjectGroupedByType(projectId)]);@@ -103,6 +106,14 @@ export const pamInsightsServiceFactory = ({resourcesWithRotation,totalAccounts,failedRotations,+ failedRotationAccounts: failedRotationAccounts.map((a) => ({+ accountId: a.id,+ accountName: a.name,+ resourceId: a.resourceId,+ resourceName: a.resourceName,+ resourceType: a.resourceType,+ lastRotatedAt: a.lastRotatedAt+ })),activeSessions,resourceTypeCount: resourceTypeCount.length};@@ -191,20 +202,30 @@ export const pamInsightsServiceFactory = ({});};- const getUpcomingRotations = async (projectId: string, actor: OrgServiceActor) => {+ const getRotationCalendar = async (projectId: string, month: number, year: number, actor: OrgServiceActor) => {await checkPamInsightsPermission(permissionService, projectId, actor);return withCache({keyStore,- key: KeyStorePrefixes.InsightsCache(projectId, "pam:upcoming-rotations"),+ key: KeyStorePrefixes.InsightsCache(projectId, `pam:rotation-calendar:${year}-${month}`),ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,fetcher: async () => {+ // Build the visible calendar grid range: from the Monday on/before the 1st through+ // the Sunday on/after the last day of the month, mirroring how the frontend renders.+ const monthStart = new Date(Date.UTC(year, month - 1, 1));+ const monthEnd = new Date(Date.UTC(year, month, 0, 23, 59, 59, 999));+ // weekday: 0=Sun..6=Sat. For Monday-start weeks, offset = (day + 6) % 7+ const startOffset = (monthStart.getUTCDay() + 6) % 7;+ const endOffset = 6 - ((monthEnd.getUTCDay() + 6) % 7);+ const rangeStart = new Date(monthStart.getTime() - startOffset * 24 * 60 * 60 * 1000);+ const rangeEnd = new Date(monthEnd.getTime() + endOffset * 24 * 60 * 60 * 1000);+const candidates = await pamAccountDAL.findRotationCandidatesByProject(projectId);- if (!candidates.length) return { rotations: [], totalScheduled: 0 };+ if (!candidates.length) return { rotations: [] };const resourceIds = [...new Set(candidates.map((c) => c.resourceId))];const allRules = await pamResourceRotationRulesDAL.findByResourceIds(resourceIds);- if (!allRules.length) return { rotations: [], totalScheduled: 0 };+ if (!allRules.length) return { rotations: [] };const rulesByResource: Record<string, typeof allRules> = {};for (const rule of allRules) {@@ -212,9 +233,8 @@ export const pamInsightsServiceFactory = ({rulesByResource[rule.resourceId].push(rule);}- const now = Date.now();-- type TUpcomingRotation = {+ type TCalendarRotationEvent = {+ id: string;accountId: string;accountName: string;resourceId: string;@@ -224,9 +244,11 @@ export const pamInsightsServiceFactory = ({nextRotationAt: Date;};- // Sort by raw nextRotationMs so the most-overdue rotations stay at the top- // even after clamping the displayed timestamp to "now" for past-due entries.- const candidatesWithRotation: { row: TUpcomingRotation; nextRotationMs: number }[] = [];+ const events: TCalendarRotationEvent[] = [];+ const rangeStartMs = rangeStart.getTime();+ const rangeEndMs = rangeEnd.getTime();+ const MAX_EVENTS_PER_ACCOUNT = 100;+for (const candidate of candidates) {const rules = rulesByResource[candidate.resourceId];// eslint-disable-next-line no-continue@@ -236,31 +258,42 @@ export const pamInsightsServiceFactory = ({// eslint-disable-next-line no-continueif (!matchedRule || !matchedRule.enabled || !matchedRule.intervalSeconds) continue;- const lastRotated = candidate.lastRotatedAt+ const baseMs = candidate.lastRotatedAt? new Date(candidate.lastRotatedAt).getTime(): candidate.createdAt.getTime();- const nextRotationMs = lastRotated + matchedRule.intervalSeconds * 1000;-- candidatesWithRotation.push({- row: {+ const intervalMs = matchedRule.intervalSeconds * 1000;+ if (intervalMs <= 0) {+ // eslint-disable-next-line no-continue+ continue;+ }++ // Fast-forward to the first occurrence within the visible range.+ let occurrenceMs = baseMs;+ if (occurrenceMs < rangeStartMs) {+ const skips = Math.ceil((rangeStartMs - occurrenceMs) / intervalMs);+ occurrenceMs = baseMs + skips * intervalMs;+ }++ let count = 0;+ while (occurrenceMs <= rangeEndMs && count < MAX_EVENTS_PER_ACCOUNT) {+ events.push({+ id: `${candidate.id}-${occurrenceMs}`,accountId: candidate.id,accountName: candidate.name,resourceId: candidate.resourceId,resourceName: candidate.resourceName,resourceType: candidate.resourceType,intervalSeconds: matchedRule.intervalSeconds,- nextRotationAt: new Date(Math.max(nextRotationMs, now))- },- nextRotationMs- });+ nextRotationAt: new Date(occurrenceMs)+ });+ occurrenceMs += intervalMs;+ count += 1;+ }}- candidatesWithRotation.sort((a, b) => a.nextRotationMs - b.nextRotationMs);+ events.sort((a, b) => a.nextRotationAt.getTime() - b.nextRotationAt.getTime());- return {- rotations: candidatesWithRotation.slice(0, UPCOMING_ROTATIONS_LIMIT).map((c) => c.row),- totalScheduled: candidatesWithRotation.length- };+ return { rotations: events };},reviver: (parsed) => {parsed.rotations.forEach((r) => {@@ -277,6 +310,6 @@ export const pamInsightsServiceFactory = ({getSessionActivity,getTopActors,getResourceBreakdown,- getUpcomingRotations+ getRotationCalendar};};diff --git a/frontend/src/hooks/api/pamInsights/index.ts b/frontend/src/hooks/api/pamInsights/index.tsindex 4e29988ec7..50958da78a 100644--- a/frontend/src/hooks/api/pamInsights/index.ts+++ b/frontend/src/hooks/api/pamInsights/index.ts@@ -2,19 +2,20 @@ export {pamInsightsKeys,useGetPamInsightsSummary,useGetPamResourceBreakdown,+ useGetPamRotationCalendar,useGetPamSessionActivity,- useGetPamTopActors,- useGetPamUpcomingRotations+ useGetPamTopActors} from "./queries";export type {TGetPamInsightsParams,+ TGetPamRotationCalendarParams,TPamInsightsSummary,TPamResourceBreakdownEntry,TPamResourceBreakdownResponse,+ TPamRotationCalendarEvent,+ TPamRotationCalendarResponse,TPamSessionActivityDay,TPamSessionActivityResponse,TPamTopActor,- TPamTopActorsResponse,- TPamUpcomingRotation,- TPamUpcomingRotationsResponse+ TPamTopActorsResponse} from "./types";diff --git a/frontend/src/hooks/api/pamInsights/queries.tsx b/frontend/src/hooks/api/pamInsights/queries.tsxindex 26b93937c4..eade828ac4 100644--- a/frontend/src/hooks/api/pamInsights/queries.tsx+++ b/frontend/src/hooks/api/pamInsights/queries.tsx@@ -4,11 +4,12 @@ import { apiRequest } from "@app/config/request";import {TGetPamInsightsParams,+ TGetPamRotationCalendarParams,TPamInsightsSummary,TPamResourceBreakdownResponse,+ TPamRotationCalendarResponse,TPamSessionActivityResponse,- TPamTopActorsResponse,- TPamUpcomingRotationsResponse+ TPamTopActorsResponse} from "./types";export const pamInsightsKeys = {@@ -21,8 +22,8 @@ export const pamInsightsKeys = {[...pamInsightsKeys.all(), "top-actors", params] as const,resourceBreakdown: (params: TGetPamInsightsParams) =>[...pamInsightsKeys.all(), "resource-breakdown", params] as const,- upcomingRotations: (params: TGetPamInsightsParams) =>- [...pamInsightsKeys.all(), "upcoming-rotations", params] as const+ rotationCalendar: (params: TGetPamRotationCalendarParams) =>+ [...pamInsightsKeys.all(), "rotation-calendar", params] as const};const PAM_INSIGHTS_STALE_TIME = 5 * 60 * 1000;@@ -130,23 +131,23 @@ export const useGetPamResourceBreakdown = (...options});-export const useGetPamUpcomingRotations = (- params: TGetPamInsightsParams,+export const useGetPamRotationCalendar = (+ params: TGetPamRotationCalendarParams,options?: Omit<UseQueryOptions<- TPamUpcomingRotationsResponse,+ TPamRotationCalendarResponse,unknown,- TPamUpcomingRotationsResponse,- ReturnType<typeof pamInsightsKeys.upcomingRotations>+ TPamRotationCalendarResponse,+ ReturnType<typeof pamInsightsKeys.rotationCalendar>>,"queryKey" | "queryFn">) =>useQuery({- queryKey: pamInsightsKeys.upcomingRotations(params),+ queryKey: pamInsightsKeys.rotationCalendar(params),queryFn: async () => {- const { data } = await apiRequest.get<TPamUpcomingRotationsResponse>(- "/api/v1/insights/pam/upcoming-rotations",+ const { data } = await apiRequest.get<TPamRotationCalendarResponse>(+ "/api/v1/insights/pam/rotation-calendar",{ params });return data;diff --git a/frontend/src/hooks/api/pamInsights/types.ts b/frontend/src/hooks/api/pamInsights/types.tsindex 5140ffc0e3..2d795f1bfd 100644--- a/frontend/src/hooks/api/pamInsights/types.ts+++ b/frontend/src/hooks/api/pamInsights/types.ts@@ -2,11 +2,21 @@ export type TGetPamInsightsParams = {projectId: string;};+export type TPamFailedRotationAccount = {+ accountId: string;+ accountName: string;+ resourceId: string;+ resourceName: string;+ resourceType: string;+ lastRotatedAt: string | null;+};+export type TPamInsightsSummary = {totalResources: number;resourcesWithRotation: number;totalAccounts: number;failedRotations: number;+ failedRotationAccounts: TPamFailedRotationAccount[];activeSessions: number;resourceTypeCount: number;};@@ -42,7 +52,8 @@ export type TPamResourceBreakdownResponse = {breakdown: TPamResourceBreakdownEntry[];};-export type TPamUpcomingRotation = {+export type TPamRotationCalendarEvent = {+ id: string;accountId: string;accountName: string;resourceId: string;@@ -52,7 +63,12 @@ export type TPamUpcomingRotation = {nextRotationAt: string;};-export type TPamUpcomingRotationsResponse = {- rotations: TPamUpcomingRotation[];- totalScheduled: number;+export type TPamRotationCalendarResponse = {+ rotations: TPamRotationCalendarEvent[];+};++export type TGetPamRotationCalendarParams = {+ projectId: string;+ month: number;+ year: number;};diff --git a/frontend/src/pages/pam/InsightsPage/InsightsPage.tsx b/frontend/src/pages/pam/InsightsPage/InsightsPage.tsxindex 27c52a7c94..3dc6d9cdb8 100644--- a/frontend/src/pages/pam/InsightsPage/InsightsPage.tsx+++ b/frontend/src/pages/pam/InsightsPage/InsightsPage.tsx@@ -8,9 +8,9 @@ import { ProjectType } from "@app/hooks/api/projects/types";import {PamInsightsKpiCards,PamResourceBreakdown,+ PamRotationCalendar,PamSessionActivityChart,- PamTopActors,- PamUpcomingRotations+ PamTopActors} from "./components";export const InsightsPage = withProjectPermission(@@ -27,10 +27,16 @@ export const InsightsPage = withProjectPermission(/><PamInsightsKpiCards /><div className="mt-6 grid grid-cols-1 gap-6 xl:grid-cols-[1.3fr_1fr]">- <PamSessionActivityChart />- <PamTopActors />- <PamResourceBreakdown />- <PamUpcomingRotations />+ <div className="flex flex-col gap-6">+ <PamRotationCalendar />+ <PamResourceBreakdown />+ </div>+ <div className="flex flex-col gap-6">+ <PamSessionActivityChart />+ <div className="flex-1">+ <PamTopActors />+ </div>+ </div></div></>);diff --git a/frontend/src/pages/pam/InsightsPage/components/PamInsightsKpiCards.tsx b/frontend/src/pages/pam/InsightsPage/components/PamInsightsKpiCards.tsxindex f8ff490724..6082e0c1bf 100644--- a/frontend/src/pages/pam/InsightsPage/components/PamInsightsKpiCards.tsx+++ b/frontend/src/pages/pam/InsightsPage/components/PamInsightsKpiCards.tsx@@ -1,9 +1,12 @@+import { useState } from "react";import { useNavigate } from "@tanstack/react-router";+import { formatDistanceToNow, parseISO } from "date-fns";import {ActivityIcon,AlertTriangleIcon,CheckIcon,DatabaseIcon,+ ExternalLinkIcon,InfoIcon,KeyRoundIcon} from "lucide-react";@@ -16,15 +19,35 @@ import {CardContent,CardHeader,CardTitle,+ Popover,+ PopoverContent,+ PopoverTrigger,Separator,- Skeleton+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";import { cn } from "@app/components/v3/utils";import { useOrganization, useProject } from "@app/context";+import { PamResourceType } from "@app/hooks/api/pam/enums";+import { PAM_RESOURCE_TYPE_MAP } from "@app/hooks/api/pam/maps";import { useGetPamInsightsSummary } from "@app/hooks/api/pamInsights";+import { TPamFailedRotationAccount } from "@app/hooks/api/pamInsights/types";++const knownResourceTypes = Object.values(PamResourceType) as string[];++const accountRoute =+ "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId" as const;type IconVariant = "warning" | "info" | "success" | "danger";-type FootnoteVariant = "success" | "info" | "danger";+type FootnoteVariant = "success" | "info" | "danger" | "warning";type StatCardProps = {title: string;@@ -34,21 +57,101 @@ type StatCardProps = {subtitle: string;footnote: React.ReactNode;footnoteVariant: FootnoteVariant;+ footnoteTooltip?: React.ReactNode;viewLabel?: string;to?: string;params?: Record<string, string>;+ popoverContent?: React.ReactNode;+ popoverDisabled?: boolean;+};++const FailedRotationsTable = ({+ accounts,+ orgId,+ projectId+}: {+ accounts: TPamFailedRotationAccount[];+ orgId: string;+ projectId: string;+}) => {+ const navigate = useNavigate();+ if (!accounts.length) {+ return <p className="p-4 text-center text-xs text-muted">No failed rotations</p>;+ }+ return (+ <Table containerClassName="max-h-72">+ <TableHeader className="sticky top-0 z-10 bg-container shadow-[inset_0_-1px_0_var(--color-border)]">+ <TableRow>+ <TableHead>Account</TableHead>+ <TableHead>Resource</TableHead>+ <TableHead>Last Rotated</TableHead>+ <TableHead className="w-8" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {accounts.map((account) => {+ const meta = knownResourceTypes.includes(account.resourceType)+ ? PAM_RESOURCE_TYPE_MAP[account.resourceType as PamResourceType]+ : null;+ return (+ <TableRow+ key={account.accountId}+ onClick={() =>+ navigate({+ to: accountRoute,+ params: {+ orgId,+ projectId,+ resourceType: account.resourceType,+ resourceId: account.resourceId,+ accountId: account.accountId+ }+ })+ }+ >+ <TableCell className="max-w-[140px] truncate font-medium" title={account.accountName}>+ {account.accountName}+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-1.5">+ {meta?.image && (+ <img+ src={`/images/integrations/${meta.image}`}+ alt={meta.name}+ className="size-3.5 shrink-0 object-contain"+ />+ )}+ <span className="max-w-[110px] truncate text-muted" title={account.resourceName}>+ {account.resourceName}+ </span>+ </div>+ </TableCell>+ <TableCell className="text-muted">+ {account.lastRotatedAt+ ? formatDistanceToNow(parseISO(account.lastRotatedAt), { addSuffix: true })+ : "Never"}+ </TableCell>+ <TableCell className="w-8 px-2">+ <ExternalLinkIcon className="size-3.5 text-muted" />+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ );};const LiveBadge = ({ count }: { count: number }) => (- <span className="flex animate-pulse items-center gap-1.5 rounded-full bg-green-900/40 px-2.5 py-1 text-xs font-medium text-green-400">- <span className="size-1.5 animate-pulse rounded-full bg-green-400" />+ <Badge variant="success" className="animate-pulse">+ <ActivityIcon />{count === 1 ? "1 session live" : `${count} sessions live`}- </span>+ </Badge>);const renderFootnoteIcon = (variant: FootnoteVariant) => {if (variant === "success") return <CheckIcon />;- if (variant === "danger") return <AlertTriangleIcon />;+ if (variant === "danger" || variant === "warning") return <AlertTriangleIcon />;return <InfoIcon />;};@@ -56,10 +159,11 @@ const computeResourcesFootnote = (totalResources: number, resourcesWithRotation:if (totalResources === 0) {return { text: "No resources yet", variant: "info" as const };}- return {- text: `${resourcesWithRotation} of ${totalResources} with rotation`,- variant: "success" as const- };+ const pct = (resourcesWithRotation / totalResources) * 100;+ const text = `${resourcesWithRotation} of ${totalResources} with rotation`;+ if (pct === 100) return { text: "All resources covered", variant: "success" as const };+ if (pct >= 50) return { text, variant: "warning" as const };+ return { text, variant: "danger" as const };};const computeAccountsFootnote = (totalAccounts: number, failedRotations: number) => {@@ -83,11 +187,33 @@ const StatCard = ({subtitle,footnote,footnoteVariant,+ footnoteTooltip,viewLabel,to,- params+ params,+ popoverContent,+ popoverDisabled}: StatCardProps) => {const navigate = useNavigate();+ const [popoverOpen, setPopoverOpen] = useState(false);+ const renderBadge = () => {+ if (typeof footnote !== "string") return footnote;+ const badge = (+ <Badge variant={footnoteVariant}>+ {renderFootnoteIcon(footnoteVariant)}+ {footnote}+ </Badge>+ );+ if (!footnoteTooltip) return badge;+ return (+ <Tooltip>+ <TooltipTrigger asChild>{badge}</TooltipTrigger>+ <TooltipContent side="bottom" className="max-w-xs">+ {footnoteTooltip}+ </TooltipContent>+ </Tooltip>+ );+ };return (<Card className="flex-1"><CardHeader>@@ -113,23 +239,31 @@ const StatCard = ({</div><Separator /><div className="flex min-h-7 items-center justify-between">- {typeof footnote === "string" ? (- <Badge variant={footnoteVariant}>- {renderFootnoteIcon(footnoteVariant)}- {footnote}- </Badge>+ {renderBadge()}+ {popoverContent && viewLabel ? (+ <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>+ <PopoverTrigger asChild>+ <Button variant="outline" size="xs" disabled={popoverDisabled}>+ {viewLabel}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[480px] p-0" align="end">+ {popoverContent}+ </PopoverContent>+ </Popover>) : (- footnote- )}- {viewLabel && to && params && (- <Button- variant="outline"- size="xs"- disabled={count === 0}- onClick={() => navigate({ to, params })}- >- {viewLabel}- </Button>+ viewLabel &&+ to &&+ params && (+ <Button+ variant="outline"+ size="xs"+ disabled={count === 0}+ onClick={() => navigate({ to, params })}+ >+ {viewLabel}+ </Button>+ ))}</div></CardContent>@@ -157,6 +291,7 @@ export const PamInsightsKpiCards = () => {const resourcesWithRotation = data?.resourcesWithRotation ?? 0;const totalAccounts = data?.totalAccounts ?? 0;const failedRotations = data?.failedRotations ?? 0;+ const failedRotationAccounts = data?.failedRotationAccounts ?? [];const activeSessions = data?.activeSessions ?? 0;const resourceTypeCount = data?.resourceTypeCount ?? 0;@@ -173,6 +308,11 @@ export const PamInsightsKpiCards = () => {subtitle={`Across ${resourceTypeCount} resource types`}footnote={resourcesFootnote.text}footnoteVariant={resourcesFootnote.variant}+ footnoteTooltip={+ totalResources > 0+ ? "Rotation reduces credential exposure by replacing account passwords on a regular schedule. We recommend configuring rotation on every resource."+ : undefined+ }viewLabel="View Resources"to="/organizations/$orgId/projects/pam/$projectId/resources"params={params}@@ -185,6 +325,17 @@ export const PamInsightsKpiCards = () => {subtitle="Privileged credentials"footnote={accountsFootnote.text}footnoteVariant={accountsFootnote.variant}+ viewLabel={failedRotations > 0 ? "View Failed Rotations" : undefined}+ popoverContent={+ failedRotations > 0 ? (+ <FailedRotationsTable+ accounts={failedRotationAccounts}+ orgId={currentOrg.id}+ projectId={projectId}+ />+ ) : undefined+ }+ popoverDisabled={failedRotations === 0}/><StatCardtitle="Active Sessions"diff --git a/frontend/src/pages/pam/InsightsPage/components/PamResourceBreakdown.tsx b/frontend/src/pages/pam/InsightsPage/components/PamResourceBreakdown.tsxindex e0f324cbd8..2224938ec7 100644--- a/frontend/src/pages/pam/InsightsPage/components/PamResourceBreakdown.tsx+++ b/frontend/src/pages/pam/InsightsPage/components/PamResourceBreakdown.tsx@@ -1,4 +1,5 @@-import { useMemo } from "react";+import { Fragment, useMemo } from "react";+import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from "recharts";import {Card,@@ -18,13 +19,30 @@ import { useGetPamResourceBreakdown } from "@app/hooks/api/pamInsights";const knownResourceTypes = Object.values(PamResourceType) as string[];+const COLORS = [+ "#63b0bd",+ "#f1c40f",+ "#6dbf8b",+ "#c084d8",+ "#e8855e",+ "#5b9bd5",+ "#e06b8f",+ "#85c46c",+ "#d4a054",+ "#7b8ec4",+ "#cb6b6b",+ "#4fc1b0",+ "#b8a060"+];++const gradientId = (index: number) => `pam-breakdown-pie-${index}`;+export const PamResourceBreakdown = () => {const { projectId } = useProject();const { data, isPending } = useGetPamResourceBreakdown({ projectId }, { enabled: !!projectId });const rows = useMemo(() => {if (!data?.breakdown) return [];- const max = Math.max(...data.breakdown.map((r) => r.resourceCount), 1);return data.breakdown.map((entry) => {const meta = knownResourceTypes.includes(entry.resourceType)? PAM_RESOURCE_TYPE_MAP[entry.resourceType as PamResourceType]@@ -32,70 +50,138 @@ export const PamResourceBreakdown = () => {return {...entry,displayName: meta?.name ?? entry.resourceType,- image: meta?.image ?? null,- widthPct: Math.max(2, Math.round((entry.resourceCount / max) * 100))+ image: meta?.image ?? null};});}, [data]);- const renderBody = () => {- if (isPending) return <Skeleton className="h-[280px] w-full" />;- if (!rows.length) {- return (- <Empty className="border-0">- <EmptyHeader>- <EmptyTitle>No resources have been added yet</EmptyTitle>- </EmptyHeader>- </Empty>- );- }- return (- <ul className="flex flex-col divide-y divide-border/60">- {rows.map((row) => (- <li- key={row.resourceType}- className="flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0"- >- <div className="flex min-w-0 flex-1 items-center gap-3">- {row.image ? (- <img- src={`/images/integrations/${row.image}`}- alt={row.displayName}- className="size-5 shrink-0 object-contain"- />- ) : (- <span className="size-5 shrink-0 rounded-sm bg-border" />- )}- <div className="flex min-w-0 flex-1 flex-col gap-1.5">- <span className="truncate font-medium">{row.displayName}</span>- <div className="h-1.5 w-full max-w-[200px] overflow-hidden rounded-full bg-border/40">- <div- className="h-full rounded-full bg-primary"- style={{ width: `${row.widthPct}%` }}- />- </div>- </div>- </div>- <div className="flex shrink-0 items-baseline gap-1.5 text-sm">- <span className="font-semibold">{row.resourceCount.toLocaleString()}</span>- <span className="text-muted">resources</span>- <span className="text-muted">·</span>- <span className="font-semibold">{row.accountCount.toLocaleString()}</span>- <span className="text-muted">accounts</span>- </div>- </li>- ))}- </ul>- );- };+ const totalResources = useMemo(() => rows.reduce((sum, r) => sum + r.resourceCount, 0), [rows]);return (<Card className="h-full"><CardHeader>- <CardTitle>Resources & Accounts by Type</CardTitle>+ <CardTitle>Resources by Type</CardTitle><CardDescription>Breakdown of managed resources across integrations</CardDescription></CardHeader>- <CardContent>{renderBody()}</CardContent>+ <CardContent>+ {isPending && <Skeleton className="h-[260px] w-full" />}+ {!isPending && rows.length === 0 && (+ <Empty className="border-0">+ <EmptyHeader>+ <EmptyTitle>No resources have been added yet</EmptyTitle>+ </EmptyHeader>+ </Empty>+ )}+ {!isPending && rows.length > 0 && (+ <div className="flex items-center gap-8">+ <div className="shrink-0">+ <ResponsiveContainer width={220} height={220}>+ <PieChart>+ <defs>+ {COLORS.map((color, i) => (+ <radialGradient+ key={gradientId(i)}+ id={gradientId(i)}+ cx="50%"+ cy="50%"+ r="50%"+ gradientUnits="userSpaceOnUse"+ fx="110"+ fy="110"+ >+ <stop offset="0%" stopColor={color} stopOpacity={0.1} />+ <stop offset="55%" stopColor={color} stopOpacity={0.4} />+ <stop offset="100%" stopColor={color} stopOpacity={0.85} />+ </radialGradient>+ ))}+ </defs>+ <Pie+ data={rows}+ dataKey="resourceCount"+ nameKey="displayName"+ cx="50%"+ cy="50%"+ innerRadius={55}+ outerRadius={95}+ strokeWidth={2}+ stroke="var(--color-card)"+ paddingAngle={2}+ isAnimationActive={false}+ >+ {rows.map((entry, index) => (+ <Cell+ key={entry.resourceType}+ fill={`url(#${gradientId(index % COLORS.length)})`}+ style={{ outline: "none" }}+ />+ ))}+ </Pie>+ <Tooltip+ contentStyle={{+ backgroundColor: "var(--color-popover)",+ border: "1px solid var(--color-border)",+ borderRadius: 8,+ fontSize: 12+ }}+ labelStyle={{ color: "var(--color-foreground)" }}+ isAnimationActive={false}+ formatter={(value, name) => [+ `${Number(value).toLocaleString()} (${+ totalResources > 0 ? Math.round((Number(value) / totalResources) * 100) : 0+ }%)`,+ String(name)+ ]}+ />+ </PieChart>+ </ResponsiveContainer>+ </div>+ <div className="grid flex-1 grid-cols-[auto_auto_1fr_auto_auto_auto] items-center gap-x-3 gap-y-2">+ {rows.map((entry, index) => {+ const pct =+ totalResources > 0 ? Math.round((entry.resourceCount / totalResources) * 100) : 0;+ return (+ <Fragment key={entry.resourceType}>+ <span+ className="size-2.5 shrink-0 rounded-full"+ style={{ backgroundColor: COLORS[index % COLORS.length] }}+ />+ {entry.image ? (+ <img+ src={`/images/integrations/${entry.image}`}+ alt={entry.displayName}+ className="size-4 shrink-0 object-contain"+ />+ ) : (+ <span className="size-4 shrink-0 rounded-sm bg-border" />+ )}+ <span className="truncate text-sm" title={entry.displayName}>+ {entry.displayName}+ </span>+ <span className="text-right text-sm text-muted">{pct}%</span>+ <span className="text-right text-sm font-medium">+ {entry.resourceCount.toLocaleString()}+ </span>+ <span className="text-left text-xs text-muted">+ {entry.resourceCount === 1 ? "resource" : "resources"}+ </span>+ </Fragment>+ );+ })}+ <div className="col-span-6 mt-1 border-t border-border" />+ <span />+ <span />+ <span className="text-sm font-medium">Total</span>+ <span />+ <span className="text-right text-sm font-medium">+ {totalResources.toLocaleString()}+ </span>+ <span className="text-left text-xs text-muted">+ {totalResources === 1 ? "resource" : "resources"}+ </span>+ </div>+ </div>+ )}+ </CardContent></Card>);};diff --git a/frontend/src/pages/pam/InsightsPage/components/PamRotationCalendar.tsx b/frontend/src/pages/pam/InsightsPage/components/PamRotationCalendar.tsxnew file mode 100644index 0000000000..b16144f91a--- /dev/null+++ b/frontend/src/pages/pam/InsightsPage/components/PamRotationCalendar.tsx@@ -0,0 +1,326 @@+import { useMemo, useState } from "react";+import { useNavigate } from "@tanstack/react-router";+import {+ addMonths,+ eachDayOfInterval,+ endOfMonth,+ endOfWeek,+ format,+ isSameMonth,+ isToday,+ parseISO,+ startOfMonth,+ startOfWeek,+ subMonths+} from "date-fns";+import { ChevronLeft, ChevronRight, ExternalLink, RefreshCwIcon } from "lucide-react";++import { Lottie } from "@app/components/v2";+import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Detail,+ DetailGroup,+ DetailLabel,+ DetailValue,+ IconButton,+ Popover,+ PopoverContent,+ PopoverTrigger,+ Separator+} from "@app/components/v3";+import { useOrganization, useProject } from "@app/context";+import { PamResourceType } from "@app/hooks/api/pam/enums";+import { PAM_RESOURCE_TYPE_MAP } from "@app/hooks/api/pam/maps";+import { TPamRotationCalendarEvent, useGetPamRotationCalendar } from "@app/hooks/api/pamInsights";++const knownResourceTypes = Object.values(PamResourceType) as string[];+const DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];++const accountRoute =+ "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId" as const;++const formatInterval = (seconds: number): string => {+ const days = Math.round(seconds / 86400);+ if (days <= 0) {+ const hours = Math.max(1, Math.round(seconds / 3600));+ return `every ${hours} hour${hours === 1 ? "" : "s"}`;+ }+ return `every ${days} day${days === 1 ? "" : "s"}`;+};++const groupEventsByDate = (+ events: TPamRotationCalendarEvent[]+): Record<string, TPamRotationCalendarEvent[]> => {+ const map: Record<string, TPamRotationCalendarEvent[]> = {};+ events.forEach((event) => {+ const key = format(parseISO(event.nextRotationAt), "yyyy-MM-dd");+ if (!map[key]) map[key] = [];+ map[key].push(event);+ });+ return map;+};++const RotationEventDetail = ({ event }: { event: TPamRotationCalendarEvent }) => {+ const { currentOrg } = useOrganization();+ const { projectId } = useProject();+ const navigate = useNavigate();+ const meta = knownResourceTypes.includes(event.resourceType)+ ? PAM_RESOURCE_TYPE_MAP[event.resourceType as PamResourceType]+ : null;+ const dateStr = format(parseISO(event.nextRotationAt), "MMM d, yyyy 'at' h:mm a");++ return (+ <div className="flex flex-col gap-4">+ <div className="flex items-center justify-between gap-2">+ <h3 className="truncate text-sm font-semibold" title={event.accountName}>+ {event.accountName}+ </h3>+ <Badge variant="info">+ <RefreshCwIcon />+ Rotation+ </Badge>+ </div>+ <Separator />+ <DetailGroup>+ <Detail>+ <DetailLabel>Date</DetailLabel>+ <DetailValue>{dateStr}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Resource</DetailLabel>+ <DetailValue>+ <div className="flex items-center gap-1.5">+ {meta?.image && (+ <img+ src={`/images/integrations/${meta.image}`}+ alt={meta.name}+ className="size-3.5 shrink-0 object-contain"+ />+ )}+ <span className="truncate">{event.resourceName}</span>+ </div>+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Type</DetailLabel>+ <DetailValue>{meta?.name ?? event.resourceType}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Interval</DetailLabel>+ <DetailValue>{formatInterval(event.intervalSeconds)}</DetailValue>+ </Detail>+ </DetailGroup>++ <Button+ variant="project"+ size="sm"+ isFullWidth+ onClick={() =>+ navigate({+ to: accountRoute,+ params: {+ orgId: currentOrg.id,+ projectId,+ resourceType: event.resourceType,+ resourceId: event.resourceId,+ accountId: event.accountId+ }+ })+ }+ >+ <ExternalLink />+ View Account+ </Button>+ </div>+ );+};++const RotationEventPill = ({ event }: { event: TPamRotationCalendarEvent }) => {+ const [open, setOpen] = useState(false);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Badge asChild className="justify-start" variant="info" isFullWidth isTruncatable>+ <button type="button" onClick={(e) => e.stopPropagation()} title={event.accountName}>+ <RefreshCwIcon />+ <span>{event.accountName}</span>+ </button>+ </Badge>+ </PopoverTrigger>+ <PopoverContent side="left" className="w-80 bg-card" align="start">+ <RotationEventDetail event={event} />+ </PopoverContent>+ </Popover>+ );+};++const MAX_SLOTS = 2;++const getBgClass = (today: boolean, isCurrentMonth: boolean) => {+ if (today) return isCurrentMonth ? "bg-muted/5" : "bg-card/50";+ return isCurrentMonth ? "bg-container" : "bg-card";+};++const RotationDayCell = ({+ date,+ isCurrentMonth,+ events+}: {+ date: Date;+ isCurrentMonth: boolean;+ events: TPamRotationCalendarEvent[];+}) => {+ const [overflowOpen, setOverflowOpen] = useState(false);+ const today = isToday(date);+ const dayNum = date.getDate();+ const hasOverflow = events.length > MAX_SLOTS;+ const visibleCount = hasOverflow ? MAX_SLOTS - 1 : events.length;+ const visibleEvents = events.slice(0, visibleCount);+ const overflowCount = events.length - visibleCount;++ return (+ <div+ className={`min-h-[86px] border border-border p-2 transition-colors duration-75 hover:bg-container-hover ${getBgClass(+ today,+ isCurrentMonth+ )}`}+ >+ <div className="mb-1">+ {today ? (+ <span className="inline-flex size-7 items-center justify-center rounded border border-border bg-muted/35 text-sm font-medium text-foreground">+ {dayNum}+ </span>+ ) : (+ <span className="text-sm text-label">{dayNum}</span>+ )}+ </div>+ <div className="flex flex-col gap-1">+ {visibleEvents.map((event) => (+ <RotationEventPill key={event.id} event={event} />+ ))}+ {hasOverflow && (+ <Popover open={overflowOpen} onOpenChange={setOverflowOpen}>+ <PopoverTrigger asChild>+ <Badge asChild variant="neutral" isFullWidth className="justify-center">+ <button type="button" onClick={(e) => e.stopPropagation()}>+ +{overflowCount} more+ </button>+ </Badge>+ </PopoverTrigger>+ <PopoverContent className="w-56 bg-card" align="start">+ <div className="flex flex-col gap-1.5">+ {events.map((event) => (+ <RotationEventPill key={`overflow-${event.id}`} event={event} />+ ))}+ </div>+ </PopoverContent>+ </Popover>+ )}+ </div>+ </div>+ );+};++const RotationLegend = () => (+ <div className="float-right mt-3 -mb-2 flex items-center gap-4">+ <div className="flex items-center gap-1.5">+ <span className="size-2 rounded-full bg-info" />+ <span className="text-xs text-muted">Rotation</span>+ </div>+ </div>+);++export const PamRotationCalendar = () => {+ const { projectId } = useProject();+ const [currentMonth, setCurrentMonth] = useState(new Date());++ const month = currentMonth.getMonth() + 1;+ const year = currentMonth.getFullYear();++ const { data, isPending } = useGetPamRotationCalendar(+ { projectId, month, year },+ { enabled: !!projectId }+ );++ const days = useMemo(() => {+ const monthStart = startOfMonth(currentMonth);+ const monthEnd = endOfMonth(currentMonth);+ const gridStart = startOfWeek(monthStart, { weekStartsOn: 1 });+ const gridEnd = endOfWeek(monthEnd, { weekStartsOn: 1 });+ return eachDayOfInterval({ start: gridStart, end: gridEnd });+ }, [currentMonth]);++ const eventsByDate = useMemo(() => groupEventsByDate(data?.rotations ?? []), [data]);++ return (+ <Card className="h-full">+ <CardHeader>+ <CardTitle>Rotation Calendar</CardTitle>+ <CardDescription>Account credentials due to rotate this month</CardDescription>+ <CardAction>+ <div className="ml-4 flex items-center gap-1">+ <IconButton+ variant="ghost"+ size="xs"+ onClick={() => setCurrentMonth((prev) => subMonths(prev, 1))}+ >+ <ChevronLeft className="size-4" />+ </IconButton>+ <span className="min-w-[140px] text-center text-sm font-medium">+ {format(currentMonth, "MMMM yyyy")}+ </span>+ <IconButton+ variant="ghost"+ size="xs"+ onClick={() => setCurrentMonth((prev) => addMonths(prev, 1))}+ >+ <ChevronRight className="size-4" />+ </IconButton>+ </div>+ </CardAction>+ </CardHeader>+ <CardContent>+ <div className="relative">+ <div className="overflow-hidden rounded-lg border border-border bg-container">+ <div className="grid grid-cols-7">+ {DAY_NAMES.map((day) => (+ <div+ key={day}+ className="border-b border-border py-2 text-center text-sm font-medium"+ >+ {day}+ </div>+ ))}+ </div>+ <div className="grid grid-cols-7">+ {days.map((day) => {+ const dateKey = format(day, "yyyy-MM-dd");+ return (+ <RotationDayCell+ key={dateKey}+ date={day}+ isCurrentMonth={isSameMonth(day, currentMonth)}+ events={eventsByDate[dateKey] ?? []}+ />+ );+ })}+ </div>+ </div>+ {isPending && (+ <div className="absolute inset-0 flex items-center justify-center bg-container/40">+ <Lottie icon="infisical_loading_white" isAutoPlay className="w-16" />+ </div>+ )}+ </div>+ <RotationLegend />+ </CardContent>+ </Card>+ );+};diff --git a/frontend/src/pages/pam/InsightsPage/components/PamSessionActivityChart.tsx b/frontend/src/pages/pam/InsightsPage/components/PamSessionActivityChart.tsxindex 96b2cef5fc..2da78d8fb0 100644--- a/frontend/src/pages/pam/InsightsPage/components/PamSessionActivityChart.tsx+++ b/frontend/src/pages/pam/InsightsPage/components/PamSessionActivityChart.tsx@@ -1,6 +1,5 @@import { useMemo } from "react";import { format, parseISO } from "date-fns";-import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";import {Card,@@ -15,11 +14,12 @@ import {} from "@app/components/v3";import { useProject } from "@app/context";import { useGetPamSessionActivity } from "@app/hooks/api/pamInsights";+import { LineChart } from "@app/pages/secret-manager/InsightsPage/components/LineChart";type ChartPoint = {date: string;- count: number;label: string;+ value: number;showTickLabel: string | null;};@@ -28,10 +28,10 @@ const buildAxisTicks = (data: ChartPoint[]): string[] => {const ticks: string[] = [];data.forEach((point, index) => {if (index === 0 || index === data.length - 1) {- ticks.push(point.date);+ ticks.push(point.label);return;}- if (index % 7 === 0) ticks.push(point.date);+ if (index % 7 === 0) ticks.push(point.label);});return ticks;};@@ -51,17 +51,22 @@ export const PamSessionActivityChart = () => {else if (isFirst || index % 7 === 0) tickLabel = format(parsed, "MMM d");return {date: day.date,- count: day.count,- label: format(parsed, "MMM d"),+ label: day.date,+ value: day.count,showTickLabel: tickLabel};});}, [data]);const ticks = useMemo(() => buildAxisTicks(chartData), [chartData]);- const totalSessions = chartData.reduce((sum, d) => sum + d.count, 0);+ const totalSessions = chartData.reduce((sum, d) => sum + d.value, 0);const hasAnyData = totalSessions > 0;+ const tickFormatter = (date: string) => {+ const point = chartData.find((p) => p.date === date);+ return point?.showTickLabel ?? "";+ };+const renderBody = () => {if (isPending) return <Skeleton className="h-[280px] w-full" />;if (!hasAnyData) {@@ -74,52 +79,14 @@ export const PamSessionActivityChart = () => {);}return (- <div className="flex flex-col gap-4 [&_*]:focus:outline-none [&_*:focus]:outline-none">- <ResponsiveContainer width="100%" height={280}>- <BarChart data={chartData} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}>- <CartesianGrid strokeDasharray="4 4" stroke="var(--color-border)" vertical={false} />- <XAxis- dataKey="date"- ticks={ticks}- tickFormatter={(date: string) => {- const point = chartData.find((p) => p.date === date);- return point?.showTickLabel ?? "";- }}- tick={{ fontSize: 11, fill: "var(--color-label)" }}- axisLine={false}- tickLine={false}- />- <YAxis- tick={{ fontSize: 11, fill: "var(--color-label)" }}- axisLine={false}- tickLine={false}- allowDecimals={false}- />- <Tooltip- contentStyle={{- backgroundColor: "var(--color-popover)",- border: "1px solid var(--color-border)",- borderRadius: 8,- fontSize: 12- }}- labelStyle={{ color: "var(--color-foreground)" }}- itemStyle={{ color: "var(--color-primary)" }}- cursor={false}- isAnimationActive={false}- labelFormatter={(date) => {- const point = chartData.find((p) => p.date === date);- return point?.label ?? String(date);- }}- formatter={(value) => [Number(value).toLocaleString(), "Sessions"]}- />- <Bar- dataKey="count"- fill="var(--color-primary)"- radius={[2, 2, 0, 0]}- style={{ outline: "none" }}- />- </BarChart>- </ResponsiveContainer>+ <div className="flex flex-col gap-4">+ <LineChart+ data={chartData}+ ticks={ticks}+ tickFormatter={tickFormatter}+ valueLabel="Sessions"+ gradientId="pam-session-activity-gradient"+ /><span className="text-xs text-muted">{totalSessions.toLocaleString()} sessions in the last 30 days ·{" "}{(data?.avgPerDay ?? 0).toLocaleString()} per day on average@@ -129,7 +96,7 @@ export const PamSessionActivityChart = () => {};return (- <Card className="h-full">+ <Card><CardHeader><CardTitle>Session Activity</CardTitle><CardDescription>PAM sessions started over the past 30 days</CardDescription>diff --git a/frontend/src/pages/pam/InsightsPage/components/PamUpcomingRotations.tsx b/frontend/src/pages/pam/InsightsPage/components/PamUpcomingRotations.tsxdeleted file mode 100644index 2f1a4c6e3b..0000000000--- a/frontend/src/pages/pam/InsightsPage/components/PamUpcomingRotations.tsx+++ /dev/null@@ -1,138 +0,0 @@-import { useMemo } from "react";-import { useNavigate } from "@tanstack/react-router";-import { formatDistanceToNow, parseISO } from "date-fns";-import { ExternalLinkIcon } from "lucide-react";--import {- Badge,- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,- Empty,- EmptyHeader,- EmptyTitle,- Skeleton,- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow-} from "@app/components/v3";-import { useOrganization, useProject } from "@app/context";-import { PamResourceType } from "@app/hooks/api/pam/enums";-import { PAM_RESOURCE_TYPE_MAP } from "@app/hooks/api/pam/maps";-import { useGetPamUpcomingRotations } from "@app/hooks/api/pamInsights";--const knownResourceTypes = Object.values(PamResourceType) as string[];--const accountRoute =- "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId" as const;--export const PamUpcomingRotations = () => {- const { currentOrg } = useOrganization();- const { projectId } = useProject();- const { data, isPending } = useGetPamUpcomingRotations({ projectId }, { enabled: !!projectId });- const navigate = useNavigate();-- const rows = useMemo(() => {- if (!data?.rotations) return [];- return data.rotations.map((r) => {- const meta = knownResourceTypes.includes(r.resourceType)- ? PAM_RESOURCE_TYPE_MAP[r.resourceType as PamResourceType]- : null;- return {- ...r,- displayType: meta?.name ?? r.resourceType,- image: meta?.image ?? null- };- });- }, [data]);-- const renderBody = () => {- if (isPending) return <Skeleton className="h-[280px] w-full" />;- if (!rows.length) {- return (- <Empty className="border-0">- <EmptyHeader>- <EmptyTitle>No rotations scheduled</EmptyTitle>- </EmptyHeader>- </Empty>- );- }- return (- <Table containerClassName="max-h-72">- <TableHeader className="sticky top-0 z-10 bg-container shadow-[inset_0_-1px_0_var(--color-border)]">- <TableRow>- <TableHead>Resource</TableHead>- <TableHead>Account</TableHead>- <TableHead>Type</TableHead>- <TableHead>Next Rotation</TableHead>- <TableHead className="w-8" />- </TableRow>- </TableHeader>- <TableBody>- {rows.map((row) => (- <TableRow- key={row.accountId}- onClick={() =>- navigate({- to: accountRoute,- params: {- orgId: currentOrg.id,- projectId,- resourceType: row.resourceType,- resourceId: row.resourceId,- accountId: row.accountId- }- })- }- >- <TableCell className="max-w-[140px] truncate font-medium" title={row.resourceName}>- {row.resourceName}- </TableCell>- <TableCell className="max-w-[120px] truncate text-muted" title={row.accountName}>- {row.accountName}- </TableCell>- <TableCell>- <div className="flex items-center gap-1.5">- {row.image && (- <img- src={`/images/integrations/${row.image}`}- alt={row.displayType}- className="size-3.5 shrink-0 object-contain"- />- )}- <span className="text-xs text-muted">{row.displayType}</span>- </div>- </TableCell>- <TableCell>- <Badge variant="warning">- {formatDistanceToNow(parseISO(row.nextRotationAt), { addSuffix: true })}- </Badge>- </TableCell>- <TableCell className="w-8 px-2">- <ExternalLinkIcon className="size-3.5 text-muted" />- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- );- };-- return (- <Card className="h-full">- <CardHeader>- <CardTitle>Upcoming Rotations</CardTitle>- <CardDescription>- {data?.totalScheduled ?? 0} scheduled rotation- {data?.totalScheduled === 1 ? "" : "s"} across this project- </CardDescription>- </CardHeader>- <CardContent>{renderBody()}</CardContent>- </Card>- );-};diff --git a/frontend/src/pages/pam/InsightsPage/components/index.ts b/frontend/src/pages/pam/InsightsPage/components/index.tsindex 2cb1aa98fd..64b1e3cf04 100644--- a/frontend/src/pages/pam/InsightsPage/components/index.ts+++ b/frontend/src/pages/pam/InsightsPage/components/index.ts@@ -1,5 +1,5 @@export { PamInsightsKpiCards } from "./PamInsightsKpiCards";export { PamResourceBreakdown } from "./PamResourceBreakdown";+export { PamRotationCalendar } from "./PamRotationCalendar";export { PamSessionActivityChart } from "./PamSessionActivityChart";export { PamTopActors } from "./PamTopActors";-export { PamUpcomingRotations } from "./PamUpcomingRotations";diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/LineChart.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/LineChart.tsxindex 0dd06fe994..f75f811ff9 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/LineChart.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/components/LineChart.tsx@@ -16,14 +16,25 @@ export type LineChartDataPoint = {type LineChartProps = {data: LineChartDataPoint[];height?: number;+ valueLabel?: string;+ ticks?: string[];+ tickFormatter?: (label: string) => string;+ gradientId?: string;};-export const LineChart = ({ data, height = 280 }: LineChartProps) => {+export const LineChart = ({+ data,+ height = 280,+ valueLabel = "Requests",+ ticks,+ tickFormatter,+ gradientId = "areaGradient"+}: LineChartProps) => {return (<ResponsiveContainer width="100%" height={height}><AreaChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}><defs>- <linearGradient id="areaGradient" x1="0" y1="0" x2="0" y2="1">+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="var(--color-info)" stopOpacity={0.15} /><stop offset="100%" stopColor="var(--color-info)" stopOpacity={0} /></linearGradient>@@ -31,6 +42,8 @@ export const LineChart = ({ data, height = 280 }: LineChartProps) => {<CartesianGrid strokeDasharray="4 4" stroke="var(--color-border)" vertical={false} /><XAxisdataKey="label"+ ticks={ticks}+ tickFormatter={tickFormatter}tick={{ fontSize: 11, fill: "var(--color-label)" }}axisLine={false}tickLine={false}@@ -51,14 +64,15 @@ export const LineChart = ({ data, height = 280 }: LineChartProps) => {labelStyle={{ color: "var(--color-foreground)" }}itemStyle={{ color: "var(--color-warning)" }}cursor={{ stroke: "var(--color-warning)", strokeWidth: 1, strokeDasharray: "4 4" }}- formatter={(value) => [Number(value).toLocaleString(), "Requests"]}+ isAnimationActive={false}+ formatter={(value) => [Number(value).toLocaleString(), valueLabel]}/><Areatype="monotoneX"dataKey="value"stroke="var(--color-info)"strokeWidth={1.5}- fill="url(#areaGradient)"+ fill={`url(#${gradientId})`}dot={{r: 4,fill: "var(--color-info)",