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/test/prepare-test-server.js
test/prepare-test-server.js
const fs = require("fs"); const path = "./data/test"; if (fs.existsSync(path)) { fs.rmSync(path, { recursive: true, force: true, }); }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/test-system-service.js
test/backend-test/test-system-service.js
const { describe, test, beforeEach, afterEach } = require("node:test"); const assert = require("node:assert"); const { SystemServiceMonitorType } = require("../../server/monitor-types/system-service"); const { DOWN, UP } = require("../../src/util"); const process = require("process"); const { execSync } = require("node:child_process"); /** * Check if the test should be skipped. * @returns {boolean} True if the test should be skipped */ function shouldSkip() { if (process.platform === "win32") { return false; } if (process.platform !== "linux") { return true; } // We currently only support systemd as an init system on linux // -> Check if PID 1 is systemd (or init which maps to systemd) try { const pid1Comm = execSync("ps -p 1 -o comm=", { encoding: "utf-8" }).trim(); return ![ "systemd", "init" ].includes(pid1Comm); } catch (e) { return true; } } describe("SystemServiceMonitorType", { skip: shouldSkip() }, () => { let monitorType; let heartbeat; let originalPlatform; beforeEach(() => { monitorType = new SystemServiceMonitorType(); heartbeat = { status: DOWN, msg: "", }; originalPlatform = Object.getOwnPropertyDescriptor(process, "platform"); }); afterEach(() => { if (originalPlatform) { Object.defineProperty(process, "platform", originalPlatform); } }); test("check() returns UP for a running service", async () => { // Windows: 'Dnscache' is always running. // Linux: 'dbus' or 'cron' are standard services. const serviceName = process.platform === "win32" ? "Dnscache" : "dbus"; const monitor = { system_service_name: serviceName, }; await monitorType.check(monitor, heartbeat); assert.strictEqual(heartbeat.status, UP); assert.ok(heartbeat.msg.includes("is running")); }); test("check() returns DOWN for a stopped service", async () => { const monitor = { system_service_name: "non-existent-service-12345", }; // Query a non-existent service to force an error/down state. // We pass the promise directly to assert.rejects, avoiding unnecessary async wrappers. await assert.rejects(monitorType.check(monitor, heartbeat)); assert.strictEqual(heartbeat.status, DOWN); }); test("check() fails gracefully with invalid characters", async () => { // Mock platform for validation logic test Object.defineProperty(process, "platform", { value: "linux", configurable: true, }); const monitor = { system_service_name: "invalid&service;name", }; // Expected validation error await assert.rejects(monitorType.check(monitor, heartbeat)); assert.strictEqual(heartbeat.status, DOWN); }); test("check() throws on unsupported platforms", async () => { // This test mocks the platform, so it can run anywhere. Object.defineProperty(process, "platform", { value: "darwin", configurable: true, }); const monitor = { system_service_name: "test-service", }; await assert.rejects(monitorType.check(monitor, heartbeat), /not supported/); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/test-status-page.js
test/backend-test/test-status-page.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const StatusPage = require("../../server/model/status_page"); const { STATUS_PAGE_ALL_UP, STATUS_PAGE_ALL_DOWN, STATUS_PAGE_PARTIAL_DOWN, STATUS_PAGE_MAINTENANCE } = require("../../src/util"); describe("StatusPage", () => { describe("getStatusDescription()", () => { test("returns 'No Services' when status is -1", () => { const description = StatusPage.getStatusDescription(-1); assert.strictEqual(description, "No Services"); }); test("returns 'All Systems Operational' when all services are up", () => { const description = StatusPage.getStatusDescription(STATUS_PAGE_ALL_UP); assert.strictEqual(description, "All Systems Operational"); }); test("returns 'Partially Degraded Service' when some services are down", () => { const description = StatusPage.getStatusDescription(STATUS_PAGE_PARTIAL_DOWN); assert.strictEqual(description, "Partially Degraded Service"); }); test("returns 'Degraded Service' when all services are down", () => { const description = StatusPage.getStatusDescription(STATUS_PAGE_ALL_DOWN); assert.strictEqual(description, "Degraded Service"); }); test("returns 'Under maintenance' when status page is in maintenance", () => { const description = StatusPage.getStatusDescription(STATUS_PAGE_MAINTENANCE); assert.strictEqual(description, "Under maintenance"); }); test("returns '?' for unknown status values", () => { const description = StatusPage.getStatusDescription(999); assert.strictEqual(description, "?"); }); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/test-domain.js
test/backend-test/test-domain.js
process.env.UPTIME_KUMA_HIDE_LOG = [ "info_db", "info_server" ].join(","); const { describe, test } = require("node:test"); const assert = require("node:assert"); const DomainExpiry = require("../../server/model/domain_expiry"); const mockWebhook = require("./notification-providers/mock-webhook"); const TestDB = require("../mock-testdb"); const { R } = require("redbean-node"); const { Notification } = require("../../server/notification"); const { Settings } = require("../../server/settings"); const { setSetting } = require("../../server/util-server"); const testDb = new TestDB(); describe("Domain Expiry", () => { const monHttpCom = { type: "http", url: "https://www.google.com", domainExpiryNotification: true }; test("getExpiryDate() returns correct expiry date for .wiki domain with no A record", async () => { await testDb.create(); Notification.init(); const d = DomainExpiry.createByName("google.wiki"); assert.deepEqual(await d.getExpiryDate(), new Date("2026-11-26T23:59:59.000Z")); }); test("forMonitor() retrieves expiration date for .com domain from RDAP", async () => { const domain = await DomainExpiry.forMonitor(monHttpCom); const expiryFromRdap = await domain.getExpiryDate(); // from RDAP assert.deepEqual(expiryFromRdap, new Date("2028-09-14T04:00:00.000Z")); }); test("checkExpiry() caches expiration date in database", async () => { await DomainExpiry.checkExpiry(monHttpCom); // RDAP -> Cache const domain = await DomainExpiry.findByName("google.com"); assert(Date.now() - domain.lastCheck < 5 * 1000); }); test("sendNotifications() triggers notification for expiring domain", async () => { await DomainExpiry.findByName("google.com"); const hook = { "port": 3010, "url": "capture" }; await setSetting("domainExpiryNotifyDays", [ 1, 2, 1500 ], "general"); const notif = R.convertToBean("notification", { "config": JSON.stringify({ type: "webhook", httpMethod: "post", webhookContentType: "json", webhookURL: `http://127.0.0.1:${hook.port}/${hook.url}` }), "active": 1, "user_id": 1, "name": "Testhook" }); const manyDays = 3650; setSetting("domainExpiryNotifyDays", [ manyDays ], "general"); const [ , data ] = await Promise.all([ DomainExpiry.sendNotifications(monHttpCom, [ notif ]), mockWebhook(hook.port, hook.url) ]); assert.match(data.msg, /will expire in/); setTimeout(async () => { Settings.stopCacheCleaner(); await testDb.destroy(); }, 200); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/test-migration.js
test/backend-test/test-migration.js
const { describe, test } = require("node:test"); const fs = require("fs"); const path = require("path"); const { GenericContainer, Wait } = require("testcontainers"); describe("Database Migration", () => { test("SQLite migrations run successfully from fresh database", async () => { const testDbPath = path.join(__dirname, "../../data/test-migration.db"); const testDbDir = path.dirname(testDbPath); // Ensure data directory exists if (!fs.existsSync(testDbDir)) { fs.mkdirSync(testDbDir, { recursive: true }); } // Clean up any existing test database if (fs.existsSync(testDbPath)) { fs.unlinkSync(testDbPath); } // Use the same SQLite driver as the project const Dialect = require("knex/lib/dialects/sqlite3/index.js"); Dialect.prototype._driver = () => require("@louislam/sqlite3"); const knex = require("knex"); const db = knex({ client: Dialect, connection: { filename: testDbPath }, useNullAsDefault: true, }); // Setup R (redbean) with knex instance like production code does const { R } = require("redbean-node"); R.setup(db); try { // Use production code to initialize SQLite tables (like first run) const { createTables } = require("../../db/knex_init_db.js"); await createTables(); // Run all migrations like production code does await R.knex.migrate.latest({ directory: path.join(__dirname, "../../db/knex_migrations") }); // Test passes if migrations complete successfully without errors } finally { // Clean up await R.knex.destroy(); if (fs.existsSync(testDbPath)) { fs.unlinkSync(testDbPath); } } }); test( "MariaDB migrations run successfully from fresh database", { skip: !!process.env.CI && (process.platform !== "linux" || process.arch !== "x64"), }, async () => { // Start MariaDB container (using MariaDB 12 to match current production) const mariadbContainer = await new GenericContainer("mariadb:12") .withEnvironment({ "MYSQL_ROOT_PASSWORD": "root", "MYSQL_DATABASE": "kuma_test", "MYSQL_USER": "kuma", "MYSQL_PASSWORD": "kuma" }) .withExposedPorts(3306) .withWaitStrategy(Wait.forLogMessage("ready for connections", 2)) .withStartupTimeout(120000) .start(); // Wait a bit more to ensure MariaDB is fully ready await new Promise(resolve => setTimeout(resolve, 2000)); const knex = require("knex"); const knexInstance = knex({ client: "mysql2", connection: { host: mariadbContainer.getHost(), port: mariadbContainer.getMappedPort(3306), user: "kuma", password: "kuma", database: "kuma_test", connectTimeout: 60000, }, pool: { min: 0, max: 10, acquireTimeoutMillis: 60000, idleTimeoutMillis: 60000, }, }); // Setup R (redbean) with knex instance like production code does const { R } = require("redbean-node"); R.setup(knexInstance); try { // Use production code to initialize MariaDB tables const { createTables } = require("../../db/knex_init_db.js"); await createTables(); // Run all migrations like production code does await R.knex.migrate.latest({ directory: path.join(__dirname, "../../db/knex_migrations") }); // Test passes if migrations complete successfully without errors } finally { // Clean up try { await R.knex.destroy(); } catch (e) { // Ignore cleanup errors } try { await mariadbContainer.stop(); } catch (e) { // Ignore cleanup errors } } } ); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/test-uptime-calculator.js
test/backend-test/test-uptime-calculator.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { UptimeCalculator } = require("../../server/uptime-calculator"); const dayjs = require("dayjs"); const { UP, DOWN, PENDING, MAINTENANCE } = require("../../src/util"); dayjs.extend(require("dayjs/plugin/utc")); dayjs.extend(require("../../server/modules/dayjs/plugin/timezone")); dayjs.extend(require("dayjs/plugin/customParseFormat")); describe("Uptime Calculator", () => { test("getCurrentDate() returns custom date when set", () => { let c1 = new UptimeCalculator(); // Test custom date UptimeCalculator.currentDate = dayjs.utc("2021-01-01T00:00:00.000Z"); assert.strictEqual(c1.getCurrentDate().unix(), dayjs.utc("2021-01-01T00:00:00.000Z").unix()); }); test("update() with UP status returns correct timestamp", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:46:59"); let c2 = new UptimeCalculator(); let date = await c2.update(UP); assert.strictEqual(date.unix(), dayjs.utc("2023-08-12 20:46:59").unix()); }); test("update() with MAINTENANCE status returns correct timestamp", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:47:20"); let c2 = new UptimeCalculator(); let date = await c2.update(MAINTENANCE); assert.strictEqual(date.unix(), dayjs.utc("2023-08-12 20:47:20").unix()); }); test("update() with DOWN status returns correct timestamp", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:47:20"); let c2 = new UptimeCalculator(); let date = await c2.update(DOWN); assert.strictEqual(date.unix(), dayjs.utc("2023-08-12 20:47:20").unix()); }); test("update() with PENDING status returns correct timestamp", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:47:20"); let c2 = new UptimeCalculator(); let date = await c2.update(PENDING); assert.strictEqual(date.unix(), dayjs.utc("2023-08-12 20:47:20").unix()); }); test("flatStatus() converts statuses correctly", () => { let c2 = new UptimeCalculator(); assert.strictEqual(c2.flatStatus(UP), UP); //assert.strictEqual(c2.flatStatus(MAINTENANCE), UP); assert.strictEqual(c2.flatStatus(DOWN), DOWN); assert.strictEqual(c2.flatStatus(PENDING), DOWN); }); test("getMinutelyKey() returns correct timestamp for start of minute", () => { let c2 = new UptimeCalculator(); let divisionKey = c2.getMinutelyKey(dayjs.utc("2023-08-12 20:46:00")); assert.strictEqual(divisionKey, dayjs.utc("2023-08-12 20:46:00").unix()); // Edge case 1 c2 = new UptimeCalculator(); divisionKey = c2.getMinutelyKey(dayjs.utc("2023-08-12 20:46:01")); assert.strictEqual(divisionKey, dayjs.utc("2023-08-12 20:46:00").unix()); // Edge case 2 c2 = new UptimeCalculator(); divisionKey = c2.getMinutelyKey(dayjs.utc("2023-08-12 20:46:59")); assert.strictEqual(divisionKey, dayjs.utc("2023-08-12 20:46:00").unix()); }); test("getDailyKey() returns correct timestamp for start of day", () => { let c2 = new UptimeCalculator(); let dailyKey = c2.getDailyKey(dayjs.utc("2023-08-12 20:46:00")); assert.strictEqual(dailyKey, dayjs.utc("2023-08-12").unix()); c2 = new UptimeCalculator(); dailyKey = c2.getDailyKey(dayjs.utc("2023-08-12 23:45:30")); assert.strictEqual(dailyKey, dayjs.utc("2023-08-12").unix()); // Edge case 1 c2 = new UptimeCalculator(); dailyKey = c2.getDailyKey(dayjs.utc("2023-08-12 23:59:59")); assert.strictEqual(dailyKey, dayjs.utc("2023-08-12").unix()); // Edge case 2 c2 = new UptimeCalculator(); dailyKey = c2.getDailyKey(dayjs.utc("2023-08-12 00:00:00")); assert.strictEqual(dailyKey, dayjs.utc("2023-08-12").unix()); // Test timezone c2 = new UptimeCalculator(); dailyKey = c2.getDailyKey(dayjs("Sat Dec 23 2023 05:38:39 GMT+0800 (Hong Kong Standard Time)")); assert.strictEqual(dailyKey, dayjs.utc("2023-12-22").unix()); }); test("lastDailyUptimeData tracks UP status correctly", async () => { let c2 = new UptimeCalculator(); await c2.update(UP); assert.strictEqual(c2.lastDailyUptimeData.up, 1); }); test("get24Hour() calculates uptime and average ping correctly", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:46:59"); // No data let c2 = new UptimeCalculator(); let data = c2.get24Hour(); assert.strictEqual(data.uptime, 0); assert.strictEqual(data.avgPing, null); // 1 Up c2 = new UptimeCalculator(); await c2.update(UP, 100); let uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 1); assert.strictEqual(c2.get24Hour().avgPing, 100); // 2 Up c2 = new UptimeCalculator(); await c2.update(UP, 100); await c2.update(UP, 200); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 1); assert.strictEqual(c2.get24Hour().avgPing, 150); // 3 Up c2 = new UptimeCalculator(); await c2.update(UP, 0); await c2.update(UP, 100); await c2.update(UP, 400); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 1); assert.strictEqual(c2.get24Hour().avgPing, 166.66666666666666); // 1 MAINTENANCE c2 = new UptimeCalculator(); await c2.update(MAINTENANCE); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0); assert.strictEqual(c2.get24Hour().avgPing, null); // 1 PENDING c2 = new UptimeCalculator(); await c2.update(PENDING); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0); assert.strictEqual(c2.get24Hour().avgPing, null); // 1 DOWN c2 = new UptimeCalculator(); await c2.update(DOWN); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0); assert.strictEqual(c2.get24Hour().avgPing, null); // 2 DOWN c2 = new UptimeCalculator(); await c2.update(DOWN); await c2.update(DOWN); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0); assert.strictEqual(c2.get24Hour().avgPing, null); // 1 DOWN, 1 UP c2 = new UptimeCalculator(); await c2.update(DOWN); await c2.update(UP, 0.5); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0.5); assert.strictEqual(c2.get24Hour().avgPing, 0.5); // 1 UP, 1 DOWN c2 = new UptimeCalculator(); await c2.update(UP, 123); await c2.update(DOWN); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0.5); assert.strictEqual(c2.get24Hour().avgPing, 123); // Add 24 hours c2 = new UptimeCalculator(); await c2.update(UP, 0); await c2.update(UP, 0); await c2.update(UP, 0); await c2.update(UP, 1); await c2.update(DOWN); uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0.8); assert.strictEqual(c2.get24Hour().avgPing, 0.25); UptimeCalculator.currentDate = UptimeCalculator.currentDate.add(24, "hour"); // After 24 hours, even if there is no data, the uptime should be still 80% uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0.8); assert.strictEqual(c2.get24Hour().avgPing, 0.25); // Add more 24 hours (48 hours) UptimeCalculator.currentDate = UptimeCalculator.currentDate.add(24, "hour"); // After 48 hours, even if there is no data, the uptime should be still 80% uptime = c2.get24Hour().uptime; assert.strictEqual(uptime, 0.8); assert.strictEqual(c2.get24Hour().avgPing, 0.25); }); test("get7Day() calculates 7-day uptime correctly", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:46:59"); // No data let c2 = new UptimeCalculator(); let uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0); // 1 Up c2 = new UptimeCalculator(); await c2.update(UP); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 1); // 2 Up c2 = new UptimeCalculator(); await c2.update(UP); await c2.update(UP); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 1); // 3 Up c2 = new UptimeCalculator(); await c2.update(UP); await c2.update(UP); await c2.update(UP); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 1); // 1 MAINTENANCE c2 = new UptimeCalculator(); await c2.update(MAINTENANCE); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0); // 1 PENDING c2 = new UptimeCalculator(); await c2.update(PENDING); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0); // 1 DOWN c2 = new UptimeCalculator(); await c2.update(DOWN); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0); // 2 DOWN c2 = new UptimeCalculator(); await c2.update(DOWN); await c2.update(DOWN); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0); // 1 DOWN, 1 UP c2 = new UptimeCalculator(); await c2.update(DOWN); await c2.update(UP); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0.5); // 1 UP, 1 DOWN c2 = new UptimeCalculator(); await c2.update(UP); await c2.update(DOWN); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0.5); // Add 7 days c2 = new UptimeCalculator(); await c2.update(UP); await c2.update(UP); await c2.update(UP); await c2.update(UP); await c2.update(DOWN); uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0.8); UptimeCalculator.currentDate = UptimeCalculator.currentDate.add(7, "day"); // After 7 days, even if there is no data, the uptime should be still 80% uptime = c2.get7Day().uptime; assert.strictEqual(uptime, 0.8); }); test("get30Day() calculates 30-day uptime correctly with 1 check per day", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:46:59"); let c2 = new UptimeCalculator(); let uptime = c2.get30Day().uptime; assert.strictEqual(uptime, 0); let up = 0; let down = 0; let flip = true; for (let i = 0; i < 30; i++) { UptimeCalculator.currentDate = UptimeCalculator.currentDate.add(1, "day"); if (flip) { await c2.update(UP); up++; } else { await c2.update(DOWN); down++; } uptime = c2.get30Day().uptime; assert.strictEqual(uptime, up / (up + down)); flip = !flip; } // Last 7 days // Down, Up, Down, Up, Down, Up, Down // So 3 UP assert.strictEqual(c2.get7Day().uptime, 3 / 7); }); test("get1Year() calculates 1-year uptime correctly with 1 check per day", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:46:59"); let c2 = new UptimeCalculator(); let uptime = c2.get1Year().uptime; assert.strictEqual(uptime, 0); let flip = true; for (let i = 0; i < 365; i++) { UptimeCalculator.currentDate = UptimeCalculator.currentDate.add(1, "day"); if (flip) { await c2.update(UP); } else { await c2.update(DOWN); } uptime = c2.get30Day().time; flip = !flip; } assert.strictEqual(c2.get1Year().uptime, 183 / 365); assert.strictEqual(c2.get30Day().uptime, 15 / 30); assert.strictEqual(c2.get7Day().uptime, 4 / 7); }); describe("Worst case scenario", () => { test("handles year-long simulation with various statuses", { skip: process.env.GITHUB_ACTIONS // Not stable on GitHub Actions" }, async (t) => { console.log("Memory usage before preparation", memoryUsage()); let c = new UptimeCalculator(); let up = 0; let down = 0; let interval = 20; await t.test("Prepare data", async () => { UptimeCalculator.currentDate = dayjs.utc("2023-08-12 20:46:59"); // Since 2023-08-12 will be out of 365 range, it starts from 2023-08-13 actually let actualStartDate = dayjs.utc("2023-08-13 00:00:00").unix(); // Simulate 1s interval for a year for (let i = 0; i < 365 * 24 * 60 * 60; i += interval) { UptimeCalculator.currentDate = UptimeCalculator.currentDate.add(interval, "second"); //Randomly UP, DOWN, MAINTENANCE, PENDING let rand = Math.random(); if (rand < 0.25) { c.update(UP); if (UptimeCalculator.currentDate.unix() > actualStartDate) { up++; } } else if (rand < 0.5) { c.update(DOWN); if (UptimeCalculator.currentDate.unix() > actualStartDate) { down++; } } else if (rand < 0.75) { c.update(MAINTENANCE); if (UptimeCalculator.currentDate.unix() > actualStartDate) { //up++; } } else { c.update(PENDING); if (UptimeCalculator.currentDate.unix() > actualStartDate) { down++; } } } console.log("Final Date: ", UptimeCalculator.currentDate.format("YYYY-MM-DD HH:mm:ss")); console.log("Memory usage before preparation", memoryUsage()); assert.strictEqual(c.minutelyUptimeDataList.length(), 1440); assert.strictEqual(c.dailyUptimeDataList.length(), 365); }); await t.test("get1YearUptime()", async () => { assert.strictEqual(c.get1Year().uptime, up / (up + down)); }); }); }); }); /** * Code from here: https://stackoverflow.com/a/64550489/1097815 * @returns {{rss: string, heapTotal: string, heapUsed: string, external: string}} Current memory usage */ function memoryUsage() { const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`; const memoryData = process.memoryUsage(); return { rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`, heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`, heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`, external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`, }; }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/test-util.js
test/backend-test/test-util.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const dayjs = require("dayjs"); const { getDaysRemaining, getDaysBetween } = require("../../server/util-server"); const { SQL_DATETIME_FORMAT } = require("../../src/util"); dayjs.extend(require("dayjs/plugin/utc")); dayjs.extend(require("dayjs/plugin/customParseFormat")); describe("Server Utilities", () => { test("getDaysBetween() calculates days between dates within same month", () => { const days = getDaysBetween(new Date(2025, 9, 7), new Date(2025, 9, 10)); assert.strictEqual(days, 3); }); test("getDaysBetween() calculates days between dates across years", () => { const days = getDaysBetween(new Date(2024, 9, 7), new Date(2025, 9, 10)); assert.strictEqual(days, 368); }); test("getDaysRemaining() returns positive value when target date is in future", () => { const days = getDaysRemaining(new Date(2025, 9, 7), new Date(2025, 9, 10)); assert.strictEqual(days, 3); }); test("getDaysRemaining() returns negative value when target date is in past", () => { const days = getDaysRemaining(new Date(2025, 9, 10), new Date(2025, 9, 7)); assert.strictEqual(days, -3); }); test("SQL_DATETIME_FORMAT constant matches MariaDB/MySQL format", () => { assert.strictEqual(SQL_DATETIME_FORMAT, "YYYY-MM-DD HH:mm:ss"); }); test("SQL_DATETIME_FORMAT produces valid SQL datetime string", () => { const current = dayjs.utc("2025-12-19T01:04:02.129Z"); const sqlFormat = current.utc().format(SQL_DATETIME_FORMAT); assert.strictEqual(sqlFormat, "2025-12-19 01:04:02"); // Verify it can be parsed back const parsedDate = dayjs.utc(sqlFormat, SQL_DATETIME_FORMAT); assert.strictEqual(parsedDate.unix(), current.unix()); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/test-cert-hostname-match.js
test/backend-test/test-cert-hostname-match.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { checkCertificateHostname } = require("../../server/util-server"); const testCert = ` -----BEGIN CERTIFICATE----- MIIFCTCCA/GgAwIBAgISBEROD0/r+BjpW4TvWCcZYxjpMA0GCSqGSIb3DQEBCwUA MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD EwJSMzAeFw0yMzA5MDQxMjExMThaFw0yMzEyMDMxMjExMTdaMBQxEjAQBgNVBAMM CSouZWZmLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALywpmHr GOFlhw9CcW11fVloL6dceeUexbIwVd/gOt0/rIlgBViOGCh1pFYA/Essty4vXBzx cp6W4WurmwU6ZOJA0/T6rxnmsjxSdrHVGBGgW18HJ9IWqBl9MigjpRo9h4SlAPJq cAsiBfPhQ0oSe/8IqwgKA4HTvlcTf5/HKnbe0MyQt7WNILWHm+zpfLE0AmLVXxqA MNc/ynQDLTsWDZnqqri4MKOW1yOAMbUoAWSsNaagoGnZU4bg8uhu/2JTi/vdjl0g fTDOjsELc70cWekZ9Mv4ND4w3SEthotbMCCtZE5bUqcGzSm4pQEJ37kQ7xjJ0onT RRcuZI6/jDWzwZ0CAwEAAaOCAjUwggIxMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUE FjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQU hTqVTd8TZ2pknzGJtKw2JaIrPJAwHwYDVR0jBBgwFoAUFC6zF7dYVsuuUAlA5h+v nYsUwsYwVQYIKwYBBQUHAQEESTBHMCEGCCsGAQUFBzABhhVodHRwOi8vcjMuby5s ZW5jci5vcmcwIgYIKwYBBQUHMAKGFmh0dHA6Ly9yMy5pLmxlbmNyLm9yZy8wPwYD VR0RBDgwNoIJKi5lZmYub3JnghEqLnN0YWdpbmcuZWZmLm9yZ4IWd3d3Lmh0dHBz LXJ1bGVzZXRzLm9yZzATBgNVHSAEDDAKMAgGBmeBDAECATCCAQMGCisGAQQB1nkC BAIEgfQEgfEA7wB2ALc++yTfnE26dfI5xbpY9Gxd/ELPep81xJ4dCYEl7bSZAAAB imBRp0EAAAQDAEcwRQIhAMW3HZwWZWXPWfahH2pr/lxCcoSluHv2huAW6rlzU3zn AiAOzD/p8F3gT1bzDgdSW+X5WDBeU+EutRbHMSV+Cx0mZwB1AHoyjFTYty22IOo4 4FIe6YQWcDIThU070ivBOlejUutSAAABimBRqRQAAAQDAEYwRAIgFXvRRZS3xx83 XdTsnto5SxSnGi1+YfzYobMdV1yqHGACIDurLvkt58TwifUbyXflGZJmOMhcC2G1 KUd29yCUjIahMA0GCSqGSIb3DQEBCwUAA4IBAQA6t2F3PKMLlb2A/JsQhPFUJLS3 6cx+97dzROQLBdnUQIMxPkJBN/lltNdsVxJa4A3DMbrJOayefX2l8UIvFiEFVseF WrxbmXDF68fwhBKBgeqZ25/S8jEdP5PWYWXHgXvx0zRdhfe9vuba5WeFyz79cR7K t3bSyv6GMJ2z3qBkVFGHSeYakcxPWes3CNmGxInwZNBXA2oc7xuncFrjno/USzUI nEefDfF3H3jC+0iP3IpsK8orwgWz4lOkcMYdan733lSZuVJ6pm7C9phTV04NGF3H iPenGDCg1awOyRnvxNq1MtMDkR9AHwksukzwiYNexYjyvE2t0UzXhFXwazQ3 -----END CERTIFICATE----- `; describe("Certificate Hostname Validation", () => { test("checkCertificateHostname() returns true when certificate matches hostname", () => { const result = checkCertificateHostname(testCert, "www.eff.org"); assert.strictEqual(result, true); }); test("checkCertificateHostname() returns false when certificate does not match hostname", () => { const result = checkCertificateHostname(testCert, "example.com"); assert.strictEqual(result, false); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/notification-providers/mock-webhook.js
test/backend-test/notification-providers/mock-webhook.js
const express = require("express"); const bodyParser = require("body-parser"); /** * @param {number} port Port number * @param {string} url Webhook URL * @param {number} timeout Timeout * @returns {Promise<object>} Webhook data */ async function mockWebhook(port, url, timeout = 2500) { return new Promise((resolve, reject) => { const app = express(); const tmo = setTimeout(() => { server.close(); reject({ reason: "Timeout" }); }, timeout); app.use(bodyParser.json()); // Middleware to parse JSON bodies app.post(`/${url}`, (req, res) => { res.status(200).send("OK"); server.close(); tmo && clearTimeout(tmo); resolve(req.body); }); const server = app.listen(port); }); } module.exports = mockWebhook;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/notification-providers/test-ntlm.js
test/backend-test/notification-providers/test-ntlm.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const hash = require("../../../server/modules/axios-ntlm/lib/hash"); describe("createPseudoRandomValue()", () => { test("returns a hexadecimal string with the requested length", () => { for (const length of [ 0, 8, 16, 32, 64 ]) { const result = hash.createPseudoRandomValue(length); assert.strictEqual(typeof result, "string"); assert.strictEqual(result.length, length); assert.ok(/^[0-9a-f]*$/.test(result)); } }); test("returns unique values across multiple calls with the same length", () => { const length = 16; const iterations = 10; const results = new Set(); for (let i = 0; i < iterations; i++) { results.add(hash.createPseudoRandomValue(length)); } assert.strictEqual(results.size, iterations); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-postgres.js
test/backend-test/monitors/test-postgres.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { PostgreSqlContainer } = require("@testcontainers/postgresql"); const { PostgresMonitorType } = require("../../../server/monitor-types/postgres"); const { UP, PENDING } = require("../../../src/util"); describe( "Postgres Single Node", { skip: !!process.env.CI && (process.platform !== "linux" || process.arch !== "x64"), }, () => { test("check() sets status to UP when Postgres server is reachable", async () => { // The default timeout of 30 seconds might not be enough for the container to start const postgresContainer = await new PostgreSqlContainer( "postgres:latest" ) .withStartupTimeout(60000) .start(); const postgresMonitor = new PostgresMonitorType(); const monitor = { databaseConnectionString: postgresContainer.getConnectionUri(), }; const heartbeat = { msg: "", status: PENDING, }; try { await postgresMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); } finally { postgresContainer.stop(); } }); test("check() rejects when Postgres server is not reachable", async () => { const postgresMonitor = new PostgresMonitorType(); const monitor = { databaseConnectionString: "http://localhost:15432", }; const heartbeat = { msg: "", status: PENDING, }; // regex match any string const regex = /.+/; await assert.rejects( postgresMonitor.check(monitor, heartbeat, {}), regex ); }); } );
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-grpc.js
test/backend-test/monitors/test-grpc.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const grpc = require("@grpc/grpc-js"); const protoLoader = require("@grpc/proto-loader"); const { GrpcKeywordMonitorType } = require("../../../server/monitor-types/grpc"); const { UP, PENDING } = require("../../../src/util"); const fs = require("fs"); const path = require("path"); const os = require("os"); const testProto = ` syntax = "proto3"; package test; service TestService { rpc Echo (EchoRequest) returns (EchoResponse); } message EchoRequest { string message = 1; } message EchoResponse { string message = 1; } `; /** * Create a gRPC server for testing * @param {number} port Port to listen on * @param {object} methodHandlers Object with method handlers * @returns {Promise<grpc.Server>} gRPC server instance */ async function createTestGrpcServer(port, methodHandlers) { // Write proto to temp file const tmpDir = os.tmpdir(); const protoPath = path.join(tmpDir, `test-${port}.proto`); fs.writeFileSync(protoPath, testProto); // Load proto file const packageDefinition = protoLoader.loadSync(protoPath, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); const testPackage = protoDescriptor.test; const server = new grpc.Server(); // Add service implementation server.addService(testPackage.TestService.service, { Echo: (call, callback) => { if (methodHandlers.Echo) { methodHandlers.Echo(call, callback); } else { callback(null, { message: call.request.message }); } }, }); return new Promise((resolve, reject) => { server.bindAsync( `0.0.0.0:${port}`, grpc.ServerCredentials.createInsecure(), (err) => { if (err) { reject(err); } else { server.start(); // Clean up temp file fs.unlinkSync(protoPath); resolve(server); } } ); }); } describe("GrpcKeywordMonitorType", { skip: !!process.env.CI && (process.platform !== "linux" || process.arch !== "x64"), }, () => { test("check() sets status to UP when keyword is found in response", async () => { const port = 50051; const server = await createTestGrpcServer(port, { Echo: (call, callback) => { callback(null, { message: "Hello World with SUCCESS keyword" }); } }); const grpcMonitor = new GrpcKeywordMonitorType(); const monitor = { grpcUrl: `localhost:${port}`, grpcProtobuf: testProto, grpcServiceName: "test.TestService", grpcMethod: "echo", grpcBody: JSON.stringify({ message: "test" }), keyword: "SUCCESS", invertKeyword: false, grpcEnableTls: false, isInvertKeyword: () => false, }; const heartbeat = { msg: "", status: PENDING, }; try { await grpcMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); assert.ok(heartbeat.msg.includes("SUCCESS")); assert.ok(heartbeat.msg.includes("is")); } finally { server.forceShutdown(); } }); test("check() rejects when keyword is not found in response", async () => { const port = 50052; const server = await createTestGrpcServer(port, { Echo: (call, callback) => { callback(null, { message: "Hello World without the expected keyword" }); } }); const grpcMonitor = new GrpcKeywordMonitorType(); const monitor = { grpcUrl: `localhost:${port}`, grpcProtobuf: testProto, grpcServiceName: "test.TestService", grpcMethod: "echo", grpcBody: JSON.stringify({ message: "test" }), keyword: "MISSING", invertKeyword: false, grpcEnableTls: false, isInvertKeyword: () => false, }; const heartbeat = { msg: "", status: PENDING, }; try { await assert.rejects( grpcMonitor.check(monitor, heartbeat, {}), (err) => { assert.ok(err.message.includes("MISSING")); assert.ok(err.message.includes("not")); return true; } ); } finally { server.forceShutdown(); } }); test("check() rejects when inverted keyword is present in response", async () => { const port = 50053; const server = await createTestGrpcServer(port, { Echo: (call, callback) => { callback(null, { message: "Response with ERROR keyword" }); } }); const grpcMonitor = new GrpcKeywordMonitorType(); const monitor = { grpcUrl: `localhost:${port}`, grpcProtobuf: testProto, grpcServiceName: "test.TestService", grpcMethod: "echo", grpcBody: JSON.stringify({ message: "test" }), keyword: "ERROR", invertKeyword: true, grpcEnableTls: false, isInvertKeyword: () => true, }; const heartbeat = { msg: "", status: PENDING, }; try { await assert.rejects( grpcMonitor.check(monitor, heartbeat, {}), (err) => { assert.ok(err.message.includes("ERROR")); assert.ok(err.message.includes("present")); return true; } ); } finally { server.forceShutdown(); } }); test("check() sets status to UP when inverted keyword is not present in response", async () => { const port = 50054; const server = await createTestGrpcServer(port, { Echo: (call, callback) => { callback(null, { message: "Response without error keyword" }); } }); const grpcMonitor = new GrpcKeywordMonitorType(); const monitor = { grpcUrl: `localhost:${port}`, grpcProtobuf: testProto, grpcServiceName: "test.TestService", grpcMethod: "echo", grpcBody: JSON.stringify({ message: "test" }), keyword: "ERROR", invertKeyword: true, grpcEnableTls: false, isInvertKeyword: () => true, }; const heartbeat = { msg: "", status: PENDING, }; try { await grpcMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); assert.ok(heartbeat.msg.includes("ERROR")); assert.ok(heartbeat.msg.includes("not")); } finally { server.forceShutdown(); } }); test("check() rejects when gRPC server is unreachable", async () => { const grpcMonitor = new GrpcKeywordMonitorType(); const monitor = { grpcUrl: "localhost:50099", grpcProtobuf: testProto, grpcServiceName: "test.TestService", grpcMethod: "echo", grpcBody: JSON.stringify({ message: "test" }), keyword: "SUCCESS", invertKeyword: false, grpcEnableTls: false, isInvertKeyword: () => false, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( grpcMonitor.check(monitor, heartbeat, {}), (err) => { // Should fail with connection error return true; } ); }); test("check() truncates long response messages in error output", async () => { const port = 50055; const longMessage = "A".repeat(100) + " with SUCCESS keyword"; const server = await createTestGrpcServer(port, { Echo: (call, callback) => { callback(null, { message: longMessage }); } }); const grpcMonitor = new GrpcKeywordMonitorType(); const monitor = { grpcUrl: `localhost:${port}`, grpcProtobuf: testProto, grpcServiceName: "test.TestService", grpcMethod: "echo", grpcBody: JSON.stringify({ message: "test" }), keyword: "MISSING", invertKeyword: false, grpcEnableTls: false, isInvertKeyword: () => false, }; const heartbeat = { msg: "", status: PENDING, }; try { await assert.rejects( grpcMonitor.check(monitor, heartbeat, {}), (err) => { // Should truncate message to 50 characters with "..." assert.ok(err.message.includes("...")); return true; } ); } finally { server.forceShutdown(); } }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-rabbitmq.js
test/backend-test/monitors/test-rabbitmq.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { RabbitMQContainer } = require("@testcontainers/rabbitmq"); const { RabbitMqMonitorType } = require("../../../server/monitor-types/rabbitmq"); const { UP, PENDING } = require("../../../src/util"); describe("RabbitMQ Single Node", { skip: !!process.env.CI && (process.platform !== "linux" || process.arch !== "x64"), }, () => { test("check() sets status to UP when RabbitMQ server is reachable", async () => { // The default timeout of 30 seconds might not be enough for the container to start const rabbitMQContainer = await new RabbitMQContainer().withStartupTimeout(60000).start(); const rabbitMQMonitor = new RabbitMqMonitorType(); const connectionString = `http://${rabbitMQContainer.getHost()}:${rabbitMQContainer.getMappedPort(15672)}`; const monitor = { rabbitmqNodes: JSON.stringify([ connectionString ]), rabbitmqUsername: "guest", rabbitmqPassword: "guest", }; const heartbeat = { msg: "", status: PENDING, }; try { await rabbitMQMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "OK"); } finally { rabbitMQContainer.stop(); } }); test("check() rejects when RabbitMQ server is not reachable", async () => { const rabbitMQMonitor = new RabbitMqMonitorType(); const monitor = { rabbitmqNodes: JSON.stringify([ "http://localhost:15672" ]), rabbitmqUsername: "rabbitmqUser", rabbitmqPassword: "rabbitmqPass", }; const heartbeat = { msg: "", status: PENDING, }; // regex match any string const regex = /.+/; await assert.rejects( rabbitMQMonitor.check(monitor, heartbeat, {}), regex ); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-tcp.js
test/backend-test/monitors/test-tcp.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { TCPMonitorType } = require("../../../server/monitor-types/tcp"); const { UP, PENDING } = require("../../../src/util"); const net = require("net"); describe("TCP Monitor", () => { /** * Creates a TCP server on a specified port * @param {number} port - The port number to listen on * @returns {Promise<net.Server>} A promise that resolves with the created server */ async function createTCPServer(port) { return new Promise((resolve, reject) => { const server = net.createServer(); server.listen(port, () => { resolve(server); }); server.on("error", err => { reject(err); }); }); } test("check() sets status to UP when TCP server is reachable", async () => { const port = 12345; const server = await createTCPServer(port); try { const tcpMonitor = new TCPMonitorType(); const monitor = { hostname: "localhost", port: port, isEnabledExpiryNotification: () => false, }; const heartbeat = { msg: "", status: PENDING, }; await tcpMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); } finally { server.close(); } }); test("check() rejects with connection failed when TCP server is not running", async () => { const tcpMonitor = new TCPMonitorType(); const monitor = { hostname: "localhost", port: 54321, isEnabledExpiryNotification: () => false, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( tcpMonitor.check(monitor, heartbeat, {}), new Error("Connection failed") ); }); test("check() rejects when TLS certificate is expired or invalid", async () => { const tcpMonitor = new TCPMonitorType(); const monitor = { hostname: "expired.badssl.com", port: 443, smtpSecurity: "secure", isEnabledExpiryNotification: () => true, handleTlsInfo: async tlsInfo => { return tlsInfo; }, }; const heartbeat = { msg: "", status: PENDING, }; // Regex: contains with "TLS Connection failed:" or "Certificate is invalid" const regex = /TLS Connection failed:|Certificate is invalid/; await assert.rejects( tcpMonitor.check(monitor, heartbeat, {}), regex ); }); test("check() sets status to UP when TLS certificate is valid (SSL)", async () => { const tcpMonitor = new TCPMonitorType(); const monitor = { hostname: "smtp.gmail.com", port: 465, smtpSecurity: "secure", isEnabledExpiryNotification: () => true, handleTlsInfo: async tlsInfo => { return tlsInfo; }, }; const heartbeat = { msg: "", status: PENDING, }; await tcpMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); }); test("check() sets status to UP when TLS certificate is valid (STARTTLS)", async () => { const tcpMonitor = new TCPMonitorType(); const monitor = { hostname: "smtp.gmail.com", port: 587, smtpSecurity: "starttls", isEnabledExpiryNotification: () => true, handleTlsInfo: async tlsInfo => { return tlsInfo; }, }; const heartbeat = { msg: "", status: PENDING, }; await tcpMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); }); test("check() rejects when TLS certificate hostname does not match (STARTTLS)", async () => { const tcpMonitor = new TCPMonitorType(); const monitor = { hostname: "wr-in-f108.1e100.net", port: 587, smtpSecurity: "starttls", isEnabledExpiryNotification: () => true, handleTlsInfo: async tlsInfo => { return tlsInfo; }, }; const heartbeat = { msg: "", status: PENDING, }; const regex = /does not match certificate/; await assert.rejects( tcpMonitor.check(monitor, heartbeat, {}), regex ); }); test("check() sets status to UP for XMPP server with valid certificate (STARTTLS)", async () => { const tcpMonitor = new TCPMonitorType(); const monitor = { hostname: "xmpp.earth", port: 5222, smtpSecurity: "starttls", isEnabledExpiryNotification: () => true, handleTlsInfo: async tlsInfo => { return tlsInfo; }, }; const heartbeat = { msg: "", status: PENDING, }; await tcpMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-websocket.js
test/backend-test/monitors/test-websocket.js
const { WebSocketServer } = require("ws"); const { describe, test } = require("node:test"); const assert = require("node:assert"); const { WebSocketMonitorType } = require("../../../server/monitor-types/websocket-upgrade"); const { UP, PENDING } = require("../../../src/util"); const net = require("node:net"); /** * Simulates non compliant WS Server, doesnt send Sec-WebSocket-Accept header * @param {number} port Port the server listens on. Defaults to 8080 * @returns {Promise} Promise that resolves to the created server once listening */ function nonCompliantWS(port = 8080) { const srv = net.createServer((socket) => { socket.once("data", (buf) => { socket.write("HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n\r\n"); socket.destroy(); }); }); return new Promise((resolve) => srv.listen(port, () => resolve(srv))); } describe("WebSocket Monitor", { }, () => { test("check() rejects with unexpected server response when connecting to non-WebSocket server", {}, async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://example.org", wsIgnoreSecWebsocketAcceptHeader: false, timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( websocketMonitor.check(monitor, heartbeat, {}), new Error("Unexpected server response: 200") ); }); test("check() sets status to UP when connecting to secure WebSocket server", async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://echo.websocket.org", wsIgnoreSecWebsocketAcceptHeader: false, accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; const expected = { msg: "1000 - OK", status: UP, }; await websocketMonitor.check(monitor, heartbeat, {}); assert.deepStrictEqual(heartbeat, expected); }); test("check() sets status to UP when connecting to insecure WebSocket server", async (t) => { t.after(() => wss.close()); const websocketMonitor = new WebSocketMonitorType(); const wss = new WebSocketServer({ port: 8080 }); const monitor = { url: "ws://localhost:8080", wsIgnoreSecWebsocketAcceptHeader: false, accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; const expected = { msg: "1000 - OK", status: UP, }; await websocketMonitor.check(monitor, heartbeat, {}); assert.deepStrictEqual(heartbeat, expected); }); test("check() rejects when status code does not match expected value", async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://echo.websocket.org", wsIgnoreSecWebsocketAcceptHeader: false, accepted_statuscodes_json: JSON.stringify([ "1001" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( websocketMonitor.check(monitor, heartbeat, {}), new Error("Unexpected status code: 1000") ); }); test("check() rejects when expected status code is empty", async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://echo.websocket.org", wsIgnoreSecWebsocketAcceptHeader: false, accepted_statuscodes_json: JSON.stringify([ "" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( websocketMonitor.check(monitor, heartbeat, {}), new Error("Unexpected status code: 1000") ); }); test("check() rejects when Sec-WebSocket-Accept header is invalid", async (t) => { t.after(() => wss.close()); const websocketMonitor = new WebSocketMonitorType(); const wss = await nonCompliantWS(); const monitor = { url: "ws://localhost:8080", wsIgnoreSecWebsocketAcceptHeader: false, accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( websocketMonitor.check(monitor, heartbeat, {}), new Error("Invalid Sec-WebSocket-Accept header") ); }); test("check() sets status to UP when ignoring invalid Sec-WebSocket-Accept header", async (t) => { t.after(() => wss.close()); const websocketMonitor = new WebSocketMonitorType(); const wss = await nonCompliantWS(); const monitor = { url: "ws://localhost:8080", wsIgnoreSecWebsocketAcceptHeader: true, accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; const expected = { msg: "1000 - OK", status: UP, }; await websocketMonitor.check(monitor, heartbeat, {}); assert.deepStrictEqual(heartbeat, expected); }); test("check() sets status to UP for compliant WebSocket server when ignoring Sec-WebSocket-Accept", async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://echo.websocket.org", wsIgnoreSecWebsocketAcceptHeader: true, accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; const expected = { msg: "1000 - OK", status: UP, }; await websocketMonitor.check(monitor, heartbeat, {}); assert.deepStrictEqual(heartbeat, expected); }); test("check() rejects non-WebSocket server even when ignoring Sec-WebSocket-Accept", async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://example.org", wsIgnoreSecWebsocketAcceptHeader: true, accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( websocketMonitor.check(monitor, heartbeat, {}), new Error("Unexpected server response: 200") ); }); test("check() rejects when server does not support requested subprotocol", async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://echo.websocket.org", wsIgnoreSecWebsocketAcceptHeader: false, wsSubprotocol: "ocpp1.6", accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( websocketMonitor.check(monitor, heartbeat, {}), new Error("Server sent no subprotocol") ); }); test("check() rejects when multiple subprotocols contain invalid characters", async () => { const websocketMonitor = new WebSocketMonitorType(); const monitor = { url: "wss://echo.websocket.org", wsIgnoreSecWebsocketAcceptHeader: false, wsSubprotocol: " # & ,ocpp2.0 [] , ocpp1.6 , ,, ; ", accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( websocketMonitor.check(monitor, heartbeat, {}), new SyntaxError("An invalid or duplicated subprotocol was specified") ); }); test("check() sets status to UP when subprotocol with multiple spaces is accepted", async (t) => { t.after(() => wss.close()); const websocketMonitor = new WebSocketMonitorType(); const wss = new WebSocketServer({ port: 8080, handleProtocols: (protocols) => { return Array.from(protocols).includes("test") ? "test" : null; } }); const monitor = { url: "ws://localhost:8080", wsIgnoreSecWebsocketAcceptHeader: false, wsSubprotocol: "invalid , test ", accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; const expected = { msg: "1000 - OK", status: UP, }; await websocketMonitor.check(monitor, heartbeat, {}); assert.deepStrictEqual(heartbeat, expected); }); test("check() sets status to UP when server supports requested subprotocol", async (t) => { t.after(() => wss.close()); const websocketMonitor = new WebSocketMonitorType(); const wss = new WebSocketServer({ port: 8080, handleProtocols: (protocols) => { return Array.from(protocols).includes("test") ? "test" : null; } }); const monitor = { url: "ws://localhost:8080", wsIgnoreSecWebsocketAcceptHeader: false, wsSubprotocol: "invalid,test", accepted_statuscodes_json: JSON.stringify([ "1000" ]), timeout: 30, }; const heartbeat = { msg: "", status: PENDING, }; const expected = { msg: "1000 - OK", status: UP, }; await websocketMonitor.check(monitor, heartbeat, {}); assert.deepStrictEqual(heartbeat, expected); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-mqtt.js
test/backend-test/monitors/test-mqtt.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { HiveMQContainer } = require("@testcontainers/hivemq"); const mqtt = require("mqtt"); const { MqttMonitorType } = require("../../../server/monitor-types/mqtt"); const { UP, PENDING } = require("../../../src/util"); /** * Runs an MQTT test with the * @param {string} mqttSuccessMessage the message that the monitor expects * @param {null|"keyword"|"json-query"} mqttCheckType the type of check we perform * @param {string} receivedMessage what message is received from the mqtt channel * @param {string} monitorTopic which MQTT topic is monitored (wildcards are allowed) * @param {string} publishTopic to which MQTT topic the message is sent * @returns {Promise<Heartbeat>} the heartbeat produced by the check */ async function testMqtt(mqttSuccessMessage, mqttCheckType, receivedMessage, monitorTopic = "test", publishTopic = "test") { const hiveMQContainer = await new HiveMQContainer().start(); const connectionString = hiveMQContainer.getConnectionString(); const mqttMonitorType = new MqttMonitorType(); const monitor = { jsonPath: "firstProp", // always return firstProp for the json-query monitor hostname: connectionString.split(":", 2).join(":"), mqttTopic: monitorTopic, port: connectionString.split(":")[2], mqttUsername: null, mqttPassword: null, mqttWebsocketPath: null, // for WebSocket connections interval: 20, // controls the timeout mqttSuccessMessage: mqttSuccessMessage, // for keywords expectedValue: mqttSuccessMessage, // for json-query mqttCheckType: mqttCheckType, }; const heartbeat = { msg: "", status: PENDING, }; const testMqttClient = mqtt.connect(hiveMQContainer.getConnectionString()); testMqttClient.on("connect", () => { testMqttClient.subscribe(monitorTopic, (error) => { if (!error) { testMqttClient.publish(publishTopic, receivedMessage); } }); }); try { await mqttMonitorType.check(monitor, heartbeat, {}); } finally { testMqttClient.end(); hiveMQContainer.stop(); } return heartbeat; } describe("MqttMonitorType", { concurrency: 4, skip: !!process.env.CI && (process.platform !== "linux" || process.arch !== "x64") }, () => { test("check() sets status to UP when keyword is found in message (type=default)", async () => { const heartbeat = await testMqtt("KEYWORD", null, "-> KEYWORD <-"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Topic: test; Message: -> KEYWORD <-"); }); test("check() sets status to UP when keyword is found in nested topic", async () => { const heartbeat = await testMqtt("KEYWORD", null, "-> KEYWORD <-", "a/b/c", "a/b/c"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Topic: a/b/c; Message: -> KEYWORD <-"); }); test("check() sets status to UP when keyword is found in nested topic with special characters", async () => { const heartbeat = await testMqtt("KEYWORD", null, "-> KEYWORD <-", "a/'/$/./*/%", "a/'/$/./*/%"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Topic: a/'/$/./*/%; Message: -> KEYWORD <-"); }); test("check() sets status to UP when keyword is found using # wildcard", async () => { const heartbeat = await testMqtt("KEYWORD", null, "-> KEYWORD <-", "a/#", "a/b/c"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Topic: a/b/c; Message: -> KEYWORD <-"); }); test("check() sets status to UP when keyword is found using + wildcard", async () => { const heartbeat = await testMqtt("KEYWORD", null, "-> KEYWORD <-", "a/+/c", "a/b/c"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Topic: a/b/c; Message: -> KEYWORD <-"); }); test("check() sets status to UP when keyword is found using + and # wildcards", async () => { const heartbeat = await testMqtt("KEYWORD", null, "-> KEYWORD <-", "a/+/c/#", "a/b/c/d/e"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Topic: a/b/c/d/e; Message: -> KEYWORD <-"); }); test("check() rejects with timeout when topic does not match", async () => { await assert.rejects( testMqtt("keyword will not be checked anyway", null, "message", "x/y/z", "a/b/c"), new Error("Timeout, Message not received"), ); }); test("check() rejects with timeout when # wildcard is not last character", async () => { await assert.rejects( testMqtt("", null, "# should be last character", "#/c", "a/b/c"), new Error("Timeout, Message not received"), ); }); test("check() rejects with timeout when + wildcard topic does not match", async () => { await assert.rejects( testMqtt("", null, "message", "x/+/z", "a/b/c"), new Error("Timeout, Message not received"), ); }); test("check() sets status to UP when keyword is found in message (type=keyword)", async () => { const heartbeat = await testMqtt("KEYWORD", "keyword", "-> KEYWORD <-"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Topic: test; Message: -> KEYWORD <-"); }); test("check() rejects when keyword is not found in message (type=default)", async () => { await assert.rejects( testMqtt("NOT_PRESENT", null, "-> KEYWORD <-"), new Error("Message Mismatch - Topic: test; Message: -> KEYWORD <-"), ); }); test("check() rejects when keyword is not found in message (type=keyword)", async () => { await assert.rejects( testMqtt("NOT_PRESENT", "keyword", "-> KEYWORD <-"), new Error("Message Mismatch - Topic: test; Message: -> KEYWORD <-"), ); }); test("check() sets status to UP when json-query finds expected value", async () => { // works because the monitors' jsonPath is hard-coded to "firstProp" const heartbeat = await testMqtt("present", "json-query", "{\"firstProp\":\"present\"}"); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Message received, expected value is found"); }); test("check() rejects when json-query path returns undefined", async () => { // works because the monitors' jsonPath is hard-coded to "firstProp" await assert.rejects( testMqtt("[not_relevant]", "json-query", "{}"), new Error("Message received but value is not equal to expected value, value was: [undefined]"), ); }); test("check() rejects when json-query value does not match expected value", async () => { // works because the monitors' jsonPath is hard-coded to "firstProp" await assert.rejects( testMqtt("[wrong_success_messsage]", "json-query", "{\"firstProp\":\"present\"}"), new Error("Message received but value is not equal to expected value, value was: [present]") ); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-mssql.js
test/backend-test/monitors/test-mssql.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { MSSQLServerContainer } = require("@testcontainers/mssqlserver"); const { MssqlMonitorType } = require("../../../server/monitor-types/mssql"); const { UP, PENDING } = require("../../../src/util"); /** * Helper function to create and start a MSSQL container * @returns {Promise<MSSQLServerContainer>} The started MSSQL container */ async function createAndStartMSSQLContainer() { return await new MSSQLServerContainer( "mcr.microsoft.com/mssql/server:2022-latest" ) .acceptLicense() // The default timeout of 30 seconds might not be enough for the container to start .withStartupTimeout(60000) .start(); } describe( "MSSQL Single Node", { skip: !!process.env.CI && (process.platform !== "linux" || process.arch !== "x64"), }, () => { test("check() sets status to UP when MSSQL server is reachable", async () => { let mssqlContainer; try { mssqlContainer = await createAndStartMSSQLContainer(); const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: mssqlContainer.getConnectionUri(false), conditions: "[]", }; const heartbeat = { msg: "", status: PENDING, }; await mssqlMonitor.check(monitor, heartbeat, {}); assert.strictEqual( heartbeat.status, UP, `Expected status ${UP} but got ${heartbeat.status}` ); } catch (error) { console.error("Test failed with error:", error.message); console.error("Error stack:", error.stack); if (mssqlContainer) { console.error("Container ID:", mssqlContainer.getId()); console.error( "Container logs:", await mssqlContainer.logs() ); } throw error; } finally { if (mssqlContainer) { console.log("Stopping MSSQL container..."); await mssqlContainer.stop(); } } }); test("check() sets status to UP when custom query returns single value", async () => { const mssqlContainer = await createAndStartMSSQLContainer(); const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: mssqlContainer.getConnectionUri(false), databaseQuery: "SELECT 42", conditions: "[]", }; const heartbeat = { msg: "", status: PENDING, }; try { await mssqlMonitor.check(monitor, heartbeat, {}); assert.strictEqual( heartbeat.status, UP, `Expected status ${UP} but got ${heartbeat.status}` ); } finally { await mssqlContainer.stop(); } }); test("check() sets status to UP when custom query result meets condition", async () => { const mssqlContainer = await createAndStartMSSQLContainer(); const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: mssqlContainer.getConnectionUri(false), databaseQuery: "SELECT 42 as value", conditions: JSON.stringify([ { type: "expression", andOr: "and", variable: "result", operator: "equals", value: "42", }, ]), }; const heartbeat = { msg: "", status: PENDING, }; try { await mssqlMonitor.check(monitor, heartbeat, {}); assert.strictEqual( heartbeat.status, UP, `Expected status ${UP} but got ${heartbeat.status}` ); } finally { await mssqlContainer.stop(); } }); test("check() rejects when custom query result does not meet condition", async () => { const mssqlContainer = await createAndStartMSSQLContainer(); const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: mssqlContainer.getConnectionUri(false), databaseQuery: "SELECT 99 as value", conditions: JSON.stringify([ { type: "expression", andOr: "and", variable: "result", operator: "equals", value: "42", }, ]), }; const heartbeat = { msg: "", status: PENDING, }; try { await assert.rejects( mssqlMonitor.check(monitor, heartbeat, {}), new Error( "Query result did not meet the specified conditions (99)" ) ); assert.strictEqual( heartbeat.status, PENDING, `Expected status should not be ${heartbeat.status}` ); } finally { await mssqlContainer.stop(); } }); test("check() rejects when query returns no results", async () => { const mssqlContainer = await createAndStartMSSQLContainer(); const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: mssqlContainer.getConnectionUri(false), databaseQuery: "SELECT 1 WHERE 1 = 0", conditions: "[]", }; const heartbeat = { msg: "", status: PENDING, }; try { await assert.rejects( mssqlMonitor.check(monitor, heartbeat, {}), new Error( "Database connection/query failed: Query returned no results" ) ); assert.strictEqual( heartbeat.status, PENDING, `Expected status should not be ${heartbeat.status}` ); } finally { await mssqlContainer.stop(); } }); test("check() rejects when query returns multiple rows", async () => { const mssqlContainer = await createAndStartMSSQLContainer(); const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: mssqlContainer.getConnectionUri(false), databaseQuery: "SELECT 1 UNION ALL SELECT 2", conditions: "[]", }; const heartbeat = { msg: "", status: PENDING, }; try { await assert.rejects( mssqlMonitor.check(monitor, heartbeat, {}), new Error( "Database connection/query failed: Multiple values were found, expected only one value" ) ); assert.strictEqual( heartbeat.status, PENDING, `Expected status should not be ${heartbeat.status}` ); } finally { await mssqlContainer.stop(); } }); test("check() rejects when query returns multiple columns", async () => { const mssqlContainer = await createAndStartMSSQLContainer(); const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: mssqlContainer.getConnectionUri(false), databaseQuery: "SELECT 1 AS col1, 2 AS col2", conditions: "[]", }; const heartbeat = { msg: "", status: PENDING, }; try { await assert.rejects( mssqlMonitor.check(monitor, heartbeat, {}), new Error( "Database connection/query failed: Multiple columns were found, expected only one value" ) ); assert.strictEqual( heartbeat.status, PENDING, `Expected status should not be ${heartbeat.status}` ); } finally { await mssqlContainer.stop(); } }); test("check() rejects when MSSQL server is not reachable", async () => { const mssqlMonitor = new MssqlMonitorType(); const monitor = { databaseConnectionString: "Server=localhost,15433;Database=master;User Id=Fail;Password=Fail;Encrypt=false", conditions: "[]", }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( mssqlMonitor.check(monitor, heartbeat, {}), new Error( "Database connection/query failed: Failed to connect to localhost:15433 - Could not connect (sequence)" ) ); assert.notStrictEqual( heartbeat.status, UP, `Expected status should not be ${heartbeat.status}` ); }); } );
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitors/test-gamedig.js
test/backend-test/monitors/test-gamedig.js
const { describe, test, mock } = require("node:test"); const assert = require("node:assert"); const { GameDigMonitorType } = require("../../../server/monitor-types/gamedig"); const { UP, PENDING } = require("../../../src/util"); const net = require("net"); const { GameDig } = require("gamedig"); describe("GameDig Monitor", () => { test("check() sets status to UP when Gamedig.query returns valid server response", async () => { const gamedigMonitor = new GameDigMonitorType(); mock.method(GameDig, "query", async () => { return { name: "Test Minecraft Server", ping: 42, players: [], }; }); const monitor = { hostname: "127.0.0.1", port: 25565, game: "minecraft", gamedigGivenPortOnly: true, }; const heartbeat = { msg: "", status: PENDING, }; try { await gamedigMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Test Minecraft Server"); assert.strictEqual(heartbeat.ping, 42); } finally { mock.restoreAll(); } }); test("check() resolves hostname to IP address when hostname is not an IP", async () => { const gamedigMonitor = new GameDigMonitorType(); mock.method(GameDig, "query", async (options) => { assert.ok( net.isIP(options.host) !== 0, `Expected IP address, got ${options.host}` ); return { name: "Test Server", ping: 50, }; }); const monitor = { hostname: "localhost", port: 25565, game: "minecraft", gamedigGivenPortOnly: false, }; const heartbeat = { msg: "", status: PENDING, }; try { await gamedigMonitor.check(monitor, heartbeat, {}); assert.strictEqual(heartbeat.status, UP); assert.strictEqual(heartbeat.msg, "Test Server"); assert.strictEqual(heartbeat.ping, 50); } finally { mock.restoreAll(); } }); test("check() uses IP address directly without DNS resolution when hostname is IPv4", async () => { const gamedigMonitor = new GameDigMonitorType(); let capturedOptions = null; mock.method(GameDig, "query", async (options) => { capturedOptions = options; return { name: "Test Server", ping: 30, }; }); const monitor = { hostname: "192.168.1.100", port: 27015, game: "valve", gamedigGivenPortOnly: true, }; const heartbeat = { msg: "", status: PENDING, }; try { await gamedigMonitor.check(monitor, heartbeat, {}); assert.strictEqual(capturedOptions.host, "192.168.1.100"); assert.strictEqual(heartbeat.status, UP); } finally { mock.restoreAll(); } }); test("check() uses IP address directly without DNS resolution when hostname is IPv6", async () => { const gamedigMonitor = new GameDigMonitorType(); let capturedOptions = null; mock.method(GameDig, "query", async (options) => { capturedOptions = options; return { name: "Test Server", ping: 30, }; }); const monitor = { hostname: "::1", port: 27015, game: "valve", gamedigGivenPortOnly: true, }; const heartbeat = { msg: "", status: PENDING, }; try { await gamedigMonitor.check(monitor, heartbeat, {}); assert.strictEqual(capturedOptions.host, "::1"); assert.strictEqual(heartbeat.status, UP); } finally { mock.restoreAll(); } }); test("check() passes correct parameters to Gamedig.query", async () => { const gamedigMonitor = new GameDigMonitorType(); let capturedOptions = null; mock.method(GameDig, "query", async (options) => { capturedOptions = options; return { name: "Test Server", ping: 25, }; }); const monitor = { hostname: "192.168.1.100", port: 27015, game: "valve", gamedigGivenPortOnly: true, }; const heartbeat = { msg: "", status: PENDING, }; try { await gamedigMonitor.check(monitor, heartbeat, {}); assert.strictEqual(capturedOptions.type, "valve"); assert.strictEqual(capturedOptions.host, "192.168.1.100"); assert.strictEqual(capturedOptions.port, 27015); assert.strictEqual(capturedOptions.givenPortOnly, true); } finally { mock.restoreAll(); } }); test("check() converts gamedigGivenPortOnly to boolean when value is truthy non-boolean", async () => { const gamedigMonitor = new GameDigMonitorType(); let capturedOptions = null; mock.method(GameDig, "query", async (options) => { capturedOptions = options; return { name: "Test Server", ping: 30, }; }); const monitor = { hostname: "127.0.0.1", port: 25565, game: "minecraft", gamedigGivenPortOnly: 1, }; const heartbeat = { msg: "", status: PENDING, }; try { await gamedigMonitor.check(monitor, heartbeat, {}); assert.strictEqual(capturedOptions.givenPortOnly, true); assert.strictEqual(typeof capturedOptions.givenPortOnly, "boolean"); } finally { mock.restoreAll(); } }); test("check() rejects when game server is unreachable", async () => { const gamedigMonitor = new GameDigMonitorType(); const monitor = { hostname: "127.0.0.1", port: 54321, game: "minecraft", gamedigGivenPortOnly: true, }; const heartbeat = { msg: "", status: PENDING, }; await assert.rejects( gamedigMonitor.check(monitor, heartbeat, {}), /Error/ ); }); test("resolveHostname() returns IP address when given valid hostname", async () => { const gamedigMonitor = new GameDigMonitorType(); const resolvedIP = await gamedigMonitor.resolveHostname("localhost"); assert.ok( net.isIP(resolvedIP) !== 0, `Expected valid IP address, got ${resolvedIP}` ); }); test("resolveHostname() rejects when DNS resolution fails for invalid hostname", async () => { const gamedigMonitor = new GameDigMonitorType(); await assert.rejects( gamedigMonitor.resolveHostname("this-domain-definitely-does-not-exist-12345.invalid"), /DNS resolution failed/ ); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitor-conditions/test-expressions.js
test/backend-test/monitor-conditions/test-expressions.js
const test = require("node:test"); const assert = require("node:assert"); const { ConditionExpressionGroup, ConditionExpression } = require("../../../server/monitor-conditions/expression.js"); test("Test ConditionExpressionGroup.fromMonitor", async (t) => { const monitor = { conditions: JSON.stringify([ { "type": "expression", "andOr": "and", "operator": "contains", "value": "foo", "variable": "record" }, { "type": "group", "andOr": "and", "children": [ { "type": "expression", "andOr": "and", "operator": "contains", "value": "bar", "variable": "record" }, { "type": "group", "andOr": "and", "children": [ { "type": "expression", "andOr": "and", "operator": "contains", "value": "car", "variable": "record" } ] }, ] }, ]), }; const root = ConditionExpressionGroup.fromMonitor(monitor); assert.strictEqual(true, root.children.length === 2); assert.strictEqual(true, root.children[0] instanceof ConditionExpression); assert.strictEqual(true, root.children[0].value === "foo"); assert.strictEqual(true, root.children[1] instanceof ConditionExpressionGroup); assert.strictEqual(true, root.children[1].children.length === 2); assert.strictEqual(true, root.children[1].children[0] instanceof ConditionExpression); assert.strictEqual(true, root.children[1].children[0].value === "bar"); assert.strictEqual(true, root.children[1].children[1] instanceof ConditionExpressionGroup); assert.strictEqual(true, root.children[1].children[1].children.length === 1); assert.strictEqual(true, root.children[1].children[1].children[0] instanceof ConditionExpression); assert.strictEqual(true, root.children[1].children[1].children[0].value === "car"); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitor-conditions/test-evaluator.js
test/backend-test/monitor-conditions/test-evaluator.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { ConditionExpressionGroup, ConditionExpression, LOGICAL } = require("../../../server/monitor-conditions/expression.js"); const { evaluateExpressionGroup, evaluateExpression } = require("../../../server/monitor-conditions/evaluator.js"); describe("Expression Evaluator", () => { test("evaluateExpression() returns true when condition matches and false otherwise", () => { const expr = new ConditionExpression("record", "contains", "mx1.example.com"); assert.strictEqual(true, evaluateExpression(expr, { record: "mx1.example.com" })); assert.strictEqual(false, evaluateExpression(expr, { record: "mx2.example.com" })); }); test("evaluateExpressionGroup() with AND logic requires all conditions to be true", () => { const group = new ConditionExpressionGroup([ new ConditionExpression("record", "contains", "mx1."), new ConditionExpression("record", "contains", "example.com", LOGICAL.AND), ]); assert.strictEqual(true, evaluateExpressionGroup(group, { record: "mx1.example.com" })); assert.strictEqual(false, evaluateExpressionGroup(group, { record: "mx1." })); assert.strictEqual(false, evaluateExpressionGroup(group, { record: "example.com" })); }); test("evaluateExpressionGroup() with OR logic requires at least one condition to be true", () => { const group = new ConditionExpressionGroup([ new ConditionExpression("record", "contains", "example.com"), new ConditionExpression("record", "contains", "example.org", LOGICAL.OR), ]); assert.strictEqual(true, evaluateExpressionGroup(group, { record: "example.com" })); assert.strictEqual(true, evaluateExpressionGroup(group, { record: "example.org" })); assert.strictEqual(false, evaluateExpressionGroup(group, { record: "example.net" })); }); test("evaluateExpressionGroup() evaluates nested groups correctly", () => { const group = new ConditionExpressionGroup([ new ConditionExpression("record", "contains", "mx1."), new ConditionExpressionGroup([ new ConditionExpression("record", "contains", "example.com"), new ConditionExpression("record", "contains", "example.org", LOGICAL.OR), ]), ]); assert.strictEqual(false, evaluateExpressionGroup(group, { record: "mx1." })); assert.strictEqual(true, evaluateExpressionGroup(group, { record: "mx1.example.com" })); assert.strictEqual(true, evaluateExpressionGroup(group, { record: "mx1.example.org" })); assert.strictEqual(false, evaluateExpressionGroup(group, { record: "example.com" })); assert.strictEqual(false, evaluateExpressionGroup(group, { record: "example.org" })); assert.strictEqual(false, evaluateExpressionGroup(group, { record: "mx1.example.net" })); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/backend-test/monitor-conditions/test-operators.js
test/backend-test/monitor-conditions/test-operators.js
const { describe, test } = require("node:test"); const assert = require("node:assert"); const { operatorMap, OP_CONTAINS, OP_NOT_CONTAINS, OP_LT, OP_GT, OP_LTE, OP_GTE, OP_STR_EQUALS, OP_STR_NOT_EQUALS, OP_NUM_EQUALS, OP_NUM_NOT_EQUALS, OP_STARTS_WITH, OP_ENDS_WITH, OP_NOT_STARTS_WITH, OP_NOT_ENDS_WITH } = require("../../../server/monitor-conditions/operators.js"); describe("Expression Operators", () => { test("StringEqualsOperator returns true for identical strings and false otherwise", () => { const op = operatorMap.get(OP_STR_EQUALS); assert.strictEqual(true, op.test("mx1.example.com", "mx1.example.com")); assert.strictEqual(false, op.test("mx1.example.com", "mx1.example.org")); assert.strictEqual(false, op.test("1", 1)); // strict equality }); test("StringNotEqualsOperator returns true for different strings and false for identical strings", () => { const op = operatorMap.get(OP_STR_NOT_EQUALS); assert.strictEqual(true, op.test("mx1.example.com", "mx1.example.org")); assert.strictEqual(false, op.test("mx1.example.com", "mx1.example.com")); assert.strictEqual(true, op.test(1, "1")); // variable is not typecasted (strict equality) }); test("ContainsOperator returns true when scalar contains substring", () => { const op = operatorMap.get(OP_CONTAINS); assert.strictEqual(true, op.test("mx1.example.org", "example.org")); assert.strictEqual(false, op.test("mx1.example.org", "example.com")); }); test("ContainsOperator returns true when array contains element", () => { const op = operatorMap.get(OP_CONTAINS); assert.strictEqual(true, op.test([ "example.org" ], "example.org")); assert.strictEqual(false, op.test([ "example.org" ], "example.com")); }); test("NotContainsOperator returns true when scalar does not contain substring", () => { const op = operatorMap.get(OP_NOT_CONTAINS); assert.strictEqual(true, op.test("example.org", ".com")); assert.strictEqual(false, op.test("example.org", ".org")); }); test("NotContainsOperator returns true when array does not contain element", () => { const op = operatorMap.get(OP_NOT_CONTAINS); assert.strictEqual(true, op.test([ "example.org" ], "example.com")); assert.strictEqual(false, op.test([ "example.org" ], "example.org")); }); test("StartsWithOperator returns true when string starts with prefix", () => { const op = operatorMap.get(OP_STARTS_WITH); assert.strictEqual(true, op.test("mx1.example.com", "mx1")); assert.strictEqual(false, op.test("mx1.example.com", "mx2")); }); test("NotStartsWithOperator returns true when string does not start with prefix", () => { const op = operatorMap.get(OP_NOT_STARTS_WITH); assert.strictEqual(true, op.test("mx1.example.com", "mx2")); assert.strictEqual(false, op.test("mx1.example.com", "mx1")); }); test("EndsWithOperator returns true when string ends with suffix", () => { const op = operatorMap.get(OP_ENDS_WITH); assert.strictEqual(true, op.test("mx1.example.com", "example.com")); assert.strictEqual(false, op.test("mx1.example.com", "example.net")); }); test("NotEndsWithOperator returns true when string does not end with suffix", () => { const op = operatorMap.get(OP_NOT_ENDS_WITH); assert.strictEqual(true, op.test("mx1.example.com", "example.net")); assert.strictEqual(false, op.test("mx1.example.com", "example.com")); }); test("NumberEqualsOperator returns true for equal numbers with type coercion", () => { const op = operatorMap.get(OP_NUM_EQUALS); assert.strictEqual(true, op.test(1, 1)); assert.strictEqual(true, op.test(1, "1")); assert.strictEqual(false, op.test(1, "2")); }); test("NumberNotEqualsOperator returns true for different numbers", () => { const op = operatorMap.get(OP_NUM_NOT_EQUALS); assert.strictEqual(true, op.test(1, "2")); assert.strictEqual(false, op.test(1, "1")); }); test("LessThanOperator returns true when first number is less than second", () => { const op = operatorMap.get(OP_LT); assert.strictEqual(true, op.test(1, 2)); assert.strictEqual(true, op.test(1, "2")); assert.strictEqual(false, op.test(1, 1)); }); test("GreaterThanOperator returns true when first number is greater than second", () => { const op = operatorMap.get(OP_GT); assert.strictEqual(true, op.test(2, 1)); assert.strictEqual(true, op.test(2, "1")); assert.strictEqual(false, op.test(1, 1)); }); test("LessThanOrEqualToOperator returns true when first number is less than or equal to second", () => { const op = operatorMap.get(OP_LTE); assert.strictEqual(true, op.test(1, 1)); assert.strictEqual(true, op.test(1, 2)); assert.strictEqual(true, op.test(1, "2")); assert.strictEqual(false, op.test(1, 0)); }); test("GreaterThanOrEqualToOperator returns true when first number is greater than or equal to second", () => { const op = operatorMap.get(OP_GTE); assert.strictEqual(true, op.test(1, 1)); assert.strictEqual(true, op.test(2, 1)); assert.strictEqual(true, op.test(2, "2")); assert.strictEqual(false, op.test(2, 3)); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/e2e/util-test.js
test/e2e/util-test.js
const fs = require("fs"); const path = require("path"); const serverUrl = require("../../config/playwright.config.js").url; const dbPath = "./../../data/playwright-test/kuma.db"; /** * @param {TestInfo} testInfo Test info * @param {Page} page Page * @returns {Promise<void>} */ export async function screenshot(testInfo, page) { const screenshot = await page.screenshot(); await testInfo.attach("screenshot", { body: screenshot, contentType: "image/png" }); } /** * @param {Page} page Page * @returns {Promise<void>} */ export async function login(page) { // Login await page.getByPlaceholder("Username").click(); await page.getByPlaceholder("Username").fill("admin"); await page.getByPlaceholder("Username").press("Tab"); await page.getByPlaceholder("Password").fill("admin123"); await page.getByLabel("Remember me").check(); await page.getByRole("button", { name: "Log in" }).click(); await page.isVisible("text=Add New Monitor"); } /** * Determines if the SQLite database has been created. This indicates setup has completed. * @returns {boolean} True if exists */ export function getSqliteDatabaseExists() { return fs.existsSync(path.resolve(__dirname, dbPath)); } /** * Makes a request to the server to take a snapshot of the SQLite database. * @param {Page|null} page Page * @returns {Promise<Response>} Promise of response from snapshot request. */ export async function takeSqliteSnapshot(page = null) { if (page) { return page.goto("./_e2e/take-sqlite-snapshot"); } else { return fetch(`${serverUrl}/_e2e/take-sqlite-snapshot`); } } /** * Makes a request to the server to restore the snapshot of the SQLite database. * @returns {Promise<Response>} Promise of response from restoration request. */ export async function restoreSqliteSnapshot() { return fetch(`${serverUrl}/_e2e/restore-sqlite-snapshot`); }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/e2e/specs/status-page.spec.js
test/e2e/specs/status-page.spec.js
import { expect, test } from "@playwright/test"; import { login, restoreSqliteSnapshot, screenshot } from "../util-test"; test.describe("Status Page", () => { test.beforeEach(async ({ page }) => { await restoreSqliteSnapshot(page); }); test("create and edit", async ({ page }, testInfo) => { test.setTimeout(60000); // Keep the timeout increase for stability // Monitor const monitorName = "Monitor for Status Page"; const tagName = "Client"; const tagValue = "Acme Inc"; const tagName2 = "Project"; // Add second tag name const tagValue2 = "Phoenix"; // Add second tag value const monitorUrl = "https://www.example.com/status"; const monitorCustomUrl = "https://www.example.com"; // Status Page const footerText = "This is footer text."; const refreshInterval = 30; const theme = "dark"; const googleAnalyticsId = "G-123"; const umamiAnalyticsScriptUrl = "https://umami.example.com/script.js"; const umamiAnalyticsWebsiteId = "606487e2-bc25-45f9-9132-fa8b065aad46"; const plausibleAnalyticsScriptUrl = "https://plausible.example.com/js/script.js"; const plausibleAnalyticsDomainsUrls = "one.com,two.com"; const matomoUrl = "https://matomoto.example.com"; const matomoSiteId = "123456789"; const customCss = "body { background: rgb(0, 128, 128) !important; }"; const descriptionText = "This is an example status page."; const incidentTitle = "Example Outage Incident"; const incidentContent = "Sample incident message."; const groupName = "Example Group 1"; // Set up a monitor that can be added to the Status Page await page.goto("./add"); await login(page); await expect(page.getByTestId("monitor-type-select")).toBeVisible(); await page.getByTestId("monitor-type-select").selectOption("http"); await page.getByTestId("friendly-name-input").fill(monitorName); await page.getByTestId("url-input").fill(monitorUrl); // Modified tag section to add multiple tags await page.getByTestId("add-tag-button").click(); await page.getByTestId("tag-name-input").fill(tagName); await page.getByTestId("tag-value-input").fill(tagValue); await page.getByTestId("tag-color-select").click(); // Vue-Multiselect component await page.getByTestId("tag-color-select").getByRole("option", { name: "Orange" }).click(); // Add another tag instead of submitting directly await page.getByRole("button", { name: "Add Another Tag" }).click(); // Add second tag await page.getByTestId("tag-name-input").fill(tagName2); await page.getByTestId("tag-value-input").fill(tagValue2); await page.getByTestId("tag-color-select").click(); await page.getByTestId("tag-color-select").getByRole("option", { name: "Blue" }).click(); // Submit both tags await page.getByTestId("add-tags-final-button").click(); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); // wait for the monitor to be created // Create a new status page await page.goto("./add-status-page"); await screenshot(testInfo, page); await page.getByTestId("name-input").fill("Example"); await page.getByTestId("slug-input").fill("example"); await page.getByTestId("submit-button").click(); await page.waitForURL("/status/example?edit"); // wait for the page to be created // Fill in some details await page.getByTestId("description-input").fill(descriptionText); await page.getByTestId("footer-text-input").fill(footerText); await page.getByTestId("refresh-interval-input").fill(String(refreshInterval)); await page.getByTestId("theme-select").selectOption(theme); await page.getByTestId("show-tags-checkbox").uncheck(); await page.getByTestId("show-powered-by-checkbox").uncheck(); await page.getByTestId("show-certificate-expiry-checkbox").uncheck(); await page.getByTestId("analytics-type-select").selectOption("google"); await page.getByTestId("analytics-id-input").fill(googleAnalyticsId); await page.getByTestId("custom-css-input").getByTestId("textarea").fill(customCss); // Prism // Add an incident await page.getByTestId("create-incident-button").click(); await page.getByTestId("incident-title").isEditable(); await page.getByTestId("incident-title").fill(incidentTitle); await page.getByTestId("incident-content-editable").fill(incidentContent); await page.getByTestId("post-incident-button").click(); // Add a group await page.getByTestId("add-group-button").click(); await page.getByTestId("group-name").isEditable(); await page.getByTestId("group-name").fill(groupName); // Add the monitor await page.getByTestId("monitor-select").click(); // Vue-Multiselect component await page.getByTestId("monitor-select").getByRole("option", { name: monitorName }).click(); await expect(page.getByTestId("monitor")).toHaveCount(1); await expect(page.getByTestId("monitor-name")).toContainText(monitorName); await expect(page.getByTestId("monitor-name")).not.toHaveAttribute("href"); // Set public url on await page.getByTestId("monitor-settings").click(); await page.getByTestId("show-clickable-link").check(); await page.getByTestId("custom-url-input").fill(monitorCustomUrl); await page.getByTestId("monitor-settings-close").click(); // Save the changes await screenshot(testInfo, page); await page.getByTestId("save-button").click(); await expect(page.getByTestId("edit-sidebar")).toHaveCount(0); // Ensure changes are visible await expect(page.getByTestId("incident")).toHaveCount(1); await expect(page.getByTestId("incident-title")).toContainText(incidentTitle); await expect(page.getByTestId("incident-content")).toContainText(incidentContent); await expect(page.getByTestId("group-name")).toContainText(groupName); await expect(page.getByTestId("powered-by")).toHaveCount(0); await expect(page.getByTestId("monitor-name")).toHaveAttribute("href", monitorCustomUrl); await expect(page.getByTestId("update-countdown-text")).toContainText("00:"); const updateCountdown = Number((await page.getByTestId("update-countdown-text").textContent()).match(/(\d+):(\d+)/)[2]); expect(updateCountdown).toBeGreaterThanOrEqual(refreshInterval - 10); // cant be certain when the timer will start, so ensure it's within expected range expect(updateCountdown).toBeLessThanOrEqual(refreshInterval); await expect(page.locator("body")).toHaveClass(theme); // Add Google Analytics ID to head and verify await page.waitForFunction(() => { return document.head.innerHTML.includes("https://www.googletagmanager.com/gtag/js?id="); }, { timeout: 5000 }); expect(await page.locator("head").innerHTML()).toContain(googleAnalyticsId); const backgroundColor = await page.evaluate(() => window.getComputedStyle(document.body).backgroundColor); expect(backgroundColor).toEqual("rgb(0, 128, 128)"); await screenshot(testInfo, page); expect(await page.locator("head").innerHTML()).toContain(googleAnalyticsId); // Flip the "Show Tags" and "Show Powered By" switches: await page.getByTestId("edit-button").click(); await expect(page.getByTestId("edit-sidebar")).toHaveCount(1); await page.getByTestId("show-tags-checkbox").setChecked(true); await page.getByTestId("show-powered-by-checkbox").setChecked(true); await screenshot(testInfo, page); // Fill in umami analytics after editing await page.getByTestId("analytics-type-select").selectOption("umami"); await page.getByTestId("analytics-script-url-input").fill(umamiAnalyticsScriptUrl); await page.getByTestId("analytics-id-input").fill(umamiAnalyticsWebsiteId); await page.getByTestId("save-button").click(); await expect(page.getByTestId("edit-sidebar")).toHaveCount(0); await expect(page.getByTestId("powered-by")).toContainText("Powered by"); // Modified tag verification to check both tags await expect(page.getByTestId("monitor-tag").filter({ hasText: tagValue })).toBeVisible(); await expect(page.getByTestId("monitor-tag").filter({ hasText: tagValue2 })).toBeVisible(); await screenshot(testInfo, page); expect(await page.locator("head").innerHTML()).toContain(umamiAnalyticsScriptUrl); expect(await page.locator("head").innerHTML()).toContain(umamiAnalyticsWebsiteId); await page.getByTestId("edit-button").click(); // Fill in plausible analytics after editing await page.getByTestId("analytics-type-select").selectOption("plausible"); await page.getByTestId("analytics-script-url-input").fill(plausibleAnalyticsScriptUrl); await page.getByTestId("analytics-id-input").fill(plausibleAnalyticsDomainsUrls); await page.getByTestId("save-button").click(); await screenshot(testInfo, page); expect(await page.locator("head").innerHTML()).toContain(plausibleAnalyticsScriptUrl); expect(await page.locator("head").innerHTML()).toContain(plausibleAnalyticsDomainsUrls); await page.getByTestId("edit-button").click(); // Fill in matomo analytics after editing await page.getByTestId("analytics-type-select").selectOption("matomo"); await page.getByTestId("analytics-script-url-input").fill(matomoUrl); await page.getByTestId("analytics-id-input").fill(matomoSiteId); await page.getByTestId("save-button").click(); await screenshot(testInfo, page); expect(await page.locator("head").innerHTML()).toContain(matomoUrl); expect(await page.locator("head").innerHTML()).toContain(matomoSiteId); }); // @todo Test certificate expiry // @todo Test domain names test("RSS feed escapes malicious monitor names", async ({ page }, testInfo) => { test.setTimeout(60000); // Test various XSS payloads in monitor names const maliciousMonitorName1 = "<script>alert(1)</script>"; const maliciousMonitorName2 = "x</title><script>alert(document.domain)</script><title>"; const normalMonitorName = "Production API Server"; await page.goto("./add"); await login(page); // Create first monitor with script tag payload await expect(page.getByTestId("monitor-type-select")).toBeVisible(); await page.getByTestId("monitor-type-select").selectOption("http"); await page.getByTestId("friendly-name-input").fill(maliciousMonitorName1); await page.getByTestId("url-input").fill("https://malicious1.example.com"); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); // Create second monitor with title breakout payload await page.goto("./add"); await page.getByTestId("monitor-type-select").selectOption("http"); await page.getByTestId("friendly-name-input").fill(maliciousMonitorName2); await page.getByTestId("url-input").fill("https://malicious2.example.com"); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); // Create third monitor with normal name await page.goto("./add"); await page.getByTestId("monitor-type-select").selectOption("http"); await page.getByTestId("friendly-name-input").fill(normalMonitorName); await page.getByTestId("url-input").fill("https://normal.example.com"); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); // Create a status page await page.goto("./add-status-page"); await page.getByTestId("name-input").fill("Security Test"); await page.getByTestId("slug-input").fill("security-test"); await page.getByTestId("submit-button").click(); await page.waitForURL("/status/security-test?edit"); // Add a group and all monitors await page.getByTestId("add-group-button").click(); await page.getByTestId("group-name").fill("Test Group"); // Add all three monitors await page.getByTestId("monitor-select").click(); await page.getByTestId("monitor-select").getByRole("option", { name: maliciousMonitorName1 }).click(); await page.getByTestId("monitor-select").click(); await page.getByTestId("monitor-select").getByRole("option", { name: maliciousMonitorName2 }).click(); await page.getByTestId("monitor-select").click(); await page.getByTestId("monitor-select").getByRole("option", { name: normalMonitorName }).click(); await page.getByTestId("save-button").click(); await expect(page.getByTestId("edit-sidebar")).toHaveCount(0); // Fetch the RSS feed const rssResponse = await page.request.get("/status/security-test/rss"); expect(rssResponse.status()).toBe(200); expect(rssResponse.headers()["content-type"]).toBe("application/rss+xml; charset=utf-8"); expect(rssResponse.ok()).toBeTruthy(); const rssContent = await rssResponse.text(); // Attach RSS content for inspection await testInfo.attach("rss-feed.xml", { body: rssContent, contentType: "application/xml" }); // Verify all payloads are escaped using CDATA expect(rssContent).toContain(`<title><![CDATA[${maliciousMonitorName1} is down]]></title>`); expect(rssContent).toContain(`<title><![CDATA[${maliciousMonitorName2} is down]]></title>`); expect(rssContent).toContain(`<title><![CDATA[${normalMonitorName} is down]]></title>`); // Verify RSS feed structure is valid expect(rssContent).toContain("<?xml version=\"1.0\""); expect(rssContent).toContain("<rss"); expect(rssContent).toContain("</rss>"); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/e2e/specs/monitor-form.spec.js
test/e2e/specs/monitor-form.spec.js
import { expect, test } from "@playwright/test"; import { login, restoreSqliteSnapshot, screenshot } from "../util-test"; /** * Selects the monitor type from the dropdown. * @param {import('@playwright/test').Page} page - The Playwright page instance. * @param {string} monitorType - The monitor type to select (default is "dns"). * @returns {Promise<void>} - A promise that resolves when the monitor type is selected. */ async function selectMonitorType(page, monitorType = "dns") { const monitorTypeSelect = page.getByTestId("monitor-type-select"); await expect(monitorTypeSelect).toBeVisible(); await monitorTypeSelect.selectOption(monitorType); const selectedValue = await monitorTypeSelect.evaluate((select) => select.value); expect(selectedValue).toBe(monitorType); } test.describe("Monitor Form", () => { test.beforeEach(async ({ page }) => { await restoreSqliteSnapshot(page); }); test("condition ui", async ({ page }, testInfo) => { await page.goto("./add"); await login(page); await screenshot(testInfo, page); await selectMonitorType(page); await page.getByTestId("add-condition-button").click(); expect(await page.getByTestId("condition").count()).toEqual(1); // 1 explicitly added await page.getByTestId("add-group-button").click(); expect(await page.getByTestId("condition-group").count()).toEqual(1); expect(await page.getByTestId("condition").count()).toEqual(2); // 1 solo conditions + 1 condition in group await screenshot(testInfo, page); await page.getByTestId("remove-condition").first().click(); expect(await page.getByTestId("condition").count()).toEqual(1); // 0 solo condition + 1 condition in group await page.getByTestId("remove-condition-group").first().click(); expect(await page.getByTestId("condition-group").count()).toEqual(0); await screenshot(testInfo, page); }); test("successful condition", async ({ page }, testInfo) => { await page.goto("./add"); await login(page); await screenshot(testInfo, page); await selectMonitorType(page); const friendlyName = "Example DNS NS"; await page.getByTestId("friendly-name-input").fill(friendlyName); await page.getByTestId("hostname-input").fill("kuma.pet"); const resolveTypeSelect = page.getByTestId("resolve-type-select"); await resolveTypeSelect.click(); await resolveTypeSelect.getByRole("option", { name: "NS" }).click(); await page.getByTestId("add-condition-button").click(); expect(await page.getByTestId("condition").count()).toEqual(1); // 1 explicitly added await page.getByTestId("add-condition-button").click(); expect(await page.getByTestId("condition").count()).toEqual(2); // 2 explicitly added await page.getByTestId("condition-value").nth(0).fill("carl.ns.cloudflare.com"); await page.getByTestId("condition-and-or").nth(0).selectOption("or"); await page.getByTestId("condition-value").nth(1).fill("jean.ns.cloudflare.com"); await screenshot(testInfo, page); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); await expect(page.getByTestId("monitor-status")).toHaveText("up", { ignoreCase: true }); await screenshot(testInfo, page); }); test("failing condition", async ({ page }, testInfo) => { await page.goto("./add"); await login(page); await screenshot(testInfo, page); await selectMonitorType(page); const friendlyName = "Example DNS NS"; await page.getByTestId("friendly-name-input").fill(friendlyName); await page.getByTestId("hostname-input").fill("kuma.pet"); const resolveTypeSelect = page.getByTestId("resolve-type-select"); await resolveTypeSelect.click(); await resolveTypeSelect.getByRole("option", { name: "NS" }).click(); await page.getByTestId("add-condition-button").click(); expect(await page.getByTestId("condition").count()).toEqual(1); // 1 explicitly added await page.getByTestId("condition-value").nth(0).fill("definitely-not.net"); await screenshot(testInfo, page); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); await expect(page.getByTestId("monitor-status")).toHaveText("down", { ignoreCase: true }); await screenshot(testInfo, page); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/e2e/specs/fridendly-name.spec.js
test/e2e/specs/fridendly-name.spec.js
import { expect, test } from "@playwright/test"; import { login, restoreSqliteSnapshot, screenshot } from "../util-test"; test.describe("Friendly Name Tests", () => { test.beforeEach(async ({ page }) => { await restoreSqliteSnapshot(page); }); test("hostname", async ({ page }, testInfo) => { // Test DNS monitor with hostname await page.goto("./add"); await login(page); await screenshot(testInfo, page); await page.getByTestId("monitor-type-select").selectOption("dns"); await page.getByTestId("hostname-input").fill("example.com"); await screenshot(testInfo, page); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); expect(page.getByTestId("monitor-list")).toContainText("example.com"); await screenshot(testInfo, page); }); test("URL hostname", async ({ page }, testInfo) => { // Test HTTP monitor with URL await page.goto("./add"); await login(page); await screenshot(testInfo, page); await page.getByTestId("monitor-type-select").selectOption("http"); await page.getByTestId("url-input").fill("https://www.example.com/"); await screenshot(testInfo, page); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); expect(page.getByTestId("monitor-list")).toContainText("www.example.com"); await screenshot(testInfo, page); }); test("custom friendly name", async ({ page }, testInfo) => { // Test custom friendly name for HTTP monitor await page.goto("./add"); await login(page); await screenshot(testInfo, page); await page.getByTestId("monitor-type-select").selectOption("http"); await page.getByTestId("url-input").fill("https://www.example.com/"); // Check if the friendly name placeholder is set to the hostname const friendlyNameInput = page.getByTestId("friendly-name-input"); expect(friendlyNameInput).toHaveAttribute("placeholder", "www.example.com"); await screenshot(testInfo, page); const customName = "Example Monitor"; await friendlyNameInput.fill(customName); await screenshot(testInfo, page); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); expect(page.getByTestId("monitor-list")).toContainText(customName); await screenshot(testInfo, page); }); test("default friendly name", async ({ page }, testInfo) => { // Test default friendly name when no custom name is provided await page.goto("./add"); await login(page); await screenshot(testInfo, page); await page.getByTestId("monitor-type-select").selectOption("group"); await screenshot(testInfo, page); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); expect(page.getByTestId("monitor-list")).toContainText("New Monitor"); await screenshot(testInfo, page); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/e2e/specs/setup-process.once.js
test/e2e/specs/setup-process.once.js
import { test } from "@playwright/test"; import { getSqliteDatabaseExists, login, screenshot, takeSqliteSnapshot } from "../util-test"; test.describe("Uptime Kuma Setup", () => { test.skip(() => getSqliteDatabaseExists(), "Must only run once per session"); test.afterEach(async ({ page }, testInfo) => { await screenshot(testInfo, page); }); /* * Setup */ test("setup sqlite", async ({ page }, testInfo) => { await page.goto("./"); await page.getByText("SQLite").click(); await page.getByRole("button", { name: "Next" }).click(); await screenshot(testInfo, page); await page.waitForURL("/setup"); // ensures the server is ready to continue to the next test }); test("setup admin", async ({ page }) => { await page.goto("./"); await page.getByPlaceholder("Username").click(); await page.getByPlaceholder("Username").fill("admin"); await page.getByPlaceholder("Username").press("Tab"); await page.getByPlaceholder("Password", { exact: true }).fill("admin123"); await page.getByPlaceholder("Password", { exact: true }).press("Tab"); await page.getByPlaceholder("Repeat Password").fill("admin123"); await page.getByRole("button", { name: "Create" }).click(); }); /* * All other tests should be run after setup */ test("login", async ({ page }) => { await page.goto("./dashboard"); await login(page); }); test("logout", async ({ page }) => { await page.goto("./dashboard"); await login(page); await page.getByText("A", { exact: true }).click(); await page.getByRole("button", { name: "Log out" }).click(); }); test("take sqlite snapshot", async ({ page }) => { await takeSqliteSnapshot(page); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/e2e/specs/example.spec.js
test/e2e/specs/example.spec.js
import { expect, test } from "@playwright/test"; import { login, restoreSqliteSnapshot, screenshot } from "../util-test"; test.describe("Example Spec", () => { test.beforeEach(async ({ page }) => { await restoreSqliteSnapshot(page); }); test("dashboard", async ({ page }, testInfo) => { await page.goto("./dashboard"); await login(page); await screenshot(testInfo, page); }); test("set up monitor", async ({ page }, testInfo) => { await page.goto("./add"); await login(page); await expect(page.getByTestId("monitor-type-select")).toBeVisible(); await page.getByTestId("monitor-type-select").selectOption("http"); await page.getByTestId("friendly-name-input").fill("example.com"); await page.getByTestId("url-input").fill("https://www.example.com/"); await page.getByTestId("save-button").click(); await page.waitForURL("/dashboard/*"); // wait for the monitor to be created await expect(page.getByTestId("monitor-list")).toContainText("example.com"); await screenshot(testInfo, page); }); test("database is reset after previous test", async ({ page }, testInfo) => { await page.goto("./dashboard"); await login(page); await expect(page.getByTestId("monitor-list")).not.toContainText("example.com"); await screenshot(testInfo, page); }); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/manual-test-grpc/simple-grpc-server.js
test/manual-test-grpc/simple-grpc-server.js
const grpc = require("@grpc/grpc-js"); const protoLoader = require("@grpc/proto-loader"); const packageDef = protoLoader.loadSync("echo.proto", {}); const grpcObject = grpc.loadPackageDefinition(packageDef); const { echo } = grpcObject; /** * Echo service implementation * @param {object} call Call object * @param {Function} callback Callback function * @returns {void} */ function Echo(call, callback) { callback(null, { message: call.request.message }); } const server = new grpc.Server(); server.addService(echo.EchoService.service, { Echo }); server.bindAsync("0.0.0.0:50051", grpc.ServerCredentials.createInsecure(), () => { console.log("gRPC server running on :50051"); server.start(); });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/deploy-demo-server.js
extra/deploy-demo-server.js
require("dotenv").config(); const { NodeSSH } = require("node-ssh"); const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const prompt = (query) => new Promise((resolve) => rl.question(query, resolve)); (async () => { try { console.log("SSH to demo server"); const ssh = new NodeSSH(); await ssh.connect({ host: process.env.UPTIME_KUMA_DEMO_HOST, port: process.env.UPTIME_KUMA_DEMO_PORT, username: process.env.UPTIME_KUMA_DEMO_USERNAME, privateKeyPath: process.env.UPTIME_KUMA_DEMO_PRIVATE_KEY_PATH }); let cwd = process.env.UPTIME_KUMA_DEMO_CWD; let result; const version = await prompt("Enter Version: "); result = await ssh.execCommand("git fetch --all", { cwd, }); console.log(result.stdout + result.stderr); await prompt("Press any key to continue..."); result = await ssh.execCommand(`git checkout ${version} --force`, { cwd, }); console.log(result.stdout + result.stderr); result = await ssh.execCommand("npm run download-dist", { cwd, }); console.log(result.stdout + result.stderr); result = await ssh.execCommand("npm install --production", { cwd, }); console.log(result.stdout + result.stderr); /* result = await ssh.execCommand("pm2 restart 1", { cwd, }); console.log(result.stdout + result.stderr);*/ } catch (e) { console.log(e); } finally { rl.close(); } })(); // When done reading prompt, exit program rl.on("close", () => process.exit(0));
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/mark-as-nightly.js
extra/mark-as-nightly.js
const pkg = require("../package.json"); const fs = require("fs"); const util = require("../src/util"); const dayjs = require("dayjs"); util.polyfill(); const oldVersion = pkg.version; const newVersion = oldVersion + "-nightly-" + dayjs().format("YYYYMMDDHHmmss"); console.log("Old Version: " + oldVersion); console.log("New Version: " + newVersion); if (newVersion) { // Process package.json pkg.version = newVersion; pkg.scripts.setup = pkg.scripts.setup.replaceAll(oldVersion, newVersion); fs.writeFileSync("package.json", JSON.stringify(pkg, null, 4) + "\n"); // Process README.md if (fs.existsSync("README.md")) { fs.writeFileSync("README.md", fs.readFileSync("README.md", "utf8").replaceAll(oldVersion, newVersion)); } }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/sort-contributors.js
extra/sort-contributors.js
const fs = require("fs"); // Read the file from private/sort-contributors.txt const file = fs.readFileSync("private/sort-contributors.txt", "utf8"); // Convert to an array of lines let lines = file.split("\n"); // Remove empty lines lines = lines.filter((line) => line !== ""); // Remove duplicates lines = [ ...new Set(lines) ]; // Remove @weblate and @UptimeKumaBot lines = lines.filter((line) => line !== "@weblate" && line !== "@UptimeKumaBot" && line !== "@louislam"); // Sort the lines lines = lines.sort(); // Output the lines, concat with " " console.log(lines.join(" "));
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/remove-empty-lang-keys.js
extra/remove-empty-lang-keys.js
// For #5231 const fs = require("fs"); let path = "../src/lang"; // list directories in the lang directory let jsonFileList = fs.readdirSync(path); for (let jsonFile of jsonFileList) { if (!jsonFile.endsWith(".json")) { continue; } let jsonPath = path + "/" + jsonFile; let langData = JSON.parse(fs.readFileSync(jsonPath, "utf8")); for (let key in langData) { if (langData[key] === "") { delete langData[key]; } } fs.writeFileSync(jsonPath, JSON.stringify(langData, null, 4) + "\n"); }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/rebase-pr.js
extra/rebase-pr.js
const { execSync } = require("child_process"); /** * Rebase a PR onto such as 1.23.X or master * @returns {Promise<void>} */ async function main() { const branch = process.argv[2]; // Use gh to get current branch's pr id let currentBranchPRID = execSync("gh pr view --json number --jq \".number\"").toString().trim(); console.log("Pr ID: ", currentBranchPRID); // Use gh commend to get pr commits const prCommits = JSON.parse(execSync(`gh pr view ${currentBranchPRID} --json commits`).toString().trim()).commits; console.log("Found commits: ", prCommits.length); // Sort the commits by authoredDate prCommits.sort((a, b) => { return new Date(a.authoredDate) - new Date(b.authoredDate); }); // Get the oldest commit id const oldestCommitID = prCommits[0].oid; console.log("Oldest commit id of this pr:", oldestCommitID); // Get the latest commit id of the target branch const latestCommitID = execSync(`git rev-parse origin/${branch}`).toString().trim(); console.log("Latest commit id of " + branch + ":", latestCommitID); // Get the original parent commit id of the oldest commit const originalParentCommitID = execSync(`git log --pretty=%P -n 1 "${oldestCommitID}"`).toString().trim(); console.log("Original parent commit id of the oldest commit:", originalParentCommitID); // Rebase the pr onto the target branch execSync(`git rebase --onto ${latestCommitID} ${originalParentCommitID}`); } main();
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/simple-dns-server.js
extra/simple-dns-server.js
/* * Simple DNS Server * For testing DNS monitoring type, dev only */ const dns2 = require("dns2"); const { Packet } = dns2; const server = dns2.createServer({ udp: true }); server.on("request", (request, send, rinfo) => { for (let question of request.questions) { console.log(question.name, type(question.type), question.class); const response = Packet.createResponseFromRequest(request); if (question.name === "existing.com") { if (question.type === Packet.TYPE.A) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, address: "1.2.3.4" }); } else if (question.type === Packet.TYPE.AAAA) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, address: "fe80::::1234:5678:abcd:ef00", }); } else if (question.type === Packet.TYPE.CNAME) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, domain: "cname1.existing.com", }); } else if (question.type === Packet.TYPE.MX) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, exchange: "mx1.existing.com", priority: 5 }); } else if (question.type === Packet.TYPE.NS) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, ns: "ns1.existing.com", }); } else if (question.type === Packet.TYPE.SOA) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, primary: "existing.com", admin: "admin@existing.com", serial: 2021082701, refresh: 300, retry: 3, expiration: 10, minimum: 10, }); } else if (question.type === Packet.TYPE.SRV) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, priority: 5, weight: 5, port: 8080, target: "srv1.existing.com", }); } else if (question.type === Packet.TYPE.TXT) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, data: "#v=spf1 include:_spf.existing.com ~all", }); } else if (question.type === Packet.TYPE.CAA) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, flags: 0, tag: "issue", value: "ca.existing.com", }); } } if (question.name === "4.3.2.1.in-addr.arpa") { if (question.type === Packet.TYPE.PTR) { response.answers.push({ name: question.name, type: question.type, class: question.class, ttl: 300, domain: "ptr1.existing.com", }); } } send(response); } }); server.on("listening", () => { console.log("Listening"); console.log(server.addresses()); }); server.on("close", () => { console.log("server closed"); }); server.listen({ udp: 5300 }); /** * Get human readable request type from request code * @param {number} code Request code to translate * @returns {string|void} Human readable request type */ function type(code) { for (let name in Packet.TYPE) { if (Packet.TYPE[name] === code) { return name; } } }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/simple-mqtt-server.js
extra/simple-mqtt-server.js
const { log } = require("../src/util"); const mqttUsername = "louis1"; const mqttPassword = "!@#$LLam"; class SimpleMqttServer { aedes = require("aedes")(); server = require("net").createServer(this.aedes.handle); /** * @param {number} port Port to listen on */ constructor(port) { this.port = port; } /** * Start the MQTT server * @returns {void} */ start() { this.server.listen(this.port, () => { console.log("server started and listening on port ", this.port); }); } } let server1 = new SimpleMqttServer(10000); server1.aedes.authenticate = function (client, username, password, callback) { if (username && password) { console.log(password.toString("utf-8")); callback(null, username === mqttUsername && password.toString("utf-8") === mqttPassword); } else { callback(null, false); } }; server1.aedes.on("subscribe", (subscriptions, client) => { console.log(subscriptions); for (let s of subscriptions) { if (s.topic === "test") { server1.aedes.publish({ topic: "test", payload: Buffer.from("ok"), }, (error) => { if (error) { log.error("mqtt_server", error); } }); } } }); server1.start();
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/remove-playwright-test-data.js
extra/remove-playwright-test-data.js
const fs = require("fs"); fs.rmSync("./data/playwright-test", { recursive: true, force: true, });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/build-healthcheck.js
extra/build-healthcheck.js
const childProcess = require("child_process"); const fs = require("fs"); const platform = process.argv[2]; if (!platform) { console.error("No platform??"); process.exit(1); } if (platform === "linux/arm/v7") { console.log("Arch: armv7"); if (fs.existsSync("./extra/healthcheck-armv7")) { fs.renameSync("./extra/healthcheck-armv7", "./extra/healthcheck"); console.log("Already built in the host, skip."); process.exit(0); } else { console.log("prebuilt not found, it will be slow! You should execute `npm run build-healthcheck-armv7` before build."); } } else { if (fs.existsSync("./extra/healthcheck-armv7")) { fs.rmSync("./extra/healthcheck-armv7"); } } const output = childProcess.execSync("go build -x -o ./extra/healthcheck ./extra/healthcheck.go").toString("utf8"); console.log(output);
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/remove-2fa.js
extra/remove-2fa.js
console.log("== Uptime Kuma Remove 2FA Tool =="); console.log("Loading the database"); const Database = require("../server/database"); const { R } = require("redbean-node"); const readline = require("readline"); const TwoFA = require("../server/2fa"); const args = require("args-parser")(process.argv); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const main = async () => { Database.initDataDir(args); await Database.connect(); try { // No need to actually reset the password for testing, just make sure no connection problem. It is ok for now. if (!process.env.TEST_BACKEND) { const user = await R.findOne("user"); if (! user) { throw new Error("user not found, have you installed?"); } console.log("Found user: " + user.username); let ans = await question("Are you sure want to remove 2FA? [y/N]"); if (ans.toLowerCase() === "y") { await TwoFA.disable2FA(user.id); console.log("2FA has been removed successfully."); } } } catch (e) { console.error("Error: " + e.message); } await Database.close(); rl.close(); console.log("Finished."); }; /** * Ask question of user * @param {string} question Question to ask * @returns {Promise<string>} Users response */ function question(question) { return new Promise((resolve) => { rl.question(question, (answer) => { resolve(answer); }); }); } if (!process.env.TEST_BACKEND) { main(); } module.exports = { main, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/healthcheck.js
extra/healthcheck.js
/* * ⚠️ ⚠️ ⚠️ ⚠️ Due to the weird issue in Portainer that the healthcheck script is still pointing to this script for unknown reason. * IT CANNOT BE DROPPED, even though it looks like it is not used. * See more: https://github.com/louislam/uptime-kuma/issues/2774#issuecomment-1429092359 * * ⚠️ Deprecated: Changed to healthcheck.go, it will be deleted in the future. * This script should be run after a period of time (180s), because the server may need some time to prepare. */ const FBSD = /^freebsd/.test(process.platform); process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; let client; const sslKey = process.env.UPTIME_KUMA_SSL_KEY || process.env.SSL_KEY || undefined; const sslCert = process.env.UPTIME_KUMA_SSL_CERT || process.env.SSL_CERT || undefined; if (sslKey && sslCert) { client = require("https"); } else { client = require("http"); } // If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available and the unspecified IPv4 address (0.0.0.0) otherwise. // Dual-stack support for (::) let hostname = process.env.UPTIME_KUMA_HOST; // Also read HOST if not *BSD, as HOST is a system environment variable in FreeBSD if (!hostname && !FBSD) { hostname = process.env.HOST; } const port = parseInt(process.env.UPTIME_KUMA_PORT || process.env.PORT || 3001); let options = { host: hostname || "127.0.0.1", port: port, timeout: 28 * 1000, }; let request = client.request(options, (res) => { console.log(`Health Check OK [Res Code: ${res.statusCode}]`); if (res.statusCode === 302) { process.exit(0); } else { process.exit(1); } }); request.on("error", function (err) { console.error("Health Check ERROR"); process.exit(1); }); request.end();
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/download-dist.js
extra/download-dist.js
console.log("Downloading dist"); const https = require("https"); const tar = require("tar"); const packageJSON = require("../package.json"); const fs = require("fs"); const version = packageJSON.version; const filename = "dist.tar.gz"; const url = `https://github.com/louislam/uptime-kuma/releases/download/${version}/${filename}`; download(url); /** * Downloads the latest version of the dist from a GitHub release. * @param {string} url The URL to download from. * @returns {void} * * Generated by Trelent */ function download(url) { console.log(url); https.get(url, (response) => { if (response.statusCode === 200) { console.log("Extracting dist..."); if (fs.existsSync("./dist")) { if (fs.existsSync("./dist-backup")) { fs.rmSync("./dist-backup", { recursive: true, force: true, }); } fs.renameSync("./dist", "./dist-backup"); } const tarStream = tar.x({ cwd: "./", }); tarStream.on("close", () => { if (fs.existsSync("./dist-backup")) { fs.rmSync("./dist-backup", { recursive: true, force: true, }); } console.log("Done"); process.exit(0); }); tarStream.on("error", () => { if (fs.existsSync("./dist-backup")) { fs.renameSync("./dist-backup", "./dist"); } console.error("Error from tarStream"); }); response.pipe(tarStream); } else if (response.statusCode === 302) { download(response.headers.location); } else { console.log("dist not found"); } }); }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/reset-migrate-aggregate-table-state.js
extra/reset-migrate-aggregate-table-state.js
const { R } = require("redbean-node"); const Database = require("../server/database"); const args = require("args-parser")(process.argv); const { Settings } = require("../server/settings"); const main = async () => { console.log("Connecting the database"); Database.initDataDir(args); await Database.connect(false, false, true); console.log("Deleting all data from aggregate tables"); await R.exec("DELETE FROM stat_minutely"); await R.exec("DELETE FROM stat_hourly"); await R.exec("DELETE FROM stat_daily"); console.log("Resetting the aggregate table state"); await Settings.set("migrateAggregateTableState", ""); await Database.close(); console.log("Done"); }; main();
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/update-version.js
extra/update-version.js
const pkg = require("../package.json"); const fs = require("fs"); const childProcess = require("child_process"); const util = require("../src/util"); util.polyfill(); const newVersion = process.env.RELEASE_VERSION; console.log("New Version: " + newVersion); if (! newVersion) { console.error("invalid version"); process.exit(1); } const exists = tagExists(newVersion); if (! exists) { // Process package.json pkg.version = newVersion; // Replace the version: https://regex101.com/r/hmj2Bc/1 pkg.scripts.setup = pkg.scripts.setup.replace(/(git checkout )([^\s]+)/, `$1${newVersion}`); fs.writeFileSync("package.json", JSON.stringify(pkg, null, 4) + "\n"); // Also update package-lock.json const npm = /^win/.test(process.platform) ? "npm.cmd" : "npm"; const resultVersion = childProcess.spawnSync(npm, [ "--no-git-tag-version", "version", newVersion ], { shell: true }); if (resultVersion.error) { console.error(resultVersion.error); console.error("error npm version!"); process.exit(1); } const resultInstall = childProcess.spawnSync(npm, [ "install" ], { shell: true }); if (resultInstall.error) { console.error(resultInstall.error); console.error("error update package-lock!"); process.exit(1); } commit(newVersion); } else { console.log("version exists"); } /** * Commit updated files * @param {string} version Version to update to * @returns {void} * @throws Error when committing files */ function commit(version) { let msg = "Update to " + version; let res = childProcess.spawnSync("git", [ "commit", "-m", msg, "-a" ]); let stdout = res.stdout.toString().trim(); console.log(stdout); if (stdout.includes("no changes added to commit")) { throw new Error("commit error"); } } /** * Check if a tag exists for the specified version * @param {string} version Version to check * @returns {boolean} Does the tag already exist * @throws Version is not valid */ function tagExists(version) { if (! version) { throw new Error("invalid version"); } let res = childProcess.spawnSync("git", [ "tag", "-l", version ]); return res.stdout.toString().trim() === version; }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/update-wiki-version.js
extra/update-wiki-version.js
const childProcess = require("child_process"); const fs = require("fs"); const newVersion = process.env.RELEASE_VERSION; if (!newVersion) { console.log("Missing version"); process.exit(1); } updateWiki(newVersion); /** * Update the wiki with new version number * @param {string} newVersion Version to update to * @returns {void} */ function updateWiki(newVersion) { const wikiDir = "./tmp/wiki"; const howToUpdateFilename = "./tmp/wiki/🆙-How-to-Update.md"; safeDelete(wikiDir); childProcess.spawnSync("git", [ "clone", "https://github.com/louislam/uptime-kuma.wiki.git", wikiDir ]); let content = fs.readFileSync(howToUpdateFilename).toString(); // Replace the version: https://regex101.com/r/hmj2Bc/1 content = content.replace(/(git checkout )([^\s]+)/, `$1${newVersion}`); fs.writeFileSync(howToUpdateFilename, content); childProcess.spawnSync("git", [ "add", "-A" ], { cwd: wikiDir, }); childProcess.spawnSync("git", [ "commit", "-m", `Update to ${newVersion}` ], { cwd: wikiDir, }); console.log("Pushing to Github"); childProcess.spawnSync("git", [ "push" ], { cwd: wikiDir, }); safeDelete(wikiDir); } /** * Check if a directory exists and then delete it * @param {string} dir Directory to delete * @returns {void} */ function safeDelete(dir) { if (fs.existsSync(dir)) { fs.rm(dir, { recursive: true, }); } }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/reset-password.js
extra/reset-password.js
console.log("== Uptime Kuma Reset Password Tool =="); const Database = require("../server/database"); const { R } = require("redbean-node"); const readline = require("readline"); const { passwordStrength } = require("check-password-strength"); const { initJWTSecret } = require("../server/util-server"); const User = require("../server/model/user"); const { io } = require("socket.io-client"); const { localWebSocketURL } = require("../server/config"); const args = require("args-parser")(process.argv); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const main = async () => { if ("dry-run" in args) { console.log("Dry run mode, no changes will be made."); } console.log("Connecting the database"); try { Database.initDataDir(args); await Database.connect(false, false, true); // No need to actually reset the password for testing, just make sure no connection problem. It is ok for now. if (!process.env.TEST_BACKEND) { const user = await R.findOne("user"); if (! user) { throw new Error("user not found, have you installed?"); } console.log("Found user: " + user.username); while (true) { let password; let confirmPassword; // When called with "--new-password" argument for unattended modification (e.g. npm run reset-password -- --new_password=secret) if ("new-password" in args) { console.log("Using password from argument"); console.warn("\x1b[31m%s\x1b[0m", "Warning: the password might be stored, in plain text, in your shell's history"); password = confirmPassword = args["new-password"] + ""; if (passwordStrength(password).value === "Too weak") { throw new Error("Password is too weak, please use a stronger password."); } } else { password = await question("New Password: "); if (passwordStrength(password).value === "Too weak") { console.log("Password is too weak, please try again."); continue; } confirmPassword = await question("Confirm New Password: "); } if (password === confirmPassword) { if (!("dry-run" in args)) { await User.resetPassword(user.id, password); // Reset all sessions by reset jwt secret await initJWTSecret(); // Disconnect all other socket clients of the user await disconnectAllSocketClients(user.username, password); } break; } else { console.log("Passwords do not match, please try again."); } } console.log("Password reset successfully."); } } catch (e) { console.error("Error: " + e.message); } await Database.close(); rl.close(); console.log("Finished."); }; /** * Ask question of user * @param {string} question Question to ask * @returns {Promise<string>} Users response */ function question(question) { return new Promise((resolve) => { rl.question(question, (answer) => { resolve(answer); }); }); } /** * Disconnect all socket clients of the user * @param {string} username Username * @param {string} password Password * @returns {Promise<void>} Promise */ function disconnectAllSocketClients(username, password) { return new Promise((resolve) => { console.log("Connecting to " + localWebSocketURL + " to disconnect all other socket clients"); // Disconnect all socket connections const socket = io(localWebSocketURL, { reconnection: false, timeout: 5000, }); socket.on("connect", () => { socket.emit("login", { username, password, }, (res) => { if (res.ok) { console.log("Logged in."); socket.emit("disconnectOtherSocketClients"); } else { console.warn("Login failed."); console.warn("Please restart the server to disconnect all sessions."); } socket.close(); }); }); socket.on("connect_error", function () { // The localWebSocketURL is not guaranteed to be working for some complicated Uptime Kuma setup // Ask the user to restart the server manually console.warn("Failed to connect to " + localWebSocketURL); console.warn("Please restart the server to disconnect all sessions manually."); resolve(); }); socket.on("disconnect", () => { resolve(); }); }); } if (!process.env.TEST_BACKEND) { main(); } module.exports = { main, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/close-incorrect-issue.js
extra/close-incorrect-issue.js
const github = require("@actions/github"); (async () => { try { const token = process.argv[2]; const issueNumber = process.argv[3]; const username = process.argv[4]; const client = github.getOctokit(token).rest; const issue = { owner: "louislam", repo: "uptime-kuma", number: issueNumber, }; const labels = ( await client.issues.listLabelsOnIssue({ owner: issue.owner, repo: issue.repo, issue_number: issue.number }) ).data.map(({ name }) => name); if (labels.length === 0) { console.log("Bad format here"); await client.issues.addLabels({ owner: issue.owner, repo: issue.repo, issue_number: issue.number, labels: [ "invalid-format" ] }); // Add the issue closing comment await client.issues.createComment({ owner: issue.owner, repo: issue.repo, issue_number: issue.number, body: `@${username}: Hello! :wave:\n\nThis issue is being automatically closed because it does not follow the issue template. Please **DO NOT open blank issues and use our [issue-templates](https://github.com/louislam/uptime-kuma/issues/new/choose) instead**.\nBlank Issues do not contain the context necessary for a good discussions.` }); // Close the issue await client.issues.update({ owner: issue.owner, repo: issue.repo, issue_number: issue.number, state: "closed" }); } else { console.log("Pass!"); } } catch (e) { console.log(e); } })();
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/check-lang-json.js
extra/check-lang-json.js
// For #5231 const fs = require("fs"); let path = "./src/lang"; // list directories in the lang directory let jsonFileList = fs.readdirSync(path); for (let jsonFile of jsonFileList) { if (!jsonFile.endsWith(".json")) { continue; } let jsonPath = path + "/" + jsonFile; let originalContent = fs.readFileSync(jsonPath, "utf8"); let langData = JSON.parse(originalContent); let formattedContent = JSON.stringify(langData, null, 4) + "\n"; if (originalContent !== formattedContent) { console.error(`File ${jsonFile} is not formatted correctly.`); process.exit(1); } } console.log("All lang json files are formatted correctly.");
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/beta/update-version.js
extra/beta/update-version.js
const pkg = require("../../package.json"); const fs = require("fs"); const childProcess = require("child_process"); const util = require("../../src/util"); util.polyfill(); const version = process.env.RELEASE_BETA_VERSION; console.log("Beta Version: " + version); if (!version || !version.includes("-beta.")) { console.error("invalid version, beta version only"); process.exit(1); } const exists = tagExists(version); if (! exists) { // Process package.json pkg.version = version; fs.writeFileSync("package.json", JSON.stringify(pkg, null, 4) + "\n"); // Also update package-lock.json const npm = /^win/.test(process.platform) ? "npm.cmd" : "npm"; const resultVersion = childProcess.spawnSync(npm, [ "--no-git-tag-version", "version", version ], { shell: true }); if (resultVersion.error) { console.error(resultVersion.error); console.error("error npm version!"); process.exit(1); } const resultInstall = childProcess.spawnSync(npm, [ "install" ], { shell: true }); if (resultInstall.error) { console.error(resultInstall.error); console.error("error update package-lock!"); process.exit(1); } commit(version); } else { console.log("version tag exists, please delete the tag or use another tag"); process.exit(1); } /** * Commit updated files * @param {string} version Version to update to * @returns {void} * @throws Error committing files */ function commit(version) { let msg = "Update to " + version; let res = childProcess.spawnSync("git", [ "commit", "-m", msg, "-a" ]); let stdout = res.stdout.toString().trim(); console.log(stdout); if (stdout.includes("no changes added to commit")) { throw new Error("commit error"); } res = childProcess.spawnSync("git", [ "push", "origin", "master" ]); console.log(res.stdout.toString().trim()); } /** * Check if a tag exists for the specified version * @param {string} version Version to check * @returns {boolean} Does the tag already exist * @throws Version is not valid */ function tagExists(version) { if (! version) { throw new Error("invalid version"); } let res = childProcess.spawnSync("git", [ "tag", "-l", version ]); return res.stdout.toString().trim() === version; }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/uptime-kuma-push/build.js
extra/uptime-kuma-push/build.js
const fs = require("fs"); const platform = process.argv[2]; if (!platform) { console.error("No platform??"); process.exit(1); } const supportedPlatforms = [ { name: "linux/amd64", bin: "./build/uptime-kuma-push-amd64" }, { name: "linux/arm64", bin: "./build/uptime-kuma-push-arm64" }, { name: "linux/arm/v7", bin: "./build/uptime-kuma-push-armv7" } ]; let platformObj = null; // Check if the platform is supported for (let i = 0; i < supportedPlatforms.length; i++) { if (supportedPlatforms[i].name === platform) { platformObj = supportedPlatforms[i]; break; } } if (platformObj) { let filename = platformObj.bin; if (!fs.existsSync(filename)) { console.error(`prebuilt: ${filename} is not found, please build it first`); process.exit(1); } fs.renameSync(filename, "./uptime-kuma-push"); process.exit(0); } else { console.error("Unsupported platform: " + platform); process.exit(1); }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/update-language-files/index.js
extra/update-language-files/index.js
// Need to use ES6 to read language files import fs from "fs"; import util from "util"; /** * Copy across the required language files * Creates a local directory (./languages) and copies the required files * into it. * @param {string} langCode Code of language to update. A file will be * created with this code if one does not already exist * @param {string} baseLang The second base language file to copy. This * will be ignored if set to "en" as en.js is copied by default * @returns {void} */ function copyFiles(langCode, baseLang) { if (fs.existsSync("./languages")) { fs.rmSync("./languages", { recursive: true, force: true, }); } fs.mkdirSync("./languages"); if (!fs.existsSync(`../../src/languages/${langCode}.js`)) { fs.closeSync(fs.openSync(`./languages/${langCode}.js`, "a")); } else { fs.copyFileSync(`../../src/languages/${langCode}.js`, `./languages/${langCode}.js`); } fs.copyFileSync("../../src/languages/en.js", "./languages/en.js"); if (baseLang !== "en") { fs.copyFileSync(`../../src/languages/${baseLang}.js`, `./languages/${baseLang}.js`); } } /** * Update the specified language file * @param {string} langCode Language code to update * @param {string} baseLangCode Second language to copy keys from * @returns {void} */ async function updateLanguage(langCode, baseLangCode) { const en = (await import("./languages/en.js")).default; const baseLang = (await import(`./languages/${baseLangCode}.js`)).default; let file = langCode + ".js"; console.log("Processing " + file); const lang = await import("./languages/" + file); let obj; if (lang.default) { obj = lang.default; } else { console.log("Empty file"); obj = { languageName: "<Your Language name in your language (not in English)>" }; } // En first for (const key in en) { if (! obj[key]) { obj[key] = en[key]; } } if (baseLang !== en) { // Base second for (const key in baseLang) { if (! obj[key]) { obj[key] = key; } } } const code = "export default " + util.inspect(obj, { depth: null, }); fs.writeFileSync(`../../src/languages/${file}`, code); } // Get command line arguments const baseLangCode = process.env.npm_config_baselang || "en"; const langCode = process.env.npm_config_language; // We need the file to edit if (langCode == null) { throw new Error("Argument --language=<code> must be provided"); } console.log("Base Lang: " + baseLangCode); console.log("Updating: " + langCode); copyFiles(langCode, baseLangCode); await updateLanguage(langCode, baseLangCode); fs.rmSync("./languages", { recursive: true, force: true, }); console.log("Done. Fixing formatting by ESLint...");
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/extra/push-examples/javascript-fetch/index.js
extra/push-examples/javascript-fetch/index.js
// Supports: Node.js >= 18, Deno, Bun const pushURL = "https://example.com/api/push/key?status=up&msg=OK&ping="; const interval = 60; const push = async () => { await fetch(pushURL); console.log("Pushed!"); }; push(); setInterval(push, interval * 1000);
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/docker.js
server/docker.js
const axios = require("axios"); const { R } = require("redbean-node"); const https = require("https"); const fsAsync = require("fs").promises; const path = require("path"); const Database = require("./database"); const { axiosAbortSignal, fsExists } = require("./util-server"); class DockerHost { static CertificateFileNameCA = "ca.pem"; static CertificateFileNameCert = "cert.pem"; static CertificateFileNameKey = "key.pem"; /** * Save a docker host * @param {object} dockerHost Docker host to save * @param {?number} dockerHostID ID of the docker host to update * @param {number} userID ID of the user who adds the docker host * @returns {Promise<Bean>} Updated docker host */ static async save(dockerHost, dockerHostID, userID) { let bean; if (dockerHostID) { bean = await R.findOne("docker_host", " id = ? AND user_id = ? ", [ dockerHostID, userID ]); if (!bean) { throw new Error("docker host not found"); } } else { bean = R.dispense("docker_host"); } bean.user_id = userID; bean.docker_daemon = dockerHost.dockerDaemon; bean.docker_type = dockerHost.dockerType; bean.name = dockerHost.name; await R.store(bean); return bean; } /** * Delete a Docker host * @param {number} dockerHostID ID of the Docker host to delete * @param {number} userID ID of the user who created the Docker host * @returns {Promise<void>} */ static async delete(dockerHostID, userID) { let bean = await R.findOne("docker_host", " id = ? AND user_id = ? ", [ dockerHostID, userID ]); if (!bean) { throw new Error("docker host not found"); } // Delete removed proxy from monitors if exists await R.exec("UPDATE monitor SET docker_host = null WHERE docker_host = ?", [ dockerHostID ]); await R.trash(bean); } /** * Fetches the amount of containers on the Docker host * @param {object} dockerHost Docker host to check for * @returns {Promise<number>} Total amount of containers on the host */ static async testDockerHost(dockerHost) { const options = { url: "/containers/json?all=true", timeout: 5000, headers: { "Accept": "*/*", }, signal: axiosAbortSignal(6000), }; if (dockerHost.dockerType === "socket") { options.socketPath = dockerHost.dockerDaemon; } else if (dockerHost.dockerType === "tcp") { options.baseURL = DockerHost.patchDockerURL(dockerHost.dockerDaemon); options.httpsAgent = new https.Agent(await DockerHost.getHttpsAgentOptions(dockerHost.dockerType, options.baseURL)); } try { let res = await axios.request(options); if (Array.isArray(res.data)) { if (res.data.length > 1) { if ("ImageID" in res.data[0]) { return res.data.length; } else { throw new Error("Invalid Docker response, is it Docker really a daemon?"); } } else { return res.data.length; } } else { throw new Error("Invalid Docker response, is it Docker really a daemon?"); } } catch (e) { if (e.code === "ECONNABORTED" || e.name === "CanceledError") { throw new Error("Connection to Docker daemon timed out."); } else { throw e; } } } /** * Since axios 0.27.X, it does not accept `tcp://` protocol. * Change it to `http://` on the fly in order to fix it. (https://github.com/louislam/uptime-kuma/issues/2165) * @param {any} url URL to fix * @returns {any} URL with tcp:// replaced by http:// */ static patchDockerURL(url) { if (typeof url === "string") { // Replace the first occurrence only with g return url.replace(/tcp:\/\//g, "http://"); } return url; } /** * Returns HTTPS agent options with client side TLS parameters if certificate files * for the given host are available under a predefined directory path. * * The base path where certificates are looked for can be set with the * 'DOCKER_TLS_DIR_PATH' environmental variable or defaults to 'data/docker-tls/'. * * If a directory in this path exists with a name matching the FQDN of the docker host * (e.g. the FQDN of 'https://example.com:2376' is 'example.com' so the directory * 'data/docker-tls/example.com/' would be searched for certificate files), * then 'ca.pem', 'key.pem' and 'cert.pem' files are included in the agent options. * File names can also be overridden via 'DOCKER_TLS_FILE_NAME_(CA|KEY|CERT)'. * @param {string} dockerType i.e. "tcp" or "socket" * @param {string} url The docker host URL rewritten to https:// * @returns {Promise<object>} HTTP agent options */ static async getHttpsAgentOptions(dockerType, url) { let baseOptions = { maxCachedSessions: 0, rejectUnauthorized: true }; let certOptions = {}; let dirName = (new URL(url)).hostname; let caPath = path.join(Database.dockerTLSDir, dirName, DockerHost.CertificateFileNameCA); let certPath = path.join(Database.dockerTLSDir, dirName, DockerHost.CertificateFileNameCert); let keyPath = path.join(Database.dockerTLSDir, dirName, DockerHost.CertificateFileNameKey); if (dockerType === "tcp" && await fsExists(caPath) && await fsExists(certPath) && await fsExists(keyPath)) { let ca = await fsAsync.readFile(caPath); let key = await fsAsync.readFile(keyPath); let cert = await fsAsync.readFile(certPath); certOptions = { ca, key, cert }; } return { ...baseOptions, ...certOptions }; } } module.exports = { DockerHost, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/proxy.js
server/proxy.js
const { R } = require("redbean-node"); const { HttpProxyAgent } = require("http-proxy-agent"); const { HttpsProxyAgent } = require("https-proxy-agent"); const { SocksProxyAgent } = require("socks-proxy-agent"); const { debug } = require("../src/util"); const { UptimeKumaServer } = require("./uptime-kuma-server"); const { CookieJar } = require("tough-cookie"); const { createCookieAgent } = require("http-cookie-agent/http"); class Proxy { static SUPPORTED_PROXY_PROTOCOLS = [ "http", "https", "socks", "socks5", "socks5h", "socks4" ]; /** * Saves and updates given proxy entity * @param {object} proxy Proxy to store * @param {number} proxyID ID of proxy to update * @param {number} userID ID of user the proxy belongs to * @returns {Promise<Bean>} Updated proxy */ static async save(proxy, proxyID, userID) { let bean; if (proxyID) { bean = await R.findOne("proxy", " id = ? AND user_id = ? ", [ proxyID, userID ]); if (!bean) { throw new Error("proxy not found"); } } else { bean = R.dispense("proxy"); } // Make sure given proxy protocol is supported if (!this.SUPPORTED_PROXY_PROTOCOLS.includes(proxy.protocol)) { throw new Error(` Unsupported proxy protocol "${proxy.protocol}. Supported protocols are ${this.SUPPORTED_PROXY_PROTOCOLS.join(", ")}."` ); } // When proxy is default update deactivate old default proxy if (proxy.default) { await R.exec("UPDATE proxy SET `default` = 0 WHERE `default` = 1"); } bean.user_id = userID; bean.protocol = proxy.protocol; bean.host = proxy.host; bean.port = proxy.port; bean.auth = proxy.auth; bean.username = proxy.username; bean.password = proxy.password; bean.active = proxy.active || true; bean.default = proxy.default || false; await R.store(bean); if (proxy.applyExisting) { await applyProxyEveryMonitor(bean.id, userID); } return bean; } /** * Deletes proxy with given id and removes it from monitors * @param {number} proxyID ID of proxy to delete * @param {number} userID ID of proxy owner * @returns {Promise<void>} */ static async delete(proxyID, userID) { const bean = await R.findOne("proxy", " id = ? AND user_id = ? ", [ proxyID, userID ]); if (!bean) { throw new Error("proxy not found"); } // Delete removed proxy from monitors if exists await R.exec("UPDATE monitor SET proxy_id = null WHERE proxy_id = ?", [ proxyID ]); // Delete proxy from list await R.trash(bean); } /** * Create HTTP and HTTPS agents related with given proxy bean object * @param {object} proxy proxy bean object * @param {object} options http and https agent options * @returns {{httpAgent: Agent, httpsAgent: Agent}} New HTTP and HTTPS agents * @throws Proxy protocol is unsupported */ static createAgents(proxy, options) { const { httpAgentOptions, httpsAgentOptions } = options || {}; let agent; let httpAgent; let httpsAgent; let jar = new CookieJar(); const proxyOptions = { cookies: { jar }, }; const proxyUrl = new URL(`${proxy.protocol}://${proxy.host}:${proxy.port}`); if (proxy.auth) { proxyUrl.username = proxy.username; proxyUrl.password = proxy.password; } debug(`Proxy URL: ${proxyUrl.toString()}`); debug(`HTTP Agent Options: ${JSON.stringify(httpAgentOptions)}`); debug(`HTTPS Agent Options: ${JSON.stringify(httpsAgentOptions)}`); switch (proxy.protocol) { case "http": case "https": // eslint-disable-next-line no-case-declarations const HttpCookieProxyAgent = createCookieAgent(HttpProxyAgent); // eslint-disable-next-line no-case-declarations const HttpsCookieProxyAgent = createCookieAgent(HttpsProxyAgent); httpAgent = new HttpCookieProxyAgent(proxyUrl.toString(), { ...(httpAgentOptions || {}), ...proxyOptions, }); httpsAgent = new HttpsCookieProxyAgent(proxyUrl.toString(), { ...(httpsAgentOptions || {}), ...proxyOptions, }); break; case "socks": case "socks5": case "socks5h": case "socks4": // eslint-disable-next-line no-case-declarations const SocksCookieProxyAgent = createCookieAgent(SocksProxyAgent); agent = new SocksCookieProxyAgent(proxyUrl.toString(), { ...httpAgentOptions, ...httpsAgentOptions, tls: { rejectUnauthorized: httpsAgentOptions.rejectUnauthorized, }, }); httpAgent = agent; httpsAgent = agent; break; default: throw new Error(`Unsupported proxy protocol provided. ${proxy.protocol}`); } return { httpAgent, httpsAgent }; } /** * Reload proxy settings for current monitors * @returns {Promise<void>} */ static async reloadProxy() { const server = UptimeKumaServer.getInstance(); let updatedList = await R.getAssoc("SELECT id, proxy_id FROM monitor"); for (let monitorID in server.monitorList) { let monitor = server.monitorList[monitorID]; if (updatedList[monitorID]) { monitor.proxy_id = updatedList[monitorID].proxy_id; } } } } /** * Applies given proxy id to monitors * @param {number} proxyID ID of proxy to apply * @param {number} userID ID of proxy owner * @returns {Promise<void>} */ async function applyProxyEveryMonitor(proxyID, userID) { // Find all monitors with id and proxy id const monitors = await R.getAll("SELECT id, proxy_id FROM monitor WHERE user_id = ?", [ userID ]); // Update proxy id not match with given proxy id for (const monitor of monitors) { if (monitor.proxy_id !== proxyID) { await R.exec("UPDATE monitor SET proxy_id = ? WHERE id = ?", [ proxyID, monitor.id ]); } } } module.exports = { Proxy, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/jobs.js
server/jobs.js
const { UptimeKumaServer } = require("./uptime-kuma-server"); const { clearOldData } = require("./jobs/clear-old-data"); const { incrementalVacuum } = require("./jobs/incremental-vacuum"); const Cron = require("croner"); const jobs = [ { name: "clear-old-data", interval: "14 03 * * *", jobFunc: clearOldData, croner: null, }, { name: "incremental-vacuum", interval: "*/5 * * * *", jobFunc: incrementalVacuum, croner: null, } ]; /** * Initialize background jobs * @returns {Promise<void>} */ const initBackgroundJobs = async function () { const timezone = await UptimeKumaServer.getInstance().getTimezone(); for (const job of jobs) { const cornerJob = new Cron( job.interval, { name: job.name, timezone, }, job.jobFunc, ); job.croner = cornerJob; } }; /** * Stop all background jobs if running * @returns {void} */ const stopBackgroundJobs = function () { for (const job of jobs) { if (job.croner) { job.croner.stop(); job.croner = null; } } }; module.exports = { initBackgroundJobs, stopBackgroundJobs };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/database.js
server/database.js
const fs = require("fs"); const fsAsync = fs.promises; const { R } = require("redbean-node"); const { setSetting, setting } = require("./util-server"); const { log, sleep } = require("../src/util"); const knex = require("knex"); const path = require("path"); const { EmbeddedMariaDB } = require("./embedded-mariadb"); const mysql = require("mysql2/promise"); const { Settings } = require("./settings"); const { UptimeCalculator } = require("./uptime-calculator"); const dayjs = require("dayjs"); const { SimpleMigrationServer } = require("./utils/simple-migration-server"); const KumaColumnCompiler = require("./utils/knex/lib/dialects/mysql2/schema/mysql2-columncompiler"); const SqlString = require("sqlstring"); /** * Database & App Data Folder */ class Database { /** * Bootstrap database for SQLite * @type {string} */ static templatePath = "./db/kuma.db"; /** * Data Dir (Default: ./data) * @type {string} */ static dataDir; /** * User Upload Dir (Default: ./data/upload) * @type {string} */ static uploadDir; /** * Chrome Screenshot Dir (Default: ./data/screenshots) * @type {string} */ static screenshotDir; /** * SQLite file path (Default: ./data/kuma.db) * @type {string} */ static sqlitePath; /** * For storing Docker TLS certs (Default: ./data/docker-tls) * @type {string} */ static dockerTLSDir; /** * @type {boolean} */ static patched = false; /** * SQLite only * Add patch filename in key * Values: * true: Add it regardless of order * false: Do nothing * { parents: []}: Need parents before add it * @deprecated */ static patchList = { "patch-setting-value-type.sql": true, "patch-improve-performance.sql": true, "patch-2fa.sql": true, "patch-add-retry-interval-monitor.sql": true, "patch-incident-table.sql": true, "patch-group-table.sql": true, "patch-monitor-push_token.sql": true, "patch-http-monitor-method-body-and-headers.sql": true, "patch-2fa-invalidate-used-token.sql": true, "patch-notification_sent_history.sql": true, "patch-monitor-basic-auth.sql": true, "patch-add-docker-columns.sql": true, "patch-status-page.sql": true, "patch-proxy.sql": true, "patch-monitor-expiry-notification.sql": true, "patch-status-page-footer-css.sql": true, "patch-added-mqtt-monitor.sql": true, "patch-add-clickable-status-page-link.sql": true, "patch-add-sqlserver-monitor.sql": true, "patch-add-other-auth.sql": { parents: [ "patch-monitor-basic-auth.sql" ] }, "patch-grpc-monitor.sql": true, "patch-add-radius-monitor.sql": true, "patch-monitor-add-resend-interval.sql": true, "patch-ping-packet-size.sql": true, "patch-maintenance-table2.sql": true, "patch-add-gamedig-monitor.sql": true, "patch-add-google-analytics-status-page-tag.sql": true, "patch-http-body-encoding.sql": true, "patch-add-description-monitor.sql": true, "patch-api-key-table.sql": true, "patch-monitor-tls.sql": true, "patch-maintenance-cron.sql": true, "patch-add-parent-monitor.sql": true, "patch-add-invert-keyword.sql": true, "patch-added-json-query.sql": true, "patch-added-kafka-producer.sql": true, "patch-add-certificate-expiry-status-page.sql": true, "patch-monitor-oauth-cc.sql": true, "patch-add-timeout-monitor.sql": true, "patch-add-gamedig-given-port.sql": true, "patch-notification-config.sql": true, "patch-fix-kafka-producer-booleans.sql": true, "patch-timeout.sql": true, "patch-monitor-tls-info-add-fk.sql": true, // The last file so far converted to a knex migration file }; /** * The final version should be 10 after merged tag feature * @deprecated Use patchList for any new feature */ static latestVersion = 10; static noReject = true; static dbConfig = {}; static knexMigrationsPath = "./db/knex_migrations"; /** * Initialize the data directory * @param {object} args Arguments to initialize DB with * @returns {void} */ static initDataDir(args) { // Data Directory (must be end with "/") Database.dataDir = process.env.DATA_DIR || args["data-dir"] || "./data/"; Database.sqlitePath = path.join(Database.dataDir, "kuma.db"); if (! fs.existsSync(Database.dataDir)) { fs.mkdirSync(Database.dataDir, { recursive: true }); } Database.uploadDir = path.join(Database.dataDir, "upload/"); if (! fs.existsSync(Database.uploadDir)) { fs.mkdirSync(Database.uploadDir, { recursive: true }); } // Create screenshot dir Database.screenshotDir = path.join(Database.dataDir, "screenshots/"); if (! fs.existsSync(Database.screenshotDir)) { fs.mkdirSync(Database.screenshotDir, { recursive: true }); } Database.dockerTLSDir = path.join(Database.dataDir, "docker-tls/"); if (! fs.existsSync(Database.dockerTLSDir)) { fs.mkdirSync(Database.dockerTLSDir, { recursive: true }); } log.info("server", `Data Dir: ${Database.dataDir}`); } /** * Read the database config * @throws {Error} If the config is invalid * @typedef {string|undefined} envString * @returns {{type: "sqlite"} | {type:envString, hostname:envString, port:envString, database:envString, username:envString, password:envString}} Database config */ static readDBConfig() { let dbConfig; let dbConfigString = fs.readFileSync(path.join(Database.dataDir, "db-config.json")).toString("utf-8"); dbConfig = JSON.parse(dbConfigString); if (typeof dbConfig !== "object") { throw new Error("Invalid db-config.json, it must be an object"); } if (typeof dbConfig.type !== "string") { throw new Error("Invalid db-config.json, type must be a string"); } return dbConfig; } /** * @typedef {string|undefined} envString * @param {{type: "sqlite"} | {type:envString, hostname:envString, port:envString, database:envString, username:envString, password:envString}} dbConfig the database configuration that should be written * @returns {void} */ static writeDBConfig(dbConfig) { fs.writeFileSync(path.join(Database.dataDir, "db-config.json"), JSON.stringify(dbConfig, null, 4)); } /** * Connect to the database * @param {boolean} testMode Should the connection be started in test mode? * @param {boolean} autoloadModels Should models be automatically loaded? * @param {boolean} noLog Should logs not be output? * @returns {Promise<void>} */ static async connect(testMode = false, autoloadModels = true, noLog = false) { // Patch "mysql2" knex client // Workaround: Tried extending the ColumnCompiler class, but it didn't work for unknown reasons, so I override the function via prototype const { getDialectByNameOrAlias } = require("knex/lib/dialects"); const mysql2 = getDialectByNameOrAlias("mysql2"); mysql2.prototype.columnCompiler = function () { return new KumaColumnCompiler(this, ...arguments); }; const acquireConnectionTimeout = 120 * 1000; let dbConfig; try { dbConfig = this.readDBConfig(); Database.dbConfig = dbConfig; } catch (err) { log.warn("db", err.message); dbConfig = { type: "sqlite", }; } let config = {}; let parsedMaxPoolConnections = parseInt(process.env.UPTIME_KUMA_DB_POOL_MAX_CONNECTIONS); if (!process.env.UPTIME_KUMA_DB_POOL_MAX_CONNECTIONS) { parsedMaxPoolConnections = 10; } else if (Number.isNaN(parsedMaxPoolConnections)) { log.warn("db", "Max database connections defaulted to 10 because UPTIME_KUMA_DB_POOL_MAX_CONNECTIONS was invalid."); parsedMaxPoolConnections = 10; } else if (parsedMaxPoolConnections < 1) { log.warn("db", "Max database connections defaulted to 10 because UPTIME_KUMA_DB_POOL_MAX_CONNECTIONS was less than 1."); parsedMaxPoolConnections = 10; } else if (parsedMaxPoolConnections > 100) { log.warn("db", "Max database connections capped to 100 because Mysql/Mariadb connections are heavy. consider using a proxy like ProxySQL or MaxScale."); parsedMaxPoolConnections = 100; } let mariadbPoolConfig = { min: 0, max: parsedMaxPoolConnections, idleTimeoutMillis: 30000, }; log.info("db", `Database Type: ${dbConfig.type}`); if (dbConfig.type === "sqlite") { if (! fs.existsSync(Database.sqlitePath)) { log.info("server", "Copying Database"); fs.copyFileSync(Database.templatePath, Database.sqlitePath); } const Dialect = require("knex/lib/dialects/sqlite3/index.js"); Dialect.prototype._driver = () => require("@louislam/sqlite3"); config = { client: Dialect, connection: { filename: Database.sqlitePath, acquireConnectionTimeout: acquireConnectionTimeout, }, useNullAsDefault: true, pool: { min: 1, max: 1, idleTimeoutMillis: 120 * 1000, propagateCreateError: false, acquireTimeoutMillis: acquireConnectionTimeout, } }; } else if (dbConfig.type === "mariadb") { const connection = await mysql.createConnection({ host: dbConfig.hostname, port: dbConfig.port, user: dbConfig.username, password: dbConfig.password, }); // Set to true, so for example "uptime.kuma", becomes `uptime.kuma`, not `uptime`.`kuma` // Doc: https://github.com/mysqljs/sqlstring?tab=readme-ov-file#escaping-query-identifiers const escapedDBName = SqlString.escapeId(dbConfig.dbName, true); await connection.execute("CREATE DATABASE IF NOT EXISTS " + escapedDBName + " CHARACTER SET utf8mb4"); connection.end(); config = { client: "mysql2", connection: { host: dbConfig.hostname, port: dbConfig.port, user: dbConfig.username, password: dbConfig.password, database: dbConfig.dbName, timezone: "Z", typeCast: function (field, next) { if (field.type === "DATETIME") { // Do not perform timezone conversion return field.string(); } return next(); }, }, pool: mariadbPoolConfig, }; } else if (dbConfig.type === "embedded-mariadb") { let embeddedMariaDB = EmbeddedMariaDB.getInstance(); await embeddedMariaDB.start(); log.info("mariadb", "Embedded MariaDB started"); config = { client: "mysql2", connection: { socketPath: embeddedMariaDB.socketPath, user: embeddedMariaDB.username, database: "kuma", timezone: "Z", typeCast: function (field, next) { if (field.type === "DATETIME") { // Do not perform timezone conversion return field.string(); } return next(); }, }, pool: mariadbPoolConfig, }; } else { throw new Error("Unknown Database type: " + dbConfig.type); } // Set to utf8mb4 for MariaDB if (dbConfig.type.endsWith("mariadb")) { config.pool = { afterCreate(conn, done) { conn.query("SET CHARACTER SET utf8mb4;", (err) => done(err, conn)); }, }; } const knexInstance = knex(config); R.setup(knexInstance); if (process.env.SQL_LOG === "1") { R.debug(true); } // Auto map the model to a bean object R.freeze(true); if (autoloadModels) { await R.autoloadModels("./server/model"); } if (dbConfig.type === "sqlite") { await this.initSQLite(testMode, noLog); } else if (dbConfig.type.endsWith("mariadb")) { await this.initMariaDB(); } } /** @param {boolean} testMode Should the connection be started in test mode? @param {boolean} noLog Should logs not be output? @returns {Promise<void>} */ static async initSQLite(testMode, noLog) { await R.exec("PRAGMA foreign_keys = ON"); if (testMode) { // Change to MEMORY await R.exec("PRAGMA journal_mode = MEMORY"); } else { // Change to WAL await R.exec("PRAGMA journal_mode = WAL"); } await R.exec("PRAGMA cache_size = -12000"); await R.exec("PRAGMA auto_vacuum = INCREMENTAL"); // This ensures that an operating system crash or power failure will not corrupt the database. // FULL synchronous is very safe, but it is also slower. // Read more: https://sqlite.org/pragma.html#pragma_synchronous await R.exec("PRAGMA synchronous = NORMAL"); if (!noLog) { log.debug("db", "SQLite config:"); log.debug("db", await R.getAll("PRAGMA journal_mode")); log.debug("db", await R.getAll("PRAGMA cache_size")); log.debug("db", "SQLite Version: " + await R.getCell("SELECT sqlite_version()")); } } /** * Initialize MariaDB * @returns {Promise<void>} */ static async initMariaDB() { log.debug("db", "Checking if MariaDB database exists..."); let hasTable = await R.hasTable("docker_host"); if (!hasTable) { const { createTables } = require("../db/knex_init_db"); await createTables(); } else { log.debug("db", "MariaDB database already exists"); } } /** * Patch the database * @param {number} port Start the migration server for aggregate tables on this port if provided * @param {string} hostname Start the migration server for aggregate tables on this hostname if provided * @returns {Promise<void>} */ static async patch(port = undefined, hostname = undefined) { // Still need to keep this for old versions of Uptime Kuma if (Database.dbConfig.type === "sqlite") { await this.patchSqlite(); } // Using knex migrations // https://knexjs.org/guide/migrations.html // https://gist.github.com/NigelEarle/70db130cc040cc2868555b29a0278261 try { // Disable foreign key check for SQLite // Known issue of knex: https://github.com/drizzle-team/drizzle-orm/issues/1813 if (Database.dbConfig.type === "sqlite") { await R.exec("PRAGMA foreign_keys = OFF"); } await R.knex.migrate.latest({ directory: Database.knexMigrationsPath, }); // Enable foreign key check for SQLite if (Database.dbConfig.type === "sqlite") { await R.exec("PRAGMA foreign_keys = ON"); } await this.migrateAggregateTable(port, hostname); } catch (e) { // Allow missing patch files for downgrade or testing pr. if (e.message.includes("the following files are missing:")) { log.warn("db", e.message); log.warn("db", "Database migration failed, you may be downgrading Uptime Kuma."); } else { log.error("db", "Database migration failed"); throw e; } } } /** * TODO * @returns {Promise<void>} */ static async rollbackLatestPatch() { } /** * Patch the database for SQLite * @returns {Promise<void>} * @deprecated */ static async patchSqlite() { let version = parseInt(await setting("database_version")); if (! version) { version = 0; } if (version !== this.latestVersion) { log.info("db", "Your database version: " + version); log.info("db", "Latest database version: " + this.latestVersion); } if (version === this.latestVersion) { log.debug("db", "Database patch not needed"); } else if (version > this.latestVersion) { log.warn("db", "Warning: Database version is newer than expected"); } else { log.info("db", "Database patch is needed"); // Try catch anything here try { for (let i = version + 1; i <= this.latestVersion; i++) { const sqlFile = `./db/old_migrations/patch${i}.sql`; log.info("db", `Patching ${sqlFile}`); await Database.importSQLFile(sqlFile); log.info("db", `Patched ${sqlFile}`); await setSetting("database_version", i); } } catch (ex) { await Database.close(); log.error("db", ex); log.error("db", "Start Uptime-Kuma failed due to issue patching the database"); log.error("db", "Please submit a bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); process.exit(1); } } await this.patchSqlite2(); await this.migrateNewStatusPage(); } /** * Patch DB using new process * Call it from patch() only * @deprecated * @private * @returns {Promise<void>} */ static async patchSqlite2() { log.debug("db", "Database Patch 2.0 Process"); let databasePatchedFiles = await setting("databasePatchedFiles"); if (! databasePatchedFiles) { databasePatchedFiles = {}; } log.debug("db", "Patched files:"); log.debug("db", databasePatchedFiles); try { for (let sqlFilename in this.patchList) { await this.patch2Recursion(sqlFilename, databasePatchedFiles); } if (this.patched) { log.info("db", "Database Patched Successfully"); } } catch (ex) { await Database.close(); log.error("db", ex); log.error("db", "Start Uptime-Kuma failed due to issue patching the database"); log.error("db", "Please submit the bug report if you still encounter the problem after restart: https://github.com/louislam/uptime-kuma/issues"); process.exit(1); } await setSetting("databasePatchedFiles", databasePatchedFiles); } /** * SQlite only * Migrate status page value in setting to "status_page" table * @returns {Promise<void>} */ static async migrateNewStatusPage() { // Fix 1.13.0 empty slug bug await R.exec("UPDATE status_page SET slug = 'empty-slug-recover' WHERE TRIM(slug) = ''"); let title = await setting("title"); if (title) { console.log("Migrating Status Page"); let statusPageCheck = await R.findOne("status_page", " slug = 'default' "); if (statusPageCheck !== null) { console.log("Migrating Status Page - Skip, default slug record is already existing"); return; } let statusPage = R.dispense("status_page"); statusPage.slug = "default"; statusPage.title = title; statusPage.description = await setting("description"); statusPage.icon = await setting("icon"); statusPage.theme = await setting("statusPageTheme"); statusPage.published = !!await setting("statusPagePublished"); statusPage.search_engine_index = !!await setting("searchEngineIndex"); statusPage.show_tags = !!await setting("statusPageTags"); statusPage.password = null; if (!statusPage.title) { statusPage.title = "My Status Page"; } if (!statusPage.icon) { statusPage.icon = ""; } if (!statusPage.theme) { statusPage.theme = "light"; } let id = await R.store(statusPage); await R.exec("UPDATE incident SET status_page_id = ? WHERE status_page_id IS NULL", [ id ]); await R.exec("UPDATE [group] SET status_page_id = ? WHERE status_page_id IS NULL", [ id ]); await R.exec("DELETE FROM setting WHERE type = 'statusPage'"); // Migrate Entry Page if it is status page let entryPage = await setting("entryPage"); if (entryPage === "statusPage") { await setSetting("entryPage", "statusPage-default", "general"); } console.log("Migrating Status Page - Done"); } } /** * Patch database using new patching process * Used it patch2() only * @private * @param {string} sqlFilename Name of SQL file to load * @param {object} databasePatchedFiles Patch status of database files * @returns {Promise<void>} */ static async patch2Recursion(sqlFilename, databasePatchedFiles) { let value = this.patchList[sqlFilename]; if (! value) { log.info("db", sqlFilename + " skip"); return; } // Check if patched if (! databasePatchedFiles[sqlFilename]) { log.info("db", sqlFilename + " is not patched"); if (value.parents) { log.info("db", sqlFilename + " need parents"); for (let parentSQLFilename of value.parents) { await this.patch2Recursion(parentSQLFilename, databasePatchedFiles); } } log.info("db", sqlFilename + " is patching"); this.patched = true; await this.importSQLFile("./db/old_migrations/" + sqlFilename); databasePatchedFiles[sqlFilename] = true; log.info("db", sqlFilename + " was patched successfully"); } else { log.debug("db", sqlFilename + " is already patched, skip"); } } /** * Load an SQL file and execute it * @param {string} filename Filename of SQL file to import * @returns {Promise<void>} */ static async importSQLFile(filename) { // Sadly, multi sql statements is not supported by many sqlite libraries, I have to implement it myself await R.getCell("SELECT 1"); let text = fs.readFileSync(filename).toString(); // Remove all comments (--) let lines = text.split("\n"); lines = lines.filter((line) => { return ! line.startsWith("--"); }); // Split statements by semicolon // Filter out empty line text = lines.join("\n"); let statements = text.split(";") .map((statement) => { return statement.trim(); }) .filter((statement) => { return statement !== ""; }); for (let statement of statements) { await R.exec(statement); } } /** * Special handle, because tarn.js throw a promise reject that cannot be caught * @returns {Promise<void>} */ static async close() { const listener = (reason, p) => { Database.noReject = false; }; process.addListener("unhandledRejection", listener); log.info("db", "Closing the database"); // Flush WAL to main database if (Database.dbConfig.type === "sqlite") { await R.exec("PRAGMA wal_checkpoint(TRUNCATE)"); } while (true) { Database.noReject = true; await R.close(); await sleep(2000); if (Database.noReject) { break; } else { log.info("db", "Waiting to close the database"); } } log.info("db", "Database closed"); process.removeListener("unhandledRejection", listener); } /** * Get the size of the database (SQLite only) * @returns {Promise<number>} Size of database */ static async getSize() { if (Database.dbConfig.type === "sqlite") { log.debug("db", "Database.getSize()"); let stats = await fsAsync.stat(Database.sqlitePath); log.debug("db", stats); return stats.size; } return 0; } /** * Shrink the database * @returns {Promise<void>} */ static async shrink() { if (Database.dbConfig.type === "sqlite") { await R.exec("VACUUM"); } } /** * @returns {string} Get the SQL for the current time plus a number of hours */ static sqlHourOffset() { if (Database.dbConfig.type === "sqlite") { return "DATETIME('now', ? || ' hours')"; } else { return "DATE_ADD(UTC_TIMESTAMP(), INTERVAL ? HOUR)"; } } /** * Migrate the old data in the heartbeat table to the new format (stat_daily, stat_hourly, stat_minutely) * It should be run once while upgrading V1 to V2 * * Normally, it should be in transaction, but UptimeCalculator wasn't designed to be in transaction before that. * I don't want to heavily modify the UptimeCalculator, so it is not in transaction. * Run `npm run reset-migrate-aggregate-table-state` to reset, in case the migration is interrupted. * @param {number} port Start the migration server on this port if provided * @param {string} hostname Start the migration server on this hostname if provided * @returns {Promise<void>} */ static async migrateAggregateTable(port, hostname = undefined) { log.debug("db", "Enter Migrate Aggregate Table function"); // Add a setting for 2.0.0-dev users to skip this migration if (process.env.SET_MIGRATE_AGGREGATE_TABLE_TO_TRUE === "1") { log.warn("db", "SET_MIGRATE_AGGREGATE_TABLE_TO_TRUE is set to 1, skipping aggregate table migration forever (for 2.0.0-dev users)"); await Settings.set("migrateAggregateTableState", "migrated"); } let migrateState = await Settings.get("migrateAggregateTableState"); // Skip if already migrated // If it is migrating, it possibly means the migration was interrupted, or the migration is in progress if (migrateState === "migrated") { log.debug("db", "Migrated aggregate table already, skip"); return; } else if (migrateState === "migrating") { log.warn("db", "Aggregate table migration is already in progress, or it was interrupted"); throw new Error("Aggregate table migration is already in progress"); } /** * Start migration server for displaying the migration status * @type {SimpleMigrationServer} */ let migrationServer; let msg; if (port) { migrationServer = new SimpleMigrationServer(); await migrationServer.start(port, hostname); } log.info("db", "Migrating Aggregate Table"); log.info("db", "Getting list of unique monitors"); // Get a list of unique monitors from the heartbeat table, using raw sql let monitors = await R.getAll(` SELECT DISTINCT monitor_id FROM heartbeat ORDER BY monitor_id ASC `); // Stop if stat_* tables are not empty for (let table of [ "stat_minutely", "stat_hourly", "stat_daily" ]) { let countResult = await R.getRow(`SELECT COUNT(*) AS count FROM ${table}`); let count = countResult.count; if (count > 0) { log.warn("db", `Aggregate table ${table} is not empty, migration will not be started (Maybe you were using 2.0.0-dev?)`); await migrationServer?.stop(); return; } } await Settings.set("migrateAggregateTableState", "migrating"); let progressPercent = 0; for (const [ i, monitor ] of monitors.entries()) { // Get a list of unique dates from the heartbeat table, using raw sql let dates = await R.getAll(` SELECT DISTINCT DATE(time) AS date FROM heartbeat WHERE monitor_id = ? ORDER BY date ASC `, [ monitor.monitor_id ]); for (const [ dateIndex, date ] of dates.entries()) { // New Uptime Calculator let calculator = new UptimeCalculator(); calculator.monitorID = monitor.monitor_id; calculator.setMigrationMode(true); // Get all the heartbeats for this monitor and date let heartbeats = await R.getAll(` SELECT status, ping, time FROM heartbeat WHERE monitor_id = ? AND DATE(time) = ? ORDER BY time ASC `, [ monitor.monitor_id, date.date ]); if (heartbeats.length > 0) { msg = `[DON'T STOP] Migrating monitor ${monitor.monitor_id}s' (${i + 1} of ${monitors.length} total) data - ${date.date} - total migration progress ${progressPercent.toFixed(2)}%`; log.info("db", msg); migrationServer?.update(msg); } for (let heartbeat of heartbeats) { await calculator.update(heartbeat.status, parseFloat(heartbeat.ping), dayjs(heartbeat.time)); } // Calculate progress: (current_monitor_index + relative_date_progress) / total_monitors progressPercent = (i + (dateIndex + 1) / dates.length) / monitors.length * 100; // Lazy to fix the floating point issue, it is acceptable since it is just a progress bar if (progressPercent > 100) { progressPercent = 100; } } } msg = "Clearing non-important heartbeats"; log.info("db", msg); migrationServer?.update(msg); await Database.clearHeartbeatData(true); await Settings.set("migrateAggregateTableState", "migrated"); await migrationServer?.stop(); if (monitors.length > 0) { log.info("db", "Aggregate Table Migration Completed"); } else { log.info("db", "No data to migrate"); } } /** * Remove all non-important heartbeats from heartbeat table, keep last 24-hour or {KEEP_LAST_ROWS} rows for each monitor * @param {boolean} detailedLog Log detailed information * @returns {Promise<void>} */ static async clearHeartbeatData(detailedLog = false) { let monitors = await R.getAll("SELECT id FROM monitor"); const sqlHourOffset = Database.sqlHourOffset(); for (let monitor of monitors) { if (detailedLog) { log.info("db", "Deleting non-important heartbeats for monitor " + monitor.id); } await R.exec(` DELETE FROM heartbeat WHERE monitor_id = ? AND important = 0 AND time < ${sqlHourOffset} AND id NOT IN (
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
true
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/radius-client.js
server/radius-client.js
/** * Custom RADIUS Client Implementation * * This is a lightweight RADIUS client implementation using the base `radius` package * Due to lack of maintenance in node-radius-client this was forked * * Implements RADIUS Access-Request functionality compatible with the original * node-radius-client API used in Uptime Kuma. */ const dgram = require("dgram"); const radius = require("radius"); /** * RADIUS Client class */ class RadiusClient { /** * @param {object} options Client configuration * @param {string} options.host RADIUS server hostname * @param {number} options.hostPort RADIUS server port (default: 1812) * @param {number} options.timeout Request timeout in milliseconds (default: 2500) * @param {number} options.retries Number of retry attempts (default: 1) * @param {Array} options.dictionaries RADIUS dictionaries for attribute encoding */ constructor(options) { this.host = options.host; this.port = options.hostPort || 1812; this.timeout = options.timeout || 2500; this.retries = options.retries || 1; this.dictionaries = options.dictionaries || []; } /** * Send RADIUS Access-Request * @param {object} params Request parameters * @param {string} params.secret RADIUS shared secret * @param {Array} params.attributes Array of [attribute, value] pairs * @returns {Promise<object>} RADIUS response */ accessRequest(params) { return new Promise((resolve, reject) => { const { secret, attributes } = params; // Build RADIUS packet const packet = { code: "Access-Request", secret: secret, attributes: {} }; // Convert attributes array to object attributes.forEach(([ attr, value ]) => { packet.attributes[attr] = value; }); // Encode packet let encodedPacket; try { encodedPacket = radius.encode(packet); } catch (error) { return reject(new Error(`RADIUS packet encoding failed: ${error.message}`)); } // Create UDP socket const socket = dgram.createSocket("udp4"); let attempts = 0; let responseReceived = false; let timeoutHandle; /** * Send RADIUS request with retry logic * @returns {void} */ const sendRequest = () => { attempts++; socket.send(encodedPacket, 0, encodedPacket.length, this.port, this.host, (err) => { if (err) { socket.close(); return reject(new Error(`Failed to send RADIUS request: ${err.message}`)); } // Set timeout for this attempt timeoutHandle = setTimeout(() => { if (responseReceived) { return; } if (attempts < this.retries + 1) { // Retry sendRequest(); } else { // All retries exhausted socket.close(); reject(new Error(`RADIUS request timeout after ${attempts} attempts`)); } }, this.timeout); }); }; // Handle response socket.on("message", (msg) => { if (responseReceived) { return; } responseReceived = true; clearTimeout(timeoutHandle); let response; try { response = radius.decode({ packet: msg, secret: secret }); } catch (error) { socket.close(); return reject(new Error(`RADIUS response decoding failed: ${error.message}`)); } socket.close(); // Map response code to match node-radius-client format const responseCode = response.code; if (responseCode === "Access-Accept") { resolve({ code: "Access-Accept", ...response }); } else if (responseCode === "Access-Reject") { // Reject as error to match original behavior const error = new Error("Access-Reject"); error.response = { code: "Access-Reject" }; reject(error); } else if (responseCode === "Access-Challenge") { // Challenge response const error = new Error("Access-Challenge"); error.response = { code: "Access-Challenge" }; reject(error); } else { resolve({ code: responseCode, ...response }); } }); // Handle socket errors socket.on("error", (err) => { if (!responseReceived) { responseReceived = true; clearTimeout(timeoutHandle); socket.close(); reject(new Error(`RADIUS socket error: ${err.message}`)); } }); // Start first request sendRequest(); }); } } module.exports = RadiusClient;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/util-server.js
server/util-server.js
const ping = require("@louislam/ping"); const { R } = require("redbean-node"); const { log, genSecret, badgeConstants, PING_PACKET_SIZE_DEFAULT, PING_GLOBAL_TIMEOUT_DEFAULT, PING_COUNT_DEFAULT, PING_PER_REQUEST_TIMEOUT_DEFAULT } = require("../src/util"); const passwordHash = require("./password-hash"); const { Resolver } = require("dns"); const iconv = require("iconv-lite"); const chardet = require("chardet"); const chroma = require("chroma-js"); const mysql = require("mysql2"); const { NtlmClient } = require("./modules/axios-ntlm/lib/ntlmClient.js"); const { Settings } = require("./settings"); const RadiusClient = require("./radius-client"); const oidc = require("openid-client"); const tls = require("tls"); const { exists } = require("fs"); const { dictionaries: { rfc2865: { file, attributes }, }, } = require("node-radius-utils"); const dayjs = require("dayjs"); // SASLOptions used in JSDoc // eslint-disable-next-line no-unused-vars const { Kafka, SASLOptions } = require("kafkajs"); const crypto = require("crypto"); const isWindows = process.platform === /^win/.test(process.platform); /** * Init or reset JWT secret * @returns {Promise<Bean>} JWT secret */ exports.initJWTSecret = async () => { let jwtSecretBean = await R.findOne("setting", " `key` = ? ", [ "jwtSecret", ]); if (!jwtSecretBean) { jwtSecretBean = R.dispense("setting"); jwtSecretBean.key = "jwtSecret"; } jwtSecretBean.value = await passwordHash.generate(genSecret()); await R.store(jwtSecretBean); return jwtSecretBean; }; /** * Decodes a jwt and returns the payload portion without verifying the jwt. * @param {string} jwt The input jwt as a string * @returns {object} Decoded jwt payload object */ exports.decodeJwt = (jwt) => { return JSON.parse(Buffer.from(jwt.split(".")[1], "base64").toString()); }; /** * Gets an Access Token from an oidc/oauth2 provider * @param {string} tokenEndpoint The token URI from the auth service provider * @param {string} clientId The oidc/oauth application client id * @param {string} clientSecret The oidc/oauth application client secret * @param {string} scope The scope(s) for which the token should be issued for * @param {string} audience The audience for which the token should be issued for * @param {string} authMethod The method used to send the credentials. Default client_secret_basic * @returns {Promise<oidc.TokenSet>} TokenSet promise if the token request was successful */ exports.getOidcTokenClientCredentials = async (tokenEndpoint, clientId, clientSecret, scope, audience, authMethod = "client_secret_basic") => { const oauthProvider = new oidc.Issuer({ token_endpoint: tokenEndpoint }); let client = new oauthProvider.Client({ client_id: clientId, client_secret: clientSecret, token_endpoint_auth_method: authMethod }); // Increase default timeout and clock tolerance client[oidc.custom.http_options] = () => ({ timeout: 10000 }); client[oidc.custom.clock_tolerance] = 5; let grantParams = { grant_type: "client_credentials" }; if (scope) { grantParams.scope = scope; } if (audience) { grantParams.audience = audience; } return await client.grant(grantParams); }; /** * Ping the specified machine * @param {string} destAddr Hostname / IP address of machine to ping * @param {number} count Number of packets to send before stopping * @param {string} sourceAddr Source address for sending/receiving echo requests * @param {boolean} numeric If true, IP addresses will be output instead of symbolic hostnames * @param {number} size Size (in bytes) of echo request to send * @param {number} deadline Maximum time in seconds before ping stops, regardless of packets sent * @param {number} timeout Maximum time in seconds to wait for each response * @returns {Promise<number>} Time for ping in ms rounded to nearest integer */ exports.ping = async ( destAddr, count = PING_COUNT_DEFAULT, sourceAddr = "", numeric = true, size = PING_PACKET_SIZE_DEFAULT, deadline = PING_GLOBAL_TIMEOUT_DEFAULT, timeout = PING_PER_REQUEST_TIMEOUT_DEFAULT, ) => { try { return await exports.pingAsync(destAddr, false, count, sourceAddr, numeric, size, deadline, timeout); } catch (e) { // If the host cannot be resolved, try again with ipv6 log.debug("ping", "IPv6 error message: " + e.message); // As node-ping does not report a specific error for this, try again if it is an empty message with ipv6 no matter what. if (!e.message) { return await exports.pingAsync(destAddr, true, count, sourceAddr, numeric, size, deadline, timeout); } else { throw e; } } }; /** * Ping the specified machine * @param {string} destAddr Hostname / IP address of machine to ping * @param {boolean} ipv6 Should IPv6 be used? * @param {number} count Number of packets to send before stopping * @param {string} sourceAddr Source address for sending/receiving echo requests * @param {boolean} numeric If true, IP addresses will be output instead of symbolic hostnames * @param {number} size Size (in bytes) of echo request to send * @param {number} deadline Maximum time in seconds before ping stops, regardless of packets sent * @param {number} timeout Maximum time in seconds to wait for each response * @returns {Promise<number>} Time for ping in ms rounded to nearest integer */ exports.pingAsync = function ( destAddr, ipv6 = false, count = PING_COUNT_DEFAULT, sourceAddr = "", numeric = true, size = PING_PACKET_SIZE_DEFAULT, deadline = PING_GLOBAL_TIMEOUT_DEFAULT, timeout = PING_PER_REQUEST_TIMEOUT_DEFAULT, ) { return new Promise((resolve, reject) => { ping.promise.probe(destAddr, { v6: ipv6, min_reply: count, sourceAddr: sourceAddr, numeric: numeric, packetSize: size, deadline: deadline, timeout: timeout }).then((res) => { // If ping failed, it will set field to unknown if (res.alive) { resolve(res.time); } else { if (isWindows) { reject(new Error(exports.convertToUTF8(res.output))); } else { reject(new Error(res.output)); } } }).catch((err) => { reject(err); }); }); }; /** * Monitor Kafka using Producer * @param {string[]} brokers List of kafka brokers to connect, host and * port joined by ':' * @param {string} topic Topic name to produce into * @param {string} message Message to produce * @param {object} options Kafka client options. Contains ssl, clientId, * allowAutoTopicCreation and interval (interval defaults to 20, * allowAutoTopicCreation defaults to false, clientId defaults to * "Uptime-Kuma" and ssl defaults to false) * @param {SASLOptions} saslOptions Options for kafka client * Authentication (SASL) (defaults to {}) * @returns {Promise<string>} Status message */ exports.kafkaProducerAsync = function (brokers, topic, message, options = {}, saslOptions = {}) { return new Promise((resolve, reject) => { const { interval = 20, allowAutoTopicCreation = false, ssl = false, clientId = "Uptime-Kuma" } = options; let connectedToKafka = false; const timeoutID = setTimeout(() => { log.debug("kafkaProducer", "KafkaProducer timeout triggered"); connectedToKafka = true; reject(new Error("Timeout")); }, interval * 1000 * 0.8); if (saslOptions.mechanism === "None") { saslOptions = undefined; } let client = new Kafka({ brokers: brokers, clientId: clientId, sasl: saslOptions, retry: { retries: 0, }, ssl: ssl, }); let producer = client.producer({ allowAutoTopicCreation: allowAutoTopicCreation, retry: { retries: 0, } }); producer.connect().then( () => { producer.send({ topic: topic, messages: [{ value: message, }], }).then((_) => { resolve("Message sent successfully"); }).catch((e) => { connectedToKafka = true; producer.disconnect(); clearTimeout(timeoutID); reject(new Error("Error sending message: " + e.message)); }).finally(() => { connectedToKafka = true; clearTimeout(timeoutID); }); } ).catch( (e) => { connectedToKafka = true; producer.disconnect(); clearTimeout(timeoutID); reject(new Error("Error in producer connection: " + e.message)); } ); producer.on("producer.network.request_timeout", (_) => { if (!connectedToKafka) { clearTimeout(timeoutID); reject(new Error("producer.network.request_timeout")); } }); producer.on("producer.disconnect", (_) => { if (!connectedToKafka) { clearTimeout(timeoutID); reject(new Error("producer.disconnect")); } }); }); }; /** * Use NTLM Auth for a http request. * @param {object} options The http request options * @param {object} ntlmOptions The auth options * @returns {Promise<(string[] | object[] | object)>} NTLM response */ exports.httpNtlm = function (options, ntlmOptions) { return new Promise((resolve, reject) => { let client = NtlmClient(ntlmOptions); client(options) .then((resp) => { resolve(resp); }) .catch((err) => { reject(err); }); }); }; /** * Resolves a given record using the specified DNS server * @param {string} hostname The hostname of the record to lookup * @param {string} resolverServer The DNS server to use * @param {string} resolverPort Port the DNS server is listening on * @param {string} rrtype The type of record to request * @returns {Promise<(string[] | object[] | object)>} DNS response */ exports.dnsResolve = function (hostname, resolverServer, resolverPort, rrtype) { const resolver = new Resolver(); // Remove brackets from IPv6 addresses so we can re-add them to // prevent issues with ::1:5300 (::1 port 5300) resolverServer = resolverServer.replace("[", "").replace("]", ""); resolver.setServers([ `[${resolverServer}]:${resolverPort}` ]); return new Promise((resolve, reject) => { if (rrtype === "PTR") { resolver.reverse(hostname, (err, records) => { if (err) { reject(err); } else { resolve(records); } }); } else { resolver.resolve(hostname, rrtype, (err, records) => { if (err) { reject(err); } else { resolve(records); } }); } }); }; /** * Run a query on MySQL/MariaDB * @param {string} connectionString The database connection string * @param {string} query The query to validate the database with * @param {?string} password The password to use * @returns {Promise<(string)>} Response from server */ exports.mysqlQuery = function (connectionString, query, password = undefined) { return new Promise((resolve, reject) => { const connection = mysql.createConnection({ uri: connectionString, password }); connection.on("error", (err) => { reject(err); }); connection.query(query, (err, res) => { if (err) { reject(err); } else { if (Array.isArray(res)) { resolve("Rows: " + res.length); } else { resolve("No Error, but the result is not an array. Type: " + typeof res); } } try { connection.end(); } catch (_) { connection.destroy(); } }); }); }; /** * Query radius server * @param {string} hostname Hostname of radius server * @param {string} username Username to use * @param {string} password Password to use * @param {string} calledStationId ID of called station * @param {string} callingStationId ID of calling station * @param {string} secret Secret to use * @param {number} port Port to contact radius server on * @param {number} timeout Timeout for connection to use * @returns {Promise<any>} Response from server */ exports.radius = function ( hostname, username, password, calledStationId, callingStationId, secret, port = 1812, timeout = 2500, ) { const client = new RadiusClient({ host: hostname, hostPort: port, timeout: timeout, retries: 1, dictionaries: [ file ], }); return client.accessRequest({ secret: secret, attributes: [ [ attributes.USER_NAME, username ], [ attributes.USER_PASSWORD, password ], [ attributes.CALLING_STATION_ID, callingStationId ], [ attributes.CALLED_STATION_ID, calledStationId ], ], }).catch((error) => { if (error.response?.code) { throw Error(error.response.code); } else { throw Error(error.message); } }); }; /** * Retrieve value of setting based on key * @param {string} key Key of setting to retrieve * @returns {Promise<any>} Value * @deprecated Use await Settings.get(key) */ exports.setting = async function (key) { return await Settings.get(key); }; /** * Sets the specified setting to specified value * @param {string} key Key of setting to set * @param {any} value Value to set to * @param {?string} type Type of setting * @returns {Promise<void>} */ exports.setSetting = async function (key, value, type = null) { await Settings.set(key, value, type); }; /** * Get settings based on type * @param {string} type The type of setting * @returns {Promise<Bean>} Settings of requested type */ exports.getSettings = async function (type) { return await Settings.getSettings(type); }; /** * Set settings based on type * @param {string} type Type of settings to set * @param {object} data Values of settings * @returns {Promise<void>} */ exports.setSettings = async function (type, data) { await Settings.setSettings(type, data); }; // ssl-checker by @dyaa //https://github.com/dyaa/ssl-checker/blob/master/src/index.ts /** * Get number of days between two dates * @param {Date} validFrom Start date * @param {Date} validTo End date * @returns {number} Number of days */ const getDaysBetween = (validFrom, validTo) => Math.round(Math.abs(+validFrom - +validTo) / 8.64e7); exports.getDaysBetween = getDaysBetween; /** * Get days remaining from a time range * @param {Date} validFrom Start date * @param {Date} validTo End date * @returns {number} Number of days remaining */ const getDaysRemaining = (validFrom, validTo) => { const daysRemaining = getDaysBetween(validFrom, validTo); if (new Date(validTo).getTime() < new Date(validFrom).getTime()) { return -daysRemaining; } return daysRemaining; }; exports.getDaysRemaining = getDaysRemaining; /** * Fix certificate info for display * @param {object} info The chain obtained from getPeerCertificate() * @returns {object} An object representing certificate information * @throws The certificate chain length exceeded 500. */ const parseCertificateInfo = function (info) { let link = info; let i = 0; const existingList = {}; while (link) { log.debug("cert", `[${i}] ${link.fingerprint}`); if (!link.valid_from || !link.valid_to) { break; } link.validTo = new Date(link.valid_to); link.validFor = link.subjectaltname?.replace(/DNS:|IP Address:/g, "").split(", "); link.daysRemaining = getDaysRemaining(new Date(), link.validTo); existingList[link.fingerprint] = true; // Move up the chain until loop is encountered if (link.issuerCertificate == null) { link.certType = (i === 0) ? "self-signed" : "root CA"; break; } else if (link.issuerCertificate.fingerprint in existingList) { // a root CA certificate is typically "signed by itself" (=> "self signed certificate") and thus the "issuerCertificate" is a reference to itself. log.debug("cert", `[Last] ${link.issuerCertificate.fingerprint}`); link.certType = (i === 0) ? "self-signed" : "root CA"; link.issuerCertificate = null; break; } else { link.certType = (i === 0) ? "server" : "intermediate CA"; link = link.issuerCertificate; } // Should be no use, but just in case. if (i > 500) { throw new Error("Dead loop occurred in parseCertificateInfo"); } i++; } return info; }; /** * Check if certificate is valid * @param {tls.TLSSocket} socket TLSSocket, which may or may not be connected * @returns {object} Object containing certificate information */ exports.checkCertificate = function (socket) { let certInfoStartTime = dayjs().valueOf(); // Return null if there is no socket if (socket === undefined || socket == null) { return null; } const info = socket.getPeerCertificate(true); const valid = socket.authorized || false; log.debug("cert", "Parsing Certificate Info"); const parsedInfo = parseCertificateInfo(info); if (process.env.TIMELOGGER === "1") { log.debug("monitor", "Cert Info Query Time: " + (dayjs().valueOf() - certInfoStartTime) + "ms"); } return { valid: valid, certInfo: parsedInfo }; }; /** * Checks if the certificate is valid for the provided hostname. * Defaults to true if feature `X509Certificate` is not available, or input is not valid. * @param {Buffer} certBuffer - The certificate buffer. * @param {string} hostname - The hostname to compare against. * @returns {boolean} True if the certificate is valid for the provided hostname, false otherwise. */ exports.checkCertificateHostname = function (certBuffer, hostname) { let X509Certificate; try { X509Certificate = require("node:crypto").X509Certificate; } catch (_) { // X509Certificate is not available in this version of Node.js return true; } if (!X509Certificate || !certBuffer || !hostname) { return true; } let certObject = new X509Certificate(certBuffer); return certObject.checkHost(hostname) !== undefined; }; /** * Check if the provided status code is within the accepted ranges * @param {number} status The status code to check * @param {string[]} acceptedCodes An array of accepted status codes * @returns {boolean} True if status code within range, false otherwise */ exports.checkStatusCode = function (status, acceptedCodes) { if (acceptedCodes == null || acceptedCodes.length === 0) { return false; } for (const codeRange of acceptedCodes) { if (typeof codeRange !== "string") { log.error("monitor", `Accepted status code not a string. ${codeRange} is of type ${typeof codeRange}`); continue; } const codeRangeSplit = codeRange.split("-").map(string => parseInt(string)); if (codeRangeSplit.length === 1) { if (status === codeRangeSplit[0]) { return true; } } else if (codeRangeSplit.length === 2) { if (status >= codeRangeSplit[0] && status <= codeRangeSplit[1]) { return true; } } else { log.error("monitor", `${codeRange} is not a valid status code range`); continue; } } return false; }; /** * Get total number of clients in room * @param {Server} io Socket server instance * @param {string} roomName Name of room to check * @returns {number} Total clients in room */ exports.getTotalClientInRoom = (io, roomName) => { const sockets = io.sockets; if (!sockets) { return 0; } const adapter = sockets.adapter; if (!adapter) { return 0; } const room = adapter.rooms.get(roomName); if (room) { return room.size; } else { return 0; } }; /** * Allow CORS all origins if development * @param {object} res Response object from axios * @returns {void} */ exports.allowDevAllOrigin = (res) => { if (process.env.NODE_ENV === "development") { exports.allowAllOrigin(res); } }; /** * Allow CORS all origins * @param {object} res Response object from axios * @returns {void} */ exports.allowAllOrigin = (res) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); }; /** * Check if a user is logged in * @param {Socket} socket Socket instance * @returns {void} * @throws The user is not logged in */ exports.checkLogin = (socket) => { if (!socket.userID) { throw new Error("You are not logged in."); } }; /** * For logged-in users, double-check the password * @param {Socket} socket Socket.io instance * @param {string} currentPassword Password to validate * @returns {Promise<Bean>} User * @throws The current password is not a string * @throws The provided password is not correct */ exports.doubleCheckPassword = async (socket, currentPassword) => { if (typeof currentPassword !== "string") { throw new Error("Wrong data type?"); } let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, ]); if (!user || !passwordHash.verify(currentPassword, user.password)) { throw new Error("Incorrect current password"); } return user; }; /** * Convert unknown string to UTF8 * @param {Uint8Array} body Buffer * @returns {string} UTF8 string */ exports.convertToUTF8 = (body) => { const guessEncoding = chardet.detect(body); const str = iconv.decode(body, guessEncoding); return str.toString(); }; /** * Returns a color code in hex format based on a given percentage: * 0% => hue = 10 => red * 100% => hue = 90 => green * @param {number} percentage float, 0 to 1 * @param {number} maxHue Maximum hue - int * @param {number} minHue Minimum hue - int * @returns {string} Color in hex */ exports.percentageToColor = (percentage, maxHue = 90, minHue = 10) => { const hue = percentage * (maxHue - minHue) + minHue; try { return chroma(`hsl(${hue}, 90%, 40%)`).hex(); } catch (err) { return badgeConstants.naColor; } }; /** * Joins and array of string to one string after filtering out empty values * @param {string[]} parts Strings to join * @param {string} connector Separator for joined strings * @returns {string} Joined strings */ exports.filterAndJoin = (parts, connector = "") => { return parts.filter((part) => !!part && part !== "").join(connector); }; /** * Send an Error response * @param {object} res Express response object * @param {string} msg Message to send * @returns {void} */ module.exports.sendHttpError = (res, msg = "") => { if (msg.includes("SQLITE_BUSY") || msg.includes("SQLITE_LOCKED")) { res.status(503).json({ "status": "fail", "msg": msg, }); } else if (msg.toLowerCase().includes("not found")) { res.status(404).json({ "status": "fail", "msg": msg, }); } else { res.status(403).json({ "status": "fail", "msg": msg, }); } }; /** * Convert timezone of time object * @param {object} obj Time object to update * @param {string} timezone New timezone to set * @param {boolean} timeObjectToUTC Convert time object to UTC * @returns {object} Time object with updated timezone */ function timeObjectConvertTimezone(obj, timezone, timeObjectToUTC = true) { let offsetString; if (timezone) { offsetString = dayjs().tz(timezone).format("Z"); } else { offsetString = dayjs().format("Z"); } let hours = parseInt(offsetString.substring(1, 3)); let minutes = parseInt(offsetString.substring(4, 6)); if ( (timeObjectToUTC && offsetString.startsWith("+")) || (!timeObjectToUTC && offsetString.startsWith("-")) ) { hours *= -1; minutes *= -1; } obj.hours += hours; obj.minutes += minutes; // Handle out of bound if (obj.minutes < 0) { obj.minutes += 60; obj.hours--; } else if (obj.minutes > 60) { obj.minutes -= 60; obj.hours++; } if (obj.hours < 0) { obj.hours += 24; } else if (obj.hours > 24) { obj.hours -= 24; } return obj; } /** * Convert time object to UTC * @param {object} obj Object to convert * @param {string} timezone Timezone of time object * @returns {object} Updated time object */ module.exports.timeObjectToUTC = (obj, timezone = undefined) => { return timeObjectConvertTimezone(obj, timezone, true); }; /** * Convert time object to local time * @param {object} obj Object to convert * @param {string} timezone Timezone to convert to * @returns {object} Updated object */ module.exports.timeObjectToLocal = (obj, timezone = undefined) => { return timeObjectConvertTimezone(obj, timezone, false); }; /** * Returns an array of SHA256 fingerprints for all known root certificates. * @returns {Set} A set of SHA256 fingerprints. */ module.exports.rootCertificatesFingerprints = () => { let fingerprints = tls.rootCertificates.map(cert => { let certLines = cert.split("\n"); certLines.shift(); certLines.pop(); let certBody = certLines.join(""); let buf = Buffer.from(certBody, "base64"); const shasum = crypto.createHash("sha256"); shasum.update(buf); return shasum.digest("hex").toUpperCase().replace(/(.{2})(?!$)/g, "$1:"); }); fingerprints.push("6D:99:FB:26:5E:B1:C5:B3:74:47:65:FC:BC:64:8F:3C:D8:E1:BF:FA:FD:C4:C2:F9:9B:9D:47:CF:7F:F1:C2:4F"); // ISRG X1 cross-signed with DST X3 fingerprints.push("8B:05:B6:8C:C6:59:E5:ED:0F:CB:38:F2:C9:42:FB:FD:20:0E:6F:2F:F9:F8:5D:63:C6:99:4E:F5:E0:B0:27:01"); // ISRG X2 cross-signed with ISRG X1 return new Set(fingerprints); }; module.exports.SHAKE256_LENGTH = 16; /** * @param {string} data The data to be hashed * @param {number} len Output length of the hash * @returns {string} The hashed data in hex format */ module.exports.shake256 = (data, len) => { if (!data) { return ""; } return crypto.createHash("shake256", { outputLength: len }) .update(data) .digest("hex"); }; /** * Non await sleep * Source: https://stackoverflow.com/questions/59099454/is-there-a-way-to-call-sleep-without-await-keyword * @param {number} n Milliseconds to wait * @returns {void} */ module.exports.wait = (n) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n); }; // For unit test, export functions if (process.env.TEST_BACKEND) { module.exports.__test = { parseCertificateInfo, }; module.exports.__getPrivateFunction = (functionName) => { return module.exports.__test[functionName]; }; } /** * Generates an abort signal with the specified timeout. * @param {number} timeoutMs - The timeout in milliseconds. * @returns {AbortSignal | null} - The generated abort signal, or null if not supported. */ module.exports.axiosAbortSignal = (timeoutMs) => { try { // Just in case, as 0 timeout here will cause the request to be aborted immediately if (!timeoutMs || timeoutMs <= 0) { timeoutMs = 5000; } return AbortSignal.timeout(timeoutMs); } catch (_) { // v16-: AbortSignal.timeout is not supported try { const abortController = new AbortController(); setTimeout(() => abortController.abort(), timeoutMs); return abortController.signal; } catch (_) { // v15-: AbortController is not supported return null; } } }; /** * Async version of fs.existsSync * @param {PathLike} path File path * @returns {Promise<boolean>} True if file exists, false otherwise */ function fsExists(path) { return new Promise(function (resolve, reject) { exists(path, function (exists) { resolve(exists); }); }); } module.exports.fsExists = fsExists; /** * By default, command-exists will throw a null error if the command does not exist, which is ugly. The function makes it better. * Read more: https://github.com/mathisonian/command-exists/issues/22 * @param {string} command Command to check * @returns {Promise<boolean>} True if command exists, false otherwise */ async function commandExists(command) { try { await require("command-exists")(command); return true; } catch (e) { return false; } } module.exports.commandExists = commandExists;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/uptime-calculator.js
server/uptime-calculator.js
const dayjs = require("dayjs"); const { UP, MAINTENANCE, DOWN, PENDING } = require("../src/util"); const { LimitQueue } = require("./utils/limit-queue"); const { log } = require("../src/util"); const { R } = require("redbean-node"); /** * Calculates the uptime of a monitor. */ class UptimeCalculator { /** * @private * @type {{string:UptimeCalculator}} */ static list = {}; /** * For testing purposes, we can set the current date to a specific date. * @type {dayjs.Dayjs} */ static currentDate = null; /** * monitorID the id of the monitor * @type {number} */ monitorID; /** * Recent 24-hour uptime, each item is a 1-minute interval * Key: {number} DivisionKey * @type {LimitQueue<number,string>} */ minutelyUptimeDataList = new LimitQueue(24 * 60); /** * Recent 30-day uptime, each item is a 1-hour interval * Key: {number} DivisionKey * @type {LimitQueue<number,string>} */ hourlyUptimeDataList = new LimitQueue(30 * 24); /** * Daily uptime data, * Key: {number} DailyKey */ dailyUptimeDataList = new LimitQueue(365); lastUptimeData = null; lastHourlyUptimeData = null; lastDailyUptimeData = null; lastDailyStatBean = null; lastHourlyStatBean = null; lastMinutelyStatBean = null; /** * For migration purposes. * @type {boolean} */ migrationMode = false; statMinutelyKeepHour = 24; statHourlyKeepDay = 30; /** * Get the uptime calculator for a monitor * Initializes and returns the monitor if it does not exist * @param {number} monitorID the id of the monitor * @returns {Promise<UptimeCalculator>} UptimeCalculator */ static async getUptimeCalculator(monitorID) { if (!monitorID) { throw new Error("Monitor ID is required"); } if (!UptimeCalculator.list[monitorID]) { UptimeCalculator.list[monitorID] = new UptimeCalculator(); await UptimeCalculator.list[monitorID].init(monitorID); } return UptimeCalculator.list[monitorID]; } /** * Remove a monitor from the list * @param {number} monitorID the id of the monitor * @returns {Promise<void>} */ static async remove(monitorID) { delete UptimeCalculator.list[monitorID]; } /** * Remove all monitors from the list * @returns {Promise<void>} */ static async removeAll() { UptimeCalculator.list = {}; } /** * */ constructor() { if (process.env.TEST_BACKEND) { // Override the getCurrentDate() method to return a specific date // Only for testing this.getCurrentDate = () => { if (UptimeCalculator.currentDate) { return UptimeCalculator.currentDate; } else { return dayjs.utc(); } }; } } /** * Initialize the uptime calculator for a monitor * @param {number} monitorID the id of the monitor * @returns {Promise<void>} */ async init(monitorID) { this.monitorID = monitorID; let now = this.getCurrentDate(); // Load minutely data from database (recent 24 hours only) let minutelyStatBeans = await R.find("stat_minutely", " monitor_id = ? AND timestamp > ? ORDER BY timestamp", [ monitorID, this.getMinutelyKey(now.subtract(24, "hour")), ]); for (let bean of minutelyStatBeans) { let data = { up: bean.up, down: bean.down, avgPing: bean.ping, minPing: bean.pingMin, maxPing: bean.pingMax, }; if (bean.extras != null) { data = { ...data, ...JSON.parse(bean.extras), }; } let key = bean.timestamp; this.minutelyUptimeDataList.push(key, data); } // Load hourly data from database (recent 30 days only) let hourlyStatBeans = await R.find("stat_hourly", " monitor_id = ? AND timestamp > ? ORDER BY timestamp", [ monitorID, this.getHourlyKey(now.subtract(30, "day")), ]); for (let bean of hourlyStatBeans) { let data = { up: bean.up, down: bean.down, avgPing: bean.ping, minPing: bean.pingMin, maxPing: bean.pingMax, }; if (bean.extras != null) { data = { ...data, ...JSON.parse(bean.extras), }; } this.hourlyUptimeDataList.push(bean.timestamp, data); } // Load daily data from database (recent 365 days only) let dailyStatBeans = await R.find("stat_daily", " monitor_id = ? AND timestamp > ? ORDER BY timestamp", [ monitorID, this.getDailyKey(now.subtract(365, "day")), ]); for (let bean of dailyStatBeans) { let data = { up: bean.up, down: bean.down, avgPing: bean.ping, minPing: bean.pingMin, maxPing: bean.pingMax, }; if (bean.extras != null) { data = { ...data, ...JSON.parse(bean.extras), }; } this.dailyUptimeDataList.push(bean.timestamp, data); } } /** * @param {number} status status * @param {number} ping Ping * @param {dayjs.Dayjs} date Date (Only for migration) * @returns {dayjs.Dayjs} date * @throws {Error} Invalid status */ async update(status, ping = 0, date) { if (!date) { date = this.getCurrentDate(); } let flatStatus = this.flatStatus(status); if (flatStatus === DOWN && ping > 0) { log.debug("uptime-calc", "The ping is not effective when the status is DOWN"); } let divisionKey = this.getMinutelyKey(date); let hourlyKey = this.getHourlyKey(date); let dailyKey = this.getDailyKey(date); let minutelyData = this.minutelyUptimeDataList[divisionKey]; let hourlyData = this.hourlyUptimeDataList[hourlyKey]; let dailyData = this.dailyUptimeDataList[dailyKey]; if (status === MAINTENANCE) { minutelyData.maintenance = minutelyData.maintenance ? minutelyData.maintenance + 1 : 1; hourlyData.maintenance = hourlyData.maintenance ? hourlyData.maintenance + 1 : 1; dailyData.maintenance = dailyData.maintenance ? dailyData.maintenance + 1 : 1; } else if (flatStatus === UP) { minutelyData.up += 1; hourlyData.up += 1; dailyData.up += 1; // Only UP status can update the ping if (!isNaN(ping)) { // Add avg ping // The first beat of the minute, the ping is the current ping if (minutelyData.up === 1) { minutelyData.avgPing = ping; minutelyData.minPing = ping; minutelyData.maxPing = ping; } else { minutelyData.avgPing = (minutelyData.avgPing * (minutelyData.up - 1) + ping) / minutelyData.up; minutelyData.minPing = Math.min(minutelyData.minPing, ping); minutelyData.maxPing = Math.max(minutelyData.maxPing, ping); } // Add avg ping // The first beat of the hour, the ping is the current ping if (hourlyData.up === 1) { hourlyData.avgPing = ping; hourlyData.minPing = ping; hourlyData.maxPing = ping; } else { hourlyData.avgPing = (hourlyData.avgPing * (hourlyData.up - 1) + ping) / hourlyData.up; hourlyData.minPing = Math.min(hourlyData.minPing, ping); hourlyData.maxPing = Math.max(hourlyData.maxPing, ping); } // Add avg ping (daily) // The first beat of the day, the ping is the current ping if (dailyData.up === 1) { dailyData.avgPing = ping; dailyData.minPing = ping; dailyData.maxPing = ping; } else { dailyData.avgPing = (dailyData.avgPing * (dailyData.up - 1) + ping) / dailyData.up; dailyData.minPing = Math.min(dailyData.minPing, ping); dailyData.maxPing = Math.max(dailyData.maxPing, ping); } } } else if (flatStatus === DOWN) { minutelyData.down += 1; hourlyData.down += 1; dailyData.down += 1; } if (minutelyData !== this.lastUptimeData) { this.lastUptimeData = minutelyData; } if (hourlyData !== this.lastHourlyUptimeData) { this.lastHourlyUptimeData = hourlyData; } if (dailyData !== this.lastDailyUptimeData) { this.lastDailyUptimeData = dailyData; } // Don't store data in test mode if (process.env.TEST_BACKEND) { log.debug("uptime-calc", "Skip storing data in test mode"); return date; } let dailyStatBean = await this.getDailyStatBean(dailyKey); dailyStatBean.up = dailyData.up; dailyStatBean.down = dailyData.down; dailyStatBean.ping = dailyData.avgPing; dailyStatBean.pingMin = dailyData.minPing; dailyStatBean.pingMax = dailyData.maxPing; { // eslint-disable-next-line no-unused-vars const { up, down, avgPing, minPing, maxPing, timestamp, ...extras } = dailyData; if (Object.keys(extras).length > 0) { dailyStatBean.extras = JSON.stringify(extras); } } await R.store(dailyStatBean); let currentDate = this.getCurrentDate(); // For migration mode, we don't need to store old hourly and minutely data, but we need 30-day's hourly data // Run anyway for non-migration mode if (!this.migrationMode || date.isAfter(currentDate.subtract(this.statHourlyKeepDay, "day"))) { let hourlyStatBean = await this.getHourlyStatBean(hourlyKey); hourlyStatBean.up = hourlyData.up; hourlyStatBean.down = hourlyData.down; hourlyStatBean.ping = hourlyData.avgPing; hourlyStatBean.pingMin = hourlyData.minPing; hourlyStatBean.pingMax = hourlyData.maxPing; { // eslint-disable-next-line no-unused-vars const { up, down, avgPing, minPing, maxPing, timestamp, ...extras } = hourlyData; if (Object.keys(extras).length > 0) { hourlyStatBean.extras = JSON.stringify(extras); } } await R.store(hourlyStatBean); } // For migration mode, we don't need to store old hourly and minutely data, but we need 24-hour's minutely data // Run anyway for non-migration mode if (!this.migrationMode || date.isAfter(currentDate.subtract(this.statMinutelyKeepHour, "hour"))) { let minutelyStatBean = await this.getMinutelyStatBean(divisionKey); minutelyStatBean.up = minutelyData.up; minutelyStatBean.down = minutelyData.down; minutelyStatBean.ping = minutelyData.avgPing; minutelyStatBean.pingMin = minutelyData.minPing; minutelyStatBean.pingMax = minutelyData.maxPing; { // eslint-disable-next-line no-unused-vars const { up, down, avgPing, minPing, maxPing, timestamp, ...extras } = minutelyData; if (Object.keys(extras).length > 0) { minutelyStatBean.extras = JSON.stringify(extras); } } await R.store(minutelyStatBean); } // No need to remove old data in migration mode if (!this.migrationMode) { // Remove the old data // TODO: Improvement: Convert it to a job? log.debug("uptime-calc", "Remove old data"); await R.exec("DELETE FROM stat_minutely WHERE monitor_id = ? AND timestamp < ?", [ this.monitorID, this.getMinutelyKey(currentDate.subtract(this.statMinutelyKeepHour, "hour")), ]); await R.exec("DELETE FROM stat_hourly WHERE monitor_id = ? AND timestamp < ?", [ this.monitorID, this.getHourlyKey(currentDate.subtract(this.statHourlyKeepDay, "day")), ]); } return date; } /** * Get the daily stat bean * @param {number} timestamp milliseconds * @returns {Promise<import("redbean-node").Bean>} stat_daily bean */ async getDailyStatBean(timestamp) { if (this.lastDailyStatBean && this.lastDailyStatBean.timestamp === timestamp) { return this.lastDailyStatBean; } let bean = await R.findOne("stat_daily", " monitor_id = ? AND timestamp = ?", [ this.monitorID, timestamp, ]); if (!bean) { bean = R.dispense("stat_daily"); bean.monitor_id = this.monitorID; bean.timestamp = timestamp; } this.lastDailyStatBean = bean; return this.lastDailyStatBean; } /** * Get the hourly stat bean * @param {number} timestamp milliseconds * @returns {Promise<import("redbean-node").Bean>} stat_hourly bean */ async getHourlyStatBean(timestamp) { if (this.lastHourlyStatBean && this.lastHourlyStatBean.timestamp === timestamp) { return this.lastHourlyStatBean; } let bean = await R.findOne("stat_hourly", " monitor_id = ? AND timestamp = ?", [ this.monitorID, timestamp, ]); if (!bean) { bean = R.dispense("stat_hourly"); bean.monitor_id = this.monitorID; bean.timestamp = timestamp; } this.lastHourlyStatBean = bean; return this.lastHourlyStatBean; } /** * Get the minutely stat bean * @param {number} timestamp milliseconds * @returns {Promise<import("redbean-node").Bean>} stat_minutely bean */ async getMinutelyStatBean(timestamp) { if (this.lastMinutelyStatBean && this.lastMinutelyStatBean.timestamp === timestamp) { return this.lastMinutelyStatBean; } let bean = await R.findOne("stat_minutely", " monitor_id = ? AND timestamp = ?", [ this.monitorID, timestamp, ]); if (!bean) { bean = R.dispense("stat_minutely"); bean.monitor_id = this.monitorID; bean.timestamp = timestamp; } this.lastMinutelyStatBean = bean; return this.lastMinutelyStatBean; } /** * Convert timestamp to minutely key * @param {dayjs.Dayjs} date The heartbeat date * @returns {number} Timestamp */ getMinutelyKey(date) { // Truncate value to minutes (e.g. 2021-01-01 12:34:56 -> 2021-01-01 12:34:00) date = date.startOf("minute"); // Convert to timestamp in second let divisionKey = date.unix(); if (! (divisionKey in this.minutelyUptimeDataList)) { this.minutelyUptimeDataList.push(divisionKey, { up: 0, down: 0, avgPing: 0, minPing: 0, maxPing: 0, }); } return divisionKey; } /** * Convert timestamp to hourly key * @param {dayjs.Dayjs} date The heartbeat date * @returns {number} Timestamp */ getHourlyKey(date) { // Truncate value to hours (e.g. 2021-01-01 12:34:56 -> 2021-01-01 12:00:00) date = date.startOf("hour"); // Convert to timestamp in second let divisionKey = date.unix(); if (! (divisionKey in this.hourlyUptimeDataList)) { this.hourlyUptimeDataList.push(divisionKey, { up: 0, down: 0, avgPing: 0, minPing: 0, maxPing: 0, }); } return divisionKey; } /** * Convert timestamp to daily key * @param {dayjs.Dayjs} date The heartbeat date * @returns {number} Timestamp */ getDailyKey(date) { // Truncate value to start of day (e.g. 2021-01-01 12:34:56 -> 2021-01-01 00:00:00) // Considering if the user keep changing could affect the calculation, so use UTC time to avoid this problem. date = date.utc().startOf("day"); let dailyKey = date.unix(); if (!this.dailyUptimeDataList[dailyKey]) { this.dailyUptimeDataList.push(dailyKey, { up: 0, down: 0, avgPing: 0, minPing: 0, maxPing: 0, }); } return dailyKey; } /** * Convert timestamp to key * @param {dayjs.Dayjs} datetime Datetime * @param {"day" | "hour" | "minute"} type the type of data which is expected to be returned * @returns {number} Timestamp * @throws {Error} If the type is invalid */ getKey(datetime, type) { switch (type) { case "day": return this.getDailyKey(datetime); case "hour": return this.getHourlyKey(datetime); case "minute": return this.getMinutelyKey(datetime); default: throw new Error("Invalid type"); } } /** * Flat status to UP or DOWN * @param {number} status the status which should be turned into a flat status * @returns {UP|DOWN|PENDING} The flat status * @throws {Error} Invalid status */ flatStatus(status) { switch (status) { case UP: case MAINTENANCE: return UP; case DOWN: case PENDING: return DOWN; } throw new Error("Invalid status"); } /** * @param {number} num the number of data points which are expected to be returned * @param {"day" | "hour" | "minute"} type the type of data which is expected to be returned * @returns {UptimeDataResult} UptimeDataResult * @throws {Error} The maximum number of minutes greater than 1440 */ getData(num, type = "day") { if (type === "hour" && num > 24 * 30) { throw new Error("The maximum number of hours is 720"); } if (type === "minute" && num > 24 * 60) { throw new Error("The maximum number of minutes is 1440"); } if (type === "day" && num > 365) { throw new Error("The maximum number of days is 365"); } // Get the current time period key based on the type let key = this.getKey(this.getCurrentDate(), type); let total = { up: 0, down: 0, }; let totalPing = 0; let endTimestamp; // Get the earliest timestamp of the required period based on the type switch (type) { case "day": endTimestamp = key - 86400 * (num - 1); break; case "hour": endTimestamp = key - 3600 * (num - 1); break; case "minute": endTimestamp = key - 60 * (num - 1); break; default: throw new Error("Invalid type"); } // Sum up all data in the specified time range while (key >= endTimestamp) { let data; switch (type) { case "day": data = this.dailyUptimeDataList[key]; break; case "hour": data = this.hourlyUptimeDataList[key]; break; case "minute": data = this.minutelyUptimeDataList[key]; break; default: throw new Error("Invalid type"); } if (data) { total.up += data.up; total.down += data.down; totalPing += data.avgPing * data.up; } // Set key to the previous time period switch (type) { case "day": key -= 86400; break; case "hour": key -= 3600; break; case "minute": key -= 60; break; default: throw new Error("Invalid type"); } } let uptimeData = new UptimeDataResult(); // If there is no data in the previous time ranges, use the last data? if (total.up === 0 && total.down === 0) { switch (type) { case "day": if (this.lastDailyUptimeData) { total = this.lastDailyUptimeData; totalPing = total.avgPing * total.up; } else { return uptimeData; } break; case "hour": if (this.lastHourlyUptimeData) { total = this.lastHourlyUptimeData; totalPing = total.avgPing * total.up; } else { return uptimeData; } break; case "minute": if (this.lastUptimeData) { total = this.lastUptimeData; totalPing = total.avgPing * total.up; } else { return uptimeData; } break; default: throw new Error("Invalid type"); } } let avgPing; if (total.up === 0) { avgPing = null; } else { avgPing = totalPing / total.up; } if (total.up + total.down === 0) { uptimeData.uptime = 0; } else { uptimeData.uptime = total.up / (total.up + total.down); } uptimeData.avgPing = avgPing; return uptimeData; } /** * Get data in form of an array * @param {number} num the number of data points which are expected to be returned * @param {"day" | "hour" | "minute"} type the type of data which is expected to be returned * @returns {Array<object>} uptime data * @throws {Error} The maximum number of minutes greater than 1440 */ getDataArray(num, type = "day") { if (type === "hour" && num > 24 * 30) { throw new Error("The maximum number of hours is 720"); } if (type === "minute" && num > 24 * 60) { throw new Error("The maximum number of minutes is 1440"); } // Get the current time period key based on the type let key = this.getKey(this.getCurrentDate(), type); let result = []; let endTimestamp; // Get the earliest timestamp of the required period based on the type switch (type) { case "day": endTimestamp = key - 86400 * (num - 1); break; case "hour": endTimestamp = key - 3600 * (num - 1); break; case "minute": endTimestamp = key - 60 * (num - 1); break; default: throw new Error("Invalid type"); } // Get datapoints in the specified time range while (key >= endTimestamp) { let data; switch (type) { case "day": data = this.dailyUptimeDataList[key]; break; case "hour": data = this.hourlyUptimeDataList[key]; break; case "minute": data = this.minutelyUptimeDataList[key]; break; default: throw new Error("Invalid type"); } if (data) { data.timestamp = key; result.push(data); } // Set key to the previous time period switch (type) { case "day": key -= 86400; break; case "hour": key -= 3600; break; case "minute": key -= 60; break; default: throw new Error("Invalid type"); } } return result; } /** * Get the uptime data for given duration. * @param {string} duration A string with a number and a unit (m,h,d,w,M,y), such as 24h, 30d, 1y. * @returns {UptimeDataResult} UptimeDataResult * @throws {Error} Invalid duration / Unsupported unit */ getDataByDuration(duration) { const durationNumStr = duration.slice(0, -1); if (!/^[0-9]+$/.test(durationNumStr)) { throw new Error(`Invalid duration: ${duration}`); } const num = Number(durationNumStr); const unit = duration.slice(-1); switch (unit) { case "m": return this.getData(num, "minute"); case "h": return this.getData(num, "hour"); case "d": return this.getData(num, "day"); case "w": return this.getData(7 * num, "day"); case "M": return this.getData(30 * num, "day"); case "y": return this.getData(365 * num, "day"); default: throw new Error(`Unsupported unit (${unit}) for badge duration ${duration}` ); } } /** * 1440 = 24 * 60mins * @returns {UptimeDataResult} UptimeDataResult */ get24Hour() { return this.getData(1440, "minute"); } /** * @returns {UptimeDataResult} UptimeDataResult */ get7Day() { return this.getData(168, "hour"); } /** * @returns {UptimeDataResult} UptimeDataResult */ get30Day() { return this.getData(30); } /** * @returns {UptimeDataResult} UptimeDataResult */ get1Year() { return this.getData(365); } /** * @returns {dayjs.Dayjs} Current datetime in UTC */ getCurrentDate() { return dayjs.utc(); } /** * For migration purposes. * @param {boolean} value Migration mode on/off * @returns {void} */ setMigrationMode(value) { this.migrationMode = value; } /** * Clear all statistics and heartbeats for a monitor * @param {number} monitorID the id of the monitor * @returns {Promise<void>} */ static async clearStatistics(monitorID) { await R.exec("DELETE FROM heartbeat WHERE monitor_id = ?", [ monitorID ]); await R.exec("DELETE FROM stat_minutely WHERE monitor_id = ?", [ monitorID ]); await R.exec("DELETE FROM stat_hourly WHERE monitor_id = ?", [ monitorID ]); await R.exec("DELETE FROM stat_daily WHERE monitor_id = ?", [ monitorID ]); await UptimeCalculator.remove(monitorID); } /** * Clear all statistics and heartbeats for all monitors * @returns {Promise<void>} */ static async clearAllStatistics() { await R.exec("DELETE FROM heartbeat"); await R.exec("DELETE FROM stat_minutely"); await R.exec("DELETE FROM stat_hourly"); await R.exec("DELETE FROM stat_daily"); await UptimeCalculator.removeAll(); } } class UptimeDataResult { /** * @type {number} Uptime */ uptime = 0; /** * @type {number} Average ping */ avgPing = null; } module.exports = { UptimeCalculator, UptimeDataResult, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/embedded-mariadb.js
server/embedded-mariadb.js
const { log } = require("../src/util"); const childProcess = require("child_process"); const fs = require("fs"); const mysql = require("mysql2"); /** * It is only used inside the docker container */ class EmbeddedMariaDB { static instance = null; exec = "mariadbd"; mariadbDataDir = "/app/data/mariadb"; runDir = "/app/data/run"; socketPath = this.runDir + "/mariadb.sock"; /** * The username to connect to the MariaDB * @type {string} */ username = null; /** * @type {ChildProcessWithoutNullStreams} * @private */ childProcess = null; running = false; started = false; /** * @returns {EmbeddedMariaDB} The singleton instance */ static getInstance() { if (!EmbeddedMariaDB.instance) { EmbeddedMariaDB.instance = new EmbeddedMariaDB(); } return EmbeddedMariaDB.instance; } /** * @returns {boolean} If the singleton instance is created */ static hasInstance() { return !!EmbeddedMariaDB.instance; } /** * Start the embedded MariaDB * @throws {Error} If the current user is not "node" or "root" * @returns {Promise<void>|void} A promise that resolves when the MariaDB is started or void if it is already started */ start() { // Check if the current user is "node" or "root" this.username = require("os").userInfo().username; if (this.username !== "node" && this.username !== "root") { throw new Error("Embedded Mariadb supports only 'node' or 'root' user, but the current user is: " + this.username); } this.initDB(); this.startChildProcess(); return new Promise((resolve) => { let interval = setInterval(() => { if (this.started) { clearInterval(interval); resolve(); } else { log.info("mariadb", "Waiting for Embedded MariaDB to start..."); } }, 1000); }); } /** * Start the child process * @returns {void} */ startChildProcess() { if (this.childProcess) { log.info("mariadb", "Already started"); return; } this.running = true; log.info("mariadb", "Starting Embedded MariaDB"); this.childProcess = childProcess.spawn(this.exec, [ "--user=node", "--datadir=" + this.mariadbDataDir, `--socket=${this.socketPath}`, `--pid-file=${this.runDir}/mysqld.pid`, // Don't add the following option, the mariadb will not report message to the console, which affects initDBAfterStarted() // "--log-error=" + `${this.mariadbDataDir}/mariadb-error.log`, ]); this.childProcess.on("close", (code) => { this.running = false; this.childProcess = null; this.started = false; log.info("mariadb", "Stopped Embedded MariaDB: " + code); if (code !== 0) { log.error("mariadb", "Try to restart Embedded MariaDB as it is not stopped by user"); this.startChildProcess(); } }); this.childProcess.on("error", (err) => { if (err.code === "ENOENT") { log.error("mariadb", `Embedded MariaDB: ${this.exec} is not found`); } else { log.error("mariadb", err); } }); let handler = (data) => { log.info("mariadb", data.toString("utf-8")); if (data.toString("utf-8").includes("ready for connections")) { this.initDBAfterStarted(); } }; this.childProcess.stdout.on("data", handler); this.childProcess.stderr.on("data", handler); } /** * Stop all the child processes * @returns {void} */ stop() { if (this.childProcess) { this.childProcess.kill("SIGINT"); this.childProcess = null; } } /** * Install MariaDB if it is not installed and make sure the `runDir` directory exists * @returns {void} */ initDB() { if (!fs.existsSync(this.mariadbDataDir)) { log.info("mariadb", `Embedded MariaDB: ${this.mariadbDataDir} is not found, create one now.`); fs.mkdirSync(this.mariadbDataDir, { recursive: true, }); let result = childProcess.spawnSync("mariadb-install-db", [ "--user=node", "--auth-root-socket-user=node", "--datadir=" + this.mariadbDataDir, "--auth-root-authentication-method=socket", ]); if (result.status !== 0) { let error = result.stderr.toString("utf-8"); log.error("mariadb", error); return; } else { log.info("mariadb", "Embedded MariaDB: mysql_install_db done:" + result.stdout.toString("utf-8")); } } // Check the owner of the mariadb directory, and change it if necessary let stat = fs.statSync(this.mariadbDataDir); if (stat.uid !== 1000 || stat.gid !== 1000) { fs.chownSync(this.mariadbDataDir, 1000, 1000); } // Check the permission of the mariadb directory, and change it if it is not 755 if (stat.mode !== 0o755) { fs.chmodSync(this.mariadbDataDir, 0o755); } if (!fs.existsSync(this.runDir)) { log.info("mariadb", `Embedded MariaDB: ${this.runDir} is not found, create one now.`); fs.mkdirSync(this.runDir, { recursive: true, }); } stat = fs.statSync(this.runDir); if (stat.uid !== 1000 || stat.gid !== 1000) { fs.chownSync(this.runDir, 1000, 1000); } if (stat.mode !== 0o755) { fs.chmodSync(this.runDir, 0o755); } } /** * Initialise the "kuma" database in mariadb if it does not exist * @returns {Promise<void>} */ async initDBAfterStarted() { const connection = mysql.createConnection({ socketPath: this.socketPath, user: this.username, }); let result = await connection.execute("CREATE DATABASE IF NOT EXISTS `kuma`"); log.debug("mariadb", "CREATE DATABASE: " + JSON.stringify(result)); log.info("mariadb", "Embedded MariaDB is ready for connections"); this.started = true; } } module.exports = { EmbeddedMariaDB, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/auth.js
server/auth.js
const basicAuth = require("express-basic-auth"); const passwordHash = require("./password-hash"); const { R } = require("redbean-node"); const { setting } = require("./util-server"); const { log } = require("../src/util"); const { loginRateLimiter, apiRateLimiter } = require("./rate-limiter"); const { Settings } = require("./settings"); const dayjs = require("dayjs"); /** * Login to web app * @param {string} username Username to login with * @param {string} password Password to login with * @returns {Promise<(Bean|null)>} User or null if login failed */ exports.login = async function (username, password) { if (typeof username !== "string" || typeof password !== "string") { return null; } let user = await R.findOne("user", "TRIM(username) = ? AND active = 1 ", [ username.trim(), ]); if (user && passwordHash.verify(password, user.password)) { // Upgrade the hash to bcrypt if (passwordHash.needRehash(user.password)) { await R.exec("UPDATE `user` SET password = ? WHERE id = ? ", [ await passwordHash.generate(password), user.id, ]); } return user; } return null; }; /** * Validate a provided API key * @param {string} key API key to verify * @returns {boolean} API is ok? */ async function verifyAPIKey(key) { if (typeof key !== "string") { return false; } // uk prefix + key ID is before _ let index = key.substring(2, key.indexOf("_")); let clear = key.substring(key.indexOf("_") + 1, key.length); let hash = await R.findOne("api_key", " id=? ", [ index ]); if (hash === null) { return false; } let current = dayjs(); let expiry = dayjs(hash.expires); if (expiry.diff(current) < 0 || !hash.active) { return false; } return hash && passwordHash.verify(clear, hash.key); } /** * Callback for basic auth authorizers * @callback authCallback * @param {any} err Any error encountered * @param {boolean} authorized Is the client authorized? */ /** * Custom authorizer for express-basic-auth * @param {string} username Username to login with * @param {string} password Password to login with * @param {authCallback} callback Callback to handle login result * @returns {void} */ function apiAuthorizer(username, password, callback) { // API Rate Limit apiRateLimiter.pass(null, 0).then((pass) => { if (pass) { verifyAPIKey(password).then((valid) => { if (!valid) { log.warn("api-auth", "Failed API auth attempt: invalid API Key"); } callback(null, valid); // Only allow a set number of api requests per minute // (currently set to 60) apiRateLimiter.removeTokens(1); }); } else { log.warn("api-auth", "Failed API auth attempt: rate limit exceeded"); callback(null, false); } }); } /** * Custom authorizer for express-basic-auth * @param {string} username Username to login with * @param {string} password Password to login with * @param {authCallback} callback Callback to handle login result * @returns {void} */ function userAuthorizer(username, password, callback) { // Login Rate Limit loginRateLimiter.pass(null, 0).then((pass) => { if (pass) { exports.login(username, password).then((user) => { callback(null, user != null); if (user == null) { log.warn("basic-auth", "Failed basic auth attempt: invalid username/password"); loginRateLimiter.removeTokens(1); } }); } else { log.warn("basic-auth", "Failed basic auth attempt: rate limit exceeded"); callback(null, false); } }); } /** * Use basic auth if auth is not disabled * @param {express.Request} req Express request object * @param {express.Response} res Express response object * @param {express.NextFunction} next Next handler in chain * @returns {Promise<void>} */ exports.basicAuth = async function (req, res, next) { const middleware = basicAuth({ authorizer: userAuthorizer, authorizeAsync: true, challenge: true, }); const disabledAuth = await setting("disableAuth"); if (!disabledAuth) { middleware(req, res, next); } else { next(); } }; /** * Use use API Key if API keys enabled, else use basic auth * @param {express.Request} req Express request object * @param {express.Response} res Express response object * @param {express.NextFunction} next Next handler in chain * @returns {Promise<void>} */ exports.apiAuth = async function (req, res, next) { if (!await Settings.get("disableAuth")) { let usingAPIKeys = await Settings.get("apiKeysEnabled"); let middleware; if (usingAPIKeys) { middleware = basicAuth({ authorizer: apiAuthorizer, authorizeAsync: true, challenge: true, }); } else { middleware = basicAuth({ authorizer: userAuthorizer, authorizeAsync: true, challenge: true, }); } middleware(req, res, next); } else { next(); } };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/remote-browser.js
server/remote-browser.js
const { R } = require("redbean-node"); class RemoteBrowser { /** * Gets remote browser from ID * @param {number} remoteBrowserID ID of the remote browser * @param {number} userID ID of the user who created the remote browser * @returns {Promise<Bean>} Remote Browser */ static async get(remoteBrowserID, userID) { let bean = await R.findOne("remote_browser", " id = ? AND user_id = ? ", [ remoteBrowserID, userID ]); if (!bean) { throw new Error("Remote browser not found"); } return bean; } /** * Save a Remote Browser * @param {object} remoteBrowser Remote Browser to save * @param {?number} remoteBrowserID ID of the Remote Browser to update * @param {number} userID ID of the user who adds the Remote Browser * @returns {Promise<Bean>} Updated Remote Browser */ static async save(remoteBrowser, remoteBrowserID, userID) { let bean; if (remoteBrowserID) { bean = await R.findOne("remote_browser", " id = ? AND user_id = ? ", [ remoteBrowserID, userID ]); if (!bean) { throw new Error("Remote browser not found"); } } else { bean = R.dispense("remote_browser"); } bean.user_id = userID; bean.name = remoteBrowser.name; bean.url = remoteBrowser.url; await R.store(bean); return bean; } /** * Delete a Remote Browser * @param {number} remoteBrowserID ID of the Remote Browser to delete * @param {number} userID ID of the user who created the Remote Browser * @returns {Promise<void>} */ static async delete(remoteBrowserID, userID) { let bean = await R.findOne("remote_browser", " id = ? AND user_id = ? ", [ remoteBrowserID, userID ]); if (!bean) { throw new Error("Remote Browser not found"); } // Delete removed remote browser from monitors if exists await R.exec("UPDATE monitor SET remote_browser = null WHERE remote_browser = ?", [ remoteBrowserID ]); await R.trash(bean); } } module.exports = { RemoteBrowser, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/config.js
server/config.js
const isFreeBSD = /^freebsd/.test(process.platform); // Interop with browser const args = (typeof process !== "undefined") ? require("args-parser")(process.argv) : {}; // If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available and the unspecified IPv4 address (0.0.0.0) otherwise. // Dual-stack support for (::) // Also read HOST if not FreeBSD, as HOST is a system environment variable in FreeBSD let hostEnv = isFreeBSD ? null : process.env.HOST; const hostname = args.host || process.env.UPTIME_KUMA_HOST || hostEnv; const port = [ args.port, process.env.UPTIME_KUMA_PORT, process.env.PORT, 3001 ] .map(portValue => parseInt(portValue)) .find(portValue => !isNaN(portValue)); const sslKey = args["ssl-key"] || process.env.UPTIME_KUMA_SSL_KEY || process.env.SSL_KEY || undefined; const sslCert = args["ssl-cert"] || process.env.UPTIME_KUMA_SSL_CERT || process.env.SSL_CERT || undefined; const sslKeyPassphrase = args["ssl-key-passphrase"] || process.env.UPTIME_KUMA_SSL_KEY_PASSPHRASE || process.env.SSL_KEY_PASSPHRASE || undefined; const isSSL = sslKey && sslCert; /** * Get the local WebSocket URL * @returns {string} The local WebSocket URL */ function getLocalWebSocketURL() { const protocol = isSSL ? "wss" : "ws"; const host = hostname || "localhost"; return `${protocol}://${host}:${port}`; } const localWebSocketURL = getLocalWebSocketURL(); const demoMode = args["demo"] || false; module.exports = { args, hostname, port, sslKey, sslCert, sslKeyPassphrase, isSSL, localWebSocketURL, demoMode, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/rate-limiter.js
server/rate-limiter.js
const { RateLimiter } = require("limiter"); const { log } = require("../src/util"); class KumaRateLimiter { /** * @param {object} config Rate limiter configuration object */ constructor(config) { this.errorMessage = config.errorMessage; this.rateLimiter = new RateLimiter(config); } /** * Callback for pass * @callback passCB * @param {object} err Too many requests */ /** * Should the request be passed through * @param {passCB} callback Callback function to call with decision * @param {number} num Number of tokens to remove * @returns {Promise<boolean>} Should the request be allowed? */ async pass(callback, num = 1) { const remainingRequests = await this.removeTokens(num); log.info("rate-limit", "remaining requests: " + remainingRequests); if (remainingRequests < 0) { if (callback) { callback({ ok: false, msg: this.errorMessage, }); } return false; } return true; } /** * Remove a given number of tokens * @param {number} num Number of tokens to remove * @returns {Promise<number>} Number of remaining tokens */ async removeTokens(num = 1) { return await this.rateLimiter.removeTokens(num); } } const loginRateLimiter = new KumaRateLimiter({ tokensPerInterval: 20, interval: "minute", fireImmediately: true, errorMessage: "Too frequently, try again later." }); const apiRateLimiter = new KumaRateLimiter({ tokensPerInterval: 60, interval: "minute", fireImmediately: true, errorMessage: "Too frequently, try again later." }); const twoFaRateLimiter = new KumaRateLimiter({ tokensPerInterval: 30, interval: "minute", fireImmediately: true, errorMessage: "Too frequently, try again later." }); module.exports = { loginRateLimiter, apiRateLimiter, twoFaRateLimiter, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/check-version.js
server/check-version.js
const { setSetting, setting } = require("./util-server"); const axios = require("axios"); const compareVersions = require("compare-versions"); const { log } = require("../src/util"); exports.version = require("../package.json").version; exports.latestVersion = null; // How much time in ms to wait between update checks const UPDATE_CHECKER_INTERVAL_MS = 1000 * 60 * 60 * 48; const UPDATE_CHECKER_LATEST_VERSION_URL = "https://uptime.kuma.pet/version"; let interval; exports.startInterval = () => { let check = async () => { if (await setting("checkUpdate") === false) { return; } log.debug("update-checker", "Retrieving latest versions"); try { const res = await axios.get(UPDATE_CHECKER_LATEST_VERSION_URL); // For debug if (process.env.TEST_CHECK_VERSION === "1") { res.data.slow = "1000.0.0"; } let checkBeta = await setting("checkBeta"); if (checkBeta && res.data.beta) { if (compareVersions.compare(res.data.beta, res.data.slow, ">")) { exports.latestVersion = res.data.beta; return; } } if (res.data.slow) { exports.latestVersion = res.data.slow; } } catch (_) { log.info("update-checker", "Failed to check for new versions"); } }; check(); interval = setInterval(check, UPDATE_CHECKER_INTERVAL_MS); }; /** * Enable the check update feature * @param {boolean} value Should the check update feature be enabled? * @returns {Promise<void>} */ exports.enableCheckUpdate = async (value) => { await setSetting("checkUpdate", value); clearInterval(interval); if (value) { exports.startInterval(); } }; exports.socket = null;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/uptime-kuma-server.js
server/uptime-kuma-server.js
const express = require("express"); const https = require("https"); const fs = require("fs"); const http = require("http"); const { Server } = require("socket.io"); const { R } = require("redbean-node"); const { log, isDev } = require("../src/util"); const Database = require("./database"); const util = require("util"); const { Settings } = require("./settings"); const dayjs = require("dayjs"); const childProcessAsync = require("promisify-child-process"); const path = require("path"); const axios = require("axios"); const { isSSL, sslKey, sslCert, sslKeyPassphrase } = require("./config"); // DO NOT IMPORT HERE IF THE MODULES USED `UptimeKumaServer.getInstance()`, put at the bottom of this file instead. /** * `module.exports` (alias: `server`) should be inside this class, in order to avoid circular dependency issue. * @type {UptimeKumaServer} */ class UptimeKumaServer { /** * Current server instance * @type {UptimeKumaServer} */ static instance = null; /** * Main monitor list * @type {{}} */ monitorList = {}; /** * Main maintenance list * @type {{}} */ maintenanceList = {}; entryPage = "dashboard"; app = undefined; httpServer = undefined; io = undefined; /** * Cache Index HTML * @type {string} */ indexHTML = ""; /** * @type {{}} */ static monitorTypeList = { }; /** * Use for decode the auth object * @type {null} */ jwtSecret = null; /** * Get the current instance of the server if it exists, otherwise * create a new instance. * @returns {UptimeKumaServer} Server instance */ static getInstance() { if (UptimeKumaServer.instance == null) { UptimeKumaServer.instance = new UptimeKumaServer(); } return UptimeKumaServer.instance; } /** * */ constructor() { // Set axios default user-agent to Uptime-Kuma/version axios.defaults.headers.common["User-Agent"] = this.getUserAgent(); // Set default axios timeout to 5 minutes instead of infinity axios.defaults.timeout = 300 * 1000; log.info("server", "Creating express and socket.io instance"); this.app = express(); if (isSSL) { log.info("server", "Server Type: HTTPS"); this.httpServer = https.createServer({ key: fs.readFileSync(sslKey), cert: fs.readFileSync(sslCert), passphrase: sslKeyPassphrase, }, this.app); } else { log.info("server", "Server Type: HTTP"); this.httpServer = http.createServer(this.app); } try { this.indexHTML = fs.readFileSync("./dist/index.html").toString(); } catch (e) { // "dist/index.html" is not necessary for development if (process.env.NODE_ENV !== "development") { log.error("server", "Error: Cannot find 'dist/index.html', did you install correctly?"); process.exit(1); } } // Set Monitor Types UptimeKumaServer.monitorTypeList["real-browser"] = new RealBrowserMonitorType(); UptimeKumaServer.monitorTypeList["tailscale-ping"] = new TailscalePing(); UptimeKumaServer.monitorTypeList["websocket-upgrade"] = new WebSocketMonitorType(); UptimeKumaServer.monitorTypeList["dns"] = new DnsMonitorType(); UptimeKumaServer.monitorTypeList["postgres"] = new PostgresMonitorType(); UptimeKumaServer.monitorTypeList["mqtt"] = new MqttMonitorType(); UptimeKumaServer.monitorTypeList["smtp"] = new SMTPMonitorType(); UptimeKumaServer.monitorTypeList["group"] = new GroupMonitorType(); UptimeKumaServer.monitorTypeList["snmp"] = new SNMPMonitorType(); UptimeKumaServer.monitorTypeList["grpc-keyword"] = new GrpcKeywordMonitorType(); UptimeKumaServer.monitorTypeList["mongodb"] = new MongodbMonitorType(); UptimeKumaServer.monitorTypeList["rabbitmq"] = new RabbitMqMonitorType(); UptimeKumaServer.monitorTypeList["gamedig"] = new GameDigMonitorType(); UptimeKumaServer.monitorTypeList["port"] = new TCPMonitorType(); UptimeKumaServer.monitorTypeList["manual"] = new ManualMonitorType(); UptimeKumaServer.monitorTypeList["redis"] = new RedisMonitorType(); UptimeKumaServer.monitorTypeList["system-service"] = new SystemServiceMonitorType(); UptimeKumaServer.monitorTypeList["sqlserver"] = new MssqlMonitorType(); // Allow all CORS origins (polling) in development let cors = undefined; if (isDev) { cors = { origin: "*", }; } this.io = new Server(this.httpServer, { cors, allowRequest: async (req, callback) => { let transport; // It should be always true, but just in case, because this property is not documented if (req._query) { transport = req._query.transport; } else { log.error("socket", "Ops!!! Cannot get transport type, assume that it is polling"); transport = "polling"; } const clientIP = await this.getClientIPwithProxy(req.connection.remoteAddress, req.headers); log.info("socket", `New ${transport} connection, IP = ${clientIP}`); // The following check is only for websocket connections, polling connections are already protected by CORS if (transport === "polling") { callback(null, true); } else if (transport === "websocket") { const bypass = process.env.UPTIME_KUMA_WS_ORIGIN_CHECK === "bypass"; if (bypass) { log.info("auth", "WebSocket origin check is bypassed"); callback(null, true); } else if (!req.headers.origin) { log.info("auth", "WebSocket with no origin is allowed"); callback(null, true); } else { let host = req.headers.host; let origin = req.headers.origin; try { let originURL = new URL(origin); let xForwardedFor; if (await Settings.get("trustProxy")) { xForwardedFor = req.headers["x-forwarded-for"]; } if (host !== originURL.host && xForwardedFor !== originURL.host) { callback(null, false); log.error("auth", `Origin (${origin}) does not match host (${host}), IP: ${clientIP}`); } else { callback(null, true); } } catch (e) { // Invalid origin url, probably not from browser callback(null, false); log.error("auth", `Invalid origin url (${origin}), IP: ${clientIP}`); } } } } }); } /** * Initialise app after the database has been set up * @returns {Promise<void>} */ async initAfterDatabaseReady() { // Static this.app.use("/screenshots", express.static(Database.screenshotDir)); process.env.TZ = await this.getTimezone(); dayjs.tz.setDefault(process.env.TZ); log.debug("DEBUG", "Timezone: " + process.env.TZ); log.debug("DEBUG", "Current Time: " + dayjs.tz().format()); await this.loadMaintenanceList(); } /** * Send list of monitors to client * @param {Socket} socket Socket to send list on * @returns {Promise<object>} List of monitors */ async sendMonitorList(socket) { let list = await this.getMonitorJSONList(socket.userID); this.io.to(socket.userID).emit("monitorList", list); return list; } /** * Update Monitor into list * @param {Socket} socket Socket to send list on * @param {number} monitorID update or deleted monitor id * @returns {Promise<void>} */ async sendUpdateMonitorIntoList(socket, monitorID) { let list = await this.getMonitorJSONList(socket.userID, monitorID); if (list && list[monitorID]) { this.io.to(socket.userID).emit("updateMonitorIntoList", list); } } /** * Delete Monitor from list * @param {Socket} socket Socket to send list on * @param {number} monitorID update or deleted monitor id * @returns {Promise<void>} */ async sendDeleteMonitorFromList(socket, monitorID) { this.io.to(socket.userID).emit("deleteMonitorFromList", monitorID); } /** * Get a list of monitors for the given user. * @param {string} userID - The ID of the user to get monitors for. * @param {number} monitorID - The ID of monitor for. * @returns {Promise<object>} A promise that resolves to an object with monitor IDs as keys and monitor objects as values. * * Generated by Trelent */ async getMonitorJSONList(userID, monitorID = null) { let query = " user_id = ? "; let queryParams = [ userID ]; if (monitorID) { query += "AND id = ? "; queryParams.push(monitorID); } let monitorList = await R.find("monitor", query + "ORDER BY weight DESC, name", queryParams); const monitorData = monitorList.map(monitor => ({ id: monitor.id, active: monitor.active, name: monitor.name, })); const preloadData = await Monitor.preparePreloadData(monitorData); const result = {}; monitorList.forEach(monitor => result[monitor.id] = monitor.toJSON(preloadData)); return result; } /** * Send maintenance list to client * @param {Socket} socket Socket.io instance to send to * @returns {Promise<object>} Maintenance list */ async sendMaintenanceList(socket) { return await this.sendMaintenanceListByUserID(socket.userID); } /** * Send list of maintenances to user * @param {number} userID User to send list to * @returns {Promise<object>} Maintenance list */ async sendMaintenanceListByUserID(userID) { let list = await this.getMaintenanceJSONList(userID); this.io.to(userID).emit("maintenanceList", list); return list; } /** * Get a list of maintenances for the given user. * @param {string} userID - The ID of the user to get maintenances for. * @returns {Promise<object>} A promise that resolves to an object with maintenance IDs as keys and maintenances objects as values. */ async getMaintenanceJSONList(userID) { let result = {}; for (let maintenanceID in this.maintenanceList) { result[maintenanceID] = await this.maintenanceList[maintenanceID].toJSON(); } return result; } /** * Load maintenance list and run * @param {any} userID Unused * @returns {Promise<void>} */ async loadMaintenanceList(userID) { let maintenanceList = await R.findAll("maintenance", " ORDER BY end_date DESC, title", [ ]); for (let maintenance of maintenanceList) { this.maintenanceList[maintenance.id] = maintenance; maintenance.run(this); } } /** * Retrieve a specific maintenance * @param {number} maintenanceID ID of maintenance to retrieve * @returns {(object|null)} Maintenance if it exists */ getMaintenance(maintenanceID) { if (this.maintenanceList[maintenanceID]) { return this.maintenanceList[maintenanceID]; } return null; } /** * Write error to log file * @param {any} error The error to write * @param {boolean} outputToConsole Should the error also be output to console? * @returns {void} */ static errorLog(error, outputToConsole = true) { const errorLogStream = fs.createWriteStream(path.join(Database.dataDir, "/error.log"), { flags: "a" }); errorLogStream.on("error", () => { log.info("", "Cannot write to error.log"); }); if (errorLogStream) { const dateTime = R.isoDateTime(); errorLogStream.write(`[${dateTime}] ` + util.format(error) + "\n"); if (outputToConsole) { console.error(error); } } errorLogStream.end(); } /** * Get the IP of the client connected to the socket * @param {Socket} socket Socket to query * @returns {Promise<string>} IP of client */ getClientIP(socket) { return this.getClientIPwithProxy(socket.client.conn.remoteAddress, socket.client.conn.request.headers); } /** * @param {string} clientIP Raw client IP * @param {IncomingHttpHeaders} headers HTTP headers * @returns {Promise<string>} Client IP with proxy (if trusted) */ async getClientIPwithProxy(clientIP, headers) { if (clientIP === undefined) { clientIP = ""; } if (await Settings.get("trustProxy")) { const forwardedFor = headers["x-forwarded-for"]; return (typeof forwardedFor === "string" ? forwardedFor.split(",")[0].trim() : null) || headers["x-real-ip"] || clientIP.replace(/^::ffff:/, ""); } else { return clientIP.replace(/^::ffff:/, ""); } } /** * Attempt to get the current server timezone * If this fails, fall back to environment variables and then make a * guess. * @returns {Promise<string>} Current timezone */ async getTimezone() { // From process.env.TZ try { if (process.env.TZ) { this.checkTimezone(process.env.TZ); return process.env.TZ; } } catch (e) { log.warn("timezone", e.message + " in process.env.TZ"); } let timezone = await Settings.get("serverTimezone"); // From Settings try { log.debug("timezone", "Using timezone from settings: " + timezone); if (timezone) { this.checkTimezone(timezone); return timezone; } } catch (e) { log.warn("timezone", e.message + " in settings"); } // Guess try { let guess = dayjs.tz.guess(); log.debug("timezone", "Guessing timezone: " + guess); if (guess) { this.checkTimezone(guess); return guess; } else { return "UTC"; } } catch (e) { // Guess failed, fall back to UTC log.debug("timezone", "Guessed an invalid timezone. Use UTC as fallback"); return "UTC"; } } /** * Get the current offset * @returns {string} Time offset */ getTimezoneOffset() { return dayjs().format("Z"); } /** * Throw an error if the timezone is invalid * @param {string} timezone Timezone to test * @returns {void} * @throws The timezone is invalid */ checkTimezone(timezone) { try { dayjs.utc("2013-11-18 11:55").tz(timezone).format(); } catch (e) { throw new Error("Invalid timezone:" + timezone); } } /** * Set the current server timezone and environment variables * @param {string} timezone Timezone to set * @returns {Promise<void>} */ async setTimezone(timezone) { this.checkTimezone(timezone); await Settings.set("serverTimezone", timezone, "general"); process.env.TZ = timezone; dayjs.tz.setDefault(timezone); } /** * TODO: Listen logic should be moved to here * @returns {Promise<void>} */ async start() { let enable = await Settings.get("nscd"); if (enable || enable === null) { await this.startNSCDServices(); } } /** * Stop the server * @returns {Promise<void>} */ async stop() { let enable = await Settings.get("nscd"); if (enable || enable === null) { await this.stopNSCDServices(); } } /** * Start all system services (e.g. nscd) * For now, only used in Docker * @returns {void} */ async startNSCDServices() { if (process.env.UPTIME_KUMA_IS_CONTAINER) { try { log.info("services", "Starting nscd"); await childProcessAsync.exec("sudo service nscd start"); } catch (e) { log.info("services", "Failed to start nscd"); } } } /** * Stop all system services * @returns {void} */ async stopNSCDServices() { if (process.env.UPTIME_KUMA_IS_CONTAINER) { try { log.info("services", "Stopping nscd"); await childProcessAsync.exec("sudo service nscd stop"); } catch (e) { log.info("services", "Failed to stop nscd"); } } } /** * Default User-Agent when making HTTP requests * @returns {string} User-Agent */ getUserAgent() { return "Uptime-Kuma/" + require("../package.json").version; } /** * Force connected sockets of a user to refresh and disconnect. * Used for resetting password. * @param {string} userID User ID * @param {string?} currentSocketID Current socket ID * @returns {void} */ disconnectAllSocketClients(userID, currentSocketID = undefined) { for (const socket of this.io.sockets.sockets.values()) { if (socket.userID === userID && socket.id !== currentSocketID) { try { socket.emit("refresh"); socket.disconnect(); } catch (e) { } } } } } module.exports = { UptimeKumaServer }; // Must be at the end to avoid circular dependencies const { RealBrowserMonitorType } = require("./monitor-types/real-browser-monitor-type"); const { TailscalePing } = require("./monitor-types/tailscale-ping"); const { WebSocketMonitorType } = require("./monitor-types/websocket-upgrade"); const { DnsMonitorType } = require("./monitor-types/dns"); const { PostgresMonitorType } = require("./monitor-types/postgres"); const { MqttMonitorType } = require("./monitor-types/mqtt"); const { SMTPMonitorType } = require("./monitor-types/smtp"); const { GroupMonitorType } = require("./monitor-types/group"); const { SNMPMonitorType } = require("./monitor-types/snmp"); const { GrpcKeywordMonitorType } = require("./monitor-types/grpc"); const { MongodbMonitorType } = require("./monitor-types/mongodb"); const { RabbitMqMonitorType } = require("./monitor-types/rabbitmq"); const { GameDigMonitorType } = require("./monitor-types/gamedig"); const { TCPMonitorType } = require("./monitor-types/tcp.js"); const { ManualMonitorType } = require("./monitor-types/manual"); const { RedisMonitorType } = require("./monitor-types/redis"); const { SystemServiceMonitorType } = require("./monitor-types/system-service"); const { MssqlMonitorType } = require("./monitor-types/mssql"); const Monitor = require("./model/monitor");
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/setup-database.js
server/setup-database.js
const express = require("express"); const { log } = require("../src/util"); const expressStaticGzip = require("express-static-gzip"); const fs = require("fs"); const path = require("path"); const Database = require("./database"); const { allowDevAllOrigin } = require("./util-server"); const mysql = require("mysql2/promise"); /** * A standalone express app that is used to setup a database * It is used when db-config.json and kuma.db are not found or invalid * Once it is configured, it will shut down and start the main server */ class SetupDatabase { /** * Show Setup Page * @type {boolean} */ needSetup = true; /** * If the server has finished the setup * @type {boolean} * @private */ runningSetup = false; /** * @inheritDoc * @type {UptimeKumaServer} * @private */ server; /** * @param {object} args The arguments passed from the command line * @param {UptimeKumaServer} server the main server instance */ constructor(args, server) { this.server = server; // Priority: env > db-config.json // If env is provided, write it to db-config.json // If db-config.json is found, check if it is valid // If db-config.json is not found or invalid, check if kuma.db is found // If kuma.db is not found, show setup page let dbConfig; try { dbConfig = Database.readDBConfig(); log.debug("setup-database", "db-config.json is found and is valid"); this.needSetup = false; } catch (e) { log.info("setup-database", "db-config.json is not found or invalid: " + e.message); // Check if kuma.db is found (1.X.X users), generate db-config.json if (fs.existsSync(path.join(Database.dataDir, "kuma.db"))) { this.needSetup = false; log.info("setup-database", "kuma.db is found, generate db-config.json"); Database.writeDBConfig({ type: "sqlite", }); } else { this.needSetup = true; } dbConfig = {}; } if (process.env.UPTIME_KUMA_DB_TYPE) { this.needSetup = false; log.info("setup-database", "UPTIME_KUMA_DB_TYPE is provided by env, try to override db-config.json"); dbConfig.type = process.env.UPTIME_KUMA_DB_TYPE; dbConfig.hostname = process.env.UPTIME_KUMA_DB_HOSTNAME; dbConfig.port = process.env.UPTIME_KUMA_DB_PORT; dbConfig.dbName = process.env.UPTIME_KUMA_DB_NAME; dbConfig.username = process.env.UPTIME_KUMA_DB_USERNAME; dbConfig.password = process.env.UPTIME_KUMA_DB_PASSWORD; Database.writeDBConfig(dbConfig); } } /** * Show Setup Page * @returns {boolean} true if the setup page should be shown */ isNeedSetup() { return this.needSetup; } /** * Check if the embedded MariaDB is enabled * @returns {boolean} true if the embedded MariaDB is enabled */ isEnabledEmbeddedMariaDB() { return process.env.UPTIME_KUMA_ENABLE_EMBEDDED_MARIADB === "1"; } /** * Start the setup-database server * @param {string} hostname where the server is listening * @param {number} port where the server is listening * @returns {Promise<void>} */ start(hostname, port) { return new Promise((resolve) => { const app = express(); let tempServer; app.use(express.json()); // Disable Keep Alive, otherwise the server will not shutdown, as the client will keep the connection alive app.use(function (req, res, next) { res.setHeader("Connection", "close"); next(); }); app.get("/", async (request, response) => { response.redirect("/setup-database"); }); app.get("/api/entry-page", async (request, response) => { allowDevAllOrigin(response); response.json({ type: "setup-database", }); }); app.get("/setup-database-info", (request, response) => { allowDevAllOrigin(response); console.log("Request /setup-database-info"); response.json({ runningSetup: this.runningSetup, needSetup: this.needSetup, isEnabledEmbeddedMariaDB: this.isEnabledEmbeddedMariaDB(), }); }); app.post("/setup-database", async (request, response) => { allowDevAllOrigin(response); if (this.runningSetup) { response.status(400).json("Setup is already running"); return; } this.runningSetup = true; let dbConfig = request.body.dbConfig; let supportedDBTypes = [ "mariadb", "sqlite" ]; if (this.isEnabledEmbeddedMariaDB()) { supportedDBTypes.push("embedded-mariadb"); } // Validate input if (typeof dbConfig !== "object") { response.status(400).json("Invalid dbConfig"); this.runningSetup = false; return; } if (!dbConfig.type) { response.status(400).json("Database Type is required"); this.runningSetup = false; return; } if (!supportedDBTypes.includes(dbConfig.type)) { response.status(400).json("Unsupported Database Type"); this.runningSetup = false; return; } // External MariaDB if (dbConfig.type === "mariadb") { if (!dbConfig.hostname) { response.status(400).json("Hostname is required"); this.runningSetup = false; return; } if (!dbConfig.port) { response.status(400).json("Port is required"); this.runningSetup = false; return; } if (!dbConfig.dbName) { response.status(400).json("Database name is required"); this.runningSetup = false; return; } if (!dbConfig.username) { response.status(400).json("Username is required"); this.runningSetup = false; return; } if (!dbConfig.password) { response.status(400).json("Password is required"); this.runningSetup = false; return; } // Test connection try { log.info("setup-database", "Testing database connection..."); const connection = await mysql.createConnection({ host: dbConfig.hostname, port: dbConfig.port, user: dbConfig.username, password: dbConfig.password, database: dbConfig.dbName, }); await connection.execute("SELECT 1"); connection.end(); } catch (e) { response.status(400).json("Cannot connect to the database: " + e.message); this.runningSetup = false; return; } } // Write db-config.json Database.writeDBConfig(dbConfig); response.json({ ok: true, }); // Shutdown down this express and start the main server log.info("setup-database", "Database is configured, close the setup-database server and start the main server now."); if (tempServer) { tempServer.close(() => { log.info("setup-database", "The setup-database server is closed"); resolve(); }); } else { resolve(); } }); app.use("/", expressStaticGzip("dist", { enableBrotli: true, })); app.get("*", async (_request, response) => { response.send(this.server.indexHTML); }); app.options("*", async (_request, response) => { allowDevAllOrigin(response); response.end(); }); tempServer = app.listen(port, hostname, () => { log.info("setup-database", `Starting Setup Database on ${port}`); let domain = (hostname) ? hostname : "localhost"; log.info("setup-database", `Open http://${domain}:${port} in your browser`); log.info("setup-database", "Waiting for user action..."); }); }); } } module.exports = { SetupDatabase, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/image-data-uri.js
server/image-data-uri.js
/* From https://github.com/DiegoZoracKy/image-data-uri/blob/master/lib/image-data-uri.js Modified with 0 dependencies */ let fs = require("fs"); const { log } = require("../src/util"); let ImageDataURI = (() => { /** * Decode the data:image/ URI * @param {string} dataURI data:image/ URI to decode * @returns {?object} An object with properties "imageType" and "dataBase64". * The former is the image type, e.g., "png", and the latter is a base64 * encoded string of the image's binary data. If it fails to parse, returns * null instead of an object. */ function decode(dataURI) { if (!/data:image\//.test(dataURI)) { log.error("image-data-uri", "It seems that it is not an Image Data URI. Couldn't match \"data:image/\""); return null; } let regExMatches = dataURI.match("data:(image/.*);base64,(.*)"); return { imageType: regExMatches[1], dataBase64: regExMatches[2], dataBuffer: new Buffer(regExMatches[2], "base64") }; } /** * Endcode an image into data:image/ URI * @param {(Buffer|string)} data Data to encode * @param {string} mediaType Media type of data * @returns {(string|null)} A string representing the base64-encoded * version of the given Buffer object or null if an error occurred. */ function encode(data, mediaType) { if (!data || !mediaType) { log.error("image-data-uri", "Missing some of the required params: data, mediaType"); return null; } mediaType = (/\//.test(mediaType)) ? mediaType : "image/" + mediaType; let dataBase64 = (Buffer.isBuffer(data)) ? data.toString("base64") : new Buffer(data).toString("base64"); let dataImgBase64 = "data:" + mediaType + ";base64," + dataBase64; return dataImgBase64; } /** * Write data URI to file * @param {string} dataURI data:image/ URI * @param {string} filePath Path to write file to * @returns {Promise<string|void>} Write file error */ function outputFile(dataURI, filePath) { filePath = filePath || "./"; return new Promise((resolve, reject) => { let imageDecoded = decode(dataURI); fs.writeFile(filePath, imageDecoded.dataBuffer, err => { if (err) { return reject("ImageDataURI :: Error :: " + JSON.stringify(err, null, 4)); } resolve(filePath); }); }); } return { decode: decode, encode: encode, outputFile: outputFile, }; })(); module.exports = ImageDataURI;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/prometheus.js
server/prometheus.js
const PrometheusClient = require("prom-client"); const { log } = require("../src/util"); const { R } = require("redbean-node"); let monitorCertDaysRemaining = null; let monitorCertIsValid = null; let monitorResponseTime = null; let monitorStatus = null; class Prometheus { monitorLabelValues = {}; /** * @param {object} monitor Monitor object to monitor * @param {Array<{name:string,value:?string}>} tags Tags to add to the monitor */ constructor(monitor, tags) { this.monitorLabelValues = { ...this.mapTagsToLabels(tags), monitor_id: monitor.id, monitor_name: monitor.name, monitor_type: monitor.type, monitor_url: monitor.url, monitor_hostname: monitor.hostname, monitor_port: monitor.port }; } /** * Initialize Prometheus metrics, and add all available tags as possible labels. * This should be called once at the start of the application. * New tags will NOT be added dynamically, a restart is sadly required to add new tags to the metrics. * Existing tags added to monitors will be updated automatically. * @returns {Promise<void>} */ static async init() { // Add all available tags as possible labels, // and use Set to remove possible duplicates (for when multiple tags contain non-ascii characters, and thus are sanitized to the same label) const tags = new Set((await R.findAll("tag")).map((tag) => { return Prometheus.sanitizeForPrometheus(tag.name); }).filter((tagName) => { return tagName !== ""; }).sort(this.sortTags)); const commonLabels = [ ...tags, "monitor_id", "monitor_name", "monitor_type", "monitor_url", "monitor_hostname", "monitor_port", ]; monitorCertDaysRemaining = new PrometheusClient.Gauge({ name: "monitor_cert_days_remaining", help: "The number of days remaining until the certificate expires", labelNames: commonLabels }); monitorCertIsValid = new PrometheusClient.Gauge({ name: "monitor_cert_is_valid", help: "Is the certificate still valid? (1 = Yes, 0= No)", labelNames: commonLabels }); monitorResponseTime = new PrometheusClient.Gauge({ name: "monitor_response_time", help: "Monitor Response Time (ms)", labelNames: commonLabels }); monitorStatus = new PrometheusClient.Gauge({ name: "monitor_status", help: "Monitor Status (1 = UP, 0= DOWN, 2= PENDING, 3= MAINTENANCE)", labelNames: commonLabels }); } /** * Sanitize a string to ensure it can be used as a Prometheus label or value. * See https://github.com/louislam/uptime-kuma/pull/4704#issuecomment-2366524692 * @param {string} text The text to sanitize * @returns {string} The sanitized text */ static sanitizeForPrometheus(text) { text = text.replace(/[^a-zA-Z0-9_]/g, ""); text = text.replace(/^[^a-zA-Z_]+/, ""); return text; } /** * Map the tags value to valid labels used in Prometheus. Sanitize them in the process. * @param {Array<{name: string, value:?string}>} tags The tags to map * @returns {object} The mapped tags, usable as labels */ mapTagsToLabels(tags) { let mappedTags = {}; tags.forEach((tag) => { let sanitizedTag = Prometheus.sanitizeForPrometheus(tag.name); if (sanitizedTag === "") { return; // Skip empty tag names } if (mappedTags[sanitizedTag] === undefined) { mappedTags[sanitizedTag] = []; } let tagValue = Prometheus.sanitizeForPrometheus(tag.value || ""); if (tagValue !== "") { mappedTags[sanitizedTag].push(tagValue); } mappedTags[sanitizedTag] = mappedTags[sanitizedTag].sort(); }); // Order the tags alphabetically return Object.keys(mappedTags).sort(this.sortTags).reduce((obj, key) => { obj[key] = mappedTags[key]; return obj; }, {}); } /** * Update the metrics page * @param {object} heartbeat Heartbeat details * @param {object} tlsInfo TLS details * @returns {void} */ update(heartbeat, tlsInfo) { if (typeof tlsInfo !== "undefined") { try { let isValid; if (tlsInfo.valid === true) { isValid = 1; } else { isValid = 0; } monitorCertIsValid.set(this.monitorLabelValues, isValid); } catch (e) { log.error("prometheus", "Caught error"); log.error("prometheus", e); } try { if (tlsInfo.certInfo != null) { monitorCertDaysRemaining.set(this.monitorLabelValues, tlsInfo.certInfo.daysRemaining); } } catch (e) { log.error("prometheus", "Caught error"); log.error("prometheus", e); } } if (heartbeat) { try { monitorStatus.set(this.monitorLabelValues, heartbeat.status); } catch (e) { log.error("prometheus", "Caught error"); log.error("prometheus", e); } try { if (typeof heartbeat.ping === "number") { monitorResponseTime.set(this.monitorLabelValues, heartbeat.ping); } else { // Is it good? monitorResponseTime.set(this.monitorLabelValues, -1); } } catch (e) { log.error("prometheus", "Caught error"); log.error("prometheus", e); } } } /** * Remove monitor from prometheus * @returns {void} */ remove() { try { monitorCertDaysRemaining.remove(this.monitorLabelValues); monitorCertIsValid.remove(this.monitorLabelValues); monitorResponseTime.remove(this.monitorLabelValues); monitorStatus.remove(this.monitorLabelValues); } catch (e) { console.error(e); } } /** * Sort the tags alphabetically, case-insensitive. * @param {string} a The first tag to compare * @param {string} b The second tag to compare * @returns {number} The alphabetical order number */ sortTags(a, b) { const aLowerCase = a.toLowerCase(); const bLowerCase = b.toLowerCase(); if (aLowerCase < bLowerCase) { return -1; } if (aLowerCase > bLowerCase) { return 1; } return 0; } } module.exports = { Prometheus };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/client.js
server/client.js
/* * For Client Socket */ const { TimeLogger } = require("../src/util"); const { R } = require("redbean-node"); const { UptimeKumaServer } = require("./uptime-kuma-server"); const server = UptimeKumaServer.getInstance(); const io = server.io; const { setting } = require("./util-server"); const checkVersion = require("./check-version"); const Database = require("./database"); /** * Send list of notification providers to client * @param {Socket} socket Socket.io socket instance * @returns {Promise<Bean[]>} List of notifications */ async function sendNotificationList(socket) { const timeLogger = new TimeLogger(); let result = []; let list = await R.find("notification", " user_id = ? ", [ socket.userID, ]); for (let bean of list) { let notificationObject = bean.export(); notificationObject.isDefault = (notificationObject.isDefault === 1); notificationObject.active = (notificationObject.active === 1); result.push(notificationObject); } io.to(socket.userID).emit("notificationList", result); timeLogger.print("Send Notification List"); return list; } /** * Send Heartbeat History list to socket * @param {Socket} socket Socket.io instance * @param {number} monitorID ID of monitor to send heartbeat history * @param {boolean} toUser True = send to all browsers with the same user id, False = send to the current browser only * @param {boolean} overwrite Overwrite client-side's heartbeat list * @returns {Promise<void>} */ async function sendHeartbeatList(socket, monitorID, toUser = false, overwrite = false) { let list = await R.getAll(` SELECT * FROM heartbeat WHERE monitor_id = ? ORDER BY time DESC LIMIT 100 `, [ monitorID, ]); let result = list.reverse(); if (toUser) { io.to(socket.userID).emit("heartbeatList", monitorID, result, overwrite); } else { socket.emit("heartbeatList", monitorID, result, overwrite); } } /** * Important Heart beat list (aka event list) * @param {Socket} socket Socket.io instance * @param {number} monitorID ID of monitor to send heartbeat history * @param {boolean} toUser True = send to all browsers with the same user id, False = send to the current browser only * @param {boolean} overwrite Overwrite client-side's heartbeat list * @returns {Promise<void>} */ async function sendImportantHeartbeatList(socket, monitorID, toUser = false, overwrite = false) { const timeLogger = new TimeLogger(); let list = await R.find("heartbeat", ` monitor_id = ? AND important = 1 ORDER BY time DESC LIMIT 500 `, [ monitorID, ]); timeLogger.print(`[Monitor: ${monitorID}] sendImportantHeartbeatList`); if (toUser) { io.to(socket.userID).emit("importantHeartbeatList", monitorID, list, overwrite); } else { socket.emit("importantHeartbeatList", monitorID, list, overwrite); } } /** * Emit proxy list to client * @param {Socket} socket Socket.io socket instance * @returns {Promise<Bean[]>} List of proxies */ async function sendProxyList(socket) { const timeLogger = new TimeLogger(); const list = await R.find("proxy", " user_id = ? ", [ socket.userID ]); io.to(socket.userID).emit("proxyList", list.map(bean => bean.export())); timeLogger.print("Send Proxy List"); return list; } /** * Emit API key list to client * @param {Socket} socket Socket.io socket instance * @returns {Promise<void>} */ async function sendAPIKeyList(socket) { const timeLogger = new TimeLogger(); let result = []; const list = await R.find( "api_key", "user_id=?", [ socket.userID ], ); for (let bean of list) { result.push(bean.toPublicJSON()); } io.to(socket.userID).emit("apiKeyList", result); timeLogger.print("Sent API Key List"); return list; } /** * Emits the version information to the client. * @param {Socket} socket Socket.io socket instance * @param {boolean} hideVersion Should we hide the version information in the response? * @returns {Promise<void>} */ async function sendInfo(socket, hideVersion = false) { const info = { primaryBaseURL: await setting("primaryBaseURL"), serverTimezone: await server.getTimezone(), serverTimezoneOffset: server.getTimezoneOffset(), }; if (!hideVersion) { info.version = checkVersion.version; info.latestVersion = checkVersion.latestVersion; info.isContainer = (process.env.UPTIME_KUMA_IS_CONTAINER === "1"); info.dbType = Database.dbConfig.type; info.runtime = { platform: process.platform, // linux or win32 arch: process.arch, // x86 or arm }; } socket.emit("info", info); } /** * Send list of docker hosts to client * @param {Socket} socket Socket.io socket instance * @returns {Promise<Bean[]>} List of docker hosts */ async function sendDockerHostList(socket) { const timeLogger = new TimeLogger(); let result = []; let list = await R.find("docker_host", " user_id = ? ", [ socket.userID, ]); for (let bean of list) { result.push(bean.toJSON()); } io.to(socket.userID).emit("dockerHostList", result); timeLogger.print("Send Docker Host List"); return list; } /** * Send list of docker hosts to client * @param {Socket} socket Socket.io socket instance * @returns {Promise<Bean[]>} List of docker hosts */ async function sendRemoteBrowserList(socket) { const timeLogger = new TimeLogger(); let result = []; let list = await R.find("remote_browser", " user_id = ? ", [ socket.userID, ]); for (let bean of list) { result.push(bean.toJSON()); } io.to(socket.userID).emit("remoteBrowserList", result); timeLogger.print("Send Remote Browser List"); return list; } /** * Send list of monitor types to client * @param {Socket} socket Socket.io socket instance * @returns {Promise<void>} */ async function sendMonitorTypeList(socket) { const result = Object.entries(UptimeKumaServer.monitorTypeList).map(([ key, type ]) => { return [ key, { supportsConditions: type.supportsConditions, conditionVariables: type.conditionVariables.map(v => { return { id: v.id, operators: v.operators.map(o => { return { id: o.id, caption: o.caption, }; }), }; }), }]; }); io.to(socket.userID).emit("monitorTypeList", Object.fromEntries(result)); } module.exports = { sendNotificationList, sendImportantHeartbeatList, sendHeartbeatList, sendProxyList, sendAPIKeyList, sendInfo, sendDockerHostList, sendRemoteBrowserList, sendMonitorTypeList, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification.js
server/notification.js
const { R } = require("redbean-node"); const { log } = require("../src/util"); const Alerta = require("./notification-providers/alerta"); const AlertNow = require("./notification-providers/alertnow"); const AliyunSms = require("./notification-providers/aliyun-sms"); const Apprise = require("./notification-providers/apprise"); const Bale = require("./notification-providers/bale"); const Bark = require("./notification-providers/bark"); const Bitrix24 = require("./notification-providers/bitrix24"); const ClickSendSMS = require("./notification-providers/clicksendsms"); const CallMeBot = require("./notification-providers/call-me-bot"); const SMSC = require("./notification-providers/smsc"); const DingDing = require("./notification-providers/dingding"); const Discord = require("./notification-providers/discord"); const Elks = require("./notification-providers/46elks"); const Feishu = require("./notification-providers/feishu"); const Notifery = require("./notification-providers/notifery"); const FreeMobile = require("./notification-providers/freemobile"); const GoogleChat = require("./notification-providers/google-chat"); const Gorush = require("./notification-providers/gorush"); const Gotify = require("./notification-providers/gotify"); const GrafanaOncall = require("./notification-providers/grafana-oncall"); const HomeAssistant = require("./notification-providers/home-assistant"); const HeiiOnCall = require("./notification-providers/heii-oncall"); const Keep = require("./notification-providers/keep"); const Kook = require("./notification-providers/kook"); const Line = require("./notification-providers/line"); const LunaSea = require("./notification-providers/lunasea"); const Matrix = require("./notification-providers/matrix"); const Mattermost = require("./notification-providers/mattermost"); const NextcloudTalk = require("./notification-providers/nextcloudtalk"); const Nostr = require("./notification-providers/nostr"); const Ntfy = require("./notification-providers/ntfy"); const Octopush = require("./notification-providers/octopush"); const OneChat = require("./notification-providers/onechat"); const OneBot = require("./notification-providers/onebot"); const Opsgenie = require("./notification-providers/opsgenie"); const PagerDuty = require("./notification-providers/pagerduty"); const Pumble = require("./notification-providers/pumble"); const FlashDuty = require("./notification-providers/flashduty"); const PagerTree = require("./notification-providers/pagertree"); const PromoSMS = require("./notification-providers/promosms"); const Pushbullet = require("./notification-providers/pushbullet"); const PushDeer = require("./notification-providers/pushdeer"); const Pushover = require("./notification-providers/pushover"); const PushPlus = require("./notification-providers/pushplus"); const Pushy = require("./notification-providers/pushy"); const RocketChat = require("./notification-providers/rocket-chat"); const SerwerSMS = require("./notification-providers/serwersms"); const Signal = require("./notification-providers/signal"); const SIGNL4 = require("./notification-providers/signl4"); const Slack = require("./notification-providers/slack"); const SMSPartner = require("./notification-providers/smspartner"); const SMSEagle = require("./notification-providers/smseagle"); const SMTP = require("./notification-providers/smtp"); const Squadcast = require("./notification-providers/squadcast"); const Stackfield = require("./notification-providers/stackfield"); const Teams = require("./notification-providers/teams"); const TechulusPush = require("./notification-providers/techulus-push"); const Telegram = require("./notification-providers/telegram"); const Threema = require("./notification-providers/threema"); const Twilio = require("./notification-providers/twilio"); const Splunk = require("./notification-providers/splunk"); const Webhook = require("./notification-providers/webhook"); const WeCom = require("./notification-providers/wecom"); const GoAlert = require("./notification-providers/goalert"); const SMSManager = require("./notification-providers/smsmanager"); const ServerChan = require("./notification-providers/serverchan"); const ZohoCliq = require("./notification-providers/zoho-cliq"); const SevenIO = require("./notification-providers/sevenio"); const Whapi = require("./notification-providers/whapi"); const WAHA = require("./notification-providers/waha"); const Evolution = require("./notification-providers/evolution"); const GtxMessaging = require("./notification-providers/gtx-messaging"); const Cellsynt = require("./notification-providers/cellsynt"); const Onesender = require("./notification-providers/onesender"); const Wpush = require("./notification-providers/wpush"); const SendGrid = require("./notification-providers/send-grid"); const Brevo = require("./notification-providers/brevo"); const Resend = require("./notification-providers/resend"); const YZJ = require("./notification-providers/yzj"); const SMSPlanet = require("./notification-providers/sms-planet"); const SpugPush = require("./notification-providers/spugpush"); const SMSIR = require("./notification-providers/smsir"); const { commandExists } = require("./util-server"); const Webpush = require("./notification-providers/Webpush"); class Notification { providerList = {}; /** * Initialize the notification providers * @returns {void} * @throws Notification provider does not have a name * @throws Duplicate notification providers in list */ static init() { log.debug("notification", "Prepare Notification Providers"); this.providerList = {}; const list = [ new Alerta(), new AlertNow(), new AliyunSms(), new Apprise(), new Bale(), new Bark(), new Bitrix24(), new ClickSendSMS(), new CallMeBot(), new SMSC(), new DingDing(), new Discord(), new Elks(), new Feishu(), new FreeMobile(), new GoogleChat(), new Gorush(), new Gotify(), new GrafanaOncall(), new HomeAssistant(), new HeiiOnCall(), new Keep(), new Kook(), new Line(), new LunaSea(), new Matrix(), new Mattermost(), new NextcloudTalk(), new Nostr(), new Ntfy(), new Octopush(), new OneChat(), new OneBot(), new Onesender(), new Opsgenie(), new PagerDuty(), new FlashDuty(), new PagerTree(), new PromoSMS(), new Pumble(), new Pushbullet(), new PushDeer(), new Pushover(), new PushPlus(), new Pushy(), new RocketChat(), new ServerChan(), new SerwerSMS(), new Signal(), new SIGNL4(), new SMSManager(), new SMSPartner(), new Slack(), new SMSEagle(), new SMTP(), new Squadcast(), new Stackfield(), new Teams(), new TechulusPush(), new Telegram(), new Threema(), new Twilio(), new Splunk(), new Webhook(), new WeCom(), new GoAlert(), new ZohoCliq(), new SevenIO(), new Whapi(), new WAHA(), new Evolution(), new GtxMessaging(), new Cellsynt(), new Wpush(), new Brevo(), new Resend(), new YZJ(), new SMSPlanet(), new SpugPush(), new Notifery(), new SMSIR(), new SendGrid(), new Webpush(), ]; for (let item of list) { if (!item.name) { throw new Error("Notification provider without name"); } if (this.providerList[item.name]) { throw new Error("Duplicate notification provider name"); } this.providerList[item.name] = item; } } /** * 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>} Successful msg * @throws Error with fail msg */ static async send( notification, msg, monitorJSON = null, heartbeatJSON = null ) { if (this.providerList[notification.type]) { return this.providerList[notification.type].send( notification, msg, monitorJSON, heartbeatJSON ); } else { throw new Error("Notification type is not supported"); } } /** * Save a notification * @param {object} notification Notification to save * @param {?number} notificationID ID of notification to update * @param {number} userID ID of user who adds notification * @returns {Promise<Bean>} Notification that was saved */ static async save(notification, notificationID, userID) { let bean; if (notificationID) { bean = await R.findOne("notification", " id = ? AND user_id = ? ", [ notificationID, userID, ]); if (!bean) { throw new Error("notification not found"); } } else { bean = R.dispense("notification"); } bean.name = notification.name; bean.user_id = userID; bean.config = JSON.stringify(notification); bean.is_default = notification.isDefault || false; await R.store(bean); if (notification.applyExisting) { await applyNotificationEveryMonitor(bean.id, userID); } return bean; } /** * Delete a notification * @param {number} notificationID ID of notification to delete * @param {number} userID ID of user who created notification * @returns {Promise<void>} */ static async delete(notificationID, userID) { let bean = await R.findOne("notification", " id = ? AND user_id = ? ", [ notificationID, userID, ]); if (!bean) { throw new Error("notification not found"); } await R.trash(bean); } /** * Check if apprise exists * @returns {Promise<boolean>} Does the command apprise exist? */ static async checkApprise() { return await commandExists("apprise"); } } /** * Apply the notification to every monitor * @param {number} notificationID ID of notification to apply * @param {number} userID ID of user who created notification * @returns {Promise<void>} */ async function applyNotificationEveryMonitor(notificationID, userID) { let monitors = await R.getAll("SELECT id FROM monitor WHERE user_id = ?", [ userID, ]); for (let i = 0; i < monitors.length; i++) { let checkNotification = await R.findOne( "monitor_notification", " monitor_id = ? AND notification_id = ? ", [ monitors[i].id, notificationID ] ); if (!checkNotification) { let relation = R.dispense("monitor_notification"); relation.monitor_id = monitors[i].id; relation.notification_id = notificationID; await R.store(relation); } } } module.exports = { Notification, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/settings.js
server/settings.js
const { R } = require("redbean-node"); const { log } = require("../src/util"); class Settings { /** * Example: * { * key1: { * value: "value2", * timestamp: 12345678 * }, * key2: { * value: 2, * timestamp: 12345678 * }, * } * @type {{}} */ static cacheList = { }; static cacheCleaner = null; /** * Retrieve value of setting based on key * @param {string} key Key of setting to retrieve * @returns {Promise<any>} Value */ static async get(key) { // Start cache clear if not started yet if (!Settings.cacheCleaner) { Settings.cacheCleaner = setInterval(() => { log.debug("settings", "Cache Cleaner is just started."); for (key in Settings.cacheList) { if (Date.now() - Settings.cacheList[key].timestamp > 60 * 1000) { log.debug("settings", "Cache Cleaner deleted: " + key); delete Settings.cacheList[key]; } } }, 60 * 1000); } // Query from cache if (key in Settings.cacheList) { const v = Settings.cacheList[key].value; log.debug("settings", `Get Setting (cache): ${key}: ${v}`); return v; } let value = await R.getCell("SELECT `value` FROM setting WHERE `key` = ? ", [ key, ]); try { const v = JSON.parse(value); log.debug("settings", `Get Setting: ${key}: ${v}`); Settings.cacheList[key] = { value: v, timestamp: Date.now() }; return v; } catch (e) { return value; } } /** * Sets the specified setting to specified value * @param {string} key Key of setting to set * @param {any} value Value to set to * @param {?string} type Type of setting * @returns {Promise<void>} */ static async set(key, value, type = null) { let bean = await R.findOne("setting", " `key` = ? ", [ key, ]); if (!bean) { bean = R.dispense("setting"); bean.key = key; } bean.type = type; bean.value = JSON.stringify(value); await R.store(bean); Settings.deleteCache([ key ]); } /** * Get settings based on type * @param {string} type The type of setting * @returns {Promise<Bean>} Settings */ static async getSettings(type) { let list = await R.getAll("SELECT `key`, `value` FROM setting WHERE `type` = ? ", [ type, ]); let result = {}; for (let row of list) { try { result[row.key] = JSON.parse(row.value); } catch (e) { result[row.key] = row.value; } } return result; } /** * Set settings based on type * @param {string} type Type of settings to set * @param {object} data Values of settings * @returns {Promise<void>} */ static async setSettings(type, data) { let keyList = Object.keys(data); let promiseList = []; for (let key of keyList) { let bean = await R.findOne("setting", " `key` = ? ", [ key ]); if (bean == null) { bean = R.dispense("setting"); bean.type = type; bean.key = key; } if (bean.type === type) { bean.value = JSON.stringify(data[key]); promiseList.push(R.store(bean)); } } await Promise.all(promiseList); Settings.deleteCache(keyList); } /** * Delete selected keys from settings cache * @param {string[]} keyList Keys to remove * @returns {void} */ static deleteCache(keyList) { for (let key of keyList) { delete Settings.cacheList[key]; } } /** * Stop the cache cleaner if running * @returns {void} */ static stopCacheCleaner() { if (Settings.cacheCleaner) { clearInterval(Settings.cacheCleaner); Settings.cacheCleaner = null; } } } module.exports = { Settings, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/2fa.js
server/2fa.js
const { R } = require("redbean-node"); class TwoFA { /** * Disable 2FA for specified user * @param {number} userID ID of user to disable * @returns {Promise<void>} */ static async disable2FA(userID) { return await R.exec("UPDATE `user` SET twofa_status = 0 WHERE id = ? ", [ userID, ]); } } module.exports = TwoFA;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/server.js
server/server.js
/* * Uptime Kuma Server * node "server/server.js" * DO NOT require("./server") in other modules, it likely creates circular dependency! */ console.log("Welcome to Uptime Kuma"); // As the log function need to use dayjs, it should be very top const dayjs = require("dayjs"); dayjs.extend(require("dayjs/plugin/utc")); dayjs.extend(require("./modules/dayjs/plugin/timezone")); dayjs.extend(require("dayjs/plugin/customParseFormat")); // Load environment variables from `.env` require("dotenv").config(); // Check Node.js Version const nodeVersion = process.versions.node; // Get the required Node.js version from package.json const requiredNodeVersions = require("../package.json").engines.node; const bannedNodeVersions = " < 18 || 20.0.* || 20.1.* || 20.2.* || 20.3.* "; console.log(`Your Node.js version: ${nodeVersion}`); const semver = require("semver"); const requiredNodeVersionsComma = requiredNodeVersions.split("||").map((version) => version.trim()).join(", "); // Exit Uptime Kuma immediately if the Node.js version is banned if (semver.satisfies(nodeVersion, bannedNodeVersions)) { console.error("\x1b[31m%s\x1b[0m", `Error: Your Node.js version: ${nodeVersion} is not supported, please upgrade your Node.js to ${requiredNodeVersionsComma}.`); process.exit(-1); } // Warning if the Node.js version is not in the support list, but it maybe still works if (!semver.satisfies(nodeVersion, requiredNodeVersions)) { console.warn("\x1b[31m%s\x1b[0m", `Warning: Your Node.js version: ${nodeVersion} is not officially supported, please upgrade your Node.js to ${requiredNodeVersionsComma}.`); } const args = require("args-parser")(process.argv); const { sleep, log, getRandomInt, genSecret, isDev } = require("../src/util"); const config = require("./config"); log.debug("server", "Arguments"); log.debug("server", args); if (! process.env.NODE_ENV) { process.env.NODE_ENV = "production"; } if (!process.env.UPTIME_KUMA_WS_ORIGIN_CHECK) { process.env.UPTIME_KUMA_WS_ORIGIN_CHECK = "cors-like"; } log.info("server", "Env: " + process.env.NODE_ENV); log.debug("server", "Inside Container: " + (process.env.UPTIME_KUMA_IS_CONTAINER === "1")); if (process.env.UPTIME_KUMA_WS_ORIGIN_CHECK === "bypass") { log.warn("server", "WebSocket Origin Check: " + process.env.UPTIME_KUMA_WS_ORIGIN_CHECK); } const checkVersion = require("./check-version"); log.info("server", "Uptime Kuma Version:", checkVersion.version); log.info("server", "Loading modules"); log.debug("server", "Importing express"); const express = require("express"); const expressStaticGzip = require("express-static-gzip"); log.debug("server", "Importing redbean-node"); const { R } = require("redbean-node"); log.debug("server", "Importing jsonwebtoken"); const jwt = require("jsonwebtoken"); log.debug("server", "Importing http-graceful-shutdown"); const gracefulShutdown = require("http-graceful-shutdown"); log.debug("server", "Importing prometheus-api-metrics"); const prometheusAPIMetrics = require("prometheus-api-metrics"); const { passwordStrength } = require("check-password-strength"); log.debug("server", "Importing 2FA Modules"); const notp = require("notp"); const base32 = require("thirty-two"); const { UptimeKumaServer } = require("./uptime-kuma-server"); const server = UptimeKumaServer.getInstance(); const io = module.exports.io = server.io; const app = server.app; log.debug("server", "Importing Monitor"); const Monitor = require("./model/monitor"); const User = require("./model/user"); log.debug("server", "Importing Settings"); const { getSettings, setSettings, setting, initJWTSecret, checkLogin, doubleCheckPassword, shake256, SHAKE256_LENGTH, allowDevAllOrigin, } = require("./util-server"); log.debug("server", "Importing Notification"); const { Notification } = require("./notification"); Notification.init(); log.debug("server", "Importing Web-Push"); const webpush = require("web-push"); log.debug("server", "Importing Database"); const Database = require("./database"); log.debug("server", "Importing Background Jobs"); const { initBackgroundJobs, stopBackgroundJobs } = require("./jobs"); const { loginRateLimiter, twoFaRateLimiter } = require("./rate-limiter"); const { apiAuth } = require("./auth"); const { login } = require("./auth"); const passwordHash = require("./password-hash"); const { Prometheus } = require("./prometheus"); const { UptimeCalculator } = require("./uptime-calculator"); const hostname = config.hostname; if (hostname) { log.info("server", "Custom hostname: " + hostname); } const port = config.port; const disableFrameSameOrigin = !!process.env.UPTIME_KUMA_DISABLE_FRAME_SAMEORIGIN || args["disable-frame-sameorigin"] || false; const cloudflaredToken = args["cloudflared-token"] || process.env.UPTIME_KUMA_CLOUDFLARED_TOKEN || undefined; // 2FA / notp verification defaults const twoFAVerifyOptions = { "window": 1, "time": 30 }; /** * Run unit test after the server is ready * @type {boolean} */ const testMode = !!args["test"] || false; // Must be after io instantiation const { sendNotificationList, sendHeartbeatList, sendInfo, sendProxyList, sendDockerHostList, sendAPIKeyList, sendRemoteBrowserList, sendMonitorTypeList } = require("./client"); const { statusPageSocketHandler } = require("./socket-handlers/status-page-socket-handler"); const { databaseSocketHandler } = require("./socket-handlers/database-socket-handler"); const { remoteBrowserSocketHandler } = require("./socket-handlers/remote-browser-socket-handler"); const TwoFA = require("./2fa"); const StatusPage = require("./model/status_page"); const { cloudflaredSocketHandler, autoStart: cloudflaredAutoStart, stop: cloudflaredStop } = require("./socket-handlers/cloudflared-socket-handler"); const { proxySocketHandler } = require("./socket-handlers/proxy-socket-handler"); const { dockerSocketHandler } = require("./socket-handlers/docker-socket-handler"); const { maintenanceSocketHandler } = require("./socket-handlers/maintenance-socket-handler"); const { apiKeySocketHandler } = require("./socket-handlers/api-key-socket-handler"); const { generalSocketHandler } = require("./socket-handlers/general-socket-handler"); const { Settings } = require("./settings"); const apicache = require("./modules/apicache"); const { resetChrome } = require("./monitor-types/real-browser-monitor-type"); const { EmbeddedMariaDB } = require("./embedded-mariadb"); const { SetupDatabase } = require("./setup-database"); const { chartSocketHandler } = require("./socket-handlers/chart-socket-handler"); app.use(express.json()); // Global Middleware app.use(function (req, res, next) { if (!disableFrameSameOrigin) { res.setHeader("X-Frame-Options", "SAMEORIGIN"); } res.removeHeader("X-Powered-By"); next(); }); /** * Show Setup Page * @type {boolean} */ let needSetup = false; (async () => { // Create a data directory Database.initDataDir(args); // Check if is chosen a database type let setupDatabase = new SetupDatabase(args, server); if (setupDatabase.isNeedSetup()) { // Hold here and start a special setup page until user choose a database type await setupDatabase.start(hostname, port); } // Connect to database try { await initDatabase(testMode); } catch (e) { log.error("server", "Failed to prepare your database: " + e.message); process.exit(1); } // Database should be ready now await server.initAfterDatabaseReady(); server.entryPage = await Settings.get("entryPage"); await StatusPage.loadDomainMappingList(); log.debug("server", "Initializing Prometheus"); await Prometheus.init(); log.debug("server", "Adding route"); // *************************** // Normal Router here // *************************** // Entry Page app.get("/", async (request, response) => { let hostname = request.hostname; if (await setting("trustProxy")) { const proxy = request.headers["x-forwarded-host"]; if (proxy) { hostname = proxy; } } log.debug("entry", `Request Domain: ${hostname}`); const uptimeKumaEntryPage = server.entryPage; if (hostname in StatusPage.domainMappingList) { log.debug("entry", "This is a status page domain"); let slug = StatusPage.domainMappingList[hostname]; await StatusPage.handleStatusPageResponse(response, server.indexHTML, slug); } else if (uptimeKumaEntryPage && uptimeKumaEntryPage.startsWith("statusPage-")) { response.redirect("/status/" + uptimeKumaEntryPage.replace("statusPage-", "")); } else { response.redirect("/dashboard"); } }); app.get("/setup-database-info", (request, response) => { allowDevAllOrigin(response); response.json({ runningSetup: false, needSetup: false, }); }); if (isDev) { app.use(express.urlencoded({ extended: true })); app.post("/test-webhook", async (request, response) => { log.debug("test", request.headers); log.debug("test", request.body); response.send("OK"); }); app.post("/test-x-www-form-urlencoded", async (request, response) => { log.debug("test", request.headers); log.debug("test", request.body); response.send("OK"); }); const fs = require("fs"); app.get("/_e2e/take-sqlite-snapshot", async (request, response) => { await Database.close(); try { fs.cpSync(Database.sqlitePath, `${Database.sqlitePath}.e2e-snapshot`); } catch (err) { throw new Error("Unable to copy SQLite DB."); } await Database.connect(); response.send("Snapshot taken."); }); app.get("/_e2e/restore-sqlite-snapshot", async (request, response) => { if (!fs.existsSync(`${Database.sqlitePath}.e2e-snapshot`)) { throw new Error("Snapshot doesn't exist."); } await Database.close(); try { fs.cpSync(`${Database.sqlitePath}.e2e-snapshot`, Database.sqlitePath); } catch (err) { throw new Error("Unable to copy snapshot file."); } await Database.connect(); response.send("Snapshot restored."); }); } // Robots.txt app.get("/robots.txt", async (_request, response) => { let txt = "User-agent: *\nDisallow:"; if (!await setting("searchEngineIndex")) { txt += " /"; } response.setHeader("Content-Type", "text/plain"); response.send(txt); }); // Basic Auth Router here // Prometheus API metrics /metrics // With Basic Auth using the first user's username/password app.get("/metrics", apiAuth, prometheusAPIMetrics()); app.use("/", expressStaticGzip("dist", { enableBrotli: true, })); // ./data/upload app.use("/upload", express.static(Database.uploadDir)); app.get("/.well-known/change-password", async (_, response) => { response.redirect("https://github.com/louislam/uptime-kuma/wiki/Reset-Password-via-CLI"); }); // API Router const apiRouter = require("./routers/api-router"); app.use(apiRouter); // Status Page Router const statusPageRouter = require("./routers/status-page-router"); app.use(statusPageRouter); // Universal Route Handler, must be at the end of all express routes. app.get("*", async (_request, response) => { if (_request.originalUrl.startsWith("/upload/")) { response.status(404).send("File not found."); } else { response.send(server.indexHTML); } }); log.debug("server", "Adding socket handler"); io.on("connection", async (socket) => { await sendInfo(socket, true); if (needSetup) { log.info("server", "Redirect to setup page"); socket.emit("setup"); } // *************************** // Public Socket API // *************************** socket.on("loginByToken", async (token, callback) => { const clientIP = await server.getClientIP(socket); log.info("auth", `Login by token. IP=${clientIP}`); try { let decoded = jwt.verify(token, server.jwtSecret); log.info("auth", "Username from JWT: " + decoded.username); let user = await R.findOne("user", " username = ? AND active = 1 ", [ decoded.username, ]); if (user) { // Check if the password changed if (decoded.h !== shake256(user.password, SHAKE256_LENGTH)) { throw new Error("The token is invalid due to password change or old token"); } log.debug("auth", "afterLogin"); await afterLogin(socket, user); log.debug("auth", "afterLogin ok"); log.info("auth", `Successfully logged in user ${decoded.username}. IP=${clientIP}`); callback({ ok: true, }); } else { log.info("auth", `Inactive or deleted user ${decoded.username}. IP=${clientIP}`); callback({ ok: false, msg: "authUserInactiveOrDeleted", msgi18n: true, }); } } catch (error) { log.error("auth", `Invalid token. IP=${clientIP}`); if (error.message) { log.error("auth", error.message, `IP=${clientIP}`); } callback({ ok: false, msg: "authInvalidToken", msgi18n: true, }); } }); socket.on("login", async (data, callback) => { const clientIP = await server.getClientIP(socket); log.info("auth", `Login by username + password. IP=${clientIP}`); // Checking if (typeof callback !== "function") { return; } if (!data) { return; } // Login Rate Limit if (!await loginRateLimiter.pass(callback)) { log.info("auth", `Too many failed requests for user ${data.username}. IP=${clientIP}`); return; } let user = await login(data.username, data.password); if (user) { if (user.twofa_status === 0) { await afterLogin(socket, user); log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`); callback({ ok: true, token: User.createJWT(user, server.jwtSecret), }); } if (user.twofa_status === 1 && !data.token) { log.info("auth", `2FA token required for user ${data.username}. IP=${clientIP}`); callback({ tokenRequired: true, }); } if (data.token) { let verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions); if (user.twofa_last_token !== data.token && verify) { await afterLogin(socket, user); await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [ data.token, socket.userID, ]); log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`); callback({ ok: true, token: User.createJWT(user, server.jwtSecret), }); } else { log.warn("auth", `Invalid token provided for user ${data.username}. IP=${clientIP}`); callback({ ok: false, msg: "authInvalidToken", msgi18n: true, }); } } } else { log.warn("auth", `Incorrect username or password for user ${data.username}. IP=${clientIP}`); callback({ ok: false, msg: "authIncorrectCreds", msgi18n: true, }); } }); socket.on("logout", async (callback) => { // Rate Limit if (!await loginRateLimiter.pass(callback)) { return; } socket.leave(socket.userID); socket.userID = null; if (typeof callback === "function") { callback(); } }); socket.on("prepare2FA", async (currentPassword, callback) => { try { if (!await twoFaRateLimiter.pass(callback)) { return; } checkLogin(socket); await doubleCheckPassword(socket, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, ]); if (user.twofa_status === 0) { let newSecret = genSecret(); let encodedSecret = base32.encode(newSecret); // Google authenticator doesn't like equal signs // The fix is found at https://github.com/guyht/notp // Related issue: https://github.com/louislam/uptime-kuma/issues/486 encodedSecret = encodedSecret.toString().replace(/=/g, ""); let uri = `otpauth://totp/Uptime%20Kuma:${user.username}?secret=${encodedSecret}`; await R.exec("UPDATE `user` SET twofa_secret = ? WHERE id = ? ", [ newSecret, socket.userID, ]); callback({ ok: true, uri: uri, }); } else { callback({ ok: false, msg: "2faAlreadyEnabled", msgi18n: true, }); } } catch (error) { callback({ ok: false, msg: error.message, }); } }); socket.on("save2FA", async (currentPassword, callback) => { const clientIP = await server.getClientIP(socket); try { if (!await twoFaRateLimiter.pass(callback)) { return; } checkLogin(socket); await doubleCheckPassword(socket, currentPassword); await R.exec("UPDATE `user` SET twofa_status = 1 WHERE id = ? ", [ socket.userID, ]); log.info("auth", `Saved 2FA token. IP=${clientIP}`); callback({ ok: true, msg: "2faEnabled", msgi18n: true, }); } catch (error) { log.error("auth", `Error changing 2FA token. IP=${clientIP}`); callback({ ok: false, msg: error.message, }); } }); socket.on("disable2FA", async (currentPassword, callback) => { const clientIP = await server.getClientIP(socket); try { if (!await twoFaRateLimiter.pass(callback)) { return; } checkLogin(socket); await doubleCheckPassword(socket, currentPassword); await TwoFA.disable2FA(socket.userID); log.info("auth", `Disabled 2FA token. IP=${clientIP}`); callback({ ok: true, msg: "2faDisabled", msgi18n: true, }); } catch (error) { log.error("auth", `Error disabling 2FA token. IP=${clientIP}`); callback({ ok: false, msg: error.message, }); } }); socket.on("verifyToken", async (token, currentPassword, callback) => { try { checkLogin(socket); await doubleCheckPassword(socket, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, ]); let verify = notp.totp.verify(token, user.twofa_secret, twoFAVerifyOptions); if (user.twofa_last_token !== token && verify) { callback({ ok: true, valid: true, }); } else { callback({ ok: false, msg: "authInvalidToken", msgi18n: true, valid: false, }); } } catch (error) { callback({ ok: false, msg: error.message, }); } }); socket.on("twoFAStatus", async (callback) => { try { checkLogin(socket); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, ]); if (user.twofa_status === 1) { callback({ ok: true, status: true, }); } else { callback({ ok: true, status: false, }); } } catch (error) { callback({ ok: false, msg: error.message, }); } }); socket.on("needSetup", async (callback) => { callback(needSetup); }); socket.on("setup", async (username, password, callback) => { try { if (passwordStrength(password).value === "Too weak") { throw new Error("Password is too weak. It should contain alphabetic and numeric characters. It must be at least 6 characters in length."); } if ((await R.knex("user").count("id as count").first()).count !== 0) { throw new Error("Uptime Kuma has been initialized. If you want to run setup again, please delete the database."); } let user = R.dispense("user"); user.username = username; user.password = await passwordHash.generate(password); await R.store(user); needSetup = false; callback({ ok: true, msg: "successAdded", msgi18n: true, }); } catch (e) { callback({ ok: false, msg: e.message, }); } }); // *************************** // Auth Only API // *************************** // Add a new monitor socket.on("add", async (monitor, callback) => { try { checkLogin(socket); let bean = R.dispense("monitor"); let notificationIDList = monitor.notificationIDList; delete monitor.notificationIDList; // Ensure status code ranges are strings if (!monitor.accepted_statuscodes.every((code) => typeof code === "string")) { throw new Error("Accepted status codes are not all strings"); } monitor.accepted_statuscodes_json = JSON.stringify(monitor.accepted_statuscodes); delete monitor.accepted_statuscodes; monitor.kafkaProducerBrokers = JSON.stringify(monitor.kafkaProducerBrokers); monitor.kafkaProducerSaslOptions = JSON.stringify(monitor.kafkaProducerSaslOptions); monitor.conditions = JSON.stringify(monitor.conditions); monitor.rabbitmqNodes = JSON.stringify(monitor.rabbitmqNodes); /* * List of frontend-only properties that should not be saved to the database. * Should clean up before saving to the database. */ const frontendOnlyProperties = [ "humanReadableInterval" ]; for (const prop of frontendOnlyProperties) { if (prop in monitor) { delete monitor[prop]; } } bean.import(monitor); bean.user_id = socket.userID; bean.validate(); await R.store(bean); await updateMonitorNotification(bean.id, notificationIDList); await server.sendUpdateMonitorIntoList(socket, bean.id); if (monitor.active !== false) { await startMonitor(socket.userID, bean.id); } log.info("monitor", `Added Monitor: ${bean.id} User ID: ${socket.userID}`); callback({ ok: true, msg: "successAdded", msgi18n: true, monitorID: bean.id, }); } catch (e) { log.error("monitor", `Error adding Monitor: ${monitor.id} User ID: ${socket.userID}`); callback({ ok: false, msg: e.message, }); } }); // Edit a monitor socket.on("editMonitor", async (monitor, callback) => { try { let removeGroupChildren = false; checkLogin(socket); let bean = await R.findOne("monitor", " id = ? ", [ monitor.id ]); if (bean.user_id !== socket.userID) { throw new Error("Permission denied."); } // Check if Parent is Descendant (would cause endless loop) if (monitor.parent !== null) { const childIDs = await Monitor.getAllChildrenIDs(monitor.id); if (childIDs.includes(monitor.parent)) { throw new Error("Invalid Monitor Group"); } } // Remove children if monitor type has changed (from group to non-group) if (bean.type === "group" && monitor.type !== bean.type) { removeGroupChildren = true; } // Ensure status code ranges are strings if (!monitor.accepted_statuscodes.every((code) => typeof code === "string")) { throw new Error("Accepted status codes are not all strings"); } bean.name = monitor.name; bean.description = monitor.description; bean.parent = monitor.parent; bean.type = monitor.type; bean.url = monitor.url; bean.wsIgnoreSecWebsocketAcceptHeader = monitor.wsIgnoreSecWebsocketAcceptHeader; bean.wsSubprotocol = monitor.wsSubprotocol; bean.method = monitor.method; bean.body = monitor.body; bean.ipFamily = monitor.ipFamily; bean.headers = monitor.headers; bean.basic_auth_user = monitor.basic_auth_user; bean.basic_auth_pass = monitor.basic_auth_pass; bean.timeout = monitor.timeout; bean.oauth_client_id = monitor.oauth_client_id; bean.oauth_client_secret = monitor.oauth_client_secret; bean.oauth_auth_method = monitor.oauth_auth_method; bean.oauth_token_url = monitor.oauth_token_url; bean.oauth_scopes = monitor.oauth_scopes; bean.oauth_audience = monitor.oauth_audience; bean.tlsCa = monitor.tlsCa; bean.tlsCert = monitor.tlsCert; bean.tlsKey = monitor.tlsKey; bean.interval = monitor.interval; bean.retryInterval = monitor.retryInterval; bean.resendInterval = monitor.resendInterval; bean.hostname = monitor.hostname; bean.game = monitor.game; bean.maxretries = monitor.maxretries; bean.port = parseInt(monitor.port); if (isNaN(bean.port)) { bean.port = null; } bean.keyword = monitor.keyword; bean.invertKeyword = monitor.invertKeyword; bean.ignoreTls = monitor.ignoreTls; bean.expiryNotification = monitor.expiryNotification; bean.domainExpiryNotification = monitor.domainExpiryNotification; bean.upsideDown = monitor.upsideDown; bean.packetSize = monitor.packetSize; bean.maxredirects = monitor.maxredirects; bean.accepted_statuscodes_json = JSON.stringify(monitor.accepted_statuscodes); bean.dns_resolve_type = monitor.dns_resolve_type; bean.dns_resolve_server = monitor.dns_resolve_server; bean.pushToken = monitor.pushToken; bean.docker_container = monitor.docker_container; bean.docker_host = monitor.docker_host; bean.proxyId = Number.isInteger(monitor.proxyId) ? monitor.proxyId : null; bean.mqttUsername = monitor.mqttUsername; bean.mqttPassword = monitor.mqttPassword; bean.mqttTopic = monitor.mqttTopic; bean.mqttSuccessMessage = monitor.mqttSuccessMessage; bean.mqttCheckType = monitor.mqttCheckType; bean.mqttWebsocketPath = monitor.mqttWebsocketPath; bean.databaseConnectionString = monitor.databaseConnectionString; bean.databaseQuery = monitor.databaseQuery; bean.authMethod = monitor.authMethod; bean.authWorkstation = monitor.authWorkstation; bean.authDomain = monitor.authDomain; bean.grpcUrl = monitor.grpcUrl; bean.grpcProtobuf = monitor.grpcProtobuf; bean.grpcServiceName = monitor.grpcServiceName; bean.grpcMethod = monitor.grpcMethod; bean.grpcBody = monitor.grpcBody; bean.grpcMetadata = monitor.grpcMetadata; bean.grpcEnableTls = monitor.grpcEnableTls; bean.radiusUsername = monitor.radiusUsername; bean.radiusPassword = monitor.radiusPassword; bean.radiusCalledStationId = monitor.radiusCalledStationId; bean.radiusCallingStationId = monitor.radiusCallingStationId; bean.radiusSecret = monitor.radiusSecret; bean.httpBodyEncoding = monitor.httpBodyEncoding; bean.expectedValue = monitor.expectedValue; bean.jsonPath = monitor.jsonPath; bean.kafkaProducerTopic = monitor.kafkaProducerTopic; bean.kafkaProducerBrokers = JSON.stringify(monitor.kafkaProducerBrokers); bean.kafkaProducerAllowAutoTopicCreation = monitor.kafkaProducerAllowAutoTopicCreation; bean.kafkaProducerSaslOptions = JSON.stringify(monitor.kafkaProducerSaslOptions); bean.kafkaProducerMessage = monitor.kafkaProducerMessage; bean.cacheBust = monitor.cacheBust; bean.kafkaProducerSsl = monitor.kafkaProducerSsl;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
true
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/password-hash.js
server/password-hash.js
const passwordHashOld = require("password-hash"); const bcrypt = require("bcryptjs"); const saltRounds = 10; /** * Hash a password * @param {string} password Password to hash * @returns {Promise<string>} Hash */ exports.generate = function (password) { return bcrypt.hash(password, saltRounds); }; /** * Verify a password against a hash * @param {string} password Password to verify * @param {string} hash Hash to verify against * @returns {boolean} Does the password match the hash? */ exports.verify = function (password, hash) { if (isSHA1(hash)) { return passwordHashOld.verify(password, hash); } return bcrypt.compareSync(password, hash); }; /** * Is the hash a SHA1 hash * @param {string} hash Hash to check * @returns {boolean} Is SHA1 hash? */ function isSHA1(hash) { return (typeof hash === "string" && hash.startsWith("sha1")); } /** * Does the hash need to be rehashed? * @param {string} hash Hash to check * @returns {boolean} Needs to be rehashed? */ exports.needRehash = function (hash) { return isSHA1(hash); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/jobs/clear-old-data.js
server/jobs/clear-old-data.js
const { R } = require("redbean-node"); const { log } = require("../../src/util"); const Database = require("../database"); const { Settings } = require("../settings"); const dayjs = require("dayjs"); const DEFAULT_KEEP_PERIOD = 365; /** * Clears old data from the heartbeat table and the stat_daily of the database. * @returns {Promise<void>} A promise that resolves when the data has been cleared. */ const clearOldData = async () => { await Database.clearHeartbeatData(); let period = await Settings.get("keepDataPeriodDays"); // Set Default Period if (period == null) { await Settings.set("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general"); period = DEFAULT_KEEP_PERIOD; } // Try parse setting let parsedPeriod; try { parsedPeriod = parseInt(period); } catch (_) { log.warn("clearOldData", "Failed to parse setting, resetting to default.."); await Settings.set("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general"); parsedPeriod = DEFAULT_KEEP_PERIOD; } if (parsedPeriod < 1) { log.info("clearOldData", `Data deletion has been disabled as period is less than 1. Period is ${parsedPeriod} days.`); } else { log.debug("clearOldData", `Clearing Data older than ${parsedPeriod} days...`); const sqlHourOffset = Database.sqlHourOffset(); try { // Heartbeat await R.exec("DELETE FROM heartbeat WHERE time < " + sqlHourOffset, [ parsedPeriod * -24, ]); let timestamp = dayjs().subtract(parsedPeriod, "day").utc().startOf("day").unix(); // stat_daily await R.exec("DELETE FROM stat_daily WHERE timestamp < ? ", [ timestamp, ]); if (Database.dbConfig.type === "sqlite") { await R.exec("PRAGMA optimize;"); } } catch (e) { log.error("clearOldData", `Failed to clear old data: ${e.message}`); } } log.debug("clearOldData", "Data cleared."); }; module.exports = { clearOldData, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/jobs/incremental-vacuum.js
server/jobs/incremental-vacuum.js
const { R } = require("redbean-node"); const { log } = require("../../src/util"); const Database = require("../database"); /** * Run incremental_vacuum and checkpoint the WAL. * @returns {Promise<void>} A promise that resolves when the process is finished. */ const incrementalVacuum = async () => { try { if (Database.dbConfig.type !== "sqlite") { log.debug("incrementalVacuum", "Skipping incremental_vacuum, not using SQLite."); return; } log.debug("incrementalVacuum", "Running incremental_vacuum and wal_checkpoint(PASSIVE)..."); await R.exec("PRAGMA incremental_vacuum(200)"); await R.exec("PRAGMA wal_checkpoint(PASSIVE)"); } catch (e) { log.error("incrementalVacuum", `Failed: ${e.message}`); } }; module.exports = { incrementalVacuum, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/user.js
server/model/user.js
const { BeanModel } = require("redbean-node/dist/bean-model"); const passwordHash = require("../password-hash"); const { R } = require("redbean-node"); const jwt = require("jsonwebtoken"); const { shake256, SHAKE256_LENGTH } = require("../util-server"); class User extends BeanModel { /** * Reset user password * Fix #1510, as in the context reset-password.js, there is no auto model mapping. Call this static function instead. * @param {number} userID ID of user to update * @param {string} newPassword Users new password * @returns {Promise<void>} */ static async resetPassword(userID, newPassword) { await R.exec("UPDATE `user` SET password = ? WHERE id = ? ", [ await passwordHash.generate(newPassword), userID ]); } /** * Reset this users password * @param {string} newPassword Users new password * @returns {Promise<void>} */ async resetPassword(newPassword) { const hashedPassword = await passwordHash.generate(newPassword); await R.exec("UPDATE `user` SET password = ? WHERE id = ? ", [ hashedPassword, this.id ]); this.password = hashedPassword; } /** * Create a new JWT for a user * @param {User} user The User to create a JsonWebToken for * @param {string} jwtSecret The key used to sign the JsonWebToken * @returns {string} the JsonWebToken as a string */ static createJWT(user, jwtSecret) { return jwt.sign({ username: user.username, h: shake256(user.password, SHAKE256_LENGTH), }, jwtSecret); } } module.exports = User;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/proxy.js
server/model/proxy.js
const { BeanModel } = require("redbean-node/dist/bean-model"); class Proxy extends BeanModel { /** * Return an object that ready to parse to JSON * @returns {object} Object ready to parse */ toJSON() { return { id: this._id, userId: this._user_id, protocol: this._protocol, host: this._host, port: this._port, auth: !!this._auth, username: this._username, password: this._password, active: !!this._active, default: !!this._default, createdDate: this._created_date, }; } } module.exports = Proxy;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/domain_expiry.js
server/model/domain_expiry.js
const { BeanModel } = require("redbean-node/dist/bean-model"); const { R } = require("redbean-node"); const { log } = require("../../src/util"); const { parse: parseTld } = require("tldts"); const { getDaysRemaining, getDaysBetween, setting, setSetting } = require("../util-server"); const { Notification } = require("../notification"); const { default: NodeFetchCache, MemoryCache } = require("node-fetch-cache"); const TABLE = "domain_expiry"; const urlTypes = [ "websocket-upgrade", "http", "keyword", "json-query", "real-browser" ]; const excludeTypes = [ "docker", "group", "push", "manual", "rabbitmq", "redis" ]; const cachedFetch = process.env.NODE_ENV ? NodeFetchCache.create({ // cache for 8h cache: new MemoryCache({ ttl: 1000 * 60 * 60 * 8 }) }) : fetch; /** * Find the RDAP server for a given TLD * @param {string} tld TLD * @returns {Promise<string>} First RDAP server found */ async function getRdapServer(tld) { let rdapList; try { const res = await cachedFetch("https://data.iana.org/rdap/dns.json"); rdapList = await res.json(); } catch (error) { log.debug("rdap", error); return null; } for (const service of rdapList["services"]) { const [ tlds, urls ] = service; if (tlds.includes(tld)) { return urls[0]; } } return null; } /** * Request RDAP server to retrieve the expiry date of a domain * @param {string} domain Domain to retrieve the expiry date from * @returns {Promise<(Date|null)>} Expiry date from RDAP server */ async function getRdapDomainExpiryDate(domain) { const tld = DomainExpiry.parseTld(domain).publicSuffix; const rdapServer = await getRdapServer(tld); if (rdapServer === null) { log.warn("rdap", `No RDAP server found, TLD ${tld} not supported.`); return null; } const url = `${rdapServer}domain/${domain}`; let rdapInfos; try { const res = await fetch(url); if (res.status !== 200) { return null; } rdapInfos = await res.json(); } catch { log.warn("rdap", "Not able to get expiry date from RDAP"); return null; } if (rdapInfos["events"] === undefined) { return null; } for (const event of rdapInfos["events"]) { if (event["eventAction"] === "expiration") { return new Date(event["eventDate"]); } } return null; } /** * Send a certificate notification when domain expires in less than target days * @param {string} domain Domain we monitor * @param {number} daysRemaining Number of days remaining on certificate * @param {number} targetDays Number of days to alert after * @param {LooseObject<any>[]} notificationList List of notification providers * @returns {Promise<void>} */ async function sendDomainNotificationByTargetDays(domain, daysRemaining, targetDays, notificationList) { let sent = false; log.debug("domain", `Send domain expiry notification for ${targetDays} deadline.`); for (let notification of notificationList) { try { log.debug("domain", `Sending to ${notification.name}`); await Notification.send( JSON.parse(notification.config), `Domain name ${domain} will expire in ${daysRemaining} days` ); sent = true; } catch (e) { log.error("domain", `Cannot send domain notification to ${notification.name}`); log.error("domain", e); } } return sent; } class DomainExpiry extends BeanModel { /** * @param {string} domain Domain name * @returns {Promise<DomainExpiry>} Domain bean */ static async findByName(domain) { return R.findOne(TABLE, "domain = ?", [ domain ]); } /** * @param {string} domain Domain name * @returns {DomainExpiry} Domain bean */ static createByName(domain) { const d = R.dispense(TABLE); d.domain = domain; return d; } static parseTld = parseTld; /** * @returns {(object)} parsed domain components */ parseName() { return parseTld(this.domain); } /** * @returns {(null|object)} parsed domain tld */ get tld() { return this.parseName().publicSuffix; } /** * @param {Monitor} monitor Monitor object * @returns {Promise<DomainExpiry>} Domain expiry bean */ static async forMonitor(monitor) { const m = monitor; if (excludeTypes.includes(m.type) || m.type?.match(/sql$/)) { return false; } const tld = parseTld(urlTypes.includes(m.type) ? m.url : m.type === "grpc-keyword" ? m.grpcUrl : m.hostname); const rdap = await getRdapServer(tld.publicSuffix); if (!rdap) { log.warn("domain", `${tld.publicSuffix} is not supported. File a bug report if you believe it should be.`); return false; } const existing = await DomainExpiry.findByName(tld.domain); if (existing) { return existing; } if (tld.domain) { return await DomainExpiry.createByName(tld.domain); } } /** * @returns {number} number of days remaining before expiry */ get daysRemaining() { return getDaysRemaining(new Date(), new Date(this.expiry)); } /** * @returns {Promise<(Date|null)>} Expiry date from RDAP */ async getExpiryDate() { return getRdapDomainExpiryDate(this.domain); } /** * @param {(Monitor)} monitor Monitor object * @returns {Promise<void>} */ static async checkExpiry(monitor) { let bean = await DomainExpiry.forMonitor(monitor); let expiryDate; if (bean?.lastCheck && getDaysBetween(new Date(bean.lastCheck), new Date()) < 1) { log.debug("domain", `Domain expiry already checked recently for ${bean.domain}, won't re-check.`); return bean.expiry; } else if (bean) { expiryDate = await bean.getExpiryDate(); if (new Date(expiryDate) > new Date(bean.expiry)) { bean.lastExpiryNotificationSent = null; } bean.expiry = expiryDate; bean.lastCheck = new Date(); await R.store(bean); } if (expiryDate === null) { return; } return expiryDate; } /** * @param {Monitor} monitor Monitor instance * @param {LooseObject<any>[]} notificationList notification List * @returns {Promise<void>} */ static async sendNotifications(monitor, notificationList) { const domain = await DomainExpiry.forMonitor(monitor); const name = domain.domain; if (!notificationList.length > 0) { // fail fast. If no notification is set, all the following checks can be skipped. log.debug("domain", "No notification, no need to send domain notification"); return; } const daysRemaining = getDaysRemaining(new Date(), domain.expiry); const lastSent = domain.lastExpiryNotificationSent; log.debug("domain", `${name} expires in ${daysRemaining} days`); let notifyDays = await setting("domainExpiryNotifyDays"); if (notifyDays == null || !Array.isArray(notifyDays)) { // Reset Default await setSetting("domainExpiryNotifyDays", [ 7, 14, 21 ], "general"); notifyDays = [ 7, 14, 21 ]; } if (Array.isArray(notifyDays)) { // Asc sort to avoid sending multiple notifications if daysRemaining is below multiple targetDays notifyDays.sort((a, b) => a - b); for (const targetDays of notifyDays) { if (daysRemaining > targetDays) { log.debug( "domain", `No need to send domain notification for ${name} (${daysRemaining} days valid) on ${targetDays} deadline.` ); continue; } else if (lastSent && lastSent <= targetDays) { log.debug( "domain", `Notification for ${name} on ${targetDays} deadline sent already, no need to send again.` ); continue; } const sent = await sendDomainNotificationByTargetDays( name, daysRemaining, targetDays, notificationList ); if (sent) { domain.lastExpiryNotificationSent = targetDays; await R.store(domain); return targetDays; } } } } } module.exports = DomainExpiry;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/docker_host.js
server/model/docker_host.js
const { BeanModel } = require("redbean-node/dist/bean-model"); class DockerHost extends BeanModel { /** * Returns an object that ready to parse to JSON * @returns {object} Object ready to parse */ toJSON() { return { id: this.id, userID: this.user_id, dockerDaemon: this.docker_daemon, dockerType: this.docker_type, name: this.name, }; } } module.exports = DockerHost;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/status_page.js
server/model/status_page.js
const { BeanModel } = require("redbean-node/dist/bean-model"); const { R } = require("redbean-node"); const cheerio = require("cheerio"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const jsesc = require("jsesc"); const analytics = require("../analytics/analytics"); const { marked } = require("marked"); const { Feed } = require("feed"); const config = require("../config"); const { STATUS_PAGE_ALL_DOWN, STATUS_PAGE_ALL_UP, STATUS_PAGE_MAINTENANCE, STATUS_PAGE_PARTIAL_DOWN, UP, MAINTENANCE, DOWN } = require("../../src/util"); class StatusPage extends BeanModel { /** * Like this: { "test-uptime.kuma.pet": "default" } * @type {{}} */ static domainMappingList = { }; /** * Handle responses to RSS pages * @param {Response} response Response object * @param {string} slug Status page slug * @returns {Promise<void>} */ static async handleStatusPageRSSResponse(response, slug) { let statusPage = await R.findOne("status_page", " slug = ? ", [ slug ]); if (statusPage) { response.type("application/rss+xml"); response.send(await StatusPage.renderRSS(statusPage, slug)); } else { response.status(404).send(UptimeKumaServer.getInstance().indexHTML); } } /** * Handle responses to status page * @param {Response} response Response object * @param {string} indexHTML HTML to render * @param {string} slug Status page slug * @returns {Promise<void>} */ static async handleStatusPageResponse(response, indexHTML, slug) { // Handle url with trailing slash (http://localhost:3001/status/) // The slug comes from the route "/status/:slug". If the slug is empty, express converts it to "index.html" if (slug === "index.html") { slug = "default"; } let statusPage = await R.findOne("status_page", " slug = ? ", [ slug ]); if (statusPage) { response.send(await StatusPage.renderHTML(indexHTML, statusPage)); } else { response.status(404).send(UptimeKumaServer.getInstance().indexHTML); } } /** * SSR for RSS feed * @param {statusPage} statusPage object * @param {slug} slug from router * @returns {Promise<string>} the rendered html */ static async renderRSS(statusPage, slug) { const { heartbeats, statusDescription } = await StatusPage.getRSSPageData(statusPage); let proto = config.isSSL ? "https" : "http"; let host = `${proto}://${config.hostname || "localhost"}:${config.port}/status/${slug}`; const feed = new Feed({ title: "uptime kuma rss feed", description: `current status: ${statusDescription}`, link: host, language: "en", // optional, used only in RSS 2.0, possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes updated: new Date(), // optional, default = today }); heartbeats.forEach(heartbeat => { feed.addItem({ title: `${heartbeat.name} is down`, description: `${heartbeat.name} has been down since ${heartbeat.time}`, id: heartbeat.monitorID, date: new Date(heartbeat.time), }); }); return feed.rss2(); } /** * SSR for status pages * @param {string} indexHTML HTML page to render * @param {StatusPage} statusPage Status page populate HTML with * @returns {Promise<string>} the rendered html */ static async renderHTML(indexHTML, statusPage) { const $ = cheerio.load(indexHTML); const description155 = marked(statusPage.description ?? "") .replace(/<[^>]+>/gm, "") .trim() .substring(0, 155); $("title").text(statusPage.title); $("meta[name=description]").attr("content", description155); if (statusPage.icon) { $("link[rel=icon]") .attr("href", statusPage.icon) .removeAttr("type"); $("link[rel=apple-touch-icon]").remove(); } const head = $("head"); if (analytics.isValidAnalyticsConfig(statusPage)) { let escapedAnalyticsScript = analytics.getAnalyticsScript(statusPage); head.append($(escapedAnalyticsScript)); } // OG Meta Tags let ogTitle = $("<meta property=\"og:title\" content=\"\" />").attr("content", statusPage.title); head.append(ogTitle); let ogDescription = $("<meta property=\"og:description\" content=\"\" />").attr("content", description155); head.append(ogDescription); let ogType = $("<meta property=\"og:type\" content=\"website\" />"); head.append(ogType); // Preload data // Add jsesc, fix https://github.com/louislam/uptime-kuma/issues/2186 const escapedJSONObject = jsesc(await StatusPage.getStatusPageData(statusPage), { "isScriptContext": true }); const script = $(` <script id="preload-data" data-json="{}"> window.preloadData = ${escapedJSONObject}; </script> `); head.append(script); // manifest.json $("link[rel=manifest]").attr("href", `/api/status-page/${statusPage.slug}/manifest.json`); return $.root().html(); } /** * @param {heartbeats} heartbeats from getRSSPageData * @returns {number} status_page constant from util.ts */ static overallStatus(heartbeats) { if (heartbeats.length === 0) { return -1; } let status = STATUS_PAGE_ALL_UP; let hasUp = false; for (let beat of heartbeats) { if (beat.status === MAINTENANCE) { return STATUS_PAGE_MAINTENANCE; } else if (beat.status === UP) { hasUp = true; } else { status = STATUS_PAGE_PARTIAL_DOWN; } } if (! hasUp) { status = STATUS_PAGE_ALL_DOWN; } return status; } /** * @param {number} status from overallStatus * @returns {string} description */ static getStatusDescription(status) { if (status === -1) { return "No Services"; } if (status === STATUS_PAGE_ALL_UP) { return "All Systems Operational"; } if (status === STATUS_PAGE_PARTIAL_DOWN) { return "Partially Degraded Service"; } if (status === STATUS_PAGE_ALL_DOWN) { return "Degraded Service"; } // TODO: show the real maintenance information: title, description, time if (status === MAINTENANCE) { return "Under maintenance"; } return "?"; } /** * Get all data required for RSS * @param {StatusPage} statusPage Status page to get data for * @returns {object} Status page data */ static async getRSSPageData(statusPage) { // get all heartbeats that correspond to this statusPage const config = await statusPage.toPublicJSON(); // Public Group List const showTags = !!statusPage.show_tags; const list = await R.find("group", " public = 1 AND status_page_id = ? ORDER BY weight ", [ statusPage.id ]); let heartbeats = []; for (let groupBean of list) { let monitorGroup = await groupBean.toPublicJSON(showTags, config?.showCertificateExpiry); for (const monitor of monitorGroup.monitorList) { const heartbeat = await R.findOne("heartbeat", "monitor_id = ? ORDER BY time DESC", [ monitor.id ]); if (heartbeat) { heartbeats.push({ ...monitor, status: heartbeat.status, time: heartbeat.time }); } } } // calculate RSS feed description let status = StatusPage.overallStatus(heartbeats); let statusDescription = StatusPage.getStatusDescription(status); // keep only DOWN heartbeats in the RSS feed heartbeats = heartbeats.filter(heartbeat => heartbeat.status === DOWN); return { heartbeats, statusDescription }; } /** * Get all status page data in one call * @param {StatusPage} statusPage Status page to get data for * @returns {object} Status page data */ static async getStatusPageData(statusPage) { const config = await statusPage.toPublicJSON(); // Incident let incident = await R.findOne("incident", " pin = 1 AND active = 1 AND status_page_id = ? ", [ statusPage.id, ]); if (incident) { incident = incident.toPublicJSON(); } let maintenanceList = await StatusPage.getMaintenanceList(statusPage.id); // Public Group List const publicGroupList = []; const showTags = !!statusPage.show_tags; const list = await R.find("group", " public = 1 AND status_page_id = ? ORDER BY weight ", [ statusPage.id ]); for (let groupBean of list) { let monitorGroup = await groupBean.toPublicJSON(showTags, config?.showCertificateExpiry); publicGroupList.push(monitorGroup); } // Response return { config, incident, publicGroupList, maintenanceList, }; } /** * Loads domain mapping from DB * Return object like this: { "test-uptime.kuma.pet": "default" } * @returns {Promise<void>} */ static async loadDomainMappingList() { StatusPage.domainMappingList = await R.getAssoc(` SELECT domain, slug FROM status_page, status_page_cname WHERE status_page.id = status_page_cname.status_page_id `); } /** * Send status page list to client * @param {Server} io io Socket server instance * @param {Socket} socket Socket.io instance * @returns {Promise<Bean[]>} Status page list */ static async sendStatusPageList(io, socket) { let result = {}; let list = await R.findAll("status_page", " ORDER BY title "); for (let item of list) { result[item.id] = await item.toJSON(); } io.to(socket.userID).emit("statusPageList", result); return list; } /** * Update list of domain names * @param {string[]} domainNameList List of status page domains * @returns {Promise<void>} */ async updateDomainNameList(domainNameList) { if (!Array.isArray(domainNameList)) { throw new Error("Invalid array"); } let trx = await R.begin(); await trx.exec("DELETE FROM status_page_cname WHERE status_page_id = ?", [ this.id, ]); try { for (let domain of domainNameList) { if (typeof domain !== "string") { throw new Error("Invalid domain"); } if (domain.trim() === "") { continue; } // If the domain name is used in another status page, delete it await trx.exec("DELETE FROM status_page_cname WHERE domain = ?", [ domain, ]); let mapping = trx.dispense("status_page_cname"); mapping.status_page_id = this.id; mapping.domain = domain; await trx.store(mapping); } await trx.commit(); } catch (error) { await trx.rollback(); throw error; } } /** * Get list of domain names * @returns {object[]} List of status page domains */ getDomainNameList() { let domainList = []; for (let domain in StatusPage.domainMappingList) { let s = StatusPage.domainMappingList[domain]; if (this.slug === s) { domainList.push(domain); } } return domainList; } /** * Return an object that ready to parse to JSON * @returns {object} Object ready to parse */ async toJSON() { return { id: this.id, slug: this.slug, title: this.title, description: this.description, icon: this.getIcon(), theme: this.theme, autoRefreshInterval: this.autoRefreshInterval, published: !!this.published, showTags: !!this.show_tags, domainNameList: this.getDomainNameList(), customCSS: this.custom_css, footerText: this.footer_text, showPoweredBy: !!this.show_powered_by, analyticsId: this.analytics_id, analyticsScriptUrl: this.analytics_script_url, analyticsType: this.analytics_type, showCertificateExpiry: !!this.show_certificate_expiry, showOnlyLastHeartbeat: !!this.show_only_last_heartbeat }; } /** * Return an object that ready to parse to JSON for public * Only show necessary data to public * @returns {object} Object ready to parse */ async toPublicJSON() { return { slug: this.slug, title: this.title, description: this.description, icon: this.getIcon(), autoRefreshInterval: this.autoRefreshInterval, theme: this.theme, published: !!this.published, showTags: !!this.show_tags, customCSS: this.custom_css, footerText: this.footer_text, showPoweredBy: !!this.show_powered_by, analyticsId: this.analytics_id, analyticsScriptUrl: this.analytics_script_url, analyticsType: this.analytics_type, showCertificateExpiry: !!this.show_certificate_expiry, showOnlyLastHeartbeat: !!this.show_only_last_heartbeat }; } /** * Convert slug to status page ID * @param {string} slug Status page slug * @returns {Promise<number>} ID of status page */ static async slugToID(slug) { return await R.getCell("SELECT id FROM status_page WHERE slug = ? ", [ slug ]); } /** * Get path to the icon for the page * @returns {string} Path */ getIcon() { if (!this.icon) { return "/icon.svg"; } else { return this.icon; } } /** * Get list of maintenances * @param {number} statusPageId ID of status page to get maintenance for * @returns {object} Object representing maintenances sanitized for public */ static async getMaintenanceList(statusPageId) { try { const publicMaintenanceList = []; let maintenanceIDList = await R.getCol(` SELECT DISTINCT maintenance_id FROM maintenance_status_page WHERE status_page_id = ? `, [ statusPageId ]); for (const maintenanceID of maintenanceIDList) { let maintenance = UptimeKumaServer.getInstance().getMaintenance(maintenanceID); if (maintenance && await maintenance.isUnderMaintenance()) { publicMaintenanceList.push(await maintenance.toPublicJSON()); } } return publicMaintenanceList; } catch (error) { return []; } } } module.exports = StatusPage;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/maintenance.js
server/model/maintenance.js
const { BeanModel } = require("redbean-node/dist/bean-model"); const { parseTimeObject, parseTimeFromTimeObject, log, SQL_DATETIME_FORMAT } = require("../../src/util"); const { R } = require("redbean-node"); const dayjs = require("dayjs"); const Cron = require("croner"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const apicache = require("../modules/apicache"); class Maintenance extends BeanModel { /** * Return an object that ready to parse to JSON for public * Only show necessary data to public * @returns {Promise<object>} Object ready to parse */ async toPublicJSON() { let dateRange = []; if (this.start_date) { dateRange.push(this.start_date); } else { dateRange.push(null); } if (this.end_date) { dateRange.push(this.end_date); } let timeRange = []; let startTime = parseTimeObject(this.start_time); timeRange.push(startTime); let endTime = parseTimeObject(this.end_time); timeRange.push(endTime); let obj = { id: this.id, title: this.title, description: this.description, strategy: this.strategy, intervalDay: this.interval_day, active: !!this.active, dateRange: dateRange, timeRange: timeRange, weekdays: (this.weekdays) ? JSON.parse(this.weekdays) : [], daysOfMonth: (this.days_of_month) ? JSON.parse(this.days_of_month) : [], timeslotList: [], cron: this.cron, duration: this.duration, durationMinutes: parseInt(this.duration / 60), timezone: await this.getTimezone(), // Only valid timezone timezoneOption: this.timezone, // Mainly for dropdown menu, because there is a option "SAME_AS_SERVER" timezoneOffset: await this.getTimezoneOffset(), status: await this.getStatus(), }; if (this.strategy === "manual") { // Do nothing, no timeslots } else if (this.strategy === "single") { obj.timeslotList.push({ startDate: this.start_date, endDate: this.end_date, }); } else { // Should be cron or recurring here if (this.beanMeta.job) { let runningTimeslot = this.getRunningTimeslot(); if (runningTimeslot) { obj.timeslotList.push(runningTimeslot); } let nextRunDate = this.beanMeta.job.nextRun(); if (nextRunDate) { let startDateDayjs = dayjs(nextRunDate); let startDate = startDateDayjs.toISOString(); let endDate = startDateDayjs.add(this.duration, "second").toISOString(); obj.timeslotList.push({ startDate, endDate, }); } } } if (!Array.isArray(obj.weekdays)) { obj.weekdays = []; } if (!Array.isArray(obj.daysOfMonth)) { obj.daysOfMonth = []; } return obj; } /** * Return an object that ready to parse to JSON * @param {string} timezone If not specified, the timeRange will be in UTC * @returns {Promise<object>} Object ready to parse */ async toJSON(timezone = null) { return this.toPublicJSON(timezone); } /** * Get a list of weekdays that the maintenance is active for * Monday=1, Tuesday=2 etc. * @returns {number[]} Array of active weekdays */ getDayOfWeekList() { log.debug("timeslot", "List: " + this.weekdays); return JSON.parse(this.weekdays).sort(function (a, b) { return a - b; }); } /** * Get a list of days in month that maintenance is active for * @returns {number[]|string[]} Array of active days in month */ getDayOfMonthList() { return JSON.parse(this.days_of_month).sort(function (a, b) { return a - b; }); } /** * Get the duration of maintenance in seconds * @returns {number} Duration of maintenance */ calcDuration() { let duration = dayjs.utc(this.end_time, "HH:mm").diff(dayjs.utc(this.start_time, "HH:mm"), "second"); // Add 24hours if it is across day if (duration < 0) { duration += 24 * 3600; } return duration; } /** * Convert data from socket to bean * @param {Bean} bean Bean to fill in * @param {object} obj Data to fill bean with * @returns {Promise<Bean>} Filled bean */ static async jsonToBean(bean, obj) { if (obj.id) { bean.id = obj.id; } bean.title = obj.title; bean.description = obj.description; bean.strategy = obj.strategy; bean.interval_day = obj.intervalDay; bean.timezone = obj.timezoneOption; bean.active = obj.active; if (obj.dateRange[0]) { const parsedDate = new Date(obj.dateRange[0]); if (isNaN(parsedDate.getTime()) || parsedDate.getFullYear() > 9999) { throw new Error("Invalid start date"); } bean.start_date = obj.dateRange[0]; } else { bean.start_date = null; } if (obj.dateRange[1]) { const parsedDate = new Date(obj.dateRange[1]); if (isNaN(parsedDate.getTime()) || parsedDate.getFullYear() > 9999) { throw new Error("Invalid end date"); } bean.end_date = obj.dateRange[1]; } else { bean.end_date = null; } if (bean.strategy === "cron") { bean.duration = obj.durationMinutes * 60; bean.cron = obj.cron; this.validateCron(bean.cron); } if (bean.strategy.startsWith("recurring-")) { bean.start_time = parseTimeFromTimeObject(obj.timeRange[0]); bean.end_time = parseTimeFromTimeObject(obj.timeRange[1]); bean.weekdays = JSON.stringify(obj.weekdays); bean.days_of_month = JSON.stringify(obj.daysOfMonth); await bean.generateCron(); this.validateCron(bean.cron); } return bean; } /** * Throw error if cron is invalid * @param {string|Date} cron Pattern or date * @returns {void} */ static validateCron(cron) { let job = new Cron(cron, () => { }); job.stop(); } /** * Run the cron * @param {boolean} throwError Should an error be thrown on failure * @returns {Promise<void>} */ async run(throwError = false) { if (this.beanMeta.job) { log.debug("maintenance", "Maintenance is already running, stop it first. id: " + this.id); this.stop(); } log.debug("maintenance", "Run maintenance id: " + this.id); // 1.21.2 migration if (!this.cron) { await this.generateCron(); if (!this.timezone) { this.timezone = "UTC"; } if (this.cron) { await R.store(this); } } if (this.strategy === "manual") { // Do nothing, because it is controlled by the user } else if (this.strategy === "single") { this.beanMeta.job = new Cron(this.start_date, { timezone: await this.getTimezone() }, () => { log.info("maintenance", "Maintenance id: " + this.id + " is under maintenance now"); UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id); apicache.clear(); }); } else if (this.cron != null) { let current = dayjs(); // Here should be cron or recurring try { this.beanMeta.status = "scheduled"; let startEvent = async (customDuration = 0) => { log.info("maintenance", "Maintenance id: " + this.id + " is under maintenance now"); this.beanMeta.status = "under-maintenance"; clearTimeout(this.beanMeta.durationTimeout); let duration = this.inferDuration(customDuration); UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id); this.beanMeta.durationTimeout = setTimeout(() => { // End of maintenance for this timeslot this.beanMeta.status = "scheduled"; UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id); }, duration); // Set last start date to current time this.last_start_date = current.utc().format(SQL_DATETIME_FORMAT); await R.store(this); }; // Create Cron if (this.strategy === "recurring-interval") { // For recurring-interval, Croner needs to have interval and startAt const startDate = dayjs(this.startDate); const [ hour, minute ] = this.startTime.split(":"); const startDateTime = startDate.hour(hour).minute(minute); // Fix #6118, since the startDateTime is optional, it will throw error if the date is null when using toISOString() let startAt = undefined; try { startAt = startDateTime.toISOString(); } catch (_) {} this.beanMeta.job = new Cron(this.cron, { timezone: await this.getTimezone(), startAt, }, () => { if (!this.lastStartDate || this.interval_day === 1) { return startEvent(); } // If last start date is set, it means the maintenance has been started before let lastStartDate = dayjs(this.lastStartDate) .subtract(1.1, "hour"); // Subtract 1.1 hour to avoid issues with timezone differences // Check if the interval is enough if (current.diff(lastStartDate, "day") < this.interval_day) { log.debug("maintenance", "Maintenance id: " + this.id + " is still in the window, skipping start event"); return; } log.debug("maintenance", "Maintenance id: " + this.id + " is not in the window, starting event"); return startEvent(); }); } else { this.beanMeta.job = new Cron(this.cron, { timezone: await this.getTimezone(), }, startEvent); } // Continue if the maintenance is still in the window let runningTimeslot = this.getRunningTimeslot(); if (runningTimeslot) { let duration = dayjs(runningTimeslot.endDate).diff(current, "second") * 1000; log.debug("maintenance", "Maintenance id: " + this.id + " Remaining duration: " + duration + "ms"); startEvent(duration); } } catch (e) { log.error("maintenance", "Error in maintenance id: " + this.id); log.error("maintenance", "Cron: " + this.cron); log.error("maintenance", e); if (throwError) { throw e; } } } else { log.error("maintenance", "Maintenance id: " + this.id + " has no cron"); } } /** * Get timeslots where maintenance is running * @returns {object|null} Maintenance time slot */ getRunningTimeslot() { let start = dayjs(this.beanMeta.job.nextRun(dayjs().add(-this.duration, "second").toDate())); let end = start.add(this.duration, "second"); let current = dayjs(); if (current.isAfter(start) && current.isBefore(end)) { return { startDate: start.toISOString(), endDate: end.toISOString(), }; } else { return null; } } /** * Calculate the maintenance duration * @param {number} customDuration - The custom duration in milliseconds. * @returns {number} The inferred duration in milliseconds. */ inferDuration(customDuration) { // Check if duration is still in the window. If not, use the duration from the current time to the end of the window if (customDuration > 0) { return customDuration; } else if (this.end_date) { let d = dayjs(this.end_date).diff(dayjs(), "second"); if (d < this.duration) { return d * 1000; } } return this.duration * 1000; } /** * Stop the maintenance * @returns {void} */ stop() { if (this.beanMeta.job) { this.beanMeta.job.stop(); delete this.beanMeta.job; } } /** * Is this maintenance currently active * @returns {Promise<boolean>} The maintenance is active? */ async isUnderMaintenance() { return (await this.getStatus()) === "under-maintenance"; } /** * Get the timezone of the maintenance * @returns {Promise<string>} timezone */ async getTimezone() { if (!this.timezone || this.timezone === "SAME_AS_SERVER") { return await UptimeKumaServer.getInstance().getTimezone(); } return this.timezone; } /** * Get offset for timezone * @returns {Promise<string>} offset */ async getTimezoneOffset() { return dayjs.tz(dayjs(), await this.getTimezone()).format("Z"); } /** * Get the current status of the maintenance * @returns {Promise<string>} Current status */ async getStatus() { if (!this.active) { return "inactive"; } if (this.strategy === "manual") { return "under-maintenance"; } // Check if the maintenance is started if (this.start_date && dayjs().isBefore(dayjs.tz(this.start_date, await this.getTimezone()))) { return "scheduled"; } // Check if the maintenance is ended if (this.end_date && dayjs().isAfter(dayjs.tz(this.end_date, await this.getTimezone()))) { return "ended"; } if (this.strategy === "single") { return "under-maintenance"; } if (!this.beanMeta.status) { return "unknown"; } return this.beanMeta.status; } /** * Generate Cron for recurring maintenance * @returns {Promise<void>} */ async generateCron() { log.info("maintenance", "Generate cron for maintenance id: " + this.id); if (this.strategy === "cron") { // Do nothing for cron } else if (!this.strategy.startsWith("recurring-")) { this.cron = ""; } else if (this.strategy === "recurring-interval") { // For intervals, the pattern is used to check if the execution should be started let array = this.start_time.split(":"); let hour = parseInt(array[0]); let minute = parseInt(array[1]); this.cron = `${minute} ${hour} * * *`; this.duration = this.calcDuration(); log.debug("maintenance", "Cron: " + this.cron); log.debug("maintenance", "Duration: " + this.duration); } else if (this.strategy === "recurring-weekday") { let list = this.getDayOfWeekList(); let array = this.start_time.split(":"); let hour = parseInt(array[0]); let minute = parseInt(array[1]); this.cron = minute + " " + hour + " * * " + list.join(","); this.duration = this.calcDuration(); } else if (this.strategy === "recurring-day-of-month") { let list = this.getDayOfMonthList(); let array = this.start_time.split(":"); let hour = parseInt(array[0]); let minute = parseInt(array[1]); let dayList = []; for (let day of list) { if (typeof day === "string" && day.startsWith("lastDay")) { if (day === "lastDay1") { dayList.push("L"); } // Unfortunately, lastDay2-4 is not supported by cron } else { dayList.push(day); } } // Remove duplicate dayList = [ ...new Set(dayList) ]; this.cron = minute + " " + hour + " " + dayList.join(",") + " * *"; this.duration = this.calcDuration(); } } } module.exports = Maintenance;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/incident.js
server/model/incident.js
const { BeanModel } = require("redbean-node/dist/bean-model"); class Incident extends BeanModel { /** * Return an object that ready to parse to JSON for public * Only show necessary data to public * @returns {object} Object ready to parse */ toPublicJSON() { return { id: this.id, style: this.style, title: this.title, content: this.content, pin: this.pin, createdDate: this.createdDate, lastUpdatedDate: this.lastUpdatedDate, }; } } module.exports = Incident;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/group.js
server/model/group.js
const { BeanModel } = require("redbean-node/dist/bean-model"); const { R } = require("redbean-node"); class Group extends BeanModel { /** * Return an object that ready to parse to JSON for public Only show * necessary data to public * @param {boolean} showTags Should the JSON include monitor tags * @param {boolean} certExpiry Should JSON include info about * certificate expiry? * @returns {Promise<object>} Object ready to parse */ async toPublicJSON(showTags = false, certExpiry = false) { let monitorBeanList = await this.getMonitorList(); let monitorList = []; for (let bean of monitorBeanList) { monitorList.push(await bean.toPublicJSON(showTags, certExpiry)); } return { id: this.id, name: this.name, weight: this.weight, monitorList, }; } /** * Get all monitors * @returns {Promise<Bean[]>} List of monitors */ async getMonitorList() { return R.convertToBeans("monitor", await R.getAll(` SELECT monitor.*, monitor_group.send_url, monitor_group.custom_url FROM monitor, monitor_group WHERE monitor.id = monitor_group.monitor_id AND group_id = ? ORDER BY monitor_group.weight `, [ this.id, ])); } } module.exports = Group;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/remote_browser.js
server/model/remote_browser.js
const { BeanModel } = require("redbean-node/dist/bean-model"); class RemoteBrowser extends BeanModel { /** * Returns an object that ready to parse to JSON * @returns {object} Object ready to parse */ toJSON() { return { id: this.id, url: this.url, name: this.name, }; } } module.exports = RemoteBrowser;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/api_key.js
server/model/api_key.js
const { BeanModel } = require("redbean-node/dist/bean-model"); const { R } = require("redbean-node"); const dayjs = require("dayjs"); class APIKey extends BeanModel { /** * Get the current status of this API key * @returns {string} active, inactive or expired */ getStatus() { let current = dayjs(); let expiry = dayjs(this.expires); if (expiry.diff(current) < 0) { return "expired"; } return this.active ? "active" : "inactive"; } /** * Returns an object that ready to parse to JSON * @returns {object} Object ready to parse */ toJSON() { return { id: this.id, key: this.key, name: this.name, userID: this.user_id, createdDate: this.created_date, active: this.active, expires: this.expires, status: this.getStatus(), }; } /** * Returns an object that ready to parse to JSON with sensitive fields * removed * @returns {object} Object ready to parse */ toPublicJSON() { return { id: this.id, name: this.name, userID: this.user_id, createdDate: this.created_date, active: this.active, expires: this.expires, status: this.getStatus(), }; } /** * Create a new API Key and store it in the database * @param {object} key Object sent by client * @param {int} userID ID of socket user * @returns {Promise<bean>} API key */ static async save(key, userID) { let bean; bean = R.dispense("api_key"); bean.key = key.key; bean.name = key.name; bean.user_id = userID; bean.active = key.active; bean.expires = key.expires; await R.store(bean); return bean; } } module.exports = APIKey;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/monitor.js
server/model/monitor.js
const dayjs = require("dayjs"); const axios = require("axios"); const { Prometheus } = require("../prometheus"); const { log, UP, DOWN, PENDING, MAINTENANCE, flipStatus, MAX_INTERVAL_SECOND, MIN_INTERVAL_SECOND, SQL_DATETIME_FORMAT, evaluateJsonQuery, PING_PACKET_SIZE_MIN, PING_PACKET_SIZE_MAX, PING_PACKET_SIZE_DEFAULT, PING_GLOBAL_TIMEOUT_MIN, PING_GLOBAL_TIMEOUT_MAX, PING_GLOBAL_TIMEOUT_DEFAULT, PING_COUNT_MIN, PING_COUNT_MAX, PING_COUNT_DEFAULT, PING_PER_REQUEST_TIMEOUT_MIN, PING_PER_REQUEST_TIMEOUT_MAX, PING_PER_REQUEST_TIMEOUT_DEFAULT } = require("../../src/util"); const { ping, checkCertificate, checkStatusCode, getTotalClientInRoom, setting, mysqlQuery, setSetting, httpNtlm, radius, kafkaProducerAsync, getOidcTokenClientCredentials, rootCertificatesFingerprints, axiosAbortSignal, checkCertificateHostname } = require("../util-server"); const { R } = require("redbean-node"); const { BeanModel } = require("redbean-node/dist/bean-model"); const { Notification } = require("../notification"); const { Proxy } = require("../proxy"); const { demoMode } = require("../config"); const version = require("../../package.json").version; const apicache = require("../modules/apicache"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const { DockerHost } = require("../docker"); const jwt = require("jsonwebtoken"); const crypto = require("crypto"); const { UptimeCalculator } = require("../uptime-calculator"); const { CookieJar } = require("tough-cookie"); const { HttpsCookieAgent } = require("http-cookie-agent/http"); const https = require("https"); const http = require("http"); const DomainExpiry = require("./domain_expiry"); const rootCertificates = rootCertificatesFingerprints(); /** * status: * 0 = DOWN * 1 = UP * 2 = PENDING * 3 = MAINTENANCE */ class Monitor extends BeanModel { /** * Return an object that ready to parse to JSON for public Only show * necessary data to public * @param {boolean} showTags Include tags in JSON * @param {boolean} certExpiry Include certificate expiry info in * JSON * @returns {Promise<object>} Object ready to parse */ async toPublicJSON(showTags = false, certExpiry = false) { let obj = { id: this.id, name: this.name, sendUrl: this.sendUrl, type: this.type, }; if (this.sendUrl) { obj.url = this.customUrl ?? this.url; } if (showTags) { obj.tags = await this.getTags(); } if (certExpiry && (this.type === "http" || this.type === "keyword" || this.type === "json-query") && this.getURLProtocol() === "https:") { const { certExpiryDaysRemaining, validCert } = await this.getCertExpiry(this.id); obj.certExpiryDaysRemaining = certExpiryDaysRemaining; obj.validCert = validCert; } return obj; } /** * Return an object that ready to parse to JSON * @param {object} preloadData to prevent n+1 problems, we query the data in a batch outside of this function * @param {boolean} includeSensitiveData Include sensitive data in * JSON * @returns {object} Object ready to parse */ toJSON(preloadData = {}, includeSensitiveData = true) { let screenshot = null; if (this.type === "real-browser") { screenshot = "/screenshots/" + jwt.sign(this.id, UptimeKumaServer.getInstance().jwtSecret) + ".png"; } const path = preloadData.paths.get(this.id) || []; const pathName = path.join(" / "); let data = { id: this.id, name: this.name, description: this.description, path, pathName, parent: this.parent, childrenIDs: preloadData.childrenIDs.get(this.id) || [], url: this.url, wsIgnoreSecWebsocketAcceptHeader: this.getWsIgnoreSecWebsocketAcceptHeader(), wsSubprotocol: this.wsSubprotocol, method: this.method, hostname: this.hostname, port: this.port, maxretries: this.maxretries, weight: this.weight, active: preloadData.activeStatus.get(this.id), forceInactive: preloadData.forceInactive.get(this.id), type: this.type, timeout: this.timeout, interval: this.interval, retryInterval: this.retryInterval, resendInterval: this.resendInterval, keyword: this.keyword, invertKeyword: this.isInvertKeyword(), expiryNotification: this.isEnabledExpiryNotification(), domainExpiryNotification: Boolean(this.domainExpiryNotification), ignoreTls: this.getIgnoreTls(), upsideDown: this.isUpsideDown(), packetSize: this.packetSize, maxredirects: this.maxredirects, accepted_statuscodes: this.getAcceptedStatuscodes(), dns_resolve_type: this.dns_resolve_type, dns_resolve_server: this.dns_resolve_server, dns_last_result: this.dns_last_result, docker_container: this.docker_container, docker_host: this.docker_host, proxyId: this.proxy_id, notificationIDList: preloadData.notifications.get(this.id) || {}, tags: preloadData.tags.get(this.id) || [], maintenance: preloadData.maintenanceStatus.get(this.id), mqttTopic: this.mqttTopic, mqttSuccessMessage: this.mqttSuccessMessage, mqttCheckType: this.mqttCheckType, databaseQuery: this.databaseQuery, authMethod: this.authMethod, grpcUrl: this.grpcUrl, grpcProtobuf: this.grpcProtobuf, grpcMethod: this.grpcMethod, grpcServiceName: this.grpcServiceName, grpcEnableTls: this.getGrpcEnableTls(), radiusCalledStationId: this.radiusCalledStationId, radiusCallingStationId: this.radiusCallingStationId, game: this.game, gamedigGivenPortOnly: this.getGameDigGivenPortOnly(), httpBodyEncoding: this.httpBodyEncoding, jsonPath: this.jsonPath, expectedValue: this.expectedValue, system_service_name: this.system_service_name, kafkaProducerTopic: this.kafkaProducerTopic, kafkaProducerBrokers: JSON.parse(this.kafkaProducerBrokers), kafkaProducerSsl: this.getKafkaProducerSsl(), kafkaProducerAllowAutoTopicCreation: this.getKafkaProducerAllowAutoTopicCreation(), kafkaProducerMessage: this.kafkaProducerMessage, screenshot, cacheBust: this.getCacheBust(), remote_browser: this.remote_browser, snmpOid: this.snmpOid, jsonPathOperator: this.jsonPathOperator, snmpVersion: this.snmpVersion, smtpSecurity: this.smtpSecurity, rabbitmqNodes: JSON.parse(this.rabbitmqNodes), conditions: JSON.parse(this.conditions), ipFamily: this.ipFamily, // ping advanced options ping_numeric: this.isPingNumeric(), ping_count: this.ping_count, ping_per_request_timeout: this.ping_per_request_timeout, }; if (includeSensitiveData) { data = { ...data, headers: this.headers, body: this.body, grpcBody: this.grpcBody, grpcMetadata: this.grpcMetadata, basic_auth_user: this.basic_auth_user, basic_auth_pass: this.basic_auth_pass, oauth_client_id: this.oauth_client_id, oauth_client_secret: this.oauth_client_secret, oauth_token_url: this.oauth_token_url, oauth_scopes: this.oauth_scopes, oauth_audience: this.oauth_audience, oauth_auth_method: this.oauth_auth_method, pushToken: this.pushToken, databaseConnectionString: this.databaseConnectionString, radiusUsername: this.radiusUsername, radiusPassword: this.radiusPassword, radiusSecret: this.radiusSecret, mqttUsername: this.mqttUsername, mqttPassword: this.mqttPassword, mqttWebsocketPath: this.mqttWebsocketPath, authWorkstation: this.authWorkstation, authDomain: this.authDomain, tlsCa: this.tlsCa, tlsCert: this.tlsCert, tlsKey: this.tlsKey, kafkaProducerSaslOptions: JSON.parse(this.kafkaProducerSaslOptions), rabbitmqUsername: this.rabbitmqUsername, rabbitmqPassword: this.rabbitmqPassword, }; } data.includeSensitiveData = includeSensitiveData; return data; } /** * Get all tags applied to this monitor * @returns {Promise<LooseObject<any>[]>} List of tags on the * monitor */ async getTags() { return await R.getAll("SELECT mt.*, tag.name, tag.color FROM monitor_tag mt JOIN tag ON mt.tag_id = tag.id WHERE mt.monitor_id = ? ORDER BY tag.name", [ this.id ]); } /** * Gets certificate expiry for this monitor * @param {number} monitorID ID of monitor to send * @returns {Promise<LooseObject<any>>} Certificate expiry info for * monitor */ async getCertExpiry(monitorID) { let tlsInfoBean = await R.findOne("monitor_tls_info", "monitor_id = ?", [ monitorID, ]); let tlsInfo; if (tlsInfoBean) { tlsInfo = JSON.parse(tlsInfoBean?.info_json); if (tlsInfo?.valid && tlsInfo?.certInfo?.daysRemaining) { return { certExpiryDaysRemaining: tlsInfo.certInfo.daysRemaining, validCert: true }; } } return { certExpiryDaysRemaining: "", validCert: false }; } /** * Encode user and password to Base64 encoding * for HTTP "basic" auth, as per RFC-7617 * @param {string|null} user - The username (nullable if not changed by a user) * @param {string|null} pass - The password (nullable if not changed by a user) * @returns {string} Encoded Base64 string */ encodeBase64(user, pass) { return Buffer.from(`${user || ""}:${pass || ""}`).toString("base64"); } /** * Is the TLS expiry notification enabled? * @returns {boolean} Enabled? */ isEnabledExpiryNotification() { return Boolean(this.expiryNotification); } /** * Check if ping should use numeric output only * @returns {boolean} True if IP addresses will be output instead of symbolic hostnames */ isPingNumeric() { return Boolean(this.ping_numeric); } /** * Parse to boolean * @returns {boolean} Should TLS errors be ignored? */ getIgnoreTls() { return Boolean(this.ignoreTls); } /** * Parse to boolean * @returns {boolean} Should WS headers be ignored? */ getWsIgnoreSecWebsocketAcceptHeader() { return Boolean(this.wsIgnoreSecWebsocketAcceptHeader); } /** * Parse to boolean * @returns {boolean} Is the monitor in upside down mode? */ isUpsideDown() { return Boolean(this.upsideDown); } /** * Parse to boolean * @returns {boolean} Invert keyword match? */ isInvertKeyword() { return Boolean(this.invertKeyword); } /** * Parse to boolean * @returns {boolean} Enable TLS for gRPC? */ getGrpcEnableTls() { return Boolean(this.grpcEnableTls); } /** * Parse to boolean * @returns {boolean} if cachebusting is enabled */ getCacheBust() { return Boolean(this.cacheBust); } /** * Get accepted status codes * @returns {object} Accepted status codes */ getAcceptedStatuscodes() { return JSON.parse(this.accepted_statuscodes_json); } /** * Get if game dig should only use the port which was provided * @returns {boolean} gamedig should only use the provided port */ getGameDigGivenPortOnly() { return Boolean(this.gamedigGivenPortOnly); } /** * Parse to boolean * @returns {boolean} Kafka Producer Ssl enabled? */ getKafkaProducerSsl() { return Boolean(this.kafkaProducerSsl); } /** * Parse to boolean * @returns {boolean} Kafka Producer Allow Auto Topic Creation Enabled? */ getKafkaProducerAllowAutoTopicCreation() { return Boolean(this.kafkaProducerAllowAutoTopicCreation); } /** * Start monitor * @param {Server} io Socket server instance * @returns {Promise<void>} */ async start(io) { let previousBeat = null; let retries = 0; try { this.prometheus = new Prometheus(this, await this.getTags()); } catch (e) { log.error("prometheus", "Please submit an issue to our GitHub repo. Prometheus update error: ", e.message); } const beat = async () => { let beatInterval = this.interval; if (! beatInterval) { beatInterval = 1; } if (demoMode) { if (beatInterval < 20) { console.log("beat interval too low, reset to 20s"); beatInterval = 20; } } // Expose here for prometheus update // undefined if not https let tlsInfo = undefined; if (!previousBeat || this.type === "push") { previousBeat = await R.findOne("heartbeat", " monitor_id = ? ORDER BY time DESC", [ this.id, ]); if (previousBeat) { retries = previousBeat.retries; } } const isFirstBeat = !previousBeat; let bean = R.dispense("heartbeat"); bean.monitor_id = this.id; bean.time = R.isoDateTimeMillis(dayjs.utc()); bean.status = DOWN; bean.downCount = previousBeat?.downCount || 0; if (this.isUpsideDown()) { bean.status = flipStatus(bean.status); } // Runtime patch timeout if it is 0 // See https://github.com/louislam/uptime-kuma/pull/3961#issuecomment-1804149144 if (!this.timeout || this.timeout <= 0) { this.timeout = this.interval * 1000 * 0.8; } try { if (await Monitor.isUnderMaintenance(this.id)) { bean.msg = "Monitor under maintenance"; bean.status = MAINTENANCE; } else if (this.type === "http" || this.type === "keyword" || this.type === "json-query") { // Do not do any queries/high loading things before the "bean.ping" let startTime = dayjs().valueOf(); // HTTP basic auth let basicAuthHeader = {}; if (this.auth_method === "basic") { basicAuthHeader = { "Authorization": "Basic " + this.encodeBase64(this.basic_auth_user, this.basic_auth_pass), }; } // OIDC: Basic client credential flow. // Additional grants might be implemented in the future let oauth2AuthHeader = {}; if (this.auth_method === "oauth2-cc") { try { if (this.oauthAccessToken === undefined || new Date(this.oauthAccessToken.expires_at * 1000) <= new Date()) { this.oauthAccessToken = await this.makeOidcTokenClientCredentialsRequest(); } oauth2AuthHeader = { "Authorization": this.oauthAccessToken.token_type + " " + this.oauthAccessToken.access_token, }; } catch (e) { throw new Error("The oauth config is invalid. " + e.message); } } let agentFamily = undefined; if (this.ipFamily === "ipv4") { agentFamily = 4; } if (this.ipFamily === "ipv6") { agentFamily = 6; } const httpsAgentOptions = { maxCachedSessions: 0, // Use Custom agent to disable session reuse (https://github.com/nodejs/node/issues/3940) rejectUnauthorized: !this.getIgnoreTls(), secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT, autoSelectFamily: true, ...(agentFamily ? { family: agentFamily } : {}) }; const httpAgentOptions = { maxCachedSessions: 0, autoSelectFamily: true, ...(agentFamily ? { family: agentFamily } : {}) }; log.debug("monitor", `[${this.name}] Prepare Options for axios`); let contentType = null; let bodyValue = null; if (this.body && (typeof this.body === "string" && this.body.trim().length > 0)) { if (!this.httpBodyEncoding || this.httpBodyEncoding === "json") { try { bodyValue = JSON.parse(this.body); contentType = "application/json"; } catch (e) { throw new Error("Your JSON body is invalid. " + e.message); } } else if (this.httpBodyEncoding === "form") { bodyValue = this.body; contentType = "application/x-www-form-urlencoded"; } else if (this.httpBodyEncoding === "xml") { bodyValue = this.body; contentType = "text/xml; charset=utf-8"; } } // Axios Options const options = { url: this.url, method: (this.method || "get").toLowerCase(), timeout: this.timeout * 1000, headers: { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", ...(contentType ? { "Content-Type": contentType } : {}), ...(basicAuthHeader), ...(oauth2AuthHeader), ...(this.headers ? JSON.parse(this.headers) : {}) }, maxRedirects: this.maxredirects, validateStatus: (status) => { return checkStatusCode(status, this.getAcceptedStatuscodes()); }, signal: axiosAbortSignal((this.timeout + 10) * 1000), }; if (bodyValue) { options.data = bodyValue; } if (this.cacheBust) { const randomFloatString = Math.random().toString(36); const cacheBust = randomFloatString.substring(2); options.params = { uptime_kuma_cachebuster: cacheBust, }; } if (this.proxy_id) { const proxy = await R.load("proxy", this.proxy_id); if (proxy && proxy.active) { const { httpAgent, httpsAgent } = Proxy.createAgents(proxy, { httpsAgentOptions: httpsAgentOptions, httpAgentOptions: httpAgentOptions, }); options.proxy = false; options.httpAgent = httpAgent; options.httpsAgent = httpsAgent; } } if (!options.httpAgent) { options.httpAgent = new http.Agent(httpAgentOptions); } if (!options.httpsAgent) { let jar = new CookieJar(); let httpsCookieAgentOptions = { ...httpsAgentOptions, cookies: { jar } }; options.httpsAgent = new HttpsCookieAgent(httpsCookieAgentOptions); } if (this.auth_method === "mtls") { if (this.tlsCert !== null && this.tlsCert !== "") { options.httpsAgent.options.cert = Buffer.from(this.tlsCert); } if (this.tlsCa !== null && this.tlsCa !== "") { options.httpsAgent.options.ca = Buffer.from(this.tlsCa); } if (this.tlsKey !== null && this.tlsKey !== "") { options.httpsAgent.options.key = Buffer.from(this.tlsKey); } } let tlsInfo = {}; // Store tlsInfo when secureConnect event is emitted // The keylog event listener is a workaround to access the tlsSocket options.httpsAgent.once("keylog", async (line, tlsSocket) => { tlsSocket.once("secureConnect", async () => { tlsInfo = checkCertificate(tlsSocket); tlsInfo.valid = tlsSocket.authorized || false; tlsInfo.hostnameMatchMonitorUrl = checkCertificateHostname(tlsInfo.certInfo.raw, this.getUrl()?.hostname); await this.handleTlsInfo(tlsInfo); }); }); log.debug("monitor", `[${this.name}] Axios Options: ${JSON.stringify(options)}`); log.debug("monitor", `[${this.name}] Axios Request`); // Make Request let res = await this.makeAxiosRequest(options); bean.msg = `${res.status} - ${res.statusText}`; bean.ping = dayjs().valueOf() - startTime; // fallback for if kelog event is not emitted, but we may still have tlsInfo, // e.g. if the connection is made through a proxy if (this.getUrl()?.protocol === "https:" && tlsInfo.valid === undefined) { const tlsSocket = res.request.res.socket; if (tlsSocket) { tlsInfo = checkCertificate(tlsSocket); tlsInfo.valid = tlsSocket.authorized || false; tlsInfo.hostnameMatchMonitorUrl = checkCertificateHostname(tlsInfo.certInfo.raw, this.getUrl()?.hostname); await this.handleTlsInfo(tlsInfo); } } // eslint-disable-next-line eqeqeq if (process.env.UPTIME_KUMA_LOG_RESPONSE_BODY_MONITOR_ID == this.id) { log.info("monitor", res.data); } if (this.type === "http") { bean.status = UP; } else if (this.type === "keyword") { let data = res.data; // Convert to string for object/array if (typeof data !== "string") { data = JSON.stringify(data); } let keywordFound = data.includes(this.keyword); if (keywordFound === !this.isInvertKeyword()) { bean.msg += ", keyword " + (keywordFound ? "is" : "not") + " found"; bean.status = UP; } else { data = data.replace(/<[^>]*>?|[\n\r]|\s+/gm, " ").trim(); if (data.length > 50) { data = data.substring(0, 47) + "..."; } throw new Error(bean.msg + ", but keyword is " + (keywordFound ? "present" : "not") + " in [" + data + "]"); } } else if (this.type === "json-query") { let data = res.data; const { status, response } = await evaluateJsonQuery(data, this.jsonPath, this.jsonPathOperator, this.expectedValue); if (status) { bean.status = UP; bean.msg = `JSON query passes (comparing ${response} ${this.jsonPathOperator} ${this.expectedValue})`; } else { throw new Error(`JSON query does not pass (comparing ${response} ${this.jsonPathOperator} ${this.expectedValue})`); } } } else if (this.type === "ping") { bean.ping = await ping(this.hostname, this.ping_count, "", this.ping_numeric, this.packetSize, this.timeout, this.ping_per_request_timeout); bean.msg = ""; bean.status = UP; } else if (this.type === "push") { // Type: Push log.debug("monitor", `[${this.name}] Checking monitor at ${dayjs().format("YYYY-MM-DD HH:mm:ss.SSS")}`); const bufferTime = 1000; // 1s buffer to accommodate clock differences if (previousBeat) { const msSinceLastBeat = dayjs.utc().valueOf() - dayjs.utc(previousBeat.time).valueOf(); log.debug("monitor", `[${this.name}] msSinceLastBeat = ${msSinceLastBeat}`); // If the previous beat was down or pending we use the regular // beatInterval/retryInterval in the setTimeout further below if (previousBeat.status !== (this.isUpsideDown() ? DOWN : UP) || msSinceLastBeat > beatInterval * 1000 + bufferTime) { bean.duration = Math.round(msSinceLastBeat / 1000); throw new Error("No heartbeat in the time window"); } else { let timeout = beatInterval * 1000 - msSinceLastBeat; if (timeout < 0) { timeout = bufferTime; } else { timeout += bufferTime; } // No need to insert successful heartbeat for push type, so end here retries = 0; log.debug("monitor", `[${this.name}] timeout = ${timeout}`); this.heartbeatInterval = setTimeout(safeBeat, timeout); return; } } else { bean.duration = beatInterval; throw new Error("No heartbeat in the time window"); } } else if (this.type === "steam") { const steamApiUrl = "https://api.steampowered.com/IGameServersService/GetServerList/v1/"; const steamAPIKey = await setting("steamAPIKey"); const filter = `addr\\${this.hostname}:${this.port}`; if (!steamAPIKey) { throw new Error("Steam API Key not found"); } let res = await axios.get(steamApiUrl, { timeout: this.timeout * 1000, headers: { "Accept": "*/*", }, httpsAgent: new https.Agent({ maxCachedSessions: 0, // Use Custom agent to disable session reuse (https://github.com/nodejs/node/issues/3940) rejectUnauthorized: !this.getIgnoreTls(), secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT, }), httpAgent: new http.Agent({ maxCachedSessions: 0, }), maxRedirects: this.maxredirects, validateStatus: (status) => { return checkStatusCode(status, this.getAcceptedStatuscodes()); }, params: { filter: filter, key: steamAPIKey, } }); if (res.data.response && res.data.response.servers && res.data.response.servers.length > 0) { bean.status = UP; bean.msg = res.data.response.servers[0].name; try { bean.ping = await ping(this.hostname, PING_COUNT_DEFAULT, "", true, this.packetSize, PING_GLOBAL_TIMEOUT_DEFAULT, PING_PER_REQUEST_TIMEOUT_DEFAULT); } catch (_) { } } else { throw new Error("Server not found on Steam"); } } else if (this.type === "docker") { log.debug("monitor", `[${this.name}] Prepare Options for Axios`); const options = { url: `/containers/${this.docker_container}/json`, timeout: this.interval * 1000 * 0.8, headers: { "Accept": "*/*", }, httpsAgent: new https.Agent({ maxCachedSessions: 0, // Use Custom agent to disable session reuse (https://github.com/nodejs/node/issues/3940) rejectUnauthorized: !this.getIgnoreTls(), secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT, }), httpAgent: new http.Agent({ maxCachedSessions: 0, }), }; const dockerHost = await R.load("docker_host", this.docker_host); if (!dockerHost) { throw new Error("Failed to load docker host config"); } if (dockerHost._dockerType === "socket") { options.socketPath = dockerHost._dockerDaemon; } else if (dockerHost._dockerType === "tcp") { options.baseURL = DockerHost.patchDockerURL(dockerHost._dockerDaemon); options.httpsAgent = new https.Agent( await DockerHost.getHttpsAgentOptions(dockerHost._dockerType, options.baseURL) ); } log.debug("monitor", `[${this.name}] Axios Request`); let res = await axios.request(options); if (res.data.State.Running) { if (res.data.State.Health.Status === "healthy") { bean.status = UP; bean.msg = res.data.State.Health ? res.data.State.Health.Status : res.data.State.Status; } else if (res.data.State.Health.Status === "unhealthy") { throw Error("Container State is unhealthy"); } else {
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
true
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/tag.js
server/model/tag.js
const { BeanModel } = require("redbean-node/dist/bean-model"); class Tag extends BeanModel { /** * Return an object that ready to parse to JSON * @returns {object} Object ready to parse */ toJSON() { return { id: this._id, name: this._name, color: this._color, }; } } module.exports = Tag;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/model/heartbeat.js
server/model/heartbeat.js
const { BeanModel } = require("redbean-node/dist/bean-model"); /** * status: * 0 = DOWN * 1 = UP * 2 = PENDING * 3 = MAINTENANCE */ class Heartbeat extends BeanModel { /** * Return an object that ready to parse to JSON for public * Only show necessary data to public * @returns {object} Object ready to parse */ toPublicJSON() { return { status: this.status, time: this.time, msg: "", // Hide for public ping: this.ping, }; } /** * Return an object that ready to parse to JSON * @returns {object} Object ready to parse */ toJSON() { return { monitorID: this._monitorId, status: this._status, time: this._time, msg: this._msg, ping: this._ping, important: this._important, duration: this._duration, retries: this._retries, }; } } module.exports = Heartbeat;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/home-assistant.js
server/notification-providers/home-assistant.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const defaultNotificationService = "notify"; class HomeAssistant extends NotificationProvider { name = "HomeAssistant"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const notificationService = notification?.notificationService || defaultNotificationService; try { let config = { headers: { Authorization: `Bearer ${notification.longLivedAccessToken}`, "Content-Type": "application/json", }, }; config = this.getAxiosConfigWithProxy(config); await axios.post( `${notification.homeAssistantUrl.trim().replace(/\/*$/, "")}/api/services/notify/${notificationService}`, { title: "Uptime Kuma", message: msg, ...(notificationService !== "persistent_notification" && { data: { name: monitorJSON?.name, status: heartbeatJSON?.status, channel: "Uptime Kuma", icon_url: "https://github.com/louislam/uptime-kuma/blob/master/public/icon.png?raw=true", } }), }, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = HomeAssistant;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/telegram.js
server/notification-providers/telegram.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Telegram extends NotificationProvider { name = "telegram"; /** * Escapes special characters for Telegram MarkdownV2 format * @param {string} text Text to escape * @returns {string} Escaped text */ escapeMarkdownV2(text) { if (!text) { return text; } // Characters that need to be escaped in MarkdownV2 // https://core.telegram.org/bots/api#markdownv2-style return String(text).replace(/[_*[\]()~>#+\-=|{}.!\\]/g, "\\$&"); } /** * Recursively escapes string properties of an object for Telegram MarkdownV2 * @param {object|string} obj Object or string to escape * @returns {object|string} Escaped object or string */ escapeObjectRecursive(obj) { if (typeof obj === "string") { return this.escapeMarkdownV2(obj); } if (typeof obj === "object" && obj !== null) { // Check if array if (Array.isArray(obj)) { return obj.map(item => this.escapeObjectRecursive(item)); } const newObj = {}; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = this.escapeObjectRecursive(obj[key]); } } return newObj; } return obj; } /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = notification.telegramServerUrl ?? "https://api.telegram.org"; try { let params = { chat_id: notification.telegramChatID, text: msg, disable_notification: notification.telegramSendSilently ?? false, protect_content: notification.telegramProtectContent ?? false, link_preview_options: { is_disabled: true }, }; if (notification.telegramMessageThreadID) { params.message_thread_id = notification.telegramMessageThreadID; } if (notification.telegramUseTemplate) { let monitorJSONCopy = monitorJSON; let heartbeatJSONCopy = heartbeatJSON; if (notification.telegramTemplateParseMode === "MarkdownV2") { msg = this.escapeMarkdownV2(msg); if (monitorJSONCopy) { monitorJSONCopy = this.escapeObjectRecursive(monitorJSONCopy); } else { // for testing monitorJSON is null, provide escaped defaults monitorJSONCopy = { name: this.escapeMarkdownV2("Monitor Name not available"), hostname: this.escapeMarkdownV2("testing.hostname"), url: this.escapeMarkdownV2("testing.hostname"), }; } if (heartbeatJSONCopy) { heartbeatJSONCopy = this.escapeObjectRecursive(heartbeatJSONCopy); } } params.text = await this.renderTemplate(notification.telegramTemplate, msg, monitorJSONCopy, heartbeatJSONCopy); if (notification.telegramTemplateParseMode !== "plain") { params.parse_mode = notification.telegramTemplateParseMode; } } let config = this.getAxiosConfigWithProxy(); await axios.post(`${url}/bot${notification.telegramBotToken}/sendMessage`, params, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Telegram;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/heii-oncall.js
server/notification-providers/heii-oncall.js
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util"); const { setting } = require("../util-server"); const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class HeiiOnCall extends NotificationProvider { name = "HeiiOnCall"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const payload = heartbeatJSON || {}; const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorJSON) { payload["url"] = baseURL + getMonitorRelativeURL(monitorJSON.id); } let config = { headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: "Bearer " + notification.heiiOnCallApiKey, }, }; const heiiUrl = `https://heiioncall.com/triggers/${notification.heiiOnCallTriggerId}/`; // docs https://heiioncall.com/docs#manual-triggers try { config = this.getAxiosConfigWithProxy(config); if (!heartbeatJSON) { // Testing or general notification like certificate expiry payload["msg"] = msg; await axios.post(heiiUrl + "alert", payload, config); return okMsg; } if (heartbeatJSON.status === DOWN) { await axios.post(heiiUrl + "alert", payload, config); return okMsg; } if (heartbeatJSON.status === UP) { await axios.post(heiiUrl + "resolve", payload, config); return okMsg; } } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = HeiiOnCall;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/gtx-messaging.js
server/notification-providers/gtx-messaging.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class GtxMessaging extends NotificationProvider { name = "gtxmessaging"; /** * @inheritDoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; // The UP/DOWN symbols will be replaced with `???` by gtx-messaging const text = msg.replaceAll("🔴 ", "").replaceAll("✅ ", ""); try { let config = this.getAxiosConfigWithProxy({}); const data = new URLSearchParams(); data.append("from", notification.gtxMessagingFrom.trim()); data.append("to", notification.gtxMessagingTo.trim()); data.append("text", text); const url = `https://rest.gtx-messaging.net/smsc/sendsms/${notification.gtxMessagingApiKey}/json`; await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = GtxMessaging;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/nextcloudtalk.js
server/notification-providers/nextcloudtalk.js
const { UP, DOWN } = require("../../src/util"); const Crypto = require("crypto"); const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class NextcloudTalk extends NotificationProvider { name = "nextcloudtalk"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { // See documentation at https://nextcloud-talk.readthedocs.io/en/latest/bots/#sending-a-chat-message const okMsg = "Sent Successfully."; // Create a random string const talkRandom = encodeURIComponent( Crypto .randomBytes(64) .toString("hex") .slice(0, 64) ); // Create the signature over random and message const talkSignature = Crypto .createHmac("sha256", Buffer.from(notification.botSecret, "utf8")) .update(Buffer.from(`${talkRandom}${msg}`, "utf8")) .digest("hex"); let silentUp = (heartbeatJSON?.status === UP && notification.sendSilentUp); let silentDown = (heartbeatJSON?.status === DOWN && notification.sendSilentDown); let silent = (silentUp || silentDown); let url = `${notification.host}/ocs/v2.php/apps/spreed/api/v1/bot/${notification.conversationToken}/message`; let config = this.getAxiosConfigWithProxy({}); const data = { message: msg, silent }; const options = { ...config, headers: { "X-Nextcloud-Talk-Bot-Random": talkRandom, "X-Nextcloud-Talk-Bot-Signature": talkSignature, "OCS-APIRequest": true, } }; try { let result = await axios.post(url, data, options); if (result?.status === 201) { return okMsg; } throw new Error("Nextcloud Talk Error " + (result?.status ?? "Unknown")); } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = NextcloudTalk;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/nostr.js
server/notification-providers/nostr.js
const NotificationProvider = require("./notification-provider"); const { finalizeEvent, Relay, kinds, nip04, nip19, } = require("nostr-tools"); // polyfills for node versions const semver = require("semver"); const nodeVersion = process.version; if (semver.lt(nodeVersion, "20.0.0")) { // polyfills for node 18 global.crypto = require("crypto"); global.WebSocket = require("isomorphic-ws"); } else { // polyfills for node 20 global.WebSocket = require("isomorphic-ws"); } class Nostr extends NotificationProvider { name = "nostr"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { // All DMs should have same timestamp const createdAt = Math.floor(Date.now() / 1000); const senderPrivateKey = await this.getPrivateKey(notification.sender); const recipientsPublicKeys = await this.getPublicKeys(notification.recipients); // Create NIP-04 encrypted direct message event for each recipient const events = []; for (const recipientPublicKey of recipientsPublicKeys) { const ciphertext = await nip04.encrypt(senderPrivateKey, recipientPublicKey, msg); let event = { kind: kinds.EncryptedDirectMessage, created_at: createdAt, tags: [[ "p", recipientPublicKey ]], content: ciphertext, }; const signedEvent = finalizeEvent(event, senderPrivateKey); events.push(signedEvent); } // Publish events to each relay const relays = notification.relays.split("\n"); let successfulRelays = 0; for (const relayUrl of relays) { const relay = await Relay.connect(relayUrl); let eventIndex = 0; // Authenticate to the relay, if required try { await relay.publish(events[0]); eventIndex = 1; } catch (error) { if (relay.challenge) { await relay.auth(async (evt) => { return finalizeEvent(evt, senderPrivateKey); }); } } try { for (let i = eventIndex; i < events.length; i++) { await relay.publish(events[i]); } successfulRelays++; } catch (error) { console.error(`Failed to publish event to ${relayUrl}:`, error); } finally { relay.close(); } } // Report success or failure if (successfulRelays === 0) { throw Error("Failed to connect to any relays."); } return `${successfulRelays}/${relays.length} relays connected.`; } /** * Get the private key for the sender * @param {string} sender Sender to retrieve key for * @returns {nip19.DecodeResult} Private key */ async getPrivateKey(sender) { try { const senderDecodeResult = await nip19.decode(sender); const { data } = senderDecodeResult; return data; } catch (error) { throw new Error(`Failed to decode private key for sender ${sender}: ${error.message}`); } } /** * Get public keys for recipients * @param {string} recipients Newline delimited list of recipients * @returns {Promise<nip19.DecodeResult[]>} Public keys */ async getPublicKeys(recipients) { const recipientsList = recipients.split("\n"); const publicKeys = []; for (const recipient of recipientsList) { try { const recipientDecodeResult = await nip19.decode(recipient); const { type, data } = recipientDecodeResult; if (type === "npub") { publicKeys.push(data); } else { throw new Error(`Recipient ${recipient} is not an npub`); } } catch (error) { throw new Error(`Error decoding recipient ${recipient}: ${error}`); } } return publicKeys; } } module.exports = Nostr;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/keep.js
server/notification-providers/keep.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Keep extends NotificationProvider { name = "Keep"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let data = { heartbeat: heartbeatJSON, monitor: monitorJSON, msg, }; let config = { headers: { "x-api-key": notification.webhookAPIKey, "content-type": "application/json", }, }; let url = notification.webhookURL; if (url.endsWith("/")) { url = url.slice(0, -1); } let webhookURL = url + "/alerts/event/uptimekuma"; config = this.getAxiosConfigWithProxy(config); await axios.post(webhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Keep;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/notifery.js
server/notification-providers/notifery.js
const { getMonitorRelativeURL, UP } = require("../../src/util"); const { setting } = require("../util-server"); const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class Notifery extends NotificationProvider { name = "notifery"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://api.notifery.com/event"; let data = { title: notification.notiferyTitle || "Uptime Kuma Alert", message: msg, }; if (notification.notiferyGroup) { data.group = notification.notiferyGroup; } // Link to the monitor const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorJSON) { data.message += `\n\nMonitor: ${baseURL}${getMonitorRelativeURL(monitorJSON.id)}`; } if (heartbeatJSON) { data.code = heartbeatJSON.status === UP ? 0 : 1; if (heartbeatJSON.ping) { data.duration = heartbeatJSON.ping; } } try { const headers = { "Content-Type": "application/json", "x-api-key": notification.notiferyApiKey, }; let config = this.getAxiosConfigWithProxy({ headers }); await axios.post(url, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Notifery;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/matrix.js
server/notification-providers/matrix.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const Crypto = require("crypto"); const { log } = require("../../src/util"); class Matrix extends NotificationProvider { name = "matrix"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const size = 20; const randomString = encodeURIComponent( Crypto .randomBytes(size) .toString("base64") .slice(0, size) ); log.debug("notification", "Random String: " + randomString); const roomId = encodeURIComponent(notification.internalRoomId); log.debug("notification", "Matrix Room ID: " + roomId); try { let config = { headers: { "Authorization": `Bearer ${notification.accessToken}`, } }; let data = { "msgtype": "m.text", "body": msg }; config = this.getAxiosConfigWithProxy(config); await axios.put(`${notification.homeserverUrl}/_matrix/client/r0/rooms/${roomId}/send/m.room.message/${randomString}`, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = Matrix;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/google-chat.js
server/notification-providers/google-chat.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { setting } = require("../util-server"); const { getMonitorRelativeURL, UP } = require("../../src/util"); class GoogleChat extends NotificationProvider { name = "GoogleChat"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; // If Google Chat Webhook rate limit is reached, retry to configured max retries defaults to 3, delay between 60-180 seconds const post = async (url, data, config) => { let retries = notification.googleChatMaxRetries || 1; // Default to 1 retries retries = (retries > 10) ? 10 : retries; // Enforce maximum retries in backend while (retries > 0) { try { await axios.post(url, data, config); return; } catch (error) { if (error.response && error.response.status === 429) { retries--; if (retries === 0) { throw error; } const delay = 60000 + Math.random() * 120000; await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } }; try { let config = this.getAxiosConfigWithProxy({}); // Google Chat message formatting: https://developers.google.com/chat/api/guides/message-formats/basic if (notification.googleChatUseTemplate && notification.googleChatTemplate) { // Send message using template const renderedText = await this.renderTemplate( notification.googleChatTemplate, msg, monitorJSON, heartbeatJSON ); const data = { "text": renderedText }; await post(notification.googleChatWebhookURL, data, config); return okMsg; } let chatHeader = { title: "Uptime Kuma Alert", }; if (monitorJSON && heartbeatJSON) { chatHeader["title"] = heartbeatJSON["status"] === UP ? `✅ ${monitorJSON["name"]} is back online` : `🔴 ${monitorJSON["name"]} went down`; } // always show msg let sectionWidgets = [ { textParagraph: { text: `<b>Message:</b>\n${msg}`, }, }, ]; // add time if available if (heartbeatJSON) { sectionWidgets.push({ textParagraph: { text: `<b>Time (${heartbeatJSON["timezone"]}):</b>\n${heartbeatJSON["localDateTime"]}`, }, }); } // add button for monitor link if available const baseURL = await setting("primaryBaseURL"); if (baseURL) { const urlPath = monitorJSON ? getMonitorRelativeURL(monitorJSON.id) : "/"; sectionWidgets.push({ buttonList: { buttons: [ { text: "Visit Uptime Kuma", onClick: { openLink: { url: baseURL + urlPath, }, }, }, ], }, }); } let chatSections = [ { widgets: sectionWidgets, }, ]; // construct json data let data = { fallbackText: chatHeader["title"], cardsV2: [ { card: { header: chatHeader, sections: chatSections, }, }, ], }; await post(notification.googleChatWebhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = GoogleChat;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/smsmanager.js
server/notification-providers/smsmanager.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); class SMSManager extends NotificationProvider { name = "SMSManager"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; const url = "https://http-api.smsmanager.cz/Send"; try { let data = { apikey: notification.smsmanagerApiKey, message: msg.replace(/[^\x00-\x7F]/g, ""), number: notification.numbers, gateway: notification.messageType, }; let config = this.getAxiosConfigWithProxy({}); await axios.get(`${url}?apikey=${data.apikey}&message=${data.message}&number=${data.number}&gateway=${data.messageType}`, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = SMSManager;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/notification-providers/alertnow.js
server/notification-providers/alertnow.js
const NotificationProvider = require("./notification-provider"); const axios = require("axios"); const { setting } = require("../util-server"); const { getMonitorRelativeURL, UP, DOWN } = require("../../src/util"); class AlertNow extends NotificationProvider { name = "AlertNow"; /** * @inheritdoc */ async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { const okMsg = "Sent Successfully."; try { let textMsg = ""; let status = "open"; let eventType = "ERROR"; let eventId = new Date().toISOString().slice(0, 10).replace(/-/g, ""); if (heartbeatJSON && heartbeatJSON.status === UP) { textMsg = `[${heartbeatJSON.name}] ✅ Application is back online`; status = "close"; eventType = "INFO"; eventId += `_${heartbeatJSON.name.replace(/\s/g, "")}`; } else if (heartbeatJSON && heartbeatJSON.status === DOWN) { textMsg = `[${heartbeatJSON.name}] 🔴 Application went down`; } textMsg += ` - ${msg}`; const baseURL = await setting("primaryBaseURL"); if (baseURL && monitorJSON) { textMsg += ` >> ${baseURL + getMonitorRelativeURL(monitorJSON.id)}`; } const data = { "summary": textMsg, "status": status, "event_type": eventType, "event_id": eventId, }; let config = this.getAxiosConfigWithProxy({}); await axios.post(notification.alertNowWebhookURL, data, config); return okMsg; } catch (error) { this.throwGeneralAxiosError(error); } } } module.exports = AlertNow;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false