From 66759a87f2955b811a5756edeb1c654ea376692b Mon Sep 17 00:00:00 2001 From: Dennis Postma Date: Sun, 9 Feb 2025 02:09:58 +0100 Subject: [PATCH] Use https if config is present --- src/managers/httpManager.ts | 23 ++++++++++++++++++----- src/server.ts | 2 +- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/managers/httpManager.ts b/src/managers/httpManager.ts index 460e85a..ae75070 100644 --- a/src/managers/httpManager.ts +++ b/src/managers/httpManager.ts @@ -1,4 +1,6 @@ +import fs from 'fs' import { createServer as httpServer, Server as HTTPServer } from 'http' +import { createServer as httpsServer, Server as HTTPSServer } from 'https' import cors from 'cors' import express, { type Application } from 'express' @@ -15,7 +17,7 @@ import { TexturesController } from '#controllers/textures' */ class HttpManager { private readonly app: Application - private readonly http: HTTPServer + private readonly server: HTTPServer | HTTPSServer private readonly logger = Logger.type(LoggerType.APP) private readonly authController: AuthController = new AuthController() private readonly avatarController: AvatarController = new AvatarController() @@ -27,7 +29,18 @@ class HttpManager { this.app.use(cors()) this.app.use(express.json()) this.app.use(express.urlencoded({ extended: true })) - this.http = httpServer(this.app) + + if (config.PUBLIC_KEY_PATH && config.PRIVATE_KEY_PATH) { + const credentials = { + key: fs.readFileSync(config.PRIVATE_KEY_PATH), + cert: fs.readFileSync(config.PUBLIC_KEY_PATH) + } + this.server = httpsServer(credentials, this.app) + this.logger.info('HTTPS server initialized') + } else { + this.server = httpServer(this.app) + this.logger.info('HTTP server initialized') + } } /** @@ -35,7 +48,7 @@ class HttpManager { * @param app */ public async boot(app: Application) { - this.http.listen(config.PORT, config.HOST) + this.server.listen(config.PORT, config.HOST) // Add CORS middleware app.use( @@ -80,8 +93,8 @@ class HttpManager { return this.app } - getHttpInstance(): HTTPServer { - return this.http + getServerInstance(): HTTPServer | HTTPSServer { + return this.server } } diff --git a/src/server.ts b/src/server.ts index a8ed7b0..7451554 100644 --- a/src/server.ts +++ b/src/server.ts @@ -21,7 +21,7 @@ export class Server { // Initialize managers await Promise.all([ HttpManager.boot(HttpManager.getAppInstance()), - SocketManager.boot(HttpManager.getAppInstance(), HttpManager.getHttpInstance()), + SocketManager.boot(HttpManager.getAppInstance(), HttpManager.getServerInstance()), QueueManager.boot(), UserManager.boot(), MapManager.boot(),