reorg to domain and api

This commit is contained in:
Alex Holliday committed 2026-06-09 12:34:15 -07:00
1 parent 0fb210e9e1
commit d022f7d849
190 files changed
+643 -830

No files matched your search

@@ -0,0 +1,275 @@
import type { Monitor } from "@/domain/monitors/monitor.types.js";
import type { HardwareStatusPayload, MonitorStatusResponse } from "@/types/network.js";
import type { MonitorActionDecision } from "@/service/job-queues/job-queue.helper.js";
import type {
NotificationMessage,
NotificationType,
NotificationSeverity,
ThresholdBreach,
NotificationContent,
} from "@/domain/notifications/notification.type.js";
export interface INotificationMessageBuilder {
buildMessage(
monitor: Monitor,
monitorStatusResponse: MonitorStatusResponse,
decision: MonitorActionDecision,
clientHost: string
): NotificationMessage;
extractThresholdBreaches(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): ThresholdBreach[];
}
const SERVICE_NAME = "NotificationMessageBuilder";
export class NotificationMessageBuilder implements INotificationMessageBuilder {
static SERVICE_NAME = SERVICE_NAME;
buildMessage(
monitor: Monitor,
monitorStatusResponse: MonitorStatusResponse,
decision: MonitorActionDecision,
clientHost: string
): NotificationMessage {
const type = this.determineNotificationType(decision, monitor);
const severity = this.determineSeverity(type);
const content = this.buildContent(type, monitor, monitorStatusResponse);
return {
type,
severity,
monitor: {
id: monitor.id,
name: monitor.name,
url: monitor.url,
type: monitor.type,
status: monitor.status,
},
content,
clientHost,
metadata: {
teamId: monitor.teamId,
notificationReason: decision.notificationReason || "status_change",
},
};
}
private determineNotificationType(decision: MonitorActionDecision, monitor: Monitor): NotificationType {
// Down status has highest priority (critical)
if (monitor.status === "down") {
return "monitor_down";
}
// Threshold breach (only if not down)
if (decision.notificationReason === "threshold_breach") {
return "threshold_breach";
}
// Recovery from threshold breach (only for hardware monitors)
if (decision.notificationReason === "status_change" && monitor.status === "up" && monitor.type === "hardware") {
return "threshold_resolved";
}
// Standard recovery (up)
if (monitor.status === "up") {
return "monitor_up";
}
// Default to monitor_up for any other case
return "monitor_up";
}
private determineSeverity(type: NotificationType): NotificationSeverity {
switch (type) {
case "monitor_down":
return "critical";
case "threshold_breach":
return "warning";
case "monitor_up":
case "threshold_resolved":
return "success";
case "test":
return "info";
default:
return "info";
}
}
private buildContent(type: NotificationType, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): NotificationContent {
switch (type) {
case "monitor_down":
return this.buildMonitorDownContent(monitor, monitorStatusResponse);
case "monitor_up":
return this.buildMonitorUpContent(monitor);
case "threshold_breach":
return this.buildThresholdBreachContent(monitor, monitorStatusResponse as MonitorStatusResponse<HardwareStatusPayload>);
case "threshold_resolved":
return this.buildThresholdResolvedContent(monitor);
default:
return this.buildDefaultContent(monitor);
}
}
private buildMonitorDownContent(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): NotificationContent {
const title = `Monitor Down: ${monitor.name}`;
const summary = `Monitor "${monitor.name}" is currently down and unreachable.`;
const details = [`URL: ${monitor.url}`, `Status: Down`, `Type: ${monitor.type}`];
// Add response code if available
if (monitorStatusResponse.code) {
details.push(`Response Code: ${monitorStatusResponse.code}`);
}
// Add error message if available
if (monitorStatusResponse.message) {
details.push(`Error: ${monitorStatusResponse.message}`);
}
return {
title,
summary,
details,
timestamp: new Date(),
};
}
private buildMonitorUpContent(monitor: Monitor): NotificationContent {
const title = `Monitor Recovered: ${monitor.name}`;
const summary = `Monitor "${monitor.name}" is back up and operational.`;
const details = [`URL: ${monitor.url}`, `Status: Up`, `Type: ${monitor.type}`];
return {
title,
summary,
details,
timestamp: new Date(),
};
}
private buildThresholdBreachContent(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse<HardwareStatusPayload>): NotificationContent {
const title = `Threshold Exceeded: ${monitor.name}`;
const summary = `Monitor "${monitor.name}" has exceeded one or more thresholds.`;
const details = [`URL: ${monitor.url}`, `Status: Threshold exceeded`, `Type: ${monitor.type}`];
const thresholds = this.extractThresholdBreaches(monitor, monitorStatusResponse);
return {
title,
summary,
details,
thresholds,
timestamp: new Date(),
};
}
private buildThresholdResolvedContent(monitor: Monitor): NotificationContent {
const title = `Thresholds Resolved: ${monitor.name}`;
const summary = `Monitor "${monitor.name}" thresholds have returned to normal.`;
const details = [`URL: ${monitor.url}`, `Status: Up`, `Type: ${monitor.type}`];
return {
title,
summary,
details,
timestamp: new Date(),
};
}
private buildDefaultContent(monitor: Monitor): NotificationContent {
return {
title: `Monitor: ${monitor.name}`,
summary: `Status update for monitor "${monitor.name}".`,
details: [`URL: ${monitor.url}`, `Status: ${monitor.status}`, `Type: ${monitor.type}`],
timestamp: new Date(),
};
}
public extractThresholdBreaches(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse<HardwareStatusPayload>): ThresholdBreach[] {
const breaches: ThresholdBreach[] = [];
// Check if this is a hardware monitor with threshold data
if (monitor.type !== "hardware" || !monitorStatusResponse.payload || typeof monitorStatusResponse.payload === "string") {
return breaches;
}
// Cast to HardwareStatusPayload type
const payload = monitorStatusResponse.payload;
const hardware = payload.data;
if (!hardware) {
return breaches;
}
// Note: usage_percent values in hardware payload are decimals (0-1)
if (monitor.cpuAlertThreshold !== undefined && monitor.cpuAlertThreshold !== null && hardware.cpu?.usage_percent !== undefined) {
const cpuUsageDecimal = hardware.cpu.usage_percent;
const cpuPercent = cpuUsageDecimal * 100;
const threshold = monitor.cpuAlertThreshold;
if (cpuPercent > threshold) {
breaches.push({
metric: "cpu",
currentValue: cpuPercent,
threshold,
unit: "%",
formattedValue: `${cpuPercent.toFixed(1)}%`,
});
}
}
// Memory threshold breach
if (monitor.memoryAlertThreshold !== undefined && monitor.memoryAlertThreshold !== null && hardware.memory?.usage_percent !== undefined) {
const memoryUsageDecimal = hardware.memory.usage_percent;
const memoryPercent = memoryUsageDecimal * 100;
const threshold = monitor.memoryAlertThreshold;
if (memoryPercent > threshold) {
breaches.push({
metric: "memory",
currentValue: memoryPercent,
threshold,
unit: "%",
formattedValue: `${memoryPercent.toFixed(1)}%`,
});
}
}
// Disk threshold breach
if (monitor.diskAlertThreshold !== undefined && monitor.diskAlertThreshold !== null && Array.isArray(hardware.disk)) {
// Find the highest disk usage
let maxDiskUsageDecimal = 0;
for (const disk of hardware.disk) {
if (disk.usage_percent !== undefined && disk.usage_percent > maxDiskUsageDecimal) {
maxDiskUsageDecimal = disk.usage_percent;
}
}
const maxDiskPercent = maxDiskUsageDecimal * 100;
const threshold = monitor.diskAlertThreshold;
if (maxDiskPercent > threshold) {
breaches.push({
metric: "disk",
currentValue: maxDiskPercent,
threshold,
unit: "%",
formattedValue: `${maxDiskPercent.toFixed(1)}%`,
});
}
}
// Temperature threshold breach
if (monitor.tempAlertThreshold !== undefined && monitor.tempAlertThreshold !== null && hardware.cpu?.temperature) {
// Temperature is an array in cpu.temperature
const temps = Array.isArray(hardware.cpu.temperature) ? hardware.cpu.temperature : [hardware.cpu.temperature];
const maxTemp = Math.max(...temps.filter((t: number) => !isNaN(t)));
const threshold = monitor.tempAlertThreshold;
if (maxTemp >= threshold) {
breaches.push({
metric: "temp",
currentValue: maxTemp,
threshold,
unit: "°C",
formattedValue: `${maxTemp.toFixed(1)}°C`,
});
}
}
return breaches;
}
}
+65
View File
@@ -0,0 +1,65 @@
import { Schema, model, type Types } from "mongoose";
import type { Notification, NotificationChannel } from "@/domain/notifications/notification.type.js";
interface NotificationDocument extends Omit<Notification, "id" | "userId" | "teamId" | "createdAt" | "updatedAt"> {
_id: Types.ObjectId;
userId: Types.ObjectId;
teamId: Types.ObjectId;
createdAt: Date;
updatedAt: Date;
}
const NotificationSchema = new Schema<NotificationDocument>(
{
userId: {
type: Schema.Types.ObjectId,
ref: "User",
immutable: true,
required: true,
},
teamId: {
type: Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
type: {
type: String,
enum: [
"email",
"slack",
"discord",
"webhook",
"pager_duty",
"matrix",
"teams",
"telegram",
"pushover",
"twilio",
"ntfy",
] as NotificationChannel[],
required: true,
},
notificationName: {
type: String,
required: true,
},
address: { type: String },
phone: { type: String },
homeserverUrl: { type: String },
roomId: { type: String },
accessToken: { type: String },
accountSid: { type: String },
twilioPhoneNumber: { type: String },
topic: { type: String },
},
{
timestamps: true,
}
);
const NotificationModel = model<NotificationDocument>("Notification", NotificationSchema);
export type { NotificationDocument };
export { NotificationModel };
export default NotificationModel;
@@ -0,0 +1,13 @@
import type { Notification } from "@/domain/notifications/notification.type.js";
export interface INotificationsRepository {
// create
create(notificationData: Partial<Notification>): Promise<Notification>;
// fetch
findById(id: string, teamId: string): Promise<Notification>;
findNotificationsByIds(ids: string[]): Promise<Notification[]>;
findByTeamId(teamId: string): Promise<Notification[]>;
// update
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
// delete
deleteById(id: string, teamId: string): Promise<Notification>;
}
@@ -0,0 +1,100 @@
import mongoose from "mongoose";
import { NotificationModel, type NotificationDocument } from "@/domain/notifications/notification.model.js";
import { INotificationsRepository } from "@/domain/notifications/notification.repository.interface.js";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { AppError } from "@/utils/AppError.js";
class MongoNotificationsRepository implements INotificationsRepository {
private mapDocuments = (documents: NotificationDocument[]): Notification[] => {
if (!documents?.length) {
return [];
}
return documents.map((doc) => this.toEntity(doc));
};
private toEntity = (doc: NotificationDocument): Notification => {
const toStringId = (value: mongoose.Types.ObjectId | string): string => {
return value instanceof mongoose.Types.ObjectId ? value.toString() : value;
};
const toDateString = (value: Date | string): string => {
return value instanceof Date ? value.toISOString() : value;
};
return {
id: toStringId(doc._id),
userId: toStringId(doc.userId),
teamId: toStringId(doc.teamId),
type: doc.type,
notificationName: doc.notificationName,
address: doc.address ?? undefined,
phone: doc.phone ?? undefined,
homeserverUrl: doc.homeserverUrl ?? undefined,
roomId: doc.roomId ?? undefined,
accessToken: doc.accessToken ?? undefined,
accountSid: doc.accountSid ?? undefined,
twilioPhoneNumber: doc.twilioPhoneNumber ?? undefined,
topic: doc.topic ?? undefined,
createdAt: toDateString(doc.createdAt),
updatedAt: toDateString(doc.updatedAt),
};
};
create = async (notificationData: Partial<Notification>) => {
const notification = await NotificationModel.create({ ...notificationData });
if (!notification) {
throw new AppError({ message: "Failed to create notification", status: 500 });
}
return this.toEntity(notification);
};
findById = async (id: string, teamId: string): Promise<Notification> => {
const notification = await NotificationModel.findOne({
_id: new mongoose.Types.ObjectId(id),
teamId: new mongoose.Types.ObjectId(teamId),
});
if (!notification) {
throw new AppError({ message: "Notification not found", status: 404 });
}
return this.toEntity(notification);
};
findNotificationsByIds = async (ids: string[]) => {
const mongoIds = ids.map((id) => new mongoose.Types.ObjectId(id));
const documents = await NotificationModel.find({ _id: { $in: mongoIds } });
return this.mapDocuments(documents);
};
findByTeamId = async (teamId: string): Promise<Notification[]> => {
const documents = await NotificationModel.find({ teamId });
return this.mapDocuments(documents);
};
updateById = async (id: string, teamId: string, patch: Partial<Notification>): Promise<Notification> => {
const notification = await NotificationModel.findOneAndUpdate(
{
_id: new mongoose.Types.ObjectId(id),
teamId: new mongoose.Types.ObjectId(teamId),
},
{ $set: patch },
{ new: true, runValidators: true }
);
if (!notification) {
throw new AppError({ message: "Notification not found or could not be updated", status: 404 });
}
return this.toEntity(notification);
};
deleteById = async (id: string, teamId: string): Promise<Notification> => {
const deleted = await NotificationModel.findOneAndDelete({
_id: new mongoose.Types.ObjectId(id),
teamId: new mongoose.Types.ObjectId(teamId),
});
if (!deleted) {
throw new AppError({ message: "Notification not found or could not be deleted", status: 404 });
}
return this.toEntity(deleted);
};
}
export default MongoNotificationsRepository;
@@ -0,0 +1,231 @@
import type { Monitor } from "@/domain/monitors/monitor.types.js";
import type { Notification } from "@/domain/notifications/notification.type.js";
import type { MonitorStatusResponse } from "@/types/network.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
import { INotificationsRepository } from "@/domain/notifications/notification.repository.interface.js";
import { INotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { MonitorActionDecision } from "@/service/job-queues/job-queue.helper.js";
import type { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
import { ILogger } from "@/utils/logger.js";
import type { INotificationMessageBuilder } from "@/domain/notifications/notification.message-builder.js";
export interface INotificationsService {
createNotification: (notificationData: Partial<Notification>, userId: string, teamId: string) => Promise<Notification>;
findById: (id: string, teamId: string) => Promise<Notification>;
findNotificationsByTeamId: (teamId: string) => Promise<Notification[]>;
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
deleteById: (id: string, teamId: string) => Promise<Notification>;
handleNotifications: (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => Promise<boolean>;
sendTestNotification: (notification: Partial<Notification>) => Promise<boolean>;
testAllNotifications: (notificationIds: string[]) => Promise<boolean>;
}
const SERVICE_NAME = "NotificationsService";
export class NotificationsService implements INotificationsService {
static SERVICE_NAME = SERVICE_NAME;
private notificationsRepository: INotificationsRepository;
private monitorsRepository: IMonitorsRepository;
private webhookProvider: INotificationProvider;
private emailProvider: INotificationProvider;
private slackProvider: INotificationProvider;
private discordProvider: INotificationProvider;
private pagerDutyProvider: INotificationProvider;
private matrixProvider: INotificationProvider;
private teamsProvider: INotificationProvider;
private telegramProvider: INotificationProvider;
private pushoverProvider: INotificationProvider;
private twilioProvider: INotificationProvider;
private ntfyProvider: INotificationProvider;
private logger: ILogger;
private settingsService: ISettingsService;
private notificationMessageBuilder: INotificationMessageBuilder;
constructor(
notificationsRepository: INotificationsRepository,
monitorsRepository: IMonitorsRepository,
webhookProvider: INotificationProvider,
emailProvider: INotificationProvider,
slackProvider: INotificationProvider,
discordProvider: INotificationProvider,
pagerDutyProvider: INotificationProvider,
matrixProvider: INotificationProvider,
teamsProvider: INotificationProvider,
telegramProvider: INotificationProvider,
pushoverProvider: INotificationProvider,
twilioProvider: INotificationProvider,
ntfyProvider: INotificationProvider,
settingsService: ISettingsService,
logger: ILogger,
notificationMessageBuilder: INotificationMessageBuilder
) {
this.notificationsRepository = notificationsRepository;
this.monitorsRepository = monitorsRepository;
this.webhookProvider = webhookProvider;
this.emailProvider = emailProvider;
this.slackProvider = slackProvider;
this.discordProvider = discordProvider;
this.pagerDutyProvider = pagerDutyProvider;
this.matrixProvider = matrixProvider;
this.teamsProvider = teamsProvider;
this.telegramProvider = telegramProvider;
this.pushoverProvider = pushoverProvider;
this.twilioProvider = twilioProvider;
this.ntfyProvider = ntfyProvider;
this.settingsService = settingsService;
this.logger = logger;
this.notificationMessageBuilder = notificationMessageBuilder;
}
private send = async (
notification: Notification,
monitor: Monitor,
monitorStatusResponse: MonitorStatusResponse,
decision: MonitorActionDecision,
notificationMessage: NotificationMessage | undefined
): Promise<boolean> => {
if (!notificationMessage) {
this.logger.warn({
message: "Notification message not provided",
service: SERVICE_NAME,
method: "send",
});
return false;
}
// Route to provider based on notification type
switch (notification.type) {
case "webhook":
return await this.webhookProvider.sendMessage!(notification, notificationMessage);
case "slack":
return await this.slackProvider.sendMessage!(notification, notificationMessage);
case "matrix":
return await this.matrixProvider.sendMessage!(notification, notificationMessage);
case "pager_duty":
return await this.pagerDutyProvider.sendMessage!(notification, notificationMessage);
case "discord":
return await this.discordProvider.sendMessage!(notification, notificationMessage);
case "email":
return await this.emailProvider.sendMessage!(notification, notificationMessage);
case "teams":
return await this.teamsProvider.sendMessage!(notification, notificationMessage);
case "telegram":
return await this.telegramProvider.sendMessage!(notification, notificationMessage);
case "pushover":
return await this.pushoverProvider.sendMessage!(notification, notificationMessage);
case "twilio":
return await this.twilioProvider.sendMessage!(notification, notificationMessage);
case "ntfy":
return await this.ntfyProvider.sendMessage!(notification, notificationMessage);
default:
this.logger.warn({
message: `Unknown notification type: ${notification.type}`,
service: SERVICE_NAME,
method: "send",
});
return false;
}
};
private sendNotifications = async (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => {
const notificationIds = monitor.notifications ?? [];
const notifications = await this.notificationsRepository.findNotificationsByIds(notificationIds);
// Build notification message once for all notifications
const settings = this.settingsService.getSettings();
const clientHost = settings.clientHost || "Host not defined";
const notificationMessage = this.notificationMessageBuilder.buildMessage(monitor, monitorStatusResponse, decision, clientHost);
const tasks = notifications.map((notification) => this.send(notification, monitor, monitorStatusResponse, decision, notificationMessage));
const outcomes = await Promise.all(tasks);
const succeeded = outcomes.filter(Boolean).length;
const failed = outcomes.length - succeeded;
if (failed > 0) {
this.logger.warn({
message: `Notification send completed with ${succeeded} success, ${failed} failure(s)`,
service: SERVICE_NAME,
method: "sendNotifications",
});
}
// Return true if all notifications succeeded
return succeeded === notifications.length;
};
handleNotifications = async (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => {
if (!decision.shouldSendNotification) {
return false;
}
// Send notifications based on decision
return await this.sendNotifications(monitor, monitorStatusResponse, decision);
};
sendTestNotification = async (notification: Partial<Notification>) => {
switch (notification.type) {
case "email":
return await this.emailProvider.sendTestAlert(notification);
case "slack":
return await this.slackProvider.sendTestAlert(notification);
case "discord":
return await this.discordProvider.sendTestAlert(notification);
case "pager_duty":
return await this.pagerDutyProvider.sendTestAlert(notification);
case "matrix":
return await this.matrixProvider.sendTestAlert(notification);
case "webhook":
return await this.webhookProvider.sendTestAlert(notification);
case "teams":
return await this.teamsProvider.sendTestAlert(notification);
case "telegram":
return await this.telegramProvider.sendTestAlert(notification);
case "pushover":
return await this.pushoverProvider.sendTestAlert(notification);
case "twilio":
return await this.twilioProvider.sendTestAlert(notification);
case "ntfy":
return await this.ntfyProvider.sendTestAlert(notification);
default:
return false;
}
};
testAllNotifications = async (notificationIds: string[]) => {
const notifications = await this.notificationsRepository.findNotificationsByIds(notificationIds);
const tasks = notifications.map((notification) => this.sendTestNotification(notification));
const outcomes = await Promise.all(tasks);
const succeeded = outcomes.filter(Boolean).length;
const failed = outcomes.length - succeeded;
if (failed > 0) {
return false;
}
return true;
};
createNotification = async (notificationData: Partial<Notification>, userId: string, teamId: string): Promise<Notification> => {
notificationData.userId = userId;
notificationData.teamId = teamId;
return await this.notificationsRepository.create(notificationData);
};
findById = async (id: string, teamId: string): Promise<Notification> => {
return await this.notificationsRepository.findById(id, teamId);
};
findNotificationsByTeamId = async (teamId: string): Promise<Notification[]> => {
return await this.notificationsRepository.findByTeamId(teamId);
};
updateById = async (id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification> => {
return await this.notificationsRepository.updateById(id, teamId, updateData);
};
deleteById = async (id: string, teamId: string): Promise<Notification> => {
await this.monitorsRepository.removeNotificationFromMonitors(id);
const deleted = await this.notificationsRepository.deleteById(id, teamId);
return deleted;
};
}
@@ -0,0 +1,112 @@
export const NotificationChannels = [
"email",
"slack",
"discord",
"webhook",
"pager_duty",
"matrix",
"teams",
"telegram",
"pushover",
"twilio",
"ntfy",
] as const;
export type NotificationChannel = (typeof NotificationChannels)[number];
export interface Notification {
id: string;
userId: string;
teamId: string;
type: NotificationChannel;
notificationName: string;
address?: string;
phone?: string;
homeserverUrl?: string;
roomId?: string;
accessToken?: string;
accountSid?: string;
twilioPhoneNumber?: string;
topic?: string;
createdAt: string;
updatedAt: string;
}
export interface AlertPagerDutyPayload {
routing_key?: string;
dedup_key?: string;
event_action?: "trigger" | "resolve";
payload: Record<string, unknown>;
}
export interface AlertMatrixPayload {
plainText: string;
htmlText: string;
}
export interface DiscordEmbedField {
name: string;
value: string;
inline?: boolean;
}
export interface AlertDiscordPayload {
title: string;
description: string;
color: number;
fields: DiscordEmbedField[];
timestamp: string;
}
/**
* Unified notification message types for cross-provider consistency
* Part of notification system unification effort
*/
export type NotificationType = "monitor_down" | "monitor_up" | "threshold_breach" | "threshold_resolved" | "test";
export type NotificationSeverity = "critical" | "warning" | "info" | "success";
export interface MonitorInfo {
id: string;
name: string;
url: string;
type: string;
status: string;
}
export interface ThresholdBreach {
metric: "cpu" | "memory" | "disk" | "temp";
currentValue: number;
threshold: number;
unit: string;
formattedValue: string; // e.g., "85%" or "72°C"
}
export interface IncidentInfo {
id: string;
url: string;
createdAt: Date;
resolvedAt?: Date;
duration?: string;
}
export interface NotificationContent {
title: string;
summary: string;
details?: string[];
thresholds?: ThresholdBreach[];
incident?: IncidentInfo;
timestamp: Date;
}
export interface NotificationMessage {
type: NotificationType;
severity: NotificationSeverity;
monitor: MonitorInfo;
content: NotificationContent;
clientHost: string;
metadata: {
teamId: string;
notificationReason: string;
};
}
@@ -0,0 +1,30 @@
import type { Notification } from "@/domain/notifications/notification.type.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { ILogger } from "@/utils/logger.js";
import type { OptionsOfJSONResponseBody } from "got";
export const DEFAULT_NOTIFICATION_TIMEOUT_MS = 30_000;
export interface INotificationProvider {
sendMessage: (notification: Notification, message: NotificationMessage) => Promise<boolean>;
sendTestAlert(notification: Partial<Notification>): Promise<boolean>;
}
export abstract class NotificationProvider implements INotificationProvider {
protected readonly logger: ILogger;
protected readonly timeoutMs: number;
constructor(logger: ILogger, timeoutMs: number = DEFAULT_NOTIFICATION_TIMEOUT_MS) {
this.logger = logger;
this.timeoutMs = timeoutMs;
}
protected gotRequestOptions(): Pick<OptionsOfJSONResponseBody, "timeout" | "retry"> {
return {
timeout: { request: this.timeoutMs },
retry: { limit: 0 },
};
}
abstract sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean>;
abstract sendTestAlert(notification: Partial<Notification>): Promise<boolean>;
}
@@ -0,0 +1,136 @@
const SERVICE_NAME = "DiscordProvider";
import type { AlertDiscordPayload, DiscordEmbedField, Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import type { NotificationMessage, NotificationSeverity } from "@/domain/notifications/notification.type.js";
import got from "got";
export class DiscordProvider extends NotificationProvider {
sendTestAlert = async (notification: Partial<Notification>) => {
if (!notification.address) {
return false;
}
try {
await got.post(notification.address, {
json: { content: getTestMessage() },
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "Discord test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: err?.stack,
});
return false;
}
};
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address) {
this.logger.warn({
message: "Discord notification missing webhook URL",
service: SERVICE_NAME,
method: "sendMessage",
});
return false;
}
const embed = this.buildDiscordEmbed(message);
try {
await got.post(notification.address, {
json: { embeds: [embed] },
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "Discord notification failed",
service: SERVICE_NAME,
method: "sendMessage",
stack: err?.stack,
});
return false;
}
}
private buildDiscordEmbed(message: NotificationMessage): AlertDiscordPayload {
const colorMap: Record<NotificationSeverity, number> = {
critical: 0xdc2626, // red-600
warning: 0xf59e0b, // amber-500
info: 0x3b82f6, // blue-500
success: 0x10b981, // green-500
};
const color = colorMap[message.severity] ?? colorMap.info;
const fields: Array<DiscordEmbedField> = [];
// Add monitor details
fields.push({
name: "Monitor",
value: message.monitor.name,
inline: true,
});
fields.push({
name: "Type",
value: message.monitor.type.toUpperCase(),
inline: true,
});
fields.push({
name: "Status",
value: message.monitor.status.charAt(0).toUpperCase() + message.monitor.status.slice(1),
inline: true,
});
// Add monitor URL
fields.push({
name: "URL",
value: message.monitor.url,
inline: false,
});
// Add threshold breaches if present
if (message.content.thresholds && message.content.thresholds.length > 0) {
const thresholdLines = message.content.thresholds
.map((t) => `• **${t.metric.toUpperCase()}**: ${t.formattedValue} (threshold: ${t.threshold}${t.unit})`)
.join("\n");
fields.push({
name: "Threshold Breaches",
value: thresholdLines,
inline: false,
});
}
// Add details if present
if (message.content.details && message.content.details.length > 0) {
const detailsText = message.content.details.join("\n");
fields.push({
name: "Details",
value: detailsText,
inline: false,
});
}
return {
title: message.content.title,
description: message.content.summary,
color,
fields,
timestamp: message.content.timestamp.toISOString(),
};
}
}
@@ -0,0 +1,129 @@
const SERVICE_NAME = "EmailProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import { buildTestEmail } from "@/domain/notifications/providers/utils.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import type { ILogger } from "@/utils/logger.js";
import { IEmailService } from "@/service/emailService.js";
export class EmailProvider extends NotificationProvider {
private emailService: IEmailService;
constructor(emailService: IEmailService, logger: ILogger) {
super(logger);
this.emailService = emailService;
}
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
const subject = "Test notification";
const html = await buildTestEmail(this.emailService);
if (!notification.address) {
this.logger.warn({
message: "Missing address",
service: SERVICE_NAME,
method: "sendTestAlert",
});
return false;
}
if (!html) {
this.logger.warn({
message: "Failed to build test email content",
service: SERVICE_NAME,
method: "sendTestAlert",
});
return false;
}
const messageId = await this.emailService.sendEmail(notification.address, subject, html);
if (!messageId) {
this.logger.warn({
message: "Email test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
});
return false;
}
return true;
}
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address) {
return false;
}
const subject = this.buildSubject(message);
const html = await this.buildEmailFromMessage(message);
if (!html) {
this.logger.warn({
message: "Failed to build email content",
service: SERVICE_NAME,
method: "sendMessage",
});
return false;
}
const messageId = await this.emailService.sendEmail(notification.address, subject, html);
if (!messageId) {
this.logger.warn({
message: "Email notification failed",
service: SERVICE_NAME,
method: "sendMessage",
});
return false;
}
return true;
}
private buildSubject(message: NotificationMessage): string {
switch (message.type) {
case "monitor_down":
return `Monitor ${message.monitor.name} is down`;
case "monitor_up":
return `Monitor ${message.monitor.name} is back up`;
case "threshold_breach":
return `Monitor ${message.monitor.name} threshold exceeded`;
case "threshold_resolved":
return `Monitor ${message.monitor.name} thresholds resolved`;
default:
return `Alert: ${message.monitor.name}`;
}
}
private async buildEmailFromMessage(message: NotificationMessage): Promise<string | undefined> {
const context = {
title: message.content.title,
summary: message.content.summary,
monitorName: message.monitor.name,
monitorUrl: message.monitor.url,
monitorType: message.monitor.type,
monitorStatus: message.monitor.status,
headerColor: this.getColorForSeverity(message.severity),
thresholds: message.content.thresholds,
details: message.content.details,
incidentUrl: message.content.incident?.url,
};
this.logger.info({
message: "[DEBUG] Building email from message",
service: SERVICE_NAME,
method: "buildEmailFromMessage",
details: { context },
});
const html = await this.emailService.buildEmail("unifiedNotificationTemplate", context);
return html;
}
private getColorForSeverity(severity: string): string {
const colorMap: Record<string, string> = {
critical: "red",
warning: "#f59e0b",
info: "#3b82f6",
success: "green",
};
return colorMap[severity] ?? "#3b82f6";
}
}
@@ -0,0 +1,167 @@
const SERVICE_NAME = "MatrixProvider";
import got from "got";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { AlertMatrixPayload, Notification } from "@/domain/notifications/notification.type.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import { randomUUID } from "crypto";
export class MatrixProvider extends NotificationProvider {
sendTestAlert = async (notification: Partial<Notification>) => {
const { homeserverUrl, accessToken, roomId } = notification;
if (!homeserverUrl || !accessToken || !roomId) {
return false;
}
const body = {
msgtype: "m.text",
body: getTestMessage(),
};
return await this.sendMessageWithBody(notification, body);
};
sendMessage = async (notification: Notification, message: NotificationMessage): Promise<boolean> => {
const { homeserverUrl, accessToken, roomId } = notification;
if (!homeserverUrl || !accessToken || !roomId) {
return false;
}
const { plainText, htmlText } = this.buildMatrixMessage(message);
const body = {
msgtype: "m.text",
body: plainText,
format: "org.matrix.custom.html",
formatted_body: htmlText,
};
return this.sendMessageWithBody(notification, body);
};
private sendMessageWithBody = async (notification: Partial<Notification>, body: unknown): Promise<boolean> => {
const { homeserverUrl, accessToken, roomId } = notification;
const txnId = randomUUID();
const url = `${homeserverUrl}/_matrix/client/v3/rooms/${roomId}/send/m.room.message/${txnId}`;
try {
await got.put(url, {
json: body,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: `Matrix notification failed : ${err.message}`,
service: SERVICE_NAME,
method: "sendMessage",
stack: err.stack,
});
return false;
}
};
/**
* Build Matrix message from NotificationMessage
* Returns both plain text and HTML formatted versions
* Matrix supports HTML subset for rich formatting
*/
private buildMatrixMessage(message: NotificationMessage): AlertMatrixPayload {
const plainLines: string[] = [];
const htmlLines: string[] = [];
// Determine color based on severity
const colorMap = {
critical: "#FF0000", // Red
warning: "#FFA500", // Orange
success: "#00FF00", // Green
info: "#0000FF", // Blue
};
const color = colorMap[message.severity] || "#808080";
// Title
plainLines.push(`# ${message.content.title}`);
htmlLines.push(`<h2 style="color: ${color};">${this.escapeHtml(message.content.title)}</h2>`);
// Summary
plainLines.push("");
plainLines.push(message.content.summary);
htmlLines.push(`<p>${this.escapeHtml(message.content.summary)}</p>`);
// Monitor details
plainLines.push("");
plainLines.push("## Monitor Details");
plainLines.push(`- Name: ${message.monitor.name}`);
plainLines.push(`- URL: ${message.monitor.url}`);
plainLines.push(`- Type: ${message.monitor.type}`);
plainLines.push(`- Status: ${message.monitor.status}`);
htmlLines.push(`<h3>Monitor Details</h3>`);
htmlLines.push(`<ul>`);
htmlLines.push(`<li><strong>Name:</strong> ${this.escapeHtml(message.monitor.name)}</li>`);
htmlLines.push(`<li><strong>URL:</strong> <a href="${this.escapeHtml(message.monitor.url)}">${this.escapeHtml(message.monitor.url)}</a></li>`);
htmlLines.push(`<li><strong>Type:</strong> ${this.escapeHtml(message.monitor.type)}</li>`);
htmlLines.push(`<li><strong>Status:</strong> ${this.escapeHtml(message.monitor.status)}</li>`);
htmlLines.push(`</ul>`);
// Threshold breaches (if any)
if (message.content.thresholds && message.content.thresholds.length > 0) {
plainLines.push("");
plainLines.push("## Threshold Breaches");
htmlLines.push(`<h3>Threshold Breaches</h3>`);
htmlLines.push(`<ul>`);
message.content.thresholds.forEach((breach) => {
plainLines.push(`- ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
htmlLines.push(
`<li><strong>${this.escapeHtml(breach.metric.toUpperCase())}:</strong> ${this.escapeHtml(breach.formattedValue)} (threshold: ${breach.threshold}${this.escapeHtml(breach.unit)})</li>`
);
});
htmlLines.push(`</ul>`);
}
// Additional details (if any)
if (message.content.details && message.content.details.length > 0) {
plainLines.push("");
plainLines.push("## Additional Information");
htmlLines.push(`<h3>Additional Information</h3>`);
htmlLines.push(`<ul>`);
message.content.details.forEach((detail) => {
plainLines.push(`- ${detail}`);
htmlLines.push(`<li>${this.escapeHtml(detail)}</li>`);
});
htmlLines.push(`</ul>`);
}
// Incident link (if incident exists)
if (message.content.incident) {
const incidentUrl = `${message.clientHost}/infrastructure/${message.monitor.id}`;
plainLines.push("");
plainLines.push(`View Incident: ${incidentUrl}`);
htmlLines.push(`<p><a href="${this.escapeHtml(incidentUrl)}">View Incident</a></p>`);
}
// Footer with timestamp
plainLines.push("");
plainLines.push(`Checkmate | ${new Date(message.content.timestamp).toUTCString()}`);
htmlLines.push(`<hr>`);
htmlLines.push(`<p><small>Checkmate | ${new Date(message.content.timestamp).toUTCString()}</small></p>`);
return {
plainText: plainLines.join("\n"),
htmlText: htmlLines.join(""),
};
}
/**
* Escape HTML special characters for safe rendering
*/
private escapeHtml(text: string): string {
return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}
}
@@ -0,0 +1,128 @@
const SERVICE_NAME = "NtfyProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import got from "got";
export class NtfyProvider extends NotificationProvider {
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
if (!notification.address || !notification.topic) {
return false;
}
try {
await got.post(this.buildTopicUrl(notification.address, notification.topic), {
body: getTestMessage(),
headers: {
Title: "Checkmate test notification",
Priority: "default",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "ntfy test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: err?.stack,
});
return false;
}
}
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address || !notification.topic) {
return false;
}
try {
await got.post(this.buildTopicUrl(notification.address, notification.topic), {
body: this.buildNtfyText(message),
headers: {
Title: message.content.title,
Priority: this.mapPriority(message.severity),
Tags: this.mapTags(message.severity),
},
...this.gotRequestOptions(),
});
this.logger.info({
message: "ntfy notification sent",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "ntfy alert failed",
service: SERVICE_NAME,
method: "sendMessage",
stack: err?.stack,
});
return false;
}
}
private buildTopicUrl(address: string, topic: string): string {
return `${address.replace(/\/+$/, "")}/${encodeURIComponent(topic)}`;
}
private buildNtfyText(message: NotificationMessage): string {
const lines = [
message.content.summary,
"",
"Monitor Details:",
`- Name: ${message.monitor.name}`,
`- URL: ${message.monitor.url}`,
`- Type: ${message.monitor.type}`,
`- Status: ${message.monitor.status}`,
];
if (message.content.details && message.content.details.length > 0) {
lines.push("", "Additional Information:");
message.content.details.forEach((detail) => lines.push(`- ${detail}`));
}
if (message.content.thresholds && message.content.thresholds.length > 0) {
lines.push("", "Threshold Breaches:");
message.content.thresholds.forEach((breach) => {
lines.push(`- ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
});
}
if (message.content.incident) {
lines.push("", `${message.clientHost}/infrastructure/${message.monitor.id}`);
}
return lines.join("\n");
}
private mapPriority(severity: NotificationMessage["severity"]): string {
switch (severity) {
case "critical":
return "high";
case "warning":
return "default";
case "success":
return "low";
default:
return "default";
}
}
private mapTags(severity: NotificationMessage["severity"]): string {
switch (severity) {
case "critical":
return "rotating_light";
case "warning":
return "warning";
case "success":
return "white_check_mark";
default:
return "information_source";
}
}
}
@@ -0,0 +1,138 @@
const SERVICE_NAME = "PagerDutyProvider";
import got from "got";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import { AlertPagerDutyPayload } from "@/domain/notifications/notification.type.js";
export class PagerDutyProvider extends NotificationProvider {
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
try {
await got.post("https://events.pagerduty.com/v2/enqueue", {
json: {
routing_key: notification.address,
event_action: "trigger",
payload: {
summary: getTestMessage(),
severity: "info",
source: "checkmate",
timestamp: new Date().toISOString(),
},
},
responseType: "json",
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "PagerDuty test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: err?.stack,
});
return false;
}
}
/**
* New unified message format implementation
*/
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address) {
this.logger.warn({
message: "PagerDuty notification missing routing key",
service: SERVICE_NAME,
method: "sendMessage",
});
return false;
}
try {
const payload = this.buildPagerDutyPayload(notification, message);
await got.post("https://events.pagerduty.com/v2/enqueue", {
json: payload,
...this.gotRequestOptions(),
});
this.logger.info({
message: "[NEW] PagerDuty notification sent via sendMessage",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "PagerDuty notification failed",
service: SERVICE_NAME,
method: "sendMessage",
stack: err?.stack,
});
return false;
}
}
private buildPagerDutyPayload(notification: Notification, message: NotificationMessage): AlertPagerDutyPayload {
// Map our notification type to PagerDuty event_action
const eventAction = message.type === "monitor_up" || message.type === "threshold_resolved" ? "resolve" : "trigger";
// Map severity to PagerDuty severity levels
const severityMap: Record<string, string> = {
critical: "critical",
warning: "warning",
info: "info",
success: "info",
};
const severity = severityMap[message.severity] || "error";
// Build deduplication key based on monitor ID for event grouping
const dedupKey = `checkmate-${message.monitor.id}`;
// Build summary
let summary = `${message.content.title} - ${message.content.summary}`;
// Add threshold details to summary if present
if (message.content.thresholds && message.content.thresholds.length > 0) {
const thresholdInfo = message.content.thresholds
.map((t) => `${t.metric.toUpperCase()}: ${t.formattedValue}/${t.threshold}${t.unit}`)
.join(", ");
summary += ` [${thresholdInfo}]`;
}
// Build custom details
const customDetails: Record<string, unknown> = {
monitor_name: message.monitor.name,
monitor_url: message.monitor.url,
monitor_type: message.monitor.type,
monitor_status: message.monitor.status,
notification_type: message.type,
};
if (message.content.thresholds && message.content.thresholds.length > 0) {
customDetails.threshold_breaches = message.content.thresholds.map((t) => ({
metric: t.metric,
current: t.formattedValue,
threshold: `${t.threshold}${t.unit}`,
}));
}
if (message.content.details && message.content.details.length > 0) {
customDetails.details = message.content.details;
}
return {
routing_key: notification.address,
dedup_key: dedupKey,
event_action: eventAction,
payload: {
summary,
severity,
source: message.monitor.url,
timestamp: message.content.timestamp.toISOString(),
custom_details: customDetails,
},
};
}
}
@@ -0,0 +1,109 @@
const SERVICE_NAME = "PushoverProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import got from "got";
export class PushoverProvider extends NotificationProvider {
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
if (!notification.address || !notification.accessToken) {
return false;
}
try {
await got.post("https://api.pushover.net/1/messages.json", {
form: {
token: notification.accessToken,
user: notification.address,
message: getTestMessage(),
title: "Checkmate Test Notification",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const errMsg = error instanceof Error ? error.message : "unknown error";
const errStack = error instanceof Error ? error.stack : undefined;
this.logger.warn({
message: "Pushover test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: errStack,
details: { error: errMsg },
});
return false;
}
}
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address || !notification.accessToken) {
return false;
}
const text = this.buildPushoverText(message);
try {
await got.post("https://api.pushover.net/1/messages.json", {
form: {
token: notification.accessToken,
user: notification.address,
message: text,
title: message.content.title,
},
...this.gotRequestOptions(),
});
this.logger.info({
message: "Pushover notification sent",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const errMsg = error instanceof Error ? error.message : "unknown error";
const errStack = error instanceof Error ? error.stack : undefined;
this.logger.warn({
message: "Pushover alert failed",
service: SERVICE_NAME,
method: "sendMessage",
stack: errStack,
details: { error: errMsg },
});
return false;
}
}
private buildPushoverText(message: NotificationMessage): string {
const lines: string[] = [];
lines.push(message.content.summary);
lines.push("");
lines.push("Monitor Details:");
lines.push(`• Name: ${message.monitor.name}`);
lines.push(`• URL: ${message.monitor.url}`);
lines.push(`• Type: ${message.monitor.type}`);
lines.push(`• Status: ${message.monitor.status}`);
if (message.content.details && message.content.details.length > 0) {
lines.push("");
lines.push("Additional Information:");
message.content.details.forEach((detail) => lines.push(`• ${detail}`));
}
if (message.content.thresholds && message.content.thresholds.length > 0) {
lines.push("");
lines.push("Threshold Breaches:");
message.content.thresholds.forEach((breach) => {
lines.push(`• ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
});
}
if (message.content.incident) {
lines.push("");
lines.push(`View Incident: ${message.clientHost}/incidents/${message.monitor.id}`);
}
return lines.join("\n");
}
}
@@ -0,0 +1,193 @@
const SERVICE_NAME = "SlackProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import got, { HTTPError } from "got";
export class SlackProvider extends NotificationProvider {
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
if (!notification.address) {
return false;
}
try {
await got.post(notification.address, {
json: { text: getTestMessage() },
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as HTTPError;
this.logger.warn({
message: "Slack test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: err?.stack,
});
return false;
}
}
/**
* New unified message format - builds Slack Block Kit payload from NotificationMessage
*/
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address) {
return false;
}
const payload = this.buildSlackPayload(message);
try {
await got.post(notification.address, {
json: payload,
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
this.logger.info({
message: "[NEW] Slack notification sent via sendMessage",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "[NEW] Slack alert failed via sendMessage",
service: SERVICE_NAME,
method: "sendMessage",
stack: err?.stack,
});
return false;
}
}
/**
* Build Slack Block Kit payload from NotificationMessage
* Uses Slack's rich formatting with sections, fields, and context blocks
*/
private buildSlackPayload(message: NotificationMessage): object {
const blocks: unknown[] = [];
// Determine color based on severity
const colorMap = {
critical: "#FF0000", // Red
warning: "#FFA500", // Orange
success: "#00FF00", // Green
info: "#0000FF", // Blue
};
const color = colorMap[message.severity] || "#808080";
// Header block with title
blocks.push({
type: "header",
text: {
type: "plain_text",
text: message.content.title,
emoji: true,
},
});
// Summary section
blocks.push({
type: "section",
text: {
type: "mrkdwn",
text: message.content.summary,
},
});
// Monitor details as fields
const monitorFields = [
{ type: "mrkdwn", text: `*Name:*\n${message.monitor.name}` },
{ type: "mrkdwn", text: `*Type:*\n${message.monitor.type}` },
{ type: "mrkdwn", text: `*Status:*\n${message.monitor.status}` },
{ type: "mrkdwn", text: `*URL:*\n${message.monitor.url}` },
];
blocks.push({
type: "section",
fields: monitorFields,
});
// Divider
blocks.push({ type: "divider" });
// Threshold breaches (if any)
if (message.content.thresholds && message.content.thresholds.length > 0) {
const thresholdText = message.content.thresholds
.map((breach) => `• *${breach.metric.toUpperCase()}:* ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`)
.join("\n");
blocks.push({
type: "section",
text: {
type: "mrkdwn",
text: `*Threshold Breaches:*\n${thresholdText}`,
},
});
blocks.push({ type: "divider" });
}
// Additional details (if any)
if (message.content.details && message.content.details.length > 0) {
const detailsText = message.content.details.map((detail) => `• ${detail}`).join("\n");
blocks.push({
type: "section",
text: {
type: "mrkdwn",
text: `*Additional Information:*\n${detailsText}`,
},
});
}
// Incident link button (if incident exists)
if (message.content.incident) {
blocks.push({
type: "actions",
elements: [
{
type: "button",
text: {
type: "plain_text",
text: "View Incident",
emoji: true,
},
url: `${message.clientHost}/infrastructure/${message.monitor.id}`,
style: "primary",
},
],
});
}
// Context footer with timestamp
blocks.push({
type: "context",
elements: [
{
type: "mrkdwn",
text: `Checkmate | ${new Date(message.content.timestamp).toUTCString()}`,
},
],
});
// Return Slack payload with blocks and attachment color
return {
blocks,
attachments: [
{
color,
blocks: [], // Empty blocks in attachment for color bar
},
],
};
}
}
@@ -0,0 +1,269 @@
const SERVICE_NAME = "TeamsProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import got, { HTTPError } from "got";
// Types for Adaptive Card elements
type TextBlock = {
type: "TextBlock";
text: string;
weight?: "Bolder" | "Normal" | "Lighter";
size?: "Small" | "Medium" | "Large" | "ExtraLarge";
color?: "Default" | "Dark" | "Light" | "Accent" | "Good" | "Warning" | "Attention";
wrap?: boolean;
spacing?: "None" | "Small" | "Medium" | "Large" | "ExtraLarge" | "Auto";
isSubtle?: boolean;
};
type ColumnSet = {
type: "ColumnSet";
separator?: boolean;
spacing?: "None" | "Small" | "Medium" | "Large" | "ExtraLarge" | "Auto";
columns: unknown[];
};
type Fact = {
title: string;
value: string;
};
type FactSet = {
type: "FactSet";
facts: Fact[];
};
type Action = {
type: string;
title: string;
url?: string;
};
type AdaptiveCard = {
type: "AdaptiveCard";
$schema: "http://adaptivecards.io/schemas/adaptive-card.json";
version: "1.4";
body: (TextBlock | ColumnSet | FactSet)[];
actions?: Action[];
};
type TeamsMessage = {
type: "message";
attachments: Array<{
contentType: "application/vnd.microsoft.card.adaptive";
contentUrl: null;
content: AdaptiveCard;
}>;
};
export class TeamsProvider extends NotificationProvider {
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
if (!notification.address) {
return false;
}
try {
const payload = this.wrapAdaptiveCard({
type: "AdaptiveCard",
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
version: "1.4",
body: [
{
type: "TextBlock",
text: getTestMessage(),
weight: "Bolder",
size: "Medium",
},
],
});
await got.post(notification.address, {
json: payload,
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as HTTPError;
this.logger.warn({
message: "Teams test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: err?.stack,
});
return false;
}
}
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address) {
return false;
}
const payload = this.wrapAdaptiveCard(this.buildAdaptiveCard(message));
try {
await got.post(notification.address, {
json: payload,
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
this.logger.info({
message: "Teams notification sent via sendMessage",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const err = error as HTTPError;
this.logger.warn({
message: "Teams alert failed via sendMessage",
service: SERVICE_NAME,
method: "sendMessage",
stack: err?.stack,
});
return false;
}
}
/**
* Wrap an Adaptive Card in the Teams webhook envelope format
*/
private wrapAdaptiveCard(card: AdaptiveCard): TeamsMessage {
return {
type: "message",
attachments: [
{
contentType: "application/vnd.microsoft.card.adaptive",
contentUrl: null,
content: card,
},
],
};
}
/**
* Build an Adaptive Card from NotificationMessage
*/
private buildAdaptiveCard(message: NotificationMessage): AdaptiveCard {
const colorMap: Record<string, string> = {
critical: "attention",
warning: "warning",
success: "good",
info: "accent",
};
const color = (colorMap[message.severity] || "default") as "Default" | "Dark" | "Light" | "Accent" | "Good" | "Warning" | "Attention" | undefined;
const body: (TextBlock | ColumnSet | FactSet)[] = [];
// Header with colored status indicator
body.push({
type: "TextBlock",
text: message.content.title,
weight: "Bolder",
size: "Large",
color,
wrap: true,
});
// Summary
body.push({
type: "TextBlock",
text: message.content.summary,
wrap: true,
spacing: "Small",
});
// Separator
body.push({
type: "ColumnSet",
separator: true,
spacing: "Medium",
columns: [],
});
// Monitor details as a FactSet
body.push({
type: "FactSet",
facts: [
{ title: "Name", value: message.monitor.name },
{ title: "Type", value: message.monitor.type },
{ title: "Status", value: message.monitor.status },
{ title: "URL", value: message.monitor.url },
],
});
// Threshold breaches
if (message.content.thresholds && message.content.thresholds.length > 0) {
body.push({
type: "TextBlock",
text: "**Threshold Breaches**",
weight: "Bolder",
spacing: "Medium",
wrap: true,
});
for (const breach of message.content.thresholds) {
body.push({
type: "TextBlock",
text: `• **${breach.metric.toUpperCase()}**: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`,
wrap: true,
spacing: "Small",
});
}
}
// Additional details
if (message.content.details && message.content.details.length > 0) {
body.push({
type: "TextBlock",
text: "**Additional Information**",
weight: "Bolder",
spacing: "Medium",
wrap: true,
});
for (const detail of message.content.details) {
body.push({
type: "TextBlock",
text: `• ${detail}`,
wrap: true,
spacing: "Small",
});
}
}
// Timestamp footer
body.push({
type: "TextBlock",
text: `Checkmate | ${new Date(message.content.timestamp).toUTCString()}`,
size: "Small",
isSubtle: true,
spacing: "Medium",
wrap: true,
});
// Actions (incident link)
const actions: Action[] = [];
if (message.content.incident) {
actions.push({
type: "Action.OpenUrl",
title: "View Incident",
url: `${message.clientHost}/incidents/${message.content.incident.id}`,
});
}
return {
type: "AdaptiveCard",
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
version: "1.4",
body,
...(actions.length > 0 ? { actions } : {}),
};
}
}
@@ -0,0 +1,109 @@
const SERVICE_NAME = "TelegramProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import got from "got";
export class TelegramProvider extends NotificationProvider {
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
if (!notification.address || !notification.accessToken) {
return false;
}
try {
await got.post(`https://api.telegram.org/bot${notification.accessToken}/sendMessage`, {
json: {
chat_id: notification.address,
text: getTestMessage(),
parse_mode: "HTML",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const errMsg = error instanceof Error ? error.message : "unknown error";
const errStack = error instanceof Error ? error.stack : undefined;
this.logger.warn({
message: "Telegram test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: errStack,
details: { error: errMsg },
});
return false;
}
}
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.address || !notification.accessToken) {
return false;
}
const text = this.buildTelegramText(message);
try {
await got.post(`https://api.telegram.org/bot${notification.accessToken}/sendMessage`, {
json: {
chat_id: notification.address,
text,
parse_mode: "HTML",
},
...this.gotRequestOptions(),
});
this.logger.info({
message: "Telegram notification sent",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const errMsg = error instanceof Error ? error.message : "unknown error";
const errStack = error instanceof Error ? error.stack : undefined;
this.logger.warn({
message: "Telegram alert failed",
service: SERVICE_NAME,
method: "sendMessage",
stack: errStack,
details: { error: errMsg },
});
return false;
}
}
private buildTelegramText(message: NotificationMessage): string {
const lines: string[] = [];
lines.push(`<b>${message.content.title}</b>`);
lines.push(message.content.summary);
lines.push("");
lines.push("<b>Monitor Details:</b>");
lines.push(`• Name: ${message.monitor.name}`);
lines.push(`• URL: ${message.monitor.url}`);
lines.push(`• Type: ${message.monitor.type}`);
lines.push(`• Status: ${message.monitor.status}`);
if (message.content.details && message.content.details.length > 0) {
lines.push("");
lines.push("<b>Additional Information:</b>");
message.content.details.forEach((detail) => lines.push(`• ${detail}`));
}
if (message.content.thresholds && message.content.thresholds.length > 0) {
lines.push("");
lines.push("<b>Threshold Breaches:</b>");
message.content.thresholds.forEach((breach) => {
lines.push(`• ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
});
}
if (message.content.incident) {
lines.push("");
lines.push(`<a href="${message.clientHost}/incidents/${message.monitor.id}">View Incident</a>`);
}
return lines.join("\n");
}
}
@@ -0,0 +1,96 @@
const SERVICE_NAME = "TwilioProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import got from "got";
export class TwilioProvider extends NotificationProvider {
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
if (!notification.accountSid || !notification.accessToken || !notification.phone || !notification.twilioPhoneNumber) {
return false;
}
try {
await got.post(`https://api.twilio.com/2010-04-01/Accounts/${notification.accountSid}/Messages.json`, {
form: {
To: notification.phone,
From: notification.twilioPhoneNumber,
Body: getTestMessage(),
},
username: notification.accountSid,
password: notification.accessToken,
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const errMsg = error instanceof Error ? error.message : "unknown error";
const errStack = error instanceof Error ? error.stack : undefined;
this.logger.warn({
message: "Twilio test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: errStack,
details: { error: errMsg },
});
return false;
}
}
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
if (!notification.accountSid || !notification.accessToken || !notification.phone || !notification.twilioPhoneNumber) {
return false;
}
const text = this.buildSmsText(message);
try {
await got.post(`https://api.twilio.com/2010-04-01/Accounts/${notification.accountSid}/Messages.json`, {
form: {
To: notification.phone,
From: notification.twilioPhoneNumber,
Body: text,
},
username: notification.accountSid,
password: notification.accessToken,
...this.gotRequestOptions(),
});
this.logger.info({
message: "Twilio SMS notification sent",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const errMsg = error instanceof Error ? error.message : "unknown error";
const errStack = error instanceof Error ? error.stack : undefined;
this.logger.warn({
message: "Twilio SMS alert failed",
service: SERVICE_NAME,
method: "sendMessage",
stack: errStack,
details: { error: errMsg },
});
return false;
}
}
private buildSmsText(message: NotificationMessage): string {
const lines: string[] = [];
lines.push(message.content.title);
lines.push(message.content.summary);
lines.push("");
lines.push(`URL: ${message.monitor.url}`);
lines.push(`Status: ${message.monitor.status}`);
if (message.content.thresholds && message.content.thresholds.length > 0) {
message.content.thresholds.forEach((breach) => {
lines.push(`${breach.metric.toUpperCase()}: ${breach.formattedValue}`);
});
}
return lines.join("\n");
}
}
@@ -0,0 +1,10 @@
import { IEmailService } from "@/service/emailService.js";
export const buildTestEmail = async (emailService: IEmailService) => {
const context = { testName: "Monitoring System" };
const html = await emailService.buildEmail("testEmailTemplate", context);
return html;
};
export const getTestMessage = () => {
return "This is a test notification from Checkmate";
};
@@ -0,0 +1,119 @@
const SERVICE_NAME = "WebhookProvider";
import type { Notification } from "@/domain/notifications/notification.type.js";
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
import got from "got";
export class WebhookProvider extends NotificationProvider {
sendMessage = async (notification: Notification, message: NotificationMessage): Promise<boolean> => {
if (!notification.address) {
return false;
}
// Build webhook payload from unified message
const payload = this.buildWebhookPayload(message);
try {
await got.post(notification.address, {
json: payload,
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
this.logger.info({
message: "Webhook notification sent",
service: SERVICE_NAME,
method: "sendMessage",
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "Webhook alert failed",
service: SERVICE_NAME,
method: "sendMessage",
stack: err?.stack,
});
return false;
}
};
private buildWebhookPayload(message: NotificationMessage): object {
const lines: string[] = [];
// Title and summary
lines.push(`**${message.content.title}**`);
lines.push(message.content.summary);
lines.push("");
// Monitor information
lines.push("**Monitor Details:**");
lines.push(`- Name: ${message.monitor.name}`);
lines.push(`- URL: ${message.monitor.url}`);
lines.push(`- Type: ${message.monitor.type}`);
lines.push(`- Status: ${message.monitor.status}`);
lines.push("");
// Additional details
if (message.content.details && message.content.details.length > 0) {
lines.push("**Additional Information:**");
message.content.details.forEach((detail) => lines.push(`- ${detail}`));
lines.push("");
}
// Threshold breaches (for hardware monitors)
if (message.content.thresholds && message.content.thresholds.length > 0) {
lines.push("**Threshold Breaches:**");
message.content.thresholds.forEach((breach) => {
lines.push(`- ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
});
lines.push("");
}
// Incident link
if (message.content.incident) {
lines.push(`[View Incident](${message.clientHost}/infrastructure/${message.monitor.id})`);
}
// Return webhook payload with both text and structured data
return {
text: lines.join("\n"),
severity: message.severity,
type: message.type,
monitor: {
id: message.monitor.id,
name: message.monitor.name,
url: message.monitor.url,
status: message.monitor.status,
},
timestamp: message.content.timestamp,
};
}
sendTestAlert = async (notification: Partial<Notification>) => {
if (!notification.address) {
return false;
}
try {
await got.post(notification.address, {
json: { text: getTestMessage() },
headers: {
"Content-Type": "application/json",
},
...this.gotRequestOptions(),
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: "Webhook test alert failed",
service: SERVICE_NAME,
method: "sendTestAlert",
stack: err?.stack,
});
return false;
}
};
}