lordceaser-baileys 2.0.2 → 2.0.3

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 (166) hide show
  1. package/index.js +1 -17
  2. package/package.json +4 -3
  3. package/WAProto/index.js +0 -155693
  4. package/lib/Defaults/baileys-version.json +0 -3
  5. package/lib/Defaults/index.d.ts +0 -53
  6. package/lib/Defaults/index.js +0 -108
  7. package/lib/Signal/libsignal.d.ts +0 -3
  8. package/lib/Signal/libsignal.js +0 -152
  9. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  10. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  11. package/lib/Socket/Client/index.d.ts +0 -3
  12. package/lib/Socket/Client/index.js +0 -19
  13. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  14. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  15. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  16. package/lib/Socket/Client/web-socket-client.js +0 -62
  17. package/lib/Socket/business.d.ts +0 -170
  18. package/lib/Socket/business.js +0 -260
  19. package/lib/Socket/chats.d.ts +0 -81
  20. package/lib/Socket/chats.js +0 -950
  21. package/lib/Socket/groups.d.ts +0 -115
  22. package/lib/Socket/groups.js +0 -315
  23. package/lib/Socket/index.d.ts +0 -172
  24. package/lib/Socket/index.js +0 -10
  25. package/lib/Socket/messages-recv.d.ts +0 -158
  26. package/lib/Socket/messages-recv.js +0 -972
  27. package/lib/Socket/messages-send.d.ts +0 -155
  28. package/lib/Socket/messages-send.js +0 -1087
  29. package/lib/Socket/newsletter.d.ts +0 -132
  30. package/lib/Socket/newsletter.js +0 -236
  31. package/lib/Socket/registration.d.ts +0 -264
  32. package/lib/Socket/registration.js +0 -166
  33. package/lib/Socket/socket.d.ts +0 -44
  34. package/lib/Socket/socket.js +0 -642
  35. package/lib/Socket/usync.d.ts +0 -37
  36. package/lib/Socket/usync.js +0 -70
  37. package/lib/Store/index.d.ts +0 -3
  38. package/lib/Store/index.js +0 -10
  39. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  40. package/lib/Store/make-cache-manager-store.js +0 -83
  41. package/lib/Store/make-in-memory-store.d.ts +0 -118
  42. package/lib/Store/make-in-memory-store.js +0 -431
  43. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  44. package/lib/Store/make-ordered-dictionary.js +0 -81
  45. package/lib/Store/object-repository.d.ts +0 -10
  46. package/lib/Store/object-repository.js +0 -27
  47. package/lib/Types/Auth.d.ts +0 -109
  48. package/lib/Types/Auth.js +0 -2
  49. package/lib/Types/Call.d.ts +0 -13
  50. package/lib/Types/Call.js +0 -2
  51. package/lib/Types/Chat.d.ts +0 -107
  52. package/lib/Types/Chat.js +0 -4
  53. package/lib/Types/Contact.d.ts +0 -19
  54. package/lib/Types/Contact.js +0 -2
  55. package/lib/Types/Events.d.ts +0 -172
  56. package/lib/Types/Events.js +0 -2
  57. package/lib/Types/GroupMetadata.d.ts +0 -56
  58. package/lib/Types/GroupMetadata.js +0 -2
  59. package/lib/Types/Label.d.ts +0 -46
  60. package/lib/Types/Label.js +0 -27
  61. package/lib/Types/LabelAssociation.d.ts +0 -29
  62. package/lib/Types/LabelAssociation.js +0 -9
  63. package/lib/Types/Message.d.ts +0 -433
  64. package/lib/Types/Message.js +0 -9
  65. package/lib/Types/Newsletter.d.ts +0 -92
  66. package/lib/Types/Newsletter.js +0 -32
  67. package/lib/Types/Product.d.ts +0 -78
  68. package/lib/Types/Product.js +0 -2
  69. package/lib/Types/Signal.d.ts +0 -57
  70. package/lib/Types/Signal.js +0 -2
  71. package/lib/Types/Socket.d.ts +0 -116
  72. package/lib/Types/Socket.js +0 -2
  73. package/lib/Types/State.d.ts +0 -27
  74. package/lib/Types/State.js +0 -2
  75. package/lib/Types/USync.d.ts +0 -25
  76. package/lib/Types/USync.js +0 -2
  77. package/lib/Types/index.d.ts +0 -66
  78. package/lib/Types/index.js +0 -42
  79. package/lib/Utils/auth-utils.d.ts +0 -18
  80. package/lib/Utils/auth-utils.js +0 -206
  81. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  82. package/lib/Utils/baileys-event-stream.js +0 -63
  83. package/lib/Utils/business.d.ts +0 -22
  84. package/lib/Utils/business.js +0 -234
  85. package/lib/Utils/c4-compat.js +0 -16
  86. package/lib/Utils/chat-utils.d.ts +0 -70
  87. package/lib/Utils/chat-utils.js +0 -745
  88. package/lib/Utils/crypto.d.ts +0 -40
  89. package/lib/Utils/crypto.js +0 -199
  90. package/lib/Utils/decode-wa-message.d.ts +0 -36
  91. package/lib/Utils/decode-wa-message.js +0 -234
  92. package/lib/Utils/event-buffer.d.ts +0 -35
  93. package/lib/Utils/event-buffer.js +0 -517
  94. package/lib/Utils/generics.d.ts +0 -88
  95. package/lib/Utils/generics.js +0 -402
  96. package/lib/Utils/history.d.ts +0 -19
  97. package/lib/Utils/history.js +0 -94
  98. package/lib/Utils/index.d.ts +0 -17
  99. package/lib/Utils/index.js +0 -34
  100. package/lib/Utils/link-preview.d.ts +0 -21
  101. package/lib/Utils/link-preview.js +0 -93
  102. package/lib/Utils/logger.d.ts +0 -2
  103. package/lib/Utils/logger.js +0 -7
  104. package/lib/Utils/lt-hash.d.ts +0 -12
  105. package/lib/Utils/lt-hash.js +0 -51
  106. package/lib/Utils/make-mutex.d.ts +0 -7
  107. package/lib/Utils/make-mutex.js +0 -43
  108. package/lib/Utils/messages-media.d.ts +0 -113
  109. package/lib/Utils/messages-media.js +0 -721
  110. package/lib/Utils/messages.d.ts +0 -77
  111. package/lib/Utils/messages.js +0 -1221
  112. package/lib/Utils/noise-handler.d.ts +0 -20
  113. package/lib/Utils/noise-handler.js +0 -160
  114. package/lib/Utils/process-message.d.ts +0 -41
  115. package/lib/Utils/process-message.js +0 -373
  116. package/lib/Utils/signal.d.ts +0 -33
  117. package/lib/Utils/signal.js +0 -159
  118. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  119. package/lib/Utils/use-multi-file-auth-state.js +0 -167
  120. package/lib/Utils/use-single-file-auth-state.d.ts +0 -12
  121. package/lib/Utils/use-single-file-auth-state.js +0 -76
  122. package/lib/Utils/validate-connection.d.ts +0 -11
  123. package/lib/Utils/validate-connection.js +0 -205
  124. package/lib/WABinary/constants.d.ts +0 -27
  125. package/lib/WABinary/constants.js +0 -40
  126. package/lib/WABinary/decode.d.ts +0 -6
  127. package/lib/WABinary/decode.js +0 -264
  128. package/lib/WABinary/encode.d.ts +0 -2
  129. package/lib/WABinary/encode.js +0 -252
  130. package/lib/WABinary/generic-utils.d.ts +0 -14
  131. package/lib/WABinary/generic-utils.js +0 -110
  132. package/lib/WABinary/index.d.ts +0 -5
  133. package/lib/WABinary/index.js +0 -21
  134. package/lib/WABinary/jid-utils.d.ts +0 -31
  135. package/lib/WABinary/jid-utils.js +0 -62
  136. package/lib/WABinary/types.d.ts +0 -18
  137. package/lib/WABinary/types.js +0 -2
  138. package/lib/WAM/BinaryInfo.d.ts +0 -8
  139. package/lib/WAM/BinaryInfo.js +0 -13
  140. package/lib/WAM/constants.d.ts +0 -38
  141. package/lib/WAM/constants.js +0 -15350
  142. package/lib/WAM/encode.d.ts +0 -2
  143. package/lib/WAM/encode.js +0 -155
  144. package/lib/WAM/index.d.ts +0 -3
  145. package/lib/WAM/index.js +0 -19
  146. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  147. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  148. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  149. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  150. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  151. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  152. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  153. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  154. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  155. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  156. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  157. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  158. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  159. package/lib/WAUSync/Protocols/index.js +0 -20
  160. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  161. package/lib/WAUSync/USyncQuery.js +0 -89
  162. package/lib/WAUSync/USyncUser.d.ts +0 -10
  163. package/lib/WAUSync/USyncUser.js +0 -26
  164. package/lib/WAUSync/index.d.ts +0 -3
  165. package/lib/WAUSync/index.js +0 -19
  166. package/lib/index.js +0 -31
@@ -1,642 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeSocket = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const crypto_1 = require("crypto");
6
- const url_1 = require("url");
7
- const util_1 = require("util");
8
- const WAProto_1 = require("../../WAProto");
9
- const Defaults_1 = require("../Defaults");
10
- const Types_1 = require("../Types");
11
- const Utils_1 = require("../Utils");
12
- const WABinary_1 = require("../WABinary");
13
- const Client_1 = require("./Client");
14
- /**
15
- * Connects to WA servers and performs:
16
- * - simple queries (no retry mechanism, wait for connection establishment)
17
- * - listen to messages and emit events
18
- * - query phone connection
19
- */
20
- const makeSocket = (config) => {
21
- var _a, _b;
22
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
23
- let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
- config.mobile = config.mobile || url.protocol === 'tcp:';
25
- if (config.mobile && url.protocol !== 'tcp:') {
26
- url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
27
- }
28
- if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
29
- url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
30
- }
31
- if (config.mobile || url.protocol === 'tcp:') {
32
- throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
33
- }
34
- if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
35
- url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
36
- }
37
- const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
38
- ws.connect();
39
- const ev = (0, Utils_1.makeEventBuffer)(logger);
40
- /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
41
- const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
42
- /** WA noise protocol wrapper */
43
- const noise = (0, Utils_1.makeNoiseHandler)({
44
- keyPair: ephemeralKeyPair,
45
- NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
46
- mobile: config.mobile,
47
- logger,
48
- routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
49
- });
50
- const { creds } = authState;
51
- // add transaction capability
52
- const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
53
- const signalRepository = makeSignalRepository({ creds, keys });
54
- let lastDateRecv;
55
- let epoch = 1;
56
- let keepAliveReq;
57
- let qrTimer;
58
- let closed = false;
59
- const uqTagId = (0, Utils_1.generateMdTagPrefix)();
60
- const generateMessageTag = () => `${uqTagId}${epoch++}`;
61
- const sendPromise = (0, util_1.promisify)(ws.send);
62
- /** send a raw buffer */
63
- const sendRawMessage = async (data) => {
64
- if (!ws.isOpen) {
65
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
66
- }
67
- const bytes = noise.encodeFrame(data);
68
- return await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
69
- try {
70
- resolve(await sendPromise.call(ws, bytes));
71
- }
72
- catch (error) {
73
- reject(error);
74
- }
75
- });
76
- };
77
- /** send a binary node */
78
- const sendNode = (frame) => {
79
- if (logger.level === 'trace') {
80
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
81
- }
82
- const buff = (0, WABinary_1.encodeBinaryNode)(frame);
83
- return sendRawMessage(buff);
84
- };
85
- /** log & process any unexpected errors */
86
- const onUnexpectedError = (err, msg) => {
87
- logger.error({ err }, `unexpected error in '${msg}'`);
88
- };
89
- /** await the next incoming message */
90
- const awaitNextMessage = async (sendMsg) => {
91
- if (!ws.isOpen) {
92
- throw new boom_1.Boom('Connection Closed', {
93
- statusCode: Types_1.DisconnectReason.connectionClosed
94
- });
95
- }
96
- let onOpen;
97
- let onClose;
98
- const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
99
- onOpen = resolve;
100
- onClose = mapWebSocketError(reject);
101
- ws.on('frame', onOpen);
102
- ws.on('close', onClose);
103
- ws.on('error', onClose);
104
- })
105
- .finally(() => {
106
- ws.off('frame', onOpen);
107
- ws.off('close', onClose);
108
- ws.off('error', onClose);
109
- });
110
- if (sendMsg) {
111
- sendRawMessage(sendMsg).catch(onClose);
112
- }
113
- return result;
114
- };
115
- /**
116
- * Wait for a message with a certain tag to be received
117
- * @param msgId the message tag to await
118
- * @param timeoutMs timeout after which the promise will reject
119
- */
120
- const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
121
- let onRecv;
122
- let onErr;
123
- try {
124
- return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
125
- onRecv = resolve;
126
- onErr = err => {
127
- reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
128
- };
129
- ws.on(`TAG:${msgId}`, onRecv);
130
- ws.on('close', onErr); // if the socket closes, you'll never receive the message
131
- ws.off('error', onErr);
132
- });
133
- }
134
- finally {
135
- ws.off(`TAG:${msgId}`, onRecv);
136
- ws.off('close', onErr); // if the socket closes, you'll never receive the message
137
- ws.off('error', onErr);
138
- }
139
- };
140
- /** send a query, and wait for its response. auto-generates message ID if not provided */
141
- const query = async (node, timeoutMs) => {
142
- if (!node.attrs.id) {
143
- node.attrs.id = generateMessageTag();
144
- }
145
- const msgId = node.attrs.id;
146
- const wait = waitForMessage(msgId, timeoutMs);
147
- await sendNode(node);
148
- const result = await wait;
149
- if ('tag' in result) {
150
- (0, WABinary_1.assertNodeErrorFree)(result);
151
- }
152
- return result;
153
- };
154
- /** connection handshake */
155
- const validateConnection = async () => {
156
- let helloMsg = {
157
- clientHello: { ephemeral: ephemeralKeyPair.public }
158
- };
159
- helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
160
- logger.info({ browser, helloMsg }, 'connected to WA');
161
- const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
162
- const result = await awaitNextMessage(init);
163
- const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
164
- logger.trace({ handshake }, 'handshake recv from WA');
165
- const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
166
- let node;
167
- if (config.mobile) {
168
- node = (0, Utils_1.generateMobileNode)(config);
169
- }
170
- else if (!creds.me) {
171
- node = (0, Utils_1.generateRegistrationNode)(creds, config);
172
- logger.info({ node }, 'not logged in, attempting registration...');
173
- }
174
- else {
175
- node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
176
- logger.info({ node }, 'logging in...');
177
- }
178
- const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
179
- await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
180
- clientFinish: {
181
- static: keyEnc,
182
- payload: payloadEnc,
183
- },
184
- }).finish());
185
- await noise.finishInit();
186
- startKeepAliveRequest();
187
- };
188
- const getAvailablePreKeysOnServer = async () => {
189
- const result = await query({
190
- tag: 'iq',
191
- attrs: {
192
- id: generateMessageTag(),
193
- xmlns: 'encrypt',
194
- type: 'get',
195
- to: WABinary_1.S_WHATSAPP_NET
196
- },
197
- content: [
198
- { tag: 'count', attrs: {} }
199
- ]
200
- });
201
- const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
202
- return +countChild.attrs.value;
203
- };
204
- /** generates and uploads a set of pre-keys to the server */
205
- const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
206
- await keys.transaction(async () => {
207
- logger.info({ count }, 'uploading pre-keys');
208
- const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
209
- await query(node);
210
- ev.emit('creds.update', update);
211
- logger.info({ count }, 'uploaded pre-keys');
212
- });
213
- };
214
- const uploadPreKeysToServerIfRequired = async () => {
215
- const preKeyCount = await getAvailablePreKeysOnServer();
216
- logger.info(`${preKeyCount} pre-keys found on server`);
217
- if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
218
- await uploadPreKeys();
219
- }
220
- };
221
- const onMessageReceived = (data) => {
222
- noise.decodeFrame(data, frame => {
223
- var _a;
224
- // reset ping timeout
225
- lastDateRecv = new Date();
226
- let anyTriggered = false;
227
- anyTriggered = ws.emit('frame', frame);
228
- // if it's a binary node
229
- if (!(frame instanceof Uint8Array)) {
230
- const msgId = frame.attrs.id;
231
- if (logger.level === 'trace') {
232
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
233
- }
234
- /* Check if this is a response to a message we sent */
235
- anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
236
- /* Check if this is a response to a message we are expecting */
237
- const l0 = frame.tag;
238
- const l1 = frame.attrs || {};
239
- const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
240
- for (const key of Object.keys(l1)) {
241
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
242
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
243
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
244
- }
245
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
246
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
247
- if (!anyTriggered && logger.level === 'debug') {
248
- logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
249
- }
250
- }
251
- });
252
- };
253
- const end = (error) => {
254
- if (closed) {
255
- logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
256
- return;
257
- }
258
- closed = true;
259
- logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
260
- clearInterval(keepAliveReq);
261
- clearTimeout(qrTimer);
262
- ws.removeAllListeners('close');
263
- ws.removeAllListeners('error');
264
- ws.removeAllListeners('open');
265
- ws.removeAllListeners('message');
266
- if (!ws.isClosed && !ws.isClosing) {
267
- try {
268
- ws.close();
269
- }
270
- catch (_a) { }
271
- }
272
- ev.emit('connection.update', {
273
- connection: 'close',
274
- lastDisconnect: {
275
- error,
276
- date: new Date()
277
- }
278
- });
279
- ev.removeAllListeners('connection.update');
280
- };
281
- const waitForSocketOpen = async () => {
282
- if (ws.isOpen) {
283
- return;
284
- }
285
- if (ws.isClosed || ws.isClosing) {
286
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
287
- }
288
- let onOpen;
289
- let onClose;
290
- await new Promise((resolve, reject) => {
291
- onOpen = () => resolve(undefined);
292
- onClose = mapWebSocketError(reject);
293
- ws.on('open', onOpen);
294
- ws.on('close', onClose);
295
- ws.on('error', onClose);
296
- })
297
- .finally(() => {
298
- ws.off('open', onOpen);
299
- ws.off('close', onClose);
300
- ws.off('error', onClose);
301
- });
302
- };
303
- const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
304
- if (!lastDateRecv) {
305
- lastDateRecv = new Date();
306
- }
307
- const diff = Date.now() - lastDateRecv.getTime();
308
- /*
309
- check if it's been a suspicious amount of time since the server responded with our last seen
310
- it could be that the network is down
311
- */
312
- if (diff > keepAliveIntervalMs + 5000) {
313
- end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
314
- }
315
- else if (ws.isOpen) {
316
- // if its all good, send a keep alive request
317
- query({
318
- tag: 'iq',
319
- attrs: {
320
- id: generateMessageTag(),
321
- to: WABinary_1.S_WHATSAPP_NET,
322
- type: 'get',
323
- xmlns: 'w:p',
324
- },
325
- content: [{ tag: 'ping', attrs: {} }]
326
- })
327
- .catch(err => {
328
- logger.error({ trace: err.stack }, 'error in sending keep alive');
329
- });
330
- }
331
- else {
332
- logger.warn('keep alive called when WS not open');
333
- }
334
- }, keepAliveIntervalMs));
335
- /** i have no idea why this exists. pls enlighten me */
336
- const sendPassiveIq = (tag) => (query({
337
- tag: 'iq',
338
- attrs: {
339
- to: WABinary_1.S_WHATSAPP_NET,
340
- xmlns: 'passive',
341
- type: 'set',
342
- },
343
- content: [
344
- { tag, attrs: {} }
345
- ]
346
- }));
347
- /** logout & invalidate connection */
348
- const logout = async (msg) => {
349
- var _a;
350
- const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
351
- if (jid) {
352
- await sendNode({
353
- tag: 'iq',
354
- attrs: {
355
- to: WABinary_1.S_WHATSAPP_NET,
356
- type: 'set',
357
- id: generateMessageTag(),
358
- xmlns: 'md'
359
- },
360
- content: [
361
- {
362
- tag: 'remove-companion-device',
363
- attrs: {
364
- jid,
365
- reason: 'user_initiated'
366
- }
367
- }
368
- ]
369
- });
370
- }
371
- end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
372
- };
373
- const requestPairingCode = async (phoneNumber, pairKey = "ABCD1234") => {
374
- if (pairKey) {
375
- authState.creds.pairingCode = pairKey.toUpperCase()
376
- } else {
377
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
378
- }
379
- authState.creds.me = {
380
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
381
- name: '~'
382
- };
383
- ev.emit('creds.update', authState.creds);
384
- const node = {
385
- tag: 'iq',
386
- attrs: {
387
- to: WABinary_1.S_WHATSAPP_NET,
388
- type: 'set',
389
- id: generateMessageTag(),
390
- xmlns: 'md'
391
- },
392
- content: [
393
- {
394
- tag: 'link_code_companion_reg',
395
- attrs: {
396
- jid: authState.creds.me.id,
397
- stage: 'companion_hello',
398
- should_show_push_notification: 'true'
399
- },
400
- content: [
401
- {
402
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
403
- attrs: {},
404
- content: await generatePairingKey()
405
- },
406
- {
407
- tag: 'companion_server_auth_key_pub',
408
- attrs: {},
409
- content: authState.creds.noiseKey.public
410
- },
411
- {
412
- tag: 'companion_platform_id',
413
- attrs: {},
414
- content: (0, Utils_1.getPlatformId)(browser[1])
415
- },
416
- {
417
- tag: 'companion_platform_display',
418
- attrs: {},
419
- content: `${browser[1]} (${browser[0]})`
420
- },
421
- {
422
- tag: 'link_code_pairing_nonce',
423
- attrs: {},
424
- content: '0'
425
- }
426
- ]
427
- }
428
- ]
429
- };
430
- await sendNode(node);
431
- return authState.creds.pairingCode;
432
- };
433
- async function generatePairingKey() {
434
- const salt = (0, crypto_1.randomBytes)(32);
435
- const randomIv = (0, crypto_1.randomBytes)(16);
436
- const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
437
- const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
438
- return Buffer.concat([salt, randomIv, ciphered]);
439
- }
440
- const sendWAMBuffer = (wamBuffer) => {
441
- return query({
442
- tag: 'iq',
443
- attrs: {
444
- to: WABinary_1.S_WHATSAPP_NET,
445
- id: generateMessageTag(),
446
- xmlns: 'w:stats'
447
- },
448
- content: [
449
- {
450
- tag: 'add',
451
- attrs: {},
452
- content: wamBuffer
453
- }
454
- ]
455
- });
456
- };
457
- ws.on('message', onMessageReceived);
458
- ws.on('open', async () => {
459
- try {
460
- await validateConnection();
461
- }
462
- catch (err) {
463
- logger.error({ err }, 'error in validating connection');
464
- end(err);
465
- }
466
- });
467
- ws.on('error', mapWebSocketError(end));
468
- ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
469
- // the server terminated the connection
470
- ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
471
- // QR gen
472
- ws.on('CB:iq,type:set,pair-device', async (stanza) => {
473
- const iq = {
474
- tag: 'iq',
475
- attrs: {
476
- to: WABinary_1.S_WHATSAPP_NET,
477
- type: 'result',
478
- id: stanza.attrs.id,
479
- }
480
- };
481
- await sendNode(iq);
482
- const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
483
- const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
484
- const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
485
- const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
486
- const advB64 = creds.advSecretKey;
487
- let qrMs = qrTimeout || 60000; // time to let a QR live
488
- const genPairQR = () => {
489
- if (!ws.isOpen) {
490
- return;
491
- }
492
- const refNode = refNodes.shift();
493
- if (!refNode) {
494
- end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
495
- return;
496
- }
497
- const ref = refNode.content.toString('utf-8');
498
- const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
499
- ev.emit('connection.update', { qr });
500
- qrTimer = setTimeout(genPairQR, qrMs);
501
- qrMs = qrTimeout || 20000; // shorter subsequent qrs
502
- };
503
- genPairQR();
504
- });
505
- // device paired for the first time
506
- // if device pairs successfully, the server asks to restart the connection
507
- ws.on('CB:iq,,pair-success', async (stanza) => {
508
- logger.debug('pair success recv');
509
- try {
510
- const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
511
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
512
- ev.emit('creds.update', updatedCreds);
513
- ev.emit('connection.update', { isNewLogin: true, qr: undefined });
514
- await sendNode(reply);
515
- }
516
- catch (error) {
517
- logger.info({ trace: error.stack }, 'error in pairing');
518
- end(error);
519
- }
520
- });
521
- // login complete
522
- ws.on('CB:success', async (node) => {
523
- try {
524
- await uploadPreKeysToServerIfRequired();
525
- await sendPassiveIq('active');
526
- logger.info('opened connection to WA');
527
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
528
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
529
- ev.emit('connection.update', { connection: 'open' });
530
- }
531
- catch (err) {
532
- logger.error({ err }, 'error opening connection');
533
- end(err);
534
- }
535
- });
536
- ws.on('CB:stream:error', (node) => {
537
- logger.error({ node }, 'stream errored out');
538
- const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
539
- end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
540
- });
541
- // stream fail, possible logout
542
- ws.on('CB:failure', (node) => {
543
- const reason = +(node.attrs.reason || 500);
544
- end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
545
- });
546
- ws.on('CB:ib,,downgrade_webclient', () => {
547
- end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
548
- });
549
- ws.on('CB:ib,,offline_preview', (node) => {
550
- logger.info('offline preview received', JSON.stringify(node));
551
- sendNode({
552
- tag: 'ib',
553
- attrs: {},
554
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
555
- });
556
- });
557
- ws.on('CB:ib,,edge_routing', (node) => {
558
- const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
559
- const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
560
- if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
561
- authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
562
- ev.emit('creds.update', authState.creds);
563
- }
564
- });
565
- let didStartBuffer = false;
566
- process.nextTick(() => {
567
- var _a;
568
- if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
569
- // start buffering important events
570
- // if we're logged in
571
- ev.buffer();
572
- didStartBuffer = true;
573
- }
574
- ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
575
- });
576
- // called when all offline notifs are handled
577
- ws.on('CB:ib,,offline', (node) => {
578
- const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
579
- const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
580
- logger.info(`handled ${offlineNotifs} offline messages/notifications`);
581
- if (didStartBuffer) {
582
- ev.flush();
583
- logger.trace('flushed events for initial buffer');
584
- }
585
- ev.emit('connection.update', { receivedPendingNotifications: true });
586
- });
587
- // update credentials when required
588
- ev.on('creds.update', update => {
589
- var _a, _b;
590
- const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
591
- // if name has just been received
592
- if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
593
- logger.debug({ name }, 'updated pushName');
594
- sendNode({
595
- tag: 'presence',
596
- attrs: { name: name }
597
- })
598
- .catch(err => {
599
- logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
600
- });
601
- }
602
- Object.assign(creds, update);
603
- });
604
- if (printQRInTerminal) {
605
- (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
606
- }
607
- return {
608
- type: 'md',
609
- ws,
610
- ev,
611
- authState: { creds, keys },
612
- signalRepository,
613
- get user() {
614
- return authState.creds.me;
615
- },
616
- generateMessageTag,
617
- query,
618
- waitForMessage,
619
- waitForSocketOpen,
620
- sendRawMessage,
621
- sendNode,
622
- logout,
623
- end,
624
- onUnexpectedError,
625
- uploadPreKeys,
626
- uploadPreKeysToServerIfRequired,
627
- requestPairingCode,
628
- /** Waits for the connection to WA to reach a state */
629
- waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
630
- sendWAMBuffer,
631
- };
632
- };
633
- exports.makeSocket = makeSocket;
634
- /**
635
- * map the websocket error to the right type
636
- * so it can be retried by the caller
637
- * */
638
- function mapWebSocketError(handler) {
639
- return (error) => {
640
- handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
641
- };
642
- }
@@ -1,37 +0,0 @@
1
- /// <reference types="node" />
2
- import { Boom } from '@hapi/boom';
3
- import { SocketConfig } from '../Types';
4
- import { BinaryNode } from '../WABinary';
5
- import { USyncQuery } from '../WAUSync';
6
- export declare const makeUSyncSocket: (config: SocketConfig) => {
7
- executeUSyncQuery: (usyncQuery: USyncQuery) => Promise<import("../WAUSync").USyncQueryResult | undefined>;
8
- type: "md";
9
- ws: any;
10
- ev: import("../Types").BaileysEventEmitter & {
11
- process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
12
- buffer(): void;
13
- createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
14
- flush(force?: boolean | undefined): boolean;
15
- isBuffering(): boolean;
16
- };
17
- authState: {
18
- creds: import("../Types").AuthenticationCreds;
19
- keys: import("../Types").SignalKeyStoreWithTransaction;
20
- };
21
- signalRepository: import("../Types").SignalRepository;
22
- user: import("../Types").Contact | undefined;
23
- generateMessageTag: () => string;
24
- query: (node: BinaryNode, timeoutMs?: number | undefined) => Promise<BinaryNode>;
25
- waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<T_1>;
26
- waitForSocketOpen: () => Promise<void>;
27
- sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
28
- sendNode: (frame: BinaryNode) => Promise<void>;
29
- logout: (msg?: string | undefined) => Promise<void>;
30
- end: (error: Error | undefined) => void;
31
- onUnexpectedError: (err: Error | Boom<any>, msg: string) => void;
32
- uploadPreKeys: (count?: number) => Promise<void>;
33
- uploadPreKeysToServerIfRequired: () => Promise<void>;
34
- requestPairingCode: (phoneNumber: string, pairCode: string) => Promise<string>;
35
- waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number | undefined) => Promise<void>;
36
- sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
37
- };