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