violetics 7.0.0-alpha

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