@yemo-dev/yebail 1.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/EXAMPLES.md +641 -0
- package/LICENSE +21 -0
- package/README.md +141 -0
- package/WAProto/GenerateStatics.sh +4 -0
- package/WAProto/WAProto.proto +4775 -0
- package/WAProto/index.js +116311 -0
- package/engine-requirements.js +10 -0
- package/lib/Defaults/index.js +142 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Defaults/yebail-version.json +7 -0
- package/lib/Signal/Group/ciphertext-message.js +15 -0
- package/lib/Signal/Group/group-session-builder.js +64 -0
- package/lib/Signal/Group/group_cipher.js +96 -0
- package/lib/Signal/Group/index.js +57 -0
- package/lib/Signal/Group/keyhelper.js +55 -0
- package/lib/Signal/Group/queue-job.js +57 -0
- package/lib/Signal/Group/sender-chain-key.js +34 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
- package/lib/Signal/Group/sender-key-message.js +69 -0
- package/lib/Signal/Group/sender-key-name.js +51 -0
- package/lib/Signal/Group/sender-key-record.js +53 -0
- package/lib/Signal/Group/sender-key-state.js +99 -0
- package/lib/Signal/Group/sender-message-key.js +29 -0
- package/lib/Signal/libsignal.js +196 -0
- package/lib/Signal/lid-mapping.js +148 -0
- package/lib/Socket/Client/index.js +18 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.js +72 -0
- package/lib/Socket/business.js +368 -0
- package/lib/Socket/chats.js +992 -0
- package/lib/Socket/communities.js +430 -0
- package/lib/Socket/groups.js +323 -0
- package/lib/Socket/index.js +10 -0
- package/lib/Socket/messages-recv.js +1133 -0
- package/lib/Socket/messages-send.js +992 -0
- package/lib/Socket/newsletter.js +250 -0
- package/lib/Socket/socket.js +631 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.js +8 -0
- package/lib/Store/make-in-memory-store.js +421 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.js +7 -0
- package/lib/Types/Newsletter.js +18 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +42 -0
- package/lib/Utils/auth-utils.js +188 -0
- package/lib/Utils/browser-utils.js +35 -0
- package/lib/Utils/business.js +230 -0
- package/lib/Utils/chat-utils.js +763 -0
- package/lib/Utils/crypto.js +187 -0
- package/lib/Utils/decode-wa-message.js +293 -0
- package/lib/Utils/event-buffer.js +514 -0
- package/lib/Utils/generics.js +453 -0
- package/lib/Utils/history.js +94 -0
- package/lib/Utils/index.js +37 -0
- package/lib/Utils/link-preview.js +121 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.js +47 -0
- package/lib/Utils/make-mutex.js +43 -0
- package/lib/Utils/message-retry-manager.js +128 -0
- package/lib/Utils/messages-media.js +910 -0
- package/lib/Utils/messages.js +1129 -0
- package/lib/Utils/noise-handler.js +150 -0
- package/lib/Utils/process-message.js +448 -0
- package/lib/Utils/signal.js +150 -0
- package/lib/Utils/use-custom-auth-state.js +110 -0
- package/lib/Utils/use-multi-file-auth-state.js +43 -0
- package/lib/Utils/use-sqlite-auth-state.js +39 -0
- package/lib/Utils/validate-connection.js +237 -0
- package/lib/Utils/yebail-event-stream.js +55 -0
- package/lib/WABinary/constants.js +1303 -0
- package/lib/WABinary/decode.js +275 -0
- package/lib/WABinary/encode.js +250 -0
- package/lib/WABinary/generic-utils.js +110 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.js +136 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.js +89 -0
- package/lib/WAUSync/USyncUser.js +26 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.js +46 -0
- package/package.json +114 -0
|
@@ -0,0 +1,631 @@
|
|
|
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
|
+
const makeSocket = (config) => {
|
|
16
|
+
var _a, _b;
|
|
17
|
+
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
|
|
18
|
+
const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
|
|
19
|
+
if (config.mobile || url.protocol === 'tcp:') {
|
|
20
|
+
throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
|
|
21
|
+
}
|
|
22
|
+
if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
|
|
23
|
+
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
|
|
24
|
+
}
|
|
25
|
+
const ws = new Client_1.WebSocketClient(url, config);
|
|
26
|
+
ws.connect();
|
|
27
|
+
const ev = (0, Utils_1.makeEventBuffer)(logger);
|
|
28
|
+
|
|
29
|
+
const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
|
|
30
|
+
|
|
31
|
+
const noise = (0, Utils_1.makeNoiseHandler)({
|
|
32
|
+
keyPair: ephemeralKeyPair,
|
|
33
|
+
NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
|
|
34
|
+
logger,
|
|
35
|
+
routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
|
|
36
|
+
});
|
|
37
|
+
const { creds } = authState;
|
|
38
|
+
// add transaction capability
|
|
39
|
+
const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
|
|
40
|
+
const signalRepository = makeSignalRepository({ creds, keys }, logger);
|
|
41
|
+
let lastDateRecv;
|
|
42
|
+
let epoch = 1;
|
|
43
|
+
let keepAliveReq;
|
|
44
|
+
let qrTimer;
|
|
45
|
+
let closed = false;
|
|
46
|
+
const uqTagId = (0, Utils_1.generateMdTagPrefix)();
|
|
47
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`;
|
|
48
|
+
const sendPromise = (0, util_1.promisify)(ws.send);
|
|
49
|
+
|
|
50
|
+
const sendRawMessage = async (data) => {
|
|
51
|
+
if (!ws.isOpen) {
|
|
52
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
|
|
53
|
+
}
|
|
54
|
+
const bytes = noise.encodeFrame(data);
|
|
55
|
+
await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
|
|
56
|
+
try {
|
|
57
|
+
await sendPromise.call(ws, bytes);
|
|
58
|
+
resolve();
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
reject(error);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const sendNode = (frame) => {
|
|
67
|
+
if (logger.level === 'trace') {
|
|
68
|
+
logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
|
|
69
|
+
}
|
|
70
|
+
const buff = (0, WABinary_1.encodeBinaryNode)(frame);
|
|
71
|
+
return sendRawMessage(buff);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const onUnexpectedError = (err, msg) => {
|
|
75
|
+
logger.error({ err }, `unexpected error in '${msg}'`);
|
|
76
|
+
const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
|
|
77
|
+
// auto recover from cryptographic desyncs by re-uploading prekeys
|
|
78
|
+
if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
|
|
79
|
+
try {
|
|
80
|
+
uploadPreKeysToServerIfRequired(true)
|
|
81
|
+
.catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
|
|
82
|
+
}
|
|
83
|
+
catch (_e) {
|
|
84
|
+
// ignore
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const awaitNextMessage = async (sendMsg) => {
|
|
90
|
+
if (!ws.isOpen) {
|
|
91
|
+
throw new boom_1.Boom('Connection Closed', {
|
|
92
|
+
statusCode: Types_1.DisconnectReason.connectionClosed
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
let onOpen;
|
|
96
|
+
let onClose;
|
|
97
|
+
const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
|
|
98
|
+
onOpen = resolve;
|
|
99
|
+
onClose = mapWebSocketError(reject);
|
|
100
|
+
ws.on('frame', onOpen);
|
|
101
|
+
ws.on('close', onClose);
|
|
102
|
+
ws.on('error', onClose);
|
|
103
|
+
})
|
|
104
|
+
.finally(() => {
|
|
105
|
+
ws.off('frame', onOpen);
|
|
106
|
+
ws.off('close', onClose);
|
|
107
|
+
ws.off('error', onClose);
|
|
108
|
+
});
|
|
109
|
+
if (sendMsg) {
|
|
110
|
+
sendRawMessage(sendMsg).catch(onClose);
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
|
|
116
|
+
let onRecv;
|
|
117
|
+
let onErr;
|
|
118
|
+
try {
|
|
119
|
+
const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
|
|
120
|
+
onRecv = resolve;
|
|
121
|
+
onErr = err => {
|
|
122
|
+
reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
|
|
123
|
+
};
|
|
124
|
+
ws.on(`TAG:${msgId}`, onRecv);
|
|
125
|
+
ws.on('close', onErr); // if the socket closes, you'll never receive the message
|
|
126
|
+
ws.off('error', onErr);
|
|
127
|
+
});
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
ws.off(`TAG:${msgId}`, onRecv);
|
|
132
|
+
ws.off('close', onErr); // if the socket closes, you'll never receive the message
|
|
133
|
+
ws.off('error', onErr);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const query = async (node, timeoutMs) => {
|
|
138
|
+
if (!node.attrs.id) {
|
|
139
|
+
node.attrs.id = generateMessageTag();
|
|
140
|
+
}
|
|
141
|
+
const msgId = node.attrs.id;
|
|
142
|
+
const [result] = await Promise.all([
|
|
143
|
+
waitForMessage(msgId, timeoutMs),
|
|
144
|
+
sendNode(node)
|
|
145
|
+
]);
|
|
146
|
+
if ('tag' in result) {
|
|
147
|
+
(0, WABinary_1.assertNodeErrorFree)(result);
|
|
148
|
+
}
|
|
149
|
+
return result;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const validateConnection = async () => {
|
|
153
|
+
let helloMsg = {
|
|
154
|
+
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
155
|
+
};
|
|
156
|
+
helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
|
|
157
|
+
logger.info({ browser, helloMsg }, 'connected to WA');
|
|
158
|
+
const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
|
|
159
|
+
const result = await awaitNextMessage(init);
|
|
160
|
+
const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
|
|
161
|
+
logger.trace({ handshake }, 'handshake recv from WA');
|
|
162
|
+
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
|
|
163
|
+
let node;
|
|
164
|
+
if (!creds.me) {
|
|
165
|
+
node = (0, Utils_1.generateRegistrationNode)(creds, config);
|
|
166
|
+
logger.info({ node }, 'not logged in, attempting registration...');
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
|
|
170
|
+
logger.info({ node }, 'logging in...');
|
|
171
|
+
}
|
|
172
|
+
const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
|
|
173
|
+
await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
|
|
174
|
+
clientFinish: {
|
|
175
|
+
static: keyEnc,
|
|
176
|
+
payload: payloadEnc,
|
|
177
|
+
},
|
|
178
|
+
}).finish());
|
|
179
|
+
noise.finishInit();
|
|
180
|
+
startKeepAliveRequest();
|
|
181
|
+
};
|
|
182
|
+
const getAvailablePreKeysOnServer = async () => {
|
|
183
|
+
const result = await query({
|
|
184
|
+
tag: 'iq',
|
|
185
|
+
attrs: {
|
|
186
|
+
id: generateMessageTag(),
|
|
187
|
+
xmlns: 'encrypt',
|
|
188
|
+
type: 'get',
|
|
189
|
+
to: WABinary_1.S_WHATSAPP_NET
|
|
190
|
+
},
|
|
191
|
+
content: [
|
|
192
|
+
{ tag: 'count', attrs: {} }
|
|
193
|
+
]
|
|
194
|
+
});
|
|
195
|
+
const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
|
|
196
|
+
return +countChild.attrs.value;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
|
|
200
|
+
await keys.transaction(async () => {
|
|
201
|
+
logger.info({ count }, 'uploading pre-keys');
|
|
202
|
+
const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
|
|
203
|
+
await query(node);
|
|
204
|
+
ev.emit('creds.update', update);
|
|
205
|
+
logger.info({ count }, 'uploaded pre-keys');
|
|
206
|
+
});
|
|
207
|
+
};
|
|
208
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
209
|
+
const preKeyCount = await getAvailablePreKeysOnServer();
|
|
210
|
+
logger.info(`${preKeyCount} pre-keys found on server`);
|
|
211
|
+
if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
|
|
212
|
+
await uploadPreKeys();
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
const onMessageReceived = (data) => {
|
|
216
|
+
noise.decodeFrame(data, frame => {
|
|
217
|
+
var _a;
|
|
218
|
+
// reset ping timeout
|
|
219
|
+
lastDateRecv = new Date();
|
|
220
|
+
let anyTriggered = false;
|
|
221
|
+
anyTriggered = ws.emit('frame', frame);
|
|
222
|
+
// if it's a binary node
|
|
223
|
+
if (!(frame instanceof Uint8Array)) {
|
|
224
|
+
const msgId = frame.attrs.id;
|
|
225
|
+
if (logger.level === 'trace') {
|
|
226
|
+
logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
|
|
230
|
+
|
|
231
|
+
const l0 = frame.tag;
|
|
232
|
+
const l1 = frame.attrs || {};
|
|
233
|
+
const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
|
|
234
|
+
for (const key of Object.keys(l1)) {
|
|
235
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
|
|
236
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
|
|
237
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
|
|
238
|
+
}
|
|
239
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
|
|
240
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
|
|
241
|
+
if (!anyTriggered && logger.level === 'debug') {
|
|
242
|
+
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
const end = (error) => {
|
|
248
|
+
if (closed) {
|
|
249
|
+
logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
closed = true;
|
|
253
|
+
logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
|
|
254
|
+
clearInterval(keepAliveReq);
|
|
255
|
+
clearTimeout(qrTimer);
|
|
256
|
+
ws.removeAllListeners('close');
|
|
257
|
+
ws.removeAllListeners('error');
|
|
258
|
+
ws.removeAllListeners('open');
|
|
259
|
+
ws.removeAllListeners('message');
|
|
260
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
261
|
+
try {
|
|
262
|
+
ws.close();
|
|
263
|
+
}
|
|
264
|
+
catch (_a) { }
|
|
265
|
+
}
|
|
266
|
+
ev.emit('connection.update', {
|
|
267
|
+
connection: 'close',
|
|
268
|
+
lastDisconnect: {
|
|
269
|
+
error,
|
|
270
|
+
date: new Date()
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
ev.removeAllListeners('connection.update');
|
|
274
|
+
};
|
|
275
|
+
const waitForSocketOpen = async () => {
|
|
276
|
+
if (ws.isOpen) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (ws.isClosed || ws.isClosing) {
|
|
280
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
|
|
281
|
+
}
|
|
282
|
+
let onOpen;
|
|
283
|
+
let onClose;
|
|
284
|
+
await new Promise((resolve, reject) => {
|
|
285
|
+
onOpen = () => resolve(undefined);
|
|
286
|
+
onClose = mapWebSocketError(reject);
|
|
287
|
+
ws.on('open', onOpen);
|
|
288
|
+
ws.on('close', onClose);
|
|
289
|
+
ws.on('error', onClose);
|
|
290
|
+
})
|
|
291
|
+
.finally(() => {
|
|
292
|
+
ws.off('open', onOpen);
|
|
293
|
+
ws.off('close', onClose);
|
|
294
|
+
ws.off('error', onClose);
|
|
295
|
+
});
|
|
296
|
+
};
|
|
297
|
+
const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
|
|
298
|
+
if (!lastDateRecv) {
|
|
299
|
+
lastDateRecv = new Date();
|
|
300
|
+
}
|
|
301
|
+
const diff = Date.now() - lastDateRecv.getTime();
|
|
302
|
+
|
|
303
|
+
if (diff > keepAliveIntervalMs + 5000) {
|
|
304
|
+
end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
|
|
305
|
+
}
|
|
306
|
+
else if (ws.isOpen) {
|
|
307
|
+
// if its all good, send a keep alive request
|
|
308
|
+
query({
|
|
309
|
+
tag: 'iq',
|
|
310
|
+
attrs: {
|
|
311
|
+
id: generateMessageTag(),
|
|
312
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
313
|
+
type: 'get',
|
|
314
|
+
xmlns: 'w:p',
|
|
315
|
+
},
|
|
316
|
+
content: [{ tag: 'ping', attrs: {} }]
|
|
317
|
+
})
|
|
318
|
+
.catch(err => {
|
|
319
|
+
logger.error({ trace: err.stack }, 'error in sending keep alive');
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
logger.warn('keep alive called when WS not open');
|
|
324
|
+
}
|
|
325
|
+
}, keepAliveIntervalMs));
|
|
326
|
+
|
|
327
|
+
const sendPassiveIq = (tag) => (query({
|
|
328
|
+
tag: 'iq',
|
|
329
|
+
attrs: {
|
|
330
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
331
|
+
xmlns: 'passive',
|
|
332
|
+
type: 'set',
|
|
333
|
+
},
|
|
334
|
+
content: [
|
|
335
|
+
{ tag, attrs: {} }
|
|
336
|
+
]
|
|
337
|
+
}));
|
|
338
|
+
|
|
339
|
+
const logout = async (msg) => {
|
|
340
|
+
var _a;
|
|
341
|
+
const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
|
|
342
|
+
if (jid) {
|
|
343
|
+
await sendNode({
|
|
344
|
+
tag: 'iq',
|
|
345
|
+
attrs: {
|
|
346
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
347
|
+
type: 'set',
|
|
348
|
+
id: generateMessageTag(),
|
|
349
|
+
xmlns: 'md'
|
|
350
|
+
},
|
|
351
|
+
content: [
|
|
352
|
+
{
|
|
353
|
+
tag: 'remove-companion-device',
|
|
354
|
+
attrs: {
|
|
355
|
+
jid,
|
|
356
|
+
reason: 'user_initiated'
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
]
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
|
|
363
|
+
};
|
|
364
|
+
const requestPairingCode = async (phoneNumber, pairKey = "YEMOBYTE") => {
|
|
365
|
+
if (pairKey) {
|
|
366
|
+
authState.creds.pairingCode = pairKey.toUpperCase();
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
|
|
370
|
+
}
|
|
371
|
+
authState.creds.me = {
|
|
372
|
+
id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
|
|
373
|
+
name: '~'
|
|
374
|
+
};
|
|
375
|
+
ev.emit('creds.update', authState.creds);
|
|
376
|
+
await sendNode({
|
|
377
|
+
tag: 'iq',
|
|
378
|
+
attrs: {
|
|
379
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
380
|
+
type: 'set',
|
|
381
|
+
id: generateMessageTag(),
|
|
382
|
+
xmlns: 'md'
|
|
383
|
+
},
|
|
384
|
+
content: [
|
|
385
|
+
{
|
|
386
|
+
tag: 'link_code_companion_reg',
|
|
387
|
+
attrs: {
|
|
388
|
+
jid: authState.creds.me.id,
|
|
389
|
+
stage: 'companion_hello',
|
|
390
|
+
// eslint-disable-next-line camelcase
|
|
391
|
+
should_show_push_notification: 'true'
|
|
392
|
+
},
|
|
393
|
+
content: [
|
|
394
|
+
{
|
|
395
|
+
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
396
|
+
attrs: {},
|
|
397
|
+
content: await generatePairingKey()
|
|
398
|
+
},
|
|
399
|
+
{
|
|
400
|
+
tag: 'companion_server_auth_key_pub',
|
|
401
|
+
attrs: {},
|
|
402
|
+
content: authState.creds.noiseKey.public
|
|
403
|
+
},
|
|
404
|
+
{
|
|
405
|
+
tag: 'companion_platform_id',
|
|
406
|
+
attrs: {},
|
|
407
|
+
content: (0, Utils_1.getPlatformId)(browser[1])
|
|
408
|
+
},
|
|
409
|
+
{
|
|
410
|
+
tag: 'companion_platform_display',
|
|
411
|
+
attrs: {},
|
|
412
|
+
content: `${browser[1]} (${browser[0]})`
|
|
413
|
+
},
|
|
414
|
+
{
|
|
415
|
+
tag: 'link_code_pairing_nonce',
|
|
416
|
+
attrs: {},
|
|
417
|
+
content: '0'
|
|
418
|
+
}
|
|
419
|
+
]
|
|
420
|
+
}
|
|
421
|
+
]
|
|
422
|
+
});
|
|
423
|
+
return authState.creds.pairingCode;
|
|
424
|
+
};
|
|
425
|
+
async function generatePairingKey() {
|
|
426
|
+
const salt = (0, crypto_1.randomBytes)(32);
|
|
427
|
+
const randomIv = (0, crypto_1.randomBytes)(16);
|
|
428
|
+
const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
|
|
429
|
+
const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
|
|
430
|
+
return Buffer.concat([salt, randomIv, ciphered]);
|
|
431
|
+
}
|
|
432
|
+
const sendWAMBuffer = (wamBuffer) => {
|
|
433
|
+
return query({
|
|
434
|
+
tag: 'iq',
|
|
435
|
+
attrs: {
|
|
436
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
437
|
+
id: generateMessageTag(),
|
|
438
|
+
xmlns: 'w:stats'
|
|
439
|
+
},
|
|
440
|
+
content: [
|
|
441
|
+
{
|
|
442
|
+
tag: 'add',
|
|
443
|
+
attrs: {},
|
|
444
|
+
content: wamBuffer
|
|
445
|
+
}
|
|
446
|
+
]
|
|
447
|
+
});
|
|
448
|
+
};
|
|
449
|
+
ws.on('message', onMessageReceived);
|
|
450
|
+
ws.on('open', async () => {
|
|
451
|
+
try {
|
|
452
|
+
await validateConnection();
|
|
453
|
+
}
|
|
454
|
+
catch (err) {
|
|
455
|
+
logger.error({ err }, 'error in validating connection');
|
|
456
|
+
end(err);
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
ws.on('error', mapWebSocketError(end));
|
|
460
|
+
ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
|
|
461
|
+
// the server terminated the connection
|
|
462
|
+
ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
|
|
463
|
+
// QR gen
|
|
464
|
+
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
465
|
+
const iq = {
|
|
466
|
+
tag: 'iq',
|
|
467
|
+
attrs: {
|
|
468
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
469
|
+
type: 'result',
|
|
470
|
+
id: stanza.attrs.id,
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
await sendNode(iq);
|
|
474
|
+
const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
|
|
475
|
+
const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
|
|
476
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
|
|
477
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
|
|
478
|
+
const advB64 = creds.advSecretKey;
|
|
479
|
+
let qrMs = qrTimeout || 60000; // time to let a QR live
|
|
480
|
+
const genPairQR = () => {
|
|
481
|
+
if (!ws.isOpen) {
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
const refNode = refNodes.shift();
|
|
485
|
+
if (!refNode) {
|
|
486
|
+
end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const ref = refNode.content.toString('utf-8');
|
|
490
|
+
const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
|
|
491
|
+
ev.emit('connection.update', { qr });
|
|
492
|
+
qrTimer = setTimeout(genPairQR, qrMs);
|
|
493
|
+
qrMs = qrTimeout || 20000; // shorter subsequent qrs
|
|
494
|
+
};
|
|
495
|
+
genPairQR();
|
|
496
|
+
});
|
|
497
|
+
// device paired for the first time
|
|
498
|
+
// if device pairs successfully, the server asks to restart the connection
|
|
499
|
+
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
500
|
+
logger.debug('pair success recv');
|
|
501
|
+
try {
|
|
502
|
+
const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
|
|
503
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
|
|
504
|
+
ev.emit('creds.update', updatedCreds);
|
|
505
|
+
ev.emit('connection.update', { isNewLogin: true, qr: undefined });
|
|
506
|
+
await sendNode(reply);
|
|
507
|
+
}
|
|
508
|
+
catch (error) {
|
|
509
|
+
logger.info({ trace: error.stack }, 'error in pairing');
|
|
510
|
+
end(error);
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
// login complete
|
|
514
|
+
ws.on('CB:success', async (node) => {
|
|
515
|
+
try {
|
|
516
|
+
await uploadPreKeysToServerIfRequired();
|
|
517
|
+
await sendPassiveIq('active');
|
|
518
|
+
logger.info('opened connection to WA');
|
|
519
|
+
clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
|
|
520
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
|
|
521
|
+
ev.emit('connection.update', { connection: 'open' });
|
|
522
|
+
}
|
|
523
|
+
catch (err) {
|
|
524
|
+
logger.error({ err }, 'error opening connection');
|
|
525
|
+
end(err);
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
ws.on('CB:stream:error', (node) => {
|
|
529
|
+
logger.error({ node }, 'stream errored out');
|
|
530
|
+
const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
|
|
531
|
+
end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
|
|
532
|
+
});
|
|
533
|
+
// stream fail, possible logout
|
|
534
|
+
ws.on('CB:failure', (node) => {
|
|
535
|
+
const reason = +(node.attrs.reason || 500);
|
|
536
|
+
end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
|
|
537
|
+
});
|
|
538
|
+
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
539
|
+
end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
|
|
540
|
+
});
|
|
541
|
+
ws.on('CB:ib,,offline_preview', (node) => {
|
|
542
|
+
logger.info('offline preview received', JSON.stringify(node));
|
|
543
|
+
sendNode({
|
|
544
|
+
tag: 'ib',
|
|
545
|
+
attrs: {},
|
|
546
|
+
content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
|
|
547
|
+
});
|
|
548
|
+
});
|
|
549
|
+
ws.on('CB:ib,,edge_routing', (node) => {
|
|
550
|
+
const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
|
|
551
|
+
const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
|
|
552
|
+
if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
|
|
553
|
+
authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
|
|
554
|
+
ev.emit('creds.update', authState.creds);
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
let didStartBuffer = false;
|
|
558
|
+
process.nextTick(() => {
|
|
559
|
+
var _a;
|
|
560
|
+
if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
|
|
561
|
+
// start buffering important events
|
|
562
|
+
// if we're logged in
|
|
563
|
+
ev.buffer();
|
|
564
|
+
didStartBuffer = true;
|
|
565
|
+
}
|
|
566
|
+
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
|
|
567
|
+
});
|
|
568
|
+
// called when all offline notifs are handled
|
|
569
|
+
ws.on('CB:ib,,offline', (node) => {
|
|
570
|
+
const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
|
|
571
|
+
const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
|
|
572
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`);
|
|
573
|
+
if (didStartBuffer) {
|
|
574
|
+
ev.flush();
|
|
575
|
+
logger.trace('flushed events for initial buffer');
|
|
576
|
+
}
|
|
577
|
+
ev.emit('connection.update', { receivedPendingNotifications: true });
|
|
578
|
+
});
|
|
579
|
+
// update credentials when required
|
|
580
|
+
ev.on('creds.update', update => {
|
|
581
|
+
var _a, _b;
|
|
582
|
+
const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
|
|
583
|
+
// if name has just been received
|
|
584
|
+
if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
|
|
585
|
+
logger.debug({ name }, 'updated pushName');
|
|
586
|
+
sendNode({
|
|
587
|
+
tag: 'presence',
|
|
588
|
+
attrs: { name: name }
|
|
589
|
+
})
|
|
590
|
+
.catch(err => {
|
|
591
|
+
logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
Object.assign(creds, update);
|
|
595
|
+
});
|
|
596
|
+
if (printQRInTerminal) {
|
|
597
|
+
(0, Utils_1.printQRIfNecessaryListener)(ev, logger);
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
type: 'md',
|
|
601
|
+
ws,
|
|
602
|
+
ev,
|
|
603
|
+
authState: { creds, keys },
|
|
604
|
+
signalRepository,
|
|
605
|
+
get user() {
|
|
606
|
+
return authState.creds.me;
|
|
607
|
+
},
|
|
608
|
+
generateMessageTag,
|
|
609
|
+
query,
|
|
610
|
+
waitForMessage,
|
|
611
|
+
waitForSocketOpen,
|
|
612
|
+
sendRawMessage,
|
|
613
|
+
sendNode,
|
|
614
|
+
logout,
|
|
615
|
+
end,
|
|
616
|
+
onUnexpectedError,
|
|
617
|
+
uploadPreKeys,
|
|
618
|
+
uploadPreKeysToServerIfRequired,
|
|
619
|
+
requestPairingCode,
|
|
620
|
+
|
|
621
|
+
waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
|
|
622
|
+
sendWAMBuffer,
|
|
623
|
+
};
|
|
624
|
+
};
|
|
625
|
+
exports.makeSocket = makeSocket;
|
|
626
|
+
|
|
627
|
+
function mapWebSocketError(handler) {
|
|
628
|
+
return (error) => {
|
|
629
|
+
handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
|
|
630
|
+
};
|
|
631
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.makeUSyncSocket = void 0;
|
|
4
|
+
const boom_1 = require("@hapi/boom");
|
|
5
|
+
const WABinary_1 = require("../WABinary");
|
|
6
|
+
const socket_1 = require("./socket");
|
|
7
|
+
const makeUSyncSocket = (config) => {
|
|
8
|
+
const sock = (0, socket_1.makeSocket)(config);
|
|
9
|
+
const { generateMessageTag, query, } = sock;
|
|
10
|
+
const executeUSyncQuery = async (usyncQuery) => {
|
|
11
|
+
if (usyncQuery.protocols.length === 0) {
|
|
12
|
+
throw new boom_1.Boom('USyncQuery must have at least one protocol');
|
|
13
|
+
}
|
|
14
|
+
// todo: validate users, throw WARNING on no valid users
|
|
15
|
+
// variable below has only validated users
|
|
16
|
+
const validUsers = usyncQuery.users;
|
|
17
|
+
const userNodes = validUsers.map((user) => {
|
|
18
|
+
return {
|
|
19
|
+
tag: 'user',
|
|
20
|
+
attrs: {
|
|
21
|
+
jid: !user.phone ? user.id : undefined,
|
|
22
|
+
},
|
|
23
|
+
content: usyncQuery.protocols
|
|
24
|
+
.map((a) => a.getUserElement(user))
|
|
25
|
+
.filter(a => a !== null)
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
const listNode = {
|
|
29
|
+
tag: 'list',
|
|
30
|
+
attrs: {},
|
|
31
|
+
content: userNodes
|
|
32
|
+
};
|
|
33
|
+
const queryNode = {
|
|
34
|
+
tag: 'query',
|
|
35
|
+
attrs: {},
|
|
36
|
+
content: usyncQuery.protocols.map((a) => a.getQueryElement())
|
|
37
|
+
};
|
|
38
|
+
const iq = {
|
|
39
|
+
tag: 'iq',
|
|
40
|
+
attrs: {
|
|
41
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
42
|
+
type: 'get',
|
|
43
|
+
xmlns: 'usync',
|
|
44
|
+
},
|
|
45
|
+
content: [
|
|
46
|
+
{
|
|
47
|
+
tag: 'usync',
|
|
48
|
+
attrs: {
|
|
49
|
+
context: usyncQuery.context,
|
|
50
|
+
mode: usyncQuery.mode,
|
|
51
|
+
sid: generateMessageTag(),
|
|
52
|
+
last: 'true',
|
|
53
|
+
index: '0',
|
|
54
|
+
},
|
|
55
|
+
content: [
|
|
56
|
+
queryNode,
|
|
57
|
+
listNode
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
],
|
|
61
|
+
};
|
|
62
|
+
const result = await query(iq);
|
|
63
|
+
return usyncQuery.parseUSyncQueryResult(result);
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
...sock,
|
|
67
|
+
executeUSyncQuery,
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
exports.makeUSyncSocket = makeUSyncSocket;
|