-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathserver.js
More file actions
319 lines (265 loc) · 8.31 KB
/
server.js
File metadata and controls
319 lines (265 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/*******************************************************************************
Highcharts Export Server
Copyright (c) 2016-2024, Highsoft
Licenced under the MIT licence.
Additionally a valid Highcharts license is required for use.
See LICENSE file in root for details.
*******************************************************************************/
import { promises as fsPromises } from 'fs';
import { posix } from 'path';
import cors from 'cors';
import express from 'express';
import http from 'http';
import https from 'https';
import multer from 'multer';
import errorHandler from './error.js';
import rateLimit from './rate_limit.js';
import { log, logWithStack } from '../logger.js';
import { __dirname } from '../utils.js';
import vSwitchRoute from './routes/change_hc_version.js';
import exportRoutes from './routes/export.js';
import healthRoute from './routes/health.js';
import uiRoute from './routes/ui.js';
import ExportError from '../errors/ExportError.js';
// Array of an active servers
const activeServers = new Map();
// Create express app
const app = express();
const modulesApp = express();
// Disable the X-Powered-By header
app.disable('x-powered-by');
// Enable CORS support
app.use(cors());
// Getting a lot of RangeNotSatisfiableError exception.
// Even though this is a deprecated options, let's try to set it to false.
app.use((_req, res, next) => {
res.set('Accept-Ranges', 'none');
next();
});
/**
* Attach error handlers to the server.
*
* @param {http.Server} server - The HTTP/HTTPS server instance.
*/
const attachServerErrorHandlers = (server) => {
server.on('clientError', (error, socket) => {
logWithStack(
1,
error,
`[server] Client error: ${error.message}, destroying socket.`
);
socket.destroy();
});
server.on('error', (error) => {
logWithStack(1, error, `[server] Server error: ${error.message}`);
});
server.on('connection', (socket) => {
socket.on('error', (error) => {
logWithStack(1, error, `[server] Socket error: ${error.message}`);
});
});
};
/**
* Starts an HTTP server used for serving module files. This port should not be exposed externally.
*
* @throws {ExportError} - Throws an error if the server cannot be configured
* and started.
*/
export const startModulesServer = async () => {
try {
const port = 5000;
const httpServer = http.createServer(modulesApp);
httpServer.listen(port, '0.0.0.0');
activeServers.set(port, httpServer);
modulesApp.use(express.static(posix.join(__dirname, 'static')));
log(3, `[server] Started Internal Modules server on localhost:${port}.`);
} catch (error) {
throw new ExportError(
'[server] Could not configure and start the modules server.'
).setError(error);
}
};
/**
* Starts an HTTP server based on the provided configuration. The `serverConfig`
* object contains all server related properties (see the `server` section
* in the `lib/schemas/config.js` file for a reference).
*
* @param {Object} serverConfig - The server configuration object.
*
* @throws {ExportError} - Throws an error if the server cannot be configured
* and started.
*/
export const startServer = async (serverConfig) => {
try {
// TODO: Read from config/env
// NOTE:
// Too big limits lead to timeouts in the export process when the
// rasterization timeout is set too low.
const uploadLimitMiB = serverConfig.maxUploadSize || 3;
const uploadLimitBytes = uploadLimitMiB * 1024 * 1024;
// Enable parsing of form data (files) with Multer package
const storage = multer.memoryStorage();
const upload = multer({
storage,
limits: {
fieldSize: uploadLimitBytes
}
});
// Enable body parser
app.use(express.json({ limit: uploadLimitBytes }));
app.use(express.urlencoded({ extended: true, limit: uploadLimitBytes }));
// Use only non-file multipart form fields
app.use(upload.none());
// Stop if not enabled
if (!serverConfig.enable) {
return false;
}
// Listen HTTP server
if (!serverConfig.ssl.force) {
// Main server instance (HTTP)
const httpServer = http.createServer(app);
// Attach error handlers and listen to the server
attachServerErrorHandlers(httpServer);
// Listen
httpServer.listen(serverConfig.port, serverConfig.host);
// Save the reference to HTTP server
activeServers.set(serverConfig.port, httpServer);
log(
3,
`[server] Started HTTP server on ${serverConfig.host}:${serverConfig.port}.`
);
}
// Listen HTTPS server
if (serverConfig.ssl.enable) {
// Set up an SSL server also
let key, cert;
try {
// Get the SSL key
key = await fsPromises.readFile(
posix.join(serverConfig.ssl.certPath, 'server.key'),
'utf8'
);
// Get the SSL certificate
cert = await fsPromises.readFile(
posix.join(serverConfig.ssl.certPath, 'server.crt'),
'utf8'
);
} catch (error) {
log(
2,
`[server] Unable to load key/certificate from the '${serverConfig.ssl.certPath}' path. Could not run secured layer server.`
);
}
if (key && cert) {
// Main server instance (HTTPS)
const httpsServer = https.createServer({ key, cert }, app);
// Attach error handlers and listen to the server
attachServerErrorHandlers(httpsServer);
// Listen
httpsServer.listen(serverConfig.ssl.port, serverConfig.host);
// Save the reference to HTTPS server
activeServers.set(serverConfig.ssl.port, httpsServer);
log(
3,
`[server] Started HTTPS server on ${serverConfig.host}:${serverConfig.ssl.port}.`
);
}
}
// Enable the rate limiter if config says so
if (
serverConfig.rateLimiting &&
serverConfig.rateLimiting.enable &&
![0, NaN].includes(serverConfig.rateLimiting.maxRequests)
) {
rateLimit(app, serverConfig.rateLimiting);
}
// Set up static folder's route
app.use(express.static(posix.join(__dirname, 'public')));
// Set up routes
healthRoute(app);
exportRoutes(app);
uiRoute(app);
vSwitchRoute(app);
// Set up centralized error handler
errorHandler(app);
} catch (error) {
throw new ExportError(
'[server] Could not configure and start the server.'
).setError(error);
}
};
/**
* Closes all servers associated with Express app instance.
*/
export const closeServers = () => {
log(4, `[server] Closing all servers.`);
for (const [port, server] of activeServers) {
server.close(() => {
activeServers.delete(port);
log(4, `[server] Closed server on port: ${port}.`);
});
}
};
/**
* Get all servers associated with Express app instance.
*
* @returns {Array} - Servers associated with Express app instance.
*/
export const getServers = () => activeServers;
/**
* Enable rate limiting for the server.
*
* @param {Object} limitConfig - Configuration object for rate limiting.
*/
export const enableRateLimiting = (limitConfig) => rateLimit(app, limitConfig);
/**
* Get the Express instance.
*
* @returns {Object} - The Express instance.
*/
export const getExpress = () => express;
/**
* Get the Express app instance.
*
* @returns {Object} - The Express app instance.
*/
export const getApp = () => app;
/**
* Apply middleware(s) to a specific path.
*
* @param {string} path - The path to which the middleware(s) should be applied.
* @param {...Function} middlewares - The middleware functions to be applied.
*/
export const use = (path, ...middlewares) => {
app.use(path, ...middlewares);
};
/**
* Set up a route with GET method and apply middleware(s).
*
* @param {string} path - The route path.
* @param {...Function} middlewares - The middleware functions to be applied.
*/
export const get = (path, ...middlewares) => {
app.get(path, ...middlewares);
};
/**
* Set up a route with POST method and apply middleware(s).
*
* @param {string} path - The route path.
* @param {...Function} middlewares - The middleware functions to be applied.
*/
export const post = (path, ...middlewares) => {
app.post(path, ...middlewares);
};
export default {
startServer,
startModulesServer,
closeServers,
getServers,
enableRateLimiting,
getExpress,
getApp,
use,
get,
post
};