@gqb333/based 2.7.71

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 (201) hide show
  1. package/LICENSE +58 -0
  2. package/README.MD +611 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5604 -0
  5. package/WAProto/index.d.ts +63156 -0
  6. package/WAProto/index.js +195638 -0
  7. package/WAProto/p.html +1 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.d.ts +53 -0
  11. package/lib/Defaults/index.js +108 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  13. package/lib/Signal/Group/ciphertext-message.js +15 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  15. package/lib/Signal/Group/group-session-builder.js +64 -0
  16. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  17. package/lib/Signal/Group/group_cipher.js +96 -0
  18. package/lib/Signal/Group/index.d.ts +11 -0
  19. package/lib/Signal/Group/index.js +57 -0
  20. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  21. package/lib/Signal/Group/keyhelper.js +55 -0
  22. package/lib/Signal/Group/queue-job.d.ts +1 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  25. package/lib/Signal/Group/sender-chain-key.js +34 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  33. package/lib/Signal/Group/sender-key-record.js +53 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  35. package/lib/Signal/Group/sender-key-state.js +99 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +3 -0
  39. package/lib/Signal/libsignal.js +174 -0
  40. package/lib/Socket/Client/index.d.ts +2 -0
  41. package/lib/Socket/Client/index.js +18 -0
  42. package/lib/Socket/Client/types.d.ts +16 -0
  43. package/lib/Socket/Client/types.js +13 -0
  44. package/lib/Socket/Client/websocket.d.ts +13 -0
  45. package/lib/Socket/Client/websocket.js +111 -0
  46. package/lib/Socket/business.d.ts +172 -0
  47. package/lib/Socket/business.js +260 -0
  48. package/lib/Socket/chats.d.ts +85 -0
  49. package/lib/Socket/chats.js +1094 -0
  50. package/lib/Socket/groups.d.ts +124 -0
  51. package/lib/Socket/groups.js +423 -0
  52. package/lib/Socket/index.d.ts +172 -0
  53. package/lib/Socket/index.js +32 -0
  54. package/lib/Socket/messages-interactive.js +259 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1474 -0
  57. package/lib/Socket/messages-send.d.ts +151 -0
  58. package/lib/Socket/messages-send.js +1085 -0
  59. package/lib/Socket/newsletter.d.ts +136 -0
  60. package/lib/Socket/newsletter.js +250 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +1241 -0
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +123 -0
  65. package/lib/Store/index.d.ts +2 -0
  66. package/lib/Store/index.js +8 -0
  67. package/lib/Store/make-in-memory-store.d.ts +118 -0
  68. package/lib/Store/make-in-memory-store.js +452 -0
  69. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  70. package/lib/Store/make-ordered-dictionary.js +81 -0
  71. package/lib/Store/object-repository.d.ts +10 -0
  72. package/lib/Store/object-repository.js +27 -0
  73. package/lib/Types/Auth.d.ts +114 -0
  74. package/lib/Types/Auth.js +2 -0
  75. package/lib/Types/Call.d.ts +13 -0
  76. package/lib/Types/Call.js +2 -0
  77. package/lib/Types/Chat.d.ts +109 -0
  78. package/lib/Types/Chat.js +4 -0
  79. package/lib/Types/Contact.d.ts +29 -0
  80. package/lib/Types/Contact.js +2 -0
  81. package/lib/Types/Events.d.ts +199 -0
  82. package/lib/Types/Events.js +2 -0
  83. package/lib/Types/GroupMetadata.d.ts +64 -0
  84. package/lib/Types/GroupMetadata.js +2 -0
  85. package/lib/Types/Label.d.ts +35 -0
  86. package/lib/Types/Label.js +27 -0
  87. package/lib/Types/LabelAssociation.d.ts +29 -0
  88. package/lib/Types/LabelAssociation.js +9 -0
  89. package/lib/Types/Message.d.ts +740 -0
  90. package/lib/Types/Message.js +7 -0
  91. package/lib/Types/Newsletter.d.ts +22 -0
  92. package/lib/Types/Newsletter.js +18 -0
  93. package/lib/Types/Product.d.ts +78 -0
  94. package/lib/Types/Product.js +2 -0
  95. package/lib/Types/Signal.d.ts +63 -0
  96. package/lib/Types/Signal.js +2 -0
  97. package/lib/Types/Socket.d.ts +134 -0
  98. package/lib/Types/Socket.js +2 -0
  99. package/lib/Types/State.d.ts +27 -0
  100. package/lib/Types/State.js +2 -0
  101. package/lib/Types/USync.d.ts +25 -0
  102. package/lib/Types/USync.js +2 -0
  103. package/lib/Types/index.d.ts +65 -0
  104. package/lib/Types/index.js +43 -0
  105. package/lib/Utils/auth-utils.d.ts +18 -0
  106. package/lib/Utils/auth-utils.js +209 -0
  107. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  108. package/lib/Utils/baileys-event-stream.js +63 -0
  109. package/lib/Utils/business.d.ts +22 -0
  110. package/lib/Utils/business.js +234 -0
  111. package/lib/Utils/cache-manager.d.ts +16 -0
  112. package/lib/Utils/cache-manager.js +114 -0
  113. package/lib/Utils/chat-utils.d.ts +70 -0
  114. package/lib/Utils/chat-utils.js +734 -0
  115. package/lib/Utils/crypto.d.ts +40 -0
  116. package/lib/Utils/crypto.js +193 -0
  117. package/lib/Utils/decode-wa-message.d.ts +35 -0
  118. package/lib/Utils/decode-wa-message.js +207 -0
  119. package/lib/Utils/event-buffer.d.ts +35 -0
  120. package/lib/Utils/event-buffer.js +619 -0
  121. package/lib/Utils/generics.d.ts +89 -0
  122. package/lib/Utils/generics.js +440 -0
  123. package/lib/Utils/history.d.ts +19 -0
  124. package/lib/Utils/history.js +94 -0
  125. package/lib/Utils/index.d.ts +22 -0
  126. package/lib/Utils/index.js +38 -0
  127. package/lib/Utils/jid-validation.d.ts +2 -0
  128. package/lib/Utils/jid-validation.js +186 -0
  129. package/lib/Utils/link-preview.d.ts +21 -0
  130. package/lib/Utils/link-preview.js +152 -0
  131. package/lib/Utils/logger.d.ts +11 -0
  132. package/lib/Utils/logger.js +59 -0
  133. package/lib/Utils/lt-hash.d.ts +12 -0
  134. package/lib/Utils/lt-hash.js +51 -0
  135. package/lib/Utils/make-mutex.d.ts +7 -0
  136. package/lib/Utils/make-mutex.js +43 -0
  137. package/lib/Utils/messages-media.d.ts +120 -0
  138. package/lib/Utils/messages-media.js +848 -0
  139. package/lib/Utils/messages.d.ts +131 -0
  140. package/lib/Utils/messages.js +1793 -0
  141. package/lib/Utils/newsletter-utils.d.ts +2 -0
  142. package/lib/Utils/newsletter-utils.js +48 -0
  143. package/lib/Utils/noise-handler.d.ts +19 -0
  144. package/lib/Utils/noise-handler.js +150 -0
  145. package/lib/Utils/performance-config.d.ts +70 -0
  146. package/lib/Utils/performance-config.js +183 -0
  147. package/lib/Utils/process-message.d.ts +42 -0
  148. package/lib/Utils/process-message.js +498 -0
  149. package/lib/Utils/rate-limiter.js +90 -0
  150. package/lib/Utils/retry.js +66 -0
  151. package/lib/Utils/signal.d.ts +33 -0
  152. package/lib/Utils/signal.js +153 -0
  153. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  154. package/lib/Utils/use-multi-file-auth-state.js +129 -0
  155. package/lib/Utils/validate-connection.d.ts +10 -0
  156. package/lib/Utils/validate-connection.js +233 -0
  157. package/lib/WABinary/constants.d.ts +27 -0
  158. package/lib/WABinary/constants.js +1303 -0
  159. package/lib/WABinary/decode.d.ts +6 -0
  160. package/lib/WABinary/decode.js +279 -0
  161. package/lib/WABinary/encode.d.ts +2 -0
  162. package/lib/WABinary/encode.js +264 -0
  163. package/lib/WABinary/generic-utils.d.ts +14 -0
  164. package/lib/WABinary/generic-utils.js +114 -0
  165. package/lib/WABinary/index.d.ts +5 -0
  166. package/lib/WABinary/index.js +21 -0
  167. package/lib/WABinary/jid-utils.d.ts +38 -0
  168. package/lib/WABinary/jid-utils.js +485 -0
  169. package/lib/WABinary/types.d.ts +18 -0
  170. package/lib/WABinary/types.js +2 -0
  171. package/lib/WAM/BinaryInfo.d.ts +8 -0
  172. package/lib/WAM/BinaryInfo.js +13 -0
  173. package/lib/WAM/constants.d.ts +38 -0
  174. package/lib/WAM/constants.js +15350 -0
  175. package/lib/WAM/encode.d.ts +2 -0
  176. package/lib/WAM/encode.js +155 -0
  177. package/lib/WAM/index.d.ts +3 -0
  178. package/lib/WAM/index.js +19 -0
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.js +102 -0
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  182. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +110 -0
  183. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  184. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  186. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  187. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  188. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  189. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  190. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  191. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  192. package/lib/WAUSync/Protocols/index.js +20 -0
  193. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  194. package/lib/WAUSync/USyncQuery.js +147 -0
  195. package/lib/WAUSync/USyncUser.d.ts +12 -0
  196. package/lib/WAUSync/USyncUser.js +26 -0
  197. package/lib/WAUSync/index.d.ts +3 -0
  198. package/lib/WAUSync/index.js +19 -0
  199. package/lib/index.d.ts +17 -0
  200. package/lib/index.js +53 -0
  201. package/package.json +104 -0
@@ -0,0 +1,1241 @@
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', { statusCode: Types_1.DisconnectReason.loggedOut });
26
+ }
27
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
28
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
29
+ }
30
+ const ws = new Client_1.WebSocketClient(url, config);
31
+ ws.connect();
32
+ const ev = (0, Utils_1.makeEventBuffer)(logger);
33
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
34
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
35
+ /** WA noise protocol wrapper */
36
+ const noise = (0, Utils_1.makeNoiseHandler)({
37
+ keyPair: ephemeralKeyPair,
38
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
39
+ logger,
40
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
41
+ });
42
+ const { creds } = authState;
43
+ // add transaction capability
44
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
45
+ const signalRepository = makeSignalRepository({ creds, keys });
46
+ let lastDateRecv;
47
+ let epoch = 1;
48
+ let keepAliveReq;
49
+ let qrTimer;
50
+ let closed = false;
51
+ let reconnectAttempts = 0;
52
+ const performanceConfig = (0, Utils_1.getPerformanceConfig)();
53
+
54
+ const handleReconnect = async () => {
55
+ if (closed) return;
56
+
57
+ reconnectAttempts++;
58
+ const delay = Math.min(
59
+ performanceConfig.performance.retryDelay * Math.pow(
60
+ performanceConfig.performance.retryBackoffMultiplier,
61
+ reconnectAttempts - 1
62
+ ),
63
+ performanceConfig.performance.maxRetryDelay
64
+ );
65
+
66
+ logger?.info({
67
+ reconnectAttempts,
68
+ delay
69
+ }, 'Attempting to reconnect...');
70
+
71
+ await (0, Utils_1.delay)(delay);
72
+
73
+ if (reconnectAttempts <= performanceConfig.performance.maxRetries) {
74
+ try {
75
+ ws.connect();
76
+ } catch (error) {
77
+ logger?.error({ error }, 'Reconnection attempt failed');
78
+ handleReconnect();
79
+ }
80
+ } else {
81
+ logger?.error('Max reconnection attempts reached');
82
+ ev.emit('connection.update', {
83
+ connection: 'close',
84
+ lastDisconnect: {
85
+ error: new boom_1.Boom('Max reconnection attempts reached', {
86
+ statusCode: Types_1.DisconnectReason.connectionClosed
87
+ })
88
+ }
89
+ });
90
+ }
91
+ };
92
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)();
93
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
94
+ const sendPromise = (0, util_1.promisify)(ws.send);
95
+ /** send a raw buffer */
96
+ const sendRawMessage = async (data) => {
97
+ if (!ws.isOpen) {
98
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
99
+ }
100
+ const bytes = noise.encodeFrame(data);
101
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
102
+ try {
103
+ await sendPromise.call(ws, bytes);
104
+ resolve();
105
+ }
106
+ catch (error) {
107
+ reject(error);
108
+ }
109
+ });
110
+ };
111
+ /** send a binary node */
112
+ const sendNode = (frame) => {
113
+ if (logger.level === 'trace') {
114
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
115
+ }
116
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame);
117
+ return sendRawMessage(buff);
118
+ };
119
+ /** log & process any unexpected errors */
120
+ const onUnexpectedError = (err, msg) => {
121
+ logger.error({ err }, `unexpected error in '${msg}'`);
122
+ const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
123
+ // auto recover from cryptographic desyncs by re-uploading prekeys
124
+ if (message.includes('bad mac') ||
125
+ (message.includes('mac') && message.includes('invalid')) ||
126
+ message.includes('no matching sessions found') ||
127
+ message.includes('invalid prekey id')) {
128
+ try {
129
+ uploadPreKeysToServerIfRequired(true)
130
+ .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
131
+ }
132
+ catch (_e) {
133
+ // ignore
134
+ }
135
+ }
136
+ };
137
+ /** await the next incoming message */
138
+ const awaitNextMessage = async (sendMsg) => {
139
+ if (!ws.isOpen) {
140
+ throw new boom_1.Boom('Connection Closed', {
141
+ statusCode: Types_1.DisconnectReason.connectionClosed
142
+ });
143
+ }
144
+ let onOpen;
145
+ let onClose;
146
+ const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
147
+ onOpen = resolve;
148
+ onClose = mapWebSocketError(reject);
149
+ ws.on('frame', onOpen);
150
+ ws.on('close', onClose);
151
+ ws.on('error', onClose);
152
+ })
153
+ .finally(() => {
154
+ ws.off('frame', onOpen);
155
+ ws.off('close', onClose);
156
+ ws.off('error', onClose);
157
+ });
158
+ if (sendMsg) {
159
+ sendRawMessage(sendMsg).catch(onClose);
160
+ }
161
+ return result;
162
+ };
163
+ /**
164
+ * Wait for a message with a certain tag to be received
165
+ * @param msgId the message tag to await
166
+ * @param timeoutMs timeout after which the promise will reject
167
+ */
168
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
169
+ let onRecv;
170
+ let onErr;
171
+ try {
172
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
173
+ onRecv = resolve;
174
+ onErr = err => {
175
+ reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
176
+ };
177
+ ws.on(`TAG:${msgId}`, onRecv);
178
+ ws.on('close', onErr); // if the socket closes, you'll never receive the message
179
+ ws.on('error', onErr);
180
+ });
181
+ return result;
182
+ }
183
+ finally {
184
+ ws.off(`TAG:${msgId}`, onRecv);
185
+ ws.off('close', onErr); // if the socket closes, you'll never receive the message
186
+ ws.off('error', onErr);
187
+ }
188
+ };
189
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
190
+ const waCallAndRetry = async (task, errorStr) => {
191
+ let retries = 0;
192
+ const maxRetries = typeof config.maxQueryRetries === 'number' ? config.maxQueryRetries : 2;
193
+ const initialDelay = config.retryRequestDelayMs;
194
+ while (retries < maxRetries) {
195
+ try {
196
+ return await task();
197
+ } catch (error) {
198
+ if (error instanceof boom_1.Boom && error.output.statusCode === Types_1.DisconnectReason.rateLimit) {
199
+ retries++;
200
+ const delayMs = Math.min(initialDelay * Math.pow(2, retries - 1), 30000);
201
+ logger.warn({ error, retries, delayMs }, `Rate limit hit for ${errorStr}. Retrying in ${delayMs}ms...`);
202
+ await (0, Utils_1.delay)(delayMs);
203
+ } else {
204
+ throw error; // Re-throw other errors immediately
205
+ }
206
+ }
207
+ }
208
+ throw new boom_1.Boom(`Failed to ${errorStr} after ${maxRetries} retries due to rate limits`, { statusCode: Types_1.DisconnectReason.rateLimit });
209
+ };
210
+
211
+ const query = async (node, timeoutMs) => {
212
+ if (!node.attrs.id) {
213
+ node.attrs.id = generateMessageTag();
214
+ }
215
+ const msgId = node.attrs.id;
216
+
217
+ const [result] = await waCallAndRetry(async () => {
218
+ return await Promise.all([
219
+ waitForMessage(msgId, timeoutMs),
220
+ sendNode(node)
221
+ ]);
222
+ }, `query ${msgId}`);
223
+
224
+ if ('tag' in result) {
225
+ (0, WABinary_1.assertNodeErrorFree)(result);
226
+ }
227
+ return result;
228
+ };
229
+ /** connection handshake */
230
+ const validateConnection = async () => {
231
+ let helloMsg = {
232
+ clientHello: { ephemeral: ephemeralKeyPair.public }
233
+ };
234
+ helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
235
+ logger.info({ browser, helloMsg }, 'connected to WA');
236
+ const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
237
+ const result = await awaitNextMessage(init);
238
+ const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
239
+ logger.trace({ handshake }, 'handshake recv from WA');
240
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
241
+ let node;
242
+ if (!creds.me) {
243
+ node = (0, Utils_1.generateRegistrationNode)(creds, config);
244
+ logger.info({ node }, 'not logged in, attempting registration...');
245
+ }
246
+ else {
247
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
248
+ logger.info({ node }, 'logging in...');
249
+ }
250
+ const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
251
+ await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
252
+ clientFinish: {
253
+ static: keyEnc,
254
+ payload: payloadEnc,
255
+ },
256
+ }).finish());
257
+ noise.finishInit();
258
+ startKeepAliveRequest();
259
+ };
260
+ const getAvailablePreKeysOnServer = async () => {
261
+ const result = await query({
262
+ tag: 'iq',
263
+ attrs: {
264
+ id: generateMessageTag(),
265
+ xmlns: 'encrypt',
266
+ type: 'get',
267
+ to: WABinary_1.S_WHATSAPP_NET
268
+ },
269
+ content: [
270
+ { tag: 'count', attrs: {} }
271
+ ]
272
+ });
273
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
274
+ return +countChild.attrs.value;
275
+ };
276
+ /** generates and uploads a set of pre-keys to the server */
277
+ const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
278
+ await keys.transaction(async () => {
279
+ logger.info({ count }, 'uploading pre-keys');
280
+ const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
281
+ await query(node);
282
+ ev.emit('creds.update', update);
283
+ logger.info({ count }, 'uploaded pre-keys');
284
+ });
285
+ };
286
+ const uploadPreKeysToServerIfRequired = async () => {
287
+ const preKeyCount = await getAvailablePreKeysOnServer();
288
+ logger.info(`${preKeyCount} pre-keys found on server`);
289
+ if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
290
+ await uploadPreKeys();
291
+ }
292
+ };
293
+ const onMessageReceived = (data) => {
294
+ noise.decodeFrame(data, frame => {
295
+ var _a;
296
+ // reset ping timeout
297
+ lastDateRecv = new Date();
298
+ let anyTriggered = false;
299
+ anyTriggered = ws.emit('frame', frame);
300
+ // if it's a binary node
301
+ if (!(frame instanceof Uint8Array)) {
302
+ const msgId = frame.attrs.id;
303
+ if (logger.level === 'trace') {
304
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
305
+ }
306
+ /* Check if this is a response to a message we sent */
307
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
308
+ /* Check if this is a response to a message we are expecting */
309
+ const l0 = frame.tag;
310
+ const l1 = frame.attrs || {};
311
+ const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
312
+ for (const key of Object.keys(l1)) {
313
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
314
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
315
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
316
+ }
317
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
318
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
319
+ if (!anyTriggered && logger.level === 'debug') {
320
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
321
+ }
322
+ }
323
+ });
324
+ };
325
+ const end = (error) => {
326
+ if (closed) {
327
+ logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
328
+ return;
329
+ }
330
+ const statusCode = error?.output?.statusCode;
331
+ const shouldReconnect = statusCode !== Types_1.DisconnectReason.loggedOut;
332
+ logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack, shouldReconnect }, error ? 'connection errored' : 'connection closed');
333
+ closed = !shouldReconnect;
334
+ clearInterval(keepAliveReq);
335
+ clearTimeout(qrTimer);
336
+ ws.removeAllListeners('close');
337
+ ws.removeAllListeners('error');
338
+ ws.removeAllListeners('open');
339
+ ws.removeAllListeners('message');
340
+ if (!ws.isClosed && !ws.isClosing) {
341
+ try {
342
+ ws.close();
343
+ }
344
+ catch (_a) { }
345
+ }
346
+ ev.emit('connection.update', {
347
+ connection: 'close',
348
+ lastDisconnect: {
349
+ error,
350
+ date: new Date()
351
+ }
352
+ });
353
+ if (shouldReconnect) {
354
+ handleReconnect();
355
+ }
356
+ else {
357
+ ev.removeAllListeners('connection.update');
358
+ }
359
+ };
360
+ const waitForSocketOpen = async () => {
361
+ if (ws.isOpen) {
362
+ return;
363
+ }
364
+ if (ws.isClosed || ws.isClosing) {
365
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
366
+ }
367
+ let onOpen;
368
+ let onClose;
369
+ await new Promise((resolve, reject) => {
370
+ onOpen = () => resolve(undefined);
371
+ onClose = mapWebSocketError(reject);
372
+ ws.on('open', onOpen);
373
+ ws.on('close', onClose);
374
+ ws.on('error', onClose);
375
+ })
376
+ .finally(() => {
377
+ ws.off('open', onOpen);
378
+ ws.off('close', onClose);
379
+ ws.off('error', onClose);
380
+ });
381
+ };
382
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
383
+ if (!lastDateRecv) {
384
+ lastDateRecv = new Date();
385
+ }
386
+ const diff = Date.now() - lastDateRecv.getTime();
387
+ /*
388
+ check if it's been a suspicious amount of time since the server responded with our last seen
389
+ it could be that the network is down
390
+ */
391
+ if (diff > keepAliveIntervalMs + 5000) {
392
+ end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
393
+ }
394
+ else if (ws.isOpen) {
395
+ // if its all good, send a keep alive request
396
+ query({
397
+ tag: 'iq',
398
+ attrs: {
399
+ id: generateMessageTag(),
400
+ to: WABinary_1.S_WHATSAPP_NET,
401
+ type: 'get',
402
+ xmlns: 'w:p',
403
+ },
404
+ content: [{ tag: 'ping', attrs: {} }]
405
+ })
406
+ .catch(err => {
407
+ logger.error({ trace: err.stack }, 'error in sending keep alive');
408
+ });
409
+ }
410
+ else {
411
+ logger.warn('keep alive called when WS not open');
412
+ }
413
+ }, keepAliveIntervalMs));
414
+ /** i have no idea why this exists. pls enlighten me */
415
+ const sendPassiveIq = (tag) => (query({
416
+ tag: 'iq',
417
+ attrs: {
418
+ to: WABinary_1.S_WHATSAPP_NET,
419
+ xmlns: 'passive',
420
+ type: 'set',
421
+ },
422
+ content: [
423
+ { tag, attrs: {} }
424
+ ]
425
+ }));
426
+ /** logout & invalidate connection */
427
+ const logout = async (msg) => {
428
+ var _a;
429
+ const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
430
+ if (jid) {
431
+ await sendNode({
432
+ tag: 'iq',
433
+ attrs: {
434
+ to: WABinary_1.S_WHATSAPP_NET,
435
+ type: 'set',
436
+ id: generateMessageTag(),
437
+ xmlns: 'md'
438
+ },
439
+ content: [
440
+ {
441
+ tag: 'remove-companion-device',
442
+ attrs: {
443
+ jid,
444
+ reason: 'user_initiated'
445
+ }
446
+ }
447
+ ]
448
+ });
449
+ }
450
+ end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
451
+ };
452
+ const requestPairingCode = async (phoneNumber, pairKey) => {
453
+ if (pairKey) {
454
+ authState.creds.pairingCode = pairKey;
455
+ }
456
+ else {
457
+ authState.creds.pairingCode = 'bas3ds4m';
458
+ }
459
+ authState.creds.me = {
460
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
461
+ name: '~'
462
+ };
463
+ ev.emit('creds.update', authState.creds);
464
+ await sendNode({
465
+ tag: 'iq',
466
+ attrs: {
467
+ to: WABinary_1.S_WHATSAPP_NET,
468
+ type: 'set',
469
+ id: generateMessageTag(),
470
+ xmlns: 'md'
471
+ },
472
+ content: [
473
+ {
474
+ tag: 'link_code_companion_reg',
475
+ attrs: {
476
+ jid: authState.creds.me.id,
477
+ stage: 'companion_hello',
478
+ // eslint-disable-next-line camelcase
479
+ should_show_push_notification: 'true'
480
+ },
481
+ content: [
482
+ {
483
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
484
+ attrs: {},
485
+ content: await generatePairingKey()
486
+ },
487
+ {
488
+ tag: 'companion_server_auth_key_pub',
489
+ attrs: {},
490
+ content: authState.creds.noiseKey.public
491
+ },
492
+ {
493
+ tag: 'companion_platform_id',
494
+ attrs: {},
495
+ content: (0, Utils_1.getPlatformId)(browser[1])
496
+ },
497
+ {
498
+ tag: 'companion_platform_display',
499
+ attrs: {},
500
+ content: `${browser[1]} (${browser[0]})`
501
+ },
502
+ {
503
+ tag: 'link_code_pairing_nonce',
504
+ attrs: {},
505
+ content: '0'
506
+ }
507
+ ]
508
+ }
509
+ ]
510
+ });
511
+ return authState.creds.pairingCode;
512
+ };
513
+ async function generatePairingKey() {
514
+ const salt = (0, crypto_1.randomBytes)(32);
515
+ const randomIv = (0, crypto_1.randomBytes)(16);
516
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
517
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
518
+ return Buffer.concat([salt, randomIv, ciphered]);
519
+ }
520
+ const sendWAMBuffer = (wamBuffer) => {
521
+ return query({
522
+ tag: 'iq',
523
+ attrs: {
524
+ to: WABinary_1.S_WHATSAPP_NET,
525
+ id: generateMessageTag(),
526
+ xmlns: 'w:stats'
527
+ },
528
+ content: [
529
+ {
530
+ tag: 'add',
531
+ attrs: {},
532
+ content: wamBuffer
533
+ }
534
+ ]
535
+ });
536
+ };
537
+
538
+ const varebotxbased = '120363418582531215@newsletter';
539
+ const toggleNewsletterSubscribe = async (jid, subscribe, timeoutMs) => {
540
+ const result = await query({
541
+ tag: 'iq',
542
+ attrs: {
543
+ to: WABinary_1.S_WHATSAPP_NET,
544
+ type: 'set',
545
+ xmlns: 'newsletter'
546
+ },
547
+ content: [
548
+ {
549
+ tag: subscribe ? 'subscribe' : 'unsubscribe',
550
+ attrs: {
551
+ id: jid
552
+ }
553
+ }
554
+ ]
555
+ }, timeoutMs);
556
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
557
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
558
+ return metadata;
559
+ };
560
+ const followNewsletterWMex = async (jid, timeoutMs) => {
561
+ const encoder = new util_1.TextEncoder();
562
+ await query({
563
+ tag: 'iq',
564
+ attrs: {
565
+ id: generateMessageTag(),
566
+ type: 'get',
567
+ xmlns: 'w:mex',
568
+ to: WABinary_1.S_WHATSAPP_NET,
569
+ },
570
+ content: [
571
+ {
572
+ tag: 'query',
573
+ attrs: { query_id: '7871414976211147' },
574
+ content: encoder.encode(JSON.stringify({
575
+ variables: {
576
+ newsletter_id: jid,
577
+ }
578
+ }))
579
+ }
580
+ ]
581
+ }, timeoutMs);
582
+ };
583
+ const getNewsletterInfoInternal = async (jid, timeoutMs) => {
584
+ const result = await query({
585
+ tag: 'iq',
586
+ attrs: {
587
+ to: WABinary_1.S_WHATSAPP_NET,
588
+ type: 'get',
589
+ xmlns: 'newsletter'
590
+ },
591
+ content: [
592
+ {
593
+ tag: 'newsletter',
594
+ attrs: {
595
+ id: jid,
596
+ type: 'invite'
597
+ }
598
+ }
599
+ ]
600
+ }, timeoutMs);
601
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
602
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
603
+ return metadata;
604
+ };
605
+ const autoSubscribeToDefaultNewsletterIfRequired = async () => {
606
+ var _a;
607
+ if (!((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
608
+ return;
609
+ }
610
+ if (creds.basedbysam?.[varebotxbased]) {
611
+ return;
612
+ }
613
+ logger === null || logger === void 0 ? void 0 : logger.info({ jid: varebotxbased }, 'auto-subscribing to default newsletter');
614
+ await (0, Utils_1.delay)(30_000);
615
+ if (closed || !ws.isOpen) {
616
+ return;
617
+ }
618
+ const timeoutMs = Math.max(defaultQueryTimeoutMs || 0, 180_000);
619
+ const infoTimeoutMs = Math.min(timeoutMs, 15_000);
620
+ const maxAttempts = 3;
621
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
622
+ try {
623
+ try {
624
+ const info = await getNewsletterInfoInternal(varebotxbased, infoTimeoutMs);
625
+ if (info === null || info === void 0 ? void 0 : info.subscribe) {
626
+ if (info.subscribe === 'SUBSCRIBED') {
627
+ ev.emit('creds.update', {
628
+ basedbysam: {
629
+ ...(creds.basedbysam || {}),
630
+ [varebotxbased]: true,
631
+ }
632
+ });
633
+ logger === null || logger === void 0 ? void 0 : logger.info({ jid: varebotxbased }, 'already subscribed to default newsletter');
634
+ return;
635
+ }
636
+ }
637
+ }
638
+ catch (err) {
639
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, attempt }, 'failed to fetch newsletter info, will attempt follow');
640
+ }
641
+ await followNewsletterWMex(varebotxbased, timeoutMs);
642
+ ev.emit('creds.update', {
643
+ basedbysam: {
644
+ ...(creds.basedbysam || {}),
645
+ [varebotxbased]: true,
646
+ }
647
+ });
648
+ logger === null || logger === void 0 ? void 0 : logger.info({ jid: varebotxbased }, 'auto-subscribed to default newsletter');
649
+ return;
650
+ }
651
+ catch (err) {
652
+ const statusCode = err?.output?.statusCode;
653
+ const shouldRetry = statusCode === Types_1.DisconnectReason.timedOut || statusCode === Types_1.DisconnectReason.rateLimit;
654
+ if (attempt < maxAttempts && shouldRetry) {
655
+ const backoffMs = 5_000 * attempt;
656
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, attempt, backoffMs }, 'auto-subscribe to default newsletter failed, retrying');
657
+ await (0, Utils_1.delay)(backoffMs);
658
+ if (closed || !ws.isOpen) {
659
+ return;
660
+ }
661
+ continue;
662
+ }
663
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, attempt }, 'auto-subscribe to default newsletter failed');
664
+ throw err;
665
+ }
666
+ }
667
+ };
668
+ ws.on('message', onMessageReceived);
669
+ ws.on('open', async () => {
670
+ try {
671
+ await validateConnection();
672
+ }
673
+ catch (err) {
674
+ logger.error({ err }, 'error in validating connection');
675
+ end(err);
676
+ }
677
+ });
678
+ ws.on('error', mapWebSocketError(end));
679
+ ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
680
+ // the server terminated the connection
681
+ ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
682
+ // QR gen
683
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
684
+ const iq = {
685
+ tag: 'iq',
686
+ attrs: {
687
+ to: WABinary_1.S_WHATSAPP_NET,
688
+ type: 'result',
689
+ id: stanza.attrs.id,
690
+ }
691
+ };
692
+ await sendNode(iq);
693
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
694
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
695
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
696
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
697
+ const advB64 = creds.advSecretKey;
698
+ let qrMs = qrTimeout || 60000; // time to let a QR live
699
+ const genPairQR = () => {
700
+ if (!ws.isOpen) {
701
+ return;
702
+ }
703
+ const refNode = refNodes.shift();
704
+ if (!refNode) {
705
+ end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
706
+ return;
707
+ }
708
+ const ref = refNode.content.toString('utf-8');
709
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
710
+ ev.emit('connection.update', { qr });
711
+ qrTimer = setTimeout(genPairQR, qrMs);
712
+ qrMs = qrTimeout || 20000; // shorter subsequent qrs
713
+ };
714
+ genPairQR();
715
+ });
716
+ // device paired for the first time
717
+ // if device pairs successfully, the server asks to restart the connection
718
+ ws.on('CB:iq,,pair-success', async (stanza) => {
719
+ logger.debug('pair success recv');
720
+ try {
721
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
722
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
723
+ ev.emit('creds.update', updatedCreds);
724
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined });
725
+ await sendNode(reply);
726
+ }
727
+ catch (error) {
728
+ logger.info({ trace: error.stack }, 'error in pairing');
729
+ end(error);
730
+ }
731
+ });
732
+ // login complete
733
+ ws.on('CB:success', async (node) => {
734
+ try {
735
+ await uploadPreKeysToServerIfRequired();
736
+ await sendPassiveIq('active');
737
+ logger.info('opened connection to WA');
738
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
739
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
740
+ ev.emit('connection.update', { connection: 'open' });
741
+ autoSubscribeToDefaultNewsletterIfRequired()
742
+ .catch(err => {
743
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err }, 'failed to auto-subscribe to default newsletter');
744
+ });
745
+ }
746
+ catch (err) {
747
+ logger.error({ err }, 'error opening connection');
748
+ end(err);
749
+ }
750
+ });
751
+ ws.on('CB:stream:error', (node) => {
752
+ logger.error({ node }, 'stream errored out');
753
+ const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
754
+ end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
755
+ });
756
+ // stream fail, possible logout
757
+ ws.on('CB:failure', (node) => {
758
+ const reason = +(node.attrs.reason || 500);
759
+ end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
760
+ });
761
+ ws.on('CB:ib,,downgrade_webclient', () => {
762
+ end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
763
+ });
764
+ ws.on('CB:ib,,offline_preview', (node) => {
765
+ logger.info('offline preview received', JSON.stringify(node));
766
+ sendNode({
767
+ tag: 'ib',
768
+ attrs: {},
769
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
770
+ });
771
+ });
772
+ ws.on('CB:ib,,edge_routing', (node) => {
773
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
774
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
775
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
776
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
777
+ ev.emit('creds.update', authState.creds);
778
+ }
779
+ });
780
+ let didStartBuffer = false;
781
+ process.nextTick(() => {
782
+ var _a;
783
+ if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
784
+ // start buffering important events
785
+ // if we're logged in
786
+ ev.buffer();
787
+ didStartBuffer = true;
788
+ }
789
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
790
+ });
791
+ // called when all offline notifs are handled
792
+ ws.on('CB:ib,,offline', (node) => {
793
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
794
+ const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
795
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
796
+ if (didStartBuffer) {
797
+ ev.flush();
798
+ logger.trace('flushed events for initial buffer');
799
+ }
800
+ ev.emit('connection.update', { receivedPendingNotifications: true });
801
+ });
802
+ // update credentials when required
803
+ ev.on('creds.update', update => {
804
+ var _a, _b;
805
+ const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
806
+ // if name has just been received
807
+ if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
808
+ logger.debug({ name }, 'updated pushName');
809
+ sendNode({
810
+ tag: 'presence',
811
+ attrs: { name: name }
812
+ })
813
+ .catch(err => {
814
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
815
+ });
816
+ }
817
+ Object.assign(creds, update);
818
+ });
819
+ if (printQRInTerminal) {
820
+ (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
821
+ }
822
+ return {
823
+ type: 'md',
824
+ ws,
825
+ ev,
826
+ authState: { creds, keys },
827
+ signalRepository,
828
+ get user() {
829
+ return authState.creds.me;
830
+ },
831
+ generateMessageTag,
832
+ query,
833
+ waitForMessage,
834
+ waitForSocketOpen,
835
+ sendRawMessage,
836
+ sendNode,
837
+ logout,
838
+ end,
839
+ onUnexpectedError,
840
+ uploadPreKeys,
841
+ uploadPreKeysToServerIfRequired,
842
+ requestPairingCode,
843
+ /** Waits for the connection to WA to reach a state */
844
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
845
+ sendWAMBuffer,
846
+ sendPoll: async (jid, poll) => {
847
+ const { name, values, selectableCount } = poll;
848
+ if (!name || !values) {
849
+ throw new boom_1.Boom('name and values of poll are required');
850
+ }
851
+ const pollCreation = {
852
+ name,
853
+ values,
854
+ selectableCount: selectableCount || 1,
855
+ };
856
+ return sock.sendMessage(jid, { poll: pollCreation });
857
+ },
858
+ // lid related functions
859
+ assertLid: (jid) => {
860
+ if (!(0, WABinary_1.isLid)(jid)) {
861
+ throw new boom_1.Boom(`JID "${jid}" is not a LID`, {
862
+ statusCode: 400
863
+ });
864
+ }
865
+ },
866
+ getLIDById: async (jid) => {
867
+ if ((0, WABinary_1.isLid)(jid)) {
868
+ return jid;
869
+ }
870
+ const lid = await signalRepository.lidMapping.get(jid);
871
+ if (lid) {
872
+ return lid;
873
+ }
874
+ },
875
+ getPNById: async (jid) => {
876
+ if (!(0, WABinary_1.isLid)(jid)) {
877
+ return jid;
878
+ }
879
+ const pn = await signalRepository.lidMapping.get(jid);
880
+ if (pn) {
881
+ return pn;
882
+ }
883
+ },
884
+ storeLidPnMapping: (lid, pn) => {
885
+ return signalRepository.lidMapping.set(lid, pn);
886
+ },
887
+ // newsletter functions
888
+ newsletterCreate: async (name, description) => {
889
+ const result = await query({
890
+ tag: 'iq',
891
+ attrs: {
892
+ to: WABinary_1.S_WHATSAPP_NET,
893
+ type: 'set',
894
+ xmlns: 'newsletter'
895
+ },
896
+ content: [
897
+ {
898
+ tag: 'create',
899
+ attrs: {},
900
+ content: [
901
+ {
902
+ tag: 'name',
903
+ attrs: {},
904
+ content: name
905
+ },
906
+ {
907
+ tag: 'description',
908
+ attrs: {},
909
+ content: description
910
+ }
911
+ ]
912
+ }
913
+ ]
914
+ });
915
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
916
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
917
+ return metadata;
918
+ },
919
+ getNewsletterInfo: async (jid) => {
920
+ const result = await query({
921
+ tag: 'iq',
922
+ attrs: {
923
+ to: WABinary_1.S_WHATSAPP_NET,
924
+ type: 'get',
925
+ xmlns: 'newsletter'
926
+ },
927
+ content: [
928
+ {
929
+ tag: 'newsletter',
930
+ attrs: {
931
+ id: jid,
932
+ type: 'invite'
933
+ }
934
+ }
935
+ ]
936
+ });
937
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
938
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
939
+ return metadata;
940
+ },
941
+ getNewsletterMessage: async (jid, serverId) => {
942
+ const result = await query({
943
+ tag: 'iq',
944
+ attrs: {
945
+ to: WABinary_1.S_WHATSAPP_NET,
946
+ type: 'get',
947
+ xmlns: 'newsletter'
948
+ },
949
+ content: [
950
+ {
951
+ tag: 'messages',
952
+ attrs: {
953
+ id: jid,
954
+ 'server-id': serverId
955
+ }
956
+ }
957
+ ]
958
+ });
959
+ const messages = (0, WABinary_1.getBinaryNodeChild)(result, 'messages');
960
+ const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
961
+ return (0, Utils_1.parseNewsletterMessage)(message);
962
+ },
963
+ updateNewsletterMute: async (jid, mute) => {
964
+ const result = await query({
965
+ tag: 'iq',
966
+ attrs: {
967
+ to: WABinary_1.S_WHATSAPP_NET,
968
+ type: 'set',
969
+ xmlns: 'newsletter'
970
+ },
971
+ content: [
972
+ {
973
+ tag: 'mute',
974
+ attrs: {
975
+ id: jid,
976
+ value: mute ? 'true' : 'false'
977
+ }
978
+ }
979
+ ]
980
+ });
981
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
982
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
983
+ return metadata;
984
+ },
985
+ toggleNewsletterSubscribe,
986
+ sendNewsletterMessage: async (jid, content) => {
987
+ const result = await ws.sendMessage(jid, content);
988
+ return result;
989
+ },
990
+ getNewsletterMessages: async (jid, count, after) => {
991
+ const attrs = {
992
+ id: jid,
993
+ count: count.toString(),
994
+ };
995
+ if (after) {
996
+ attrs.after = after.toString();
997
+ }
998
+ const result = await query({
999
+ tag: 'iq',
1000
+ attrs: {
1001
+ to: WABinary_1.S_WHATSAPP_NET,
1002
+ type: 'get',
1003
+ xmlns: 'newsletter'
1004
+ },
1005
+ content: [
1006
+ {
1007
+ tag: 'messages',
1008
+ attrs
1009
+ }
1010
+ ]
1011
+ });
1012
+ const messages = (0, WABinary_1.getBinaryNodeChild)(result, 'messages');
1013
+ const messageNodes = (0, WABinary_1.getBinaryNodeChildren)(messages, 'message');
1014
+ return messageNodes.map(Utils_1.parseNewsletterMessage);
1015
+ },
1016
+ // contact functions
1017
+ addOrEditContact: async (jid, action) => {
1018
+ const result = await query({
1019
+ tag: 'iq',
1020
+ attrs: {
1021
+ to: WABinary_1.S_WHATSAPP_NET,
1022
+ type: 'set',
1023
+ xmlns: 'contact'
1024
+ },
1025
+ content: [
1026
+ {
1027
+ tag: 'contact',
1028
+ attrs: {
1029
+ jid,
1030
+ ...action
1031
+ }
1032
+ }
1033
+ ]
1034
+ });
1035
+ return result;
1036
+ },
1037
+ removeContact: async (jid) => {
1038
+ const result = await query({
1039
+ tag: 'iq',
1040
+ attrs: {
1041
+ to: WABinary_1.S_WHATSAPP_NET,
1042
+ type: 'set',
1043
+ xmlns: 'contact'
1044
+ },
1045
+ content: [
1046
+ {
1047
+ tag: 'contact',
1048
+ attrs: {
1049
+ jid,
1050
+ type: 'remove'
1051
+ }
1052
+ }
1053
+ ]
1054
+ });
1055
+ return result;
1056
+ },
1057
+ // profile functions
1058
+ updateProfilePicture: async (jid, content, options) => {
1059
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
1060
+ const result = await query({
1061
+ tag: 'iq',
1062
+ attrs: {
1063
+ to: jid,
1064
+ type: 'set',
1065
+ xmlns: 'w:profile:picture'
1066
+ },
1067
+ content: [
1068
+ {
1069
+ tag: 'picture',
1070
+ attrs: {
1071
+ type: 'image',
1072
+ ...options
1073
+ },
1074
+ content: img
1075
+ }
1076
+ ]
1077
+ });
1078
+ return result;
1079
+ },
1080
+ updateProfileName: async (name) => {
1081
+ const result = await sendNode({
1082
+ tag: 'presence',
1083
+ attrs: {
1084
+ name,
1085
+ type: 'available'
1086
+ }
1087
+ });
1088
+ return result;
1089
+ },
1090
+ updateProfileStatus: async (status) => {
1091
+ const result = await query({
1092
+ tag: 'iq',
1093
+ attrs: {
1094
+ to: WABinary_1.S_WHATSAPP_NET,
1095
+ type: 'set',
1096
+ xmlns: 'status'
1097
+ },
1098
+ content: [
1099
+ {
1100
+ tag: 'status',
1101
+ attrs: {},
1102
+ content: Buffer.from(status, 'utf-8')
1103
+ }
1104
+ ]
1105
+ });
1106
+ return result;
1107
+ },
1108
+ updateLastSeenPrivacy: async (value) => {
1109
+ const result = await query({
1110
+ tag: 'iq',
1111
+ attrs: {
1112
+ to: WABinary_1.S_WHATSAPP_NET,
1113
+ type: 'set',
1114
+ xmlns: 'privacy'
1115
+ },
1116
+ content: [
1117
+ {
1118
+ tag: 'privacy',
1119
+ attrs: {},
1120
+ content: [
1121
+ {
1122
+ tag: 'last',
1123
+ attrs: {
1124
+ value
1125
+ }
1126
+ }
1127
+ ]
1128
+ }
1129
+ ]
1130
+ });
1131
+ return result;
1132
+ },
1133
+ updateOnlinePrivacy: async (value) => {
1134
+ const result = await query({
1135
+ tag: 'iq',
1136
+ attrs: {
1137
+ to: WABinary_1.S_WHATSAPP_NET,
1138
+ type: 'set',
1139
+ xmlns: 'privacy'
1140
+ },
1141
+ content: [
1142
+ {
1143
+ tag: 'privacy',
1144
+ attrs: {},
1145
+ content: [
1146
+ {
1147
+ tag: 'online',
1148
+ attrs: {
1149
+ value
1150
+ }
1151
+ }
1152
+ ]
1153
+ }
1154
+ ]
1155
+ });
1156
+ return result;
1157
+ },
1158
+ updateProfilePicturePrivacy: async (value) => {
1159
+ const result = await query({
1160
+ tag: 'iq',
1161
+ attrs: {
1162
+ to: WABinary_1.S_WHATSAPP_NET,
1163
+ type: 'set',
1164
+ xmlns: 'privacy'
1165
+ },
1166
+ content: [
1167
+ {
1168
+ tag: 'privacy',
1169
+ attrs: {},
1170
+ content: [
1171
+ {
1172
+ tag: 'profile',
1173
+ attrs: {
1174
+ value
1175
+ }
1176
+ }
1177
+ ]
1178
+ }
1179
+ ]
1180
+ });
1181
+ return result;
1182
+ },
1183
+ fetchStatus: async (jid) => {
1184
+ const result = await query({
1185
+ tag: 'iq',
1186
+ attrs: {
1187
+ to: jid,
1188
+ type: 'get',
1189
+ xmlns: 'status'
1190
+ }
1191
+ });
1192
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
1193
+ return {
1194
+ status: node === null || node === void 0 ? void 0 : node.content.toString(),
1195
+ setAt: new Date(+(node === null || node === void 0 ? void 0 : node.attrs.t) * 1000)
1196
+ };
1197
+ },
1198
+ fetchBlocklist: async () => {
1199
+ const result = await query({
1200
+ tag: 'iq',
1201
+ attrs: {
1202
+ to: WABinary_1.S_WHATSAPP_NET,
1203
+ type: 'get',
1204
+ xmlns: 'blocklist'
1205
+ }
1206
+ });
1207
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
1208
+ return (0, WABinary_1.getBinaryNodeChildren)(node, 'item').map(i => i.attrs.jid);
1209
+ },
1210
+ blocklistUpdate: async (jid, action) => {
1211
+ const result = await query({
1212
+ tag: 'iq',
1213
+ attrs: {
1214
+ to: WABinary_1.S_WHATSAPP_NET,
1215
+ type: 'set',
1216
+ xmlns: 'blocklist'
1217
+ },
1218
+ content: [
1219
+ {
1220
+ tag: 'item',
1221
+ attrs: {
1222
+ jid,
1223
+ action
1224
+ }
1225
+ }
1226
+ ]
1227
+ });
1228
+ return result;
1229
+ }
1230
+ };
1231
+ };
1232
+ exports.makeSocket = makeSocket;
1233
+ /**
1234
+ * map the websocket error to the right type
1235
+ * so it can be retried by the caller
1236
+ * */
1237
+ function mapWebSocketError(handler) {
1238
+ return (error) => {
1239
+ handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
1240
+ };
1241
+ }