@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,648 @@
1
+ import { Boom } from "@hapi/boom";
2
+ import { proto } from "../../WAProto/index.js";
3
+ import { WAMessageStubType } from "../Types/index.js";
4
+ import { getContentType, normalizeMessageContent } from "../Utils/messages.js";
5
+ import {
6
+ areJidsSameUser,
7
+ isHostedLidUser,
8
+ isHostedPnUser,
9
+ isJidBroadcast,
10
+ isJidStatusBroadcast,
11
+ isLidUser,
12
+ jidDecode,
13
+ jidEncode,
14
+ jidNormalizedUser,
15
+ } from "../WABinary/index.js";
16
+ import { aesDecryptGCM, hmacSign } from "./crypto.js";
17
+ import { getKeyAuthor, toNumber } from "./generics.js";
18
+ import { downloadAndProcessHistorySyncNotification } from "./history.js";
19
+ import {
20
+ buildMergedTcTokenIndexWrite,
21
+ resolveTcTokenJid,
22
+ } from "./tc-token-utils.js";
23
+ import { normalizeMessageIdentity } from "./normalize-message-identity.js";
24
+ const REAL_MSG_STUB_TYPES = new Set([
25
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
26
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
27
+ WAMessageStubType.CALL_MISSED_VIDEO,
28
+ WAMessageStubType.CALL_MISSED_VOICE,
29
+ ]);
30
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
31
+ WAMessageStubType.GROUP_PARTICIPANT_ADD,
32
+ ]);
33
+ async function storeTcTokensFromHistorySync(
34
+ chats,
35
+ signalRepository,
36
+ keyStore,
37
+ logger,
38
+ ) {
39
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(
40
+ signalRepository.lidMapping,
41
+ );
42
+ const candidates = [];
43
+ for (const chat of chats) {
44
+ const ts = chat.tcTokenTimestamp ? toNumber(chat.tcTokenTimestamp) : 0;
45
+ if (chat.tcToken?.length && ts > 0) {
46
+ const jid = jidNormalizedUser(chat.id);
47
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
48
+ candidates.push({
49
+ storageJid,
50
+ token: Buffer.from(chat.tcToken),
51
+ ts,
52
+ senderTs: chat.tcTokenSenderTimestamp
53
+ ? toNumber(chat.tcTokenSenderTimestamp)
54
+ : undefined,
55
+ });
56
+ }
57
+ }
58
+ if (!candidates.length) {
59
+ return;
60
+ }
61
+ const jids = candidates.map((c) => c.storageJid);
62
+ const existing = await keyStore.get("tctoken", jids);
63
+ const entries = {};
64
+ for (const c of candidates) {
65
+ const existingEntry = existing[c.storageJid];
66
+ const existingTs = existingEntry?.timestamp
67
+ ? Number(existingEntry.timestamp)
68
+ : 0;
69
+ if (existingTs > 0 && existingTs >= c.ts) {
70
+ continue;
71
+ }
72
+ entries[c.storageJid] = {
73
+ ...existingEntry,
74
+ token: c.token,
75
+ timestamp: String(c.ts),
76
+ ...(c.senderTs !== undefined ? { senderTimestamp: c.senderTs } : {}),
77
+ };
78
+ }
79
+ if (Object.keys(entries).length) {
80
+ logger?.debug(
81
+ { count: Object.keys(entries).length },
82
+ "storing tctokens from history sync",
83
+ );
84
+ try {
85
+ const indexWrite = await buildMergedTcTokenIndexWrite(
86
+ keyStore,
87
+ Object.keys(entries),
88
+ );
89
+ await keyStore.set({ tctoken: { ...entries, ...indexWrite } });
90
+ } catch (err) {
91
+ logger?.warn({ err }, "failed to store tctokens from history sync");
92
+ }
93
+ }
94
+ }
95
+ /** Cleans a received message to further processing */
96
+ export const cleanMessage = (message, meId, meLid) => {
97
+ if (
98
+ isHostedPnUser(message.key.remoteJid) ||
99
+ isHostedLidUser(message.key.remoteJid)
100
+ ) {
101
+ message.key.remoteJid = jidEncode(
102
+ jidDecode(message.key?.remoteJid)?.user,
103
+ isHostedPnUser(message.key.remoteJid) ? "s.whatsapp.net" : "lid",
104
+ );
105
+ } else {
106
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
107
+ }
108
+ if (
109
+ isHostedPnUser(message.key.participant) ||
110
+ isHostedLidUser(message.key.participant)
111
+ ) {
112
+ message.key.participant = jidEncode(
113
+ jidDecode(message.key.participant)?.user,
114
+ isHostedPnUser(message.key.participant) ? "s.whatsapp.net" : "lid",
115
+ );
116
+ } else {
117
+ message.key.participant = jidNormalizedUser(message.key.participant);
118
+ }
119
+ const content = normalizeMessageContent(message.message);
120
+ if (content?.reactionMessage) {
121
+ normaliseKey(content.reactionMessage.key);
122
+ }
123
+ if (content?.pollUpdateMessage) {
124
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
125
+ }
126
+ function normaliseKey(msgKey) {
127
+ if (!message.key.fromMe) {
128
+ msgKey.fromMe = !msgKey.fromMe
129
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
130
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
131
+ : msgKey.fromMe;
132
+ }
133
+ }
134
+ if (
135
+ isJidBroadcast(message.key.remoteJid) ||
136
+ isJidStatusBroadcast(message.key.remoteJid)
137
+ ) {
138
+ message.key.participant = jidNormalizedUser(
139
+ message.key.participant || message.participant,
140
+ );
141
+ }
142
+ };
143
+ export function decryptEventResponse(
144
+ { encPayload, encIv },
145
+ { eventCreatorJid, eventMsgId, eventEncKey, responderJid },
146
+ ) {
147
+ const sign = Buffer.concat([
148
+ toBinary(eventMsgId),
149
+ toBinary(eventCreatorJid),
150
+ toBinary(responderJid),
151
+ toBinary("Event Response"),
152
+ new Uint8Array([1]),
153
+ ]);
154
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), "sha256");
155
+ const decKey = hmacSign(sign, key0, "sha256");
156
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`);
157
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
158
+ return proto.Message.EventResponseMessage.decode(decrypted);
159
+ function toBinary(txt) {
160
+ return Buffer.from(txt);
161
+ }
162
+ }
163
+ export const isRealMessage = (message) => {
164
+ const normalizedContent = normalizeMessageContent(message.message);
165
+ const hasSomeContent = !!getContentType(normalizedContent);
166
+ return (
167
+ (!!normalizedContent ||
168
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
169
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
170
+ hasSomeContent &&
171
+ !normalizedContent?.protocolMessage &&
172
+ !normalizedContent?.reactionMessage &&
173
+ !normalizedContent?.pollUpdateMessage
174
+ );
175
+ };
176
+ export const shouldIncrementChatUnread = (message) =>
177
+ !message.key.fromMe && !message.messageStubType;
178
+
179
+ const processMessage = async (
180
+ message,
181
+ {
182
+ shouldProcessHistoryMsg,
183
+ placeholderResendCache,
184
+ ev,
185
+ creds,
186
+ signalRepository,
187
+ keyStore,
188
+ logger,
189
+ options,
190
+ getMessage,
191
+ },
192
+ ) => {
193
+ const meId = creds.me.id;
194
+ const { accountSettings } = creds;
195
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
196
+ const isRealMsg = isRealMessage(message);
197
+ if (isRealMsg) {
198
+ chat.messages = [{ message }];
199
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
200
+ if (shouldIncrementChatUnread(message)) {
201
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
202
+ }
203
+ }
204
+ const content = normalizeMessageContent(message.message);
205
+ if (
206
+ (isRealMsg || content?.reactionMessage?.key?.fromMe) &&
207
+ accountSettings?.unarchiveChats
208
+ ) {
209
+ chat.archived = false;
210
+ chat.readOnly = false;
211
+ }
212
+ const protocolMsg = content?.protocolMessage;
213
+ if (protocolMsg) {
214
+ const SELF_ONLY_TYPES = new Set([
215
+ proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
216
+ proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
217
+ proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
218
+ proto.Message.ProtocolMessage.Type
219
+ .PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE,
220
+ ]);
221
+ if (
222
+ protocolMsg.type !== null &&
223
+ protocolMsg.type !== undefined &&
224
+ SELF_ONLY_TYPES.has(protocolMsg.type) &&
225
+ !message.key.fromMe
226
+ ) {
227
+ logger?.warn(
228
+ {
229
+ msgId: message.key.id,
230
+ type: protocolMsg.type,
231
+ from: message.key.participant || message.key.remoteJid,
232
+ },
233
+ "dropping spoofed self-only protocolMessage from non-self origin",
234
+ );
235
+ return;
236
+ }
237
+ switch (protocolMsg.type) {
238
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
239
+ const histNotification = protocolMsg.historySyncNotification;
240
+ const process = shouldProcessHistoryMsg;
241
+ const isLatest = !creds.processedHistoryMessages?.length;
242
+ logger?.info(
243
+ {
244
+ histNotification,
245
+ process,
246
+ id: message.key.id,
247
+ isLatest,
248
+ },
249
+ "got history notification",
250
+ );
251
+ if (process) {
252
+ if (
253
+ histNotification.syncType !==
254
+ proto.HistorySync.HistorySyncType.ON_DEMAND
255
+ ) {
256
+ ev.emit("creds.update", {
257
+ processedHistoryMessages: [
258
+ ...(creds.processedHistoryMessages || []),
259
+ {
260
+ key: message.key,
261
+ messageTimestamp: message.messageTimestamp,
262
+ },
263
+ ],
264
+ });
265
+ }
266
+ const data = await downloadAndProcessHistorySyncNotification(
267
+ histNotification,
268
+ options,
269
+ logger,
270
+ );
271
+ if (data.lidPnMappings?.length) {
272
+ logger?.debug(
273
+ { count: data.lidPnMappings.length },
274
+ "processing LID-PN mappings from history sync",
275
+ );
276
+ await signalRepository.lidMapping
277
+ .storeLIDPNMappings(data.lidPnMappings)
278
+ .catch((err) =>
279
+ logger?.warn(
280
+ { err },
281
+ "failed to store LID-PN mappings from history sync",
282
+ ),
283
+ );
284
+ }
285
+ await storeTcTokensFromHistorySync(
286
+ data.chats,
287
+ signalRepository,
288
+ keyStore,
289
+ logger,
290
+ );
291
+ if (data.nctSalt?.length) {
292
+ ev.emit("creds.update", { nctSalt: data.nctSalt });
293
+ }
294
+ ev.emit("messaging-history.set", {
295
+ ...data,
296
+ isLatest:
297
+ histNotification.syncType !==
298
+ proto.HistorySync.HistorySyncType.ON_DEMAND
299
+ ? isLatest
300
+ : undefined,
301
+ chunkOrder: histNotification.chunkOrder,
302
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId,
303
+ });
304
+ }
305
+ break;
306
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
307
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
308
+ if (keys?.length) {
309
+ let newAppStateSyncKeyId = "";
310
+ await keyStore.transaction(async () => {
311
+ const newKeys = [];
312
+ for (const { keyData, keyId } of keys) {
313
+ const strKeyId = Buffer.from(keyId.keyId).toString("base64");
314
+ newKeys.push(strKeyId);
315
+ await keyStore.set({
316
+ "app-state-sync-key": { [strKeyId]: keyData },
317
+ });
318
+ newAppStateSyncKeyId = strKeyId;
319
+ }
320
+ logger?.info(
321
+ { newAppStateSyncKeyId, newKeys },
322
+ "injecting new app state sync keys",
323
+ );
324
+ }, meId);
325
+ ev.emit("creds.update", { myAppStateKeyId: newAppStateSyncKeyId });
326
+ } else {
327
+ logger?.info({ protocolMsg }, "recv app state sync with 0 keys");
328
+ }
329
+ break;
330
+ case proto.Message.ProtocolMessage.Type.REVOKE:
331
+ ev.emit("messages.update", [
332
+ {
333
+ key: {
334
+ ...message.key,
335
+ id: protocolMsg.key.id,
336
+ },
337
+ update: {
338
+ message: null,
339
+ messageStubType: WAMessageStubType.REVOKE,
340
+ key: message.key,
341
+ },
342
+ },
343
+ ]);
344
+ break;
345
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
346
+ Object.assign(chat, {
347
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
348
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null,
349
+ });
350
+ break;
351
+ case proto.Message.ProtocolMessage.Type
352
+ .PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
353
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
354
+ if (response) {
355
+ const peerDataOperationResult =
356
+ response.peerDataOperationResult || [];
357
+ for (const result of peerDataOperationResult) {
358
+ const retryResponse = result?.placeholderMessageResendResponse;
359
+ if (!retryResponse?.webMessageInfoBytes) {
360
+ continue;
361
+ }
362
+ try {
363
+ const webMessageInfo = proto.WebMessageInfo.decode(
364
+ retryResponse.webMessageInfoBytes,
365
+ );
366
+ const msgId = webMessageInfo.key?.id;
367
+ const cachedData = msgId
368
+ ? await placeholderResendCache?.get(msgId)
369
+ : undefined;
370
+ if (msgId) {
371
+ await placeholderResendCache?.del(msgId);
372
+ }
373
+ let finalMsg;
374
+ if (cachedData && typeof cachedData === "object") {
375
+ cachedData.message = webMessageInfo.message;
376
+ if (webMessageInfo.messageTimestamp) {
377
+ cachedData.messageTimestamp = webMessageInfo.messageTimestamp;
378
+ }
379
+ finalMsg = cachedData;
380
+ } else {
381
+ finalMsg = webMessageInfo;
382
+ }
383
+ logger?.debug(
384
+ { msgId, requestId: response.stanzaId },
385
+ "received placeholder resend",
386
+ );
387
+ ev.emit("messages.upsert", {
388
+ messages: [normalizeMessageIdentity(finalMsg)],
389
+ type: "notify",
390
+ requestId: response.stanzaId,
391
+ });
392
+ } catch (err) {
393
+ logger?.warn(
394
+ { err, stanzaId: response.stanzaId },
395
+ "failed to decode placeholder resend response",
396
+ );
397
+ }
398
+ }
399
+ }
400
+ break;
401
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
402
+ ev.emit("messages.update", [
403
+ {
404
+ key: { ...message.key, id: protocolMsg.key?.id },
405
+ update: {
406
+ message: {
407
+ editedMessage: {
408
+ message: protocolMsg.editedMessage,
409
+ },
410
+ },
411
+ messageTimestamp: protocolMsg.timestampMs
412
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
413
+ : message.messageTimestamp,
414
+ },
415
+ },
416
+ ]);
417
+ break;
418
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
419
+ const labelAssociationMsg = protocolMsg.memberLabel;
420
+ if (labelAssociationMsg?.label) {
421
+ ev.emit("group.member-tag.update", {
422
+ groupId: chat.id,
423
+ label: labelAssociationMsg.label,
424
+ participant: message.key.participant,
425
+ participantAlt: message.key.participantAlt,
426
+ messageTimestamp: Number(message.messageTimestamp),
427
+ });
428
+ }
429
+ break;
430
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
431
+ const encodedPayload =
432
+ protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
433
+ const { pnToLidMappings, chatDbMigrationTimestamp } =
434
+ proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
435
+ logger?.debug(
436
+ { pnToLidMappings, chatDbMigrationTimestamp },
437
+ "got lid mappings and chat db migration timestamp",
438
+ );
439
+ const pairs = [];
440
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
441
+ const lid = latestLid || assignedLid;
442
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
443
+ }
444
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
445
+ if (pairs.length) {
446
+ for (const { pn, lid } of pairs) {
447
+ await signalRepository.migrateSession(pn, lid);
448
+ }
449
+ }
450
+ }
451
+ } else if (content?.reactionMessage) {
452
+ const reaction = {
453
+ ...content.reactionMessage,
454
+ key: message.key,
455
+ };
456
+ ev.emit("messages.reaction", [
457
+ {
458
+ reaction,
459
+ key: content.reactionMessage?.key,
460
+ },
461
+ ]);
462
+ } else if (content?.encEventResponseMessage) {
463
+ const encEventResponse = content.encEventResponseMessage;
464
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
465
+ const eventMsg = await getMessage(creationMsgKey);
466
+ if (eventMsg) {
467
+ try {
468
+ const meIdNormalised = jidNormalizedUser(meId);
469
+ const eventCreatorKey =
470
+ creationMsgKey.participant || creationMsgKey.remoteJid;
471
+ const eventCreatorPn = isLidUser(eventCreatorKey)
472
+ ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey)
473
+ : eventCreatorKey;
474
+ const eventCreatorJid = getKeyAuthor(
475
+ {
476
+ remoteJid: jidNormalizedUser(eventCreatorPn),
477
+ fromMe: meIdNormalised === eventCreatorPn,
478
+ },
479
+ meIdNormalised,
480
+ );
481
+ const responderJid = getKeyAuthor(message.key, meIdNormalised);
482
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret;
483
+ if (!eventEncKey) {
484
+ logger?.warn(
485
+ { creationMsgKey },
486
+ "event response: missing messageSecret for decryption",
487
+ );
488
+ } else {
489
+ const responseMsg = decryptEventResponse(encEventResponse, {
490
+ eventEncKey,
491
+ eventCreatorJid,
492
+ eventMsgId: creationMsgKey.id,
493
+ responderJid,
494
+ });
495
+ const eventResponse = {
496
+ eventResponseMessageKey: message.key,
497
+ senderTimestampMs: responseMsg.timestampMs,
498
+ response: responseMsg,
499
+ };
500
+ ev.emit("messages.update", [
501
+ {
502
+ key: creationMsgKey,
503
+ update: {
504
+ eventResponses: [eventResponse],
505
+ },
506
+ },
507
+ ]);
508
+ }
509
+ } catch (err) {
510
+ logger?.warn(
511
+ { err, creationMsgKey },
512
+ "failed to decrypt event response",
513
+ );
514
+ }
515
+ } else {
516
+ logger?.warn(
517
+ { creationMsgKey },
518
+ "event creation message not found, cannot decrypt response",
519
+ );
520
+ }
521
+ } else if (message.messageStubType) {
522
+ const jid = message.key?.remoteJid;
523
+ let participants;
524
+ const emitParticipantsUpdate = (action) =>
525
+ ev.emit("group-participants.update", {
526
+ id: jid,
527
+ author: message.key.participant,
528
+ authorPn: message.key.participantAlt,
529
+ participants: participants,
530
+ action: action,
531
+ });
532
+ const emitGroupUpdate = (update) => {
533
+ ev.emit("groups.update", [
534
+ {
535
+ id: jid,
536
+ ...update,
537
+ author: message.key.participant ?? undefined,
538
+ authorPn: message.key.participantAlt,
539
+ },
540
+ ]);
541
+ };
542
+ const participantsIncludesMe = () =>
543
+ participants.find((jid) =>
544
+ areJidsSameUser(meId, jid.phoneNumber || jid.lid),
545
+ );
546
+ switch (message.messageStubType) {
547
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
548
+ participants =
549
+ message.messageStubParameters.map((a) => JSON.parse(a)) || [];
550
+ emitParticipantsUpdate("modify");
551
+ break;
552
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
553
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
554
+ participants =
555
+ message.messageStubParameters.map((a) => JSON.parse(a)) || [];
556
+ emitParticipantsUpdate("remove");
557
+ if (participantsIncludesMe()) {
558
+ chat.readOnly = true;
559
+ }
560
+ break;
561
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
562
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
563
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
564
+ participants =
565
+ message.messageStubParameters.map((a) => JSON.parse(a)) || [];
566
+ if (participantsIncludesMe()) {
567
+ chat.readOnly = false;
568
+ }
569
+ emitParticipantsUpdate("add");
570
+ break;
571
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
572
+ participants =
573
+ message.messageStubParameters.map((a) => JSON.parse(a)) || [];
574
+ emitParticipantsUpdate("demote");
575
+ break;
576
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
577
+ participants =
578
+ message.messageStubParameters.map((a) => JSON.parse(a)) || [];
579
+ emitParticipantsUpdate("promote");
580
+ break;
581
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
582
+ const announceValue = message.messageStubParameters?.[0];
583
+ emitGroupUpdate({
584
+ announce: announceValue === "true" || announceValue === "on",
585
+ });
586
+ break;
587
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
588
+ const restrictValue = message.messageStubParameters?.[0];
589
+ emitGroupUpdate({
590
+ restrict: restrictValue === "true" || restrictValue === "on",
591
+ });
592
+ break;
593
+ }
594
+ }
595
+ return { chat };
596
+ };
597
+ /**
598
+ * Get the ID of the chat from the given key.
599
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
600
+ * (مضافة من الرسمية: التعامل الصحيح مع الـ broadcast lists بدل remoteJid فقط)
601
+ */
602
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
603
+ if (!remoteJid) {
604
+ throw new Boom("Cannot derive chat id: message key is missing remoteJid", {
605
+ data: { remoteJid, participant, fromMe },
606
+ });
607
+ }
608
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
609
+ if (!participant) {
610
+ throw new Boom(
611
+ "Cannot derive chat id: broadcast message key is missing participant",
612
+ { data: { remoteJid, fromMe } },
613
+ );
614
+ }
615
+ return participant;
616
+ }
617
+ return remoteJid;
618
+ };
619
+
620
+ /**
621
+ * Decrypt a poll vote (مضافة من الرسمية: جينتوكي كان بيطبّع مفتاح رسالة التصويت
622
+ * بس مكنش بيفك تشفيره فعليًا)
623
+ * @param vote encrypted vote
624
+ * @param ctx additional info about the poll required for decryption
625
+ * @returns list of SHA256 options
626
+ */
627
+ export function decryptPollVote(
628
+ { encPayload, encIv },
629
+ { pollCreatorJid, pollMsgId, pollEncKey, voterJid },
630
+ ) {
631
+ const sign = Buffer.concat([
632
+ toBinary(pollMsgId),
633
+ toBinary(pollCreatorJid),
634
+ toBinary(voterJid),
635
+ toBinary("Poll Vote"),
636
+ new Uint8Array([1]),
637
+ ]);
638
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), "sha256");
639
+ const decKey = hmacSign(sign, key0, "sha256");
640
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
641
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
642
+ return proto.Message.PollVoteMessage.decode(decrypted);
643
+ function toBinary(txt) {
644
+ return Buffer.from(txt);
645
+ }
646
+ }
647
+
648
+ export { processMessage };