@badzz88/baileys 8.4.7 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/index.js +5 -5
  4. package/lib/Defaults/index.js +187 -127
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +14 -11
  7. package/lib/Signal/Group/group-session-builder.js +91 -29
  8. package/lib/Signal/Group/group_cipher.js +88 -81
  9. package/lib/Signal/Group/index.js +136 -12
  10. package/lib/Signal/Group/keyhelper.js +70 -15
  11. package/lib/Signal/Group/sender-chain-key.js +31 -25
  12. package/lib/Signal/Group/sender-key-distribution-message.js +65 -62
  13. package/lib/Signal/Group/sender-key-message.js +68 -65
  14. package/lib/Signal/Group/sender-key-name.js +43 -41
  15. package/lib/Signal/Group/sender-key-record.js +43 -40
  16. package/lib/Signal/Group/sender-key-state.js +96 -83
  17. package/lib/Signal/Group/sender-message-key.js +29 -25
  18. package/lib/Signal/libsignal.js +483 -424
  19. package/lib/Signal/lid-mapping.js +261 -276
  20. package/lib/Socket/Client/index.js +30 -3
  21. package/lib/Socket/Client/types.js +12 -10
  22. package/lib/Socket/Client/websocket.js +61 -53
  23. package/lib/Socket/aigroups.js +240 -0
  24. package/lib/Socket/business.js +422 -379
  25. package/lib/Socket/chats.js +1816 -1193
  26. package/lib/Socket/communities.js +549 -431
  27. package/lib/Socket/graphql.js +656 -0
  28. package/lib/Socket/groups.js +764 -374
  29. package/lib/Socket/index.js +38 -11
  30. package/lib/Socket/interactive-handler.js +522 -0
  31. package/lib/Socket/interop.js +549 -0
  32. package/lib/Socket/luxu.js +6 -5
  33. package/lib/Socket/managed-account.js +183 -0
  34. package/lib/Socket/messages-recv.js +2439 -1915
  35. package/lib/Socket/messages-send.js +1642 -1242
  36. package/lib/Socket/mex.js +59 -40
  37. package/lib/Socket/newsletter.js +812 -249
  38. package/lib/Socket/privacy.js +449 -0
  39. package/lib/Socket/registration.js +427 -0
  40. package/lib/Socket/socket.js +1077 -965
  41. package/lib/Socket/text-router.js +83 -0
  42. package/lib/Socket/username.js +237 -140
  43. package/lib/Store/index.js +36 -10
  44. package/lib/Store/make-cache-manager-store.js +85 -80
  45. package/lib/Store/make-in-memory-store.js +591 -185
  46. package/lib/Store/make-ordered-dictionary.js +78 -72
  47. package/lib/Store/object-repository.js +25 -28
  48. package/lib/Types/Auth.js +38 -2
  49. package/lib/Types/Bussines.js +2 -2
  50. package/lib/Types/Call.js +2 -2
  51. package/lib/Types/Chat.js +4 -8
  52. package/lib/Types/Contact.js +2 -2
  53. package/lib/Types/Events.js +2 -2
  54. package/lib/Types/GroupMetadata.js +2 -2
  55. package/lib/Types/Label.js +26 -24
  56. package/lib/Types/LabelAssociation.js +8 -6
  57. package/lib/Types/Message.js +95 -11
  58. package/lib/Types/Mex.js +112 -37
  59. package/lib/Types/Newsletter.js +121 -0
  60. package/lib/Types/Product.js +2 -2
  61. package/lib/Types/Signal.js +2 -2
  62. package/lib/Types/Socket.js +2 -3
  63. package/lib/Types/State.js +70 -56
  64. package/lib/Types/USync.js +2 -2
  65. package/lib/Types/index.js +55 -26
  66. package/lib/Utils/auth-utils.js +292 -288
  67. package/lib/Utils/browser-utils.js +113 -48
  68. package/lib/Utils/business.js +240 -224
  69. package/lib/Utils/chat-utils.js +1205 -869
  70. package/lib/Utils/command-loader.d.ts +31 -0
  71. package/lib/Utils/command-loader.js +100 -0
  72. package/lib/Utils/companion-reg-client-utils.js +41 -34
  73. package/lib/Utils/consumer-application.js +107 -0
  74. package/lib/Utils/crypto.js +144 -107
  75. package/lib/Utils/curve25519-js.js +275 -0
  76. package/lib/Utils/decode-wa-message.js +518 -308
  77. package/lib/Utils/event-buffer.js +596 -611
  78. package/lib/Utils/generics.js +514 -354
  79. package/lib/Utils/group-history.js +60 -0
  80. package/lib/Utils/history.js +244 -134
  81. package/lib/Utils/identity-change-handler.js +51 -49
  82. package/lib/Utils/index.js +57 -23
  83. package/lib/Utils/jid-display-normalization.js +218 -0
  84. package/lib/Utils/link-preview.js +135 -77
  85. package/lib/Utils/logger.js +9 -3
  86. package/lib/Utils/lt-hash.js +37 -6
  87. package/lib/Utils/make-mutex.js +36 -33
  88. package/lib/Utils/message-composer.js +439 -233
  89. package/lib/Utils/message-retry-manager.js +265 -260
  90. package/lib/Utils/messages-media.js +855 -747
  91. package/lib/Utils/messages.js +2528 -884
  92. package/lib/Utils/meta-ai-msmsg.js +262 -0
  93. package/lib/Utils/native-bridge.js +82 -0
  94. package/lib/Utils/noise-handler.js +195 -200
  95. package/lib/Utils/offline-node-processor.js +35 -33
  96. package/lib/Utils/pre-key-manager.js +103 -102
  97. package/lib/Utils/process-message.js +978 -560
  98. package/lib/Utils/reporting-utils.js +257 -253
  99. package/lib/Utils/session-pool.d.ts +16 -0
  100. package/lib/Utils/session-pool.js +94 -0
  101. package/lib/Utils/signal.js +218 -195
  102. package/lib/Utils/stanza-ack.js +31 -29
  103. package/lib/Utils/sticker.d.ts +17 -0
  104. package/lib/Utils/sticker.js +145 -0
  105. package/lib/Utils/sync-action-utils.js +50 -45
  106. package/lib/Utils/tc-token-utils.js +137 -139
  107. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  108. package/lib/Utils/validate-connection.js +218 -202
  109. package/lib/Utils/view-once-cache.d.ts +9 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +22 -0
  112. package/lib/WABinary/constants.js +1302 -1299
  113. package/lib/WABinary/decode.js +343 -262
  114. package/lib/WABinary/encode.js +12 -4
  115. package/lib/WABinary/generic-utils.js +223 -187
  116. package/lib/WABinary/index.js +33 -6
  117. package/lib/WABinary/jid-utils.js +351 -88
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.js +12 -9
  120. package/lib/WAM/constants.js +39486 -22853
  121. package/lib/WAM/encode.js +132 -140
  122. package/lib/WAM/index.js +31 -4
  123. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -51
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +56 -53
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -26
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  129. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  131. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -37
  133. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  134. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +26 -24
  135. package/lib/WAUSync/Protocols/index.js +39 -6
  136. package/lib/WAUSync/USyncQuery.js +132 -97
  137. package/lib/WAUSync/USyncUser.js +49 -30
  138. package/lib/WAUSync/index.js +31 -4
  139. package/lib/antiban.js +4637 -0
  140. package/lib/index.js +48 -15
  141. package/package.json +55 -92
  142. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  143. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  144. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
@@ -1,980 +1,1092 @@
1
- import { Boom } from '@hapi/boom';
2
- import { randomBytes } from 'crypto';
3
- import { URL } from 'url';
4
- import { promisify } from 'util';
5
- import { proto } from '../../WAProto/index.js';
6
- import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
7
- import { QueryIds, ReachoutTimelockEnforcementType } from '../Types/index.js';
8
- import { DisconnectReason, XWAPaths } from '../Types/index.js';
9
- import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, buildPairingQRData, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getCompanionPlatformId, getErrorCodeFromStreamError, getNextPreKeysNode, makeEventBuffer, makeNoiseHandler, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
10
- import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
11
- import { BinaryInfo } from '../WAM/BinaryInfo.js';
12
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
- import { WebSocketClient } from './Client/index.js';
14
- import { executeWMexQuery } from './mex.js';
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 index_js_1 = require('../../WAProto/index.js')
9
+ const Defaults_1 = require('../Defaults')
10
+ const Types_1 = require('../Types')
11
+ const Utils_1 = require('../Utils')
12
+ const browser_utils_1 = require('../Utils/browser-utils')
13
+ const WABinary_1 = require('../WABinary')
14
+ const BinaryInfo_js_1 = require('../WAM/BinaryInfo.js')
15
+ const WAUSync_1 = require('../WAUSync/')
16
+ const Client_1 = require('./Client')
17
+ const mex_1 = require('./mex')
15
18
  /**
16
19
  * Connects to WA servers and performs:
17
20
  * - simple queries (no retry mechanism, wait for connection establishment)
18
21
  * - listen to messages and emit events
19
22
  * - query phone connection
20
23
  */
21
- export const makeSocket = (config) => {
22
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
23
- const publicWAMBuffer = new BinaryInfo();
24
- let serverTimeOffsetMs = 0;
25
- const uqTagId = generateMdTagPrefix();
26
- const generateMessageTag = () => `XZCYYX-${epoch++}`;
27
- if (printQRInTerminal) {
28
- logger.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.');
29
- }
30
- const syncDisabled = PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false)
31
- .length === PROCESSABLE_HISTORY_TYPES.length;
32
- if (syncDisabled) {
33
- logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
34
- }
35
- const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
36
- if (config.mobile || url.protocol === 'tcp:') {
37
- throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
38
- }
39
- if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
40
- url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
41
- }
42
- /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
43
- const ephemeralKeyPair = Curve.generateKeyPair();
44
- /** WA noise protocol wrapper */
45
- const noise = makeNoiseHandler({
46
- keyPair: ephemeralKeyPair,
47
- NOISE_HEADER: NOISE_WA_HEADER,
48
- logger,
49
- routingInfo: authState?.creds?.routingInfo
50
- });
51
- const ws = new WebSocketClient(url, config);
52
- ws.connect();
53
- const sendPromise = promisify(ws.send);
54
- /** send a raw buffer */
55
- const sendRawMessage = async (data) => {
56
- if (!ws.isOpen) {
57
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
58
- }
59
- const bytes = noise.encodeFrame(data);
60
- await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
61
- try {
62
- await sendPromise.call(ws, bytes);
63
- resolve();
64
- }
65
- catch (error) {
66
- reject(error);
67
- }
68
- });
69
- };
70
- /** send a binary node */
71
- const sendNode = (frame) => {
72
- if (logger.level === 'trace') {
73
- logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
74
- }
75
- const buff = encodeBinaryNode(frame);
76
- return sendRawMessage(buff);
77
- };
78
- /**
79
- * Wait for a message with a certain tag to be received
80
- * @param msgId the message tag to await
81
- * @param timeoutMs timeout after which the promise will reject
82
- */
83
- const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
84
- let onRecv;
85
- let onErr;
86
- try {
87
- const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
88
- onRecv = data => {
89
- resolve(data);
90
- };
91
- onErr = err => {
92
- reject(err ||
93
- new Boom('Connection Closed', {
94
- statusCode: DisconnectReason.connectionClosed
95
- }));
96
- };
97
- ws.on(`TAG:${msgId}`, onRecv);
98
- ws.on('close', onErr);
99
- ws.on('error', onErr);
100
- return () => reject(new Boom('Query Cancelled'));
101
- });
102
- return result;
103
- }
104
- catch (error) {
105
- // Catch timeout and return undefined instead of throwing
106
- if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
107
- logger?.warn?.({ msgId }, 'timed out waiting for message');
108
- return undefined;
109
- }
110
- throw error;
111
- }
112
- finally {
113
- if (onRecv)
114
- ws.off(`TAG:${msgId}`, onRecv);
115
- if (onErr) {
116
- ws.off('close', onErr);
117
- ws.off('error', onErr);
118
- }
119
- }
120
- };
121
- /** send a query, and wait for its response. auto-generates message ID if not provided */
122
- const query = async (node, timeoutMs) => {
123
- if (!node.attrs.id) {
124
- node.attrs.id = generateMessageTag();
125
- }
126
- const msgId = node.attrs.id;
127
- const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
128
- const result = waitForMessage(msgId, timeoutMs).catch(reject);
129
- sendNode(node)
130
- .then(async () => resolve(await result))
131
- .catch(reject);
132
- });
133
- if (result && 'tag' in result) {
134
- assertNodeErrorFree(result);
135
- }
136
- return result;
137
- };
138
- // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
139
- const digestKeyBundle = async () => {
140
- const res = await query({
141
- tag: 'iq',
142
- attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
143
- content: [{ tag: 'digest', attrs: {} }]
144
- });
145
- const digestNode = getBinaryNodeChild(res, 'digest');
146
- if (!digestNode) {
147
- await uploadPreKeys();
148
- throw new Error('encrypt/get digest returned no digest node');
149
- }
150
- };
151
- // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
152
- const rotateSignedPreKey = async () => {
153
- const newId = (creds.signedPreKey.keyId || 0) + 1;
154
- const skey = await signedKeyPair(creds.signedIdentityKey, newId);
155
- await query({
156
- tag: 'iq',
157
- attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
158
- content: [
159
- {
160
- tag: 'rotate',
161
- attrs: {},
162
- content: [xmppSignedPreKey(skey)]
163
- }
164
- ]
165
- });
166
- // Persist new signed pre-key in creds
167
- ev.emit('creds.update', { signedPreKey: skey });
168
- };
169
- const executeUSyncQuery = async (usyncQuery) => {
170
- if (usyncQuery.protocols.length === 0) {
171
- throw new Boom('USyncQuery must have at least one protocol');
172
- }
173
- // todo: validate users, throw WARNING on no valid users
174
- // variable below has only validated users
175
- const validUsers = usyncQuery.users;
176
- const userNodes = validUsers.map(user => {
177
- return {
178
- tag: 'user',
179
- attrs: {
180
- jid: !user.phone ? user.id : undefined
181
- },
182
- content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
183
- };
184
- });
185
- const listNode = {
186
- tag: 'list',
187
- attrs: {},
188
- content: userNodes
189
- };
190
- const queryNode = {
191
- tag: 'query',
192
- attrs: {},
193
- content: usyncQuery.protocols.map(a => a.getQueryElement())
194
- };
195
- const iq = {
196
- tag: 'iq',
197
- attrs: {
198
- to: S_WHATSAPP_NET,
199
- type: 'get',
200
- xmlns: 'usync'
201
- },
202
- content: [
203
- {
204
- tag: 'usync',
205
- attrs: {
206
- context: usyncQuery.context,
207
- mode: usyncQuery.mode,
208
- sid: generateMessageTag(),
209
- last: 'true',
210
- index: '0'
211
- },
212
- content: [queryNode, listNode]
213
- }
214
- ]
215
- };
216
- const result = await query(iq);
217
- return usyncQuery.parseUSyncQueryResult(result);
218
- };
219
- const onWhatsApp = async (...phoneNumber) => {
220
- let usyncQuery = new USyncQuery()
221
- .withContactProtocol()
222
- .withLIDProtocol();
223
- let contactEnabled = false;
224
- for (const jid of phoneNumber) {
225
- if (isLidUser(jid)) {
226
- logger?.warn('LIDs are not supported with onWhatsApp');
227
- continue;
228
- }
229
- else {
230
- if (!contactEnabled) {
231
- contactEnabled = true;
232
- usyncQuery = usyncQuery.withContactProtocol();
233
- }
234
- const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
235
- usyncQuery.withUser(new USyncUser().withPhone(phone));
236
- }
237
- }
238
- if (usyncQuery.users.length === 0) {
239
- return []; // return early without forcing an empty query
240
- }
241
- const results = await executeUSyncQuery(usyncQuery);
242
- if (results) {
243
- return results.list.filter(a => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, lid, exists: contact }));
244
- }
245
- };
246
- const pnFromLIDUSync = async (jids) => {
247
- const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background');
248
- for (const jid of jids) {
249
- if (isLidUser(jid)) {
250
- logger?.warn('LID user found in LID fetch call');
251
- continue;
252
- }
253
- else {
254
- usyncQuery.withUser(new USyncUser().withId(jid));
255
- }
256
- }
257
- if (usyncQuery.users.length === 0) {
258
- return []; // return early without forcing an empty query
259
- }
260
- const results = await executeUSyncQuery(usyncQuery);
261
- if (results) {
262
- return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
263
- }
264
- return [];
265
- };
266
- const toPn = async (jid) => {
267
- const results = await pnFromLIDUSync([jid]);
268
- return results?.[0]?.pn ?? null;
269
- }
270
- const toLid = async (jid) => {
271
- const results = await onWhatsApp(jid);
272
- return results?.[0]?.lid ?? null;
273
- }
274
- const ev = makeEventBuffer(logger);
275
- const { creds } = authState;
276
- // add transaction capability
277
- const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
278
- const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
279
- let lastDateRecv;
280
- let epoch = 1;
281
- let keepAliveReq;
282
- let qrTimer;
283
- let closed = false;
284
- const socketEndHandlers = [];
285
- /** log & process any unexpected errors */
286
- const onUnexpectedError = (err, msg) => {
287
- logger.error({ err }, `unexpected error in '${msg}'`);
288
- };
289
- /** await the next incoming message */
290
- const awaitNextMessage = async (sendMsg) => {
291
- if (!ws.isOpen) {
292
- throw new Boom('Connection Closed', {
293
- statusCode: DisconnectReason.connectionClosed
294
- });
295
- }
296
- let onOpen;
297
- let onClose;
298
- const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
299
- onOpen = resolve;
300
- onClose = mapWebSocketError(reject);
301
- ws.on('frame', onOpen);
302
- ws.on('close', onClose);
303
- ws.on('error', onClose);
304
- }).finally(() => {
305
- ws.off('frame', onOpen);
306
- ws.off('close', onClose);
307
- ws.off('error', onClose);
308
- });
309
- if (sendMsg) {
310
- sendRawMessage(sendMsg).catch(onClose);
311
- }
312
- return result;
313
- };
314
- /** connection handshake */
315
- const validateConnection = async () => {
316
- let helloMsg = {
317
- clientHello: { ephemeral: ephemeralKeyPair.public }
318
- };
319
- helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
320
- logger.info({ browser, helloMsg }, 'connected to WA');
321
- const init = proto.HandshakeMessage.encode(helloMsg).finish();
322
- const result = await awaitNextMessage(init);
323
- const handshake = proto.HandshakeMessage.decode(result);
324
- logger.trace({ handshake }, 'handshake recv from WA');
325
- const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
326
- let node;
327
- if (!creds.me) {
328
- node = generateRegistrationNode(creds, config);
329
- logger.info({ node }, 'not logged in, attempting registration...');
330
- }
331
- else {
332
- node = generateLoginNode(creds.me.id, config);
333
- logger.info({ node }, 'logging in...');
334
- }
335
- const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
336
- await sendRawMessage(proto.HandshakeMessage.encode({
337
- clientFinish: {
338
- static: keyEnc,
339
- payload: payloadEnc
340
- }
341
- }).finish());
342
- await noise.finishInit();
343
- startKeepAliveRequest();
344
- };
345
- const getAvailablePreKeysOnServer = async () => {
346
- const result = await query({
347
- tag: 'iq',
348
- attrs: {
349
- id: generateMessageTag(),
350
- xmlns: 'encrypt',
351
- type: 'get',
352
- to: S_WHATSAPP_NET
353
- },
354
- content: [{ tag: 'count', attrs: {} }]
355
- });
356
- const countChild = getBinaryNodeChild(result, 'count');
357
- return +countChild.attrs.value;
358
- };
359
- // WAWeb has no time throttle here; the server drives uploads via PreKeyLow notifications.
360
- let uploadPreKeysPromise = null;
361
- /** generates and uploads a set of pre-keys to the server */
362
- const uploadPreKeys = async (count = MIN_PREKEY_COUNT) => {
363
- if (uploadPreKeysPromise) {
364
- logger.debug('Pre-key upload already in progress, waiting for completion');
365
- await uploadPreKeysPromise;
366
- return;
367
- }
368
- const uploadLogic = async (retryCount) => {
369
- logger.info({ count, retryCount }, 'uploading pre-keys');
370
- // Generate and save pre-keys atomically (prevents ID collisions on retry)
371
- const node = await keys.transaction(async () => {
372
- logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
373
- const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
374
- // Update credentials immediately to prevent duplicate IDs on retry
375
- ev.emit('creds.update', update);
376
- return node;
377
- }, creds?.me?.id || 'upload-pre-keys');
378
- // Upload to server (outside transaction, can fail without affecting local keys)
379
- try {
380
- await query(node);
381
- logger.info({ count }, 'uploaded pre-keys successfully');
382
- }
383
- catch (uploadError) {
384
- logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
385
- // Recurse into uploadLogic; calling uploadPreKeys would await its own in-flight promise.
386
- if (retryCount < 3) {
387
- const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
388
- logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
389
- await new Promise(resolve => setTimeout(resolve, backoffDelay));
390
- return uploadLogic(retryCount + 1);
391
- }
392
- throw uploadError;
393
- }
394
- };
395
- // Add timeout protection
396
- uploadPreKeysPromise = Promise.race([
397
- uploadLogic(0),
398
- new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
399
- ]);
400
- try {
401
- await uploadPreKeysPromise;
402
- }
403
- finally {
404
- uploadPreKeysPromise = null;
405
- }
406
- };
407
- const verifyCurrentPreKeyExists = async () => {
408
- const currentPreKeyId = creds.nextPreKeyId - 1;
409
- if (currentPreKeyId <= 0) {
410
- return { exists: false, currentPreKeyId: 0 };
411
- }
412
- const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
413
- const exists = !!preKeys[currentPreKeyId.toString()];
414
- return { exists, currentPreKeyId };
415
- };
416
- const uploadPreKeysToServerIfRequired = async () => {
417
- try {
418
- let count = 0;
419
- const preKeyCount = await getAvailablePreKeysOnServer();
420
- if (preKeyCount === 0)
421
- count = INITIAL_PREKEY_COUNT;
422
- else
423
- count = MIN_PREKEY_COUNT;
424
- const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
425
- logger.info(`${preKeyCount} pre-keys found on server`);
426
- logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
427
- const lowServerCount = preKeyCount <= count;
428
- const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
429
- const shouldUpload = lowServerCount || missingCurrentPreKey;
430
- if (shouldUpload) {
431
- const reasons = [];
432
- if (lowServerCount)
433
- reasons.push(`server count low (${preKeyCount})`);
434
- if (missingCurrentPreKey)
435
- reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
436
- logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
437
- await uploadPreKeys(count);
438
- }
439
- else {
440
- logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
441
- }
442
- }
443
- catch (error) {
444
- logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
445
- // Don't throw - allow connection to continue even if pre-key check fails
446
- }
447
- };
448
- const onMessageReceived = async (data) => {
449
- await noise.decodeFrame(data, frame => {
450
- // reset ping timeout
451
- lastDateRecv = new Date();
452
- let anyTriggered = false;
453
- anyTriggered = ws.emit('frame', frame);
454
- // if it's a binary node
455
- if (!(frame instanceof Uint8Array)) {
456
- const msgId = frame.attrs.id;
457
- if (logger.level === 'trace') {
458
- logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
459
- }
460
- /* Check if this is a response to a message we sent */
461
- anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
462
- /* Check if this is a response to a message we are expecting */
463
- const l0 = frame.tag;
464
- const l1 = frame.attrs || {};
465
- const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
466
- for (const key of Object.keys(l1)) {
467
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
468
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
469
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
470
- }
471
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
472
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
473
- if (!anyTriggered && logger.level === 'debug') {
474
- logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
475
- }
476
- }
477
- });
478
- };
479
- const end = async (error) => {
480
- if (closed) {
481
- logger.trace({ trace: error?.stack }, 'connection already closed');
482
- return;
483
- }
484
- closed = true;
485
- logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
486
- clearInterval(keepAliveReq);
487
- clearTimeout(qrTimer);
488
- ws.removeAllListeners('close');
489
- ws.removeAllListeners('open');
490
- ws.removeAllListeners('message');
491
- signalRepository.close?.();
492
- if (!ws.isClosed && !ws.isClosing) {
493
- try {
494
- await ws.close();
495
- }
496
- catch { }
497
- }
498
- for (const handler of socketEndHandlers) {
499
- try {
500
- await handler(error);
501
- }
502
- catch (err) {
503
- logger.error({ err }, 'error in socket end handler');
504
- }
505
- }
506
- ev.emit('connection.update', {
507
- connection: 'close',
508
- lastDisconnect: {
509
- error,
510
- date: new Date()
511
- }
512
- });
513
- ev.removeAllListeners('connection.update');
514
- ev.destroy();
515
- };
516
- const waitForSocketOpen = async () => {
517
- if (ws.isOpen) {
518
- return;
519
- }
520
- if (ws.isClosed || ws.isClosing) {
521
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
522
- }
523
- let onOpen;
524
- let onClose;
525
- await new Promise((resolve, reject) => {
526
- onOpen = () => resolve(undefined);
527
- onClose = mapWebSocketError(reject);
528
- ws.on('open', onOpen);
529
- ws.on('close', onClose);
530
- ws.on('error', onClose);
531
- }).finally(() => {
532
- ws.off('open', onOpen);
533
- ws.off('close', onClose);
534
- ws.off('error', onClose);
535
- });
536
- };
537
- const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
538
- if (!lastDateRecv) {
539
- lastDateRecv = new Date();
540
- }
541
- const diff = Date.now() - lastDateRecv.getTime();
542
- /*
24
+ const makeSocket = config => {
25
+ const {
26
+ waWebSocketUrl,
27
+ connectTimeoutMs,
28
+ logger,
29
+ keepAliveIntervalMs,
30
+ browser,
31
+ auth: authState,
32
+ printQRInTerminal,
33
+ defaultQueryTimeoutMs,
34
+ transactionOpts,
35
+ qrTimeout,
36
+ makeSignalRepository
37
+ } = config
38
+ const publicWAMBuffer = new BinaryInfo_js_1.BinaryInfo()
39
+ let serverTimeOffsetMs = 0
40
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)()
41
+ const generateMessageTag = () => `${uqTagId}${epoch++}`
42
+ if (printQRInTerminal) {
43
+ logger.warn(
44
+ {},
45
+ '⚠️ 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.'
46
+ )
47
+ }
48
+ const syncDisabled =
49
+ Defaults_1.PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(
50
+ x => x === false
51
+ ).length === Defaults_1.PROCESSABLE_HISTORY_TYPES.length
52
+ if (syncDisabled) {
53
+ logger.warn(
54
+ '⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS'
55
+ )
56
+ }
57
+ const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl
58
+ if (config.mobile || url.protocol === 'tcp:') {
59
+ throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut })
60
+ }
61
+ if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
62
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
63
+ }
64
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
65
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair()
66
+ /** WA noise protocol wrapper */
67
+ const noise = (0, Utils_1.makeNoiseHandler)({
68
+ keyPair: ephemeralKeyPair,
69
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
70
+ logger,
71
+ routingInfo: authState?.creds?.routingInfo
72
+ })
73
+ const ws = new Client_1.WebSocketClient(url, config)
74
+ ws.connect()
75
+ const sendPromise = (0, util_1.promisify)(ws.send)
76
+ /** send a raw buffer */
77
+ const sendRawMessage = async data => {
78
+ if (!ws.isOpen) {
79
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed })
80
+ }
81
+ const bytes = noise.encodeFrame(data)
82
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
83
+ try {
84
+ await sendPromise.call(ws, bytes)
85
+ resolve()
86
+ } catch (error) {
87
+ reject(error)
88
+ }
89
+ })
90
+ }
91
+ /** send a binary node */
92
+ const sendNode = frame => {
93
+ if (logger.level === 'trace') {
94
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' })
95
+ }
96
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame)
97
+ return sendRawMessage(buff)
98
+ }
99
+ /**
100
+ * Wait for a message with a certain tag to be received
101
+ * @param msgId the message tag to await
102
+ * @param timeoutMs timeout after which the promise will reject
103
+ */
104
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
105
+ let onRecv
106
+ let onErr
107
+ try {
108
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
109
+ onRecv = data => {
110
+ resolve(data)
111
+ }
112
+ onErr = err => {
113
+ reject(
114
+ err ||
115
+ new boom_1.Boom('Connection Closed', {
116
+ statusCode: Types_1.DisconnectReason.connectionClosed
117
+ })
118
+ )
119
+ }
120
+ ws.on(`TAG:${msgId}`, onRecv)
121
+ ws.on('close', onErr)
122
+ ws.on('error', onErr)
123
+ return () => reject(new boom_1.Boom('Query Cancelled'))
124
+ })
125
+ return result
126
+ } catch (error) {
127
+ // Catch timeout and return undefined instead of throwing
128
+ if (error instanceof boom_1.Boom && error.output?.statusCode === Types_1.DisconnectReason.timedOut) {
129
+ logger?.warn?.({ msgId }, 'timed out waiting for message')
130
+ return undefined
131
+ }
132
+ throw error
133
+ } finally {
134
+ if (onRecv) ws.off(`TAG:${msgId}`, onRecv)
135
+ if (onErr) {
136
+ ws.off('close', onErr)
137
+ ws.off('error', onErr)
138
+ }
139
+ }
140
+ }
141
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
142
+ const query = async (node, timeoutMs) => {
143
+ if (!node.attrs.id) {
144
+ node.attrs.id = generateMessageTag()
145
+ }
146
+ const msgId = node.attrs.id
147
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, async (resolve, reject) => {
148
+ const result = waitForMessage(msgId, timeoutMs).catch(reject)
149
+ sendNode(node)
150
+ .then(async () => resolve(await result))
151
+ .catch(reject)
152
+ })
153
+ if (result && 'tag' in result) {
154
+ ;(0, WABinary_1.assertNodeErrorFree)(result)
155
+ }
156
+ return result
157
+ }
158
+ // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
159
+ const digestKeyBundle = async () => {
160
+ const res = await query({
161
+ tag: 'iq',
162
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
163
+ content: [{ tag: 'digest', attrs: {} }]
164
+ })
165
+ const digestNode = (0, WABinary_1.getBinaryNodeChild)(res, 'digest')
166
+ if (!digestNode) {
167
+ await uploadPreKeys()
168
+ throw new Error('encrypt/get digest returned no digest node')
169
+ }
170
+ }
171
+ // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
172
+ const rotateSignedPreKey = async () => {
173
+ const newId = (creds.signedPreKey.keyId || 0) + 1
174
+ const skey = await (0, Utils_1.signedKeyPair)(creds.signedIdentityKey, newId)
175
+ await query({
176
+ tag: 'iq',
177
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
178
+ content: [
179
+ {
180
+ tag: 'rotate',
181
+ attrs: {},
182
+ content: [(0, Utils_1.xmppSignedPreKey)(skey)]
183
+ }
184
+ ]
185
+ })
186
+ // Persist new signed pre-key in creds
187
+ ev.emit('creds.update', { signedPreKey: skey })
188
+ }
189
+ const executeUSyncQuery = async usyncQuery => {
190
+ if (usyncQuery.protocols.length === 0) {
191
+ throw new boom_1.Boom('USyncQuery must have at least one protocol')
192
+ }
193
+ // todo: validate users, throw WARNING on no valid users
194
+ // variable below has only validated users
195
+ const validUsers = usyncQuery.users
196
+ const userNodes = validUsers.map(user => {
197
+ return {
198
+ tag: 'user',
199
+ attrs: {
200
+ jid: !user.phone ? user.id : undefined
201
+ },
202
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
203
+ }
204
+ })
205
+ const listNode = {
206
+ tag: 'list',
207
+ attrs: {},
208
+ content: userNodes
209
+ }
210
+ const queryNode = {
211
+ tag: 'query',
212
+ attrs: {},
213
+ content: usyncQuery.protocols.map(a => a.getQueryElement())
214
+ }
215
+ const iq = {
216
+ tag: 'iq',
217
+ attrs: {
218
+ to: WABinary_1.S_WHATSAPP_NET,
219
+ type: 'get',
220
+ xmlns: 'usync'
221
+ },
222
+ content: [
223
+ {
224
+ tag: 'usync',
225
+ attrs: {
226
+ context: usyncQuery.context,
227
+ mode: usyncQuery.mode,
228
+ sid: generateMessageTag(),
229
+ last: 'true',
230
+ index: '0'
231
+ },
232
+ content: [queryNode, listNode]
233
+ }
234
+ ]
235
+ }
236
+ const result = await query(iq)
237
+ return usyncQuery.parseUSyncQueryResult(result)
238
+ }
239
+ const onWhatsApp = async (...phoneNumber) => {
240
+ let usyncQuery = new WAUSync_1.USyncQuery()
241
+ let contactEnabled = false
242
+ for (const jid of phoneNumber) {
243
+ if ((0, WABinary_1.isLidUser)(jid)) {
244
+ logger?.warn('LIDs are not supported with onWhatsApp')
245
+ continue
246
+ } else {
247
+ if (!contactEnabled) {
248
+ contactEnabled = true
249
+ usyncQuery = usyncQuery.withContactProtocol()
250
+ }
251
+ const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`
252
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone))
253
+ }
254
+ }
255
+ if (usyncQuery.users.length === 0) {
256
+ return [] // return early without forcing an empty query
257
+ }
258
+ const results = await executeUSyncQuery(usyncQuery)
259
+ if (results) {
260
+ return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }))
261
+ }
262
+ }
263
+ const pnFromLIDUSync = async jids => {
264
+ const usyncQuery = new WAUSync_1.USyncQuery().withLIDProtocol().withContext('background')
265
+ for (const jid of jids) {
266
+ if ((0, WABinary_1.isLidUser)(jid)) {
267
+ logger?.warn('LID user found in LID fetch call')
268
+ continue
269
+ } else {
270
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
271
+ }
272
+ }
273
+ if (usyncQuery.users.length === 0) {
274
+ return [] // return early without forcing an empty query
275
+ }
276
+ const results = await executeUSyncQuery(usyncQuery)
277
+ if (results) {
278
+ return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }))
279
+ }
280
+ return []
281
+ }
282
+ /**
283
+ * @param {string | string[]} lid - @lid JID or array of @lid JID
284
+ * @returns {Promise<{ lid: string, pn: string | null }[]>}
285
+ */
286
+ const toPn = async lid => {
287
+ const lids = Array.isArray(lid) ? lid : [lid]
288
+ const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol()
289
+ for (const l of lids) {
290
+ const decoded = (0, WABinary_1.jidDecode)(l)
291
+ if (!decoded) continue
292
+ usyncQuery.withUser(
293
+ new WAUSync_1.USyncUser().withId((0, WABinary_1.jidEncode)(decoded.user, 's.whatsapp.net')).withLid(l)
294
+ )
295
+ }
296
+ const result = await executeUSyncQuery(usyncQuery)
297
+ return lids.map(l => {
298
+ const decoded = (0, WABinary_1.jidDecode)(l)
299
+ if (!decoded) return { lid: l, pn: null }
300
+ const match = result?.list?.find(entry => {
301
+ const entryDecoded = (0, WABinary_1.jidDecode)(entry.id)
302
+ return entryDecoded?.user === decoded.user
303
+ })
304
+ if (!match?.contact) return { lid: l, pn: null }
305
+ const pn = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(match.id)?.user, 's.whatsapp.net')
306
+ return { lid: l, pn: pn ?? null }
307
+ })
308
+ }
309
+ /**
310
+ * @param {string | string[]} pn - @s.whatsapp.net JID or array of @s.whatsapp.net JID
311
+ * @returns {Promise<{ pn: string, lid: string | null }[]>}
312
+ */
313
+ const toLID = async pn => {
314
+ const pns = Array.isArray(pn) ? pn : [pn]
315
+ const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol()
316
+ for (const p of pns) {
317
+ const decoded = (0, WABinary_1.jidDecode)(p)
318
+ if (!decoded) continue
319
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId((0, WABinary_1.jidEncode)(decoded.user, 's.whatsapp.net')))
320
+ }
321
+ const result = await executeUSyncQuery(usyncQuery)
322
+ return pns.map(p => {
323
+ const decoded = (0, WABinary_1.jidDecode)(p)
324
+ if (!decoded) return { pn: p, lid: null }
325
+ const match = result?.list?.find(entry => {
326
+ return (0, WABinary_1.jidDecode)(entry.id)?.user === decoded.user
327
+ })
328
+ if (!match?.contact) return { pn: p, lid: null }
329
+ const lidVal = match?.lid ?? null
330
+ const lid = lidVal ? (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(lidVal)?.user ?? lidVal, 'lid') : null
331
+ return { pn: p, lid }
332
+ })
333
+ }
334
+ /**
335
+ * @param {string | string[]} username - username to fetch
336
+ * @param {string} [pin] - pin of username if the user has one set
337
+ * @returns {Promise<{ username: string, pn: string | null, lid: string | null }[]>}
338
+ */
339
+ const fetchUsername = async (username, pin) => {
340
+ const usernames = Array.isArray(username) ? username : [username]
341
+ const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol()
342
+ for (const u of usernames) {
343
+ const user = new WAUSync_1.USyncUser().withUsername(u)
344
+ if (pin) user.withUsernameKey(pin)
345
+ usyncQuery.withUser(user)
346
+ }
347
+ const result = await executeUSyncQuery(usyncQuery)
348
+ return usernames.map(u => {
349
+ const match = result?.list?.find(entry => entry?.username === u)
350
+ if (!match?.contact) return { username: u, pn: null, lid: null }
351
+ const lid = match.lid
352
+ const pn = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(match.id)?.user, 's.whatsapp.net')
353
+ return { username: u, pn: pn ?? null, lid: lid ?? null }
354
+ })
355
+ }
356
+ const ev = (0, Utils_1.makeEventBuffer)(logger)
357
+ const { creds } = authState
358
+ // add transaction capability
359
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts)
360
+ const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync)
361
+ let lastDateRecv
362
+ let epoch = 1
363
+ let keepAliveReq
364
+ let qrTimer
365
+ let closed = false
366
+ const socketEndHandlers = []
367
+ /** log & process any unexpected errors */
368
+ const onUnexpectedError = (err, msg) => {
369
+ logger.error({ err }, `unexpected error in '${msg}'`)
370
+ }
371
+ /** await the next incoming message */
372
+ const awaitNextMessage = async sendMsg => {
373
+ if (!ws.isOpen) {
374
+ throw new boom_1.Boom('Connection Closed', {
375
+ statusCode: Types_1.DisconnectReason.connectionClosed
376
+ })
377
+ }
378
+ let onOpen
379
+ let onClose
380
+ const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
381
+ onOpen = resolve
382
+ onClose = mapWebSocketError(reject)
383
+ ws.on('frame', onOpen)
384
+ ws.on('close', onClose)
385
+ ws.on('error', onClose)
386
+ }).finally(() => {
387
+ ws.off('frame', onOpen)
388
+ ws.off('close', onClose)
389
+ ws.off('error', onClose)
390
+ })
391
+ if (sendMsg) {
392
+ sendRawMessage(sendMsg).catch(onClose)
393
+ }
394
+ return result
395
+ }
396
+ /** connection handshake */
397
+ const validateConnection = async () => {
398
+ let helloMsg = {
399
+ clientHello: { ephemeral: ephemeralKeyPair.public }
400
+ }
401
+ helloMsg = index_js_1.proto.HandshakeMessage.fromObject(helloMsg)
402
+ logger.info({ browser, helloMsg }, 'connected to WA')
403
+ const init = index_js_1.proto.HandshakeMessage.encode(helloMsg).finish()
404
+ const result = await awaitNextMessage(init)
405
+ const handshake = index_js_1.proto.HandshakeMessage.decode(result)
406
+ logger.trace({ handshake }, 'handshake recv from WA')
407
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey)
408
+ let node
409
+ if (!creds.me) {
410
+ node = (0, Utils_1.generateRegistrationNode)(creds, config)
411
+ logger.info({ node }, 'not logged in, attempting registration...')
412
+ } else {
413
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, config, creds)
414
+ logger.info({ node }, 'logging in...')
415
+ }
416
+ const payloadEnc = noise.encrypt(index_js_1.proto.ClientPayload.encode(node).finish())
417
+ await sendRawMessage(
418
+ index_js_1.proto.HandshakeMessage.encode({
419
+ clientFinish: {
420
+ static: keyEnc,
421
+ payload: payloadEnc
422
+ }
423
+ }).finish()
424
+ )
425
+ await noise.finishInit()
426
+ startKeepAliveRequest()
427
+ }
428
+ const getAvailablePreKeysOnServer = async () => {
429
+ const result = await query({
430
+ tag: 'iq',
431
+ attrs: {
432
+ id: generateMessageTag(),
433
+ xmlns: 'encrypt',
434
+ type: 'get',
435
+ to: WABinary_1.S_WHATSAPP_NET
436
+ },
437
+ content: [{ tag: 'count', attrs: {} }]
438
+ })
439
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count')
440
+ return +countChild.attrs.value
441
+ }
442
+ // Pre-key upload state management
443
+ let uploadPreKeysPromise = null
444
+ let lastUploadTime = 0
445
+ /** generates and uploads a set of pre-keys to the server */
446
+ const uploadPreKeys = async (count = Defaults_1.MIN_PREKEY_COUNT, retryCount = 0) => {
447
+ // Check minimum interval (except for retries)
448
+ if (retryCount === 0) {
449
+ const timeSinceLastUpload = Date.now() - lastUploadTime
450
+ if (timeSinceLastUpload < Defaults_1.MIN_UPLOAD_INTERVAL) {
451
+ logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`)
452
+ return
453
+ }
454
+ }
455
+ // Prevent multiple concurrent uploads
456
+ if (uploadPreKeysPromise) {
457
+ logger.debug('Pre-key upload already in progress, waiting for completion')
458
+ await uploadPreKeysPromise
459
+ }
460
+ const uploadLogic = async () => {
461
+ logger.info({ count, retryCount }, 'uploading pre-keys')
462
+ // Generate and save pre-keys atomically (prevents ID collisions on retry)
463
+ const node = await keys.transaction(async () => {
464
+ logger.debug({ requestedCount: count }, 'generating pre-keys with requested count')
465
+ const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count)
466
+ // Update credentials immediately to prevent duplicate IDs on retry
467
+ ev.emit('creds.update', update)
468
+ return node // Only return node since update is already used
469
+ }, creds?.me?.id || 'upload-pre-keys')
470
+ // Upload to server (outside transaction, can fail without affecting local keys)
471
+ try {
472
+ await query(node)
473
+ logger.info({ count }, 'uploaded pre-keys successfully')
474
+ lastUploadTime = Date.now()
475
+ } catch (uploadError) {
476
+ logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server')
477
+ // Exponential backoff retry (max 3 retries)
478
+ if (retryCount < 3) {
479
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000)
480
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`)
481
+ await new Promise(resolve => setTimeout(resolve, backoffDelay))
482
+ return uploadPreKeys(count, retryCount + 1)
483
+ }
484
+ throw uploadError
485
+ }
486
+ }
487
+ // Add timeout protection
488
+ uploadPreKeysPromise = Promise.race([
489
+ uploadLogic(),
490
+ new Promise((_, reject) =>
491
+ setTimeout(
492
+ () => reject(new boom_1.Boom('Pre-key upload timeout', { statusCode: 408 })),
493
+ Defaults_1.UPLOAD_TIMEOUT
494
+ )
495
+ )
496
+ ])
497
+ try {
498
+ await uploadPreKeysPromise
499
+ } finally {
500
+ uploadPreKeysPromise = null
501
+ }
502
+ }
503
+ const verifyCurrentPreKeyExists = async () => {
504
+ const currentPreKeyId = creds.nextPreKeyId - 1
505
+ if (currentPreKeyId <= 0) {
506
+ return { exists: false, currentPreKeyId: 0 }
507
+ }
508
+ const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()])
509
+ const exists = !!preKeys[currentPreKeyId.toString()]
510
+ return { exists, currentPreKeyId }
511
+ }
512
+ const uploadPreKeysToServerIfRequired = async () => {
513
+ try {
514
+ let count = 0
515
+ const preKeyCount = await getAvailablePreKeysOnServer()
516
+ if (preKeyCount === 0) count = Defaults_1.INITIAL_PREKEY_COUNT
517
+ else count = Defaults_1.MIN_PREKEY_COUNT
518
+ const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists()
519
+ logger.info(`${preKeyCount} pre-keys found on server`)
520
+ logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`)
521
+ const lowServerCount = preKeyCount <= count
522
+ const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
523
+ const shouldUpload = lowServerCount || missingCurrentPreKey
524
+ if (shouldUpload) {
525
+ const reasons = []
526
+ if (lowServerCount) reasons.push(`server count low (${preKeyCount})`)
527
+ if (missingCurrentPreKey) reasons.push(`current prekey ${currentPreKeyId} missing from storage`)
528
+ logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`)
529
+ await uploadPreKeys(count)
530
+ } else {
531
+ logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`)
532
+ }
533
+ } catch (error) {
534
+ logger.error({ error }, 'Failed to check/upload pre-keys during initialization')
535
+ // Don't throw - allow connection to continue even if pre-key check fails
536
+ }
537
+ }
538
+ const onMessageReceived = async data => {
539
+ await noise.decodeFrame(data, frame => {
540
+ // reset ping timeout
541
+ lastDateRecv = new Date()
542
+ let anyTriggered = false
543
+ anyTriggered = ws.emit('frame', frame)
544
+ // if it's a binary node
545
+ if (!(frame instanceof Uint8Array)) {
546
+ const msgId = frame.attrs.id
547
+ if (logger.level === 'trace') {
548
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' })
549
+ }
550
+ /* Check if this is a response to a message we sent */
551
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
552
+ /* Check if this is a response to a message we are expecting */
553
+ const l0 = frame.tag
554
+ const l1 = frame.attrs || {}
555
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
556
+ for (const key of Object.keys(l1)) {
557
+ anyTriggered =
558
+ ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
559
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
560
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
561
+ }
562
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
563
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
564
+ if (!anyTriggered && logger.level === 'debug') {
565
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
566
+ }
567
+ }
568
+ })
569
+ }
570
+ const end = async error => {
571
+ if (closed) {
572
+ logger.trace({ trace: error?.stack }, 'connection already closed')
573
+ return
574
+ }
575
+ closed = true
576
+ logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
577
+ clearInterval(keepAliveReq)
578
+ clearTimeout(qrTimer)
579
+ ws.removeAllListeners('close')
580
+ ws.removeAllListeners('open')
581
+ ws.removeAllListeners('message')
582
+ if (!ws.isClosed && !ws.isClosing) {
583
+ try {
584
+ await ws.close()
585
+ } catch {}
586
+ }
587
+ for (const handler of socketEndHandlers) {
588
+ try {
589
+ await handler(error)
590
+ } catch (err) {
591
+ logger.error({ err }, 'error in socket end handler')
592
+ }
593
+ }
594
+ ev.emit('connection.update', {
595
+ connection: 'close',
596
+ lastDisconnect: {
597
+ error,
598
+ date: new Date()
599
+ }
600
+ })
601
+ ev.removeAllListeners('connection.update')
602
+ }
603
+ const waitForSocketOpen = async () => {
604
+ if (ws.isOpen) {
605
+ return
606
+ }
607
+ if (ws.isClosed || ws.isClosing) {
608
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed })
609
+ }
610
+ let onOpen
611
+ let onClose
612
+ await new Promise((resolve, reject) => {
613
+ onOpen = () => resolve(undefined)
614
+ onClose = mapWebSocketError(reject)
615
+ ws.on('open', onOpen)
616
+ ws.on('close', onClose)
617
+ ws.on('error', onClose)
618
+ }).finally(() => {
619
+ ws.off('open', onOpen)
620
+ ws.off('close', onClose)
621
+ ws.off('error', onClose)
622
+ })
623
+ }
624
+ const startKeepAliveRequest = () =>
625
+ (keepAliveReq = setInterval(() => {
626
+ if (!lastDateRecv) {
627
+ lastDateRecv = new Date()
628
+ }
629
+ const diff = Date.now() - lastDateRecv.getTime()
630
+ /*
543
631
  check if it's been a suspicious amount of time since the server responded with our last seen
544
632
  it could be that the network is down
545
633
  */
546
- if (diff > keepAliveIntervalMs + 5000) {
547
- void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
548
- }
549
- else if (ws.isOpen) {
550
- // if its all good, send a keep alive request
551
- query({
552
- tag: 'iq',
553
- attrs: {
554
- id: generateMessageTag(),
555
- to: S_WHATSAPP_NET,
556
- type: 'get',
557
- xmlns: 'w:p'
558
- },
559
- content: [{ tag: 'ping', attrs: {} }]
560
- }).catch(err => {
561
- logger.error({ trace: err.stack }, 'error in sending keep alive');
562
- });
563
- }
564
- else {
565
- logger.warn('keep alive called when WS not open');
566
- }
567
- }, keepAliveIntervalMs));
568
- /** i have no idea why this exists. pls enlighten me */
569
- const sendPassiveIq = (tag) => query({
570
- tag: 'iq',
571
- attrs: {
572
- to: S_WHATSAPP_NET,
573
- xmlns: 'passive',
574
- type: 'set'
575
- },
576
- content: [{ tag, attrs: {} }]
577
- });
578
- /** logout & invalidate connection */
579
- const logout = async (msg) => {
580
- const jid = authState.creds.me?.id;
581
- if (jid) {
582
- await sendNode({
583
- tag: 'iq',
584
- attrs: {
585
- to: S_WHATSAPP_NET,
586
- type: 'set',
587
- id: generateMessageTag(),
588
- xmlns: 'md'
589
- },
590
- content: [
591
- {
592
- tag: 'remove-companion-device',
593
- attrs: {
594
- jid,
595
- reason: 'user_initiated'
596
- }
597
- }
598
- ]
599
- });
600
- }
601
- void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
602
- };
603
- const requestPairingCode = async (phoneNumber, customPairingCode) => {
604
- const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
605
- if (customPairingCode && customPairingCode?.length !== 8) {
606
- throw new Error('Custom pairing code must be exactly 8 chars');
607
- }
608
- authState.creds.pairingCode = pairingCode;
609
- authState.creds.me = {
610
- id: jidEncode(phoneNumber, 's.whatsapp.net'),
611
- name: '~'
612
- };
613
- ev.emit('creds.update', authState.creds);
614
- await sendNode({
615
- tag: 'iq',
616
- attrs: {
617
- to: S_WHATSAPP_NET,
618
- type: 'set',
619
- id: generateMessageTag(),
620
- xmlns: 'md'
621
- },
622
- content: [
623
- {
624
- tag: 'link_code_companion_reg',
625
- attrs: {
626
- jid: authState.creds.me.id,
627
- stage: 'companion_hello',
628
- should_show_push_notification: 'true'
629
- },
630
- content: [
631
- {
632
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
633
- attrs: {},
634
- content: await generatePairingKey()
635
- },
636
- {
637
- tag: 'companion_server_auth_key_pub',
638
- attrs: {},
639
- content: authState.creds.noiseKey.public
640
- },
641
- {
642
- tag: 'companion_platform_id',
643
- attrs: {},
644
- content: getCompanionPlatformId(browser)
645
- },
646
- {
647
- tag: 'companion_platform_display',
648
- attrs: {},
649
- content: `${browser[1]} (${browser[0]})`
650
- },
651
- {
652
- tag: 'link_code_pairing_nonce',
653
- attrs: {},
654
- content: '0'
655
- }
656
- ]
657
- }
658
- ]
659
- });
660
- return authState.creds.pairingCode;
661
- };
662
- async function generatePairingKey() {
663
- const salt = randomBytes(32);
664
- const randomIv = randomBytes(16);
665
- const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
666
- const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
667
- return Buffer.concat([salt, randomIv, ciphered]);
668
- }
669
- const sendWAMBuffer = (wamBuffer) => {
670
- return query({
671
- tag: 'iq',
672
- attrs: {
673
- to: S_WHATSAPP_NET,
674
- id: generateMessageTag(),
675
- xmlns: 'w:stats'
676
- },
677
- content: [
678
- {
679
- tag: 'add',
680
- attrs: { t: Math.round(Date.now() / 1000) + '' },
681
- content: wamBuffer
682
- }
683
- ]
684
- });
685
- };
686
- ws.on('message', onMessageReceived);
687
- ws.on('open', async () => {
688
- try {
689
- await validateConnection();
690
- }
691
- catch (err) {
692
- logger.error({ err }, 'error in validating connection');
693
- void end(err);
694
- }
695
- });
696
- ws.on('error', mapWebSocketError(end));
697
- ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
698
- // the server terminated the connection
699
- ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
700
- // QR gen
701
- ws.on('CB:iq,type:set,pair-device', async (stanza) => {
702
- const iq = {
703
- tag: 'iq',
704
- attrs: {
705
- to: S_WHATSAPP_NET,
706
- type: 'result',
707
- id: stanza.attrs.id
708
- }
709
- };
710
- await sendNode(iq);
711
- const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
712
- const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
713
- const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
714
- const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
715
- const advB64 = creds.advSecretKey;
716
- let qrMs = qrTimeout || 60000; // time to let a QR live
717
- const genPairQR = () => {
718
- if (!ws.isOpen) {
719
- return;
720
- }
721
- const refNode = refNodes.shift();
722
- if (!refNode) {
723
- void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
724
- return;
725
- }
726
- const ref = refNode.content.toString('utf-8');
727
- const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser);
728
- ev.emit('connection.update', { qr });
729
- qrTimer = setTimeout(genPairQR, qrMs);
730
- qrMs = qrTimeout || 20000; // shorter subsequent qrs
731
- };
732
- genPairQR();
733
- });
734
- // device paired for the first time
735
- // if device pairs successfully, the server asks to restart the connection
736
- ws.on('CB:iq,,pair-success', async (stanza) => {
737
- logger.debug('pair success recv');
738
- try {
739
- updateServerTimeOffset(stanza);
740
- const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
741
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
742
- ev.emit('creds.update', updatedCreds);
743
- ev.emit('connection.update', { isNewLogin: true, qr: undefined });
744
- await sendNode(reply);
745
- void sendUnifiedSession();
746
- }
747
- catch (error) {
748
- logger.info({ trace: error.stack }, 'error in pairing');
749
- void end(error);
750
- }
751
- });
752
- // login complete
753
- ws.on('CB:success', async (node) => {
754
- try {
755
- updateServerTimeOffset(node);
756
- await uploadPreKeysToServerIfRequired();
757
- await sendPassiveIq('active');
758
- // After successful login, validate our key-bundle against server
759
- try {
760
- await digestKeyBundle();
761
- }
762
- catch (e) {
763
- logger.warn({ e }, 'failed to run digest after login');
764
- }
765
- }
766
- catch (err) {
767
- logger.warn({ err }, 'failed to send initial passive iq');
768
- }
769
- logger.info('opened connection to WA');
770
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
771
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
772
- ev.emit('connection.update', { connection: 'open' });
773
- void sendUnifiedSession();
774
- if (node.attrs.lid && authState.creds.me?.id) {
775
- const myLID = node.attrs.lid;
776
- process.nextTick(async () => {
777
- try {
778
- const myPN = authState.creds.me.id;
779
- // Store our own LID-PN mapping
780
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
781
- // Create device list for our own user (needed for bulk migration)
782
- const { user, device } = jidDecode(myPN);
783
- await authState.keys.set({
784
- 'device-list': {
785
- [user]: [device?.toString() || '0']
786
- }
787
- });
788
- // migrate our own session
789
- await signalRepository.migrateSession(myPN, myLID);
790
- logger.info({ myPN, myLID }, 'Own LID session created successfully');
791
- }
792
- catch (error) {
793
- logger.error({ error, lid: myLID }, 'Failed to create own LID session');
794
- }
795
- });
796
- }
797
- });
798
- ws.on('CB:stream:error', (node) => {
799
- const [reasonNode] = getAllBinaryNodeChildren(node);
800
- logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
801
- const { reason, statusCode } = getErrorCodeFromStreamError(node);
802
- void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
803
- });
804
- // stream fail, possible logout
805
- ws.on('CB:failure', (node) => {
806
- const reason = +(node.attrs.reason || 500);
807
- void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
808
- });
809
- ws.on('CB:ib,,downgrade_webclient', () => {
810
- void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
811
- });
812
- ws.on('CB:ib,,offline_preview', async (node) => {
813
- logger.info('offline preview received', JSON.stringify(node));
814
- await sendNode({
815
- tag: 'ib',
816
- attrs: {},
817
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
818
- });
819
- });
820
- ws.on('CB:ib,,edge_routing', (node) => {
821
- const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
822
- const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
823
- if (routingInfo?.content) {
824
- authState.creds.routingInfo = Buffer.from(routingInfo?.content);
825
- ev.emit('creds.update', authState.creds);
826
- }
827
- });
828
- let didStartBuffer = false;
829
- process.nextTick(() => {
830
- if (creds.me?.id) {
831
- // start buffering important events
832
- // if we're logged in
833
- ev.buffer();
834
- didStartBuffer = true;
835
- }
836
- ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
837
- });
838
- // called when all offline notifs are handled
839
- ws.on('CB:ib,,offline', (node) => {
840
- const child = getBinaryNodeChild(node, 'offline');
841
- const offlineNotifs = +(child?.attrs.count || 0);
842
- logger.info(`handled ${offlineNotifs} offline messages/notifications`);
843
- if (didStartBuffer) {
844
- ev.flush();
845
- logger.trace('flushed events for initial buffer');
846
- }
847
- ev.emit('connection.update', { receivedPendingNotifications: true });
848
- });
849
- // update credentials when required
850
- ev.on('creds.update', update => {
851
- const name = update.me?.name;
852
- // if name has just been received
853
- if (creds.me?.name !== name) {
854
- logger.debug({ name }, 'updated pushName');
855
- sendNode({
856
- tag: 'presence',
857
- attrs: { name: name }
858
- }).catch(err => {
859
- logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
860
- });
861
- }
862
- Object.assign(creds, update);
863
- });
864
- const updateServerTimeOffset = ({ attrs }) => {
865
- const tValue = attrs?.t;
866
- if (!tValue) {
867
- return;
868
- }
869
- const parsed = Number(tValue);
870
- if (Number.isNaN(parsed) || parsed <= 0) {
871
- return;
872
- }
873
- const localMs = Date.now();
874
- serverTimeOffsetMs = parsed * 1000 - localMs;
875
- logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
876
- };
877
- const getUnifiedSessionId = () => {
878
- const offsetMs = 3 * TimeMs.Day;
879
- const now = Date.now() + serverTimeOffsetMs;
880
- const id = (now + offsetMs) % TimeMs.Week;
881
- return id.toString();
882
- };
883
- const sendUnifiedSession = async () => {
884
- if (!ws.isOpen) {
885
- return;
886
- }
887
- const node = {
888
- tag: 'ib',
889
- attrs: {},
890
- content: [
891
- {
892
- tag: 'unified_session',
893
- attrs: {
894
- id: getUnifiedSessionId()
895
- }
896
- }
897
- ]
898
- };
899
- try {
900
- await sendNode(node);
901
- }
902
- catch (error) {
903
- logger.debug({ error }, 'failed to send unified_session telemetry');
904
- }
905
- };
906
- const registerSocketEndHandler = (handler) => {
907
- socketEndHandlers.push(handler);
908
- };
909
- /**
910
- * Fetches your account's standing when it comes to restrictions.
911
- * @returns Returns the state of the restrictions.
912
- */
913
- const fetchAccountReachoutTimelock = async () => {
914
- const queryResult = await executeWMexQuery({}, QueryIds.REACHOUT_TIMELOCK, XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag);
915
- const result = {
916
- isActive: !!queryResult?.is_active,
917
- timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0'
918
- ? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000)
919
- : undefined,
920
- enforcementType: queryResult?.enforcement_type ?? ReachoutTimelockEnforcementType.DEFAULT
921
- };
922
- ev.emit('connection.update', { reachoutTimeLock: result });
923
- return result;
924
- };
925
- /**
926
- * Fetches your account's new chat limits.
927
- * @returns Returns the quota and the usage.
928
- */
929
- const fetchNewChatMessageCap = async () => {
930
- return executeWMexQuery({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, QueryIds.MESSAGE_CAPPING_INFO, XWAPaths.xwa2_message_capping_info, query, generateMessageTag);
931
- };
932
- return {
933
- type: 'md',
934
- ws,
935
- ev,
936
- authState: { creds, keys },
937
- signalRepository,
938
- get user() {
939
- return authState.creds.me;
940
- },
941
- generateMessageTag,
942
- query,
943
- waitForMessage,
944
- waitForSocketOpen,
945
- sendRawMessage,
946
- sendNode,
947
- logout,
948
- end,
949
- registerSocketEndHandler,
950
- onUnexpectedError,
951
- uploadPreKeys,
952
- uploadPreKeysToServerIfRequired,
953
- digestKeyBundle,
954
- rotateSignedPreKey,
955
- requestPairingCode,
956
- updateServerTimeOffset,
957
- sendUnifiedSession,
958
- wamBuffer: publicWAMBuffer,
959
- /** Waits for the connection to WA to reach a state */
960
- waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
961
- sendWAMBuffer,
962
- executeUSyncQuery,
963
- onWhatsApp,
964
- fetchAccountReachoutTimelock,
965
- fetchNewChatMessageCap,
966
- toPn,
967
- toLid,
968
- pnFromLIDUSync
969
- };
970
- };
634
+ if (diff > keepAliveIntervalMs + 5000) {
635
+ void end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }))
636
+ } else if (ws.isOpen) {
637
+ // if its all good, send a keep alive request
638
+ query({
639
+ tag: 'iq',
640
+ attrs: {
641
+ id: generateMessageTag(),
642
+ to: WABinary_1.S_WHATSAPP_NET,
643
+ type: 'get',
644
+ xmlns: 'w:p'
645
+ },
646
+ content: [{ tag: 'ping', attrs: {} }]
647
+ }).catch(err => {
648
+ logger.error({ trace: err.stack }, 'error in sending keep alive')
649
+ })
650
+ } else {
651
+ logger.warn('keep alive called when WS not open')
652
+ }
653
+ }, keepAliveIntervalMs))
654
+ /** i have no idea why this exists. pls enlighten me */
655
+ const sendPassiveIq = tag =>
656
+ query({
657
+ tag: 'iq',
658
+ attrs: {
659
+ to: WABinary_1.S_WHATSAPP_NET,
660
+ xmlns: 'passive',
661
+ type: 'set'
662
+ },
663
+ content: [{ tag, attrs: {} }]
664
+ })
665
+ /** logout & invalidate connection */
666
+ const logout = async msg => {
667
+ const jid = authState.creds.me?.id
668
+ if (jid) {
669
+ await sendNode({
670
+ tag: 'iq',
671
+ attrs: {
672
+ to: WABinary_1.S_WHATSAPP_NET,
673
+ type: 'set',
674
+ id: generateMessageTag(),
675
+ xmlns: 'md'
676
+ },
677
+ content: [
678
+ {
679
+ tag: 'remove-companion-device',
680
+ attrs: {
681
+ jid,
682
+ reason: 'user_initiated'
683
+ }
684
+ }
685
+ ]
686
+ })
687
+ }
688
+ void end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }))
689
+ }
690
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
691
+ const pairingCode = customPairingCode ?? (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5))
692
+ if (customPairingCode && customPairingCode?.length !== 8) {
693
+ throw new Error('Custom pairing code must be exactly 8 chars')
694
+ }
695
+ authState.creds.pairingCode = pairingCode
696
+ authState.creds.me = {
697
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
698
+ name: '~'
699
+ }
700
+ ev.emit('creds.update', authState.creds)
701
+ await sendNode({
702
+ tag: 'iq',
703
+ attrs: {
704
+ to: WABinary_1.S_WHATSAPP_NET,
705
+ type: 'set',
706
+ id: generateMessageTag(),
707
+ xmlns: 'md'
708
+ },
709
+ content: [
710
+ {
711
+ tag: 'link_code_companion_reg',
712
+ attrs: {
713
+ jid: authState.creds.me.id,
714
+ stage: 'companion_hello',
715
+ should_show_push_notification: 'true'
716
+ },
717
+ content: [
718
+ {
719
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
720
+ attrs: {},
721
+ content: await generatePairingKey()
722
+ },
723
+ {
724
+ tag: 'companion_server_auth_key_pub',
725
+ attrs: {},
726
+ content: authState.creds.noiseKey.public
727
+ },
728
+ {
729
+ tag: 'companion_platform_id',
730
+ attrs: {},
731
+ content: (0, browser_utils_1.getPlatformId)(browser[1])
732
+ },
733
+ {
734
+ tag: 'companion_platform_display',
735
+ attrs: {},
736
+ content: `${browser[1]} (${browser[0]})`
737
+ },
738
+ {
739
+ tag: 'link_code_pairing_nonce',
740
+ attrs: {},
741
+ content: '0'
742
+ }
743
+ ]
744
+ }
745
+ ]
746
+ })
747
+ return authState.creds.pairingCode
748
+ }
749
+ async function generatePairingKey() {
750
+ const salt = (0, crypto_1.randomBytes)(32)
751
+ const randomIv = (0, crypto_1.randomBytes)(16)
752
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt)
753
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
754
+ return Buffer.concat([salt, randomIv, ciphered])
755
+ }
756
+ const sendWAMBuffer = wamBuffer => {
757
+ return query({
758
+ tag: 'iq',
759
+ attrs: {
760
+ to: WABinary_1.S_WHATSAPP_NET,
761
+ id: generateMessageTag(),
762
+ xmlns: 'w:stats'
763
+ },
764
+ content: [
765
+ {
766
+ tag: 'add',
767
+ attrs: { t: Math.round(Date.now() / 1000) + '' },
768
+ content: wamBuffer
769
+ }
770
+ ]
771
+ })
772
+ }
773
+ ws.on('message', onMessageReceived)
774
+ ws.on('open', async () => {
775
+ try {
776
+ await validateConnection()
777
+ } catch (err) {
778
+ logger.error({ err }, 'error in validating connection')
779
+ void end(err)
780
+ }
781
+ })
782
+ ws.on('error', mapWebSocketError(end))
783
+ ws.on(
784
+ 'close',
785
+ () => void end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed }))
786
+ )
787
+ // the server terminated the connection
788
+ ws.on(
789
+ 'CB:xmlstreamend',
790
+ () =>
791
+ void end(
792
+ new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })
793
+ )
794
+ )
795
+ // QR gen
796
+ ws.on('CB:iq,type:set,pair-device', async stanza => {
797
+ const iq = {
798
+ tag: 'iq',
799
+ attrs: {
800
+ to: WABinary_1.S_WHATSAPP_NET,
801
+ type: 'result',
802
+ id: stanza.attrs.id
803
+ }
804
+ }
805
+ await sendNode(iq)
806
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device')
807
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref')
808
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
809
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
810
+ const advB64 = creds.advSecretKey
811
+ let qrMs = qrTimeout || 60000 // time to let a QR live
812
+ const genPairQR = () => {
813
+ if (!ws.isOpen) {
814
+ return
815
+ }
816
+ const refNode = refNodes.shift()
817
+ if (!refNode) {
818
+ void end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }))
819
+ return
820
+ }
821
+ const ref = refNode.content.toString('utf-8')
822
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',')
823
+ ev.emit('connection.update', { qr })
824
+ qrTimer = setTimeout(genPairQR, qrMs)
825
+ qrMs = qrTimeout || 20000 // shorter subsequent qrs
826
+ }
827
+ genPairQR()
828
+ })
829
+ // device paired for the first time
830
+ // if device pairs successfully, the server asks to restart the connection
831
+ ws.on('CB:iq,,pair-success', async stanza => {
832
+ logger.debug('pair success recv')
833
+ try {
834
+ updateServerTimeOffset(stanza)
835
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds)
836
+ logger.info(
837
+ { me: updatedCreds.me, platform: updatedCreds.platform },
838
+ 'pairing configured successfully, expect to restart the connection...'
839
+ )
840
+ ev.emit('creds.update', updatedCreds)
841
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined })
842
+ await sendNode(reply)
843
+ void sendUnifiedSession()
844
+ } catch (error) {
845
+ logger.info({ trace: error.stack }, 'error in pairing')
846
+ void end(error)
847
+ }
848
+ })
849
+ // login complete
850
+ ws.on('CB:success', async node => {
851
+ try {
852
+ updateServerTimeOffset(node)
853
+ await uploadPreKeysToServerIfRequired()
854
+ // passive→active handshake only for companion (passive) sessions
855
+ if (!config.masqueradeAsPrimary) {
856
+ await sendPassiveIq('active')
857
+ }
858
+ // After successful login, validate our key-bundle against server
859
+ try {
860
+ await digestKeyBundle()
861
+ } catch (e) {
862
+ logger.warn({ e }, 'failed to run digest after login')
863
+ }
864
+ } catch (err) {
865
+ logger.warn({ err }, 'failed to send initial passive iq')
866
+ }
867
+ logger.info('opened connection to WA')
868
+ clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
869
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
870
+ if (config.syncFullHistory && authState.creds.initialFullSyncDone !== true) {
871
+ logger.debug('initial full history sync completed, persisting one-time flag')
872
+ ev.emit('creds.update', { initialFullSyncDone: true })
873
+ }
874
+ ev.emit('connection.update', { connection: 'open' })
875
+ void sendUnifiedSession()
876
+ if (node.attrs.lid && authState.creds.me?.id) {
877
+ const myLID = node.attrs.lid
878
+ process.nextTick(async () => {
879
+ try {
880
+ const myPN = authState.creds.me.id
881
+ // Store our own LID-PN mapping
882
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }])
883
+ // Create device list for our own user (needed for bulk migration)
884
+ const { user, device } = (0, WABinary_1.jidDecode)(myPN)
885
+ await authState.keys.set({
886
+ 'device-list': {
887
+ [user]: [device?.toString() || '0']
888
+ }
889
+ })
890
+ // migrate our own session
891
+ await signalRepository.migrateSession(myPN, myLID)
892
+ logger.info({ myPN, myLID }, 'Own LID session created successfully')
893
+ } catch (error) {
894
+ logger.error({ error, lid: myLID }, 'Failed to create own LID session')
895
+ }
896
+ })
897
+ }
898
+ })
899
+ ws.on('CB:stream:error', node => {
900
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node)
901
+ logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out')
902
+ const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node)
903
+ void end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }))
904
+ })
905
+ // stream fail, possible logout
906
+ ws.on('CB:failure', node => {
907
+ const reason = +(node.attrs.reason || 500)
908
+ void end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
909
+ })
910
+ ws.on('CB:ib,,downgrade_webclient', () => {
911
+ void end(
912
+ new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch })
913
+ )
914
+ })
915
+ ws.on('CB:ib,,offline_preview', async node => {
916
+ logger.info('offline preview received', JSON.stringify(node))
917
+ await sendNode({
918
+ tag: 'ib',
919
+ attrs: {},
920
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
921
+ })
922
+ })
923
+ ws.on('CB:ib,,edge_routing', node => {
924
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing')
925
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info')
926
+ if (routingInfo?.content) {
927
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content)
928
+ ev.emit('creds.update', authState.creds)
929
+ }
930
+ })
931
+ let didStartBuffer = false
932
+ process.nextTick(() => {
933
+ if (creds.me?.id) {
934
+ // start buffering important events
935
+ // if we're logged in
936
+ ev.buffer()
937
+ didStartBuffer = true
938
+ }
939
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
940
+ })
941
+ // called when all offline notifs are handled
942
+ ws.on('CB:ib,,offline', node => {
943
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline')
944
+ const offlineNotifs = +(child?.attrs.count || 0)
945
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`)
946
+ if (didStartBuffer) {
947
+ ev.flush()
948
+ logger.trace('flushed events for initial buffer')
949
+ }
950
+ ev.emit('connection.update', { receivedPendingNotifications: true })
951
+ })
952
+ // update credentials when required
953
+ ev.on('creds.update', update => {
954
+ const name = update.me?.name
955
+ // if name has just been received
956
+ if (creds.me?.name !== name) {
957
+ logger.debug({ name }, 'updated pushName')
958
+ sendNode({
959
+ tag: 'presence',
960
+ attrs: { name: name }
961
+ }).catch(err => {
962
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
963
+ })
964
+ }
965
+ Object.assign(creds, update)
966
+ })
967
+ const updateServerTimeOffset = ({ attrs }) => {
968
+ const tValue = attrs?.t
969
+ if (!tValue) {
970
+ return
971
+ }
972
+ const parsed = Number(tValue)
973
+ if (Number.isNaN(parsed) || parsed <= 0) {
974
+ return
975
+ }
976
+ const localMs = Date.now()
977
+ serverTimeOffsetMs = parsed * 1000 - localMs
978
+ logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset')
979
+ }
980
+ const getUnifiedSessionId = () => {
981
+ const offsetMs = 3 * Defaults_1.TimeMs.Day
982
+ const now = Date.now() + serverTimeOffsetMs
983
+ const id = (now + offsetMs) % Defaults_1.TimeMs.Week
984
+ return id.toString()
985
+ }
986
+ const sendUnifiedSession = async () => {
987
+ if (!ws.isOpen) {
988
+ return
989
+ }
990
+ const node = {
991
+ tag: 'ib',
992
+ attrs: {},
993
+ content: [
994
+ {
995
+ tag: 'unified_session',
996
+ attrs: {
997
+ id: getUnifiedSessionId()
998
+ }
999
+ }
1000
+ ]
1001
+ }
1002
+ try {
1003
+ await sendNode(node)
1004
+ } catch (error) {
1005
+ logger.debug({ error }, 'failed to send unified_session telemetry')
1006
+ }
1007
+ }
1008
+ const fetchAccountReachoutTimelock = async () => {
1009
+ const queryResult = await (0, mex_1.executeWMexQuery)(
1010
+ {},
1011
+ Types_1.QueryIds.REACHOUT_TIMELOCK,
1012
+ Types_1.XWAPaths.xwa2_fetch_account_reachout_timelock,
1013
+ query,
1014
+ generateMessageTag
1015
+ )
1016
+ const result = {
1017
+ isActive: !!queryResult?.is_active,
1018
+ timeEnforcementEnds:
1019
+ queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0'
1020
+ ? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000)
1021
+ : undefined,
1022
+ enforcementType: queryResult?.enforcement_type ?? Types_1.ReachoutTimelockEnforcementType.DEFAULT
1023
+ }
1024
+ ev.emit('connection.update', { reachoutTimeLock: result })
1025
+ return result
1026
+ }
1027
+ const fetchNewChatMessageCap = async () => {
1028
+ return (0, mex_1.executeWMexQuery)(
1029
+ { input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } },
1030
+ Types_1.QueryIds.MESSAGE_CAPPING_INFO,
1031
+ Types_1.XWAPaths.xwa2_message_capping_info,
1032
+ query,
1033
+ generateMessageTag
1034
+ )
1035
+ }
1036
+ const registerSocketEndHandler = handler => {
1037
+ socketEndHandlers.push(handler)
1038
+ }
1039
+ return {
1040
+ type: 'md',
1041
+ ws,
1042
+ ev,
1043
+ authState: { creds, keys },
1044
+ signalRepository,
1045
+ get user() {
1046
+ return authState.creds.me
1047
+ },
1048
+ generateMessageTag,
1049
+ query,
1050
+ waitForMessage,
1051
+ waitForSocketOpen,
1052
+ sendRawMessage,
1053
+ sendNode,
1054
+ logout,
1055
+ end,
1056
+ registerSocketEndHandler,
1057
+ toPn,
1058
+ toLID,
1059
+ fetchUsername,
1060
+ onUnexpectedError,
1061
+ uploadPreKeys,
1062
+ uploadPreKeysToServerIfRequired,
1063
+ digestKeyBundle,
1064
+ rotateSignedPreKey,
1065
+ requestPairingCode,
1066
+ updateServerTimeOffset,
1067
+ sendUnifiedSession,
1068
+ wamBuffer: publicWAMBuffer,
1069
+ /** Waits for the connection to WA to reach a state */
1070
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
1071
+ sendWAMBuffer,
1072
+ executeUSyncQuery,
1073
+ onWhatsApp,
1074
+ fetchAccountReachoutTimelock,
1075
+ fetchNewChatMessageCap
1076
+ }
1077
+ }
1078
+ exports.makeSocket = makeSocket
971
1079
  /**
972
1080
  * map the websocket error to the right type
973
1081
  * so it can be retried by the caller
974
1082
  * */
975
1083
  function mapWebSocketError(handler) {
976
- return (error) => {
977
- handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
978
- };
1084
+ return error => {
1085
+ handler(
1086
+ new boom_1.Boom(`WebSocket Error (${error?.message})`, {
1087
+ statusCode: (0, Utils_1.getCodeFromWSError)(error),
1088
+ data: error
1089
+ })
1090
+ )
1091
+ }
979
1092
  }
980
- //# sourceMappingURL=socket.js.map