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