@ -11,40 +11,42 @@ if (nodeVersion < requiredVersion) {
}
}
const args = require ( "args-parser" ) ( process . argv ) ;
const args = require ( "args-parser" ) ( process . argv ) ;
const { sleep , debu g, getRandomInt , genSecret } = require ( "../src/util" ) ;
const { sleep , lo g, getRandomInt , genSecret , debug } = require ( "../src/util" ) ;
const config = require ( "./config" ) ;
const config = require ( "./config" ) ;
debug ( args ) ;
log . info ( "server" , "Welcome to Uptime Kuma" ) ;
log . debug ( "server" , "Arguments" ) ;
log . debug ( "server" , args ) ;
if ( ! process . env . NODE _ENV ) {
if ( ! process . env . NODE _ENV ) {
process . env . NODE _ENV = "production" ;
process . env . NODE _ENV = "production" ;
}
}
console. log ( "Node Env: " + process . env . NODE _ENV ) ;
log. info ( "server" , "Node Env: " + process . env . NODE _ENV ) ;
console. log ( "Importing Node libraries" ) ;
log. info ( "server" , "Importing Node libraries" ) ;
const fs = require ( "fs" ) ;
const fs = require ( "fs" ) ;
const http = require ( "http" ) ;
const http = require ( "http" ) ;
const https = require ( "https" ) ;
const https = require ( "https" ) ;
console. log ( "Importing 3rd-party libraries" ) ;
log. info ( "server" , "Importing 3rd-party libraries" ) ;
debug ( "Importing express" ) ;
log . debug ( "server" , "Importing express" ) ;
const express = require ( "express" ) ;
const express = require ( "express" ) ;
debug ( "Importing socket.io" ) ;
log . debug ( "server" , "Importing socket.io" ) ;
const { Server } = require ( "socket.io" ) ;
const { Server } = require ( "socket.io" ) ;
debug ( "Importing redbean-node" ) ;
log . debug ( "server" , "Importing redbean-node" ) ;
const { R } = require ( "redbean-node" ) ;
const { R } = require ( "redbean-node" ) ;
debug ( "Importing jsonwebtoken" ) ;
log . debug ( "server" , "Importing jsonwebtoken" ) ;
const jwt = require ( "jsonwebtoken" ) ;
const jwt = require ( "jsonwebtoken" ) ;
debug ( "Importing http-graceful-shutdown" ) ;
log . debug ( "server" , "Importing http-graceful-shutdown" ) ;
const gracefulShutdown = require ( "http-graceful-shutdown" ) ;
const gracefulShutdown = require ( "http-graceful-shutdown" ) ;
debug ( "Importing prometheus-api-metrics" ) ;
log . debug ( "server" , "Importing prometheus-api-metrics" ) ;
const prometheusAPIMetrics = require ( "prometheus-api-metrics" ) ;
const prometheusAPIMetrics = require ( "prometheus-api-metrics" ) ;
debug ( "Importing compare-versions" ) ;
log . debug ( "server" , "Importing compare-versions" ) ;
const compareVersions = require ( "compare-versions" ) ;
const compareVersions = require ( "compare-versions" ) ;
const { passwordStrength } = require ( "check-password-strength" ) ;
const { passwordStrength } = require ( "check-password-strength" ) ;
debug ( "Importing 2FA Modules" ) ;
log . debug ( "server" , "Importing 2FA Modules" ) ;
const notp = require ( "notp" ) ;
const notp = require ( "notp" ) ;
const base32 = require ( "thirty-two" ) ;
const base32 = require ( "thirty-two" ) ;
@ -69,23 +71,23 @@ class UptimeKumaServer {
const server = module . exports = new UptimeKumaServer ( ) ;
const server = module . exports = new UptimeKumaServer ( ) ;
console. log ( "Importing this project modules" ) ;
log. info ( "server" , "Importing this project modules" ) ;
debug ( "Importing Monitor" ) ;
log . debug ( "server" , "Importing Monitor" ) ;
const Monitor = require ( "./model/monitor" ) ;
const Monitor = require ( "./model/monitor" ) ;
debug ( "Importing Settings" ) ;
log . debug ( "server" , "Importing Settings" ) ;
const { getSettings , setSettings , setting , initJWTSecret , checkLogin , startUnitTest , FBSD , errorLog , doubleCheckPassword } = require ( "./util-server" ) ;
const { getSettings , setSettings , setting , initJWTSecret , checkLogin , startUnitTest , FBSD , errorLog , doubleCheckPassword } = require ( "./util-server" ) ;
debug ( "Importing Notification" ) ;
log . debug ( "server" , "Importing Notification" ) ;
const { Notification } = require ( "./notification" ) ;
const { Notification } = require ( "./notification" ) ;
Notification . init ( ) ;
Notification . init ( ) ;
debug ( "Importing Proxy" ) ;
log . debug ( "server" , "Importing Proxy" ) ;
const { Proxy } = require ( "./proxy" ) ;
const { Proxy } = require ( "./proxy" ) ;
debug ( "Importing Database" ) ;
log . debug ( "server" , "Importing Database" ) ;
const Database = require ( "./database" ) ;
const Database = require ( "./database" ) ;
debug ( "Importing Background Jobs" ) ;
log . debug ( "server" , "Importing Background Jobs" ) ;
const { initBackgroundJobs , stopBackgroundJobs } = require ( "./jobs" ) ;
const { initBackgroundJobs , stopBackgroundJobs } = require ( "./jobs" ) ;
const { loginRateLimiter , twoFaRateLimiter } = require ( "./rate-limiter" ) ;
const { loginRateLimiter , twoFaRateLimiter } = require ( "./rate-limiter" ) ;
@ -94,27 +96,26 @@ const { login } = require("./auth");
const passwordHash = require ( "./password-hash" ) ;
const passwordHash = require ( "./password-hash" ) ;
const checkVersion = require ( "./check-version" ) ;
const checkVersion = require ( "./check-version" ) ;
console. info ( "Version: " + checkVersion . version ) ;
log. info ( "server" , "Version: " + checkVersion . version ) ;
// 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.
// 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 (::)
// Dual-stack support for (::)
let hostname = process . env . UPTIME _KUMA _HOST || args . host ;
// Also read HOST if not FreeBSD, as HOST is a system environment variable in FreeBSD
// Also read HOST if not FreeBSD, as HOST is a system environment variable in FreeBSD
if ( ! hostname && ! FBSD ) {
let hostEnv = FBSD ? null : process . env . HOST ;
hostname = process . env . HOST ;
let hostname = args . host || process . env . UPTIME _KUMA _HOST || hostEnv ;
}
if ( hostname ) {
if ( hostname ) {
console. log ( "Custom hostname: " + hostname ) ;
log. info ( "server" , "Custom hostname: " + hostname ) ;
}
}
const port = parseInt ( process . env . UPTIME _KUMA _PORT || process . env . PORT || args . port || 3001 ) ;
const port = [ args . port , process . env . UPTIME _KUMA _PORT , process . env . PORT , 3001 ]
. map ( portValue => parseInt ( portValue ) )
. find ( portValue => ! isNaN ( portValue ) ) ;
// SSL
// SSL
const sslKey = process. env . UPTIME _KUMA _SSL _KEY || process . env . SSL _KEY || args [ "ssl-key" ] || undefined ;
const sslKey = args[ "ssl-key" ] || process. env . UPTIME _KUMA _SSL _KEY || process . env . SSL _KEY || undefined ;
const sslCert = process. env . UPTIME _KUMA _SSL _CERT || process . env . SSL _CERT || args [ "ssl-cert" ] || undefined ;
const sslCert = args[ "ssl-cert" ] || process. env . UPTIME _KUMA _SSL _CERT || process . env . SSL _CERT || undefined ;
const disableFrameSameOrigin = ! ! process . env . UPTIME _KUMA _DISABLE _FRAME _SAMEORIGIN || args [ "disable-frame-sameorigin" ] || false ;
const disableFrameSameOrigin = args [ "disable-frame-sameorigin" ] || ! ! process . env . UPTIME _KUMA _DISABLE _FRAME _SAMEORIGIN || false ;
const cloudflaredToken = args [ "cloudflared-token" ] || process . env . UPTIME _KUMA _CLOUDFLARED _TOKEN || undefined ;
const cloudflaredToken = args [ "cloudflared-token" ] || process . env . UPTIME _KUMA _CLOUDFLARED _TOKEN || undefined ;
// 2FA / notp verification defaults
// 2FA / notp verification defaults
@ -130,22 +131,22 @@ const twofa_verification_opts = {
const testMode = ! ! args [ "test" ] || false ;
const testMode = ! ! args [ "test" ] || false ;
if ( config . demoMode ) {
if ( config . demoMode ) {
console. log ( "==== Demo Mode ====" ) ;
log. info ( "server" , "==== Demo Mode ====" ) ;
}
}
console. log ( "Creating express and socket.io instance" ) ;
log. info ( "server" , "Creating express and socket.io instance" ) ;
const app = express ( ) ;
const app = express ( ) ;
let httpServer ;
let httpServer ;
if ( sslKey && sslCert ) {
if ( sslKey && sslCert ) {
console. log ( "Server Type: HTTPS" ) ;
log. info ( "server" , "Server Type: HTTPS" ) ;
httpServer = https . createServer ( {
httpServer = https . createServer ( {
key : fs . readFileSync ( sslKey ) ,
key : fs . readFileSync ( sslKey ) ,
cert : fs . readFileSync ( sslCert )
cert : fs . readFileSync ( sslCert )
} , app ) ;
} , app ) ;
} else {
} else {
console. log ( "Server Type: HTTP" ) ;
log. info ( "server" , "Server Type: HTTP" ) ;
httpServer = http . createServer ( app ) ;
httpServer = http . createServer ( app ) ;
}
}
@ -201,7 +202,7 @@ try {
} catch ( e ) {
} catch ( e ) {
// "dist/index.html" is not necessary for development
// "dist/index.html" is not necessary for development
if ( process . env . NODE _ENV !== "development" ) {
if ( process . env . NODE _ENV !== "development" ) {
console. error ( "Error: Cannot find 'dist/index.html', did you install correctly?" ) ;
log. error ( "server" , "Error: Cannot find 'dist/index.html', did you install correctly?" ) ;
process . exit ( 1 ) ;
process . exit ( 1 ) ;
}
}
}
}
@ -213,7 +214,7 @@ try {
exports . entryPage = await setting ( "entryPage" ) ;
exports . entryPage = await setting ( "entryPage" ) ;
await StatusPage . loadDomainMappingList ( ) ;
await StatusPage . loadDomainMappingList ( ) ;
console. log ( "Adding route" ) ;
log. info ( "server" , "Adding route" ) ;
// ***************************
// ***************************
// Normal Router here
// Normal Router here
@ -271,7 +272,7 @@ try {
}
}
} ) ;
} ) ;
console. log ( "Adding socket handler" ) ;
log. info ( "server" , "Adding socket handler" ) ;
io . on ( "connection" , async ( socket ) => {
io . on ( "connection" , async ( socket ) => {
sendInfo ( socket ) ;
sendInfo ( socket ) ;
@ -279,7 +280,7 @@ try {
totalClient ++ ;
totalClient ++ ;
if ( needSetup ) {
if ( needSetup ) {
console. log ( "Redirect to setup page" ) ;
log. info ( "server" , "Redirect to setup page" ) ;
socket . emit ( "setup" ) ;
socket . emit ( "setup" ) ;
}
}
@ -292,33 +293,40 @@ try {
// ***************************
// ***************************
socket . on ( "loginByToken" , async ( token , callback ) => {
socket . on ( "loginByToken" , async ( token , callback ) => {
log . info ( "auth" , ` Login by token. IP= ${ getClientIp ( socket ) } ` ) ;
try {
try {
let decoded = jwt . verify ( token , jwtSecret ) ;
let decoded = jwt . verify ( token , jwtSecret ) ;
console. log ( "Username from JWT: " + decoded . username ) ;
log. info ( "auth" , "Username from JWT: " + decoded . username ) ;
let user = await R . findOne ( "user" , " username = ? AND active = 1 " , [
let user = await R . findOne ( "user" , " username = ? AND active = 1 " , [
decoded . username ,
decoded . username ,
] ) ;
] ) ;
if ( user ) {
if ( user ) {
debug ( "afterLogin" ) ;
log . debug ( "auth" , "afterLogin" ) ;
afterLogin ( socket , user ) ;
afterLogin ( socket , user ) ;
log . debug ( "auth" , "afterLogin ok" ) ;
debug( "afterLogin ok" ) ;
log. info ( "auth" , ` Successfully logged in user ${ decoded . username } . IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : true ,
ok : true ,
} ) ;
} ) ;
} else {
} else {
log . info ( "auth" , ` Inactive or deleted user ${ decoded . username } . IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : "The user is inactive or deleted." ,
msg : "The user is inactive or deleted." ,
} ) ;
} ) ;
}
}
} catch ( error ) {
} catch ( error ) {
log . error ( "auth" , ` Invalid token. IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : "Invalid token." ,
msg : "Invalid token." ,
@ -328,7 +336,7 @@ try {
} ) ;
} ) ;
socket . on ( "login" , async ( data , callback ) => {
socket . on ( "login" , async ( data , callback ) => {
console. log ( "Login" ) ;
log. info ( "auth" , ` Login by username + password. IP= ${ getClientIp ( socket ) } ` ) ;
// Checking
// Checking
if ( typeof callback !== "function" ) {
if ( typeof callback !== "function" ) {
@ -341,6 +349,7 @@ try {
// Login Rate Limit
// Login Rate Limit
if ( ! await loginRateLimiter . pass ( callback ) ) {
if ( ! await loginRateLimiter . pass ( callback ) ) {
log . info ( "auth" , ` Too many failed requests for user ${ data . username } . IP= ${ getClientIp ( socket ) } ` ) ;
return ;
return ;
}
}
@ -349,6 +358,9 @@ try {
if ( user ) {
if ( user ) {
if ( user . twofa _status == 0 ) {
if ( user . twofa _status == 0 ) {
afterLogin ( socket , user ) ;
afterLogin ( socket , user ) ;
log . info ( "auth" , ` Successfully logged in user ${ data . username } . IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : true ,
ok : true ,
token : jwt . sign ( {
token : jwt . sign ( {
@ -358,6 +370,9 @@ try {
}
}
if ( user . twofa _status == 1 && ! data . token ) {
if ( user . twofa _status == 1 && ! data . token ) {
log . info ( "auth" , ` 2FA token required for user ${ data . username } . IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
tokenRequired : true ,
tokenRequired : true ,
} ) ;
} ) ;
@ -374,6 +389,8 @@ try {
socket . userID ,
socket . userID ,
] ) ;
] ) ;
log . info ( "auth" , ` Successfully logged in user ${ data . username } . IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : true ,
ok : true ,
token : jwt . sign ( {
token : jwt . sign ( {
@ -381,6 +398,9 @@ try {
} , jwtSecret ) ,
} , jwtSecret ) ,
} ) ;
} ) ;
} else {
} else {
log . warn ( "auth" , ` Invalid token provided for user ${ data . username } . IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : "Invalid Token!" ,
msg : "Invalid Token!" ,
@ -388,6 +408,9 @@ try {
}
}
}
}
} else {
} else {
log . warn ( "auth" , ` Incorrect username or password for user ${ data . username } . IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : "Incorrect username or password." ,
msg : "Incorrect username or password." ,
@ -470,11 +493,16 @@ try {
socket . userID ,
socket . userID ,
] ) ;
] ) ;
log . info ( "auth" , ` Saved 2FA token. IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : true ,
ok : true ,
msg : "2FA Enabled." ,
msg : "2FA Enabled." ,
} ) ;
} ) ;
} catch ( error ) {
} catch ( error ) {
log . error ( "auth" , ` Error changing 2FA token. IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : error . message ,
msg : error . message ,
@ -492,11 +520,16 @@ try {
await doubleCheckPassword ( socket , currentPassword ) ;
await doubleCheckPassword ( socket , currentPassword ) ;
await TwoFA . disable2FA ( socket . userID ) ;
await TwoFA . disable2FA ( socket . userID ) ;
log . info ( "auth" , ` Disabled 2FA token. IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : true ,
ok : true ,
msg : "2FA Disabled." ,
msg : "2FA Disabled." ,
} ) ;
} ) ;
} catch ( error ) {
} catch ( error ) {
log . error ( "auth" , ` Error disabling 2FA token. IP= ${ getClientIp ( socket ) } ` ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : error . message ,
msg : error . message ,
@ -623,6 +656,8 @@ try {
await server . sendMonitorList ( socket ) ;
await server . sendMonitorList ( socket ) ;
await startMonitor ( socket . userID , bean . id ) ;
await startMonitor ( socket . userID , bean . id ) ;
log . info ( "monitor" , ` Added Monitor: ${ monitor . id } User ID: ${ socket . userID } ` ) ;
callback ( {
callback ( {
ok : true ,
ok : true ,
msg : "Added Successfully." ,
msg : "Added Successfully." ,
@ -630,6 +665,9 @@ try {
} ) ;
} ) ;
} catch ( e ) {
} catch ( e ) {
log . error ( "monitor" , ` Error adding Monitor: ${ monitor . id } User ID: ${ socket . userID } ` ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : e . message ,
msg : e . message ,
@ -692,7 +730,7 @@ try {
} ) ;
} ) ;
} catch ( e ) {
} catch ( e ) {
console. error ( e ) ;
log. error ( "monitor" , e ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : e . message ,
msg : e . message ,
@ -708,7 +746,7 @@ try {
ok : true ,
ok : true ,
} ) ;
} ) ;
} catch ( e ) {
} catch ( e ) {
console. error ( e ) ;
log. error ( "monitor" , e ) ;
callback ( {
callback ( {
ok : false ,
ok : false ,
msg : e . message ,
msg : e . message ,
@ -720,7 +758,7 @@ try {
try {
try {
checkLogin ( socket ) ;
checkLogin ( socket ) ;
console. log ( ` Get Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
log. info ( "monitor" , ` Get Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
let bean = await R . findOne ( "monitor" , " id = ? AND user_id = ? " , [
let bean = await R . findOne ( "monitor" , " id = ? AND user_id = ? " , [
monitorID ,
monitorID ,
@ -744,7 +782,7 @@ try {
try {
try {
checkLogin ( socket ) ;
checkLogin ( socket ) ;
console. log ( ` Get Monitor Beats: ${ monitorID } User ID: ${ socket . userID } ` ) ;
log. info ( "monitor" , ` Get Monitor Beats: ${ monitorID } User ID: ${ socket . userID } ` ) ;
if ( period == null ) {
if ( period == null ) {
throw new Error ( "Invalid period." ) ;
throw new Error ( "Invalid period." ) ;
@ -815,7 +853,7 @@ try {
try {
try {
checkLogin ( socket ) ;
checkLogin ( socket ) ;
console. log ( ` Delete Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
log. info ( "manage" , ` Delete Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
if ( monitorID in server . monitorList ) {
if ( monitorID in server . monitorList ) {
server . monitorList [ monitorID ] . stop ( ) ;
server . monitorList [ monitorID ] . stop ( ) ;
@ -1147,7 +1185,7 @@ try {
let backupData = JSON . parse ( uploadedJSON ) ;
let backupData = JSON . parse ( uploadedJSON ) ;
console. log ( ` Importing Backup, User ID: ${ socket . userID } , Version: ${ backupData . version } ` ) ;
log. info ( "manage" , ` Importing Backup, User ID: ${ socket . userID } , Version: ${ backupData . version } ` ) ;
let notificationListData = backupData . notificationList ;
let notificationListData = backupData . notificationList ;
let proxyListData = backupData . proxyList ;
let proxyListData = backupData . proxyList ;
@ -1190,7 +1228,7 @@ try {
}
}
// Only starts importing if the backup file contains at least one proxy
// Only starts importing if the backup file contains at least one proxy
if ( proxyListData . length >= 1 ) {
if ( proxyListData && proxyListData . length >= 1 ) {
const proxies = await R . findAll ( "proxy" ) ;
const proxies = await R . findAll ( "proxy" ) ;
// Loop over proxy list and save proxies
// Loop over proxy list and save proxies
@ -1342,7 +1380,7 @@ try {
try {
try {
checkLogin ( socket ) ;
checkLogin ( socket ) ;
console. log ( ` Clear Events Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
log. info ( "manage" , ` Clear Events Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
await R . exec ( "UPDATE heartbeat SET msg = ?, important = ? WHERE monitor_id = ? " , [
await R . exec ( "UPDATE heartbeat SET msg = ?, important = ? WHERE monitor_id = ? " , [
"" ,
"" ,
@ -1368,7 +1406,7 @@ try {
try {
try {
checkLogin ( socket ) ;
checkLogin ( socket ) ;
console. log ( ` Clear Heartbeats Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
log. info ( "manage" , ` Clear Heartbeats Monitor: ${ monitorID } User ID: ${ socket . userID } ` ) ;
await R . exec ( "DELETE FROM heartbeat WHERE monitor_id = ?" , [
await R . exec ( "DELETE FROM heartbeat WHERE monitor_id = ?" , [
monitorID
monitorID
@ -1392,7 +1430,7 @@ try {
try {
try {
checkLogin ( socket ) ;
checkLogin ( socket ) ;
console. log ( ` Clear Statistics User ID: ${ socket . userID } ` ) ;
log. info ( "manage" , ` Clear Statistics User ID: ${ socket . userID } ` ) ;
await R . exec ( "DELETE FROM heartbeat" ) ;
await R . exec ( "DELETE FROM heartbeat" ) ;
@ -1414,24 +1452,24 @@ try {
databaseSocketHandler ( socket ) ;
databaseSocketHandler ( socket ) ;
proxySocketHandler ( socket ) ;
proxySocketHandler ( socket ) ;
debug( "added all socket handlers" ) ;
log. debug( "server" , "added all socket handlers" ) ;
// ***************************
// ***************************
// Better do anything after added all socket handlers here
// Better do anything after added all socket handlers here
// ***************************
// ***************************
debug( "check auto login" ) ;
log. debug( "auth" , "check auto login" ) ;
if ( await setting ( "disableAuth" ) ) {
if ( await setting ( "disableAuth" ) ) {
console. log ( "Disabled Auth: auto login to admin" ) ;
log. info ( "auth" , "Disabled Auth: auto login to admin" ) ;
afterLogin ( socket , await R . findOne ( "user" ) ) ;
afterLogin ( socket , await R . findOne ( "user" ) ) ;
socket . emit ( "autoLogin" ) ;
socket . emit ( "autoLogin" ) ;
} else {
} else {
debug( "need auth" ) ;
log. debug( "auth" , "need auth" ) ;
}
}
} ) ;
} ) ;
console. log ( "Init the server" ) ;
log. info ( "server" , "Init the server" ) ;
httpServer . once ( "error" , async ( err ) => {
httpServer . once ( "error" , async ( err ) => {
console . error ( "Cannot listen: " + err . message ) ;
console . error ( "Cannot listen: " + err . message ) ;
@ -1440,9 +1478,9 @@ try {
httpServer . listen ( port , hostname , ( ) => {
httpServer . listen ( port , hostname , ( ) => {
if ( hostname ) {
if ( hostname ) {
console. log ( ` Listening on ${ hostname } : ${ port } ` ) ;
log. info ( "server" , ` Listening on ${ hostname } : ${ port } ` ) ;
} else {
} else {
console. log ( ` Listening on ${ port } ` ) ;
log. info ( "server" , ` Listening on ${ port } ` ) ;
}
}
startMonitors ( ) ;
startMonitors ( ) ;
checkVersion . startInterval ( ) ;
checkVersion . startInterval ( ) ;
@ -1459,6 +1497,13 @@ try {
} ) ( ) ;
} ) ( ) ;
/ * *
* Adds or removes notifications from a monitor .
* @ param { number } monitorID The ID of the monitor to add / remove notifications from .
* @ param { Array . < number > } notificationIDList An array of IDs for the notifications to add / remove .
*
* Generated by Trelent
* /
async function updateMonitorNotification ( monitorID , notificationIDList ) {
async function updateMonitorNotification ( monitorID , notificationIDList ) {
await R . exec ( "DELETE FROM monitor_notification WHERE monitor_id = ? " , [
await R . exec ( "DELETE FROM monitor_notification WHERE monitor_id = ? " , [
monitorID ,
monitorID ,
@ -1474,6 +1519,13 @@ async function updateMonitorNotification(monitorID, notificationIDList) {
}
}
}
}
/ * *
* This function checks if the user owns a monitor with the given ID .
* @ param { number } monitorID - The ID of the monitor to check ownership for .
* @ param { number } userID - The ID of the user who is trying to access this data .
*
* Generated by Trelent
* /
async function checkOwner ( userID , monitorID ) {
async function checkOwner ( userID , monitorID ) {
let row = await R . getRow ( "SELECT id FROM monitor WHERE id = ? AND user_id = ? " , [
let row = await R . getRow ( "SELECT id FROM monitor WHERE id = ? AND user_id = ? " , [
monitorID ,
monitorID ,
@ -1485,6 +1537,10 @@ async function checkOwner(userID, monitorID) {
}
}
}
}
/ * *
* This function is used to send the heartbeat list of a monitor .
* @ param { Socket } socket - The socket object that will be used to send the data .
* /
async function afterLogin ( socket , user ) {
async function afterLogin ( socket , user ) {
socket . userID = user . id ;
socket . userID = user . id ;
socket . join ( user . id ) ;
socket . join ( user . id ) ;
@ -1510,6 +1566,13 @@ async function afterLogin(socket, user) {
}
}
}
}
/ * *
* Get a list of monitors for the given user .
* @ param { string } userID - The ID of the user to get monitors 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 function getMonitorJSONList ( userID ) {
async function getMonitorJSONList ( userID ) {
let result = { } ;
let result = { } ;
@ -1524,15 +1587,20 @@ async function getMonitorJSONList(userID) {
return result ;
return result ;
}
}
/ * *
* Connect to the database and patch it if necessary .
*
* Generated by Trelent
* /
async function initDatabase ( testMode = false ) {
async function initDatabase ( testMode = false ) {
if ( ! fs . existsSync ( Database . path ) ) {
if ( ! fs . existsSync ( Database . path ) ) {
console . log ( "Copying Database" ) ;
log. info ( "server" , "Copying Database" ) ;
fs . copyFileSync ( Database . templatePath , Database . path ) ;
fs . copyFileSync ( Database . templatePath , Database . path ) ;
}
}
console. log ( "Connecting to the Database" ) ;
log. info ( "server" , "Connecting to the Database" ) ;
await Database . connect ( testMode ) ;
await Database . connect ( testMode ) ;
console. log ( "Connected" ) ;
log. info ( "server" , "Connected" ) ;
// Patch the database
// Patch the database
await Database . patch ( ) ;
await Database . patch ( ) ;
@ -1542,26 +1610,33 @@ async function initDatabase(testMode = false) {
] ) ;
] ) ;
if ( ! jwtSecretBean ) {
if ( ! jwtSecretBean ) {
console. log ( "JWT secret is not found, generate one." ) ;
log. info ( "server" , "JWT secret is not found, generate one." ) ;
jwtSecretBean = await initJWTSecret ( ) ;
jwtSecretBean = await initJWTSecret ( ) ;
console. log ( "Stored JWT secret into database" ) ;
log. info ( "server" , "Stored JWT secret into database" ) ;
} else {
} else {
console. log ( "Load JWT secret from database." ) ;
log. info ( "server" , "Load JWT secret from database." ) ;
}
}
// If there is no record in user table, it is a new Uptime Kuma instance, need to setup
// If there is no record in user table, it is a new Uptime Kuma instance, need to setup
if ( ( await R . count ( "user" ) ) === 0 ) {
if ( ( await R . count ( "user" ) ) === 0 ) {
console. log ( "No user, need setup" ) ;
log. info ( "server" , "No user, need setup" ) ;
needSetup = true ;
needSetup = true ;
}
}
jwtSecret = jwtSecretBean . value ;
jwtSecret = jwtSecretBean . value ;
}
}
/ * *
* Resume a monitor .
* @ param { string } userID - The ID of the user who owns the monitor .
* @ param { string } monitorID - The ID of the monitor to resume .
*
* Generated by Trelent
* /
async function startMonitor ( userID , monitorID ) {
async function startMonitor ( userID , monitorID ) {
await checkOwner ( userID , monitorID ) ;
await checkOwner ( userID , monitorID ) ;
console . log ( ` Resume Monitor: ${ monitorID } User ID: ${ userID } ` ) ;
log. info ( "manage" , ` Resume Monitor: ${ monitorID } User ID: ${ userID } ` ) ;
await R . exec ( "UPDATE monitor SET active = 1 WHERE id = ? AND user_id = ? " , [
await R . exec ( "UPDATE monitor SET active = 1 WHERE id = ? AND user_id = ? " , [
monitorID ,
monitorID ,
@ -1584,10 +1659,17 @@ async function restartMonitor(userID, monitorID) {
return await startMonitor ( userID , monitorID ) ;
return await startMonitor ( userID , monitorID ) ;
}
}
/ * *
* Pause a monitor .
* @ param { string } userID - The ID of the user who owns the monitor .
* @ param { string } monitorID - The ID of the monitor to pause .
*
* Generated by Trelent
* /
async function pauseMonitor ( userID , monitorID ) {
async function pauseMonitor ( userID , monitorID ) {
await checkOwner ( userID , monitorID ) ;
await checkOwner ( userID , monitorID ) ;
console . log ( ` Pause Monitor: ${ monitorID } User ID: ${ userID } ` ) ;
log. info ( "manage" , ` Pause Monitor: ${ monitorID } User ID: ${ userID } ` ) ;
await R . exec ( "UPDATE monitor SET active = 0 WHERE id = ? AND user_id = ? " , [
await R . exec ( "UPDATE monitor SET active = 0 WHERE id = ? AND user_id = ? " , [
monitorID ,
monitorID ,
@ -1616,11 +1698,17 @@ async function startMonitors() {
}
}
}
}
/ * *
* Stops all monitors and closes the database connection .
* @ param { string } signal The signal that triggered this function to be called .
*
* Generated by Trelent
* /
async function shutdownFunction ( signal ) {
async function shutdownFunction ( signal ) {
console . log ( "Shutdown requested" ) ;
log. info ( "server" , "Shutdown requested" ) ;
console . log ( "Called signal: " + signal ) ;
log. info ( "server" , "Called signal: " + signal ) ;
console . log ( "Stopping all monitors" ) ;
log. info ( "server" , "Stopping all monitors" ) ;
for ( let id in server . monitorList ) {
for ( let id in server . monitorList ) {
let monitor = server . monitorList [ id ] ;
let monitor = server . monitorList [ id ] ;
monitor . stop ( ) ;
monitor . stop ( ) ;
@ -1632,8 +1720,12 @@ async function shutdownFunction(signal) {
await cloudflaredStop ( ) ;
await cloudflaredStop ( ) ;
}
}
function getClientIp ( socket ) {
return socket . client . conn . remoteAddress . replace ( /^.*:/ , "" ) ;
}
function finalFunction ( ) {
function finalFunction ( ) {
console . log ( "Graceful shutdown successful!" ) ;
log. info ( "server" , "Graceful shutdown successful!" ) ;
}
}
gracefulShutdown ( httpServer , {
gracefulShutdown ( httpServer , {