@badzz88/baileys 8.5.4 → 8.5.6

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