| 1 | import type { IncomingMessage } from 'node:http' |
| 2 | |
| 3 | import { BaseError } from '../../exception/index.js' |
| 4 | import { Protocol, ProtocolVersion } from '../../types/index.js' |
| 5 | import { logger, logPrefix } from '../../utils/index.js' |
| 6 | |
| 7 | export const getUsernameAndPasswordFromAuthorizationToken = ( |
| 8 | authorizationToken: string, |
| 9 | next: (err?: Error) => void |
| 10 | ): [string, string] => { |
| 11 | if ( |
| 12 | !/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/.test(authorizationToken) |
| 13 | ) { |
| 14 | next(new BaseError('Invalid basic authentication token format')) |
| 15 | } |
| 16 | const authentication = Buffer.from(authorizationToken, 'base64').toString() |
| 17 | const authenticationParts = authentication.split(/:/) |
| 18 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 19 | return [authenticationParts.shift()!, authenticationParts.join(':')] |
| 20 | } |
| 21 | |
| 22 | export const handleProtocols = ( |
| 23 | protocols: Set<string>, |
| 24 | _request: IncomingMessage |
| 25 | ): false | string => { |
| 26 | let protocol: Protocol | undefined |
| 27 | let version: ProtocolVersion | undefined |
| 28 | if (protocols.size === 0) { |
| 29 | return false |
| 30 | } |
| 31 | for (const fullProtocol of protocols) { |
| 32 | if (isProtocolAndVersionSupported(fullProtocol)) { |
| 33 | return fullProtocol |
| 34 | } |
| 35 | } |
| 36 | logger.error( |
| 37 | `${logPrefix( |
| 38 | ' UI WebSocket Server |' |
| 39 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 40 | )} Unsupported protocol: '${protocol}' or protocol version: '${version}'` |
| 41 | ) |
| 42 | return false |
| 43 | } |
| 44 | |
| 45 | export const isProtocolAndVersionSupported = (protocolStr: string): boolean => { |
| 46 | const [protocol, version] = getProtocolAndVersion(protocolStr) |
| 47 | return ( |
| 48 | Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version) |
| 49 | ) |
| 50 | } |
| 51 | |
| 52 | export const getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => { |
| 53 | const protocolIndex = protocolStr.indexOf(Protocol.UI) |
| 54 | const protocol = protocolStr.substring( |
| 55 | protocolIndex, |
| 56 | protocolIndex + Protocol.UI.length |
| 57 | ) as Protocol |
| 58 | const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion |
| 59 | return [protocol, version] |
| 60 | } |
| 61 | |
| 62 | export const isLoopback = (address: string): boolean => { |
| 63 | // eslint-disable-next-line no-useless-escape |
| 64 | return /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/i.test(address) |
| 65 | } |