| 2704 | } |
| 2705 | |
| 2706 | const parseWebSocketFrames = ( |
| 2707 | stream: Buffer.Buffer |
| 2708 | ): { readonly frames: ReadonlyArray<WebSocketFrame>; readonly trailing: Buffer.Buffer } => { |
| 2709 | const frames: Array<WebSocketFrame> = [] |
| 2710 | let offset = 0 |
| 2711 | while (stream.length - offset >= 2) { |
| 2712 | const first = stream[offset] |
| 2713 | const second = stream[offset + 1] |
| 2714 | const opcode = first & 0x0f |
| 2715 | let length = second & 0x7f |
| 2716 | let headerSize = 2 |
| 2717 | if (length === 126) { |
| 2718 | if (stream.length - offset < 4) break |
| 2719 | length = stream.readUInt16BE(offset + 2) |
| 2720 | headerSize = 4 |
| 2721 | } else if (length === 127) { |
| 2722 | break |
| 2723 | } |
| 2724 | const controlFrame = (opcode & 0x8) !== 0 |
| 2725 | if ( |
| 2726 | (first & 0x70) !== 0 || (second & 0x80) !== 0 || |
| 2727 | ![0x0, 0x1, 0x2, 0x8, 0x9, 0xa].includes(opcode) || |
| 2728 | (controlFrame && length > 125) |
| 2729 | ) { |
| 2730 | break |
| 2731 | } |
| 2732 | if (stream.length - offset < headerSize + length) break |
| 2733 | frames.push({ opcode, payload: stream.subarray(offset + headerSize, offset + headerSize + length) }) |
| 2734 | offset += headerSize + length |
| 2735 | } |
| 2736 | return { frames, trailing: stream.subarray(offset) } |
| 2737 | } |
| 2738 | |
| 2739 | const upgradeRequest = (path: string): string => |
| 2740 | [ |