@baileys-md/baileys 11.2.4 → 12.0.1

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