| 1 | import type { IncomingMessage } from 'http'; |
| 2 | import type internal from 'stream'; |
| 3 | |
| 4 | import { StatusCodes } from 'http-status-codes'; |
| 5 | import WebSocket, { type RawData, WebSocketServer } from 'ws'; |
| 6 | |
| 7 | import type { UIServerConfiguration } from '../../types/ConfigurationData'; |
| 8 | import type { ProtocolRequest, ProtocolResponse } from '../../types/UIProtocol'; |
| 9 | import { WebSocketCloseEventStatusCode } from '../../types/WebSocket'; |
| 10 | import logger from '../../utils/Logger'; |
| 11 | import Utils from '../../utils/Utils'; |
| 12 | import { AbstractUIServer } from './AbstractUIServer'; |
| 13 | import { UIServerUtils } from './UIServerUtils'; |
| 14 | |
| 15 | const moduleName = 'UIWebSocketServer'; |
| 16 | |
| 17 | export default class UIWebSocketServer extends AbstractUIServer { |
| 18 | private readonly webSocketServer: WebSocketServer; |
| 19 | |
| 20 | public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) { |
| 21 | super(uiServerConfiguration); |
| 22 | this.webSocketServer = new WebSocketServer({ |
| 23 | handleProtocols: UIServerUtils.handleProtocols, |
| 24 | noServer: true, |
| 25 | }); |
| 26 | } |
| 27 | |
| 28 | public start(): void { |
| 29 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 30 | this.webSocketServer.on('connection', (ws: WebSocket, req: IncomingMessage): void => { |
| 31 | if (UIServerUtils.isProtocolAndVersionSupported(ws.protocol) === false) { |
| 32 | logger.error( |
| 33 | `${this.logPrefix( |
| 34 | moduleName, |
| 35 | 'start.server.onconnection' |
| 36 | )} Unsupported UI protocol version: '${ws.protocol}'` |
| 37 | ); |
| 38 | ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR); |
| 39 | } |
| 40 | const [, version] = UIServerUtils.getProtocolAndVersion(ws.protocol); |
| 41 | this.registerProtocolVersionUIService(version); |
| 42 | ws.on('message', (rawData) => { |
| 43 | const request = this.validateRawDataRequest(rawData); |
| 44 | if (request === false) { |
| 45 | ws.close(WebSocketCloseEventStatusCode.CLOSE_INVALID_PAYLOAD); |
| 46 | return; |
| 47 | } |
| 48 | const [requestId] = request as ProtocolRequest; |
| 49 | this.responseHandlers.set(requestId, ws); |
| 50 | this.uiServices |
| 51 | .get(version) |
| 52 | .requestHandler(request) |
| 53 | .catch(() => { |
| 54 | /* Error caught by AbstractUIService */ |
| 55 | }); |
| 56 | }); |
| 57 | ws.on('error', (error) => { |
| 58 | logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error); |
| 59 | }); |
| 60 | ws.on('close', (code, reason) => { |
| 61 | logger.debug( |
| 62 | `${this.logPrefix( |
| 63 | moduleName, |
| 64 | 'start.ws.onclose' |
| 65 | )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString( |
| 66 | code |
| 67 | )}' - '${reason.toString()}'` |
| 68 | ); |
| 69 | }); |
| 70 | }); |
| 71 | this.httpServer.on( |
| 72 | 'upgrade', |
| 73 | (req: IncomingMessage, socket: internal.Duplex, head: Buffer): void => { |
| 74 | this.authenticate(req, (err) => { |
| 75 | if (err) { |
| 76 | socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`); |
| 77 | socket.destroy(); |
| 78 | return; |
| 79 | } |
| 80 | this.webSocketServer.handleUpgrade(req, socket, head, (ws: WebSocket) => { |
| 81 | this.webSocketServer.emit('connection', ws, req); |
| 82 | }); |
| 83 | }); |
| 84 | } |
| 85 | ); |
| 86 | this.startHttpServer(); |
| 87 | } |
| 88 | |
| 89 | public sendRequest(request: ProtocolRequest): void { |
| 90 | this.broadcastToClients(JSON.stringify(request)); |
| 91 | } |
| 92 | |
| 93 | public sendResponse(response: ProtocolResponse): void { |
| 94 | const responseId = response[0]; |
| 95 | try { |
| 96 | if (this.responseHandlers.has(responseId)) { |
| 97 | const ws = this.responseHandlers.get(responseId) as WebSocket; |
| 98 | if (ws?.readyState === WebSocket.OPEN) { |
| 99 | ws.send(JSON.stringify(response)); |
| 100 | } else { |
| 101 | logger.error( |
| 102 | `${this.logPrefix( |
| 103 | moduleName, |
| 104 | 'sendResponse' |
| 105 | )} Error at sending response id '${responseId}', WebSocket is not open: ${ |
| 106 | ws?.readyState |
| 107 | }` |
| 108 | ); |
| 109 | } |
| 110 | } else { |
| 111 | logger.error( |
| 112 | `${this.logPrefix( |
| 113 | moduleName, |
| 114 | 'sendResponse' |
| 115 | )} Response for unknown request id: ${responseId}` |
| 116 | ); |
| 117 | } |
| 118 | } catch (error) { |
| 119 | logger.error( |
| 120 | `${this.logPrefix( |
| 121 | moduleName, |
| 122 | 'sendResponse' |
| 123 | )} Error at sending response id '${responseId}':`, |
| 124 | error |
| 125 | ); |
| 126 | } finally { |
| 127 | this.responseHandlers.delete(responseId); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string { |
| 132 | const logMsgPrefix = prefixSuffix |
| 133 | ? `UI WebSocket Server ${prefixSuffix}` |
| 134 | : 'UI WebSocket Server'; |
| 135 | const logMsg = |
| 136 | modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`; |
| 137 | return Utils.logPrefix(logMsg); |
| 138 | } |
| 139 | |
| 140 | private broadcastToClients(message: string): void { |
| 141 | for (const client of this.webSocketServer.clients) { |
| 142 | if (client?.readyState === WebSocket.OPEN) { |
| 143 | client.send(message); |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | private validateRawDataRequest(rawData: RawData): ProtocolRequest | false { |
| 149 | // logger.debug( |
| 150 | // `${this.logPrefix( |
| 151 | // moduleName, |
| 152 | // 'validateRawDataRequest' |
| 153 | // )} Raw data received in string format: ${rawData.toString()}` |
| 154 | // ); |
| 155 | |
| 156 | const request = JSON.parse(rawData.toString()) as ProtocolRequest; |
| 157 | |
| 158 | if (Array.isArray(request) === false) { |
| 159 | logger.error( |
| 160 | `${this.logPrefix( |
| 161 | moduleName, |
| 162 | 'validateRawDataRequest' |
| 163 | )} UI protocol request is not an array:`, |
| 164 | request |
| 165 | ); |
| 166 | return false; |
| 167 | } |
| 168 | |
| 169 | if (request.length !== 3) { |
| 170 | logger.error( |
| 171 | `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`, |
| 172 | request |
| 173 | ); |
| 174 | return false; |
| 175 | } |
| 176 | |
| 177 | if (Utils.validateUUID(request[0]) === false) { |
| 178 | logger.error( |
| 179 | `${this.logPrefix( |
| 180 | moduleName, |
| 181 | 'validateRawDataRequest' |
| 182 | )} UI protocol request UUID field is invalid:`, |
| 183 | request |
| 184 | ); |
| 185 | return false; |
| 186 | } |
| 187 | |
| 188 | return request; |
| 189 | } |
| 190 | } |