@netifyjs/netify 0.0.0-stage → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/package.json +65 -4
  4. package/src/bootstrap/client/index.ts +191 -0
  5. package/src/bootstrap/dispatcher/index.ts +204 -0
  6. package/src/bootstrap/index.ts +22 -0
  7. package/src/bootstrap/reconnect/index.ts +334 -0
  8. package/src/bootstrap/server/index.ts +284 -0
  9. package/src/buffer/bits/index.ts +2 -0
  10. package/src/buffer/bits/reader/index.ts +64 -0
  11. package/src/buffer/bits/writer/index.ts +79 -0
  12. package/src/buffer/index.ts +1375 -0
  13. package/src/buffer/pool/index.ts +46 -0
  14. package/src/buffer/quantizer/index.ts +101 -0
  15. package/src/channel/attribute/index.ts +89 -0
  16. package/src/channel/context/index.ts +621 -0
  17. package/src/channel/group/index.ts +256 -0
  18. package/src/channel/handler/duplex/index.ts +105 -0
  19. package/src/channel/handler/inbound/index.ts +78 -0
  20. package/src/channel/handler/index.ts +135 -0
  21. package/src/channel/handler/outbound/index.ts +33 -0
  22. package/src/channel/index.ts +619 -0
  23. package/src/channel/initializer/index.ts +77 -0
  24. package/src/channel/outbound/index.ts +611 -0
  25. package/src/channel/pipeline/head/index.ts +100 -0
  26. package/src/channel/pipeline/index.ts +414 -0
  27. package/src/channel/pipeline/tail/index.ts +45 -0
  28. package/src/channel/pipeline/tracker/index.ts +120 -0
  29. package/src/channel/queue/index.ts +203 -0
  30. package/src/channel/resolved/index.ts +34 -0
  31. package/src/channel/server/index.ts +164 -0
  32. package/src/channel/shutdown/index.ts +25 -0
  33. package/src/channel/simple/index.ts +38 -0
  34. package/src/channel/transport/index.ts +74 -0
  35. package/src/channel/transport/socket/index.ts +80 -0
  36. package/src/cluster/index.ts +360 -0
  37. package/src/codec/binary/index.ts +102 -0
  38. package/src/codec/decoder/index.ts +479 -0
  39. package/src/codec/delimiter/index.ts +189 -0
  40. package/src/codec/encoder/index.ts +48 -0
  41. package/src/codec/error/index.ts +33 -0
  42. package/src/codec/fixed/index.ts +45 -0
  43. package/src/codec/http/aggregator/index.ts +236 -0
  44. package/src/codec/http/client/index.ts +120 -0
  45. package/src/codec/http/decoder/index.ts +4 -0
  46. package/src/codec/http/decoder/object/index.ts +644 -0
  47. package/src/codec/http/decoder/request/index.ts +49 -0
  48. package/src/codec/http/decoder/response/index.ts +59 -0
  49. package/src/codec/http/encoder/index.ts +3 -0
  50. package/src/codec/http/encoder/object/index.ts +196 -0
  51. package/src/codec/http/encoder/request/index.ts +24 -0
  52. package/src/codec/http/encoder/response/index.ts +26 -0
  53. package/src/codec/http/headers/index.ts +287 -0
  54. package/src/codec/http/index.ts +33 -0
  55. package/src/codec/http/message/content/index.ts +36 -0
  56. package/src/codec/http/message/full/index.ts +10 -0
  57. package/src/codec/http/message/full/request/index.ts +45 -0
  58. package/src/codec/http/message/full/response/index.ts +43 -0
  59. package/src/codec/http/message/head/index.ts +79 -0
  60. package/src/codec/http/message/index.ts +16 -0
  61. package/src/codec/http/message/last/index.ts +27 -0
  62. package/src/codec/http/message/request/index.ts +39 -0
  63. package/src/codec/http/message/response/index.ts +31 -0
  64. package/src/codec/http/method/index.ts +101 -0
  65. package/src/codec/http/server/index.ts +81 -0
  66. package/src/codec/http/status/index.ts +170 -0
  67. package/src/codec/http/version/index.ts +70 -0
  68. package/src/codec/index.ts +83 -0
  69. package/src/codec/length/index.ts +330 -0
  70. package/src/codec/line/index.ts +45 -0
  71. package/src/codec/message/decoder/index.ts +84 -0
  72. package/src/codec/message/encoder/index.ts +56 -0
  73. package/src/codec/message/index.ts +2 -0
  74. package/src/codec/msgpack/index.ts +51 -0
  75. package/src/codec/prepender/index.ts +296 -0
  76. package/src/codec/protobuf/index.ts +57 -0
  77. package/src/codec/string/decoder/index.ts +47 -0
  78. package/src/codec/string/encoder/index.ts +26 -0
  79. package/src/codec/string/index.ts +2 -0
  80. package/src/codec/websocket/client/index.ts +235 -0
  81. package/src/codec/websocket/decoder/index.ts +371 -0
  82. package/src/codec/websocket/encoder/index.ts +170 -0
  83. package/src/codec/websocket/error/index.ts +42 -0
  84. package/src/codec/websocket/frame/base/index.ts +55 -0
  85. package/src/codec/websocket/frame/binary/index.ts +24 -0
  86. package/src/codec/websocket/frame/close/index.ts +82 -0
  87. package/src/codec/websocket/frame/continuation/index.ts +31 -0
  88. package/src/codec/websocket/frame/index.ts +10 -0
  89. package/src/codec/websocket/frame/opcode/index.ts +35 -0
  90. package/src/codec/websocket/frame/ping/index.ts +24 -0
  91. package/src/codec/websocket/frame/pong/index.ts +24 -0
  92. package/src/codec/websocket/frame/text/index.ts +31 -0
  93. package/src/codec/websocket/handshake/index.ts +38 -0
  94. package/src/codec/websocket/index.ts +25 -0
  95. package/src/codec/websocket/key/index.ts +41 -0
  96. package/src/codec/websocket/protocol/index.ts +147 -0
  97. package/src/codec/websocket/server/index.ts +233 -0
  98. package/src/codec/websocket/status/index.ts +97 -0
  99. package/src/codec/websocket/upgrade/index.ts +116 -0
  100. package/src/datagram/bootstrap/index.ts +269 -0
  101. package/src/datagram/channel/index.ts +103 -0
  102. package/src/datagram/index.ts +10 -0
  103. package/src/datagram/packet/index.ts +72 -0
  104. package/src/datagram/transport/index.ts +239 -0
  105. package/src/handler/flush/index.ts +187 -0
  106. package/src/handler/idle/index.ts +295 -0
  107. package/src/handler/index.ts +22 -0
  108. package/src/handler/logging/index.ts +195 -0
  109. package/src/handler/metrics/index.ts +300 -0
  110. package/src/handler/offload/index.ts +141 -0
  111. package/src/handler/timeout/error/index.ts +29 -0
  112. package/src/handler/timeout/index.ts +3 -0
  113. package/src/handler/timeout/read/index.ts +44 -0
  114. package/src/handler/timeout/write/index.ts +89 -0
  115. package/src/handler/traffic/index.ts +259 -0
  116. package/src/index.ts +258 -0
  117. package/src/logger/index.ts +47 -0
  118. package/src/reliable/bootstrap/index.ts +154 -0
  119. package/src/reliable/cipher/index.ts +227 -0
  120. package/src/reliable/cookie/index.ts +78 -0
  121. package/src/reliable/handler/index.ts +1202 -0
  122. package/src/reliable/handshake/index.ts +144 -0
  123. package/src/reliable/index.ts +38 -0
  124. package/src/reliable/lane/index.ts +420 -0
  125. package/src/reliable/message/index.ts +102 -0
  126. package/src/reliable/packet/index.ts +117 -0
  127. package/src/reliable/peer/index.ts +929 -0
  128. package/src/reliable/registry/index.ts +107 -0
  129. package/src/serve/bootstrap/index.ts +606 -0
  130. package/src/serve/channel/index.ts +246 -0
  131. package/src/serve/index.ts +17 -0
  132. package/src/serve/outbox/index.ts +292 -0
  133. package/src/serve/transport/index.ts +96 -0
  134. package/src/serve/writer/index.ts +119 -0
  135. package/src/shard/envelope/index.ts +44 -0
  136. package/src/shard/gateway/index.ts +119 -0
  137. package/src/shard/index.ts +11 -0
  138. package/src/shard/link/index.ts +743 -0
  139. package/src/shard/map/index.ts +91 -0
  140. package/src/worker/group/index.ts +175 -0
  141. package/src/worker/index.ts +10 -0
  142. package/src/worker/pool/index.ts +235 -0
  143. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,235 @@
1
+ import { HttpHeaders } from '../../http/headers/index.ts'
2
+ import { FullHttpRequest } from '../../http/message/full/request/index.ts'
3
+ import { FullHttpResponse } from '../../http/message/full/response/index.ts'
4
+ import { HttpMethod } from '../../http/method/index.ts'
5
+ import { WebSocketFrameDecoder } from '../decoder/index.ts'
6
+ import { WebSocketFrameEncoder } from '../encoder/index.ts'
7
+ import { HandshakeError } from '../error/index.ts'
8
+ import { WebSocketHandshakeComplete } from '../handshake/index.ts'
9
+ import { WebSocketKey } from '../key/index.ts'
10
+ import { WebSocketProtocolHandler } from '../protocol/index.ts'
11
+ import { WebSocketUpgrade } from '../upgrade/index.ts'
12
+ import type { HandlerContext } from '../../../channel/context/index.ts'
13
+
14
+ /**
15
+ * Settings for WebSocketClientProtocolHandler
16
+ */
17
+ export type WebSocketClientOptions = {
18
+ /**
19
+ * Server URL, ws, wss, http and https all work
20
+ */
21
+ readonly uri: string
22
+
23
+ /**
24
+ * Subprotocols to ask for, in order of preference
25
+ */
26
+ readonly subprotocols?: readonly string[]
27
+
28
+ /**
29
+ * Added to the upgrade request, handy for auth or cookies
30
+ */
31
+ readonly headers?: HttpHeaders
32
+
33
+ /**
34
+ * Payload cap for inbound frames, 64 KiB by default
35
+ */
36
+ readonly maxFramePayloadLength?: number
37
+ }
38
+
39
+ /**
40
+ * Sends the upgrade request once connected and runs the protocol after the 101
41
+ * @class
42
+ */
43
+ export class WebSocketClientProtocolHandler extends WebSocketProtocolHandler {
44
+ /**
45
+ * Parsed server URL
46
+ */
47
+ private readonly target: URL
48
+
49
+ /**
50
+ * Subprotocols we ask for
51
+ */
52
+ private readonly subprotocols: readonly string[]
53
+
54
+ /**
55
+ * Caller's extra upgrade headers
56
+ */
57
+ private readonly headers: HttpHeaders
58
+
59
+ /**
60
+ * Passed on to the frame decoder
61
+ */
62
+ private readonly maxFramePayloadLength: number
63
+
64
+ /**
65
+ * Fresh for each connection, checked against Sec-WebSocket-Accept
66
+ */
67
+ private key: WebSocketKey
68
+
69
+ /**
70
+ * Once set, responses pass straight through
71
+ */
72
+ private upgraded: boolean
73
+
74
+ /**
75
+ * Sets up the handler from a URL or full options
76
+ * @param options a URL on its own, or full options
77
+ */
78
+ public constructor(options: WebSocketClientOptions | string) {
79
+ super(false)
80
+
81
+ const settings = typeof options === 'string' ? { uri: options } : options
82
+ this.target = WebSocketClientProtocolHandler.parse(settings.uri)
83
+ this.subprotocols = settings.subprotocols ?? []
84
+ this.headers = settings.headers ?? new HttpHeaders()
85
+ this.maxFramePayloadLength =
86
+ settings.maxFramePayloadLength ??
87
+ WebSocketFrameDecoder.defaultMaxFramePayloadLength
88
+ this.key = new WebSocketKey()
89
+ this.upgraded = false
90
+ }
91
+
92
+ /**
93
+ * Parses the URL, refusing anything that isn't ws, wss, http or https
94
+ * @param uri URL from the options
95
+ */
96
+ private static parse(uri: string): URL {
97
+ let target: URL
98
+ try {
99
+ target = new URL(uri)
100
+ } catch (cause) {
101
+ throw new TypeError('Address is invalid', { cause })
102
+ }
103
+
104
+ if (!['ws:', 'wss:', 'http:', 'https:'].includes(target.protocol)) {
105
+ throw new TypeError('Address is invalid')
106
+ }
107
+
108
+ return target
109
+ }
110
+
111
+ /**
112
+ * Lets the channel go active, then sends the upgrade with a new key
113
+ * @param context where the upgrade goes
114
+ */
115
+ public override async channelActive(context: HandlerContext): Promise<void> {
116
+ await context.fireChannelActive()
117
+
118
+ this.key = new WebSocketKey()
119
+ await context.writeAndFlush(this.request())
120
+ }
121
+
122
+ /**
123
+ * Checks the 101 and upgrades, closing and throwing if it's wrong
124
+ * @param context the handler's context
125
+ * @param message usually a FullHttpResponse
126
+ */
127
+ protected async readMessage(
128
+ context: HandlerContext,
129
+ message: unknown,
130
+ ): Promise<void> {
131
+ if (this.upgraded || !(message instanceof FullHttpResponse)) {
132
+ await context.fireChannelRead(message)
133
+ return
134
+ }
135
+
136
+ const reason = this.refusal(message)
137
+ if (reason !== null) {
138
+ await context.close()
139
+ throw new HandshakeError(reason)
140
+ }
141
+
142
+ await this.upgrade(context, message)
143
+ }
144
+
145
+ /**
146
+ * GET with our key, version 13 and any extra headers
147
+ */
148
+ private request(): FullHttpRequest {
149
+ const { pathname, search, host } = this.target
150
+
151
+ const request = new FullHttpRequest(HttpMethod.GET, `${pathname}${search}`)
152
+ for (const [name, value] of this.headers) request.headers.add(name, value)
153
+ request.headers
154
+ .set('Host', host)
155
+ .set('Upgrade', 'websocket')
156
+ .set('Connection', 'Upgrade')
157
+ .set('Sec-WebSocket-Key', this.key.value)
158
+ .set('Sec-WebSocket-Version', '13')
159
+ if (this.subprotocols.length > 0) {
160
+ request.headers.set(
161
+ 'Sec-WebSocket-Protocol',
162
+ this.subprotocols.join(', '),
163
+ )
164
+ }
165
+
166
+ return request
167
+ }
168
+
169
+ /**
170
+ * Needs 101, the right Upgrade and Connection, a matching accept key and a subprotocol we offered
171
+ * @param response reply to our upgrade
172
+ */
173
+ private refusal(response: FullHttpResponse): string | null {
174
+ const { headers } = response
175
+ const accept = headers.get('sec-websocket-accept')?.trim()
176
+ const subprotocol = headers.get('sec-websocket-protocol')?.trim()
177
+
178
+ if (response.status.code !== 101) return 'Status is unexpected'
179
+ if (!headers.hasToken('upgrade', 'websocket')) {
180
+ return 'Upgrade header is invalid'
181
+ }
182
+
183
+ if (!headers.hasToken('connection', 'upgrade')) {
184
+ return 'Connection header is invalid'
185
+ }
186
+
187
+ if (accept !== this.key.accept()) return 'Accept key is invalid'
188
+ if (subprotocol !== undefined && !this.subprotocols.includes(subprotocol)) {
189
+ return 'Subprotocol is unexpected'
190
+ }
191
+
192
+ return null
193
+ }
194
+
195
+ /**
196
+ * Swaps in the frame codecs and fires the handshake event
197
+ * @param context the handler's context
198
+ * @param response the accepted 101
199
+ */
200
+ private async upgrade(
201
+ context: HandlerContext,
202
+ response: FullHttpResponse,
203
+ ): Promise<void> {
204
+ const subprotocol = response.headers.get('sec-websocket-protocol')?.trim()
205
+
206
+ const upgrade = new WebSocketUpgrade(context.pipeline)
207
+ upgrade.install(
208
+ new WebSocketFrameDecoder({
209
+ /**
210
+ * Servers send unmasked frames
211
+ */
212
+ expectMaskedFrames: false,
213
+ /**
214
+ * Our payload cap
215
+ */
216
+ maxFramePayloadLength: this.maxFramePayloadLength,
217
+ }),
218
+ new WebSocketFrameEncoder({
219
+ /**
220
+ * Clients mask their frames
221
+ */
222
+ maskPayload: true,
223
+ }),
224
+ )
225
+ this.upgraded = true
226
+ await context.fireUserEventTriggered(
227
+ new WebSocketHandshakeComplete(
228
+ `${this.target.pathname}${this.target.search}`,
229
+ response.headers,
230
+ subprotocol ?? null,
231
+ ),
232
+ )
233
+ await upgrade.release()
234
+ }
235
+ }
@@ -0,0 +1,371 @@
1
+ import { ByteBuf } from '../../../buffer/index.ts'
2
+ import type { HandlerContext } from '../../../channel/context/index.ts'
3
+ import { ByteToMessageDecoder } from '../../decoder/index.ts'
4
+ import { CorruptedFrameError } from '../error/index.ts'
5
+ import type { WebSocketFrame } from '../frame/base/index.ts'
6
+ import { BinaryWebSocketFrame } from '../frame/binary/index.ts'
7
+ import { CloseWebSocketFrame } from '../frame/close/index.ts'
8
+ import { ContinuationWebSocketFrame } from '../frame/continuation/index.ts'
9
+ import { WebSocketOpcode } from '../frame/opcode/index.ts'
10
+ import { PingWebSocketFrame } from '../frame/ping/index.ts'
11
+ import { PongWebSocketFrame } from '../frame/pong/index.ts'
12
+ import { TextWebSocketFrame } from '../frame/text/index.ts'
13
+ import { WebSocketCloseStatus } from '../status/index.ts'
14
+
15
+ /**
16
+ * Settings for WebSocketFrameDecoder
17
+ */
18
+ export type WebSocketDecoderOptions = {
19
+ /**
20
+ * True on servers, since clients have to mask every frame
21
+ */
22
+ readonly expectMaskedFrames: boolean
23
+
24
+ /**
25
+ * Payloads over this many bytes close with 1009, 64 KiB by default
26
+ */
27
+ readonly maxFramePayloadLength?: number
28
+ }
29
+
30
+ /**
31
+ * Fields packed into the first two header bytes
32
+ */
33
+ type FrameHead = {
34
+ /**
35
+ * The FIN bit
36
+ */
37
+ finalFragment: boolean
38
+
39
+ /**
40
+ * RSV1 to RSV3, which have to be zero without extensions
41
+ */
42
+ reserved: number
43
+
44
+ /**
45
+ * Low four bits of the first byte
46
+ */
47
+ opcode: number
48
+
49
+ /**
50
+ * The MASK bit
51
+ */
52
+ masked: boolean
53
+
54
+ /**
55
+ * Payload length, or 126 and 127 to point at a longer field
56
+ */
57
+ shortLength: number
58
+ }
59
+
60
+ /**
61
+ * Reads RFC 6455 frames off the wire and unmasks them
62
+ * @class
63
+ */
64
+ export class WebSocketFrameDecoder extends ByteToMessageDecoder<WebSocketFrame> {
65
+ /**
66
+ * 64 KiB
67
+ */
68
+ public static readonly defaultMaxFramePayloadLength: number = 65536
69
+
70
+ /**
71
+ * Throws on bad UTF-8, used for close reasons
72
+ */
73
+ private static readonly utf8: TextDecoder = new TextDecoder('utf-8', {
74
+ /**
75
+ * Throw rather than swap in replacement characters
76
+ */
77
+ fatal: true,
78
+ })
79
+
80
+ /**
81
+ * Opcodes we accept, anything else is a protocol error
82
+ */
83
+ private static readonly opcodes: Set<number> = new Set<number>(
84
+ Object.values(WebSocketOpcode),
85
+ )
86
+
87
+ /**
88
+ * Masked frames are refused when this is off, unmasked ones when it's on
89
+ */
90
+ private readonly expectMaskedFrames: boolean
91
+
92
+ /**
93
+ * Payload cap in bytes
94
+ */
95
+ private readonly maxFramePayloadLength: number
96
+
97
+ /**
98
+ * Set between the first fragment and the final one
99
+ */
100
+ private fragmented: boolean
101
+
102
+ /**
103
+ * Once set, every later byte is thrown away
104
+ */
105
+ private failed: boolean
106
+
107
+ /**
108
+ * Header of the frame being read, reused so no frame allocates one
109
+ */
110
+ private readonly head: FrameHead
111
+
112
+ /**
113
+ * Sets up a decoder for one side of the connection
114
+ * @param options masking rule and payload cap of at least 125
115
+ */
116
+ public constructor(options: WebSocketDecoderOptions) {
117
+ super()
118
+
119
+ const limit =
120
+ options.maxFramePayloadLength ??
121
+ WebSocketFrameDecoder.defaultMaxFramePayloadLength
122
+ if (!Number.isSafeInteger(limit) || limit < 125) {
123
+ throw new RangeError('Frame limit is invalid')
124
+ }
125
+
126
+ this.expectMaskedFrames = options.expectMaskedFrames
127
+ this.maxFramePayloadLength = limit
128
+ this.fragmented = false
129
+ this.failed = false
130
+ this.head = {
131
+ finalFragment: false,
132
+ reserved: 0,
133
+ opcode: 0,
134
+ masked: false,
135
+ shortLength: 0,
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Reads one frame, giving up on the stream after any protocol error
141
+ * @param context unused here
142
+ * @param input bytes gathered so far
143
+ * @param out where finished frames go
144
+ */
145
+ protected decode(
146
+ context: HandlerContext,
147
+ input: ByteBuf,
148
+ out: WebSocketFrame[],
149
+ ): void {
150
+ if (this.failed) {
151
+ input.skipBytes(input.readableBytes)
152
+ return
153
+ }
154
+
155
+ try {
156
+ const frame = this.readFrame(input)
157
+ if (frame !== null) out.push(frame)
158
+ } catch (error) {
159
+ this.failed = true
160
+ input.skipBytes(input.readableBytes)
161
+ throw error
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Waits for the whole frame before reading anything, or returns null
167
+ * @param input bytes gathered so far
168
+ */
169
+ private readFrame(input: ByteBuf): WebSocketFrame | null {
170
+ if (!input.isReadable(2)) return null
171
+
172
+ const start = input.readerIndex
173
+ const head = this.readHead(input.getUint8(start), input.getUint8(start + 1))
174
+ const reason = this.refusal(head)
175
+ if (reason !== null) {
176
+ throw new CorruptedFrameError(
177
+ reason,
178
+ WebSocketCloseStatus.PROTOCOL_ERROR.code,
179
+ )
180
+ }
181
+
182
+ const extended =
183
+ head.shortLength === 126 ? 2 : head.shortLength === 127 ? 8 : 0
184
+ const headerLength = 2 + extended + (head.masked ? 4 : 0)
185
+ if (!input.isReadable(headerLength)) return null
186
+ const length = this.payloadLength(input, start + 2, head.shortLength)
187
+ if (!input.isReadable(headerLength + length)) return null
188
+
189
+ input.skipBytes(2 + extended)
190
+ if (!head.masked) return this.createFrame(head, input.readBytes(length))
191
+
192
+ const payload = WebSocketFrameDecoder.unmask(
193
+ input.array,
194
+ input.arrayOffset + input.readerIndex,
195
+ length,
196
+ )
197
+ input.skipBytes(4 + length)
198
+ return this.createFrame(head, payload)
199
+ }
200
+
201
+ /**
202
+ * Copies a masked payload out of the input and unmasks it in the same pass
203
+ * @param bytes the input's backing bytes
204
+ * @param keyAt where the masking key starts
205
+ * @param length payload bytes after the key
206
+ */
207
+ private static unmask(
208
+ bytes: Uint8Array,
209
+ keyAt: number,
210
+ length: number,
211
+ ): Uint8Array {
212
+ const first = bytes[keyAt] ?? 0
213
+ const second = bytes[keyAt + 1] ?? 0
214
+ const third = bytes[keyAt + 2] ?? 0
215
+ const fourth = bytes[keyAt + 3] ?? 0
216
+ const start = keyAt + 4
217
+ const payload = new Uint8Array(length)
218
+ const whole = length - (length & 3)
219
+
220
+ let index = 0
221
+ for (; index < whole; index += 4) {
222
+ payload[index] = (bytes[start + index] ?? 0) ^ first
223
+ payload[index + 1] = (bytes[start + index + 1] ?? 0) ^ second
224
+ payload[index + 2] = (bytes[start + index + 2] ?? 0) ^ third
225
+ payload[index + 3] = (bytes[start + index + 3] ?? 0) ^ fourth
226
+ }
227
+
228
+ for (; index < length; index++) {
229
+ const byte = index & 3
230
+ const part =
231
+ byte === 0 ? first : byte === 1 ? second : byte === 2 ? third : fourth
232
+ payload[index] = (bytes[start + index] ?? 0) ^ part
233
+ }
234
+
235
+ return payload
236
+ }
237
+
238
+ /**
239
+ * Unpacks the FIN, RSV, opcode, MASK and length bits
240
+ * @param first FIN, RSV and opcode
241
+ * @param second MASK and the short length
242
+ */
243
+ private readHead(first: number, second: number): FrameHead {
244
+ const head = this.head
245
+ head.finalFragment = (first & 0x80) !== 0
246
+ head.reserved = first & 0x70
247
+ head.opcode = first & 0x0f
248
+ head.masked = (second & 0x80) !== 0
249
+ head.shortLength = second & 0x7f
250
+
251
+ return head
252
+ }
253
+
254
+ /**
255
+ * Opcodes from 0x8 up are control frames
256
+ * @param opcode four bit opcode
257
+ */
258
+ private static isControl(opcode: number): boolean {
259
+ return opcode >= 0x8
260
+ }
261
+
262
+ /**
263
+ * Catches reserved bits, wrong masking, bad opcodes and fragments out of order
264
+ * @param head unpacked header bits
265
+ */
266
+ private refusal(head: FrameHead): string | null {
267
+ const control = WebSocketFrameDecoder.isControl(head.opcode)
268
+
269
+ if (head.reserved !== 0) return 'Reserved bits are set'
270
+ if (head.masked && !this.expectMaskedFrames) return 'Frame is masked'
271
+ if (!head.masked && this.expectMaskedFrames) return 'Frame is not masked'
272
+ if (!WebSocketFrameDecoder.opcodes.has(head.opcode)) {
273
+ return 'Opcode is unknown'
274
+ }
275
+
276
+ if (control && !head.finalFragment) return 'Control frame is fragmented'
277
+ if (control && head.shortLength > 125) return 'Control frame is too large'
278
+ if (head.opcode === WebSocketOpcode.CONTINUATION && !this.fragmented) {
279
+ return 'Continuation is unexpected'
280
+ }
281
+
282
+ if (!control && head.opcode !== 0 && this.fragmented) {
283
+ return 'Fragment is missing'
284
+ }
285
+
286
+ return null
287
+ }
288
+
289
+ /**
290
+ * Reads the 16 or 64 bit length when there is one, closing with 1009 if it's too big
291
+ * @param input buffer to peek into
292
+ * @param index where the extended length starts
293
+ * @param shortLength 126 or 127 means read further
294
+ */
295
+ private payloadLength(
296
+ input: ByteBuf,
297
+ index: number,
298
+ shortLength: number,
299
+ ): number {
300
+ const length =
301
+ shortLength === 126
302
+ ? input.getUint16(index)
303
+ : shortLength === 127
304
+ ? input.getUint64(index)
305
+ : shortLength
306
+
307
+ if (length > this.maxFramePayloadLength) {
308
+ throw new CorruptedFrameError(
309
+ 'Frame is too large',
310
+ WebSocketCloseStatus.MESSAGE_TOO_BIG.code,
311
+ )
312
+ }
313
+
314
+ return Number(length)
315
+ }
316
+
317
+ /**
318
+ * Wraps the payload in the right frame class and updates the fragment state
319
+ * @param head unpacked header bits
320
+ * @param payload already unmasked
321
+ */
322
+ private createFrame(head: FrameHead, payload: Uint8Array): WebSocketFrame {
323
+ const content = ByteBuf.wrap(payload)
324
+ const final = head.finalFragment
325
+
326
+ if (!WebSocketFrameDecoder.isControl(head.opcode)) this.fragmented = !final
327
+ switch (head.opcode) {
328
+ case WebSocketOpcode.TEXT:
329
+ return new TextWebSocketFrame(content, final)
330
+ case WebSocketOpcode.BINARY:
331
+ return new BinaryWebSocketFrame(content, final)
332
+ case WebSocketOpcode.CONTINUATION:
333
+ return new ContinuationWebSocketFrame(content, final)
334
+ case WebSocketOpcode.PING:
335
+ return new PingWebSocketFrame(content)
336
+ case WebSocketOpcode.PONG:
337
+ return new PongWebSocketFrame(content)
338
+ default:
339
+ return WebSocketFrameDecoder.createClose(payload)
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Parses the close code and UTF-8 reason, an empty payload meaning no code
345
+ * @param payload raw close payload
346
+ */
347
+ private static createClose(payload: Uint8Array): CloseWebSocketFrame {
348
+ if (payload.length === 0) return new CloseWebSocketFrame()
349
+
350
+ const status = ((payload[0] ?? 0) << 8) | (payload[1] ?? 0)
351
+ if (payload.length === 1 || !WebSocketCloseStatus.isValid(status)) {
352
+ throw new CorruptedFrameError(
353
+ 'Close status is invalid',
354
+ WebSocketCloseStatus.PROTOCOL_ERROR.code,
355
+ )
356
+ }
357
+
358
+ let reason: string
359
+ try {
360
+ reason = WebSocketFrameDecoder.utf8.decode(payload.subarray(2))
361
+ } catch (cause) {
362
+ throw new CorruptedFrameError(
363
+ 'Close reason is invalid',
364
+ WebSocketCloseStatus.INVALID_PAYLOAD.code,
365
+ { cause },
366
+ )
367
+ }
368
+
369
+ return new CloseWebSocketFrame(status, reason)
370
+ }
371
+ }