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