gifted-baileys 1.5.4 → 1.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 (252) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +88 -969
  3. package/WAProto/index.d.ts +1256 -13195
  4. package/WAProto/index.js +74730 -125106
  5. package/package.json +9 -27
  6. package/src/Defaults/baileys-version.json +3 -0
  7. package/{lib → src}/Defaults/index.js +14 -7
  8. package/src/Defaults/index.ts +131 -0
  9. package/src/README.md +1 -0
  10. package/src/Signal/libsignal.js +180 -0
  11. package/src/Signal/libsignal.ts +141 -0
  12. package/src/Socket/Client/abstract-socket-client.ts +19 -0
  13. package/{lib → src}/Socket/Client/index.js +3 -2
  14. package/src/Socket/Client/index.ts +3 -0
  15. package/src/Socket/Client/mobile-socket-client.js +78 -0
  16. package/src/Socket/Client/mobile-socket-client.ts +66 -0
  17. package/src/Socket/Client/web-socket-client.js +75 -0
  18. package/src/Socket/Client/web-socket-client.ts +57 -0
  19. package/{lib → src}/Socket/business.js +33 -28
  20. package/src/Socket/business.ts +281 -0
  21. package/{lib → src}/Socket/chats.js +176 -174
  22. package/src/Socket/chats.ts +1030 -0
  23. package/{lib → src}/Socket/groups.js +68 -80
  24. package/src/Socket/groups.ts +356 -0
  25. package/{lib → src}/Socket/index.js +1 -4
  26. package/src/Socket/index.ts +13 -0
  27. package/{lib → src}/Socket/messages-recv.js +211 -378
  28. package/src/Socket/messages-recv.ts +985 -0
  29. package/{lib → src}/Socket/messages-send.js +177 -452
  30. package/src/Socket/messages-send.ts +871 -0
  31. package/{lib → src}/Socket/newsletter.js +98 -107
  32. package/src/Socket/newsletter.ts +282 -0
  33. package/{lib → src}/Socket/registration.js +48 -56
  34. package/src/Socket/registration.ts +250 -0
  35. package/{lib → src}/Socket/socket.js +77 -77
  36. package/src/Socket/socket.ts +777 -0
  37. package/src/Store/index.ts +3 -0
  38. package/{lib → src}/Store/make-cache-manager-store.js +34 -25
  39. package/src/Store/make-cache-manager-store.ts +100 -0
  40. package/{lib → src}/Store/make-in-memory-store.js +32 -36
  41. package/src/Store/make-in-memory-store.ts +475 -0
  42. package/src/Store/make-ordered-dictionary.ts +86 -0
  43. package/{lib → src}/Store/object-repository.js +1 -1
  44. package/src/Store/object-repository.ts +32 -0
  45. package/src/Tests/test.app-state-sync.js +204 -0
  46. package/src/Tests/test.app-state-sync.ts +207 -0
  47. package/src/Tests/test.event-buffer.js +270 -0
  48. package/src/Tests/test.event-buffer.ts +319 -0
  49. package/src/Tests/test.key-store.js +76 -0
  50. package/src/Tests/test.key-store.ts +92 -0
  51. package/src/Tests/test.libsignal.js +141 -0
  52. package/src/Tests/test.libsignal.ts +186 -0
  53. package/src/Tests/test.media-download.js +93 -0
  54. package/src/Tests/test.media-download.ts +76 -0
  55. package/src/Tests/test.messages.js +33 -0
  56. package/src/Tests/test.messages.ts +37 -0
  57. package/src/Tests/utils.js +34 -0
  58. package/src/Tests/utils.ts +36 -0
  59. package/src/Types/Auth.ts +113 -0
  60. package/src/Types/Call.ts +15 -0
  61. package/src/Types/Chat.ts +106 -0
  62. package/{lib/Types/Contact.d.ts → src/Types/Contact.ts} +9 -8
  63. package/src/Types/Events.ts +93 -0
  64. package/src/Types/GroupMetadata.ts +53 -0
  65. package/src/Types/Label.ts +36 -0
  66. package/{lib/Types/LabelAssociation.d.ts → src/Types/LabelAssociation.ts} +22 -16
  67. package/src/Types/Message.ts +288 -0
  68. package/src/Types/Newsletter.ts +98 -0
  69. package/src/Types/Product.ts +85 -0
  70. package/src/Types/Signal.ts +68 -0
  71. package/{lib/Types/Socket.d.ts → src/Types/Socket.ts} +68 -61
  72. package/src/Types/State.ts +29 -0
  73. package/src/Types/index.ts +59 -0
  74. package/{lib → src}/Utils/auth-utils.js +90 -73
  75. package/src/Utils/auth-utils.ts +222 -0
  76. package/src/Utils/baileys-event-stream.js +92 -0
  77. package/src/Utils/baileys-event-stream.ts +66 -0
  78. package/{lib → src}/Utils/business.js +43 -15
  79. package/src/Utils/business.ts +275 -0
  80. package/{lib → src}/Utils/chat-utils.js +94 -87
  81. package/src/Utils/chat-utils.ts +860 -0
  82. package/{lib → src}/Utils/crypto.js +2 -4
  83. package/src/Utils/crypto.ts +131 -0
  84. package/src/Utils/decode-wa-message.js +211 -0
  85. package/src/Utils/decode-wa-message.ts +228 -0
  86. package/{lib → src}/Utils/event-buffer.js +13 -4
  87. package/src/Utils/event-buffer.ts +613 -0
  88. package/{lib → src}/Utils/generics.js +86 -67
  89. package/src/Utils/generics.ts +434 -0
  90. package/{lib → src}/Utils/history.js +39 -13
  91. package/src/Utils/history.ts +112 -0
  92. package/src/Utils/index.ts +17 -0
  93. package/{lib → src}/Utils/link-preview.js +54 -17
  94. package/src/Utils/link-preview.ts +122 -0
  95. package/src/Utils/logger.ts +3 -0
  96. package/src/Utils/lt-hash.ts +61 -0
  97. package/{lib → src}/Utils/make-mutex.js +13 -4
  98. package/src/Utils/make-mutex.ts +44 -0
  99. package/{lib → src}/Utils/messages-media.js +255 -193
  100. package/src/Utils/messages-media.ts +847 -0
  101. package/{lib → src}/Utils/messages.js +118 -588
  102. package/src/Utils/messages.ts +956 -0
  103. package/src/Utils/noise-handler.ts +197 -0
  104. package/{lib → src}/Utils/process-message.js +30 -27
  105. package/src/Utils/process-message.ts +414 -0
  106. package/{lib → src}/Utils/signal.js +42 -25
  107. package/src/Utils/signal.ts +177 -0
  108. package/{lib → src}/Utils/use-multi-file-auth-state.js +28 -27
  109. package/src/Utils/use-multi-file-auth-state.ts +90 -0
  110. package/{lib → src}/Utils/validate-connection.js +9 -40
  111. package/src/Utils/validate-connection.ts +238 -0
  112. package/src/WABinary/constants.ts +42 -0
  113. package/src/WABinary/decode.ts +265 -0
  114. package/{lib → src}/WABinary/encode.js +10 -16
  115. package/src/WABinary/encode.ts +236 -0
  116. package/src/WABinary/generic-utils.ts +121 -0
  117. package/src/WABinary/index.ts +5 -0
  118. package/src/WABinary/jid-utils.ts +68 -0
  119. package/src/WABinary/types.ts +17 -0
  120. package/src/WAM/BinaryInfo.ts +12 -0
  121. package/src/WAM/constants.ts +15382 -0
  122. package/src/WAM/encode.ts +174 -0
  123. package/src/WAM/index.ts +3 -0
  124. package/{lib → src}/index.js +0 -1
  125. package/src/index.ts +13 -0
  126. package/README.md +0 -1645
  127. package/lib/Defaults/baileys-version.json +0 -3
  128. package/lib/Defaults/index.d.ts +0 -284
  129. package/lib/Signal/libsignal.d.ts +0 -3
  130. package/lib/Signal/libsignal.js +0 -161
  131. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -15
  132. package/lib/Socket/Client/index.d.ts +0 -2
  133. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -12
  134. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  135. package/lib/Socket/Client/types.d.ts +0 -17
  136. package/lib/Socket/Client/types.js +0 -13
  137. package/lib/Socket/Client/websocket.d.ts +0 -12
  138. package/lib/Socket/Client/websocket.js +0 -62
  139. package/lib/Socket/business.d.ts +0 -170
  140. package/lib/Socket/chats.d.ts +0 -81
  141. package/lib/Socket/groups.d.ts +0 -115
  142. package/lib/Socket/index.d.ts +0 -172
  143. package/lib/Socket/messages-recv.d.ts +0 -158
  144. package/lib/Socket/messages-send.d.ts +0 -155
  145. package/lib/Socket/newsletter.d.ts +0 -132
  146. package/lib/Socket/registration.d.ts +0 -264
  147. package/lib/Socket/socket.d.ts +0 -44
  148. package/lib/Socket/usync.d.ts +0 -37
  149. package/lib/Socket/usync.js +0 -70
  150. package/lib/Store/index.d.ts +0 -3
  151. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  152. package/lib/Store/make-in-memory-store.d.ts +0 -118
  153. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  154. package/lib/Store/object-repository.d.ts +0 -10
  155. package/lib/Types/Auth.d.ts +0 -109
  156. package/lib/Types/Call.d.ts +0 -13
  157. package/lib/Types/Chat.d.ts +0 -107
  158. package/lib/Types/Events.d.ts +0 -172
  159. package/lib/Types/GroupMetadata.d.ts +0 -56
  160. package/lib/Types/Label.d.ts +0 -46
  161. package/lib/Types/Message.d.ts +0 -433
  162. package/lib/Types/Newsletter.d.ts +0 -92
  163. package/lib/Types/Product.d.ts +0 -78
  164. package/lib/Types/Signal.d.ts +0 -57
  165. package/lib/Types/State.d.ts +0 -27
  166. package/lib/Types/USync.d.ts +0 -25
  167. package/lib/Types/USync.js +0 -2
  168. package/lib/Types/index.d.ts +0 -66
  169. package/lib/Utils/auth-utils.d.ts +0 -18
  170. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  171. package/lib/Utils/baileys-event-stream.js +0 -63
  172. package/lib/Utils/business.d.ts +0 -22
  173. package/lib/Utils/chat-utils.d.ts +0 -70
  174. package/lib/Utils/crypto.d.ts +0 -40
  175. package/lib/Utils/decode-wa-message.d.ts +0 -36
  176. package/lib/Utils/decode-wa-message.js +0 -226
  177. package/lib/Utils/event-buffer.d.ts +0 -35
  178. package/lib/Utils/generics.d.ts +0 -88
  179. package/lib/Utils/history.d.ts +0 -19
  180. package/lib/Utils/index.d.ts +0 -17
  181. package/lib/Utils/link-preview.d.ts +0 -21
  182. package/lib/Utils/logger.d.ts +0 -2
  183. package/lib/Utils/lt-hash.d.ts +0 -12
  184. package/lib/Utils/make-mutex.d.ts +0 -7
  185. package/lib/Utils/messages-media.d.ts +0 -113
  186. package/lib/Utils/messages.d.ts +0 -77
  187. package/lib/Utils/noise-handler.d.ts +0 -20
  188. package/lib/Utils/process-message.d.ts +0 -41
  189. package/lib/Utils/signal.d.ts +0 -33
  190. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  191. package/lib/Utils/validate-connection.d.ts +0 -11
  192. package/lib/WABinary/constants.d.ts +0 -27
  193. package/lib/WABinary/decode.d.ts +0 -6
  194. package/lib/WABinary/encode.d.ts +0 -2
  195. package/lib/WABinary/generic-utils.d.ts +0 -14
  196. package/lib/WABinary/index.d.ts +0 -5
  197. package/lib/WABinary/jid-utils.d.ts +0 -31
  198. package/lib/WABinary/types.d.ts +0 -18
  199. package/lib/WAM/BinaryInfo.d.ts +0 -8
  200. package/lib/WAM/constants.d.ts +0 -38
  201. package/lib/WAM/encode.d.ts +0 -2
  202. package/lib/WAM/index.d.ts +0 -3
  203. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  204. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  205. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  206. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  207. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  208. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  209. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  210. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  211. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  212. package/lib/WAUSync/Protocols/index.js +0 -20
  213. package/lib/WAUSync/USyncQuery.d.ts +0 -26
  214. package/lib/WAUSync/USyncQuery.js +0 -79
  215. package/lib/WAUSync/USyncUser.d.ts +0 -10
  216. package/lib/WAUSync/USyncUser.js +0 -22
  217. package/lib/WAUSync/index.d.ts +0 -3
  218. package/lib/WAUSync/index.js +0 -19
  219. /package/{lib → src}/Defaults/phonenumber-mcc.json +0 -0
  220. /package/{lib → src}/Socket/Client/abstract-socket-client.js +0 -0
  221. /package/{lib → src}/Store/index.js +0 -0
  222. /package/{lib → src}/Store/make-ordered-dictionary.js +0 -0
  223. /package/{lib → src}/Types/Auth.js +0 -0
  224. /package/{lib → src}/Types/Call.js +0 -0
  225. /package/{lib → src}/Types/Chat.js +0 -0
  226. /package/{lib → src}/Types/Contact.js +0 -0
  227. /package/{lib → src}/Types/Events.js +0 -0
  228. /package/{lib → src}/Types/GroupMetadata.js +0 -0
  229. /package/{lib → src}/Types/Label.js +0 -0
  230. /package/{lib → src}/Types/LabelAssociation.js +0 -0
  231. /package/{lib → src}/Types/Message.js +0 -0
  232. /package/{lib → src}/Types/Newsletter.js +0 -0
  233. /package/{lib → src}/Types/Product.js +0 -0
  234. /package/{lib → src}/Types/Signal.js +0 -0
  235. /package/{lib → src}/Types/Socket.js +0 -0
  236. /package/{lib → src}/Types/State.js +0 -0
  237. /package/{lib → src}/Types/index.js +0 -0
  238. /package/{lib → src}/Utils/index.js +0 -0
  239. /package/{lib → src}/Utils/logger.js +0 -0
  240. /package/{lib → src}/Utils/lt-hash.js +0 -0
  241. /package/{lib → src}/Utils/noise-handler.js +0 -0
  242. /package/{lib → src}/WABinary/constants.js +0 -0
  243. /package/{lib → src}/WABinary/decode.js +0 -0
  244. /package/{lib → src}/WABinary/generic-utils.js +0 -0
  245. /package/{lib → src}/WABinary/index.js +0 -0
  246. /package/{lib → src}/WABinary/jid-utils.js +0 -0
  247. /package/{lib → src}/WABinary/types.js +0 -0
  248. /package/{lib → src}/WAM/BinaryInfo.js +0 -0
  249. /package/{lib → src}/WAM/constants.js +0 -0
  250. /package/{lib → src}/WAM/encode.js +0 -0
  251. /package/{lib → src}/WAM/index.js +0 -0
  252. /package/{lib → src}/gifted +0 -0
@@ -0,0 +1,777 @@
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'
6
+ import {
7
+ DEF_CALLBACK_PREFIX,
8
+ DEF_TAG_PREFIX,
9
+ INITIAL_PREKEY_COUNT,
10
+ MIN_PREKEY_COUNT,
11
+ MOBILE_ENDPOINT,
12
+ MOBILE_NOISE_HEADER,
13
+ MOBILE_PORT,
14
+ NOISE_WA_HEADER
15
+ } from '../Defaults'
16
+ import { DisconnectReason, SocketConfig } from '../Types'
17
+ import {
18
+ addTransactionCapability,
19
+ aesEncryptCTR,
20
+ bindWaitForConnectionUpdate,
21
+ bytesToCrockford,
22
+ configureSuccessfulPairing,
23
+ Curve,
24
+ derivePairingCodeKey,
25
+ generateLoginNode,
26
+ generateMdTagPrefix,
27
+ generateMobileNode,
28
+ generateRegistrationNode,
29
+ getCodeFromWSError,
30
+ getErrorCodeFromStreamError,
31
+ getNextPreKeysNode,
32
+ makeEventBuffer,
33
+ makeNoiseHandler,
34
+ printQRIfNecessaryListener,
35
+ promiseTimeout
36
+ } from '../Utils'
37
+ import {
38
+ assertNodeErrorFree,
39
+ BinaryNode,
40
+ binaryNodeToString,
41
+ encodeBinaryNode,
42
+ getBinaryNodeChild,
43
+ getBinaryNodeChildren,
44
+ jidEncode,
45
+ S_WHATSAPP_NET
46
+ } from '../WABinary'
47
+ import { MobileSocketClient, WebSocketClient } from './Client'
48
+
49
+ /**
50
+ * Connects to WA servers and performs:
51
+ * - simple queries (no retry mechanism, wait for connection establishment)
52
+ * - listen to messages and emit events
53
+ * - query phone connection
54
+ */
55
+
56
+ export const makeSocket = (config: SocketConfig) => {
57
+ const {
58
+ waWebSocketUrl,
59
+ connectTimeoutMs,
60
+ logger,
61
+ keepAliveIntervalMs,
62
+ browser,
63
+ auth: authState,
64
+ printQRInTerminal,
65
+ defaultQueryTimeoutMs,
66
+ transactionOpts,
67
+ qrTimeout,
68
+ makeSignalRepository,
69
+ } = config
70
+
71
+ let url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl
72
+
73
+ config.mobile = config.mobile || url.protocol === 'tcp:'
74
+
75
+ if(config.mobile && url.protocol !== 'tcp:') {
76
+ url = new URL(`tcp://${MOBILE_ENDPOINT}:${MOBILE_PORT}`)
77
+ }
78
+
79
+ if(!config.mobile && url.protocol === 'wss' && authState?.creds?.routingInfo) {
80
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
81
+ }
82
+
83
+ const ws = config.socket ? config.socket : config.mobile ? new MobileSocketClient(url, config) : new WebSocketClient(url, config)
84
+
85
+ ws.connect()
86
+
87
+ const ev = makeEventBuffer(logger)
88
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
89
+ const ephemeralKeyPair = Curve.generateKeyPair()
90
+ /** WA noise protocol wrapper */
91
+ const noise = makeNoiseHandler({
92
+ keyPair: ephemeralKeyPair,
93
+ NOISE_HEADER: config.mobile ? MOBILE_NOISE_HEADER : NOISE_WA_HEADER,
94
+ mobile: config.mobile,
95
+ logger,
96
+ routingInfo: authState?.creds?.routingInfo
97
+ })
98
+
99
+ const { creds } = authState
100
+ // add transaction capability
101
+ const keys = addTransactionCapability(authState.keys, logger, transactionOpts)
102
+ const signalRepository = makeSignalRepository({ creds, keys })
103
+
104
+ let lastDateRecv: Date
105
+ let epoch = 1
106
+ let keepAliveReq: NodeJS.Timeout
107
+ let qrTimer: NodeJS.Timeout
108
+ let closed = false
109
+
110
+ const uqTagId = generateMdTagPrefix()
111
+ const generateMessageTag = () => `${uqTagId}${epoch++}`
112
+
113
+ const sendPromise = promisify(ws.send)
114
+ /** send a raw buffer */
115
+ const sendRawMessage = async(data: Uint8Array | Buffer) => {
116
+ if(!ws.isOpen) {
117
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
118
+ }
119
+
120
+ const bytes = noise.encodeFrame(data)
121
+ await promiseTimeout<void>(
122
+ connectTimeoutMs,
123
+ async(resolve, reject) => {
124
+ try {
125
+ await sendPromise.call(ws, bytes)
126
+ resolve()
127
+ } catch(error) {
128
+ reject(error)
129
+ }
130
+ }
131
+ )
132
+ }
133
+
134
+ /** send a binary node */
135
+ const sendNode = (frame: BinaryNode) => {
136
+ if(logger.level === 'trace') {
137
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
138
+ }
139
+
140
+ const buff = encodeBinaryNode(frame)
141
+ return sendRawMessage(buff)
142
+ }
143
+
144
+ /** log & process any unexpected errors */
145
+ const onUnexpectedError = (err: Error | Boom, msg: string) => {
146
+ logger.error(
147
+ { err },
148
+ `unexpected error in '${msg}'`
149
+ )
150
+ }
151
+
152
+ /** await the next incoming message */
153
+ const awaitNextMessage = async<T>(sendMsg?: Uint8Array) => {
154
+ if(!ws.isOpen) {
155
+ throw new Boom('Connection Closed', {
156
+ statusCode: DisconnectReason.connectionClosed
157
+ })
158
+ }
159
+
160
+ let onOpen: (data: T) => void
161
+ let onClose: (err: Error) => void
162
+
163
+ const result = promiseTimeout<T>(connectTimeoutMs, (resolve, reject) => {
164
+ onOpen = resolve
165
+ onClose = mapWebSocketError(reject)
166
+ ws.on('frame', onOpen)
167
+ ws.on('close', onClose)
168
+ ws.on('error', onClose)
169
+ })
170
+ .finally(() => {
171
+ ws.off('frame', onOpen)
172
+ ws.off('close', onClose)
173
+ ws.off('error', onClose)
174
+ })
175
+
176
+ if(sendMsg) {
177
+ sendRawMessage(sendMsg).catch(onClose!)
178
+ }
179
+
180
+ return result
181
+ }
182
+
183
+ /**
184
+ * Wait for a message with a certain tag to be received
185
+ * @param msgId the message tag to await
186
+ * @param timeoutMs timeout after which the promise will reject
187
+ */
188
+ const waitForMessage = async<T>(msgId: string, timeoutMs = defaultQueryTimeoutMs) => {
189
+ let onRecv: (json) => void
190
+ let onErr: (err) => void
191
+ try {
192
+ return await promiseTimeout<T>(timeoutMs,
193
+ (resolve, reject) => {
194
+ onRecv = resolve
195
+ onErr = err => {
196
+ reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
197
+ }
198
+
199
+ ws.on(`TAG:${msgId}`, onRecv)
200
+ ws.on('close', onErr) // if the socket closes, you'll never receive the message
201
+ ws.off('error', onErr)
202
+ },
203
+ )
204
+ } finally {
205
+ ws.off(`TAG:${msgId}`, onRecv!)
206
+ ws.off('close', onErr!) // if the socket closes, you'll never receive the message
207
+ ws.off('error', onErr!)
208
+ }
209
+ }
210
+
211
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
212
+ const query = async(node: BinaryNode, timeoutMs?: number) => {
213
+ if(!node.attrs.id) {
214
+ node.attrs.id = generateMessageTag()
215
+ }
216
+
217
+ const msgId = node.attrs.id
218
+ const wait = waitForMessage(msgId, timeoutMs)
219
+
220
+ await sendNode(node)
221
+
222
+ const result = await (wait as Promise<BinaryNode>)
223
+ if('tag' in result) {
224
+ assertNodeErrorFree(result)
225
+ }
226
+
227
+ return result
228
+ }
229
+
230
+ /** connection handshake */
231
+ const validateConnection = async() => {
232
+ let helloMsg: proto.IHandshakeMessage = {
233
+ clientHello: { ephemeral: ephemeralKeyPair.public }
234
+ }
235
+ helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
236
+
237
+ logger.info({ browser, helloMsg }, 'connected to WA')
238
+
239
+ const init = proto.HandshakeMessage.encode(helloMsg).finish()
240
+
241
+ const result = await awaitNextMessage<Uint8Array>(init)
242
+ const handshake = proto.HandshakeMessage.decode(result)
243
+
244
+ logger.trace({ handshake }, 'handshake recv from WA')
245
+
246
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey)
247
+
248
+ let node: proto.IClientPayload
249
+ if(config.mobile) {
250
+ node = generateMobileNode(config)
251
+ } else if(!creds.me) {
252
+ node = generateRegistrationNode(creds, config)
253
+ logger.info({ node }, 'not logged in, attempting registration...')
254
+ } else {
255
+ node = generateLoginNode(creds.me.id, config)
256
+ logger.info({ node }, 'logging in...')
257
+ }
258
+
259
+ const payloadEnc = noise.encrypt(
260
+ proto.ClientPayload.encode(node).finish()
261
+ )
262
+ await sendRawMessage(
263
+ proto.HandshakeMessage.encode({
264
+ clientFinish: {
265
+ static: keyEnc,
266
+ payload: payloadEnc,
267
+ },
268
+ }).finish()
269
+ )
270
+ noise.finishInit()
271
+ startKeepAliveRequest()
272
+ }
273
+
274
+ const getAvailablePreKeysOnServer = async() => {
275
+ const result = await query({
276
+ tag: 'iq',
277
+ attrs: {
278
+ id: generateMessageTag(),
279
+ xmlns: 'encrypt',
280
+ type: 'get',
281
+ to: S_WHATSAPP_NET
282
+ },
283
+ content: [
284
+ { tag: 'count', attrs: {} }
285
+ ]
286
+ })
287
+ const countChild = getBinaryNodeChild(result, 'count')
288
+ return +countChild!.attrs.value
289
+ }
290
+
291
+ /** generates and uploads a set of pre-keys to the server */
292
+ const uploadPreKeys = async(count = INITIAL_PREKEY_COUNT) => {
293
+ await keys.transaction(
294
+ async() => {
295
+ logger.info({ count }, 'uploading pre-keys')
296
+ const { update, node } = await getNextPreKeysNode({ creds, keys }, count)
297
+
298
+ await query(node)
299
+ ev.emit('creds.update', update)
300
+
301
+ logger.info({ count }, 'uploaded pre-keys')
302
+ }
303
+ )
304
+ }
305
+
306
+ const uploadPreKeysToServerIfRequired = async() => {
307
+ const preKeyCount = await getAvailablePreKeysOnServer()
308
+ logger.info(`${preKeyCount} pre-keys found on server`)
309
+ if(preKeyCount <= MIN_PREKEY_COUNT) {
310
+ await uploadPreKeys()
311
+ }
312
+ }
313
+
314
+ const onMessageReceived = (data: Buffer) => {
315
+ noise.decodeFrame(data, frame => {
316
+ // reset ping timeout
317
+ lastDateRecv = new Date()
318
+
319
+ let anyTriggered = false
320
+
321
+ anyTriggered = ws.emit('frame', frame)
322
+ // if it's a binary node
323
+ if(!(frame instanceof Uint8Array)) {
324
+ const msgId = frame.attrs.id
325
+
326
+ if(logger.level === 'trace') {
327
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
328
+ }
329
+
330
+ /* Check if this is a response to a message we sent */
331
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
332
+ /* Check if this is a response to a message we are expecting */
333
+ const l0 = frame.tag
334
+ const l1 = frame.attrs || {}
335
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
336
+
337
+ Object.keys(l1).forEach(key => {
338
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
339
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
340
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
341
+ })
342
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
343
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
344
+
345
+ if(!anyTriggered && logger.level === 'debug') {
346
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
347
+ }
348
+ }
349
+ })
350
+ }
351
+
352
+ const end = (error: Error | undefined) => {
353
+ if(closed) {
354
+ logger.trace({ trace: error?.stack }, 'connection already closed')
355
+ return
356
+ }
357
+
358
+ closed = true
359
+ logger.info(
360
+ { trace: error?.stack },
361
+ error ? 'connection errored' : 'connection closed'
362
+ )
363
+
364
+ clearInterval(keepAliveReq)
365
+ clearTimeout(qrTimer)
366
+
367
+ ws.removeAllListeners('close')
368
+ ws.removeAllListeners('error')
369
+ ws.removeAllListeners('open')
370
+ ws.removeAllListeners('message')
371
+
372
+ if(!ws.isClosed && !ws.isClosing) {
373
+ try {
374
+ ws.close()
375
+ } catch{ }
376
+ }
377
+
378
+ ev.emit('connection.update', {
379
+ connection: 'close',
380
+ lastDisconnect: {
381
+ error,
382
+ date: new Date()
383
+ }
384
+ })
385
+ ev.removeAllListeners('connection.update')
386
+ }
387
+
388
+ const waitForSocketOpen = async() => {
389
+ if(ws.isOpen) {
390
+ return
391
+ }
392
+
393
+ if(ws.isClosed || ws.isClosing) {
394
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
395
+ }
396
+
397
+ let onOpen: () => void
398
+ let onClose: (err: Error) => void
399
+ await new Promise((resolve, reject) => {
400
+ onOpen = () => resolve(undefined)
401
+ onClose = mapWebSocketError(reject)
402
+ ws.on('open', onOpen)
403
+ ws.on('close', onClose)
404
+ ws.on('error', onClose)
405
+ })
406
+ .finally(() => {
407
+ ws.off('open', onOpen)
408
+ ws.off('close', onClose)
409
+ ws.off('error', onClose)
410
+ })
411
+ }
412
+
413
+ const startKeepAliveRequest = () => (
414
+ keepAliveReq = setInterval(() => {
415
+ if(!lastDateRecv) {
416
+ lastDateRecv = new Date()
417
+ }
418
+
419
+ const diff = Date.now() - lastDateRecv.getTime()
420
+ /*
421
+ check if it's been a suspicious amount of time since the server responded with our last seen
422
+ it could be that the network is down
423
+ */
424
+ if(diff > keepAliveIntervalMs + 5000) {
425
+ end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
426
+ } else if(ws.isOpen) {
427
+ // if its all good, send a keep alive request
428
+ query(
429
+ {
430
+ tag: 'iq',
431
+ attrs: {
432
+ id: generateMessageTag(),
433
+ to: S_WHATSAPP_NET,
434
+ type: 'get',
435
+ xmlns: 'w:p',
436
+ },
437
+ content: [{ tag: 'ping', attrs: {} }]
438
+ }
439
+ )
440
+ .catch(err => {
441
+ logger.error({ trace: err.stack }, 'error in sending keep alive')
442
+ })
443
+ } else {
444
+ logger.warn('keep alive called when WS not open')
445
+ }
446
+ }, keepAliveIntervalMs)
447
+ )
448
+ /** i have no idea why this exists. pls enlighten me */
449
+ const sendPassiveIq = (tag: 'passive' | 'active') => (
450
+ query({
451
+ tag: 'iq',
452
+ attrs: {
453
+ to: S_WHATSAPP_NET,
454
+ xmlns: 'passive',
455
+ type: 'set',
456
+ },
457
+ content: [
458
+ { tag, attrs: {} }
459
+ ]
460
+ })
461
+ )
462
+
463
+ /** logout & invalidate connection */
464
+ const logout = async(msg?: string) => {
465
+ const jid = authState.creds.me?.id
466
+ if(jid) {
467
+ await sendNode({
468
+ tag: 'iq',
469
+ attrs: {
470
+ to: S_WHATSAPP_NET,
471
+ type: 'set',
472
+ id: generateMessageTag(),
473
+ xmlns: 'md'
474
+ },
475
+ content: [
476
+ {
477
+ tag: 'remove-companion-device',
478
+ attrs: {
479
+ jid,
480
+ reason: 'user_initiated'
481
+ }
482
+ }
483
+ ]
484
+ })
485
+ }
486
+
487
+ end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }))
488
+ }
489
+
490
+ const requestPairingCode = async(phoneNumber: string): Promise<string> => {
491
+ authState.creds.pairingCode = bytesToCrockford(randomBytes(5))
492
+ authState.creds.me = {
493
+ id: jidEncode(phoneNumber, 's.whatsapp.net'),
494
+ name: '~'
495
+ }
496
+ ev.emit('creds.update', authState.creds)
497
+ await sendNode({
498
+ tag: 'iq',
499
+ attrs: {
500
+ to: S_WHATSAPP_NET,
501
+ type: 'set',
502
+ id: generateMessageTag(),
503
+ xmlns: 'md'
504
+ },
505
+ content: [
506
+ {
507
+ tag: 'link_code_companion_reg',
508
+ attrs: {
509
+ jid: authState.creds.me.id,
510
+ stage: 'companion_hello',
511
+ // eslint-disable-next-line camelcase
512
+ should_show_push_notification: 'true'
513
+ },
514
+ content: [
515
+ {
516
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
517
+ attrs: {},
518
+ content: await generatePairingKey()
519
+ },
520
+ {
521
+ tag: 'companion_server_auth_key_pub',
522
+ attrs: {},
523
+ content: authState.creds.noiseKey.public
524
+ },
525
+ {
526
+ tag: 'companion_platform_id',
527
+ attrs: {},
528
+ content: '49' // Chrome
529
+ },
530
+ {
531
+ tag: 'companion_platform_display',
532
+ attrs: {},
533
+ content: `${browser[1]} (${browser[0]})`
534
+ },
535
+ {
536
+ tag: 'link_code_pairing_nonce',
537
+ attrs: {},
538
+ content: '0'
539
+ }
540
+ ]
541
+ }
542
+ ]
543
+ })
544
+ return authState.creds.pairingCode
545
+ }
546
+
547
+ async function generatePairingKey() {
548
+ const salt = randomBytes(32)
549
+ const randomIv = randomBytes(16)
550
+ const key = derivePairingCodeKey(authState.creds.pairingCode!, salt)
551
+ const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
552
+ return Buffer.concat([salt, randomIv, ciphered])
553
+ }
554
+
555
+ const sendWAMBuffer = (wamBuffer: Buffer) => {
556
+ return query({
557
+ tag: 'iq',
558
+ attrs: {
559
+ to: S_WHATSAPP_NET,
560
+ id: generateMessageTag(),
561
+ xmlns: 'w:stats'
562
+ },
563
+ content: [
564
+ {
565
+ tag: 'add',
566
+ attrs: {},
567
+ content: wamBuffer
568
+ }
569
+ ]
570
+ })
571
+ }
572
+
573
+ ws.on('message', onMessageReceived)
574
+
575
+ ws.on('open', async() => {
576
+ try {
577
+ await validateConnection()
578
+ } catch(err) {
579
+ logger.error({ err }, 'error in validating connection')
580
+ end(err)
581
+ }
582
+ })
583
+ ws.on('error', mapWebSocketError(end))
584
+ ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
585
+ // the server terminated the connection
586
+ ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
587
+ // QR gen
588
+ ws.on('CB:iq,type:set,pair-device', async(stanza: BinaryNode) => {
589
+ const iq: BinaryNode = {
590
+ tag: 'iq',
591
+ attrs: {
592
+ to: S_WHATSAPP_NET,
593
+ type: 'result',
594
+ id: stanza.attrs.id,
595
+ }
596
+ }
597
+ await sendNode(iq)
598
+
599
+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device')
600
+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref')
601
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
602
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
603
+ const advB64 = creds.advSecretKey
604
+
605
+ let qrMs = qrTimeout || 60_000 // time to let a QR live
606
+ const genPairQR = () => {
607
+ if(!ws.isOpen) {
608
+ return
609
+ }
610
+
611
+ const refNode = refNodes.shift()
612
+ if(!refNode) {
613
+ end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
614
+ return
615
+ }
616
+
617
+ const ref = (refNode.content as Buffer).toString('utf-8')
618
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',')
619
+
620
+ ev.emit('connection.update', { qr })
621
+
622
+ qrTimer = setTimeout(genPairQR, qrMs)
623
+ qrMs = qrTimeout || 20_000 // shorter subsequent qrs
624
+ }
625
+
626
+ genPairQR()
627
+ })
628
+ // device paired for the first time
629
+ // if device pairs successfully, the server asks to restart the connection
630
+ ws.on('CB:iq,,pair-success', async(stanza: BinaryNode) => {
631
+ logger.debug('pair success recv')
632
+ try {
633
+ const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
634
+
635
+ logger.info(
636
+ { me: updatedCreds.me, platform: updatedCreds.platform },
637
+ 'pairing configured successfully, expect to restart the connection...'
638
+ )
639
+
640
+ ev.emit('creds.update', updatedCreds)
641
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined })
642
+
643
+ await sendNode(reply)
644
+ } catch(error) {
645
+ logger.info({ trace: error.stack }, 'error in pairing')
646
+ end(error)
647
+ }
648
+ })
649
+ // login complete
650
+ ws.on('CB:success', async(node: BinaryNode) => {
651
+ await uploadPreKeysToServerIfRequired()
652
+ await sendPassiveIq('active')
653
+
654
+ logger.info('opened connection to WA')
655
+ clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
656
+
657
+ ev.emit('creds.update', { me: { ...authState.creds.me!, lid: node.attrs.lid } })
658
+
659
+ ev.emit('connection.update', { connection: 'open' })
660
+ })
661
+
662
+ ws.on('CB:stream:error', (node: BinaryNode) => {
663
+ logger.error({ node }, 'stream errored out')
664
+
665
+ const { reason, statusCode } = getErrorCodeFromStreamError(node)
666
+
667
+ end(new Boom(`Stream Errored (${reason})`, { statusCode, data: node }))
668
+ })
669
+ // stream fail, possible logout
670
+ ws.on('CB:failure', (node: BinaryNode) => {
671
+ const reason = +(node.attrs.reason || 500)
672
+ end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
673
+ })
674
+
675
+ ws.on('CB:ib,,downgrade_webclient', () => {
676
+ end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }))
677
+ })
678
+
679
+ ws.on('CB:ib,,edge_routing', (node: BinaryNode) => {
680
+ const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
681
+ const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
682
+ if(routingInfo?.content) {
683
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content as Uint8Array)
684
+ }
685
+ })
686
+
687
+ let didStartBuffer = false
688
+ process.nextTick(() => {
689
+ if(creds.me?.id) {
690
+ // start buffering important events
691
+ // if we're logged in
692
+ ev.buffer()
693
+ didStartBuffer = true
694
+ }
695
+
696
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
697
+ })
698
+
699
+ // called when all offline notifs are handled
700
+ ws.on('CB:ib,,offline', (node: BinaryNode) => {
701
+ const child = getBinaryNodeChild(node, 'offline')
702
+ const offlineNotifs = +(child?.attrs.count || 0)
703
+
704
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`)
705
+ if(didStartBuffer) {
706
+ ev.flush()
707
+ logger.trace('flushed events for initial buffer')
708
+ }
709
+
710
+ ev.emit('connection.update', { receivedPendingNotifications: true })
711
+ })
712
+
713
+ // update credentials when required
714
+ ev.on('creds.update', update => {
715
+ const name = update.me?.name
716
+ // if name has just been received
717
+ if(creds.me?.name !== name) {
718
+ logger.debug({ name }, 'updated pushName')
719
+ sendNode({
720
+ tag: 'presence',
721
+ attrs: { name: name! }
722
+ })
723
+ .catch(err => {
724
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
725
+ })
726
+ }
727
+
728
+ Object.assign(creds, update)
729
+ })
730
+
731
+ if(printQRInTerminal) {
732
+ printQRIfNecessaryListener(ev, logger)
733
+ }
734
+
735
+ return {
736
+ type: 'md' as 'md',
737
+ ws,
738
+ ev,
739
+ authState: { creds, keys },
740
+ signalRepository,
741
+ get user() {
742
+ return authState.creds.me
743
+ },
744
+ generateMessageTag,
745
+ query,
746
+ waitForMessage,
747
+ waitForSocketOpen,
748
+ sendRawMessage,
749
+ sendNode,
750
+ logout,
751
+ end,
752
+ onUnexpectedError,
753
+ uploadPreKeys,
754
+ uploadPreKeysToServerIfRequired,
755
+ requestPairingCode,
756
+ /** Waits for the connection to WA to reach a state */
757
+ waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
758
+ sendWAMBuffer,
759
+ }
760
+ }
761
+
762
+ /**
763
+ * map the websocket error to the right type
764
+ * so it can be retried by the caller
765
+ * */
766
+ function mapWebSocketError(handler: (err: Error) => void) {
767
+ return (error: Error) => {
768
+ handler(
769
+ new Boom(
770
+ `WebSocket Error (${error?.message})`,
771
+ { statusCode: getCodeFromWSError(error), data: error }
772
+ )
773
+ )
774
+ }
775
+ }
776
+
777
+ export type Socket = ReturnType<typeof makeSocket>