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