@badzz88/baileys 8.4.7 → 8.4.9

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