Files
MagicMirror/js/server.js
T

173 lines
5.7 KiB
JavaScript
Raw Normal View History

const fs = require("node:fs");
const http = require("node:http");
const https = require("node:https");
const path = require("node:path");
2023-04-04 20:44:32 +02:00
const express = require("express");
2021-01-05 18:37:16 +01:00
const helmet = require("helmet");
2023-04-04 20:44:32 +02:00
const socketio = require("socket.io");
2021-02-18 19:14:53 +01:00
const Log = require("logger");
2017-03-10 18:20:11 -03:00
const { ipAccessControl, socketIpAccessControl } = require("./ip_access_control");
const vendor = require("./vendor");
const { getHtml, getVersion, getEnvVars, cors } = require("#server_functions");
2021-01-06 13:17:39 +01:00
/**
* Server
* @param {object} configObj The MM config full and redacted
2021-01-06 13:17:39 +01:00
* @class
*/
function Server (configObj) {
const config = configObj.fullConf;
2023-01-01 18:09:08 +01:00
const app = express();
2021-01-05 18:37:16 +01:00
const port = process.env.MM_PORT || config.port;
2021-09-24 00:30:00 +02:00
const serverSockets = new Set();
2021-01-05 18:37:16 +01:00
let server = null;
2023-01-01 18:09:08 +01:00
/**
* Opens the server for incoming connections
* @returns {Promise} A promise that is resolved when the server listens to connections
*/
this.open = function () {
return new Promise((resolve) => {
if (config.useHttps) {
const options = {
key: fs.readFileSync(config.httpsPrivateKey),
cert: fs.readFileSync(config.httpsCertificate)
};
2023-04-04 20:44:32 +02:00
server = https.Server(options, app);
} else {
2023-04-04 20:44:32 +02:00
server = http.Server(app);
2023-01-01 18:09:08 +01:00
}
2023-04-04 20:44:32 +02:00
const io = socketio(server, {
allowRequest: socketIpAccessControl(config.ipWhitelist),
2023-01-01 18:09:08 +01:00
cors: {
origin: /.*$/,
credentials: true
},
allowEIO3: true,
pingInterval: 120000, // server → client ping every 2 mins
pingTimeout: 120000 // wait up to 2 mins for client pong
2023-01-01 18:09:08 +01:00
});
server.on("connection", (socket) => {
serverSockets.add(socket);
socket.on("close", () => {
serverSockets.delete(socket);
});
});
Log.log(`Starting server on port ${port} ... `);
// Add explicit error handling BEFORE calling listen so we can give user-friendly feedback
server.once("error", (err) => {
if (err && err.code === "EADDRINUSE") {
const bindAddr = config.address || "localhost";
const portInUseMessage = [
"",
"────────────────────────────────────────────────────────────────",
` PORT IN USE: ${bindAddr}:${port}`,
"",
" Another process (most likely another MagicMirror instance)",
" is already using this port.",
"",
" Stop the other process (free the port) or use a different port.",
"────────────────────────────────────────────────────────────────"
].join("\n");
Log.error(portInUseMessage);
return;
}
Log.error("Failed to start server:", err);
});
2023-01-01 18:09:08 +01:00
server.listen(port, config.address || "localhost");
if (config.ipWhitelist instanceof Array && config.ipWhitelist.length === 0) {
2024-01-16 21:54:55 +01:00
Log.warn("You're using a full whitelist configuration to allow for all IPs");
}
2022-01-24 23:45:17 +01:00
app.use(ipAccessControl(config.ipWhitelist));
2023-01-01 18:09:08 +01:00
app.use(helmet(config.httpHeaders));
app.use("/js", express.static(__dirname));
if (config.hideConfigSecrets) {
app.get("/config/config.env", (req, res) => {
res.status(404).send("<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /config/config.env</pre>\n</body>\n</html>");
});
}
let directories = ["/config", "/css", "/favicon.svg", "/defaultmodules", "/modules", "/node_modules/animate.css", "/node_modules/@fontsource", "/node_modules/@fortawesome", "/translations", "/tests/configs", "/tests/mocks"];
for (const value of Object.values(vendor)) {
const dirArr = value.split("/");
if (dirArr[0] === "node_modules") directories.push(`/${dirArr[0]}/${dirArr[1]}`);
}
const uniqDirs = [...new Set(directories)];
for (const directory of uniqDirs) {
2023-01-01 18:09:08 +01:00
app.use(directory, express.static(path.resolve(global.root_path + directory)));
}
2016-12-29 22:23:08 -03:00
const startUp = new Date();
const getStartup = (req, res) => res.send(startUp);
const getConfig = (req, res) => {
const obj = config.hideConfigSecrets ? configObj.redactedConf : configObj.fullConf;
// Functions can't survive JSON.stringify, so we wrap them in a
// tagged object { __mmFunction: "<source>" }. The client-side
// JSON reviver in main.js recognises this tag and reconstructs
// the live function from the source string.
const jsonString = JSON.stringify(obj, (key, value) => {
if (typeof value === "function") {
return { __mmFunction: value.toString() };
}
return value;
});
res.set("Content-Type", "application/json");
res.send(jsonString);
};
app.get("/config", (req, res) => getConfig(req, res));
2023-01-01 18:09:08 +01:00
app.get("/cors", async (req, res) => await cors(req, res));
2017-06-29 21:22:00 +02:00
2023-01-01 18:09:08 +01:00
app.get("/version", (req, res) => getVersion(req, res));
2016-10-13 16:42:15 +02:00
2023-10-01 20:13:41 +02:00
app.get("/startup", (req, res) => getStartup(req, res));
app.get("/env", (req, res) => getEnvVars(req, res));
2023-01-01 18:09:08 +01:00
app.get("/", (req, res) => getHtml(req, res));
// Reload endpoint for watch mode - triggers browser reload
app.get("/reload", (req, res) => {
Log.info("Reload request received, notifying all clients");
io.emit("RELOAD");
res.status(200).send("OK");
});
2023-01-01 18:09:08 +01:00
server.on("listening", () => {
resolve({
app,
io
});
});
});
};
2021-09-15 21:09:31 +02:00
2023-01-01 18:09:08 +01:00
/**
* Closes the server and destroys all lingering connections to it.
* @returns {Promise} A promise that resolves when server has successfully shut down
*/
2021-09-15 21:09:31 +02:00
this.close = function () {
2023-01-01 18:09:08 +01:00
return new Promise((resolve) => {
for (const socket of serverSockets.values()) {
socket.destroy();
}
server.close(resolve);
});
2021-09-16 22:36:18 +02:00
};
2021-01-05 18:37:16 +01:00
}
2016-04-03 19:52:13 +02:00
module.exports = Server;