@xbibzlibrary/whatsbibz 1.3.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 (260) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +22 -0
  3. package/LICENSE.upstream +21 -0
  4. package/README.md +280 -0
  5. package/VERIFIKASI-IDENTITAS-2026-09-03.md +138 -0
  6. package/WAProto/GenerateStatics.sh +3 -0
  7. package/WAProto/WAProto.proto +6035 -0
  8. package/WAProto/fix-imports.js +81 -0
  9. package/WAProto/index.d.ts +15314 -0
  10. package/WAProto/index.js +132326 -0
  11. package/assets/logo/README.md +21 -0
  12. package/assets/logo/png/banner-1200x360.png +0 -0
  13. package/assets/logo/png/icon-1024.png +0 -0
  14. package/assets/logo/png/icon-128.png +0 -0
  15. package/assets/logo/png/icon-16.png +0 -0
  16. package/assets/logo/png/icon-24.png +0 -0
  17. package/assets/logo/png/icon-256.png +0 -0
  18. package/assets/logo/png/icon-32.png +0 -0
  19. package/assets/logo/png/icon-48.png +0 -0
  20. package/assets/logo/png/icon-512.png +0 -0
  21. package/assets/logo/png/icon-64.png +0 -0
  22. package/assets/logo/png/mark-512.png +0 -0
  23. package/assets/logo/preview.png +0 -0
  24. package/assets/logo/whatsbibz.ico +0 -0
  25. package/lib/BibzWhats/client.d.ts +95 -0
  26. package/lib/BibzWhats/client.js +501 -0
  27. package/lib/BibzWhats/device-identity.d.ts +60 -0
  28. package/lib/BibzWhats/device-identity.js +234 -0
  29. package/lib/BibzWhats/extract.d.ts +29 -0
  30. package/lib/BibzWhats/extract.js +115 -0
  31. package/lib/BibzWhats/index.d.ts +7 -0
  32. package/lib/BibzWhats/index.js +8 -0
  33. package/lib/BibzWhats/jid.d.ts +22 -0
  34. package/lib/BibzWhats/jid.js +98 -0
  35. package/lib/BibzWhats/pairing.d.ts +35 -0
  36. package/lib/BibzWhats/pairing.js +186 -0
  37. package/lib/BibzWhats/send.d.ts +9 -0
  38. package/lib/BibzWhats/send.js +107 -0
  39. package/lib/BibzWhats/version.d.ts +6 -0
  40. package/lib/BibzWhats/version.js +7 -0
  41. package/lib/Defaults/index.d.ts +73 -0
  42. package/lib/Defaults/index.js +141 -0
  43. package/lib/Modded/message_builder.d.ts +15 -0
  44. package/lib/Modded/message_builder.js +2330 -0
  45. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  46. package/lib/Signal/Group/ciphertext-message.js +11 -0
  47. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  48. package/lib/Signal/Group/group-session-builder.js +29 -0
  49. package/lib/Signal/Group/group_cipher.d.ts +16 -0
  50. package/lib/Signal/Group/group_cipher.js +81 -0
  51. package/lib/Signal/Group/index.d.ts +11 -0
  52. package/lib/Signal/Group/index.js +11 -0
  53. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  54. package/lib/Signal/Group/keyhelper.js +17 -0
  55. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  56. package/lib/Signal/Group/sender-chain-key.js +25 -0
  57. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  58. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  59. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  60. package/lib/Signal/Group/sender-key-message.js +65 -0
  61. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  62. package/lib/Signal/Group/sender-key-name.js +47 -0
  63. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  64. package/lib/Signal/Group/sender-key-record.js +40 -0
  65. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  66. package/lib/Signal/Group/sender-key-state.js +83 -0
  67. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  68. package/lib/Signal/Group/sender-message-key.js +25 -0
  69. package/lib/Signal/libsignal.d.ts +4 -0
  70. package/lib/Signal/libsignal.js +406 -0
  71. package/lib/Signal/lid-mapping.d.ts +18 -0
  72. package/lib/Signal/lid-mapping.js +276 -0
  73. package/lib/Socket/Client/index.d.ts +2 -0
  74. package/lib/Socket/Client/index.js +2 -0
  75. package/lib/Socket/Client/types.d.ts +15 -0
  76. package/lib/Socket/Client/types.js +10 -0
  77. package/lib/Socket/Client/websocket.d.ts +12 -0
  78. package/lib/Socket/Client/websocket.js +53 -0
  79. package/lib/Socket/business.d.ts +537 -0
  80. package/lib/Socket/business.js +421 -0
  81. package/lib/Socket/chats.d.ts +110 -0
  82. package/lib/Socket/chats.js +1006 -0
  83. package/lib/Socket/communities.d.ts +646 -0
  84. package/lib/Socket/communities.js +430 -0
  85. package/lib/Socket/engine.d.ts +129 -0
  86. package/lib/Socket/engine.js +767 -0
  87. package/lib/Socket/groups.d.ts +149 -0
  88. package/lib/Socket/groups.js +326 -0
  89. package/lib/Socket/index.d.ts +637 -0
  90. package/lib/Socket/index.js +14 -0
  91. package/lib/Socket/messages-recv.d.ts +239 -0
  92. package/lib/Socket/messages-recv.js +1307 -0
  93. package/lib/Socket/messages-send.d.ts +580 -0
  94. package/lib/Socket/messages-send.js +1639 -0
  95. package/lib/Socket/mex.d.ts +2 -0
  96. package/lib/Socket/mex.js +47 -0
  97. package/lib/Socket/newsletter.d.ts +176 -0
  98. package/lib/Socket/newsletter.js +456 -0
  99. package/lib/Socket/socket.d.ts +56 -0
  100. package/lib/Socket/socket.js +998 -0
  101. package/lib/Types/Auth.d.ts +115 -0
  102. package/lib/Types/Auth.js +1 -0
  103. package/lib/Types/Bussines.d.ts +36 -0
  104. package/lib/Types/Bussines.js +1 -0
  105. package/lib/Types/Call.d.ts +14 -0
  106. package/lib/Types/Call.js +1 -0
  107. package/lib/Types/Chat.d.ts +124 -0
  108. package/lib/Types/Chat.js +7 -0
  109. package/lib/Types/Contact.d.ts +23 -0
  110. package/lib/Types/Contact.js +1 -0
  111. package/lib/Types/Events.d.ts +241 -0
  112. package/lib/Types/Events.js +1 -0
  113. package/lib/Types/GroupMetadata.d.ts +67 -0
  114. package/lib/Types/GroupMetadata.js +1 -0
  115. package/lib/Types/Label.d.ts +46 -0
  116. package/lib/Types/Label.js +24 -0
  117. package/lib/Types/LabelAssociation.d.ts +29 -0
  118. package/lib/Types/LabelAssociation.js +6 -0
  119. package/lib/Types/Message.d.ts +427 -0
  120. package/lib/Types/Message.js +10 -0
  121. package/lib/Types/Newsletter.d.ts +134 -0
  122. package/lib/Types/Newsletter.js +30 -0
  123. package/lib/Types/Product.d.ts +78 -0
  124. package/lib/Types/Product.js +1 -0
  125. package/lib/Types/Signal.d.ts +77 -0
  126. package/lib/Types/Signal.js +1 -0
  127. package/lib/Types/Socket.d.ts +173 -0
  128. package/lib/Types/Socket.js +2 -0
  129. package/lib/Types/State.d.ts +38 -0
  130. package/lib/Types/State.js +12 -0
  131. package/lib/Types/USync.d.ts +25 -0
  132. package/lib/Types/USync.js +1 -0
  133. package/lib/Types/index.d.ts +75 -0
  134. package/lib/Types/index.js +32 -0
  135. package/lib/Utils/auth-utils.d.ts +18 -0
  136. package/lib/Utils/auth-utils.js +289 -0
  137. package/lib/Utils/browser-utils.d.ts +3 -0
  138. package/lib/Utils/browser-utils.js +47 -0
  139. package/lib/Utils/business.d.ts +22 -0
  140. package/lib/Utils/business.js +230 -0
  141. package/lib/Utils/chat-utils.d.ts +69 -0
  142. package/lib/Utils/chat-utils.js +811 -0
  143. package/lib/Utils/companion-reg-client-utils.d.ts +20 -0
  144. package/lib/Utils/companion-reg-client-utils.js +66 -0
  145. package/lib/Utils/crypto.d.ts +41 -0
  146. package/lib/Utils/crypto.js +117 -0
  147. package/lib/Utils/decode-wa-message.d.ts +47 -0
  148. package/lib/Utils/decode-wa-message.js +282 -0
  149. package/lib/Utils/event-buffer.d.ts +35 -0
  150. package/lib/Utils/event-buffer.js +590 -0
  151. package/lib/Utils/generics.d.ts +90 -0
  152. package/lib/Utils/generics.js +384 -0
  153. package/lib/Utils/history.d.ts +21 -0
  154. package/lib/Utils/history.js +130 -0
  155. package/lib/Utils/identity-change-handler.d.ts +36 -0
  156. package/lib/Utils/identity-change-handler.js +48 -0
  157. package/lib/Utils/index.d.ts +25 -0
  158. package/lib/Utils/index.js +24 -0
  159. package/lib/Utils/link-preview.d.ts +20 -0
  160. package/lib/Utils/link-preview.js +84 -0
  161. package/lib/Utils/logger.d.ts +12 -0
  162. package/lib/Utils/logger.js +2 -0
  163. package/lib/Utils/lt-hash.d.ts +10 -0
  164. package/lib/Utils/lt-hash.js +7 -0
  165. package/lib/Utils/make-mutex.d.ts +8 -0
  166. package/lib/Utils/make-mutex.js +32 -0
  167. package/lib/Utils/message-retry-manager.d.ts +109 -0
  168. package/lib/Utils/message-retry-manager.js +224 -0
  169. package/lib/Utils/messages-media.d.ts +129 -0
  170. package/lib/Utils/messages-media.js +784 -0
  171. package/lib/Utils/messages.d.ts +90 -0
  172. package/lib/Utils/messages.js +1240 -0
  173. package/lib/Utils/noise-handler.d.ts +19 -0
  174. package/lib/Utils/noise-handler.js +200 -0
  175. package/lib/Utils/offline-node-processor.d.ts +16 -0
  176. package/lib/Utils/offline-node-processor.js +39 -0
  177. package/lib/Utils/platform-identity.d.ts +14 -0
  178. package/lib/Utils/platform-identity.js +148 -0
  179. package/lib/Utils/pre-key-manager.d.ts +27 -0
  180. package/lib/Utils/pre-key-manager.js +105 -0
  181. package/lib/Utils/process-message.d.ts +59 -0
  182. package/lib/Utils/process-message.js +544 -0
  183. package/lib/Utils/reporting-utils.d.ts +10 -0
  184. package/lib/Utils/reporting-utils.js +257 -0
  185. package/lib/Utils/rich-messages.d.ts +276 -0
  186. package/lib/Utils/rich-messages.js +1143 -0
  187. package/lib/Utils/signal.d.ts +33 -0
  188. package/lib/Utils/signal.js +158 -0
  189. package/lib/Utils/stanza-ack.d.ts +10 -0
  190. package/lib/Utils/stanza-ack.js +37 -0
  191. package/lib/Utils/sticker-pack.d.ts +10 -0
  192. package/lib/Utils/sticker-pack.js +111 -0
  193. package/lib/Utils/sync-action-utils.d.ts +18 -0
  194. package/lib/Utils/sync-action-utils.js +47 -0
  195. package/lib/Utils/tc-token-utils.d.ts +8 -0
  196. package/lib/Utils/tc-token-utils.js +45 -0
  197. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  198. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  199. package/lib/Utils/validate-connection.d.ts +10 -0
  200. package/lib/Utils/validate-connection.js +222 -0
  201. package/lib/VoIP/audio-feeder.d.ts +15 -0
  202. package/lib/VoIP/audio-feeder.js +136 -0
  203. package/lib/VoIP/index.d.ts +12 -0
  204. package/lib/VoIP/index.js +282 -0
  205. package/lib/VoIP/relay-transport.d.ts +43 -0
  206. package/lib/VoIP/relay-transport.js +559 -0
  207. package/lib/VoIP/signaling.js +603 -0
  208. package/lib/VoIP/types.d.ts +69 -0
  209. package/lib/VoIP/types.js +17 -0
  210. package/lib/VoIP/wasm-engine.d.ts +103 -0
  211. package/lib/VoIP/wasm-engine.js +1214 -0
  212. package/lib/VoIP/worker-bootstrap.js +1042 -0
  213. package/lib/WABinary/constants.d.ts +27 -0
  214. package/lib/WABinary/constants.js +1300 -0
  215. package/lib/WABinary/decode.d.ts +6 -0
  216. package/lib/WABinary/decode.js +261 -0
  217. package/lib/WABinary/encode.d.ts +2 -0
  218. package/lib/WABinary/encode.js +219 -0
  219. package/lib/WABinary/generic-utils.d.ts +16 -0
  220. package/lib/WABinary/generic-utils.js +190 -0
  221. package/lib/WABinary/index.d.ts +5 -0
  222. package/lib/WABinary/index.js +5 -0
  223. package/lib/WABinary/jid-utils.d.ts +47 -0
  224. package/lib/WABinary/jid-utils.js +95 -0
  225. package/lib/WABinary/types.d.ts +18 -0
  226. package/lib/WABinary/types.js +1 -0
  227. package/lib/WAM/BinaryInfo.d.ts +8 -0
  228. package/lib/WAM/BinaryInfo.js +9 -0
  229. package/lib/WAM/constants.d.ts +39 -0
  230. package/lib/WAM/constants.js +22852 -0
  231. package/lib/WAM/encode.d.ts +2 -0
  232. package/lib/WAM/encode.js +149 -0
  233. package/lib/WAM/index.d.ts +3 -0
  234. package/lib/WAM/index.js +3 -0
  235. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  236. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  237. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  238. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  239. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  240. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  241. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  242. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  243. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  244. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  245. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +9 -0
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  247. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  248. package/lib/WAUSync/Protocols/index.js +4 -0
  249. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  250. package/lib/WAUSync/USyncQuery.js +93 -0
  251. package/lib/WAUSync/USyncUser.d.ts +12 -0
  252. package/lib/WAUSync/USyncUser.js +22 -0
  253. package/lib/WAUSync/index.d.ts +3 -0
  254. package/lib/WAUSync/index.js +3 -0
  255. package/lib/assets/wasm/loader.js +5 -0
  256. package/lib/assets/wasm/whatsapp.wasm +0 -0
  257. package/lib/assets/wasm/worker-modules.js +273 -0
  258. package/lib/index.d.ts +21 -0
  259. package/lib/index.js +22 -0
  260. package/package.json +111 -0
@@ -0,0 +1,544 @@
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 } from './crypto.js';
6
+ import { getKeyAuthor, toNumber } from './generics.js';
7
+ import { downloadAndProcessHistorySyncNotification } from './history.js';
8
+ const SELF_ONLY_PROTOCOL_TYPES = new Set([
9
+ proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
10
+ proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
11
+ proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
12
+ proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE
13
+ ]);
14
+ const REAL_MSG_STUB_TYPES = new Set([
15
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
16
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
17
+ WAMessageStubType.CALL_MISSED_VIDEO,
18
+ WAMessageStubType.CALL_MISSED_VOICE
19
+ ]);
20
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
21
+ /** Cleans a received message to further processing */
22
+ export const cleanMessage = (message, meId, meLid) => {
23
+ // ensure remoteJid and participant doesn't have device or agent in it
24
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
25
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
26
+ }
27
+ else {
28
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
29
+ }
30
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
31
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid');
32
+ }
33
+ else {
34
+ message.key.participant = jidNormalizedUser(message.key.participant);
35
+ }
36
+ const content = normalizeMessageContent(message.message);
37
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
38
+ if (content?.reactionMessage) {
39
+ normaliseKey(content.reactionMessage.key);
40
+ }
41
+ if (content?.pollUpdateMessage) {
42
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
43
+ }
44
+ function normaliseKey(msgKey) {
45
+ // if the reaction is from another user
46
+ // we've to correctly map the key to this user's perspective
47
+ if (!message.key.fromMe) {
48
+ // if the sender believed the message being reacted to is not from them
49
+ // we've to correct the key to be from them, or some other participant
50
+ msgKey.fromMe = !msgKey.fromMe
51
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
52
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
53
+ : // if the message being reacted to, was from them
54
+ // fromMe automatically becomes false
55
+ false;
56
+ // set the remoteJid to being the same as the chat the message came from
57
+ // TODO: investigate inconsistencies
58
+ msgKey.remoteJid = message.key.remoteJid;
59
+ // set participant of the message
60
+ msgKey.participant = msgKey.participant || message.key.participant;
61
+ }
62
+ }
63
+ };
64
+ // TODO: target:audit AUDIT THIS FUNCTION AGAIN
65
+ export const isRealMessage = (message) => {
66
+ const normalizedContent = normalizeMessageContent(message.message);
67
+ const hasSomeContent = !!getContentType(normalizedContent);
68
+ return ((!!normalizedContent ||
69
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
70
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
71
+ hasSomeContent &&
72
+ !normalizedContent?.protocolMessage &&
73
+ !normalizedContent?.reactionMessage &&
74
+ !normalizedContent?.pollUpdateMessage);
75
+ };
76
+ export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
77
+ /**
78
+ * Get the ID of the chat from the given key.
79
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
80
+ */
81
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
82
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
83
+ return participant;
84
+ }
85
+ return remoteJid;
86
+ };
87
+ /**
88
+ * Decrypt a poll vote
89
+ * @param vote encrypted vote
90
+ * @param ctx additional info about the poll required for decryption
91
+ * @returns list of SHA256 options
92
+ */
93
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
94
+ const sign = Buffer.concat([
95
+ toBinary(pollMsgId),
96
+ toBinary(pollCreatorJid),
97
+ toBinary(voterJid),
98
+ toBinary('Poll Vote'),
99
+ new Uint8Array([1])
100
+ ]);
101
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
102
+ const decKey = hmacSign(sign, key0, 'sha256');
103
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
104
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
105
+ return proto.Message.PollVoteMessage.decode(decrypted);
106
+ function toBinary(txt) {
107
+ return Buffer.from(txt);
108
+ }
109
+ }
110
+ /**
111
+ * Decrypt an event response
112
+ * @param response encrypted event response
113
+ * @param ctx additional info about the event required for decryption
114
+ * @returns event response message
115
+ */
116
+ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
117
+ const sign = Buffer.concat([
118
+ toBinary(eventMsgId),
119
+ toBinary(eventCreatorJid),
120
+ toBinary(responderJid),
121
+ toBinary('Event Response'),
122
+ new Uint8Array([1])
123
+ ]);
124
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256');
125
+ const decKey = hmacSign(sign, key0, 'sha256');
126
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`);
127
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
128
+ return proto.Message.EventResponseMessage.decode(decrypted);
129
+ function toBinary(txt) {
130
+ return Buffer.from(txt);
131
+ }
132
+ }
133
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
134
+ const meId = creds.me.id;
135
+ const { accountSettings } = creds;
136
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
137
+ const isRealMsg = isRealMessage(message);
138
+ if (isRealMsg) {
139
+ chat.messages = [{ message }];
140
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
141
+ // only increment unread count if not CIPHERTEXT and from another person
142
+ if (shouldIncrementChatUnread(message)) {
143
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
144
+ }
145
+ }
146
+ const content = normalizeMessageContent(message.message);
147
+ // unarchive chat if it's a real message, or someone reacted to our message
148
+ // and we've the unarchive chats setting on
149
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
150
+ chat.archived = false;
151
+ chat.readOnly = false;
152
+ }
153
+ const protocolMsg = content?.protocolMessage;
154
+ if (protocolMsg) {
155
+ // BibzWhats (upstream rc12): tipe protocolMessage yang hanya boleh berasal dari
156
+ // perangkat kita sendiri. Tanpa guard ini pengirim asing bisa memalsukan
157
+ // history sync / app-state key share dan memanipulasi state lokal.
158
+ // REVOKE, MESSAGE_EDIT, EPHEMERAL_SETTING dsb. TIDAK termasuk (sah dari orang lain).
159
+ if (protocolMsg.type !== null &&
160
+ protocolMsg.type !== undefined &&
161
+ SELF_ONLY_PROTOCOL_TYPES.has(protocolMsg.type) &&
162
+ !message.key.fromMe) {
163
+ logger?.warn({ msgId: message.key.id, type: protocolMsg.type, from: message.key.participant || message.key.remoteJid }, 'dropping spoofed self-only protocolMessage from non-self origin');
164
+ return;
165
+ }
166
+ switch (protocolMsg.type) {
167
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
168
+ const histNotification = protocolMsg.historySyncNotification;
169
+ const process = shouldProcessHistoryMsg;
170
+ const isLatest = !creds.processedHistoryMessages?.length;
171
+ logger?.info({
172
+ histNotification,
173
+ process,
174
+ id: message.key.id,
175
+ isLatest
176
+ }, 'got history notification');
177
+ if (process) {
178
+ // TODO: investigate
179
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
180
+ ev.emit('creds.update', {
181
+ processedHistoryMessages: [
182
+ ...(creds.processedHistoryMessages || []),
183
+ { key: message.key, messageTimestamp: message.messageTimestamp }
184
+ ]
185
+ });
186
+ }
187
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger);
188
+ if (data.lidPnMappings?.length) {
189
+ logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync');
190
+ await signalRepository.lidMapping
191
+ .storeLIDPNMappings(data.lidPnMappings)
192
+ .catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'));
193
+ }
194
+ ev.emit('messaging-history.set', {
195
+ ...data,
196
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
197
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
198
+ });
199
+ }
200
+ break;
201
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
202
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
203
+ if (keys?.length) {
204
+ let newAppStateSyncKeyId = '';
205
+ await keyStore.transaction(async () => {
206
+ const newKeys = [];
207
+ for (const { keyData, keyId } of keys) {
208
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
209
+ newKeys.push(strKeyId);
210
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
211
+ newAppStateSyncKeyId = strKeyId;
212
+ }
213
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
214
+ }, meId);
215
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
216
+ }
217
+ else {
218
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
219
+ }
220
+ break;
221
+ case proto.Message.ProtocolMessage.Type.REVOKE:
222
+ ev.emit('messages.update', [
223
+ {
224
+ key: {
225
+ ...message.key,
226
+ id: protocolMsg.key.id
227
+ },
228
+ update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
229
+ }
230
+ ]);
231
+ break;
232
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
233
+ Object.assign(chat, {
234
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
235
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
236
+ });
237
+ break;
238
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
239
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
240
+ if (response) {
241
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
242
+ const peerDataOperationResult = response.peerDataOperationResult || [];
243
+ for (const result of peerDataOperationResult) {
244
+ const retryResponse = result?.placeholderMessageResendResponse;
245
+ //eslint-disable-next-line max-depth
246
+ if (!retryResponse?.webMessageInfoBytes) {
247
+ continue;
248
+ }
249
+ //eslint-disable-next-line max-depth
250
+ try {
251
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
252
+ const msgId = webMessageInfo.key?.id;
253
+ // Retrieve cached original message data (preserves LID details,
254
+ // timestamps, etc. that the phone may omit in its PDO response)
255
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined;
256
+ //eslint-disable-next-line max-depth
257
+ if (msgId) {
258
+ await placeholderResendCache?.del(msgId);
259
+ }
260
+ let finalMsg;
261
+ //eslint-disable-next-line max-depth
262
+ if (cachedData && typeof cachedData === 'object') {
263
+ // Apply decoded message content onto cached metadata (preserves LID etc.)
264
+ cachedData.message = webMessageInfo.message;
265
+ //eslint-disable-next-line max-depth
266
+ if (webMessageInfo.messageTimestamp) {
267
+ cachedData.messageTimestamp = webMessageInfo.messageTimestamp;
268
+ }
269
+ finalMsg = cachedData;
270
+ }
271
+ else {
272
+ finalMsg = webMessageInfo;
273
+ }
274
+ logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend');
275
+ ev.emit('messages.upsert', {
276
+ messages: [finalMsg],
277
+ type: 'notify',
278
+ requestId: response.stanzaId
279
+ });
280
+ }
281
+ catch (err) {
282
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response');
283
+ }
284
+ }
285
+ }
286
+ break;
287
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
288
+ ev.emit('messages.update', [
289
+ {
290
+ // flip the sender / fromMe properties because they're in the perspective of the sender
291
+ key: { ...message.key, id: protocolMsg.key?.id },
292
+ update: {
293
+ message: {
294
+ editedMessage: {
295
+ message: protocolMsg.editedMessage
296
+ }
297
+ },
298
+ messageTimestamp: protocolMsg.timestampMs
299
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
300
+ : message.messageTimestamp
301
+ }
302
+ }
303
+ ]);
304
+ break;
305
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
306
+ const labelAssociationMsg = protocolMsg.memberLabel;
307
+ if (labelAssociationMsg?.label) {
308
+ ev.emit('group.member-tag.update', {
309
+ groupId: chat.id,
310
+ label: labelAssociationMsg.label,
311
+ participant: message.key.participant,
312
+ participantAlt: message.key.participantAlt,
313
+ messageTimestamp: Number(message.messageTimestamp)
314
+ });
315
+ }
316
+ break;
317
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
318
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
319
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
320
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
321
+ const pairs = [];
322
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
323
+ const lid = latestLid || assignedLid;
324
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
325
+ }
326
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
327
+ if (pairs.length) {
328
+ for (const { pn, lid } of pairs) {
329
+ await signalRepository.migrateSession(pn, lid);
330
+ }
331
+ }
332
+ }
333
+ }
334
+ else if (content?.reactionMessage) {
335
+ const reaction = {
336
+ ...content.reactionMessage,
337
+ key: message.key
338
+ };
339
+ ev.emit('messages.reaction', [
340
+ {
341
+ reaction,
342
+ key: content.reactionMessage?.key
343
+ }
344
+ ]);
345
+ }
346
+ else if (content?.encEventResponseMessage) {
347
+ const encEventResponse = content.encEventResponseMessage;
348
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
349
+ // we need to fetch the event creation message to get the event enc key
350
+ const eventMsg = await getMessage(creationMsgKey);
351
+ if (eventMsg) {
352
+ try {
353
+ const meIdNormalised = jidNormalizedUser(meId);
354
+ // all jids need to be PN
355
+ const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid;
356
+ const eventCreatorPn = isLidUser(eventCreatorKey)
357
+ ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey)
358
+ : eventCreatorKey;
359
+ const eventCreatorJid = getKeyAuthor({ remoteJid: jidNormalizedUser(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised);
360
+ const responderJid = getKeyAuthor(message.key, meIdNormalised);
361
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret;
362
+ if (!eventEncKey) {
363
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption');
364
+ }
365
+ else {
366
+ const responseMsg = decryptEventResponse(encEventResponse, {
367
+ eventEncKey,
368
+ eventCreatorJid,
369
+ eventMsgId: creationMsgKey.id,
370
+ responderJid
371
+ });
372
+ const eventResponse = {
373
+ eventResponseMessageKey: message.key,
374
+ senderTimestampMs: responseMsg.timestampMs,
375
+ response: responseMsg
376
+ };
377
+ ev.emit('messages.update', [
378
+ {
379
+ key: creationMsgKey,
380
+ update: {
381
+ eventResponses: [eventResponse]
382
+ }
383
+ }
384
+ ]);
385
+ }
386
+ }
387
+ catch (err) {
388
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response');
389
+ }
390
+ }
391
+ else {
392
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response');
393
+ }
394
+ }
395
+ else if (message.messageStubType) {
396
+ const jid = message.key?.remoteJid;
397
+ //let actor = whatsappID (message.participant)
398
+ let participants;
399
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', {
400
+ id: jid,
401
+ author: message.key.participant,
402
+ authorPn: message.key.participantAlt,
403
+ participants,
404
+ action
405
+ });
406
+ const emitGroupUpdate = (update) => {
407
+ ev.emit('groups.update', [
408
+ { id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt }
409
+ ]);
410
+ };
411
+ const emitGroupRequestJoin = (participant, action, method) => {
412
+ ev.emit('group.join-request', {
413
+ id: jid,
414
+ author: message.key.participant,
415
+ authorPn: message.key.participantAlt,
416
+ participant: participant.lid,
417
+ participantPn: participant.pn,
418
+ action,
419
+ method: method
420
+ });
421
+ };
422
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)); // ADD SUPPORT FOR LID
423
+ switch (message.messageStubType) {
424
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
425
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
426
+ emitParticipantsUpdate('modify');
427
+ break;
428
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
429
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
430
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
431
+ emitParticipantsUpdate('remove');
432
+ // mark the chat read only if you left the group
433
+ if (participantsIncludesMe()) {
434
+ chat.readOnly = true;
435
+ }
436
+ break;
437
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
438
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
439
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
440
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
441
+ if (participantsIncludesMe()) {
442
+ chat.readOnly = false;
443
+ }
444
+ emitParticipantsUpdate('add');
445
+ break;
446
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
447
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
448
+ emitParticipantsUpdate('demote');
449
+ break;
450
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
451
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
452
+ emitParticipantsUpdate('promote');
453
+ break;
454
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
455
+ const announceValue = message.messageStubParameters?.[0];
456
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
457
+ break;
458
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
459
+ const restrictValue = message.messageStubParameters?.[0];
460
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
461
+ break;
462
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
463
+ const name = message.messageStubParameters?.[0];
464
+ chat.name = name;
465
+ emitGroupUpdate({ subject: name });
466
+ break;
467
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
468
+ const description = message.messageStubParameters?.[0];
469
+ chat.description = description;
470
+ emitGroupUpdate({ desc: description });
471
+ break;
472
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
473
+ const code = message.messageStubParameters?.[0];
474
+ emitGroupUpdate({ inviteCode: code });
475
+ break;
476
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
477
+ const memberAddValue = message.messageStubParameters?.[0];
478
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
479
+ break;
480
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
481
+ const approvalMode = message.messageStubParameters?.[0];
482
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
483
+ break;
484
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: // TODO: Add other events
485
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
486
+ const action = message.messageStubParameters?.[1];
487
+ const method = message.messageStubParameters?.[2];
488
+ emitGroupRequestJoin(participant, action, method);
489
+ break;
490
+ }
491
+ } /* else if(content?.pollUpdateMessage) {
492
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
493
+ // we need to fetch the poll creation message to get the poll enc key
494
+ // TODO: make standalone, remove getMessage reference
495
+ // TODO: Remove entirely
496
+ const pollMsg = await getMessage(creationMsgKey)
497
+ if(pollMsg) {
498
+ const meIdNormalised = jidNormalizedUser(meId)
499
+ const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
500
+ const voterJid = getKeyAuthor(message.key, meIdNormalised)
501
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret!
502
+
503
+ try {
504
+ const voteMsg = decryptPollVote(
505
+ content.pollUpdateMessage.vote!,
506
+ {
507
+ pollEncKey,
508
+ pollCreatorJid,
509
+ pollMsgId: creationMsgKey.id!,
510
+ voterJid,
511
+ }
512
+ )
513
+ ev.emit('messages.update', [
514
+ {
515
+ key: creationMsgKey,
516
+ update: {
517
+ pollUpdates: [
518
+ {
519
+ pollUpdateMessageKey: message.key,
520
+ vote: voteMsg,
521
+ senderTimestampMs: (content.pollUpdateMessage.senderTimestampMs! as Long).toNumber(),
522
+ }
523
+ ]
524
+ }
525
+ }
526
+ ])
527
+ } catch(err) {
528
+ logger?.warn(
529
+ { err, creationMsgKey },
530
+ 'failed to decrypt poll vote'
531
+ )
532
+ }
533
+ } else {
534
+ logger?.warn(
535
+ { creationMsgKey },
536
+ 'poll creation message not found, cannot decrypt update'
537
+ )
538
+ }
539
+ } */
540
+ if (Object.keys(chat).length > 1) {
541
+ ev.emit('chats.update', [chat]);
542
+ }
543
+ };
544
+ export default processMessage;
@@ -0,0 +1,10 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { WAMessageContent, WAMessageKey } from '../Types/index.js';
3
+ import type { BinaryNode } from '../WABinary/index.js';
4
+ export type ReportingField = {
5
+ f: number;
6
+ m?: boolean;
7
+ s?: ReportingField[];
8
+ };
9
+ export declare const shouldIncludeReportingToken: (message: proto.IMessage) => boolean;
10
+ export declare const getMessageReportingToken: (msgProtobuf: Buffer, message: WAMessageContent, key: WAMessageKey) => Promise<BinaryNode | null>;