nrx-bails 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1541 -0
- package/WAProto/GenerateStatics.sh +4 -0
- package/WAProto/WAProto.proto +4775 -0
- package/WAProto/index.d.ts +2 -0
- package/WAProto/index.js +169661 -0
- package/lib/Defaults/index.d.ts +113 -0
- package/lib/Defaults/index.js +156 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Defaults/ye-bail-version.json +3 -0
- package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
- package/lib/Signal/Group/ciphertext-message.js +41 -0
- package/lib/Signal/Group/group-session-builder.d.ts +8 -0
- package/lib/Signal/Group/group-session-builder.js +90 -0
- package/lib/Signal/Group/group_cipher.d.ts +12 -0
- package/lib/Signal/Group/group_cipher.js +122 -0
- package/lib/Signal/Group/index.d.ts +22 -0
- package/lib/Signal/Group/index.js +83 -0
- package/lib/Signal/Group/keyhelper.d.ts +7 -0
- package/lib/Signal/Group/keyhelper.js +81 -0
- package/lib/Signal/Group/queue-job.d.ts +3 -0
- package/lib/Signal/Group/queue-job.js +83 -0
- package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
- package/lib/Signal/Group/sender-chain-key.js +60 -0
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +92 -0
- package/lib/Signal/Group/sender-key-message.d.ts +19 -0
- package/lib/Signal/Group/sender-key-message.js +95 -0
- package/lib/Signal/Group/sender-key-name.d.ts +12 -0
- package/lib/Signal/Group/sender-key-name.js +77 -0
- package/lib/Signal/Group/sender-key-record.d.ts +13 -0
- package/lib/Signal/Group/sender-key-record.js +79 -0
- package/lib/Signal/Group/sender-key-state.d.ts +17 -0
- package/lib/Signal/Group/sender-key-state.js +125 -0
- package/lib/Signal/Group/sender-message-key.d.ts +12 -0
- package/lib/Signal/Group/sender-message-key.js +55 -0
- package/lib/Signal/libsignal.d.ts +37 -0
- package/lib/Signal/libsignal.js +200 -0
- package/lib/Socket/Client/index.d.ts +1 -0
- package/lib/Socket/Client/index.js +44 -0
- package/lib/Socket/Client/types.d.ts +7 -0
- package/lib/Socket/Client/types.js +39 -0
- package/lib/Socket/Client/websocket.d.ts +19 -0
- package/lib/Socket/Client/websocket.js +137 -0
- package/lib/Socket/business.d.ts +329 -0
- package/lib/Socket/business.js +286 -0
- package/lib/Socket/chats.d.ts +84 -0
- package/lib/Socket/chats.js +1022 -0
- package/lib/Socket/groups.d.ts +216 -0
- package/lib/Socket/groups.js +358 -0
- package/lib/Socket/index.d.ts +330 -0
- package/lib/Socket/index.js +36 -0
- package/lib/Socket/messages-recv.d.ts +271 -0
- package/lib/Socket/messages-recv.js +1079 -0
- package/lib/Socket/messages-send.d.ts +258 -0
- package/lib/Socket/messages-send.js +1190 -0
- package/lib/Socket/newsletter.d.ts +253 -0
- package/lib/Socket/newsletter.js +362 -0
- package/lib/Socket/registration.d.ts +361 -0
- package/lib/Socket/registration.js +179 -0
- package/lib/Socket/socket.d.ts +33 -0
- package/lib/Socket/socket.js +699 -0
- package/lib/Socket/usync.d.ts +27 -0
- package/lib/Socket/usync.js +96 -0
- package/lib/Store/index.d.ts +3 -0
- package/lib/Store/index.js +36 -0
- package/lib/Store/make-cache-manager-auth-state.d.ts +16 -0
- package/lib/Store/make-cache-manager-auth-state.js +118 -0
- package/lib/Store/make-in-memory-store.d.ts +64 -0
- package/lib/Store/make-in-memory-store.js +465 -0
- package/lib/Store/make-ordered-dictionary.d.ts +14 -0
- package/lib/Store/make-ordered-dictionary.js +107 -0
- package/lib/Store/object-repository.d.ts +11 -0
- package/lib/Store/object-repository.js +53 -0
- package/lib/Types/Auth.d.ts +1 -0
- package/lib/Types/Auth.js +28 -0
- package/lib/Types/Call.d.ts +1 -0
- package/lib/Types/Call.js +28 -0
- package/lib/Types/Chat.d.ts +2 -0
- package/lib/Types/Chat.js +30 -0
- package/lib/Types/Contact.d.ts +1 -0
- package/lib/Types/Contact.js +28 -0
- package/lib/Types/Events.d.ts +1 -0
- package/lib/Types/Events.js +28 -0
- package/lib/Types/GroupMetadata.d.ts +1 -0
- package/lib/Types/GroupMetadata.js +28 -0
- package/lib/Types/Label.d.ts +2 -0
- package/lib/Types/Label.js +53 -0
- package/lib/Types/LabelAssociation.d.ts +2 -0
- package/lib/Types/LabelAssociation.js +35 -0
- package/lib/Types/Message.d.ts +2 -0
- package/lib/Types/Message.js +33 -0
- package/lib/Types/Newsletter.d.ts +4 -0
- package/lib/Types/Newsletter.js +62 -0
- package/lib/Types/Product.d.ts +1 -0
- package/lib/Types/Product.js +28 -0
- package/lib/Types/Signal.d.ts +1 -0
- package/lib/Types/Signal.js +28 -0
- package/lib/Types/Socket.d.ts +1 -0
- package/lib/Types/Socket.js +28 -0
- package/lib/Types/State.d.ts +1 -0
- package/lib/Types/State.js +28 -0
- package/lib/Types/USync.d.ts +1 -0
- package/lib/Types/USync.js +28 -0
- package/lib/Types/index.d.ts +2 -0
- package/lib/Types/index.js +68 -0
- package/lib/Utils/auth-utils.d.ts +63 -0
- package/lib/Utils/auth-utils.js +248 -0
- package/lib/Utils/browser-utils.d.ts +3 -0
- package/lib/Utils/browser-utils.js +61 -0
- package/lib/Utils/business.d.ts +53 -0
- package/lib/Utils/business.js +260 -0
- package/lib/Utils/chat-utils.d.ts +253 -0
- package/lib/Utils/chat-utils.js +756 -0
- package/lib/Utils/crypto.d.ts +43 -0
- package/lib/Utils/crypto.js +219 -0
- package/lib/Utils/decode-wa-message.d.ts +61 -0
- package/lib/Utils/decode-wa-message.js +233 -0
- package/lib/Utils/event-buffer.d.ts +17 -0
- package/lib/Utils/event-buffer.js +544 -0
- package/lib/Utils/generics.d.ts +89 -0
- package/lib/Utils/generics.js +471 -0
- package/lib/Utils/history.d.ts +59 -0
- package/lib/Utils/history.js +120 -0
- package/lib/Utils/index.d.ts +1 -0
- package/lib/Utils/index.js +61 -0
- package/lib/Utils/link-preview.d.ts +19 -0
- package/lib/Utils/link-preview.js +152 -0
- package/lib/Utils/logger.d.ts +3 -0
- package/lib/Utils/logger.js +33 -0
- package/lib/Utils/lt-hash.d.ts +13 -0
- package/lib/Utils/lt-hash.js +77 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +69 -0
- package/lib/Utils/message-retry-manager.d.ts +34 -0
- package/lib/Utils/message-retry-manager.js +154 -0
- package/lib/Utils/messages-media.d.ts +137 -0
- package/lib/Utils/messages-media.js +1024 -0
- package/lib/Utils/messages.d.ts +66 -0
- package/lib/Utils/messages.js +1407 -0
- package/lib/Utils/noise-handler.d.ts +21 -0
- package/lib/Utils/noise-handler.js +176 -0
- package/lib/Utils/pre-key-manager.d.ts +13 -0
- package/lib/Utils/pre-key-manager.js +93 -0
- package/lib/Utils/process-message.d.ts +40 -0
- package/lib/Utils/process-message.js +430 -0
- package/lib/Utils/signal.d.ts +72 -0
- package/lib/Utils/signal.js +179 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
- package/lib/Utils/use-multi-file-auth-state.js +151 -0
- package/lib/Utils/validate-connection.d.ts +43 -0
- package/lib/Utils/validate-connection.js +255 -0
- package/lib/Utils/ye-bail-event-stream.d.ts +16 -0
- package/lib/Utils/ye-bail-event-stream.js +89 -0
- package/lib/WABinary/constants.d.ts +23 -0
- package/lib/WABinary/constants.js +1328 -0
- package/lib/WABinary/decode.d.ts +10 -0
- package/lib/WABinary/decode.js +291 -0
- package/lib/WABinary/encode.d.ts +2 -0
- package/lib/WABinary/encode.js +276 -0
- package/lib/WABinary/generic-utils.d.ts +16 -0
- package/lib/WABinary/generic-utils.js +155 -0
- package/lib/WABinary/index.d.ts +1 -0
- package/lib/WABinary/index.js +47 -0
- package/lib/WABinary/jid-utils.d.ts +34 -0
- package/lib/WABinary/jid-utils.js +111 -0
- package/lib/WABinary/types.d.ts +1 -0
- package/lib/WABinary/types.js +28 -0
- package/lib/WAM/BinaryInfo.d.ts +8 -0
- package/lib/WAM/BinaryInfo.js +39 -0
- package/lib/WAM/constants.d.ts +35374 -0
- package/lib/WAM/constants.js +15376 -0
- package/lib/WAM/encode.d.ts +2 -0
- package/lib/WAM/encode.js +181 -0
- package/lib/WAM/index.d.ts +1 -0
- package/lib/WAM/index.js +45 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +14 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +58 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +83 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +56 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +68 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +79 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +50 -0
- package/lib/WAUSync/Protocols/index.d.ts +1 -0
- package/lib/WAUSync/Protocols/index.js +46 -0
- package/lib/WAUSync/USyncQuery.d.ts +20 -0
- package/lib/WAUSync/USyncQuery.js +115 -0
- package/lib/WAUSync/USyncUser.d.ts +13 -0
- package/lib/WAUSync/USyncUser.js +52 -0
- package/lib/WAUSync/index.d.ts +1 -0
- package/lib/WAUSync/index.js +45 -0
- package/lib/index.js +81 -0
- package/package.json +113 -0
- package/requirements.js +32 -0
|
@@ -0,0 +1,699 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ╔═══════════════════════════════════════════════════════════╗
|
|
3
|
+
* ║ NEROX - WhatsApp API Library ║
|
|
4
|
+
* ║ Premium Edition ║
|
|
5
|
+
* ╚═══════════════════════════════════════════════════════════╝
|
|
6
|
+
*
|
|
7
|
+
* @package nerox-bails
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @author NEROX Development Team
|
|
10
|
+
* @copyright Copyright (c) 2025 NEROX. All rights reserved.
|
|
11
|
+
* @license MIT License
|
|
12
|
+
*
|
|
13
|
+
* Permission is hereby granted, free of charge, to any person obtaining
|
|
14
|
+
* a copy of this software and associated documentation files (the "Software"),
|
|
15
|
+
* to deal in the Software without restriction, including without limitation
|
|
16
|
+
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
17
|
+
* and/or sell copies of the Software, and to permit persons to whom the
|
|
18
|
+
* Software is furnished to do so, subject to the following conditions:
|
|
19
|
+
*
|
|
20
|
+
* The above copyright notice and this permission notice shall be included
|
|
21
|
+
* in all copies or substantial portions of the Software.
|
|
22
|
+
*
|
|
23
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
24
|
+
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
25
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
26
|
+
*/
|
|
27
|
+
"use strict";
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.makeSocket = void 0;
|
|
30
|
+
const boom_1 = require("@hapi/boom");
|
|
31
|
+
const crypto_1 = require("crypto");
|
|
32
|
+
const url_1 = require("url");
|
|
33
|
+
const util_1 = require("util");
|
|
34
|
+
const WAProto_1 = require("../../WAProto");
|
|
35
|
+
const Defaults_1 = require("../Defaults");
|
|
36
|
+
const Types_1 = require("../Types");
|
|
37
|
+
const Utils_1 = require("../Utils");
|
|
38
|
+
const WABinary_1 = require("../WABinary");
|
|
39
|
+
const Client_1 = require("./Client");
|
|
40
|
+
/**
|
|
41
|
+
* Connects to WA servers and performs:
|
|
42
|
+
* - simple queries (no retry mechanism, wait for connection establishment)
|
|
43
|
+
* - listen to messages and emit events
|
|
44
|
+
* - query phone connection
|
|
45
|
+
*/
|
|
46
|
+
const makeSocket = (config) => {
|
|
47
|
+
var _a, _b;
|
|
48
|
+
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
|
|
49
|
+
const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
|
|
50
|
+
if (config.mobile || url.protocol === 'tcp:') {
|
|
51
|
+
throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
|
|
52
|
+
}
|
|
53
|
+
if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
|
|
54
|
+
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
|
|
55
|
+
}
|
|
56
|
+
const ws = new Client_1.WebSocketClient(url, config);
|
|
57
|
+
ws.connect();
|
|
58
|
+
const ev = (0, Utils_1.makeEventBuffer)(logger);
|
|
59
|
+
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
|
|
60
|
+
const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
|
|
61
|
+
/** WA noise protocol wrapper */
|
|
62
|
+
const noise = (0, Utils_1.makeNoiseHandler)({
|
|
63
|
+
keyPair: ephemeralKeyPair,
|
|
64
|
+
NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
|
|
65
|
+
logger,
|
|
66
|
+
routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
|
|
67
|
+
});
|
|
68
|
+
const { creds } = authState;
|
|
69
|
+
|
|
70
|
+
const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
|
|
71
|
+
const signalRepository = makeSignalRepository({ creds, keys });
|
|
72
|
+
let lastDateRecv;
|
|
73
|
+
let epoch = 1;
|
|
74
|
+
let keepAliveReq;
|
|
75
|
+
let qrTimer;
|
|
76
|
+
let closed = false;
|
|
77
|
+
const uqTagId = (0, Utils_1.generateMdTagPrefix)();
|
|
78
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`;
|
|
79
|
+
const sendPromise = (0, util_1.promisify)(ws.send);
|
|
80
|
+
/** send a raw buffer */
|
|
81
|
+
const sendRawMessage = async (data) => {
|
|
82
|
+
if (!ws.isOpen) {
|
|
83
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
|
|
84
|
+
}
|
|
85
|
+
const bytes = noise.encodeFrame(data);
|
|
86
|
+
await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
|
|
87
|
+
try {
|
|
88
|
+
await sendPromise.call(ws, bytes);
|
|
89
|
+
resolve();
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
reject(error);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
/** send a binary node */
|
|
97
|
+
const sendNode = (frame) => {
|
|
98
|
+
if (logger.level === 'trace') {
|
|
99
|
+
logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
|
|
100
|
+
}
|
|
101
|
+
const buff = (0, WABinary_1.encodeBinaryNode)(frame);
|
|
102
|
+
return sendRawMessage(buff);
|
|
103
|
+
};
|
|
104
|
+
/** log & process any unexpected errors */
|
|
105
|
+
const onUnexpectedError = (err, msg) => {
|
|
106
|
+
logger.error({ err }, `unexpected error in '${msg}'`);
|
|
107
|
+
const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
|
|
108
|
+
|
|
109
|
+
if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
|
|
110
|
+
try {
|
|
111
|
+
uploadPreKeysToServerIfRequired(true)
|
|
112
|
+
.catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
|
|
113
|
+
}
|
|
114
|
+
catch (_e) {
|
|
115
|
+
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (message.includes('429') || message.includes('rate limit')) {
|
|
120
|
+
const wait = Math.min(30000, (config.backoffDelayMs || 5000));
|
|
121
|
+
logger.info({ wait }, 'backing off due to rate limit');
|
|
122
|
+
setTimeout(() => {
|
|
123
|
+
|
|
124
|
+
}, wait);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
/** await the next incoming message */
|
|
128
|
+
const awaitNextMessage = async (sendMsg) => {
|
|
129
|
+
if (!ws.isOpen) {
|
|
130
|
+
throw new boom_1.Boom('Connection Closed', {
|
|
131
|
+
statusCode: Types_1.DisconnectReason.connectionClosed
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
let onOpen;
|
|
135
|
+
let onClose;
|
|
136
|
+
const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
|
|
137
|
+
onOpen = resolve;
|
|
138
|
+
onClose = mapWebSocketError(reject);
|
|
139
|
+
ws.on('frame', onOpen);
|
|
140
|
+
ws.on('close', onClose);
|
|
141
|
+
ws.on('error', onClose);
|
|
142
|
+
})
|
|
143
|
+
.finally(() => {
|
|
144
|
+
ws.off('frame', onOpen);
|
|
145
|
+
ws.off('close', onClose);
|
|
146
|
+
ws.off('error', onClose);
|
|
147
|
+
});
|
|
148
|
+
if (sendMsg) {
|
|
149
|
+
sendRawMessage(sendMsg).catch(onClose);
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
};
|
|
153
|
+
/**
|
|
154
|
+
* Wait for a message with a certain tag to be received
|
|
155
|
+
* @param msgId the message tag to await
|
|
156
|
+
* @param timeoutMs timeout after which the promise will reject
|
|
157
|
+
*/
|
|
158
|
+
const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
|
|
159
|
+
let onRecv;
|
|
160
|
+
let onErr;
|
|
161
|
+
try {
|
|
162
|
+
const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
|
|
163
|
+
onRecv = resolve;
|
|
164
|
+
onErr = err => {
|
|
165
|
+
reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
|
|
166
|
+
};
|
|
167
|
+
ws.on(`TAG:${msgId}`, onRecv);
|
|
168
|
+
ws.on('close', onErr);
|
|
169
|
+
ws.off('error', onErr);
|
|
170
|
+
});
|
|
171
|
+
return result;
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
ws.off(`TAG:${msgId}`, onRecv);
|
|
175
|
+
ws.off('close', onErr);
|
|
176
|
+
ws.off('error', onErr);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
|
180
|
+
const query = async (node, timeoutMs) => {
|
|
181
|
+
if (!node.attrs.id) {
|
|
182
|
+
node.attrs.id = generateMessageTag();
|
|
183
|
+
}
|
|
184
|
+
const msgId = node.attrs.id;
|
|
185
|
+
const [result] = await Promise.all([
|
|
186
|
+
waitForMessage(msgId, timeoutMs),
|
|
187
|
+
sendNode(node)
|
|
188
|
+
]);
|
|
189
|
+
if ('tag' in result) {
|
|
190
|
+
(0, WABinary_1.assertNodeErrorFree)(result);
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
};
|
|
194
|
+
/** connection handshake */
|
|
195
|
+
const validateConnection = async () => {
|
|
196
|
+
let helloMsg = {
|
|
197
|
+
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
198
|
+
};
|
|
199
|
+
helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
|
|
200
|
+
logger.info({ browser, helloMsg }, 'connected to WA');
|
|
201
|
+
const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
|
|
202
|
+
const result = await awaitNextMessage(init);
|
|
203
|
+
const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
|
|
204
|
+
logger.trace({ handshake }, 'handshake recv from WA');
|
|
205
|
+
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
|
|
206
|
+
let node;
|
|
207
|
+
if (!creds.me) {
|
|
208
|
+
node = (0, Utils_1.generateRegistrationNode)(creds, config);
|
|
209
|
+
logger.info({ node }, 'not logged in, attempting registration...');
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
|
|
213
|
+
logger.info({ node }, 'logging in...');
|
|
214
|
+
}
|
|
215
|
+
const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
|
|
216
|
+
await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
|
|
217
|
+
clientFinish: {
|
|
218
|
+
static: keyEnc,
|
|
219
|
+
payload: payloadEnc,
|
|
220
|
+
},
|
|
221
|
+
}).finish());
|
|
222
|
+
noise.finishInit();
|
|
223
|
+
startKeepAliveRequest();
|
|
224
|
+
};
|
|
225
|
+
const getAvailablePreKeysOnServer = async () => {
|
|
226
|
+
const result = await query({
|
|
227
|
+
tag: 'iq',
|
|
228
|
+
attrs: {
|
|
229
|
+
id: generateMessageTag(),
|
|
230
|
+
xmlns: 'encrypt',
|
|
231
|
+
type: 'get',
|
|
232
|
+
to: WABinary_1.S_WHATSAPP_NET
|
|
233
|
+
},
|
|
234
|
+
content: [
|
|
235
|
+
{ tag: 'count', attrs: {} }
|
|
236
|
+
]
|
|
237
|
+
});
|
|
238
|
+
const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
|
|
239
|
+
return +countChild.attrs.value;
|
|
240
|
+
};
|
|
241
|
+
/** generates and uploads a set of pre-keys to the server */
|
|
242
|
+
const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
|
|
243
|
+
await keys.transaction(async () => {
|
|
244
|
+
logger.info({ count }, 'uploading pre-keys');
|
|
245
|
+
const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
|
|
246
|
+
await query(node);
|
|
247
|
+
ev.emit('creds.update', update);
|
|
248
|
+
logger.info({ count }, 'uploaded pre-keys');
|
|
249
|
+
});
|
|
250
|
+
};
|
|
251
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
252
|
+
const preKeyCount = await getAvailablePreKeysOnServer();
|
|
253
|
+
logger.info(`${preKeyCount} pre-keys found on server`);
|
|
254
|
+
if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
|
|
255
|
+
await uploadPreKeys();
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
const onMessageReceived = (data) => {
|
|
259
|
+
noise.decodeFrame(data, frame => {
|
|
260
|
+
var _a;
|
|
261
|
+
|
|
262
|
+
lastDateRecv = new Date();
|
|
263
|
+
let anyTriggered = false;
|
|
264
|
+
anyTriggered = ws.emit('frame', frame);
|
|
265
|
+
|
|
266
|
+
if (!(frame instanceof Uint8Array)) {
|
|
267
|
+
const msgId = frame.attrs.id;
|
|
268
|
+
if (logger.level === 'trace') {
|
|
269
|
+
logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
|
|
270
|
+
}
|
|
271
|
+
/* Check if this is a response to a message we sent */
|
|
272
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
|
|
273
|
+
/* Check if this is a response to a message we are expecting */
|
|
274
|
+
const l0 = frame.tag;
|
|
275
|
+
const l1 = frame.attrs || {};
|
|
276
|
+
const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
|
|
277
|
+
for (const key of Object.keys(l1)) {
|
|
278
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
|
|
279
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
|
|
280
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
|
|
281
|
+
}
|
|
282
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
|
|
283
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
|
|
284
|
+
if (!anyTriggered && logger.level === 'debug') {
|
|
285
|
+
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
};
|
|
290
|
+
const end = (error) => {
|
|
291
|
+
if (closed) {
|
|
292
|
+
logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
closed = true;
|
|
296
|
+
logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
|
|
297
|
+
clearInterval(keepAliveReq);
|
|
298
|
+
clearTimeout(qrTimer);
|
|
299
|
+
ws.removeAllListeners('close');
|
|
300
|
+
ws.removeAllListeners('error');
|
|
301
|
+
ws.removeAllListeners('open');
|
|
302
|
+
ws.removeAllListeners('message');
|
|
303
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
304
|
+
try {
|
|
305
|
+
ws.close();
|
|
306
|
+
}
|
|
307
|
+
catch (_a) { }
|
|
308
|
+
}
|
|
309
|
+
ev.emit('connection.update', {
|
|
310
|
+
connection: 'close',
|
|
311
|
+
lastDisconnect: {
|
|
312
|
+
error,
|
|
313
|
+
date: new Date()
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
ev.removeAllListeners('connection.update');
|
|
317
|
+
};
|
|
318
|
+
const waitForSocketOpen = async () => {
|
|
319
|
+
if (ws.isOpen) {
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (ws.isClosed || ws.isClosing) {
|
|
323
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
|
|
324
|
+
}
|
|
325
|
+
let onOpen;
|
|
326
|
+
let onClose;
|
|
327
|
+
await new Promise((resolve, reject) => {
|
|
328
|
+
onOpen = () => resolve(undefined);
|
|
329
|
+
onClose = mapWebSocketError(reject);
|
|
330
|
+
ws.on('open', onOpen);
|
|
331
|
+
ws.on('close', onClose);
|
|
332
|
+
ws.on('error', onClose);
|
|
333
|
+
})
|
|
334
|
+
.finally(() => {
|
|
335
|
+
ws.off('open', onOpen);
|
|
336
|
+
ws.off('close', onClose);
|
|
337
|
+
ws.off('error', onClose);
|
|
338
|
+
});
|
|
339
|
+
};
|
|
340
|
+
const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
|
|
341
|
+
if (!lastDateRecv) {
|
|
342
|
+
lastDateRecv = new Date();
|
|
343
|
+
}
|
|
344
|
+
const diff = Date.now() - lastDateRecv.getTime();
|
|
345
|
+
/*
|
|
346
|
+
check if it's been a suspicious amount of time since the server responded with our last seen
|
|
347
|
+
it could be that the network is down
|
|
348
|
+
*/
|
|
349
|
+
if (diff > keepAliveIntervalMs + 5000) {
|
|
350
|
+
end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
|
|
351
|
+
}
|
|
352
|
+
else if (ws.isOpen) {
|
|
353
|
+
|
|
354
|
+
query({
|
|
355
|
+
tag: 'iq',
|
|
356
|
+
attrs: {
|
|
357
|
+
id: generateMessageTag(),
|
|
358
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
359
|
+
type: 'get',
|
|
360
|
+
xmlns: 'w:p',
|
|
361
|
+
},
|
|
362
|
+
content: [{ tag: 'ping', attrs: {} }]
|
|
363
|
+
})
|
|
364
|
+
.catch(err => {
|
|
365
|
+
logger.error({ trace: err.stack }, 'error in sending keep alive');
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
logger.warn('keep alive called when WS not open');
|
|
370
|
+
}
|
|
371
|
+
}, keepAliveIntervalMs));
|
|
372
|
+
/** i have no idea why this exists. pls enlighten me */
|
|
373
|
+
const sendPassiveIq = (tag) => (query({
|
|
374
|
+
tag: 'iq',
|
|
375
|
+
attrs: {
|
|
376
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
377
|
+
xmlns: 'passive',
|
|
378
|
+
type: 'set',
|
|
379
|
+
},
|
|
380
|
+
content: [
|
|
381
|
+
{ tag, attrs: {} }
|
|
382
|
+
]
|
|
383
|
+
}));
|
|
384
|
+
/** logout & invalidate connection */
|
|
385
|
+
const logout = async (msg) => {
|
|
386
|
+
var _a;
|
|
387
|
+
const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
|
|
388
|
+
if (jid) {
|
|
389
|
+
await sendNode({
|
|
390
|
+
tag: 'iq',
|
|
391
|
+
attrs: {
|
|
392
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
393
|
+
type: 'set',
|
|
394
|
+
id: generateMessageTag(),
|
|
395
|
+
xmlns: 'md'
|
|
396
|
+
},
|
|
397
|
+
content: [
|
|
398
|
+
{
|
|
399
|
+
tag: 'remove-companion-device',
|
|
400
|
+
attrs: {
|
|
401
|
+
jid,
|
|
402
|
+
reason: 'user_initiated'
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
]
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
|
|
409
|
+
};
|
|
410
|
+
const requestPairingCode = async (phoneNumber, pairCode = "NEROXRTX") => {
|
|
411
|
+
if (!phoneNumber || typeof phoneNumber !== 'string') {
|
|
412
|
+
logger.error("phoneNumber must be a valid string");
|
|
413
|
+
throw new boom_1.Boom('Phone number must be a valid string', { statusCode: 400 });
|
|
414
|
+
}
|
|
415
|
+
const cleanPhoneNumber = phoneNumber.replace(/[\s\-\(\)]/g, '');
|
|
416
|
+
if (!Object.keys(Defaults_1.PHONENUMBER_MCC).some(mcc => cleanPhoneNumber.startsWith(mcc))) {
|
|
417
|
+
logger.error({ phoneNumber: cleanPhoneNumber }, "phoneNumber format must start with country code");
|
|
418
|
+
throw new boom_1.Boom('Invalid phone number format. Must start with country code (e.g., 62xxx for Indonesia)', { statusCode: 400 });
|
|
419
|
+
}
|
|
420
|
+
if (cleanPhoneNumber.length < 10 || cleanPhoneNumber.length > 15) {
|
|
421
|
+
logger.error({ phoneNumber: cleanPhoneNumber }, "phoneNumber length is invalid");
|
|
422
|
+
throw new boom_1.Boom('Invalid phone number length. Must be between 10-15 digits', { statusCode: 400 });
|
|
423
|
+
}
|
|
424
|
+
if (pairCode && typeof pairCode === 'string') {
|
|
425
|
+
authState.creds.pairingCode = pairCode.toUpperCase();
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
|
|
429
|
+
}
|
|
430
|
+
authState.creds.me = {
|
|
431
|
+
id: (0, WABinary_1.jidEncode)(cleanPhoneNumber, 's.whatsapp.net'),
|
|
432
|
+
name: '~'
|
|
433
|
+
};
|
|
434
|
+
ev.emit('creds.update', authState.creds);
|
|
435
|
+
try {
|
|
436
|
+
await sendNode({
|
|
437
|
+
tag: 'iq',
|
|
438
|
+
attrs: {
|
|
439
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
440
|
+
type: 'set',
|
|
441
|
+
id: generateMessageTag(),
|
|
442
|
+
xmlns: 'md'
|
|
443
|
+
},
|
|
444
|
+
content: [
|
|
445
|
+
{
|
|
446
|
+
tag: 'link_code_companion_reg',
|
|
447
|
+
attrs: {
|
|
448
|
+
jid: authState.creds.me.id,
|
|
449
|
+
stage: 'companion_hello',
|
|
450
|
+
should_show_push_notification: 'true'
|
|
451
|
+
},
|
|
452
|
+
content: [
|
|
453
|
+
{
|
|
454
|
+
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
455
|
+
attrs: {},
|
|
456
|
+
content: await generatePairingKey()
|
|
457
|
+
},
|
|
458
|
+
{
|
|
459
|
+
tag: 'companion_server_auth_key_pub',
|
|
460
|
+
attrs: {},
|
|
461
|
+
content: authState.creds.noiseKey.public
|
|
462
|
+
},
|
|
463
|
+
{
|
|
464
|
+
tag: 'companion_platform_id',
|
|
465
|
+
attrs: {},
|
|
466
|
+
content: (0, Utils_1.getPlatformId)(browser[1])
|
|
467
|
+
},
|
|
468
|
+
{
|
|
469
|
+
tag: 'companion_platform_display',
|
|
470
|
+
attrs: {},
|
|
471
|
+
content: `${browser[1]} (${browser[0]})`
|
|
472
|
+
},
|
|
473
|
+
{
|
|
474
|
+
tag: 'link_code_pairing_nonce',
|
|
475
|
+
attrs: {},
|
|
476
|
+
content: '0'
|
|
477
|
+
}
|
|
478
|
+
]
|
|
479
|
+
}
|
|
480
|
+
]
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
logger.error({ error, phoneNumber: cleanPhoneNumber }, 'Failed to send pairing request');
|
|
485
|
+
throw new boom_1.Boom('Failed to request pairing code', { statusCode: 500, data: error });
|
|
486
|
+
}
|
|
487
|
+
logger.info({ pairingCode: authState.creds.pairingCode, phoneNumber: cleanPhoneNumber }, 'Pairing code generated successfully');
|
|
488
|
+
return authState.creds.pairingCode;
|
|
489
|
+
};
|
|
490
|
+
async function generatePairingKey() {
|
|
491
|
+
const salt = (0, crypto_1.randomBytes)(32);
|
|
492
|
+
const randomIv = (0, crypto_1.randomBytes)(16);
|
|
493
|
+
const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
|
|
494
|
+
const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
|
|
495
|
+
return Buffer.concat([salt, randomIv, ciphered]);
|
|
496
|
+
}
|
|
497
|
+
const sendWAMBuffer = (wamBuffer) => {
|
|
498
|
+
return query({
|
|
499
|
+
tag: 'iq',
|
|
500
|
+
attrs: {
|
|
501
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
502
|
+
id: generateMessageTag(),
|
|
503
|
+
xmlns: 'w:stats'
|
|
504
|
+
},
|
|
505
|
+
content: [
|
|
506
|
+
{
|
|
507
|
+
tag: 'add',
|
|
508
|
+
attrs: { t: Math.round(Date.now() / 1000).toString() },
|
|
509
|
+
content: wamBuffer
|
|
510
|
+
}
|
|
511
|
+
]
|
|
512
|
+
});
|
|
513
|
+
};
|
|
514
|
+
ws.on('message', onMessageReceived);
|
|
515
|
+
ws.on('open', async () => {
|
|
516
|
+
try {
|
|
517
|
+
await validateConnection();
|
|
518
|
+
}
|
|
519
|
+
catch (err) {
|
|
520
|
+
logger.error({ err }, 'error in validating connection');
|
|
521
|
+
end(err);
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
ws.on('error', mapWebSocketError(end));
|
|
525
|
+
ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
|
|
526
|
+
|
|
527
|
+
ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
|
|
528
|
+
|
|
529
|
+
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
530
|
+
const iq = {
|
|
531
|
+
tag: 'iq',
|
|
532
|
+
attrs: {
|
|
533
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
534
|
+
type: 'result',
|
|
535
|
+
id: stanza.attrs.id,
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
await sendNode(iq);
|
|
539
|
+
const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
|
|
540
|
+
const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
|
|
541
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
|
|
542
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
|
|
543
|
+
const advB64 = creds.advSecretKey;
|
|
544
|
+
let qrMs = qrTimeout || 60000;
|
|
545
|
+
const genPairQR = () => {
|
|
546
|
+
if (!ws.isOpen) {
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
const refNode = refNodes.shift();
|
|
550
|
+
if (!refNode) {
|
|
551
|
+
end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
const ref = refNode.content.toString('utf-8');
|
|
555
|
+
const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
|
|
556
|
+
ev.emit('connection.update', { qr });
|
|
557
|
+
qrTimer = setTimeout(genPairQR, qrMs);
|
|
558
|
+
qrMs = qrTimeout || 20000;
|
|
559
|
+
};
|
|
560
|
+
genPairQR();
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
565
|
+
logger.debug('pair success recv');
|
|
566
|
+
try {
|
|
567
|
+
const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
|
|
568
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
|
|
569
|
+
ev.emit('creds.update', updatedCreds);
|
|
570
|
+
ev.emit('connection.update', { isNewLogin: true, qr: undefined });
|
|
571
|
+
await sendNode(reply);
|
|
572
|
+
}
|
|
573
|
+
catch (error) {
|
|
574
|
+
logger.info({ trace: error.stack }, 'error in pairing');
|
|
575
|
+
end(error);
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
ws.on('CB:success', async (node) => {
|
|
580
|
+
try {
|
|
581
|
+
await uploadPreKeysToServerIfRequired();
|
|
582
|
+
await sendPassiveIq('active');
|
|
583
|
+
logger.info('opened connection to WA');
|
|
584
|
+
clearTimeout(qrTimer);
|
|
585
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
|
|
586
|
+
ev.emit('connection.update', { connection: 'open' });
|
|
587
|
+
}
|
|
588
|
+
catch (err) {
|
|
589
|
+
logger.error({ err }, 'error opening connection');
|
|
590
|
+
end(err);
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
ws.on('CB:stream:error', (node) => {
|
|
594
|
+
logger.error({ node }, 'stream errored out');
|
|
595
|
+
const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
|
|
596
|
+
end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
ws.on('CB:failure', (node) => {
|
|
600
|
+
const reason = +(node.attrs.reason || 500);
|
|
601
|
+
end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
|
|
602
|
+
});
|
|
603
|
+
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
604
|
+
end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
|
|
605
|
+
});
|
|
606
|
+
ws.on('CB:ib,,offline_preview', (node) => {
|
|
607
|
+
logger.info('offline preview received', JSON.stringify(node));
|
|
608
|
+
sendNode({
|
|
609
|
+
tag: 'ib',
|
|
610
|
+
attrs: {},
|
|
611
|
+
content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
|
|
612
|
+
});
|
|
613
|
+
});
|
|
614
|
+
ws.on('CB:ib,,edge_routing', (node) => {
|
|
615
|
+
const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
|
|
616
|
+
const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
|
|
617
|
+
if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
|
|
618
|
+
authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
|
|
619
|
+
ev.emit('creds.update', authState.creds);
|
|
620
|
+
}
|
|
621
|
+
});
|
|
622
|
+
let didStartBuffer = false;
|
|
623
|
+
process.nextTick(() => {
|
|
624
|
+
var _a;
|
|
625
|
+
if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
ev.buffer();
|
|
629
|
+
didStartBuffer = true;
|
|
630
|
+
}
|
|
631
|
+
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
ws.on('CB:ib,,offline', (node) => {
|
|
635
|
+
const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
|
|
636
|
+
const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
|
|
637
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`);
|
|
638
|
+
if (didStartBuffer) {
|
|
639
|
+
ev.flush();
|
|
640
|
+
logger.trace('flushed events for initial buffer');
|
|
641
|
+
}
|
|
642
|
+
ev.emit('connection.update', { receivedPendingNotifications: true });
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
ev.on('creds.update', update => {
|
|
646
|
+
var _a, _b;
|
|
647
|
+
const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
|
|
648
|
+
|
|
649
|
+
if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
|
|
650
|
+
logger.debug({ name }, 'updated pushName');
|
|
651
|
+
sendNode({
|
|
652
|
+
tag: 'presence',
|
|
653
|
+
attrs: { name: name }
|
|
654
|
+
})
|
|
655
|
+
.catch(err => {
|
|
656
|
+
logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
Object.assign(creds, update);
|
|
660
|
+
});
|
|
661
|
+
if (printQRInTerminal) {
|
|
662
|
+
(0, Utils_1.printQRIfNecessaryListener)(ev, logger);
|
|
663
|
+
}
|
|
664
|
+
return {
|
|
665
|
+
type: 'md',
|
|
666
|
+
ws,
|
|
667
|
+
ev,
|
|
668
|
+
authState: { creds, keys },
|
|
669
|
+
signalRepository,
|
|
670
|
+
get user() {
|
|
671
|
+
return authState.creds.me;
|
|
672
|
+
},
|
|
673
|
+
generateMessageTag,
|
|
674
|
+
query,
|
|
675
|
+
waitForMessage,
|
|
676
|
+
waitForSocketOpen,
|
|
677
|
+
sendRawMessage,
|
|
678
|
+
sendNode,
|
|
679
|
+
logout,
|
|
680
|
+
end,
|
|
681
|
+
onUnexpectedError,
|
|
682
|
+
uploadPreKeys,
|
|
683
|
+
uploadPreKeysToServerIfRequired,
|
|
684
|
+
requestPairingCode,
|
|
685
|
+
/** Waits for the connection to WA to reach a state */
|
|
686
|
+
waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
|
|
687
|
+
sendWAMBuffer,
|
|
688
|
+
};
|
|
689
|
+
};
|
|
690
|
+
exports.makeSocket = makeSocket;
|
|
691
|
+
/**
|
|
692
|
+
* map the websocket error to the right type
|
|
693
|
+
* so it can be retried by the caller
|
|
694
|
+
* */
|
|
695
|
+
function mapWebSocketError(handler) {
|
|
696
|
+
return (error) => {
|
|
697
|
+
handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
|
|
698
|
+
};
|
|
699
|
+
}
|