repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/goalert.js
server/notification-providers/goalert.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP } = require("../../src/util"); class GoAlert extends NotificationProvider { name = "GoAlert"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let data = { summary: msg, }; if (heartbeatJSON != null && heartbeatJSON["status"] === UP) { data["action"] = "close"; } let headers = { "Content-Type": "multipart/form-data", }; let config = { headers: headers }; config = this.getAxiosConfigWithProxy(config); await axios.post(`${notification.goAlertBaseURL}/api/v2/generic/incoming?token=${notification.goAlertToken}`, data, config); return okMsg; } catch (error) { let msg = (error.response.data) ? error.response.data : "Error without response"; throw new Error(msg); } } } module.exports = GoAlert;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pagerduty.js
server/notification-providers/pagerduty.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util"); const { setting } = require("../util-server"); let successMessage = "Sent Successfully."; class PagerDuty extends NotificationProvider { name = "PagerDuty"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { try { if (heartbeatJSON == null) { const title = "Uptime Kuma Alert"; const monitor = { type: "ping", url: "Uptime Kuma Test Button", }; return this.postNotification(notification, title, msg, monitor); } if (heartbeatJSON.status === UP) { const title = "Uptime Kuma Monitor βœ… Up"; return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, "resolve"); } if (heartbeatJSON.status === DOWN) { const title = "Uptime Kuma Monitor πŸ”΄ Down"; return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, "trigger"); } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Check if result is successful, result code should be in range 2xx * @param {object} result Axios response object * @returns {void} * @throws {Error} The status code is not in range 2xx */ checkResult(result) { if (result.status == null) { throw new Error("PagerDuty notification failed with invalid response!"); } if (result.status < 200 || result.status >= 300) { throw new Error("PagerDuty notification failed with status code " + result.status); } } /** * Send the message * @param {BeanModel} notification Message title * @param {string} title Message title * @param {string} body Message * @param {object} monitorInfo Monitor details (For Up/Down only) * @param {?string} eventAction Action event for PagerDuty (trigger, acknowledge, resolve) * @returns {Promise<string>} Success message */ async postNotification(notification, title, body, monitorInfo, eventAction = "trigger") { let monitorUrl; if (monitorInfo.type === "port") { monitorUrl = monitorInfo.hostname; if (monitorInfo.port) { monitorUrl += ":" + monitorInfo.port; } } else if (monitorInfo.hostname != null) { monitorUrl = monitorInfo.hostname; } else { monitorUrl = monitorInfo.url; } if (eventAction === "resolve") { if (notification.pagerdutyAutoResolve === "0") { return "no action required"; } eventAction = notification.pagerdutyAutoResolve; } const options = { method: "POST", url: notification.pagerdutyIntegrationUrl, headers: { "Content-Type": "application/json" }, data: { payload: { summary: `[${title}] [${monitorInfo.name}] ${body}`, severity: notification.pagerdutyPriority || "warning", source: monitorUrl, }, routing_key: notification.pagerdutyIntegrationKey, event_action: eventAction, dedup_key: "Uptime Kuma/" + monitorInfo.id, } }; const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorInfo) { options.client = "Uptime Kuma"; options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id); } let result = await axios.request(options); this.checkResult(result); if (result.statusText != null) { return "PagerDuty notification succeed: " + result.statusText; } return successMessage; } } module.exports = PagerDuty;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/discord.js
server/notification-providers/discord.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class Discord extends NotificationProvider { name = "discord"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); const discordDisplayName = notification.discordUsername || "Uptime Kuma"; const webhookUrl = new URL(notification.discordWebhookUrl); if (notification.discordChannelType === "postToThread") { webhookUrl.searchParams.append("thread_id", notification.threadId); } // Check if the webhook has an avatar let webhookHasAvatar = true; try { const webhookInfo = await axios.get(webhookUrl.toString(), config); webhookHasAvatar = !!webhookInfo.data.avatar; } catch (e) { // If we can't verify, we assume he has an avatar to avoid forcing the default avatar webhookHasAvatar = true; } // If heartbeatJSON is null, assume we're testing. if (heartbeatJSON == null) { let discordtestdata = { username: discordDisplayName, content: msg, }; if (!webhookHasAvatar) { discordtestdata.avatar_url = "https://github.com/louislam/uptime-kuma/raw/master/public/icon.png"; } if (notification.discordChannelType === "createNewForumPost") { discordtestdata.thread_name = notification.postName; } await axios.post(webhookUrl.toString(), discordtestdata, config); return okMsg; } // If heartbeatJSON is not null, we go into the normal alerting loop. let addess = this.extractAddress(monitorJSON); if (heartbeatJSON["status"] === DOWN) { let discorddowndata = { username: discordDisplayName, embeds: [{ title: "❌ Your service " + monitorJSON["name"] + " went down. ❌", color: 16711680, timestamp: heartbeatJSON["time"], fields: [ { name: "Service Name", value: monitorJSON["name"], }, ...((!notification.disableUrl && addess) ? [{ name: monitorJSON["type"] === "push" ? "Service Type" : "Service URL", value: addess, }] : []), { name: `Time (${heartbeatJSON["timezone"]})`, value: heartbeatJSON["localDateTime"], }, { name: "Error", value: heartbeatJSON["msg"] == null ? "N/A" : heartbeatJSON["msg"], }, ], }], }; if (!webhookHasAvatar) { discorddowndata.avatar_url = "https://github.com/louislam/uptime-kuma/raw/master/public/icon.png"; } if (notification.discordChannelType === "createNewForumPost") { discorddowndata.thread_name = notification.postName; } if (notification.discordPrefixMessage) { discorddowndata.content = notification.discordPrefixMessage; } await axios.post(webhookUrl.toString(), discorddowndata, config); return okMsg; } else if (heartbeatJSON["status"] === UP) { let discordupdata = { username: discordDisplayName, embeds: [{ title: "βœ… Your service " + monitorJSON["name"] + " is up! βœ…", color: 65280, timestamp: heartbeatJSON["time"], fields: [ { name: "Service Name", value: monitorJSON["name"], }, ...((!notification.disableUrl && addess) ? [{ name: monitorJSON["type"] === "push" ? "Service Type" : "Service URL", value: addess, }] : []), { name: `Time (${heartbeatJSON["timezone"]})`, value: heartbeatJSON["localDateTime"], }, ...(heartbeatJSON["ping"] != null ? [{ name: "Ping", value: heartbeatJSON["ping"] + " ms", }] : []), ], }], }; if (!webhookHasAvatar) { discordupdata.avatar_url = "https://github.com/louislam/uptime-kuma/raw/master/public/icon.png"; } if (notification.discordChannelType === "createNewForumPost") { discordupdata.thread_name = notification.postName; } if (notification.discordPrefixMessage) { discordupdata.content = notification.discordPrefixMessage; } await axios.post(webhookUrl.toString(), discordupdata, config); return okMsg; } } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Discord;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pushdeer.js
server/notification-providers/pushdeer.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class PushDeer extends NotificationProvider { name = "PushDeer"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const serverUrl = notification.pushdeerServer || "https://api2.pushdeer.com"; // capture group below is necessary to prevent an ReDOS-attack const url = `${serverUrl.trim().replace(/([^/])\/+$/, "$1")}/message/push`; let valid = msg != null && monitorJSON != null && heartbeatJSON != null; let title; if (valid && heartbeatJSON.status === UP) { title = "## Uptime Kuma: " + monitorJSON.name + " up"; } else if (valid && heartbeatJSON.status === DOWN) { title = "## Uptime Kuma: " + monitorJSON.name + " down"; } else { title = "## Uptime Kuma Message"; } let data = { "pushkey": notification.pushdeerKey, "text": title, "desp": msg.replace(/\n/g, "\n\n"), "type": "markdown", }; try { let config = this.getAxiosConfigWithProxy({}); let res = await axios.post(url, data, config); if ("error" in res.data) { let error = res.data.error; this.throwGeneralAxiosError(error); } if (res.data.content.result.length === 0) { let error = "Invalid PushDeer key"; this.throwGeneralAxiosError(error); } else if (JSON.parse(res.data.content.result[0]).success !== "ok") { let error = "Unknown error"; this.throwGeneralAxiosError(error); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = PushDeer;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/aliyun-sms.js
server/notification-providers/aliyun-sms.js
const NotificationProvider = require("./notification-provider"); const { DOWN, UP } = require("../../src/util"); const { default: axios } = require("axios"); const Crypto = require("crypto"); const qs = require("qs"); class AliyunSMS extends NotificationProvider { name = "AliyunSMS"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { if (heartbeatJSON != null) { let msgBody = JSON.stringify({ name: monitorJSON["name"], time: heartbeatJSON["localDateTime"], status: this.statusToString(heartbeatJSON["status"]), msg: heartbeatJSON["msg"], }); if (await this.sendSms(notification, msgBody)) { return okMsg; } } else { let msgBody = JSON.stringify({ name: "", time: "", status: "", msg: msg, }); if (await this.sendSms(notification, msgBody)) { return okMsg; } } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Send the SMS notification * @param {BeanModel} notification Notification details * @param {string} msgbody Message template * @returns {Promise<boolean>} True if successful else false */ async sendSms(notification, msgbody) { let params = { PhoneNumbers: notification.phonenumber, TemplateCode: notification.templateCode, SignName: notification.signName, TemplateParam: msgbody, AccessKeyId: notification.accessKeyId, Format: "JSON", SignatureMethod: "HMAC-SHA1", SignatureVersion: "1.0", SignatureNonce: Math.random().toString(), Timestamp: new Date().toISOString(), Action: "SendSms", Version: "2017-05-25", }; params.Signature = this.sign(params, notification.secretAccessKey); let config = { method: "POST", url: "http://dysmsapi.aliyuncs.com/", headers: { "Content-Type": "application/x-www-form-urlencoded", }, data: qs.stringify(params), }; config = this.getAxiosConfigWithProxy(config); let result = await axios(config); if (result.data.Message === "OK") { return true; } throw new Error(result.data.Message); } /** * Aliyun request sign * @param {object} param Parameters object to sign * @param {string} AccessKeySecret Secret key to sign parameters with * @returns {string} Base64 encoded request */ sign(param, AccessKeySecret) { let param2 = {}; let data = []; let oa = Object.keys(param).sort(); for (let i = 0; i < oa.length; i++) { let key = oa[i]; param2[key] = param[key]; } // Escape more characters than encodeURIComponent does. // For generating Aliyun signature, all characters except A-Za-z0-9~-._ are encoded. // See https://help.aliyun.com/document_detail/315526.html // This encoding methods as known as RFC 3986 (https://tools.ietf.org/html/rfc3986) let moreEscapesTable = function (m) { return { "!": "%21", "*": "%2A", "'": "%27", "(": "%28", ")": "%29" }[m]; }; for (let key in param2) { let value = encodeURIComponent(param2[key]).replace(/[!*'()]/g, moreEscapesTable); data.push(`${encodeURIComponent(key)}=${value}`); } let StringToSign = `POST&${encodeURIComponent("/")}&${encodeURIComponent(data.join("&"))}`; return Crypto .createHmac("sha1", `${AccessKeySecret}&`) .update(Buffer.from(StringToSign)) .digest("base64"); } /** * Convert status constant to string * @param {const} status The status constant * @returns {string} Status */ statusToString(status) { switch (status) { case DOWN: return "DOWN"; case UP: return "UP"; default: return status; } } } module.exports = AliyunSMS;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/mattermost.js
server/notification-providers/mattermost.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class Mattermost extends NotificationProvider { name = "mattermost"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); const mattermostUserName = notification.mattermostusername || "Uptime Kuma"; // If heartbeatJSON is null, assume non monitoring notification (Certificate warning) or testing. if (heartbeatJSON == null) { let mattermostTestData = { username: mattermostUserName, text: msg, }; await axios.post(notification.mattermostWebhookUrl, mattermostTestData, config); return okMsg; } let mattermostChannel; if (typeof notification.mattermostchannel === "string") { mattermostChannel = notification.mattermostchannel.toLowerCase(); } const mattermostIconEmoji = notification.mattermosticonemo; let mattermostIconEmojiOnline = ""; let mattermostIconEmojiOffline = ""; if (mattermostIconEmoji && typeof mattermostIconEmoji === "string") { const emojiArray = mattermostIconEmoji.split(" "); if (emojiArray.length >= 2) { mattermostIconEmojiOnline = emojiArray[0]; mattermostIconEmojiOffline = emojiArray[1]; } } const mattermostIconUrl = notification.mattermosticonurl; let iconEmoji = mattermostIconEmoji; let statusField = { short: false, title: "Error", value: heartbeatJSON.msg, }; let statusText = "unknown"; let color = "#000000"; if (heartbeatJSON.status === DOWN) { iconEmoji = mattermostIconEmojiOffline || mattermostIconEmoji; statusField = { short: false, title: "Error", value: heartbeatJSON.msg, }; statusText = "down."; color = "#FF0000"; } else if (heartbeatJSON.status === UP) { iconEmoji = mattermostIconEmojiOnline || mattermostIconEmoji; statusField = { short: false, title: "Ping", value: heartbeatJSON.ping + "ms", }; statusText = "up!"; color = "#32CD32"; } let mattermostdata = { username: monitorJSON.name + " " + mattermostUserName, channel: mattermostChannel, icon_emoji: iconEmoji, icon_url: mattermostIconUrl, attachments: [ { fallback: "Your " + monitorJSON.pathName + " service went " + statusText, color: color, title: monitorJSON.pathName + " service went " + statusText, title_link: monitorJSON.url, fields: [ statusField, { short: true, title: `Time (${heartbeatJSON["timezone"]})`, value: heartbeatJSON.localDateTime, }, ], }, ], }; await axios.post(notification.mattermostWebhookUrl, mattermostdata, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Mattermost;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/gotify.js
server/notification-providers/gotify.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Gotify extends NotificationProvider { name = "gotify"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); if (notification.gotifyserverurl && notification.gotifyserverurl.endsWith("/")) { notification.gotifyserverurl = notification.gotifyserverurl.slice(0, -1); } await axios.post(`${notification.gotifyserverurl}/message?token=${notification.gotifyapplicationToken}`, { "message": msg, "priority": notification.gotifyPriority || 8, "title": "Uptime-Kuma", }, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Gotify;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/stackfield.js
server/notification-providers/stackfield.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { setting } = require("../util-server"); const { getMonitorRelativeURL } = require("../../src/util"); class Stackfield extends NotificationProvider { name = "stackfield"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { // Stackfield message formatting: https://www.stackfield.com/help/formatting-messages-2001 let textMsg = "+Uptime Kuma Alert+"; if (monitorJSON && monitorJSON.name) { textMsg += `\n*${monitorJSON.name}*`; } textMsg += `\n${msg}`; const baseURL = await setting("primaryBaseURL"); if (baseURL) { textMsg += `\n${baseURL + getMonitorRelativeURL(monitorJSON.id)}`; } const data = { "Title": textMsg, }; let config = this.getAxiosConfigWithProxy({}); await axios.post(notification.stackfieldwebhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Stackfield;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/wecom.js
server/notification-providers/wecom.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class WeCom extends NotificationProvider { name = "WeCom"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { "Content-Type": "application/json" } }; config = this.getAxiosConfigWithProxy(config); let body = this.composeMessage(heartbeatJSON, msg); await axios.post(`https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${notification.weComBotKey}`, body, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } /** * Generate the message to send * @param {object} heartbeatJSON Heartbeat details (For Up/Down only) * @param {string} msg General message * @returns {object} Message */ composeMessage(heartbeatJSON, msg) { let title = "UptimeKuma Message"; if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] === UP) { title = "UptimeKuma Monitor Up"; } if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] === DOWN) { title = "UptimeKuma Monitor Down"; } return { msgtype: "text", text: { content: title + "\n" + msg } }; } } module.exports = WeCom;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/Webpush.js
server/notification-providers/Webpush.js
const NotificationProvider = require("./notification-provider"); const { UP } = require("../../src/util"); const webpush = require("web-push"); const { setting } = require("../util-server"); class Webpush extends NotificationProvider { name = "Webpush"; /** * @inheritDoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { const publicVapidKey = await setting("webpushPublicVapidKey"); const privateVapidKey = await setting("webpushPrivateVapidKey"); webpush.setVapidDetails("https://github.com/louislam/uptime-kuma", publicVapidKey, privateVapidKey); if (heartbeatJSON === null && monitorJSON === null) { // Test message const data = JSON.stringify({ title: "TEST", body: `Test Alert - ${msg}` }); await webpush.sendNotification(notification.subscription, data); return okMsg; } const data = JSON.stringify({ title: heartbeatJSON["status"] === UP ? "Monitor Up" : "Monitor DOWN", body: heartbeatJSON["status"] === UP ? `❌ ${heartbeatJSON["name"]} is DOWN` : `βœ… ${heartbeatJSON["name"]} is UP` }); await webpush.sendNotification(notification.subscription, data); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Webpush;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/splunk.js
server/notification-providers/splunk.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util"); const { setting } = require("../util-server"); let successMessage = "Sent Successfully."; class Splunk extends NotificationProvider { name = "Splunk"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { try { if (heartbeatJSON == null) { const title = "Uptime Kuma Alert"; const monitor = { type: "ping", url: "Uptime Kuma Test Button", }; return this.postNotification(notification, title, msg, monitor, "trigger"); } if (heartbeatJSON.status === UP) { const title = "Uptime Kuma Monitor βœ… Up"; return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, "recovery"); } if (heartbeatJSON.status === DOWN) { const title = "Uptime Kuma Monitor πŸ”΄ Down"; return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, "trigger"); } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Check if result is successful, result code should be in range 2xx * @param {object} result Axios response object * @returns {void} * @throws {Error} The status code is not in range 2xx */ checkResult(result) { if (result.status == null) { throw new Error("Splunk notification failed with invalid response!"); } if (result.status < 200 || result.status >= 300) { throw new Error("Splunk notification failed with status code " + result.status); } } /** * Send the message * @param {BeanModel} notification Message title * @param {string} title Message title * @param {string} body Message * @param {object} monitorInfo Monitor details (For Up/Down only) * @param {?string} eventAction Action event for PagerDuty (trigger, acknowledge, resolve) * @returns {Promise<string>} Success state */ async postNotification(notification, title, body, monitorInfo, eventAction = "trigger") { let monitorUrl; if (monitorInfo.type === "port") { monitorUrl = monitorInfo.hostname; if (monitorInfo.port) { monitorUrl += ":" + monitorInfo.port; } } else if (monitorInfo.hostname != null) { monitorUrl = monitorInfo.hostname; } else { monitorUrl = monitorInfo.url; } if (eventAction === "recovery") { if (notification.splunkAutoResolve === "0") { return "No action required"; } eventAction = notification.splunkAutoResolve; } else { eventAction = notification.splunkSeverity; } const options = { method: "POST", url: notification.splunkRestURL, headers: { "Content-Type": "application/json" }, data: { message_type: eventAction, state_message: `[${title}] [${monitorUrl}] ${body}`, entity_display_name: "Uptime Kuma Alert: " + monitorInfo.name, routing_key: notification.pagerdutyIntegrationKey, entity_id: "Uptime Kuma/" + monitorInfo.id, } }; const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorInfo) { options.client = "Uptime Kuma"; options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id); } let result = await axios.request(options); this.checkResult(result); if (result.statusText != null) { return "Splunk notification succeed: " + result.statusText; } return successMessage; } } module.exports = Splunk;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/lunasea.js
server/notification-providers/lunasea.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class LunaSea extends NotificationProvider { name = "lunasea"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://notify.lunasea.app/v1"; try { let config = this.getAxiosConfigWithProxy({}); const target = this.getTarget(notification); if (heartbeatJSON == null) { let testdata = { "title": "Uptime Kuma Alert", "body": msg, }; await axios.post(`${url}/custom/${target}`, testdata, config); return okMsg; } if (heartbeatJSON["status"] === DOWN) { let downdata = { "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[πŸ”΄ Down] " + heartbeatJSON["msg"] + `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` }; await axios.post(`${url}/custom/${target}`, downdata, config); return okMsg; } if (heartbeatJSON["status"] === UP) { let updata = { "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[βœ… Up] " + heartbeatJSON["msg"] + `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` }; await axios.post(`${url}/custom/${target}`, updata, config); return okMsg; } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Generates the lunasea target to send the notification to * @param {BeanModel} notification Notification details * @returns {string} The target to send the notification to */ getTarget(notification) { if (notification.lunaseaTarget === "user") { return "user/" + notification.lunaseaUserID; } return "device/" + notification.lunaseaDevice; } } module.exports = LunaSea;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/slack.js
server/notification-providers/slack.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { setSettings, setting } = require("../util-server"); const { getMonitorRelativeURL, UP, log } = require("../../src/util"); const isUrl = require("is-url"); class Slack extends NotificationProvider { name = "slack"; /** * Deprecated property notification.slackbutton * Set it as primary base url if this is not yet set. * @deprecated * @param {string} url The primary base URL to use * @returns {Promise<void>} */ static async deprecateURL(url) { let currentPrimaryBaseURL = await setting("primaryBaseURL"); if (!currentPrimaryBaseURL) { console.log("Move the url to be the primary base URL"); await setSettings("general", { primaryBaseURL: url, }); } else { console.log("Already there, no need to move the primary base URL"); } } /** * Builds the actions available in the slack message * @param {string} baseURL Uptime Kuma base URL * @param {object} monitorJSON The monitor config * @returns {Array} The relevant action objects */ buildActions(baseURL, monitorJSON) { const actions = []; if (baseURL) { actions.push({ "type": "button", "text": { "type": "plain_text", "text": "Visit Uptime Kuma", }, "value": "Uptime-Kuma", "url": baseURL + getMonitorRelativeURL(monitorJSON.id), }); } const address = this.extractAddress(monitorJSON); if (isUrl(address)) { try { actions.push({ "type": "button", "text": { "type": "plain_text", "text": "Visit site", }, "value": "Site", "url": new URL(address), }); } catch (e) { log.debug("slack", `Failed to parse address ${address} as URL`); } } return actions; } /** * Builds the different blocks the Slack message consists of. * @param {string} baseURL Uptime Kuma base URL * @param {object} monitorJSON The monitor object * @param {object} heartbeatJSON The heartbeat object * @param {string} title The message title * @param {string} msg The message body * @returns {Array<object>} The rich content blocks for the Slack message */ buildBlocks(baseURL, monitorJSON, heartbeatJSON, title, msg) { //create an array to dynamically add blocks const blocks = []; // the header block blocks.push({ "type": "header", "text": { "type": "plain_text", "text": title, }, }); // the body block, containing the details blocks.push({ "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Message*\n" + msg, }, { "type": "mrkdwn", "text": `*Time (${heartbeatJSON["timezone"]})*\n${heartbeatJSON["localDateTime"]}`, } ], }); const actions = this.buildActions(baseURL, monitorJSON); if (actions.length > 0) { //the actions block, containing buttons blocks.push({ "type": "actions", "elements": actions, }); } return blocks; } /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; if (notification.slackchannelnotify) { msg += " <!channel>"; } try { let config = this.getAxiosConfigWithProxy({}); if (heartbeatJSON == null) { let data = { "text": msg, "channel": notification.slackchannel, "username": notification.slackusername, "icon_emoji": notification.slackiconemo, }; await axios.post(notification.slackwebhookURL, data, config); return okMsg; } const baseURL = await setting("primaryBaseURL"); const title = "Uptime Kuma Alert"; let data = { "text": msg, "channel": notification.slackchannel, "username": notification.slackusername, "icon_emoji": notification.slackiconemo, "attachments": [], }; if (notification.slackrichmessage) { data.attachments.push( { "color": (heartbeatJSON["status"] === UP) ? "#2eb886" : "#e01e5a", "blocks": this.buildBlocks(baseURL, monitorJSON, heartbeatJSON, title, msg), } ); } else { data.text = `${title}\n${msg}`; } if (notification.slackbutton) { await Slack.deprecateURL(notification.slackbutton); } await axios.post(notification.slackwebhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Slack;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pumble.js
server/notification-providers/pumble.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP } = require("../../src/util"); class Pumble extends NotificationProvider { name = "pumble"; /** * @inheritDoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); if (heartbeatJSON === null && monitorJSON === null) { let data = { "attachments": [ { "title": "Uptime Kuma Alert", "text": msg, "color": "#5BDD8B" } ] }; await axios.post(notification.webhookURL, data, config); return okMsg; } let data = { "attachments": [ { "title": `${monitorJSON["name"]} is ${heartbeatJSON["status"] === UP ? "up" : "down"}`, "text": heartbeatJSON["msg"], "color": (heartbeatJSON["status"] === UP ? "#5BDD8B" : "#DC3645"), } ] }; await axios.post(notification.webhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Pumble;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/sms-planet.js
server/notification-providers/sms-planet.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SMSPlanet extends NotificationProvider { name = "SMSPlanet"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api2.smsplanet.pl/sms"; try { let config = { headers: { "Authorization": "Bearer " + notification.smsplanetApiToken, "content-type": "multipart/form-data" } }; config = this.getAxiosConfigWithProxy(config); let data = { "from": notification.smsplanetSenderName, "to": notification.smsplanetPhoneNumbers, "msg": msg.replace(/πŸ”΄/, "❌") }; let response = await axios.post(url, data, config); if (!response.data?.messageId) { throw new Error(response.data?.errorMsg ?? "SMSPlanet server did not respond with the expected result"); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SMSPlanet;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/spugpush.js
server/notification-providers/spugpush.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class SpugPush extends NotificationProvider { name = "SpugPush"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { let okMsg = "Sent Successfully."; try { let formData = { title: "Uptime Kuma Message", content: msg }; if (heartbeatJSON) { if (heartbeatJSON["status"] === UP) { formData.title = `UptimeKuma γ€Œ${monitorJSON["name"]}」 is Up`; formData.content = `[βœ… Up] ${heartbeatJSON["msg"]}`; } else if (heartbeatJSON["status"] === DOWN) { formData.title = `UptimeKuma γ€Œ${monitorJSON["name"]}」 is Down`; formData.content = `[πŸ”΄ Down] ${heartbeatJSON["msg"]}`; } } const apiUrl = `https://push.spug.cc/send/${notification.templateKey}`; let config = this.getAxiosConfigWithProxy({}); await axios.post(apiUrl, formData, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SpugPush;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pushbullet.js
server/notification-providers/pushbullet.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class Pushbullet extends NotificationProvider { name = "pushbullet"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api.pushbullet.com/v2/pushes"; try { let config = { headers: { "Access-Token": notification.pushbulletAccessToken, "Content-Type": "application/json" } }; config = this.getAxiosConfigWithProxy(config); if (heartbeatJSON == null) { let data = { "type": "note", "title": "Uptime Kuma Alert", "body": msg, }; await axios.post(url, data, config); } else if (heartbeatJSON["status"] === DOWN) { let downData = { "type": "note", "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[πŸ”΄ Down] " + heartbeatJSON["msg"] + `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, }; await axios.post(url, downData, config); } else if (heartbeatJSON["status"] === UP) { let upData = { "type": "note", "title": "UptimeKuma Alert: " + monitorJSON["name"], "body": "[βœ… Up] " + heartbeatJSON["msg"] + `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, }; await axios.post(url, upData, config); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Pushbullet;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/dingding.js
server/notification-providers/dingding.js
const NotificationProvider = require("./notification-provider"); const { DOWN, UP } = require("../../src/util"); const { default: axios } = require("axios"); const Crypto = require("crypto"); class DingDing extends NotificationProvider { name = "DingDing"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const mentionAll = notification.mentioning === "everyone"; const mobileList = notification.mentioning === "specify-mobiles" ? notification.mobileList : []; const userList = notification.mentioning === "specify-users" ? notification.userList : []; const finalList = [ ...mobileList || [], ...userList || [] ]; const mentionStr = finalList.length > 0 ? "\n" : "" + finalList.map(item => `@${item}`).join(" "); try { if (heartbeatJSON != null) { let params = { msgtype: "markdown", markdown: { title: `[${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]}`, text: `## [${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]} \n> ${heartbeatJSON["msg"]}\n> Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}${mentionStr}`, }, at: { isAtAll: mentionAll, atUserIds: userList, atMobiles: mobileList } }; if (await this.sendToDingDing(notification, params)) { return okMsg; } } else { let params = { msgtype: "text", text: { content: `${msg}${mentionStr}` }, at: { isAtAll: mentionAll, atUserIds: userList, atMobiles: mobileList } }; if (await this.sendToDingDing(notification, params)) { return okMsg; } } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Send message to DingDing * @param {BeanModel} notification Notification to send * @param {object} params Parameters of message * @returns {Promise<boolean>} True if successful else false */ async sendToDingDing(notification, params) { let timestamp = Date.now(); let config = { method: "POST", headers: { "Content-Type": "application/json", }, url: `${notification.webHookUrl}&timestamp=${timestamp}&sign=${encodeURIComponent(this.sign(timestamp, notification.secretKey))}`, data: JSON.stringify(params), }; config = this.getAxiosConfigWithProxy(config); let result = await axios(config); if (result.data.errmsg === "ok") { return true; } throw new Error(result.data.errmsg); } /** * DingDing sign * @param {Date} timestamp Timestamp of message * @param {string} secretKey Secret key to sign data with * @returns {string} Base64 encoded signature */ sign(timestamp, secretKey) { return Crypto .createHmac("sha256", Buffer.from(secretKey, "utf8")) .update(Buffer.from(`${timestamp}\n${secretKey}`, "utf8")) .digest("base64"); } /** * Convert status constant to string * @param {const} status The status constant * @returns {string} Status */ statusToString(status) { switch (status) { case DOWN: return "DOWN"; case UP: return "UP"; default: return status; } } } module.exports = DingDing;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/onebot.js
server/notification-providers/onebot.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class OneBot extends NotificationProvider { name = "OneBot"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let url = notification.httpAddr; if (!url.startsWith("http")) { url = "http://" + url; } if (!url.endsWith("/")) { url += "/"; } url += "send_msg"; let config = { headers: { "Content-Type": "application/json", "Authorization": "Bearer " + notification.accessToken, } }; config = this.getAxiosConfigWithProxy(config); let pushText = "UptimeKuma Alert: " + msg; let data = { "auto_escape": true, "message": pushText, }; if (notification.msgType === "group") { data["message_type"] = "group"; data["group_id"] = notification.recieverId; } else { data["message_type"] = "private"; data["user_id"] = notification.recieverId; } await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = OneBot;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/promosms.js
server/notification-providers/promosms.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class PromoSMS extends NotificationProvider { name = "promosms"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://promosms.com/api/rest/v3_2/sms"; if (notification.promosmsAllowLongSMS === undefined) { notification.promosmsAllowLongSMS = false; } //TODO: Add option for enabling special characters. It will decrease message max length from 160 to 70 chars. //Lets remove non ascii char let cleanMsg = msg.replace(/[^\x00-\x7F]/g, ""); try { let config = { headers: { "Content-Type": "application/json", "Authorization": "Basic " + Buffer.from(notification.promosmsLogin + ":" + notification.promosmsPassword).toString("base64"), "Accept": "text/json", } }; config = this.getAxiosConfigWithProxy(config); let data = { "recipients": [ notification.promosmsPhoneNumber ], //Trim message to maximum length of 1 SMS or 4 if we allowed long messages "text": notification.promosmsAllowLongSMS ? cleanMsg.substring(0, 639) : cleanMsg.substring(0, 159), "long-sms": notification.promosmsAllowLongSMS, "type": Number(notification.promosmsSMSType), "sender": notification.promosmsSenderName }; let resp = await axios.post(url, data, config); if (resp.data.response.status !== 0) { let error = "Something gone wrong. Api returned " + resp.data.response.status + "."; this.throwGeneralAxiosError(error); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = PromoSMS;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/flashduty.js
server/notification-providers/flashduty.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util"); const { setting } = require("../util-server"); const successMessage = "Sent Successfully."; class FlashDuty extends NotificationProvider { name = "FlashDuty"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { try { if (heartbeatJSON == null) { const title = "Uptime Kuma Alert"; const monitor = { type: "ping", url: msg, name: "https://flashcat.cloud" }; return this.postNotification(notification, title, msg, monitor); } if (heartbeatJSON.status === UP) { const title = "Uptime Kuma Monitor βœ… Up"; return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, "Ok"); } if (heartbeatJSON.status === DOWN) { const title = "Uptime Kuma Monitor πŸ”΄ Down"; return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, notification.flashdutySeverity); } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Generate a monitor url from the monitors information * @param {object} monitorInfo Monitor details * @returns {string|undefined} Monitor URL */ genMonitorUrl(monitorInfo) { if (monitorInfo.type === "port" && monitorInfo.port) { return monitorInfo.hostname + ":" + monitorInfo.port; } if (monitorInfo.hostname != null) { return monitorInfo.hostname; } return monitorInfo.url; } /** * Send the message * @param {BeanModel} notification Message title * @param {string} title Message * @param {string} body Message * @param {object} monitorInfo Monitor details * @param {string} eventStatus Monitor status (Info, Warning, Critical, Ok) * @returns {string} Success message */ async postNotification(notification, title, body, monitorInfo, eventStatus) { let labels = { resource: this.genMonitorUrl(monitorInfo), check: monitorInfo.name, }; if (monitorInfo.tags && monitorInfo.tags.length > 0) { for (let tag of monitorInfo.tags) { labels[tag.name] = tag.value; } } const options = { method: "POST", url: notification.flashdutyIntegrationKey.startsWith("http") ? notification.flashdutyIntegrationKey : "https://api.flashcat.cloud/event/push/alert/standard?integration_key=" + notification.flashdutyIntegrationKey, headers: { "Content-Type": "application/json" }, data: { description: `[${title}] [${monitorInfo.name}] ${body}`, title, event_status: eventStatus || "Info", alert_key: monitorInfo.id ? String(monitorInfo.id) : Math.random().toString(36).substring(7), labels, } }; const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorInfo) { options.client = "Uptime Kuma"; options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id); } let result = await axios.request(options); if (result.status == null) { throw new Error("FlashDuty notification failed with invalid response!"); } if (result.status < 200 || result.status >= 300) { throw new Error("FlashDuty notification failed with status code " + result.status); } if (result.statusText != null) { return "FlashDuty notification succeed: " + result.statusText; } return successMessage; } } module.exports = FlashDuty;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/sevenio.js
server/notification-providers/sevenio.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class SevenIO extends NotificationProvider { name = "SevenIO"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const data = { to: notification.sevenioReceiver, from: notification.sevenioSender || "Uptime Kuma", text: msg, }; let config = { baseURL: "https://gateway.seven.io/api/", headers: { "Content-Type": "application/json", "X-API-Key": notification.sevenioApiKey, }, }; try { config = this.getAxiosConfigWithProxy(config); // testing or certificate expiry notification if (heartbeatJSON == null) { await axios.post("sms", data, config); return okMsg; } let address = this.extractAddress(monitorJSON); if (address !== "") { address = `(${address}) `; } // If heartbeatJSON is not null, we go into the normal alerting loop. if (heartbeatJSON["status"] === DOWN) { data.text = `Your service ${monitorJSON["name"]} ${address}went down at ${heartbeatJSON["localDateTime"]} ` + `(${heartbeatJSON["timezone"]}). Error: ${heartbeatJSON["msg"]}`; } else if (heartbeatJSON["status"] === UP) { data.text = `Your service ${monitorJSON["name"]} ${address}went back up at ${heartbeatJSON["localDateTime"]} ` + `(${heartbeatJSON["timezone"]}).`; } await axios.post("sms", data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SevenIO;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/techulus-push.js
server/notification-providers/techulus-push.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class TechulusPush extends NotificationProvider { name = "PushByTechulus"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; let data = { "title": notification?.pushTitle?.length ? notification.pushTitle : "Uptime-Kuma", "body": msg, "timeSensitive": notification.pushTimeSensitive ?? true, }; if (notification.pushChannel) { data.channel = notification.pushChannel; } if (notification.pushSound) { data.sound = notification.pushSound; } try { let config = this.getAxiosConfigWithProxy({}); await axios.post(`https://push.techulus.com/api/v1/notify/${notification.pushAPIKey}`, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = TechulusPush;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/smspartner.js
server/notification-providers/smspartner.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SMSPartner extends NotificationProvider { name = "SMSPartner"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api.smspartner.fr/v1/send"; try { // smspartner does not support non ascii characters and only a maximum 639 characters let cleanMsg = msg.replace(/[^\x00-\x7F]/g, "").substring(0, 639); let data = { "apiKey": notification.smspartnerApikey, "sender": notification.smspartnerSenderName.substring(0, 11), "phoneNumbers": notification.smspartnerPhoneNumber, "message": cleanMsg, }; let config = { headers: { "Content-Type": "application/json", "cache-control": "no-cache", "Accept": "application/json", } }; config = this.getAxiosConfigWithProxy(config); let resp = await axios.post(url, data, config); if (resp.data.success !== true) { throw Error(`Api returned ${resp.data.response.status}.`); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SMSPartner;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/signal.js
server/notification-providers/signal.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Signal extends NotificationProvider { name = "signal"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let data = { "message": msg, "number": notification.signalNumber, "recipients": notification.signalRecipients.replace(/\s/g, "").split(","), }; let config = {}; config = this.getAxiosConfigWithProxy(config); await axios.post(notification.signalURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Signal;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/onechat.js
server/notification-providers/onechat.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class OneChat extends NotificationProvider { name = "OneChat"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://chat-api.one.th/message/api/v1/push_message"; try { let config = { headers: { "Content-Type": "application/json", Authorization: "Bearer " + notification.accessToken, }, }; config = this.getAxiosConfigWithProxy(config); if (heartbeatJSON == null) { const testMessage = { to: notification.recieverId, bot_id: notification.botId, type: "text", message: "Test Successful!", }; await axios.post(url, testMessage, config); } else if (heartbeatJSON["status"] === DOWN) { const downMessage = { to: notification.recieverId, bot_id: notification.botId, type: "text", message: `UptimeKuma Alert: [πŸ”΄ Down] Name: ${monitorJSON["name"]} ${heartbeatJSON["msg"]} Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, }; await axios.post(url, downMessage, config); } else if (heartbeatJSON["status"] === UP) { const upMessage = { to: notification.recieverId, bot_id: notification.botId, type: "text", message: `UptimeKuma Alert: [🟒 Up] Name: ${monitorJSON["name"]} ${heartbeatJSON["msg"]} Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, }; await axios.post(url, upMessage, config); } return okMsg; } catch (error) { // Handle errors and throw a descriptive message if (error.response) { const errorMessage = error.response.data?.message || "Unknown API error occurred."; throw new Error(`OneChat API Error: ${errorMessage}`); } else { this.throwGeneralAxiosError(error); } } } } module.exports = OneChat;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/teams.js
server/notification-providers/teams.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { setting } = require("../util-server"); const { DOWN, UP, getMonitorRelativeURL } = require("../../src/util"); class Teams extends NotificationProvider { name = "teams"; /** * Generate the message to send * @param {const} status The status constant * @param {string} monitorName Name of monitor * @param {boolean} withStatusSymbol If the status should be prepended as symbol * @returns {string} Status message */ _statusMessageFactory = (status, monitorName, withStatusSymbol) => { if (status === DOWN) { return (withStatusSymbol ? "πŸ”΄ " : "") + `[${monitorName}] went down`; } else if (status === UP) { return (withStatusSymbol ? "βœ… " : "") + `[${monitorName}] is back online`; } return "Notification"; }; /** * Select the style to use based on status * @param {const} status The status constant * @returns {string} Selected style for adaptive cards */ _getStyle = (status) => { if (status === DOWN) { return "attention"; } if (status === UP) { return "good"; } return "emphasis"; }; /** * Generate payload for notification * @param {object} args Method arguments * @param {object} args.heartbeatJSON Heartbeat details * @param {string} args.monitorName Name of the monitor affected * @param {string} args.monitorUrl URL of the monitor affected * @param {string} args.dashboardUrl URL of the dashboard affected * @returns {object} Notification payload */ _notificationPayloadFactory = ({ heartbeatJSON, monitorName, monitorUrl, dashboardUrl, }) => { const status = heartbeatJSON?.status; const facts = []; const actions = []; if (dashboardUrl) { actions.push({ "type": "Action.OpenUrl", "title": "Visit Uptime Kuma", "url": dashboardUrl }); } if (heartbeatJSON?.msg) { facts.push({ title: "Description", value: heartbeatJSON.msg, }); } if (monitorName) { facts.push({ title: "Monitor", value: monitorName, }); } if (monitorUrl && monitorUrl !== "https://") { facts.push({ title: "URL", // format URL as markdown syntax, to be clickable value: `[${monitorUrl}](${monitorUrl})`, }); actions.push({ "type": "Action.OpenUrl", "title": "Visit Monitor URL", "url": monitorUrl }); } if (heartbeatJSON?.localDateTime) { facts.push({ title: "Time", value: heartbeatJSON.localDateTime + (heartbeatJSON.timezone ? ` (${heartbeatJSON.timezone})` : ""), }); } const payload = { "type": "message", // message with status prefix as notification text "summary": this._statusMessageFactory(status, monitorName, true), "attachments": [ { "contentType": "application/vnd.microsoft.card.adaptive", "contentUrl": "", "content": { "type": "AdaptiveCard", "body": [ { "type": "Container", "verticalContentAlignment": "Center", "items": [ { "type": "ColumnSet", "style": this._getStyle(status), "columns": [ { "type": "Column", "width": "auto", "verticalContentAlignment": "Center", "items": [ { "type": "Image", "width": "32px", "style": "Person", "url": "https://raw.githubusercontent.com/louislam/uptime-kuma/master/public/icon.png", "altText": "Uptime Kuma Logo" } ] }, { "type": "Column", "width": "stretch", "items": [ { "type": "TextBlock", "size": "Medium", "weight": "Bolder", "text": `**${this._statusMessageFactory(status, monitorName, false)}**`, }, { "type": "TextBlock", "size": "Small", "weight": "Default", "text": "Uptime Kuma Alert", "isSubtle": true, "spacing": "None" } ] } ] } ] }, { "type": "FactSet", "separator": false, "facts": facts } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.5" } } ] }; if (actions) { payload.attachments[0].content.body.push({ "type": "ActionSet", "actions": actions, }); } return payload; }; /** * Send the notification * @param {string} webhookUrl URL to send the request to * @param {object} payload Payload generated by _notificationPayloadFactory * @returns {Promise<void>} */ _sendNotification = async (webhookUrl, payload) => { let config = this.getAxiosConfigWithProxy({}); await axios.post(webhookUrl, payload, config); }; /** * Send a general notification * @param {string} webhookUrl URL to send request to * @param {string} msg Message to send * @returns {Promise<void>} */ _handleGeneralNotification = (webhookUrl, msg) => { const payload = this._notificationPayloadFactory({ heartbeatJSON: { msg: msg } }); return this._sendNotification(webhookUrl, payload); }; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { if (heartbeatJSON == null) { await this._handleGeneralNotification(notification.webhookUrl, msg); return okMsg; } const baseURL = await setting("primaryBaseURL"); let dashboardUrl; if (baseURL) { dashboardUrl = baseURL + getMonitorRelativeURL(monitorJSON.id); } const payload = this._notificationPayloadFactory({ heartbeatJSON: heartbeatJSON, monitorName: monitorJSON.name, monitorUrl: this.extractAddress(monitorJSON), dashboardUrl: dashboardUrl, }); await this._sendNotification(notification.webhookUrl, payload); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Teams;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/smsc.js
server/notification-providers/smsc.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SMSC extends NotificationProvider { name = "smsc"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://smsc.kz/sys/send.php?"; try { let config = { headers: { "Content-Type": "application/json", "Accept": "text/json", } }; config = this.getAxiosConfigWithProxy(config); let getArray = [ "fmt=3", "translit=" + notification.smscTranslit, "login=" + notification.smscLogin, "psw=" + notification.smscPassword, "phones=" + notification.smscToNumber, "mes=" + encodeURIComponent(msg.replace(/[^\x00-\x7F]/g, "")), ]; if (notification.smscSenderName !== "") { getArray.push("sender=" + notification.smscSenderName); } let resp = await axios.get(url + getArray.join("&"), config); if (resp.data.id === undefined) { let error = `Something gone wrong. Api returned code ${resp.data.error_code}: ${resp.data.error}`; this.throwGeneralAxiosError(error); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SMSC;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pagertree.js
server/notification-providers/pagertree.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util"); const { setting } = require("../util-server"); let successMessage = "Sent Successfully."; class PagerTree extends NotificationProvider { name = "PagerTree"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { try { if (heartbeatJSON == null) { // general messages return this.postNotification(notification, msg, monitorJSON, heartbeatJSON); } if (heartbeatJSON.status === UP && notification.pagertreeAutoResolve === "resolve") { return this.postNotification(notification, null, monitorJSON, heartbeatJSON, notification.pagertreeAutoResolve); } if (heartbeatJSON.status === DOWN) { const title = `Uptime Kuma Monitor "${monitorJSON.name}" is DOWN`; return this.postNotification(notification, title, monitorJSON, heartbeatJSON); } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Check if result is successful, result code should be in range 2xx * @param {object} result Axios response object * @returns {void} * @throws {Error} The status code is not in range 2xx */ checkResult(result) { if (result.status == null) { throw new Error("PagerTree notification failed with invalid response!"); } if (result.status < 200 || result.status >= 300) { throw new Error("PagerTree notification failed with status code " + result.status); } } /** * Send the message * @param {BeanModel} notification Message title * @param {string} title Message title * @param {object} monitorJSON Monitor details (For Up/Down only) * @param {object} heartbeatJSON Heartbeat details (For Up/Down only) * @param {?string} eventAction Action event for PagerTree (create, resolve) * @returns {Promise<string>} Success state */ async postNotification(notification, title, monitorJSON, heartbeatJSON, eventAction = "create") { if (eventAction == null) { return "No action required"; } const options = { method: "POST", url: notification.pagertreeIntegrationUrl, headers: { "Content-Type": "application/json" }, data: { event_type: eventAction, id: heartbeatJSON?.monitorID || "uptime-kuma", title: title, urgency: notification.pagertreeUrgency, heartbeat: heartbeatJSON, monitor: monitorJSON } }; const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorJSON) { options.client = "Uptime Kuma"; options.client_url = baseURL + getMonitorRelativeURL(monitorJSON.id); } let result = await axios.request(options); this.checkResult(result); if (result.statusText != null) { return "PagerTree notification succeed: " + result.statusText; } return successMessage; } } module.exports = PagerTree;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/gorush.js
server/notification-providers/gorush.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Gorush extends NotificationProvider { name = "gorush"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; let platformMapping = { "ios": 1, "android": 2, "huawei": 3, }; try { let data = { "notifications": [ { "tokens": [ notification.gorushDeviceToken ], "platform": platformMapping[notification.gorushPlatform], "message": msg, // Optional "title": notification.gorushTitle, "priority": notification.gorushPriority, "retry": parseInt(notification.gorushRetry) || 0, "topic": notification.gorushTopic, } ] }; let config = this.getAxiosConfigWithProxy({}); await axios.post(`${notification.gorushServerURL}/api/push`, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Gorush;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/freemobile.js
server/notification-providers/freemobile.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class FreeMobile extends NotificationProvider { name = "FreeMobile"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); await axios.post(`https://smsapi.free-mobile.fr/sendmsg?msg=${encodeURIComponent(msg.replace("πŸ”΄", "⛔️"))}`, { "user": notification.freemobileUser, "pass": notification.freemobilePass, }, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = FreeMobile;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/grafana-oncall.js
server/notification-providers/grafana-oncall.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class GrafanaOncall extends NotificationProvider { name = "GrafanaOncall"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; if (!notification.GrafanaOncallURL) { throw new Error("GrafanaOncallURL cannot be empty"); } try { let config = this.getAxiosConfigWithProxy({}); if (heartbeatJSON === null) { let grafanaupdata = { title: "General notification", message: msg, state: "alerting", }; await axios.post(notification.GrafanaOncallURL, grafanaupdata, config); return okMsg; } else if (heartbeatJSON["status"] === DOWN) { let grafanadowndata = { title: monitorJSON["name"] + " is down", message: heartbeatJSON["msg"], state: "alerting", }; await axios.post(notification.GrafanaOncallURL, grafanadowndata, config); return okMsg; } else if (heartbeatJSON["status"] === UP) { let grafanaupdata = { title: monitorJSON["name"] + " is up", message: heartbeatJSON["msg"], state: "ok", }; await axios.post(notification.GrafanaOncallURL, grafanaupdata, config); return okMsg; } } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = GrafanaOncall;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/serverchan.js
server/notification-providers/serverchan.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class ServerChan extends NotificationProvider { name = "ServerChan"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; // serverchan3 requires sending via ft07.com const matchResult = String(notification.serverChanSendKey).match(/^sctp(\d+)t/i); const url = matchResult && matchResult[1] ? `https://${matchResult[1]}.push.ft07.com/send/${notification.serverChanSendKey}.send` : `https://sctapi.ftqq.com/${notification.serverChanSendKey}.send`; try { let config = this.getAxiosConfigWithProxy({}); await axios.post(url, { "title": this.checkStatus(heartbeatJSON, monitorJSON), "desp": msg, }, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } /** * Get the formatted title for message * @param {?object} heartbeatJSON Heartbeat details (For Up/Down only) * @param {?object} monitorJSON Monitor details (For Up/Down only) * @returns {string} Formatted title */ checkStatus(heartbeatJSON, monitorJSON) { let title = "UptimeKuma Message"; if (heartbeatJSON != null && heartbeatJSON["status"] === UP) { title = "UptimeKuma Monitor Up " + monitorJSON["name"]; } if (heartbeatJSON != null && heartbeatJSON["status"] === DOWN) { title = "UptimeKuma Monitor Down " + monitorJSON["name"]; } return title; } } module.exports = ServerChan;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/46elks.js
server/notification-providers/46elks.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Elks extends NotificationProvider { name = "Elks"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api.46elks.com/a1/sms"; try { let data = new URLSearchParams(); data.append("from", notification.elksFromNumber); data.append("to", notification.elksToNumber ); data.append("message", msg); let config = { headers: { "Authorization": "Basic " + Buffer.from(`${notification.elksUsername}:${notification.elksAuthToken}`).toString("base64") } }; config = this.getAxiosConfigWithProxy(config); await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Elks;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/webhook.js
server/notification-providers/webhook.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const FormData = require("form-data"); class Webhook extends NotificationProvider { name = "webhook"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { const httpMethod = notification.httpMethod.toLowerCase() || "post"; let data = { heartbeat: heartbeatJSON, monitor: monitorJSON, msg, }; let config = { headers: {} }; if (httpMethod === "get") { config.params = { msg: msg }; if (heartbeatJSON) { config.params.heartbeat = JSON.stringify(heartbeatJSON); } if (monitorJSON) { config.params.monitor = JSON.stringify(monitorJSON); } } else if (notification.webhookContentType === "form-data") { const formData = new FormData(); formData.append("data", JSON.stringify(data)); config.headers = formData.getHeaders(); data = formData; } else if (notification.webhookContentType === "custom") { data = await this.renderTemplate(notification.webhookCustomBody, msg, monitorJSON, heartbeatJSON); } if (notification.webhookAdditionalHeaders) { try { config.headers = { ...config.headers, ...JSON.parse(notification.webhookAdditionalHeaders) }; } catch (err) { throw new Error("Additional Headers is not a valid JSON"); } } config = this.getAxiosConfigWithProxy(config); if (httpMethod === "get") { await axios.get(notification.webhookURL, config); } else { await axios.post(notification.webhookURL, data, config); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Webhook;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/ntfy.js
server/notification-providers/ntfy.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class Ntfy extends NotificationProvider { name = "ntfy"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let headers = {}; if (notification.ntfyAuthenticationMethod === "usernamePassword") { headers = { "Authorization": "Basic " + Buffer.from(notification.ntfyusername + ":" + notification.ntfypassword).toString("base64"), }; } else if (notification.ntfyAuthenticationMethod === "accessToken") { headers = { "Authorization": "Bearer " + notification.ntfyaccesstoken, }; } let config = { headers }; config = this.getAxiosConfigWithProxy(config); // If heartbeatJSON is null, assume non monitoring notification (Certificate warning) or testing. if (heartbeatJSON == null) { let ntfyTestData = { "topic": notification.ntfytopic, "title": (monitorJSON?.name || notification.ntfytopic) + " [Uptime-Kuma]", "message": msg, "priority": notification.ntfyPriority, "tags": [ "test_tube" ], }; await axios.post(notification.ntfyserverurl, ntfyTestData, config); return okMsg; } let tags = []; let status = "unknown"; let priority = notification.ntfyPriority || 4; if ("status" in heartbeatJSON) { if (heartbeatJSON.status === DOWN) { tags = [ "red_circle" ]; status = "Down"; // defaults to max(priority + 1, 5) priority = notification.ntfyPriorityDown || (priority === 5 ? priority : priority + 1); } else if (heartbeatJSON["status"] === UP) { tags = [ "green_circle" ]; status = "Up"; } } let data = { "topic": notification.ntfytopic, "message": heartbeatJSON.msg, "priority": priority, "title": monitorJSON.name + " " + status + " [Uptime-Kuma]", "tags": tags, }; if (monitorJSON.url && monitorJSON.url !== "https://") { data.actions = [ { "action": "view", "label": "Open " + monitorJSON.name, "url": monitorJSON.url, }, ]; } if (notification.ntfyIcon) { data.icon = notification.ntfyIcon; } await axios.post(notification.ntfyserverurl, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Ntfy;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/send-grid.js
server/notification-providers/send-grid.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SendGrid extends NotificationProvider { name = "SendGrid"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${notification.sendgridApiKey}`, }, }; config = this.getAxiosConfigWithProxy(config); let personalizations = { to: [{ email: notification.sendgridToEmail }], }; // Add CC recipients if provided if (notification.sendgridCcEmail) { personalizations.cc = notification.sendgridCcEmail .split(",") .map((email) => ({ email: email.trim() })); } // Add BCC recipients if provided if (notification.sendgridBccEmail) { personalizations.bcc = notification.sendgridBccEmail .split(",") .map((email) => ({ email: email.trim() })); } let data = { personalizations: [ personalizations ], from: { email: notification.sendgridFromEmail.trim() }, subject: notification.sendgridSubject || "Notification from Your Uptime Kuma", content: [ { type: "text/plain", value: msg, }, ], }; await axios.post( "https://api.sendgrid.com/v3/mail/send", data, config ); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SendGrid;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/serwersms.js
server/notification-providers/serwersms.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SerwerSMS extends NotificationProvider { name = "serwersms"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api2.serwersms.pl/messages/send_sms"; try { let config = { headers: { "Content-Type": "application/json", } }; config = this.getAxiosConfigWithProxy(config); let data = { "username": notification.serwersmsUsername, "password": notification.serwersmsPassword, "phone": notification.serwersmsPhoneNumber, "text": msg.replace(/[^\x00-\x7F]/g, ""), "sender": notification.serwersmsSenderName, }; let resp = await axios.post(url, data, config); if (!resp.data.success) { if (resp.data.error) { let error = `SerwerSMS.pl API returned error code ${resp.data.error.code} (${resp.data.error.type}) with error message: ${resp.data.error.message}`; this.throwGeneralAxiosError(error); } else { let error = "SerwerSMS.pl API returned an unexpected response"; this.throwGeneralAxiosError(error); } } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SerwerSMS;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/kook.js
server/notification-providers/kook.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Kook extends NotificationProvider { name = "Kook"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://www.kookapp.cn/api/v3/message/create"; let data = { target_id: notification.kookGuildID, content: msg, }; let config = { headers: { "Authorization": "Bot " + notification.kookBotToken, "Content-Type": "application/json", }, }; try { config = this.getAxiosConfigWithProxy(config); await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Kook;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pushplus.js
server/notification-providers/pushplus.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class PushPlus extends NotificationProvider { name = "PushPlus"; /** * @inheritdoc * @param {BeanModel} notification Notification object * @param {string} msg Message content * @param {?object} monitorJSON Monitor details * @param {?object} heartbeatJSON Heartbeat details * @returns {Promise<string>} Success message */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://www.pushplus.plus/send"; try { let config = { headers: { "Content-Type": "application/json", }, }; config = this.getAxiosConfigWithProxy(config); const params = { "token": notification.pushPlusSendKey, "title": this.checkStatus(heartbeatJSON, monitorJSON), "content": msg, "template": "html" }; await axios.post(url, params, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } /** * Get the formatted title for message * @param {?object} heartbeatJSON Heartbeat details (For Up/Down only) * @param {?object} monitorJSON Monitor details (For Up/Down only) * @returns {string} Formatted title */ checkStatus(heartbeatJSON, monitorJSON) { let title = "UptimeKuma Message"; if (heartbeatJSON != null && heartbeatJSON["status"] === UP) { title = "UptimeKuma Monitor Up " + monitorJSON["name"]; } if (heartbeatJSON != null && heartbeatJSON["status"] === DOWN) { title = "UptimeKuma Monitor Down " + monitorJSON["name"]; } return title; } } module.exports = PushPlus;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/whapi.js
server/notification-providers/whapi.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Whapi extends NotificationProvider { name = "whapi"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer " + notification.whapiAuthToken, } }; config = this.getAxiosConfigWithProxy(config); let data = { "to": notification.whapiRecipient, "body": msg, }; let url = (notification.whapiApiUrl || "https://gate.whapi.cloud/").replace(/([^/])\/+$/, "$1") + "/messages/text"; await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Whapi;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/apprise.js
server/notification-providers/apprise.js
const NotificationProvider = require("./notification-provider"); const childProcessAsync = require("promisify-child-process"); class Apprise extends NotificationProvider { name = "apprise"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const args = [ "-vv", "-b", msg, notification.appriseURL ]; if (notification.title) { args.push("-t"); args.push(notification.title); } const s = await childProcessAsync.spawn("apprise", args, { encoding: "utf8", }); const output = (s.stdout) ? s.stdout.toString() : "ERROR: maybe apprise not found"; if (output) { if (! output.includes("ERROR")) { return okMsg; } throw new Error(output); } else { return "No output from apprise"; } } } module.exports = Apprise;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/squadcast.js
server/notification-providers/squadcast.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN } = require("../../src/util"); class Squadcast extends NotificationProvider { name = "squadcast"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = {}; let data = { message: msg, description: "", tags: {}, heartbeat: heartbeatJSON, source: "uptime-kuma" }; if (heartbeatJSON !== null) { data.description = heartbeatJSON["msg"]; data.event_id = heartbeatJSON["monitorID"]; if (heartbeatJSON["status"] === DOWN) { data.message = `${monitorJSON["name"]} is DOWN`; data.status = "trigger"; } else { data.message = `${monitorJSON["name"]} is UP`; data.status = "resolve"; } data.tags["AlertAddress"] = this.extractAddress(monitorJSON); monitorJSON["tags"].forEach(tag => { data.tags[tag["name"]] = { value: tag["value"] }; if (tag["color"] !== null) { data.tags[tag["name"]]["color"] = tag["color"]; } }); } config = this.getAxiosConfigWithProxy(config); await axios.post(notification.squadcastWebhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Squadcast;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/onesender.js
server/notification-providers/onesender.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Onesender extends NotificationProvider { name = "Onesender"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let data = { heartbeat: heartbeatJSON, monitor: monitorJSON, msg, to: notification.onesenderReceiver, type: "text", recipient_type: "individual", text: { body: msg } }; if (notification.onesenderTypeReceiver === "private") { data.to = notification.onesenderReceiver + "@s.whatsapp.net"; } else { data.recipient_type = "group"; data.to = notification.onesenderReceiver + "@g.us"; } let config = { headers: { "Authorization": "Bearer " + notification.onesenderToken, } }; config = this.getAxiosConfigWithProxy(config); await axios.post(notification.onesenderURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Onesender;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/rocket-chat.js
server/notification-providers/rocket-chat.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const Slack = require("./slack"); const { setting } = require("../util-server"); const { getMonitorRelativeURL, DOWN } = require("../../src/util"); class RocketChat extends NotificationProvider { name = "rocket.chat"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); if (heartbeatJSON == null) { let data = { "text": msg, "channel": notification.rocketchannel, "username": notification.rocketusername, "icon_emoji": notification.rocketiconemo, }; await axios.post(notification.rocketwebhookURL, data, config); return okMsg; } let data = { "text": "Uptime Kuma Alert", "channel": notification.rocketchannel, "username": notification.rocketusername, "icon_emoji": notification.rocketiconemo, "attachments": [ { "title": `Uptime Kuma Alert *Time (${heartbeatJSON["timezone"]})*\n${heartbeatJSON["localDateTime"]}`, "text": "*Message*\n" + msg, } ] }; // Color if (heartbeatJSON.status === DOWN) { data.attachments[0].color = "#ff0000"; } else { data.attachments[0].color = "#32cd32"; } if (notification.rocketbutton) { await Slack.deprecateURL(notification.rocketbutton); } const baseURL = await setting("primaryBaseURL"); if (baseURL) { data.attachments[0].title_link = baseURL + getMonitorRelativeURL(monitorJSON.id); } await axios.post(notification.rocketwebhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = RocketChat;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/smsir.js
server/notification-providers/smsir.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SMSIR extends NotificationProvider { name = "smsir"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api.sms.ir/v1/send/verify"; try { let config = { headers: { "Content-Type": "application/json", "Accept": "application/json", "X-API-Key": notification.smsirApiKey } }; config = this.getAxiosConfigWithProxy(config); const formattedMobiles = notification.smsirNumber .split(",") .map(mobile => { if (mobile.length === 11 && mobile.startsWith("09") && String(parseInt(mobile)) === mobile.substring(1)) { // 09xxxxxxxxx Format return mobile.substring(1); } return mobile; }); const MAX_MESSAGE_LENGTH = 20; // This is a limitation placed by SMSIR // Shorten By removing spaces, keeping context is better than cutting off the text // If that does not work, truncate. Still better than not receiving an SMS if (msg.length > MAX_MESSAGE_LENGTH) { msg = msg.replace(/\s/g, ""); } if (msg.length > MAX_MESSAGE_LENGTH) { msg = msg.substring(0, MAX_MESSAGE_LENGTH - 1 - "...".length) + "..."; } // Run multiple network requests at once const requestPromises = formattedMobiles .map(mobile => { axios.post( url, { mobile: mobile, templateId: parseInt(notification.smsirTemplate), parameters: [ { name: "uptkumaalert", value: msg } ] }, config ); }); await Promise.all(requestPromises); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SMSIR;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/bitrix24.js
server/notification-providers/bitrix24.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP } = require("../../src/util"); class Bitrix24 extends NotificationProvider { name = "Bitrix24"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { const params = { user_id: notification.bitrix24UserID, message: "[B]Uptime Kuma[/B]", "ATTACH[COLOR]": (heartbeatJSON ?? {})["status"] === UP ? "#b73419" : "#67b518", "ATTACH[BLOCKS][0][MESSAGE]": msg }; let config = this.getAxiosConfigWithProxy({ params }); await axios.get(`${notification.bitrix24WebhookURL}/im.notify.system.add.json`, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Bitrix24;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/call-me-bot.js
server/notification-providers/call-me-bot.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class CallMeBot extends NotificationProvider { name = "CallMeBot"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { const url = new URL(notification.callMeBotEndpoint); url.searchParams.set("text", msg); let config = this.getAxiosConfigWithProxy({}); await axios.get(url.toString(), config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = CallMeBot;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pushover.js
server/notification-providers/pushover.js
const { getMonitorRelativeURL } = require("../../src/util"); const { setting } = require("../util-server"); const { UP } = require("../../src/util"); const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Pushover extends NotificationProvider { name = "pushover"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api.pushover.net/1/messages.json"; let data = { "message": msg, "user": notification.pushoveruserkey, "token": notification.pushoverapptoken, "sound": notification.pushoversounds, "priority": notification.pushoverpriority, "title": notification.pushovertitle, "retry": "30", "expire": "3600", "html": 1, }; const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorJSON) { data["url"] = baseURL + getMonitorRelativeURL(monitorJSON.id); data["url_title"] = "Link to Monitor"; } if (notification.pushoverdevice) { data.device = notification.pushoverdevice; } if (notification.pushoverttl) { data.ttl = notification.pushoverttl; } try { let config = this.getAxiosConfigWithProxy({}); if (heartbeatJSON == null) { await axios.post(url, data, config); return okMsg; } if (heartbeatJSON.status === UP && notification.pushoversounds_up) { // default = DOWN => DOWN-sound is also played for non-UP/DOWN notiifcations data.sound = notification.pushoversounds_up; } data.message += `\n<b>Time (${heartbeatJSON["timezone"]})</b>: ${heartbeatJSON["localDateTime"]}`; await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Pushover;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/threema.js
server/notification-providers/threema.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Threema extends NotificationProvider { name = "threema"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const url = "https://msgapi.threema.ch/send_simple"; let config = { headers: { "Accept": "*/*", "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" } }; config = this.getAxiosConfigWithProxy(config); const data = { from: notification.threemaSenderIdentity, secret: notification.threemaSecret, text: msg }; switch (notification.threemaRecipientType) { case "identity": data.to = notification.threemaRecipient; break; case "phone": data.phone = notification.threemaRecipient; break; case "email": data.email = notification.threemaRecipient; break; default: throw new Error(`Unsupported recipient type: ${notification.threemaRecipientType}`); } try { await axios.post(url, new URLSearchParams(data), config); return "Threema notification sent successfully."; } catch (error) { const errorMessage = this.handleApiError(error); this.throwGeneralAxiosError(errorMessage); } } /** * Handle Threema API errors * @param {any} error The error to handle * @returns {string} Additional error context */ handleApiError(error) { if (!error.response) { return error.message; } switch (error.response.status) { case 400: return "Invalid recipient identity or account not set up for basic mode (400)."; case 401: return "Incorrect API identity or secret (401)."; case 402: return "No credits remaining (402)."; case 404: return "Recipient not found (404)."; case 413: return "Message is too long (413)."; case 500: return "Temporary internal server error (500)."; default: return error.message; } } } module.exports = Threema;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/brevo.js
server/notification-providers/brevo.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Brevo extends NotificationProvider { name = "Brevo"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { "Accept": "application/json", "Content-Type": "application/json", "api-key": notification.brevoApiKey, }, }; config = this.getAxiosConfigWithProxy(config); let to = [{ email: notification.brevoToEmail }]; let data = { sender: { email: notification.brevoFromEmail.trim(), name: notification.brevoFromName || "Uptime Kuma" }, to: to, subject: notification.brevoSubject || "Notification from Your Uptime Kuma", htmlContent: `<html><head></head><body><p>${msg.replace(/\n/g, "<br>")}</p></body></html>` }; if (notification.brevoCcEmail) { data.cc = notification.brevoCcEmail .split(",") .map((email) => ({ email: email.trim() })); } if (notification.brevoBccEmail) { data.bcc = notification.brevoBccEmail .split(",") .map((email) => ({ email: email.trim() })); } let result = await axios.post( "https://api.brevo.com/v3/smtp/email", data, config ); if (result.status === 201) { return okMsg; } else { throw new Error(`Unexpected status code: ${result.status}`); } } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Brevo;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/cellsynt.js
server/notification-providers/cellsynt.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Cellsynt extends NotificationProvider { name = "Cellsynt"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const data = { // docs at https://www.cellsynt.com/en/sms/api-integration params: { "username": notification.cellsyntLogin, "password": notification.cellsyntPassword, "destination": notification.cellsyntDestination, "text": msg.replace(/[^\x00-\x7F]/g, ""), "originatortype": notification.cellsyntOriginatortype, "originator": notification.cellsyntOriginator, "allowconcat": notification.cellsyntAllowLongSMS ? 6 : 1 } }; try { let config = this.getAxiosConfigWithProxy(data); const resp = await axios.post("https://se-1.cellsynt.net/sms.php", null, config); if (resp.data == null ) { throw new Error("Could not connect to Cellsynt, please try again."); } else if (resp.data.includes("Error:")) { resp.data = resp.data.replaceAll("Error:", ""); throw new Error(resp.data); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Cellsynt;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/waha.js
server/notification-providers/waha.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class WAHA extends NotificationProvider { name = "waha"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { "Accept": "application/json", "Content-Type": "application/json", "X-Api-Key": notification.wahaApiKey, } }; config = this.getAxiosConfigWithProxy(config); let data = { "session": notification.wahaSession, "chatId": notification.wahaChatId, "text": msg, }; let url = notification.wahaApiUrl.replace(/([^/])\/+$/, "$1") + "/api/sendText"; await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = WAHA;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/wpush.js
server/notification-providers/wpush.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class WPush extends NotificationProvider { name = "WPush"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { const context = { "title": this.checkStatus(heartbeatJSON, monitorJSON), "content": msg, "apikey": notification.wpushAPIkey, "channel": notification.wpushChannel }; let config = this.getAxiosConfigWithProxy({}); const result = await axios.post("https://api.wpush.cn/api/v1/send", context, config); if (result.data.code !== 0) { throw result.data.message; } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } /** * Get the formatted title for message * @param {?object} heartbeatJSON Heartbeat details (For Up/Down only) * @param {?object} monitorJSON Monitor details (For Up/Down only) * @returns {string} Formatted title */ checkStatus(heartbeatJSON, monitorJSON) { let title = "UptimeKuma Message"; if (heartbeatJSON != null && heartbeatJSON["status"] === UP) { title = "UptimeKuma Monitor Up " + monitorJSON["name"]; } if (heartbeatJSON != null && heartbeatJSON["status"] === DOWN) { title = "UptimeKuma Monitor Down " + monitorJSON["name"]; } return title; } } module.exports = WPush;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/line.js
server/notification-providers/line.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class Line extends NotificationProvider { name = "line"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api.line.me/v2/bot/message/push"; try { let config = { headers: { "Content-Type": "application/json", "Authorization": "Bearer " + notification.lineChannelAccessToken } }; config = this.getAxiosConfigWithProxy(config); if (heartbeatJSON == null) { let testMessage = { "to": notification.lineUserID, "messages": [ { "type": "text", "text": "Test Successful!" } ] }; await axios.post(url, testMessage, config); } else if (heartbeatJSON["status"] === DOWN) { let downMessage = { "to": notification.lineUserID, "messages": [ { "type": "text", "text": "UptimeKuma Alert: [πŸ”΄ Down]\n" + "Name: " + monitorJSON["name"] + " \n" + heartbeatJSON["msg"] + `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` } ] }; await axios.post(url, downMessage, config); } else if (heartbeatJSON["status"] === UP) { let upMessage = { "to": notification.lineUserID, "messages": [ { "type": "text", "text": "UptimeKuma Alert: [βœ… Up]\n" + "Name: " + monitorJSON["name"] + " \n" + heartbeatJSON["msg"] + `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` } ] }; await axios.post(url, upMessage, config); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Line;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/resend.js
server/notification-providers/resend.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Resend extends NotificationProvider { name = "Resend"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { Authorization: `Bearer ${notification.resendApiKey}`, "Content-Type": "application/json", }, }; config = this.getAxiosConfigWithProxy(config); const email = notification.resendFromEmail.trim(); const fromName = notification.resendFromName?.trim() || "Uptime Kuma"; let data = { from: `${fromName} <${email}>`, to: notification.resendToEmail, subject: notification.resendSubject || "Notification from Your Uptime Kuma", // supplied text directly instead of html text: msg, }; let result = await axios.post( "https://api.resend.com/emails", data, config ); if (result.status === 200) { return okMsg; } else { throw new Error(`Unexpected status code: ${result.status}`); } } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Resend;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/signl4.js
server/notification-providers/signl4.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP, DOWN } = require("../../src/util"); class SIGNL4 extends NotificationProvider { name = "SIGNL4"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let data = { heartbeat: heartbeatJSON, monitor: monitorJSON, msg, // Source system "X-S4-SourceSystem": "UptimeKuma", monitorUrl: this.extractAddress(monitorJSON), }; let config = { headers: { "Content-Type": "application/json" } }; config = this.getAxiosConfigWithProxy(config); if (heartbeatJSON == null) { // Test alert data.title = "Uptime Kuma Alert"; data.message = msg; } else if (heartbeatJSON.status === UP) { data.title = "Uptime Kuma Monitor βœ… Up"; data["X-S4-ExternalID"] = "UptimeKuma-" + monitorJSON.monitorID; data["X-S4-Status"] = "resolved"; } else if (heartbeatJSON.status === DOWN) { data.title = "Uptime Kuma Monitor πŸ”΄ Down"; data["X-S4-ExternalID"] = "UptimeKuma-" + monitorJSON.monitorID; data["X-S4-Status"] = "new"; } await axios.post(notification.webhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SIGNL4;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/zoho-cliq.js
server/notification-providers/zoho-cliq.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class ZohoCliq extends NotificationProvider { name = "ZohoCliq"; /** * Generate the message to send * @param {const} status The status constant * @param {string} monitorName Name of monitor * @returns {string} Status message */ _statusMessageFactory = (status, monitorName) => { if (status === DOWN) { return `πŸ”΄ [${monitorName}] went down\n`; } else if (status === UP) { return `### βœ… [${monitorName}] is back online\n`; } return "Notification\n"; }; /** * Send the notification * @param {string} webhookUrl URL to send the request to * @param {Array} payload Payload generated by _notificationPayloadFactory * @returns {Promise<void>} */ _sendNotification = async (webhookUrl, payload) => { let config = this.getAxiosConfigWithProxy({}); await axios.post(webhookUrl, { text: payload.join("\n") }, config); }; /** * Generate payload for notification * @param {object} args Method arguments * @param {const} args.status The status of the monitor * @param {string} args.monitorMessage Message to send * @param {string} args.monitorName Name of monitor affected * @param {string} args.monitorUrl URL of monitor affected * @returns {Array} Notification payload */ _notificationPayloadFactory = ({ status, monitorMessage, monitorName, monitorUrl, }) => { const payload = []; payload.push(this._statusMessageFactory(status, monitorName)); payload.push(`*Description:* ${monitorMessage}`); if (monitorUrl && monitorUrl !== "https://") { payload.push(`*URL:* ${monitorUrl}`); } return payload; }; /** * Send a general notification * @param {string} webhookUrl URL to send request to * @param {string} msg Message to send * @returns {Promise<void>} */ _handleGeneralNotification = (webhookUrl, msg) => { const payload = this._notificationPayloadFactory({ monitorMessage: msg }); return this._sendNotification(webhookUrl, payload); }; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { if (heartbeatJSON == null) { await this._handleGeneralNotification(notification.webhookUrl, msg); return okMsg; } const payload = this._notificationPayloadFactory({ monitorMessage: heartbeatJSON.msg, monitorName: monitorJSON.name, monitorUrl: this.extractAddress(monitorJSON), status: heartbeatJSON.status }); await this._sendNotification(notification.webhookUrl, payload); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = ZohoCliq;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/bale.js
server/notification-providers/bale.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Bale extends NotificationProvider { name = "bale"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://tapi.bale.ai"; try { await axios.post( `${url}/bot${notification.baleBotToken}/sendMessage`, { chat_id: notification.baleChatID, text: msg }, { headers: { "content-type": "application/json", }, } ); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Bale;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/alerta.js
server/notification-providers/alerta.js
const NotificationProvider = require("./notification-provider"); const { DOWN, UP } = require("../../src/util"); const axios = require("axios"); class Alerta extends NotificationProvider { name = "alerta"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { "Content-Type": "application/json;charset=UTF-8", "Authorization": "Key " + notification.alertaApiKey, } }; let data = { environment: notification.alertaEnvironment, severity: "critical", correlate: [], service: [ "UptimeKuma" ], value: "Timeout", tags: [ "uptimekuma" ], attributes: {}, origin: "uptimekuma", type: "exceptionAlert", }; config = this.getAxiosConfigWithProxy(config); if (heartbeatJSON == null) { let postData = Object.assign({ event: "msg", text: msg, group: "uptimekuma-msg", resource: "Message", }, data); await axios.post(notification.alertaApiEndpoint, postData, config); } else { let datadup = Object.assign( { correlate: [ "service_up", "service_down" ], event: monitorJSON["type"], group: "uptimekuma-" + monitorJSON["type"], resource: monitorJSON["name"], }, data ); if (heartbeatJSON["status"] === DOWN) { datadup.severity = notification.alertaAlertState; // critical datadup.text = "Service " + monitorJSON["type"] + " is down."; await axios.post(notification.alertaApiEndpoint, datadup, config); } else if (heartbeatJSON["status"] === UP) { datadup.severity = notification.alertaRecoverState; // cleaned datadup.text = "Service " + monitorJSON["type"] + " is up."; await axios.post(notification.alertaApiEndpoint, datadup, config); } } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Alerta;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/opsgenie.js
server/notification-providers/opsgenie.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { UP, DOWN } = require("../../src/util"); const opsgenieAlertsUrlEU = "https://api.eu.opsgenie.com/v2/alerts"; const opsgenieAlertsUrlUS = "https://api.opsgenie.com/v2/alerts"; const okMsg = "Sent Successfully."; class Opsgenie extends NotificationProvider { name = "Opsgenie"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { let opsgenieAlertsUrl; let priority = (!notification.opsgeniePriority) ? 3 : notification.opsgeniePriority; const textMsg = "Uptime Kuma Alert"; try { switch (notification.opsgenieRegion) { case "us": opsgenieAlertsUrl = opsgenieAlertsUrlUS; break; case "eu": opsgenieAlertsUrl = opsgenieAlertsUrlEU; break; default: opsgenieAlertsUrl = opsgenieAlertsUrlUS; } if (heartbeatJSON == null) { let notificationTestAlias = "uptime-kuma-notification-test"; let data = { "message": msg, "alias": notificationTestAlias, "source": "Uptime Kuma", "priority": "P5" }; return this.post(notification, opsgenieAlertsUrl, data); } if (heartbeatJSON.status === DOWN) { let data = { "message": monitorJSON ? textMsg + `: ${monitorJSON.name}` : textMsg, "alias": monitorJSON.name, "description": msg, "source": "Uptime Kuma", "priority": `P${priority}` }; return this.post(notification, opsgenieAlertsUrl, data); } if (heartbeatJSON.status === UP) { let opsgenieAlertsCloseUrl = `${opsgenieAlertsUrl}/${encodeURIComponent(monitorJSON.name)}/close?identifierType=alias`; let data = { "source": "Uptime Kuma", }; return this.post(notification, opsgenieAlertsCloseUrl, data); } } catch (error) { this.throwGeneralAxiosError(error); } } /** * Make POST request to Opsgenie * @param {BeanModel} notification Notification to send * @param {string} url Request url * @param {object} data Request body * @returns {Promise<string>} Success message */ async post(notification, url, data) { let config = { headers: { "Content-Type": "application/json", "Authorization": `GenieKey ${notification.opsgenieApiKey}`, } }; config = this.getAxiosConfigWithProxy(config); let res = await axios.post(url, data, config); if (res.status == null) { return "Opsgenie notification failed with invalid response!"; } if (res.status < 200 || res.status >= 300) { return `Opsgenie notification failed with status code ${res.status}`; } return okMsg; } } module.exports = Opsgenie;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/evolution.js
server/notification-providers/evolution.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Evolution extends NotificationProvider { name = "evolution"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = { headers: { "Accept": "application/json", "Content-Type": "application/json", "apikey": notification.evolutionAuthToken, } }; config = this.getAxiosConfigWithProxy(config); let data = { "number": notification.evolutionRecipient, "text": msg, }; let url = (notification.evolutionApiUrl || "https://evolapicloud.com/").replace(/([^/])\/+$/, "$1") + "/message/sendText/" + encodeURIComponent(notification.evolutionInstanceName); await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Evolution;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/bark.js
server/notification-providers/bark.js
// // bark.js // UptimeKuma // // Created by Lakr Aream on 2021/10/24. // Copyright Β© 2021 Lakr Aream. All rights reserved. // const NotificationProvider = require("./notification-provider"); const { DOWN, UP } = require("../../src/util"); const { default: axios } = require("axios"); // bark is an APN bridge that sends notifications to Apple devices. const barkNotificationAvatar = "https://github.com/louislam/uptime-kuma/raw/master/public/icon.png"; const successMessage = "Successes!"; class Bark extends NotificationProvider { name = "Bark"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { let barkEndpoint = notification.barkEndpoint; // check if the endpoint has a "/" suffix, if so, delete it first if (barkEndpoint.endsWith("/")) { barkEndpoint = barkEndpoint.substring(0, barkEndpoint.length - 1); } if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] === UP) { let title = "UptimeKuma Monitor Up"; return await this.postNotification(notification, title, msg, barkEndpoint); } if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] === DOWN) { let title = "UptimeKuma Monitor Down"; return await this.postNotification(notification, title, msg, barkEndpoint); } if (msg != null) { let title = "UptimeKuma Message"; return await this.postNotification(notification, title, msg, barkEndpoint); } } /** * Add additional parameter for Bark v1 endpoints. * Leads to better on device styles (iOS 15 optimized) * @param {BeanModel} notification Notification to send * @returns {string} Additional URL parameters */ additionalParameters(notification) { // set icon to uptime kuma icon, 11kb should be fine let params = "?icon=" + barkNotificationAvatar; // grouping all our notifications if (notification.barkGroup != null) { params += "&group=" + notification.barkGroup; } else { // default name params += "&group=" + "UptimeKuma"; } // picked a sound, this should follow system's mute status when arrival if (notification.barkSound != null) { params += "&sound=" + notification.barkSound; } else { // default sound params += "&sound=" + "telegraph"; } return params; } /** * Check if result is successful * @param {object} result Axios response object * @returns {void} * @throws {Error} The status code is not in range 2xx */ checkResult(result) { if (result.status == null) { throw new Error("Bark notification failed with invalid response!"); } if (result.status < 200 || result.status >= 300) { throw new Error("Bark notification failed with status code " + result.status); } } /** * Send the message * @param {BeanModel} notification Notification to send * @param {string} title Message title * @param {string} subtitle Message * @param {string} endpoint Endpoint to send request to * @returns {Promise<string>} Success message */ async postNotification(notification, title, subtitle, endpoint) { let result; let config = this.getAxiosConfigWithProxy({}); if (notification.apiVersion === "v1" || notification.apiVersion == null) { // url encode title and subtitle title = encodeURIComponent(title); subtitle = encodeURIComponent(subtitle); const params = this.additionalParameters(notification); result = await axios.get(`${endpoint}/${title}/${subtitle}${params}`, config); } else { result = await axios.post(endpoint, { title, body: subtitle, icon: barkNotificationAvatar, sound: notification.barkSound || "telegraph", // default sound is telegraph group: notification.barkGroup || "UptimeKuma", // default group is UptimeKuma }, config); } this.checkResult(result); if (result.statusText != null) { return "Bark notification succeed: " + result.statusText; } // because returned in range 200 ..< 300 return successMessage; } } module.exports = Bark;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/yzj.js
server/notification-providers/yzj.js
const NotificationProvider = require("./notification-provider"); const { DOWN, UP } = require("../../src/util"); const { default: axios } = require("axios"); class YZJ extends NotificationProvider { name = "YZJ"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { let okMsg = "Sent Successfully."; try { if (heartbeatJSON !== null) { msg = `${this.statusToString(heartbeatJSON["status"])} ${monitorJSON["name"]} \n> ${heartbeatJSON["msg"]}\n> Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`; } let config = { headers: { "Content-Type": "application/json", }, }; const params = { content: msg }; // yzjtype=0 => general robot const url = `${notification.yzjWebHookUrl}?yzjtype=0&yzjtoken=${notification.yzjToken}`; config = this.getAxiosConfigWithProxy(config); const result = await axios.post(url, params, config); if (!result.data?.success) { throw new Error(result.data?.errmsg ?? "yzj's server did not respond with the expected result"); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } /** * Convert status constant to string * @param {string} status The status constant * @returns {string} status */ statusToString(status) { switch (status) { case DOWN: return "❌"; case UP: return "βœ…"; default: return status; } } } module.exports = YZJ;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/octopush.js
server/notification-providers/octopush.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Octopush extends NotificationProvider { name = "octopush"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const urlV2 = "https://api.octopush.com/v1/public/sms-campaign/send"; const urlV1 = "https://www.octopush-dm.com/api/sms/json"; try { // Default - V2 if (notification.octopushVersion === "2" || !notification.octopushVersion) { let config = { headers: { "api-key": notification.octopushAPIKey, "api-login": notification.octopushLogin, "cache-control": "no-cache" } }; config = this.getAxiosConfigWithProxy(config); let data = { "recipients": [ { "phone_number": notification.octopushPhoneNumber } ], //octopush not supporting non ascii char "text": msg.replace(/[^\x00-\x7F]/g, ""), "type": notification.octopushSMSType, "purpose": "alert", "sender": notification.octopushSenderName }; await axios.post(urlV2, data, config); } else if (notification.octopushVersion === "1") { let data = { "user_login": notification.octopushDMLogin, "api_key": notification.octopushDMAPIKey, "sms_recipients": notification.octopushDMPhoneNumber, "sms_sender": notification.octopushDMSenderName, "sms_type": (notification.octopushDMSMSType === "sms_premium") ? "FR" : "XXX", "transactional": "1", //octopush not supporting non ascii char "sms_text": msg.replace(/[^\x00-\x7F]/g, ""), }; let config = { headers: { "cache-control": "no-cache" }, params: data }; config = this.getAxiosConfigWithProxy(config); // V1 API returns 200 even on error so we must check // response data let response = await axios.post(urlV1, {}, config); if ("error_code" in response.data) { if (response.data.error_code !== "000") { this.throwGeneralAxiosError(`Octopush error ${JSON.stringify(response.data)}`); } } } else { throw new Error("Unknown Octopush version!"); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Octopush;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/notification-provider.js
server/notification-providers/notification-provider.js
const { Liquid } = require("liquidjs"); const { DOWN } = require("../../src/util"); const { HttpProxyAgent } = require("http-proxy-agent"); const { HttpsProxyAgent } = require("https-proxy-agent"); class NotificationProvider { /** * Notification Provider Name * @type {string} */ name = undefined; /** * Send a notification * @param {BeanModel} notification Notification to send * @param {string} msg General Message * @param {?object} monitorJSON Monitor details (For Up/Down only) * @param {?object} heartbeatJSON Heartbeat details (For Up/Down only) * @returns {Promise<string>} Return Successful Message * @throws Error with fail msg */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { throw new Error("Have to override Notification.send(...)"); } /** * Extracts the address from a monitor JSON object based on its type. * @param {?object} monitorJSON Monitor details (For Up/Down only) * @returns {string} The extracted address based on the monitor type. */ extractAddress(monitorJSON) { if (!monitorJSON) { return ""; } switch (monitorJSON["type"]) { case "push": return "Heartbeat"; case "ping": return monitorJSON["hostname"]; case "port": case "dns": case "gamedig": case "steam": if (monitorJSON["port"]) { return monitorJSON["hostname"] + ":" + monitorJSON["port"]; } return monitorJSON["hostname"]; default: if (![ "https://", "http://", "" ].includes(monitorJSON["url"])) { return monitorJSON["url"]; } return ""; } } /** * Renders a message template with notification context * @param {string} template the template * @param {string} msg the message that will be included in the context * @param {?object} monitorJSON Monitor details (For Up/Down/Cert-Expiry only) * @param {?object} heartbeatJSON Heartbeat details (For Up/Down only) * @returns {Promise<string>} rendered template */ async renderTemplate(template, msg, monitorJSON, heartbeatJSON) { const engine = new Liquid({ root: "./no-such-directory-uptime-kuma", relativeReference: false, dynamicPartials: false, }); const parsedTpl = engine.parse(template); // Let's start with dummy values to simplify code let monitorName = "Monitor Name not available"; let monitorHostnameOrURL = "testing.hostname"; if (monitorJSON !== null) { monitorName = monitorJSON["name"]; monitorHostnameOrURL = this.extractAddress(monitorJSON); } let serviceStatus = "⚠️ Test"; if (heartbeatJSON !== null) { serviceStatus = (heartbeatJSON["status"] === DOWN) ? "πŸ”΄ Down" : "βœ… Up"; } const context = { // for v1 compatibility, to be removed in v3 "STATUS": serviceStatus, "NAME": monitorName, "HOSTNAME_OR_URL": monitorHostnameOrURL, // variables which are officially supported "status": serviceStatus, "name": monitorName, "hostnameOrURL": monitorHostnameOrURL, monitorJSON, heartbeatJSON, msg, }; return engine.render(parsedTpl, context); } /** * Throws an error * @param {any} error The error to throw * @returns {void} * @throws {any} The error specified */ throwGeneralAxiosError(error) { let msg = "Error: " + error + " "; if (error.response && error.response.data) { if (typeof error.response.data === "string") { msg += error.response.data; } else { msg += JSON.stringify(error.response.data); } } throw new Error(msg); } /** * Returns axios config with proxy agent if proxy env is set. * @param {object} axiosConfig - Axios config containing params * @returns {object} Axios config */ getAxiosConfigWithProxy(axiosConfig = {}) { const proxyEnv = process.env.notification_proxy || process.env.NOTIFICATION_PROXY; if (proxyEnv) { const proxyUrl = new URL(proxyEnv); if (proxyUrl.protocol === "http:") { axiosConfig.httpAgent = new HttpProxyAgent(proxyEnv); axiosConfig.httpsAgent = new HttpsProxyAgent(proxyEnv); } else if (proxyUrl.protocol === "https:") { const agent = new HttpsProxyAgent(proxyEnv); axiosConfig.httpAgent = agent; axiosConfig.httpsAgent = agent; } axiosConfig.proxy = false; } return axiosConfig; } } module.exports = NotificationProvider;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/clicksendsms.js
server/notification-providers/clicksendsms.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class ClickSendSMS extends NotificationProvider { name = "clicksendsms"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://rest.clicksend.com/v3/sms/send"; try { let config = { headers: { "Content-Type": "application/json", "Authorization": "Basic " + Buffer.from(notification.clicksendsmsLogin + ":" + notification.clicksendsmsPassword).toString("base64"), "Accept": "text/json", } }; let data = { messages: [ { "body": msg.replace(/[^\x00-\x7F]/g, ""), "to": notification.clicksendsmsToNumber, "source": "uptime-kuma", "from": notification.clicksendsmsSenderName, } ] }; config = this.getAxiosConfigWithProxy(config); let resp = await axios.post(url, data, config); if (resp.data.data.messages[0].status !== "SUCCESS") { let error = "Something gone wrong. Api returned " + resp.data.data.messages[0].status + "."; this.throwGeneralAxiosError(error); } return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = ClickSendSMS;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/twilio.js
server/notification-providers/twilio.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Twilio extends NotificationProvider { name = "twilio"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; let apiKey = notification.twilioApiKey ? notification.twilioApiKey : notification.twilioAccountSID; try { let config = { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8", "Authorization": "Basic " + Buffer.from(apiKey + ":" + notification.twilioAuthToken).toString("base64"), } }; config = this.getAxiosConfigWithProxy(config); let data = new URLSearchParams(); data.append("To", notification.twilioToNumber); data.append("From", notification.twilioFromNumber); data.append("Body", msg); if (notification.twilioMessagingServiceSID) { data.append("MessagingServiceSid", notification.twilioMessagingServiceSID); } await axios.post(`https://api.twilio.com/2010-04-01/Accounts/${(notification.twilioAccountSID)}/Messages.json`, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Twilio;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/pushy.js
server/notification-providers/pushy.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Pushy extends NotificationProvider { name = "pushy"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); await axios.post(`https://api.pushy.me/push?api_key=${notification.pushyAPIKey}`, { "to": notification.pushyToken, "data": { "message": "Uptime-Kuma" }, "notification": { "body": msg, "badge": 1, "sound": "ping.aiff" } }, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Pushy;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/smseagle.js
server/notification-providers/smseagle.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SMSEagle extends NotificationProvider { name = "SMSEagle"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { if (notification.smseagleApiType === "smseagle-apiv1") { // according to https://www.smseagle.eu/apiv1/ let config = { headers: { "Content-Type": "application/x-www-form-urlencoded", } }; config = this.getAxiosConfigWithProxy(config); let sendMethod; let recipientType; let duration; let voiceId; if (notification.smseagleRecipientType === "smseagle-contact") { recipientType = "contactname"; sendMethod = "/send_tocontact"; } else if (notification.smseagleRecipientType === "smseagle-group") { recipientType = "groupname"; sendMethod = "/send_togroup"; } else if (notification.smseagleRecipientType === "smseagle-to") { recipientType = "to"; sendMethod = "/send_sms"; if (notification.smseagleMsgType !== "smseagle-sms") { duration = notification.smseagleDuration ?? 10; if (notification.smseagleMsgType === "smseagle-ring") { sendMethod = "/ring_call"; } else if (notification.smseagleMsgType === "smseagle-tts") { sendMethod = "/tts_call"; } else if (notification.smseagleMsgType === "smseagle-tts-advanced") { sendMethod = "/tts_adv_call"; voiceId = notification.smseagleTtsModel ? notification.smseagleTtsModel : 1; } } } const url = new URL(notification.smseagleUrl + "/http_api" + sendMethod); url.searchParams.append("access_token", notification.smseagleToken); url.searchParams.append(recipientType, notification.smseagleRecipient); if (!notification.smseagleRecipientType || notification.smseagleRecipientType === "smseagle-sms") { url.searchParams.append("unicode", (notification.smseagleEncoding) ? "1" : "0"); url.searchParams.append("highpriority", notification.smseaglePriority ?? "0"); } else { url.searchParams.append("duration", duration); } if (notification.smseagleRecipientType !== "smseagle-ring") { url.searchParams.append("message", msg); } if (voiceId) { url.searchParams.append("voice_id", voiceId); } let resp = await axios.get(url.toString(), config); if (resp.data.indexOf("OK") === -1) { let error = `SMSEagle API returned error: ${resp.data}`; throw new Error(error); } return okMsg; } else if (notification.smseagleApiType === "smseagle-apiv2") { // according to https://www.smseagle.eu/docs/apiv2/ let config = { headers: { "access-token": notification.smseagleToken, "Content-Type": "application/json", } }; config = this.getAxiosConfigWithProxy(config); let encoding = (notification.smseagleEncoding) ? "unicode" : "standard"; let priority = (notification.smseaglePriority) ?? 0; let postData = { text: msg, encoding: encoding, priority: priority }; if (notification.smseagleRecipientContact) { postData["contacts"] = notification.smseagleRecipientContact.split(",").map(Number); } if (notification.smseagleRecipientGroup) { postData["groups"] = notification.smseagleRecipientGroup.split(",").map(Number); } if (notification.smseagleRecipientTo) { postData["to"] = notification.smseagleRecipientTo.split(","); } let endpoint = "/messages/sms"; if (notification.smseagleMsgType !== "smseagle-sms") { postData["duration"] = notification.smseagleDuration ?? 10; if (notification.smseagleMsgType === "smseagle-ring") { endpoint = "/calls/ring"; } else if (notification.smseagleMsgType === "smseagle-tts") { endpoint = "/calls/tts"; } else if (notification.smseagleMsgType === "smseagle-tts-advanced") { endpoint = "/calls/tts_advanced"; postData["voice_id"] = notification.smseagleTtsModel ?? 1; } } let resp = await axios.post(notification.smseagleUrl + "/api/v2" + endpoint, postData, config); const queuedCount = resp.data.filter(x => x.status === "queued").length; const unqueuedCount = resp.data.length - queuedCount; if (resp.status !== 200 || queuedCount === 0) { if (!resp.data.length) { throw new Error("SMSEagle API returned an empty response"); } throw new Error(`SMSEagle API returned error: ${JSON.stringify(resp.data)}`); } if (unqueuedCount) { return `Sent ${queuedCount}/${resp.data.length} Messages Successfully.`; } return okMsg; } } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SMSEagle;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/smtp.js
server/notification-providers/smtp.js
const nodemailer = require("nodemailer"); const NotificationProvider = require("./notification-provider"); class SMTP extends NotificationProvider { name = "smtp"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const config = { host: notification.smtpHost, port: notification.smtpPort, secure: notification.smtpSecure, tls: { rejectUnauthorized: !notification.smtpIgnoreTLSError || false, } }; // Fix #1129 if (notification.smtpDkimDomain) { config.dkim = { domainName: notification.smtpDkimDomain, keySelector: notification.smtpDkimKeySelector, privateKey: notification.smtpDkimPrivateKey, hashAlgo: notification.smtpDkimHashAlgo, headerFieldNames: notification.smtpDkimheaderFieldNames, skipFields: notification.smtpDkimskipFields, }; } // Should fix the issue in https://github.com/louislam/uptime-kuma/issues/26#issuecomment-896373904 if (notification.smtpUsername || notification.smtpPassword) { config.auth = { user: notification.smtpUsername, pass: notification.smtpPassword, }; } // default values in case the user does not want to template let subject = msg; let body = msg; let useHTMLBody = false; if (heartbeatJSON) { body = `${msg}\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`; } // subject and body are templated if ((monitorJSON && heartbeatJSON) || msg.endsWith("Testing")) { // cannot end with whitespace as this often raises spam scores const customSubject = notification.customSubject?.trim() || ""; const customBody = notification.customBody?.trim() || ""; if (customSubject !== "") { subject = await this.renderTemplate(customSubject, msg, monitorJSON, heartbeatJSON); } if (customBody !== "") { useHTMLBody = notification.htmlBody || false; body = await this.renderTemplate(customBody, msg, monitorJSON, heartbeatJSON); } } // send mail with defined transport object let transporter = nodemailer.createTransport(config); await transporter.sendMail({ from: notification.smtpFrom, cc: notification.smtpCC, bcc: notification.smtpBCC, to: notification.smtpTo, subject: subject, // If the email body is custom, and the user wants it, set the email body as HTML [useHTMLBody ? "html" : "text"]: body }); return okMsg; } } module.exports = SMTP;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/feishu.js
server/notification-providers/feishu.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { DOWN, UP } = require("../../src/util"); class Feishu extends NotificationProvider { name = "Feishu"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let config = this.getAxiosConfigWithProxy({}); if (heartbeatJSON == null) { let testdata = { msg_type: "text", content: { text: msg, }, }; await axios.post(notification.feishuWebHookUrl, testdata, config); return okMsg; } if (heartbeatJSON["status"] === DOWN) { let downdata = { msg_type: "interactive", card: { config: { update_multi: false, wide_screen_mode: true, }, header: { title: { tag: "plain_text", content: "UptimeKuma Alert: [Down] " + monitorJSON["name"], }, template: "red", }, elements: [ { tag: "div", text: { tag: "lark_md", content: getContent(heartbeatJSON), }, } ] } }; await axios.post(notification.feishuWebHookUrl, downdata, config); return okMsg; } if (heartbeatJSON["status"] === UP) { let updata = { msg_type: "interactive", card: { config: { update_multi: false, wide_screen_mode: true, }, header: { title: { tag: "plain_text", content: "UptimeKuma Alert: [UP] " + monitorJSON["name"], }, template: "green", }, elements: [ { tag: "div", text: { tag: "lark_md", content: getContent(heartbeatJSON), }, }, ] } }; await axios.post(notification.feishuWebHookUrl, updata, config); return okMsg; } } catch (error) { this.throwGeneralAxiosError(error); } } } /** * Get content * @param {?object} heartbeatJSON Heartbeat details (For Up/Down only) * @returns {string} Return Successful Message */ function getContent(heartbeatJSON) { return [ "**Message**: " + heartbeatJSON["msg"], "**Ping**: " + (heartbeatJSON["ping"] == null ? "N/A" : heartbeatJSON["ping"] + " ms"), `**Time (${heartbeatJSON["timezone"]})**: ${heartbeatJSON["localDateTime"]}` ].join("\n"); } module.exports = Feishu;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/cloudflared-socket-handler.js
server/socket-handlers/cloudflared-socket-handler.js
const { checkLogin, setSetting, setting, doubleCheckPassword } = require("../util-server"); const { CloudflaredTunnel } = require("node-cloudflared-tunnel"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const { log } = require("../../src/util"); const io = UptimeKumaServer.getInstance().io; const prefix = "cloudflared_"; const cloudflared = new CloudflaredTunnel(); /** * Change running state * @param {string} running Is it running? * @param {string} message Message to pass * @returns {void} */ cloudflared.change = (running, message) => { io.to("cloudflared").emit(prefix + "running", running); io.to("cloudflared").emit(prefix + "message", message); }; /** * Emit an error message * @param {string} errorMessage Error message to send * @returns {void} */ cloudflared.error = (errorMessage) => { io.to("cloudflared").emit(prefix + "errorMessage", errorMessage); }; /** * Handler for cloudflared * @param {Socket} socket Socket.io instance * @returns {void} */ module.exports.cloudflaredSocketHandler = (socket) => { socket.on(prefix + "join", async () => { try { checkLogin(socket); socket.join("cloudflared"); io.to(socket.userID).emit(prefix + "installed", cloudflared.checkInstalled()); io.to(socket.userID).emit(prefix + "running", cloudflared.running); io.to(socket.userID).emit(prefix + "token", await setting("cloudflaredTunnelToken")); } catch (error) { } }); socket.on(prefix + "leave", async () => { try { checkLogin(socket); socket.leave("cloudflared"); } catch (error) { } }); socket.on(prefix + "start", async (token) => { try { checkLogin(socket); if (token && typeof token === "string") { await setSetting("cloudflaredTunnelToken", token); cloudflared.token = token; } else { cloudflared.token = null; } cloudflared.start(); } catch (error) { } }); socket.on(prefix + "stop", async (currentPassword, callback) => { try { checkLogin(socket); const disabledAuth = await setting("disableAuth"); if (!disabledAuth) { await doubleCheckPassword(socket, currentPassword); } cloudflared.stop(); } catch (error) { callback({ ok: false, msg: error.message, }); } }); socket.on(prefix + "removeToken", async () => { try { checkLogin(socket); await setSetting("cloudflaredTunnelToken", ""); } catch (error) { } }); }; /** * Automatically start cloudflared * @param {string} token Cloudflared tunnel token * @returns {Promise<void>} */ module.exports.autoStart = async (token) => { if (!token) { token = await setting("cloudflaredTunnelToken"); } else { // Override the current token via args or env var await setSetting("cloudflaredTunnelToken", token); console.log("Use cloudflared token from args or env var"); } if (token) { console.log("Start cloudflared"); cloudflared.token = token; cloudflared.start(); } }; /** * Stop cloudflared * @returns {Promise<void>} */ module.exports.stop = async () => { log.info("cloudflared", "Stop cloudflared"); if (cloudflared) { cloudflared.stop(); } };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/maintenance-socket-handler.js
server/socket-handlers/maintenance-socket-handler.js
const { checkLogin } = require("../util-server"); const { log } = require("../../src/util"); const { R } = require("redbean-node"); const apicache = require("../modules/apicache"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const Maintenance = require("../model/maintenance"); const server = UptimeKumaServer.getInstance(); /** * Handlers for Maintenance * @param {Socket} socket Socket.io instance * @returns {void} */ module.exports.maintenanceSocketHandler = (socket) => { // Add a new maintenance socket.on("addMaintenance", async (maintenance, callback) => { try { checkLogin(socket); log.debug("maintenance", maintenance); let bean = await Maintenance.jsonToBean(R.dispense("maintenance"), maintenance); bean.user_id = socket.userID; let maintenanceID = await R.store(bean); server.maintenanceList[maintenanceID] = bean; await bean.run(true); await server.sendMaintenanceList(socket); callback({ ok: true, msg: "successAdded", msgi18n: true, maintenanceID, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); // Edit a maintenance socket.on("editMaintenance", async (maintenance, callback) => { try { checkLogin(socket); let bean = server.getMaintenance(maintenance.id); if (bean.user_id !== socket.userID) { throw new Error("Permission denied."); } await Maintenance.jsonToBean(bean, maintenance); await R.store(bean); await bean.run(true); await server.sendMaintenanceList(socket); callback({ ok: true, msg: "Saved.", msgi18n: true, maintenanceID: bean.id, }); } catch (e) { console.error(e); callback({ ok: false, msg: e.message, }); } }); // Add a new monitor_maintenance socket.on("addMonitorMaintenance", async (maintenanceID, monitors, callback) => { try { checkLogin(socket); await R.exec("DELETE FROM monitor_maintenance WHERE maintenance_id = ?", [ maintenanceID ]); for await (const monitor of monitors) { let bean = R.dispense("monitor_maintenance"); bean.import({ monitor_id: monitor.id, maintenance_id: maintenanceID }); await R.store(bean); } apicache.clear(); callback({ ok: true, msg: "successAdded", msgi18n: true, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); // Add a new monitor_maintenance socket.on("addMaintenanceStatusPage", async (maintenanceID, statusPages, callback) => { try { checkLogin(socket); await R.exec("DELETE FROM maintenance_status_page WHERE maintenance_id = ?", [ maintenanceID ]); for await (const statusPage of statusPages) { let bean = R.dispense("maintenance_status_page"); bean.import({ status_page_id: statusPage.id, maintenance_id: maintenanceID }); await R.store(bean); } apicache.clear(); callback({ ok: true, msg: "successAdded", msgi18n: true, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("getMaintenance", async (maintenanceID, callback) => { try { checkLogin(socket); log.debug("maintenance", `Get Maintenance: ${maintenanceID} User ID: ${socket.userID}`); let bean = await R.findOne("maintenance", " id = ? AND user_id = ? ", [ maintenanceID, socket.userID, ]); callback({ ok: true, maintenance: await bean.toJSON(), }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("getMaintenanceList", async (callback) => { try { checkLogin(socket); await server.sendMaintenanceList(socket); callback({ ok: true, }); } catch (e) { console.error(e); callback({ ok: false, msg: e.message, }); } }); socket.on("getMonitorMaintenance", async (maintenanceID, callback) => { try { checkLogin(socket); log.debug("maintenance", `Get Monitors for Maintenance: ${maintenanceID} User ID: ${socket.userID}`); let monitors = await R.getAll("SELECT monitor.id FROM monitor_maintenance mm JOIN monitor ON mm.monitor_id = monitor.id WHERE mm.maintenance_id = ? ", [ maintenanceID, ]); callback({ ok: true, monitors, }); } catch (e) { console.error(e); callback({ ok: false, msg: e.message, }); } }); socket.on("getMaintenanceStatusPage", async (maintenanceID, callback) => { try { checkLogin(socket); log.debug("maintenance", `Get Status Pages for Maintenance: ${maintenanceID} User ID: ${socket.userID}`); let statusPages = await R.getAll("SELECT status_page.id, status_page.title FROM maintenance_status_page msp JOIN status_page ON msp.status_page_id = status_page.id WHERE msp.maintenance_id = ? ", [ maintenanceID, ]); callback({ ok: true, statusPages, }); } catch (e) { console.error(e); callback({ ok: false, msg: e.message, }); } }); socket.on("deleteMaintenance", async (maintenanceID, callback) => { try { checkLogin(socket); log.debug("maintenance", `Delete Maintenance: ${maintenanceID} User ID: ${socket.userID}`); if (maintenanceID in server.maintenanceList) { server.maintenanceList[maintenanceID].stop(); delete server.maintenanceList[maintenanceID]; } await R.exec("DELETE FROM maintenance WHERE id = ? AND user_id = ? ", [ maintenanceID, socket.userID, ]); apicache.clear(); callback({ ok: true, msg: "successDeleted", msgi18n: true, }); await server.sendMaintenanceList(socket); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("pauseMaintenance", async (maintenanceID, callback) => { try { checkLogin(socket); log.debug("maintenance", `Pause Maintenance: ${maintenanceID} User ID: ${socket.userID}`); let maintenance = server.getMaintenance(maintenanceID); if (!maintenance) { throw new Error("Maintenance not found"); } maintenance.active = false; await R.store(maintenance); maintenance.stop(); apicache.clear(); callback({ ok: true, msg: "successPaused", msgi18n: true, }); await server.sendMaintenanceList(socket); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("resumeMaintenance", async (maintenanceID, callback) => { try { checkLogin(socket); log.debug("maintenance", `Resume Maintenance: ${maintenanceID} User ID: ${socket.userID}`); let maintenance = server.getMaintenance(maintenanceID); if (!maintenance) { throw new Error("Maintenance not found"); } maintenance.active = true; await R.store(maintenance); await maintenance.run(); apicache.clear(); callback({ ok: true, msg: "successResumed", msgi18n: true, }); await server.sendMaintenanceList(socket); } catch (e) { callback({ ok: false, msg: e.message, }); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/general-socket-handler.js
server/socket-handlers/general-socket-handler.js
const { log } = require("../../src/util"); const { Settings } = require("../settings"); const { sendInfo } = require("../client"); const { checkLogin } = require("../util-server"); const { games } = require("gamedig"); const { testChrome } = require("../monitor-types/real-browser-monitor-type"); const fsAsync = require("fs").promises; const path = require("path"); /** * Get a game list via GameDig * @returns {object} list of games supported by GameDig */ function getGameList() { let gameList = []; gameList = Object.keys(games).map(key => { const item = games[key]; return { keys: [ key ], pretty: item.name, options: item.options, extra: item.extra || {} }; }); gameList.sort((a, b) => { if ( a.pretty < b.pretty ) { return -1; } if ( a.pretty > b.pretty ) { return 1; } return 0; }); return gameList; } /** * Handler for general events * @param {Socket} socket Socket.io instance * @param {UptimeKumaServer} server Uptime Kuma server * @returns {void} */ module.exports.generalSocketHandler = (socket, server) => { socket.on("initServerTimezone", async (timezone) => { try { checkLogin(socket); log.debug("generalSocketHandler", "Timezone: " + timezone); await Settings.set("initServerTimezone", true); await server.setTimezone(timezone); await sendInfo(socket); } catch (e) { log.warn("initServerTimezone", e.message); } }); socket.on("getGameList", async (callback) => { try { checkLogin(socket); callback({ ok: true, gameList: getGameList(), }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("testChrome", (executable, callback) => { try { checkLogin(socket); // Just noticed that await call could block the whole socket.io server!!! Use pure promise instead. testChrome(executable).then((version) => { callback({ ok: true, msg: { key: "foundChromiumVersion", values: [ version ], }, msgi18n: true, }); }).catch((e) => { callback({ ok: false, msg: e.message, }); }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("getPushExample", async (language, callback) => { try { checkLogin(socket); if (!/^[a-z-]+$/.test(language)) { throw new Error("Invalid language"); } } catch (e) { callback({ ok: false, msg: e.message, }); return; } try { let dir = path.join("./extra/push-examples", language); let files = await fsAsync.readdir(dir); for (let file of files) { if (file.startsWith("index.")) { callback({ ok: true, code: await fsAsync.readFile(path.join(dir, file), "utf8"), }); return; } } } catch (e) { } callback({ ok: false, msg: "Not found", }); }); // Disconnect all other socket clients of the user socket.on("disconnectOtherSocketClients", async () => { try { checkLogin(socket); server.disconnectAllSocketClients(socket.userID, socket.id); } catch (e) { log.warn("disconnectAllSocketClients", e.message); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/database-socket-handler.js
server/socket-handlers/database-socket-handler.js
const { checkLogin } = require("../util-server"); const Database = require("../database"); /** * Handlers for database * @param {Socket} socket Socket.io instance * @returns {void} */ module.exports.databaseSocketHandler = (socket) => { // Post or edit incident socket.on("getDatabaseSize", async (callback) => { try { checkLogin(socket); callback({ ok: true, size: await Database.getSize(), }); } catch (error) { callback({ ok: false, msg: error.message, }); } }); socket.on("shrinkDatabase", async (callback) => { try { checkLogin(socket); await Database.shrink(); callback({ ok: true, }); } catch (error) { callback({ ok: false, msg: error.message, }); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/api-key-socket-handler.js
server/socket-handlers/api-key-socket-handler.js
const { checkLogin } = require("../util-server"); const { log } = require("../../src/util"); const { R } = require("redbean-node"); const { nanoid } = require("nanoid"); const passwordHash = require("../password-hash"); const apicache = require("../modules/apicache"); const APIKey = require("../model/api_key"); const { Settings } = require("../settings"); const { sendAPIKeyList } = require("../client"); /** * Handlers for API keys * @param {Socket} socket Socket.io instance * @returns {void} */ module.exports.apiKeySocketHandler = (socket) => { // Add a new api key socket.on("addAPIKey", async (key, callback) => { try { checkLogin(socket); let clearKey = nanoid(40); let hashedKey = await passwordHash.generate(clearKey); key["key"] = hashedKey; let bean = await APIKey.save(key, socket.userID); log.debug("apikeys", "Added API Key"); log.debug("apikeys", key); // Append key ID and prefix to start of key separated by _, used to get // correct hash when validating key. let formattedKey = "uk" + bean.id + "_" + clearKey; await sendAPIKeyList(socket); // Enable API auth if the user creates a key, otherwise only basic // auth will be used for API. await Settings.set("apiKeysEnabled", true); callback({ ok: true, msg: "successAdded", msgi18n: true, key: formattedKey, keyID: bean.id, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("getAPIKeyList", async (callback) => { try { checkLogin(socket); await sendAPIKeyList(socket); callback({ ok: true, }); } catch (e) { console.error(e); callback({ ok: false, msg: e.message, }); } }); socket.on("deleteAPIKey", async (keyID, callback) => { try { checkLogin(socket); log.debug("apikeys", `Deleted API Key: ${keyID} User ID: ${socket.userID}`); await R.exec("DELETE FROM api_key WHERE id = ? AND user_id = ? ", [ keyID, socket.userID, ]); apicache.clear(); callback({ ok: true, msg: "successDeleted", msgi18n: true, }); await sendAPIKeyList(socket); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("disableAPIKey", async (keyID, callback) => { try { checkLogin(socket); log.debug("apikeys", `Disabled Key: ${keyID} User ID: ${socket.userID}`); await R.exec("UPDATE api_key SET active = 0 WHERE id = ? ", [ keyID, ]); apicache.clear(); callback({ ok: true, msg: "successDisabled", msgi18n: true, }); await sendAPIKeyList(socket); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("enableAPIKey", async (keyID, callback) => { try { checkLogin(socket); log.debug("apikeys", `Enabled Key: ${keyID} User ID: ${socket.userID}`); await R.exec("UPDATE api_key SET active = 1 WHERE id = ? ", [ keyID, ]); apicache.clear(); callback({ ok: true, msg: "successEnabled", msgi18n: true, }); await sendAPIKeyList(socket); } catch (e) { callback({ ok: false, msg: e.message, }); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/remote-browser-socket-handler.js
server/socket-handlers/remote-browser-socket-handler.js
const { sendRemoteBrowserList } = require("../client"); const { checkLogin } = require("../util-server"); const { RemoteBrowser } = require("../remote-browser"); const { log } = require("../../src/util"); const { testRemoteBrowser } = require("../monitor-types/real-browser-monitor-type"); /** * Handlers for docker hosts * @param {Socket} socket Socket.io instance * @returns {void} */ module.exports.remoteBrowserSocketHandler = (socket) => { socket.on("addRemoteBrowser", async (remoteBrowser, remoteBrowserID, callback) => { try { checkLogin(socket); let remoteBrowserBean = await RemoteBrowser.save(remoteBrowser, remoteBrowserID, socket.userID); await sendRemoteBrowserList(socket); callback({ ok: true, msg: "Saved.", msgi18n: true, id: remoteBrowserBean.id, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("deleteRemoteBrowser", async (dockerHostID, callback) => { try { checkLogin(socket); await RemoteBrowser.delete(dockerHostID, socket.userID); await sendRemoteBrowserList(socket); callback({ ok: true, msg: "successDeleted", msgi18n: true, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("testRemoteBrowser", async (remoteBrowser, callback) => { try { checkLogin(socket); let check = await testRemoteBrowser(remoteBrowser.url); log.info("remoteBrowser", "Tested remote browser: " + check); let msg; if (check) { msg = "Connected Successfully."; } callback({ ok: true, msg, }); } catch (e) { log.error("remoteBrowser", e); callback({ ok: false, msg: e.message, }); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/docker-socket-handler.js
server/socket-handlers/docker-socket-handler.js
const { sendDockerHostList } = require("../client"); const { checkLogin } = require("../util-server"); const { DockerHost } = require("../docker"); const { log } = require("../../src/util"); /** * Handlers for docker hosts * @param {Socket} socket Socket.io instance * @returns {void} */ module.exports.dockerSocketHandler = (socket) => { socket.on("addDockerHost", async (dockerHost, dockerHostID, callback) => { try { checkLogin(socket); let dockerHostBean = await DockerHost.save(dockerHost, dockerHostID, socket.userID); await sendDockerHostList(socket); callback({ ok: true, msg: "Saved.", msgi18n: true, id: dockerHostBean.id, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("deleteDockerHost", async (dockerHostID, callback) => { try { checkLogin(socket); await DockerHost.delete(dockerHostID, socket.userID); await sendDockerHostList(socket); callback({ ok: true, msg: "successDeleted", msgi18n: true, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("testDockerHost", async (dockerHost, callback) => { try { checkLogin(socket); let amount = await DockerHost.testDockerHost(dockerHost); let msg; if (amount >= 1) { msg = "Connected Successfully. Amount of containers: " + amount; } else { msg = "Connected Successfully, but there are no containers?"; } callback({ ok: true, msg, }); } catch (e) { log.error("docker", e); callback({ ok: false, msg: e.message, }); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/chart-socket-handler.js
server/socket-handlers/chart-socket-handler.js
const { checkLogin } = require("../util-server"); const { UptimeCalculator } = require("../uptime-calculator"); const { log } = require("../../src/util"); module.exports.chartSocketHandler = (socket) => { socket.on("getMonitorChartData", async (monitorID, period, callback) => { try { checkLogin(socket); log.debug("monitor", `Get Monitor Chart Data: ${monitorID} User ID: ${socket.userID}`); if (period == null) { throw new Error("Invalid period."); } let uptimeCalculator = await UptimeCalculator.getUptimeCalculator(monitorID); let data; if (period <= 24) { data = uptimeCalculator.getDataArray(period * 60, "minute"); } else if (period <= 720) { data = uptimeCalculator.getDataArray(period, "hour"); } else { data = uptimeCalculator.getDataArray(period / 24, "day"); } callback({ ok: true, data, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/proxy-socket-handler.js
server/socket-handlers/proxy-socket-handler.js
const { checkLogin } = require("../util-server"); const { Proxy } = require("../proxy"); const { sendProxyList } = require("../client"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const server = UptimeKumaServer.getInstance(); /** * Handlers for proxy * @param {Socket} socket Socket.io instance * @returns {void} */ module.exports.proxySocketHandler = (socket) => { socket.on("addProxy", async (proxy, proxyID, callback) => { try { checkLogin(socket); const proxyBean = await Proxy.save(proxy, proxyID, socket.userID); await sendProxyList(socket); if (proxy.applyExisting) { await Proxy.reloadProxy(); await server.sendMonitorList(socket); } callback({ ok: true, msg: "Saved.", msgi18n: true, id: proxyBean.id, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); socket.on("deleteProxy", async (proxyID, callback) => { try { checkLogin(socket); await Proxy.delete(proxyID, socket.userID); await sendProxyList(socket); await Proxy.reloadProxy(); callback({ ok: true, msg: "successDeleted", msgi18n: true, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/socket-handlers/status-page-socket-handler.js
server/socket-handlers/status-page-socket-handler.js
const { R } = require("redbean-node"); const { checkLogin, setSetting } = require("../util-server"); const dayjs = require("dayjs"); const { log } = require("../../src/util"); const ImageDataURI = require("../image-data-uri"); const Database = require("../database"); const apicache = require("../modules/apicache"); const StatusPage = require("../model/status_page"); const { UptimeKumaServer } = require("../uptime-kuma-server"); /** * Socket handlers for status page * @param {Socket} socket Socket.io instance to add listeners on * @returns {void} */ module.exports.statusPageSocketHandler = (socket) => { // Post or edit incident socket.on("postIncident", async (slug, incident, callback) => { try { checkLogin(socket); let statusPageID = await StatusPage.slugToID(slug); if (!statusPageID) { throw new Error("slug is not found"); } await R.exec("UPDATE incident SET pin = 0 WHERE status_page_id = ? ", [ statusPageID ]); let incidentBean; if (incident.id) { incidentBean = await R.findOne("incident", " id = ? AND status_page_id = ? ", [ incident.id, statusPageID ]); } if (incidentBean == null) { incidentBean = R.dispense("incident"); } incidentBean.title = incident.title; incidentBean.content = incident.content; incidentBean.style = incident.style; incidentBean.pin = true; incidentBean.status_page_id = statusPageID; if (incident.id) { incidentBean.lastUpdatedDate = R.isoDateTime(dayjs.utc()); } else { incidentBean.createdDate = R.isoDateTime(dayjs.utc()); } await R.store(incidentBean); callback({ ok: true, incident: incidentBean.toPublicJSON(), }); } catch (error) { callback({ ok: false, msg: error.message, }); } }); socket.on("unpinIncident", async (slug, callback) => { try { checkLogin(socket); let statusPageID = await StatusPage.slugToID(slug); await R.exec("UPDATE incident SET pin = 0 WHERE pin = 1 AND status_page_id = ? ", [ statusPageID ]); callback({ ok: true, }); } catch (error) { callback({ ok: false, msg: error.message, }); } }); socket.on("getStatusPage", async (slug, callback) => { try { checkLogin(socket); let statusPage = await R.findOne("status_page", " slug = ? ", [ slug ]); if (!statusPage) { throw new Error("No slug?"); } callback({ ok: true, config: await statusPage.toJSON(), }); } catch (error) { callback({ ok: false, msg: error.message, }); } }); // Save Status Page // imgDataUrl Only Accept PNG! socket.on("saveStatusPage", async (slug, config, imgDataUrl, publicGroupList, callback) => { try { checkLogin(socket); // Save Config let statusPage = await R.findOne("status_page", " slug = ? ", [ slug ]); if (!statusPage) { throw new Error("No slug?"); } checkSlug(config.slug); const header = "data:image/png;base64,"; // Check logo format // If is image data url, convert to png file // Else assume it is a url, nothing to do if (imgDataUrl.startsWith("data:")) { if (! imgDataUrl.startsWith(header)) { throw new Error("Only allowed PNG logo."); } const filename = `logo${statusPage.id}.png`; // Convert to file await ImageDataURI.outputFile(imgDataUrl, Database.uploadDir + filename); config.logo = `/upload/${filename}?t=` + Date.now(); } else { config.logo = imgDataUrl; } statusPage.slug = config.slug; statusPage.title = config.title; statusPage.description = config.description; statusPage.icon = config.logo; statusPage.autoRefreshInterval = config.autoRefreshInterval, statusPage.theme = config.theme; //statusPage.published = ; //statusPage.search_engine_index = ; statusPage.show_tags = config.showTags; //statusPage.password = null; statusPage.footer_text = config.footerText; statusPage.custom_css = config.customCSS; statusPage.show_powered_by = config.showPoweredBy; statusPage.show_only_last_heartbeat = config.showOnlyLastHeartbeat; statusPage.show_certificate_expiry = config.showCertificateExpiry; statusPage.modified_date = R.isoDateTime(); statusPage.analytics_id = config.analyticsId; statusPage.analytics_script_url = config.analyticsScriptUrl; statusPage.analytics_type = config.analyticsType; await R.store(statusPage); await statusPage.updateDomainNameList(config.domainNameList); await StatusPage.loadDomainMappingList(); // Save Public Group List const groupIDList = []; let groupOrder = 1; for (let group of publicGroupList) { let groupBean; if (group.id) { groupBean = await R.findOne("group", " id = ? AND public = 1 AND status_page_id = ? ", [ group.id, statusPage.id ]); } else { groupBean = R.dispense("group"); } groupBean.status_page_id = statusPage.id; groupBean.name = group.name; groupBean.public = true; groupBean.weight = groupOrder++; await R.store(groupBean); await R.exec("DELETE FROM monitor_group WHERE group_id = ? ", [ groupBean.id ]); let monitorOrder = 1; for (let monitor of group.monitorList) { let relationBean = R.dispense("monitor_group"); relationBean.weight = monitorOrder++; relationBean.group_id = groupBean.id; relationBean.monitor_id = monitor.id; if (monitor.sendUrl !== undefined) { relationBean.send_url = monitor.sendUrl; } if (monitor.url !== undefined) { relationBean.custom_url = monitor.url; } await R.store(relationBean); } groupIDList.push(groupBean.id); group.id = groupBean.id; } // Delete groups that are not in the list log.debug("socket", "Delete groups that are not in the list"); if (groupIDList.length === 0) { await R.exec("DELETE FROM `group` WHERE status_page_id = ?", [ statusPage.id ]); } else { const slots = groupIDList.map(() => "?").join(","); const data = [ ...groupIDList, statusPage.id ]; await R.exec(`DELETE FROM \`group\` WHERE id NOT IN (${slots}) AND status_page_id = ?`, data); } const server = UptimeKumaServer.getInstance(); // Also change entry page to new slug if it is the default one, and slug is changed. if (server.entryPage === "statusPage-" + slug && statusPage.slug !== slug) { server.entryPage = "statusPage-" + statusPage.slug; await setSetting("entryPage", server.entryPage, "general"); } apicache.clear(); callback({ ok: true, publicGroupList, }); } catch (error) { log.error("socket", error); callback({ ok: false, msg: error.message, }); } }); // Add a new status page socket.on("addStatusPage", async (title, slug, callback) => { try { checkLogin(socket); title = title?.trim(); slug = slug?.trim(); // Check empty if (!title || !slug) { throw new Error("Please input all fields"); } // Make sure slug is string if (typeof slug !== "string") { throw new Error("Slug -Accept string only"); } // lower case only slug = slug.toLowerCase(); checkSlug(slug); let statusPage = R.dispense("status_page"); statusPage.slug = slug; statusPage.title = title; statusPage.theme = "auto"; statusPage.icon = ""; statusPage.autoRefreshInterval = 300; await R.store(statusPage); callback({ ok: true, msg: "successAdded", msgi18n: true, slug: slug }); } catch (error) { console.error(error); callback({ ok: false, msg: error.message, }); } }); // Delete a status page socket.on("deleteStatusPage", async (slug, callback) => { const server = UptimeKumaServer.getInstance(); try { checkLogin(socket); let statusPageID = await StatusPage.slugToID(slug); if (statusPageID) { // Reset entry page if it is the default one. if (server.entryPage === "statusPage-" + slug) { server.entryPage = "dashboard"; await setSetting("entryPage", server.entryPage, "general"); } // No need to delete records from `status_page_cname`, because it has cascade foreign key. // But for incident & group, it is hard to add cascade foreign key during migration, so they have to be deleted manually. // Delete incident await R.exec("DELETE FROM incident WHERE status_page_id = ? ", [ statusPageID ]); // Delete group await R.exec("DELETE FROM `group` WHERE status_page_id = ? ", [ statusPageID ]); // Delete status_page await R.exec("DELETE FROM status_page WHERE id = ? ", [ statusPageID ]); apicache.clear(); } else { throw new Error("Status Page is not found"); } callback({ ok: true, }); } catch (error) { callback({ ok: false, msg: error.message, }); } }); }; /** * Check slug a-z, 0-9, - only * Regex from: https://stackoverflow.com/questions/22454258/js-regex-string-validation-for-slug * @param {string} slug Slug to test * @returns {void} * @throws Slug is not valid */ function checkSlug(slug) { if (typeof slug !== "string") { throw new Error("Slug must be string"); } slug = slug.trim(); if (!slug) { throw new Error("Slug cannot be empty"); } if (!slug.match(/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/)) { throw new Error("Invalid Slug"); } }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/utils/array-with-key.js
server/utils/array-with-key.js
/** * An object that can be used as an array with a key * Like PHP's array * @template K * @template V */ class ArrayWithKey { /** * All keys that are stored in the current object * @type {K[]} * @private */ __stack = []; /** * Push an element to the end of the array * @param {K} key The key of the element * @param {V} value The value of the element * @returns {void} */ push(key, value) { this[key] = value; this.__stack.push(key); } /** * Get the last element and remove it from the array * @returns {V|undefined} The first value, or undefined if there is no element to pop */ pop() { let key = this.__stack.pop(); let prop = this[key]; delete this[key]; return prop; } /** * Get the last key * @returns {K|null} The last key, or null if the array is empty */ getLastKey() { if (this.__stack.length === 0) { return null; } return this.__stack[this.__stack.length - 1]; } /** * Get the first element * @returns {{key:K,value:V}|null} The first element, or null if the array is empty */ shift() { let key = this.__stack.shift(); let value = this[key]; delete this[key]; return { key, value, }; } /** * Get the length of the array * @returns {number} Amount of elements stored */ length() { return this.__stack.length; } /** * Get the last value * @returns {V|null} The last element without removing it, or null if the array is empty */ last() { let key = this.getLastKey(); if (key === null) { return null; } return this[key]; } } module.exports = { ArrayWithKey };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/utils/simple-migration-server.js
server/utils/simple-migration-server.js
const express = require("express"); const http = require("node:http"); const { log } = require("../../src/util"); /** * SimpleMigrationServer * For displaying the migration status of the server * Also, it is used to let Docker healthcheck know the status of the server, as the main server is not started yet, healthcheck will think the server is down incorrectly. */ class SimpleMigrationServer { /** * Express app instance * @type {?Express} */ app; /** * Server instance * @type {?Server} */ server; /** * Response object * @type {?Response} */ response; /** * Start the server * @param {number} port Port * @param {string} hostname Hostname * @returns {Promise<void>} */ start(port, hostname) { this.app = express(); this.server = http.createServer(this.app); this.app.get("/", (req, res) => { res.set("Content-Type", "text/html"); // Don't use meta tag redirect, it may cause issues in Chrome (#6223) res.end(` <html lang="en"> <head><title>Uptime Kuma Migration</title></head> <body> Migration is in progress, it may take some time. You can check the progress in the console, or <a href="/migrate-status" target="_blank">click here to check</a>. </body> </html> `); }); this.app.get("/migrate-status", (req, res) => { res.set("Content-Type", "text/plain"); res.write("Migration is in progress, listening message...\n"); if (this.response) { this.response.write("Disconnected\n"); this.response.end(); } this.response = res; // never ending response }); return new Promise((resolve) => { this.server.listen(port, hostname, () => { if (hostname) { log.info("migration", `Migration server is running on http://${hostname}:${port}`); } else { log.info("migration", `Migration server is running on http://localhost:${port}`); } resolve(); }); }); } /** * Update the message * @param {string} msg Message to update * @returns {void} */ update(msg) { this.response?.write(msg + "\n"); } /** * Stop the server * @returns {Promise<void>} */ async stop() { this.response?.write("Finished, please refresh this page.\n"); this.response?.end(); await this.server?.close(); } } module.exports = { SimpleMigrationServer, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/utils/limit-queue.js
server/utils/limit-queue.js
const { ArrayWithKey } = require("./array-with-key"); /** * Limit Queue * The first element will be removed when the length exceeds the limit */ class LimitQueue extends ArrayWithKey { /** * The limit of the queue after which the first element will be removed * @private * @type {number} */ __limit; /** * The callback function when the queue exceeds the limit * @private * @callback onExceedCallback * @param {{key:K,value:V}|nul} item */ __onExceed = null; /** * @param {number} limit The limit of the queue after which the first element will be removed */ constructor(limit) { super(); this.__limit = limit; } /** * @inheritDoc */ push(key, value) { super.push(key, value); if (this.length() > this.__limit) { let item = this.shift(); if (this.__onExceed) { this.__onExceed(item); } } } } module.exports = { LimitQueue };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/utils/knex/lib/dialects/mysql2/schema/mysql2-columncompiler.js
server/utils/knex/lib/dialects/mysql2/schema/mysql2-columncompiler.js
const ColumnCompilerMySQL = require("knex/lib/dialects/mysql/schema/mysql-columncompiler"); const { formatDefault } = require("knex/lib/formatter/formatterUtils"); const { log } = require("../../../../../../../src/util"); class KumaColumnCompiler extends ColumnCompilerMySQL { /** * Override defaultTo method to handle default value for TEXT fields * @param {any} value Value * @returns {string|void} Default value (Don't understand why it can return void or string, but it's the original code, lol) */ defaultTo(value) { if (this.type === "text" && typeof value === "string") { log.debug("defaultTo", `${this.args[0]}: ${this.type} ${value} ${typeof value}`); // MySQL 8.0 is required and only if the value is written as an expression: https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html // MariaDB 10.2 is required: https://mariadb.com/kb/en/text/ return `default (${formatDefault(value, this.type, this.client)})`; } return super.defaultTo.apply(this, arguments); } } module.exports = KumaColumnCompiler;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-conditions/variables.js
server/monitor-conditions/variables.js
/** * Represents a variable used in a condition and the set of operators that can be applied to this variable. * * A `ConditionVariable` holds the ID of the variable and a list of operators that define how this variable can be evaluated * in conditions. For example, if the variable is a request body or a specific field in a request, the operators can include * operations such as equality checks, comparisons, or other custom evaluations. */ class ConditionVariable { /** * @type {string} */ id; /** * @type {import("./operators").ConditionOperator[]} */ operators = {}; /** * @param {string} id ID of variable * @param {import("./operators").ConditionOperator[]} operators Operators the condition supports */ constructor(id, operators = []) { this.id = id; this.operators = operators; } } module.exports = { ConditionVariable, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-conditions/expression.js
server/monitor-conditions/expression.js
/** * @readonly * @enum {string} */ const LOGICAL = { AND: "and", OR: "or", }; /** * Recursively processes an array of raw condition objects and populates the given parent group with * corresponding ConditionExpression or ConditionExpressionGroup instances. * @param {Array} conditions Array of raw condition objects, where each object represents either a group or an expression. * @param {ConditionExpressionGroup} parentGroup The parent group to which the instantiated ConditionExpression or ConditionExpressionGroup objects will be added. * @returns {void} */ function processMonitorConditions(conditions, parentGroup) { conditions.forEach(condition => { const andOr = condition.andOr === LOGICAL.OR ? LOGICAL.OR : LOGICAL.AND; if (condition.type === "group") { const group = new ConditionExpressionGroup([], andOr); // Recursively process the group's children processMonitorConditions(condition.children, group); parentGroup.children.push(group); } else if (condition.type === "expression") { const expression = new ConditionExpression(condition.variable, condition.operator, condition.value, andOr); parentGroup.children.push(expression); } }); } class ConditionExpressionGroup { /** * @type {ConditionExpressionGroup[]|ConditionExpression[]} Groups and/or expressions to test */ children = []; /** * @type {LOGICAL} Connects group result with previous group/expression results */ andOr; /** * @param {ConditionExpressionGroup[]|ConditionExpression[]} children Groups and/or expressions to test * @param {LOGICAL} andOr Connects group result with previous group/expression results */ constructor(children = [], andOr = LOGICAL.AND) { this.children = children; this.andOr = andOr; } /** * @param {Monitor} monitor Monitor instance * @returns {ConditionExpressionGroup|null} A ConditionExpressionGroup with the Monitor's conditions */ static fromMonitor(monitor) { const conditions = JSON.parse(monitor.conditions); if (conditions.length === 0) { return null; } const root = new ConditionExpressionGroup(); processMonitorConditions(conditions, root); return root; } } class ConditionExpression { /** * @type {string} ID of variable */ variable; /** * @type {string} ID of operator */ operator; /** * @type {string} Value to test with the operator */ value; /** * @type {LOGICAL} Connects expression result with previous group/expression results */ andOr; /** * @param {string} variable ID of variable to test against * @param {string} operator ID of operator to test the variable with * @param {string} value Value to test with the operator * @param {LOGICAL} andOr Connects expression result with previous group/expression results */ constructor(variable, operator, value, andOr = LOGICAL.AND) { this.variable = variable; this.operator = operator; this.value = value; this.andOr = andOr; } } module.exports = { LOGICAL, ConditionExpressionGroup, ConditionExpression, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-conditions/evaluator.js
server/monitor-conditions/evaluator.js
const { ConditionExpressionGroup, ConditionExpression, LOGICAL } = require("./expression"); const { operatorMap } = require("./operators"); /** * @param {ConditionExpression} expression Expression to evaluate * @param {object} context Context to evaluate against; These are values for variables in the expression * @returns {boolean} Whether the expression evaluates true or false * @throws {Error} */ function evaluateExpression(expression, context) { /** * @type {import("./operators").ConditionOperator|null} */ const operator = operatorMap.get(expression.operator) || null; if (operator === null) { throw new Error("Unexpected expression operator ID '" + expression.operator + "'. Expected one of [" + operatorMap.keys().join(",") + "]"); } if (!Object.prototype.hasOwnProperty.call(context, expression.variable)) { throw new Error("Variable missing in context: " + expression.variable); } return operator.test(context[expression.variable], expression.value); } /** * @param {ConditionExpressionGroup} group Group of expressions to evaluate * @param {object} context Context to evaluate against; These are values for variables in the expression * @returns {boolean} Whether the group evaluates true or false * @throws {Error} */ function evaluateExpressionGroup(group, context) { if (!group.children.length) { throw new Error("ConditionExpressionGroup must contain at least one child."); } let result = null; for (const child of group.children) { let childResult; if (child instanceof ConditionExpression) { childResult = evaluateExpression(child, context); } else if (child instanceof ConditionExpressionGroup) { childResult = evaluateExpressionGroup(child, context); } else { throw new Error("Invalid child type in ConditionExpressionGroup. Expected ConditionExpression or ConditionExpressionGroup"); } if (result === null) { result = childResult; // Initialize result with the first child's result } else if (child.andOr === LOGICAL.OR) { result = result || childResult; } else if (child.andOr === LOGICAL.AND) { result = result && childResult; } else { throw new Error("Invalid logical operator in child of ConditionExpressionGroup. Expected 'and' or 'or'. Got '" + group.andOr + "'"); } } if (result === null) { throw new Error("ConditionExpressionGroup did not result in a boolean."); } return result; } module.exports = { evaluateExpression, evaluateExpressionGroup, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-conditions/operators.js
server/monitor-conditions/operators.js
class ConditionOperator { id = undefined; caption = undefined; /** * @type {mixed} variable * @type {mixed} value */ test(variable, value) { throw new Error("You need to override test()"); } } const OP_STR_EQUALS = "equals"; const OP_STR_NOT_EQUALS = "not_equals"; const OP_CONTAINS = "contains"; const OP_NOT_CONTAINS = "not_contains"; const OP_STARTS_WITH = "starts_with"; const OP_NOT_STARTS_WITH = "not_starts_with"; const OP_ENDS_WITH = "ends_with"; const OP_NOT_ENDS_WITH = "not_ends_with"; const OP_NUM_EQUALS = "num_equals"; const OP_NUM_NOT_EQUALS = "num_not_equals"; const OP_LT = "lt"; const OP_GT = "gt"; const OP_LTE = "lte"; const OP_GTE = "gte"; /** * Asserts a variable is equal to a value. */ class StringEqualsOperator extends ConditionOperator { id = OP_STR_EQUALS; caption = "equals"; /** * @inheritdoc */ test(variable, value) { return variable === value; } } /** * Asserts a variable is not equal to a value. */ class StringNotEqualsOperator extends ConditionOperator { id = OP_STR_NOT_EQUALS; caption = "not equals"; /** * @inheritdoc */ test(variable, value) { return variable !== value; } } /** * Asserts a variable contains a value. * Handles both Array and String variable types. */ class ContainsOperator extends ConditionOperator { id = OP_CONTAINS; caption = "contains"; /** * @inheritdoc */ test(variable, value) { if (Array.isArray(variable)) { return variable.includes(value); } return variable.indexOf(value) !== -1; } } /** * Asserts a variable does not contain a value. * Handles both Array and String variable types. */ class NotContainsOperator extends ConditionOperator { id = OP_NOT_CONTAINS; caption = "not contains"; /** * @inheritdoc */ test(variable, value) { if (Array.isArray(variable)) { return !variable.includes(value); } return variable.indexOf(value) === -1; } } /** * Asserts a variable starts with a value. */ class StartsWithOperator extends ConditionOperator { id = OP_STARTS_WITH; caption = "starts with"; /** * @inheritdoc */ test(variable, value) { return variable.startsWith(value); } } /** * Asserts a variable does not start with a value. */ class NotStartsWithOperator extends ConditionOperator { id = OP_NOT_STARTS_WITH; caption = "not starts with"; /** * @inheritdoc */ test(variable, value) { return !variable.startsWith(value); } } /** * Asserts a variable ends with a value. */ class EndsWithOperator extends ConditionOperator { id = OP_ENDS_WITH; caption = "ends with"; /** * @inheritdoc */ test(variable, value) { return variable.endsWith(value); } } /** * Asserts a variable does not end with a value. */ class NotEndsWithOperator extends ConditionOperator { id = OP_NOT_ENDS_WITH; caption = "not ends with"; /** * @inheritdoc */ test(variable, value) { return !variable.endsWith(value); } } /** * Asserts a numeric variable is equal to a value. */ class NumberEqualsOperator extends ConditionOperator { id = OP_NUM_EQUALS; caption = "equals"; /** * @inheritdoc */ test(variable, value) { return variable === Number(value); } } /** * Asserts a numeric variable is not equal to a value. */ class NumberNotEqualsOperator extends ConditionOperator { id = OP_NUM_NOT_EQUALS; caption = "not equals"; /** * @inheritdoc */ test(variable, value) { return variable !== Number(value); } } /** * Asserts a variable is less than a value. */ class LessThanOperator extends ConditionOperator { id = OP_LT; caption = "less than"; /** * @inheritdoc */ test(variable, value) { return variable < Number(value); } } /** * Asserts a variable is greater than a value. */ class GreaterThanOperator extends ConditionOperator { id = OP_GT; caption = "greater than"; /** * @inheritdoc */ test(variable, value) { return variable > Number(value); } } /** * Asserts a variable is less than or equal to a value. */ class LessThanOrEqualToOperator extends ConditionOperator { id = OP_LTE; caption = "less than or equal to"; /** * @inheritdoc */ test(variable, value) { return variable <= Number(value); } } /** * Asserts a variable is greater than or equal to a value. */ class GreaterThanOrEqualToOperator extends ConditionOperator { id = OP_GTE; caption = "greater than or equal to"; /** * @inheritdoc */ test(variable, value) { return variable >= Number(value); } } const operatorMap = new Map([ [ OP_STR_EQUALS, new StringEqualsOperator ], [ OP_STR_NOT_EQUALS, new StringNotEqualsOperator ], [ OP_CONTAINS, new ContainsOperator ], [ OP_NOT_CONTAINS, new NotContainsOperator ], [ OP_STARTS_WITH, new StartsWithOperator ], [ OP_NOT_STARTS_WITH, new NotStartsWithOperator ], [ OP_ENDS_WITH, new EndsWithOperator ], [ OP_NOT_ENDS_WITH, new NotEndsWithOperator ], [ OP_NUM_EQUALS, new NumberEqualsOperator ], [ OP_NUM_NOT_EQUALS, new NumberNotEqualsOperator ], [ OP_LT, new LessThanOperator ], [ OP_GT, new GreaterThanOperator ], [ OP_LTE, new LessThanOrEqualToOperator ], [ OP_GTE, new GreaterThanOrEqualToOperator ], ]); const defaultStringOperators = [ operatorMap.get(OP_STR_EQUALS), operatorMap.get(OP_STR_NOT_EQUALS), operatorMap.get(OP_CONTAINS), operatorMap.get(OP_NOT_CONTAINS), operatorMap.get(OP_STARTS_WITH), operatorMap.get(OP_NOT_STARTS_WITH), operatorMap.get(OP_ENDS_WITH), operatorMap.get(OP_NOT_ENDS_WITH) ]; const defaultNumberOperators = [ operatorMap.get(OP_NUM_EQUALS), operatorMap.get(OP_NUM_NOT_EQUALS), operatorMap.get(OP_LT), operatorMap.get(OP_GT), operatorMap.get(OP_LTE), operatorMap.get(OP_GTE) ]; module.exports = { OP_STR_EQUALS, OP_STR_NOT_EQUALS, OP_CONTAINS, OP_NOT_CONTAINS, OP_STARTS_WITH, OP_NOT_STARTS_WITH, OP_ENDS_WITH, OP_NOT_ENDS_WITH, OP_NUM_EQUALS, OP_NUM_NOT_EQUALS, OP_LT, OP_GT, OP_LTE, OP_GTE, operatorMap, defaultStringOperators, defaultNumberOperators, ConditionOperator, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/dayjs/plugin/timezone.js
server/modules/dayjs/plugin/timezone.js
/** * Copy from node_modules/dayjs/plugin/timezone.js * Try to fix https://github.com/louislam/uptime-kuma/issues/2318 * Source: https://github.com/iamkun/dayjs/tree/dev/src/plugin/utc * License: MIT */ !function (t, e) { // eslint-disable-next-line no-undef typeof exports == "object" && typeof module != "undefined" ? module.exports = e() : typeof define == "function" && define.amd ? define(e) : (t = typeof globalThis != "undefined" ? globalThis : t || self).dayjs_plugin_timezone = e(); }(this, (function () { "use strict"; let t = { year: 0, month: 1, day: 2, hour: 3, minute: 4, second: 5 }; let e = {}; return function (n, i, o) { let r; let a = function (t, n, i) { void 0 === i && (i = {}); let o = new Date(t); let r = function (t, n) { void 0 === n && (n = {}); let i = n.timeZoneName || "short"; let o = t + "|" + i; let r = e[o]; return r || (r = new Intl.DateTimeFormat("en-US", { hour12: !1, timeZone: t, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZoneName: i }), e[o] = r), r; }(n, i); return r.formatToParts(o); }; let u = function (e, n) { let i = a(e, n); let r = []; let u = 0; for (; u < i.length; u += 1) { let f = i[u]; let s = f.type; let m = f.value; let c = t[s]; c >= 0 && (r[c] = parseInt(m, 10)); } let d = r[3]; let l = d === 24 ? 0 : d; let v = r[0] + "-" + r[1] + "-" + r[2] + " " + l + ":" + r[4] + ":" + r[5] + ":000"; let h = +e; return (o.utc(v).valueOf() - (h -= h % 1e3)) / 6e4; }; let f = i.prototype; f.tz = function (t, e) { void 0 === t && (t = r); let n = this.utcOffset(); let i = this.toDate(); let a = i.toLocaleString("en-US", { timeZone: t }).replace("\u202f", " "); let u = Math.round((i - new Date(a)) / 1e3 / 60); let f = o(a).$set("millisecond", this.$ms).utcOffset(15 * -Math.round(i.getTimezoneOffset() / 15) - u, !0); if (e) { let s = f.utcOffset(); f = f.add(n - s, "minute"); } return f.$x.$timezone = t, f; }, f.offsetName = function (t) { let e = this.$x.$timezone || o.tz.guess(); let n = a(this.valueOf(), e, { timeZoneName: t }).find((function (t) { return t.type.toLowerCase() === "timezonename"; })); return n && n.value; }; let s = f.startOf; f.startOf = function (t, e) { if (!this.$x || !this.$x.$timezone) { return s.call(this, t, e); } let n = o(this.format("YYYY-MM-DD HH:mm:ss:SSS")); return s.call(n, t, e).tz(this.$x.$timezone, !0); }, o.tz = function (t, e, n) { let i = n && e; let a = n || e || r; let f = u(+o(), a); if (typeof t != "string") { return o(t).tz(a); } let s = function (t, e, n) { let i = t - 60 * e * 1e3; let o = u(i, n); if (e === o) { return [ i, e ]; } let r = u(i -= 60 * (o - e) * 1e3, n); return o === r ? [ i, o ] : [ t - 60 * Math.min(o, r) * 1e3, Math.max(o, r) ]; }(o.utc(t, i).valueOf(), f, a); let m = s[0]; let c = s[1]; let d = o(m).utcOffset(c); return d.$x.$timezone = a, d; }, o.tz.guess = function () { return Intl.DateTimeFormat().resolvedOptions().timeZone; }, o.tz.setDefault = function (t) { r = t; }; }; }));
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/axios-ntlm/lib/ntlmClient.js
server/modules/axios-ntlm/lib/ntlmClient.js
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NtlmClient = void 0; var axios_1 = __importDefault(require("axios")); var ntlm = __importStar(require("./ntlm")); var https = __importStar(require("https")); var http = __importStar(require("http")); var dev_null_1 = __importDefault(require("dev-null")); /** * @param credentials An NtlmCredentials object containing the username and password * @param AxiosConfig The Axios config for the instance you wish to create * * @returns This function returns an axios instance configured to use the provided credentials */ function NtlmClient(credentials, AxiosConfig) { var _this = this; var config = AxiosConfig !== null && AxiosConfig !== void 0 ? AxiosConfig : {}; if (!config.httpAgent) { config.httpAgent = new http.Agent({ keepAlive: true }); } if (!config.httpsAgent) { config.httpsAgent = new https.Agent({ keepAlive: true }); } var client = axios_1.default.create(config); client.interceptors.response.use(function (response) { return response; }, function (err) { return __awaiter(_this, void 0, void 0, function () { var error, t1Msg, t2Msg, t3Msg, stream_1; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: error = err.response; // The header may look like this: `Negotiate, NTLM, Basic realm="itsahiddenrealm.example.net"`Add commentMore actions // so extract the 'NTLM' part first const ntlmheader = error.headers['www-authenticate'].split(',').find(_ => _.match(/ *NTLM/))?.trim() || ''; if (!(error && error.status === 401 && error.headers['www-authenticate'] && error.headers['www-authenticate'].includes('NTLM'))) return [3 /*break*/, 3]; // This length check is a hack because SharePoint is awkward and will // include the Negotiate option when responding with the T2 message // There is nore we could do to ensure we are processing correctly, // but this is the easiest option for now if (ntlmheader.length < 50) { t1Msg = ntlm.createType1Message(credentials.workstation, credentials.domain); error.config.headers["Authorization"] = t1Msg; } else { t2Msg = ntlm.decodeType2Message((ntlmheader.match(/^NTLM\s+(.+?)(,|\s+|$)/) || [])[1]); t3Msg = ntlm.createType3Message(t2Msg, credentials.username, credentials.password, credentials.workstation, credentials.domain); error.config.headers["X-retry"] = "false"; error.config.headers["Authorization"] = t3Msg; } if (!(error.config.responseType === "stream")) return [3 /*break*/, 2]; stream_1 = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data; if (!(stream_1 && !stream_1.readableEnded)) return [3 /*break*/, 2]; return [4 /*yield*/, new Promise(function (resolve) { stream_1.pipe((0, dev_null_1.default)()); stream_1.once('close', resolve); })]; case 1: _b.sent(); _b.label = 2; case 2: return [2 /*return*/, client(error.config)]; case 3: throw err; } }); }); }); return client; } exports.NtlmClient = NtlmClient; //# sourceMappingURL=ntlmClient.js.map
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/axios-ntlm/lib/flags.js
server/modules/axios-ntlm/lib/flags.js
'use strict'; // Original file https://raw.githubusercontent.com/elasticio/node-ntlm-client/master/lib/flags.js module.exports.NTLMFLAG_NEGOTIATE_UNICODE = 1 << 0; /* Indicates that Unicode strings are supported for use in security buffer data. */ module.exports.NTLMFLAG_NEGOTIATE_OEM = 1 << 1; /* Indicates that OEM strings are supported for use in security buffer data. */ module.exports.NTLMFLAG_REQUEST_TARGET = 1 << 2; /* Requests that the server's authentication realm be included in the Type 2 message. */ /* unknown (1<<3) */ module.exports.NTLMFLAG_NEGOTIATE_SIGN = 1 << 4; /* Specifies that authenticated communication between the client and server should carry a digital signature (message integrity). */ module.exports.NTLMFLAG_NEGOTIATE_SEAL = 1 << 5; /* Specifies that authenticated communication between the client and server should be encrypted (message confidentiality). */ module.exports.NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE = 1 << 6; /* Indicates that datagram authentication is being used. */ module.exports.NTLMFLAG_NEGOTIATE_LM_KEY = 1 << 7; /* Indicates that the LAN Manager session key should be used for signing and sealing authenticated communications. */ module.exports.NTLMFLAG_NEGOTIATE_NETWARE = 1 << 8; /* unknown purpose */ module.exports.NTLMFLAG_NEGOTIATE_NTLM_KEY = 1 << 9; /* Indicates that NTLM authentication is being used. */ /* unknown (1<<10) */ module.exports.NTLMFLAG_NEGOTIATE_ANONYMOUS = 1 << 11; /* Sent by the client in the Type 3 message to indicate that an anonymous context has been established. This also affects the response fields. */ module.exports.NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED = 1 << 12; /* Sent by the client in the Type 1 message to indicate that a desired authentication realm is included in the message. */ module.exports.NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED = 1 << 13; /* Sent by the client in the Type 1 message to indicate that the client workstation's name is included in the message. */ module.exports.NTLMFLAG_NEGOTIATE_LOCAL_CALL = 1 << 14; /* Sent by the server to indicate that the server and client are on the same machine. Implies that the client may use a pre-established local security context rather than responding to the challenge. */ module.exports.NTLMFLAG_NEGOTIATE_ALWAYS_SIGN = 1 << 15; /* Indicates that authenticated communication between the client and server should be signed with a "dummy" signature. */ module.exports.NTLMFLAG_TARGET_TYPE_DOMAIN = 1 << 16; /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a domain. */ module.exports.NTLMFLAG_TARGET_TYPE_SERVER = 1 << 17; /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a server. */ module.exports.NTLMFLAG_TARGET_TYPE_SHARE = 1 << 18; /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a share. Presumably, this is for share-level authentication. Usage is unclear. */ module.exports.NTLMFLAG_NEGOTIATE_NTLM2_KEY = 1 << 19; /* Indicates that the NTLM2 signing and sealing scheme should be used for protecting authenticated communications. */ module.exports.NTLMFLAG_REQUEST_INIT_RESPONSE = 1 << 20; /* unknown purpose */ module.exports.NTLMFLAG_REQUEST_ACCEPT_RESPONSE = 1 << 21; /* unknown purpose */ module.exports.NTLMFLAG_REQUEST_NONNT_SESSION_KEY = 1 << 22; /* unknown purpose */ module.exports.NTLMFLAG_NEGOTIATE_TARGET_INFO = 1 << 23; /* Sent by the server in the Type 2 message to indicate that it is including a Target Information block in the message. */ /* unknown (1<24) */ /* unknown (1<25) */ /* unknown (1<26) */ /* unknown (1<27) */ /* unknown (1<28) */ module.exports.NTLMFLAG_NEGOTIATE_128 = 1 << 29; /* Indicates that 128-bit encryption is supported. */ module.exports.NTLMFLAG_NEGOTIATE_KEY_EXCHANGE = 1 << 30; /* Indicates that the client will provide an encrypted master key in the "Session Key" field of the Type 3 message. */ module.exports.NTLMFLAG_NEGOTIATE_56 = 1 << 31; //# sourceMappingURL=flags.js.map
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/axios-ntlm/lib/hash.js
server/modules/axios-ntlm/lib/hash.js
'use strict'; // Original source at https://github.com/elasticio/node-ntlm-client/blob/master/lib/hash.js var crypto = require('crypto'); function createLMResponse(challenge, lmhash) { var buf = new Buffer.alloc(24), pwBuffer = new Buffer.alloc(21).fill(0); lmhash.copy(pwBuffer); calculateDES(pwBuffer.slice(0, 7), challenge).copy(buf); calculateDES(pwBuffer.slice(7, 14), challenge).copy(buf, 8); calculateDES(pwBuffer.slice(14), challenge).copy(buf, 16); return buf; } function createLMHash(password) { var buf = new Buffer.alloc(16), pwBuffer = new Buffer.alloc(14), magicKey = new Buffer.from('KGS!@#$%', 'ascii'); if (password.length > 14) { buf.fill(0); return buf; } pwBuffer.fill(0); pwBuffer.write(password.toUpperCase(), 0, 'ascii'); return Buffer.concat([ calculateDES(pwBuffer.slice(0, 7), magicKey), calculateDES(pwBuffer.slice(7), magicKey) ]); } function calculateDES(key, message) { var desKey = new Buffer.alloc(8); desKey[0] = key[0] & 0xFE; desKey[1] = ((key[0] << 7) & 0xFF) | (key[1] >> 1); desKey[2] = ((key[1] << 6) & 0xFF) | (key[2] >> 2); desKey[3] = ((key[2] << 5) & 0xFF) | (key[3] >> 3); desKey[4] = ((key[3] << 4) & 0xFF) | (key[4] >> 4); desKey[5] = ((key[4] << 3) & 0xFF) | (key[5] >> 5); desKey[6] = ((key[5] << 2) & 0xFF) | (key[6] >> 6); desKey[7] = (key[6] << 1) & 0xFF; for (var i = 0; i < 8; i++) { var parity = 0; for (var j = 1; j < 8; j++) { parity += (desKey[i] >> j) % 2; } desKey[i] |= (parity % 2) === 0 ? 1 : 0; } var des = crypto.createCipheriv('DES-ECB', desKey, ''); return des.update(message); } function createNTLMResponse(challenge, ntlmhash) { var buf = new Buffer.alloc(24), ntlmBuffer = new Buffer.alloc(21).fill(0); ntlmhash.copy(ntlmBuffer); calculateDES(ntlmBuffer.slice(0, 7), challenge).copy(buf); calculateDES(ntlmBuffer.slice(7, 14), challenge).copy(buf, 8); calculateDES(ntlmBuffer.slice(14), challenge).copy(buf, 16); return buf; } function createNTLMHash(password) { var md4sum = crypto.createHash('md4'); md4sum.update(new Buffer.from(password, 'ucs2')); return md4sum.digest(); } function createNTLMv2Hash(ntlmhash, username, authTargetName) { var hmac = crypto.createHmac('md5', ntlmhash); hmac.update(new Buffer.from(username.toUpperCase() + authTargetName, 'ucs2')); return hmac.digest(); } function createLMv2Response(type2message, username, ntlmhash, nonce, targetName) { var buf = new Buffer.alloc(24), ntlm2hash = createNTLMv2Hash(ntlmhash, username, targetName), hmac = crypto.createHmac('md5', ntlm2hash); //server challenge type2message.challenge.copy(buf, 8); //client nonce buf.write(nonce || createPseudoRandomValue(16), 16, 'hex'); //create hash hmac.update(buf.slice(8)); var hashedBuffer = hmac.digest(); hashedBuffer.copy(buf); return buf; } function createNTLMv2Response(type2message, username, ntlmhash, nonce, targetName) { var buf = new Buffer.alloc(48 + type2message.targetInfo.buffer.length), ntlm2hash = createNTLMv2Hash(ntlmhash, username, targetName), hmac = crypto.createHmac('md5', ntlm2hash); //the first 8 bytes are spare to store the hashed value before the blob //server challenge type2message.challenge.copy(buf, 8); //blob signature buf.writeUInt32BE(0x01010000, 16); //reserved buf.writeUInt32LE(0, 20); //timestamp //TODO: we are losing precision here since js is not able to handle those large integers // maybe think about a different solution here // 11644473600000 = diff between 1970 and 1601 var timestamp = ((Date.now() + 11644473600000) * 10000).toString(16); var timestampLow = Number('0x' + timestamp.substring(Math.max(0, timestamp.length - 8))); var timestampHigh = Number('0x' + timestamp.substring(0, Math.max(0, timestamp.length - 8))); buf.writeUInt32LE(timestampLow, 24, false); buf.writeUInt32LE(timestampHigh, 28, false); //random client nonce buf.write(nonce || createPseudoRandomValue(16), 32, 'hex'); //zero buf.writeUInt32LE(0, 40); //complete target information block from type 2 message type2message.targetInfo.buffer.copy(buf, 44); //zero buf.writeUInt32LE(0, 44 + type2message.targetInfo.buffer.length); hmac.update(buf.slice(8)); var hashedBuffer = hmac.digest(); hashedBuffer.copy(buf); return buf; } function createPseudoRandomValue(length) { var str = ''; while (str.length < length) { str += crypto.randomInt(16).toString(16); } return str; } module.exports = { createLMHash: createLMHash, createNTLMHash: createNTLMHash, createLMResponse: createLMResponse, createNTLMResponse: createNTLMResponse, createLMv2Response: createLMv2Response, createNTLMv2Response: createNTLMv2Response, createPseudoRandomValue: createPseudoRandomValue }; //# sourceMappingURL=hash.js.map
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/axios-ntlm/lib/ntlm.js
server/modules/axios-ntlm/lib/ntlm.js
'use strict'; // Original file https://raw.githubusercontent.com/elasticio/node-ntlm-client/master/lib/ntlm.js var os = require('os'), flags = require('./flags'), hash = require('./hash'); var NTLMSIGNATURE = "NTLMSSP\0"; function createType1Message(workstation, target) { var dataPos = 32, pos = 0, buf = new Buffer.alloc(1024); workstation = workstation === undefined ? os.hostname() : workstation; target = target === undefined ? '' : target; //signature buf.write(NTLMSIGNATURE, pos, NTLMSIGNATURE.length, 'ascii'); pos += NTLMSIGNATURE.length; //message type buf.writeUInt32LE(1, pos); pos += 4; //flags buf.writeUInt32LE(flags.NTLMFLAG_NEGOTIATE_OEM | flags.NTLMFLAG_REQUEST_TARGET | flags.NTLMFLAG_NEGOTIATE_NTLM_KEY | flags.NTLMFLAG_NEGOTIATE_NTLM2_KEY | flags.NTLMFLAG_NEGOTIATE_ALWAYS_SIGN, pos); pos += 4; //domain security buffer buf.writeUInt16LE(target.length, pos); pos += 2; buf.writeUInt16LE(target.length, pos); pos += 2; buf.writeUInt32LE(target.length === 0 ? 0 : dataPos, pos); pos += 4; if (target.length > 0) { dataPos += buf.write(target, dataPos, 'ascii'); } //workstation security buffer buf.writeUInt16LE(workstation.length, pos); pos += 2; buf.writeUInt16LE(workstation.length, pos); pos += 2; buf.writeUInt32LE(workstation.length === 0 ? 0 : dataPos, pos); pos += 4; if (workstation.length > 0) { dataPos += buf.write(workstation, dataPos, 'ascii'); } return 'NTLM ' + buf.toString('base64', 0, dataPos); } function decodeType2Message(str) { if (str === undefined) { throw new Error('Invalid argument'); } //convenience if (Object.prototype.toString.call(str) !== '[object String]') { if (str.hasOwnProperty('headers') && str.headers.hasOwnProperty('www-authenticate')) { str = str.headers['www-authenticate']; } else { throw new Error('Invalid argument'); } } var ntlmMatch = /^NTLM ([^,\s]+)/.exec(str); if (ntlmMatch) { str = ntlmMatch[1]; } var buf = new Buffer.from(str, 'base64'), obj = {}; //check signature if (buf.toString('ascii', 0, NTLMSIGNATURE.length) !== NTLMSIGNATURE) { throw new Error('Invalid message signature: ' + str); } //check message type if (buf.readUInt32LE(NTLMSIGNATURE.length) !== 2) { throw new Error('Invalid message type (no type 2)'); } //read flags obj.flags = buf.readUInt32LE(20); obj.encoding = (obj.flags & flags.NTLMFLAG_NEGOTIATE_OEM) ? 'ascii' : 'ucs2'; obj.version = (obj.flags & flags.NTLMFLAG_NEGOTIATE_NTLM2_KEY) ? 2 : 1; obj.challenge = buf.slice(24, 32); //read target name obj.targetName = (function () { var length = buf.readUInt16LE(12); //skipping allocated space var offset = buf.readUInt32LE(16); if (length === 0) { return ''; } if ((offset + length) > buf.length || offset < 32) { throw new Error('Bad type 2 message'); } return buf.toString(obj.encoding, offset, offset + length); })(); //read target info if (obj.flags & flags.NTLMFLAG_NEGOTIATE_TARGET_INFO) { obj.targetInfo = (function () { var info = {}; var length = buf.readUInt16LE(40); //skipping allocated space var offset = buf.readUInt32LE(44); var targetInfoBuffer = new Buffer.alloc(length); buf.copy(targetInfoBuffer, 0, offset, offset + length); if (length === 0) { return info; } if ((offset + length) > buf.length || offset < 32) { throw new Error('Bad type 2 message'); } var pos = offset; while (pos < (offset + length)) { var blockType = buf.readUInt16LE(pos); pos += 2; var blockLength = buf.readUInt16LE(pos); pos += 2; if (blockType === 0) { //reached the terminator subblock break; } var blockTypeStr = void 0; switch (blockType) { case 1: blockTypeStr = 'SERVER'; break; case 2: blockTypeStr = 'DOMAIN'; break; case 3: blockTypeStr = 'FQDN'; break; case 4: blockTypeStr = 'DNS'; break; case 5: blockTypeStr = 'PARENT_DNS'; break; default: blockTypeStr = ''; break; } if (blockTypeStr) { info[blockTypeStr] = buf.toString('ucs2', pos, pos + blockLength); } pos += blockLength; } return { parsed: info, buffer: targetInfoBuffer }; })(); } return obj; } function createType3Message(type2Message, username, password, workstation, target) { var dataPos = 52, buf = new Buffer.alloc(1024); if (workstation === undefined) { workstation = os.hostname(); } if (target === undefined) { target = type2Message.targetName; } //signature buf.write(NTLMSIGNATURE, 0, NTLMSIGNATURE.length, 'ascii'); //message type buf.writeUInt32LE(3, 8); if (type2Message.version === 2) { dataPos = 64; var ntlmHash = hash.createNTLMHash(password), nonce = hash.createPseudoRandomValue(16), lmv2 = hash.createLMv2Response(type2Message, username, ntlmHash, nonce, target), ntlmv2 = hash.createNTLMv2Response(type2Message, username, ntlmHash, nonce, target); //lmv2 security buffer buf.writeUInt16LE(lmv2.length, 12); buf.writeUInt16LE(lmv2.length, 14); buf.writeUInt32LE(dataPos, 16); lmv2.copy(buf, dataPos); dataPos += lmv2.length; //ntlmv2 security buffer buf.writeUInt16LE(ntlmv2.length, 20); buf.writeUInt16LE(ntlmv2.length, 22); buf.writeUInt32LE(dataPos, 24); ntlmv2.copy(buf, dataPos); dataPos += ntlmv2.length; } else { var lmHash = hash.createLMHash(password), ntlmHash = hash.createNTLMHash(password), lm = hash.createLMResponse(type2Message.challenge, lmHash), ntlm = hash.createNTLMResponse(type2Message.challenge, ntlmHash); //lm security buffer buf.writeUInt16LE(lm.length, 12); buf.writeUInt16LE(lm.length, 14); buf.writeUInt32LE(dataPos, 16); lm.copy(buf, dataPos); dataPos += lm.length; //ntlm security buffer buf.writeUInt16LE(ntlm.length, 20); buf.writeUInt16LE(ntlm.length, 22); buf.writeUInt32LE(dataPos, 24); ntlm.copy(buf, dataPos); dataPos += ntlm.length; } //target name security buffer buf.writeUInt16LE(type2Message.encoding === 'ascii' ? target.length : target.length * 2, 28); buf.writeUInt16LE(type2Message.encoding === 'ascii' ? target.length : target.length * 2, 30); buf.writeUInt32LE(dataPos, 32); dataPos += buf.write(target, dataPos, type2Message.encoding); //user name security buffer buf.writeUInt16LE(type2Message.encoding === 'ascii' ? username.length : username.length * 2, 36); buf.writeUInt16LE(type2Message.encoding === 'ascii' ? username.length : username.length * 2, 38); buf.writeUInt32LE(dataPos, 40); dataPos += buf.write(username, dataPos, type2Message.encoding); //workstation name security buffer buf.writeUInt16LE(type2Message.encoding === 'ascii' ? workstation.length : workstation.length * 2, 44); buf.writeUInt16LE(type2Message.encoding === 'ascii' ? workstation.length : workstation.length * 2, 46); buf.writeUInt32LE(dataPos, 48); dataPos += buf.write(workstation, dataPos, type2Message.encoding); if (type2Message.version === 2) { //session key security buffer buf.writeUInt16LE(0, 52); buf.writeUInt16LE(0, 54); buf.writeUInt32LE(0, 56); //flags buf.writeUInt32LE(type2Message.flags, 60); } return 'NTLM ' + buf.toString('base64', 0, dataPos); } module.exports = { createType1Message: createType1Message, decodeType2Message: decodeType2Message, createType3Message: createType3Message }; //# sourceMappingURL=ntlm.js.map
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/apicache/memory-cache.js
server/modules/apicache/memory-cache.js
function MemoryCache() { this.cache = {}; this.size = 0; } /** * * @param {string} key Key to store cache as * @param {any} value Value to store * @param {number} time Time to store for * @param {function(any, string)} timeoutCallback Callback to call in * case of timeout * @returns {Object} */ MemoryCache.prototype.add = function (key, value, time, timeoutCallback) { let old = this.cache[key]; let instance = this; let entry = { value: value, expire: time + Date.now(), timeout: setTimeout(function () { instance.delete(key); return timeoutCallback && typeof timeoutCallback === "function" && timeoutCallback(value, key); }, time) }; this.cache[key] = entry; this.size = Object.keys(this.cache).length; return entry; }; /** * Delete a cache entry * @param {string} key Key to delete * @returns {null} */ MemoryCache.prototype.delete = function (key) { let entry = this.cache[key]; if (entry) { clearTimeout(entry.timeout); } delete this.cache[key]; this.size = Object.keys(this.cache).length; return null; }; /** * Get value of key * @param {string} key * @returns {Object} */ MemoryCache.prototype.get = function (key) { let entry = this.cache[key]; return entry; }; /** * Get value of cache entry * @param {string} key * @returns {any} */ MemoryCache.prototype.getValue = function (key) { let entry = this.get(key); return entry && entry.value; }; /** * Clear cache * @returns {boolean} */ MemoryCache.prototype.clear = function () { Object.keys(this.cache).forEach(function (key) { this.delete(key); }, this); return true; }; module.exports = MemoryCache;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/apicache/index.js
server/modules/apicache/index.js
const apicache = require("./apicache"); apicache.options({ headerBlacklist: [ "cache-control" ], headers: { // Disable client side cache, only server side cache. // BUG! Not working for the second request "cache-control": "no-cache", }, }); module.exports = apicache;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/modules/apicache/apicache.js
server/modules/apicache/apicache.js
let url = require("url"); let MemoryCache = require("./memory-cache"); let t = { ms: 1, second: 1000, minute: 60000, hour: 3600000, day: 3600000 * 24, week: 3600000 * 24 * 7, month: 3600000 * 24 * 30, }; let instances = []; /** * Does a === b * @param {any} a * @returns {function(any): boolean} */ let matches = function (a) { return function (b) { return a === b; }; }; /** * Does a!==b * @param {any} a * @returns {function(any): boolean} */ let doesntMatch = function (a) { return function (b) { return !matches(a)(b); }; }; /** * Get log duration * @param {number} d Time in ms * @param {string} prefix Prefix for log * @returns {string} Coloured log string */ let logDuration = function (d, prefix) { let str = d > 1000 ? (d / 1000).toFixed(2) + "sec" : d + "ms"; return "\x1b[33m- " + (prefix ? prefix + " " : "") + str + "\x1b[0m"; }; /** * Get safe headers * @param {Object} res Express response object * @returns {Object} */ function getSafeHeaders(res) { return res.getHeaders ? res.getHeaders() : res._headers; } /** Constructor for ApiCache instance */ function ApiCache() { let memCache = new MemoryCache(); let globalOptions = { debug: false, defaultDuration: 3600000, enabled: true, appendKey: [], jsonp: false, redisClient: false, headerBlacklist: [], statusCodes: { include: [], exclude: [], }, events: { expire: undefined, }, headers: { // 'cache-control': 'no-cache' // example of header overwrite }, trackPerformance: false, respectCacheControl: false, }; let middlewareOptions = []; let instance = this; let index = null; let timers = {}; let performanceArray = []; // for tracking cache hit rate instances.push(this); this.id = instances.length; /** * Logs a message to the console if the `DEBUG` environment variable is set. * @param {string} a The first argument to log. * @param {string} b The second argument to log. * @param {string} c The third argument to log. * @param {string} d The fourth argument to log, and so on... (optional) * * Generated by Trelent */ function debug(a, b, c, d) { let arr = ["\x1b[36m[apicache]\x1b[0m", a, b, c, d].filter(function (arg) { return arg !== undefined; }); let debugEnv = process.env.DEBUG && process.env.DEBUG.split(",").indexOf("apicache") !== -1; return (globalOptions.debug || debugEnv) && console.log.apply(null, arr); } /** * Returns true if the given request and response should be logged. * @param {Object} request The HTTP request object. * @param {Object} response The HTTP response object. * @param {function(Object, Object):boolean} toggle * @returns {boolean} */ function shouldCacheResponse(request, response, toggle) { let opt = globalOptions; let codes = opt.statusCodes; if (!response) { return false; } if (toggle && !toggle(request, response)) { return false; } if (codes.exclude && codes.exclude.length && codes.exclude.indexOf(response.statusCode) !== -1) { return false; } if (codes.include && codes.include.length && codes.include.indexOf(response.statusCode) === -1) { return false; } return true; } /** * Add key to index array * @param {string} key Key to add * @param {Object} req Express request object */ function addIndexEntries(key, req) { let groupName = req.apicacheGroup; if (groupName) { debug("group detected \"" + groupName + "\""); let group = (index.groups[groupName] = index.groups[groupName] || []); group.unshift(key); } index.all.unshift(key); } /** * Returns a new object containing only the whitelisted headers. * @param {Object} headers The original object of header names and * values. * @param {string[]} globalOptions.headerWhitelist An array of * strings representing the whitelisted header names to keep in the * output object. * * Generated by Trelent */ function filterBlacklistedHeaders(headers) { return Object.keys(headers) .filter(function (key) { return globalOptions.headerBlacklist.indexOf(key) === -1; }) .reduce(function (acc, header) { acc[header] = headers[header]; return acc; }, {}); } /** * Create a cache object * @param {Object} headers The response headers to filter. * @returns {Object} A new object containing only the whitelisted * response headers. * * Generated by Trelent */ function createCacheObject(status, headers, data, encoding) { return { status: status, headers: filterBlacklistedHeaders(headers), data: data, encoding: encoding, timestamp: new Date().getTime() / 1000, // seconds since epoch. This is used to properly decrement max-age headers in cached responses. }; } /** * Sets a cache value for the given key. * @param {string} key The cache key to set. * @param {any} value The cache value to set. * @param {number} duration How long in milliseconds the cached * response should be valid for (defaults to 1 hour). * * Generated by Trelent */ function cacheResponse(key, value, duration) { let redis = globalOptions.redisClient; let expireCallback = globalOptions.events.expire; if (redis && redis.connected) { try { redis.hset(key, "response", JSON.stringify(value)); redis.hset(key, "duration", duration); redis.expire(key, duration / 1000, expireCallback || function () {}); } catch (err) { debug("[apicache] error in redis.hset()"); } } else { memCache.add(key, value, duration, expireCallback); } // add automatic cache clearing from duration, includes max limit on setTimeout timers[key] = setTimeout(function () { instance.clear(key, true); }, Math.min(duration, 2147483647)); } /** * Appends content to the response. * @param {Object} res Express response object * @param {(string|Buffer)} content The content to append. * * Generated by Trelent */ function accumulateContent(res, content) { if (content) { if (typeof content == "string") { res._apicache.content = (res._apicache.content || "") + content; } else if (Buffer.isBuffer(content)) { let oldContent = res._apicache.content; if (typeof oldContent === "string") { oldContent = !Buffer.from ? new Buffer(oldContent) : Buffer.from(oldContent); } if (!oldContent) { oldContent = !Buffer.alloc ? new Buffer(0) : Buffer.alloc(0); } res._apicache.content = Buffer.concat( [oldContent, content], oldContent.length + content.length ); } else { res._apicache.content = content; } } } /** * Monkeypatches the response object to add cache control headers * and create a cache object. * @param {Object} req Express request object * @param {Object} res Express response object * @param {function} next Function to call next * @param {string} key Key to add response as * @param {number} duration Time to cache response for * @param {string} strDuration Duration in string form * @param {function(Object, Object):boolean} toggle */ function makeResponseCacheable(req, res, next, key, duration, strDuration, toggle) { // monkeypatch res.end to create cache object res._apicache = { write: res.write, writeHead: res.writeHead, end: res.end, cacheable: true, content: undefined, }; // append header overwrites if applicable Object.keys(globalOptions.headers).forEach(function (name) { res.setHeader(name, globalOptions.headers[name]); }); res.writeHead = function () { // add cache control headers if (!globalOptions.headers["cache-control"]) { if (shouldCacheResponse(req, res, toggle)) { res.setHeader("cache-control", "max-age=" + (duration / 1000).toFixed(0)); } else { res.setHeader("cache-control", "no-cache, no-store, must-revalidate"); } } res._apicache.headers = Object.assign({}, getSafeHeaders(res)); return res._apicache.writeHead.apply(this, arguments); }; // patch res.write res.write = function (content) { accumulateContent(res, content); return res._apicache.write.apply(this, arguments); }; // patch res.end res.end = function (content, encoding) { if (shouldCacheResponse(req, res, toggle)) { accumulateContent(res, content); if (res._apicache.cacheable && res._apicache.content) { addIndexEntries(key, req); let headers = res._apicache.headers || getSafeHeaders(res); let cacheObject = createCacheObject( res.statusCode, headers, res._apicache.content, encoding ); cacheResponse(key, cacheObject, duration); // display log entry let elapsed = new Date() - req.apicacheTimer; debug("adding cache entry for \"" + key + "\" @ " + strDuration, logDuration(elapsed)); debug("_apicache.headers: ", res._apicache.headers); debug("res.getHeaders(): ", getSafeHeaders(res)); debug("cacheObject: ", cacheObject); } } return res._apicache.end.apply(this, arguments); }; next(); } /** * Send a cached response to client * @param {Request} request Express request object * @param {Response} response Express response object * @param {object} cacheObject Cache object to send * @param {function(Object, Object):boolean} toggle * @param {function} next Function to call next * @param {number} duration Not used * @returns {boolean|undefined} true if the request should be * cached, false otherwise. If undefined, defaults to true. */ function sendCachedResponse(request, response, cacheObject, toggle, next, duration) { if (toggle && !toggle(request, response)) { return next(); } let headers = getSafeHeaders(response); // Modified by @louislam, removed Cache-control, since I don't need client side cache! // Original Source: https://github.com/kwhitley/apicache/blob/0d5686cc21fad353c6dddee646288c2fca3e4f50/src/apicache.js#L254 Object.assign(headers, filterBlacklistedHeaders(cacheObject.headers || {})); // only embed apicache headers when not in production environment if (process.env.NODE_ENV !== "production") { Object.assign(headers, { "apicache-store": globalOptions.redisClient ? "redis" : "memory", "apicache-version": "1.6.2-modified", }); } // unstringify buffers let data = cacheObject.data; if (data && data.type === "Buffer") { data = typeof data.data === "number" ? new Buffer.alloc(data.data) : new Buffer.from(data.data); } // test Etag against If-None-Match for 304 let cachedEtag = cacheObject.headers.etag; let requestEtag = request.headers["if-none-match"]; if (requestEtag && cachedEtag === requestEtag) { response.writeHead(304, headers); return response.end(); } response.writeHead(cacheObject.status || 200, headers); return response.end(data, cacheObject.encoding); } /** Sync caching options */ function syncOptions() { for (let i in middlewareOptions) { Object.assign(middlewareOptions[i].options, globalOptions, middlewareOptions[i].localOptions); } } /** * Clear key from cache * @param {string} target Key to clear * @param {boolean} isAutomatic Is the key being cleared automatically * @returns {number} */ this.clear = function (target, isAutomatic) { let group = index.groups[target]; let redis = globalOptions.redisClient; if (group) { debug("clearing group \"" + target + "\""); group.forEach(function (key) { debug("clearing cached entry for \"" + key + "\""); clearTimeout(timers[key]); delete timers[key]; if (!globalOptions.redisClient) { memCache.delete(key); } else { try { redis.del(key); } catch (err) { console.log("[apicache] error in redis.del(\"" + key + "\")"); } } index.all = index.all.filter(doesntMatch(key)); }); delete index.groups[target]; } else if (target) { debug("clearing " + (isAutomatic ? "expired" : "cached") + " entry for \"" + target + "\""); clearTimeout(timers[target]); delete timers[target]; // clear actual cached entry if (!redis) { memCache.delete(target); } else { try { redis.del(target); } catch (err) { console.log("[apicache] error in redis.del(\"" + target + "\")"); } } // remove from global index index.all = index.all.filter(doesntMatch(target)); // remove target from each group that it may exist in Object.keys(index.groups).forEach(function (groupName) { index.groups[groupName] = index.groups[groupName].filter(doesntMatch(target)); // delete group if now empty if (!index.groups[groupName].length) { delete index.groups[groupName]; } }); } else { debug("clearing entire index"); if (!redis) { memCache.clear(); } else { // clear redis keys one by one from internal index to prevent clearing non-apicache entries index.all.forEach(function (key) { clearTimeout(timers[key]); delete timers[key]; try { redis.del(key); } catch (err) { console.log("[apicache] error in redis.del(\"" + key + "\")"); } }); } this.resetIndex(); } return this.getIndex(); }; /** * Converts a duration string to an integer number of milliseconds. * @param {(string|number)} duration The string to convert. * @param {number} defaultDuration The default duration to return if * can't parse duration * @returns {number} The converted value in milliseconds, or the * defaultDuration if it can't be parsed. */ function parseDuration(duration, defaultDuration) { if (typeof duration === "number") { return duration; } if (typeof duration === "string") { let split = duration.match(/^([\d\.,]+)\s?([a-zA-Z]+)$/); if (split.length === 3) { let len = parseFloat(split[1]); let unit = split[2].replace(/s$/i, "").toLowerCase(); if (unit === "m") { unit = "ms"; } return (len || 1) * (t[unit] || 0); } } return defaultDuration; } /** * Parse duration * @param {(number|string)} duration * @returns {number} Duration parsed to a number */ this.getDuration = function (duration) { return parseDuration(duration, globalOptions.defaultDuration); }; /** * Return cache performance statistics (hit rate). Suitable for * putting into a route: * <code> * app.get('/api/cache/performance', (req, res) => { * res.json(apicache.getPerformance()) * }) * </code> * @returns {any[]} */ this.getPerformance = function () { return performanceArray.map(function (p) { return p.report(); }); }; /** * Get index of a group * @param {string} group * @returns {number} */ this.getIndex = function (group) { if (group) { return index.groups[group]; } else { return index; } }; /** * Express middleware * @param {(string|number)} strDuration Duration to cache responses * for. * @param {function(Object, Object):boolean} middlewareToggle * @param {Object} localOptions Options for APICache * @returns */ this.middleware = function cache(strDuration, middlewareToggle, localOptions) { let duration = instance.getDuration(strDuration); let opt = {}; middlewareOptions.push({ options: opt, }); let options = function (localOptions) { if (localOptions) { middlewareOptions.find(function (middleware) { return middleware.options === opt; }).localOptions = localOptions; } syncOptions(); return opt; }; options(localOptions); /** * A Function for non tracking performance */ function NOOPCachePerformance() { this.report = this.hit = this.miss = function () {}; // noop; } /** * A function for tracking and reporting hit rate. These * statistics are returned by the getPerformance() call above. */ function CachePerformance() { /** * Tracks the hit rate for the last 100 requests. If there * have been fewer than 100 requests, the hit rate just * considers the requests that have happened. */ this.hitsLast100 = new Uint8Array(100 / 4); // each hit is 2 bits /** * Tracks the hit rate for the last 1000 requests. If there * have been fewer than 1000 requests, the hit rate just * considers the requests that have happened. */ this.hitsLast1000 = new Uint8Array(1000 / 4); // each hit is 2 bits /** * Tracks the hit rate for the last 10000 requests. If there * have been fewer than 10000 requests, the hit rate just * considers the requests that have happened. */ this.hitsLast10000 = new Uint8Array(10000 / 4); // each hit is 2 bits /** * Tracks the hit rate for the last 100000 requests. If * there have been fewer than 100000 requests, the hit rate * just considers the requests that have happened. */ this.hitsLast100000 = new Uint8Array(100000 / 4); // each hit is 2 bits /** * The number of calls that have passed through the * middleware since the server started. */ this.callCount = 0; /** * The total number of hits since the server started */ this.hitCount = 0; /** * The key from the last cache hit. This is useful in * identifying which route these statistics apply to. */ this.lastCacheHit = null; /** * The key from the last cache miss. This is useful in * identifying which route these statistics apply to. */ this.lastCacheMiss = null; /** * Return performance statistics * @returns {Object} */ this.report = function () { return { lastCacheHit: this.lastCacheHit, lastCacheMiss: this.lastCacheMiss, callCount: this.callCount, hitCount: this.hitCount, missCount: this.callCount - this.hitCount, hitRate: this.callCount == 0 ? null : this.hitCount / this.callCount, hitRateLast100: this.hitRate(this.hitsLast100), hitRateLast1000: this.hitRate(this.hitsLast1000), hitRateLast10000: this.hitRate(this.hitsLast10000), hitRateLast100000: this.hitRate(this.hitsLast100000), }; }; /** * Computes a cache hit rate from an array of hits and * misses. * @param {Uint8Array} array An array representing hits and * misses. * @returns {?number} a number between 0 and 1, or null if * the array has no hits or misses */ this.hitRate = function (array) { let hits = 0; let misses = 0; for (let i = 0; i < array.length; i++) { let n8 = array[i]; for (let j = 0; j < 4; j++) { switch (n8 & 3) { case 1: hits++; break; case 2: misses++; break; } n8 >>= 2; } } let total = hits + misses; if (total == 0) { return null; } return hits / total; }; /** * Record a hit or miss in the given array. It will be * recorded at a position determined by the current value of * the callCount variable. * @param {Uint8Array} array An array representing hits and * misses. * @param {boolean} hit true for a hit, false for a miss * Each element in the array is 8 bits, and encodes 4 * hit/miss records. Each hit or miss is encoded as to bits * as follows: 00 means no hit or miss has been recorded in * these bits 01 encodes a hit 10 encodes a miss */ this.recordHitInArray = function (array, hit) { let arrayIndex = ~~(this.callCount / 4) % array.length; let bitOffset = (this.callCount % 4) * 2; // 2 bits per record, 4 records per uint8 array element let clearMask = ~(3 << bitOffset); let record = (hit ? 1 : 2) << bitOffset; array[arrayIndex] = (array[arrayIndex] & clearMask) | record; }; /** * Records the hit or miss in the tracking arrays and * increments the call count. * @param {boolean} hit true records a hit, false records a * miss */ this.recordHit = function (hit) { this.recordHitInArray(this.hitsLast100, hit); this.recordHitInArray(this.hitsLast1000, hit); this.recordHitInArray(this.hitsLast10000, hit); this.recordHitInArray(this.hitsLast100000, hit); if (hit) { this.hitCount++; } this.callCount++; }; /** * Records a hit event, setting lastCacheMiss to the given key * @param {string} key The key that had the cache hit */ this.hit = function (key) { this.recordHit(true); this.lastCacheHit = key; }; /** * Records a miss event, setting lastCacheMiss to the given key * @param {string} key The key that had the cache miss */ this.miss = function (key) { this.recordHit(false); this.lastCacheMiss = key; }; } let perf = globalOptions.trackPerformance ? new CachePerformance() : new NOOPCachePerformance(); performanceArray.push(perf); /** * Cache a request * @param {Object} req Express request object * @param {Object} res Express response object * @param {function} next Function to call next * @returns {any} */ let cache = function (req, res, next) { function bypass() { debug("bypass detected, skipping cache."); return next(); } // initial bypass chances if (!opt.enabled) { return bypass(); } if ( req.headers["x-apicache-bypass"] || req.headers["x-apicache-force-fetch"] || (opt.respectCacheControl && req.headers["cache-control"] == "no-cache") ) { return bypass(); } // REMOVED IN 0.11.1 TO CORRECT MIDDLEWARE TOGGLE EXECUTE ORDER // if (typeof middlewareToggle === 'function') { // if (!middlewareToggle(req, res)) return bypass() // } else if (middlewareToggle !== undefined && !middlewareToggle) { // return bypass() // } // embed timer req.apicacheTimer = new Date(); // In Express 4.x the url is ambigious based on where a router is mounted. originalUrl will give the full Url let key = req.originalUrl || req.url; // Remove querystring from key if jsonp option is enabled if (opt.jsonp) { key = url.parse(key).pathname; } // add appendKey (either custom function or response path) if (typeof opt.appendKey === "function") { key += "$$appendKey=" + opt.appendKey(req, res); } else if (opt.appendKey.length > 0) { let appendKey = req; for (let i = 0; i < opt.appendKey.length; i++) { appendKey = appendKey[opt.appendKey[i]]; } key += "$$appendKey=" + appendKey; } // attempt cache hit let redis = opt.redisClient; let cached = !redis ? memCache.getValue(key) : null; // send if cache hit from memory-cache if (cached) { let elapsed = new Date() - req.apicacheTimer; debug("sending cached (memory-cache) version of", key, logDuration(elapsed)); perf.hit(key); return sendCachedResponse(req, res, cached, middlewareToggle, next, duration); } // send if cache hit from redis if (redis && redis.connected) { try { redis.hgetall(key, function (err, obj) { if (!err && obj && obj.response) { let elapsed = new Date() - req.apicacheTimer; debug("sending cached (redis) version of", key, logDuration(elapsed)); perf.hit(key); return sendCachedResponse( req, res, JSON.parse(obj.response), middlewareToggle, next, duration ); } else { perf.miss(key); return makeResponseCacheable( req, res, next, key, duration, strDuration, middlewareToggle ); } }); } catch (err) { // bypass redis on error perf.miss(key); return makeResponseCacheable(req, res, next, key, duration, strDuration, middlewareToggle); } } else { perf.miss(key); return makeResponseCacheable(req, res, next, key, duration, strDuration, middlewareToggle); } }; cache.options = options; return cache; }; /** * Process options * @param {Object} options * @returns {Object} */ this.options = function (options) { if (options) { Object.assign(globalOptions, options); syncOptions(); if ("defaultDuration" in options) { // Convert the default duration to a number in milliseconds (if needed) globalOptions.defaultDuration = parseDuration(globalOptions.defaultDuration, 3600000); } if (globalOptions.trackPerformance) { debug("WARNING: using trackPerformance flag can cause high memory usage!"); } return this; } else { return globalOptions; } }; /** Reset the index */ this.resetIndex = function () { index = { all: [], groups: {}, }; }; /** * Create a new instance of ApiCache * @param {Object} config Config to pass * @returns {ApiCache} */ this.newInstance = function (config) { let instance = new ApiCache(); if (config) { instance.options(config); } return instance; }; /** Clone this instance */ this.clone = function () { return this.newInstance(this.options()); }; // initialize index this.resetIndex(); } module.exports = new ApiCache();
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/redis.js
server/monitor-types/redis.js
const { MonitorType } = require("./monitor-type"); const { UP } = require("../../src/util"); const redis = require("redis"); class RedisMonitorType extends MonitorType { name = "redis"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { heartbeat.msg = await this.redisPingAsync(monitor.databaseConnectionString, !monitor.ignoreTls); heartbeat.status = UP; } /** * Redis server ping * @param {string} dsn The redis connection string * @param {boolean} rejectUnauthorized If false, allows unverified server certificates. * @returns {Promise<any>} Response from redis server */ redisPingAsync(dsn, rejectUnauthorized) { return new Promise((resolve, reject) => { const client = redis.createClient({ url: dsn, socket: { rejectUnauthorized } }); client.on("error", (err) => { if (client.isOpen) { client.disconnect(); } reject(err); }); client.connect().then(() => { if (!client.isOpen) { client.emit("error", new Error("connection isn't open")); } client.ping().then((res, err) => { if (client.isOpen) { client.disconnect(); } if (err) { reject(err); } else { resolve(res); } }).catch(error => reject(error)); }); }); } } module.exports = { RedisMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/monitor-type.js
server/monitor-types/monitor-type.js
class MonitorType { name = undefined; /** * Whether or not this type supports monitor conditions. Controls UI visibility in monitor form. * @type {boolean} */ supportsConditions = false; /** * Variables supported by this type. e.g. an HTTP type could have a "response_code" variable to test against. * This property controls the choices displayed in the monitor edit form. * @type {import("../monitor-conditions/variables").ConditionVariable[]} */ conditionVariables = []; /** * Allows setting any custom status to heartbeat, other than UP. * @type {boolean} */ allowCustomStatus = false; /** * Run the monitoring check on the given monitor * * Successful cases: Should update heartbeat.status to "up" and set response time. * Failure cases: Throw an error with a descriptive message. * @param {Monitor} monitor Monitor to check * @param {Heartbeat} heartbeat Monitor heartbeat to update * @param {UptimeKumaServer} server Uptime Kuma server * @returns {Promise<void>} */ async check(monitor, heartbeat, server) { throw new Error("You need to override check()"); } } module.exports = { MonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false