@badzz88/baileys 8.5.7 → 8.5.8

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