queenjusmy-baileys 3.0.8

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