@vinzsocket/baileys 2.8.10 → 2.8.20

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 (83) hide show
  1. package/lib/Defaults/index.js +75 -73
  2. package/lib/Signal/Group/ciphertext-message.js +9 -9
  3. package/lib/Signal/Group/group-session-builder.js +21 -21
  4. package/lib/Signal/Group/group_cipher.js +79 -81
  5. package/lib/Signal/Group/index.js +2 -2
  6. package/lib/Signal/Group/keyhelper.js +9 -9
  7. package/lib/Signal/Group/queue-job.js +43 -46
  8. package/lib/Signal/Group/sender-chain-key.js +24 -25
  9. package/lib/Signal/Group/sender-key-distribution-message.js +50 -58
  10. package/lib/Signal/Group/sender-key-message.js +55 -60
  11. package/lib/Signal/Group/sender-key-name.js +38 -39
  12. package/lib/Signal/Group/sender-key-record.js +39 -41
  13. package/lib/Signal/Group/sender-key-state.js +85 -89
  14. package/lib/Signal/Group/sender-message-key.js +22 -22
  15. package/lib/Signal/libsignal.js +387 -292
  16. package/lib/Signal/lid-mapping.js +98 -93
  17. package/lib/Socket/Client/types.js +6 -6
  18. package/lib/Socket/Client/websocket.js +44 -44
  19. package/lib/Socket/business.js +350 -365
  20. package/lib/Socket/chats.js +1019 -914
  21. package/lib/Socket/communities.js +454 -376
  22. package/lib/Socket/groups.js +378 -310
  23. package/lib/Socket/index.js +11 -11
  24. package/lib/Socket/messages-recv.js +1355 -1182
  25. package/lib/Socket/messages-send.js +1224 -1081
  26. package/lib/Socket/mex.js +40 -34
  27. package/lib/Socket/newsletter.js +212 -169
  28. package/lib/Socket/socket.js +896 -757
  29. package/lib/Store/index.js +1 -1
  30. package/lib/Store/make-cache-manager-store.js +75 -79
  31. package/lib/Store/make-in-memory-store.js +450 -389
  32. package/lib/Store/make-ordered-dictionary.js +73 -76
  33. package/lib/Store/object-repository.js +24 -22
  34. package/lib/Types/Chat.js +1 -7
  35. package/lib/Types/Label.js +20 -20
  36. package/lib/Types/LabelAssociation.js +2 -2
  37. package/lib/Types/Message.js +2 -2
  38. package/lib/Types/Newsletter.js +24 -24
  39. package/lib/Types/Socket.js +1 -1
  40. package/lib/Types/State.js +8 -8
  41. package/lib/Types/index.js +10 -10
  42. package/lib/Utils/auth-utils.js +408 -401
  43. package/lib/Utils/baileys-event-stream.js +44 -35
  44. package/lib/Utils/business.js +200 -197
  45. package/lib/Utils/chat-utils.js +775 -708
  46. package/lib/Utils/crypto.js +97 -85
  47. package/lib/Utils/decode-wa-message.js +240 -227
  48. package/lib/Utils/event-buffer.js +547 -518
  49. package/lib/Utils/extended-messages.js +250 -203
  50. package/lib/Utils/generics.js +300 -289
  51. package/lib/Utils/history.js +76 -69
  52. package/lib/Utils/lid-resolver.js +47 -42
  53. package/lib/Utils/link-preview.js +75 -65
  54. package/lib/Utils/logger.js +3 -1
  55. package/lib/Utils/lt-hash.js +38 -34
  56. package/lib/Utils/make-mutex.js +32 -34
  57. package/lib/Utils/mention.js +79 -86
  58. package/lib/Utils/message-retry-manager.js +148 -136
  59. package/lib/Utils/messages-media.js +652 -562
  60. package/lib/Utils/messages.js +753 -707
  61. package/lib/Utils/noise-handler.js +156 -135
  62. package/lib/Utils/process-message.js +404 -341
  63. package/lib/Utils/signal.js +180 -118
  64. package/lib/Utils/use-multi-file-auth-state.js +87 -91
  65. package/lib/Utils/validate-connection.js +167 -142
  66. package/lib/WABinary/constants.js +28 -1293
  67. package/lib/WABinary/decode.js +220 -218
  68. package/lib/WABinary/encode.js +199 -201
  69. package/lib/WABinary/generic-utils.js +80 -77
  70. package/lib/WABinary/jid-utils.js +41 -35
  71. package/lib/WAM/BinaryInfo.js +7 -7
  72. package/lib/WAM/constants.js +1 -15241
  73. package/lib/WAM/encode.js +124 -131
  74. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  75. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +51 -47
  76. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +22 -22
  77. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +30 -32
  78. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +19 -19
  79. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -43
  80. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +17 -17
  81. package/lib/WAUSync/USyncQuery.js +82 -84
  82. package/lib/WAUSync/USyncUser.js +20 -20
  83. package/package.json +5 -2
@@ -15,791 +15,930 @@ import { WebSocketClient } from './Client/index.js';
15
15
  * - listen to messages and emit events
16
16
  * - query phone connection
17
17
  */
18
- export const makeSocket = (config) => {
19
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
20
- const uqTagId = generateMdTagPrefix();
21
- const generateMessageTag = () => `${uqTagId}${epoch++}`;
22
- if (printQRInTerminal) {
23
- console.warn('⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
24
- }
25
- const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
26
- if (config.mobile || url.protocol === 'tcp:') {
27
- throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
28
- }
29
- if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
30
- url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
31
- }
32
- /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
33
- const ephemeralKeyPair = Curve.generateKeyPair();
34
- /** WA noise protocol wrapper */
35
- const noise = makeNoiseHandler({
36
- keyPair: ephemeralKeyPair,
37
- NOISE_HEADER: NOISE_WA_HEADER,
38
- logger,
39
- routingInfo: authState?.creds?.routingInfo
18
+ export const makeSocket = config => {
19
+ const {
20
+ waWebSocketUrl,
21
+ connectTimeoutMs,
22
+ logger,
23
+ keepAliveIntervalMs,
24
+ browser,
25
+ auth: authState,
26
+ printQRInTerminal,
27
+ defaultQueryTimeoutMs,
28
+ transactionOpts,
29
+ qrTimeout,
30
+ makeSignalRepository
31
+ } = config;
32
+ const uqTagId = generateMdTagPrefix();
33
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
34
+ if (printQRInTerminal) {
35
+ console.warn('⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
36
+ }
37
+ const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
38
+ if (config.mobile || url.protocol === 'tcp:') {
39
+ throw new Boom('Mobile API is not supported anymore', {
40
+ statusCode: DisconnectReason.loggedOut
40
41
  });
41
- const ws = new WebSocketClient(url, config);
42
- ws.connect();
43
- const sendPromise = promisify(ws.send);
44
- /** send a raw buffer */
45
- const sendRawMessage = async (data) => {
46
- if (!ws.isOpen) {
47
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
48
- }
49
- const bytes = noise.encodeFrame(data);
50
- await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
51
- try {
52
- await sendPromise.call(ws, bytes);
53
- resolve();
54
- }
55
- catch (error) {
56
- reject(error);
57
- }
58
- });
59
- };
60
- /** send a binary node */
61
- const sendNode = (frame) => {
62
- if (logger.level === 'trace') {
63
- logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
64
- }
65
- const buff = encodeBinaryNode(frame);
66
- return sendRawMessage(buff);
67
- };
68
- /**
69
- * Wait for a message with a certain tag to be received
70
- * @param msgId the message tag to await
71
- * @param timeoutMs timeout after which the promise will reject
72
- */
73
- const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
74
- let onRecv;
75
- let onErr;
76
- try {
77
- const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
78
- onRecv = data => {
79
- resolve(data);
80
- };
81
- onErr = err => {
82
- reject(err ||
83
- new Boom('Connection Closed', {
84
- statusCode: DisconnectReason.connectionClosed
85
- }));
86
- };
87
- ws.on(`TAG:${msgId}`, onRecv);
88
- ws.on('close', onErr);
89
- ws.on('error', onErr);
90
- return () => reject(new Boom('Query Cancelled'));
91
- });
92
- return result;
93
- }
94
- catch (error) {
95
- // Catch timeout and return undefined instead of throwing
96
- if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
97
- logger?.warn?.({ msgId }, 'timed out waiting for message');
98
- return undefined;
99
- }
100
- throw error;
101
- }
102
- finally {
103
- if (onRecv)
104
- ws.off(`TAG:${msgId}`, onRecv);
105
- if (onErr) {
106
- ws.off('close', onErr);
107
- ws.off('error', onErr);
108
- }
109
- }
110
- };
111
- /** send a query, and wait for its response. auto-generates message ID if not provided */
112
- const query = async (node, timeoutMs) => {
113
- if (!node.attrs.id) {
114
- node.attrs.id = generateMessageTag();
115
- }
116
- const msgId = node.attrs.id;
117
- const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
118
- const result = waitForMessage(msgId, timeoutMs).catch(reject);
119
- sendNode(node)
120
- .then(async () => resolve(await result))
121
- .catch(reject);
122
- });
123
- if (result && 'tag' in result) {
124
- assertNodeErrorFree(result);
125
- }
126
- return result;
127
- };
128
- const executeUSyncQuery = async (usyncQuery) => {
129
- if (usyncQuery.protocols.length === 0) {
130
- throw new Boom('USyncQuery must have at least one protocol');
131
- }
132
- // todo: validate users, throw WARNING on no valid users
133
- // variable below has only validated users
134
- const validUsers = usyncQuery.users;
135
- const userNodes = validUsers.map(user => {
136
- return {
137
- tag: 'user',
138
- attrs: {
139
- jid: !user.phone ? user.id : undefined
140
- },
141
- content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
142
- };
143
- });
144
- const listNode = {
145
- tag: 'list',
146
- attrs: {},
147
- content: userNodes
148
- };
149
- const queryNode = {
150
- tag: 'query',
151
- attrs: {},
152
- content: usyncQuery.protocols.map(a => a.getQueryElement())
153
- };
154
- const iq = {
155
- tag: 'iq',
156
- attrs: {
157
- to: S_WHATSAPP_NET,
158
- type: 'get',
159
- xmlns: 'usync'
160
- },
161
- content: [
162
- {
163
- tag: 'usync',
164
- attrs: {
165
- context: usyncQuery.context,
166
- mode: usyncQuery.mode,
167
- sid: generateMessageTag(),
168
- last: 'true',
169
- index: '0'
170
- },
171
- content: [queryNode, listNode]
172
- }
173
- ]
42
+ }
43
+ if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
44
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
45
+ }
46
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
47
+ const ephemeralKeyPair = Curve.generateKeyPair();
48
+ /** WA noise protocol wrapper */
49
+ const noise = makeNoiseHandler({
50
+ keyPair: ephemeralKeyPair,
51
+ NOISE_HEADER: NOISE_WA_HEADER,
52
+ logger,
53
+ routingInfo: authState?.creds?.routingInfo
54
+ });
55
+ const ws = new WebSocketClient(url, config);
56
+ ws.connect();
57
+ const sendPromise = promisify(ws.send);
58
+ /** send a raw buffer */
59
+ const sendRawMessage = async data => {
60
+ if (!ws.isOpen) {
61
+ throw new Boom('Connection Closed', {
62
+ statusCode: DisconnectReason.connectionClosed
63
+ });
64
+ }
65
+ const bytes = noise.encodeFrame(data);
66
+ await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
67
+ try {
68
+ await sendPromise.call(ws, bytes);
69
+ resolve();
70
+ } catch (error) {
71
+ reject(error);
72
+ }
73
+ });
74
+ };
75
+ /** send a binary node */
76
+ const sendNode = frame => {
77
+ if (logger.level === 'trace') {
78
+ logger.trace({
79
+ xml: binaryNodeToString(frame),
80
+ msg: 'xml send'
81
+ });
82
+ }
83
+ const buff = encodeBinaryNode(frame);
84
+ return sendRawMessage(buff);
85
+ };
86
+ /**
87
+ * Wait for a message with a certain tag to be received
88
+ * @param msgId the message tag to await
89
+ * @param timeoutMs timeout after which the promise will reject
90
+ */
91
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
92
+ let onRecv;
93
+ let onErr;
94
+ try {
95
+ const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
96
+ onRecv = data => {
97
+ resolve(data);
174
98
  };
175
- const result = await query(iq);
176
- return usyncQuery.parseUSyncQueryResult(result);
177
- };
178
- const onWhatsApp = async (...jids) => {
179
- const usyncQuery = new USyncQuery().withLIDProtocol();
180
- // .withContactProtocol() when dealing with phone
181
- // .withId simply with LIDs and WIDs
182
- for (const jid of jids) {
183
- if (isLidUser(jid)) {
184
- usyncQuery.withUser(new USyncUser().withId(jid)); // intentional
185
- }
186
- else {
187
- const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
188
- usyncQuery.withUser(new USyncUser().withPhone(phone));
189
- }
190
- }
191
- const results = await executeUSyncQuery(usyncQuery);
192
- if (results) {
193
- if (results.list.filter(a => a.lid).length > 0) {
194
- const lidMapping = signalRepository.getLIDMappingStore();
195
- const lidOnly = results.list.filter(a => a.lid);
196
- await lidMapping.storeLIDPNMappings(lidOnly.map(a => ({ pn: a.id, lid: a.lid })));
197
- }
198
- return results.list
199
- .filter(a => !!a.contact)
200
- .map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid: lid }));
201
- }
202
- };
203
- const ev = makeEventBuffer(logger);
204
- const { creds } = authState;
205
- // add transaction capability
206
- const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
207
- const signalRepository = makeSignalRepository({ creds, keys }, onWhatsApp);
208
- let lastDateRecv;
209
- let epoch = 1;
210
- let keepAliveReq;
211
- let qrTimer;
212
- let closed = false;
213
- /** log & process any unexpected errors */
214
- const onUnexpectedError = (err, msg) => {
215
- logger.error({ err }, `unexpected error in '${msg}'`);
216
- };
217
- /** await the next incoming message */
218
- const awaitNextMessage = async (sendMsg) => {
219
- if (!ws.isOpen) {
220
- throw new Boom('Connection Closed', {
221
- statusCode: DisconnectReason.connectionClosed
222
- });
223
- }
224
- let onOpen;
225
- let onClose;
226
- const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
227
- onOpen = resolve;
228
- onClose = mapWebSocketError(reject);
229
- ws.on('frame', onOpen);
230
- ws.on('close', onClose);
231
- ws.on('error', onClose);
232
- }).finally(() => {
233
- ws.off('frame', onOpen);
234
- ws.off('close', onClose);
235
- ws.off('error', onClose);
236
- });
237
- if (sendMsg) {
238
- sendRawMessage(sendMsg).catch(onClose);
239
- }
240
- return result;
241
- };
242
- /** connection handshake */
243
- const validateConnection = async () => {
244
- let helloMsg = {
245
- clientHello: { ephemeral: ephemeralKeyPair.public }
99
+ onErr = err => {
100
+ reject(err || new Boom('Connection Closed', {
101
+ statusCode: DisconnectReason.connectionClosed
102
+ }));
246
103
  };
247
- helloMsg = proto.HandshakeMessage.create(helloMsg);
248
- logger.info({ browser, helloMsg }, 'connected to WA');
249
- const init = proto.HandshakeMessage.encode(helloMsg).finish();
250
- const result = await awaitNextMessage(init);
251
- const handshake = proto.HandshakeMessage.decode(result);
252
- logger.trace({ handshake }, 'handshake recv from WA');
253
- const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
254
- let node;
255
- if (!creds.me) {
256
- node = generateRegistrationNode(creds, config);
257
- logger.info({ node }, 'not logged in, attempting registration...');
258
- }
259
- else {
260
- node = generateLoginNode(creds.me.id, config);
261
- logger.info({ node }, 'logging in...');
262
- }
263
- const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
264
- await sendRawMessage(proto.HandshakeMessage.encode({
265
- clientFinish: {
266
- static: keyEnc,
267
- payload: payloadEnc
268
- }
269
- }).finish());
270
- noise.finishInit();
271
- startKeepAliveRequest();
272
- };
273
- const getAvailablePreKeysOnServer = async () => {
274
- const result = await query({
275
- tag: 'iq',
276
- attrs: {
277
- id: generateMessageTag(),
278
- xmlns: 'encrypt',
279
- type: 'get',
280
- to: S_WHATSAPP_NET
281
- },
282
- content: [{ tag: 'count', attrs: {} }]
283
- });
284
- const countChild = getBinaryNodeChild(result, 'count');
285
- return +countChild.attrs.value;
286
- };
287
- // Pre-key upload state management
288
- let uploadPreKeysPromise = null;
289
- let lastUploadTime = 0;
290
- /** generates and uploads a set of pre-keys to the server */
291
- const uploadPreKeys = async (count = INITIAL_PREKEY_COUNT, retryCount = 0) => {
292
- // Check minimum interval (except for retries)
293
- if (retryCount === 0) {
294
- const timeSinceLastUpload = Date.now() - lastUploadTime;
295
- if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
296
- logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
297
- return;
298
- }
299
- }
300
- // Prevent multiple concurrent uploads
301
- if (uploadPreKeysPromise) {
302
- logger.debug('Pre-key upload already in progress, waiting for completion');
303
- return uploadPreKeysPromise;
304
- }
305
- const uploadLogic = async () => {
306
- logger.info({ count, retryCount }, 'uploading pre-keys');
307
- // Generate and save pre-keys atomically (prevents ID collisions on retry)
308
- const node = await keys.transaction(async () => {
309
- logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
310
- const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
311
- // Update credentials immediately to prevent duplicate IDs on retry
312
- ev.emit('creds.update', update);
313
- return node; // Only return node since update is already used
314
- }, creds?.me?.id || 'upload-pre-keys');
315
- // Upload to server (outside transaction, can fail without affecting local keys)
316
- try {
317
- await query(node);
318
- logger.info({ count }, 'uploaded pre-keys successfully');
319
- lastUploadTime = Date.now();
320
- }
321
- catch (uploadError) {
322
- logger.error({ uploadError, count }, 'Failed to upload pre-keys to server');
323
- // Exponential backoff retry (max 3 retries)
324
- if (retryCount < 3) {
325
- const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
326
- logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
327
- await new Promise(resolve => setTimeout(resolve, backoffDelay));
328
- return uploadPreKeys(count, retryCount + 1);
329
- }
330
- throw uploadError;
331
- }
332
- };
333
- // Add timeout protection
334
- uploadPreKeysPromise = Promise.race([
335
- uploadLogic(),
336
- new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
337
- ]);
338
- try {
339
- await uploadPreKeysPromise;
340
- }
341
- finally {
342
- uploadPreKeysPromise = null;
343
- }
344
- };
345
- const verifyCurrentPreKeyExists = async () => {
346
- const currentPreKeyId = creds.nextPreKeyId - 1;
347
- if (currentPreKeyId <= 0) {
348
- return { exists: false, currentPreKeyId: 0 };
349
- }
350
- const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
351
- const exists = !!preKeys[currentPreKeyId.toString()];
352
- return { exists, currentPreKeyId };
353
- };
354
- const uploadPreKeysToServerIfRequired = async () => {
355
- try {
356
- const preKeyCount = await getAvailablePreKeysOnServer();
357
- const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
358
- logger.info(`${preKeyCount} pre-keys found on server`);
359
- logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
360
- const lowServerCount = preKeyCount <= MIN_PREKEY_COUNT;
361
- const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
362
- const shouldUpload = lowServerCount || missingCurrentPreKey;
363
- if (shouldUpload) {
364
- const reasons = [];
365
- if (lowServerCount)
366
- reasons.push(`server count low (${preKeyCount})`);
367
- if (missingCurrentPreKey)
368
- reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
369
- logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
370
- await uploadPreKeys();
371
- }
372
- else {
373
- logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
374
- }
375
- }
376
- catch (error) {
377
- logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
378
- // Don't throw - allow connection to continue even if pre-key check fails
379
- }
380
- };
381
- const onMessageReceived = (data) => {
382
- noise.decodeFrame(data, frame => {
383
- // reset ping timeout
384
- lastDateRecv = new Date();
385
- let anyTriggered = false;
386
- anyTriggered = ws.emit('frame', frame);
387
- // if it's a binary node
388
- if (!(frame instanceof Uint8Array)) {
389
- const msgId = frame.attrs.id;
390
- if (logger.level === 'trace') {
391
- logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
392
- }
393
- /* Check if this is a response to a message we sent */
394
- anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
395
- /* Check if this is a response to a message we are expecting */
396
- const l0 = frame.tag;
397
- const l1 = frame.attrs || {};
398
- const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
399
- for (const key of Object.keys(l1)) {
400
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
401
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
402
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
403
- }
404
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
405
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
406
- if (!anyTriggered && logger.level === 'debug') {
407
- logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
408
- }
409
- }
410
- });
411
- };
412
- const end = (error) => {
413
- if (closed) {
414
- logger.trace({ trace: error?.stack }, 'connection already closed');
415
- return;
416
- }
417
- closed = true;
418
- logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
419
- clearInterval(keepAliveReq);
420
- clearTimeout(qrTimer);
421
- ws.removeAllListeners('close');
422
- ws.removeAllListeners('open');
423
- ws.removeAllListeners('message');
424
- if (!ws.isClosed && !ws.isClosing) {
425
- try {
426
- ws.close();
427
- }
428
- catch { }
429
- }
430
- ev.emit('connection.update', {
431
- connection: 'close',
432
- lastDisconnect: {
433
- error,
434
- date: new Date()
435
- }
436
- });
437
- ev.removeAllListeners('connection.update');
104
+ ws.on(`TAG:${msgId}`, onRecv);
105
+ ws.on('close', onErr);
106
+ ws.on('error', onErr);
107
+ return () => reject(new Boom('Query Cancelled'));
108
+ });
109
+ return result;
110
+ } catch (error) {
111
+ // Catch timeout and return undefined instead of throwing
112
+ if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
113
+ logger?.warn?.({
114
+ msgId
115
+ }, 'timed out waiting for message');
116
+ return undefined;
117
+ }
118
+ throw error;
119
+ } finally {
120
+ if (onRecv) ws.off(`TAG:${msgId}`, onRecv);
121
+ if (onErr) {
122
+ ws.off('close', onErr);
123
+ ws.off('error', onErr);
124
+ }
125
+ }
126
+ };
127
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
128
+ const query = async (node, timeoutMs) => {
129
+ if (!node.attrs.id) {
130
+ node.attrs.id = generateMessageTag();
131
+ }
132
+ const msgId = node.attrs.id;
133
+ const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
134
+ const result = waitForMessage(msgId, timeoutMs).catch(reject);
135
+ sendNode(node).then(async () => resolve(await result)).catch(reject);
136
+ });
137
+ if (result && 'tag' in result) {
138
+ assertNodeErrorFree(result);
139
+ }
140
+ return result;
141
+ };
142
+ const executeUSyncQuery = async usyncQuery => {
143
+ if (usyncQuery.protocols.length === 0) {
144
+ throw new Boom('USyncQuery must have at least one protocol');
145
+ }
146
+ // todo: validate users, throw WARNING on no valid users
147
+ // variable below has only validated users
148
+ const validUsers = usyncQuery.users;
149
+ const userNodes = validUsers.map(user => {
150
+ return {
151
+ tag: 'user',
152
+ attrs: {
153
+ jid: !user.phone ? user.id : undefined
154
+ },
155
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
156
+ };
157
+ });
158
+ const listNode = {
159
+ tag: 'list',
160
+ attrs: {},
161
+ content: userNodes
438
162
  };
439
- const waitForSocketOpen = async () => {
440
- if (ws.isOpen) {
441
- return;
442
- }
443
- if (ws.isClosed || ws.isClosing) {
444
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
445
- }
446
- let onOpen;
447
- let onClose;
448
- await new Promise((resolve, reject) => {
449
- onOpen = () => resolve(undefined);
450
- onClose = mapWebSocketError(reject);
451
- ws.on('open', onOpen);
452
- ws.on('close', onClose);
453
- ws.on('error', onClose);
454
- }).finally(() => {
455
- ws.off('open', onOpen);
456
- ws.off('close', onClose);
457
- ws.off('error', onClose);
458
- });
163
+ const queryNode = {
164
+ tag: 'query',
165
+ attrs: {},
166
+ content: usyncQuery.protocols.map(a => a.getQueryElement())
459
167
  };
460
- const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
461
- if (!lastDateRecv) {
462
- lastDateRecv = new Date();
463
- }
464
- const diff = Date.now() - lastDateRecv.getTime();
465
- /*
466
- check if it's been a suspicious amount of time since the server responded with our last seen
467
- it could be that the network is down
468
- */
469
- if (diff > keepAliveIntervalMs + 5000) {
470
- end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
471
- }
472
- else if (ws.isOpen) {
473
- // if its all good, send a keep alive request
474
- query({
475
- tag: 'iq',
476
- attrs: {
477
- id: generateMessageTag(),
478
- to: S_WHATSAPP_NET,
479
- type: 'get',
480
- xmlns: 'w:p'
481
- },
482
- content: [{ tag: 'ping', attrs: {} }]
483
- }).catch(err => {
484
- logger.error({ trace: err.stack }, 'error in sending keep alive');
485
- });
486
- }
487
- else {
488
- logger.warn('keep alive called when WS not open');
489
- }
490
- }, keepAliveIntervalMs));
491
- /** i have no idea why this exists. pls enlighten me */
492
- const sendPassiveIq = (tag) => query({
493
- tag: 'iq',
168
+ const iq = {
169
+ tag: 'iq',
170
+ attrs: {
171
+ to: S_WHATSAPP_NET,
172
+ type: 'get',
173
+ xmlns: 'usync'
174
+ },
175
+ content: [{
176
+ tag: 'usync',
494
177
  attrs: {
495
- to: S_WHATSAPP_NET,
496
- xmlns: 'passive',
497
- type: 'set'
178
+ context: usyncQuery.context,
179
+ mode: usyncQuery.mode,
180
+ sid: generateMessageTag(),
181
+ last: 'true',
182
+ index: '0'
498
183
  },
499
- content: [{ tag, attrs: {} }]
184
+ content: [queryNode, listNode]
185
+ }]
186
+ };
187
+ const result = await query(iq);
188
+ return usyncQuery.parseUSyncQueryResult(result);
189
+ };
190
+ const onWhatsApp = async (...jids) => {
191
+ const usyncQuery = new USyncQuery().withLIDProtocol();
192
+ // .withContactProtocol() when dealing with phone
193
+ // .withId simply with LIDs and WIDs
194
+ for (const jid of jids) {
195
+ if (isLidUser(jid)) {
196
+ usyncQuery.withUser(new USyncUser().withId(jid)); // intentional
197
+ } else {
198
+ const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
199
+ usyncQuery.withUser(new USyncUser().withPhone(phone));
200
+ }
201
+ }
202
+ const results = await executeUSyncQuery(usyncQuery);
203
+ if (results) {
204
+ if (results.list.filter(a => a.lid).length > 0) {
205
+ const lidMapping = signalRepository.getLIDMappingStore();
206
+ const lidOnly = results.list.filter(a => a.lid);
207
+ await lidMapping.storeLIDPNMappings(lidOnly.map(a => ({
208
+ pn: a.id,
209
+ lid: a.lid
210
+ })));
211
+ }
212
+ return results.list.filter(a => !!a.contact).map(({
213
+ contact,
214
+ id,
215
+ lid
216
+ }) => ({
217
+ jid: id,
218
+ exists: contact,
219
+ lid: lid
220
+ }));
221
+ }
222
+ };
223
+ const ev = makeEventBuffer(logger);
224
+ const {
225
+ creds
226
+ } = authState;
227
+ // add transaction capability
228
+ const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
229
+ const signalRepository = makeSignalRepository({
230
+ creds,
231
+ keys
232
+ }, onWhatsApp);
233
+ let lastDateRecv;
234
+ let epoch = 1;
235
+ let keepAliveReq;
236
+ let qrTimer;
237
+ let closed = false;
238
+ /** log & process any unexpected errors */
239
+ const onUnexpectedError = (err, msg) => {
240
+ logger.error({
241
+ err
242
+ }, `unexpected error in '${msg}'`);
243
+ };
244
+ /** await the next incoming message */
245
+ const awaitNextMessage = async sendMsg => {
246
+ if (!ws.isOpen) {
247
+ throw new Boom('Connection Closed', {
248
+ statusCode: DisconnectReason.connectionClosed
249
+ });
250
+ }
251
+ let onOpen;
252
+ let onClose;
253
+ const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
254
+ onOpen = resolve;
255
+ onClose = mapWebSocketError(reject);
256
+ ws.on('frame', onOpen);
257
+ ws.on('close', onClose);
258
+ ws.on('error', onClose);
259
+ }).finally(() => {
260
+ ws.off('frame', onOpen);
261
+ ws.off('close', onClose);
262
+ ws.off('error', onClose);
500
263
  });
501
- /** logout & invalidate connection */
502
- const logout = async (msg) => {
503
- const jid = authState.creds.me?.id;
504
- if (jid) {
505
- await sendNode({
506
- tag: 'iq',
507
- attrs: {
508
- to: S_WHATSAPP_NET,
509
- type: 'set',
510
- id: generateMessageTag(),
511
- xmlns: 'md'
512
- },
513
- content: [
514
- {
515
- tag: 'remove-companion-device',
516
- attrs: {
517
- jid,
518
- reason: 'user_initiated'
519
- }
520
- }
521
- ]
522
- });
523
- }
524
- end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
264
+ if (sendMsg) {
265
+ sendRawMessage(sendMsg).catch(onClose);
266
+ }
267
+ return result;
268
+ };
269
+ /** connection handshake */
270
+ const validateConnection = async () => {
271
+ let helloMsg = {
272
+ clientHello: {
273
+ ephemeral: ephemeralKeyPair.public
274
+ }
525
275
  };
526
- const requestPairingCode = async (phoneNumber, customPairingCode) => {
527
- const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
528
- if (customPairingCode && customPairingCode?.length !== 8) {
529
- throw new Error('Custom pairing code must be exactly 8 chars');
530
- }
531
- authState.creds.pairingCode = pairingCode;
532
- authState.creds.me = {
533
- id: jidEncode(phoneNumber, 's.whatsapp.net'),
534
- name: '~'
535
- };
536
- ev.emit('creds.update', authState.creds);
537
- await sendNode({
538
- tag: 'iq',
539
- attrs: {
540
- to: S_WHATSAPP_NET,
541
- type: 'set',
542
- id: generateMessageTag(),
543
- xmlns: 'md'
544
- },
545
- content: [
546
- {
547
- tag: 'link_code_companion_reg',
548
- attrs: {
549
- jid: authState.creds.me.id,
550
- stage: 'companion_hello',
551
- should_show_push_notification: 'true'
552
- },
553
- content: [
554
- {
555
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
556
- attrs: {},
557
- content: await generatePairingKey()
558
- },
559
- {
560
- tag: 'companion_server_auth_key_pub',
561
- attrs: {},
562
- content: authState.creds.noiseKey.public
563
- },
564
- {
565
- tag: 'companion_platform_id',
566
- attrs: {},
567
- content: getPlatformId(browser[1])
568
- },
569
- {
570
- tag: 'companion_platform_display',
571
- attrs: {},
572
- content: `${browser[1]} (${browser[0]})`
573
- },
574
- {
575
- tag: 'link_code_pairing_nonce',
576
- attrs: {},
577
- content: '0'
578
- }
579
- ]
580
- }
581
- ]
582
- });
583
- return authState.creds.pairingCode;
276
+ helloMsg = proto.HandshakeMessage.create(helloMsg);
277
+ logger.info({
278
+ browser,
279
+ helloMsg
280
+ }, 'connected to WA');
281
+ const init = proto.HandshakeMessage.encode(helloMsg).finish();
282
+ const result = await awaitNextMessage(init);
283
+ const handshake = proto.HandshakeMessage.decode(result);
284
+ logger.trace({
285
+ handshake
286
+ }, 'handshake recv from WA');
287
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
288
+ let node;
289
+ if (!creds.me) {
290
+ node = generateRegistrationNode(creds, config);
291
+ logger.info({
292
+ node
293
+ }, 'not logged in, attempting registration...');
294
+ } else {
295
+ node = generateLoginNode(creds.me.id, config);
296
+ logger.info({
297
+ node
298
+ }, 'logging in...');
299
+ }
300
+ const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
301
+ await sendRawMessage(proto.HandshakeMessage.encode({
302
+ clientFinish: {
303
+ static: keyEnc,
304
+ payload: payloadEnc
305
+ }
306
+ }).finish());
307
+ noise.finishInit();
308
+ startKeepAliveRequest();
309
+ };
310
+ const getAvailablePreKeysOnServer = async () => {
311
+ const result = await query({
312
+ tag: 'iq',
313
+ attrs: {
314
+ id: generateMessageTag(),
315
+ xmlns: 'encrypt',
316
+ type: 'get',
317
+ to: S_WHATSAPP_NET
318
+ },
319
+ content: [{
320
+ tag: 'count',
321
+ attrs: {}
322
+ }]
323
+ });
324
+ const countChild = getBinaryNodeChild(result, 'count');
325
+ return +countChild.attrs.value;
326
+ };
327
+ // Pre-key upload state management
328
+ let uploadPreKeysPromise = null;
329
+ let lastUploadTime = 0;
330
+ /** generates and uploads a set of pre-keys to the server */
331
+ const uploadPreKeys = async (count = INITIAL_PREKEY_COUNT, retryCount = 0) => {
332
+ // Check minimum interval (except for retries)
333
+ if (retryCount === 0) {
334
+ const timeSinceLastUpload = Date.now() - lastUploadTime;
335
+ if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
336
+ logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
337
+ return;
338
+ }
339
+ }
340
+ // Prevent multiple concurrent uploads
341
+ if (uploadPreKeysPromise) {
342
+ logger.debug('Pre-key upload already in progress, waiting for completion');
343
+ return uploadPreKeysPromise;
344
+ }
345
+ const uploadLogic = async () => {
346
+ logger.info({
347
+ count,
348
+ retryCount
349
+ }, 'uploading pre-keys');
350
+ // Generate and save pre-keys atomically (prevents ID collisions on retry)
351
+ const node = await keys.transaction(async () => {
352
+ logger.debug({
353
+ requestedCount: count
354
+ }, 'generating pre-keys with requested count');
355
+ const {
356
+ update,
357
+ node
358
+ } = await getNextPreKeysNode({
359
+ creds,
360
+ keys
361
+ }, count);
362
+ // Update credentials immediately to prevent duplicate IDs on retry
363
+ ev.emit('creds.update', update);
364
+ return node; // Only return node since update is already used
365
+ }, creds?.me?.id || 'upload-pre-keys');
366
+ // Upload to server (outside transaction, can fail without affecting local keys)
367
+ try {
368
+ await query(node);
369
+ logger.info({
370
+ count
371
+ }, 'uploaded pre-keys successfully');
372
+ lastUploadTime = Date.now();
373
+ } catch (uploadError) {
374
+ logger.error({
375
+ uploadError,
376
+ count
377
+ }, 'Failed to upload pre-keys to server');
378
+ // Exponential backoff retry (max 3 retries)
379
+ if (retryCount < 3) {
380
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
381
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
382
+ await new Promise(resolve => setTimeout(resolve, backoffDelay));
383
+ return uploadPreKeys(count, retryCount + 1);
384
+ }
385
+ throw uploadError;
386
+ }
584
387
  };
585
- async function generatePairingKey() {
586
- const salt = randomBytes(32);
587
- const randomIv = randomBytes(16);
588
- const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
589
- const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
590
- return Buffer.concat([salt, randomIv, ciphered]);
591
- }
592
- const sendWAMBuffer = (wamBuffer) => {
593
- return query({
594
- tag: 'iq',
595
- attrs: {
596
- to: S_WHATSAPP_NET,
597
- id: generateMessageTag(),
598
- xmlns: 'w:stats'
599
- },
600
- content: [
601
- {
602
- tag: 'add',
603
- attrs: {},
604
- content: wamBuffer
605
- }
606
- ]
607
- });
388
+ // Add timeout protection
389
+ uploadPreKeysPromise = Promise.race([uploadLogic(), new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', {
390
+ statusCode: 408
391
+ })), UPLOAD_TIMEOUT))]);
392
+ try {
393
+ await uploadPreKeysPromise;
394
+ } finally {
395
+ uploadPreKeysPromise = null;
396
+ }
397
+ };
398
+ const verifyCurrentPreKeyExists = async () => {
399
+ const currentPreKeyId = creds.nextPreKeyId - 1;
400
+ if (currentPreKeyId <= 0) {
401
+ return {
402
+ exists: false,
403
+ currentPreKeyId: 0
404
+ };
405
+ }
406
+ const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
407
+ const exists = !!preKeys[currentPreKeyId.toString()];
408
+ return {
409
+ exists,
410
+ currentPreKeyId
608
411
  };
609
- ws.on('message', onMessageReceived);
610
- ws.on('open', async () => {
611
- try {
612
- await validateConnection();
613
- }
614
- catch (err) {
615
- logger.error({ err }, 'error in validating connection');
616
- end(err);
617
- }
618
- });
619
- ws.on('error', mapWebSocketError(end));
620
- ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
621
- // the server terminated the connection
622
- ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
623
- // QR gen
624
- ws.on('CB:iq,type:set,pair-device', async (stanza) => {
625
- const iq = {
626
- tag: 'iq',
627
- attrs: {
628
- to: S_WHATSAPP_NET,
629
- type: 'result',
630
- id: stanza.attrs.id
631
- }
632
- };
633
- await sendNode(iq);
634
- const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
635
- const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
636
- const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
637
- const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
638
- const advB64 = creds.advSecretKey;
639
- let qrMs = qrTimeout || 60000; // time to let a QR live
640
- const genPairQR = () => {
641
- if (!ws.isOpen) {
642
- return;
643
- }
644
- const refNode = refNodes.shift();
645
- if (!refNode) {
646
- end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
647
- return;
648
- }
649
- const ref = refNode.content.toString('utf-8');
650
- const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
651
- ev.emit('connection.update', { qr });
652
- qrTimer = setTimeout(genPairQR, qrMs);
653
- qrMs = qrTimeout || 20000; // shorter subsequent qrs
654
- };
655
- genPairQR();
412
+ };
413
+ const uploadPreKeysToServerIfRequired = async () => {
414
+ try {
415
+ const preKeyCount = await getAvailablePreKeysOnServer();
416
+ const {
417
+ exists: currentPreKeyExists,
418
+ currentPreKeyId
419
+ } = await verifyCurrentPreKeyExists();
420
+ logger.info(`${preKeyCount} pre-keys found on server`);
421
+ logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
422
+ const lowServerCount = preKeyCount <= MIN_PREKEY_COUNT;
423
+ const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
424
+ const shouldUpload = lowServerCount || missingCurrentPreKey;
425
+ if (shouldUpload) {
426
+ const reasons = [];
427
+ if (lowServerCount) reasons.push(`server count low (${preKeyCount})`);
428
+ if (missingCurrentPreKey) reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
429
+ logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
430
+ await uploadPreKeys();
431
+ } else {
432
+ logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
433
+ }
434
+ } catch (error) {
435
+ logger.error({
436
+ error
437
+ }, 'Failed to check/upload pre-keys during initialization');
438
+ // Don't throw - allow connection to continue even if pre-key check fails
439
+ }
440
+ };
441
+ const onMessageReceived = data => {
442
+ noise.decodeFrame(data, frame => {
443
+ // reset ping timeout
444
+ lastDateRecv = new Date();
445
+ let anyTriggered = false;
446
+ anyTriggered = ws.emit('frame', frame);
447
+ // if it's a binary node
448
+ if (!(frame instanceof Uint8Array)) {
449
+ const msgId = frame.attrs.id;
450
+ if (logger.level === 'trace') {
451
+ logger.trace({
452
+ xml: binaryNodeToString(frame),
453
+ msg: 'recv xml'
454
+ });
455
+ }
456
+ /* Check if this is a response to a message we sent */
457
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
458
+ /* Check if this is a response to a message we are expecting */
459
+ const l0 = frame.tag;
460
+ const l1 = frame.attrs || {};
461
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
462
+ for (const key of Object.keys(l1)) {
463
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
464
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
465
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
466
+ }
467
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
468
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
469
+ if (!anyTriggered && logger.level === 'debug') {
470
+ logger.debug({
471
+ unhandled: true,
472
+ msgId,
473
+ fromMe: false,
474
+ frame
475
+ }, 'communication recv');
476
+ }
477
+ }
656
478
  });
657
- // device paired for the first time
658
- // if device pairs successfully, the server asks to restart the connection
659
- ws.on('CB:iq,,pair-success', async (stanza) => {
660
- logger.debug('pair success recv');
661
- try {
662
- const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
663
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
664
- ev.emit('creds.update', updatedCreds);
665
- ev.emit('connection.update', { isNewLogin: true, qr: undefined });
666
- await sendNode(reply);
667
- }
668
- catch (error) {
669
- logger.info({ trace: error.stack }, 'error in pairing');
670
- end(error);
671
- }
479
+ };
480
+ const end = error => {
481
+ if (closed) {
482
+ logger.trace({
483
+ trace: error?.stack
484
+ }, 'connection already closed');
485
+ return;
486
+ }
487
+ closed = true;
488
+ logger.info({
489
+ trace: error?.stack
490
+ }, error ? 'connection errored' : 'connection closed');
491
+ clearInterval(keepAliveReq);
492
+ clearTimeout(qrTimer);
493
+ ws.removeAllListeners('close');
494
+ ws.removeAllListeners('open');
495
+ ws.removeAllListeners('message');
496
+ if (!ws.isClosed && !ws.isClosing) {
497
+ try {
498
+ ws.close();
499
+ } catch {}
500
+ }
501
+ ev.emit('connection.update', {
502
+ connection: 'close',
503
+ lastDisconnect: {
504
+ error,
505
+ date: new Date()
506
+ }
672
507
  });
673
- // login complete
674
- ws.on('CB:success', async (node) => {
675
- try {
676
- await uploadPreKeysToServerIfRequired();
677
- await sendPassiveIq('active');
678
- }
679
- catch (err) {
680
- logger.warn({ err }, 'failed to send initial passive iq');
681
- }
682
- logger.info('opened connection to WA');
683
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
684
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
685
- ev.emit('connection.update', { connection: 'open' });
686
- if (node.attrs.lid && authState.creds.me?.id) {
687
- const myLID = node.attrs.lid;
688
- process.nextTick(async () => {
689
- try {
690
- const myPN = authState.creds.me.id;
691
- // Store our own LID-PN mapping
692
- await signalRepository.storeLIDPNMapping(myLID, myPN);
693
- // Create LID session for ourselves (whatsmeow pattern)
694
- await signalRepository.migrateSession(myPN, myLID);
695
- logger.info({ myPN, myLID }, 'Own LID session created successfully');
696
- }
697
- catch (error) {
698
- logger.error({ error, lid: myLID }, 'Failed to create own LID session');
699
- }
700
- });
701
- }
508
+ ev.removeAllListeners('connection.update');
509
+ };
510
+ const waitForSocketOpen = async () => {
511
+ if (ws.isOpen) {
512
+ return;
513
+ }
514
+ if (ws.isClosed || ws.isClosing) {
515
+ throw new Boom('Connection Closed', {
516
+ statusCode: DisconnectReason.connectionClosed
517
+ });
518
+ }
519
+ let onOpen;
520
+ let onClose;
521
+ await new Promise((resolve, reject) => {
522
+ onOpen = () => resolve(undefined);
523
+ onClose = mapWebSocketError(reject);
524
+ ws.on('open', onOpen);
525
+ ws.on('close', onClose);
526
+ ws.on('error', onClose);
527
+ }).finally(() => {
528
+ ws.off('open', onOpen);
529
+ ws.off('close', onClose);
530
+ ws.off('error', onClose);
702
531
  });
703
- ws.on('CB:stream:error', (node) => {
704
- logger.error({ node }, 'stream errored out');
705
- const { reason, statusCode } = getErrorCodeFromStreamError(node);
706
- end(new Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
532
+ };
533
+ const startKeepAliveRequest = () => keepAliveReq = setInterval(() => {
534
+ if (!lastDateRecv) {
535
+ lastDateRecv = new Date();
536
+ }
537
+ const diff = Date.now() - lastDateRecv.getTime();
538
+ /*
539
+ check if it's been a suspicious amount of time since the server responded with our last seen
540
+ it could be that the network is down
541
+ */
542
+ if (diff > keepAliveIntervalMs + 5000) {
543
+ end(new Boom('Connection was lost', {
544
+ statusCode: DisconnectReason.connectionLost
545
+ }));
546
+ } else if (ws.isOpen) {
547
+ // if its all good, send a keep alive request
548
+ query({
549
+ tag: 'iq',
550
+ attrs: {
551
+ id: generateMessageTag(),
552
+ to: S_WHATSAPP_NET,
553
+ type: 'get',
554
+ xmlns: 'w:p'
555
+ },
556
+ content: [{
557
+ tag: 'ping',
558
+ attrs: {}
559
+ }]
560
+ }).catch(err => {
561
+ logger.error({
562
+ trace: err.stack
563
+ }, 'error in sending keep alive');
564
+ });
565
+ } else {
566
+ logger.warn('keep alive called when WS not open');
567
+ }
568
+ }, keepAliveIntervalMs);
569
+ /** i have no idea why this exists. pls enlighten me */
570
+ const sendPassiveIq = tag => query({
571
+ tag: 'iq',
572
+ attrs: {
573
+ to: S_WHATSAPP_NET,
574
+ xmlns: 'passive',
575
+ type: 'set'
576
+ },
577
+ content: [{
578
+ tag,
579
+ attrs: {}
580
+ }]
581
+ });
582
+ /** logout & invalidate connection */
583
+ const logout = async msg => {
584
+ const jid = authState.creds.me?.id;
585
+ if (jid) {
586
+ await sendNode({
587
+ tag: 'iq',
588
+ attrs: {
589
+ to: S_WHATSAPP_NET,
590
+ type: 'set',
591
+ id: generateMessageTag(),
592
+ xmlns: 'md'
593
+ },
594
+ content: [{
595
+ tag: 'remove-companion-device',
596
+ attrs: {
597
+ jid,
598
+ reason: 'user_initiated'
599
+ }
600
+ }]
601
+ });
602
+ }
603
+ end(new Boom(msg || 'Intentional Logout', {
604
+ statusCode: DisconnectReason.loggedOut
605
+ }));
606
+ };
607
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
608
+ const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
609
+ if (customPairingCode && customPairingCode?.length !== 8) {
610
+ throw new Error('Custom pairing code must be exactly 8 chars');
611
+ }
612
+ authState.creds.pairingCode = pairingCode;
613
+ authState.creds.me = {
614
+ id: jidEncode(phoneNumber, 's.whatsapp.net'),
615
+ name: '~'
616
+ };
617
+ ev.emit('creds.update', authState.creds);
618
+ await sendNode({
619
+ tag: 'iq',
620
+ attrs: {
621
+ to: S_WHATSAPP_NET,
622
+ type: 'set',
623
+ id: generateMessageTag(),
624
+ xmlns: 'md'
625
+ },
626
+ content: [{
627
+ tag: 'link_code_companion_reg',
628
+ attrs: {
629
+ jid: authState.creds.me.id,
630
+ stage: 'companion_hello',
631
+ should_show_push_notification: 'true'
632
+ },
633
+ content: [{
634
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
635
+ attrs: {},
636
+ content: await generatePairingKey()
637
+ }, {
638
+ tag: 'companion_server_auth_key_pub',
639
+ attrs: {},
640
+ content: authState.creds.noiseKey.public
641
+ }, {
642
+ tag: 'companion_platform_id',
643
+ attrs: {},
644
+ content: getPlatformId(browser[1])
645
+ }, {
646
+ tag: 'companion_platform_display',
647
+ attrs: {},
648
+ content: `${browser[1]} (${browser[0]})`
649
+ }, {
650
+ tag: 'link_code_pairing_nonce',
651
+ attrs: {},
652
+ content: '0'
653
+ }]
654
+ }]
707
655
  });
708
- // stream fail, possible logout
709
- ws.on('CB:failure', (node) => {
710
- const reason = +(node.attrs.reason || 500);
711
- end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
656
+ return authState.creds.pairingCode;
657
+ };
658
+ async function generatePairingKey() {
659
+ const salt = randomBytes(32);
660
+ const randomIv = randomBytes(16);
661
+ const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
662
+ const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
663
+ return Buffer.concat([salt, randomIv, ciphered]);
664
+ }
665
+ const sendWAMBuffer = wamBuffer => {
666
+ return query({
667
+ tag: 'iq',
668
+ attrs: {
669
+ to: S_WHATSAPP_NET,
670
+ id: generateMessageTag(),
671
+ xmlns: 'w:stats'
672
+ },
673
+ content: [{
674
+ tag: 'add',
675
+ attrs: {},
676
+ content: wamBuffer
677
+ }]
712
678
  });
713
- ws.on('CB:ib,,downgrade_webclient', () => {
714
- end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
679
+ };
680
+ ws.on('message', onMessageReceived);
681
+ ws.on('open', async () => {
682
+ try {
683
+ await validateConnection();
684
+ } catch (err) {
685
+ logger.error({
686
+ err
687
+ }, 'error in validating connection');
688
+ end(err);
689
+ }
690
+ });
691
+ ws.on('error', mapWebSocketError(end));
692
+ ws.on('close', () => end(new Boom('Connection Terminated', {
693
+ statusCode: DisconnectReason.connectionClosed
694
+ })));
695
+ // the server terminated the connection
696
+ ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', {
697
+ statusCode: DisconnectReason.connectionClosed
698
+ })));
699
+ // QR gen
700
+ ws.on('CB:iq,type:set,pair-device', async stanza => {
701
+ const iq = {
702
+ tag: 'iq',
703
+ attrs: {
704
+ to: S_WHATSAPP_NET,
705
+ type: 'result',
706
+ id: stanza.attrs.id
707
+ }
708
+ };
709
+ await sendNode(iq);
710
+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
711
+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
712
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
713
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
714
+ const advB64 = creds.advSecretKey;
715
+ let qrMs = qrTimeout || 60000; // time to let a QR live
716
+ const genPairQR = () => {
717
+ if (!ws.isOpen) {
718
+ return;
719
+ }
720
+ const refNode = refNodes.shift();
721
+ if (!refNode) {
722
+ end(new Boom('QR refs attempts ended', {
723
+ statusCode: DisconnectReason.timedOut
724
+ }));
725
+ return;
726
+ }
727
+ const ref = refNode.content.toString('utf-8');
728
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
729
+ ev.emit('connection.update', {
730
+ qr
731
+ });
732
+ qrTimer = setTimeout(genPairQR, qrMs);
733
+ qrMs = qrTimeout || 20000; // shorter subsequent qrs
734
+ };
735
+ genPairQR();
736
+ });
737
+ // device paired for the first time
738
+ // if device pairs successfully, the server asks to restart the connection
739
+ ws.on('CB:iq,,pair-success', async stanza => {
740
+ logger.debug('pair success recv');
741
+ try {
742
+ const {
743
+ reply,
744
+ creds: updatedCreds
745
+ } = configureSuccessfulPairing(stanza, creds);
746
+ logger.info({
747
+ me: updatedCreds.me,
748
+ platform: updatedCreds.platform
749
+ }, 'pairing configured successfully, expect to restart the connection...');
750
+ ev.emit('creds.update', updatedCreds);
751
+ ev.emit('connection.update', {
752
+ isNewLogin: true,
753
+ qr: undefined
754
+ });
755
+ await sendNode(reply);
756
+ } catch (error) {
757
+ logger.info({
758
+ trace: error.stack
759
+ }, 'error in pairing');
760
+ end(error);
761
+ }
762
+ });
763
+ // login complete
764
+ ws.on('CB:success', async node => {
765
+ try {
766
+ await uploadPreKeysToServerIfRequired();
767
+ await sendPassiveIq('active');
768
+ } catch (err) {
769
+ logger.warn({
770
+ err
771
+ }, 'failed to send initial passive iq');
772
+ }
773
+ logger.info('opened connection to WA');
774
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
775
+ ev.emit('creds.update', {
776
+ me: {
777
+ ...authState.creds.me,
778
+ lid: node.attrs.lid
779
+ }
715
780
  });
716
- ws.on('CB:ib,,offline_preview', (node) => {
717
- logger.info('offline preview received', JSON.stringify(node));
718
- sendNode({
719
- tag: 'ib',
720
- attrs: {},
721
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
722
- });
781
+ ev.emit('connection.update', {
782
+ connection: 'open'
723
783
  });
724
- ws.on('CB:ib,,edge_routing', (node) => {
725
- const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
726
- const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
727
- if (routingInfo?.content) {
728
- authState.creds.routingInfo = Buffer.from(routingInfo?.content);
729
- ev.emit('creds.update', authState.creds);
784
+ if (node.attrs.lid && authState.creds.me?.id) {
785
+ const myLID = node.attrs.lid;
786
+ process.nextTick(async () => {
787
+ try {
788
+ const myPN = authState.creds.me.id;
789
+ // Store our own LID-PN mapping
790
+ await signalRepository.storeLIDPNMapping(myLID, myPN);
791
+ // Create LID session for ourselves (whatsmeow pattern)
792
+ await signalRepository.migrateSession(myPN, myLID);
793
+ logger.info({
794
+ myPN,
795
+ myLID
796
+ }, 'Own LID session created successfully');
797
+ } catch (error) {
798
+ logger.error({
799
+ error,
800
+ lid: myLID
801
+ }, 'Failed to create own LID session');
802
+ }
803
+ });
804
+ }
805
+ });
806
+ ws.on('CB:stream:error', node => {
807
+ logger.error({
808
+ node
809
+ }, 'stream errored out');
810
+ const {
811
+ reason,
812
+ statusCode
813
+ } = getErrorCodeFromStreamError(node);
814
+ end(new Boom(`Stream Errored (${reason})`, {
815
+ statusCode,
816
+ data: node
817
+ }));
818
+ });
819
+ // stream fail, possible logout
820
+ ws.on('CB:failure', node => {
821
+ const reason = +(node.attrs.reason || 500);
822
+ end(new Boom('Connection Failure', {
823
+ statusCode: reason,
824
+ data: node.attrs
825
+ }));
826
+ });
827
+ ws.on('CB:ib,,downgrade_webclient', () => {
828
+ end(new Boom('Multi-device beta not joined', {
829
+ statusCode: DisconnectReason.multideviceMismatch
830
+ }));
831
+ });
832
+ ws.on('CB:ib,,offline_preview', node => {
833
+ logger.info('offline preview received', JSON.stringify(node));
834
+ sendNode({
835
+ tag: 'ib',
836
+ attrs: {},
837
+ content: [{
838
+ tag: 'offline_batch',
839
+ attrs: {
840
+ count: '100'
730
841
  }
842
+ }]
731
843
  });
732
- let didStartBuffer = false;
733
- process.nextTick(() => {
734
- if (creds.me?.id) {
735
- // start buffering important events
736
- // if we're logged in
737
- ev.buffer();
738
- didStartBuffer = true;
739
- }
740
- ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
844
+ });
845
+ ws.on('CB:ib,,edge_routing', node => {
846
+ const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
847
+ const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
848
+ if (routingInfo?.content) {
849
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content);
850
+ ev.emit('creds.update', authState.creds);
851
+ }
852
+ });
853
+ let didStartBuffer = false;
854
+ process.nextTick(() => {
855
+ if (creds.me?.id) {
856
+ // start buffering important events
857
+ // if we're logged in
858
+ ev.buffer();
859
+ didStartBuffer = true;
860
+ }
861
+ ev.emit('connection.update', {
862
+ connection: 'connecting',
863
+ receivedPendingNotifications: false,
864
+ qr: undefined
741
865
  });
742
- // called when all offline notifs are handled
743
- ws.on('CB:ib,,offline', (node) => {
744
- const child = getBinaryNodeChild(node, 'offline');
745
- const offlineNotifs = +(child?.attrs.count || 0);
746
- logger.info(`handled ${offlineNotifs} offline messages/notifications`);
747
- if (didStartBuffer) {
748
- ev.flush();
749
- logger.trace('flushed events for initial buffer');
750
- }
751
- ev.emit('connection.update', { receivedPendingNotifications: true });
866
+ });
867
+ // called when all offline notifs are handled
868
+ ws.on('CB:ib,,offline', node => {
869
+ const child = getBinaryNodeChild(node, 'offline');
870
+ const offlineNotifs = +(child?.attrs.count || 0);
871
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
872
+ if (didStartBuffer) {
873
+ ev.flush();
874
+ logger.trace('flushed events for initial buffer');
875
+ }
876
+ ev.emit('connection.update', {
877
+ receivedPendingNotifications: true
752
878
  });
753
- // update credentials when required
754
- ev.on('creds.update', update => {
755
- const name = update.me?.name;
756
- // if name has just been received
757
- if (creds.me?.name !== name) {
758
- logger.debug({ name }, 'updated pushName');
759
- sendNode({
760
- tag: 'presence',
761
- attrs: { name: name }
762
- }).catch(err => {
763
- logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
764
- });
879
+ });
880
+ // update credentials when required
881
+ ev.on('creds.update', update => {
882
+ const name = update.me?.name;
883
+ // if name has just been received
884
+ if (creds.me?.name !== name) {
885
+ logger.debug({
886
+ name
887
+ }, 'updated pushName');
888
+ sendNode({
889
+ tag: 'presence',
890
+ attrs: {
891
+ name: name
765
892
  }
766
- Object.assign(creds, update);
767
- });
768
- return {
769
- type: 'md',
770
- ws,
771
- ev,
772
- authState: { creds, keys },
773
- signalRepository,
774
- get user() {
775
- return authState.creds.me;
776
- },
777
- generateMessageTag,
778
- query,
779
- waitForMessage,
780
- waitForSocketOpen,
781
- sendRawMessage,
782
- sendNode,
783
- logout,
784
- end,
785
- onUnexpectedError,
786
- uploadPreKeys,
787
- uploadPreKeysToServerIfRequired,
788
- requestPairingCode,
789
- /** Waits for the connection to WA to reach a state */
790
- waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
791
- sendWAMBuffer,
792
- executeUSyncQuery,
793
- onWhatsApp
794
- };
893
+ }).catch(err => {
894
+ logger.warn({
895
+ trace: err.stack
896
+ }, 'error in sending presence update on name change');
897
+ });
898
+ }
899
+ Object.assign(creds, update);
900
+ });
901
+ return {
902
+ type: 'md',
903
+ ws,
904
+ ev,
905
+ authState: {
906
+ creds,
907
+ keys
908
+ },
909
+ signalRepository,
910
+ get user() {
911
+ return authState.creds.me;
912
+ },
913
+ generateMessageTag,
914
+ query,
915
+ waitForMessage,
916
+ waitForSocketOpen,
917
+ sendRawMessage,
918
+ sendNode,
919
+ logout,
920
+ end,
921
+ onUnexpectedError,
922
+ uploadPreKeys,
923
+ uploadPreKeysToServerIfRequired,
924
+ requestPairingCode,
925
+ /** Waits for the connection to WA to reach a state */
926
+ waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
927
+ sendWAMBuffer,
928
+ executeUSyncQuery,
929
+ onWhatsApp
930
+ };
795
931
  };
796
932
  /**
797
933
  * map the websocket error to the right type
798
934
  * so it can be retried by the caller
799
935
  * */
800
936
  function mapWebSocketError(handler) {
801
- return (error) => {
802
- handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
803
- };
937
+ return error => {
938
+ handler(new Boom(`WebSocket Error (${error?.message})`, {
939
+ statusCode: getCodeFromWSError(error),
940
+ data: error
941
+ }));
942
+ };
804
943
  }
805
944
  //# sourceMappingURL=socket.js.map