Files
Checkmate/server/src/service/infrastructure/notificationProviders/matrix.ts
T

167 lines
5.7 KiB
TypeScript
Raw Normal View History

2026-01-19 22:16:33 +00:00
const SERVICE_NAME = "MatrixProvider";
2026-01-19 21:39:02 +00:00
import got from "got";
2026-04-13 12:55:20 -07:00
import { NotificationProvider } from "@/service/index.js";
2026-03-04 17:32:50 +00:00
import type { AlertMatrixPayload, Notification } from "@/types/index.js";
2026-02-16 21:49:42 +00:00
import type { NotificationMessage } from "@/types/notificationMessage.js";
2026-02-17 17:28:43 +00:00
import { getTestMessage } from "@/service/infrastructure/notificationProviders/utils.js";
import { randomUUID } from "crypto";
2026-01-19 21:39:02 +00:00
2026-04-13 12:55:20 -07:00
export class MatrixProvider extends NotificationProvider {
2026-03-11 13:40:35 -07:00
sendTestAlert = async (notification: Partial<Notification>) => {
2026-01-19 21:58:48 +00:00
const { homeserverUrl, accessToken, roomId } = notification;
if (!homeserverUrl || !accessToken || !roomId) {
return false;
}
2026-01-19 21:58:48 +00:00
const body = {
msgtype: "m.text",
body: getTestMessage(),
};
return await this.sendMessageWithBody(notification, body);
2026-01-19 21:39:02 +00:00
};
2026-02-16 21:49:42 +00:00
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}`;
2026-02-16 21:49:42 +00:00
try {
await got.put(url, {
2026-02-16 21:49:42 +00:00
json: body,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
2026-02-16 21:49:42 +00:00
},
2026-04-13 12:55:20 -07:00
...this.gotRequestOptions(),
2026-02-16 21:49:42 +00:00
});
return true;
} catch (error) {
const err = error as Error;
this.logger.warn({
message: `Matrix notification failed : ${err.message}`,
2026-02-16 21:49:42 +00:00
service: SERVICE_NAME,
method: "sendMessage",
2026-04-09 11:05:21 -07:00
stack: err.stack,
2026-02-16 21:49:42 +00:00
});
return false;
}
};
/**
* Build Matrix message from NotificationMessage
* Returns both plain text and HTML formatted versions
* Matrix supports HTML subset for rich formatting
*/
2026-03-04 17:32:50 +00:00
private buildMatrixMessage(message: NotificationMessage): AlertMatrixPayload {
2026-02-16 21:49:42 +00:00
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;");
}
2026-01-19 21:39:02 +00:00
}