@sgintokic/baileys 0.0.2

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.

Potentially problematic release.


This version of @sgintokic/baileys might be problematic. Click here for more details.

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