@unionschool/easy-agents 0.2.2 → 0.3.0

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.
@@ -0,0 +1,565 @@
1
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
2
+
3
+ 'use strict';
4
+
5
+ const EventEmitter = require('events');
6
+ const http = require('http');
7
+ const { Duplex } = require('stream');
8
+ const { createHash } = require('crypto');
9
+
10
+ const extension = require('./extension');
11
+ const PerMessageDeflate = require('./permessage-deflate');
12
+ const subprotocol = require('./subprotocol');
13
+ const WebSocket = require('./websocket');
14
+ const { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');
15
+
16
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
17
+
18
+ const RUNNING = 0;
19
+ const CLOSING = 1;
20
+ const CLOSED = 2;
21
+
22
+ /**
23
+ * Class representing a WebSocket server.
24
+ *
25
+ * @extends EventEmitter
26
+ */
27
+ class WebSocketServer extends EventEmitter {
28
+ /**
29
+ * Create a `WebSocketServer` instance.
30
+ *
31
+ * @param {Object} options Configuration options
32
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
33
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
34
+ * multiple times in the same tick
35
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
36
+ * automatically send a pong in response to a ping
37
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
38
+ * pending connections
39
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
40
+ * track clients
41
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
42
+ * wait for the closing handshake to finish after `websocket.close()` is
43
+ * called
44
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
45
+ * @param {String} [options.host] The hostname where to bind the server
46
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
47
+ * buffered data chunks
48
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
49
+ * fragments
50
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
51
+ * size
52
+ * @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
53
+ * pending automatic pongs
54
+ * @param {Boolean} [options.noServer=false] Enable no server mode
55
+ * @param {String} [options.path] Accept only connections matching this path
56
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
57
+ * permessage-deflate
58
+ * @param {Number} [options.port] The port where to bind the server
59
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
60
+ * server to use
61
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
62
+ * not to skip UTF-8 validation for text and close messages
63
+ * @param {Function} [options.verifyClient] A hook to reject connections
64
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
65
+ * class to use. It must be the `WebSocket` class or class that extends it
66
+ * @param {Function} [callback] A listener for the `listening` event
67
+ */
68
+ constructor(options, callback) {
69
+ super();
70
+
71
+ options = {
72
+ allowSynchronousEvents: true,
73
+ autoPong: true,
74
+ maxBufferedChunks: 256 * 1024,
75
+ maxFragments: 16 * 1024,
76
+ maxPayload: 100 * 1024 * 1024,
77
+ maxPendingAutoPongs: 60,
78
+ skipUTF8Validation: false,
79
+ perMessageDeflate: false,
80
+ handleProtocols: null,
81
+ clientTracking: true,
82
+ closeTimeout: CLOSE_TIMEOUT,
83
+ verifyClient: null,
84
+ noServer: false,
85
+ backlog: null, // use default (511 as implemented in net.js)
86
+ server: null,
87
+ host: null,
88
+ path: null,
89
+ port: null,
90
+ WebSocket,
91
+ ...options
92
+ };
93
+
94
+ if (
95
+ (options.port == null && !options.server && !options.noServer) ||
96
+ (options.port != null && (options.server || options.noServer)) ||
97
+ (options.server && options.noServer)
98
+ ) {
99
+ throw new TypeError(
100
+ 'One and only one of the "port", "server", or "noServer" options ' +
101
+ 'must be specified'
102
+ );
103
+ }
104
+
105
+ if (options.port != null) {
106
+ this._server = http.createServer((req, res) => {
107
+ const body = http.STATUS_CODES[426];
108
+
109
+ res.writeHead(426, {
110
+ 'Content-Length': body.length,
111
+ 'Content-Type': 'text/plain'
112
+ });
113
+ res.end(body);
114
+ });
115
+ this._server.listen(
116
+ options.port,
117
+ options.host,
118
+ options.backlog,
119
+ callback
120
+ );
121
+ } else if (options.server) {
122
+ this._server = options.server;
123
+ }
124
+
125
+ if (this._server) {
126
+ const emitConnection = this.emit.bind(this, 'connection');
127
+
128
+ this._removeListeners = addListeners(this._server, {
129
+ listening: this.emit.bind(this, 'listening'),
130
+ error: this.emit.bind(this, 'error'),
131
+ upgrade: (req, socket, head) => {
132
+ this.handleUpgrade(req, socket, head, emitConnection);
133
+ }
134
+ });
135
+ }
136
+
137
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
138
+ if (options.clientTracking) {
139
+ this.clients = new Set();
140
+ this._shouldEmitClose = false;
141
+ }
142
+
143
+ this.options = options;
144
+ this._state = RUNNING;
145
+ }
146
+
147
+ /**
148
+ * Returns the bound address, the address family name, and port of the server
149
+ * as reported by the operating system if listening on an IP socket.
150
+ * If the server is listening on a pipe or UNIX domain socket, the name is
151
+ * returned as a string.
152
+ *
153
+ * @return {(Object|String|null)} The address of the server
154
+ * @public
155
+ */
156
+ address() {
157
+ if (this.options.noServer) {
158
+ throw new Error('The server is operating in "noServer" mode');
159
+ }
160
+
161
+ if (!this._server) return null;
162
+ return this._server.address();
163
+ }
164
+
165
+ /**
166
+ * Stop the server from accepting new connections and emit the `'close'` event
167
+ * when all existing connections are closed.
168
+ *
169
+ * @param {Function} [cb] A one-time listener for the `'close'` event
170
+ * @public
171
+ */
172
+ close(cb) {
173
+ if (this._state === CLOSED) {
174
+ if (cb) {
175
+ this.once('close', () => {
176
+ cb(new Error('The server is not running'));
177
+ });
178
+ }
179
+
180
+ process.nextTick(emitClose, this);
181
+ return;
182
+ }
183
+
184
+ if (cb) this.once('close', cb);
185
+
186
+ if (this._state === CLOSING) return;
187
+ this._state = CLOSING;
188
+
189
+ if (this.options.noServer || this.options.server) {
190
+ if (this._server) {
191
+ this._removeListeners();
192
+ this._removeListeners = this._server = null;
193
+ }
194
+
195
+ if (this.clients) {
196
+ if (!this.clients.size) {
197
+ process.nextTick(emitClose, this);
198
+ } else {
199
+ this._shouldEmitClose = true;
200
+ }
201
+ } else {
202
+ process.nextTick(emitClose, this);
203
+ }
204
+ } else {
205
+ const server = this._server;
206
+
207
+ this._removeListeners();
208
+ this._removeListeners = this._server = null;
209
+
210
+ //
211
+ // The HTTP/S server was created internally. Close it, and rely on its
212
+ // `'close'` event.
213
+ //
214
+ server.close(() => {
215
+ emitClose(this);
216
+ });
217
+ }
218
+ }
219
+
220
+ /**
221
+ * See if a given request should be handled by this server instance.
222
+ *
223
+ * @param {http.IncomingMessage} req Request object to inspect
224
+ * @return {Boolean} `true` if the request is valid, else `false`
225
+ * @public
226
+ */
227
+ shouldHandle(req) {
228
+ if (this.options.path) {
229
+ const index = req.url.indexOf('?');
230
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
231
+
232
+ if (pathname !== this.options.path) return false;
233
+ }
234
+
235
+ return true;
236
+ }
237
+
238
+ /**
239
+ * Handle a HTTP Upgrade request.
240
+ *
241
+ * @param {http.IncomingMessage} req The request object
242
+ * @param {Duplex} socket The network socket between the server and client
243
+ * @param {Buffer} head The first packet of the upgraded stream
244
+ * @param {Function} cb Callback
245
+ * @public
246
+ */
247
+ handleUpgrade(req, socket, head, cb) {
248
+ socket.on('error', socketOnError);
249
+
250
+ const key = req.headers['sec-websocket-key'];
251
+ const upgrade = req.headers.upgrade;
252
+ const version = +req.headers['sec-websocket-version'];
253
+
254
+ if (req.method !== 'GET') {
255
+ const message = 'Invalid HTTP method';
256
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
257
+ return;
258
+ }
259
+
260
+ if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
261
+ const message = 'Invalid Upgrade header';
262
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
263
+ return;
264
+ }
265
+
266
+ if (key === undefined || !keyRegex.test(key)) {
267
+ const message = 'Missing or invalid Sec-WebSocket-Key header';
268
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
269
+ return;
270
+ }
271
+
272
+ if (version !== 13 && version !== 8) {
273
+ const message = 'Missing or invalid Sec-WebSocket-Version header';
274
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
275
+ 'Sec-WebSocket-Version': '13, 8'
276
+ });
277
+ return;
278
+ }
279
+
280
+ if (!this.shouldHandle(req)) {
281
+ abortHandshake(socket, 400);
282
+ return;
283
+ }
284
+
285
+ const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
286
+ let protocols = new Set();
287
+
288
+ if (secWebSocketProtocol !== undefined) {
289
+ try {
290
+ protocols = subprotocol.parse(secWebSocketProtocol);
291
+ } catch (err) {
292
+ const message = 'Invalid Sec-WebSocket-Protocol header';
293
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
294
+ return;
295
+ }
296
+ }
297
+
298
+ const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
299
+ const extensions = {};
300
+
301
+ if (
302
+ this.options.perMessageDeflate &&
303
+ secWebSocketExtensions !== undefined
304
+ ) {
305
+ const perMessageDeflate = new PerMessageDeflate({
306
+ ...this.options.perMessageDeflate,
307
+ isServer: true,
308
+ maxPayload: this.options.maxPayload
309
+ });
310
+
311
+ try {
312
+ const offers = extension.parse(secWebSocketExtensions);
313
+
314
+ if (offers[PerMessageDeflate.extensionName]) {
315
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
316
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
317
+ }
318
+ } catch (err) {
319
+ const message =
320
+ 'Invalid or unacceptable Sec-WebSocket-Extensions header';
321
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
322
+ return;
323
+ }
324
+ }
325
+
326
+ //
327
+ // Optionally call external client verification handler.
328
+ //
329
+ if (this.options.verifyClient) {
330
+ const info = {
331
+ origin:
332
+ req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
333
+ secure: !!(req.socket.authorized || req.socket.encrypted),
334
+ req
335
+ };
336
+
337
+ if (this.options.verifyClient.length === 2) {
338
+ this.options.verifyClient(info, (verified, code, message, headers) => {
339
+ if (!verified) {
340
+ return abortHandshake(socket, code || 401, message, headers);
341
+ }
342
+
343
+ this.completeUpgrade(
344
+ extensions,
345
+ key,
346
+ protocols,
347
+ req,
348
+ socket,
349
+ head,
350
+ cb
351
+ );
352
+ });
353
+ return;
354
+ }
355
+
356
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
357
+ }
358
+
359
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
360
+ }
361
+
362
+ /**
363
+ * Upgrade the connection to WebSocket.
364
+ *
365
+ * @param {Object} extensions The accepted extensions
366
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
367
+ * @param {Set} protocols The subprotocols
368
+ * @param {http.IncomingMessage} req The request object
369
+ * @param {Duplex} socket The network socket between the server and client
370
+ * @param {Buffer} head The first packet of the upgraded stream
371
+ * @param {Function} cb Callback
372
+ * @throws {Error} If called more than once with the same socket
373
+ * @private
374
+ */
375
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
376
+ //
377
+ // Destroy the socket if the client has already sent a FIN packet.
378
+ //
379
+ if (!socket.readable || !socket.writable) return socket.destroy();
380
+
381
+ if (socket[kWebSocket]) {
382
+ throw new Error(
383
+ 'server.handleUpgrade() was called more than once with the same ' +
384
+ 'socket, possibly due to a misconfiguration'
385
+ );
386
+ }
387
+
388
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
389
+
390
+ const digest = createHash('sha1')
391
+ .update(key + GUID)
392
+ .digest('base64');
393
+
394
+ const headers = [
395
+ 'HTTP/1.1 101 Switching Protocols',
396
+ 'Upgrade: websocket',
397
+ 'Connection: Upgrade',
398
+ `Sec-WebSocket-Accept: ${digest}`
399
+ ];
400
+
401
+ const ws = new this.options.WebSocket(null, undefined, this.options);
402
+
403
+ if (protocols.size) {
404
+ //
405
+ // Optionally call external protocol selection handler.
406
+ //
407
+ const protocol = this.options.handleProtocols
408
+ ? this.options.handleProtocols(protocols, req)
409
+ : protocols.values().next().value;
410
+
411
+ if (protocol) {
412
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
413
+ ws._protocol = protocol;
414
+ }
415
+ }
416
+
417
+ if (extensions[PerMessageDeflate.extensionName]) {
418
+ const params = extensions[PerMessageDeflate.extensionName].params;
419
+ const value = extension.format({
420
+ [PerMessageDeflate.extensionName]: [params]
421
+ });
422
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
423
+ ws._extensions = extensions;
424
+ }
425
+
426
+ //
427
+ // Allow external modification/inspection of handshake headers.
428
+ //
429
+ this.emit('headers', headers, req);
430
+
431
+ socket.write(headers.concat('\r\n').join('\r\n'));
432
+ socket.removeListener('error', socketOnError);
433
+
434
+ ws.setSocket(socket, head, {
435
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
436
+ maxBufferedChunks: this.options.maxBufferedChunks,
437
+ maxFragments: this.options.maxFragments,
438
+ maxPayload: this.options.maxPayload,
439
+ skipUTF8Validation: this.options.skipUTF8Validation
440
+ });
441
+
442
+ if (this.clients) {
443
+ this.clients.add(ws);
444
+ ws.on('close', () => {
445
+ this.clients.delete(ws);
446
+
447
+ if (this._shouldEmitClose && !this.clients.size) {
448
+ process.nextTick(emitClose, this);
449
+ }
450
+ });
451
+ }
452
+
453
+ cb(ws, req);
454
+ }
455
+ }
456
+
457
+ module.exports = WebSocketServer;
458
+
459
+ /**
460
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
461
+ * pairs.
462
+ *
463
+ * @param {EventEmitter} server The event emitter
464
+ * @param {Object.<String, Function>} map The listeners to add
465
+ * @return {Function} A function that will remove the added listeners when
466
+ * called
467
+ * @private
468
+ */
469
+ function addListeners(server, map) {
470
+ for (const event of Object.keys(map)) server.on(event, map[event]);
471
+
472
+ return function removeListeners() {
473
+ for (const event of Object.keys(map)) {
474
+ server.removeListener(event, map[event]);
475
+ }
476
+ };
477
+ }
478
+
479
+ /**
480
+ * Emit a `'close'` event on an `EventEmitter`.
481
+ *
482
+ * @param {EventEmitter} server The event emitter
483
+ * @private
484
+ */
485
+ function emitClose(server) {
486
+ server._state = CLOSED;
487
+ server.emit('close');
488
+ }
489
+
490
+ /**
491
+ * Handle socket errors.
492
+ *
493
+ * @private
494
+ */
495
+ function socketOnError() {
496
+ this.destroy();
497
+ }
498
+
499
+ /**
500
+ * Close the connection when preconditions are not fulfilled.
501
+ *
502
+ * @param {Duplex} socket The socket of the upgrade request
503
+ * @param {Number} code The HTTP response status code
504
+ * @param {String} [message] The HTTP response body
505
+ * @param {Object} [headers] Additional HTTP response headers
506
+ * @private
507
+ */
508
+ function abortHandshake(socket, code, message, headers) {
509
+ //
510
+ // The socket is writable unless the user destroyed or ended it before calling
511
+ // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
512
+ // error. Handling this does not make much sense as the worst that can happen
513
+ // is that some of the data written by the user might be discarded due to the
514
+ // call to `socket.end()` below, which triggers an `'error'` event that in
515
+ // turn causes the socket to be destroyed.
516
+ //
517
+ message = message || http.STATUS_CODES[code];
518
+ headers = {
519
+ Connection: 'close',
520
+ 'Content-Type': 'text/html',
521
+ 'Content-Length': Buffer.byteLength(message),
522
+ ...headers
523
+ };
524
+
525
+ socket.once('finish', socket.destroy);
526
+
527
+ socket.end(
528
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
529
+ Object.keys(headers)
530
+ .map((h) => `${h}: ${headers[h]}`)
531
+ .join('\r\n') +
532
+ '\r\n\r\n' +
533
+ message
534
+ );
535
+ }
536
+
537
+ /**
538
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
539
+ * one listener for it, otherwise call `abortHandshake()`.
540
+ *
541
+ * @param {WebSocketServer} server The WebSocket server
542
+ * @param {http.IncomingMessage} req The request object
543
+ * @param {Duplex} socket The socket of the upgrade request
544
+ * @param {Number} code The HTTP response status code
545
+ * @param {String} message The HTTP response body
546
+ * @param {Object} [headers] The HTTP response headers
547
+ * @private
548
+ */
549
+ function abortHandshakeOrEmitwsClientError(
550
+ server,
551
+ req,
552
+ socket,
553
+ code,
554
+ message,
555
+ headers
556
+ ) {
557
+ if (server.listenerCount('wsClientError')) {
558
+ const err = new Error(message);
559
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
560
+
561
+ server.emit('wsClientError', err, socket, req);
562
+ } else {
563
+ abortHandshake(socket, code, message, headers);
564
+ }
565
+ }