Skip to content

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

create inline channel

Thiago Araujo da Silva5de40752a375
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index dd35b66b29..672a8f2591 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1050,12 +1050,6 @@ export const registerRoutes = async (
alertProviderRegistry,
alertEngine
});
- const alertService = alertServiceFactory({
- alertDAL,
- alertChannelDAL,
- alertChannelMembershipDAL,
- alertProviderRegistry
- });
const alertChannelService = alertChannelServiceFactory({
alertChannelDAL,
alertChannelRecipientDAL,
@@ -1066,6 +1060,14 @@ export const registerRoutes = async (
projectDAL,
groupDAL
});
+ const alertService = alertServiceFactory({
+ alertDAL,
+ alertChannelDAL,
+ alertChannelMembershipDAL,
+ alertChannelService,
+ kmsService,
+ alertProviderRegistry
+ });
const auditLogStreamService = auditLogStreamServiceFactory({
licenseService,
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index 79bc32ebc4..6afe710b71 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -2,8 +2,32 @@ import { z } from "zod";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AlertChannelType } from "@app/services/alert/alert-channel-types";
+import { AlertPrincipalType } from "@app/services/alert/alert-types";
import { AuthMode } from "@app/services/auth/auth-type";
+const ChannelRecipientSchema = z.object({
+ principalType: z.nativeEnum(AlertPrincipalType),
+ principalId: z.string().min(1)
+});
+
+const CreateChannelInputSchema = z.object({
+ name: z.string().min(1).max(255),
+ channelType: z.nativeEnum(AlertChannelType),
+ config: z.record(z.unknown()).default({}),
+ enabled: z.boolean().optional(),
+ recipients: z.array(ChannelRecipientSchema).optional()
+});
+
+const UpdateChannelInputSchema = z.object({
+ id: z.string().uuid().optional(),
+ name: z.string().min(1).max(255),
+ channelType: z.nativeEnum(AlertChannelType),
+ config: z.record(z.unknown()).optional(),
+ enabled: z.boolean().optional(),
+ recipients: z.array(ChannelRecipientSchema).optional()
+});
+
const AlertResponseSchema = z.object({
id: z.string().uuid(),
name: z.string(),
@@ -22,7 +46,9 @@ const AlertResponseSchema = z.object({
name: z.string(),
channelType: z.string(),
directed: z.boolean(),
- enabled: z.boolean()
+ enabled: z.boolean(),
+ config: z.record(z.unknown()),
+ recipients: z.array(z.object({ principalType: z.string(), principalId: z.string() }))
})
),
createdAt: z.date(),
@@ -46,7 +72,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
filters: z.unknown().optional(),
enabled: z.boolean().optional(),
projectId: z.string().nullable().optional(),
- channelIds: z.array(z.string().uuid()).min(1)
+ channels: z.array(CreateChannelInputSchema).min(1)
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
@@ -128,7 +154,7 @@ export const registerAlertRouter = async (server: FastifyZodProvider) => {
condition: z.unknown().optional(),
filters: z.unknown().optional(),
enabled: z.boolean().optional(),
- channelIds: z.array(z.string().uuid()).min(1).optional()
+ channels: z.array(UpdateChannelInputSchema).min(1).optional()
}),
response: { 200: z.object({ alert: AlertResponseSchema }) }
},
diff --git a/backend/src/services/alert/alert-channel-service-types.ts b/backend/src/services/alert/alert-channel-service-types.ts
index 320fcfe930..d3887198a5 100644
--- a/backend/src/services/alert/alert-channel-service-types.ts
+++ b/backend/src/services/alert/alert-channel-service-types.ts
@@ -46,7 +46,6 @@ export type TAlertChannelDetail = {
updatedAt: Date;
};
-// Lightweight reference embedded in an alert response (the alert no longer owns config/recipients).
export type TAlertChannelSummary = {
id: string;
name: string;
@@ -55,4 +54,23 @@ export type TAlertChannelSummary = {
enabled: boolean;
};
+export type TAlertChannelEmbedded = {
+ id: string;
+ name: string;
+ channelType: string;
+ directed: boolean;
+ enabled: boolean;
+ config: Record<string, unknown>;
+ recipients: { principalType: string; principalId: string }[];
+};
+
+export type TAlertChannelInput = {
+ id?: string;
+ name: string;
+ channelType: AlertChannelType;
+ config?: Record<string, unknown>;
+ enabled?: boolean;
+ recipients?: TChannelRecipientInput[];
+};
+
export type { AlertChannelType };
diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.ts
index c44046bca7..5c3d830dc4 100644
--- a/backend/src/services/alert/alert-channel-service.ts
+++ b/backend/src/services/alert/alert-channel-service.ts
@@ -1,6 +1,7 @@
import { ForbiddenError } from "@casl/ability";
+import { Knex } from "knex";
-import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
+import { ActionProjectType, OrganizationActionScope, TAlertChannels } 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";
@@ -11,12 +12,19 @@ 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, getAlertChannelCipher } from "./alert-channel-crypto-fns";
+import {
+ decryptChannelConfig,
+ encryptChannelConfig,
+ getAlertChannelCipher,
+ TAlertDecryptor,
+ TAlertEncryptor
+} from "./alert-channel-crypto-fns";
import { TAlertChannelDALFactory } from "./alert-channel-dal";
import { TAlertChannelMembershipDALFactory } from "./alert-channel-membership-dal";
import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
import {
TAlertChannelDetail,
+ TAlertChannelEmbedded,
TChannelRecipientInput,
TCreateAlertChannelDTO,
TDeleteAlertChannelDTO,
@@ -41,6 +49,27 @@ export type TAlertChannelServiceFactoryDep = {
export type TAlertChannelServiceFactory = ReturnType<typeof alertChannelServiceFactory>;
+// Everything the transaction-aware primitives need to write a channel inline, without the standalone
+// endpoint's org/project Settings permission check or reusable-name-uniqueness check.
+export type TCreateChannelInTxInput = {
+ name: string;
+ channelType: AlertChannelType | string;
+ config: Record<string, unknown>;
+ enabled?: boolean;
+ recipients?: TChannelRecipientInput[];
+ orgId: string;
+ projectId?: string | null;
+ createdByUserId?: string | null;
+};
+
+export type TUpdateChannelInTxInput = {
+ channelId: string;
+ name?: string;
+ config?: Record<string, unknown>;
+ enabled?: boolean;
+ recipients?: TChannelRecipientInput[];
+};
+
const capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);
export const alertChannelServiceFactory = ({
@@ -152,6 +181,31 @@ export const alertChannelServiceFactory = ({
}
};
+ const $assertRecipientRules = (
+ definition: { directed: boolean },
+ channelType: string,
+ recipients: TChannelRecipientInput[]
+ ) => {
+ if (!definition.directed && recipients.length > 0) {
+ throw new BadRequestError({ message: `${channelType} channels do not take recipients` });
+ }
+ if (definition.directed && recipients.length === 0) {
+ throw new BadRequestError({ message: `${channelType} channels require at least one recipient` });
+ }
+ };
+
+ const $assertConfigValid = (
+ definition: { configSchema: { parse: (value: unknown) => unknown } },
+ channelType: string,
+ config: Record<string, unknown>
+ ) => {
+ try {
+ definition.configSchema.parse(config);
+ } catch (err) {
+ throw new BadRequestError({ message: `Invalid ${channelType} channel config` });
+ }
+ };
+
const $redactConfig = (channelType: string, config: Record<string, unknown>): Record<string, unknown> => {
const definition = ALERT_CHANNEL_REGISTRY[channelType as AlertChannelType];
if (!definition) return {};
@@ -235,6 +289,126 @@ export const alertChannelServiceFactory = ({
}
};
+ const createChannelInTx = async (
+ input: TCreateChannelInTxInput,
+ encryptor: TAlertEncryptor,
+ tx: Knex
+ ): Promise<TAlertChannels> => {
+ const definition = $getDefinition(input.channelType);
+ const recipients = input.recipients ?? [];
+ $assertRecipientRules(definition, input.channelType, recipients);
+ $assertConfigValid(definition, input.channelType, input.config);
+ await $validateRecipients(input.orgId, input.projectId, recipients);
+
+ const created = await alertChannelDAL.create(
+ {
+ name: input.name,
+ channelType: input.channelType,
+ encryptedConfig: encryptChannelConfig(input.config, encryptor),
+ enabled: input.enabled ?? true,
+ orgId: input.orgId,
+ projectId: input.projectId ?? null,
+ createdByUserId: input.createdByUserId ?? null
+ },
+ tx
+ );
+
+ if (recipients.length) {
+ await alertChannelRecipientDAL.insertMany(
+ recipients.map((r) => ({ channelId: created.id, principalType: r.principalType, principalId: r.principalId })),
+ tx
+ );
+ }
+ return created;
+ };
+
+ const updateChannelInTx = async (
+ input: TUpdateChannelInTxInput,
+ channel: TAlertChannels,
+ cipher: { encryptor: TAlertEncryptor; decryptor: TAlertDecryptor },
+ tx: Knex
+ ): Promise<Record<string, unknown>> => {
+ const definition = $getDefinition(channel.channelType);
+ const existingConfig = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, cipher.decryptor);
+
+ let finalConfig = existingConfig;
+ if (input.config !== undefined) {
+ const merged = $mergeConfigForUpdate(channel.channelType, input.config, existingConfig);
+ $assertConfigValid(definition, channel.channelType, merged);
+ finalConfig = merged;
+ }
+
+ if (input.recipients !== undefined) {
+ $assertRecipientRules(definition, channel.channelType, input.recipients);
+ await $validateRecipients(channel.orgId, channel.projectId, input.recipients);
+ }
+
+ await alertChannelDAL.updateById(
+ channel.id,
+ {
+ ...(input.name !== undefined ? { name: input.name } : {}),
+ ...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
+ ...(input.config !== undefined ? { encryptedConfig: encryptChannelConfig(finalConfig, cipher.encryptor) } : {})
+ },
+ tx
+ );
+
+ if (input.recipients !== undefined) {
+ await alertChannelRecipientDAL.deleteByChannelId(channel.id, tx);
+ if (input.recipients.length) {
+ await alertChannelRecipientDAL.insertMany(
+ input.recipients.map((r) => ({
+ channelId: channel.id,
+ principalType: r.principalType,
+ principalId: r.principalId
+ })),
+ tx
+ );
+ }
+ }
+
+ return finalConfig;
+ };
+
+ const deleteChannelInTx = async (channelId: string, tx: Knex): Promise<void> => {
+ await alertChannelDAL.deleteById(channelId, tx);
+ };
+
+ const getDetailsForChannels = async (
+ channels: TAlertChannels[],
+ cipher: { decryptor: TAlertDecryptor },
+ tx?: Knex
+ ): Promise<TAlertChannelEmbedded[]> => {
+ if (channels.length === 0) return [];
+
+ const recipients = await alertChannelRecipientDAL.findByChannelIds(
+ channels.map((c) => c.id),
+ tx
+ );
+ 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 definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
+ const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, cipher.decryptor);
+ return {
+ id: channel.id,
+ name: channel.name,
+ channelType: channel.channelType,
+ directed: Boolean(definition?.directed),
+ enabled: channel.enabled,
+ config: $redactConfig(channel.channelType, config),
+ recipients: recipientsByChannel.get(channel.id) ?? []
+ };
+ });
+ };
+
+ // ----- Standalone channel endpoints (reusable model) -----
+
const createChannel = async (dto: TCreateAlertChannelDTO): Promise<TAlertChannelDetail> => {
const actor: TGenericPermission = {
actor: dto.actor,
@@ -243,56 +417,30 @@ export const alertChannelServiceFactory = ({
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 getAlertChannelCipher(kmsService, {
orgId: dto.actorOrgId,
projectId: dto.projectId ?? null
});
- const channel = await alertChannelDAL.transaction(async (tx) => {
- const created = await alertChannelDAL.create(
+ const recipients = dto.recipients ?? [];
+ const channel = await alertChannelDAL.transaction((tx) =>
+ createChannelInTx(
{
name: dto.name,
channelType: dto.channelType,
- encryptedConfig: encryptChannelConfig(dto.config, encryptor),
- enabled: dto.enabled ?? true,
+ config: dto.config,
+ enabled: dto.enabled,
+ recipients,
orgId: dto.actorOrgId,
projectId: dto.projectId ?? null,
createdByUserId: dto.actorId
},
+ encryptor,
tx
- );
-
- if (recipients.length) {
- await alertChannelRecipientDAL.insertMany(
- recipients.map((r) => ({
- channelId: created.id,
- principalType: r.principalType,
- principalId: r.principalId
- })),
- tx
- );
- }
- return created;
- });
+ )
+ );
return $buildDetail(channel, dto.config, recipients, 0);
};
@@ -310,62 +458,20 @@ export const alertChannelServiceFactory = ({
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 getAlertChannelCipher(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 alertChannelDAL.transaction(async (tx) => {
- await alertChannelDAL.updateById(
- channel.id,
- {
- ...(dto.name !== undefined ? { name: dto.name } : {}),
- ...(dto.enabled !== undefined ? { enabled: dto.enabled } : {}),
- ...(dto.config !== undefined ? { encryptedConfig: encryptChannelConfig(finalConfig, encryptor) } : {})
- },
+ const cipher = await getAlertChannelCipher(kmsService, scope);
+ const finalConfig = await alertChannelDAL.transaction((tx) =>
+ updateChannelInTx(
+ { channelId: channel.id, name: dto.name, config: dto.config, enabled: dto.enabled, recipients: dto.recipients },
+ channel,
+ cipher,
tx
- );
-
- if (dto.recipients !== undefined) {
- await alertChannelRecipientDAL.deleteByChannelId(channel.id, tx);
- if (dto.recipients.length) {
- await alertChannelRecipientDAL.insertMany(
- dto.recipients.map((r) => ({
- channelId: channel.id,
- principalType: r.principalType,
- principalId: r.principalId
- })),
- tx
- );
- }
- }
- });
+ )
+ );
const [updated, recipients, usageCount] = await Promise.all([
alertChannelDAL.findById(channel.id),
@@ -457,5 +563,15 @@ export const alertChannelServiceFactory = ({
});
};
- return { createChannel, updateChannel, deleteChannel, getChannelById, listChannels };
+ return {
+ createChannel,
+ updateChannel,
+ deleteChannel,
+ getChannelById,
+ listChannels,
+ createChannelInTx,
+ updateChannelInTx,
+ deleteChannelInTx,
+ getDetailsForChannels
+ };
};
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index c28499bd68..582c27045f 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -1,6 +1,6 @@
import { TGenericPermission } from "@app/lib/types";
-import { TAlertChannelSummary } from "./alert-channel-service-types";
+import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-service-types";
export type TCreateAlertDTO = TGenericPermission & {
name: string;
@@ -12,7 +12,7 @@ export type TCreateAlertDTO = TGenericPermission & {
filters?: unknown;
enabled?: boolean;
projectId?: string | null;
- channelIds: string[];
+ channels: TAlertChannelInput[];
};
export type TUpdateAlertDTO = TGenericPermission & {
@@ -22,7 +22,7 @@ export type TUpdateAlertDTO = TGenericPermission & {
condition?: unknown;
filters?: unknown;
enabled?: boolean;
- channelIds?: string[];
+ channels?: TAlertChannelInput[];
};
export type TGetAlertDTO = TGenericPermission & { alertId: string };
@@ -48,7 +48,7 @@ export type TAlertResponse = {
enabled: boolean;
orgId: string;
projectId: string | null;
- channels: TAlertChannelSummary[];
+ channels: TAlertChannelEmbedded[];
createdAt: Date;
updatedAt: Date;
};
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index f0062eb8ea..9ab1a24bbc 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -1,12 +1,15 @@
+import { Knex } from "knex";
import { z } from "zod";
import { TAlertChannels, TAlerts } from "@app/db/schemas";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { getAlertChannelCipher } from "./alert-channel-crypto-fns";
import { TAlertChannelDALFactory } from "./alert-channel-dal";
import { TAlertChannelMembershipDALFactory } from "./alert-channel-membership-dal";
-import { TAlertChannelSummary } from "./alert-channel-service-types";
-import { AlertChannelType } from "./alert-channel-types";
+import { TAlertChannelServiceFactory } from "./alert-channel-service";
+import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-service-types";
import { TAlertDALFactory } from "./alert-dal";
import { TAlertProviderRegistry } from "./alert-provider-registry";
import {
@@ -18,32 +21,27 @@ import {
TUpdateAlertDTO
} from "./alert-service-types";
import { AlertPermissionAction, AlertTriggerType, IResourceAlertProvider } from "./alert-types";
-import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
export type TAlertServiceFactoryDep = {
alertDAL: TAlertDALFactory;
- alertChannelDAL: Pick<TAlertChannelDALFactory, "findByIdsInScope" | "findByAlertId" | "findByAlertIds">;
- alertChannelMembershipDAL: Pick<TAlertChannelMembershipDALFactory, "insertMany" | "deleteByAlertId">;
+ alertChannelDAL: Pick<TAlertChannelDALFactory, "findByAlertId" | "findByAlertIds">;
+ alertChannelMembershipDAL: Pick<TAlertChannelMembershipDALFactory, "insertMany">;
+ alertChannelService: Pick<
+ TAlertChannelServiceFactory,
+ "createChannelInTx" | "updateChannelInTx" | "deleteChannelInTx" | "getDetailsForChannels"
+ >;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
alertProviderRegistry: TAlertProviderRegistry;
};
export type TAlertServiceFactory = ReturnType<typeof alertServiceFactory>;
-const toChannelSummary = (channel: TAlertChannels): TAlertChannelSummary => {
- const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
- return {
- id: channel.id,
- name: channel.name,
- channelType: channel.channelType,
- directed: Boolean(definition?.directed),
- enabled: channel.enabled
- };
-};
-
export const alertServiceFactory = ({
alertDAL,
alertChannelDAL,
alertChannelMembershipDAL,
+ alertChannelService,
+ kmsService,
alertProviderRegistry
}: TAlertServiceFactoryDep) => {
const $getProvider = (resourceType: string): IResourceAlertProvider => {
@@ -75,23 +73,7 @@ export const alertServiceFactory = ({
}
};
- 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" });
- }
- const uniqueIds = [...new Set(channelIds)];
- const found = await alertChannelDAL.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 = (alert: TAlerts, channels: TAlertChannels[]): TAlertResponse => ({
+ const $assembleResponse = (alert: TAlerts, channels: TAlertChannelEmbedded[]): TAlertResponse => ({
id: alert.id,
name: alert.name,
description: alert.description ?? null,
@@ -103,7 +85,7 @@ export const alertServiceFactory = ({
enabled: alert.enabled,
orgId: alert.orgId,
projectId: alert.projectId ?? null,
- channels: channels.map(toChannelSummary),
+ channels,
createdAt: alert.createdAt,
updatedAt: alert.updatedAt
});
@@ -146,7 +128,12 @@ export const alertServiceFactory = ({
});
}
- await $resolveChannelsInScope(dto.channelIds, { orgId: dto.actorOrgId, projectId: dto.projectId });
+ if (!dto.channels || dto.channels.length === 0) {
+ throw new BadRequestError({ message: "At least one channel is required" });
+ }
+
+ const scope = { orgId: dto.actorOrgId, projectId: dto.projectId ?? null };
+ const cipher = await getAlertChannelCipher(kmsService, scope);
const { created, channels } = await alertDAL.transaction(async (tx) => {
const createdAlert = await alertDAL.create(
@@ -167,16 +154,32 @@ export const alertServiceFactory = ({
tx
);
- await alertChannelMembershipDAL.insertMany(
- [...new Set(dto.channelIds)].map((channelId) => ({ alertId: createdAlert.id, channelId })),
- tx
- );
+ for (const channelInput of dto.channels) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const channel = await alertChannelService.createChannelInTx(
+ {
+ name: channelInput.name,
+ channelType: channelInput.channelType,
+ config: channelInput.config ?? {},
+ enabled: channelInput.enabled,
+ recipients: channelInput.recipients,
+ orgId: dto.actorOrgId,
+ projectId: dto.projectId ?? null,
+ createdByUserId: dto.actorId
+ },
+ cipher.encryptor,
+ tx
+ );
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelMembershipDAL.insertMany([{ alertId: createdAlert.id, channelId: channel.id }], tx);
+ }
const attachedChannels = await alertChannelDAL.findByAlertId(createdAlert.id, tx);
- return { created: createdAlert, channels: attachedChannels };
+ const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);
+ return { created: createdAlert, channels: details };
});
- return $buildResponse(created, channels);
+ return $assembleResponse(created, channels);
};
const getAlertById = async (dto: TGetAlertDTO): Promise<TAlertResponse> => {
@@ -198,7 +201,9 @@ export const alertServiceFactory = ({
});
const channels = await alertChannelDAL.findByAlertId(alert.id);
- return $buildResponse(alert, channels);
+ const cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId });
+ const details = await alertChannelService.getDetailsForChannels(channels, cipher);
+ return $assembleResponse(alert, details);
};
const listAlerts = async (dto: TListAlertsDTO): Promise<TAlertResponse[]> => {
@@ -226,14 +231,85 @@ export const alertServiceFactory = ({
if (alerts.length === 0) return [];
const channels = await alertChannelDAL.findByAlertIds(alerts.map((alert) => alert.id));
- const channelsByAlert = new Map<string, TAlertChannels[]>();
+ const cipher = await getAlertChannelCipher(kmsService, { orgId: dto.actorOrgId, projectId: dto.projectId ?? null });
+ const details = await alertChannelService.getDetailsForChannels(channels, cipher);
+
+ const detailById = new Map(details.map((detail) => [detail.id, detail]));
+ const channelIdsByAlert = new Map<string, string[]>();
channels.forEach((channel) => {
- const list = channelsByAlert.get(channel.alertId) ?? [];
- list.push(channel);
- channelsByAlert.set(channel.alertId, list);
+ const list = channelIdsByAlert.get(channel.alertId) ?? [];
+ list.push(channel.id);
+ channelIdsByAlert.set(channel.alertId, list);
});
- return alerts.map((alert) => $buildResponse(alert, channelsByAlert.get(alert.id) ?? []));
+ return alerts.map((alert) =>
+ $assembleResponse(
+ alert,
+ (channelIdsByAlert.get(alert.id) ?? [])
+ .map((id) => detailById.get(id))
+ .filter((detail): detail is TAlertChannelEmbedded => Boolean(detail))
+ )
+ );
+ };
+
+ const $reconcileChannels = async (
+ alert: TAlerts,
+ incoming: TAlertChannelInput[],
+ cipher: Awaited<ReturnType<typeof getAlertChannelCipher>>,
+ tx: Knex
+ ) => {
+ const existing = await alertChannelDAL.findByAlertId(alert.id, tx);
+ const existingById = new Map<string, TAlertChannels>(existing.map((channel) => [channel.id, channel]));
+
+ const incomingIds = new Set(incoming.filter((channel) => channel.id).map((channel) => channel.id as string));
+ for (const id of incomingIds) {
+ if (!existingById.has(id)) {
+ throw new BadRequestError({ message: `Channel '${id}' does not belong to this alert` });
+ }
+ }
+
+ const toDelete = existing.filter((channel) => !incomingIds.has(channel.id));
+ for (const channel of toDelete) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelService.deleteChannelInTx(channel.id, tx);
+ }
+
+ for (const channelInput of incoming) {
+ if (channelInput.id) {
+ const existingChannel = existingById.get(channelInput.id) as TAlertChannels;
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelService.updateChannelInTx(
+ {
+ channelId: channelInput.id,
+ name: channelInput.name,
+ config: channelInput.config,
+ enabled: channelInput.enabled,
+ recipients: channelInput.recipients
+ },
+ existingChannel,
+ cipher,
+ tx
+ );
+ } else {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ const channel = await alertChannelService.createChannelInTx(
+ {
+ name: channelInput.name,
+ channelType: channelInput.channelType,
+ config: channelInput.config ?? {},
+ enabled: channelInput.enabled,
+ recipients: channelInput.recipients,
+ orgId: alert.orgId,
+ projectId: alert.projectId,
+ createdByUserId: alert.createdByUserId
+ },
+ cipher.encryptor,
+ tx
+ );
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelMembershipDAL.insertMany([{ alertId: alert.id, channelId: channel.id }], tx);
+ }
+ }
};
const updateAlert = async (dto: TUpdateAlertDTO): Promise<TAlertResponse> => {
@@ -255,10 +331,13 @@ export const alertServiceFactory = ({
});
if (dto.condition !== undefined) $validate(provider, { condition: dto.condition });
- if (dto.channelIds !== undefined) {
- await $resolveChannelsInScope(dto.channelIds, { orgId: alert.orgId, projectId: alert.projectId });
+ if (dto.channels !== undefined && dto.channels.length === 0) {
+ throw new BadRequestError({ message: "At least one channel is required" });
}
+ const scope = { orgId: alert.orgId, projectId: alert.projectId };
+ const cipher = await getAlertChannelCipher(kmsService, scope);
+
const { updated, channels } = await alertDAL.transaction(async (tx) => {
const patch = {
...(dto.name !== undefined ? { name: dto.name } : {}),
@@ -272,19 +351,16 @@ export const alertServiceFactory = ({
const updatedAlert = Object.keys(patch).length > 0 ? await alertDAL.updateById(alert.id, patch, tx) : alert;
- if (dto.channelIds !== undefined) {
- await alertChannelMembershipDAL.deleteByAlertId(alert.id, tx);
- await alertChannelMembershipDAL.insertMany(
- [...new Set(dto.channelIds)].map((channelId) => ({ alertId: alert.id, channelId })),
- tx
- );
+ if (dto.channels !== undefined) {
+ await $reconcileChannels(alert, dto.channels, cipher, tx);
}
const attachedChannels = await alertChannelDAL.findByAlertId(alert.id, tx);
- return { updated: updatedAlert, channels: attachedChannels };
+ const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);
+ return { updated: updatedAlert, channels: details };
});
- return $buildResponse(updated, channels);
+ return $assembleResponse(updated, channels);
};
const deleteAlert = async (dto: TDeleteAlertDTO): Promise<{ id: string }> => {
@@ -305,7 +381,15 @@ export const alertServiceFactory = ({
}
});
- await alertDAL.deleteById(alert.id);
+ await alertDAL.transaction(async (tx) => {
+ const channels = await alertChannelDAL.findByAlertId(alert.id, tx);
+ for (const channel of channels) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial
+ await alertChannelService.deleteChannelInTx(channel.id, tx);
+ }
+ await alertDAL.deleteById(alert.id, tx);
+ });
+
return { id: alert.id };
};
diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.ts
index 00c93d12b9..97870dc8b5 100644
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@ -51,13 +51,19 @@ export const ALERT_CHANNEL_TYPE_LABELS: Record<AlertChannelType, string> = {
[AlertChannelType.PagerDuty]: "PagerDuty"
};
-// Lightweight channel reference embedded in an alert (full channel lives in the alertChannels domain).
-export type TAlertChannelSummary = {
+export type TAlertChannelRecipient = {
+ principalType: AlertPrincipalType;
+ principalId: string;
+};
+
+export type TAlertChannelEmbedded = {
id: string;
name: string;
channelType: AlertChannelType;
directed: boolean;
enabled: boolean;
+ config: Record<string, unknown>;
+ recipients: TAlertChannelRecipient[];
};
export type TAlert = {
@@ -72,7 +78,7 @@ export type TAlert = {
enabled: boolean;
orgId: string;
projectId: string | null;
- channels: TAlertChannelSummary[];
+ channels: TAlertChannelEmbedded[];
createdAt: string;
updatedAt: string;
};
@@ -84,6 +90,15 @@ export type TListAlertsDTO = {
enabled?: boolean;
};
+export type TAlertChannelInput = {
+ id?: string;
+ name: string;
+ channelType: AlertChannelType;
+ config?: Record<string, unknown>;
+ enabled?: boolean;
+ recipients?: TAlertChannelRecipient[];
+};
+
export type TCreateAlertDTO = {
name: string;
description?: string;
@@ -94,21 +109,84 @@ export type TCreateAlertDTO = {
filters?: unknown;
enabled?: boolean;
projectId?: string | null;
- channelIds: string[];
+ channels: TAlertChannelInput[];
};
export type TUpdateAlertDTO = {
alertId: string;
- // Carried only so mutations can invalidate the right scope; not sent to the API.
projectId?: string | null;
name?: string;
description?: string | null;
condition?: unknown;
filters?: unknown;
enabled?: boolean;
- channelIds?: string[];
+ channels?: TAlertChannelInput[];
};
+export const channelFormSchema = z
+ .object({
+ id: z.string().optional(),
+ channelType: z.nativeEnum(AlertChannelType),
+ name: z.string().min(1, "Name is required").max(255),
+ enabled: z.boolean().default(true),
+ webhookUrl: z.string().optional(),
+ url: z.string().optional(),
+ signingSecret: z.string().optional(),
+ integrationKey: z.string().optional(),
+ recipients: z
+ .array(
+ z.object({
+ principalType: z.nativeEnum(AlertPrincipalType),
+ principalId: z.string()
+ })
+ )
+ .default([]),
+ hasWebhookUrl: z.boolean().optional(),
+ hasSigningSecret: z.boolean().optional(),
+ hasIntegrationKey: z.boolean().optional()
+ })
+ .superRefine((channel, ctx) => {
+ const isNew = !channel.id;
+ switch (channel.channelType) {
+ case AlertChannelType.Email:
+ if (channel.recipients.length === 0) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["recipients"],
+ message: "Add at least one recipient"
+ });
+ }
+ break;
+ case AlertChannelType.Slack:
+ if ((isNew || !channel.hasWebhookUrl) && !channel.webhookUrl) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["webhookUrl"],
+ message: "Webhook URL is required"
+ });
+ }
+ break;
+ case AlertChannelType.Webhook:
+ if (!channel.url) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["url"], message: "URL is required" });
+ }
+ break;
+ case AlertChannelType.PagerDuty:
+ if ((isNew || !channel.hasIntegrationKey) && !channel.integrationKey) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["integrationKey"],
+ message: "Integration key is required"
+ });
+ }
+ break;
+ default:
+ break;
+ }
+ });
+
+export type TChannelForm = z.infer<typeof channelFormSchema>;
+
export const alertFormSchema = z.object({
name: z.string().min(1, "Name is required").max(255),
description: z.string().max(1000).optional(),
@@ -122,7 +200,7 @@ export const alertFormSchema = z.object({
alertBeforeUnit: z.nativeEnum(AlertTimeUnit),
dailyReminder: z.boolean().default(false),
enabled: z.boolean().default(true),
- channelIds: z.array(z.string()).min(1, "At least one channel is required")
+ channels: z.array(channelFormSchema).min(1, "At least one channel is required")
});
export type TAlertForm = z.infer<typeof alertFormSchema>;
diff --git a/frontend/src/views/AlertsPage/components/AlertForm.tsx b/frontend/src/views/AlertsPage/components/AlertForm.tsx
index ddad102a9d..faf2d98dd3 100644
--- a/frontend/src/views/AlertsPage/components/AlertForm.tsx
+++ b/frontend/src/views/AlertsPage/components/AlertForm.tsx
@@ -33,17 +33,20 @@ import {
ALERT_EVENT_TYPE_LABELS,
ALERT_RESOURCE_TYPE_LABELS,
ALERT_TIME_UNIT_LABELS,
+ AlertChannelType,
AlertEventType,
alertFormSchema,
AlertResourceType,
AlertTimeUnit,
TAlert,
+ TAlertChannelInput,
TAlertForm,
+ TChannelForm,
useCreateAlert,
useUpdateAlert
} from "@app/hooks/api/alerts";
-import { AttachChannelsField } from "./AttachChannelsField";
+import { ChannelsField } from "./ChannelsField";
type Props = {
projectId?: string;
@@ -84,6 +87,21 @@ const parseAlertBefore = (alertBefore?: string): { value: number; unit: AlertTim
return { value: 7, unit: AlertTimeUnit.Days };
};
+const toChannelForm = (channel: TAlert["channels"][number]): TChannelForm => ({
+ id: channel.id,
+ channelType: channel.channelType,
+ name: channel.name,
+ enabled: channel.enabled,
+ recipients: channel.recipients,
+ webhookUrl: "",
+ url: (channel.config.url as string) ?? "",
+ signingSecret: "",
+ integrationKey: "",
+ hasWebhookUrl: Boolean(channel.config.hasWebhookUrl),
+ hasSigningSecret: Boolean(channel.config.hasSigningSecret),
+ hasIntegrationKey: Boolean(channel.config.hasIntegrationKey)
+});
+
const buildFormDefaults = (alert?: TAlert): TAlertForm => {
if (!alert) {
return {
@@ -95,7 +113,7 @@ const buildFormDefaults = (alert?: TAlert): TAlertForm => {
alertBeforeUnit: AlertTimeUnit.Days,
dailyReminder: false,
enabled: true,
- channelIds: []
+ channels: []
};
}
@@ -110,8 +128,39 @@ const buildFormDefaults = (alert?: TAlert): TAlertForm => {
alertBeforeUnit: unit,
dailyReminder: alert.condition?.dailyReminder ?? false,
enabled: alert.enabled,
- channelIds: alert.channels.map((channel) => channel.id)
+ channels: alert.channels.map(toChannelForm)
+ };
+};
+
+const toChannelInput = (channel: TChannelForm): TAlertChannelInput => {
+ const base: TAlertChannelInput = {
+ ...(channel.id ? { id: channel.id } : {}),
+ name: channel.name,
+ channelType: channel.channelType,
+ enabled: channel.enabled
};
+
+ switch (channel.channelType) {
+ case AlertChannelType.Email:
+ return { ...base, config: {}, recipients: channel.recipients };
+ case AlertChannelType.Slack:
+ return { ...base, config: channel.webhookUrl ? { webhookUrl: channel.webhookUrl } : {} };
+ case AlertChannelType.Webhook:
+ return {
+ ...base,
+ config: {
+ url: channel.url,
+ ...(channel.signingSecret ? { signingSecret: channel.signingSecret } : {})
+ }
+ };
+ case AlertChannelType.PagerDuty:
+ return {
+ ...base,
+ config: channel.integrationKey ? { integrationKey: channel.integrationKey } : {}
+ };
+ default:
+ return { ...base, config: {} };
+ }
};
export const AlertForm = ({
@@ -137,7 +186,7 @@ export const AlertForm = ({
control,
register,
handleSubmit,
- formState: { errors, isSubmitting, dirtyFields }
+ formState: { errors, isSubmitting }
} = formMethods;
const isProjectScope = Boolean(projectId);
@@ -171,9 +220,9 @@ export const AlertForm = ({
const onSubmit = async (data: TAlertForm) => {
const alertBefore = `${data.alertBeforeValue}${data.alertBeforeUnit}`;
const condition = { alertBefore, dailyReminder: data.dailyReminder };
+ const channels = data.channels.map(toChannelInput);
try {
if (isEditing && alert) {
- const channelsDirty = Boolean(dirtyFields.channelIds);
await updateAlert.mutateAsync({
alertId: alert.id,
projectId: alert.projectId,
@@ -181,7 +230,7 @@ export const AlertForm = ({
description: data.description || null,
enabled: data.enabled,
condition,
- ...(channelsDirty ? { channelIds: data.channelIds } : {})
+ channels
});
createNotification({ text: "Successfully updated alert", type: "success" });
} else {
@@ -195,7 +244,7 @@ export const AlertForm = ({
filters: null,
enabled: data.enabled,
projectId: projectId ?? null,
- channelIds: data.channelIds
+ channels
});
createNotification({ text: "Successfully created alert", type: "success" });
}
@@ -384,7 +433,7 @@ export const AlertForm = ({
<section className="flex flex-col gap-4">
<SectionHeader step={3} title="Delivery" />
- <AttachChannelsField projectId={projectId} />
+ <ChannelsField projectId={projectId} />
</section>
</div>
diff --git a/frontend/src/views/AlertsPage/components/AttachChannelsField.tsx b/frontend/src/views/AlertsPage/components/AttachChannelsField.tsx
deleted file mode 100644
index c7bcf45d29..0000000000
--- a/frontend/src/views/AlertsPage/components/AttachChannelsField.tsx
+++ /dev/null
@@ -1,132 +0,0 @@
-import { Controller, useFormContext } from "react-hook-form";
-import { ChevronDownIcon, PlusIcon, XIcon } from "lucide-react";
-
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- FieldLabel,
- IconButton,
- Skeleton
-} from "@app/components/v3";
-import { TAlertChannel, useListAlertChannels } from "@app/hooks/api/alertChannels";
-import { TAlertForm } from "@app/hooks/api/alerts";
-
-import { getChannelIcon } from "./channelIcons";
-
-type Props = {
- projectId?: string;
-};
-
-export const AttachChannelsField = ({ projectId }: Props) => {
- const {
- control,
- formState: { errors }
- } = useFormContext<TAlertForm>();
- const { isPending, data: channels = [] } = useListAlertChannels(projectId ? { projectId } : {});
-
- 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: TAlertChannel) => {
- const Icon = getChannelIcon(channel.channelType);
- 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 = getChannelIcon(channel.channelType);
- 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 TAlertChannel => Boolean(c))
- .map(renderCard)
- )}
- </div>
- )}
- </div>
- );
- }}
- />
- );
-};
diff --git a/frontend/src/views/AlertsPage/components/ChannelCard.tsx b/frontend/src/views/AlertsPage/components/ChannelCard.tsx
new file mode 100644
index 0000000000..b4f95d6089
--- /dev/null
+++ b/frontend/src/views/AlertsPage/components/ChannelCard.tsx
@@ -0,0 +1,186 @@
+import { Controller, useFormContext, useWatch } from "react-hook-form";
+import { TrashIcon } from "lucide-react";
+
+import {
+ Field,
+ FieldContent,
+ FieldError,
+ FieldLabel,
+ IconButton,
+ Input,
+ Switch
+} from "@app/components/v3";
+import { useScopeVariant } from "@app/hooks";
+import { ALERT_CHANNEL_TYPE_LABELS, AlertChannelType, TAlertForm } from "@app/hooks/api/alerts";
+
+import { getChannelIcon } from "./channelIcons";
+import { ChannelRecipientsField } from "./ChannelRecipientsField";
+
+type Props = {
+ index: number;
+ projectId?: string;
+ onRemove: () => void;
+ canRemove: boolean;
+};
+
+const KEEP_PLACEHOLDER = "•••••••• (leave blank to keep)";
+
+export const ChannelCard = ({ index, projectId, onRemove, canRemove }: Props) => {
+ const scopeVariant = useScopeVariant();
+ const {
+ control,
+ register,
+ formState: { errors }
+ } = useFormContext<TAlertForm>();
+
+ const channel = useWatch({ control, name: `channels.${index}` });
+ const channelType = channel?.channelType;
+ const isExisting = Boolean(channel?.id);
+ const channelErrors = errors.channels?.[index];
+
+ const Icon = getChannelIcon(channelType);
+
+ return (
+ <div className="flex flex-col gap-4 rounded-md border border-border p-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Icon className="size-4 text-muted" />
+ <span className="text-sm font-medium text-foreground">
+ {ALERT_CHANNEL_TYPE_LABELS[channelType]}
+ </span>
+ </div>
+ <div className="flex items-center gap-3">
+ <Controller
+ control={control}
+ name={`channels.${index}.enabled`}
+ render={({ field }) => (
+ <FieldLabel
+ htmlFor={`channel-${index}-enabled`}
+ className="flex cursor-pointer items-center gap-2 text-xs text-muted"
+ >
+ Enabled
+ <Switch
+ id={`channel-${index}-enabled`}
+ variant={scopeVariant}
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FieldLabel>
+ )}
+ />
+ {canRemove && (
+ <IconButton aria-label="Remove channel" variant="ghost" size="xs" onClick={onRemove}>
+ <TrashIcon className="size-4" />
+ </IconButton>
+ )}
+ </div>
+ </div>
+
+ <Field>
+ <FieldLabel htmlFor={`channel-${index}-name`}>Name</FieldLabel>
+ <FieldContent>
+ <Input
+ id={`channel-${index}-name`}
+ placeholder="Notify on-call"
+ isError={Boolean(channelErrors?.name)}
+ {...register(`channels.${index}.name`)}
+ />
+ <FieldError errors={[channelErrors?.name]} />
+ </FieldContent>
+ </Field>
+
+ {channelType === AlertChannelType.Email && (
+ <Field>
+ <FieldLabel>Recipients</FieldLabel>
+ <FieldContent>
+ <Controller
+ control={control}
+ name={`channels.${index}.recipients`}
+ render={({ field }) => (
+ <ChannelRecipientsField
+ projectId={projectId}
+ value={field.value ?? []}
+ onChange={field.onChange}
+ isError={Boolean(channelErrors?.recipients)}
+ />
+ )}
+ />
+ <FieldError errors={[channelErrors?.recipients as { message?: string } | undefined]} />
+ </FieldContent>
+ </Field>
+ )}
+
+ {channelType === AlertChannelType.Slack && (
+ <Field>
+ <FieldLabel htmlFor={`channel-${index}-webhookUrl`}>Webhook URL</FieldLabel>
+ <FieldContent>
+ <Input
+ id={`channel-${index}-webhookUrl`}
+ type="password"
+ placeholder={
+ isExisting && channel?.hasWebhookUrl
+ ? KEEP_PLACEHOLDER
+ : "https://hooks.slack.com/..."
+ }
+ isError={Boolean(channelErrors?.webhookUrl)}
+ {...register(`channels.${index}.webhookUrl`)}
+ />
+ <FieldError errors={[channelErrors?.webhookUrl]} />
+ </FieldContent>
+ </Field>
+ )}
+
+ {channelType === AlertChannelType.Webhook && (
+ <>
+ <Field>
+ <FieldLabel htmlFor={`channel-${index}-url`}>URL</FieldLabel>
+ <FieldContent>
+ <Input
+ id={`channel-${index}-url`}
+ placeholder="https://example.com/webhook"
+ isError={Boolean(channelErrors?.url)}
+ {...register(`channels.${index}.url`)}
+ />
+ <FieldError errors={[channelErrors?.url]} />
+ </FieldContent>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`channel-${index}-signingSecret`}>
+ Signing secret <span className="text-mineshaft-400">(optional)</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ id={`channel-${index}-signingSecret`}
+ type="password"
+ placeholder={isExisting && channel?.hasSigningSecret ? KEEP_PLACEHOLDER : ""}
+ isError={Boolean(channelErrors?.signingSecret)}
+ {...register(`channels.${index}.signingSecret`)}
+ />
+ <FieldError errors={[channelErrors?.signingSecret]} />
+ </FieldContent>
+ </Field>
+ </>
+ )}
+
+ {channelType === AlertChannelType.PagerDuty && (
+ <Field>
+ <FieldLabel htmlFor={`channel-${index}-integrationKey`}>Integration key</FieldLabel>
+ <FieldContent>
+ <Input
+ id={`channel-${index}-integrationKey`}
+ type="password"
+ placeholder={
+ isExisting && channel?.hasIntegrationKey
+ ? KEEP_PLACEHOLDER
+ : "32-character integration key"
+ }
+ isError={Boolean(channelErrors?.integrationKey)}
+ {...register(`channels.${index}.integrationKey`)}
+ />
+ <FieldError errors={[channelErrors?.integrationKey]} />
+ </FieldContent>
+ </Field>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/views/AlertsPage/components/ChannelRecipientsField.tsx b/frontend/src/views/AlertsPage/components/ChannelRecipientsField.tsx
new file mode 100644
index 0000000000..6f52904c54
--- /dev/null
+++ b/frontend/src/views/AlertsPage/components/ChannelRecipientsField.tsx
@@ -0,0 +1,141 @@
+import { UserIcon, UsersIcon } from "lucide-react";
+
+import { FilterableSelect } from "@app/components/v3";
+import { useOrganization } from "@app/context";
+import {
+ useGetOrganizationGroups,
+ useGetOrgUsers,
+ useGetWorkspaceUsers,
+ useListWorkspaceGroups
+} from "@app/hooks/api";
+import { AlertPrincipalType, TAlertChannelRecipient } from "@app/hooks/api/alerts";
+
+type RecipientOption = {
+ principalType: AlertPrincipalType;
+ principalId: string;
+ label: string;
+ groupLabel: "Users" | "Groups";
+};
+
+const userLabel = (user: {
+ firstName?: string;
+ lastName?: string;
+ username?: string;
+ email?: string;
+}): string => {
+ const name = `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim();
+ return name || user.username || user.email || "Unknown user";
+};
+
+type SelectProps = {
+ value: TAlertChannelRecipient[];
+ onChange: (recipients: TAlertChannelRecipient[]) => void;
+ isError?: boolean;
+};
+
+const RecipientSelect = ({
+ options,
+ value,
+ onChange,
+ isError
+}: SelectProps & { options: RecipientOption[] }) => {
+ const byKey = new Map(options.map((o) => [`${o.principalType}-${o.principalId}`, o]));
+ const selected = value.map(
+ (recipient) =>
+ byKey.get(`${recipient.principalType}-${recipient.principalId}`) ?? {
+ principalType: recipient.principalType,
+ principalId: recipient.principalId,
+ label: recipient.principalId,
+ groupLabel:
+ recipient.principalType === AlertPrincipalType.Group ? "Groups" : ("Users" as const)
+ }
+ );
+
+ return (
+ <FilterableSelect<RecipientOption>
+ isMulti
+ placeholder="Select users or groups..."
+ options={options}
+ value={selected}
+ isError={isError}
+ groupBy="groupLabel"
+ getGroupHeaderLabel={(groupValue) => groupValue}
+ getOptionValue={(option) => `${option.principalType}-${option.principalId}`}
+ getOptionLabel={(option) => option.label}
+ formatOptionLabel={(option) => (
+ <span className="flex items-center gap-2">
+ {option.principalType === AlertPrincipalType.Group ? (
+ <UsersIcon className="size-3.5 text-muted" />
+ ) : (
+ <UserIcon className="size-3.5 text-muted" />
+ )}
+ {option.label}
+ </span>
+ )}
+ onChange={(newValue) =>
+ onChange(
+ (newValue as RecipientOption[]).map((option) => ({
+ principalType: option.principalType,
+ principalId: option.principalId
+ }))
+ )
+ }
+ />
+ );
+};
+
+const OrgRecipientSelect = ({ orgId, ...props }: SelectProps & { orgId: string }) => {
+ const { data: users = [] } = useGetOrgUsers(orgId);
+ const { data: groups = [] } = useGetOrganizationGroups(orgId);
+
+ const options: RecipientOption[] = [
+ ...users.map((membership) => ({
+ principalType: AlertPrincipalType.User,
+ principalId: membership.user.id,
+ label: userLabel(membership.user),
+ groupLabel: "Users" as const
+ })),
+ ...groups.map((group) => ({
+ principalType: AlertPrincipalType.Group,
+ principalId: group.id,
+ label: group.name,
+ groupLabel: "Groups" as const
+ }))
+ ];
+
+ return <RecipientSelect options={options} {...props} />;
+};
+
+const ProjectRecipientSelect = ({ projectId, ...props }: SelectProps & { projectId: string }) => {
+ const { data: users = [] } = useGetWorkspaceUsers(projectId);
+ const { data: groups = [] } = useListWorkspaceGroups(projectId);
+
+ const options: RecipientOption[] = [
+ ...users.map((membership) => ({
+ principalType: AlertPrincipalType.User,
+ principalId: membership.user.id,
+ label: userLabel(membership.user),
+ groupLabel: "Users" as const
+ })),
+ ...groups.map((membership) => ({
+ principalType: AlertPrincipalType.Group,
+ principalId: membership.group.id,
+ label: membership.group.name,
+ groupLabel: "Groups" as const
+ }))
+ ];
+
+ return <RecipientSelect options={options} {...props} />;
+};
+
+type Props = SelectProps & { projectId?: string };
+
+export const ChannelRecipientsField = ({ projectId, ...props }: Props) => {
+ const { currentOrg } = useOrganization();
+
+ return projectId ? (
+ <ProjectRecipientSelect projectId={projectId} {...props} />
+ ) : (
+ <OrgRecipientSelect orgId={currentOrg.id} {...props} />
+ );
+};
diff --git a/frontend/src/views/AlertsPage/components/ChannelsField.tsx b/frontend/src/views/AlertsPage/components/ChannelsField.tsx
new file mode 100644
index 0000000000..1f6abedbe9
--- /dev/null
+++ b/frontend/src/views/AlertsPage/components/ChannelsField.tsx
@@ -0,0 +1,102 @@
+import { useFieldArray, useFormContext } from "react-hook-form";
+import { ChevronDownIcon, PlusIcon } from "lucide-react";
+
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ FieldLabel
+} from "@app/components/v3";
+import {
+ ALERT_CHANNEL_TYPE_LABELS,
+ AlertChannelType,
+ AlertPrincipalType,
+ TAlertForm,
+ TChannelForm
+} from "@app/hooks/api/alerts";
+
+import { ChannelCard } from "./ChannelCard";
+import { getChannelIcon } from "./channelIcons";
+
+type Props = {
+ projectId?: string;
+};
+
+const buildNewChannel = (channelType: AlertChannelType): TChannelForm => ({
+ channelType,
+ name: "",
+ enabled: true,
+ recipients: [] as { principalType: AlertPrincipalType; principalId: string }[],
+ webhookUrl: "",
+ url: "",
+ signingSecret: "",
+ integrationKey: ""
+});
+
+export const ChannelsField = ({ projectId }: Props) => {
+ const {
+ control,
+ formState: { errors }
+ } = useFormContext<TAlertForm>();
+ const { fields, append, remove } = useFieldArray({ control, name: "channels" });
+ 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">
+ <FieldLabel>
+ Channels <span className="text-red">*</span>
+ </FieldLabel>
+ <span className="text-xs text-muted">Add at least one delivery channel.</span>
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="button" variant="outline" size="sm">
+ <PlusIcon className="size-4" />
+ Add channel
+ <ChevronDownIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ sideOffset={4}
+ className="w-[var(--radix-dropdown-menu-trigger-width)]"
+ >
+ {Object.values(AlertChannelType).map((type) => {
+ const Icon = getChannelIcon(type);
+ return (
+ <DropdownMenuItem key={type} onClick={() => append(buildNewChannel(type))}>
+ <Icon className="size-4" />
+ {ALERT_CHANNEL_TYPE_LABELS[type]}
+ </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 yet. Add at least one channel to receive notifications.
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3">
+ {fields.map((field, index) => (
+ <ChannelCard
+ key={field.id}
+ index={index}
+ projectId={projectId}
+ canRemove={fields.length > 1}
+ onRemove={() => remove(index)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};