Commit | Line | Data |
---|---|---|
01f4001e | 1 | import type { IncomingMessage } from 'node:http'; |
8114d10e | 2 | |
268a74bb | 3 | import { Protocol, ProtocolVersion } from '../../types'; |
9bf0ef23 | 4 | import { logPrefix, logger } from '../../utils'; |
4198ad5c | 5 | |
ed3d2808 | 6 | export class UIServerUtils { |
d5bd1c00 JB |
7 | private constructor() { |
8 | // This is intentional | |
9 | } | |
10 | ||
e7aeea18 JB |
11 | public static handleProtocols = ( |
12 | protocols: Set<string>, | |
7cb5b17f | 13 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
5edd8ba0 | 14 | request: IncomingMessage, |
e7aeea18 | 15 | ): string | false => { |
e1d9a0f4 JB |
16 | let protocol: Protocol | undefined; |
17 | let version: ProtocolVersion | undefined; | |
a92929f1 JB |
18 | if (protocols.size === 0) { |
19 | return false; | |
20 | } | |
4198ad5c | 21 | for (const fullProtocol of protocols) { |
ed3d2808 | 22 | if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === true) { |
4198ad5c JB |
23 | return fullProtocol; |
24 | } | |
25 | } | |
e7aeea18 | 26 | logger.error( |
9bf0ef23 | 27 | `${logPrefix( |
5edd8ba0 | 28 | ' UI WebSocket Server |', |
90aceaf6 | 29 | )} Unsupported protocol: '${protocol}' or protocol version: '${version}'`, |
e7aeea18 | 30 | ); |
4198ad5c JB |
31 | return false; |
32 | }; | |
d5bd1c00 | 33 | |
7cb5b17f | 34 | public static isProtocolAndVersionSupported = (protocolStr: string): boolean => { |
ed3d2808 | 35 | const [protocol, version] = UIServerUtils.getProtocolAndVersion(protocolStr); |
7cb5b17f JB |
36 | return ( |
37 | Object.values(Protocol).includes(protocol) === true && | |
38 | Object.values(ProtocolVersion).includes(version) === true | |
39 | ); | |
40 | }; | |
1f7fa4de | 41 | |
a92929f1 JB |
42 | public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => { |
43 | const protocolIndex = protocolStr.indexOf(Protocol.UI); | |
44 | const protocol = protocolStr.substring( | |
45 | protocolIndex, | |
5edd8ba0 | 46 | protocolIndex + Protocol.UI.length, |
a92929f1 JB |
47 | ) as Protocol; |
48 | const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion; | |
49 | return [protocol, version]; | |
50 | }; | |
51 | ||
d5bd1c00 JB |
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$/, | |
5edd8ba0 | 56 | 'i', |
d5bd1c00 JB |
57 | ); |
58 | return isLoopbackRegExp.test(address); | |
59 | } | |
4198ad5c | 60 | } |