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,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;
}
};
}