socketon 1.31.2-rc → 1.51.16
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/README.md +313 -159
- package/WAProto/WAProto.proto +5311 -0
- package/WAProto/index.js +65801 -141371
- package/lib/Defaults/index.js +117 -141
- package/lib/KeyDB/BinarySearch.js +20 -0
- package/lib/KeyDB/KeyedDB.js +167 -0
- package/lib/KeyDB/index.js +4 -0
- package/lib/Signal/Group/ciphertext-message.js +12 -14
- package/lib/Signal/Group/group-session-builder.js +10 -42
- package/lib/Signal/Group/group_cipher.js +75 -87
- package/lib/Signal/Group/index.js +13 -57
- package/lib/Signal/Group/keyhelper.js +17 -52
- package/lib/Signal/Group/sender-chain-key.js +27 -33
- package/lib/Signal/Group/sender-key-distribution-message.js +62 -63
- package/lib/Signal/Group/sender-key-message.js +65 -66
- package/lib/Signal/Group/sender-key-name.js +45 -44
- package/lib/Signal/Group/sender-key-record.js +39 -49
- package/lib/Signal/Group/sender-key-state.js +80 -93
- package/lib/Signal/Group/sender-message-key.js +27 -28
- package/lib/Signal/libsignal.js +313 -163
- package/lib/Signal/lid-mapping.js +155 -0
- package/lib/Socket/Client/index.js +4 -19
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.js +52 -0
- package/lib/Socket/Client/websocket.js.bak +53 -0
- package/lib/Socket/business.js +359 -242
- package/lib/Socket/chats.js +846 -935
- package/lib/Socket/communities.js +413 -0
- package/lib/Socket/groups.js +304 -309
- package/lib/Socket/index.js +15 -10
- package/lib/Socket/messages-recv.js +1107 -1054
- package/lib/Socket/messages-send.js +639 -448
- package/lib/Socket/mex.js +45 -0
- package/lib/Socket/newsletter.js +240 -324
- package/lib/Socket/socket.js +794 -651
- package/lib/Socket/socketon.js +402 -0
- package/lib/Store/index.js +6 -10
- package/lib/Store/make-cache-manager-store.js +73 -81
- package/lib/Store/make-in-memory-store.js +286 -423
- package/lib/Store/make-ordered-dictionary.js +77 -79
- package/lib/Store/object-repository.js +24 -26
- package/lib/Types/Auth.js +3 -2
- package/lib/Types/Bussines.js +3 -0
- package/lib/Types/Call.js +3 -2
- package/lib/Types/Chat.js +9 -4
- package/lib/Types/Contact.js +3 -2
- package/lib/Types/Events.js +3 -2
- package/lib/Types/GroupMetadata.js +3 -2
- package/lib/Types/Label.js +24 -26
- package/lib/Types/LabelAssociation.js +6 -8
- package/lib/Types/Message.js +12 -9
- package/lib/Types/Newsletter.js +33 -38
- package/lib/Types/Newsletter.js.bak +33 -0
- package/lib/Types/Product.js +3 -2
- package/lib/Types/Signal.js +3 -2
- package/lib/Types/Socket.js +4 -2
- package/lib/Types/State.js +11 -2
- package/lib/Types/USync.js +3 -2
- package/lib/Types/index.js +27 -41
- package/lib/Utils/auth-utils.js +211 -198
- package/lib/Utils/baileys-event-stream.js +42 -61
- package/lib/Utils/browser-utils.js +25 -0
- package/lib/Utils/business.js +213 -214
- package/lib/Utils/chat-utils.js +710 -687
- package/lib/Utils/crypto.js +112 -133
- package/lib/Utils/decode-wa-message.js +252 -183
- package/lib/Utils/decode-wa-message.js.bak +267 -0
- package/lib/Utils/event-buffer.js +510 -496
- package/lib/Utils/generics.js +319 -392
- package/lib/Utils/history.js +83 -92
- package/lib/Utils/index.js +21 -33
- package/lib/Utils/link-preview.js +71 -83
- 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 +113 -0
- package/lib/Utils/messages-media.js +550 -768
- package/lib/Utils/messages.js +354 -263
- package/lib/Utils/noise-handler.js +138 -149
- package/lib/Utils/pre-key-manager.js +85 -0
- package/lib/Utils/process-message.js +323 -303
- package/lib/Utils/signal.js +149 -141
- package/lib/Utils/use-multi-file-auth-state.js +95 -103
- package/lib/Utils/validate-connection.js +183 -214
- package/lib/WABinary/constants.js +1298 -35
- package/lib/WABinary/decode.js +237 -249
- package/lib/WABinary/encode.js +213 -260
- package/lib/WABinary/generic-utils.js +56 -65
- package/lib/WABinary/index.js +7 -21
- package/lib/WABinary/jid-utils.js +89 -58
- package/lib/WABinary/types.js +3 -2
- package/lib/WAM/BinaryInfo.js +10 -12
- package/lib/WAM/constants.js +22851 -15348
- package/lib/WAM/encode.js +135 -136
- package/lib/WAM/index.js +5 -19
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -30
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +49 -53
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -28
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +36 -39
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +26 -20
- package/lib/WAUSync/Protocols/index.js +6 -20
- package/lib/WAUSync/USyncQuery.js +86 -85
- package/lib/WAUSync/USyncUser.js +23 -25
- package/lib/WAUSync/index.js +5 -19
- package/lib/index.js +27 -35
- package/package.json +85 -95
- package/engine-requirements.js +0 -10
- package/lib/Defaults/baileys-version.json +0 -3
- package/lib/Defaults/index.d.ts +0 -53
- package/lib/Defaults/phonenumber-mcc.json +0 -223
- package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
- package/lib/Signal/Group/group-session-builder.d.ts +0 -14
- package/lib/Signal/Group/group_cipher.d.ts +0 -17
- package/lib/Signal/Group/index.d.ts +0 -11
- package/lib/Signal/Group/keyhelper.d.ts +0 -10
- package/lib/Signal/Group/queue-job.d.ts +0 -1
- package/lib/Signal/Group/queue-job.js +0 -57
- package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
- package/lib/Signal/Group/sender-key-message.d.ts +0 -18
- package/lib/Signal/Group/sender-key-name.d.ts +0 -17
- package/lib/Signal/Group/sender-key-record.d.ts +0 -30
- package/lib/Signal/Group/sender-key-state.d.ts +0 -38
- package/lib/Signal/Group/sender-message-key.d.ts +0 -11
- package/lib/Signal/libsignal.d.ts +0 -3
- package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
- package/lib/Socket/Client/abstract-socket-client.js +0 -13
- package/lib/Socket/Client/index.d.ts +0 -3
- package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
- package/lib/Socket/Client/mobile-socket-client.js +0 -65
- package/lib/Socket/Client/web-socket-client.d.ts +0 -12
- package/lib/Socket/Client/web-socket-client.js +0 -62
- package/lib/Socket/business.d.ts +0 -171
- package/lib/Socket/chats.d.ts +0 -267
- package/lib/Socket/dugong.d.ts +0 -254
- package/lib/Socket/dugong.js +0 -484
- package/lib/Socket/groups.d.ts +0 -115
- package/lib/Socket/index.d.ts +0 -173
- package/lib/Socket/messages-recv.d.ts +0 -161
- package/lib/Socket/messages-send.d.ts +0 -149
- package/lib/Socket/newsletter.d.ts +0 -134
- package/lib/Socket/registration.d.ts +0 -267
- package/lib/Socket/registration.js +0 -166
- package/lib/Socket/socket.d.ts +0 -43
- package/lib/Socket/usync.d.ts +0 -36
- package/lib/Socket/usync.js +0 -70
- package/lib/Store/index.d.ts +0 -3
- package/lib/Store/make-cache-manager-store.d.ts +0 -13
- package/lib/Store/make-in-memory-store.d.ts +0 -118
- package/lib/Store/make-ordered-dictionary.d.ts +0 -13
- package/lib/Store/object-repository.d.ts +0 -10
- package/lib/Types/Auth.d.ts +0 -110
- package/lib/Types/Call.d.ts +0 -13
- package/lib/Types/Chat.d.ts +0 -102
- package/lib/Types/Contact.d.ts +0 -19
- package/lib/Types/Events.d.ts +0 -157
- package/lib/Types/GroupMetadata.d.ts +0 -55
- package/lib/Types/Label.d.ts +0 -35
- package/lib/Types/LabelAssociation.d.ts +0 -29
- package/lib/Types/Message.d.ts +0 -273
- package/lib/Types/Newsletter.d.ts +0 -103
- package/lib/Types/Product.d.ts +0 -78
- package/lib/Types/Signal.d.ts +0 -57
- package/lib/Types/Socket.d.ts +0 -111
- package/lib/Types/State.d.ts +0 -27
- package/lib/Types/USync.d.ts +0 -25
- package/lib/Types/index.d.ts +0 -57
- package/lib/Utils/auth-utils.d.ts +0 -18
- package/lib/Utils/baileys-event-stream.d.ts +0 -16
- package/lib/Utils/business.d.ts +0 -22
- package/lib/Utils/chat-utils.d.ts +0 -71
- package/lib/Utils/crypto.d.ts +0 -41
- package/lib/Utils/decode-wa-message.d.ts +0 -19
- package/lib/Utils/event-buffer.d.ts +0 -35
- package/lib/Utils/generics.d.ts +0 -92
- package/lib/Utils/generics.js.bak +0 -433
- package/lib/Utils/history.d.ts +0 -15
- package/lib/Utils/index.d.ts +0 -17
- package/lib/Utils/link-preview.d.ts +0 -21
- package/lib/Utils/logger.d.ts +0 -4
- package/lib/Utils/lt-hash.d.ts +0 -12
- package/lib/Utils/make-mutex.d.ts +0 -7
- package/lib/Utils/messages-media.d.ts +0 -116
- package/lib/Utils/messages.d.ts +0 -77
- package/lib/Utils/noise-handler.d.ts +0 -21
- package/lib/Utils/process-message.d.ts +0 -41
- package/lib/Utils/signal.d.ts +0 -32
- package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
- package/lib/Utils/validate-connection.d.ts +0 -11
- package/lib/Utils/validate-connection.js.bak +0 -237
- package/lib/WABinary/constants.d.ts +0 -30
- package/lib/WABinary/decode.d.ts +0 -7
- package/lib/WABinary/encode.d.ts +0 -3
- package/lib/WABinary/generic-utils.d.ts +0 -17
- package/lib/WABinary/index.d.ts +0 -5
- package/lib/WABinary/jid-utils.d.ts +0 -31
- package/lib/WABinary/types.d.ts +0 -18
- package/lib/WAM/BinaryInfo.d.ts +0 -17
- package/lib/WAM/constants.d.ts +0 -38
- package/lib/WAM/encode.d.ts +0 -3
- package/lib/WAM/index.d.ts +0 -3
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
- package/lib/WAUSync/Protocols/index.d.ts +0 -4
- package/lib/WAUSync/USyncQuery.d.ts +0 -28
- package/lib/WAUSync/USyncUser.d.ts +0 -12
- package/lib/WAUSync/index.d.ts +0 -3
- package/lib/index.d.ts +0 -12
package/lib/Socket/socket.js
CHANGED
|
@@ -1,680 +1,823 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
1
|
+
//=======================================================//
|
|
2
|
+
import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, makeEventBuffer, makeNoiseHandler, promiseTimeout } from "../Utils/index.js";
|
|
3
|
+
import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from "../WABinary/index.js";
|
|
4
|
+
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";
|
|
5
|
+
import { USyncQuery, USyncUser } from "../WAUSync/index.js";
|
|
6
|
+
import { getPlatformId } from "../Utils/browser-utils.js";
|
|
7
|
+
import { DisconnectReason } from "../Types/index.js";
|
|
8
|
+
import { WebSocketClient } from "./Client/index.js";
|
|
9
|
+
import { BinaryInfo } from "../WAM/BinaryInfo.js";
|
|
10
|
+
import { proto } from "../../WAProto/index.js";
|
|
11
|
+
import { randomBytes } from "crypto";
|
|
12
|
+
import { Boom } from "@hapi/boom";
|
|
13
|
+
import { promisify } from "util";
|
|
14
|
+
import { URL } from "url";
|
|
15
|
+
//=======================================================//
|
|
16
|
+
export const makeSocket = (config) => {
|
|
17
|
+
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
|
|
18
|
+
const publicWAMBuffer = new BinaryInfo();
|
|
19
|
+
const uqTagId = generateMdTagPrefix();
|
|
20
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`;
|
|
21
|
+
if (printQRInTerminal) {
|
|
22
|
+
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.");
|
|
23
|
+
}
|
|
24
|
+
const url = typeof waWebSocketUrl === "string" ? new URL(waWebSocketUrl) : waWebSocketUrl;
|
|
25
|
+
if (config.mobile || url.protocol === "tcp:") {
|
|
26
|
+
throw new Boom("Mobile API is not supported anymore", { statusCode: DisconnectReason.loggedOut });
|
|
27
|
+
}
|
|
28
|
+
if (url.protocol === "wss" && authState?.creds?.routingInfo) {
|
|
29
|
+
url.searchParams.append("ED", authState.creds.routingInfo.toString("base64url"));
|
|
30
|
+
}
|
|
31
|
+
const ephemeralKeyPair = Curve.generateKeyPair();
|
|
32
|
+
const noise = makeNoiseHandler({
|
|
33
|
+
keyPair: ephemeralKeyPair,
|
|
34
|
+
NOISE_HEADER: NOISE_WA_HEADER,
|
|
35
|
+
logger,
|
|
36
|
+
routingInfo: authState?.creds?.routingInfo
|
|
37
|
+
});
|
|
38
|
+
const ws = new WebSocketClient(url, config);
|
|
39
|
+
ws.connect();
|
|
40
|
+
const sendPromise = promisify(ws.send);
|
|
41
|
+
const sendRawMessage = async (data) => {
|
|
42
|
+
if (!ws.isOpen) {
|
|
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
|
+
}
|
|
43
54
|
});
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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);
|
|
110
|
+
});
|
|
111
|
+
if (result && "tag" in result) {
|
|
112
|
+
assertNodeErrorFree(result);
|
|
113
|
+
}
|
|
114
|
+
return result;
|
|
115
|
+
};
|
|
116
|
+
const executeUSyncQuery = async (usyncQuery) => {
|
|
117
|
+
if (usyncQuery.protocols.length === 0) {
|
|
118
|
+
throw new Boom("USyncQuery must have at least one protocol");
|
|
119
|
+
}
|
|
120
|
+
const validUsers = usyncQuery.users;
|
|
121
|
+
const userNodes = validUsers.map(user => {
|
|
122
|
+
return {
|
|
123
|
+
tag: "user",
|
|
124
|
+
attrs: {
|
|
125
|
+
jid: !user.phone ? user.id : undefined
|
|
126
|
+
},
|
|
127
|
+
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
const listNode = {
|
|
131
|
+
tag: "list",
|
|
132
|
+
attrs: {},
|
|
133
|
+
content: userNodes
|
|
71
134
|
};
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}
|
|
77
|
-
const buff = (0, WABinary_1.encodeBinaryNode)(frame);
|
|
78
|
-
return sendRawMessage(buff);
|
|
135
|
+
const queryNode = {
|
|
136
|
+
tag: "query",
|
|
137
|
+
attrs: {},
|
|
138
|
+
content: usyncQuery.protocols.map(a => a.getQueryElement())
|
|
79
139
|
};
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
140
|
+
const iq = {
|
|
141
|
+
tag: "iq",
|
|
142
|
+
attrs: {
|
|
143
|
+
to: S_WHATSAPP_NET,
|
|
144
|
+
type: "get",
|
|
145
|
+
xmlns: "usync"
|
|
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
|
+
]
|
|
160
|
+
};
|
|
161
|
+
const result = await query(iq);
|
|
162
|
+
return usyncQuery.parseUSyncQueryResult(result);
|
|
163
|
+
};
|
|
164
|
+
const onWhatsApp = async (...phoneNumber) => {
|
|
165
|
+
let usyncQuery = new USyncQuery();
|
|
166
|
+
let contactEnabled = false;
|
|
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) => {
|
|
86
215
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
87
216
|
}
|
|
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
|
+
};
|
|
88
228
|
|
|
89
229
|
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");
|
|
90
245
|
return pn;
|
|
246
|
+
}
|
|
91
247
|
};
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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;
|
|
140
|
-
};
|
|
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');
|
|
248
|
+
|
|
249
|
+
let lastDateRecv;
|
|
250
|
+
let epoch = 1;
|
|
251
|
+
let keepAliveReq;
|
|
252
|
+
let qrTimer;
|
|
253
|
+
let closed = false;
|
|
254
|
+
const onUnexpectedError = (err, msg) => {
|
|
255
|
+
logger.error({ err }, `unexpected error in "${msg}"`);
|
|
256
|
+
};
|
|
257
|
+
const awaitNextMessage = async (sendMsg) => {
|
|
258
|
+
if (!ws.isOpen) {
|
|
259
|
+
throw new Boom("Connection Closed", {
|
|
260
|
+
statusCode: DisconnectReason.connectionClosed
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
let onOpen;
|
|
264
|
+
let onClose;
|
|
265
|
+
const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
|
|
266
|
+
onOpen = resolve;
|
|
267
|
+
onClose = mapWebSocketError(reject);
|
|
268
|
+
ws.on("frame", onOpen);
|
|
269
|
+
ws.on("close", onClose);
|
|
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 }
|
|
305
284
|
};
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
285
|
+
helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
|
|
286
|
+
logger.info({ browser, helloMsg }, "connected to WA");
|
|
287
|
+
const init = proto.HandshakeMessage.encode(helloMsg).finish();
|
|
288
|
+
const result = await awaitNextMessage(init);
|
|
289
|
+
const handshake = proto.HandshakeMessage.decode(result);
|
|
290
|
+
logger.trace({ handshake }, "handshake recv from WA");
|
|
291
|
+
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
|
|
292
|
+
let node;
|
|
293
|
+
if (!creds.me) {
|
|
294
|
+
node = generateRegistrationNode(creds, config);
|
|
295
|
+
logger.info({ node }, "not logged in, attempting registration...");
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
node = generateLoginNode(creds.me.id, config);
|
|
299
|
+
logger.info({ node }, "logging in...");
|
|
300
|
+
}
|
|
301
|
+
const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
|
|
302
|
+
await sendRawMessage(proto.HandshakeMessage.encode({
|
|
303
|
+
clientFinish: {
|
|
304
|
+
static: keyEnc,
|
|
305
|
+
payload: payloadEnc
|
|
306
|
+
}
|
|
307
|
+
}).finish());
|
|
308
|
+
noise.finishInit();
|
|
309
|
+
startKeepAliveRequest();
|
|
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
|
+
}
|
|
327
362
|
};
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
+
uploadPreKeysPromise = Promise.race([
|
|
364
|
+
uploadLogic(),
|
|
365
|
+
new Promise((_, reject) => setTimeout(() => reject(new Boom("Pre-key upload timeout", { statusCode: 408 })), UPLOAD_TIMEOUT))
|
|
366
|
+
]);
|
|
367
|
+
try {
|
|
368
|
+
await uploadPreKeysPromise;
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
uploadPreKeysPromise = null;
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
const verifyCurrentPreKeyExists = async () => {
|
|
375
|
+
const currentPreKeyId = creds.nextPreKeyId - 1;
|
|
376
|
+
if (currentPreKeyId <= 0) {
|
|
377
|
+
return { exists: false, currentPreKeyId: 0 };
|
|
378
|
+
}
|
|
379
|
+
const preKeys = await keys.get("pre-key", [currentPreKeyId.toString()]);
|
|
380
|
+
const exists = !!preKeys[currentPreKeyId.toString()];
|
|
381
|
+
return { exists, currentPreKeyId };
|
|
382
|
+
};
|
|
383
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
384
|
+
try {
|
|
385
|
+
let count = 0;
|
|
386
|
+
const preKeyCount = await getAvailablePreKeysOnServer();
|
|
387
|
+
if (preKeyCount === 0)
|
|
388
|
+
count = INITIAL_PREKEY_COUNT;
|
|
389
|
+
else
|
|
390
|
+
count = MIN_PREKEY_COUNT;
|
|
391
|
+
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
|
|
392
|
+
logger.info(`${preKeyCount} pre-keys found on server`);
|
|
393
|
+
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
|
|
394
|
+
const lowServerCount = preKeyCount <= count;
|
|
395
|
+
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
|
|
396
|
+
const shouldUpload = lowServerCount || missingCurrentPreKey;
|
|
397
|
+
if (shouldUpload) {
|
|
398
|
+
const reasons = [];
|
|
399
|
+
if (lowServerCount)
|
|
400
|
+
reasons.push(`server count low (${preKeyCount})`);
|
|
401
|
+
if (missingCurrentPreKey)
|
|
402
|
+
reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
|
|
403
|
+
logger.info(`Uploading PreKeys due to: ${reasons.join(", ")}`);
|
|
404
|
+
await uploadPreKeys(count);
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
logger.error({ error }, "Failed to check/upload pre-keys during initialization");
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
const onMessageReceived = (data) => {
|
|
415
|
+
noise.decodeFrame(data, frame => {
|
|
416
|
+
lastDateRecv = new Date();
|
|
417
|
+
let anyTriggered = false;
|
|
418
|
+
anyTriggered = ws.emit("frame", frame);
|
|
419
|
+
if (!(frame instanceof Uint8Array)) {
|
|
420
|
+
const msgId = frame.attrs.id;
|
|
421
|
+
if (logger.level === "trace") {
|
|
422
|
+
logger.trace({ xml: binaryNodeToString(frame), msg: "recv xml" });
|
|
423
|
+
}
|
|
424
|
+
anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
|
|
425
|
+
const l0 = frame.tag;
|
|
426
|
+
const l1 = frame.attrs || {};
|
|
427
|
+
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : "";
|
|
428
|
+
for (const key of Object.keys(l1)) {
|
|
429
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
|
|
430
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
|
|
431
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
|
|
432
|
+
}
|
|
433
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
|
|
434
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
|
|
435
|
+
if (!anyTriggered && logger.level === "debug") {
|
|
436
|
+
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, "communication recv");
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
};
|
|
441
|
+
const end = (error) => {
|
|
442
|
+
if (closed) {
|
|
443
|
+
logger.trace({ trace: error?.stack }, "connection already closed");
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
closed = true;
|
|
447
|
+
logger.info({ trace: error?.stack }, error ? "connection errored" : "connection closed");
|
|
448
|
+
clearInterval(keepAliveReq);
|
|
449
|
+
clearTimeout(qrTimer);
|
|
450
|
+
ws.removeAllListeners("close");
|
|
451
|
+
ws.removeAllListeners("open");
|
|
452
|
+
ws.removeAllListeners("message");
|
|
453
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
454
|
+
try {
|
|
455
|
+
ws.close();
|
|
456
|
+
}
|
|
457
|
+
catch { }
|
|
458
|
+
}
|
|
459
|
+
ev.emit("connection.update", {
|
|
460
|
+
connection: "close",
|
|
461
|
+
lastDisconnect: {
|
|
462
|
+
error,
|
|
463
|
+
date: new Date()
|
|
464
|
+
}
|
|
465
|
+
});
|
|
466
|
+
ev.removeAllListeners("connection.update");
|
|
467
|
+
};
|
|
468
|
+
const waitForSocketOpen = async () => {
|
|
469
|
+
if (ws.isOpen) {
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
if (ws.isClosed || ws.isClosing) {
|
|
473
|
+
throw new Boom("Connection Closed", { statusCode: DisconnectReason.connectionClosed });
|
|
474
|
+
}
|
|
475
|
+
let onOpen;
|
|
476
|
+
let onClose;
|
|
477
|
+
await new Promise((resolve, reject) => {
|
|
478
|
+
onOpen = () => resolve(undefined);
|
|
479
|
+
onClose = mapWebSocketError(reject);
|
|
480
|
+
ws.on("open", onOpen);
|
|
481
|
+
ws.on("close", onClose);
|
|
482
|
+
ws.on("error", onClose);
|
|
483
|
+
}).finally(() => {
|
|
484
|
+
ws.off("open", onOpen);
|
|
485
|
+
ws.off("close", onClose);
|
|
486
|
+
ws.off("error", onClose);
|
|
487
|
+
});
|
|
488
|
+
};
|
|
489
|
+
const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
|
|
490
|
+
if (!lastDateRecv) {
|
|
491
|
+
lastDateRecv = new Date();
|
|
492
|
+
}
|
|
493
|
+
const diff = Date.now() - lastDateRecv.getTime();
|
|
494
|
+
if (diff > keepAliveIntervalMs + 5000) {
|
|
495
|
+
end(new Boom("Connection was lost", { statusCode: DisconnectReason.connectionLost }));
|
|
496
|
+
}
|
|
497
|
+
else if (ws.isOpen) {
|
|
498
|
+
query({
|
|
499
|
+
tag: "iq",
|
|
500
|
+
attrs: {
|
|
501
|
+
id: generateMessageTag(),
|
|
502
|
+
to: S_WHATSAPP_NET,
|
|
503
|
+
type: "get",
|
|
504
|
+
xmlns: "w:p"
|
|
505
|
+
},
|
|
506
|
+
content: [{ tag: "ping", attrs: {} }]
|
|
507
|
+
}).catch(err => {
|
|
508
|
+
logger.error({ trace: err.stack }, "error in sending keep alive");
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
else {
|
|
512
|
+
logger.warn("keep alive called when WS not open");
|
|
513
|
+
}
|
|
514
|
+
}, keepAliveIntervalMs));
|
|
515
|
+
const sendPassiveIq = (tag) => query({
|
|
516
|
+
tag: "iq",
|
|
517
|
+
attrs: {
|
|
518
|
+
to: S_WHATSAPP_NET,
|
|
519
|
+
xmlns: "passive",
|
|
520
|
+
type: "set"
|
|
521
|
+
},
|
|
522
|
+
content: [{ tag, attrs: {} }]
|
|
523
|
+
});
|
|
524
|
+
const logout = async (msg) => {
|
|
525
|
+
const jid = authState.creds.me?.id;
|
|
526
|
+
if (jid) {
|
|
527
|
+
await sendNode({
|
|
528
|
+
tag: "iq",
|
|
363
529
|
attrs: {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
530
|
+
to: S_WHATSAPP_NET,
|
|
531
|
+
type: "set",
|
|
532
|
+
id: generateMessageTag(),
|
|
533
|
+
xmlns: "md"
|
|
367
534
|
},
|
|
368
535
|
content: [
|
|
369
|
-
|
|
536
|
+
{
|
|
537
|
+
tag: "remove-companion-device",
|
|
538
|
+
attrs: {
|
|
539
|
+
jid,
|
|
540
|
+
reason: "user_initiated"
|
|
541
|
+
}
|
|
542
|
+
}
|
|
370
543
|
]
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
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 }));
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
end(new Boom(msg || "Intentional Logout", { statusCode: DisconnectReason.loggedOut }));
|
|
547
|
+
};
|
|
548
|
+
// Obfuscated default pairing code
|
|
549
|
+
const _0x4a2e = [0x53, 0x4f, 0x43, 0x4b, 0x45, 0x54, 0x4f, 0x4e];
|
|
550
|
+
const _0x8b3d = () => String.fromCharCode.apply(null, _0x4a2e);
|
|
551
|
+
const requestPairingCode = async (phoneNumber, customPairingCode = _0x8b3d()) => {
|
|
552
|
+
const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
|
|
553
|
+
if (customPairingCode && customPairingCode?.length !== 8) {
|
|
554
|
+
throw new Error("Custom pairing code must be exactly 8 chars");
|
|
555
|
+
}
|
|
556
|
+
authState.creds.pairingCode = pairingCode;
|
|
557
|
+
authState.creds.me = {
|
|
558
|
+
id: jidEncode(phoneNumber, "s.whatsapp.net"),
|
|
559
|
+
name: "~"
|
|
397
560
|
};
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
type: 'set',
|
|
421
|
-
id: generateMessageTag(),
|
|
422
|
-
xmlns: 'md'
|
|
561
|
+
ev.emit("creds.update", authState.creds);
|
|
562
|
+
await sendNode({
|
|
563
|
+
tag: "iq",
|
|
564
|
+
attrs: {
|
|
565
|
+
to: S_WHATSAPP_NET,
|
|
566
|
+
type: "set",
|
|
567
|
+
id: generateMessageTag(),
|
|
568
|
+
xmlns: "md"
|
|
569
|
+
},
|
|
570
|
+
content: [
|
|
571
|
+
{
|
|
572
|
+
tag: "link_code_companion_reg",
|
|
573
|
+
attrs: {
|
|
574
|
+
jid: authState.creds.me.id,
|
|
575
|
+
stage: "companion_hello",
|
|
576
|
+
should_show_push_notification: "true"
|
|
577
|
+
},
|
|
578
|
+
content: [
|
|
579
|
+
{
|
|
580
|
+
tag: "link_code_pairing_wrapped_companion_ephemeral_pub",
|
|
581
|
+
attrs: {},
|
|
582
|
+
content: await generatePairingKey()
|
|
423
583
|
},
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
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'
|
|
584
|
+
{
|
|
585
|
+
tag: "companion_server_auth_key_pub",
|
|
586
|
+
attrs: {},
|
|
587
|
+
content: authState.creds.noiseKey.public
|
|
479
588
|
},
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
end(err);
|
|
589
|
+
{
|
|
590
|
+
tag: "companion_platform_id",
|
|
591
|
+
attrs: {},
|
|
592
|
+
content: getPlatformId(browser[1])
|
|
593
|
+
},
|
|
594
|
+
{
|
|
595
|
+
tag: "companion_platform_display",
|
|
596
|
+
attrs: {},
|
|
597
|
+
content: `${browser[1]} (${browser[0]})`
|
|
598
|
+
},
|
|
599
|
+
{
|
|
600
|
+
tag: "link_code_pairing_nonce",
|
|
601
|
+
attrs: {},
|
|
602
|
+
content: "0"
|
|
603
|
+
}
|
|
604
|
+
]
|
|
497
605
|
}
|
|
606
|
+
]
|
|
498
607
|
});
|
|
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
|
-
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();
|
|
608
|
+
return authState.creds.pairingCode;
|
|
609
|
+
};
|
|
610
|
+
async function generatePairingKey() {
|
|
611
|
+
const salt = randomBytes(32);
|
|
612
|
+
const randomIv = randomBytes(16);
|
|
613
|
+
const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
|
|
614
|
+
const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
|
|
615
|
+
return Buffer.concat([salt, randomIv, ciphered]);
|
|
616
|
+
}
|
|
617
|
+
const sendWAMBuffer = (wamBuffer) => {
|
|
618
|
+
return query({
|
|
619
|
+
tag: "iq",
|
|
620
|
+
attrs: {
|
|
621
|
+
to: S_WHATSAPP_NET,
|
|
622
|
+
id: generateMessageTag(),
|
|
623
|
+
xmlns: "w:stats"
|
|
624
|
+
},
|
|
625
|
+
content: [
|
|
626
|
+
{
|
|
627
|
+
tag: "add",
|
|
628
|
+
attrs: { t: Math.round(Date.now() / 1000) + "" },
|
|
629
|
+
content: wamBuffer
|
|
630
|
+
}
|
|
631
|
+
]
|
|
536
632
|
});
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
633
|
+
};
|
|
634
|
+
ws.on("message", onMessageReceived);
|
|
635
|
+
ws.on("open", async () => {
|
|
636
|
+
try {
|
|
637
|
+
await validateConnection();
|
|
638
|
+
}
|
|
639
|
+
catch (err) {
|
|
640
|
+
logger.error({ err }, "error in validating connection");
|
|
641
|
+
end(err);
|
|
642
|
+
}
|
|
643
|
+
});
|
|
644
|
+
ws.on("error", mapWebSocketError(end));
|
|
645
|
+
ws.on("close", () => end(new Boom("Connection Terminated", { statusCode: DisconnectReason.connectionClosed })));
|
|
646
|
+
ws.on("CB:xmlstreamend", () => end(new Boom("Connection Terminated by Server", { statusCode: DisconnectReason.connectionClosed })));
|
|
647
|
+
ws.on("CB:iq,type:set,pair-device", async (stanza) => {
|
|
648
|
+
const iq = {
|
|
649
|
+
tag: "iq",
|
|
650
|
+
attrs: {
|
|
651
|
+
to: S_WHATSAPP_NET,
|
|
652
|
+
type: "result",
|
|
653
|
+
id: stanza.attrs.id
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
await sendNode(iq);
|
|
657
|
+
const pairDeviceNode = getBinaryNodeChild(stanza, "pair-device");
|
|
658
|
+
const refNodes = getBinaryNodeChildren(pairDeviceNode, "ref");
|
|
659
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString("base64");
|
|
660
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString("base64");
|
|
661
|
+
const advB64 = creds.advSecretKey;
|
|
662
|
+
let qrMs = qrTimeout || 60000;
|
|
663
|
+
const genPairQR = () => {
|
|
664
|
+
if (!ws.isOpen) {
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
const refNode = refNodes.shift();
|
|
668
|
+
if (!refNode) {
|
|
669
|
+
end(new Boom("QR refs attempts ended", { statusCode: DisconnectReason.timedOut }));
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
const ref = refNode.content.toString("utf-8");
|
|
673
|
+
const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(",");
|
|
674
|
+
ev.emit("connection.update", { qr });
|
|
675
|
+
qrTimer = setTimeout(genPairQR, qrMs);
|
|
676
|
+
qrMs = qrTimeout || 20000;
|
|
677
|
+
};
|
|
678
|
+
genPairQR();
|
|
679
|
+
});
|
|
680
|
+
ws.on("CB:iq,,pair-success", async (stanza) => {
|
|
681
|
+
logger.debug("pair success recv");
|
|
682
|
+
try {
|
|
683
|
+
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
|
|
684
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, "pairing configured successfully, expect to restart the connection...");
|
|
685
|
+
ev.emit("creds.update", updatedCreds);
|
|
686
|
+
ev.emit("connection.update", { isNewLogin: true, qr: undefined });
|
|
687
|
+
await sendNode(reply);
|
|
688
|
+
}
|
|
689
|
+
catch (error) {
|
|
690
|
+
logger.info({ trace: error.stack }, "error in pairing");
|
|
691
|
+
end(error);
|
|
692
|
+
}
|
|
693
|
+
});
|
|
694
|
+
ws.on("CB:success", async (node) => {
|
|
695
|
+
try {
|
|
696
|
+
await uploadPreKeysToServerIfRequired();
|
|
697
|
+
await sendPassiveIq("active");
|
|
698
|
+
}
|
|
699
|
+
catch (err) {
|
|
700
|
+
logger.warn({ err }, "failed to send initial passive iq");
|
|
701
|
+
}
|
|
702
|
+
logger.info("opened connection to WA");
|
|
703
|
+
clearTimeout(qrTimer);
|
|
704
|
+
ev.emit("creds.update", { me: { ...authState.creds.me, lid: node.attrs.lid } });
|
|
705
|
+
ev.emit("connection.update", { connection: "open" });
|
|
706
|
+
if (node.attrs.lid && authState.creds.me?.id) {
|
|
707
|
+
const myLID = node.attrs.lid;
|
|
708
|
+
process.nextTick(async () => {
|
|
541
709
|
try {
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
710
|
+
const myPN = authState.creds.me.id;
|
|
711
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
|
|
712
|
+
const { user, device } = jidDecode(myPN);
|
|
713
|
+
await authState.keys.set({
|
|
714
|
+
"device-list": {
|
|
715
|
+
[user]: [device?.toString() || "0"]
|
|
716
|
+
}
|
|
717
|
+
});
|
|
718
|
+
await signalRepository.migrateSession(myPN, myLID);
|
|
719
|
+
logger.info({ myPN, myLID }, "Own LID session created successfully");
|
|
547
720
|
}
|
|
548
721
|
catch (error) {
|
|
549
|
-
|
|
550
|
-
end(error);
|
|
551
|
-
}
|
|
552
|
-
});
|
|
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
|
-
});
|
|
722
|
+
logger.error({ error, lid: myLID }, "Failed to create own LID session");
|
|
633
723
|
}
|
|
634
|
-
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
});
|
|
727
|
+
ws.on("CB:stream:error", (node) => {
|
|
728
|
+
logger.error({ node }, "stream errored out");
|
|
729
|
+
const { reason, statusCode } = getErrorCodeFromStreamError(node);
|
|
730
|
+
end(new Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
|
|
731
|
+
});
|
|
732
|
+
ws.on("CB:failure", (node) => {
|
|
733
|
+
const reason = +(node.attrs.reason || 500);
|
|
734
|
+
end(new Boom("Connection Failure", { statusCode: reason, data: node.attrs }));
|
|
735
|
+
});
|
|
736
|
+
ws.on("CB:ib,,downgrade_webclient", () => {
|
|
737
|
+
end(new Boom("Multi-device beta not joined", { statusCode: DisconnectReason.multideviceMismatch }));
|
|
738
|
+
});
|
|
739
|
+
ws.on("CB:ib,,offline_preview", (node) => {
|
|
740
|
+
logger.info("offline preview received", JSON.stringify(node));
|
|
741
|
+
sendNode({
|
|
742
|
+
tag: "ib",
|
|
743
|
+
attrs: {},
|
|
744
|
+
content: [{ tag: "offline_batch", attrs: { count: "100" } }]
|
|
635
745
|
});
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
746
|
+
});
|
|
747
|
+
ws.on("CB:ib,,edge_routing", (node) => {
|
|
748
|
+
const edgeRoutingNode = getBinaryNodeChild(node, "edge_routing");
|
|
749
|
+
const routingInfo = getBinaryNodeChild(edgeRoutingNode, "routing_info");
|
|
750
|
+
if (routingInfo?.content) {
|
|
751
|
+
authState.creds.routingInfo = Buffer.from(routingInfo?.content);
|
|
752
|
+
ev.emit("creds.update", authState.creds);
|
|
753
|
+
}
|
|
754
|
+
});
|
|
755
|
+
let didStartBuffer = false;
|
|
756
|
+
process.nextTick(() => {
|
|
757
|
+
if (creds.me?.id) {
|
|
758
|
+
ev.buffer();
|
|
759
|
+
didStartBuffer = true;
|
|
760
|
+
}
|
|
761
|
+
ev.emit("connection.update", { connection: "connecting", receivedPendingNotifications: false, qr: undefined });
|
|
762
|
+
});
|
|
763
|
+
ws.on("CB:ib,,offline", (node) => {
|
|
764
|
+
const child = getBinaryNodeChild(node, "offline");
|
|
765
|
+
const offlineNotifs = +(child?.attrs.count || 0);
|
|
766
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`);
|
|
767
|
+
if (didStartBuffer) {
|
|
768
|
+
ev.flush();
|
|
769
|
+
logger.trace("flushed events for initial buffer");
|
|
770
|
+
}
|
|
771
|
+
ev.emit("connection.update", { receivedPendingNotifications: true });
|
|
772
|
+
});
|
|
773
|
+
ev.on("creds.update", update => {
|
|
774
|
+
const name = update.me?.name;
|
|
775
|
+
if (creds.me?.name !== name) {
|
|
776
|
+
logger.debug({ name }, "updated pushName");
|
|
777
|
+
sendNode({
|
|
778
|
+
tag: "presence",
|
|
779
|
+
attrs: { name: name }
|
|
780
|
+
}).catch(err => {
|
|
781
|
+
logger.warn({ trace: err.stack }, "error in sending presence update on name change");
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
Object.assign(creds, update);
|
|
785
|
+
});
|
|
786
|
+
return {
|
|
787
|
+
type: "md",
|
|
788
|
+
ws,
|
|
789
|
+
ev,
|
|
790
|
+
authState: { creds, keys },
|
|
791
|
+
signalRepository,
|
|
792
|
+
get user() {
|
|
793
|
+
return authState.creds.me;
|
|
794
|
+
},
|
|
795
|
+
generateMessageTag,
|
|
796
|
+
query,
|
|
797
|
+
delay,
|
|
798
|
+
waitForMessage,
|
|
799
|
+
waitForSocketOpen,
|
|
800
|
+
sendRawMessage,
|
|
801
|
+
sendNode,
|
|
802
|
+
logout,
|
|
803
|
+
end,
|
|
804
|
+
onUnexpectedError,
|
|
805
|
+
uploadPreKeys,
|
|
806
|
+
uploadPreKeysToServerIfRequired,
|
|
807
|
+
requestPairingCode,
|
|
808
|
+
wamBuffer: publicWAMBuffer,
|
|
809
|
+
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
|
810
|
+
sendWAMBuffer,
|
|
811
|
+
executeUSyncQuery,
|
|
812
|
+
onWhatsApp,
|
|
813
|
+
toLid,
|
|
814
|
+
toPn
|
|
815
|
+
};
|
|
670
816
|
};
|
|
671
|
-
|
|
672
|
-
/**
|
|
673
|
-
* map the websocket error to the right type
|
|
674
|
-
* so it can be retried by the caller
|
|
675
|
-
* */
|
|
817
|
+
//=======================================================//
|
|
676
818
|
function mapWebSocketError(handler) {
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
819
|
+
return (error) => {
|
|
820
|
+
handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
|
|
821
|
+
};
|
|
680
822
|
}
|
|
823
|
+
//=======================================================//
|