plogme 1.0.0

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 (154) hide show
  1. package/LICENSE +61 -0
  2. package/README.md +212 -0
  3. package/WAProto/V +1 -0
  4. package/WAProto/WAProto.proto +8051 -0
  5. package/WAProto/index.js +289292 -0
  6. package/engine-requirements.js +51 -0
  7. package/lib/Defaults/ban-checker.js +44 -0
  8. package/lib/Defaults/index.js +158 -0
  9. package/lib/Signal/Group/ciphertext-message.js +11 -0
  10. package/lib/Signal/Group/group-session-builder.js +29 -0
  11. package/lib/Signal/Group/group_cipher.js +81 -0
  12. package/lib/Signal/Group/index.js +11 -0
  13. package/lib/Signal/Group/keyhelper.js +17 -0
  14. package/lib/Signal/Group/sender-chain-key.js +25 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  16. package/lib/Signal/Group/sender-key-message.js +65 -0
  17. package/lib/Signal/Group/sender-key-name.js +47 -0
  18. package/lib/Signal/Group/sender-key-record.js +40 -0
  19. package/lib/Signal/Group/sender-key-state.js +83 -0
  20. package/lib/Signal/Group/sender-message-key.js +25 -0
  21. package/lib/Signal/libsignal.js +428 -0
  22. package/lib/Signal/lid-mapping.js +280 -0
  23. package/lib/Socket/Client/index.js +2 -0
  24. package/lib/Socket/Client/types.js +10 -0
  25. package/lib/Socket/Client/websocket.js +53 -0
  26. package/lib/Socket/aigroups.js +315 -0
  27. package/lib/Socket/ban-checker.js +153 -0
  28. package/lib/Socket/business.js +407 -0
  29. package/lib/Socket/chats.js +1831 -0
  30. package/lib/Socket/chats.js[old] +1227 -0
  31. package/lib/Socket/communities.js +431 -0
  32. package/lib/Socket/graphql.js +899 -0
  33. package/lib/Socket/groups.js +549 -0
  34. package/lib/Socket/groups.js[old] +347 -0
  35. package/lib/Socket/index.js +71 -0
  36. package/lib/Socket/interactive-handler.js +600 -0
  37. package/lib/Socket/interop.js +563 -0
  38. package/lib/Socket/managed-account.js +208 -0
  39. package/lib/Socket/messages-recv.js +2144 -0
  40. package/lib/Socket/messages-send.js +2650 -0
  41. package/lib/Socket/messages-send.js[latest working] +1759 -0
  42. package/lib/Socket/mex.js +41 -0
  43. package/lib/Socket/newsletter.js +226 -0
  44. package/lib/Socket/privacy.js +446 -0
  45. package/lib/Socket/registration.js +428 -0
  46. package/lib/Socket/socket.js +1050 -0
  47. package/lib/Socket/username.js +229 -0
  48. package/lib/Store/index.js +4 -0
  49. package/lib/Store/make-cache-manager-store.js +89 -0
  50. package/lib/Store/make-in-memory-store.js +420 -0
  51. package/lib/Store/make-ordered-dictionary.js +78 -0
  52. package/lib/Store/object-repository.js +23 -0
  53. package/lib/Types/Auth.js +1 -0
  54. package/lib/Types/Bussines.js +1 -0
  55. package/lib/Types/Call.js +1 -0
  56. package/lib/Types/Chat.js +7 -0
  57. package/lib/Types/Contact.js +1 -0
  58. package/lib/Types/Events.js +1 -0
  59. package/lib/Types/GroupMetadata.js +1 -0
  60. package/lib/Types/Label.js +24 -0
  61. package/lib/Types/LabelAssociation.js +6 -0
  62. package/lib/Types/Message.js +17 -0
  63. package/lib/Types/Mex.js +39 -0
  64. package/lib/Types/Product.js +1 -0
  65. package/lib/Types/RichType.js +22 -0
  66. package/lib/Types/Signal.js +1 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +48 -0
  69. package/lib/Types/USync.js +1 -0
  70. package/lib/Types/index.js +25 -0
  71. package/lib/Utils/auth-utils.js +301 -0
  72. package/lib/Utils/bot-planning-replay.js +169 -0
  73. package/lib/Utils/browser-utils.js +28 -0
  74. package/lib/Utils/business.js +230 -0
  75. package/lib/Utils/channel-policy.js +1 -0
  76. package/lib/Utils/chat-utils.js +885 -0
  77. package/lib/Utils/chat-utils.js[old] +871 -0
  78. package/lib/Utils/companion-reg-client-utils.js +32 -0
  79. package/lib/Utils/consumer-application.js +102 -0
  80. package/lib/Utils/crypto.js +117 -0
  81. package/lib/Utils/decode-wa-message.js +484 -0
  82. package/lib/Utils/event-buffer.js +589 -0
  83. package/lib/Utils/games/slot-machine.js +258 -0
  84. package/lib/Utils/games/website-preview.js +293 -0
  85. package/lib/Utils/generics.js +390 -0
  86. package/lib/Utils/generics.js@old +385 -0
  87. package/lib/Utils/group-history.js +56 -0
  88. package/lib/Utils/history.js +130 -0
  89. package/lib/Utils/identity-change-handler.js +48 -0
  90. package/lib/Utils/index.js +35 -0
  91. package/lib/Utils/integrity.js +296 -0
  92. package/lib/Utils/jid-display-normalization.js +209 -0
  93. package/lib/Utils/link-preview.js +84 -0
  94. package/lib/Utils/logger.js +2 -0
  95. package/lib/Utils/lt-hash.js +7 -0
  96. package/lib/Utils/make-mutex.js +32 -0
  97. package/lib/Utils/message-composer.js +467 -0
  98. package/lib/Utils/message-inspect.js +67 -0
  99. package/lib/Utils/message-retry-manager.js +241 -0
  100. package/lib/Utils/messages-media.js +1006 -0
  101. package/lib/Utils/messages-media.js[old] +916 -0
  102. package/lib/Utils/messages.js +1982 -0
  103. package/lib/Utils/messages.js[old] +1902 -0
  104. package/lib/Utils/meta-ai-msmsg.js +130 -0
  105. package/lib/Utils/meta-compositing.js +202 -0
  106. package/lib/Utils/native-flow.js +100 -0
  107. package/lib/Utils/noise-handler.js +200 -0
  108. package/lib/Utils/offline-node-processor.js +39 -0
  109. package/lib/Utils/pre-key-manager.js +105 -0
  110. package/lib/Utils/process-message.js +582 -0
  111. package/lib/Utils/reporting-utils.js +257 -0
  112. package/lib/Utils/rich-message-utils.js +942 -0
  113. package/lib/Utils/rich-message-utils.js[Old] +387 -0
  114. package/lib/Utils/signal.js +200 -0
  115. package/lib/Utils/stanza-ack.js +37 -0
  116. package/lib/Utils/sync-action-utils.js +47 -0
  117. package/lib/Utils/tc-token-utils.js +162 -0
  118. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  119. package/lib/Utils/use-single-file-auth-state.js +96 -0
  120. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  121. package/lib/Utils/validate-connection.js +206 -0
  122. package/lib/Utils/view-once-utils.js +206 -0
  123. package/lib/Utils/voip-rekey.js +20 -0
  124. package/lib/Utils/welcome-flow.js +220 -0
  125. package/lib/WABinary/constants.js +1463 -0
  126. package/lib/WABinary/decode.js +261 -0
  127. package/lib/WABinary/encode.js +219 -0
  128. package/lib/WABinary/generic-utils.js +227 -0
  129. package/lib/WABinary/index.js +5 -0
  130. package/lib/WABinary/jid-utils.js +95 -0
  131. package/lib/WABinary/types.js +1 -0
  132. package/lib/WAM/BinaryInfo.js +9 -0
  133. package/lib/WAM/constants.js +22852 -0
  134. package/lib/WAM/encode.js +149 -0
  135. package/lib/WAM/index.js +3 -0
  136. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  137. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  138. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  139. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  140. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  141. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  142. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  143. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  144. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  145. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  146. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  147. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  148. package/lib/WAUSync/Protocols/index.js +12 -0
  149. package/lib/WAUSync/USyncQuery.js +201 -0
  150. package/lib/WAUSync/USyncUser.js +54 -0
  151. package/lib/WAUSync/index.js +3 -0
  152. package/lib/index.d.ts +406 -0
  153. package/lib/index.js +11 -0
  154. package/package.json +125 -0
@@ -0,0 +1,105 @@
1
+ import PQueue from 'p-queue';
2
+ /**
3
+ * Manages pre-key operations with proper concurrency control
4
+ */
5
+ export class PreKeyManager {
6
+ constructor(store, logger) {
7
+ this.store = store;
8
+ this.logger = logger;
9
+ this.queues = new Map();
10
+ }
11
+ /**
12
+ * Get or create a queue for a specific key type
13
+ */
14
+ getQueue(keyType) {
15
+ if (!this.queues.has(keyType)) {
16
+ this.queues.set(keyType, new PQueue({ concurrency: 1 }));
17
+ }
18
+ return this.queues.get(keyType);
19
+ }
20
+ /**
21
+ * Process pre-key operations (updates and deletions)
22
+ */
23
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
24
+ const keyData = data[keyType];
25
+ if (!keyData)
26
+ return;
27
+ return this.getQueue(keyType).add(async () => {
28
+ // Ensure structures exist
29
+ transactionCache[keyType] = transactionCache[keyType] || {};
30
+ mutations[keyType] = mutations[keyType] || {};
31
+ // Separate deletions from updates
32
+ const deletions = [];
33
+ const updates = {};
34
+ for (const keyId in keyData) {
35
+ if (keyData[keyId] === null) {
36
+ deletions.push(keyId);
37
+ }
38
+ else {
39
+ updates[keyId] = keyData[keyId];
40
+ }
41
+ }
42
+ // Process updates (no validation needed)
43
+ if (Object.keys(updates).length > 0) {
44
+ Object.assign(transactionCache[keyType], updates);
45
+ Object.assign(mutations[keyType], updates);
46
+ }
47
+ // Process deletions with validation
48
+ if (deletions.length > 0) {
49
+ await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction);
50
+ }
51
+ });
52
+ }
53
+ /**
54
+ * Process deletions with validation
55
+ */
56
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
57
+ if (isInTransaction) {
58
+ // In transaction, only allow deletion if key exists in cache
59
+ for (const keyId of ids) {
60
+ if (transactionCache[keyType]?.[keyId]) {
61
+ transactionCache[keyType][keyId] = null;
62
+ mutations[keyType][keyId] = null;
63
+ }
64
+ else {
65
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`);
66
+ }
67
+ }
68
+ }
69
+ else {
70
+ // Outside transaction, validate against store
71
+ const existingKeys = await this.store.get(keyType, ids);
72
+ for (const keyId of ids) {
73
+ if (existingKeys[keyId]) {
74
+ transactionCache[keyType][keyId] = null;
75
+ mutations[keyType][keyId] = null;
76
+ }
77
+ else {
78
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ /**
84
+ * Validate and process pre-key deletions outside transactions
85
+ */
86
+ async validateDeletions(data, keyType) {
87
+ const keyData = data[keyType];
88
+ if (!keyData)
89
+ return;
90
+ return this.getQueue(keyType).add(async () => {
91
+ // Find all deletion requests
92
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null);
93
+ if (deletionIds.length === 0)
94
+ return;
95
+ // Validate deletions
96
+ const existingKeys = await this.store.get(keyType, deletionIds);
97
+ for (const keyId of deletionIds) {
98
+ if (!existingKeys[keyId]) {
99
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
100
+ delete data[keyType][keyId];
101
+ }
102
+ }
103
+ });
104
+ }
105
+ }
@@ -0,0 +1,582 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { WAMessageStubType } from '../Types/index.js';
3
+ import { getContentType, normalizeMessageContent } from '../Utils/messages.js';
4
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidStatusBroadcast, isLidUser, jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
5
+ import { aesDecryptGCM, hmacSign, sha256 } from './crypto.js';
6
+ import { getKeyAuthor, toNumber } from './generics.js';
7
+ import { downloadAndProcessHistorySyncNotification } from './history.js';
8
+ const REAL_MSG_STUB_TYPES = new Set([
9
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
10
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
11
+ WAMessageStubType.CALL_MISSED_VIDEO,
12
+ WAMessageStubType.CALL_MISSED_VOICE
13
+ ]);
14
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
15
+ /** Cleans a received message to further processing */
16
+ export const cleanMessage = (message, meId, meLid) => {
17
+ // ensure remoteJid and participant doesn't have device or agent in it
18
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
19
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
20
+ }
21
+ else {
22
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
23
+ }
24
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
25
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid');
26
+ }
27
+ else {
28
+ message.key.participant = jidNormalizedUser(message.key.participant);
29
+ }
30
+ const content = normalizeMessageContent(message.message);
31
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
32
+ if (content?.reactionMessage) {
33
+ normaliseKey(content.reactionMessage.key);
34
+ }
35
+ if (content?.pollUpdateMessage) {
36
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
37
+ }
38
+ function normaliseKey(msgKey) {
39
+ // if the reaction is from another user
40
+ // we've to correctly map the key to this user's perspective
41
+ if (!message.key.fromMe) {
42
+ // if the sender believed the message being reacted to is not from them
43
+ // we've to correct the key to be from them, or some other participant
44
+ msgKey.fromMe = !msgKey.fromMe
45
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
46
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
47
+ : // if the message being reacted to, was from them
48
+ // fromMe automatically becomes false
49
+ false;
50
+ // set the remoteJid to being the same as the chat the message came from
51
+ // TODO: investigate inconsistencies
52
+ msgKey.remoteJid = message.key.remoteJid;
53
+ // set participant of the message
54
+ msgKey.participant = msgKey.participant || message.key.participant;
55
+ }
56
+ }
57
+ };
58
+ // TODO: target:audit AUDIT THIS FUNCTION AGAIN
59
+ export const isRealMessage = (message) => {
60
+ const normalizedContent = normalizeMessageContent(message.message);
61
+ const hasSomeContent = !!getContentType(normalizedContent);
62
+ return ((!!normalizedContent ||
63
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
64
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
65
+ hasSomeContent &&
66
+ !normalizedContent?.protocolMessage &&
67
+ !normalizedContent?.reactionMessage &&
68
+ !normalizedContent?.pollUpdateMessage);
69
+ };
70
+ export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
71
+ /**
72
+ * Get the ID of the chat from the given key.
73
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
74
+ */
75
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
76
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
77
+ return participant;
78
+ }
79
+ return remoteJid;
80
+ };
81
+ /**
82
+ * Decrypt a poll vote
83
+ * @param vote encrypted vote
84
+ * @param ctx additional info about the poll required for decryption
85
+ * @returns list of SHA256 options
86
+ */
87
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
88
+ const sign = Buffer.concat([
89
+ toBinary(pollMsgId),
90
+ toBinary(pollCreatorJid),
91
+ toBinary(voterJid),
92
+ toBinary('Poll Vote'),
93
+ new Uint8Array([1])
94
+ ]);
95
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
96
+ const decKey = hmacSign(sign, key0, 'sha256');
97
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
98
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
99
+ return proto.Message.PollVoteMessage.decode(decrypted);
100
+ function toBinary(txt) {
101
+ return Buffer.from(txt);
102
+ }
103
+ }
104
+ /**
105
+ * Decrypt an event response
106
+ * @param response encrypted event response
107
+ * @param ctx additional info about the event required for decryption
108
+ * @returns event response message
109
+ */
110
+ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
111
+ const sign = Buffer.concat([
112
+ toBinary(eventMsgId),
113
+ toBinary(eventCreatorJid),
114
+ toBinary(responderJid),
115
+ toBinary('Event Response'),
116
+ new Uint8Array([1])
117
+ ]);
118
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256');
119
+ const decKey = hmacSign(sign, key0, 'sha256');
120
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`);
121
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
122
+ return proto.Message.EventResponseMessage.decode(decrypted);
123
+ function toBinary(txt) {
124
+ return Buffer.from(txt);
125
+ }
126
+ }
127
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
128
+ const meId = creds.me.id;
129
+ const { accountSettings } = creds;
130
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
131
+ const isRealMsg = isRealMessage(message);
132
+ if (isRealMsg) {
133
+ chat.messages = [{ message }];
134
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
135
+ // only increment unread count if not CIPHERTEXT and from another person
136
+ if (shouldIncrementChatUnread(message)) {
137
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
138
+ }
139
+ }
140
+ const content = normalizeMessageContent(message.message);
141
+ // unarchive chat if it's a real message, or someone reacted to our message
142
+ // and we've the unarchive chats setting on
143
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
144
+ chat.archived = false;
145
+ chat.readOnly = false;
146
+ }
147
+ const protocolMsg = content?.protocolMessage;
148
+ if (protocolMsg) {
149
+ switch (protocolMsg.type) {
150
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
151
+ const histNotification = protocolMsg.historySyncNotification;
152
+ const process = shouldProcessHistoryMsg;
153
+ const isLatest = !creds.processedHistoryMessages?.length;
154
+ logger?.info({
155
+ histNotification,
156
+ process,
157
+ id: message.key.id,
158
+ isLatest
159
+ }, 'got history notification');
160
+ if (process) {
161
+ // TODO: investigate
162
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
163
+ ev.emit('creds.update', {
164
+ processedHistoryMessages: [
165
+ ...(creds.processedHistoryMessages || []),
166
+ { key: message.key, messageTimestamp: message.messageTimestamp }
167
+ ]
168
+ });
169
+ }
170
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger);
171
+ if (data.lidPnMappings?.length) {
172
+ logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync');
173
+ await signalRepository.lidMapping
174
+ .storeLIDPNMappings(data.lidPnMappings)
175
+ .catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'));
176
+ }
177
+ ev.emit('messaging-history.set', {
178
+ ...data,
179
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
180
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
181
+ });
182
+ }
183
+ break;
184
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
185
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
186
+ if (keys?.length) {
187
+ let newAppStateSyncKeyId = '';
188
+ await keyStore.transaction(async () => {
189
+ const newKeys = [];
190
+ for (const { keyData, keyId } of keys) {
191
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
192
+ newKeys.push(strKeyId);
193
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
194
+ newAppStateSyncKeyId = strKeyId;
195
+ }
196
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
197
+ }, meId);
198
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
199
+ }
200
+ else {
201
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
202
+ }
203
+ break;
204
+ case proto.Message.ProtocolMessage.Type.REVOKE:
205
+ ev.emit('messages.update', [
206
+ {
207
+ key: {
208
+ ...message.key,
209
+ id: protocolMsg.key.id
210
+ },
211
+ update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
212
+ }
213
+ ]);
214
+ break;
215
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
216
+ Object.assign(chat, {
217
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
218
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
219
+ });
220
+ break;
221
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
222
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
223
+ if (response) {
224
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
225
+ const peerDataOperationResult = response.peerDataOperationResult || [];
226
+ for (const result of peerDataOperationResult) {
227
+ const retryResponse = result?.placeholderMessageResendResponse;
228
+ //eslint-disable-next-line max-depth
229
+ if (!retryResponse?.webMessageInfoBytes) {
230
+ continue;
231
+ }
232
+ //eslint-disable-next-line max-depth
233
+ try {
234
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
235
+ const msgId = webMessageInfo.key?.id;
236
+ // Retrieve cached original message data (preserves LID details,
237
+ // timestamps, etc. that the phone may omit in its PDO response)
238
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined;
239
+ //eslint-disable-next-line max-depth
240
+ if (msgId) {
241
+ await placeholderResendCache?.del(msgId);
242
+ }
243
+ let finalMsg;
244
+ //eslint-disable-next-line max-depth
245
+ if (cachedData && typeof cachedData === 'object') {
246
+ // Apply decoded message content onto cached metadata (preserves LID etc.)
247
+ cachedData.message = webMessageInfo.message;
248
+ //eslint-disable-next-line max-depth
249
+ if (webMessageInfo.messageTimestamp) {
250
+ cachedData.messageTimestamp = webMessageInfo.messageTimestamp;
251
+ }
252
+ finalMsg = cachedData;
253
+ }
254
+ else {
255
+ finalMsg = webMessageInfo;
256
+ }
257
+ logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend');
258
+ ev.emit('messages.upsert', {
259
+ messages: [finalMsg],
260
+ type: 'notify',
261
+ requestId: response.stanzaId
262
+ });
263
+ }
264
+ catch (err) {
265
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response');
266
+ }
267
+ }
268
+ }
269
+ break;
270
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
271
+ ev.emit('messages.update', [
272
+ {
273
+ // flip the sender / fromMe properties because they're in the perspective of the sender
274
+ key: { ...message.key, id: protocolMsg.key?.id },
275
+ update: {
276
+ message: {
277
+ editedMessage: {
278
+ message: protocolMsg.editedMessage
279
+ }
280
+ },
281
+ messageTimestamp: protocolMsg.timestampMs
282
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
283
+ : message.messageTimestamp
284
+ }
285
+ }
286
+ ]);
287
+ break;
288
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
289
+ const labelAssociationMsg = protocolMsg.memberLabel;
290
+ if (labelAssociationMsg?.label) {
291
+ ev.emit('group.member-tag.update', {
292
+ groupId: chat.id,
293
+ label: labelAssociationMsg.label,
294
+ participant: message.key.participant,
295
+ participantAlt: message.key.participantAlt,
296
+ messageTimestamp: Number(message.messageTimestamp)
297
+ });
298
+ }
299
+ break;
300
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
301
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
302
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
303
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
304
+ const pairs = [];
305
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
306
+ const lid = latestLid || assignedLid;
307
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
308
+ }
309
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
310
+ if (pairs.length) {
311
+ for (const { pn, lid } of pairs) {
312
+ await signalRepository.migrateSession(pn, lid);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ else if (content?.reactionMessage) {
318
+ const reaction = {
319
+ ...content.reactionMessage,
320
+ key: message.key
321
+ };
322
+ ev.emit('messages.reaction', [
323
+ {
324
+ reaction,
325
+ key: content.reactionMessage?.key
326
+ }
327
+ ]);
328
+ }
329
+ else if (content?.encEventResponseMessage) {
330
+ const encEventResponse = content.encEventResponseMessage;
331
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
332
+ // we need to fetch the event creation message to get the event enc key
333
+ const eventMsg = getMessage ? await getMessage(creationMsgKey) : undefined;
334
+ if (eventMsg) {
335
+ try {
336
+ const meIdNormalised = jidNormalizedUser(meId);
337
+ // all jids need to be PN
338
+ const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid;
339
+ const eventCreatorPn = isLidUser(eventCreatorKey)
340
+ ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey)
341
+ : eventCreatorKey;
342
+ const eventCreatorJid = getKeyAuthor({ remoteJid: jidNormalizedUser(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised);
343
+ const responderJid = getKeyAuthor(message.key, meIdNormalised);
344
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret;
345
+ if (!eventEncKey) {
346
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption');
347
+ }
348
+ else {
349
+ const responseMsg = decryptEventResponse(encEventResponse, {
350
+ eventEncKey,
351
+ eventCreatorJid,
352
+ eventMsgId: creationMsgKey.id,
353
+ responderJid
354
+ });
355
+ const eventResponse = {
356
+ eventResponseMessageKey: message.key,
357
+ senderTimestampMs: responseMsg.timestampMs,
358
+ response: responseMsg
359
+ };
360
+ ev.emit('messages.update', [
361
+ {
362
+ key: creationMsgKey,
363
+ update: {
364
+ eventResponses: [eventResponse]
365
+ }
366
+ }
367
+ ]);
368
+ }
369
+ }
370
+ catch (err) {
371
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response');
372
+ }
373
+ }
374
+ else {
375
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response');
376
+ }
377
+ }
378
+ else if (message.messageStubType) {
379
+ const jid = message.key?.remoteJid;
380
+ //let actor = whatsappID (message.participant)
381
+ let participants;
382
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', {
383
+ id: jid,
384
+ author: message.key.participant,
385
+ authorPn: message.key.participantAlt,
386
+ participants,
387
+ action
388
+ });
389
+ const emitGroupUpdate = (update) => {
390
+ ev.emit('groups.update', [
391
+ { id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt }
392
+ ]);
393
+ };
394
+ const emitGroupRequestJoin = (participant, action, method) => {
395
+ ev.emit('group.join-request', {
396
+ id: jid,
397
+ author: message.key.participant,
398
+ authorPn: message.key.participantAlt,
399
+ participant: participant.lid,
400
+ participantPn: participant.pn,
401
+ action,
402
+ method: method
403
+ });
404
+ };
405
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)); // ADD SUPPORT FOR LID
406
+ switch (message.messageStubType) {
407
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
408
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
409
+ emitParticipantsUpdate('modify');
410
+ break;
411
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
412
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
413
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
414
+ emitParticipantsUpdate('remove');
415
+ // mark the chat read only if you left the group
416
+ if (participantsIncludesMe()) {
417
+ chat.readOnly = true;
418
+ }
419
+ break;
420
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
421
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
422
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
423
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
424
+ if (participantsIncludesMe()) {
425
+ chat.readOnly = false;
426
+ }
427
+ emitParticipantsUpdate('add');
428
+ break;
429
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
430
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
431
+ emitParticipantsUpdate('demote');
432
+ break;
433
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
434
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
435
+ emitParticipantsUpdate('promote');
436
+ break;
437
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
438
+ const announceValue = message.messageStubParameters?.[0];
439
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
440
+ break;
441
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
442
+ const restrictValue = message.messageStubParameters?.[0];
443
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
444
+ break;
445
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
446
+ const name = message.messageStubParameters?.[0];
447
+ chat.name = name;
448
+ emitGroupUpdate({ subject: name });
449
+ break;
450
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
451
+ const description = message.messageStubParameters?.[0];
452
+ chat.description = description;
453
+ emitGroupUpdate({ desc: description });
454
+ break;
455
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
456
+ const code = message.messageStubParameters?.[0];
457
+ emitGroupUpdate({ inviteCode: code });
458
+ break;
459
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
460
+ const memberAddValue = message.messageStubParameters?.[0];
461
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
462
+ break;
463
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
464
+ const approvalMode = message.messageStubParameters?.[0];
465
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
466
+ break;
467
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: // TODO: Add other events
468
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
469
+ const action = message.messageStubParameters?.[1];
470
+ const method = message.messageStubParameters?.[2];
471
+ emitGroupRequestJoin(participant, action, method);
472
+ break;
473
+ }
474
+ }
475
+ else if (content?.pollUpdateMessage) {
476
+ const pollUpdate = content.pollUpdateMessage;
477
+ const creationMsgKey = pollUpdate.pollCreationMessageKey;
478
+ const pollMsg = getMessage ? await getMessage(creationMsgKey) : undefined;
479
+ if (!pollMsg) {
480
+ logger?.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
481
+ }
482
+ else if (!pollUpdate.vote || !creationMsgKey?.id) {
483
+ logger?.warn({ creationMsgKey }, 'poll update is missing encrypted vote data or creation id');
484
+ }
485
+ else {
486
+ const pollContent = normalizeMessageContent(pollMsg.message);
487
+ const pollCreation = pollContent?.pollCreationMessage ||
488
+ pollContent?.pollCreationMessageV2 ||
489
+ pollContent?.pollCreationMessageV3 ||
490
+ pollContent?.pollCreationMessageV4 ||
491
+ pollContent?.pollCreationMessageV5 ||
492
+ pollContent?.pollCreationMessageV6;
493
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret || pollContent?.messageContextInfo?.messageSecret;
494
+ if (!pollEncKey) {
495
+ logger?.warn({ creationMsgKey }, 'poll vote: missing messageSecret for decryption');
496
+ }
497
+ else {
498
+ const meIdNormalized = jidNormalizedUser(meId);
499
+ const meLidNormalized = creds.me?.lid ? jidNormalizedUser(creds.me.lid) : undefined;
500
+ const creatorKeyJid = creationMsgKey.participant || creationMsgKey.remoteJid;
501
+ const creatorPn = creatorKeyJid && isLidUser(creatorKeyJid)
502
+ ? await signalRepository.lidMapping.getPNForLID(creatorKeyJid).catch(() => undefined)
503
+ : creatorKeyJid;
504
+ const creatorCandidates = [...new Set([
505
+ creationMsgKey.fromMe && meLidNormalized,
506
+ creatorKeyJid && isLidUser(creatorKeyJid) && creatorKeyJid,
507
+ creatorPn && jidNormalizedUser(creatorPn),
508
+ getKeyAuthor(creationMsgKey, meIdNormalized)
509
+ ].filter(Boolean).map(jidNormalizedUser))];
510
+ const voterCandidates = [...new Set([
511
+ message.key.participant,
512
+ message.key.participantAlt,
513
+ message.key.remoteJid,
514
+ getKeyAuthor(message.key, meIdNormalized)
515
+ ].filter(Boolean).map(jidNormalizedUser))];
516
+ let voteMsg;
517
+ let resolvedCreatorJid;
518
+ let resolvedVoterJid;
519
+ for (const pollCreatorJid of creatorCandidates) {
520
+ for (const voterJid of voterCandidates) {
521
+ try {
522
+ voteMsg = decryptPollVote(pollUpdate.vote, {
523
+ pollEncKey,
524
+ pollCreatorJid,
525
+ pollMsgId: creationMsgKey.id,
526
+ voterJid
527
+ });
528
+ resolvedCreatorJid = pollCreatorJid;
529
+ resolvedVoterJid = voterJid;
530
+ break;
531
+ }
532
+ catch {
533
+ // WhatsApp currently mixes LID and PN identities in poll crypto.
534
+ }
535
+ }
536
+ if (voteMsg) {
537
+ break;
538
+ }
539
+ }
540
+ if (!voteMsg) {
541
+ logger?.warn({ creationMsgKey, creatorCandidates, voterCandidates }, 'failed to decrypt poll vote with available LID/PN identities');
542
+ }
543
+ else {
544
+ const options = pollCreation?.options || [];
545
+ const optionByHash = new Map(options.map(option => [
546
+ sha256(Buffer.from(option.optionName || '')).toString(),
547
+ option.optionName || ''
548
+ ]));
549
+ const selectedHashes = (voteMsg.selectedOptions || []).map(option => option.toString());
550
+ const selectedOptions = selectedHashes.map(hash => optionByHash.get(hash) || 'Unknown');
551
+ const unselectedOptions = options
552
+ .map(option => option.optionName || '')
553
+ .filter(optionName => !selectedOptions.includes(optionName));
554
+ const pollVote = {
555
+ pollUpdateMessageKey: message.key,
556
+ pollCreationMessageKey: creationMsgKey,
557
+ vote: voteMsg,
558
+ voterJid: resolvedVoterJid,
559
+ pollCreatorJid: resolvedCreatorJid,
560
+ selectedOptions,
561
+ selectedOptionHashes: selectedHashes,
562
+ unselectedOptions,
563
+ senderTimestampMs: pollUpdate.senderTimestampMs ? toNumber(pollUpdate.senderTimestampMs) : undefined
564
+ };
565
+ ev.emit('messages.update', [
566
+ {
567
+ key: creationMsgKey,
568
+ update: {
569
+ pollUpdates: [pollVote]
570
+ }
571
+ }
572
+ ]);
573
+ ev.emit('poll.vote', pollVote);
574
+ }
575
+ }
576
+ }
577
+ }
578
+ if (Object.keys(chat).length > 1) {
579
+ ev.emit('chats.update', [chat]);
580
+ }
581
+ };
582
+ export default processMessage;