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