cloudstorm 0.3.2 → 0.4.2

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.
@@ -2,193 +2,542 @@
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
+ // This ultra light weigth WS code is a slimmed down version originally found at https://github.com/timotejroiko/tiny-discord
6
+ // Modifications and use of this code was granted for this project by the author, Timotej Roiko.
7
+ // A major thank you to Tim for better performing software.
5
8
  const events_1 = require("events");
6
- const zlib_sync_1 = __importDefault(require("zlib-sync"));
7
- let Erlpack;
8
- try {
9
- Erlpack = require("erlpack");
10
- }
11
- catch (e) {
12
- Erlpack = null;
13
- }
9
+ const crypto_1 = require("crypto");
10
+ const zlib_1 = require("zlib");
11
+ const https_1 = require("https");
12
+ const util_1 = __importDefault(require("util"));
13
+ const Z_SYNC_FLUSH = zlib_1.constants.Z_SYNC_FLUSH;
14
14
  const Constants_1 = require("../Constants");
15
- const ws_1 = __importDefault(require("ws"));
16
15
  const RatelimitBucket_1 = __importDefault(require("./RatelimitBucket"));
17
16
  /**
18
17
  * Helper Class for simplifying the websocket connection to Discord.
19
18
  */
20
19
  class BetterWs extends events_1.EventEmitter {
21
- /**
22
- * Create a new BetterWs instance.
23
- */
24
- constructor(address, options = {}) {
20
+ constructor(address, options) {
25
21
  super();
26
- this.zlibInflate = null;
27
- this.ws = new ws_1.default(address, options.socket);
28
- this.bindWs(this.ws);
29
22
  this.wsBucket = new RatelimitBucket_1.default(120, 60000);
30
- this.presenceBucket = new RatelimitBucket_1.default(5, 20000);
31
- if (options.compress) {
32
- this.zlibInflate = new zlib_sync_1.default.Inflate({ chunkSize: 65535 });
33
- this.compress = true;
34
- }
35
- else
36
- this.compress = false;
23
+ this.presenceBucket = new RatelimitBucket_1.default(5, 60000);
24
+ this._connecting = false;
25
+ this.encoding = options.encoding === "etf" ? "etf" : "json";
26
+ this.compress = options.compress || false;
27
+ this.address = address;
37
28
  this.options = options;
29
+ this._socket = null;
30
+ this._internal = {
31
+ closePromise: null,
32
+ zlib: null,
33
+ };
34
+ }
35
+ get status() {
36
+ const internal = this._internal;
37
+ if (this._connecting)
38
+ return 2;
39
+ if (internal.closePromise)
40
+ return 3; // closing
41
+ if (!this._socket)
42
+ return 4; // closed
43
+ return 1; // connected
38
44
  }
39
- /**
40
- * Get the raw websocket connection currently used.
41
- */
42
- get rawWs() {
43
- return this.ws;
45
+ connect() {
46
+ if (this._socket)
47
+ return Promise.resolve(void 0);
48
+ const key = (0, crypto_1.randomBytes)(16).toString("base64");
49
+ this.emit("debug", "Creating connection");
50
+ const url = new URL(this.address);
51
+ const req = (0, https_1.request)({
52
+ hostname: url.hostname,
53
+ path: `${url.pathname}${url.search}`,
54
+ headers: {
55
+ "Connection": "Upgrade",
56
+ "Upgrade": "websocket",
57
+ "Sec-WebSocket-Key": key,
58
+ "Sec-WebSocket-Version": "13",
59
+ }
60
+ });
61
+ this._connecting = true;
62
+ return new Promise((resolve, reject) => {
63
+ req.on("upgrade", (res, socket) => {
64
+ const hash = (0, crypto_1.createHash)("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
65
+ const accept = res.headers["sec-websocket-accept"];
66
+ if (hash !== accept) {
67
+ socket.end(() => {
68
+ this.emit("debug", "Failed websocket-key validation");
69
+ this._connecting = false;
70
+ reject(new Error(`Invalid Sec-Websocket-Accept | expected: ${hash} | received: ${accept}`));
71
+ });
72
+ return;
73
+ }
74
+ socket.on("error", this._onError.bind(this));
75
+ socket.on("close", this._onClose.bind(this));
76
+ socket.on("readable", this._onReadable.bind(this));
77
+ this._socket = socket;
78
+ this._connecting = false;
79
+ if (this.compress) {
80
+ const z = (0, zlib_1.createInflate)();
81
+ // @ts-ignore
82
+ z._c = z.close;
83
+ // @ts-ignore
84
+ z._h = z._handle;
85
+ // @ts-ignore
86
+ z._hc = z._handle.close;
87
+ // @ts-ignore
88
+ z._v = () => void 0;
89
+ this._internal.zlib = z;
90
+ }
91
+ this.emit("ws_open");
92
+ resolve(void 0);
93
+ });
94
+ req.on("error", e => {
95
+ this._connecting = false;
96
+ reject(e);
97
+ });
98
+ req.end();
99
+ });
44
100
  }
45
- /**
46
- * Add eventlisteners to a passed websocket connection.
47
- * @param ws Websocket.
48
- */
49
- bindWs(ws) {
50
- ws.on("message", (msg) => {
51
- this.onMessage(msg);
101
+ async close() {
102
+ const internal = this._internal;
103
+ if (internal.closePromise)
104
+ return internal.closePromise;
105
+ if (!this._socket)
106
+ return Promise.resolve(void 0);
107
+ let resolver;
108
+ const promise = new Promise(resolve => {
109
+ resolver = resolve;
110
+ this._write(Buffer.allocUnsafe(0), 8);
111
+ }).then(() => {
112
+ internal.closePromise = null;
52
113
  });
53
- ws.on("close", (code, reason) => this.onClose(code, reason.toString()));
54
- ws.on("error", (err) => {
55
- this.emit("error", err);
114
+ // @ts-ignore
115
+ promise.resolve = resolver;
116
+ internal.closePromise = promise;
117
+ }
118
+ sendMessage(data) {
119
+ if (!isValidRequest(data))
120
+ return Promise.reject(new Error("Invalid request"));
121
+ return new Promise(res => {
122
+ const presence = data.op === Constants_1.GATEWAY_OP_CODES.PRESENCE_UPDATE;
123
+ const sendMsg = () => {
124
+ this.wsBucket.queue(() => {
125
+ this.emit("debug_send", data);
126
+ if (this.encoding === "json")
127
+ this._write(Buffer.from(JSON.stringify(data)), 1);
128
+ else {
129
+ const etf = writeETF(data);
130
+ this._write(etf, 2);
131
+ }
132
+ res(void 0);
133
+ });
134
+ };
135
+ if (presence)
136
+ this.presenceBucket.queue(sendMsg);
137
+ else
138
+ sendMsg();
56
139
  });
57
- ws.on("open", () => this.onOpen());
58
140
  }
59
- /**
60
- * Create a new websocket connection if the old one was closed/destroyed.
61
- * @param address Address to connect to.
62
- * @param options Options used by the websocket connection.
63
- */
64
- recreateWs(address, options = {}) {
65
- this.ws.removeAllListeners();
66
- if (options.compress) {
67
- this.zlibInflate = new zlib_sync_1.default.Inflate({ chunkSize: 65535 });
68
- this.compress = true;
141
+ _write(packet, opcode) {
142
+ const socket = this._socket;
143
+ if (!socket || !socket.writable)
144
+ return;
145
+ const length = packet.length;
146
+ let frame;
147
+ if (length < 126) {
148
+ frame = Buffer.allocUnsafe(6 + length);
149
+ frame[1] = 128 + length;
150
+ }
151
+ else if (length < (1 << 16)) {
152
+ frame = Buffer.allocUnsafe(8 + length);
153
+ frame[1] = 254;
154
+ frame[2] = length >> 8;
155
+ frame[3] = length & 255;
69
156
  }
70
157
  else {
71
- this.zlibInflate = null;
72
- this.compress = false;
158
+ frame = Buffer.allocUnsafe(14 + length);
159
+ frame[1] = 255;
160
+ frame.writeBigUInt64BE(BigInt(length), 2);
73
161
  }
74
- this.ws = new ws_1.default(address, options.socket);
75
- this.options = options;
162
+ frame[0] = 128 + opcode;
163
+ frame.writeUInt32BE(0, frame.length - length - 4);
164
+ frame.set(packet, frame.length - length);
165
+ socket.write(frame);
166
+ }
167
+ _onError(error) {
168
+ if (!this._socket)
169
+ return;
170
+ this.emit("debug", util_1.default.inspect(error, true, 1, false));
171
+ this._write(Buffer.allocUnsafe(0), 8);
172
+ }
173
+ _onClose() {
174
+ const socket = this._socket;
175
+ const internal = this._internal;
176
+ if (!socket)
177
+ return;
178
+ this.emit("debug", "Connection closed");
179
+ socket.removeListener("data", this._onReadable);
180
+ socket.removeListener("error", this._onError);
181
+ socket.removeListener("close", this._onClose);
76
182
  this.wsBucket.dropQueue();
77
183
  this.presenceBucket.dropQueue();
78
- this.wsBucket = new RatelimitBucket_1.default(120, 60000);
79
- this.presenceBucket = new RatelimitBucket_1.default(5, 60000);
80
- this.bindWs(this.ws);
81
- }
82
- /**
83
- * Called upon opening of the websocket connection.
84
- */
85
- onOpen() {
86
- this.emit("ws_open");
184
+ this._socket = null;
185
+ if (internal.zlib) {
186
+ internal.zlib.close();
187
+ internal.zlib = null;
188
+ }
189
+ if (internal.closePromise) {
190
+ // @ts-ignore
191
+ internal.closePromise.resolve(void 0);
192
+ }
87
193
  }
88
- /**
89
- * Called once a websocket message is received,
90
- * uncompresses the message using zlib and parses it via Erlpack or JSON.parse.
91
- * @param message Message received by websocket.
92
- */
93
- onMessage(message) {
94
- let parsed;
95
- try {
96
- let msg;
97
- if (this.compress && this.zlibInflate) {
98
- const length = message.length;
99
- const flush = length >= 4 &&
100
- message[length - 4] === 0x00 &&
101
- message[length - 3] === 0x00 &&
102
- message[length - 2] === 0xFF &&
103
- message[length - 1] === 0xFF;
104
- this.zlibInflate.push(message, flush ? zlib_sync_1.default.Z_SYNC_FLUSH : false);
105
- if (!flush)
194
+ _onReadable() {
195
+ const socket = this._socket;
196
+ while (socket.readableLength > 1) {
197
+ let length = readRange(socket, 1, 1) & 127;
198
+ let bytes = 0;
199
+ if (length > 125) {
200
+ bytes = length === 126 ? 2 : 8;
201
+ if (socket.readableLength < 2 + bytes)
106
202
  return;
107
- msg = this.zlibInflate.result;
203
+ length = readRange(socket, 2, bytes);
108
204
  }
109
- else
110
- msg = message;
111
- if (Erlpack) {
112
- parsed = Erlpack.unpack(msg);
205
+ const frame = socket.read(2 + bytes + length);
206
+ if (!frame)
207
+ return;
208
+ const fin = frame[0] >> 7;
209
+ const opcode = frame[0] & 15;
210
+ if (fin !== 1 || opcode === 0)
211
+ this.emit("debug", "discord actually does send messages with fin=0. if you see this error let me know");
212
+ const payload = frame.slice(2 + bytes);
213
+ this._processFrame(opcode, payload);
214
+ }
215
+ }
216
+ _processFrame(opcode, message) {
217
+ const internal = this._internal;
218
+ switch (opcode) {
219
+ case 1: {
220
+ const packet = JSON.parse(message.toString());
221
+ this.emit("ws_message", packet);
222
+ break;
113
223
  }
114
- else {
115
- parsed = JSON.parse(String(msg));
224
+ case 2: {
225
+ let packet;
226
+ if (this.compress) {
227
+ const z = internal.zlib;
228
+ let error = null;
229
+ let data = null;
230
+ // @ts-ignore
231
+ z.close = z._handle.close = z._v;
232
+ try {
233
+ // @ts-ignore
234
+ data = z._processChunk(message, Z_SYNC_FLUSH);
235
+ }
236
+ catch (e) {
237
+ error = e;
238
+ }
239
+ const l = message.length;
240
+ if (message[l - 4] !== 0 || message[l - 3] !== 0 || message[l - 2] !== 255 || message[l - 1] !== 255)
241
+ this.emit("debug", "discord actually does send fragmented zlib messages. if you see this error let me know");
242
+ // @ts-ignore
243
+ z.close = z._c;
244
+ // @ts-ignore
245
+ z._handle = z._h;
246
+ // @ts-ignore
247
+ z._handle.close = z._hc;
248
+ // @ts-ignore
249
+ z._events.error = void 0;
250
+ // @ts-ignore
251
+ z._eventCount--;
252
+ z.removeAllListeners("error");
253
+ if (error) {
254
+ this.emit("debug", "Zlib error");
255
+ this._write(Buffer.allocUnsafe(0), 8);
256
+ return;
257
+ }
258
+ if (!data)
259
+ return; // This should never run, but TS is lame
260
+ packet = this.encoding === "json" ? JSON.parse(String(data)) : readETF(data, 1);
261
+ }
262
+ else if (this.encoding === "json") {
263
+ const data = (0, zlib_1.inflateSync)(message);
264
+ packet = JSON.parse(data.toString());
265
+ }
266
+ else
267
+ packet = readETF(message, 1);
268
+ this.emit("ws_message", packet);
269
+ break;
270
+ }
271
+ case 8: {
272
+ const code = message.length > 1 ? (message[0] << 8) + message[1] : 0;
273
+ const reason = message.length > 2 ? message.slice(2).toString() : "";
274
+ this.emit("ws_close", code, reason);
275
+ this._write(Buffer.from([code >> 8, code & 255]), 8);
276
+ break;
277
+ }
278
+ case 9: {
279
+ this._write(message, 10);
280
+ break;
116
281
  }
117
282
  }
118
- catch (e) {
119
- this.emit("error", `Message: ${message} was not parseable`);
120
- return;
121
- }
122
- this.emit("ws_message", parsed);
123
283
  }
124
- /**
125
- * Called when the websocket connection closes for some reason.
126
- * @param code Websocket close code.
127
- * @param reason Reason of the close if any.
128
- */
129
- onClose(code, reason) {
130
- this.emit("ws_close", code, reason);
131
- }
132
- /**
133
- * Send a message to the Discord gateway.
134
- * @param data Data to send.
135
- */
136
- sendMessage(data) {
137
- if (this.ws.readyState !== ws_1.default.OPEN)
138
- return Promise.reject(new Error("WS is not open"));
139
- this.emit("debug_send", data);
140
- return new Promise((res, rej) => {
141
- const presence = data.op === Constants_1.GATEWAY_OP_CODES.PRESENCE_UPDATE;
142
- try {
143
- if (Erlpack) {
144
- data = Erlpack.pack(data);
284
+ }
285
+ function isValidRequest(value) {
286
+ return value && typeof value === "object" && Number.isInteger(value.op) && typeof value.d !== "undefined";
287
+ }
288
+ function readRange(socket, index, bytes) {
289
+ // @ts-ignore
290
+ let head = socket._readableState.buffer.head;
291
+ let cursor = 0;
292
+ let read = 0;
293
+ let num = 0;
294
+ do {
295
+ for (let i = 0; i < head.data.length; i++) {
296
+ if (++cursor > index) {
297
+ num *= 256;
298
+ num += head.data[i];
299
+ if (++read === bytes)
300
+ return num;
301
+ }
302
+ }
303
+ } while ((head = head.next));
304
+ throw new Error("readRange failed?");
305
+ }
306
+ function readETF(data, start) {
307
+ let view;
308
+ let x = start;
309
+ const loop = () => {
310
+ const type = data[x++];
311
+ switch (type) {
312
+ case 97: {
313
+ return data[x++];
314
+ }
315
+ case 98: {
316
+ const int = data.readInt32BE(x);
317
+ x += 4;
318
+ return int;
319
+ }
320
+ case 100: {
321
+ const length = data.readUInt16BE(x);
322
+ let atom = "";
323
+ if (length > 30) {
324
+ // @ts-ignore
325
+ atom = data.latin1Slice(x += 2, x + length);
145
326
  }
146
327
  else {
147
- data = JSON.stringify(data);
328
+ for (let i = x += 2; i < x + length; i++) {
329
+ atom += String.fromCharCode(data[i]);
330
+ }
148
331
  }
332
+ x += length;
333
+ if (!atom)
334
+ return undefined;
335
+ if (atom === "nil" || atom === "null")
336
+ return null;
337
+ if (atom === "true")
338
+ return true;
339
+ if (atom === "false")
340
+ return false;
341
+ return atom;
149
342
  }
150
- catch (e) {
151
- return rej(e);
343
+ case 108:
344
+ case 106: {
345
+ const array = [];
346
+ if (type === 108) {
347
+ const length = data.readUInt32BE(x);
348
+ x += 4;
349
+ for (let i = 0; i < length; i++) {
350
+ array.push(loop());
351
+ }
352
+ x++;
353
+ }
354
+ return array;
152
355
  }
153
- const sendMsg = () => {
154
- // The promise from wsBucket is ignored, since the method passed to it does not return a promise
155
- this.wsBucket.queue(() => {
156
- this.ws.send(data, {}, (e) => {
157
- if (e) {
158
- return rej(e);
159
- }
160
- res();
161
- });
162
- });
163
- };
164
- if (presence) {
165
- // same here
166
- this.presenceBucket.queue(sendMsg);
356
+ case 107: {
357
+ const array = [];
358
+ const length = data.readUInt16BE(x);
359
+ x += 2;
360
+ for (let i = 0; i < length; i++) {
361
+ array.push(data[x++]);
362
+ }
363
+ return array;
167
364
  }
168
- else {
169
- sendMsg();
365
+ case 109: {
366
+ const length = data.readUInt32BE(x);
367
+ let str = "";
368
+ if (length > 30) {
369
+ // @ts-ignore
370
+ str = data.utf8Slice(x += 4, x + length);
371
+ }
372
+ else {
373
+ let i = x += 4;
374
+ const l = x + length;
375
+ while (i < l) {
376
+ const byte = data[i++];
377
+ if (byte < 128)
378
+ str += String.fromCharCode(byte);
379
+ else if (byte < 224)
380
+ str += String.fromCharCode(((byte & 31) << 6) + (data[i++] & 63));
381
+ else if (byte < 240)
382
+ str += String.fromCharCode(((byte & 15) << 12) + ((data[i++] & 63) << 6) + (data[i++] & 63));
383
+ else
384
+ str += String.fromCodePoint(((byte & 7) << 18) + ((data[i++] & 63) << 12) + ((data[i++] & 63) << 6) + (data[i++] & 63));
385
+ }
386
+ }
387
+ x += length;
388
+ return str;
170
389
  }
171
- });
172
- }
173
- /**
174
- * Close the current websocket connection.
175
- * @param code Websocket close code to use.
176
- * @param reason Reason of the disconnect.
177
- */
178
- close(code = 1000, reason = "Unknown") {
179
- if (this.ws.readyState === ws_1.default.CLOSING || this.ws.readyState === ws_1.default.CLOSED)
180
- return Promise.reject(new Error("WS is already closing or is closed"));
181
- return new Promise((res, rej) => {
182
- const timeout = setTimeout(() => {
183
- return rej("Websocket not closed within 5 seconds");
184
- }, 5 * 1000);
185
- this.ws.once("close", () => {
186
- clearTimeout(timeout);
187
- return res();
188
- });
189
- this.ws.close(code, reason);
190
- });
191
- }
390
+ case 110: {
391
+ // @ts-ignore
392
+ if (!view)
393
+ view = new DataView(data.buffer, data.offset, data.byteLength);
394
+ const length = data[x++];
395
+ const sign = data[x++];
396
+ let left = length;
397
+ let num = BigInt(0);
398
+ while (left > 0) {
399
+ if (left >= 8) {
400
+ num <<= BigInt(64);
401
+ num += view.getBigUint64(x + (left -= 8), true);
402
+ }
403
+ else if (left >= 4) {
404
+ num <<= BigInt(32);
405
+ // @ts-ignore
406
+ num += BigInt(view.getUint32(x + (left -= 4)), true);
407
+ }
408
+ else if (left >= 2) {
409
+ num <<= BigInt(16);
410
+ // @ts-ignore
411
+ num += BigInt(view.getUint16(x + (left -= 2)), true);
412
+ }
413
+ else {
414
+ num <<= BigInt(8);
415
+ num += BigInt(data[x]);
416
+ left--;
417
+ }
418
+ }
419
+ x += length;
420
+ return (sign ? -num : num).toString();
421
+ }
422
+ case 116: {
423
+ const obj = {};
424
+ const length = data.readUInt32BE(x);
425
+ x += 4;
426
+ for (let i = 0; i < length; i++) {
427
+ const key = loop();
428
+ // @ts-ignore
429
+ obj[key] = loop();
430
+ }
431
+ return obj;
432
+ }
433
+ }
434
+ throw new Error(`Missing etf type: ${type}`);
435
+ };
436
+ return loop();
437
+ }
438
+ function writeETF(data) {
439
+ const b = Buffer.allocUnsafe(1 << 12);
440
+ b[0] = 131;
441
+ let i = 1;
442
+ const loop = (obj) => {
443
+ const type = typeof obj;
444
+ switch (type) {
445
+ case "boolean": {
446
+ b[i++] = 100;
447
+ if (obj) {
448
+ b.writeUInt16BE(4, i);
449
+ // @ts-ignore
450
+ b.latin1Write("true", i += 2);
451
+ i += 4;
452
+ }
453
+ else {
454
+ b.writeUInt16BE(5, i);
455
+ // @ts-ignore
456
+ b.latin1Write("false", i += 2);
457
+ i += 5;
458
+ }
459
+ break;
460
+ }
461
+ case "string": {
462
+ const length = Buffer.byteLength(obj);
463
+ b[i++] = 109;
464
+ b.writeUInt32BE(length, i);
465
+ // @ts-ignore
466
+ b.utf8Write(obj, i += 4);
467
+ i += length;
468
+ break;
469
+ }
470
+ case "number": {
471
+ if (Number.isInteger(obj)) {
472
+ const abs = Math.abs(obj);
473
+ if (abs < 2147483648) {
474
+ b[i++] = 98;
475
+ b.writeInt32BE(obj, i);
476
+ i += 4;
477
+ }
478
+ else if (abs < Number.MAX_SAFE_INTEGER) {
479
+ b[i++] = 110;
480
+ b[i++] = 8;
481
+ b[i++] = Number(obj < 0);
482
+ b.writeBigUInt64LE(BigInt(abs), i);
483
+ i += 8;
484
+ break;
485
+ }
486
+ else {
487
+ b[i++] = 70;
488
+ b.writeDoubleBE(obj, i);
489
+ i += 8;
490
+ }
491
+ }
492
+ else {
493
+ b[i++] = 70;
494
+ b.writeDoubleBE(obj, i);
495
+ i += 8;
496
+ }
497
+ break;
498
+ }
499
+ case "bigint": {
500
+ b[i++] = 110;
501
+ b[i++] = 8;
502
+ b[i++] = Number(obj < 0);
503
+ b.writeBigUInt64LE(obj, i);
504
+ i += 8;
505
+ break;
506
+ }
507
+ case "object": {
508
+ if (obj === null) {
509
+ b[i++] = 100;
510
+ b.writeUInt16BE(3, i);
511
+ // @ts-ignore
512
+ b.latin1Write("nil", i += 2);
513
+ i += 3;
514
+ }
515
+ else if (Array.isArray(obj)) {
516
+ if (obj.length) {
517
+ b[i++] = 108;
518
+ b.writeUInt32BE(obj.length, i);
519
+ i += 4;
520
+ for (const item of obj) {
521
+ loop(item);
522
+ }
523
+ }
524
+ b[i++] = 106;
525
+ }
526
+ else {
527
+ const entries = Object.entries(obj).filter(x => typeof x[1] !== "undefined");
528
+ b[i++] = 116;
529
+ b.writeUInt32BE(entries.length, i);
530
+ i += 4;
531
+ for (const [key, value] of entries) {
532
+ loop(key);
533
+ loop(value);
534
+ }
535
+ }
536
+ break;
537
+ }
538
+ }
539
+ };
540
+ loop(data);
541
+ return Buffer.from(b.slice(0, i));
192
542
  }
193
- BetterWs.default = BetterWs;
194
543
  module.exports = BetterWs;