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
refactor to avoid dup
Thiago Araujo da Silvaf82d13781974
diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.tsindex 4734daf64f..683353c338 100644--- a/backend/src/services/alert/alert-channel-service.ts+++ b/backend/src/services/alert/alert-channel-service.ts@@ -17,6 +17,7 @@ import { TAlertChannelDALFactory } from "./alert-channel-dal";import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";import { TAlertChannelEmbedded, TChannelRecipientInput } from "./alert-channel-service-types";import { AlertChannelType } from "./alert-channel-types";+import { resolvePrincipalsInScope } from "./alert-principal-scope-fns";import { AlertPrincipalType } from "./alert-types";import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";@@ -83,48 +84,24 @@ export const alertChannelServiceFactory = ({];if (userIds.length === 0 && groupIds.length === 0) return;- if (projectId) {- const { effectiveUserIds, effectiveGroupIds } = await projectDAL.findEffectiveProjectSubjectsMembership({- orgId,- projectId,- userIds,- groupIds- });- const projectUserIds = new Set(effectiveUserIds);- const missingUsers = userIds.filter((id) => !projectUserIds.has(id));- if (missingUsers.length) {- throw new BadRequestError({ message: `Some users are not members of the project: ${missingUsers.join(", ")}` });- }- const projectGroupIds = new Set(effectiveGroupIds);- const missingGroups = groupIds.filter((id) => !projectGroupIds.has(id));- if (missingGroups.length) {- throw new BadRequestError({- message: `Some groups are not members of the project: ${missingGroups.join(", ")}`- });- }- return;- }+ const inScope = await resolvePrincipalsInScope(+ { orgDAL, projectDAL, groupDAL },+ { orgId, projectId, userIds, groupIds }+ );+ const scopeLabel = projectId ? "project" : "organization";- if (userIds.length) {- const memberships = await orgDAL.findMembership({ $in: { actorUserId: userIds }, scopeOrgId: orgId });- const orgUserIds = new Set(memberships.map((m) => m.actorUserId));- const missingUsers = userIds.filter((id) => !orgUserIds.has(id));- if (missingUsers.length) {- throw new BadRequestError({- message: `Some users are not members of the organization: ${missingUsers.join(", ")}`- });- }+ const missingUsers = userIds.filter((id) => !inScope.userIds.has(id));+ if (missingUsers.length) {+ throw new BadRequestError({+ message: `Some users are not members of the ${scopeLabel}: ${missingUsers.join(", ")}`+ });}- if (groupIds.length) {- const orgGroups = await groupDAL.find({ $in: { id: groupIds }, orgId });- const orgGroupIds = new Set(orgGroups.map((g) => g.id));- const missingGroups = groupIds.filter((id) => !orgGroupIds.has(id));- if (missingGroups.length) {- throw new BadRequestError({- message: `Some groups are not part of the organization: ${missingGroups.join(", ")}`- });- }+ const missingGroups = groupIds.filter((id) => !inScope.groupIds.has(id));+ if (missingGroups.length) {+ throw new BadRequestError({+ message: `Some groups are not members of the ${scopeLabel}: ${missingGroups.join(", ")}`+ });}};diff --git a/backend/src/services/alert/alert-principal-scope-fns.ts b/backend/src/services/alert/alert-principal-scope-fns.tsnew file mode 100644index 0000000000..6e8353b870--- /dev/null+++ b/backend/src/services/alert/alert-principal-scope-fns.ts@@ -0,0 +1,54 @@+import { TGroupDALFactory } from "@app/ee/services/group/group-dal";+import { TOrgDALFactory } from "@app/services/org/org-dal";+import { TProjectDALFactory } from "@app/services/project/project-dal";++export type TPrincipalScopeDALs = {+ orgDAL: Pick<TOrgDALFactory, "findMembership">;+ projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;+ // Only needed when org-scoped group membership must be verified (see below).+ groupDAL?: Pick<TGroupDALFactory, "find">;+};++export type TPrincipalScope = { orgId: string; projectId?: string | null };++export type TInScopePrincipals = { userIds: Set<string>; groupIds: Set<string> };++/**+ * Narrows a set of user/group ids down to the ones that are actually in the alert's scope. Shared by+ * the write path (validating an alert channel's recipients) and the send path (re-checking recipients+ * at delivery time), so both agree on what "in scope" means.+ *+ * Project scope: effective project membership, i.e. directly added or inherited via a project group.+ * Org scope: org membership for users. Groups are verified against the org only when `groupDAL` is+ * supplied — a group cannot move between orgs, so the send path skips that query and trusts the ids+ * that were already validated at write time.+ */+export const resolvePrincipalsInScope = async (+ { orgDAL, projectDAL, groupDAL }: TPrincipalScopeDALs,+ { orgId, projectId, userIds, groupIds }: TPrincipalScope & { userIds: string[]; groupIds: string[] }+): Promise<TInScopePrincipals> => {+ if (userIds.length === 0 && groupIds.length === 0) return { userIds: new Set(), groupIds: new Set() };++ if (projectId) {+ const { effectiveUserIds, effectiveGroupIds } = await projectDAL.findEffectiveProjectSubjectsMembership({+ orgId,+ projectId,+ userIds,+ groupIds+ });+ return { userIds: new Set(effectiveUserIds), groupIds: new Set(effectiveGroupIds) };+ }++ const inScopeUserIds = new Set<string>();+ if (userIds.length) {+ const memberships = await orgDAL.findMembership({ $in: { actorUserId: userIds }, scopeOrgId: orgId });+ memberships.forEach((membership) => {+ if (membership.actorUserId) inScopeUserIds.add(membership.actorUserId);+ });+ }++ if (!groupDAL || groupIds.length === 0) return { userIds: inScopeUserIds, groupIds: new Set(groupIds) };++ const orgGroups = await groupDAL.find({ $in: { id: groupIds }, orgId });+ return { userIds: inScopeUserIds, groupIds: new Set(orgGroups.map((group) => group.id)) };+};diff --git a/backend/src/services/alert/alert-recipient-resolver.ts b/backend/src/services/alert/alert-recipient-resolver.tsindex 2e9f4980e7..89b0031dff 100644--- a/backend/src/services/alert/alert-recipient-resolver.ts+++ b/backend/src/services/alert/alert-recipient-resolver.ts@@ -5,6 +5,7 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";import { TUserDALFactory } from "@app/services/user/user-dal";import { TAlertRecipient } from "./alert-channel-types";+import { resolvePrincipalsInScope } from "./alert-principal-scope-fns";import { AlertPrincipalType } from "./alert-types";type TAlertRecipientResolverDep = {@@ -26,32 +27,6 @@ export const alertRecipientResolverFactory = ({orgDAL,projectDAL}: TAlertRecipientResolverDep) => {- const resolveInScope = async (- scope: TResolveScope,- userIds: string[],- groupIds: string[]- ): Promise<{ userIds: Set<string>; groupIds: Set<string> }> => {- if (userIds.length === 0) return { userIds: new Set(), groupIds: new Set() };-- if (scope.projectId) {- const { effectiveUserIds, effectiveGroupIds } = await projectDAL.findEffectiveProjectSubjectsMembership({- orgId: scope.orgId,- projectId: scope.projectId,- userIds,- groupIds- });- return { userIds: new Set(effectiveUserIds), groupIds: new Set(effectiveGroupIds) };- }-- const memberships = await orgDAL.findMembership({ $in: { actorUserId: userIds }, scopeOrgId: scope.orgId });- return {- userIds: new Set(- memberships.map((membership) => membership.actorUserId).filter((id): id is string => Boolean(id))- ),- groupIds: new Set(groupIds)- };- };-const resolveMany = async (rowsByChannel: Map<string, TResolvableRecipient[]>,scope: TResolveScope@@ -76,10 +51,9 @@ export const alertRecipientResolverFactory = ({});}- const { userIds: inScopeUserIds, groupIds: inScopeGroupIds } = await resolveInScope(- scope,- [...allUserIds],- [...allGroupIds]+ const { userIds: inScopeUserIds, groupIds: inScopeGroupIds } = await resolvePrincipalsInScope(+ { orgDAL, projectDAL },+ { orgId: scope.orgId, projectId: scope.projectId, userIds: [...allUserIds], groupIds: [...allGroupIds] });const usersById = new Map<string, Awaited<ReturnType<typeof userDAL.find>>[number]>();if (inScopeUserIds.size > 0) {diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex 493fdfc660..91ff01e42e 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -368,12 +368,18 @@ describe("alert service", () => {);});- test("deletes an alert after checking Delete permission", async () => {- const { service, permissionCalls } = buildService();+ test("deletes an alert and its owned channels after checking Delete permission", async () => {+ const { service, permissionCalls, alerts, channels } = buildService();await service.createAlert(validCreate);+ expect(channels.size).toBe(2);+const result = await service.deleteAlert({ alertId: "alert-1", ...actor });+expect(result.id).toBe("alert-1");expect(permissionCalls.some((c) => c.action === "delete")).toBe(true);+ expect(alerts.size).toBe(0);+ // Same reaping as deleteAlertsForResource: no channel is left dangling.+ expect(channels.size).toBe(0);});test("deleteAlertsForResource reaps a resource's alerts and their owned channels", async () => {diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.tsindex 6a5dddbcea..6d280ca02b 100644--- a/backend/src/services/alert/alert-service.ts+++ b/backend/src/services/alert/alert-service.ts@@ -368,6 +368,17 @@ export const alertServiceFactory = ({return $assembleResponse(updated, channels);};+ const $deleteAlerts = async (alertIds: string[], tx: Knex): Promise<number> => {+ if (alertIds.length === 0) return 0;++ const channels = await alertChannelDAL.findByAlertIds(alertIds, tx);+ await alertDAL.delete({ $in: { id: alertIds } }, tx);+ if (channels.length > 0) {+ await alertChannelDAL.delete({ $in: { id: [...new Set(channels.map((channel) => channel.id))] } }, tx);+ }+ return alertIds.length;+ };+const deleteAlert = async (dto: TDeleteAlertDTO): Promise<{@@ -389,14 +400,7 @@ export const alertServiceFactory = ({dto);- await alertDAL.transaction(async (tx) => {- const channels = await alertChannelDAL.findByAlertId(alert.id, {}, tx);- for (const channel of channels) {- // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial- await alertChannelService.deleteChannelInTx(channel.id, tx);- }- await alertDAL.deleteById(alert.id, tx);- });+ await alertDAL.transaction((tx) => $deleteAlerts([alert.id], tx));return {id: alert.id,@@ -414,17 +418,10 @@ export const alertServiceFactory = ({): Promise<number> => {const run = async (trx: Knex) => {const alerts = await alertDAL.find({ orgId, resourceType, resourceId }, { tx: trx });- if (alerts.length === 0) return 0;-- const alertIds = alerts.map((alert) => alert.id);- // Capture the owned channels before deleting the alerts, since that cascades the membership rows.- const channels = await alertChannelDAL.findByAlertIds(alertIds, trx);-- await alertDAL.delete({ $in: { id: alertIds } }, trx);- if (channels.length > 0) {- await alertChannelDAL.delete({ $in: { id: [...new Set(channels.map((channel) => channel.id))] } }, trx);- }- return alertIds.length;+ return $deleteAlerts(+ alerts.map((alert) => alert.id),+ trx+ );};return tx ? run(tx) : alertDAL.transaction(run);diff --git a/frontend/src/hooks/api/alerts/index.ts b/frontend/src/hooks/api/alerts/index.tsindex 177955438b..1499a742f5 100644--- a/frontend/src/hooks/api/alerts/index.ts+++ b/frontend/src/hooks/api/alerts/index.ts@@ -1,3 +1,4 @@export * from "./mutations";export * from "./queries";export * from "./types";+export * from "./utils";diff --git a/frontend/src/hooks/api/alerts/utils.ts b/frontend/src/hooks/api/alerts/utils.tsnew file mode 100644index 0000000000..c8e46f95b7--- /dev/null+++ b/frontend/src/hooks/api/alerts/utils.ts@@ -0,0 +1,16 @@+// The backend stores an alert's lead time as a whole number of days, e.g. "30d".+const ALERT_BEFORE_PATTERN = /^(\d+)d$/;++export const parseAlertBeforeDays = (alertBefore?: string): number | null => {+ const match = alertBefore?.match(ALERT_BEFORE_PATTERN);+ return match ? parseInt(match[1], 10) : null;+};++export const toAlertBefore = (days: number): string => `${days}d`;++// "30d" -> "alert 30 days before". Empty string when the value is missing or malformed.+export const formatAlertBefore = (alertBefore?: string): string => {+ const days = parseAlertBeforeDays(alertBefore);+ if (days === null) return "";+ return `alert ${days} day${days === 1 ? "" : "s"} before`;+};diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsxindex 1fa1900e7b..5bf6be7633 100644--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityAlertDetail.tsx@@ -1,151 +1,23 @@-import { BellPlusIcon, MoreHorizontalIcon, PencilIcon, TrashIcon } from "lucide-react";--import { createNotification } from "@app/components/notifications";import { OrgPermissionCan } from "@app/components/permissions";-import { DeleteActionModal } from "@app/components/v2";-import {- Badge,- Button,- Detail,- DetailLabel,- DetailValue,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- IconButton-} from "@app/components/v3";import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/context";-import { usePopUp } from "@app/hooks";-import {- ALERT_EVENT_TYPE_LABELS,- AlertEventType,- AlertResourceType,- TAlert,- useDeleteAlert,- useListAlerts-} from "@app/hooks/api/alerts";-import { AddAlertModal } from "@app/views/Alerts";+import { AlertDetail } from "@app/views/Alerts";type Props = {identityId: string;identityName: string;};-const formatCondition = (alertBefore?: string): string => {- const match = alertBefore?.match(/^(\d+)d$/);- if (!match) return "";- const days = parseInt(match[1], 10);- return `alert ${days} day${days === 1 ? "" : "s"} before`;-};--export const IdentityAlertDetail = ({ identityId, identityName }: Props) => {- const { data: alerts = [] } = useListAlerts({- resourceType: AlertResourceType.IdentityAuthentication,- resourceId: identityId- });-- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["alert", "deleteAlert"] as const);-- const deleteAlert = useDeleteAlert();-- const existingAlert = alerts[0] as TAlert | undefined;-- const eventLabel = existingAlert- ? (ALERT_EVENT_TYPE_LABELS[existingAlert.eventType as AlertEventType] ??- existingAlert.eventType)- : "";- const conditionLabel = formatCondition(existingAlert?.condition?.alertBefore);- const summary = [eventLabel, conditionLabel].filter(Boolean).join(" · ");-- const handleDeleteAlert = async () => {- if (!existingAlert) return;-- try {- await deleteAlert.mutateAsync({ alertId: existingAlert.id });- createNotification({ text: "Successfully deleted alert", type: "success" });- handlePopUpToggle("deleteAlert", false);- } catch {- createNotification({ text: "Failed to delete alert", type: "error" });- }- };-- return (- <Detail>- <DetailLabel>Alert</DetailLabel>- <DetailValue>- {existingAlert ? (- <div className="flex w-full items-center gap-2">- <Badge variant={existingAlert.enabled ? "success" : "neutral"}>- {existingAlert.enabled ? "Enabled" : "Disabled"}- </Badge>- <span className="min-w-0 flex-1 truncate text-xs text-muted">{summary}</span>- <OrgPermissionCan- I={OrgPermissionIdentityActions.Edit}- a={OrgPermissionSubjects.Identity}- >- {(isAllowed) => (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label="Alert actions"- isDisabled={!isAllowed}- variant="ghost"- size="xs"- >- <MoreHorizontalIcon />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => handlePopUpOpen("alert")}>- <PencilIcon />- Edit- </DropdownMenuItem>- <DropdownMenuItem- variant="danger"- onClick={() => handlePopUpOpen("deleteAlert")}- >- <TrashIcon />- Remove- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </OrgPermissionCan>- </div>- ) : (- <OrgPermissionCan- I={OrgPermissionIdentityActions.Edit}- a={OrgPermissionSubjects.Identity}- >- {(isAllowed) => (- <Button- variant="outline"- size="xs"- isDisabled={!isAllowed}- onClick={() => handlePopUpOpen("alert")}- >- <BellPlusIcon />- Create Alert- </Button>- )}- </OrgPermissionCan>- )}- </DetailValue>- <AddAlertModal- isOpen={popUp.alert.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("alert", isOpen)}- resourceId={identityId}- resourceName={identityName}- alert={existingAlert}- />- <DeleteActionModal- isOpen={popUp.deleteAlert.isOpen}- title={`Are you sure you want to delete the alert ${existingAlert?.name ?? ""}?`}- onChange={(isOpen) => handlePopUpToggle("deleteAlert", isOpen)}- deleteKey="confirm"- onDeleteApproved={handleDeleteAlert}- />- </Detail>- );-};+export const IdentityAlertDetail = ({ identityId, identityName }: Props) => (+ <AlertDetail+ identityId={identityId}+ identityName={identityName}+ renderPermissionGate={(render) => (+ <OrgPermissionCan+ I={OrgPermissionIdentityActions.Edit}+ a={OrgPermissionSubjects.Identity}+ >+ {render}+ </OrgPermissionCan>+ )}+ />+);diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsxindex 94085b1d32..d6b3a85638 100644--- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsx+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/ProjectIdentityAlertDetail.tsx@@ -1,32 +1,8 @@import { subject } from "@casl/ability";-import { BellPlusIcon, MoreHorizontalIcon, PencilIcon, TrashIcon } from "lucide-react";-import { createNotification } from "@app/components/notifications";import { ProjectPermissionCan } from "@app/components/permissions";-import { DeleteActionModal } from "@app/components/v2";-import {- Badge,- Button,- Detail,- DetailLabel,- DetailValue,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- IconButton-} from "@app/components/v3";import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/context";-import { usePopUp } from "@app/hooks";-import {- ALERT_EVENT_TYPE_LABELS,- AlertEventType,- AlertResourceType,- TAlert,- useDeleteAlert,- useListAlerts-} from "@app/hooks/api/alerts";-import { AddAlertModal } from "@app/views/Alerts";+import { AlertDetail } from "@app/views/Alerts";type Props = {identityId: string;@@ -36,145 +12,26 @@ type Props = {readOnly?: boolean;};-const formatCondition = (alertBefore?: string): string => {- const match = alertBefore?.match(/^(\d+)d$/);- if (!match) return "";- const days = parseInt(match[1], 10);- return `alert ${days} day${days === 1 ? "" : "s"} before`;-};-export const ProjectIdentityAlertDetail = ({identityId,identityName,projectId,projectName,readOnly = false-}: Props) => {- const { data: alerts = [] } = useListAlerts({- resourceType: AlertResourceType.IdentityAuthentication,- resourceId: identityId,- ...(projectId ? { projectId } : {})- });-- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["alert", "deleteAlert"] as const);-- const deleteAlert = useDeleteAlert();-- const existingAlert = alerts[0] as TAlert | undefined;-- const eventLabel = existingAlert- ? (ALERT_EVENT_TYPE_LABELS[existingAlert.eventType as AlertEventType] ??- existingAlert.eventType)- : "";- const conditionLabel = formatCondition(existingAlert?.condition?.alertBefore);- const summary = [eventLabel, conditionLabel].filter(Boolean).join(" · ");-- const handleDeleteAlert = async () => {- if (!existingAlert) return;-- try {- await deleteAlert.mutateAsync({ alertId: existingAlert.id });- createNotification({ text: "Successfully deleted alert", type: "success" });- handlePopUpToggle("deleteAlert", false);- } catch {- createNotification({ text: "Failed to delete alert", type: "error" });- }- };-- const renderValue = () => {- if (existingAlert) {- return (- <div className="flex w-full items-center gap-2">- <Badge variant={existingAlert.enabled ? "success" : "neutral"}>- {existingAlert.enabled ? "Enabled" : "Disabled"}- </Badge>- <span className="min-w-0 flex-1 truncate text-xs text-muted">{summary}</span>- {!readOnly && (- <ProjectPermissionCan- I={ProjectPermissionIdentityActions.Edit}- a={subject(ProjectPermissionSub.Identity, { identityId })}- >- {(isAllowed) => (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label="Alert actions"- isDisabled={!isAllowed}- variant="ghost"- size="xs"- >- <MoreHorizontalIcon />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => handlePopUpOpen("alert")}>- <PencilIcon />- Edit- </DropdownMenuItem>- <DropdownMenuItem- variant="danger"- onClick={() => handlePopUpOpen("deleteAlert")}- >- <TrashIcon />- Remove- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </ProjectPermissionCan>- )}- </div>- );- }-- if (readOnly) {- return <span className="text-muted">—</span>;- }-- return (+}: Props) => (+ <AlertDetail+ identityId={identityId}+ identityName={identityName}+ projectId={projectId}+ scopeName={projectName}+ readOnly={readOnly}+ renderPermissionGate={(render) => (<ProjectPermissionCanI={ProjectPermissionIdentityActions.Edit}a={subject(ProjectPermissionSub.Identity, { identityId })}>- {(isAllowed) => (- <Button- variant="outline"- size="xs"- isDisabled={!isAllowed}- onClick={() => handlePopUpOpen("alert")}- >- <BellPlusIcon />- Create Alert- </Button>- )}+ {render}</ProjectPermissionCan>- );- };-- return (- <Detail>- <DetailLabel>Alert</DetailLabel>- <DetailValue>{renderValue()}</DetailValue>- {!readOnly && (- <>- <AddAlertModal- isOpen={popUp.alert.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("alert", isOpen)}- projectId={projectId}- scopeName={projectName}- resourceId={identityId}- resourceName={identityName}- alert={existingAlert}- />- <DeleteActionModal- isOpen={popUp.deleteAlert.isOpen}- title={`Are you sure you want to delete the alert ${existingAlert?.name ?? ""}?`}- onChange={(isOpen) => handlePopUpToggle("deleteAlert", isOpen)}- deleteKey="confirm"- onDeleteApproved={handleDeleteAlert}- />- </>- )}- </Detail>- );-};+ )}+ />+);diff --git a/frontend/src/views/Alerts/AlertDetail.tsx b/frontend/src/views/Alerts/AlertDetail.tsxnew file mode 100644index 0000000000..305f39730c--- /dev/null+++ b/frontend/src/views/Alerts/AlertDetail.tsx@@ -0,0 +1,164 @@+import { ReactNode } from "react";+import { BellPlusIcon, MoreHorizontalIcon, PencilIcon, TrashIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { DeleteActionModal } from "@app/components/v2";+import {+ Badge,+ Button,+ Detail,+ DetailLabel,+ DetailValue,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ IconButton+} from "@app/components/v3";+import { usePopUp } from "@app/hooks";+import {+ ALERT_EVENT_TYPE_LABELS,+ AlertEventType,+ AlertResourceType,+ formatAlertBefore,+ TAlert,+ useDeleteAlert,+ useListAlerts+} from "@app/hooks/api/alerts";++import { AddAlertModal } from "./AddAlertModal";++type Props = {+ identityId: string;+ identityName: string;+ // Org-scoped when omitted.+ projectId?: string;+ scopeName?: string;+ // Renders the alert without any way to create, edit or remove it.+ readOnly?: boolean;+ // Wraps the mutating actions in the caller's permission gate (org- or project-scoped), which is the+ // only thing that differs between the org and project entry points.+ renderPermissionGate: (render: (isAllowed: boolean) => ReactNode) => ReactNode;+};++export const AlertDetail = ({+ identityId,+ identityName,+ projectId,+ scopeName,+ readOnly = false,+ renderPermissionGate+}: Props) => {+ const { data: alerts = [] } = useListAlerts({+ resourceType: AlertResourceType.IdentityAuthentication,+ resourceId: identityId,+ ...(projectId ? { projectId } : {})+ });++ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["alert", "deleteAlert"] as const);++ const deleteAlert = useDeleteAlert();++ const existingAlert = alerts[0] as TAlert | undefined;++ const eventLabel = existingAlert+ ? (ALERT_EVENT_TYPE_LABELS[existingAlert.eventType as AlertEventType] ??+ existingAlert.eventType)+ : "";+ const summary = [eventLabel, formatAlertBefore(existingAlert?.condition?.alertBefore)]+ .filter(Boolean)+ .join(" · ");++ const handleDeleteAlert = async () => {+ if (!existingAlert) return;++ try {+ await deleteAlert.mutateAsync({ alertId: existingAlert.id });+ createNotification({ text: "Successfully deleted alert", type: "success" });+ handlePopUpToggle("deleteAlert", false);+ } catch {+ createNotification({ text: "Failed to delete alert", type: "error" });+ }+ };++ const renderValue = () => {+ if (existingAlert) {+ return (+ <div className="flex w-full items-center gap-2">+ <Badge variant={existingAlert.enabled ? "success" : "neutral"}>+ {existingAlert.enabled ? "Enabled" : "Disabled"}+ </Badge>+ <span className="min-w-0 flex-1 truncate text-xs text-muted">{summary}</span>+ {!readOnly &&+ renderPermissionGate((isAllowed) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Alert actions"+ isDisabled={!isAllowed}+ variant="ghost"+ size="xs"+ >+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => handlePopUpOpen("alert")}>+ <PencilIcon />+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem variant="danger" onClick={() => handlePopUpOpen("deleteAlert")}>+ <TrashIcon />+ Remove+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ))}+ </div>+ );+ }++ if (readOnly) {+ return <span className="text-muted">—</span>;+ }++ return renderPermissionGate((isAllowed) => (+ <Button+ variant="outline"+ size="xs"+ isDisabled={!isAllowed}+ onClick={() => handlePopUpOpen("alert")}+ >+ <BellPlusIcon />+ Create Alert+ </Button>+ ));+ };++ return (+ <Detail>+ <DetailLabel>Alert</DetailLabel>+ <DetailValue>{renderValue()}</DetailValue>+ {!readOnly && (+ <>+ <AddAlertModal+ isOpen={popUp.alert.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("alert", isOpen)}+ projectId={projectId}+ scopeName={scopeName}+ resourceId={identityId}+ resourceName={identityName}+ alert={existingAlert}+ />+ <DeleteActionModal+ isOpen={popUp.deleteAlert.isOpen}+ title={`Are you sure you want to delete the alert ${existingAlert?.name ?? ""}?`}+ onChange={(isOpen) => handlePopUpToggle("deleteAlert", isOpen)}+ deleteKey="confirm"+ onDeleteApproved={handleDeleteAlert}+ />+ </>+ )}+ </Detail>+ );+};diff --git a/frontend/src/views/Alerts/AlertForm.tsx b/frontend/src/views/Alerts/AlertForm.tsxindex a3356bd4ee..934a8f6099 100644--- a/frontend/src/views/Alerts/AlertForm.tsx+++ b/frontend/src/views/Alerts/AlertForm.tsx@@ -38,10 +38,12 @@ import {AlertResourceType,MAX_ALERT_BEFORE_DAYS,MIN_ALERT_BEFORE_DAYS,+ parseAlertBeforeDays,TAlert,TAlertChannelInput,TAlertForm,TChannelForm,+ toAlertBefore,useCreateAlert,useUpdateAlert} from "@app/hooks/api/alerts";@@ -73,11 +75,6 @@ const FixedField = ({ label, children }: { label: string; children: ReactNode })const DEFAULT_ALERT_BEFORE_DAYS = 7;-const parseAlertBeforeDays = (alertBefore?: string): number => {- const match = alertBefore?.match(/^(\d+)d$/);- return match ? parseInt(match[1], 10) : DEFAULT_ALERT_BEFORE_DAYS;-};-const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({id: channel.id,channelType: channel.channelType,@@ -113,7 +110,8 @@ const buildFormDefaults = (alert?: TAlert): TAlertForm => {resourceType:(alert.resourceType as AlertResourceType) ?? AlertResourceType.IdentityAuthentication,eventType: (alert.eventType as AlertEventType) ?? AlertEventType.IdentityAuthenticationExpiry,- alertBeforeDays: parseAlertBeforeDays(alert.condition?.alertBefore),+ alertBeforeDays:+ parseAlertBeforeDays(alert.condition?.alertBefore) ?? DEFAULT_ALERT_BEFORE_DAYS,dailyReminder: alert.condition?.dailyReminder ?? false,enabled: alert.enabled,channels: alert.channels.map(toChannelForm)@@ -207,7 +205,7 @@ export const AlertForm = ({const onSubmit = async (data: TAlertForm) => {const condition = {- alertBefore: `${data.alertBeforeDays}d`,+ alertBefore: toAlertBefore(data.alertBeforeDays),dailyReminder: data.dailyReminder};const channels = data.channels.map(toChannelInput);diff --git a/frontend/src/views/Alerts/ChannelRecipientsField.tsx b/frontend/src/views/Alerts/ChannelRecipientsField.tsxindex ad68b3f4e1..eab6af104e 100644--- a/frontend/src/views/Alerts/ChannelRecipientsField.tsx+++ b/frontend/src/views/Alerts/ChannelRecipientsField.tsx@@ -27,6 +27,24 @@ const userLabel = (user: {return user.email || user.username || name || "Unknown user";};+const buildOptions = (+ users: { user: { id: string; firstName?: string; lastName?: string; username?: string } }[],+ groups: { id: string; name: string }[]+): RecipientOption[] => [+ ...users.map((membership) => ({+ principalType: AlertPrincipalType.User,+ principalId: membership.user.id,+ label: userLabel(membership.user),+ groupLabel: "Users" as const+ })),+ ...groups.map((group) => ({+ principalType: AlertPrincipalType.Group,+ principalId: group.id,+ label: group.name,+ groupLabel: "Groups" as const+ }))+];+const formatOptionLabel = (option: RecipientOption) => (<span className="flex items-center gap-2">{option.principalType === AlertPrincipalType.Group ? (@@ -89,44 +107,22 @@ const OrgRecipientSelect = ({ orgId, ...props }: SelectProps & { orgId: string }const { data: users = [] } = useGetOrgUsers(orgId);const { data: groups = [] } = useGetOrganizationGroups(orgId);- const options: RecipientOption[] = [- ...users.map((membership) => ({- principalType: AlertPrincipalType.User,- principalId: membership.user.id,- label: userLabel(membership.user),- groupLabel: "Users" as const- })),- ...groups.map((group) => ({- principalType: AlertPrincipalType.Group,- principalId: group.id,- label: group.name,- groupLabel: "Groups" as const- }))- ];-- return <RecipientSelect options={options} {...props} />;+ return <RecipientSelect options={buildOptions(users, groups)} {...props} />;};const ProjectRecipientSelect = ({ projectId, ...props }: SelectProps & { projectId: string }) => {const { data: users = [] } = useGetWorkspaceUsers(projectId);const { data: groups = [] } = useListWorkspaceGroups(projectId);- const options: RecipientOption[] = [- ...users.map((membership) => ({- principalType: AlertPrincipalType.User,- principalId: membership.user.id,- label: userLabel(membership.user),- groupLabel: "Users" as const- })),- ...groups.map((membership) => ({- principalType: AlertPrincipalType.Group,- principalId: membership.group.id,- label: membership.group.name,- groupLabel: "Groups" as const- }))- ];-- return <RecipientSelect options={options} {...props} />;+ return (+ <RecipientSelect+ options={buildOptions(+ users,+ groups.map((membership) => membership.group)+ )}+ {...props}+ />+ );};type Props = SelectProps & { projectId?: string };diff --git a/frontend/src/views/Alerts/index.ts b/frontend/src/views/Alerts/index.tsindex baa7a1e924..b0b1d6ebf6 100644--- a/frontend/src/views/Alerts/index.ts+++ b/frontend/src/views/Alerts/index.ts@@ -1 +1,2 @@export { AddAlertModal } from "./AddAlertModal";+export { AlertDetail } from "./AlertDetail";