@prototypevip/baileys 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +23 -0
  2. package/WAProto/index.js +131118 -0
  3. package/engine-requirements.js +1 -0
  4. package/lib/Defaults/index.js +187 -0
  5. package/lib/Signal/Group/ciphertext-message.js +11 -0
  6. package/lib/Signal/Group/group-session-builder.js +41 -0
  7. package/lib/Signal/Group/group_cipher.js +108 -0
  8. package/lib/Signal/Group/index.js +11 -0
  9. package/lib/Signal/Group/keyhelper.js +14 -0
  10. package/lib/Signal/Group/sender-chain-key.js +31 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  12. package/lib/Signal/Group/sender-key-message.js +79 -0
  13. package/lib/Signal/Group/sender-key-name.js +49 -0
  14. package/lib/Signal/Group/sender-key-record.js +46 -0
  15. package/lib/Signal/Group/sender-key-state.js +104 -0
  16. package/lib/Signal/Group/sender-message-key.js +29 -0
  17. package/lib/Signal/libsignal.js +532 -0
  18. package/lib/Signal/lid-mapping.js +312 -0
  19. package/lib/Socket/Client/index.js +2 -0
  20. package/lib/Socket/Client/types.js +10 -0
  21. package/lib/Socket/Client/websocket.js +64 -0
  22. package/lib/Socket/business.js +293 -0
  23. package/lib/Socket/chats.js +1124 -0
  24. package/lib/Socket/communities.js +528 -0
  25. package/lib/Socket/groups.js +465 -0
  26. package/lib/Socket/index.js +14 -0
  27. package/lib/Socket/messages-recv.js +2325 -0
  28. package/lib/Socket/messages-send.js +1746 -0
  29. package/lib/Socket/mex.js +55 -0
  30. package/lib/Socket/newsletter.js +317 -0
  31. package/lib/Socket/socket.js +1185 -0
  32. package/lib/Store/cache-factory.js +20 -0
  33. package/lib/Store/index.js +5 -0
  34. package/lib/Store/make-in-memory-store.js +523 -0
  35. package/lib/Store/make-ordered-dictionary.js +203 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Store/prototype-store.js +958 -0
  38. package/lib/Types/Auth.js +1 -0
  39. package/lib/Types/Bussines.js +1 -0
  40. package/lib/Types/Call.js +1 -0
  41. package/lib/Types/Chat.js +7 -0
  42. package/lib/Types/Contact.js +1 -0
  43. package/lib/Types/Events.js +1 -0
  44. package/lib/Types/GroupMetadata.js +1 -0
  45. package/lib/Types/Label.js +24 -0
  46. package/lib/Types/LabelAssociation.js +6 -0
  47. package/lib/Types/Message.js +18 -0
  48. package/lib/Types/Mex.js +37 -0
  49. package/lib/Types/Newsletter.js +36 -0
  50. package/lib/Types/Product.js +1 -0
  51. package/lib/Types/RichType.js +25 -0
  52. package/lib/Types/Signal.js +1 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +78 -0
  55. package/lib/Types/USync.js +1 -0
  56. package/lib/Types/index.js +33 -0
  57. package/lib/Utils/auth-utils.js +303 -0
  58. package/lib/Utils/browser-utils.js +32 -0
  59. package/lib/Utils/business.js +245 -0
  60. package/lib/Utils/chat-utils.js +971 -0
  61. package/lib/Utils/companion-reg-client-utils.js +54 -0
  62. package/lib/Utils/constants.js +24 -0
  63. package/lib/Utils/crypto.js +133 -0
  64. package/lib/Utils/cstoken-utils.js +41 -0
  65. package/lib/Utils/decode-wa-message.js +406 -0
  66. package/lib/Utils/event-buffer.js +616 -0
  67. package/lib/Utils/generics.js +438 -0
  68. package/lib/Utils/history.js +147 -0
  69. package/lib/Utils/identity-change-handler.js +63 -0
  70. package/lib/Utils/index.js +29 -0
  71. package/lib/Utils/interactive-message-handler.js +478 -0
  72. package/lib/Utils/link-preview.js +91 -0
  73. package/lib/Utils/logger.js +2 -0
  74. package/lib/Utils/lt-hash.js +6 -0
  75. package/lib/Utils/make-mutex.js +31 -0
  76. package/lib/Utils/message-retry-manager.js +291 -0
  77. package/lib/Utils/messages-media.js +881 -0
  78. package/lib/Utils/messages.js +1434 -0
  79. package/lib/Utils/noise-handler.js +229 -0
  80. package/lib/Utils/normalize-message-identity.js +73 -0
  81. package/lib/Utils/offline-node-processor.js +50 -0
  82. package/lib/Utils/pre-key-manager.js +119 -0
  83. package/lib/Utils/process-message.js +648 -0
  84. package/lib/Utils/reporting-utils.js +355 -0
  85. package/lib/Utils/rich-message-utils.js +264 -0
  86. package/lib/Utils/signal.js +233 -0
  87. package/lib/Utils/stanza-ack.js +33 -0
  88. package/lib/Utils/sticker-utils.js +221 -0
  89. package/lib/Utils/sync-action-utils.js +53 -0
  90. package/lib/Utils/tc-token-utils.js +182 -0
  91. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  92. package/lib/Utils/use-prototype-auth-state.js +217 -0
  93. package/lib/Utils/use-single-file-auth-state.js +94 -0
  94. package/lib/Utils/validate-connection.js +235 -0
  95. package/lib/WABinary/constants.js +1468 -0
  96. package/lib/WABinary/decode.js +258 -0
  97. package/lib/WABinary/encode.js +219 -0
  98. package/lib/WABinary/generic-utils.js +202 -0
  99. package/lib/WABinary/index.js +5 -0
  100. package/lib/WABinary/jid-utils.js +94 -0
  101. package/lib/WABinary/types.js +1 -0
  102. package/lib/WAM/BinaryInfo.js +9 -0
  103. package/lib/WAM/constants.js +20669 -0
  104. package/lib/WAM/encode.js +151 -0
  105. package/lib/WAM/index.js +3 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  113. package/lib/WAUSync/Protocols/index.js +4 -0
  114. package/lib/WAUSync/USyncQuery.js +133 -0
  115. package/lib/WAUSync/USyncUser.js +22 -0
  116. package/lib/WAUSync/index.js +3 -0
  117. package/lib/index.js +12 -0
  118. package/package.json +78 -0
@@ -0,0 +1,438 @@
1
+ import { Boom } from "@hapi/boom";
2
+ import { createHash, randomBytes } from "crypto";
3
+ import { proto } from "../../WAProto/index.js";
4
+ import { DEFAULT_CONNECTION_CONFIG as config } from "../Defaults/index.js";
5
+ const baileysVersion = [2, 3e3, 1035194821];
6
+ import { DisconnectReason } from "../Types/index.js";
7
+ import {
8
+ getAllBinaryNodeChildren,
9
+ jidDecode,
10
+ isPnUser,
11
+ isLidUser,
12
+ isHostedPnUser,
13
+ isHostedLidUser,
14
+ jidNormalizedUser,
15
+ } from "../WABinary/index.js";
16
+ import { sha256 } from "./crypto.js";
17
+
18
+ export const resolveJID = (jid, lidMapping) => {
19
+ if (!jid || typeof jid !== "string") return jid;
20
+ if (isPnUser(jid) || isHostedPnUser(jid)) {
21
+ return jidNormalizedUser(jid);
22
+ }
23
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
24
+ const pn = lidMapping?.getPNForLIDSync(jid);
25
+ if (pn) return jidNormalizedUser(pn);
26
+ }
27
+ return jidNormalizedUser(jid);
28
+ };
29
+
30
+ export const BufferJSON = {
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
+ replacer: (k, value) => {
33
+ if (
34
+ Buffer.isBuffer(value) ||
35
+ value instanceof Uint8Array ||
36
+ value?.type === "Buffer"
37
+ ) {
38
+ return {
39
+ type: "Buffer",
40
+ data: Buffer.from(value?.data || value).toString("base64"),
41
+ };
42
+ }
43
+ return value;
44
+ },
45
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
46
+ reviver: (_, value) => {
47
+ if (
48
+ typeof value === "object" &&
49
+ value !== null &&
50
+ value.type === "Buffer" &&
51
+ typeof value.data === "string"
52
+ ) {
53
+ return Buffer.from(value.data, "base64");
54
+ }
55
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
56
+ const keys = Object.keys(value);
57
+ if (keys.length > 0 && keys.every((k) => !isNaN(parseInt(k, 10)))) {
58
+ const values = Object.values(value);
59
+ if (values.every((v) => typeof v === "number")) {
60
+ return Buffer.from(values);
61
+ }
62
+ }
63
+ }
64
+ return value;
65
+ },
66
+ };
67
+ export const getKeyAuthor = (key, meId) =>
68
+ (key?.fromMe
69
+ ? meId
70
+ : key?.participant ||
71
+ key?.remoteJid ||
72
+ key?.participantAlt ||
73
+ key?.remoteJidAlt) || "";
74
+ export const isStringNullOrEmpty = (value) =>
75
+ // eslint-disable-next-line eqeqeq
76
+ value == null || value === "";
77
+ export const writeRandomPadMax16 = (msg) => {
78
+ const pad = randomBytes(1);
79
+ const padLength = (pad[0] & 15) + 1;
80
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
81
+ };
82
+ export const unpadRandomMax16 = (e) => {
83
+ const t = new Uint8Array(e);
84
+ if (0 === t.length) {
85
+ throw new Error("unpadPkcs7 given empty bytes");
86
+ }
87
+ var r = t[t.length - 1];
88
+ if (r > t.length) {
89
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
90
+ }
91
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
92
+ };
93
+ // code is inspired by whatsmeow
94
+ export const generateParticipantHashV2 = (participants) => {
95
+ participants.sort();
96
+ const sha256Hash = sha256(Buffer.from(participants.join(""))).toString(
97
+ "base64",
98
+ );
99
+ return "2:" + sha256Hash.slice(0, 6);
100
+ };
101
+ export const encodeWAMessage = (message) =>
102
+ writeRandomPadMax16(proto.Message.encode(message).finish());
103
+ export const generateRegistrationId = () => {
104
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
105
+ };
106
+ export const encodeBigEndian = (e, t = 4) => {
107
+ let r = e;
108
+ const a = new Uint8Array(t);
109
+ for (let i = t - 1; i >= 0; i--) {
110
+ a[i] = 255 & r;
111
+ r >>>= 8;
112
+ }
113
+ return a;
114
+ };
115
+ export const toNumber = (t) =>
116
+ typeof t === "object" && t
117
+ ? "toNumber" in t
118
+ ? t.toNumber()
119
+ : t.low
120
+ : t || 0;
121
+ /** unix timestamp of a date in seconds */ export const unixTimestampSeconds = (
122
+ date = Date.now(),
123
+ ) => (date / 1e3) | 0; // Changed from new Date → Date.now for faster operation
124
+ export const debouncedTimeout = (intervalMs = 1e3, task) => {
125
+ let timeout;
126
+ return {
127
+ start: (newIntervalMs, newTask) => {
128
+ task = newTask || task;
129
+ intervalMs = newIntervalMs || intervalMs;
130
+ timeout && clearTimeout(timeout);
131
+ timeout = setTimeout(() => task?.(), intervalMs);
132
+ },
133
+ cancel: () => {
134
+ timeout && clearTimeout(timeout);
135
+ timeout = undefined;
136
+ },
137
+ setTask: (newTask) => (task = newTask),
138
+ setInterval: (newInterval) => (intervalMs = newInterval),
139
+ };
140
+ };
141
+ export const delay = (ms) => delayCancellable(ms).delay;
142
+ export const delayCancellable = (ms) => {
143
+ const stack = new Error().stack;
144
+ let timeout;
145
+ let reject;
146
+ const delay = new Promise((resolve, _reject) => {
147
+ timeout = setTimeout(resolve, ms);
148
+ reject = _reject;
149
+ });
150
+ const cancel = () => {
151
+ clearTimeout(timeout);
152
+ reject(new Boom("Cancelled", { statusCode: 500, data: { stack: stack } }));
153
+ };
154
+ return { delay: delay, cancel: cancel };
155
+ };
156
+ export async function promiseTimeout(ms, promise) {
157
+ if (!ms) {
158
+ return new Promise(promise);
159
+ }
160
+ const stack = new Error().stack;
161
+ // Create a promise that rejects in <ms> milliseconds
162
+ const { delay, cancel } = delayCancellable(ms);
163
+ const p = new Promise((resolve, reject) => {
164
+ delay
165
+ .then(() =>
166
+ reject(
167
+ new Boom("Timed Out", {
168
+ statusCode: DisconnectReason.timedOut,
169
+ data: { stack: stack },
170
+ }),
171
+ ),
172
+ )
173
+ .catch((err) => reject(err));
174
+ promise(resolve, reject);
175
+ }).finally(cancel);
176
+ return p;
177
+ }
178
+ // inspired from whatsmeow code
179
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
180
+ export const generateMessageIDV2 = (userId) => {
181
+ const idFromConfig =
182
+ typeof config.generateMessageIDV2 === "function"
183
+ ? config.generateMessageIDV2(userId)
184
+ : null;
185
+
186
+ if (typeof idFromConfig === "string" && idFromConfig) {
187
+ return idFromConfig;
188
+ }
189
+
190
+ const data = Buffer.allocUnsafe(8 + 20 + 16);
191
+ data.writeBigUInt64BE(BigInt(unixTimestampSeconds()));
192
+
193
+ if (userId) {
194
+ const id = jidDecode(userId);
195
+ if (id?.user) {
196
+ const len = data.write(id.user, 8);
197
+ data.write("@c.us", 8 + len);
198
+ }
199
+ }
200
+
201
+ randomBytes(16).copy(data, 28);
202
+ const hash = createHash("sha256").update(data).digest();
203
+ const hex = hash.toString("hex").toUpperCase();
204
+ return hex.substring(0, 32);
205
+ };
206
+
207
+ export const generateMessageID = () => {
208
+ const idFromConfig =
209
+ typeof config.generateMessageID === "function"
210
+ ? config.generateMessageID()
211
+ : null;
212
+
213
+ if (typeof idFromConfig === "string" && idFromConfig) {
214
+ return idFromConfig;
215
+ }
216
+
217
+ return randomBytes(32).toString("hex").toUpperCase();
218
+ };
219
+
220
+ export function bindWaitForEvent(ev, event) {
221
+ return async (check, timeoutMs) => {
222
+ let listener;
223
+ let closeListener;
224
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
225
+ closeListener = ({ connection, lastDisconnect }) => {
226
+ if (connection === "close") {
227
+ reject(
228
+ lastDisconnect?.error ||
229
+ new Boom("Connection Closed", {
230
+ statusCode: DisconnectReason.connectionClosed,
231
+ }),
232
+ );
233
+ }
234
+ };
235
+ ev.on("connection.update", closeListener);
236
+ listener = async (update) => {
237
+ if (await check(update)) {
238
+ resolve();
239
+ }
240
+ };
241
+ ev.on(event, listener);
242
+ }).finally(() => {
243
+ ev.off(event, listener);
244
+ ev.off("connection.update", closeListener);
245
+ });
246
+ };
247
+ }
248
+ export const bindWaitForConnectionUpdate = (ev) =>
249
+ bindWaitForEvent(ev, "connection.update");
250
+ /**
251
+ * utility that fetches latest baileys version from the master branch.
252
+ * Use to ensure your WA connection is always on the latest version
253
+ */ export const fetchLatestBaileysVersion = async (options = {}) => {
254
+ const URL =
255
+ "https://raw.githubusercontent.com/whiskeysockets/baileys/master/src/Defaults/baileys-version.json";
256
+ try {
257
+ const response = await fetch(URL, {
258
+ dispatcher: options.dispatcher,
259
+ method: "GET",
260
+ headers: options.headers,
261
+ });
262
+ if (!response.ok) {
263
+ throw new Boom(
264
+ `Failed to fetch latest Baileys version: ${response.statusText}`,
265
+ { statusCode: response.status },
266
+ );
267
+ }
268
+ const json = await response.json();
269
+ if (Array.isArray(json.version)) {
270
+ return { version: json.version, isLatest: true };
271
+ } else {
272
+ throw new Error("Could not get baileys version");
273
+ }
274
+ } catch (error) {
275
+ return { version: baileysVersion, isLatest: false, error: error };
276
+ }
277
+ };
278
+ /**
279
+ * A utility that fetches the latest web version of whatsapp.
280
+ * Use to ensure your WA connection is always on the latest version
281
+ */ export const fetchLatestWaWebVersion = async (options = {}) => {
282
+ try {
283
+ // Absolute minimal headers required to bypass anti-bot detection
284
+ const defaultHeaders = {
285
+ "sec-fetch-site": "none",
286
+ "user-agent":
287
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
288
+ };
289
+ const headers = { ...defaultHeaders, ...options.headers };
290
+ const response = await fetch("https://web.whatsapp.com/sw.js", {
291
+ ...options,
292
+ method: "GET",
293
+ headers: headers,
294
+ });
295
+ if (!response.ok) {
296
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, {
297
+ statusCode: response.status,
298
+ });
299
+ }
300
+ const data = await response.text();
301
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
302
+ const match = data.match(regex);
303
+ if (!match?.[1]) {
304
+ return {
305
+ version: baileysVersion,
306
+ isLatest: false,
307
+ error: {
308
+ message: "Could not find client revision in the fetched content",
309
+ },
310
+ };
311
+ }
312
+ const clientRevision = match[1];
313
+ return { version: [2, 3e3, +clientRevision], isLatest: true };
314
+ } catch (error) {
315
+ return { version: baileysVersion, isLatest: false, error: error };
316
+ }
317
+ };
318
+ /** unique message tag prefix for MD clients */ export const generateMdTagPrefix =
319
+ () => {
320
+ const bytes = randomBytes(4);
321
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
322
+ };
323
+ const STATUS_MAP = {
324
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
325
+ played: proto.WebMessageInfo.Status.PLAYED,
326
+ read: proto.WebMessageInfo.Status.READ,
327
+ "read-self": proto.WebMessageInfo.Status.READ,
328
+ };
329
+ /**
330
+ * Given a type of receipt, returns what the new status of the message should be
331
+ * @param type type from receipt
332
+ */ export const getStatusFromReceiptType = (type) => {
333
+ const status = STATUS_MAP[type];
334
+ if (typeof type === "undefined") {
335
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
336
+ }
337
+ return status;
338
+ };
339
+ const CODE_MAP = { conflict: DisconnectReason.connectionReplaced };
340
+ /**
341
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
342
+ * @param reason the string reason given, eg. "conflict"
343
+ */ export const getErrorCodeFromStreamError = (node) => {
344
+ const [reasonNode] = getAllBinaryNodeChildren(node);
345
+ let reason = reasonNode?.tag || "unknown";
346
+ const statusCode = +(
347
+ node.attrs.code ||
348
+ CODE_MAP[reason] ||
349
+ DisconnectReason.badSession
350
+ );
351
+ if (statusCode === DisconnectReason.restartRequired) {
352
+ reason = "restart required";
353
+ }
354
+ return { reason: reason, statusCode: statusCode };
355
+ };
356
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
357
+ let status;
358
+ switch (tag) {
359
+ case "offer":
360
+ case "offer_notice":
361
+ status = "offer";
362
+ break;
363
+ case "terminate":
364
+ if (attrs.reason === "timeout") {
365
+ status = "timeout";
366
+ } else {
367
+ //fired when accepted/rejected/timeout/caller hangs up
368
+ status = "terminate";
369
+ }
370
+ break;
371
+ case "reject":
372
+ status = "reject";
373
+ break;
374
+ case "accept":
375
+ status = "accept";
376
+ break;
377
+ default:
378
+ status = "ringing";
379
+ break;
380
+ }
381
+ return status;
382
+ };
383
+ const UNEXPECTED_SERVER_CODE_TEXT = "Unexpected server response: ";
384
+ export const getCodeFromWSError = (error) => {
385
+ let statusCode = 500;
386
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
387
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
388
+ if (!Number.isNaN(code) && code >= 400) {
389
+ statusCode = code;
390
+ }
391
+ } else if (
392
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
393
+ error?.code?.startsWith("E") ||
394
+ error?.message?.includes("timed out")
395
+ ) {
396
+ // handle ETIMEOUT, ENOTFOUND etc
397
+ statusCode = 408;
398
+ }
399
+ return statusCode;
400
+ };
401
+ /**
402
+ * Is the given platform WA business
403
+ * @param platform AuthenticationCreds.platform
404
+ */ export const isWABusinessPlatform = (platform) => {
405
+ return platform === "smbi" || platform === "smba";
406
+ };
407
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
408
+ export function trimUndefined(obj) {
409
+ for (const key in obj) {
410
+ if (typeof obj[key] === "undefined") {
411
+ delete obj[key];
412
+ }
413
+ }
414
+ return obj;
415
+ }
416
+ const CROCKFORD_CHARACTERS = "123456789ABCDEFGHJKLMNPQRSTVWXYZ";
417
+ export function bytesToCrockford(buffer) {
418
+ let value = 0;
419
+ let bitCount = 0;
420
+ const crockford = [];
421
+ for (const element of buffer) {
422
+ value = (value << 8) | (element & 255);
423
+ bitCount += 8;
424
+ while (bitCount >= 5) {
425
+ crockford.push(
426
+ CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31),
427
+ );
428
+ bitCount -= 5;
429
+ }
430
+ }
431
+ if (bitCount > 0) {
432
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
433
+ }
434
+ return crockford.join("");
435
+ }
436
+ export function encodeNewsletterMessage(message) {
437
+ return proto.Message.encode(message).finish();
438
+ }
@@ -0,0 +1,147 @@
1
+ import { pipeline } from "stream/promises";
2
+ import { promisify } from "util";
3
+ import { createInflate, inflate } from "zlib";
4
+ import { proto } from "../../WAProto/index.js";
5
+ import { WAMessageStubType } from "../Types/index.js";
6
+ import {
7
+ isHostedLidUser,
8
+ isHostedPnUser,
9
+ isLidUser,
10
+ isPnUser,
11
+ } from "../WABinary/index.js";
12
+ import { toNumber } from "./generics.js";
13
+ import { normalizeMessageContent } from "./messages.js";
14
+ import { downloadContentFromMessage } from "./messages-media.js";
15
+ const inflatePromise = promisify(inflate);
16
+ const extractPnFromMessages = (messages) => {
17
+ for (const msgItem of messages) {
18
+ const message = msgItem.message;
19
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
20
+ continue;
21
+ }
22
+ const userJid = message.userReceipt[0]?.userJid;
23
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
24
+ return userJid;
25
+ }
26
+ }
27
+ return undefined;
28
+ };
29
+ export const downloadHistory = async (msg, options) => {
30
+ const stream = await downloadContentFromMessage(msg, "md-msg-hist", {
31
+ options,
32
+ });
33
+ const inflater = createInflate();
34
+ const chunks = [];
35
+ inflater.on("data", (chunk) => chunks.push(chunk));
36
+ await pipeline(stream, inflater);
37
+ const buffer = Buffer.concat(chunks);
38
+ const syncData = proto.HistorySync.decode(buffer);
39
+ return syncData;
40
+ };
41
+ export const processHistoryMessage = (item, logger) => {
42
+ const messages = [];
43
+ const contacts = [];
44
+ const chats = [];
45
+ const lidPnMappings = [];
46
+ logger?.trace(
47
+ { progress: item.progress },
48
+ "processing history of type " + item.syncType?.toString(),
49
+ );
50
+ for (const m of item.phoneNumberToLidMappings || []) {
51
+ if (m.lidJid && m.pnJid) {
52
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
53
+ }
54
+ }
55
+ switch (item.syncType) {
56
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
57
+ case proto.HistorySync.HistorySyncType.RECENT:
58
+ case proto.HistorySync.HistorySyncType.FULL:
59
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
60
+ for (const chat of item.conversations) {
61
+ contacts.push({
62
+ id: chat.id,
63
+ name: chat.displayName || chat.name || chat.username || undefined,
64
+ username: chat.username || undefined,
65
+ lid: chat.lidJid || chat.accountLid || undefined,
66
+ phoneNumber: chat.pnJid || undefined,
67
+ });
68
+ const chatId = chat.id;
69
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
70
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
71
+ if (isLid && chat.pnJid) {
72
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
73
+ } else if (isPn && chat.lidJid) {
74
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
75
+ } else if (isLid && !chat.pnJid) {
76
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
77
+ if (pnFromReceipt) {
78
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
79
+ }
80
+ }
81
+ const msgs = chat.messages || [];
82
+ delete chat.messages;
83
+ for (const item of msgs) {
84
+ const message = item.message;
85
+ messages.push(message);
86
+ if (!chat.messages?.length) {
87
+ chat.messages = [{ message }];
88
+ }
89
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
90
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
91
+ }
92
+ if (
93
+ (message.messageStubType ===
94
+ WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
95
+ message.messageStubType ===
96
+ WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
97
+ message.messageStubParameters?.[0]
98
+ ) {
99
+ contacts.push({
100
+ id: message.key.participant || message.key.remoteJid,
101
+ verifiedName: message.messageStubParameters?.[0],
102
+ });
103
+ }
104
+ }
105
+ chats.push(chat);
106
+ }
107
+ break;
108
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
109
+ for (const c of item.pushnames) {
110
+ contacts.push({ id: c.id, notify: c.pushname });
111
+ }
112
+ break;
113
+ }
114
+ return {
115
+ chats,
116
+ contacts,
117
+ messages,
118
+ lidPnMappings,
119
+ nctSalt: item.nctSalt,
120
+ pastParticipants: item.pastParticipants,
121
+ syncType: item.syncType,
122
+ progress: item.progress,
123
+ };
124
+ };
125
+ export const downloadAndProcessHistorySyncNotification = async (
126
+ msg,
127
+ options,
128
+ logger,
129
+ ) => {
130
+ let historyMsg;
131
+ if (msg.initialHistBootstrapInlinePayload) {
132
+ historyMsg = proto.HistorySync.decode(
133
+ await inflatePromise(msg.initialHistBootstrapInlinePayload),
134
+ );
135
+ } else {
136
+ historyMsg = await downloadHistory(msg, options);
137
+ }
138
+ return processHistoryMessage(historyMsg, logger);
139
+ };
140
+ export const getHistoryMsg = (message) => {
141
+ const normalizedContent = !!message
142
+ ? normalizeMessageContent(message)
143
+ : undefined;
144
+ const anyHistoryMsg =
145
+ normalizedContent?.protocolMessage?.historySyncNotification;
146
+ return anyHistoryMsg;
147
+ };
@@ -0,0 +1,63 @@
1
+ import NodeCache from "@cacheable/node-cache";
2
+ import {
3
+ areJidsSameUser,
4
+ getBinaryNodeChild,
5
+ jidDecode,
6
+ } from "../WABinary/index.js";
7
+ import { isStringNullOrEmpty } from "./generics.js";
8
+ export async function handleIdentityChange(node, ctx) {
9
+ const from = node.attrs.from;
10
+ if (!from) {
11
+ return { action: "invalid_notification" };
12
+ }
13
+ const identityNode = getBinaryNodeChild(node, "identity");
14
+ if (!identityNode) {
15
+ return { action: "no_identity_node" };
16
+ }
17
+ ctx.logger.info({ jid: from }, "identity changed");
18
+ const decoded = jidDecode(from);
19
+ if (decoded?.device && decoded.device !== 0) {
20
+ ctx.logger.debug(
21
+ { jid: from, device: decoded.device },
22
+ "ignoring identity change from companion device",
23
+ );
24
+ return { action: "skipped_companion_device", device: decoded.device };
25
+ }
26
+ const isSelfPrimary =
27
+ ctx.meId &&
28
+ (areJidsSameUser(from, ctx.meId) ||
29
+ (ctx.meLid && areJidsSameUser(from, ctx.meLid)));
30
+ if (isSelfPrimary) {
31
+ ctx.logger.info({ jid: from }, "self primary identity changed");
32
+ return { action: "skipped_self_primary" };
33
+ }
34
+ if (ctx.debounceCache.get(from)) {
35
+ ctx.logger.debug({ jid: from }, "skipping identity assert (debounced)");
36
+ return { action: "debounced" };
37
+ }
38
+ ctx.debounceCache.set(from, true);
39
+ const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
40
+ const hasExistingSession = await ctx.validateSession(from);
41
+ if (!hasExistingSession.exists) {
42
+ ctx.logger.debug({ jid: from }, "no old session, skipping session refresh");
43
+ return { action: "skipped_no_session" };
44
+ }
45
+ ctx.logger.debug({ jid: from }, "old session exists, will refresh session");
46
+ if (isOfflineNotification) {
47
+ ctx.logger.debug(
48
+ { jid: from },
49
+ "skipping session refresh during offline processing",
50
+ );
51
+ return { action: "skipped_offline" };
52
+ }
53
+ try {
54
+ await ctx.assertSessions([from], true);
55
+ return { action: "session_refreshed" };
56
+ } catch (error) {
57
+ ctx.logger.warn(
58
+ { error: error, jid: from },
59
+ "failed to assert sessions after identity change",
60
+ );
61
+ return { action: "session_refresh_failed", error: error };
62
+ }
63
+ }
@@ -0,0 +1,29 @@
1
+ export * from "./make-mutex.js";
2
+ export * from "./generics.js";
3
+ export * from "./decode-wa-message.js";
4
+ export * from "./messages.js";
5
+ export * from "./messages-media.js";
6
+ export * from "./validate-connection.js";
7
+ export * from "./crypto.js";
8
+ export * from "./signal.js";
9
+ export * from "./noise-handler.js";
10
+ export * from "./history.js";
11
+ export * from "./chat-utils.js";
12
+ export * from "./lt-hash.js";
13
+ export * from "./auth-utils.js";
14
+ export * from "./use-multi-file-auth-state.js";
15
+ export * from "./use-single-file-auth-state.js";
16
+ export * from "./link-preview.js";
17
+ export * from "./event-buffer.js";
18
+ export * from "./process-message.js";
19
+ export * from "./message-retry-manager.js";
20
+ export * from "./browser-utils.js";
21
+ export * from "./companion-reg-client-utils.js";
22
+ export * from "./identity-change-handler.js";
23
+ export * from "./stanza-ack.js";
24
+ export * from "./tc-token-utils.js";
25
+ export * from "./cstoken-utils.js";
26
+ export * from "./use-prototype-auth-state.js";
27
+ export * from "./sticker-utils.js";
28
+ export * from "./rich-message-utils.js";
29
+ export * from "./constants.js";