| 961 | } |
| 962 | |
| 963 | const parseWebSocketFrames = ( |
| 964 | stream: Buffer.Buffer |
| 965 | ): { readonly frames: ReadonlyArray<WebSocketFrame>; readonly trailing: Buffer.Buffer } => { |
| 966 | const frames: Array<WebSocketFrame> = [] |
| 967 | let offset = 0 |
| 968 | while (stream.length - offset >= 2) { |
| 969 | const first = stream[offset] |
| 970 | const second = stream[offset + 1] |
| 971 | const opcode = first & 0x0f |
| 972 | let length = second & 0x7f |
| 973 | let headerSize = 2 |
| 974 | if (length === 126) { |
| 975 | if (stream.length - offset < 4) break |
| 976 | length = stream.readUInt16BE(offset + 2) |
| 977 | headerSize = 4 |
| 978 | } else if (length === 127) { |
| 979 | break |
| 980 | } |
| 981 | const controlFrame = (opcode & 0x8) !== 0 |
| 982 | if ( |
| 983 | (first & 0x70) !== 0 || (second & 0x80) !== 0 || |
| 984 | ![0x0, 0x1, 0x2, 0x8, 0x9, 0xa].includes(opcode) || |
| 985 | (controlFrame && length > 125) |
| 986 | ) { |
| 987 | break |
| 988 | } |
| 989 | if (stream.length - offset < headerSize + length) break |
| 990 | frames.push({ opcode, payload: stream.subarray(offset + headerSize, offset + headerSize + length) }) |
| 991 | offset += headerSize + length |
| 992 | } |
| 993 | return { frames, trailing: stream.subarray(offset) } |
| 994 | } |
| 995 | |
| 996 | const upgradeRequest = (path: string): string => |
| 997 | [ |