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
decouple channels
Thiago Araujo da Silvad0e3cf01ca4d
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 42c060863b..f296e7fc67 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -79,6 +79,7 @@ import { RequestMemoizer } from "@app/lib/request-context/request-memoizer";import { TAuthMode } from "@app/server/plugins/auth/inject-identity";import { TAccountRecoveryServiceFactory } from "@app/services/account-recovery/account-recovery-service";import { TAdditionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";+import { TAlarmChannelServiceFactory } from "@app/services/alarm/alarm-channel-service";import { TAlarmServiceFactory } from "@app/services/alarm/alarm-service";import { TAnnouncementServiceFactory } from "@app/services/announcement/announcement-service";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";@@ -441,6 +442,7 @@ declare module "fastify" {identityAuthTemplate: TIdentityAuthTemplateServiceFactory;notification: TNotificationServiceFactory;alarm: TAlarmServiceFactory;+ alarmChannel: TAlarmChannelServiceFactory;announcement: TAnnouncementServiceFactory;offlineUsageReport: TOfflineUsageReportServiceFactory;orgProductStats: TOrgProductStatsServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 1b157ee726..58d6e25028 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -41,6 +41,12 @@ import {TAiMcpServerUserCredentials,TAiMcpServerUserCredentialsInsert,TAiMcpServerUserCredentialsUpdate,+ TAlarmChannelMemberships,+ TAlarmChannelMembershipsInsert,+ TAlarmChannelMembershipsUpdate,+ TAlarmChannelRecipients,+ TAlarmChannelRecipientsInsert,+ TAlarmChannelRecipientsUpdate,TAlarmChannels,TAlarmChannelsInsert,TAlarmChannelsUpdate,@@ -50,9 +56,6 @@ import {TAlarmHistoryTargetInsert,TAlarmHistoryTargetUpdate,TAlarmHistoryUpdate,- TAlarmRecipients,- TAlarmRecipientsInsert,- TAlarmRecipientsUpdate,TAlarms,TAlarmsInsert,TAlarmsUpdate,@@ -1575,16 +1578,21 @@ declare module "knex/types/tables" {TResourceMetadataUpdate>;[TableName.Alarm]: KnexOriginal.CompositeTableType<TAlarms, TAlarmsInsert, TAlarmsUpdate>;- [TableName.AlarmRecipient]: KnexOriginal.CompositeTableType<- TAlarmRecipients,- TAlarmRecipientsInsert,- TAlarmRecipientsUpdate- >;[TableName.AlarmChannel]: KnexOriginal.CompositeTableType<TAlarmChannels,TAlarmChannelsInsert,TAlarmChannelsUpdate>;+ [TableName.AlarmChannelRecipient]: KnexOriginal.CompositeTableType<+ TAlarmChannelRecipients,+ TAlarmChannelRecipientsInsert,+ TAlarmChannelRecipientsUpdate+ >;+ [TableName.AlarmChannelMembership]: KnexOriginal.CompositeTableType<+ TAlarmChannelMemberships,+ TAlarmChannelMembershipsInsert,+ TAlarmChannelMembershipsUpdate+ >;[TableName.AlarmHistory]: KnexOriginal.CompositeTableType<TAlarmHistory, TAlarmHistoryInsert, TAlarmHistoryUpdate>;[TableName.AlarmHistoryTarget]: KnexOriginal.CompositeTableType<TAlarmHistoryTarget,diff --git a/backend/src/db/migrations/20260714120000_add-alarms.ts b/backend/src/db/migrations/20260714120000_add-alarms.tsindex cc902d2638..b61d7dcef3 100644--- a/backend/src/db/migrations/20260714120000_add-alarms.ts+++ b/backend/src/db/migrations/20260714120000_add-alarms.ts@@ -29,31 +29,60 @@ export async function up(knex: Knex): Promise<void> {});}- if (!(await knex.schema.hasTable(TableName.AlarmRecipient))) {- await knex.schema.createTable(TableName.AlarmRecipient, (t) => {+ // Channels are standalone, reusable delivery destinations scoped to an org (projectId null) or a+ // project. Alarms reference them through alarm_channel_memberships, so editing a channel's config+ // (including clearing an optional secret) is a first-class operation independent of any alarm.+ if (!(await knex.schema.hasTable(TableName.AlarmChannel))) {+ await knex.schema.createTable(TableName.AlarmChannel, (t) => {t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());- t.uuid("alarmId").notNullable();+ t.string("name").notNullable();+ t.string("channelType").notNullable();+ t.binary("encryptedConfig").notNullable();+ t.boolean("enabled").notNullable().defaultTo(true);+ t.uuid("orgId").notNullable();+ t.string("projectId").nullable();+ t.uuid("createdByUserId").nullable();+ t.timestamps(true, true, true);++ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");+ t.foreign("createdByUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");+ t.index("orgId");+ t.index("projectId");+ t.index("createdByUserId");+ });+ }++ // Recipients belong to the channel (directed channels such as Email), so a shared channel is+ // self-contained and every alarm that references it notifies the same list.+ if (!(await knex.schema.hasTable(TableName.AlarmChannelRecipient))) {+ await knex.schema.createTable(TableName.AlarmChannelRecipient, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("channelId").notNullable();t.string("principalType").notNullable();t.string("principalId").notNullable();t.timestamps(true, true, true);- t.foreign("alarmId").references("id").inTable(TableName.Alarm).onDelete("CASCADE");- t.index("alarmId");- t.unique(["alarmId", "principalType", "principalId"]);+ t.foreign("channelId").references("id").inTable(TableName.AlarmChannel).onDelete("CASCADE");+ t.index("channelId");+ t.unique(["channelId", "principalType", "principalId"]);});}- if (!(await knex.schema.hasTable(TableName.AlarmChannel))) {- await knex.schema.createTable(TableName.AlarmChannel, (t) => {+ // Many-to-many between alarms and channels. The count of rows for a channel powers the "used by N+ // alarms" column in the UI.+ if (!(await knex.schema.hasTable(TableName.AlarmChannelMembership))) {+ await knex.schema.createTable(TableName.AlarmChannelMembership, (t) => {t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());t.uuid("alarmId").notNullable();- t.string("channelType").notNullable();- t.binary("encryptedConfig").notNullable();- t.boolean("enabled").notNullable().defaultTo(true);+ t.uuid("channelId").notNullable();t.timestamps(true, true, true);t.foreign("alarmId").references("id").inTable(TableName.Alarm).onDelete("CASCADE");+ t.foreign("channelId").references("id").inTable(TableName.AlarmChannel).onDelete("CASCADE");t.index("alarmId");+ t.index("channelId");+ t.unique(["alarmId", "channelId"]);});}@@ -105,12 +134,15 @@ export async function down(knex: Knex): Promise<void> {if (await knex.schema.hasTable(TableName.AlarmHistory)) {await knex.schema.dropTable(TableName.AlarmHistory);}+ if (await knex.schema.hasTable(TableName.AlarmChannelMembership)) {+ await knex.schema.dropTable(TableName.AlarmChannelMembership);+ }+ if (await knex.schema.hasTable(TableName.AlarmChannelRecipient)) {+ await knex.schema.dropTable(TableName.AlarmChannelRecipient);+ }if (await knex.schema.hasTable(TableName.AlarmChannel)) {await knex.schema.dropTable(TableName.AlarmChannel);}- if (await knex.schema.hasTable(TableName.AlarmRecipient)) {- await knex.schema.dropTable(TableName.AlarmRecipient);- }if (await knex.schema.hasTable(TableName.Alarm)) {await knex.schema.dropTable(TableName.Alarm);}diff --git a/backend/src/db/schemas/alarm-channel-memberships.ts b/backend/src/db/schemas/alarm-channel-memberships.tsnew file mode 100644index 0000000000..d63ae5bb7f--- /dev/null+++ b/backend/src/db/schemas/alarm-channel-memberships.ts@@ -0,0 +1,22 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const AlarmChannelMembershipsSchema = z.object({+ id: z.string().uuid(),+ alarmId: z.string().uuid(),+ channelId: z.string().uuid(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAlarmChannelMemberships = z.infer<typeof AlarmChannelMembershipsSchema>;+export type TAlarmChannelMembershipsInsert = Omit<z.input<typeof AlarmChannelMembershipsSchema>, TImmutableDBKeys>;+export type TAlarmChannelMembershipsUpdate = Partial<+ Omit<z.input<typeof AlarmChannelMembershipsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/alarm-channel-recipients.ts b/backend/src/db/schemas/alarm-channel-recipients.tsnew file mode 100644index 0000000000..bbb53928b9--- /dev/null+++ b/backend/src/db/schemas/alarm-channel-recipients.ts@@ -0,0 +1,23 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const AlarmChannelRecipientsSchema = z.object({+ id: z.string().uuid(),+ channelId: z.string().uuid(),+ principalType: z.string(),+ principalId: z.string(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAlarmChannelRecipients = z.infer<typeof AlarmChannelRecipientsSchema>;+export type TAlarmChannelRecipientsInsert = Omit<z.input<typeof AlarmChannelRecipientsSchema>, TImmutableDBKeys>;+export type TAlarmChannelRecipientsUpdate = Partial<+ Omit<z.input<typeof AlarmChannelRecipientsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/alarm-channels.ts b/backend/src/db/schemas/alarm-channels.tsindex b824d14e84..0122fcbd32 100644--- a/backend/src/db/schemas/alarm-channels.ts+++ b/backend/src/db/schemas/alarm-channels.ts@@ -11,10 +11,13 @@ import { TImmutableDBKeys } from "./models";export const AlarmChannelsSchema = z.object({id: z.string().uuid(),- alarmId: z.string().uuid(),+ name: z.string(),channelType: z.string(),encryptedConfig: zodBuffer,enabled: z.boolean().default(true),+ orgId: z.string().uuid(),+ projectId: z.string().nullable().optional(),+ createdByUserId: z.string().uuid().nullable().optional(),createdAt: z.date(),updatedAt: z.date()});diff --git a/backend/src/db/schemas/alarm-recipients.ts b/backend/src/db/schemas/alarm-recipients.tsdeleted file mode 100644index 2b90ddefdf..0000000000--- a/backend/src/db/schemas/alarm-recipients.ts+++ /dev/null@@ -1,21 +0,0 @@-// Code generated by automation script, DO NOT EDIT.-// Automated by pulling database and generating zod schema-// To update. Just run npm run generate:schema-// Written by akhilmhdh.--import { z } from "zod";--import { TImmutableDBKeys } from "./models";--export const AlarmRecipientsSchema = z.object({- id: z.string().uuid(),- alarmId: z.string().uuid(),- principalType: z.string(),- principalId: z.string(),- createdAt: z.date(),- updatedAt: z.date()-});--export type TAlarmRecipients = z.infer<typeof AlarmRecipientsSchema>;-export type TAlarmRecipientsInsert = Omit<z.input<typeof AlarmRecipientsSchema>, TImmutableDBKeys>;-export type TAlarmRecipientsUpdate = Partial<Omit<z.input<typeof AlarmRecipientsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex eeb17be853..254570843a 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -11,10 +11,11 @@ export * from "./ai-mcp-endpoints";export * from "./ai-mcp-server-tools";export * from "./ai-mcp-server-user-credentials";export * from "./ai-mcp-servers";+export * from "./alarm-channel-memberships";+export * from "./alarm-channel-recipients";export * from "./alarm-channels";export * from "./alarm-history";export * from "./alarm-history-target";-export * from "./alarm-recipients";export * from "./alarms";export * from "./app-connection-credential-rotations";export * from "./app-connections";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 8bd281da43..b54ad422b9 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -45,8 +45,9 @@ export enum TableName {PkiCollection = "pki_collections",PkiCollectionItem = "pki_collection_items",Alarm = "alarms",- AlarmRecipient = "alarm_recipients",AlarmChannel = "alarm_channels",+ AlarmChannelRecipient = "alarm_channel_recipients",+ AlarmChannelMembership = "alarm_channel_memberships",AlarmHistory = "alarm_history",AlarmHistoryTarget = "alarm_history_target",Groups = "groups",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 9f984806bb..02850e2daa 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -237,12 +237,14 @@ import { accountRecoveryServiceFactory } from "@app/services/account-recovery/acimport { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";import { additionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";import { alarmChannelDALFactory } from "@app/services/alarm/alarm-channel-dal";+import { alarmChannelMembershipDALFactory } from "@app/services/alarm/alarm-channel-membership-dal";+import { alarmChannelRecipientDALFactory } from "@app/services/alarm/alarm-channel-recipient-dal";+import { alarmChannelServiceFactory } from "@app/services/alarm/alarm-channel-service";import { alarmDALFactory } from "@app/services/alarm/alarm-dal";import { alarmEngineFactory } from "@app/services/alarm/alarm-engine";import { alarmHistoryDALFactory } from "@app/services/alarm/alarm-history-dal";import { alarmProviderRegistryFactory } from "@app/services/alarm/alarm-provider-registry";import { alarmQueueServiceFactory } from "@app/services/alarm/alarm-queue";-import { alarmRecipientDALFactory } from "@app/services/alarm/alarm-recipient-dal";import { alarmRecipientResolverFactory } from "@app/services/alarm/alarm-recipient-resolver";import { alarmServiceFactory } from "@app/services/alarm/alarm-service";import { identityCredentialAlarmDALFactory } from "@app/services/alarm/providers/identity-credential-alarm-dal";@@ -1012,7 +1014,8 @@ export const registerRoutes = async (const alarmDAL = alarmDALFactory(db);const alarmChannelDAL = alarmChannelDALFactory(db);- const alarmRecipientDAL = alarmRecipientDALFactory(db);+ const alarmChannelRecipientDAL = alarmChannelRecipientDALFactory(db);+ const alarmChannelMembershipDAL = alarmChannelMembershipDALFactory(db);const alarmHistoryDAL = alarmHistoryDALFactory(db);const alarmProviderRegistry = alarmProviderRegistryFactory();alarmProviderRegistry.register(@@ -1024,7 +1027,7 @@ export const registerRoutes = async (const alarmRecipientResolver = alarmRecipientResolverFactory({ userDAL, userGroupMembershipDAL });const alarmEngine = alarmEngineFactory({alarmChannelDAL,- alarmRecipientDAL,+ alarmChannelRecipientDAL,alarmHistoryDAL,alarmProviderRegistry,alarmRecipientResolver,@@ -1043,9 +1046,15 @@ export const registerRoutes = async (const alarmService = alarmServiceFactory({alarmDAL,alarmChannelDAL,- alarmRecipientDAL,- alarmProviderRegistry,+ alarmChannelMembershipDAL,+ alarmProviderRegistry+ });+ const alarmChannelService = alarmChannelServiceFactory({+ alarmChannelDAL,+ alarmChannelRecipientDAL,+ alarmChannelMembershipDAL,kmsService,+ permissionService,orgDAL,projectDAL,groupDAL@@ -4089,6 +4098,7 @@ export const registerRoutes = async (projectEventsSSE: projectEventsSSEService,notification: notificationService,alarm: alarmService,+ alarmChannel: alarmChannelService,announcement: announcementService,mfaSession: mfaSessionService,membershipUser: membershipUserService,diff --git a/backend/src/server/routes/v1/alarm-channel-router.ts b/backend/src/server/routes/v1/alarm-channel-router.tsnew file mode 100644index 0000000000..5f1229de43--- /dev/null+++ b/backend/src/server/routes/v1/alarm-channel-router.ts@@ -0,0 +1,153 @@+import { z } from "zod";++import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AlarmChannelType } from "@app/services/alarm/alarm-channel-types";+import { AlarmPrincipalType } from "@app/services/alarm/alarm-types";+import { AuthMode } from "@app/services/auth/auth-type";++const RecipientInputSchema = z.object({+ principalType: z.nativeEnum(AlarmPrincipalType),+ principalId: z.string().min(1)+});++const ChannelResponseSchema = z.object({+ id: z.string().uuid(),+ name: z.string(),+ channelType: z.string(),+ directed: z.boolean(),+ config: z.record(z.unknown()),+ enabled: z.boolean(),+ recipients: z.array(z.object({ principalType: z.string(), principalId: z.string() })),+ usageCount: z.number(),+ orgId: z.string(),+ projectId: z.string().nullable(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export const registerAlarmChannelRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "createAlarmChannel",+ body: z.object({+ name: z.string().min(1).max(255),+ channelType: z.nativeEnum(AlarmChannelType),+ config: z.record(z.unknown()).default({}),+ enabled: z.boolean().optional(),+ recipients: z.array(RecipientInputSchema).optional(),+ projectId: z.string().nullable().optional()+ }),+ response: { 200: z.object({ channel: ChannelResponseSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const channel = await server.services.alarmChannel.createChannel({+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ return { channel };+ }+ });++ server.route({+ method: "GET",+ url: "/",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "listAlarmChannels",+ querystring: z.object({ projectId: z.string().optional() }),+ response: { 200: z.object({ channels: ChannelResponseSchema.array() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const channels = await server.services.alarmChannel.listChannels({+ ...req.query,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ return { channels };+ }+ });++ server.route({+ method: "GET",+ url: "/:channelId",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getAlarmChannelById",+ params: z.object({ channelId: z.string().uuid() }),+ response: { 200: z.object({ channel: ChannelResponseSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const channel = await server.services.alarmChannel.getChannelById({+ channelId: req.params.channelId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ return { channel };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:channelId",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "updateAlarmChannel",+ params: z.object({ channelId: z.string().uuid() }),+ body: z.object({+ name: z.string().min(1).max(255).optional(),+ config: z.record(z.unknown()).optional(),+ enabled: z.boolean().optional(),+ recipients: z.array(RecipientInputSchema).optional()+ }),+ response: { 200: z.object({ channel: ChannelResponseSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const channel = await server.services.alarmChannel.updateChannel({+ channelId: req.params.channelId,+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ return { channel };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:channelId",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "deleteAlarmChannel",+ params: z.object({ channelId: z.string().uuid() }),+ response: { 200: z.object({ channel: z.object({ id: z.string().uuid() }) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const channel = await server.services.alarmChannel.deleteChannel({+ channelId: req.params.channelId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ return { channel };+ }+ });+};diff --git a/backend/src/server/routes/v1/alarm-router.ts b/backend/src/server/routes/v1/alarm-router.tsindex 5ff1a42820..6aa68fb786 100644--- a/backend/src/server/routes/v1/alarm-router.ts+++ b/backend/src/server/routes/v1/alarm-router.ts@@ -2,22 +2,8 @@ import { z } from "zod";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { AlarmChannelType } from "@app/services/alarm/alarm-channel-types";-import { AlarmPrincipalType } from "@app/services/alarm/alarm-types";import { AuthMode } from "@app/services/auth/auth-type";-const RecipientInputSchema = z.object({- principalType: z.nativeEnum(AlarmPrincipalType),- principalId: z.string().min(1)-});--const ChannelInputSchema = z.object({- id: z.string().uuid().optional(),- channelType: z.nativeEnum(AlarmChannelType),- config: z.record(z.unknown()).default({}),- enabled: z.boolean().optional()-});-const AlarmResponseSchema = z.object({id: z.string().uuid(),name: z.string(),@@ -30,15 +16,13 @@ const AlarmResponseSchema = z.object({enabled: z.boolean(),orgId: z.string(),projectId: z.string().nullable(),- recipients: z.array(z.object({ principalType: z.string(), principalId: z.string() })),channels: z.array(z.object({id: z.string().uuid(),+ name: z.string(),channelType: z.string(),- config: z.record(z.unknown()),- enabled: z.boolean(),- createdAt: z.date(),- updatedAt: z.date()+ directed: z.boolean(),+ enabled: z.boolean()})),createdAt: z.date(),@@ -62,8 +46,7 @@ export const registerAlarmRouter = async (server: FastifyZodProvider) => {filters: z.unknown().optional(),enabled: z.boolean().optional(),projectId: z.string().nullable().optional(),- recipients: z.array(RecipientInputSchema).default([]),- channels: z.array(ChannelInputSchema).min(1)+ channelIds: z.array(z.string().uuid()).min(1)}),response: { 200: z.object({ alarm: AlarmResponseSchema }) }},@@ -145,8 +128,7 @@ export const registerAlarmRouter = async (server: FastifyZodProvider) => {condition: z.unknown().optional(),filters: z.unknown().optional(),enabled: z.boolean().optional(),- recipients: z.array(RecipientInputSchema).optional(),- channels: z.array(ChannelInputSchema).min(1).optional()+ channelIds: z.array(z.string().uuid()).min(1).optional()}),response: { 200: z.object({ alarm: AlarmResponseSchema }) }},diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex 95b19c7d23..3989c45b95 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -11,6 +11,7 @@ import { registerSecretSyncRouter, SECRET_SYNC_REGISTER_ROUTER_MAP } from "@app/import { registerAccountRecoveryRouter } from "./account-recovery-router";import { registerAdminRouter } from "./admin-router";+import { registerAlarmChannelRouter } from "./alarm-channel-router";import { registerAlarmRouter } from "./alarm-router";import { registerAnnouncementRouter } from "./announcement-router";import { APPROVAL_POLICY_REGISTER_ROUTER_MAP } from "./approval-policy-routers";@@ -140,6 +141,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {await server.register(registerUserRouter, { prefix: "/user" });await server.register(registerNotificationRouter, { prefix: "/notifications" });await server.register(registerAlarmRouter, { prefix: "/alarms" });+ await server.register(registerAlarmChannelRouter, { prefix: "/alarm-channels" });await server.register(registerAnnouncementRouter, { prefix: "/announcement" });await server.register(registerInviteOrgRouter, { prefix: "/invite-org" });await server.register(registerUserActionRouter, { prefix: "/user-action" });diff --git a/backend/src/services/alarm/alarm-channel-dal.ts b/backend/src/services/alarm/alarm-channel-dal.tsindex c281712223..9669d0a279 100644--- a/backend/src/services/alarm/alarm-channel-dal.ts+++ b/backend/src/services/alarm/alarm-channel-dal.ts@@ -7,13 +7,97 @@ import { ormify, selectAllTableCols } from "@app/lib/knex";export type TAlarmChannelDALFactory = ReturnType<typeof alarmChannelDALFactory>;+export type TAlarmChannelWithUsage = TAlarmChannels & { usageCount: number };+export type TAlarmChannelWithAlarmId = TAlarmChannels & { alarmId: string };+export const alarmChannelDALFactory = (db: TDbClient) => {const alarmChannelOrm = ormify(db, TableName.AlarmChannel);+ const scopeFilter = (query: Knex.QueryBuilder, orgId: string, projectId?: string | null): void => {+ void query.where(`${TableName.AlarmChannel}.orgId`, orgId);+ if (projectId) void query.where(`${TableName.AlarmChannel}.projectId`, projectId);+ else void query.whereNull(`${TableName.AlarmChannel}.projectId`);+ };++ const findWithUsageByScope = async (+ { orgId, projectId }: { orgId: string; projectId?: string | null },+ tx?: Knex+ ): Promise<TAlarmChannelWithUsage[]> => {+ try {+ const query = (tx || db.replicaNode())(TableName.AlarmChannel).leftJoin(+ TableName.AlarmChannelMembership,+ `${TableName.AlarmChannel}.id`,+ `${TableName.AlarmChannelMembership}.channelId`+ );+ scopeFilter(query, orgId, projectId);++ const rows = await query+ .groupBy(`${TableName.AlarmChannel}.id`)+ .select(selectAllTableCols(TableName.AlarmChannel))+ .select(db.raw(`count(??.??)::int as "usageCount"`, [TableName.AlarmChannelMembership, "id"]))+ .orderBy(`${TableName.AlarmChannel}.createdAt`, "asc");++ return rows as unknown as TAlarmChannelWithUsage[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindWithUsageByScope" });+ }+ };++ const findByIdInScope = async (+ id: string,+ { orgId, projectId }: { orgId: string; projectId?: string | null },+ tx?: Knex+ ): Promise<TAlarmChannels | undefined> => {+ try {+ const query = (tx || db.replicaNode())(TableName.AlarmChannel).where(`${TableName.AlarmChannel}.id`, id);+ scopeFilter(query, orgId, projectId);+ const channel = await query.select(selectAllTableCols(TableName.AlarmChannel)).first();+ return channel as TAlarmChannels | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByIdInScope" });+ }+ };++ const findByIdsInScope = async (+ ids: string[],+ { orgId, projectId }: { orgId: string; projectId?: string | null },+ tx?: Knex+ ): Promise<TAlarmChannels[]> => {+ try {+ if (!ids.length) return [];+ const query = (tx || db.replicaNode())(TableName.AlarmChannel).whereIn(`${TableName.AlarmChannel}.id`, ids);+ scopeFilter(query, orgId, projectId);+ const channels = await query.select(selectAllTableCols(TableName.AlarmChannel));+ return channels as TAlarmChannels[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByIdsInScope" });+ }+ };++ const findByNameInScope = async (+ name: string,+ { orgId, projectId }: { orgId: string; projectId?: string | null },+ tx?: Knex+ ): Promise<TAlarmChannels | undefined> => {+ try {+ const query = (tx || db.replicaNode())(TableName.AlarmChannel).where(`${TableName.AlarmChannel}.name`, name);+ scopeFilter(query, orgId, projectId);+ const channel = await query.select(selectAllTableCols(TableName.AlarmChannel)).first();+ return channel as TAlarmChannels | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByNameInScope" });+ }+ };+const findByAlarmId = async (alarmId: string, tx?: Knex): Promise<TAlarmChannels[]> => {try {const channels = await (tx || db.replicaNode())(TableName.AlarmChannel)- .where(`${TableName.AlarmChannel}.alarmId`, alarmId)+ .join(+ TableName.AlarmChannelMembership,+ `${TableName.AlarmChannel}.id`,+ `${TableName.AlarmChannelMembership}.channelId`+ )+ .where(`${TableName.AlarmChannelMembership}.alarmId`, alarmId).select(selectAllTableCols(TableName.AlarmChannel)).orderBy(`${TableName.AlarmChannel}.createdAt`, "asc");@@ -23,15 +107,22 @@ export const alarmChannelDALFactory = (db: TDbClient) => {}};- const findByAlarmIds = async (alarmIds: string[], tx?: Knex): Promise<TAlarmChannels[]> => {+ // Returns each attached channel tagged with the alarmId it is attached to, for batched list responses.+ const findByAlarmIds = async (alarmIds: string[], tx?: Knex): Promise<TAlarmChannelWithAlarmId[]> => {try {if (!alarmIds.length) return [];const channels = await (tx || db.replicaNode())(TableName.AlarmChannel)- .whereIn(`${TableName.AlarmChannel}.alarmId`, alarmIds)+ .join(+ TableName.AlarmChannelMembership,+ `${TableName.AlarmChannel}.id`,+ `${TableName.AlarmChannelMembership}.channelId`+ )+ .whereIn(`${TableName.AlarmChannelMembership}.alarmId`, alarmIds).select(selectAllTableCols(TableName.AlarmChannel))+ .select(db.ref("alarmId").withSchema(TableName.AlarmChannelMembership).as("alarmId")).orderBy(`${TableName.AlarmChannel}.createdAt`, "asc");- return channels as TAlarmChannels[];+ return channels as unknown as TAlarmChannelWithAlarmId[];} catch (error) {throw new DatabaseError({ error, name: "FindByAlarmIds" });}@@ -39,6 +130,10 @@ export const alarmChannelDALFactory = (db: TDbClient) => {return {...alarmChannelOrm,+ findWithUsageByScope,+ findByIdInScope,+ findByIdsInScope,+ findByNameInScope,findByAlarmId,findByAlarmIds};diff --git a/backend/src/services/alarm/alarm-channel-membership-dal.ts b/backend/src/services/alarm/alarm-channel-membership-dal.tsnew file mode 100644index 0000000000..3b3f11c17d--- /dev/null+++ b/backend/src/services/alarm/alarm-channel-membership-dal.ts@@ -0,0 +1,40 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAlarmChannelMemberships } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, selectAllTableCols } from "@app/lib/knex";++export type TAlarmChannelMembershipDALFactory = ReturnType<typeof alarmChannelMembershipDALFactory>;++export const alarmChannelMembershipDALFactory = (db: TDbClient) => {+ const alarmChannelMembershipOrm = ormify(db, TableName.AlarmChannelMembership);++ const findByAlarmId = async (alarmId: string, tx?: Knex): Promise<TAlarmChannelMemberships[]> => {+ try {+ const memberships = await (tx || db.replicaNode())(TableName.AlarmChannelMembership)+ .where(`${TableName.AlarmChannelMembership}.alarmId`, alarmId)+ .select(selectAllTableCols(TableName.AlarmChannelMembership));++ return memberships as TAlarmChannelMemberships[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByAlarmId" });+ }+ };++ const deleteByAlarmId = async (alarmId: string, tx?: Knex): Promise<number> => {+ try {+ return await (tx || db)(TableName.AlarmChannelMembership)+ .where(`${TableName.AlarmChannelMembership}.alarmId`, alarmId)+ .del();+ } catch (error) {+ throw new DatabaseError({ error, name: "DeleteByAlarmId" });+ }+ };++ return {+ ...alarmChannelMembershipOrm,+ findByAlarmId,+ deleteByAlarmId+ };+};diff --git a/backend/src/services/alarm/alarm-channel-recipient-dal.ts b/backend/src/services/alarm/alarm-channel-recipient-dal.tsnew file mode 100644index 0000000000..243c24fb41--- /dev/null+++ b/backend/src/services/alarm/alarm-channel-recipient-dal.ts@@ -0,0 +1,54 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAlarmChannelRecipients } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, selectAllTableCols } from "@app/lib/knex";++export type TAlarmChannelRecipientDALFactory = ReturnType<typeof alarmChannelRecipientDALFactory>;++export const alarmChannelRecipientDALFactory = (db: TDbClient) => {+ const alarmChannelRecipientOrm = ormify(db, TableName.AlarmChannelRecipient);++ const findByChannelId = async (channelId: string, tx?: Knex): Promise<TAlarmChannelRecipients[]> => {+ try {+ const recipients = await (tx || db.replicaNode())(TableName.AlarmChannelRecipient)+ .where(`${TableName.AlarmChannelRecipient}.channelId`, channelId)+ .select(selectAllTableCols(TableName.AlarmChannelRecipient));++ return recipients as TAlarmChannelRecipients[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByChannelId" });+ }+ };++ const findByChannelIds = async (channelIds: string[], tx?: Knex): Promise<TAlarmChannelRecipients[]> => {+ try {+ if (!channelIds.length) return [];+ const recipients = await (tx || db.replicaNode())(TableName.AlarmChannelRecipient)+ .whereIn(`${TableName.AlarmChannelRecipient}.channelId`, channelIds)+ .select(selectAllTableCols(TableName.AlarmChannelRecipient));++ return recipients as TAlarmChannelRecipients[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByChannelIds" });+ }+ };++ const deleteByChannelId = async (channelId: string, tx?: Knex): Promise<number> => {+ try {+ return await (tx || db)(TableName.AlarmChannelRecipient)+ .where(`${TableName.AlarmChannelRecipient}.channelId`, channelId)+ .del();+ } catch (error) {+ throw new DatabaseError({ error, name: "DeleteByChannelId" });+ }+ };++ return {+ ...alarmChannelRecipientOrm,+ findByChannelId,+ findByChannelIds,+ deleteByChannelId+ };+};diff --git a/backend/src/services/alarm/alarm-channel-service-types.ts b/backend/src/services/alarm/alarm-channel-service-types.tsnew file mode 100644index 0000000000..51467f6e36--- /dev/null+++ b/backend/src/services/alarm/alarm-channel-service-types.ts@@ -0,0 +1,58 @@+import { TGenericPermission } from "@app/lib/types";++import { AlarmChannelType } from "./alarm-channel-types";+import { AlarmPrincipalType } from "./alarm-types";++export type TChannelRecipientInput = {+ principalType: AlarmPrincipalType;+ principalId: string;+};++export type TCreateAlarmChannelDTO = TGenericPermission & {+ name: string;+ channelType: AlarmChannelType;+ config: Record<string, unknown>;+ enabled?: boolean;+ recipients?: TChannelRecipientInput[];+ projectId?: string | null;+};++export type TUpdateAlarmChannelDTO = TGenericPermission & {+ channelId: string;+ name?: string;+ config?: Record<string, unknown>;+ enabled?: boolean;+ recipients?: TChannelRecipientInput[];+};++export type TDeleteAlarmChannelDTO = TGenericPermission & { channelId: string };++export type TGetAlarmChannelDTO = TGenericPermission & { channelId: string };++export type TListAlarmChannelsDTO = TGenericPermission & { projectId?: string | null };++export type TAlarmChannelDetail = {+ id: string;+ name: string;+ channelType: string;+ directed: boolean;+ config: Record<string, unknown>;+ enabled: boolean;+ recipients: { principalType: string; principalId: string }[];+ usageCount: number;+ orgId: string;+ projectId: string | null;+ createdAt: Date;+ updatedAt: Date;+};++// Lightweight reference embedded in an alarm response (the alarm no longer owns config/recipients).+export type TAlarmChannelSummary = {+ id: string;+ name: string;+ channelType: string;+ directed: boolean;+ enabled: boolean;+};++export type { AlarmChannelType };diff --git a/backend/src/services/alarm/alarm-channel-service.test.ts b/backend/src/services/alarm/alarm-channel-service.test.tsnew file mode 100644index 0000000000..e2b3103db4--- /dev/null+++ b/backend/src/services/alarm/alarm-channel-service.test.ts@@ -0,0 +1,322 @@+import { createMongoAbility } from "@casl/ability";++import { alarmChannelServiceFactory, TAlarmChannelServiceFactoryDep } from "./alarm-channel-service";+import { AlarmChannelType } from "./alarm-channel-types";+import { AlarmPrincipalType } from "./alarm-types";++// Identity cipher: encryptedConfig is just JSON bytes of the config.+const kmsServiceMock = {+ createCipherPairWithDataKey: async () => ({+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob+ })+};+const encConfig = (config: unknown) => Buffer.from(JSON.stringify(config));++type TRow = {+ id: string;+ name: string;+ channelType: AlarmChannelType;+ encryptedConfig: Buffer;+ enabled: boolean;+ orgId: string;+ projectId: string | null;+ createdByUserId: string | null;+ createdAt: Date;+ updatedAt: Date;+};++const actor = {+ actor: "user" as never,+ actorId: "user-1",+ actorAuthMethod: null as never,+ actorOrgId: "org-1"+};++const buildService = (opts?: { seed?: TRow[]; allow?: boolean }) => {+ const store = new Map<string, TRow>();+ (opts?.seed ?? []).forEach((r) => store.set(r.id, r));+ const recipients = new Map<string, Array<{ channelId: string; principalType: string; principalId: string }>>();+ const memberships = new Map<string, number>(); // channelId -> usage count+ let counter = 0;++ const ability = () =>+ createMongoAbility(+ opts?.allow === false ? [] : [{ action: ["read", "create", "edit", "delete"], subject: "settings" }]+ );++ const service = alarmChannelServiceFactory({+ alarmChannelDAL: {+ transaction: async (cb: (tx: unknown) => unknown) => cb({}),+ create: async (data: Record<string, unknown>) => {+ counter += 1;+ const row = {+ id: `ch-${counter}`,+ enabled: true,+ projectId: null,+ createdByUserId: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ ...data+ } as TRow;+ store.set(row.id, row);+ return row;+ },+ findById: async (id: string) => store.get(id),+ updateById: async (id: string, data: Record<string, unknown>) => {+ store.set(id, { ...(store.get(id) as TRow), ...data, updatedAt: new Date() });+ return store.get(id);+ },+ deleteById: async (id: string) => {+ store.delete(id);+ return { id };+ },+ findByNameInScope: async (name: string, scope: { orgId: string; projectId?: string | null }) =>+ [...store.values()].find(+ (r) => r.name === name && r.orgId === scope.orgId && (r.projectId ?? null) === (scope.projectId ?? null)+ ),+ findWithUsageByScope: async (scope: { orgId: string; projectId?: string | null }) =>+ [...store.values()]+ .filter((r) => r.orgId === scope.orgId && (r.projectId ?? null) === (scope.projectId ?? null))+ .map((r) => ({ ...r, usageCount: memberships.get(r.id) ?? 0 }))+ },+ alarmChannelRecipientDAL: {+ insertMany: async (data: Array<{ channelId: string; principalType: string; principalId: string }>) => {+ data.forEach((r) => recipients.set(r.channelId, [...(recipients.get(r.channelId) ?? []), r]));+ return data;+ },+ findByChannelId: async (channelId: string) => recipients.get(channelId) ?? [],+ findByChannelIds: async (ids: string[]) => ids.flatMap((id) => recipients.get(id) ?? []),+ deleteByChannelId: async (channelId: string) => {+ recipients.delete(channelId);+ return 0;+ }+ },+ alarmChannelMembershipDAL: {+ find: async ({ channelId }: { channelId: string }) =>+ Array.from({ length: memberships.get(channelId) ?? 0 }, (_, i) => ({ id: `m${i}` }))+ },+ kmsService: kmsServiceMock,+ permissionService: {+ getOrgPermission: async () => ({ permission: ability() }),+ getProjectPermission: async () => ({ permission: ability() })+ },+ orgDAL: {+ findMembership: async (filter: { $in?: { actorUserId?: string[] } }) =>+ (filter.$in?.actorUserId ?? []).map((actorUserId) => ({ actorUserId }))+ },+ projectDAL: {+ findEffectiveProjectSubjectsMembership: async ({+ userIds,+ groupIds+ }: {+ userIds: string[];+ groupIds: string[];+ }) => ({+ effectiveUserIds: userIds,+ effectiveGroupIds: groupIds+ })+ },+ groupDAL: { find: async (filter: { $in?: { id?: string[] } }) => (filter.$in?.id ?? []).map((id) => ({ id })) }+ } as unknown as TAlarmChannelServiceFactoryDep);++ return { service, store, recipients, memberships };+};++const seedRow = (+ over: Partial<TRow> & { id: string; channelType: AlarmChannelType; encryptedConfig: Buffer }+): TRow => ({+ name: over.id,+ enabled: true,+ orgId: "org-1",+ projectId: null,+ createdByUserId: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ ...over+});++describe("alarm channel service", () => {+ test("creates a webhook channel, stores config, and reports zero usage", async () => {+ const { service, store } = buildService();+ const channel = await service.createChannel({+ name: "Ops webhook",+ channelType: AlarmChannelType.WEBHOOK,+ config: { url: "https://example.com/hook", signingSecret: "s3cr3t" },+ ...actor+ });++ expect(channel.name).toBe("Ops webhook");+ expect(channel.usageCount).toBe(0);+ // Secret is redacted on the way out.+ expect(channel.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });+ expect(store.get(channel.id)).toBeDefined();+ });++ test("requires recipients for a directed (email) channel and rejects them for others", async () => {+ const { service } = buildService();+ await expect(+ service.createChannel({ name: "Team email", channelType: AlarmChannelType.EMAIL, config: {}, ...actor })+ ).rejects.toThrow("require at least one recipient");++ await expect(+ service.createChannel({+ name: "Ops webhook",+ channelType: AlarmChannelType.WEBHOOK,+ config: { url: "https://example.com/hook" },+ recipients: [{ principalType: AlarmPrincipalType.USER, principalId: "user-1" }],+ ...actor+ })+ ).rejects.toThrow("do not take recipients");+ });++ test("creates a directed email channel with recipients", async () => {+ const { service, recipients } = buildService();+ const channel = await service.createChannel({+ name: "Team email",+ channelType: AlarmChannelType.EMAIL,+ config: {},+ recipients: [{ principalType: AlarmPrincipalType.USER, principalId: "user-1" }],+ ...actor+ });+ expect(channel.directed).toBe(true);+ expect(channel.recipients).toEqual([{ principalType: "user", principalId: "user-1" }]);+ expect(recipients.get(channel.id)).toHaveLength(1);+ });++ test("rejects a duplicate channel name in the same scope", async () => {+ const { service } = buildService({+ seed: [+ seedRow({+ id: "ch-x",+ name: "dupe",+ channelType: AlarmChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com" })+ })+ ]+ });+ await expect(+ service.createChannel({+ name: "dupe",+ channelType: AlarmChannelType.WEBHOOK,+ config: { url: "https://example.com/hook" },+ ...actor+ })+ ).rejects.toThrow(/already exists/);+ });++ test("keeps an omitted secret on update", async () => {+ const { service } = buildService({+ seed: [+ seedRow({+ id: "ch-1",+ channelType: AlarmChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" })+ })+ ]+ });++ // Config sent without signingSecret -> keep the existing one.+ const updated = await service.updateChannel({+ channelId: "ch-1",+ config: { url: "https://example.com/hook" },+ ...actor+ });+ expect(updated.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });+ });++ test("clears an optional secret when explicitly emptied on update (fixes #2)", async () => {+ const { service, store } = buildService({+ seed: [+ seedRow({+ id: "ch-1",+ channelType: AlarmChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" })+ })+ ]+ });++ const updated = await service.updateChannel({+ channelId: "ch-1",+ config: { url: "https://example.com/hook", signingSecret: "" },+ ...actor+ });++ expect(updated.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: false });+ // And it is actually gone from the stored ciphertext, not just hidden.+ const stored = JSON.parse(store.get("ch-1")!.encryptedConfig.toString()) as Record<string, unknown>;+ expect(stored).not.toHaveProperty("signingSecret");+ });++ test("sets a new secret when a value is provided on update", async () => {+ const { service, store } = buildService({+ seed: [+ seedRow({+ id: "ch-1",+ channelType: AlarmChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "old" })+ })+ ]+ });++ await service.updateChannel({+ channelId: "ch-1",+ config: { url: "https://example.com/hook", signingSecret: "new" },+ ...actor+ });+ const stored = JSON.parse(store.get("ch-1")!.encryptedConfig.toString()) as Record<string, unknown>;+ expect(stored.signingSecret).toBe("new");+ });++ test("rejects clearing a required secret (Slack webhook URL)", async () => {+ const { service } = buildService({+ seed: [+ seedRow({+ id: "ch-1",+ channelType: AlarmChannelType.SLACK,+ encryptedConfig: encConfig({ webhookUrl: "https://hooks.slack.com/services/T/B/xxx" })+ })+ ]+ });++ await expect(service.updateChannel({ channelId: "ch-1", config: { webhookUrl: "" }, ...actor })).rejects.toThrow(+ /Invalid slack channel config/+ );+ });++ test("denies channel management without the settings permission", async () => {+ const { service } = buildService({ allow: false });+ await expect(+ service.createChannel({+ name: "nope",+ channelType: AlarmChannelType.WEBHOOK,+ config: { url: "https://example.com/hook" },+ ...actor+ })+ ).rejects.toThrow();+ });++ test("lists channels with their usage counts", async () => {+ const { service, memberships } = buildService({+ seed: [+ seedRow({+ id: "ch-1",+ name: "a",+ channelType: AlarmChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com/1" })+ }),+ seedRow({+ id: "ch-2",+ name: "b",+ channelType: AlarmChannelType.WEBHOOK,+ encryptedConfig: encConfig({ url: "https://example.com/2" })+ })+ ]+ });+ memberships.set("ch-1", 3);++ const channels = await service.listChannels({ ...actor });+ expect(channels.find((c) => c.id === "ch-1")?.usageCount).toBe(3);+ expect(channels.find((c) => c.id === "ch-2")?.usageCount).toBe(0);+ });+});diff --git a/backend/src/services/alarm/alarm-channel-service.ts b/backend/src/services/alarm/alarm-channel-service.tsnew file mode 100644index 0000000000..df1594d171--- /dev/null+++ b/backend/src/services/alarm/alarm-channel-service.ts@@ -0,0 +1,464 @@+import { ForbiddenError } from "@casl/ability";++import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";+import { TGroupDALFactory } from "@app/ee/services/group/group-dal";+import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { TGenericPermission } from "@app/lib/types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TOrgDALFactory } from "@app/services/org/org-dal";+import { TProjectDALFactory } from "@app/services/project/project-dal";++import { decryptChannelConfig, encryptChannelConfig, getAlarmChannelCipher } from "./alarm-channel-crypto-fns";+import { TAlarmChannelDALFactory } from "./alarm-channel-dal";+import { TAlarmChannelMembershipDALFactory } from "./alarm-channel-membership-dal";+import { TAlarmChannelRecipientDALFactory } from "./alarm-channel-recipient-dal";+import {+ TAlarmChannelDetail,+ TChannelRecipientInput,+ TCreateAlarmChannelDTO,+ TDeleteAlarmChannelDTO,+ TGetAlarmChannelDTO,+ TListAlarmChannelsDTO,+ TUpdateAlarmChannelDTO+} from "./alarm-channel-service-types";+import { AlarmChannelType } from "./alarm-channel-types";+import { AlarmPrincipalType } from "./alarm-types";+import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";++export type TAlarmChannelServiceFactoryDep = {+ alarmChannelDAL: TAlarmChannelDALFactory;+ alarmChannelRecipientDAL: TAlarmChannelRecipientDALFactory;+ alarmChannelMembershipDAL: Pick<TAlarmChannelMembershipDALFactory, "find">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;+ orgDAL: Pick<TOrgDALFactory, "findMembership">;+ projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;+ groupDAL: Pick<TGroupDALFactory, "find">;+};++export type TAlarmChannelServiceFactory = ReturnType<typeof alarmChannelServiceFactory>;++const capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);++export const alarmChannelServiceFactory = ({+ alarmChannelDAL,+ alarmChannelRecipientDAL,+ alarmChannelMembershipDAL,+ kmsService,+ permissionService,+ orgDAL,+ projectDAL,+ groupDAL+}: TAlarmChannelServiceFactoryDep) => {+ const $getDefinition = (channelType: string) => {+ const definition = ALARM_CHANNEL_REGISTRY[channelType as AlarmChannelType];+ if (!definition) throw new BadRequestError({ message: `Unknown channel type '${channelType}'` });+ return definition;+ };++ const $assertPermission = async (+ action: OrgPermissionActions,+ orgId: string,+ projectId: string | null | undefined,+ actor: TGenericPermission+ ) => {+ if (projectId) {+ const { permission } = await permissionService.getProjectPermission({+ actor: actor.actor,+ actorId: actor.actorId,+ projectId,+ actorAuthMethod: actor.actorAuthMethod,+ actorOrgId: actor.actorOrgId,+ actionProjectType: ActionProjectType.Any+ });+ ForbiddenError.from(permission).throwUnlessCan(+ action as unknown as ProjectPermissionActions,+ ProjectPermissionSub.Settings+ );+ return;+ }++ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: actor.actor,+ actorId: actor.actorId,+ orgId,+ actorAuthMethod: actor.actorAuthMethod,+ actorOrgId: actor.actorOrgId+ });+ ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.Settings);+ };++ // Confirms every recipient principal (user/group) actually belongs to the channel's scope so an+ // alarm can't be made to notify a foreign principal.+ const $validateRecipients = async (+ orgId: string,+ projectId: string | null | undefined,+ recipients: TChannelRecipientInput[]+ ) => {+ const userIds = [+ ...new Set(recipients.filter((r) => r.principalType === AlarmPrincipalType.USER).map((r) => r.principalId))+ ];+ const groupIds = [+ ...new Set(recipients.filter((r) => r.principalType === AlarmPrincipalType.GROUP).map((r) => r.principalId))+ ];+ 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;+ }++ 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(", ")}`+ });+ }+ }++ 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 $redactConfig = (channelType: string, config: Record<string, unknown>): Record<string, unknown> => {+ const definition = ALARM_CHANNEL_REGISTRY[channelType as AlarmChannelType];+ if (!definition) return {};+ const redacted: Record<string, unknown> = {};+ Object.entries(config).forEach(([key, value]) => {+ if (!definition.secretFields.includes(key)) redacted[key] = value;+ });+ definition.secretFields.forEach((field) => {+ redacted[`has${capitalize(field)}`] = Boolean(config[field]);+ });+ return redacted;+ };++ // Three-state merge of secret fields on update:+ // - field omitted -> keep the existing secret+ // - field empty / null -> clear it (valid only for optional secrets; the config schema rejects+ // clearing a required secret)+ // - field with a value -> set the new secret+ const $mergeConfigForUpdate = (+ channelType: string,+ incomingConfig: Record<string, unknown>,+ existingConfig: Record<string, unknown>+ ): Record<string, unknown> => {+ const definition = ALARM_CHANNEL_REGISTRY[channelType as AlarmChannelType];+ if (!definition) return incomingConfig;++ const merged: Record<string, unknown> = { ...incomingConfig };+ definition.secretFields.forEach((field) => {+ if (!(field in incomingConfig)) {+ if (existingConfig[field] != null) merged[field] = existingConfig[field];+ return;+ }+ const value = incomingConfig[field];+ if (value === "" || value === null || value === undefined) delete merged[field];+ });+ return merged;+ };++ const $countUsage = async (channelId: string): Promise<number> => {+ const memberships = await alarmChannelMembershipDAL.find({ channelId });+ return memberships.length;+ };++ const $buildDetail = (+ channel: {+ id: string;+ name: string;+ channelType: string;+ enabled: boolean;+ orgId: string;+ projectId?: string | null;+ createdAt: Date;+ updatedAt: Date;+ },+ config: Record<string, unknown>,+ recipients: { principalType: string; principalId: string }[],+ usageCount: number+ ): TAlarmChannelDetail => {+ const definition = ALARM_CHANNEL_REGISTRY[channel.channelType as AlarmChannelType];+ return {+ id: channel.id,+ name: channel.name,+ channelType: channel.channelType,+ directed: Boolean(definition?.directed),+ config: $redactConfig(channel.channelType, config),+ enabled: channel.enabled,+ recipients,+ usageCount,+ orgId: channel.orgId,+ projectId: channel.projectId ?? null,+ createdAt: channel.createdAt,+ updatedAt: channel.updatedAt+ };+ };++ const $assertNameAvailable = async (+ name: string,+ scope: { orgId: string; projectId?: string | null },+ excludeId?: string+ ) => {+ const existing = await alarmChannelDAL.findByNameInScope(name, scope);+ if (existing && existing.id !== excludeId) {+ throw new BadRequestError({ message: `A channel named '${name}' already exists in this scope` });+ }+ };++ const createChannel = async (dto: TCreateAlarmChannelDTO): Promise<TAlarmChannelDetail> => {+ const actor: TGenericPermission = {+ actor: dto.actor,+ actorId: dto.actorId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId+ };+ await $assertPermission(OrgPermissionActions.Create, dto.actorOrgId, dto.projectId, actor);++ const definition = $getDefinition(dto.channelType);+ const recipients = dto.recipients ?? [];+ if (!definition.directed && recipients.length > 0) {+ throw new BadRequestError({ message: `${dto.channelType} channels do not take recipients` });+ }+ if (definition.directed && recipients.length === 0) {+ throw new BadRequestError({ message: `${dto.channelType} channels require at least one recipient` });+ }++ try {+ definition.configSchema.parse(dto.config);+ } catch (err) {+ throw new BadRequestError({ message: `Invalid ${dto.channelType} channel config` });+ }++ await $assertNameAvailable(dto.name, { orgId: dto.actorOrgId, projectId: dto.projectId });+ await $validateRecipients(dto.actorOrgId, dto.projectId, recipients);++ const { encryptor } = await getAlarmChannelCipher(kmsService, {+ orgId: dto.actorOrgId,+ projectId: dto.projectId ?? null+ });++ const channel = await alarmChannelDAL.transaction(async (tx) => {+ const created = await alarmChannelDAL.create(+ {+ name: dto.name,+ channelType: dto.channelType,+ encryptedConfig: encryptChannelConfig(dto.config, encryptor),+ enabled: dto.enabled ?? true,+ orgId: dto.actorOrgId,+ projectId: dto.projectId ?? null,+ createdByUserId: dto.actorId+ },+ tx+ );++ if (recipients.length) {+ await alarmChannelRecipientDAL.insertMany(+ recipients.map((r) => ({+ channelId: created.id,+ principalType: r.principalType,+ principalId: r.principalId+ })),+ tx+ );+ }+ return created;+ });++ return $buildDetail(channel, dto.config, recipients, 0);+ };++ const updateChannel = async (dto: TUpdateAlarmChannelDTO): Promise<TAlarmChannelDetail> => {+ const actor: TGenericPermission = {+ actor: dto.actor,+ actorId: dto.actorId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId+ };++ const channel = await alarmChannelDAL.findById(dto.channelId);+ if (!channel) throw new NotFoundError({ message: `Channel with ID '${dto.channelId}' not found` });++ await $assertPermission(OrgPermissionActions.Edit, channel.orgId, channel.projectId, actor);++ const definition = $getDefinition(channel.channelType);+ const scope = { orgId: channel.orgId, projectId: channel.projectId };++ const { encryptor, decryptor } = await getAlarmChannelCipher(kmsService, scope);+ const existingConfig = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);++ let finalConfig = existingConfig;+ if (dto.config !== undefined) {+ const merged = $mergeConfigForUpdate(channel.channelType, dto.config, existingConfig);+ try {+ definition.configSchema.parse(merged);+ } catch (err) {+ throw new BadRequestError({ message: `Invalid ${channel.channelType} channel config` });+ }+ finalConfig = merged;+ }++ if (dto.recipients !== undefined) {+ if (!definition.directed && dto.recipients.length > 0) {+ throw new BadRequestError({ message: `${channel.channelType} channels do not take recipients` });+ }+ if (definition.directed && dto.recipients.length === 0) {+ throw new BadRequestError({ message: `${channel.channelType} channels require at least one recipient` });+ }+ await $validateRecipients(channel.orgId, channel.projectId, dto.recipients);+ }++ if (dto.name !== undefined && dto.name !== channel.name) {+ await $assertNameAvailable(dto.name, scope, channel.id);+ }++ await alarmChannelDAL.transaction(async (tx) => {+ await alarmChannelDAL.updateById(+ channel.id,+ {+ ...(dto.name !== undefined ? { name: dto.name } : {}),+ ...(dto.enabled !== undefined ? { enabled: dto.enabled } : {}),+ ...(dto.config !== undefined ? { encryptedConfig: encryptChannelConfig(finalConfig, encryptor) } : {})+ },+ tx+ );++ if (dto.recipients !== undefined) {+ await alarmChannelRecipientDAL.deleteByChannelId(channel.id, tx);+ if (dto.recipients.length) {+ await alarmChannelRecipientDAL.insertMany(+ dto.recipients.map((r) => ({+ channelId: channel.id,+ principalType: r.principalType,+ principalId: r.principalId+ })),+ tx+ );+ }+ }+ });++ const [updated, recipients, usageCount] = await Promise.all([+ alarmChannelDAL.findById(channel.id),+ alarmChannelRecipientDAL.findByChannelId(channel.id),+ $countUsage(channel.id)+ ]);+ return $buildDetail(+ updated,+ finalConfig,+ recipients.map((r) => ({ principalType: r.principalType, principalId: r.principalId })),+ usageCount+ );+ };++ const deleteChannel = async (dto: TDeleteAlarmChannelDTO): Promise<{ id: string }> => {+ const actor: TGenericPermission = {+ actor: dto.actor,+ actorId: dto.actorId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId+ };+ const channel = await alarmChannelDAL.findById(dto.channelId);+ if (!channel) throw new NotFoundError({ message: `Channel with ID '${dto.channelId}' not found` });++ await $assertPermission(OrgPermissionActions.Delete, channel.orgId, channel.projectId, actor);++ // Membership rows CASCADE-delete, detaching the channel from every alarm that referenced it.+ await alarmChannelDAL.deleteById(channel.id);+ return { id: channel.id };+ };++ const getChannelById = async (dto: TGetAlarmChannelDTO): Promise<TAlarmChannelDetail> => {+ const actor: TGenericPermission = {+ actor: dto.actor,+ actorId: dto.actorId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId+ };+ const channel = await alarmChannelDAL.findById(dto.channelId);+ if (!channel) throw new NotFoundError({ message: `Channel with ID '${dto.channelId}' not found` });++ await $assertPermission(OrgPermissionActions.Read, channel.orgId, channel.projectId, actor);++ const { decryptor } = await getAlarmChannelCipher(kmsService, {+ orgId: channel.orgId,+ projectId: channel.projectId+ });+ const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);+ const [recipients, usageCount] = await Promise.all([+ alarmChannelRecipientDAL.findByChannelId(channel.id),+ $countUsage(channel.id)+ ]);+ return $buildDetail(+ channel,+ config,+ recipients.map((r) => ({ principalType: r.principalType, principalId: r.principalId })),+ usageCount+ );+ };++ const listChannels = async (dto: TListAlarmChannelsDTO): Promise<TAlarmChannelDetail[]> => {+ const actor: TGenericPermission = {+ actor: dto.actor,+ actorId: dto.actorId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId+ };+ await $assertPermission(OrgPermissionActions.Read, dto.actorOrgId, dto.projectId, actor);++ const scope = { orgId: dto.actorOrgId, projectId: dto.projectId ?? null };+ const channels = await alarmChannelDAL.findWithUsageByScope(scope);+ if (channels.length === 0) return [];++ const [recipients, { decryptor }] = await Promise.all([+ alarmChannelRecipientDAL.findByChannelIds(channels.map((c) => c.id)),+ getAlarmChannelCipher(kmsService, scope)+ ]);++ const recipientsByChannel = new Map<string, { principalType: string; principalId: string }[]>();+ recipients.forEach((r) => {+ const list = recipientsByChannel.get(r.channelId) ?? [];+ list.push({ principalType: r.principalType, principalId: r.principalId });+ recipientsByChannel.set(r.channelId, list);+ });++ return channels.map((channel) => {+ const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);+ return $buildDetail(channel, config, recipientsByChannel.get(channel.id) ?? [], channel.usageCount);+ });+ };++ return { createChannel, updateChannel, deleteChannel, getChannelById, listChannels };+};diff --git a/backend/src/services/alarm/alarm-engine.test.ts b/backend/src/services/alarm/alarm-engine.test.tsindex e46e42ebec..c4558dd982 100644--- a/backend/src/services/alarm/alarm-engine.test.ts+++ b/backend/src/services/alarm/alarm-engine.test.ts@@ -95,17 +95,17 @@ const buildEngine = (opts: {const engine = alarmEngineFactory({alarmChannelDAL: { findByAlarmId: async () => opts.channels },- alarmRecipientDAL: {- findByAlarmId: async () => [- {- id: "r1",- alarmId: "alarm-1",+ alarmChannelRecipientDAL: {+ // One recipient row per directed channel in the run, so each resolves its own list.+ findByChannelIds: async (channelIds: string[]) =>+ channelIds.map((channelId) => ({+ id: `r-${channelId}`,+ channelId,principalType: AlarmPrincipalType.USER,principalId: "u1",createdAt: new Date(),updatedAt: new Date()- }- ]+ }))},alarmHistoryDAL: {findRecentlyAlarmedTargets: async () => opts.recentlyAlarmed ?? [],diff --git a/backend/src/services/alarm/alarm-engine.ts b/backend/src/services/alarm/alarm-engine.tsindex 668d807614..5d38f44951 100644--- a/backend/src/services/alarm/alarm-engine.ts+++ b/backend/src/services/alarm/alarm-engine.ts@@ -8,10 +8,10 @@ import { TSmtpService } from "@app/services/smtp/smtp-service";import { decryptChannelConfig, getAlarmChannelCipher } from "./alarm-channel-crypto-fns";import { TAlarmChannelDALFactory } from "./alarm-channel-dal";+import { TAlarmChannelRecipientDALFactory } from "./alarm-channel-recipient-dal";import { AlarmChannelType, TAlarmChannelDeps, TAlarmRecipient } from "./alarm-channel-types";import { TAlarmHistoryDALFactory } from "./alarm-history-dal";import { TAlarmProviderRegistry } from "./alarm-provider-registry";-import { TAlarmRecipientDALFactory } from "./alarm-recipient-dal";import { TAlarmRecipientResolver } from "./alarm-recipient-resolver";import { AlarmRunStatus, DEFAULT_DEDUP_WINDOW_HOURS, TAlarmContext } from "./alarm-types";import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";@@ -20,7 +20,7 @@ const FAILURE_NOTIFICATION_MAX_ERROR_LENGTH = 200;export type TAlarmEngineDep = {alarmChannelDAL: Pick<TAlarmChannelDALFactory, "findByAlarmId">;- alarmRecipientDAL: Pick<TAlarmRecipientDALFactory, "findByAlarmId">;+ alarmChannelRecipientDAL: Pick<TAlarmChannelRecipientDALFactory, "findByChannelIds">;alarmHistoryDAL: Pick<TAlarmHistoryDALFactory, "createWithTargets" | "findRecentlyAlarmedTargets">;alarmProviderRegistry: TAlarmProviderRegistry;alarmRecipientResolver: TAlarmRecipientResolver;@@ -34,7 +34,7 @@ export type TAlarmEngine = ReturnType<typeof alarmEngineFactory>;export const alarmEngineFactory = ({alarmChannelDAL,- alarmRecipientDAL,+ alarmChannelRecipientDAL,alarmHistoryDAL,alarmProviderRegistry,alarmRecipientResolver,@@ -129,12 +129,23 @@ export const alarmEngineFactory = ({projectId: alarm.projectId});- const hasDirectedChannel = channelWork.some(- (work) => ALARM_CHANNEL_REGISTRY[work.channel.channelType as AlarmChannelType]?.directed- );- let recipients: TAlarmRecipient[] = [];- if (hasDirectedChannel) {- recipients = await alarmRecipientResolver.resolve(await alarmRecipientDAL.findByAlarmId(alarm.id));+ const directedChannelIds = channelWork+ .filter((work) => ALARM_CHANNEL_REGISTRY[work.channel.channelType as AlarmChannelType]?.directed)+ .map((work) => work.channel.id);+ const recipientsByChannel = new Map<string, TAlarmRecipient[]>();+ if (directedChannelIds.length) {+ const recipientRows = await alarmChannelRecipientDAL.findByChannelIds(directedChannelIds);+ const rowsByChannel = new Map<string, { principalType: string; principalId: string }[]>();+ recipientRows.forEach((row) => {+ const list = rowsByChannel.get(row.channelId) ?? [];+ list.push(row);+ rowsByChannel.set(row.channelId, list);+ });+ await Promise.all(+ [...rowsByChannel.entries()].map(async ([channelId, rows]) => {+ recipientsByChannel.set(channelId, await alarmRecipientResolver.resolve(rows));+ })+ );}const deps: TAlarmChannelDeps = { smtpService };@@ -158,6 +169,7 @@ export const alarmEngineFactory = ({try {if (definition.directed) {+ const recipients = recipientsByChannel.get(channel.id) ?? [];if (recipients.length === 0) {return { ...base, success: false, error: "No recipients could be resolved for this channel" };}diff --git a/backend/src/services/alarm/alarm-recipient-dal.ts b/backend/src/services/alarm/alarm-recipient-dal.tsdeleted file mode 100644index 28d435c5fb..0000000000--- a/backend/src/services/alarm/alarm-recipient-dal.ts+++ /dev/null@@ -1,52 +0,0 @@-import { Knex } from "knex";--import { TDbClient } from "@app/db";-import { TableName, TAlarmRecipients } from "@app/db/schemas";-import { DatabaseError } from "@app/lib/errors";-import { ormify, selectAllTableCols } from "@app/lib/knex";--export type TAlarmRecipientDALFactory = ReturnType<typeof alarmRecipientDALFactory>;--export const alarmRecipientDALFactory = (db: TDbClient) => {- const alarmRecipientOrm = ormify(db, TableName.AlarmRecipient);-- const findByAlarmId = async (alarmId: string, tx?: Knex): Promise<TAlarmRecipients[]> => {- try {- const recipients = await (tx || db.replicaNode())(TableName.AlarmRecipient)- .where(`${TableName.AlarmRecipient}.alarmId`, alarmId)- .select(selectAllTableCols(TableName.AlarmRecipient));-- return recipients as TAlarmRecipients[];- } catch (error) {- throw new DatabaseError({ error, name: "FindByAlarmId" });- }- };-- const findByAlarmIds = async (alarmIds: string[], tx?: Knex): Promise<TAlarmRecipients[]> => {- try {- if (!alarmIds.length) return [];- const recipients = await (tx || db.replicaNode())(TableName.AlarmRecipient)- .whereIn(`${TableName.AlarmRecipient}.alarmId`, alarmIds)- .select(selectAllTableCols(TableName.AlarmRecipient));-- return recipients as TAlarmRecipients[];- } catch (error) {- throw new DatabaseError({ error, name: "FindByAlarmIds" });- }- };-- const deleteByAlarmId = async (alarmId: string, tx?: Knex): Promise<number> => {- try {- return await (tx || db)(TableName.AlarmRecipient).where(`${TableName.AlarmRecipient}.alarmId`, alarmId).del();- } catch (error) {- throw new DatabaseError({ error, name: "DeleteByAlarmId" });- }- };-- return {- ...alarmRecipientOrm,- findByAlarmId,- findByAlarmIds,- deleteByAlarmId- };-};diff --git a/backend/src/services/alarm/alarm-recipient-resolver.ts b/backend/src/services/alarm/alarm-recipient-resolver.tsindex bf4a264605..9eecd1fb34 100644--- a/backend/src/services/alarm/alarm-recipient-resolver.ts+++ b/backend/src/services/alarm/alarm-recipient-resolver.ts@@ -1,4 +1,3 @@-import { TAlarmRecipients } from "@app/db/schemas";import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";import { logger } from "@app/lib/logger";import { TUserDALFactory } from "@app/services/user/user-dal";@@ -11,10 +10,12 @@ type TAlarmRecipientResolverDep = {userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;};+type TResolvableRecipient = { principalType: string; principalId: string };+export type TAlarmRecipientResolver = ReturnType<typeof alarmRecipientResolverFactory>;export const alarmRecipientResolverFactory = ({ userDAL, userGroupMembershipDAL }: TAlarmRecipientResolverDep) => {- const resolve = async (recipients: TAlarmRecipients[]): Promise<TAlarmRecipient[]> => {+ const resolve = async (recipients: TResolvableRecipient[]): Promise<TAlarmRecipient[]> => {const userIds = new Set<string>();const groupIds = new Set<string>();const rawEmails = new Set<string>();diff --git a/backend/src/services/alarm/alarm-service-types.ts b/backend/src/services/alarm/alarm-service-types.tsindex 4dda6543ea..4a5f93f09c 100644--- a/backend/src/services/alarm/alarm-service-types.ts+++ b/backend/src/services/alarm/alarm-service-types.ts@@ -1,19 +1,6 @@import { TGenericPermission } from "@app/lib/types";-import { AlarmChannelType } from "./alarm-channel-types";-import { AlarmPrincipalType } from "./alarm-types";--export type TAlarmRecipientInput = {- principalType: AlarmPrincipalType;- principalId: string;-};--export type TAlarmChannelInput = {- id?: string;- channelType: AlarmChannelType;- config: unknown;- enabled?: boolean;-};+import { TAlarmChannelSummary } from "./alarm-channel-service-types";export type TCreateAlarmDTO = TGenericPermission & {name: string;@@ -25,8 +12,7 @@ export type TCreateAlarmDTO = TGenericPermission & {filters?: unknown;enabled?: boolean;projectId?: string | null;- recipients: TAlarmRecipientInput[];- channels: TAlarmChannelInput[];+ channelIds: string[];};export type TUpdateAlarmDTO = TGenericPermission & {@@ -36,8 +22,7 @@ export type TUpdateAlarmDTO = TGenericPermission & {condition?: unknown;filters?: unknown;enabled?: boolean;- recipients?: TAlarmRecipientInput[];- channels?: TAlarmChannelInput[];+ channelIds?: string[];};export type TGetAlarmDTO = TGenericPermission & { alarmId: string };@@ -51,20 +36,6 @@ export type TListAlarmsDTO = TGenericPermission & {enabled?: boolean;};-export type TAlarmChannelResponse = {- id: string;- channelType: string;- config: Record<string, unknown>;- enabled: boolean;- createdAt: Date;- updatedAt: Date;-};--export type TAlarmRecipientResponse = {- principalType: string;- principalId: string;-};-export type TAlarmResponse = {id: string;name: string;@@ -77,8 +48,7 @@ export type TAlarmResponse = {enabled: boolean;orgId: string;projectId: string | null;- recipients: TAlarmRecipientResponse[];- channels: TAlarmChannelResponse[];+ channels: TAlarmChannelSummary[];createdAt: Date;updatedAt: Date;};diff --git a/backend/src/services/alarm/alarm-service.test.ts b/backend/src/services/alarm/alarm-service.test.tsindex 2c512beb49..62f2151787 100644--- a/backend/src/services/alarm/alarm-service.test.ts+++ b/backend/src/services/alarm/alarm-service.test.ts@@ -3,23 +3,35 @@ import { z } from "zod";import { AlarmChannelType, TAlarmPayload } from "./alarm-channel-types";import { alarmProviderRegistryFactory } from "./alarm-provider-registry";import { alarmServiceFactory, TAlarmServiceFactoryDep } from "./alarm-service";-import { AlarmPrincipalType, IResourceAlarmProvider, TAlarmPermissionInput } from "./alarm-types";+import { IResourceAlarmProvider, TAlarmPermissionInput } from "./alarm-types";const RESOURCE_TYPE = "test.resource";-// Identity cipher: encryptedConfig is just JSON bytes of the config.-const kmsServiceMock = {- createCipherPairWithDataKey: async () => ({- encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),- decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob- })+type TChannelRow = {+ id: string;+ name: string;+ channelType: AlarmChannelType;+ enabled: boolean;+ orgId: string;+ projectId: string | null;+ createdAt: Date;+ updatedAt: Date;};-const encConfig = (config: unknown) => Buffer.from(JSON.stringify(config));++const channelRow = (over: Partial<TChannelRow> & { id: string; channelType: AlarmChannelType }): TChannelRow => ({+ name: over.id,+ enabled: true,+ orgId: "org-1",+ projectId: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ ...over+});const buildService = (opts?: {assertPermission?: (input: TAlarmPermissionInput) => Promise<void>;resourceScopeThrows?: boolean;- rejectRecipients?: boolean;+ channels?: TChannelRow[];}) => {const permissionCalls: TAlarmPermissionInput[] = [];const provider: IResourceAlarmProvider = {@@ -35,18 +47,22 @@ const buildService = (opts?: {if (opts?.assertPermission) await opts.assertPermission(input);},assertResourceInScope: async (input) => {- // Mirror the real contract: no-op when there is no resource to bind-check.if (input.resourceId && opts?.resourceScopeThrows) throw new Error("resource out of scope");}};const registry = alarmProviderRegistryFactory();registry.register(provider);+ const channelStore = new Map<string, TChannelRow>();+ (opts?.channels ?? []).forEach((c) => channelStore.set(c.id, c));+const alarms = new Map<string, Record<string, unknown>>();- const channels = new Map<string, Array<Record<string, unknown>>>();- const recipients = new Map<string, Array<Record<string, unknown>>>();+ const memberships = new Map<string, string[]>(); // alarmId -> channelIdsconst findFilters: Array<Record<string, unknown>> = [];+ const inScope = (c: TChannelRow, scope: { orgId: string; projectId?: string | null }) =>+ c.orgId === scope.orgId && (c.projectId ?? null) === (scope.projectId ?? null);+const service = alarmServiceFactory({alarmDAL: {transaction: async (cb: (tx: unknown) => unknown) => cb({}),@@ -66,10 +82,7 @@ const buildService = (opts?: {find: async (filter: Record<string, unknown>) => {findFilters.push(filter);return [...alarms.values()].filter((row) =>- Object.entries(filter).every(([key, value]) => {- if (value === undefined) return true;- return row[key] === value;- })+ Object.entries(filter).every(([key, value]) => value === undefined || row[key] === value));},updateById: async (id: string, data: Record<string, unknown>) => {@@ -79,72 +92,34 @@ const buildService = (opts?: {deleteById: async (id: string) => alarms.delete(id)},alarmChannelDAL: {- insertMany: async (data: Array<Record<string, unknown>>) => {- const withMeta = data.map((c, i) => ({ id: `c${i}`, createdAt: new Date(), updatedAt: new Date(), ...c }));- channels.set(data[0].alarmId as string, [...(channels.get(data[0].alarmId as string) ?? []), ...withMeta]);- return withMeta;- },- findByAlarmId: async (alarmId: string) => channels.get(alarmId) ?? [],- findByAlarmIds: async (alarmIds: string[]) => alarmIds.flatMap((alarmId) => channels.get(alarmId) ?? []),- updateById: async (id: string, data: Record<string, unknown>) => {- for (const [alarmId, rows] of channels) {- const idx = rows.findIndex((c) => c.id === id);- if (idx >= 0) {- rows[idx] = { ...rows[idx], ...data, updatedAt: new Date() };- channels.set(alarmId, rows);- return rows[idx];- }- }- return undefined;- },- delete: async (filter: { $in?: { id?: string[] } }) => {- const ids = new Set(filter.$in?.id ?? []);- for (const [alarmId, rows] of channels) {- channels.set(- alarmId,- rows.filter((c) => !ids.has(c.id as string))- );- }- return [];- }+ findByIdsInScope: async (ids: string[], scope: { orgId: string; projectId?: string | null }) =>+ ids.map((id) => channelStore.get(id)).filter((c): c is TChannelRow => Boolean(c) && inScope(c!, scope)),+ findByAlarmId: async (alarmId: string) =>+ (memberships.get(alarmId) ?? []).map((id) => channelStore.get(id)).filter(Boolean),+ findByAlarmIds: async (alarmIds: string[]) =>+ alarmIds.flatMap((alarmId) =>+ (memberships.get(alarmId) ?? [])+ .map((id) => channelStore.get(id))+ .filter(Boolean)+ .map((c) => ({ ...(c as TChannelRow), alarmId }))+ )},- alarmRecipientDAL: {- insertMany: async (data: Array<Record<string, unknown>>) => {- recipients.set(data[0].alarmId as string, data);+ alarmChannelMembershipDAL: {+ insertMany: async (data: Array<{ alarmId: string; channelId: string }>) => {+ data.forEach(({ alarmId, channelId }) =>+ memberships.set(alarmId, [...(memberships.get(alarmId) ?? []), channelId])+ );return data;},- findByAlarmId: async (alarmId: string) => recipients.get(alarmId) ?? [],- findByAlarmIds: async (alarmIds: string[]) => alarmIds.flatMap((alarmId) => recipients.get(alarmId) ?? []),deleteByAlarmId: async (alarmId: string) => {- recipients.delete(alarmId);+ memberships.delete(alarmId);return 0;}},- alarmProviderRegistry: registry,- kmsService: kmsServiceMock,- orgDAL: {- findMembership: async (filter: { $in?: { actorUserId?: string[] } }) =>- opts?.rejectRecipients ? [] : (filter.$in?.actorUserId ?? []).map((actorUserId) => ({ actorUserId }))- },- projectDAL: {- findEffectiveProjectSubjectsMembership: async ({- userIds,- groupIds- }: {- userIds: string[];- groupIds: string[];- }) =>- opts?.rejectRecipients- ? { effectiveUserIds: [], effectiveGroupIds: [] }- : { effectiveUserIds: userIds, effectiveGroupIds: groupIds }- },- groupDAL: {- find: async (filter: { $in?: { id?: string[] } }) =>- opts?.rejectRecipients ? [] : (filter.$in?.id ?? []).map((id) => ({ id }))- }+ alarmProviderRegistry: registry} as unknown as TAlarmServiceFactoryDep);- return { service, permissionCalls, alarms, channels, recipients, findFilters };+ return { service, permissionCalls, alarms, memberships, channelStore, findFilters };};const actor = {@@ -154,70 +129,71 @@ const actor = {actorOrgId: "org-1"};+const orgChannels: TChannelRow[] = [+ channelRow({ id: "ch-email", channelType: AlarmChannelType.EMAIL }),+ channelRow({ id: "ch-webhook", channelType: AlarmChannelType.WEBHOOK })+];+const validCreate = {name: "test-alarm",resourceType: RESOURCE_TYPE,eventType: "test.resource.expiration",condition: { alertBefore: "30d" },- recipients: [{ principalType: AlarmPrincipalType.USER, principalId: "user-1" }],- channels: [- { channelType: AlarmChannelType.EMAIL, config: {} },- { channelType: AlarmChannelType.WEBHOOK, config: { url: "https://example.com/hook" } }- ],+ channelIds: ["ch-email", "ch-webhook"],...actor};describe("alarm service", () => {- test("creates an alarm, persists channels + recipients, and checks Create permission", async () => {- const { service, permissionCalls } = buildService();+ test("creates an alarm, attaches channels, and checks Create permission", async () => {+ const { service, permissionCalls, memberships } = buildService({ channels: orgChannels });const alarm = await service.createAlarm(validCreate);expect(alarm.id).toBe("alarm-1");expect(alarm.orgId).toBe("org-1");- expect(alarm.channels).toHaveLength(2);- expect(alarm.recipients).toEqual([{ principalType: "user", principalId: "user-1" }]);+ expect(alarm.channels.map((c) => c.id).sort()).toEqual(["ch-email", "ch-webhook"]);+ expect(alarm.channels.find((c) => c.id === "ch-email")?.directed).toBe(true);+ expect(alarm.channels.find((c) => c.id === "ch-webhook")?.directed).toBe(false);+ expect(memberships.get("alarm-1")?.sort()).toEqual(["ch-email", "ch-webhook"]);expect(permissionCalls[0].action).toBe("create");- expect(permissionCalls[0].orgId).toBe("org-1");});test("rejects an unknown resource type", async () => {- const { service } = buildService();+ const { service } = buildService({ channels: orgChannels });await expect(service.createAlarm({ ...validCreate, resourceType: "nope.unknown" })).rejects.toThrow();});test("runs the provider resource-scope check when resourceId is set", async () => {- const { service } = buildService({ resourceScopeThrows: true });+ const { service } = buildService({ channels: orgChannels, resourceScopeThrows: true });await expect(service.createAlarm({ ...validCreate, resourceId: "foreign-resource" })).rejects.toThrow("resource out of scope");});test("skips the resource-scope check for a filter-based alarm (no resourceId)", async () => {- const { service } = buildService({ resourceScopeThrows: true });- // No resourceId, so the scope check must not run and creation succeeds.+ const { service } = buildService({ channels: orgChannels, resourceScopeThrows: true });await expect(service.createAlarm(validCreate)).resolves.toBeDefined();});test("rejects a condition that fails the provider schema", async () => {- const { service } = buildService();+ const { service } = buildService({ channels: orgChannels });await expect(service.createAlarm({ ...validCreate, condition: { wrong: 1 } })).rejects.toThrow();});test("rejects a create with no condition when the provider requires one", async () => {- const { service } = buildService();- // Omitted condition must be caught at create time (400), not stored as null and thrown at cron time.+ const { service } = buildService({ channels: orgChannels });await expect(service.createAlarm({ ...validCreate, condition: undefined })).rejects.toThrow(/Invalid alarm condition/);});test("rejects an event type the provider does not support", async () => {- const { service } = buildService();+ const { service } = buildService({ channels: orgChannels });await expect(service.createAlarm({ ...validCreate, eventType: "test.resource.renewal" })).rejects.toThrow();});test("propagates a permission denial from the provider", async () => {const { service } = buildService({+ channels: orgChannels,assertPermission: async () => {throw new Error("forbidden");}@@ -225,95 +201,20 @@ describe("alarm service", () => {await expect(service.createAlarm(validCreate)).rejects.toThrow("forbidden");});- test("rejects recipients that do not belong to the scope", async () => {- const { service } = buildService({ rejectRecipients: true });- await expect(service.createAlarm(validCreate)).rejects.toThrow(/not members of the organization/);- });-- test("accepts EMAIL recipients without a membership check", async () => {- // rejectRecipients makes every user/group lookup come back empty; an email-only alarm must- // still succeed because raw addresses are not validated against the org/project.- const { service } = buildService({ rejectRecipients: true });- const alarm = await service.createAlarm({- ...validCreate,- recipients: [{ principalType: AlarmPrincipalType.EMAIL, principalId: "[email protected]" }]- });- expect(alarm.recipients).toEqual([{ principalType: "email", principalId: "[email protected]" }]);- });-- test("redacts the webhook signing secret on read", async () => {- const { service, alarms, channels } = buildService();- alarms.set("alarm-1", {- id: "alarm-1",- name: "wh",- resourceType: RESOURCE_TYPE,- resourceId: null,- eventType: "test.resource.expiration",- condition: null,- filters: null,- enabled: true,- orgId: "org-1",- projectId: null,- createdAt: new Date(),- updatedAt: new Date()- });- channels.set("alarm-1", [- {- id: "c0",- channelType: AlarmChannelType.WEBHOOK,- encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" }),- enabled: true,- createdAt: new Date(),- updatedAt: new Date()- }- ]);-- const alarm = await service.getAlarmById({ alarmId: "alarm-1", ...actor });- expect(alarm.channels[0].config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });- expect(alarm.channels[0].config).not.toHaveProperty("signingSecret");+ test("rejects channel ids that are not in the alarm's scope", async () => {+ // The channel exists but belongs to a different project, so it must not be attachable here.+ const foreign = channelRow({ id: "ch-foreign", channelType: AlarmChannelType.WEBHOOK, projectId: "other" });+ const { service } = buildService({ channels: [...orgChannels, foreign] });+ await expect(service.createAlarm({ ...validCreate, channelIds: ["ch-foreign"] })).rejects.toThrow(+ /not found in this scope/+ );});- test("redacts the Slack webhook URL and PagerDuty integration key on read", async () => {- const { service, alarms, channels } = buildService();- alarms.set("alarm-1", {- id: "alarm-1",- name: "creds",- resourceType: RESOURCE_TYPE,- resourceId: null,- eventType: "test.resource.expiration",- condition: null,- filters: null,- enabled: true,- orgId: "org-1",- projectId: null,- createdAt: new Date(),- updatedAt: new Date()- });- channels.set("alarm-1", [- {- id: "c0",- channelType: AlarmChannelType.SLACK,- encryptedConfig: encConfig({ webhookUrl: "https://hooks.slack.com/services/T/B/xxx" }),- enabled: true,- createdAt: new Date(),- updatedAt: new Date()- },- {- id: "c1",- channelType: AlarmChannelType.PAGERDUTY,- encryptedConfig: encConfig({ integrationKey: "a".repeat(32) }),- enabled: true,- createdAt: new Date(),- updatedAt: new Date()- }- ]);-- const alarm = await service.getAlarmById({ alarmId: "alarm-1", ...actor });-- expect(alarm.channels[0].config).toEqual({ hasWebhookUrl: true });- expect(alarm.channels[0].config).not.toHaveProperty("webhookUrl");- expect(alarm.channels[1].config).toEqual({ hasIntegrationKey: true });- expect(alarm.channels[1].config).not.toHaveProperty("integrationKey");+ test("rejects an empty channel list", async () => {+ const { service } = buildService({ channels: orgChannels });+ await expect(service.createAlarm({ ...validCreate, channelIds: [] })).rejects.toThrow(+ "At least one channel is required"+ );});const listBase = {@@ -329,7 +230,7 @@ describe("alarm service", () => {};test("org-scoped list returns only org-level alarms, never other projects'", async () => {- const { service, alarms, findFilters } = buildService();+ const { service, alarms, findFilters } = buildService({ channels: orgChannels });alarms.set("org-alarm", { id: "org-alarm", name: "org", projectId: null, ...listBase });alarms.set("proj-alarm", { id: "proj-alarm", name: "proj", projectId: "proj-x", ...listBase });@@ -340,7 +241,7 @@ describe("alarm service", () => {});test("project-scoped list filters to the requested project", async () => {- const { service, alarms, findFilters } = buildService();+ const { service, alarms, findFilters } = buildService({ channels: orgChannels });alarms.set("org-alarm", { id: "org-alarm", name: "org", projectId: null, ...listBase });alarms.set("proj-alarm", { id: "proj-alarm", name: "proj", projectId: "proj-x", ...listBase });@@ -350,134 +251,28 @@ describe("alarm service", () => {expect(findFilters[0]).toMatchObject({ projectId: "proj-x" });});- const seedAlarmWithChannel = (- channelType: AlarmChannelType,- config: unknown,- channelId = "c0"- ): ReturnType<typeof buildService> => {- const built = buildService();- built.alarms.set("alarm-1", {- id: "alarm-1",- name: "a",- resourceType: RESOURCE_TYPE,- resourceId: null,- eventType: "test.resource.expiration",- condition: null,- filters: null,- enabled: true,- orgId: "org-1",- projectId: null,- createdAt: new Date(),- updatedAt: new Date()- });- built.channels.set("alarm-1", [- {- id: channelId,- channelType,- encryptedConfig: encConfig(config),- enabled: true,- createdAt: new Date(),- updatedAt: new Date()- }- ]);- return built;- };-- test("preserves an unresent webhook signing secret when a channel is edited by id", async () => {- const { service } = seedAlarmWithChannel(AlarmChannelType.WEBHOOK, {- url: "https://example.com/hook",- signingSecret: "s3cr3t"- });-- const updated = await service.updateAlarm({- alarmId: "alarm-1",- channels: [{ id: "c0", channelType: AlarmChannelType.WEBHOOK, config: { url: "https://example.com/hook" } }],- ...actor- });-- expect(updated.channels[0].config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });- });-- test("preserves an unresent Slack webhook URL when a channel is edited by id", async () => {- const { service } = seedAlarmWithChannel(AlarmChannelType.SLACK, {- webhookUrl: "https://hooks.slack.com/services/T/B/xxx"- });-- const updated = await service.updateAlarm({- alarmId: "alarm-1",- channels: [{ id: "c0", channelType: AlarmChannelType.SLACK, config: {} }],- ...actor- });-- expect(updated.channels[0].config).toEqual({ hasWebhookUrl: true });- });-- test("preserves the channel id when an existing channel is edited so dedup history stays intact", async () => {- const { service, channels } = seedAlarmWithChannel(AlarmChannelType.WEBHOOK, {- url: "https://example.com/hook"- });-- const updated = await service.updateAlarm({- alarmId: "alarm-1",- channels: [- { id: "c0", channelType: AlarmChannelType.WEBHOOK, config: { url: "https://example.com/hook" }, enabled: false }- ],- ...actor- });-- // The channel must keep its original id (not be deleted + recreated with a fresh UUID), otherwise- // alarm_history_target.channelId would no longer match and per-channel dedup would reset.- expect(updated.channels[0].id).toBe("c0");- expect(updated.channels[0].enabled).toBe(false);- expect((channels.get("alarm-1") ?? []).map((c) => c.id)).toEqual(["c0"]);- });-- test("does not fabricate a secret for a newly added channel (no id)", async () => {- const { service } = seedAlarmWithChannel(AlarmChannelType.WEBHOOK, {- url: "https://old.example.com/hook",- signingSecret: "s3cr3t"- });-- const updated = await service.updateAlarm({- alarmId: "alarm-1",- channels: [{ channelType: AlarmChannelType.WEBHOOK, config: { url: "https://new.example.com/hook" } }],- ...actor- });-- expect(updated.channels[0].config).toEqual({ url: "https://new.example.com/hook", hasSigningSecret: false });- });+ test("update replaces the alarm's attached channels", async () => {+ const { service, memberships } = buildService({ channels: orgChannels });+ await service.createAlarm(validCreate);+ expect(memberships.get("alarm-1")?.sort()).toEqual(["ch-email", "ch-webhook"]);- test("allows a channel-only update of an email alarm using its existing recipients", async () => {- const { service, recipients } = seedAlarmWithChannel(AlarmChannelType.EMAIL, {});- recipients.set("alarm-1", [{ principalType: AlarmPrincipalType.USER, principalId: "user-1" }]);-- // No recipients in the update, but the alarm already has one; the directed-channel requirement- // must be satisfied by the existing recipients rather than rejecting the edit.- const updated = await service.updateAlarm({- alarmId: "alarm-1",- name: "renamed",- channels: [{ id: "c0", channelType: AlarmChannelType.EMAIL, config: {} }],- ...actor- });+ const updated = await service.updateAlarm({ alarmId: "alarm-1", channelIds: ["ch-webhook"], ...actor });- expect(updated.name).toBe("renamed");- expect(updated.recipients).toEqual([{ principalType: "user", principalId: "user-1" }]);+ expect(updated.channels.map((c) => c.id)).toEqual(["ch-webhook"]);+ expect(memberships.get("alarm-1")).toEqual(["ch-webhook"]);});- test("still rejects an email channel when the alarm has no recipients", async () => {- const { service } = seedAlarmWithChannel(AlarmChannelType.EMAIL, {});-- await expect(- service.updateAlarm({- alarmId: "alarm-1",- channels: [{ id: "c0", channelType: AlarmChannelType.EMAIL, config: {} }],- ...actor- })- ).rejects.toThrow("At least one recipient is required");+ test("update rejects a channel id outside the alarm's scope", async () => {+ const foreign = channelRow({ id: "ch-foreign", channelType: AlarmChannelType.WEBHOOK, projectId: "other" });+ const { service } = buildService({ channels: [...orgChannels, foreign] });+ await service.createAlarm(validCreate);+ await expect(service.updateAlarm({ alarmId: "alarm-1", channelIds: ["ch-foreign"], ...actor })).rejects.toThrow(+ /not found in this scope/+ );});test("deletes an alarm after checking Delete permission", async () => {- const { service, permissionCalls } = buildService();+ const { service, permissionCalls } = buildService({ channels: orgChannels });await service.createAlarm(validCreate);const result = await service.deleteAlarm({ alarmId: "alarm-1", ...actor });expect(result.id).toBe("alarm-1");diff --git a/backend/src/services/alarm/alarm-service.ts b/backend/src/services/alarm/alarm-service.tsindex 70ad18775f..403082c996 100644--- a/backend/src/services/alarm/alarm-service.ts+++ b/backend/src/services/alarm/alarm-service.ts@@ -1,26 +1,15 @@import { z } from "zod";-import { TAlarmChannels, TAlarmChannelsInsert, TAlarmRecipients, TAlarms } from "@app/db/schemas";-import { TGroupDALFactory } from "@app/ee/services/group/group-dal";+import { TAlarmChannels, TAlarms } from "@app/db/schemas";import { BadRequestError, NotFoundError } from "@app/lib/errors";-import { TKmsServiceFactory } from "@app/services/kms/kms-service";-import { TOrgDALFactory } from "@app/services/org/org-dal";-import { TProjectDALFactory } from "@app/services/project/project-dal";-import {- decryptChannelConfig,- encryptChannelConfig,- getAlarmChannelCipher,- TAlarmDecryptor-} from "./alarm-channel-crypto-fns";import { TAlarmChannelDALFactory } from "./alarm-channel-dal";+import { TAlarmChannelMembershipDALFactory } from "./alarm-channel-membership-dal";+import { TAlarmChannelSummary } from "./alarm-channel-service-types";import { AlarmChannelType } from "./alarm-channel-types";import { TAlarmDALFactory } from "./alarm-dal";import { TAlarmProviderRegistry } from "./alarm-provider-registry";-import { TAlarmRecipientDALFactory } from "./alarm-recipient-dal";import {- TAlarmChannelInput,- TAlarmChannelResponse,TAlarmResponse,TCreateAlarmDTO,TDeleteAlarmDTO,@@ -28,74 +17,34 @@ import {TListAlarmsDTO,TUpdateAlarmDTO} from "./alarm-service-types";-import { AlarmPermissionAction, AlarmPrincipalType, IResourceAlarmProvider } from "./alarm-types";+import { AlarmPermissionAction, IResourceAlarmProvider } from "./alarm-types";import { ALARM_CHANNEL_REGISTRY } from "./channels/alarm-channel-registry";export type TAlarmServiceFactoryDep = {alarmDAL: TAlarmDALFactory;- alarmChannelDAL: Pick<- TAlarmChannelDALFactory,- "insertMany" | "findByAlarmId" | "findByAlarmIds" | "updateById" | "delete"- >;- alarmRecipientDAL: Pick<- TAlarmRecipientDALFactory,- "insertMany" | "findByAlarmId" | "findByAlarmIds" | "deleteByAlarmId"- >;+ alarmChannelDAL: Pick<TAlarmChannelDALFactory, "findByIdsInScope" | "findByAlarmId" | "findByAlarmIds">;+ alarmChannelMembershipDAL: Pick<TAlarmChannelMembershipDALFactory, "insertMany" | "deleteByAlarmId">;alarmProviderRegistry: TAlarmProviderRegistry;- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;- orgDAL: Pick<TOrgDALFactory, "findMembership">;- projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;- groupDAL: Pick<TGroupDALFactory, "find">;};export type TAlarmServiceFactory = ReturnType<typeof alarmServiceFactory>;-const isValidPrincipalType = (value: string): value is AlarmPrincipalType =>- Object.values(AlarmPrincipalType).includes(value as AlarmPrincipalType);--const capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);--const $redactChannelConfig = (channelType: string, config: Record<string, unknown>): Record<string, unknown> => {- const definition = ALARM_CHANNEL_REGISTRY[channelType as AlarmChannelType];- if (!definition) return {};-- const redacted: Record<string, unknown> = {};- Object.entries(config).forEach(([key, value]) => {- if (!definition.secretFields.includes(key)) redacted[key] = value;- });- definition.secretFields.forEach((field) => {- redacted[`has${capitalize(field)}`] = Boolean(config[field]);- });- return redacted;-};--const $preserveChannelSecrets = (- channelType: string,- incomingConfig: Record<string, unknown>,- existingConfig: Record<string, unknown>-): Record<string, unknown> => {- const definition = ALARM_CHANNEL_REGISTRY[channelType as AlarmChannelType];- if (!definition) return incomingConfig;-- const merged = { ...incomingConfig };- definition.secretFields.forEach((field) => {- const incoming = merged[field];- if ((incoming === undefined || incoming === null || incoming === "") && existingConfig[field] != null) {- merged[field] = existingConfig[field];- }- });- return merged;+const toChannelSummary = (channel: TAlarmChannels): TAlarmChannelSummary => {+ const definition = ALARM_CHANNEL_REGISTRY[channel.channelType as AlarmChannelType];+ return {+ id: channel.id,+ name: channel.name,+ channelType: channel.channelType,+ directed: Boolean(definition?.directed),+ enabled: channel.enabled+ };};export const alarmServiceFactory = ({alarmDAL,alarmChannelDAL,- alarmRecipientDAL,- alarmProviderRegistry,- kmsService,- orgDAL,- projectDAL,- groupDAL+ alarmChannelMembershipDAL,+ alarmProviderRegistry}: TAlarmServiceFactoryDep) => {const $getProvider = (resourceType: string): IResourceAlarmProvider => {const provider = alarmProviderRegistry.get(resourceType);@@ -107,12 +56,7 @@ export const alarmServiceFactory = ({const $validate = (provider: IResourceAlarmProvider,- input: {- eventType?: string;- condition?: unknown;- channels?: TAlarmChannelInput[];- recipients?: { principalType: string }[];- },+ input: { eventType?: string; condition?: unknown },opts: { alwaysValidateCondition?: boolean } = {}) => {if (input.eventType && !provider.eventTypes.includes(input.eventType)) {@@ -129,168 +73,46 @@ export const alarmServiceFactory = ({throw new BadRequestError({ message: `Invalid alarm condition: ${message}` });}}-- (input.recipients ?? []).forEach((recipient) => {- if (!isValidPrincipalType(recipient.principalType)) {- throw new BadRequestError({ message: `Invalid recipient principal type '${recipient.principalType}'` });- }- });-- if (input.channels) {- if (input.channels.length === 0) {- throw new BadRequestError({ message: "At least one channel is required" });- }-- const directedChannels = input.channels.filter(- (channel) => ALARM_CHANNEL_REGISTRY[channel.channelType]?.directed- );- if (directedChannels.length > 0 && (input.recipients ?? []).length === 0) {- const directedTypes = [...new Set(directedChannels.map((channel) => channel.channelType))].join(", ");- throw new BadRequestError({ message: `At least one recipient is required for ${directedTypes} channels` });- }-- for (const channel of input.channels) {- const definition = ALARM_CHANNEL_REGISTRY[channel.channelType];- if (!definition) throw new BadRequestError({ message: `Unknown channel type '${channel.channelType}'` });-- // configSchema already enforces the Slack hooks.slack.com/https allowlist (and sendSlackNotification- // re-checks at dispatch), so no separate validateSlackWebhookUrl call is needed here.- try {- definition.configSchema.parse(channel.config);- } catch (err) {- const message =- err instanceof z.ZodError ? err.issues.map((i) => i.message).join(", ") : "Invalid channel config";- throw new BadRequestError({ message: `Invalid ${channel.channelType} channel config: ${message}` });- }- }- }};- const $validateRecipients = async (- orgId: string,- projectId: string | null | undefined,- recipients: { principalType: string; principalId: string }[]- ) => {- const userIds = [- ...new Set(- recipients- .filter((recipient) => recipient.principalType === AlarmPrincipalType.USER)- .map((recipient) => recipient.principalId)- )- ];- const groupIds = [- ...new Set(- recipients- .filter((recipient) => recipient.principalType === AlarmPrincipalType.GROUP)- .map((recipient) => recipient.principalId)- )- ];-- 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 $resolveChannelsInScope = async (+ channelIds: string[],+ scope: { orgId: string; projectId?: string | null }+ ): Promise<void> => {+ if (channelIds.length === 0) {+ throw new BadRequestError({ message: "At least one channel is required" });}-- if (userIds.length) {- const memberships = await orgDAL.findMembership({ $in: { actorUserId: userIds }, scopeOrgId: orgId });- const orgUserIds = new Set(memberships.map((membership) => membership.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(", ")}`- });- }- }-- if (groupIds.length) {- const orgGroups = await groupDAL.find({ $in: { id: groupIds }, orgId });- const orgGroupIds = new Set(orgGroups.map((group) => group.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 uniqueIds = [...new Set(channelIds)];+ const found = await alarmChannelDAL.findByIdsInScope(uniqueIds, scope);+ if (found.length !== uniqueIds.length) {+ const foundIds = new Set(found.map((c) => c.id));+ const missing = uniqueIds.filter((id) => !foundIds.has(id));+ throw new BadRequestError({ message: `Some channels were not found in this scope: ${missing.join(", ")}` });}};- const $buildResponse = (- alarm: TAlarms,- channels: TAlarmChannels[],- recipients: TAlarmRecipients[],- decryptor: TAlarmDecryptor- ): TAlarmResponse => {- const channelResponses: TAlarmChannelResponse[] = channels.map((channel) => {- const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);-- return {- id: channel.id,- channelType: channel.channelType,- config: $redactChannelConfig(channel.channelType, config),- enabled: channel.enabled,- createdAt: channel.createdAt,- updatedAt: channel.updatedAt- };- });-- return {- id: alarm.id,- name: alarm.name,- description: alarm.description ?? null,- resourceType: alarm.resourceType,- resourceId: alarm.resourceId ?? null,- eventType: alarm.eventType,- condition: alarm.condition ?? null,- filters: alarm.filters ?? null,- enabled: alarm.enabled,- orgId: alarm.orgId,- projectId: alarm.projectId ?? null,- recipients: recipients.map((recipient) => ({- principalType: recipient.principalType,- principalId: recipient.principalId- })),- channels: channelResponses,- createdAt: alarm.createdAt,- updatedAt: alarm.updatedAt- };- };+ const $buildResponse = (alarm: TAlarms, channels: TAlarmChannels[]): TAlarmResponse => ({+ id: alarm.id,+ name: alarm.name,+ description: alarm.description ?? null,+ resourceType: alarm.resourceType,+ resourceId: alarm.resourceId ?? null,+ eventType: alarm.eventType,+ condition: alarm.condition ?? null,+ filters: alarm.filters ?? null,+ enabled: alarm.enabled,+ orgId: alarm.orgId,+ projectId: alarm.projectId ?? null,+ channels: channels.map(toChannelSummary),+ createdAt: alarm.createdAt,+ updatedAt: alarm.updatedAt+ });const $formatResponse = async (alarmId: string): Promise<TAlarmResponse> => {const alarm = await alarmDAL.findById(alarmId);if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${alarmId}' not found` });-- const [channels, recipients] = await Promise.all([- alarmChannelDAL.findByAlarmId(alarmId),- alarmRecipientDAL.findByAlarmId(alarmId)- ]);-- const { decryptor } = await getAlarmChannelCipher(kmsService, {- orgId: alarm.orgId,- projectId: alarm.projectId- });-- return $buildResponse(alarm, channels, recipients, decryptor);+ const channels = await alarmChannelDAL.findByAlarmId(alarmId);+ return $buildResponse(alarm, channels);};const createAlarm = async (dto: TCreateAlarmDTO): Promise<TAlarmResponse> => {@@ -316,12 +138,7 @@ export const alarmServiceFactory = ({resourceId: dto.resourceId});- await $validateRecipients(dto.actorOrgId, dto.projectId, dto.recipients);-- const { encryptor } = await getAlarmChannelCipher(kmsService, {- orgId: dto.actorOrgId,- projectId: dto.projectId- });+ await $resolveChannelsInScope(dto.channelIds, { orgId: dto.actorOrgId, projectId: dto.projectId });const alarm = await alarmDAL.transaction(async (tx) => {const created = await alarmDAL.create(@@ -341,22 +158,8 @@ export const alarmServiceFactory = ({tx);- await alarmChannelDAL.insertMany(- dto.channels.map((channel) => ({- alarmId: created.id,- channelType: channel.channelType,- encryptedConfig: encryptChannelConfig(channel.config, encryptor),- enabled: channel.enabled ?? true- })),- tx- );-- await alarmRecipientDAL.insertMany(- dto.recipients.map((recipient) => ({- alarmId: created.id,- principalType: recipient.principalType,- principalId: recipient.principalId- })),+ await alarmChannelMembershipDAL.insertMany(+ [...new Set(dto.channelIds)].map((channelId) => ({ alarmId: created.id, channelId })),tx);@@ -411,29 +214,15 @@ export const alarmServiceFactory = ({});if (alarms.length === 0) return [];- const alarmIds = alarms.map((alarm) => alarm.id);- const [channels, recipients, { decryptor }] = await Promise.all([- alarmChannelDAL.findByAlarmIds(alarmIds),- alarmRecipientDAL.findByAlarmIds(alarmIds),- getAlarmChannelCipher(kmsService, { orgId: dto.actorOrgId, projectId: dto.projectId ?? null })- ]);-+ const channels = await alarmChannelDAL.findByAlarmIds(alarms.map((alarm) => alarm.id));const channelsByAlarm = new Map<string, TAlarmChannels[]>();channels.forEach((channel) => {const list = channelsByAlarm.get(channel.alarmId) ?? [];list.push(channel);channelsByAlarm.set(channel.alarmId, list);});- const recipientsByAlarm = new Map<string, TAlarmRecipients[]>();- recipients.forEach((recipient) => {- const list = recipientsByAlarm.get(recipient.alarmId) ?? [];- list.push(recipient);- recipientsByAlarm.set(recipient.alarmId, list);- });- return alarms.map((alarm) =>- $buildResponse(alarm, channelsByAlarm.get(alarm.id) ?? [], recipientsByAlarm.get(alarm.id) ?? [], decryptor)- );+ return alarms.map((alarm) => $buildResponse(alarm, channelsByAlarm.get(alarm.id) ?? []));};const updateAlarm = async (dto: TUpdateAlarmDTO): Promise<TAlarmResponse> => {@@ -441,7 +230,6 @@ export const alarmServiceFactory = ({if (!alarm) throw new NotFoundError({ message: `Alarm with ID '${dto.alarmId}' not found` });const provider = $getProvider(alarm.resourceType);-await provider.assertPermission({action: AlarmPermissionAction.Edit,orgId: alarm.orgId,@@ -455,38 +243,12 @@ export const alarmServiceFactory = ({}});- const { encryptor, decryptor } = await getAlarmChannelCipher(kmsService, {- orgId: alarm.orgId,- projectId: alarm.projectId- });-- $validate(provider, { condition: dto.condition, recipients: dto.recipients });- if (dto.recipients) await $validateRecipients(alarm.orgId, alarm.projectId, dto.recipients);+ if (dto.condition !== undefined) $validate(provider, { condition: dto.condition });+ if (dto.channelIds !== undefined) {+ await $resolveChannelsInScope(dto.channelIds, { orgId: alarm.orgId, projectId: alarm.projectId });+ }await alarmDAL.transaction(async (tx) => {- const existingChannels = dto.channels ? await alarmChannelDAL.findByAlarmId(alarm.id, tx) : [];- const existingChannelById = new Map(existingChannels.map((channel) => [channel.id, channel]));-- let resolvedChannels: TAlarmChannelInput[] | undefined;- if (dto.channels) {- resolvedChannels = dto.channels.map((channel) => {- const existing = channel.id ? existingChannelById.get(channel.id) : undefined;- if (!existing || existing.channelType !== channel.channelType) return channel;- const existingConfig = decryptChannelConfig<Record<string, unknown>>(existing.encryptedConfig, decryptor);- return {- ...channel,- config: $preserveChannelSecrets(- channel.channelType,- channel.config as Record<string, unknown>,- existingConfig- )- };- });-- const effectiveRecipients = dto.recipients ?? (await alarmRecipientDAL.findByAlarmId(alarm.id, tx));- $validate(provider, { channels: resolvedChannels, recipients: effectiveRecipients });- }-await alarmDAL.updateById(alarm.id,{@@ -501,40 +263,10 @@ export const alarmServiceFactory = ({tx);- if (resolvedChannels) {- const keptIds = new Set<string>();- const toInsert: TAlarmChannelsInsert[] = [];-- for (const channel of resolvedChannels) {- const existing = channel.id ? existingChannelById.get(channel.id) : undefined;- const encryptedConfig = encryptChannelConfig(channel.config, encryptor);- if (existing && existing.channelType === channel.channelType) {- keptIds.add(existing.id);- // eslint-disable-next-line no-await-in-loop- await alarmChannelDAL.updateById(existing.id, { encryptedConfig, enabled: channel.enabled ?? true }, tx);- } else {- toInsert.push({- alarmId: alarm.id,- channelType: channel.channelType,- encryptedConfig,- enabled: channel.enabled ?? true- });- }- }-- const idsToDelete = existingChannels.filter((channel) => !keptIds.has(channel.id)).map((channel) => channel.id);- if (idsToDelete.length) await alarmChannelDAL.delete({ $in: { id: idsToDelete } }, tx);- if (toInsert.length) await alarmChannelDAL.insertMany(toInsert, tx);- }-- if (dto.recipients) {- await alarmRecipientDAL.deleteByAlarmId(alarm.id, tx);- await alarmRecipientDAL.insertMany(- dto.recipients.map((recipient) => ({- alarmId: alarm.id,- principalType: recipient.principalType,- principalId: recipient.principalId- })),+ if (dto.channelIds !== undefined) {+ await alarmChannelMembershipDAL.deleteByAlarmId(alarm.id, tx);+ await alarmChannelMembershipDAL.insertMany(+ [...new Set(dto.channelIds)].map((channelId) => ({ alarmId: alarm.id, channelId })),tx);}@@ -565,11 +297,5 @@ export const alarmServiceFactory = ({return { id: alarm.id };};- return {- createAlarm,- getAlarmById,- listAlarms,- updateAlarm,- deleteAlarm- };+ return { createAlarm, getAlarmById, listAlarms, updateAlarm, deleteAlarm };};diff --git a/frontend/src/hooks/api/alarmChannels/index.ts b/frontend/src/hooks/api/alarmChannels/index.tsnew file mode 100644index 0000000000..177955438b--- /dev/null+++ b/frontend/src/hooks/api/alarmChannels/index.ts@@ -0,0 +1,3 @@+export * from "./mutations";+export * from "./queries";+export * from "./types";diff --git a/frontend/src/hooks/api/alarmChannels/mutations.ts b/frontend/src/hooks/api/alarmChannels/mutations.tsnew file mode 100644index 0000000000..6a5ebca502--- /dev/null+++ b/frontend/src/hooks/api/alarmChannels/mutations.ts@@ -0,0 +1,68 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import { alarmKeys } from "../alarms/queries";+import { alarmChannelKeys } from "./queries";+import {+ TAlarmChannel,+ TCreateAlarmChannelDTO,+ TDeleteAlarmChannelDTO,+ TUpdateAlarmChannelDTO+} from "./types";++export const useCreateAlarmChannel = () => {+ const queryClient = useQueryClient();++ return useMutation<TAlarmChannel, unknown, TCreateAlarmChannelDTO>({+ mutationFn: async (dto) => {+ const { data } = await apiRequest.post<{ channel: TAlarmChannel }>(+ "/api/v1/alarm-channels",+ dto+ );+ return data.channel;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: alarmChannelKeys.all });+ }+ });+};++export const useUpdateAlarmChannel = () => {+ const queryClient = useQueryClient();++ return useMutation<TAlarmChannel, unknown, TUpdateAlarmChannelDTO>({+ mutationFn: async ({ channelId, projectId, ...body }) => {+ const { data } = await apiRequest.patch<{ channel: TAlarmChannel }>(+ `/api/v1/alarm-channels/${channelId}`,+ body+ );+ return data.channel;+ },+ onSuccess: (_, { channelId }) => {+ queryClient.invalidateQueries({ queryKey: alarmChannelKeys.all });+ queryClient.invalidateQueries({ queryKey: alarmChannelKeys.byId(channelId) });+ // A channel's directed/enabled state shows up in alarm summaries.+ queryClient.invalidateQueries({ queryKey: alarmKeys.all });+ }+ });+};++export const useDeleteAlarmChannel = () => {+ const queryClient = useQueryClient();++ return useMutation<{ id: string }, unknown, TDeleteAlarmChannelDTO>({+ mutationFn: async ({ channelId }) => {+ const { data } = await apiRequest.delete<{ channel: { id: string } }>(+ `/api/v1/alarm-channels/${channelId}`+ );+ return data.channel;+ },+ onSuccess: (_, { channelId }) => {+ queryClient.invalidateQueries({ queryKey: alarmChannelKeys.all });+ queryClient.removeQueries({ queryKey: alarmChannelKeys.byId(channelId) });+ // Deleting a channel detaches it from alarms.+ queryClient.invalidateQueries({ queryKey: alarmKeys.all });+ }+ });+};diff --git a/frontend/src/hooks/api/alarmChannels/queries.ts b/frontend/src/hooks/api/alarmChannels/queries.tsnew file mode 100644index 0000000000..56c25d20fb--- /dev/null+++ b/frontend/src/hooks/api/alarmChannels/queries.ts@@ -0,0 +1,62 @@+import { useQuery, UseQueryOptions } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import { TAlarmChannel, TListAlarmChannelsDTO } from "./types";++export const alarmChannelKeys = {+ all: ["alarm-channels"] as const,+ list: (filters: TListAlarmChannelsDTO) => [...alarmChannelKeys.all, "list", filters] as const,+ byId: (channelId: string) => [...alarmChannelKeys.all, channelId] as const+};++const fetchAlarmChannels = async (filters: TListAlarmChannelsDTO) => {+ const { data } = await apiRequest.get<{ channels: TAlarmChannel[] }>("/api/v1/alarm-channels", {+ params: filters+ });+ return data.channels;+};++export const useListAlarmChannels = (+ filters: TListAlarmChannelsDTO,+ options?: Omit<+ UseQueryOptions<+ TAlarmChannel[],+ unknown,+ TAlarmChannel[],+ ReturnType<typeof alarmChannelKeys.list>+ >,+ "queryKey" | "queryFn"+ >+) =>+ useQuery({+ queryKey: alarmChannelKeys.list(filters),+ queryFn: () => fetchAlarmChannels(filters),+ ...options+ });++const fetchAlarmChannelById = async (channelId: string) => {+ const { data } = await apiRequest.get<{ channel: TAlarmChannel }>(+ `/api/v1/alarm-channels/${channelId}`+ );+ return data.channel;+};++export const useGetAlarmChannelById = (+ channelId: string,+ options?: Omit<+ UseQueryOptions<+ TAlarmChannel,+ unknown,+ TAlarmChannel,+ ReturnType<typeof alarmChannelKeys.byId>+ >,+ "queryKey" | "queryFn"+ >+) =>+ useQuery({+ queryKey: alarmChannelKeys.byId(channelId),+ queryFn: () => fetchAlarmChannelById(channelId),+ enabled: Boolean(channelId),+ ...options+ });diff --git a/frontend/src/hooks/api/alarmChannels/types.ts b/frontend/src/hooks/api/alarmChannels/types.tsnew file mode 100644index 0000000000..ad61cae745--- /dev/null+++ b/frontend/src/hooks/api/alarmChannels/types.ts@@ -0,0 +1,143 @@+import { z } from "zod";++import { AlarmChannelType, AlarmPrincipalType } from "../alarms/types";++export type TAlarmChannelRecipient = {+ principalType: AlarmPrincipalType;+ principalId: string;+};++export type TAlarmChannel = {+ id: string;+ name: string;+ channelType: AlarmChannelType;+ directed: boolean;+ config: Record<string, unknown>;+ enabled: boolean;+ recipients: TAlarmChannelRecipient[];+ usageCount: number;+ orgId: string;+ projectId: string | null;+ createdAt: string;+ updatedAt: string;+};++export type TListAlarmChannelsDTO = {+ projectId?: string;+};++export type TCreateAlarmChannelDTO = {+ name: string;+ channelType: AlarmChannelType;+ config: Record<string, unknown>;+ enabled?: boolean;+ recipients?: TAlarmChannelRecipient[];+ projectId?: string | null;+};++export type TUpdateAlarmChannelDTO = {+ channelId: string;+ // Carried only for cache invalidation; not sent to the API.+ projectId?: string | null;+ name?: string;+ config?: Record<string, unknown>;+ enabled?: boolean;+ recipients?: TAlarmChannelRecipient[];+};++export type TDeleteAlarmChannelDTO = {+ channelId: string;+ projectId?: string | null;+};++// A recipient chosen in the channel form. `label` is display-only (not sent to the API).+export const alarmChannelRecipientFormSchema = z.object({+ principalType: z.nativeEnum(AlarmPrincipalType),+ principalId: z.string().min(1),+ label: z.string().optional()+});++export type TAlarmChannelRecipientForm = z.infer<typeof alarmChannelRecipientFormSchema>;++// The channel form flattens per-type config into named fields; a superRefine enforces the+// per-type required fields. On edit, required secrets may be left blank to keep the existing value.+export const buildChannelFormSchema = (isEditing: boolean) =>+ z+ .object({+ name: z.string().min(1, "Name is required").max(255),+ channelType: z.nativeEnum(AlarmChannelType),+ enabled: z.boolean().default(true),+ // slack+ webhookUrl: z.string().optional(),+ // webhook+ url: z.string().optional(),+ signingSecret: z.string().optional(),+ // pagerduty+ integrationKey: z.string().optional(),+ recipients: z.array(alarmChannelRecipientFormSchema).optional()+ })+ .superRefine((data, ctx) => {+ if (data.channelType === AlarmChannelType.Slack && !isEditing && !data.webhookUrl) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["webhookUrl"],+ message: "Slack webhook URL is required"+ });+ }+ if (data.channelType === AlarmChannelType.Slack && data.webhookUrl) {+ try {+ const parsed = new URL(data.webhookUrl);+ if (parsed.protocol !== "https:" || parsed.hostname !== "hooks.slack.com") {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["webhookUrl"],+ message: "Must be a valid https://hooks.slack.com/... URL"+ });+ }+ } catch {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["webhookUrl"],+ message: "Must be a valid URL"+ });+ }+ }+ if (data.channelType === AlarmChannelType.Webhook) {+ if (!data.url || !data.url.startsWith("https://")) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["url"],+ message: "Webhook URL must be a valid HTTPS URL"+ });+ }+ }+ if (data.channelType === AlarmChannelType.PagerDuty) {+ if (!isEditing && !data.integrationKey) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["integrationKey"],+ message: "Integration key is required"+ });+ }+ if (data.integrationKey && !/^[a-f0-9]{32}$/i.test(data.integrationKey)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["integrationKey"],+ message: "Integration key must be a 32-character hex string"+ });+ }+ }+ if (+ data.channelType === AlarmChannelType.Email &&+ (!data.recipients || data.recipients.length === 0)+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["recipients"],+ message: "At least one recipient is required"+ });+ }+ });++export type TAlarmChannelForm = z.infer<ReturnType<typeof buildChannelFormSchema>>;diff --git a/frontend/src/hooks/api/alarms/types.ts b/frontend/src/hooks/api/alarms/types.tsindex 6d08e5f1ec..1288d7e43d 100644--- a/frontend/src/hooks/api/alarms/types.ts+++ b/frontend/src/hooks/api/alarms/types.ts@@ -60,18 +60,13 @@ export const ALARM_CHANNEL_TYPE_LABELS: Record<AlarmChannelType, string> = {[AlarmChannelType.PagerDuty]: "PagerDuty"};-export type TAlarmRecipient = {- principalType: AlarmPrincipalType;- principalId: string;-};--export type TAlarmChannel = {+// Lightweight channel reference embedded in an alarm (full channel lives in the alarmChannels domain).+export type TAlarmChannelSummary = {id: string;+ name: string;channelType: AlarmChannelType;- config: Record<string, unknown>;+ directed: boolean;enabled: boolean;- createdAt: string;- updatedAt: string;};export type TAlarm = {@@ -86,8 +81,7 @@ export type TAlarm = {enabled: boolean;orgId: string;projectId: string | null;- recipients: TAlarmRecipient[];- channels: TAlarmChannel[];+ channels: TAlarmChannelSummary[];createdAt: string;updatedAt: string;};@@ -99,14 +93,6 @@ export type TListAlarmsDTO = {enabled?: boolean;};-export type TAlarmChannelInput = {- // Present when editing an existing channel; lets the server preserve secret fields left blank.- id?: string;- channelType: AlarmChannelType;- config: Record<string, unknown>;- enabled?: boolean;-};-export type TCreateAlarmDTO = {name: string;description?: string;@@ -117,8 +103,7 @@ export type TCreateAlarmDTO = {filters?: unknown;enabled?: boolean;projectId?: string | null;- recipients: TAlarmRecipient[];- channels: TAlarmChannelInput[];+ channelIds: string[];};export type TUpdateAlarmDTO = {@@ -130,8 +115,7 @@ export type TUpdateAlarmDTO = {condition?: unknown;filters?: unknown;enabled?: boolean;- recipients?: TAlarmRecipient[];- channels?: TAlarmChannelInput[];+ channelIds?: string[];};export type TDeleteAlarmDTO = {@@ -139,142 +123,19 @@ export type TDeleteAlarmDTO = {projectId?: string | null;};-// --- Form schema (mirrors the PKI alert channel schemas) -----// A recipient chosen in the form. `label` is display-only (not sent to the API); `principalId` is-// the user id, group id, role slug, or raw email address depending on `principalType`.-export const alarmRecipientFormSchema = z.object({- principalType: z.nativeEnum(AlarmPrincipalType),- principalId: z.string().min(1),- label: z.string().optional()+export const alarmFormSchema = z.object({+ name: z.string().min(1, "Name is required").max(255),+ description: z.string().max(1000).optional(),+ resourceType: z.nativeEnum(AlarmResourceType),+ eventType: z.nativeEnum(AlarmEventType),+ alertBeforeValue: z+ .number({ invalid_type_error: "Enter a number" })+ .int("Must be a whole number")+ .min(1, "Must be at least 1")+ .max(3650, "Too large"),+ alertBeforeUnit: z.nativeEnum(AlarmTimeUnit),+ enabled: z.boolean().default(true),+ channelIds: z.array(z.string()).min(1, "At least one channel is required")});-export type TAlarmRecipientForm = z.infer<typeof alarmRecipientFormSchema>;--const emailChannelConfigSchema = z.object({- recipients: z- .array(alarmRecipientFormSchema)- .min(1, "At least one recipient is required")- .refine((recipients) => recipients.length <= 100, "Maximum 100 recipients allowed")- .refine(- (recipients) =>- recipients- .filter((recipient) => recipient.principalType === AlarmPrincipalType.Email)- .every((recipient) => z.string().email().safeParse(recipient.principalId).success),- "All email recipients must be valid email addresses"- )- .refine(- (recipients) =>- new Set(recipients.map((r) => `${r.principalType}:${r.principalId}`)).size ===- recipients.length,- "Duplicate recipients are not allowed"- )-});--const slackChannelConfigSchema = z.object({- webhookUrl: z- .string()- .optional()- .refine((url) => {- if (!url) return true;- try {- const parsed = new URL(url);- return parsed.protocol === "https:" && parsed.hostname === "hooks.slack.com";- } catch {- return false;- }- }, "Must be a valid https://hooks.slack.com/... URL")-});--const webhookChannelConfigSchema = z.object({- url: z- .string()- .url("Must be a valid URL")- .refine((url) => url.startsWith("https://"), "Webhook URL must use HTTPS"),- signingSecret: z.string().max(256).nullable().optional()-});--const pagerdutyChannelConfigSchema = z.object({- integrationKey: z- .string()- .optional()- .refine(- (val) => !val || /^[a-f0-9]{32}$/i.test(val),- "Integration key must be a 32-character hex string"- )-});--export const alarmChannelFormSchema = z.discriminatedUnion("channelType", [- z.object({- id: z.string().optional(),- channelType: z.literal(AlarmChannelType.Email),- config: emailChannelConfigSchema,- enabled: z.boolean().default(true)- }),- z.object({- id: z.string().optional(),- channelType: z.literal(AlarmChannelType.Slack),- config: slackChannelConfigSchema,- enabled: z.boolean().default(true)- }),- z.object({- id: z.string().optional(),- channelType: z.literal(AlarmChannelType.Webhook),- config: webhookChannelConfigSchema,- enabled: z.boolean().default(true)- }),- z.object({- id: z.string().optional(),- channelType: z.literal(AlarmChannelType.PagerDuty),- config: pagerdutyChannelConfigSchema,- enabled: z.boolean().default(true)- })-]);--export const alarmFormSchema = z- .object({- name: z.string().min(1, "Name is required").max(255),- description: z.string().max(1000).optional(),- alertBeforeValue: z- .number({ invalid_type_error: "Enter a number" })- .int("Must be a whole number")- .min(1, "Must be at least 1")- .max(3650, "Too large"),- alertBeforeUnit: z.nativeEnum(AlarmTimeUnit),- enabled: z.boolean().default(true),- channels: z- .array(alarmChannelFormSchema)- .min(1, "At least one notification channel is required")- .refine(- (channels) => channels.some((channel) => channel.enabled),- "At least one notification channel must be enabled"- )- })- .superRefine((data, ctx) => {- data.channels.forEach((channel, index) => {- if (- channel.channelType === AlarmChannelType.Slack &&- !channel.id &&- !channel.config.webhookUrl- ) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["channels", index, "config", "webhookUrl"],- message: "Slack webhook URL is required"- });- }- if (- channel.channelType === AlarmChannelType.PagerDuty &&- !channel.id &&- !channel.config.integrationKey- ) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["channels", index, "config", "integrationKey"],- message: "Integration key is required"- });- }- });- });-export type TAlarmForm = z.infer<typeof alarmFormSchema>;diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsxindex cf1f4a9438..0716360eb2 100644--- a/frontend/src/hooks/api/index.tsx+++ b/frontend/src/hooks/api/index.tsx@@ -4,6 +4,7 @@ export * from "./admin";export * from "./aiMcpActivityLogs";export * from "./aiMcpEndpoints";export * from "./aiMcpServers";+export * from "./alarmChannels";export * from "./alarms";export * from "./approvalGrants";export * from "./approvalPolicies";diff --git a/frontend/src/views/AlarmsPage/AlarmsPage.tsx b/frontend/src/views/AlarmsPage/AlarmsPage.tsxindex 2c3b2dd5d3..d50df6b2e8 100644--- a/frontend/src/views/AlarmsPage/AlarmsPage.tsx+++ b/frontend/src/views/AlarmsPage/AlarmsPage.tsx@@ -1,10 +1,12 @@-import { ComponentProps } from "react";+import { ComponentProps, useState } from "react";import { Helmet } from "react-helmet";import { Bell } from "lucide-react";-import { PageHeader } from "@app/components/v2";+import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";+import { useScopeVariant } from "@app/hooks";import { AlarmsTable } from "./components/AlarmsTable";+import { ChannelsTable } from "./components/channels/ChannelsTable";type Props = {projectId?: string;@@ -12,7 +14,16 @@ type Props = {scope: ComponentProps<typeof PageHeader>["scope"];};+enum AlarmsPageTab {+ Alarms = "alarms",+ Channels = "channels"+}+export const AlarmsPage = ({ projectId, scopeName, scope }: Props) => {+ const scopeVariant = useScopeVariant();+ const tabVariant = scopeVariant === "sub-org" ? "namespace" : scopeVariant;+ const [selectedTab, setSelectedTab] = useState<string>(AlarmsPageTab.Alarms);+return (<div className="h-full bg-bunker-800"><Helmet>@@ -27,7 +38,22 @@ export const AlarmsPage = ({ projectId, scopeName, scope }: Props) => {title="Alarms"description="Route resource events to recipients over your channels. An alarm covers a bound resource, or every resource matching a filter."/>- <AlarmsTable projectId={projectId} scopeName={scopeName} />+ <Tabs value={selectedTab} onValueChange={setSelectedTab}>+ <TabList>+ <Tab variant={tabVariant} value={AlarmsPageTab.Alarms}>+ Alarms+ </Tab>+ <Tab variant={tabVariant} value={AlarmsPageTab.Channels}>+ Channels+ </Tab>+ </TabList>+ <TabPanel value={AlarmsPageTab.Alarms}>+ <AlarmsTable projectId={projectId} scopeName={scopeName} />+ </TabPanel>+ <TabPanel value={AlarmsPageTab.Channels}>+ <ChannelsTable projectId={projectId} />+ </TabPanel>+ </Tabs></div></div></div>diff --git a/frontend/src/views/AlarmsPage/components/AlarmChannelsField.tsx b/frontend/src/views/AlarmsPage/components/AlarmChannelsField.tsxdeleted file mode 100644index c44be380dd..0000000000--- a/frontend/src/views/AlarmsPage/components/AlarmChannelsField.tsx+++ /dev/null@@ -1,278 +0,0 @@-import { Controller, useFieldArray, useFormContext } from "react-hook-form";-import {- BellIcon,- ChevronDownIcon,- HashIcon,- LinkIcon,- MailIcon,- PlusIcon,- Trash2Icon-} from "lucide-react";--import {- Button,- Card,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- Field,- FieldContent,- FieldDescription,- FieldError,- FieldLabel,- IconButton,- Input,- Switch-} from "@app/components/v3";-import { useScopeVariant } from "@app/hooks";-import { ALARM_CHANNEL_TYPE_LABELS, AlarmChannelType, TAlarmForm } from "@app/hooks/api/alarms";--import { AlarmRecipientsField } from "./AlarmRecipientsField";--const MAX_CHANNELS = 10;--const CHANNEL_ICONS: Record<AlarmChannelType, typeof MailIcon> = {- [AlarmChannelType.Email]: MailIcon,- [AlarmChannelType.Slack]: HashIcon,- [AlarmChannelType.Webhook]: LinkIcon,- [AlarmChannelType.PagerDuty]: BellIcon-};--const getDefaultConfig = (type: AlarmChannelType): Record<string, unknown> => {- switch (type) {- case AlarmChannelType.Email:- return { recipients: [] };- case AlarmChannelType.Slack:- return { webhookUrl: "" };- case AlarmChannelType.Webhook:- return { url: "", signingSecret: "" };- case AlarmChannelType.PagerDuty:- return { integrationKey: "" };- default:- return {};- }-};--export const AlarmChannelsField = () => {- const {- control,- watch,- formState: { errors }- } = useFormContext<TAlarmForm>();-- const { fields, append, remove } = useFieldArray({ control, name: "channels" });- const scopeVariant = useScopeVariant();-- const channels = watch("channels");- const hasEmailChannel = channels?.some(- (channel) => channel.channelType === AlarmChannelType.Email- );- const isLimitReached = fields.length >= MAX_CHANNELS;-- const addChannel = (type: AlarmChannelType) => {- append({ channelType: type, config: getDefaultConfig(type), enabled: true } as never);- };-- const rootError = errors.channels?.message || errors.channels?.root?.message;-- return (- <div className="flex flex-col gap-3">- <div className="flex items-center justify-between">- <div className="flex flex-col">- <span className="text-sm text-mineshaft-100">Notification Channels</span>- <span className="text-xs text-mineshaft-400">- Where this alarm delivers when it fires.- </span>- </div>- <DropdownMenu>- <DropdownMenuTrigger asChild disabled={isLimitReached}>- <Button type="button" variant="outline" size="sm" isDisabled={isLimitReached}>- <PlusIcon className="size-4" />- Add Channel- <ChevronDownIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="end"- sideOffset={4}- className="min-w-[var(--radix-dropdown-menu-trigger-width)]"- >- <DropdownMenuItem- isDisabled={hasEmailChannel}- onClick={() => addChannel(AlarmChannelType.Email)}- >- <MailIcon />- </DropdownMenuItem>- <DropdownMenuItem onClick={() => addChannel(AlarmChannelType.Slack)}>- <HashIcon />- Slack- </DropdownMenuItem>- <DropdownMenuItem onClick={() => addChannel(AlarmChannelType.Webhook)}>- <LinkIcon />- Webhook- </DropdownMenuItem>- <DropdownMenuItem onClick={() => addChannel(AlarmChannelType.PagerDuty)}>- <BellIcon />- PagerDuty- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>-- {rootError && <p className="text-xs text-red-500">{rootError}</p>}-- {fields.length === 0 ? (- <div className="rounded-lg border border-dashed border-border p-4 text-center text-sm text-muted">- No channels added yet. Add at least one channel to receive notifications.- </div>- ) : (- fields.map((field, index) => {- const channelType = channels?.[index]?.channelType;- const Icon = channelType ? CHANNEL_ICONS[channelType] : BellIcon;-- return (- <Card key={field.id} className="gap-0 p-0">- <div className="flex items-center justify-between border-b border-border px-4 py-3">- <div className="flex items-center gap-2 text-sm text-foreground">- <Icon className="size-4 text-muted" />- {channelType ? ALARM_CHANNEL_TYPE_LABELS[channelType] : "Channel"}- </div>- <div className="flex items-center gap-3">- <Controller- control={control}- name={`channels.${index}.enabled`}- render={({ field: enabledField }) => (- <Switch- id={`channel-enabled-${field.id}`}- size="sm"- variant={scopeVariant}- checked={enabledField.value}- onCheckedChange={enabledField.onChange}- />- )}- />- <IconButton- aria-label="Remove channel"- variant="ghost"- size="xs"- onClick={() => remove(index)}- >- <Trash2Icon className="size-4" />- </IconButton>- </div>- </div>-- <div className="p-4">- {channelType === AlarmChannelType.Email && <AlarmRecipientsField index={index} />}-- {channelType === AlarmChannelType.Slack && (- <Controller- control={control}- name={`channels.${index}.config.webhookUrl`}- render={({ field: urlField, fieldState: { error } }) => (- <Field>- <FieldLabel>Slack Webhook URL</FieldLabel>- <FieldContent>- <Input- placeholder="https://hooks.slack.com/services/..."- isError={Boolean(error)}- value={(urlField.value as string) ?? ""}- onChange={urlField.onChange}- onBlur={urlField.onBlur}- />- <FieldDescription>- Create an Incoming Webhook in your Slack workspace settings. Existing- URLs are hidden; leave blank to keep the current one.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- )}-- {channelType === AlarmChannelType.Webhook && (- <div className="flex flex-col gap-4">- <Controller- control={control}- name={`channels.${index}.config.url`}- render={({ field: urlField, fieldState: { error } }) => (- <Field>- <FieldLabel>Webhook URL</FieldLabel>- <FieldContent>- <Input- placeholder="https://api.example.com/webhook"- isError={Boolean(error)}- value={(urlField.value as string) ?? ""}- onChange={urlField.onChange}- onBlur={urlField.onBlur}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- <Controller- control={control}- name={`channels.${index}.config.signingSecret`}- render={({ field: secretField, fieldState: { error } }) => (- <Field>- <FieldLabel>- Signing Secret <span className="text-mineshaft-400">(optional)</span>- </FieldLabel>- <FieldContent>- <Input- type="password"- placeholder="Enter signing secret..."- isError={Boolean(error)}- value={(secretField.value as string) ?? ""}- onChange={secretField.onChange}- onBlur={secretField.onBlur}- />- <FieldDescription>- Adds an x-infisical-signature header so receivers can verify payloads.- Existing secrets are hidden; leave blank to keep the webhook unsigned.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- </div>- )}-- {channelType === AlarmChannelType.PagerDuty && (- <Controller- control={control}- name={`channels.${index}.config.integrationKey`}- render={({ field: keyField, fieldState: { error } }) => (- <Field>- <FieldLabel>Integration Key</FieldLabel>- <FieldContent>- <Input- placeholder="32-character hex integration key"- isError={Boolean(error)}- value={(keyField.value as string) ?? ""}- onChange={keyField.onChange}- onBlur={keyField.onBlur}- />- <FieldDescription>- Find this in PagerDuty under Services → Integrations → Events API v2.- Existing keys are hidden; leave blank to keep the current one.- </FieldDescription>- <FieldError errors={[error]} />- </FieldContent>- </Field>- )}- />- )}- </div>- </Card>- );- })- )}- </div>- );-};diff --git a/frontend/src/views/AlarmsPage/components/AlarmForm.tsx b/frontend/src/views/AlarmsPage/components/AlarmForm.tsxindex 6e6989f815..c8ed148b33 100644--- a/frontend/src/views/AlarmsPage/components/AlarmForm.tsx+++ b/frontend/src/views/AlarmsPage/components/AlarmForm.tsx@@ -30,23 +30,17 @@ import {ALARM_EVENT_TYPE_LABELS,ALARM_RESOURCE_TYPE_LABELS,ALARM_TIME_UNIT_LABELS,- AlarmChannelType,AlarmEventType,alarmFormSchema,AlarmResourceType,AlarmTimeUnit,TAlarm,- TAlarmChannelInput,TAlarmForm,- TAlarmRecipient,useCreateAlarm,useUpdateAlarm} from "@app/hooks/api/alarms";-import { AlarmChannelsField } from "./AlarmChannelsField";--const RESOURCE_TYPE_VALUE = AlarmResourceType.IdentityCredential;-const EVENT_TYPE_VALUE = AlarmEventType.IdentityCredentialExpiry;+import { AttachChannelsField } from "./AttachChannelsField";type Props = {projectId?: string;@@ -83,118 +77,31 @@ const parseAlertBefore = (alertBefore?: string): { value: number; unit: AlarmTimreturn { value: 7, unit: AlarmTimeUnit.Days };};-const buildChannelsPayload = (channels: TAlarmForm["channels"]): TAlarmChannelInput[] =>- channels.map((channel) => {- const id = channel.id ? { id: channel.id } : {};- switch (channel.channelType) {- case AlarmChannelType.Slack:- return {- ...id,- channelType: AlarmChannelType.Slack,- config: channel.config.webhookUrl ? { webhookUrl: channel.config.webhookUrl } : {},- enabled: channel.enabled- };- case AlarmChannelType.Webhook: {- const config: Record<string, unknown> = { url: channel.config.url };- if (channel.config.signingSecret) config.signingSecret = channel.config.signingSecret;- return { ...id, channelType: AlarmChannelType.Webhook, config, enabled: channel.enabled };- }- case AlarmChannelType.PagerDuty:- return {- ...id,- channelType: AlarmChannelType.PagerDuty,- config: channel.config.integrationKey- ? { integrationKey: channel.config.integrationKey }- : {},- enabled: channel.enabled- };- case AlarmChannelType.Email:- default:- return { ...id, channelType: AlarmChannelType.Email, config: {}, enabled: channel.enabled };- }- });--const buildRecipientsPayload = (channels: TAlarmForm["channels"]): TAlarmRecipient[] => {- const seen = new Set<string>();- const recipients: TAlarmRecipient[] = [];- channels.forEach((channel) => {- if (channel.channelType === AlarmChannelType.Email) {- channel.config.recipients.forEach(({ principalType, principalId }) => {- const key = `${principalType}:${principalId}`;- if (!seen.has(key)) {- seen.add(key);- recipients.push({ principalType, principalId });- }- });- }- });- return recipients;-};-const buildFormDefaults = (alarm?: TAlarm): TAlarmForm => {if (!alarm) {return {name: "",description: "",+ resourceType: AlarmResourceType.IdentityCredential,+ eventType: AlarmEventType.IdentityCredentialExpiry,alertBeforeValue: 7,alertBeforeUnit: AlarmTimeUnit.Days,enabled: true,- channels: []+ channelIds: []};}- const emailRecipients = alarm.recipients.map((recipient) => ({- principalType: recipient.principalType,- principalId: recipient.principalId,- label: recipient.principalId- }));-- const channels = alarm.channels- .map((channel) => {- switch (channel.channelType) {- case AlarmChannelType.Email:- return {- id: channel.id,- channelType: AlarmChannelType.Email,- config: { recipients: emailRecipients },- enabled: channel.enabled- };- case AlarmChannelType.Slack:- return {- id: channel.id,- channelType: AlarmChannelType.Slack,- config: { webhookUrl: "" },- enabled: channel.enabled- };- case AlarmChannelType.Webhook:- return {- id: channel.id,- channelType: AlarmChannelType.Webhook,- config: { url: (channel.config.url as string) ?? "", signingSecret: "" },- enabled: channel.enabled- };- case AlarmChannelType.PagerDuty:- return {- id: channel.id,- channelType: AlarmChannelType.PagerDuty,- config: { integrationKey: "" },- enabled: channel.enabled- };- default:- return null;- }- })- .filter(Boolean) as TAlarmForm["channels"];-const { value, unit } = parseAlertBefore(alarm.condition?.alertBefore);return {name: alarm.name,description: alarm.description ?? "",+ resourceType: (alarm.resourceType as AlarmResourceType) ?? AlarmResourceType.IdentityCredential,+ eventType: (alarm.eventType as AlarmEventType) ?? AlarmEventType.IdentityCredentialExpiry,alertBeforeValue: value,alertBeforeUnit: unit,enabled: alarm.enabled,- channels+ channelIds: alarm.channels.map((channel) => channel.id)};};@@ -237,7 +144,7 @@ export const AlarmForm = ({ projectId, scopeName, alarm, onComplete, onCancel }:const alertBefore = `${data.alertBeforeValue}${data.alertBeforeUnit}`;try {if (isEditing && alarm) {- const channelsDirty = Boolean(dirtyFields.channels);+ const channelsDirty = Boolean(dirtyFields.channelIds);await updateAlarm.mutateAsync({alarmId: alarm.id,projectId: alarm.projectId,@@ -245,27 +152,21 @@ export const AlarmForm = ({ projectId, scopeName, alarm, onComplete, onCancel }:description: data.description || null,enabled: data.enabled,condition: { alertBefore },- ...(channelsDirty- ? {- channels: buildChannelsPayload(data.channels),- recipients: buildRecipientsPayload(data.channels)- }- : {})+ ...(channelsDirty ? { channelIds: data.channelIds } : {})});createNotification({ text: "Successfully updated alarm", type: "success" });} else {await createAlarm.mutateAsync({name: data.name,description: data.description || undefined,- resourceType: RESOURCE_TYPE_VALUE,+ resourceType: data.resourceType,resourceId: null,- eventType: EVENT_TYPE_VALUE,+ eventType: data.eventType,condition: { alertBefore },filters: null,enabled: data.enabled,projectId: projectId ?? null,- recipients: buildRecipientsPayload(data.channels),- channels: buildChannelsPayload(data.channels)+ channelIds: data.channelIds});createNotification({ text: "Successfully created alarm", type: "success" });}@@ -322,15 +223,35 @@ export const AlarmForm = ({ projectId, scopeName, alarm, onComplete, onCancel }:<section className="flex flex-col gap-4"><SectionHeader step={2} title="Trigger" />- <FixedField label="Resource type">- <KeyRoundIcon className="size-5 text-blue-400" />- <div className="flex flex-col">- <span className="text-sm text-foreground">- {ALARM_RESOURCE_TYPE_LABELS[RESOURCE_TYPE_VALUE]}- </span>- <span className="font-mono text-xs text-muted">{RESOURCE_TYPE_VALUE}</span>- </div>- </FixedField>+ <Controller+ control={control}+ name="resourceType"+ render={({ field: { value, onChange } }) => (+ <Field>+ <FieldLabel>Resource type</FieldLabel>+ <FieldContent>+ <Select value={value} onValueChange={onChange}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(AlarmResourceType).map((resourceType) => (+ <SelectItem key={resourceType} value={resourceType}>+ <span className="flex items-center gap-2">+ <KeyRoundIcon className="size-4 text-blue-400" />+ <span className="font-medium">+ {ALARM_RESOURCE_TYPE_LABELS[resourceType]}+ </span>+ <span className="font-mono text-xs text-muted">{resourceType}</span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ )}+ /><FixedField label="Scope"><ScopeIcon className={`size-5 ${scopeColor}`} />@@ -340,10 +261,34 @@ export const AlarmForm = ({ projectId, scopeName, alarm, onComplete, onCancel }:</div></FixedField>- <FixedField label="Event">- <Badge variant="warning">{ALARM_EVENT_TYPE_LABELS[EVENT_TYPE_VALUE]}</Badge>- <span className="text-xs text-muted">Fires as the credential nears expiration</span>- </FixedField>+ <Controller+ control={control}+ name="eventType"+ render={({ field: { value, onChange } }) => (+ <Field>+ <FieldLabel>Event</FieldLabel>+ <FieldContent>+ <Select value={value} onValueChange={onChange}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(AlarmEventType).map((eventType) => (+ <SelectItem key={eventType} value={eventType}>+ <span className="flex items-center gap-2">+ <Badge variant="warning">{ALARM_EVENT_TYPE_LABELS[eventType]}</Badge>+ <span className="text-mineshaft-300">+ Fires as the credential nears expiration+ </span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ )}+ /><div className="flex flex-col gap-1.5"><FieldLabel>Condition</FieldLabel>@@ -384,7 +329,7 @@ export const AlarmForm = ({ projectId, scopeName, alarm, onComplete, onCancel }:<section className="flex flex-col gap-4"><SectionHeader step={3} title="Delivery" />- <AlarmChannelsField />+ <AttachChannelsField projectId={projectId} /></section></div>diff --git a/frontend/src/views/AlarmsPage/components/AlarmRow.tsx b/frontend/src/views/AlarmsPage/components/AlarmRow.tsxindex f4f153353c..acee5f27e6 100644--- a/frontend/src/views/AlarmsPage/components/AlarmRow.tsx+++ b/frontend/src/views/AlarmsPage/components/AlarmRow.tsx@@ -7,10 +7,7 @@ import {LinkIcon,MailIcon,PencilIcon,- ShieldIcon,- Trash2Icon,- UserIcon,- UsersIcon+ Trash2Icon} from "lucide-react";import {@@ -20,25 +17,17 @@ import {DropdownMenuItem,DropdownMenuTrigger,IconButton,- Popover,- PopoverContent,- PopoverTrigger,TableCell,- TableRow,- Tooltip,- TooltipContent,- TooltipTrigger+ TableRow} from "@app/components/v3";import {- ALARM_CHANNEL_TYPE_LABELS,ALARM_EVENT_TYPE_LABELS,ALARM_RESOURCE_TYPE_LABELS,AlarmChannelType,AlarmEventType,- AlarmPrincipalType,AlarmResourceType,TAlarm,- TAlarmRecipient+ TAlarmChannelSummary} from "@app/hooks/api/alarms";type LucideIcon = typeof MailIcon;@@ -54,21 +43,13 @@ const CHANNEL_ICONS: Record<AlarmChannelType, LucideIcon> = {[AlarmChannelType.PagerDuty]: AlertTriangleIcon};-const RECIPIENT_ICONS: Record<AlarmPrincipalType, LucideIcon> = {- [AlarmPrincipalType.Email]: MailIcon,- [AlarmPrincipalType.User]: UserIcon,- [AlarmPrincipalType.Group]: UsersIcon,- [AlarmPrincipalType.Role]: ShieldIcon-};-type Props = {alarm: TAlarm;- resolveRecipientLabel: (recipient: TAlarmRecipient) => string;onEdit: (alarm: TAlarm) => void;onDelete: (alarm: TAlarm) => void;};-export const AlarmRow = ({ alarm, resolveRecipientLabel, onEdit, onDelete }: Props) => {+export const AlarmRow = ({ alarm, onEdit, onDelete }: Props) => {const ResourceIcon = RESOURCE_ICONS[alarm.resourceType] ?? KeyRoundIcon;const resourceLabel =ALARM_RESOURCE_TYPE_LABELS[alarm.resourceType as AlarmResourceType] ?? alarm.resourceType;@@ -77,19 +58,17 @@ export const AlarmRow = ({ alarm, resolveRecipientLabel, onEdit, onDelete }: Pro? `Alert before ${alarm.condition.alertBefore}`: "On event";- const [firstRecipient, ...restRecipients] = alarm.recipients;-- const renderRecipient = (recipient: TAlarmRecipient) => {- const Icon = RECIPIENT_ICONS[recipient.principalType];+ const renderChannel = (channel: TAlarmChannelSummary) => {+ const Icon = CHANNEL_ICONS[channel.channelType] ?? BellIcon;return (<Badge- key={`${recipient.principalType}:${recipient.principalId}`}+ key={channel.id}variant="neutral"isTruncatable- className="max-w-[10rem]"+ className={`max-w-[10rem] ${channel.enabled ? "" : "opacity-40"}`}><Icon className="size-3" />- <span>{resolveRecipientLabel(recipient)}</span>+ <span>{channel.name}</span></Badge>);};@@ -102,9 +81,7 @@ export const AlarmRow = ({ alarm, resolveRecipientLabel, onEdit, onDelete }: Pro<TableCell><div className="flex items-center gap-2"><ResourceIcon className="size-4 shrink-0 text-muted" />- <div className="flex flex-col">- <span className="text-foreground">{resourceLabel}</span>- </div>+ <span className="text-foreground">{resourceLabel}</span></div></TableCell><TableCell>@@ -112,60 +89,14 @@ export const AlarmRow = ({ alarm, resolveRecipientLabel, onEdit, onDelete }: Pro</TableCell><TableCell>{condition}</TableCell><TableCell>- {firstRecipient ? (- <div className="flex items-center gap-1">- {renderRecipient(firstRecipient)}- {restRecipients.length > 0 && (- <Popover>- <Tooltip>- <TooltipTrigger className="flex h-4 items-center">- <PopoverTrigger asChild>- <Badge variant="neutral" asChild>- <button type="button" onClick={(e) => e.stopPropagation()}>- +{restRecipients.length}- </button>- </Badge>- </PopoverTrigger>- </TooltipTrigger>- <TooltipContent>Click to view all recipients</TooltipContent>- </Tooltip>- <PopoverContent- side="right"- className="flex w-auto max-w-sm flex-wrap gap-1.5"- onClick={(e) => e.stopPropagation()}- >- {restRecipients.map((recipient) => renderRecipient(recipient))}- </PopoverContent>- </Popover>- )}+ {alarm.channels.length ? (+ <div className="flex flex-wrap items-center gap-1">+ {alarm.channels.map(renderChannel)}</div>) : (<span className="text-muted">—</span>)}</TableCell>- <TableCell>- <div className="flex items-center gap-2 text-muted">- {alarm.channels.length ? (- alarm.channels.map((channel) => {- const Icon = CHANNEL_ICONS[channel.channelType as AlarmChannelType] ?? BellIcon;- return (- <span- key={channel.id}- title={- ALARM_CHANNEL_TYPE_LABELS[channel.channelType as AlarmChannelType] ??- channel.channelType- }- className={channel.enabled ? "" : "opacity-40"}- >- <Icon className="size-4" />- </span>- );- })- ) : (- <span>—</span>- )}- </div>- </TableCell><TableCell><Badge variant={alarm.enabled ? "success" : "neutral"}>{alarm.enabled ? "Enabled" : "Disabled"}diff --git a/frontend/src/views/AlarmsPage/components/AlarmsTable.tsx b/frontend/src/views/AlarmsPage/components/AlarmsTable.tsxindex 4a0ac6a7bf..60212be358 100644--- a/frontend/src/views/AlarmsPage/components/AlarmsTable.tsx+++ b/frontend/src/views/AlarmsPage/components/AlarmsTable.tsx@@ -26,18 +26,11 @@ import {TableHeader,TableRow} from "@app/components/v3";-import { OrgPermissionSubjects, ProjectPermissionSub, useOrganization } from "@app/context";+import { OrgPermissionSubjects, ProjectPermissionSub } from "@app/context";import { OrgPermissionIdentityActions } from "@app/context/OrgPermissionContext/types";import { ProjectPermissionIdentityActions } from "@app/context/ProjectPermissionContext/types";import { usePagination, usePopUp, useResetPageHelper, useScopeVariant } from "@app/hooks";-import { useGetOrganizationGroups, useGetOrgUsers } from "@app/hooks/api";-import {- AlarmPrincipalType,- AlarmResourceType,- TAlarm,- TAlarmRecipient,- useListAlarms-} from "@app/hooks/api/alarms";+import { AlarmResourceType, TAlarm, useListAlarms } from "@app/hooks/api/alarms";import { AddAlarmModal } from "./AddAlarmModal";import { AlarmRow } from "./AlarmRow";@@ -51,36 +44,12 @@ type Props = {export const AlarmsTable = ({ projectId, scopeName }: Props) => {const isProjectView = Boolean(projectId);const scopeVariant = useScopeVariant();- const { currentOrg } = useOrganization();const { isPending, data: allAlarms = [] } = useListAlarms({resourceType: AlarmResourceType.IdentityCredential,...(projectId ? { projectId } : {})});- const { data: orgUsers = [] } = useGetOrgUsers(currentOrg.id);- const { data: orgGroups = [] } = useGetOrganizationGroups(currentOrg.id);-- const resolveRecipientLabel = useMemo(() => {- const lookup = new Map<string, string>();- orgUsers.forEach((member) => {- if (member.user?.id) {- lookup.set(- `${AlarmPrincipalType.User}:${member.user.id}`,- member.user.username || member.user.email || member.user.id- );- }- });- orgGroups.forEach((group) => lookup.set(`${AlarmPrincipalType.Group}:${group.id}`, group.name));-- return (recipient: TAlarmRecipient) => {- if (recipient.principalType === AlarmPrincipalType.Email) return recipient.principalId;- return (- lookup.get(`${recipient.principalType}:${recipient.principalId}`) ?? recipient.principalId- );- };- }, [orgUsers, orgGroups]);-const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["addAlarm","editAlarm",@@ -177,7 +146,6 @@ export const AlarmsTable = ({ projectId, scopeName }: Props) => {<TableHead>Resource</TableHead><TableHead>Event</TableHead><TableHead>Condition</TableHead>- <TableHead>Recipients</TableHead><TableHead>Channels</TableHead><TableHead>Status</TableHead><TableHead className="w-5" />@@ -187,7 +155,7 @@ export const AlarmsTable = ({ projectId, scopeName }: Props) => {{isPending &&Array.from({ length: 5 }).map((_, i) => (<TableRow key={`skeleton-${i + 1}`}>- {Array.from({ length: 8 }).map((__, j) => (+ {Array.from({ length: 7 }).map((__, j) => (<TableCell key={`skeleton-cell-${i + 1}-${j + 1}`}><Skeleton className="h-4 w-full" /></TableCell>@@ -199,7 +167,6 @@ export const AlarmsTable = ({ projectId, scopeName }: Props) => {<AlarmRowkey={alarm.id}alarm={alarm}- resolveRecipientLabel={resolveRecipientLabel}onEdit={(data) => handlePopUpOpen("editAlarm", data)}onDelete={(data) => handlePopUpOpen("deleteAlarm", data)}/>diff --git a/frontend/src/views/AlarmsPage/components/AttachChannelsField.tsx b/frontend/src/views/AlarmsPage/components/AttachChannelsField.tsxnew file mode 100644index 0000000000..11a5048ad5--- /dev/null+++ b/frontend/src/views/AlarmsPage/components/AttachChannelsField.tsx@@ -0,0 +1,159 @@+import { useState } from "react";+import { Controller, useFormContext } from "react-hook-form";+import {+ AlertTriangleIcon,+ BellIcon,+ ChevronDownIcon,+ HashIcon,+ LinkIcon,+ MailIcon,+ PlusIcon,+ XIcon+} from "lucide-react";++import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ FieldLabel,+ IconButton,+ Skeleton+} from "@app/components/v3";+import { TAlarmChannel, useListAlarmChannels } from "@app/hooks/api/alarmChannels";+import { AlarmChannelType, TAlarmForm } from "@app/hooks/api/alarms";++import { AddChannelModal } from "./channels/AddChannelModal";++type LucideIcon = typeof MailIcon;++const CHANNEL_ICONS: Record<AlarmChannelType, LucideIcon> = {+ [AlarmChannelType.Email]: MailIcon,+ [AlarmChannelType.Slack]: HashIcon,+ [AlarmChannelType.Webhook]: LinkIcon,+ [AlarmChannelType.PagerDuty]: AlertTriangleIcon+};++type Props = {+ projectId?: string;+};++export const AttachChannelsField = ({ projectId }: Props) => {+ const {+ control,+ formState: { errors }+ } = useFormContext<TAlarmForm>();+ const { isPending, data: channels = [] } = useListAlarmChannels(projectId ? { projectId } : {});+ const [isChannelModalOpen, setIsChannelModalOpen] = useState(false);++ const byId = new Map(channels.map((c) => [c.id, c]));+ const rootError = errors.channelIds?.message || errors.channelIds?.root?.message;++ return (+ <Controller+ control={control}+ name="channelIds"+ render={({ field }) => {+ const selectedIds: string[] = field.value ?? [];+ const available = channels.filter((c) => !selectedIds.includes(c.id));++ const renderCard = (channel: TAlarmChannel) => {+ const Icon = CHANNEL_ICONS[channel.channelType] ?? BellIcon;+ return (+ <div+ key={channel.id}+ className="flex items-center justify-between rounded-md border border-border p-3"+ >+ <div className="flex items-center gap-3">+ <Icon className="size-4 text-muted" />+ <span className="text-sm text-foreground">{channel.name}</span>+ </div>+ <IconButton+ aria-label="Detach channel"+ variant="ghost"+ size="xs"+ onClick={() => field.onChange(selectedIds.filter((id) => id !== channel.id))}+ >+ <XIcon className="size-4" />+ </IconButton>+ </div>+ );+ };++ return (+ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div className="flex flex-col">+ <FieldLabel>+ Channels <span className="text-red">*</span>+ </FieldLabel>+ <span className="text-xs text-muted">+ Pick from your channels, at least one is required.+ </span>+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={available.length === 0}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ isDisabled={available.length === 0}+ >+ <PlusIcon className="size-4" />+ Attach channel+ <ChevronDownIcon className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ sideOffset={4}+ className="max-h-64 min-w-[var(--radix-dropdown-menu-trigger-width)] overflow-y-auto"+ >+ {available.map((channel) => {+ const Icon = CHANNEL_ICONS[channel.channelType] ?? BellIcon;+ return (+ <DropdownMenuItem+ key={channel.id}+ onClick={() => field.onChange([...selectedIds, channel.id])}+ >+ <Icon className="size-4" />+ {channel.name}+ </DropdownMenuItem>+ );+ })}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ {rootError && <p className="text-xs text-red-500">{rootError}</p>}++ {isPending ? (+ <Skeleton className="h-16 w-full" />+ ) : (+ <div className="flex flex-col gap-2">+ {selectedIds.length === 0 ? (+ <div className="rounded-lg border border-dashed border-border p-4 text-center text-sm text-muted">+ No channels attached yet. Attach at least one channel to receive notifications.+ </div>+ ) : (+ selectedIds+ .map((id) => byId.get(id))+ .filter((c): c is TAlarmChannel => Boolean(c))+ .map(renderCard)+ )}+ </div>+ )}++ <AddChannelModal+ isOpen={isChannelModalOpen}+ onOpenChange={setIsChannelModalOpen}+ projectId={projectId}+ onCreated={(channelId) => field.onChange([...selectedIds, channelId])}+ />+ </div>+ );+ }}+ />+ );+};diff --git a/frontend/src/views/AlarmsPage/components/channels/AddChannelModal.tsx b/frontend/src/views/AlarmsPage/components/channels/AddChannelModal.tsxnew file mode 100644index 0000000000..0253269f45--- /dev/null+++ b/frontend/src/views/AlarmsPage/components/channels/AddChannelModal.tsx@@ -0,0 +1,39 @@+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@app/components/v3";+import { TAlarmChannel } from "@app/hooks/api/alarmChannels";++import { ChannelForm } from "./ChannelForm";++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ projectId?: string;+ channel?: TAlarmChannel;+ onCreated?: (channelId: string) => void;+};++export const AddChannelModal = ({ isOpen, onOpenChange, projectId, channel, onCreated }: Props) => {+ const isEditing = Boolean(channel);++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-xl">+ <SheetHeader className="border-b">+ <SheetTitle>{isEditing ? "Edit Channel" : "Add Channel"}</SheetTitle>+ <SheetDescription>A delivery destination that any alarm can reference.</SheetDescription>+ </SheetHeader>+ {isOpen && (+ <ChannelForm+ key={channel?.id ?? "new"}+ projectId={projectId}+ channel={channel}+ onComplete={(channelId) => {+ onCreated?.(channelId);+ onOpenChange(false);+ }}+ onCancel={() => onOpenChange(false)}+ />+ )}+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/views/AlarmsPage/components/channels/ChannelForm.tsx b/frontend/src/views/AlarmsPage/components/channels/ChannelForm.tsxnew file mode 100644index 0000000000..a6f362f523--- /dev/null+++ b/frontend/src/views/AlarmsPage/components/channels/ChannelForm.tsx@@ -0,0 +1,360 @@+import { useState } from "react";+import { Controller, FormProvider, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { AlertTriangleIcon, HashIcon, LinkIcon, MailIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Checkbox,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ SheetFooter,+ Switch+} from "@app/components/v3";+import { useScopeVariant } from "@app/hooks";+import {+ buildChannelFormSchema,+ TAlarmChannel,+ TAlarmChannelForm,+ TAlarmChannelRecipientForm,+ useCreateAlarmChannel,+ useUpdateAlarmChannel+} from "@app/hooks/api/alarmChannels";+import { ALARM_CHANNEL_TYPE_LABELS, AlarmChannelType } from "@app/hooks/api/alarms";++import { ChannelRecipientsField } from "./ChannelRecipientsField";++const CHANNEL_TYPES: { type: AlarmChannelType; icon: typeof MailIcon }[] = [+ { type: AlarmChannelType.Email, icon: MailIcon },+ { type: AlarmChannelType.Slack, icon: HashIcon },+ { type: AlarmChannelType.Webhook, icon: LinkIcon },+ { type: AlarmChannelType.PagerDuty, icon: AlertTriangleIcon }+];++const DIRECTED_TYPES = new Set<AlarmChannelType>([AlarmChannelType.Email]);++type Props = {+ projectId?: string;+ channel?: TAlarmChannel;+ onComplete: (channelId: string) => void;+ onCancel: () => void;+};++const buildDefaults = (channel?: TAlarmChannel): Partial<TAlarmChannelForm> => {+ if (!channel) {+ return { name: "", channelType: AlarmChannelType.Email, enabled: true, recipients: [] };+ }+ const config = channel.config ?? {};+ return {+ name: channel.name,+ channelType: channel.channelType,+ enabled: channel.enabled,+ url: (config.url as string) ?? "",+ webhookUrl: "",+ signingSecret: "",+ integrationKey: "",+ recipients: channel.recipients.map((r) => ({+ principalType: r.principalType,+ principalId: r.principalId,+ label: r.principalId+ })) as TAlarmChannelRecipientForm[]+ };+};++export const ChannelForm = ({ projectId, channel, onComplete, onCancel }: Props) => {+ const isEditing = Boolean(channel);+ const scopeVariant = useScopeVariant();+ const createChannel = useCreateAlarmChannel();+ const updateChannel = useUpdateAlarmChannel();+ const [clearSigningSecret, setClearSigningSecret] = useState(false);++ const formMethods = useForm<TAlarmChannelForm>({+ resolver: zodResolver(buildChannelFormSchema(isEditing)),+ defaultValues: buildDefaults(channel) as TAlarmChannelForm+ });+ const {+ control,+ register,+ handleSubmit,+ watch,+ formState: { errors, isSubmitting }+ } = formMethods;++ const channelType = watch("channelType");+ const hasSigningSecret = Boolean(channel?.config?.hasSigningSecret);++ const buildConfig = (data: TAlarmChannelForm): Record<string, unknown> => {+ switch (data.channelType) {+ case AlarmChannelType.Slack:+ // Blank on edit => omit so the server keeps the existing URL.+ return data.webhookUrl ? { webhookUrl: data.webhookUrl } : {};+ case AlarmChannelType.Webhook: {+ const config: Record<string, unknown> = { url: data.url };+ if (clearSigningSecret) config.signingSecret = "";+ else if (data.signingSecret) config.signingSecret = data.signingSecret;+ return config;+ }+ case AlarmChannelType.PagerDuty:+ return data.integrationKey ? { integrationKey: data.integrationKey } : {};+ case AlarmChannelType.Email:+ default:+ return {};+ }+ };++ const onSubmit = async (data: TAlarmChannelForm) => {+ const recipients = DIRECTED_TYPES.has(data.channelType)+ ? (data.recipients ?? []).map((r) => ({+ principalType: r.principalType,+ principalId: r.principalId+ }))+ : [];+ try {+ if (isEditing && channel) {+ const updated = await updateChannel.mutateAsync({+ channelId: channel.id,+ projectId: channel.projectId,+ name: data.name,+ enabled: data.enabled,+ config: buildConfig(data),+ ...(DIRECTED_TYPES.has(data.channelType) ? { recipients } : {})+ });+ createNotification({ text: "Successfully updated channel", type: "success" });+ onComplete(updated.id);+ } else {+ const created = await createChannel.mutateAsync({+ name: data.name,+ channelType: data.channelType,+ enabled: data.enabled,+ config: buildConfig(data),+ projectId: projectId ?? null,+ ...(DIRECTED_TYPES.has(data.channelType) ? { recipients } : {})+ });+ createNotification({ text: "Successfully created channel", type: "success" });+ onComplete(created.id);+ }+ } catch (err) {+ const message =+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??+ "Failed to save channel";+ createNotification({ text: message, type: "error" });+ }+ };++ return (+ <FormProvider {...formMethods}>+ <form+ onSubmit={handleSubmit(onSubmit)}+ className="flex min-h-0 flex-1 flex-col overflow-y-auto"+ >+ <div className="flex flex-col gap-6 p-4">+ <Field>+ <FieldLabel htmlFor="channel-name">Name</FieldLabel>+ <FieldContent>+ <Input+ id="channel-name"+ autoFocus+ placeholder="#sre-alerts"+ isError={Boolean(errors.name)}+ {...register("name")}+ />+ <FieldDescription>Shown when picking a channel on an alarm.</FieldDescription>+ <FieldError errors={[errors.name]} />+ </FieldContent>+ </Field>++ <Controller+ control={control}+ name="channelType"+ render={({ field }) => (+ <Field>+ <FieldLabel>Channel type</FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={field.onChange} disabled={isEditing}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a channel type" />+ </SelectTrigger>+ <SelectContent position="popper">+ {CHANNEL_TYPES.map(({ type, icon: Icon }) => (+ <SelectItem key={type} value={type}>+ <span className="flex items-center gap-2">+ <Icon className="size-4 text-muted" />+ {ALARM_CHANNEL_TYPE_LABELS[type]}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ )}+ />++ {channelType === AlarmChannelType.Email && <ChannelRecipientsField />}++ {channelType === AlarmChannelType.Slack && (+ <Controller+ control={control}+ name="webhookUrl"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Incoming webhook URL</FieldLabel>+ <FieldContent>+ <Input+ placeholder="https://hooks.slack.com/services/T0/B0/xxxx"+ isError={Boolean(error)}+ value={(field.value as string) ?? ""}+ onChange={field.onChange}+ onBlur={field.onBlur}+ />+ {isEditing && (+ <FieldDescription>+ Existing URL is hidden; leave blank to keep it.+ </FieldDescription>+ )}+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ )}++ {channelType === AlarmChannelType.Webhook && (+ <div className="flex flex-col gap-4">+ <Controller+ control={control}+ name="url"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Webhook URL</FieldLabel>+ <FieldContent>+ <Input+ placeholder="https://api.example.com/webhook"+ isError={Boolean(error)}+ value={(field.value as string) ?? ""}+ onChange={field.onChange}+ onBlur={field.onBlur}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="signingSecret"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Signing secret <span className="text-mineshaft-400">(optional)</span>+ </FieldLabel>+ <FieldContent>+ <Input+ type="password"+ placeholder="Enter signing secret..."+ isError={Boolean(error)}+ disabled={clearSigningSecret}+ value={(field.value as string) ?? ""}+ onChange={field.onChange}+ onBlur={field.onBlur}+ />+ {isEditing && hasSigningSecret && (+ <div className="mt-1 flex items-center gap-2 text-xs text-muted">+ <Checkbox+ id="clear-signing-secret"+ isChecked={clearSigningSecret}+ onCheckedChange={(checked) => setClearSigningSecret(Boolean(checked))}+ >+ Remove the existing signing secret+ </Checkbox>+ </div>+ )}+ <FieldDescription>+ Adds an x-infisical-signature header so receivers can verify payloads.+ {isEditing && " Leave blank to keep the current secret."}+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </div>+ )}++ {channelType === AlarmChannelType.PagerDuty && (+ <Controller+ control={control}+ name="integrationKey"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Integration key</FieldLabel>+ <FieldContent>+ <Input+ placeholder="32-character hex integration key"+ isError={Boolean(error)}+ value={(field.value as string) ?? ""}+ onChange={field.onChange}+ onBlur={field.onBlur}+ />+ {isEditing && (+ <FieldDescription>+ Existing key is hidden; leave blank to keep it.+ </FieldDescription>+ )}+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ )}+ </div>++ <SheetFooter className="sticky bottom-0 border-t bg-popover">+ <div className="flex w-full items-center justify-between">+ <div className="flex items-center gap-2">+ <Button+ type="submit"+ variant={scopeVariant}+ isPending={isSubmitting}+ isDisabled={isSubmitting}+ >+ {isEditing ? "Update Channel" : "Add Channel"}+ </Button>+ <Button type="button" variant="outline" onClick={onCancel} isDisabled={isSubmitting}>+ Cancel+ </Button>+ </div>+ <Controller+ control={control}+ name="enabled"+ render={({ field }) => (+ <FieldLabel+ htmlFor="channel-enabled"+ className="flex cursor-pointer items-center gap-2 text-sm text-muted"+ >+ Enabled+ <Switch+ id="channel-enabled"+ variant={scopeVariant}+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FieldLabel>+ )}+ />+ </div>+ </SheetFooter>+ </form>+ </FormProvider>+ );+};diff --git a/frontend/src/views/AlarmsPage/components/AlarmRecipientsField.tsx b/frontend/src/views/AlarmsPage/components/channels/ChannelRecipientsField.tsxsimilarity index 85%rename from frontend/src/views/AlarmsPage/components/AlarmRecipientsField.tsxrename to frontend/src/views/AlarmsPage/components/channels/ChannelRecipientsField.tsxindex 1fcfb77e70..1e1438d0eb 100644--- a/frontend/src/views/AlarmsPage/components/AlarmRecipientsField.tsx+++ b/frontend/src/views/AlarmsPage/components/channels/ChannelRecipientsField.tsx@@ -11,12 +11,8 @@ import {} from "@app/components/v3";import { useOrganization } from "@app/context";import { useGetOrganizationGroups, useGetOrgUsers } from "@app/hooks/api";-import {- ALARM_PRINCIPAL_TYPE_LABELS,- AlarmPrincipalType,- TAlarmForm,- TAlarmRecipientForm-} from "@app/hooks/api/alarms";+import { TAlarmChannelForm, TAlarmChannelRecipientForm } from "@app/hooks/api/alarmChannels";+import { ALARM_PRINCIPAL_TYPE_LABELS, AlarmPrincipalType } from "@app/hooks/api/alarms";const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;@@ -26,16 +22,11 @@ type RecipientOption = {label: string;};-type Props = {- index: number;-};--export const AlarmRecipientsField = ({ index }: Props) => {- const { control } = useFormContext<TAlarmForm>();+export const ChannelRecipientsField = () => {+ const { control } = useFormContext<TAlarmChannelForm>();const { currentOrg } = useOrganization();const orgId = currentOrg.id;- // Only reveal the (potentially large) option list once the user starts typing.const [inputValue, setInputValue] = useState("");const { data: orgUsers = [] } = useGetOrgUsers(orgId);@@ -72,7 +63,7 @@ export const AlarmRecipientsField = ({ index }: Props) => {[userOptions, groupOptions]);- const toOption = (recipient: TAlarmRecipientForm): RecipientOption => {+ const toOption = (recipient: TAlarmChannelRecipientForm): RecipientOption => {if (recipient.principalType === AlarmPrincipalType.Email) {return {principalType: AlarmPrincipalType.Email,@@ -91,9 +82,11 @@ export const AlarmRecipientsField = ({ index }: Props) => {return (<Controllercontrol={control}- name={`channels.${index}.config.recipients`}+ name="recipients"render={({ field, fieldState: { error } }) => {- const value = ((field.value as TAlarmRecipientForm[] | undefined) ?? []).map(toOption);+ const value = ((field.value as TAlarmChannelRecipientForm[] | undefined) ?? []).map(+ toOption+ );return (<Field>@@ -103,7 +96,6 @@ export const AlarmRecipientsField = ({ index }: Props) => {isMulticloseMenuOnSelect={false}placeholder="Add users, groups, or type an email..."- // Hide the full list until the user types; keep it lightweight.options={inputValue.trim() ? groupedOptions : []}value={value}isError={Boolean(error)}@@ -140,7 +132,7 @@ export const AlarmRecipientsField = ({ index }: Props) => {}}/><FieldDescription>- Email channels deliver to these recipients. Add org users, groups, or raw email+ This channel delivers to these recipients. Add org users, groups, or raw emailaddresses.</FieldDescription><FieldError errors={[error]} />diff --git a/frontend/src/views/AlarmsPage/components/channels/ChannelRow.tsx b/frontend/src/views/AlarmsPage/components/channels/ChannelRow.tsxnew file mode 100644index 0000000000..ad816ab361--- /dev/null+++ b/frontend/src/views/AlarmsPage/components/channels/ChannelRow.tsx@@ -0,0 +1,86 @@+import {+ AlertTriangleIcon,+ BellIcon,+ Ellipsis,+ HashIcon,+ LinkIcon,+ MailIcon,+ PencilIcon,+ Trash2Icon+} from "lucide-react";++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ IconButton,+ TableCell,+ TableRow+} from "@app/components/v3";+import { TAlarmChannel } from "@app/hooks/api/alarmChannels";+import { ALARM_CHANNEL_TYPE_LABELS, AlarmChannelType } from "@app/hooks/api/alarms";++type LucideIcon = typeof MailIcon;++const CHANNEL_ICONS: Record<AlarmChannelType, LucideIcon> = {+ [AlarmChannelType.Email]: MailIcon,+ [AlarmChannelType.Slack]: HashIcon,+ [AlarmChannelType.Webhook]: LinkIcon,+ [AlarmChannelType.PagerDuty]: AlertTriangleIcon+};++type Props = {+ channel: TAlarmChannel;+ onEdit: (channel: TAlarmChannel) => void;+ onDelete: (channel: TAlarmChannel) => void;+};++export const ChannelRow = ({ channel, onEdit, onDelete }: Props) => {+ const Icon = CHANNEL_ICONS[channel.channelType] ?? BellIcon;+ const typeLabel = ALARM_CHANNEL_TYPE_LABELS[channel.channelType] ?? channel.channelType;++ return (+ <TableRow>+ <TableCell>+ <span className={channel.enabled ? "text-foreground" : "text-muted"}>{channel.name}</span>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2 text-muted">+ <Icon className="size-4 shrink-0" />+ <span className="text-foreground">{typeLabel}</span>+ </div>+ </TableCell>+ <TableCell>+ {channel.usageCount ? (+ <span className="text-warning">+ {channel.usageCount} alarm{channel.usageCount === 1 ? "" : "s"}+ </span>+ ) : (+ <span className="text-muted">Unused</span>+ )}+ </TableCell>+ <TableCell>+ <div className="flex items-center justify-end gap-2">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton aria-label="Options" variant="ghost" size="xs">+ <Ellipsis />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent sideOffset={2} align="end">+ <DropdownMenuItem onClick={() => onEdit(channel)}>+ <PencilIcon />+ Edit Channel+ </DropdownMenuItem>+ <DropdownMenuItem variant="danger" onClick={() => onDelete(channel)}>+ <Trash2Icon />+ Delete Channel+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </TableCell>+ </TableRow>+ );+};diff --git a/frontend/src/views/AlarmsPage/components/channels/ChannelsTable.tsx b/frontend/src/views/AlarmsPage/components/channels/ChannelsTable.tsxnew file mode 100644index 0000000000..9ebe22db70--- /dev/null+++ b/frontend/src/views/AlarmsPage/components/channels/ChannelsTable.tsx@@ -0,0 +1,196 @@+import { useMemo } from "react";+import { PlusIcon, SearchIcon } from "lucide-react";++import { VariablePermissionCan } from "@app/components/permissions";+import {+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Pagination,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { OrgPermissionSubjects, ProjectPermissionSub } from "@app/context";+import { OrgPermissionActions } from "@app/context/OrgPermissionContext/types";+import { ProjectPermissionActions } from "@app/context/ProjectPermissionContext/types";+import { usePagination, usePopUp, useResetPageHelper, useScopeVariant } from "@app/hooks";+import { TAlarmChannel, useListAlarmChannels } from "@app/hooks/api/alarmChannels";++import { AddChannelModal } from "./AddChannelModal";+import { ChannelRow } from "./ChannelRow";+import { DeleteChannelModal } from "./DeleteChannelModal";++type Props = {+ projectId?: string;+};++export const ChannelsTable = ({ projectId }: Props) => {+ const isProjectView = Boolean(projectId);+ const scopeVariant = useScopeVariant();++ const { isPending, data: allChannels = [] } = useListAlarmChannels(+ projectId ? { projectId } : {}+ );++ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([+ "addChannel",+ "editChannel",+ "deleteChannel"+ ] as const);++ const { search, setSearch, setPage, page, perPage, setPerPage, offset } = usePagination("", {+ initPerPage: 20+ });++ const filteredChannels = useMemo(+ () =>+ allChannels.filter((channel) => {+ const value = search.trim().toLowerCase();+ if (!value) return true;+ return channel.name.toLowerCase().includes(value);+ }),+ [allChannels, search]+ );++ useResetPageHelper({ totalCount: filteredChannels.length, offset, setPage });++ const visibleChannels = filteredChannels.slice(offset, perPage * page);++ return (+ <>+ <Card>+ <CardHeader>+ <CardTitle>Channels</CardTitle>+ <CardDescription>+ Reusable delivery destinations. Create a channel once, then attach it to any alarm.+ </CardDescription>+ <CardAction>+ <VariablePermissionCan+ type={isProjectView ? "project" : "org"}+ I={isProjectView ? ProjectPermissionActions.Create : OrgPermissionActions.Create}+ a={isProjectView ? ProjectPermissionSub.Settings : OrgPermissionSubjects.Settings}+ >+ {(isAllowed) => (+ <Button+ variant={scopeVariant}+ onClick={() => handlePopUpOpen("addChannel")}+ isDisabled={!isAllowed}+ >+ <PlusIcon />+ Add Channel+ </Button>+ )}+ </VariablePermissionCan>+ </CardAction>+ </CardHeader>+ <CardContent>+ <div className="flex items-center gap-2">+ <InputGroup className="flex-1">+ <InputGroupAddon align="inline-start">+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ placeholder="Search channels..."+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ />+ </InputGroup>+ </div>+ <div className="mt-4">+ {!isPending && !filteredChannels.length ? (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>+ {allChannels.length+ ? "No channels match search"+ : "No channels have been created"}+ </EmptyTitle>+ <EmptyDescription>+ {allChannels.length+ ? "Adjust your search to view channels."+ : "Add a channel to route alarm notifications."}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Type</TableHead>+ <TableHead>Used by</TableHead>+ <TableHead className="w-5" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {isPending &&+ Array.from({ length: 5 }).map((_, i) => (+ <TableRow key={`skeleton-${i + 1}`}>+ {Array.from({ length: 4 }).map((__, j) => (+ <TableCell key={`skeleton-cell-${i + 1}-${j + 1}`}>+ <Skeleton className="h-4 w-full" />+ </TableCell>+ ))}+ </TableRow>+ ))}+ {!isPending &&+ visibleChannels.map((channel) => (+ <ChannelRow+ key={channel.id}+ channel={channel}+ onEdit={(data) => handlePopUpOpen("editChannel", data)}+ onDelete={(data) => handlePopUpOpen("deleteChannel", data)}+ />+ ))}+ </TableBody>+ </Table>+ {!isPending && (+ <Pagination+ count={filteredChannels.length}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={setPerPage}+ />+ )}+ </>+ )}+ </div>+ </CardContent>+ </Card>+ <AddChannelModal+ isOpen={popUp.addChannel.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("addChannel", isOpen)}+ projectId={projectId}+ />+ <AddChannelModal+ isOpen={popUp.editChannel.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("editChannel", isOpen)}+ projectId={projectId}+ channel={popUp.editChannel.data as TAlarmChannel | undefined}+ />+ <DeleteChannelModal+ isOpen={popUp.deleteChannel.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("deleteChannel", isOpen)}+ channel={popUp.deleteChannel.data as TAlarmChannel | undefined}+ />+ </>+ );+};diff --git a/frontend/src/views/AlarmsPage/components/channels/DeleteChannelModal.tsx b/frontend/src/views/AlarmsPage/components/channels/DeleteChannelModal.tsxnew file mode 100644index 0000000000..b924533d5c--- /dev/null+++ b/frontend/src/views/AlarmsPage/components/channels/DeleteChannelModal.tsx@@ -0,0 +1,73 @@+import { Trash2Icon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogTitle,+ Button+} from "@app/components/v3";+import { TAlarmChannel, useDeleteAlarmChannel } from "@app/hooks/api/alarmChannels";++type Props = {+ channel?: TAlarmChannel;+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+};++export const DeleteChannelModal = ({ isOpen, onOpenChange, channel }: Props) => {+ const deleteChannel = useDeleteAlarmChannel();++ if (!channel) return null;++ const handleDelete = async () => {+ if (deleteChannel.isPending) return;+ try {+ await deleteChannel.mutateAsync({ channelId: channel.id, projectId: channel.projectId });+ createNotification({+ text: `Successfully deleted channel "${channel.name}"`,+ type: "success"+ });+ onOpenChange(false);+ } catch (err) {+ const message =+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??+ "Failed to delete channel";+ createNotification({ text: message, type: "error" });+ }+ };++ const usage = channel.usageCount+ ? `This channel is used by ${channel.usageCount} alarm${channel.usageCount === 1 ? "" : "s"}; it will be detached from ${channel.usageCount === 1 ? "it" : "them"}.`+ : "This action is irreversible.";++ return (+ <AlertDialog open={isOpen} onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogMedia>+ <Trash2Icon />+ </AlertDialogMedia>+ <AlertDialogTitle>Are you sure you want to delete {channel.name}?</AlertDialogTitle>+ <AlertDialogDescription>{usage}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <Button+ variant="danger"+ size="sm"+ isPending={deleteChannel.isPending}+ onClick={handleDelete}+ >+ Delete+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+};