@sixcore/baileys 1.0.0

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