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