keith-baileys 1.0.26

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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/WAProto/GenerateStatics.sh +2 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/index.js +165029 -0
  6. package/WAProto/keith +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/Keith +1 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.js +105 -0
  11. package/lib/Signal/Group/Keith +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Keith +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Socket/Client/Keith +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +62 -0
  31. package/lib/Socket/Keith +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +880 -0
  34. package/lib/Socket/groups.js +340 -0
  35. package/lib/Socket/groupstatus.js +237 -0
  36. package/lib/Socket/index.js +10 -0
  37. package/lib/Socket/messages-recv.js +1077 -0
  38. package/lib/Socket/messages-send.js +988 -0
  39. package/lib/Socket/mex.js +46 -0
  40. package/lib/Socket/newsletter.js +233 -0
  41. package/lib/Socket/socket.js +617 -0
  42. package/lib/Socket/usync.js +65 -0
  43. package/lib/Types/Auth.js +2 -0
  44. package/lib/Types/Call.js +2 -0
  45. package/lib/Types/Chat.js +10 -0
  46. package/lib/Types/Contact.js +2 -0
  47. package/lib/Types/Events.js +2 -0
  48. package/lib/Types/GroupMetadata.js +2 -0
  49. package/lib/Types/Keith +1 -0
  50. package/lib/Types/Label.js +27 -0
  51. package/lib/Types/LabelAssociation.js +9 -0
  52. package/lib/Types/Message.js +7 -0
  53. package/lib/Types/Newsletter.js +33 -0
  54. package/lib/Types/Product.js +2 -0
  55. package/lib/Types/Signal.js +2 -0
  56. package/lib/Types/Socket.js +2 -0
  57. package/lib/Types/State.js +2 -0
  58. package/lib/Types/USync.js +2 -0
  59. package/lib/Types/index.js +42 -0
  60. package/lib/Utils/Keith +1 -0
  61. package/lib/Utils/auth-utils.js +199 -0
  62. package/lib/Utils/baileys-event-stream.js +63 -0
  63. package/lib/Utils/business.js +240 -0
  64. package/lib/Utils/chat-utils.js +741 -0
  65. package/lib/Utils/crypto.js +187 -0
  66. package/lib/Utils/decode-wa-message.js +283 -0
  67. package/lib/Utils/event-buffer.js +516 -0
  68. package/lib/Utils/generics.js +400 -0
  69. package/lib/Utils/history.js +100 -0
  70. package/lib/Utils/index.js +34 -0
  71. package/lib/Utils/lid-mapping.js +88 -0
  72. package/lib/Utils/link-preview.js +122 -0
  73. package/lib/Utils/logger.js +7 -0
  74. package/lib/Utils/lt-hash.js +51 -0
  75. package/lib/Utils/make-mutex.js +44 -0
  76. package/lib/Utils/messages-media.js +706 -0
  77. package/lib/Utils/messages.js +797 -0
  78. package/lib/Utils/noise-handler.js +150 -0
  79. package/lib/Utils/process-message.js +381 -0
  80. package/lib/Utils/signal.js +155 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  82. package/lib/Utils/validate-connection.js +170 -0
  83. package/lib/WABinary/Keith +1 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +266 -0
  86. package/lib/WABinary/encode.js +252 -0
  87. package/lib/WABinary/generic-utils.js +110 -0
  88. package/lib/WABinary/index.js +21 -0
  89. package/lib/WABinary/jid-utils.js +66 -0
  90. package/lib/WABinary/types.js +2 -0
  91. package/lib/WAM/BinaryInfo.js +13 -0
  92. package/lib/WAM/constants.js +15243 -0
  93. package/lib/WAM/encode.js +153 -0
  94. package/lib/WAM/index.js +19 -0
  95. package/lib/WAM/keith +1 -0
  96. package/lib/WAUSync/Keith +1 -0
  97. package/lib/WAUSync/Protocols/Keith +1 -0
  98. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  99. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  100. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  104. package/lib/WAUSync/Protocols/index.js +20 -0
  105. package/lib/WAUSync/USyncQuery.js +93 -0
  106. package/lib/WAUSync/USyncUser.js +26 -0
  107. package/lib/WAUSync/index.js +19 -0
  108. package/lib/index.js +30 -0
  109. package/package.json +32 -0
@@ -0,0 +1,400 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
7
+ exports.promiseTimeout = promiseTimeout;
8
+ exports.bindWaitForEvent = bindWaitForEvent;
9
+ exports.trimUndefined = trimUndefined;
10
+ exports.bytesToCrockford = bytesToCrockford;
11
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
12
+ const boom_1 = require("@hapi/boom");
13
+ const axios_1 = __importDefault(require("axios"));
14
+ const crypto_1 = require("crypto");
15
+ const os_1 = require("os");
16
+ const WAProto_1 = require("../../WAProto");
17
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json");
18
+ const Types_1 = require("../Types");
19
+ const WABinary_1 = require("../WABinary");
20
+ const PLATFORM_MAP = {
21
+ aix: 'AIX',
22
+ darwin: 'Mac OS',
23
+ win32: 'Windows',
24
+ android: 'Android',
25
+ freebsd: 'FreeBSD',
26
+ openbsd: 'OpenBSD',
27
+ sunos: 'Solaris'
28
+ };
29
+ exports.Browsers = {
30
+ ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
31
+ macOS: browser => ['Mac OS', browser, '14.4.1'],
32
+ baileys: browser => ['Baileys', browser, '6.5.0'],
33
+ windows: browser => ['Windows', browser, '10.0.22631'],
34
+ /** The appropriate browser based on your OS & release */
35
+ appropriate: browser => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
36
+ };
37
+ const getPlatformId = (browser) => {
38
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
39
+ return platformType ? platformType.toString() : '1'; //chrome
40
+ };
41
+ exports.getPlatformId = getPlatformId;
42
+ exports.BufferJSON = {
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ replacer: (k, value) => {
45
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
46
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
47
+ }
48
+ return value;
49
+ },
50
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
51
+ reviver: (_, value) => {
52
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
53
+ const val = value.data || value.value;
54
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
55
+ }
56
+ return value;
57
+ }
58
+ };
59
+ const getKeyAuthor = (key, meId = 'me') => ((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '';
60
+ exports.getKeyAuthor = getKeyAuthor;
61
+ const writeRandomPadMax16 = (msg) => {
62
+ const pad = (0, crypto_1.randomBytes)(1);
63
+ pad[0] &= 0xf;
64
+ if (!pad[0]) {
65
+ pad[0] = 0xf;
66
+ }
67
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
68
+ };
69
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
70
+ const unpadRandomMax16 = (e) => {
71
+ const t = new Uint8Array(e);
72
+ if (0 === t.length) {
73
+ throw new Error('unpadPkcs7 given empty bytes');
74
+ }
75
+ var r = t[t.length - 1];
76
+ if (r > t.length) {
77
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
78
+ }
79
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
80
+ };
81
+ exports.unpadRandomMax16 = unpadRandomMax16;
82
+ const encodeWAMessage = (message) => (0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish());
83
+ exports.encodeWAMessage = encodeWAMessage;
84
+ const generateRegistrationId = () => {
85
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
86
+ };
87
+ exports.generateRegistrationId = generateRegistrationId;
88
+ const encodeBigEndian = (e, t = 4) => {
89
+ let r = e;
90
+ const a = new Uint8Array(t);
91
+ for (let i = t - 1; i >= 0; i--) {
92
+ a[i] = 255 & r;
93
+ r >>>= 8;
94
+ }
95
+ return a;
96
+ };
97
+ exports.encodeBigEndian = encodeBigEndian;
98
+ const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
99
+ exports.toNumber = toNumber;
100
+ /** unix timestamp of a date in seconds */
101
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
102
+ exports.unixTimestampSeconds = unixTimestampSeconds;
103
+ const debouncedTimeout = (intervalMs = 1000, task) => {
104
+ let timeout;
105
+ return {
106
+ start: (newIntervalMs, newTask) => {
107
+ task = newTask || task;
108
+ intervalMs = newIntervalMs || intervalMs;
109
+ timeout && clearTimeout(timeout);
110
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
111
+ },
112
+ cancel: () => {
113
+ timeout && clearTimeout(timeout);
114
+ timeout = undefined;
115
+ },
116
+ setTask: (newTask) => (task = newTask),
117
+ setInterval: (newInterval) => (intervalMs = newInterval)
118
+ };
119
+ };
120
+ exports.debouncedTimeout = debouncedTimeout;
121
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
122
+ exports.delay = delay;
123
+ const delayCancellable = (ms) => {
124
+ const stack = new Error().stack;
125
+ let timeout;
126
+ let reject;
127
+ const delay = new Promise((resolve, _reject) => {
128
+ timeout = setTimeout(resolve, ms);
129
+ reject = _reject;
130
+ });
131
+ const cancel = () => {
132
+ clearTimeout(timeout);
133
+ reject(new boom_1.Boom('Cancelled', {
134
+ statusCode: 500,
135
+ data: {
136
+ stack
137
+ }
138
+ }));
139
+ };
140
+ return { delay, cancel };
141
+ };
142
+ exports.delayCancellable = delayCancellable;
143
+ async function promiseTimeout(ms, promise) {
144
+ if (!ms) {
145
+ return new Promise(promise);
146
+ }
147
+ const stack = new Error().stack;
148
+ // Create a promise that rejects in <ms> milliseconds
149
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
150
+ const p = new Promise((resolve, reject) => {
151
+ delay
152
+ .then(() => reject(new boom_1.Boom('Timed Out', {
153
+ statusCode: Types_1.DisconnectReason.timedOut,
154
+ data: {
155
+ stack
156
+ }
157
+ })))
158
+ .catch(err => reject(err));
159
+ promise(resolve, reject);
160
+ }).finally(cancel);
161
+ return p;
162
+ }
163
+ // inspired from whatsmeow code
164
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
165
+ const generateMessageIDV2 = (userId) => {
166
+ const data = Buffer.alloc(8 + 20 + 16);
167
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
168
+ if (userId) {
169
+ const id = (0, WABinary_1.jidDecode)(userId);
170
+ if (id === null || id === void 0 ? void 0 : id.user) {
171
+ data.write(id.user, 8);
172
+ data.write('@c.us', 8 + id.user.length);
173
+ }
174
+ }
175
+ const random = (0, crypto_1.randomBytes)(16);
176
+ random.copy(data, 28);
177
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
178
+ return 'KEITH-' + hash.toString('hex').toUpperCase().substring(0, 18);
179
+ };
180
+ exports.generateMessageIDV2 = generateMessageIDV2;
181
+ // generate a random ID to attach to a message
182
+ const generateMessageID = () => 'KEITH-' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
183
+ exports.generateMessageID = generateMessageID;
184
+ function bindWaitForEvent(ev, event) {
185
+ return async (check, timeoutMs) => {
186
+ let listener;
187
+ let closeListener;
188
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
189
+ closeListener = ({ connection, lastDisconnect }) => {
190
+ if (connection === 'close') {
191
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error) || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
192
+ }
193
+ };
194
+ ev.on('connection.update', closeListener);
195
+ listener = async (update) => {
196
+ if (await check(update)) {
197
+ resolve();
198
+ }
199
+ };
200
+ ev.on(event, listener);
201
+ }).finally(() => {
202
+ ev.off(event, listener);
203
+ ev.off('connection.update', closeListener);
204
+ });
205
+ };
206
+ }
207
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
208
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
209
+ /**
210
+ * utility that fetches latest baileys version from the master branch.
211
+ * Use to ensure your WA connection is always on the latest version
212
+ */
213
+ const fetchLatestBaileysVersion = async (options = {}) => {
214
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json';
215
+ try {
216
+ const result = await axios_1.default.get(URL, {
217
+ ...options,
218
+ responseType: 'json'
219
+ });
220
+ return {
221
+ version: result.data.version,
222
+ isLatest: true
223
+ };
224
+ }
225
+ catch (error) {
226
+ return {
227
+ version: baileys_version_json_1.version,
228
+ isLatest: false,
229
+ error
230
+ };
231
+ }
232
+ };
233
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
234
+ /**
235
+ * A utility that fetches the latest web version of whatsapp.
236
+ * Use to ensure your WA connection is always on the latest version
237
+ */
238
+ const fetchLatestWaWebVersion = async (options) => {
239
+ try {
240
+ const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
241
+ ...options,
242
+ responseType: 'json'
243
+ });
244
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
245
+ const match = data.match(regex);
246
+ if (!(match === null || match === void 0 ? void 0 : match[1])) {
247
+ return {
248
+ version: baileys_version_json_1.version,
249
+ isLatest: false,
250
+ error: {
251
+ message: 'Could not find client revision in the fetched content'
252
+ }
253
+ };
254
+ }
255
+ const clientRevision = match[1];
256
+ return {
257
+ version: [2, 3000, +clientRevision],
258
+ isLatest: true
259
+ };
260
+ }
261
+ catch (error) {
262
+ return {
263
+ version: baileys_version_json_1.version,
264
+ isLatest: false,
265
+ error
266
+ };
267
+ }
268
+ };
269
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
270
+ /** unique message tag prefix for MD clients */
271
+ const generateMdTagPrefix = () => {
272
+ const bytes = (0, crypto_1.randomBytes)(4);
273
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
274
+ };
275
+ exports.generateMdTagPrefix = generateMdTagPrefix;
276
+ const STATUS_MAP = {
277
+ sender: WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
278
+ played: WAProto_1.proto.WebMessageInfo.Status.PLAYED,
279
+ read: WAProto_1.proto.WebMessageInfo.Status.READ,
280
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
281
+ };
282
+ /**
283
+ * Given a type of receipt, returns what the new status of the message should be
284
+ * @param type type from receipt
285
+ */
286
+ const getStatusFromReceiptType = (type) => {
287
+ const status = STATUS_MAP[type];
288
+ if (typeof type === 'undefined') {
289
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
290
+ }
291
+ return status;
292
+ };
293
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
294
+ const CODE_MAP = {
295
+ conflict: Types_1.DisconnectReason.connectionReplaced
296
+ };
297
+ /**
298
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
299
+ * @param reason the string reason given, eg. "conflict"
300
+ */
301
+ const getErrorCodeFromStreamError = (node) => {
302
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
303
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
304
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
305
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
306
+ reason = 'restart required';
307
+ }
308
+ return {
309
+ reason,
310
+ statusCode
311
+ };
312
+ };
313
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
314
+ const getCallStatusFromNode = ({ tag, attrs }) => {
315
+ let status;
316
+ switch (tag) {
317
+ case 'offer':
318
+ case 'offer_notice':
319
+ status = 'offer';
320
+ break;
321
+ case 'terminate':
322
+ if (attrs.reason === 'timeout') {
323
+ status = 'timeout';
324
+ }
325
+ else {
326
+ //fired when accepted/rejected/timeout/caller hangs up
327
+ status = 'terminate';
328
+ }
329
+ break;
330
+ case 'reject':
331
+ status = 'reject';
332
+ break;
333
+ case 'accept':
334
+ status = 'accept';
335
+ break;
336
+ default:
337
+ status = 'ringing';
338
+ break;
339
+ }
340
+ return status;
341
+ };
342
+ exports.getCallStatusFromNode = getCallStatusFromNode;
343
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
344
+ const getCodeFromWSError = (error) => {
345
+ var _a, _b, _c;
346
+ let statusCode = 500;
347
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
348
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
349
+ if (!Number.isNaN(code) && code >= 400) {
350
+ statusCode = code;
351
+ }
352
+ }
353
+ else if (
354
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
+ ((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E')) ||
356
+ ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) {
357
+ // handle ETIMEOUT, ENOTFOUND etc
358
+ statusCode = 408;
359
+ }
360
+ return statusCode;
361
+ };
362
+ exports.getCodeFromWSError = getCodeFromWSError;
363
+ /**
364
+ * Is the given platform WA business
365
+ * @param platform AuthenticationCreds.platform
366
+ */
367
+ const isWABusinessPlatform = (platform) => {
368
+ return platform === 'smbi' || platform === 'smba';
369
+ };
370
+ exports.isWABusinessPlatform = isWABusinessPlatform;
371
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
372
+ function trimUndefined(obj) {
373
+ for (const key in obj) {
374
+ if (typeof obj[key] === 'undefined') {
375
+ delete obj[key];
376
+ }
377
+ }
378
+ return obj;
379
+ }
380
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
381
+ function bytesToCrockford(buffer) {
382
+ let value = 0;
383
+ let bitCount = 0;
384
+ const crockford = [];
385
+ for (const element of buffer) {
386
+ value = (value << 8) | (element & 0xff);
387
+ bitCount += 8;
388
+ while (bitCount >= 5) {
389
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
390
+ bitCount -= 5;
391
+ }
392
+ }
393
+ if (bitCount > 0) {
394
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
395
+ }
396
+ return crockford.join('');
397
+ }
398
+ function encodeNewsletterMessage(message) {
399
+ return WAProto_1.proto.Message.encode(message).finish();
400
+ }
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
+ const util_1 = require("util");
5
+ const zlib_1 = require("zlib");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const Types_1 = require("../Types");
8
+ const WABinary_1 = require("../WABinary");
9
+ const generics_1 = require("./generics");
10
+ const messages_1 = require("./messages");
11
+ const messages_media_1 = require("./messages-media");
12
+ const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
+ const downloadHistory = async (msg, options) => {
14
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
15
+ const bufferArray = [];
16
+ for await (const chunk of stream) {
17
+ bufferArray.push(chunk);
18
+ }
19
+ let buffer = Buffer.concat(bufferArray);
20
+ // decompress buffer
21
+ buffer = await inflatePromise(buffer);
22
+ const syncData = WAProto_1.proto.HistorySync.decode(buffer);
23
+ return syncData;
24
+ };
25
+ exports.downloadHistory = downloadHistory;
26
+ const processHistoryMessage = (item) => {
27
+ var _a, _b, _c;
28
+ const messages = [];
29
+ const contacts = [];
30
+ const chats = [];
31
+ switch (item.syncType) {
32
+ case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
+ case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
+ case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
35
+ case WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND:
36
+ for (const chat of item.conversations) {
37
+ contacts.push({ id: chat.id, name: chat.name || undefined, lid: chat.lidJid });
38
+ contacts.push({
39
+ id: chat.id,
40
+ name: chat.name || undefined,
41
+ lid: chat.lidJid || undefined,
42
+ jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : undefined
43
+ });
44
+ const msgs = chat.messages || [];
45
+ delete chat.messages;
46
+ delete chat.archived;
47
+ delete chat.muteEndTime;
48
+ delete chat.pinned;
49
+ for (const item of msgs) {
50
+ const message = item.message;
51
+ messages.push(message);
52
+ if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
53
+ // keep only the most recent message in the chat array
54
+ chat.messages = [{ message }];
55
+ }
56
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
57
+ chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
58
+ }
59
+ if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
60
+ message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
61
+ ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
62
+ contacts.push({
63
+ id: message.key.participant || message.key.remoteJid,
64
+ verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0]
65
+ });
66
+ }
67
+ }
68
+ if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
69
+ delete chat.readOnly;
70
+ }
71
+ chats.push({ ...chat });
72
+ }
73
+ break;
74
+ case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
75
+ for (const c of item.pushnames) {
76
+ contacts.push({ id: c.id, notify: c.pushname });
77
+ }
78
+ break;
79
+ }
80
+ return {
81
+ chats,
82
+ contacts,
83
+ messages,
84
+ syncType: item.syncType,
85
+ progress: item.progress
86
+ };
87
+ };
88
+ exports.processHistoryMessage = processHistoryMessage;
89
+ const downloadAndProcessHistorySyncNotification = async (msg, options) => {
90
+ const historyMsg = await (0, exports.downloadHistory)(msg, options);
91
+ return (0, exports.processHistoryMessage)(historyMsg);
92
+ };
93
+ exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
94
+ const getHistoryMsg = (message) => {
95
+ var _a;
96
+ const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
97
+ const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
98
+ return anyHistoryMsg;
99
+ };
100
+ exports.getHistoryMsg = getHistoryMsg;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./generics"), exports);
18
+ __exportStar(require("./decode-wa-message"), exports);
19
+ __exportStar(require("./messages"), exports);
20
+ __exportStar(require("./messages-media"), exports);
21
+ __exportStar(require("./validate-connection"), exports);
22
+ __exportStar(require("./crypto"), exports);
23
+ __exportStar(require("./signal"), exports);
24
+ __exportStar(require("./noise-handler"), exports);
25
+ __exportStar(require("./history"), exports);
26
+ __exportStar(require("./chat-utils"), exports);
27
+ __exportStar(require("./lt-hash"), exports);
28
+ __exportStar(require("./auth-utils"), exports);
29
+ __exportStar(require("./baileys-event-stream"), exports);
30
+ __exportStar(require("./use-multi-file-auth-state"), exports);
31
+ __exportStar(require("./link-preview"), exports);
32
+ __exportStar(require("./event-buffer"), exports);
33
+ __exportStar(require("./process-message"), exports);
34
+ __exportStar(require("./lid-mapping"), exports);
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLidMappingStore = exports.globalLidMapping = void 0;
4
+
5
+ const lidToPnMap = new Map();
6
+ const pnToLidMap = new Map();
7
+
8
+ const normalizeJid = (jid) => {
9
+ if (!jid) return null;
10
+ return jid.split(':')[0].split('@')[0];
11
+ };
12
+
13
+ exports.globalLidMapping = {
14
+ set(lid, pn) {
15
+ if (!lid || !pn) return;
16
+ const lidNorm = normalizeJid(lid);
17
+ const pnNorm = normalizeJid(pn);
18
+ if (lidNorm && pnNorm && /^\d+$/.test(pnNorm)) {
19
+ lidToPnMap.set(lidNorm, pnNorm + '@s.whatsapp.net');
20
+ pnToLidMap.set(pnNorm, lidNorm + '@lid');
21
+ }
22
+ },
23
+ getPnFromLid(lid) {
24
+ if (!lid) return undefined;
25
+ const lidNorm = normalizeJid(lid);
26
+ return lidToPnMap.get(lidNorm);
27
+ },
28
+ getLidFromPn(pn) {
29
+ if (!pn) return undefined;
30
+ const pnNorm = normalizeJid(pn);
31
+ return pnToLidMap.get(pnNorm);
32
+ },
33
+ getAll() {
34
+ const result = {};
35
+ lidToPnMap.forEach((pn, lid) => {
36
+ result[lid] = pn;
37
+ });
38
+ return result;
39
+ },
40
+ clear() {
41
+ lidToPnMap.clear();
42
+ pnToLidMap.clear();
43
+ },
44
+ size() {
45
+ return lidToPnMap.size;
46
+ }
47
+ };
48
+
49
+ const createLidMappingStore = () => {
50
+ const store = new Map();
51
+ const reverseStore = new Map();
52
+
53
+ const normalizeJid = (jid) => {
54
+ if (!jid) return null;
55
+ return jid.split(':')[0].split('@')[0];
56
+ };
57
+
58
+ return {
59
+ set(lid, pn) {
60
+ if (!lid || !pn) return;
61
+ const lidNorm = normalizeJid(lid);
62
+ const pnNorm = normalizeJid(pn);
63
+ if (lidNorm && pnNorm && /^\d+$/.test(pnNorm)) {
64
+ store.set(lidNorm, pnNorm + '@s.whatsapp.net');
65
+ reverseStore.set(pnNorm, lidNorm + '@lid');
66
+ exports.globalLidMapping.set(lid, pn);
67
+ }
68
+ },
69
+ getPnFromLid(lid) {
70
+ if (!lid) return undefined;
71
+ const lidNorm = normalizeJid(lid);
72
+ return store.get(lidNorm) || exports.globalLidMapping.getPnFromLid(lid);
73
+ },
74
+ getLidFromPn(pn) {
75
+ if (!pn) return undefined;
76
+ const pnNorm = normalizeJid(pn);
77
+ return reverseStore.get(pnNorm) || exports.globalLidMapping.getLidFromPn(pn);
78
+ },
79
+ getAll() {
80
+ const result = {};
81
+ store.forEach((pn, lid) => {
82
+ result[lid] = pn;
83
+ });
84
+ return result;
85
+ }
86
+ };
87
+ };
88
+ exports.createLidMappingStore = createLidMappingStore;