| 1 | import type { IncomingMessage } from 'node:http'; |
| 2 | |
| 3 | import { Protocol, ProtocolVersion } from '../../types'; |
| 4 | import { logPrefix, logger } from '../../utils'; |
| 5 | |
| 6 | export class UIServerUtils { |
| 7 | private constructor() { |
| 8 | // This is intentional |
| 9 | } |
| 10 | |
| 11 | public static handleProtocols = ( |
| 12 | protocols: Set<string>, |
| 13 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 14 | request: IncomingMessage, |
| 15 | ): string | false => { |
| 16 | let protocol: Protocol | undefined; |
| 17 | let version: ProtocolVersion | undefined; |
| 18 | if (protocols.size === 0) { |
| 19 | return false; |
| 20 | } |
| 21 | for (const fullProtocol of protocols) { |
| 22 | if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === true) { |
| 23 | return fullProtocol; |
| 24 | } |
| 25 | } |
| 26 | logger.error( |
| 27 | `${logPrefix( |
| 28 | ' UI WebSocket Server |', |
| 29 | )} Unsupported protocol: '${protocol}' or protocol version: '${version}'`, |
| 30 | ); |
| 31 | return false; |
| 32 | }; |
| 33 | |
| 34 | public static isProtocolAndVersionSupported = (protocolStr: string): boolean => { |
| 35 | const [protocol, version] = UIServerUtils.getProtocolAndVersion(protocolStr); |
| 36 | return ( |
| 37 | Object.values(Protocol).includes(protocol) === true && |
| 38 | Object.values(ProtocolVersion).includes(version) === true |
| 39 | ); |
| 40 | }; |
| 41 | |
| 42 | public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => { |
| 43 | const protocolIndex = protocolStr.indexOf(Protocol.UI); |
| 44 | const protocol = protocolStr.substring( |
| 45 | protocolIndex, |
| 46 | protocolIndex + Protocol.UI.length, |
| 47 | ) as Protocol; |
| 48 | const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion; |
| 49 | return [protocol, version]; |
| 50 | }; |
| 51 | |
| 52 | public static isLoopback(address: string): boolean { |
| 53 | const isLoopbackRegExp = new RegExp( |
| 54 | // eslint-disable-next-line no-useless-escape |
| 55 | /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/, |
| 56 | 'i', |
| 57 | ); |
| 58 | return isLoopbackRegExp.test(address); |
| 59 | } |
| 60 | } |