2
2
3
3
const { maxUnsigned16Bit } = require ( './constants' )
4
4
5
+ const BUFFER_SIZE = 16386
6
+
5
7
/** @type {import('crypto') } */
6
8
let crypto
9
+ let buffer = null
10
+ let bufIdx = 0
11
+
7
12
try {
8
13
crypto = require ( 'node:crypto' )
9
14
/* c8 ignore next 3 */
10
15
} catch {
11
16
12
17
}
13
18
19
+ function generateMask ( ) {
20
+ if ( buffer === null ) {
21
+ buffer = crypto . randomFillSync ( Buffer . allocUnsafe ( BUFFER_SIZE ) , 0 , BUFFER_SIZE )
22
+ }
23
+ if ( bufIdx + 4 > BUFFER_SIZE ) {
24
+ bufIdx = 0
25
+ crypto . randomFillSync ( buffer , 0 , BUFFER_SIZE )
26
+ }
27
+ return [ buffer [ bufIdx ++ ] , buffer [ bufIdx ++ ] , buffer [ bufIdx ++ ] , buffer [ bufIdx ++ ] ]
28
+ }
29
+
14
30
class WebsocketFrameSend {
15
31
/**
16
32
* @param {Buffer|undefined } data
17
33
*/
18
34
constructor ( data ) {
19
35
this . frameData = data
20
- this . maskKey = crypto . randomBytes ( 4 )
21
36
}
22
37
23
38
createFrame ( opcode ) {
24
- const bodyLength = this . frameData ?. byteLength ?? 0
39
+ const frameData = this . frameData
40
+ const maskKey = generateMask ( )
41
+ const bodyLength = frameData ?. byteLength ?? 0
25
42
26
43
/** @type {number } */
27
44
let payloadLength = bodyLength // 0-125
@@ -43,10 +60,10 @@ class WebsocketFrameSend {
43
60
buffer [ 0 ] = ( buffer [ 0 ] & 0xF0 ) + opcode // opcode
44
61
45
62
/*! ws. MIT License. Einar Otto Stangvik <[email protected] > */
46
- buffer [ offset - 4 ] = this . maskKey [ 0 ]
47
- buffer [ offset - 3 ] = this . maskKey [ 1 ]
48
- buffer [ offset - 2 ] = this . maskKey [ 2 ]
49
- buffer [ offset - 1 ] = this . maskKey [ 3 ]
63
+ buffer [ offset - 4 ] = maskKey [ 0 ]
64
+ buffer [ offset - 3 ] = maskKey [ 1 ]
65
+ buffer [ offset - 2 ] = maskKey [ 2 ]
66
+ buffer [ offset - 1 ] = maskKey [ 3 ]
50
67
51
68
buffer [ 1 ] = payloadLength
52
69
@@ -61,8 +78,8 @@ class WebsocketFrameSend {
61
78
buffer [ 1 ] |= 0x80 // MASK
62
79
63
80
// mask body
64
- for ( let i = 0 ; i < bodyLength ; i ++ ) {
65
- buffer [ offset + i ] = this . frameData [ i ] ^ this . maskKey [ i % 4 ]
81
+ for ( let i = 0 ; i < bodyLength ; ++ i ) {
82
+ buffer [ offset + i ] = frameData [ i ] ^ maskKey [ i & 3 ]
66
83
}
67
84
68
85
return buffer
0 commit comments