@dyyxyzz/baileys-mod 6.0.49 → 6.0.51

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.
Files changed (2) hide show
  1. package/lib/Socket/socket.js +789 -648
  2. package/package.json +1 -1
@@ -1,677 +1,818 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeSocket = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const crypto_1 = require("crypto");
6
- const url_1 = require("url");
7
- const util_1 = require("util");
8
- const WAProto_1 = require("../../WAProto");
9
- const Defaults_1 = require("../Defaults");
10
- const Types_1 = require("../Types");
11
- const Utils_1 = require("../Utils");
12
- const WABinary_1 = require("../WABinary");
13
- const Client_1 = require("./Client");
14
- /**
15
- * Connects to WA servers and performs:
16
- * - simple queries (no retry mechanism, wait for connection establishment)
17
- * - listen to messages and emit events
18
- * - query phone connection
19
- */
20
- const makeSocket = (config) => {
21
- var _a, _b;
22
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
23
- const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
- if (config.mobile || url.protocol === 'tcp:') {
25
- throw new boom_1.Boom('Mobile API is not supported anymore', {
26
- statusCode: Types_1.DisconnectReason.loggedOut
27
- });
28
- }
29
- if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
30
- url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
31
- }
32
- const ws = new Client_1.WebSocketClient(url, config);
33
- ws.connect();
34
- const ev = (0, Utils_1.makeEventBuffer)(logger);
35
- /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
36
- const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
37
- /** WA noise protocol wrapper */
38
- const noise = (0, Utils_1.makeNoiseHandler)({
39
- keyPair: ephemeralKeyPair,
40
- NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
41
- logger,
42
- routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
43
- });
44
- const { creds } = authState;
45
- // add transaction capability
46
- const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
47
- const signalRepository = makeSignalRepository({ creds, keys });
48
- let lastDateRecv;
49
- let epoch = 1;
50
- let keepAliveReq;
51
- let qrTimer;
52
- let closed = false;
53
- const uqTagId = (0, Utils_1.generateMdTagPrefix)();
54
- const generateMessageTag = () => `${uqTagId}${epoch++}`;
55
- const sendPromise = (0, util_1.promisify)(ws.send);
56
- /** send a raw buffer */
57
- const sendRawMessage = async (data) => {
58
- if (!ws.isOpen) {
59
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
60
- }
61
- const bytes = noise.encodeFrame(data);
62
- await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
63
- try {
64
- await sendPromise.call(ws, bytes);
65
- resolve();
66
- }
67
- catch (error) {
68
- reject(error);
69
- }
70
- });
71
- };
72
- /** send a binary node */
73
- const sendNode = (frame) => {
74
- if (logger.level === 'trace') {
75
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
76
- }
77
- const buff = (0, WABinary_1.encodeBinaryNode)(frame);
78
- return sendRawMessage(buff);
79
- };
80
-
81
- const toLid = async (pn) => {
82
- return pn;
83
- };
84
-
85
- const delay = async (ms) => {
86
- return new Promise(resolve => setTimeout(resolve, ms));
87
- };
88
-
89
- const toPn = async (pn) => {
90
- return pn;
91
- };
92
-
93
- /** log & process any unexpected errors */
94
- const onUnexpectedError = (err, msg) => {
95
- logger.error({ err }, `unexpected error in '${msg}'`);
96
- const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
97
- if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
98
- try {
99
- uploadPreKeysToServerIfRequired(true)
100
- .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
101
- }
102
- catch (_e) {}
103
- }
104
- if (message.includes('429') || message.includes('rate limit')) {
105
- const wait = Math.min(30000, (config.backoffDelayMs || 5000));
106
- logger.info({ wait }, 'backing off due to rate limit');
107
- setTimeout(() => {}, wait);
108
- }
109
- };
110
-
111
- /** await the next incoming message */
112
- const awaitNextMessage = async (sendMsg) => {
113
- if (!ws.isOpen) {
114
- throw new boom_1.Boom('Connection Closed', {
115
- statusCode: Types_1.DisconnectReason.connectionClosed
116
- });
117
- }
118
- let onOpen;
119
- let onClose;
120
- const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
121
- onOpen = resolve;
122
- onClose = mapWebSocketError(reject);
123
- ws.on('frame', onOpen);
124
- ws.on('close', onClose);
125
- ws.on('error', onClose);
126
- })
127
- .finally(() => {
128
- ws.off('frame', onOpen);
129
- ws.off('close', onClose);
130
- ws.off('error', onClose);
131
- });
132
- if (sendMsg) {
133
- sendRawMessage(sendMsg).catch(onClose);
134
- }
135
- return result;
136
- };
137
-
138
- const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
139
- let onRecv;
140
- let onErr;
141
- try {
142
- const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
143
- onRecv = resolve;
144
- onErr = err => {
145
- reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
146
- };
147
- ws.on(`TAG:${msgId}`, onRecv);
148
- ws.on('close', onErr);
149
- ws.off('error', onErr);
150
- });
151
- return result;
152
- }
153
- finally {
154
- ws.off(`TAG:${msgId}`, onRecv);
155
- ws.off('close', onErr);
156
- ws.off('error', onErr);
157
- }
158
- };
159
-
160
- const query = async (node, timeoutMs) => {
161
- if (!node.attrs.id) {
162
- node.attrs.id = generateMessageTag();
163
- }
164
- const msgId = node.attrs.id;
165
- const [result] = await Promise.all([
166
- waitForMessage(msgId, timeoutMs),
167
- sendNode(node)
168
- ]);
169
- if ('tag' in result) {
170
- (0, WABinary_1.assertNodeErrorFree)(result);
171
- }
172
- return result;
173
- };
174
1
 
175
- /** connection handshake */
176
- const validateConnection = async () => {
177
- let helloMsg = {
178
- clientHello: { ephemeral: ephemeralKeyPair.public }
2
+ import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, makeEventBuffer, makeNoiseHandler, promiseTimeout } from "../Utils/index.js";
3
+ import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from "../WABinary/index.js";
4
+ import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, MIN_UPLOAD_INTERVAL, NOISE_WA_HEADER, UPLOAD_TIMEOUT } from "../Defaults/index.js";
5
+ import { USyncQuery, USyncUser } from "../WAUSync/index.js";
6
+ import { getPlatformId } from "../Utils/browser-utils.js";
7
+ import { DisconnectReason } from "../Types/index.js";
8
+ import { WebSocketClient } from "./Client/index.js";
9
+ import { BinaryInfo } from "../WAM/BinaryInfo.js";
10
+ import { proto } from "../../WAProto/index.js";
11
+ import { randomBytes } from "crypto";
12
+ import { Boom } from "@hapi/boom";
13
+ import { promisify } from "util";
14
+ import { URL } from "url";
15
+ export const makeSocket = (config) => {
16
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
17
+ const publicWAMBuffer = new BinaryInfo();
18
+ const uqTagId = generateMdTagPrefix();
19
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
20
+ if (printQRInTerminal) {
21
+ console.warn("⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.");
22
+ }
23
+ const url = typeof waWebSocketUrl === "string" ? new URL(waWebSocketUrl) : waWebSocketUrl;
24
+ if (config.mobile || url.protocol === "tcp:") {
25
+ throw new Boom("Mobile API is not supported anymore", { statusCode: DisconnectReason.loggedOut });
26
+ }
27
+ if (url.protocol === "wss" && authState?.creds?.routingInfo) {
28
+ url.searchParams.append("ED", authState.creds.routingInfo.toString("base64url"));
29
+ }
30
+ const ephemeralKeyPair = Curve.generateKeyPair();
31
+ const noise = makeNoiseHandler({
32
+ keyPair: ephemeralKeyPair,
33
+ NOISE_HEADER: NOISE_WA_HEADER,
34
+ logger,
35
+ routingInfo: authState?.creds?.routingInfo
36
+ });
37
+ const ws = new WebSocketClient(url, config);
38
+ ws.connect();
39
+ const sendPromise = promisify(ws.send);
40
+ const sendRawMessage = async (data) => {
41
+ if (!ws.isOpen) {
42
+ throw new Boom("Connection Closed", { statusCode: DisconnectReason.connectionClosed });
43
+ }
44
+ const bytes = noise.encodeFrame(data);
45
+ await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
46
+ try {
47
+ await sendPromise.call(ws, bytes);
48
+ resolve();
49
+ }
50
+ catch (error) {
51
+ reject(error);
52
+ }
53
+ });
54
+ };
55
+ const sendNode = (frame) => {
56
+ if (logger.level === "trace") {
57
+ logger.trace({ xml: binaryNodeToString(frame), msg: "xml send" });
58
+ }
59
+ const buff = encodeBinaryNode(frame);
60
+ return sendRawMessage(buff);
61
+ };
62
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
63
+ let onRecv;
64
+ let onErr;
65
+ try {
66
+ const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
67
+ onRecv = data => {
68
+ resolve(data);
179
69
  };
180
- helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
181
- logger.info({ browser, helloMsg }, 'connected to WA');
182
- const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
183
- const result = await awaitNextMessage(init);
184
- const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
185
- logger.trace({ handshake }, 'handshake recv from WA');
186
- const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
187
- let node;
188
- if (!creds.me) {
189
- node = (0, Utils_1.generateRegistrationNode)(creds, config);
190
- logger.info({ node }, 'not logged in, attempting registration...');
191
- }
192
- else {
193
- node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
194
- logger.info({ node }, 'logging in...');
195
- }
196
- const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
197
- await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
198
- clientFinish: {
199
- static: keyEnc,
200
- payload: payloadEnc,
201
- },
202
- }).finish());
203
- noise.finishInit();
204
- startKeepAliveRequest();
205
- };
206
-
207
- const getAvailablePreKeysOnServer = async () => {
208
- const result = await query({
209
- tag: 'iq',
210
- attrs: {
211
- id: generateMessageTag(),
212
- xmlns: 'encrypt',
213
- type: 'get',
214
- to: WABinary_1.S_WHATSAPP_NET
215
- },
216
- content: [
217
- { tag: 'count', attrs: {} }
218
- ]
219
- });
220
- const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
221
- return +countChild.attrs.value;
70
+ onErr = err => {
71
+ reject(err ||
72
+ new Boom("Connection Closed", {
73
+ statusCode: DisconnectReason.connectionClosed
74
+ }));
75
+ };
76
+ ws.on(`TAG:${msgId}`, onRecv);
77
+ ws.on("close", onErr);
78
+ ws.on("error", onErr);
79
+ return () => reject(new Boom("Query Cancelled"));
80
+ });
81
+ return result;
82
+ }
83
+ catch (error) {
84
+ if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
85
+ logger?.warn?.({ msgId }, "timed out waiting for message");
86
+ return undefined;
87
+ }
88
+ throw error;
89
+ }
90
+ finally {
91
+ if (onRecv)
92
+ ws.off(`TAG:${msgId}`, onRecv);
93
+ if (onErr) {
94
+ ws.off("close", onErr);
95
+ ws.off("error", onErr);
96
+ }
97
+ }
98
+ };
99
+ const query = async (node, timeoutMs) => {
100
+ if (!node.attrs.id) {
101
+ node.attrs.id = generateMessageTag();
102
+ }
103
+ const msgId = node.attrs.id;
104
+ const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
105
+ const result = waitForMessage(msgId, timeoutMs).catch(reject);
106
+ sendNode(node)
107
+ .then(async () => resolve(await result))
108
+ .catch(reject);
109
+ });
110
+ if (result && "tag" in result) {
111
+ assertNodeErrorFree(result);
112
+ }
113
+ return result;
114
+ };
115
+ const executeUSyncQuery = async (usyncQuery) => {
116
+ if (usyncQuery.protocols.length === 0) {
117
+ throw new Boom("USyncQuery must have at least one protocol");
118
+ }
119
+ const validUsers = usyncQuery.users;
120
+ const userNodes = validUsers.map(user => {
121
+ return {
122
+ tag: "user",
123
+ attrs: {
124
+ jid: !user.phone ? user.id : undefined
125
+ },
126
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
127
+ };
128
+ });
129
+ const listNode = {
130
+ tag: "list",
131
+ attrs: {},
132
+ content: userNodes
222
133
  };
223
-
224
- const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
225
- await keys.transaction(async () => {
226
- logger.info({ count }, 'uploading pre-keys');
227
- const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
228
- await query(node);
229
- ev.emit('creds.update', update);
230
- logger.info({ count }, 'uploaded pre-keys');
231
- });
134
+ const queryNode = {
135
+ tag: "query",
136
+ attrs: {},
137
+ content: usyncQuery.protocols.map(a => a.getQueryElement())
232
138
  };
233
-
234
- const uploadPreKeysToServerIfRequired = async () => {
235
- const preKeyCount = await getAvailablePreKeysOnServer();
236
- logger.info(`${preKeyCount} pre-keys found on server`);
237
- if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
238
- await uploadPreKeys();
239
- }
139
+ const iq = {
140
+ tag: "iq",
141
+ attrs: {
142
+ to: S_WHATSAPP_NET,
143
+ type: "get",
144
+ xmlns: "usync"
145
+ },
146
+ content: [
147
+ {
148
+ tag: "usync",
149
+ attrs: {
150
+ context: usyncQuery.context,
151
+ mode: usyncQuery.mode,
152
+ sid: generateMessageTag(),
153
+ last: "true",
154
+ index: "0"
155
+ },
156
+ content: [queryNode, listNode]
157
+ }
158
+ ]
240
159
  };
160
+ const result = await query(iq);
161
+ return usyncQuery.parseUSyncQueryResult(result);
162
+ };
163
+ const onWhatsApp = async (...phoneNumber) => {
164
+ let usyncQuery = new USyncQuery();
165
+ let contactEnabled = false;
166
+ for (const jid of phoneNumber) {
167
+ if (isLidUser(jid)) {
168
+ logger?.warn("LIDs are not supported with onWhatsApp");
169
+ continue;
170
+ }
171
+ else {
172
+ if (!contactEnabled) {
173
+ contactEnabled = true;
174
+ usyncQuery = usyncQuery.withContactProtocol();
175
+ }
176
+ const phone = `+${jid.replace("+", "").split("@")[0]?.split(":")[0]}`;
177
+ usyncQuery.withUser(new USyncUser().withPhone(phone));
178
+ }
179
+ }
180
+ if (usyncQuery.users.length === 0) {
181
+ return [];
182
+ }
183
+ const results = await executeUSyncQuery(usyncQuery);
184
+ if (results) {
185
+ return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
186
+ }
187
+ };
188
+ const pnFromLIDUSync = async (jids) => {
189
+ const usyncQuery = new USyncQuery().withLIDProtocol().withContext("background");
190
+ for (const jid of jids) {
191
+ if (isLidUser(jid)) {
192
+ logger?.warn("LID user found in LID fetch call");
193
+ continue;
194
+ }
195
+ else {
196
+ usyncQuery.withUser(new USyncUser().withId(jid));
197
+ }
198
+ }
199
+ if (usyncQuery.users.length === 0) {
200
+ return [];
201
+ }
202
+ const results = await executeUSyncQuery(usyncQuery);
203
+ if (results) {
204
+ return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
205
+ }
206
+ return [];
207
+ };
208
+ const ev = makeEventBuffer(logger);
209
+ const { creds } = authState;
210
+ const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
211
+ const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
212
+
213
+ const delay = async (ms) => {
214
+ return new Promise(resolve => setTimeout(resolve, ms));
215
+ }
216
+
217
+ const toLid = async (pn) => {
218
+ if (!pn) return "";
219
+ if (pn.includes("@lid")) return pn;
220
+ try {
221
+ return signalRepository.lidMapping.getLIDForPN(pn);
222
+ } catch (err) {
223
+ logger.error({ err }, "error jid unknown");
224
+ return pn;
225
+ }
226
+ };
241
227
 
242
- const onMessageReceived = (data) => {
243
- noise.decodeFrame(data, frame => {
244
- var _a;
245
- lastDateRecv = new Date();
246
- let anyTriggered = false;
247
- anyTriggered = ws.emit('frame', frame);
248
- if (!(frame instanceof Uint8Array)) {
249
- const msgId = frame.attrs.id;
250
- if (logger.level === 'trace') {
251
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
252
- }
253
- anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
254
- const l0 = frame.tag;
255
- const l1 = frame.attrs || {};
256
- const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
257
- for (const key of Object.keys(l1)) {
258
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
259
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
260
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
261
- }
262
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
263
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
264
- if (!anyTriggered && logger.level === 'debug') {
265
- logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
266
- }
267
- }
268
- });
269
- };
228
+ const toPn = async (pn) => {
229
+ if (!pn) return "";
230
+ if (
231
+ pn.includes("@s.whatsapp.net") ||
232
+ pn.includes("@g.us") ||
233
+ pn.includes("@newsletter")
234
+ ) return pn;
235
+
236
+ try {
237
+ const jid = await signalRepository.lidMapping.getPNForLID(pn);
238
+ if (!jid) return "";
239
+ const server = "@" + jid.split("@")[1];
240
+ const pN = jid.split(":")[0] + server;
241
+ return pN.toString();
242
+ } catch (err) {
243
+ logger.error({ err }, "error lid unknown");
244
+ return pn;
245
+ }
246
+ };
270
247
 
271
- const end = (error) => {
272
- if (closed) {
273
- logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
274
- return;
275
- }
276
- closed = true;
277
- logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
278
- clearInterval(keepAliveReq);
279
- clearTimeout(qrTimer);
280
- ws.removeAllListeners('close');
281
- ws.removeAllListeners('error');
282
- ws.removeAllListeners('open');
283
- ws.removeAllListeners('message');
284
- if (!ws.isClosed && !ws.isClosing) {
285
- try {
286
- ws.close();
287
- }
288
- catch (_a) { }
289
- }
290
- ev.emit('connection.update', {
291
- connection: 'close',
292
- lastDisconnect: {
293
- error,
294
- date: new Date()
295
- }
296
- });
297
- ev.removeAllListeners('connection.update');
248
+ let lastDateRecv;
249
+ let epoch = 1;
250
+ let keepAliveReq;
251
+ let qrTimer;
252
+ let closed = false;
253
+ const onUnexpectedError = (err, msg) => {
254
+ logger.error({ err }, `unexpected error in "${msg}"`);
255
+ };
256
+ const awaitNextMessage = async (sendMsg) => {
257
+ if (!ws.isOpen) {
258
+ throw new Boom("Connection Closed", {
259
+ statusCode: DisconnectReason.connectionClosed
260
+ });
261
+ }
262
+ let onOpen;
263
+ let onClose;
264
+ const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
265
+ onOpen = resolve;
266
+ onClose = mapWebSocketError(reject);
267
+ ws.on("frame", onOpen);
268
+ ws.on("close", onClose);
269
+ ws.on("error", onClose);
270
+ }).finally(() => {
271
+ ws.off("frame", onOpen);
272
+ ws.off("close", onClose);
273
+ ws.off("error", onClose);
274
+ });
275
+ if (sendMsg) {
276
+ sendRawMessage(sendMsg).catch(onClose);
277
+ }
278
+ return result;
279
+ };
280
+ const validateConnection = async () => {
281
+ let helloMsg = {
282
+ clientHello: { ephemeral: ephemeralKeyPair.public }
298
283
  };
299
-
300
- const waitForSocketOpen = async () => {
301
- if (ws.isOpen) {
302
- return;
303
- }
304
- if (ws.isClosed || ws.isClosing) {
305
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
306
- }
307
- let onOpen;
308
- let onClose;
309
- await new Promise((resolve, reject) => {
310
- onOpen = () => resolve(undefined);
311
- onClose = mapWebSocketError(reject);
312
- ws.on('open', onOpen);
313
- ws.on('close', onClose);
314
- ws.on('error', onClose);
315
- })
316
- .finally(() => {
317
- ws.off('open', onOpen);
318
- ws.off('close', onClose);
319
- ws.off('error', onClose);
320
- });
284
+ helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
285
+ logger.info({ browser, helloMsg }, "connected to WA");
286
+ const init = proto.HandshakeMessage.encode(helloMsg).finish();
287
+ const result = await awaitNextMessage(init);
288
+ const handshake = proto.HandshakeMessage.decode(result);
289
+ logger.trace({ handshake }, "handshake recv from WA");
290
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
291
+ let node;
292
+ if (!creds.me) {
293
+ node = generateRegistrationNode(creds, config);
294
+ logger.info({ node }, "not logged in, attempting registration...");
295
+ }
296
+ else {
297
+ node = generateLoginNode(creds.me.id, config);
298
+ logger.info({ node }, "logging in...");
299
+ }
300
+ const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
301
+ await sendRawMessage(proto.HandshakeMessage.encode({
302
+ clientFinish: {
303
+ static: keyEnc,
304
+ payload: payloadEnc
305
+ }
306
+ }).finish());
307
+ noise.finishInit();
308
+ startKeepAliveRequest();
309
+ };
310
+ const getAvailablePreKeysOnServer = async () => {
311
+ const result = await query({
312
+ tag: "iq",
313
+ attrs: {
314
+ id: generateMessageTag(),
315
+ xmlns: "encrypt",
316
+ type: "get",
317
+ to: S_WHATSAPP_NET
318
+ },
319
+ content: [{ tag: "count", attrs: {} }]
320
+ });
321
+ const countChild = getBinaryNodeChild(result, "count");
322
+ return +countChild.attrs.value;
323
+ };
324
+ let uploadPreKeysPromise = null;
325
+ let lastUploadTime = 0;
326
+ const uploadPreKeys = async (count = MIN_PREKEY_COUNT, retryCount = 0) => {
327
+ if (retryCount === 0) {
328
+ const timeSinceLastUpload = Date.now() - lastUploadTime;
329
+ if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
330
+ logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
331
+ return;
332
+ }
333
+ }
334
+ if (uploadPreKeysPromise) {
335
+ logger.debug("Pre-key upload already in progress, waiting for completion");
336
+ await uploadPreKeysPromise;
337
+ }
338
+ const uploadLogic = async () => {
339
+ logger.info({ count, retryCount }, "uploading pre-keys");
340
+ const node = await keys.transaction(async () => {
341
+ logger.debug({ requestedCount: count }, "generating pre-keys with requested count");
342
+ const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
343
+ ev.emit("creds.update", update);
344
+ return node;
345
+ }, creds?.me?.id || "upload-pre-keys");
346
+ try {
347
+ await query(node);
348
+ logger.info({ count }, "uploaded pre-keys successfully");
349
+ lastUploadTime = Date.now();
350
+ }
351
+ catch (uploadError) {
352
+ logger.error({ uploadError: uploadError.toString(), count }, "Failed to upload pre-keys to server");
353
+ if (retryCount < 3) {
354
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
355
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
356
+ await new Promise(resolve => setTimeout(resolve, backoffDelay));
357
+ return uploadPreKeys(count, retryCount + 1);
358
+ }
359
+ throw uploadError;
360
+ }
321
361
  };
322
-
323
- const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
324
- if (!lastDateRecv) {
325
- lastDateRecv = new Date();
326
- }
327
- const diff = Date.now() - lastDateRecv.getTime();
328
- if (diff > keepAliveIntervalMs + 5000) {
329
- end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
330
- }
331
- else if (ws.isOpen) {
332
- query({
333
- tag: 'iq',
334
- attrs: {
335
- id: generateMessageTag(),
336
- to: WABinary_1.S_WHATSAPP_NET,
337
- type: 'get',
338
- xmlns: 'w:p',
339
- },
340
- content: [{ tag: 'ping', attrs: {} }]
341
- })
342
- .catch(err => {
343
- logger.error({ trace: err.stack }, 'error in sending keep alive');
344
- });
345
- }
346
- else {
347
- logger.warn('keep alive called when WS not open');
348
- }
349
- }, keepAliveIntervalMs));
350
-
351
- const sendPassiveIq = (tag) => (query({
352
- tag: 'iq',
362
+ uploadPreKeysPromise = Promise.race([
363
+ uploadLogic(),
364
+ new Promise((_, reject) => setTimeout(() => reject(new Boom("Pre-key upload timeout", { statusCode: 408 })), UPLOAD_TIMEOUT))
365
+ ]);
366
+ try {
367
+ await uploadPreKeysPromise;
368
+ }
369
+ finally {
370
+ uploadPreKeysPromise = null;
371
+ }
372
+ };
373
+ const verifyCurrentPreKeyExists = async () => {
374
+ const currentPreKeyId = creds.nextPreKeyId - 1;
375
+ if (currentPreKeyId <= 0) {
376
+ return { exists: false, currentPreKeyId: 0 };
377
+ }
378
+ const preKeys = await keys.get("pre-key", [currentPreKeyId.toString()]);
379
+ const exists = !!preKeys[currentPreKeyId.toString()];
380
+ return { exists, currentPreKeyId };
381
+ };
382
+ const uploadPreKeysToServerIfRequired = async () => {
383
+ try {
384
+ let count = 0;
385
+ const preKeyCount = await getAvailablePreKeysOnServer();
386
+ if (preKeyCount === 0)
387
+ count = INITIAL_PREKEY_COUNT;
388
+ else
389
+ count = MIN_PREKEY_COUNT;
390
+ const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
391
+ logger.info(`${preKeyCount} pre-keys found on server`);
392
+ logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
393
+ const lowServerCount = preKeyCount <= count;
394
+ const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
395
+ const shouldUpload = lowServerCount || missingCurrentPreKey;
396
+ if (shouldUpload) {
397
+ const reasons = [];
398
+ if (lowServerCount)
399
+ reasons.push(`server count low (${preKeyCount})`);
400
+ if (missingCurrentPreKey)
401
+ reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
402
+ logger.info(`Uploading PreKeys due to: ${reasons.join(", ")}`);
403
+ await uploadPreKeys(count);
404
+ }
405
+ else {
406
+ logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
407
+ }
408
+ }
409
+ catch (error) {
410
+ logger.error({ error }, "Failed to check/upload pre-keys during initialization");
411
+ }
412
+ };
413
+ const onMessageReceived = (data) => {
414
+ noise.decodeFrame(data, frame => {
415
+ lastDateRecv = new Date();
416
+ let anyTriggered = false;
417
+ anyTriggered = ws.emit("frame", frame);
418
+ if (!(frame instanceof Uint8Array)) {
419
+ const msgId = frame.attrs.id;
420
+ if (logger.level === "trace") {
421
+ logger.trace({ xml: binaryNodeToString(frame), msg: "recv xml" });
422
+ }
423
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
424
+ const l0 = frame.tag;
425
+ const l1 = frame.attrs || {};
426
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : "";
427
+ for (const key of Object.keys(l1)) {
428
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
429
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
430
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
431
+ }
432
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
433
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
434
+ if (!anyTriggered && logger.level === "debug") {
435
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, "communication recv");
436
+ }
437
+ }
438
+ });
439
+ };
440
+ const end = (error) => {
441
+ if (closed) {
442
+ logger.trace({ trace: error?.stack }, "connection already closed");
443
+ return;
444
+ }
445
+ closed = true;
446
+ logger.info({ trace: error?.stack }, error ? "connection errored" : "connection closed");
447
+ clearInterval(keepAliveReq);
448
+ clearTimeout(qrTimer);
449
+ ws.removeAllListeners("close");
450
+ ws.removeAllListeners("open");
451
+ ws.removeAllListeners("message");
452
+ if (!ws.isClosed && !ws.isClosing) {
453
+ try {
454
+ ws.close();
455
+ }
456
+ catch { }
457
+ }
458
+ ev.emit("connection.update", {
459
+ connection: "close",
460
+ lastDisconnect: {
461
+ error,
462
+ date: new Date()
463
+ }
464
+ });
465
+ ev.removeAllListeners("connection.update");
466
+ };
467
+ const waitForSocketOpen = async () => {
468
+ if (ws.isOpen) {
469
+ return;
470
+ }
471
+ if (ws.isClosed || ws.isClosing) {
472
+ throw new Boom("Connection Closed", { statusCode: DisconnectReason.connectionClosed });
473
+ }
474
+ let onOpen;
475
+ let onClose;
476
+ await new Promise((resolve, reject) => {
477
+ onOpen = () => resolve(undefined);
478
+ onClose = mapWebSocketError(reject);
479
+ ws.on("open", onOpen);
480
+ ws.on("close", onClose);
481
+ ws.on("error", onClose);
482
+ }).finally(() => {
483
+ ws.off("open", onOpen);
484
+ ws.off("close", onClose);
485
+ ws.off("error", onClose);
486
+ });
487
+ };
488
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
489
+ if (!lastDateRecv) {
490
+ lastDateRecv = new Date();
491
+ }
492
+ const diff = Date.now() - lastDateRecv.getTime();
493
+ if (diff > keepAliveIntervalMs + 5000) {
494
+ end(new Boom("Connection was lost", { statusCode: DisconnectReason.connectionLost }));
495
+ }
496
+ else if (ws.isOpen) {
497
+ query({
498
+ tag: "iq",
499
+ attrs: {
500
+ id: generateMessageTag(),
501
+ to: S_WHATSAPP_NET,
502
+ type: "get",
503
+ xmlns: "w:p"
504
+ },
505
+ content: [{ tag: "ping", attrs: {} }]
506
+ }).catch(err => {
507
+ logger.error({ trace: err.stack }, "error in sending keep alive");
508
+ });
509
+ }
510
+ else {
511
+ logger.warn("keep alive called when WS not open");
512
+ }
513
+ }, keepAliveIntervalMs));
514
+ const sendPassiveIq = (tag) => query({
515
+ tag: "iq",
516
+ attrs: {
517
+ to: S_WHATSAPP_NET,
518
+ xmlns: "passive",
519
+ type: "set"
520
+ },
521
+ content: [{ tag, attrs: {} }]
522
+ });
523
+ const logout = async (msg) => {
524
+ const jid = authState.creds.me?.id;
525
+ if (jid) {
526
+ await sendNode({
527
+ tag: "iq",
353
528
  attrs: {
354
- to: WABinary_1.S_WHATSAPP_NET,
355
- xmlns: 'passive',
356
- type: 'set',
529
+ to: S_WHATSAPP_NET,
530
+ type: "set",
531
+ id: generateMessageTag(),
532
+ xmlns: "md"
357
533
  },
358
534
  content: [
359
- { tag, attrs: {} }
535
+ {
536
+ tag: "remove-companion-device",
537
+ attrs: {
538
+ jid,
539
+ reason: "user_initiated"
540
+ }
541
+ }
360
542
  ]
361
- }));
362
-
363
- const logout = async (msg) => {
364
- var _a;
365
- const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
366
- if (jid) {
367
- await sendNode({
368
- tag: 'iq',
369
- attrs: {
370
- to: WABinary_1.S_WHATSAPP_NET,
371
- type: 'set',
372
- id: generateMessageTag(),
373
- xmlns: 'md'
374
- },
375
- content: [
376
- {
377
- tag: 'remove-companion-device',
378
- attrs: {
379
- jid,
380
- reason: 'user_initiated'
381
- }
382
- }
383
- ]
384
- });
385
- }
386
- end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
543
+ });
544
+ }
545
+ end(new Boom(msg || "Intentional Logout", { statusCode: DisconnectReason.loggedOut }));
546
+ };
547
+ const requestPairingCode = async (phoneNumber, customPairingCode = "SKYZOOOO") => {
548
+ const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
549
+ if (customPairingCode && customPairingCode?.length !== 8) {
550
+ throw new Error("Custom pairing code must be exactly 8 chars");
551
+ }
552
+ authState.creds.pairingCode = pairingCode;
553
+ authState.creds.me = {
554
+ id: jidEncode(phoneNumber, "s.whatsapp.net"),
555
+ name: "~"
387
556
  };
388
-
389
- /** This method was created by snowi, and implemented by KyuuRzy */
390
- /** hey bro, if you delete this text */
391
- /** you are the most cursed human being who likes to claim other people's property 😹🙌🏻 */
392
- const requestPairingCode = async (phoneNumber, pairKey) => {
393
- if (pairKey) {
394
- authState.creds.pairingCode = pairKey.toUpperCase();
395
- } else {
396
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
397
- }
398
-
399
- authState.creds.me = {
400
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
401
- name: '~'
402
- };
403
-
404
- ev.emit('creds.update', authState.creds);
405
-
406
- // ── FIX: Platform ID 1 = Chrome, dikenali WA sebagai companion browser valid ──
407
- // Sebelumnya pakai getPlatformId(browser[1]) yang return nilai tidak dikenal
408
- // untuk string 'Android' sehingga WA tidak mengirimkan push notif pairing ke HP
409
- const PLATFORM_ID = Buffer.from([1]); // 1 = Chrome/Browser companion
410
- const PLATFORM_DISPLAY = Buffer.from('Chrome (Linux)', 'utf-8');
411
-
412
- await sendNode({
413
- tag: 'iq',
414
- attrs: {
415
- to: WABinary_1.S_WHATSAPP_NET,
416
- type: 'set',
417
- id: generateMessageTag(),
418
- xmlns: 'md'
557
+ ev.emit("creds.update", authState.creds);
558
+ await sendNode({
559
+ tag: "iq",
560
+ attrs: {
561
+ to: S_WHATSAPP_NET,
562
+ type: "set",
563
+ id: generateMessageTag(),
564
+ xmlns: "md"
565
+ },
566
+ content: [
567
+ {
568
+ tag: "link_code_companion_reg",
569
+ attrs: {
570
+ jid: authState.creds.me.id,
571
+ stage: "companion_hello",
572
+ should_show_push_notification: "true"
573
+ },
574
+ content: [
575
+ {
576
+ tag: "link_code_pairing_wrapped_companion_ephemeral_pub",
577
+ attrs: {},
578
+ content: await generatePairingKey()
419
579
  },
420
- content: [
421
- {
422
- tag: 'link_code_companion_reg',
423
- attrs: {
424
- jid: authState.creds.me.id,
425
- stage: 'companion_hello',
426
- should_show_push_notification: 'true'
427
- },
428
- content: [
429
- {
430
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
431
- attrs: {},
432
- content: await generatePairingKey()
433
- },
434
- {
435
- tag: 'companion_server_auth_key_pub',
436
- attrs: {},
437
- content: authState.creds.noiseKey.public
438
- },
439
- {
440
- tag: 'companion_platform_id',
441
- attrs: {},
442
- content: PLATFORM_ID
443
- },
444
- {
445
- tag: 'companion_platform_display',
446
- attrs: {},
447
- content: PLATFORM_DISPLAY
448
- },
449
- {
450
- tag: 'link_code_pairing_nonce',
451
- attrs: {},
452
- content: Buffer.from('0', 'utf-8')
453
- }
454
- ]
455
- }
456
- ]
457
- });
458
-
459
- return authState.creds.pairingCode;
460
- };
461
-
462
- async function generatePairingKey() {
463
- const salt = (0, crypto_1.randomBytes)(32);
464
- const randomIv = (0, crypto_1.randomBytes)(16);
465
- const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
466
- const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
467
- return Buffer.concat([salt, randomIv, ciphered]);
468
- }
469
-
470
- const sendWAMBuffer = (wamBuffer) => {
471
- return query({
472
- tag: 'iq',
473
- attrs: {
474
- to: WABinary_1.S_WHATSAPP_NET,
475
- id: generateMessageTag(),
476
- xmlns: 'w:stats'
580
+ {
581
+ tag: "companion_server_auth_key_pub",
582
+ attrs: {},
583
+ content: authState.creds.noiseKey.public
477
584
  },
478
- content: [
479
- {
480
- tag: 'add',
481
- attrs: {},
482
- content: wamBuffer
483
- }
484
- ]
485
- });
486
- };
487
-
488
- ws.on('message', onMessageReceived);
489
- ws.on('open', async () => {
490
- try {
491
- await validateConnection();
492
- }
493
- catch (err) {
494
- logger.error({ err }, 'error in validating connection');
495
- end(err);
585
+ {
586
+ tag: "companion_platform_id",
587
+ attrs: {},
588
+ content: getPlatformId(browser[1])
589
+ },
590
+ {
591
+ tag: "companion_platform_display",
592
+ attrs: {},
593
+ content: `${browser[1]} (${browser[0]})`
594
+ },
595
+ {
596
+ tag: "link_code_pairing_nonce",
597
+ attrs: {},
598
+ content: "0"
599
+ }
600
+ ]
496
601
  }
602
+ ]
497
603
  });
498
- ws.on('error', mapWebSocketError(end));
499
- ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
500
- ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
501
-
502
- ws.on('CB:iq,type:set,pair-device', async (stanza) => {
503
- const iq = {
504
- tag: 'iq',
505
- attrs: {
506
- to: WABinary_1.S_WHATSAPP_NET,
507
- type: 'result',
508
- id: stanza.attrs.id,
509
- }
510
- };
511
- await sendNode(iq);
512
- const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
513
- const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
514
- const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
515
- const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
516
- const advB64 = creds.advSecretKey;
517
- let qrMs = qrTimeout || 60000;
518
- const genPairQR = () => {
519
- if (!ws.isOpen) {
520
- return;
521
- }
522
- const refNode = refNodes.shift();
523
- if (!refNode) {
524
- end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
525
- return;
526
- }
527
- const ref = refNode.content.toString('utf-8');
528
- const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
529
- ev.emit('connection.update', { qr });
530
- qrTimer = setTimeout(genPairQR, qrMs);
531
- qrMs = qrTimeout || 20000;
532
- };
533
- genPairQR();
604
+ return authState.creds.pairingCode;
605
+ };
606
+ async function generatePairingKey() {
607
+ const salt = randomBytes(32);
608
+ const randomIv = randomBytes(16);
609
+ const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
610
+ const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
611
+ return Buffer.concat([salt, randomIv, ciphered]);
612
+ }
613
+ const sendWAMBuffer = (wamBuffer) => {
614
+ return query({
615
+ tag: "iq",
616
+ attrs: {
617
+ to: S_WHATSAPP_NET,
618
+ id: generateMessageTag(),
619
+ xmlns: "w:stats"
620
+ },
621
+ content: [
622
+ {
623
+ tag: "add",
624
+ attrs: { t: Math.round(Date.now() / 1000) + "" },
625
+ content: wamBuffer
626
+ }
627
+ ]
534
628
  });
535
-
536
- ws.on('CB:iq,,pair-success', async (stanza) => {
537
- logger.debug('pair success recv');
629
+ };
630
+ ws.on("message", onMessageReceived);
631
+ ws.on("open", async () => {
632
+ try {
633
+ await validateConnection();
634
+ }
635
+ catch (err) {
636
+ logger.error({ err }, "error in validating connection");
637
+ end(err);
638
+ }
639
+ });
640
+ ws.on("error", mapWebSocketError(end));
641
+ ws.on("close", () => end(new Boom("Connection Terminated", { statusCode: DisconnectReason.connectionClosed })));
642
+ ws.on("CB:xmlstreamend", () => end(new Boom("Connection Terminated by Server", { statusCode: DisconnectReason.connectionClosed })));
643
+ ws.on("CB:iq,type:set,pair-device", async (stanza) => {
644
+ const iq = {
645
+ tag: "iq",
646
+ attrs: {
647
+ to: S_WHATSAPP_NET,
648
+ type: "result",
649
+ id: stanza.attrs.id
650
+ }
651
+ };
652
+ await sendNode(iq);
653
+ const pairDeviceNode = getBinaryNodeChild(stanza, "pair-device");
654
+ const refNodes = getBinaryNodeChildren(pairDeviceNode, "ref");
655
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString("base64");
656
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString("base64");
657
+ const advB64 = creds.advSecretKey;
658
+ let qrMs = qrTimeout || 60000;
659
+ const genPairQR = () => {
660
+ if (!ws.isOpen) {
661
+ return;
662
+ }
663
+ const refNode = refNodes.shift();
664
+ if (!refNode) {
665
+ end(new Boom("QR refs attempts ended", { statusCode: DisconnectReason.timedOut }));
666
+ return;
667
+ }
668
+ const ref = refNode.content.toString("utf-8");
669
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(",");
670
+ ev.emit("connection.update", { qr });
671
+ qrTimer = setTimeout(genPairQR, qrMs);
672
+ qrMs = qrTimeout || 20000;
673
+ };
674
+ genPairQR();
675
+ });
676
+ ws.on("CB:iq,,pair-success", async (stanza) => {
677
+ logger.debug("pair success recv");
678
+ try {
679
+ const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
680
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, "pairing configured successfully, expect to restart the connection...");
681
+ ev.emit("creds.update", updatedCreds);
682
+ ev.emit("connection.update", { isNewLogin: true, qr: undefined });
683
+ await sendNode(reply);
684
+ }
685
+ catch (error) {
686
+ logger.info({ trace: error.stack }, "error in pairing");
687
+ end(error);
688
+ }
689
+ });
690
+ ws.on("CB:success", async (node) => {
691
+ try {
692
+ await uploadPreKeysToServerIfRequired();
693
+ await sendPassiveIq("active");
694
+ }
695
+ catch (err) {
696
+ logger.warn({ err }, "failed to send initial passive iq");
697
+ }
698
+ logger.info("opened connection to WA");
699
+ clearTimeout(qrTimer);
700
+ ev.emit("creds.update", { me: { ...authState.creds.me, lid: node.attrs.lid } });
701
+ ev.emit("connection.update", { connection: "open" });
702
+ if (node.attrs.lid && authState.creds.me?.id) {
703
+ const myLID = node.attrs.lid;
704
+ process.nextTick(async () => {
538
705
  try {
539
- const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
540
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
541
- ev.emit('creds.update', updatedCreds);
542
- ev.emit('connection.update', { isNewLogin: true, qr: undefined });
543
- await sendNode(reply);
706
+ const myPN = authState.creds.me.id;
707
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
708
+ const { user, device } = jidDecode(myPN);
709
+ await authState.keys.set({
710
+ "device-list": {
711
+ [user]: [device?.toString() || "0"]
712
+ }
713
+ });
714
+ await signalRepository.migrateSession(myPN, myLID);
715
+ logger.info({ myPN, myLID }, "Own LID session created successfully");
544
716
  }
545
717
  catch (error) {
546
- logger.info({ trace: error.stack }, 'error in pairing');
547
- end(error);
718
+ logger.error({ error, lid: myLID }, "Failed to create own LID session");
548
719
  }
720
+ });
721
+ }
722
+ });
723
+ ws.on("CB:stream:error", (node) => {
724
+ logger.error({ node }, "stream errored out");
725
+ const { reason, statusCode } = getErrorCodeFromStreamError(node);
726
+ end(new Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
727
+ });
728
+ ws.on("CB:failure", (node) => {
729
+ const reason = +(node.attrs.reason || 500);
730
+ end(new Boom("Connection Failure", { statusCode: reason, data: node.attrs }));
731
+ });
732
+ ws.on("CB:ib,,downgrade_webclient", () => {
733
+ end(new Boom("Multi-device beta not joined", { statusCode: DisconnectReason.multideviceMismatch }));
734
+ });
735
+ ws.on("CB:ib,,offline_preview", (node) => {
736
+ logger.info("offline preview received", JSON.stringify(node));
737
+ sendNode({
738
+ tag: "ib",
739
+ attrs: {},
740
+ content: [{ tag: "offline_batch", attrs: { count: "100" } }]
549
741
  });
550
-
551
- ws.on('CB:success', async (node) => {
552
- try {
553
- await uploadPreKeysToServerIfRequired();
554
- await sendPassiveIq('active');
555
- logger.info('opened connection to WA');
556
- clearTimeout(qrTimer);
557
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
558
- ev.emit('connection.update', { connection: 'open' });
559
- }
560
- catch (err) {
561
- logger.error({ err }, 'error opening connection');
562
- end(err);
563
- }
564
- });
565
-
566
- ws.on('CB:stream:error', (node) => {
567
- logger.error({ node }, 'stream errored out');
568
- const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
569
- end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
570
- });
571
-
572
- ws.on('CB:failure', (node) => {
573
- const reason = +(node.attrs.reason || 500);
574
- end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
575
- });
576
-
577
- ws.on('CB:ib,,downgrade_webclient', () => {
578
- end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
579
- });
580
-
581
- ws.on('CB:ib,,offline_preview', (node) => {
582
- logger.info('offline preview received', JSON.stringify(node));
583
- sendNode({
584
- tag: 'ib',
585
- attrs: {},
586
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
587
- });
588
- });
589
-
590
- ws.on('CB:ib,,edge_routing', (node) => {
591
- const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
592
- const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
593
- if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
594
- authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
595
- ev.emit('creds.update', authState.creds);
596
- }
597
- });
598
-
599
- let didStartBuffer = false;
600
- process.nextTick(() => {
601
- var _a;
602
- if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
603
- ev.buffer();
604
- didStartBuffer = true;
605
- }
606
- ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
607
- });
608
-
609
- ws.on('CB:ib,,offline', (node) => {
610
- const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
611
- const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
612
- logger.info(`handled ${offlineNotifs} offline messages/notifications`);
613
- if (didStartBuffer) {
614
- ev.flush();
615
- logger.trace('flushed events for initial buffer');
616
- }
617
- ev.emit('connection.update', { receivedPendingNotifications: true });
618
- });
619
-
620
- ev.on('creds.update', update => {
621
- var _a, _b;
622
- const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
623
- if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
624
- logger.debug({ name }, 'updated pushName');
625
- sendNode({
626
- tag: 'presence',
627
- attrs: { name: name }
628
- })
629
- .catch(err => {
630
- logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
631
- });
632
- }
633
- Object.assign(creds, update);
634
- });
635
-
636
- if (printQRInTerminal) {
637
- (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
742
+ });
743
+ ws.on("CB:ib,,edge_routing", (node) => {
744
+ const edgeRoutingNode = getBinaryNodeChild(node, "edge_routing");
745
+ const routingInfo = getBinaryNodeChild(edgeRoutingNode, "routing_info");
746
+ if (routingInfo?.content) {
747
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content);
748
+ ev.emit("creds.update", authState.creds);
638
749
  }
639
-
640
- return {
641
- type: 'md',
642
- ws,
643
- ev,
644
- authState: {
645
- creds,
646
- keys
647
- },
648
- signalRepository,
649
- get user() {
650
- return authState.creds.me;
651
- },
652
- toLid,
653
- toPn,
654
- delay,
655
- generateMessageTag,
656
- query,
657
- waitForMessage,
658
- waitForSocketOpen,
659
- sendRawMessage,
660
- sendNode,
661
- logout,
662
- end,
663
- onUnexpectedError,
664
- uploadPreKeys,
665
- uploadPreKeysToServerIfRequired,
666
- requestPairingCode,
667
- waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
668
- sendWAMBuffer,
669
- };
750
+ });
751
+ let didStartBuffer = false;
752
+ process.nextTick(() => {
753
+ if (creds.me?.id) {
754
+ ev.buffer();
755
+ didStartBuffer = true;
756
+ }
757
+ ev.emit("connection.update", { connection: "connecting", receivedPendingNotifications: false, qr: undefined });
758
+ });
759
+ ws.on("CB:ib,,offline", (node) => {
760
+ const child = getBinaryNodeChild(node, "offline");
761
+ const offlineNotifs = +(child?.attrs.count || 0);
762
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
763
+ if (didStartBuffer) {
764
+ ev.flush();
765
+ logger.trace("flushed events for initial buffer");
766
+ }
767
+ ev.emit("connection.update", { receivedPendingNotifications: true });
768
+ });
769
+ ev.on("creds.update", update => {
770
+ const name = update.me?.name;
771
+ if (creds.me?.name !== name) {
772
+ logger.debug({ name }, "updated pushName");
773
+ sendNode({
774
+ tag: "presence",
775
+ attrs: { name: name }
776
+ }).catch(err => {
777
+ logger.warn({ trace: err.stack }, "error in sending presence update on name change");
778
+ });
779
+ }
780
+ Object.assign(creds, update);
781
+ });
782
+ return {
783
+ type: "md",
784
+ ws,
785
+ ev,
786
+ authState: { creds, keys },
787
+ signalRepository,
788
+ get user() {
789
+ return authState.creds.me;
790
+ },
791
+ generateMessageTag,
792
+ query,
793
+ delay,
794
+ waitForMessage,
795
+ waitForSocketOpen,
796
+ sendRawMessage,
797
+ sendNode,
798
+ logout,
799
+ end,
800
+ onUnexpectedError,
801
+ uploadPreKeys,
802
+ uploadPreKeysToServerIfRequired,
803
+ requestPairingCode,
804
+ wamBuffer: publicWAMBuffer,
805
+ waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
806
+ sendWAMBuffer,
807
+ executeUSyncQuery,
808
+ onWhatsApp,
809
+ toLid,
810
+ toPn
811
+ };
670
812
  };
671
- exports.makeSocket = makeSocket;
672
813
 
673
814
  function mapWebSocketError(handler) {
674
- return (error) => {
675
- handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
676
- };
815
+ return (error) => {
816
+ handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
817
+ };
677
818
  }