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