WS UI Server: do not crash the server at authentication error
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIWebSocketServer.ts
1 import { IncomingMessage, createServer } from 'http';
2 import type internal from 'stream';
3
4 import { StatusCodes } from 'http-status-codes';
5 import WebSocket, { RawData, WebSocketServer } from 'ws';
6
7 import BaseError from '../../exception/BaseError';
8 import type { UIServerConfiguration } from '../../types/ConfigurationData';
9 import type { ProtocolRequest, ProtocolResponse } from '../../types/UIProtocol';
10 import { WebSocketCloseEventStatusCode } from '../../types/WebSocket';
11 import logger from '../../utils/Logger';
12 import Utils from '../../utils/Utils';
13 import { AbstractUIServer } from './AbstractUIServer';
14 import UIServiceFactory from './ui-services/UIServiceFactory';
15 import { UIServiceUtils } from './ui-services/UIServiceUtils';
16
17 const moduleName = 'UIWebSocketServer';
18
19 export default class UIWebSocketServer extends AbstractUIServer {
20 private readonly webSocketServer: WebSocketServer;
21
22 public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) {
23 super(uiServerConfiguration);
24 this.httpServer = createServer();
25 this.webSocketServer = new WebSocketServer({
26 handleProtocols: UIServiceUtils.handleProtocols,
27 noServer: true,
28 });
29 }
30
31 public start(): void {
32 this.webSocketServer.on('connection', (ws: WebSocket, req: IncomingMessage): void => {
33 const [protocol, version] = UIServiceUtils.getProtocolAndVersion(ws.protocol);
34 if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) {
35 logger.error(
36 `${this.logPrefix(
37 moduleName,
38 'start.server.onconnection'
39 )} Unsupported UI protocol version: '${protocol}${version}'`
40 );
41 ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR);
42 }
43 if (this.uiServices.has(version) === false) {
44 this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this));
45 }
46 ws.on('message', (rawData) => {
47 const [messageId, procedureName, payload] = this.validateRawDataRequest(rawData);
48 this.uiServices
49 .get(version)
50 .requestHandler(this.buildProtocolRequest(messageId, procedureName, payload))
51 .catch(() => {
52 /* Error caught by AbstractUIService */
53 });
54 });
55 ws.on('error', (error) => {
56 logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error);
57 });
58 ws.on('close', (code, reason) => {
59 logger.debug(
60 `${this.logPrefix(
61 moduleName,
62 'start.ws.onclose'
63 )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString(
64 code
65 )}' - '${reason.toString()}'`
66 );
67 });
68 });
69 this.httpServer.on(
70 'upgrade',
71 (req: IncomingMessage, socket: internal.Duplex, head: Buffer): void => {
72 this.authenticate(req, (err) => {
73 if (err) {
74 socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
75 socket.destroy();
76 return;
77 }
78 this.webSocketServer.handleUpgrade(req, socket, head, (ws: WebSocket) => {
79 this.webSocketServer.emit('connection', ws, req);
80 });
81 });
82 }
83 );
84 if (this.httpServer.listening === false) {
85 this.httpServer.listen(this.uiServerConfiguration.options);
86 }
87 }
88
89 public stop(): void {
90 this.chargingStations.clear();
91 }
92
93 public sendRequest(request: ProtocolRequest): void {
94 this.broadcastToClients(JSON.stringify(request));
95 }
96
97 public sendResponse(response: ProtocolResponse): void {
98 // TODO: send response only to the client that sent the request
99 this.broadcastToClients(JSON.stringify(response));
100 }
101
102 public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string {
103 const logMsgPrefix = prefixSuffix
104 ? `UI WebSocket Server ${prefixSuffix}`
105 : 'UI WebSocket Server';
106 const logMsg =
107 modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
108 return Utils.logPrefix(logMsg);
109 }
110
111 private broadcastToClients(message: string): void {
112 for (const client of this.webSocketServer.clients) {
113 if (client?.readyState === WebSocket.OPEN) {
114 client.send(message);
115 }
116 }
117 }
118
119 private authenticate(req: IncomingMessage, next: (err?: Error) => void): void {
120 if (this.isBasicAuthEnabled() === true) {
121 if (this.isValidBasicAuth(req) === false) {
122 next(new Error('Unauthorized'));
123 } else {
124 next();
125 }
126 } else {
127 next();
128 }
129 }
130
131 private validateRawDataRequest(rawData: RawData): ProtocolRequest {
132 // logger.debug(
133 // `${this.logPrefix(
134 // moduleName,
135 // 'validateRawDataRequest'
136 // )} Raw data received in string format: ${rawData.toString()}`
137 // );
138
139 const request = JSON.parse(rawData.toString()) as ProtocolRequest;
140
141 if (Array.isArray(request) === false) {
142 throw new BaseError('UI protocol request is not an array');
143 }
144
145 if (request.length !== 3) {
146 throw new BaseError('UI protocol request is malformed');
147 }
148
149 return request;
150 }
151 }