@hanzzy/baileys-mod 8.0.6 → 8.0.10

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