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