supunmd-bail 2.0.1

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