| 1 | import type { IncomingMessage } from 'node:http' |
| 2 | |
| 3 | import { Protocol, ProtocolVersion } from '../../types/index.js' |
| 4 | import { logPrefix, logger } from '../../utils/index.js' |
| 5 | |
| 6 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class |
| 7 | export class UIServerUtils { |
| 8 | private constructor () { |
| 9 | // This is intentional |
| 10 | } |
| 11 | |
| 12 | public static readonly handleProtocols = ( |
| 13 | protocols: Set<string>, |
| 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)) { |
| 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 readonly isProtocolAndVersionSupported = (protocolStr: string): boolean => { |
| 35 | const [protocol, version] = UIServerUtils.getProtocolAndVersion(protocolStr) |
| 36 | return ( |
| 37 | Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version) |
| 38 | ) |
| 39 | } |
| 40 | |
| 41 | public static readonly getProtocolAndVersion = ( |
| 42 | protocolStr: string |
| 43 | ): [Protocol, ProtocolVersion] => { |
| 44 | const protocolIndex = protocolStr.indexOf(Protocol.UI) |
| 45 | const protocol = protocolStr.substring( |
| 46 | protocolIndex, |
| 47 | protocolIndex + Protocol.UI.length |
| 48 | ) as Protocol |
| 49 | const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion |
| 50 | return [protocol, version] |
| 51 | } |
| 52 | |
| 53 | public static isLoopback (address: string): boolean { |
| 54 | // eslint-disable-next-line no-useless-escape |
| 55 | return /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/i.test(address) |
| 56 | } |
| 57 | } |