1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
|
'use strict';
const assert = require('assert');
const EventEmitter = require('events');
const { createServer } = require('http');
const { Duplex } = require('stream');
const { randomBytes } = require('crypto');
const createWebSocketStream = require('../lib/stream');
const Sender = require('../lib/sender');
const WebSocket = require('..');
const { EMPTY_BUFFER } = require('../lib/constants');
describe('createWebSocketStream', () => {
it('is exposed as a property of the `WebSocket` class', () => {
assert.strictEqual(WebSocket.createWebSocketStream, createWebSocketStream);
});
it('returns a `Duplex` stream', () => {
const duplex = createWebSocketStream(new EventEmitter());
assert.ok(duplex instanceof Duplex);
});
it('passes the options object to the `Duplex` constructor', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws, {
allowHalfOpen: false,
encoding: 'utf8'
});
duplex.on('data', (chunk) => {
assert.strictEqual(chunk, 'hi');
duplex.on('close', () => {
wss.close(done);
});
});
});
wss.on('connection', (ws) => {
ws.send(Buffer.from('hi'));
ws.close();
});
});
describe('The returned stream', () => {
it('buffers writes if `readyState` is `CONNECTING`', (done) => {
const chunk = randomBytes(1024);
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
assert.strictEqual(ws.readyState, WebSocket.CONNECTING);
const duplex = createWebSocketStream(ws);
duplex.write(chunk);
});
wss.on('connection', (ws) => {
ws.on('message', (message, isBinary) => {
ws.on('close', (code, reason) => {
assert.deepStrictEqual(message, chunk);
assert.ok(isBinary);
assert.strictEqual(code, 1005);
assert.strictEqual(reason, EMPTY_BUFFER);
wss.close(done);
});
});
ws.close();
});
});
it('errors if a write occurs when `readyState` is `CLOSING`', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('error', (err) => {
assert.ok(duplex.destroyed);
assert.ok(err instanceof Error);
assert.strictEqual(
err.message,
'WebSocket is not open: readyState 2 (CLOSING)'
);
duplex.on('close', () => {
wss.close(done);
});
});
ws.on('open', () => {
ws._receiver.on('conclude', () => {
duplex.write('hi');
});
});
});
wss.on('connection', (ws) => {
ws.close();
});
});
it('errors if a write occurs when `readyState` is `CLOSED`', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('error', (err) => {
assert.ok(duplex.destroyed);
assert.ok(err instanceof Error);
assert.strictEqual(
err.message,
'WebSocket is not open: readyState 3 (CLOSED)'
);
duplex.on('close', () => {
wss.close(done);
});
});
ws.on('close', () => {
duplex.write('hi');
});
});
wss.on('connection', (ws) => {
ws.close();
});
});
it('does not error if `_final()` is called while connecting', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
assert.strictEqual(ws.readyState, WebSocket.CONNECTING);
const duplex = createWebSocketStream(ws);
duplex.on('close', () => {
wss.close(done);
});
duplex.resume();
duplex.end();
});
});
it('makes `_final()` a noop if no socket is assigned', (done) => {
const server = createServer();
server.on('upgrade', (request, socket) => {
socket.on('end', socket.end);
const headers = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: foo'
];
socket.write(headers.concat('\r\n').join('\r\n'));
});
server.listen(() => {
const called = [];
const ws = new WebSocket(`ws://localhost:${server.address().port}`);
const duplex = WebSocket.createWebSocketStream(ws);
const final = duplex._final;
duplex._final = (callback) => {
called.push('final');
assert.strictEqual(ws.readyState, WebSocket.CLOSING);
assert.strictEqual(ws._socket, null);
final(callback);
};
duplex.on('error', (err) => {
called.push('error');
assert.ok(err instanceof Error);
assert.strictEqual(
err.message,
'Invalid Sec-WebSocket-Accept header'
);
});
duplex.on('finish', () => {
called.push('finish');
});
duplex.on('close', () => {
assert.deepStrictEqual(called, ['final', 'error']);
server.close(done);
});
ws.on('upgrade', () => {
process.nextTick(() => {
duplex.end();
});
});
});
});
it('reemits errors', (done) => {
let duplexCloseEventEmitted = false;
let serverClientCloseEventEmitted = false;
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('error', (err) => {
assert.ok(err instanceof RangeError);
assert.strictEqual(err.code, 'WS_ERR_INVALID_OPCODE');
assert.strictEqual(
err.message,
'Invalid WebSocket frame: invalid opcode 5'
);
duplex.on('close', () => {
duplexCloseEventEmitted = true;
if (serverClientCloseEventEmitted) wss.close(done);
});
});
});
wss.on('connection', (ws) => {
ws._socket.write(Buffer.from([0x85, 0x00]));
ws.on('close', (code, reason) => {
assert.strictEqual(code, 1002);
assert.deepStrictEqual(reason, EMPTY_BUFFER);
serverClientCloseEventEmitted = true;
if (duplexCloseEventEmitted) wss.close(done);
});
});
});
it('does not swallow errors that may occur while destroying', (done) => {
const frame = Buffer.concat(
Sender.frame(Buffer.from([0x22, 0xfa, 0xec, 0x78]), {
fin: true,
rsv1: true,
opcode: 0x02,
mask: false,
readOnly: false
})
);
const wss = new WebSocket.Server(
{
perMessageDeflate: true,
port: 0
},
() => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('error', (err) => {
assert.ok(err instanceof Error);
assert.strictEqual(err.code, 'Z_DATA_ERROR');
assert.strictEqual(err.errno, -3);
duplex.on('close', () => {
wss.close(done);
});
});
let bytesRead = 0;
ws.on('open', () => {
ws._socket.on('data', (chunk) => {
bytesRead += chunk.length;
if (bytesRead === frame.length) duplex.destroy();
});
});
}
);
wss.on('connection', (ws) => {
ws._socket.write(frame);
});
});
it("does not suppress the throwing behavior of 'error' events", (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
createWebSocketStream(ws);
});
wss.on('connection', (ws) => {
ws._socket.write(Buffer.from([0x85, 0x00]));
});
assert.strictEqual(process.listenerCount('uncaughtException'), 1);
const [listener] = process.listeners('uncaughtException');
process.removeAllListeners('uncaughtException');
process.once('uncaughtException', (err) => {
assert.ok(err instanceof Error);
assert.strictEqual(
err.message,
'Invalid WebSocket frame: invalid opcode 5'
);
process.on('uncaughtException', listener);
wss.close(done);
});
});
it("is destroyed after 'end' and 'finish' are emitted (1/2)", (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const events = [];
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('end', () => {
events.push('end');
assert.ok(duplex.destroyed);
});
duplex.on('close', () => {
assert.deepStrictEqual(events, ['finish', 'end']);
wss.close(done);
});
duplex.on('finish', () => {
events.push('finish');
assert.ok(!duplex.destroyed);
assert.ok(duplex.readable);
duplex.resume();
});
ws.on('close', () => {
duplex.end();
});
});
wss.on('connection', (ws) => {
ws.send('foo');
ws.close();
});
});
it("is destroyed after 'end' and 'finish' are emitted (2/2)", (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const events = [];
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('end', () => {
events.push('end');
assert.ok(!duplex.destroyed);
assert.ok(duplex.writable);
duplex.end();
});
duplex.on('close', () => {
assert.deepStrictEqual(events, ['end', 'finish']);
wss.close(done);
});
duplex.on('finish', () => {
events.push('finish');
});
duplex.resume();
});
wss.on('connection', (ws) => {
ws.close();
});
});
it('handles backpressure (1/3)', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
// eslint-disable-next-line no-unused-vars
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
});
wss.on('connection', (ws) => {
const duplex = createWebSocketStream(ws);
duplex.resume();
duplex.on('drain', () => {
duplex.on('close', () => {
wss.close(done);
});
duplex.end();
});
const chunk = randomBytes(1024);
let ret;
do {
ret = duplex.write(chunk);
} while (ret !== false);
});
});
it('handles backpressure (2/3)', (done) => {
const wss = new WebSocket.Server(
{ port: 0, perMessageDeflate: true },
() => {
const called = [];
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
const read = duplex._read;
duplex._read = () => {
duplex._read = read;
called.push('read');
assert.ok(ws._receiver._writableState.needDrain);
read();
assert.ok(ws._socket.isPaused());
};
ws.on('open', () => {
ws._socket.on('pause', () => {
duplex.resume();
});
ws._receiver.on('drain', () => {
called.push('drain');
assert.ok(!ws._socket.isPaused());
duplex.end();
});
const opts = {
fin: true,
opcode: 0x02,
mask: false,
readOnly: false
};
const list = [
...Sender.frame(randomBytes(16 * 1024), { rsv1: false, ...opts }),
...Sender.frame(Buffer.alloc(1), { rsv1: true, ...opts })
];
// This hack is used because there is no guarantee that more than
// 16 KiB will be sent as a single TCP packet.
ws._socket.push(Buffer.concat(list));
});
duplex.on('close', () => {
assert.deepStrictEqual(called, ['read', 'drain']);
wss.close(done);
});
}
);
});
it('handles backpressure (3/3)', (done) => {
const wss = new WebSocket.Server(
{ port: 0, perMessageDeflate: true },
() => {
const called = [];
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
const read = duplex._read;
duplex._read = () => {
called.push('read');
assert.ok(!ws._receiver._writableState.needDrain);
read();
assert.ok(!ws._socket.isPaused());
duplex.end();
};
ws.on('open', () => {
ws._receiver.on('drain', () => {
called.push('drain');
assert.ok(ws._socket.isPaused());
duplex.resume();
});
const opts = {
fin: true,
opcode: 0x02,
mask: false,
readOnly: false
};
const list = [
...Sender.frame(randomBytes(16 * 1024), { rsv1: false, ...opts }),
...Sender.frame(Buffer.alloc(1), { rsv1: true, ...opts })
];
ws._socket.push(Buffer.concat(list));
});
duplex.on('close', () => {
assert.deepStrictEqual(called, ['drain', 'read']);
wss.close(done);
});
}
);
});
it('can be destroyed (1/2)', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const error = new Error('Oops');
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('error', (err) => {
assert.strictEqual(err, error);
duplex.on('close', () => {
wss.close(done);
});
});
ws.on('open', () => {
duplex.destroy(error);
});
});
});
it('can be destroyed (2/2)', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
duplex.on('close', () => {
wss.close(done);
});
ws.on('open', () => {
duplex.destroy();
});
});
});
it('converts text messages to strings in readable object mode', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const events = [];
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws, { readableObjectMode: true });
duplex.on('data', (data) => {
events.push('data');
assert.strictEqual(data, 'foo');
});
duplex.on('end', () => {
events.push('end');
duplex.end();
});
duplex.on('close', () => {
assert.deepStrictEqual(events, ['data', 'end']);
wss.close(done);
});
});
wss.on('connection', (ws) => {
ws.send('foo');
ws.close();
});
});
it('resumes the socket if `readyState` is `CLOSING`', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);
ws.on('message', () => {
assert.ok(ws._socket.isPaused());
duplex.on('close', () => {
wss.close(done);
});
duplex.end();
process.nextTick(() => {
assert.strictEqual(ws.readyState, WebSocket.CLOSING);
duplex.resume();
});
});
});
wss.on('connection', (ws) => {
ws.send(randomBytes(16 * 1024));
});
});
});
});
|