@vanzxy/baileys 1.4.0 → 1.4.2
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/cjs/WAProto/index.js +106053 -0
- package/cjs/lib/Defaults/index.js +168 -0
- package/cjs/lib/Signal/Group/ciphertext-message.js +16 -0
- package/cjs/lib/Signal/Group/group-session-builder.js +67 -0
- package/cjs/lib/Signal/Group/group_cipher.js +86 -0
- package/cjs/lib/Signal/Group/index.js +58 -0
- package/cjs/lib/Signal/Group/keyhelper.js +56 -0
- package/cjs/lib/Signal/Group/sender-chain-key.js +30 -0
- package/cjs/lib/Signal/Group/sender-key-distribution-message.js +67 -0
- package/cjs/lib/Signal/Group/sender-key-message.js +70 -0
- package/cjs/lib/Signal/Group/sender-key-name.js +52 -0
- package/cjs/lib/Signal/Group/sender-key-record.js +45 -0
- package/cjs/lib/Signal/Group/sender-key-state.js +88 -0
- package/cjs/lib/Signal/Group/sender-message-key.js +30 -0
- package/cjs/lib/Signal/libsignal.js +467 -0
- package/cjs/lib/Signal/lid-mapping.js +281 -0
- package/cjs/lib/Socket/Client/index.js +19 -0
- package/cjs/lib/Socket/Client/types.js +15 -0
- package/cjs/lib/Socket/Client/websocket.js +61 -0
- package/cjs/lib/Socket/business.js +384 -0
- package/cjs/lib/Socket/chats.js +1257 -0
- package/cjs/lib/Socket/communities.js +442 -0
- package/cjs/lib/Socket/dugong.js +753 -0
- package/cjs/lib/Socket/groups.js +360 -0
- package/cjs/lib/Socket/index.js +19 -0
- package/cjs/lib/Socket/messages-recv.js +1790 -0
- package/cjs/lib/Socket/messages-send.js +1390 -0
- package/cjs/lib/Socket/mex.js +46 -0
- package/cjs/lib/Socket/newsletter.js +340 -0
- package/cjs/lib/Socket/socket.js +1007 -0
- package/cjs/lib/Store/index.js +20 -0
- package/cjs/lib/Store/make-in-memory-store.js +438 -0
- package/cjs/lib/Store/make-ordered-dictionary.js +82 -0
- package/cjs/lib/Store/object-repository.js +28 -0
- package/cjs/lib/Types/Auth.js +3 -0
- package/cjs/lib/Types/Bussines.js +3 -0
- package/cjs/lib/Types/Call.js +3 -0
- package/cjs/lib/Types/Chat.js +11 -0
- package/cjs/lib/Types/Contact.js +3 -0
- package/cjs/lib/Types/Events.js +4 -0
- package/cjs/lib/Types/GroupMetadata.js +3 -0
- package/cjs/lib/Types/Label.js +26 -0
- package/cjs/lib/Types/LabelAssociation.js +8 -0
- package/cjs/lib/Types/Message.js +19 -0
- package/cjs/lib/Types/Mex.js +40 -0
- package/cjs/lib/Types/Product.js +3 -0
- package/cjs/lib/Types/RichType.js +24 -0
- package/cjs/lib/Types/Signal.js +4 -0
- package/cjs/lib/Types/Socket.js +4 -0
- package/cjs/lib/Types/State.js +54 -0
- package/cjs/lib/Types/USync.js +4 -0
- package/cjs/lib/Types/index.js +42 -0
- package/cjs/lib/Utils/MessageBuilder.js +2164 -0
- package/cjs/lib/Utils/auth-utils.js +312 -0
- package/cjs/lib/Utils/browser-utils.js +32 -0
- package/cjs/lib/Utils/business.js +245 -0
- package/cjs/lib/Utils/chat-utils.js +937 -0
- package/cjs/lib/Utils/companion-reg-client-utils.js +45 -0
- package/cjs/lib/Utils/crypto.js +196 -0
- package/cjs/lib/Utils/decode-wa-message.js +324 -0
- package/cjs/lib/Utils/event-buffer.js +643 -0
- package/cjs/lib/Utils/generics.js +429 -0
- package/cjs/lib/Utils/history.js +151 -0
- package/cjs/lib/Utils/identity-change-handler.js +56 -0
- package/cjs/lib/Utils/index.js +42 -0
- package/cjs/lib/Utils/link-preview.js +122 -0
- package/cjs/lib/Utils/logger.js +8 -0
- package/cjs/lib/Utils/lt-hash.js +62 -0
- package/cjs/lib/Utils/make-mutex.js +38 -0
- package/cjs/lib/Utils/message-retry-manager.js +267 -0
- package/cjs/lib/Utils/messages-media.js +933 -0
- package/cjs/lib/Utils/messages.js +2175 -0
- package/cjs/lib/Utils/noise-handler.js +205 -0
- package/cjs/lib/Utils/offline-node-processor.js +43 -0
- package/cjs/lib/Utils/pre-key-manager.js +113 -0
- package/cjs/lib/Utils/process-message.js +772 -0
- package/cjs/lib/Utils/reporting-utils.js +263 -0
- package/cjs/lib/Utils/rich-message-utils.js +439 -0
- package/cjs/lib/Utils/signal.js +214 -0
- package/cjs/lib/Utils/stanza-ack.js +41 -0
- package/cjs/lib/Utils/sync-action-utils.js +54 -0
- package/cjs/lib/Utils/tc-token-utils.js +174 -0
- package/cjs/lib/Utils/use-multi-file-auth-state.js +125 -0
- package/cjs/lib/Utils/use-single-file-auth-state.js +121 -0
- package/cjs/lib/Utils/use-sqlite-auth-state.js +182 -0
- package/cjs/lib/Utils/validate-connection.js +210 -0
- package/cjs/lib/WABinary/constants.js +1470 -0
- package/cjs/lib/WABinary/decode.js +301 -0
- package/cjs/lib/WABinary/encode.js +257 -0
- package/cjs/lib/WABinary/generic-utils.js +274 -0
- package/cjs/lib/WABinary/index.js +22 -0
- package/cjs/lib/WABinary/jid-utils.js +114 -0
- package/cjs/lib/WABinary/types.js +37 -0
- package/cjs/lib/WAM/BinaryInfo.js +14 -0
- package/cjs/lib/WAM/constants.js +22856 -0
- package/cjs/lib/WAM/encode.js +154 -0
- package/cjs/lib/WAM/index.js +20 -0
- package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
- package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +67 -0
- package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
- package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
- package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +55 -0
- package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +33 -0
- package/cjs/lib/WAUSync/Protocols/index.js +24 -0
- package/cjs/lib/WAUSync/USyncQuery.js +126 -0
- package/cjs/lib/WAUSync/USyncUser.js +35 -0
- package/cjs/lib/WAUSync/index.js +20 -0
- package/cjs/lib/index.js +34 -0
- package/cjs/package.json +1 -0
- package/lib/Socket/messages-send.js +4 -3
- package/lib/Utils/messages.js +4 -1
- package/package.json +16 -5
- package/postinstall-banner.js +3 -2
|
@@ -0,0 +1,1007 @@
|
|
|
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 index_js_1 = require("../../WAProto/index.js");
|
|
9
|
+
const index_js_2 = require("../Defaults/index.js");
|
|
10
|
+
const index_js_3 = require("../Types/index.js");
|
|
11
|
+
const index_js_4 = require("../Types/index.js");
|
|
12
|
+
const index_js_5 = require("../Utils/index.js");
|
|
13
|
+
const index_js_6 = require("../WABinary/index.js");
|
|
14
|
+
const BinaryInfo_js_1 = require("../WAM/BinaryInfo.js");
|
|
15
|
+
const index_js_7 = require("../WAUSync/index.js");
|
|
16
|
+
const index_js_8 = require("./Client/index.js");
|
|
17
|
+
const mex_js_1 = require("./mex.js");
|
|
18
|
+
/**
|
|
19
|
+
* Connects to WA servers and performs:
|
|
20
|
+
* - simple queries (no retry mechanism, wait for connection establishment)
|
|
21
|
+
* - listen to messages and emit events
|
|
22
|
+
* - query phone connection
|
|
23
|
+
*/
|
|
24
|
+
const makeSocket = (config) => {
|
|
25
|
+
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
|
|
26
|
+
const publicWAMBuffer = new BinaryInfo_js_1.BinaryInfo();
|
|
27
|
+
let serverTimeOffsetMs = 0;
|
|
28
|
+
const uqTagId = (0, index_js_5.generateMdTagPrefix)();
|
|
29
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`;
|
|
30
|
+
if (printQRInTerminal) {
|
|
31
|
+
logger.warn({}, '⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
|
|
32
|
+
}
|
|
33
|
+
const syncDisabled = index_js_2.PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false)
|
|
34
|
+
.length === index_js_2.PROCESSABLE_HISTORY_TYPES.length;
|
|
35
|
+
if (syncDisabled) {
|
|
36
|
+
logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
|
|
37
|
+
}
|
|
38
|
+
const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
|
|
39
|
+
if (config.mobile || url.protocol === 'tcp:') {
|
|
40
|
+
throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: index_js_4.DisconnectReason.loggedOut });
|
|
41
|
+
}
|
|
42
|
+
if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
|
43
|
+
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
|
|
44
|
+
}
|
|
45
|
+
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
|
|
46
|
+
const ephemeralKeyPair = index_js_5.Curve.generateKeyPair();
|
|
47
|
+
/** WA noise protocol wrapper */
|
|
48
|
+
const noise = (0, index_js_5.makeNoiseHandler)({
|
|
49
|
+
keyPair: ephemeralKeyPair,
|
|
50
|
+
NOISE_HEADER: index_js_2.NOISE_WA_HEADER,
|
|
51
|
+
logger,
|
|
52
|
+
routingInfo: authState?.creds?.routingInfo
|
|
53
|
+
});
|
|
54
|
+
const ws = new index_js_8.WebSocketClient(url, config);
|
|
55
|
+
ws.connect();
|
|
56
|
+
const sendPromise = (0, util_1.promisify)(ws.send);
|
|
57
|
+
/** send a raw buffer */
|
|
58
|
+
const sendRawMessage = async (data) => {
|
|
59
|
+
if (!ws.isOpen) {
|
|
60
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: index_js_4.DisconnectReason.connectionClosed });
|
|
61
|
+
}
|
|
62
|
+
const bytes = noise.encodeFrame(data);
|
|
63
|
+
await (0, index_js_5.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
|
|
64
|
+
try {
|
|
65
|
+
await sendPromise.call(ws, bytes);
|
|
66
|
+
resolve();
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
reject(error);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
/** send a binary node */
|
|
74
|
+
const sendNode = (frame) => {
|
|
75
|
+
if (logger.level === 'trace') {
|
|
76
|
+
logger.trace({ xml: (0, index_js_6.binaryNodeToString)(frame), msg: 'xml send' });
|
|
77
|
+
}
|
|
78
|
+
const buff = (0, index_js_6.encodeBinaryNode)(frame);
|
|
79
|
+
return sendRawMessage(buff);
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Wait for a message with a certain tag to be received
|
|
83
|
+
* @param msgId the message tag to await
|
|
84
|
+
* @param timeoutMs timeout after which the promise will reject
|
|
85
|
+
*/
|
|
86
|
+
const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
|
|
87
|
+
let onRecv;
|
|
88
|
+
let onErr;
|
|
89
|
+
try {
|
|
90
|
+
const result = await (0, index_js_5.promiseTimeout)(timeoutMs, (resolve, reject) => {
|
|
91
|
+
onRecv = data => {
|
|
92
|
+
resolve(data);
|
|
93
|
+
};
|
|
94
|
+
onErr = err => {
|
|
95
|
+
reject(err ||
|
|
96
|
+
new boom_1.Boom('Connection Closed', {
|
|
97
|
+
statusCode: index_js_4.DisconnectReason.connectionClosed
|
|
98
|
+
}));
|
|
99
|
+
};
|
|
100
|
+
ws.on(`TAG:${msgId}`, onRecv);
|
|
101
|
+
ws.on('close', onErr);
|
|
102
|
+
ws.on('error', onErr);
|
|
103
|
+
return () => reject(new boom_1.Boom('Query Cancelled'));
|
|
104
|
+
});
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
// Catch timeout and return undefined instead of throwing
|
|
109
|
+
if (error instanceof boom_1.Boom && error.output?.statusCode === index_js_4.DisconnectReason.timedOut) {
|
|
110
|
+
logger?.warn?.({ msgId }, 'timed out waiting for message');
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
if (onRecv)
|
|
117
|
+
ws.off(`TAG:${msgId}`, onRecv);
|
|
118
|
+
if (onErr) {
|
|
119
|
+
ws.off('close', onErr);
|
|
120
|
+
ws.off('error', onErr);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
|
125
|
+
const query = async (node, timeoutMs) => {
|
|
126
|
+
if (!node.attrs.id) {
|
|
127
|
+
node.attrs.id = generateMessageTag();
|
|
128
|
+
}
|
|
129
|
+
const msgId = node.attrs.id;
|
|
130
|
+
const result = await (0, index_js_5.promiseTimeout)(timeoutMs, async (resolve, reject) => {
|
|
131
|
+
const result = waitForMessage(msgId, timeoutMs).catch(reject);
|
|
132
|
+
sendNode(node)
|
|
133
|
+
.then(async () => resolve(await result))
|
|
134
|
+
.catch(reject);
|
|
135
|
+
});
|
|
136
|
+
if (result && 'tag' in result) {
|
|
137
|
+
(0, index_js_6.assertNodeErrorFree)(result);
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
};
|
|
141
|
+
// Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
|
|
142
|
+
const digestKeyBundle = async () => {
|
|
143
|
+
const res = await query({
|
|
144
|
+
tag: 'iq',
|
|
145
|
+
attrs: { to: index_js_6.S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
|
|
146
|
+
content: [{ tag: 'digest', attrs: {} }]
|
|
147
|
+
});
|
|
148
|
+
const digestNode = (0, index_js_6.getBinaryNodeChild)(res, 'digest');
|
|
149
|
+
if (!digestNode) {
|
|
150
|
+
await uploadPreKeys();
|
|
151
|
+
throw new Error('encrypt/get digest returned no digest node');
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
// Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
|
|
155
|
+
const rotateSignedPreKey = async () => {
|
|
156
|
+
const newId = (creds.signedPreKey.keyId || 0) + 1;
|
|
157
|
+
const skey = await (0, index_js_5.signedKeyPair)(creds.signedIdentityKey, newId);
|
|
158
|
+
await query({
|
|
159
|
+
tag: 'iq',
|
|
160
|
+
attrs: { to: index_js_6.S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
|
|
161
|
+
content: [
|
|
162
|
+
{
|
|
163
|
+
tag: 'rotate',
|
|
164
|
+
attrs: {},
|
|
165
|
+
content: [(0, index_js_5.xmppSignedPreKey)(skey)]
|
|
166
|
+
}
|
|
167
|
+
]
|
|
168
|
+
});
|
|
169
|
+
// Persist new signed pre-key in creds
|
|
170
|
+
ev.emit('creds.update', { signedPreKey: skey });
|
|
171
|
+
};
|
|
172
|
+
const executeUSyncQuery = async (usyncQuery) => {
|
|
173
|
+
if (usyncQuery.protocols.length === 0) {
|
|
174
|
+
throw new boom_1.Boom('USyncQuery must have at least one protocol');
|
|
175
|
+
}
|
|
176
|
+
// todo: validate users, throw WARNING on no valid users
|
|
177
|
+
// variable below has only validated users
|
|
178
|
+
const validUsers = usyncQuery.users;
|
|
179
|
+
const userNodes = validUsers.map(user => {
|
|
180
|
+
return {
|
|
181
|
+
tag: 'user',
|
|
182
|
+
attrs: {
|
|
183
|
+
jid: !user.phone ? user.id : undefined
|
|
184
|
+
},
|
|
185
|
+
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
|
186
|
+
};
|
|
187
|
+
});
|
|
188
|
+
const listNode = {
|
|
189
|
+
tag: 'list',
|
|
190
|
+
attrs: {},
|
|
191
|
+
content: userNodes
|
|
192
|
+
};
|
|
193
|
+
const queryNode = {
|
|
194
|
+
tag: 'query',
|
|
195
|
+
attrs: {},
|
|
196
|
+
content: usyncQuery.protocols.map(a => a.getQueryElement())
|
|
197
|
+
};
|
|
198
|
+
const iq = {
|
|
199
|
+
tag: 'iq',
|
|
200
|
+
attrs: {
|
|
201
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
202
|
+
type: 'get',
|
|
203
|
+
xmlns: 'usync'
|
|
204
|
+
},
|
|
205
|
+
content: [
|
|
206
|
+
{
|
|
207
|
+
tag: 'usync',
|
|
208
|
+
attrs: {
|
|
209
|
+
context: usyncQuery.context,
|
|
210
|
+
mode: usyncQuery.mode,
|
|
211
|
+
sid: generateMessageTag(),
|
|
212
|
+
last: 'true',
|
|
213
|
+
index: '0'
|
|
214
|
+
},
|
|
215
|
+
content: [queryNode, listNode]
|
|
216
|
+
}
|
|
217
|
+
]
|
|
218
|
+
};
|
|
219
|
+
const result = await query(iq);
|
|
220
|
+
return usyncQuery.parseUSyncQueryResult(result);
|
|
221
|
+
};
|
|
222
|
+
const onWhatsApp = async (...phoneNumber) => {
|
|
223
|
+
let usyncQuery = new index_js_7.USyncQuery();
|
|
224
|
+
let contactEnabled = false;
|
|
225
|
+
const lidUsers = [];
|
|
226
|
+
for (const jid of phoneNumber) {
|
|
227
|
+
if ((0, index_js_6.isLidUser)(jid)) {
|
|
228
|
+
// Vanz@Fix (bug 7): was just warn+skip — now attempt PN lookup via LID mapping
|
|
229
|
+
lidUsers.push(jid);
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
if (!contactEnabled) {
|
|
234
|
+
contactEnabled = true;
|
|
235
|
+
usyncQuery = usyncQuery.withContactProtocol();
|
|
236
|
+
}
|
|
237
|
+
const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
|
|
238
|
+
usyncQuery.withUser(new index_js_7.USyncUser().withPhone(phone));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
// Fallback: resolve LID -> PN, then check PN on WA
|
|
242
|
+
if (lidUsers.length > 0) {
|
|
243
|
+
try {
|
|
244
|
+
const pnMappings = await pnFromLIDUSync(lidUsers);
|
|
245
|
+
for (const { pn } of pnMappings) {
|
|
246
|
+
if (pn) {
|
|
247
|
+
if (!contactEnabled) {
|
|
248
|
+
contactEnabled = true;
|
|
249
|
+
usyncQuery = usyncQuery.withContactProtocol();
|
|
250
|
+
}
|
|
251
|
+
const phone = `+${pn.split('@')[0]?.split(':')[0]}`;
|
|
252
|
+
usyncQuery.withUser(new index_js_7.USyncUser().withPhone(phone));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
catch (e) {
|
|
257
|
+
logger?.warn({ e, lidUsers }, 'onWhatsApp: LID->PN fallback failed');
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (usyncQuery.users.length === 0) {
|
|
261
|
+
return []; // return early without forcing an empty query
|
|
262
|
+
}
|
|
263
|
+
const results = await executeUSyncQuery(usyncQuery);
|
|
264
|
+
if (results) {
|
|
265
|
+
return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
const pnFromLIDUSync = async (jids) => {
|
|
269
|
+
const usyncQuery = new index_js_7.USyncQuery().withLIDProtocol().withContext('background');
|
|
270
|
+
for (const jid of jids) {
|
|
271
|
+
if ((0, index_js_6.isLidUser)(jid)) {
|
|
272
|
+
logger?.warn('LID user found in LID fetch call');
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
usyncQuery.withUser(new index_js_7.USyncUser().withId(jid));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (usyncQuery.users.length === 0) {
|
|
280
|
+
return []; // return early without forcing an empty query
|
|
281
|
+
}
|
|
282
|
+
const results = await executeUSyncQuery(usyncQuery);
|
|
283
|
+
if (results) {
|
|
284
|
+
return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
|
|
285
|
+
}
|
|
286
|
+
return [];
|
|
287
|
+
};
|
|
288
|
+
const ev = (0, index_js_5.makeEventBuffer)(logger, config.eventBufferTimeoutMs);
|
|
289
|
+
const { creds } = authState;
|
|
290
|
+
// add transaction capability
|
|
291
|
+
const keys = (0, index_js_5.addTransactionCapability)(authState.keys, logger, transactionOpts);
|
|
292
|
+
const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
|
|
293
|
+
let lastDateRecv;
|
|
294
|
+
let epoch = 1;
|
|
295
|
+
let keepAliveReq;
|
|
296
|
+
let qrTimer;
|
|
297
|
+
let closed = false;
|
|
298
|
+
const socketEndHandlers = [];
|
|
299
|
+
/** log & process any unexpected errors */
|
|
300
|
+
const onUnexpectedError = (err, msg) => {
|
|
301
|
+
logger.error({ err }, `unexpected error in '${msg}'`);
|
|
302
|
+
};
|
|
303
|
+
/** await the next incoming message */
|
|
304
|
+
const awaitNextMessage = async (sendMsg) => {
|
|
305
|
+
if (!ws.isOpen) {
|
|
306
|
+
throw new boom_1.Boom('Connection Closed', {
|
|
307
|
+
statusCode: index_js_4.DisconnectReason.connectionClosed
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
let onOpen;
|
|
311
|
+
let onClose;
|
|
312
|
+
const result = (0, index_js_5.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
|
|
313
|
+
onOpen = resolve;
|
|
314
|
+
onClose = mapWebSocketError(reject);
|
|
315
|
+
ws.on('frame', onOpen);
|
|
316
|
+
ws.on('close', onClose);
|
|
317
|
+
ws.on('error', onClose);
|
|
318
|
+
}).finally(() => {
|
|
319
|
+
ws.off('frame', onOpen);
|
|
320
|
+
ws.off('close', onClose);
|
|
321
|
+
ws.off('error', onClose);
|
|
322
|
+
});
|
|
323
|
+
if (sendMsg) {
|
|
324
|
+
sendRawMessage(sendMsg).catch(onClose);
|
|
325
|
+
}
|
|
326
|
+
return result;
|
|
327
|
+
};
|
|
328
|
+
/** connection handshake */
|
|
329
|
+
const validateConnection = async () => {
|
|
330
|
+
let helloMsg = {
|
|
331
|
+
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
332
|
+
};
|
|
333
|
+
helloMsg = index_js_1.proto.HandshakeMessage.fromObject(helloMsg);
|
|
334
|
+
logger.info({ browser, helloMsg }, 'connected to WA');
|
|
335
|
+
const init = index_js_1.proto.HandshakeMessage.encode(helloMsg).finish();
|
|
336
|
+
const result = await awaitNextMessage(init);
|
|
337
|
+
const handshake = index_js_1.proto.HandshakeMessage.decode(result);
|
|
338
|
+
logger.trace({ handshake }, 'handshake recv from WA');
|
|
339
|
+
const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
|
|
340
|
+
let node;
|
|
341
|
+
if (!creds.me) {
|
|
342
|
+
node = (0, index_js_5.generateRegistrationNode)(creds, config);
|
|
343
|
+
logger.info({ node }, 'not logged in, attempting registration...');
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
node = (0, index_js_5.generateLoginNode)(creds.me.id, config);
|
|
347
|
+
logger.info({ node }, 'logging in...');
|
|
348
|
+
}
|
|
349
|
+
const payloadEnc = noise.encrypt(index_js_1.proto.ClientPayload.encode(node).finish());
|
|
350
|
+
await sendRawMessage(index_js_1.proto.HandshakeMessage.encode({
|
|
351
|
+
clientFinish: {
|
|
352
|
+
static: keyEnc,
|
|
353
|
+
payload: payloadEnc
|
|
354
|
+
}
|
|
355
|
+
}).finish());
|
|
356
|
+
await noise.finishInit();
|
|
357
|
+
startKeepAliveRequest();
|
|
358
|
+
};
|
|
359
|
+
const getAvailablePreKeysOnServer = async () => {
|
|
360
|
+
const result = await query({
|
|
361
|
+
tag: 'iq',
|
|
362
|
+
attrs: {
|
|
363
|
+
id: generateMessageTag(),
|
|
364
|
+
xmlns: 'encrypt',
|
|
365
|
+
type: 'get',
|
|
366
|
+
to: index_js_6.S_WHATSAPP_NET
|
|
367
|
+
},
|
|
368
|
+
content: [{ tag: 'count', attrs: {} }]
|
|
369
|
+
});
|
|
370
|
+
const countChild = (0, index_js_6.getBinaryNodeChild)(result, 'count');
|
|
371
|
+
return +countChild.attrs.value;
|
|
372
|
+
};
|
|
373
|
+
// WAWeb has no time throttle here; the server drives uploads via PreKeyLow notifications.
|
|
374
|
+
let uploadPreKeysPromise = null;
|
|
375
|
+
/** generates and uploads a set of pre-keys to the server */
|
|
376
|
+
const uploadPreKeys = async (count = index_js_2.MIN_PREKEY_COUNT) => {
|
|
377
|
+
if (uploadPreKeysPromise) {
|
|
378
|
+
logger.debug('Pre-key upload already in progress, waiting for completion');
|
|
379
|
+
await uploadPreKeysPromise;
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const uploadLogic = async (retryCount) => {
|
|
383
|
+
logger.info({ count, retryCount }, 'uploading pre-keys');
|
|
384
|
+
// Generate and save pre-keys atomically (prevents ID collisions on retry)
|
|
385
|
+
const node = await keys.transaction(async () => {
|
|
386
|
+
logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
|
|
387
|
+
const { update, node } = await (0, index_js_5.getNextPreKeysNode)({ creds, keys }, count);
|
|
388
|
+
// Update credentials immediately to prevent duplicate IDs on retry
|
|
389
|
+
ev.emit('creds.update', update);
|
|
390
|
+
return node;
|
|
391
|
+
}, creds?.me?.id || 'upload-pre-keys');
|
|
392
|
+
// Upload to server (outside transaction, can fail without affecting local keys)
|
|
393
|
+
try {
|
|
394
|
+
await query(node);
|
|
395
|
+
logger.info({ count }, 'uploaded pre-keys successfully');
|
|
396
|
+
}
|
|
397
|
+
catch (uploadError) {
|
|
398
|
+
logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
|
|
399
|
+
// Recurse into uploadLogic; calling uploadPreKeys would await its own in-flight promise.
|
|
400
|
+
if (retryCount < 3) {
|
|
401
|
+
const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
|
|
402
|
+
logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
|
|
403
|
+
await new Promise(resolve => setTimeout(resolve, backoffDelay));
|
|
404
|
+
return uploadLogic(retryCount + 1);
|
|
405
|
+
}
|
|
406
|
+
throw uploadError;
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
// Add timeout protection
|
|
410
|
+
uploadPreKeysPromise = Promise.race([
|
|
411
|
+
uploadLogic(0),
|
|
412
|
+
new Promise((_, reject) => setTimeout(() => reject(new boom_1.Boom('Pre-key upload timeout', { statusCode: 408 })), index_js_2.UPLOAD_TIMEOUT))
|
|
413
|
+
]);
|
|
414
|
+
try {
|
|
415
|
+
await uploadPreKeysPromise;
|
|
416
|
+
}
|
|
417
|
+
finally {
|
|
418
|
+
uploadPreKeysPromise = null;
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
const verifyCurrentPreKeyExists = async () => {
|
|
422
|
+
const currentPreKeyId = creds.nextPreKeyId - 1;
|
|
423
|
+
if (currentPreKeyId <= 0) {
|
|
424
|
+
return { exists: false, currentPreKeyId: 0 };
|
|
425
|
+
}
|
|
426
|
+
const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
|
|
427
|
+
const exists = !!preKeys[currentPreKeyId.toString()];
|
|
428
|
+
return { exists, currentPreKeyId };
|
|
429
|
+
};
|
|
430
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
431
|
+
try {
|
|
432
|
+
let count = 0;
|
|
433
|
+
const preKeyCount = await getAvailablePreKeysOnServer();
|
|
434
|
+
if (preKeyCount === 0)
|
|
435
|
+
count = index_js_2.INITIAL_PREKEY_COUNT;
|
|
436
|
+
else
|
|
437
|
+
count = index_js_2.MIN_PREKEY_COUNT;
|
|
438
|
+
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
|
|
439
|
+
logger.info(`${preKeyCount} pre-keys found on server`);
|
|
440
|
+
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
|
|
441
|
+
const lowServerCount = preKeyCount <= count;
|
|
442
|
+
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
|
|
443
|
+
const shouldUpload = lowServerCount || missingCurrentPreKey;
|
|
444
|
+
if (shouldUpload) {
|
|
445
|
+
const reasons = [];
|
|
446
|
+
if (lowServerCount)
|
|
447
|
+
reasons.push(`server count low (${preKeyCount})`);
|
|
448
|
+
if (missingCurrentPreKey)
|
|
449
|
+
reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
|
|
450
|
+
logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
|
|
451
|
+
await uploadPreKeys(count);
|
|
452
|
+
}
|
|
453
|
+
else {
|
|
454
|
+
logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
catch (error) {
|
|
458
|
+
logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
|
|
459
|
+
// Don't throw - allow connection to continue even if pre-key check fails
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
const onMessageReceived = async (data) => {
|
|
463
|
+
await noise.decodeFrame(data, frame => {
|
|
464
|
+
// reset ping timeout
|
|
465
|
+
lastDateRecv = new Date();
|
|
466
|
+
let anyTriggered = false;
|
|
467
|
+
anyTriggered = ws.emit('frame', frame);
|
|
468
|
+
// if it's a binary node
|
|
469
|
+
if (!(frame instanceof Uint8Array)) {
|
|
470
|
+
const msgId = frame.attrs.id;
|
|
471
|
+
if (logger.level === 'trace') {
|
|
472
|
+
logger.trace({ xml: (0, index_js_6.binaryNodeToString)(frame), msg: 'recv xml' });
|
|
473
|
+
}
|
|
474
|
+
/* Check if this is a response to a message we sent */
|
|
475
|
+
anyTriggered = ws.emit(`${index_js_2.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
|
|
476
|
+
/* Check if this is a response to a message we are expecting */
|
|
477
|
+
const l0 = frame.tag;
|
|
478
|
+
const l1 = frame.attrs || {};
|
|
479
|
+
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
|
|
480
|
+
for (const key of Object.keys(l1)) {
|
|
481
|
+
anyTriggered = ws.emit(`${index_js_2.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
|
|
482
|
+
anyTriggered = ws.emit(`${index_js_2.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
|
|
483
|
+
anyTriggered = ws.emit(`${index_js_2.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
|
|
484
|
+
}
|
|
485
|
+
anyTriggered = ws.emit(`${index_js_2.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
|
|
486
|
+
anyTriggered = ws.emit(`${index_js_2.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
|
|
487
|
+
if (!anyTriggered && logger.level === 'debug') {
|
|
488
|
+
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
};
|
|
493
|
+
const end = async (error) => {
|
|
494
|
+
if (closed) {
|
|
495
|
+
logger.trace({ trace: error?.stack }, 'connection already closed');
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
closed = true;
|
|
499
|
+
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
|
|
500
|
+
clearInterval(keepAliveReq);
|
|
501
|
+
clearTimeout(qrTimer);
|
|
502
|
+
ws.removeAllListeners('close');
|
|
503
|
+
ws.removeAllListeners('open');
|
|
504
|
+
ws.removeAllListeners('message');
|
|
505
|
+
signalRepository.close?.();
|
|
506
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
507
|
+
try {
|
|
508
|
+
await ws.close();
|
|
509
|
+
}
|
|
510
|
+
catch { }
|
|
511
|
+
}
|
|
512
|
+
for (const handler of socketEndHandlers) {
|
|
513
|
+
try {
|
|
514
|
+
await handler(error);
|
|
515
|
+
}
|
|
516
|
+
catch (err) {
|
|
517
|
+
logger.error({ err }, 'error in socket end handler');
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
ev.emit('connection.update', {
|
|
521
|
+
connection: 'close',
|
|
522
|
+
lastDisconnect: {
|
|
523
|
+
error,
|
|
524
|
+
date: new Date()
|
|
525
|
+
}
|
|
526
|
+
});
|
|
527
|
+
ev.removeAllListeners('connection.update');
|
|
528
|
+
ev.destroy();
|
|
529
|
+
};
|
|
530
|
+
const waitForSocketOpen = async () => {
|
|
531
|
+
if (ws.isOpen) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
if (ws.isClosed || ws.isClosing) {
|
|
535
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: index_js_4.DisconnectReason.connectionClosed });
|
|
536
|
+
}
|
|
537
|
+
let onOpen;
|
|
538
|
+
let onClose;
|
|
539
|
+
await new Promise((resolve, reject) => {
|
|
540
|
+
onOpen = () => resolve(undefined);
|
|
541
|
+
onClose = mapWebSocketError(reject);
|
|
542
|
+
ws.on('open', onOpen);
|
|
543
|
+
ws.on('close', onClose);
|
|
544
|
+
ws.on('error', onClose);
|
|
545
|
+
}).finally(() => {
|
|
546
|
+
ws.off('open', onOpen);
|
|
547
|
+
ws.off('close', onClose);
|
|
548
|
+
ws.off('error', onClose);
|
|
549
|
+
});
|
|
550
|
+
};
|
|
551
|
+
const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
|
|
552
|
+
if (!lastDateRecv) {
|
|
553
|
+
lastDateRecv = new Date();
|
|
554
|
+
}
|
|
555
|
+
const diff = Date.now() - lastDateRecv.getTime();
|
|
556
|
+
/*
|
|
557
|
+
check if it's been a suspicious amount of time since the server responded with our last seen
|
|
558
|
+
it could be that the network is down
|
|
559
|
+
*/
|
|
560
|
+
if (diff > keepAliveIntervalMs + 5000) {
|
|
561
|
+
void end(new boom_1.Boom('Connection was lost', { statusCode: index_js_4.DisconnectReason.connectionLost }));
|
|
562
|
+
}
|
|
563
|
+
else if (ws.isOpen) {
|
|
564
|
+
// if its all good, send a keep alive request
|
|
565
|
+
query({
|
|
566
|
+
tag: 'iq',
|
|
567
|
+
attrs: {
|
|
568
|
+
id: generateMessageTag(),
|
|
569
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
570
|
+
type: 'get',
|
|
571
|
+
xmlns: 'w:p'
|
|
572
|
+
},
|
|
573
|
+
content: [{ tag: 'ping', attrs: {} }]
|
|
574
|
+
}).catch(err => {
|
|
575
|
+
logger.error({ trace: err.stack }, 'error in sending keep alive');
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
logger.warn('keep alive called when WS not open');
|
|
580
|
+
}
|
|
581
|
+
}, keepAliveIntervalMs));
|
|
582
|
+
/** i have no idea why this exists. pls enlighten me */
|
|
583
|
+
const sendPassiveIq = (tag) => query({
|
|
584
|
+
tag: 'iq',
|
|
585
|
+
attrs: {
|
|
586
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
587
|
+
xmlns: 'passive',
|
|
588
|
+
type: 'set'
|
|
589
|
+
},
|
|
590
|
+
content: [{ tag, attrs: {} }]
|
|
591
|
+
});
|
|
592
|
+
/** logout & invalidate connection */
|
|
593
|
+
const logout = async (msg) => {
|
|
594
|
+
const jid = authState.creds.me?.id;
|
|
595
|
+
if (jid) {
|
|
596
|
+
await sendNode({
|
|
597
|
+
tag: 'iq',
|
|
598
|
+
attrs: {
|
|
599
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
600
|
+
type: 'set',
|
|
601
|
+
id: generateMessageTag(),
|
|
602
|
+
xmlns: 'md'
|
|
603
|
+
},
|
|
604
|
+
content: [
|
|
605
|
+
{
|
|
606
|
+
tag: 'remove-companion-device',
|
|
607
|
+
attrs: {
|
|
608
|
+
jid,
|
|
609
|
+
reason: 'user_initiated'
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
]
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
void end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: index_js_4.DisconnectReason.loggedOut }));
|
|
616
|
+
};
|
|
617
|
+
const requestPairingCode = async (phoneNumber, customPairingCode) => {
|
|
618
|
+
const pairingCode = customPairingCode ?? (0, index_js_5.bytesToCrockford)((0, crypto_1.randomBytes)(5));
|
|
619
|
+
if (customPairingCode && customPairingCode?.length !== 8) {
|
|
620
|
+
throw new Error('Custom pairing code must be exactly 8 chars');
|
|
621
|
+
}
|
|
622
|
+
authState.creds.pairingCode = pairingCode;
|
|
623
|
+
authState.creds.me = {
|
|
624
|
+
id: (0, index_js_6.jidEncode)(phoneNumber, 's.whatsapp.net'),
|
|
625
|
+
name: '~'
|
|
626
|
+
};
|
|
627
|
+
ev.emit('creds.update', authState.creds);
|
|
628
|
+
await sendNode({
|
|
629
|
+
tag: 'iq',
|
|
630
|
+
attrs: {
|
|
631
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
632
|
+
type: 'set',
|
|
633
|
+
id: generateMessageTag(),
|
|
634
|
+
xmlns: 'md'
|
|
635
|
+
},
|
|
636
|
+
content: [
|
|
637
|
+
{
|
|
638
|
+
tag: 'link_code_companion_reg',
|
|
639
|
+
attrs: {
|
|
640
|
+
jid: authState.creds.me.id,
|
|
641
|
+
stage: 'companion_hello',
|
|
642
|
+
should_show_push_notification: 'true'
|
|
643
|
+
},
|
|
644
|
+
content: [
|
|
645
|
+
{
|
|
646
|
+
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
647
|
+
attrs: {},
|
|
648
|
+
content: await generatePairingKey()
|
|
649
|
+
},
|
|
650
|
+
{
|
|
651
|
+
tag: 'companion_server_auth_key_pub',
|
|
652
|
+
attrs: {},
|
|
653
|
+
content: authState.creds.noiseKey.public
|
|
654
|
+
},
|
|
655
|
+
{
|
|
656
|
+
tag: 'companion_platform_id',
|
|
657
|
+
attrs: {},
|
|
658
|
+
content: (0, index_js_5.getCompanionPlatformId)(browser)
|
|
659
|
+
},
|
|
660
|
+
{
|
|
661
|
+
tag: 'companion_platform_display',
|
|
662
|
+
attrs: {},
|
|
663
|
+
content: `${browser[1]} (${browser[0]})`
|
|
664
|
+
},
|
|
665
|
+
{
|
|
666
|
+
tag: 'link_code_pairing_nonce',
|
|
667
|
+
attrs: {},
|
|
668
|
+
content: '0'
|
|
669
|
+
}
|
|
670
|
+
]
|
|
671
|
+
}
|
|
672
|
+
]
|
|
673
|
+
});
|
|
674
|
+
return authState.creds.pairingCode;
|
|
675
|
+
};
|
|
676
|
+
async function generatePairingKey() {
|
|
677
|
+
const salt = (0, crypto_1.randomBytes)(32);
|
|
678
|
+
const randomIv = (0, crypto_1.randomBytes)(16);
|
|
679
|
+
const key = await (0, index_js_5.derivePairingCodeKey)(authState.creds.pairingCode, salt);
|
|
680
|
+
const ciphered = (0, index_js_5.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
|
|
681
|
+
return Buffer.concat([salt, randomIv, ciphered]);
|
|
682
|
+
}
|
|
683
|
+
const sendWAMBuffer = (wamBuffer) => {
|
|
684
|
+
return query({
|
|
685
|
+
tag: 'iq',
|
|
686
|
+
attrs: {
|
|
687
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
688
|
+
id: generateMessageTag(),
|
|
689
|
+
xmlns: 'w:stats'
|
|
690
|
+
},
|
|
691
|
+
content: [
|
|
692
|
+
{
|
|
693
|
+
tag: 'add',
|
|
694
|
+
attrs: { t: Math.round(Date.now() / 1000) + '' },
|
|
695
|
+
content: wamBuffer
|
|
696
|
+
}
|
|
697
|
+
]
|
|
698
|
+
});
|
|
699
|
+
};
|
|
700
|
+
ws.on('message', onMessageReceived);
|
|
701
|
+
ws.on('open', async () => {
|
|
702
|
+
try {
|
|
703
|
+
await validateConnection();
|
|
704
|
+
}
|
|
705
|
+
catch (err) {
|
|
706
|
+
logger.error({ err }, 'error in validating connection');
|
|
707
|
+
void end(err);
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
ws.on('error', mapWebSocketError(end));
|
|
711
|
+
ws.on('close', () => void end(new boom_1.Boom('Connection Terminated', { statusCode: index_js_4.DisconnectReason.connectionClosed })));
|
|
712
|
+
// the server terminated the connection
|
|
713
|
+
ws.on('CB:xmlstreamend', () => void end(new boom_1.Boom('Connection Terminated by Server', { statusCode: index_js_4.DisconnectReason.connectionClosed })));
|
|
714
|
+
// QR gen
|
|
715
|
+
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
716
|
+
const iq = {
|
|
717
|
+
tag: 'iq',
|
|
718
|
+
attrs: {
|
|
719
|
+
to: index_js_6.S_WHATSAPP_NET,
|
|
720
|
+
type: 'result',
|
|
721
|
+
id: stanza.attrs.id
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
await sendNode(iq);
|
|
725
|
+
const pairDeviceNode = (0, index_js_6.getBinaryNodeChild)(stanza, 'pair-device');
|
|
726
|
+
const refNodes = (0, index_js_6.getBinaryNodeChildren)(pairDeviceNode, 'ref');
|
|
727
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
|
|
728
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
|
|
729
|
+
const advB64 = creds.advSecretKey;
|
|
730
|
+
let qrMs = qrTimeout || 60000; // time to let a QR live
|
|
731
|
+
const genPairQR = () => {
|
|
732
|
+
if (!ws.isOpen) {
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const refNode = refNodes.shift();
|
|
736
|
+
if (!refNode) {
|
|
737
|
+
void end(new boom_1.Boom('QR refs attempts ended', { statusCode: index_js_4.DisconnectReason.timedOut }));
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
const ref = refNode.content.toString('utf-8');
|
|
741
|
+
const qr = (0, index_js_5.buildPairingQRData)(ref, noiseKeyB64, identityKeyB64, advB64, browser);
|
|
742
|
+
ev.emit('connection.update', { qr });
|
|
743
|
+
qrTimer = setTimeout(genPairQR, qrMs);
|
|
744
|
+
qrMs = qrTimeout || 20000; // shorter subsequent qrs
|
|
745
|
+
};
|
|
746
|
+
genPairQR();
|
|
747
|
+
});
|
|
748
|
+
// device paired for the first time
|
|
749
|
+
// if device pairs successfully, the server asks to restart the connection
|
|
750
|
+
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
751
|
+
logger.debug('pair success recv');
|
|
752
|
+
try {
|
|
753
|
+
updateServerTimeOffset(stanza);
|
|
754
|
+
const { reply, creds: updatedCreds } = (0, index_js_5.configureSuccessfulPairing)(stanza, creds);
|
|
755
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
|
|
756
|
+
ev.emit('creds.update', updatedCreds);
|
|
757
|
+
ev.emit('connection.update', { isNewLogin: true, qr: undefined });
|
|
758
|
+
await sendNode(reply);
|
|
759
|
+
void sendUnifiedSession();
|
|
760
|
+
}
|
|
761
|
+
catch (error) {
|
|
762
|
+
logger.info({ trace: error.stack }, 'error in pairing');
|
|
763
|
+
void end(error);
|
|
764
|
+
}
|
|
765
|
+
});
|
|
766
|
+
// login complete
|
|
767
|
+
ws.on('CB:success', async (node) => {
|
|
768
|
+
try {
|
|
769
|
+
updateServerTimeOffset(node);
|
|
770
|
+
await uploadPreKeysToServerIfRequired();
|
|
771
|
+
// Vanz@Fix (bug 37): rotateSignedPreKey was never called automatically.
|
|
772
|
+
// WA expects periodic rotation. We trigger it once per connect if the key is old (>7 days).
|
|
773
|
+
try {
|
|
774
|
+
const keyAge = Date.now() - (creds.signedPreKey?.keyId ? (creds.signedPreKey.keyId * 0) : 0);
|
|
775
|
+
const lastRotation = creds.lastSignedPreKeyRotation || 0;
|
|
776
|
+
const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;
|
|
777
|
+
if (Date.now() - lastRotation > sevenDaysMs) {
|
|
778
|
+
await rotateSignedPreKey();
|
|
779
|
+
ev.emit('creds.update', { lastSignedPreKeyRotation: Date.now() });
|
|
780
|
+
logger.info('Rotated signed pre-key (periodic rotation)');
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
catch (e) {
|
|
784
|
+
logger.warn({ e }, 'failed to rotate signed pre-key');
|
|
785
|
+
}
|
|
786
|
+
await sendPassiveIq('active');
|
|
787
|
+
// After successful login, validate our key-bundle against server
|
|
788
|
+
try {
|
|
789
|
+
await digestKeyBundle();
|
|
790
|
+
}
|
|
791
|
+
catch (e) {
|
|
792
|
+
logger.warn({ e }, 'failed to run digest after login');
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
catch (err) {
|
|
796
|
+
logger.warn({ err }, 'failed to send initial passive iq');
|
|
797
|
+
}
|
|
798
|
+
logger.info('opened connection to WA');
|
|
799
|
+
clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
|
|
800
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
|
|
801
|
+
ev.emit('connection.update', { connection: 'open' });
|
|
802
|
+
void sendUnifiedSession();
|
|
803
|
+
if (node.attrs.lid && authState.creds.me?.id) {
|
|
804
|
+
const myLID = node.attrs.lid;
|
|
805
|
+
process.nextTick(async () => {
|
|
806
|
+
try {
|
|
807
|
+
const myPN = authState.creds.me.id;
|
|
808
|
+
// Store our own LID-PN mapping
|
|
809
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
|
|
810
|
+
// Create device list for our own user (needed for bulk migration)
|
|
811
|
+
const { user, device } = (0, index_js_6.jidDecode)(myPN);
|
|
812
|
+
await authState.keys.set({
|
|
813
|
+
'device-list': {
|
|
814
|
+
[user]: [device?.toString() || '0']
|
|
815
|
+
}
|
|
816
|
+
});
|
|
817
|
+
// migrate our own session
|
|
818
|
+
await signalRepository.migrateSession(myPN, myLID);
|
|
819
|
+
logger.info({ myPN, myLID }, 'Own LID session created successfully');
|
|
820
|
+
}
|
|
821
|
+
catch (error) {
|
|
822
|
+
logger.error({ error, lid: myLID }, 'Failed to create own LID session');
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
ws.on('CB:stream:error', (node) => {
|
|
828
|
+
const [reasonNode] = (0, index_js_6.getAllBinaryNodeChildren)(node);
|
|
829
|
+
logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
|
|
830
|
+
const { reason, statusCode } = (0, index_js_5.getErrorCodeFromStreamError)(node);
|
|
831
|
+
void end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
|
|
832
|
+
});
|
|
833
|
+
// stream fail, possible logout
|
|
834
|
+
ws.on('CB:failure', (node) => {
|
|
835
|
+
const reason = +(node.attrs.reason || 500);
|
|
836
|
+
void end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
|
|
837
|
+
});
|
|
838
|
+
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
839
|
+
void end(new boom_1.Boom('Multi-device beta not joined', { statusCode: index_js_4.DisconnectReason.multideviceMismatch }));
|
|
840
|
+
});
|
|
841
|
+
ws.on('CB:ib,,offline_preview', async (node) => {
|
|
842
|
+
logger.info('offline preview received', JSON.stringify(node));
|
|
843
|
+
await sendNode({
|
|
844
|
+
tag: 'ib',
|
|
845
|
+
attrs: {},
|
|
846
|
+
content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
|
|
847
|
+
});
|
|
848
|
+
});
|
|
849
|
+
ws.on('CB:ib,,edge_routing', (node) => {
|
|
850
|
+
const edgeRoutingNode = (0, index_js_6.getBinaryNodeChild)(node, 'edge_routing');
|
|
851
|
+
const routingInfo = (0, index_js_6.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
|
|
852
|
+
if (routingInfo?.content) {
|
|
853
|
+
authState.creds.routingInfo = Buffer.from(routingInfo?.content);
|
|
854
|
+
ev.emit('creds.update', authState.creds);
|
|
855
|
+
}
|
|
856
|
+
});
|
|
857
|
+
let didStartBuffer = false;
|
|
858
|
+
process.nextTick(() => {
|
|
859
|
+
if (creds.me?.id) {
|
|
860
|
+
// start buffering important events
|
|
861
|
+
// if we're logged in
|
|
862
|
+
ev.buffer();
|
|
863
|
+
didStartBuffer = true;
|
|
864
|
+
}
|
|
865
|
+
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
|
|
866
|
+
});
|
|
867
|
+
// called when all offline notifs are handled
|
|
868
|
+
ws.on('CB:ib,,offline', (node) => {
|
|
869
|
+
const child = (0, index_js_6.getBinaryNodeChild)(node, 'offline');
|
|
870
|
+
const offlineNotifs = +(child?.attrs.count || 0);
|
|
871
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`);
|
|
872
|
+
if (didStartBuffer) {
|
|
873
|
+
ev.flush();
|
|
874
|
+
logger.trace('flushed events for initial buffer');
|
|
875
|
+
}
|
|
876
|
+
ev.emit('connection.update', { receivedPendingNotifications: true });
|
|
877
|
+
});
|
|
878
|
+
// update credentials when required
|
|
879
|
+
ev.on('creds.update', update => {
|
|
880
|
+
const name = update.me?.name;
|
|
881
|
+
// if name has just been received
|
|
882
|
+
if (creds.me?.name !== name) {
|
|
883
|
+
logger.debug({ name }, 'updated pushName');
|
|
884
|
+
sendNode({
|
|
885
|
+
tag: 'presence',
|
|
886
|
+
attrs: { name: name }
|
|
887
|
+
}).catch(err => {
|
|
888
|
+
logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
Object.assign(creds, update);
|
|
892
|
+
});
|
|
893
|
+
const updateServerTimeOffset = ({ attrs }) => {
|
|
894
|
+
const tValue = attrs?.t;
|
|
895
|
+
if (!tValue) {
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
const parsed = Number(tValue);
|
|
899
|
+
if (Number.isNaN(parsed) || parsed <= 0) {
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
const localMs = Date.now();
|
|
903
|
+
serverTimeOffsetMs = parsed * 1000 - localMs;
|
|
904
|
+
logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
|
|
905
|
+
};
|
|
906
|
+
const getUnifiedSessionId = () => {
|
|
907
|
+
const offsetMs = 3 * index_js_2.TimeMs.Day;
|
|
908
|
+
const now = Date.now() + serverTimeOffsetMs;
|
|
909
|
+
const id = (now + offsetMs) % index_js_2.TimeMs.Week;
|
|
910
|
+
return id.toString();
|
|
911
|
+
};
|
|
912
|
+
const sendUnifiedSession = async () => {
|
|
913
|
+
if (!ws.isOpen) {
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
const node = {
|
|
917
|
+
tag: 'ib',
|
|
918
|
+
attrs: {},
|
|
919
|
+
content: [
|
|
920
|
+
{
|
|
921
|
+
tag: 'unified_session',
|
|
922
|
+
attrs: {
|
|
923
|
+
id: getUnifiedSessionId()
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
]
|
|
927
|
+
};
|
|
928
|
+
try {
|
|
929
|
+
await sendNode(node);
|
|
930
|
+
}
|
|
931
|
+
catch (error) {
|
|
932
|
+
logger.debug({ error }, 'failed to send unified_session telemetry');
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
const registerSocketEndHandler = (handler) => {
|
|
936
|
+
socketEndHandlers.push(handler);
|
|
937
|
+
};
|
|
938
|
+
/**
|
|
939
|
+
* Fetches your account's standing when it comes to restrictions.
|
|
940
|
+
* @returns Returns the state of the restrictions.
|
|
941
|
+
*/
|
|
942
|
+
const fetchAccountReachoutTimelock = async () => {
|
|
943
|
+
const queryResult = await (0, mex_js_1.executeWMexQuery)({}, index_js_3.QueryIds.REACHOUT_TIMELOCK, index_js_4.XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag);
|
|
944
|
+
const result = {
|
|
945
|
+
isActive: !!queryResult?.is_active,
|
|
946
|
+
timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0'
|
|
947
|
+
? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000)
|
|
948
|
+
: undefined,
|
|
949
|
+
enforcementType: queryResult?.enforcement_type ?? index_js_3.ReachoutTimelockEnforcementType.DEFAULT
|
|
950
|
+
};
|
|
951
|
+
ev.emit('connection.update', { reachoutTimeLock: result });
|
|
952
|
+
return result;
|
|
953
|
+
};
|
|
954
|
+
/**
|
|
955
|
+
* Fetches your account's new chat limits.
|
|
956
|
+
* @returns Returns the quota and the usage.
|
|
957
|
+
*/
|
|
958
|
+
const fetchNewChatMessageCap = async () => {
|
|
959
|
+
return (0, mex_js_1.executeWMexQuery)({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, index_js_3.QueryIds.MESSAGE_CAPPING_INFO, index_js_4.XWAPaths.xwa2_message_capping_info, query, generateMessageTag);
|
|
960
|
+
};
|
|
961
|
+
return {
|
|
962
|
+
type: 'md',
|
|
963
|
+
ws,
|
|
964
|
+
ev,
|
|
965
|
+
authState: { creds, keys },
|
|
966
|
+
signalRepository,
|
|
967
|
+
get user() {
|
|
968
|
+
return authState.creds.me;
|
|
969
|
+
},
|
|
970
|
+
generateMessageTag,
|
|
971
|
+
query,
|
|
972
|
+
waitForMessage,
|
|
973
|
+
waitForSocketOpen,
|
|
974
|
+
sendRawMessage,
|
|
975
|
+
sendNode,
|
|
976
|
+
logout,
|
|
977
|
+
end,
|
|
978
|
+
registerSocketEndHandler,
|
|
979
|
+
onUnexpectedError,
|
|
980
|
+
uploadPreKeys,
|
|
981
|
+
uploadPreKeysToServerIfRequired,
|
|
982
|
+
digestKeyBundle,
|
|
983
|
+
rotateSignedPreKey,
|
|
984
|
+
requestPairingCode,
|
|
985
|
+
updateServerTimeOffset,
|
|
986
|
+
sendUnifiedSession,
|
|
987
|
+
wamBuffer: publicWAMBuffer,
|
|
988
|
+
/** Waits for the connection to WA to reach a state */
|
|
989
|
+
waitForConnectionUpdate: (0, index_js_5.bindWaitForConnectionUpdate)(ev),
|
|
990
|
+
sendWAMBuffer,
|
|
991
|
+
executeUSyncQuery,
|
|
992
|
+
onWhatsApp,
|
|
993
|
+
fetchAccountReachoutTimelock,
|
|
994
|
+
fetchNewChatMessageCap
|
|
995
|
+
};
|
|
996
|
+
};
|
|
997
|
+
exports.makeSocket = makeSocket;
|
|
998
|
+
/**
|
|
999
|
+
* map the websocket error to the right type
|
|
1000
|
+
* so it can be retried by the caller
|
|
1001
|
+
* */
|
|
1002
|
+
function mapWebSocketError(handler) {
|
|
1003
|
+
return (error) => {
|
|
1004
|
+
handler(new boom_1.Boom(`WebSocket Error (${error?.message})`, { statusCode: (0, index_js_5.getCodeFromWSError)(error), data: error }));
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
//# sourceMappingURL=socket.js.map
|