@aseppxyzz12/baileys 1.1.8

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 (185) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +2579 -0
  3. package/WAProto/AICommon/AICommon.js +19396 -0
  4. package/WAProto/AICommon/AICommon.proto +820 -0
  5. package/WAProto/Adv/Adv.js +1137 -0
  6. package/WAProto/Adv/Adv.proto +42 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +8975 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +484 -0
  9. package/WAProto/Cert/Cert.js +893 -0
  10. package/WAProto/Cert/Cert.proto +30 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +2457 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +103 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
  17. package/WAProto/E2E/E2E.js +78728 -0
  18. package/WAProto/E2E/E2E.proto +1970 -0
  19. package/WAProto/Ephemeral/Ephemeral.js +143 -0
  20. package/WAProto/Ephemeral/Ephemeral.proto +7 -0
  21. package/WAProto/HistorySync/HistorySync.js +95931 -0
  22. package/WAProto/HistorySync/HistorySync.proto +229 -0
  23. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
  24. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
  25. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
  26. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
  27. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
  28. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
  29. package/WAProto/MmsRetry/MmsRetry.js +310 -0
  30. package/WAProto/MmsRetry/MmsRetry.proto +19 -0
  31. package/WAProto/Protocol/Protocol.js +399 -0
  32. package/WAProto/Protocol/Protocol.proto +22 -0
  33. package/WAProto/Reporting/Reporting.js +535 -0
  34. package/WAProto/Reporting/Reporting.proto +22 -0
  35. package/WAProto/ServerSync/ServerSync.js +1830 -0
  36. package/WAProto/ServerSync/ServerSync.proto +70 -0
  37. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
  38. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
  39. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
  40. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
  41. package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
  42. package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
  43. package/WAProto/SyncAction/SyncAction.js +17424 -0
  44. package/WAProto/SyncAction/SyncAction.proto +663 -0
  45. package/WAProto/UserPassword/UserPassword.js +544 -0
  46. package/WAProto/UserPassword/UserPassword.proto +28 -0
  47. package/WAProto/VnameCert/VnameCert.js +1466 -0
  48. package/WAProto/VnameCert/VnameCert.proto +65 -0
  49. package/WAProto/Wa6/Wa6.js +4601 -0
  50. package/WAProto/Wa6/Wa6.proto +241 -0
  51. package/WAProto/Web/Web.js +90819 -0
  52. package/WAProto/Web/Web.proto +605 -0
  53. package/WAProto/index.js +30 -0
  54. package/engine-requirements.js +9 -0
  55. package/lib/Defaults/baileys-version.json +3 -0
  56. package/lib/Defaults/connection.js +39 -0
  57. package/lib/Defaults/constants.js +50 -0
  58. package/lib/Defaults/history.js +13 -0
  59. package/lib/Defaults/index.js +36 -0
  60. package/lib/Defaults/media.js +43 -0
  61. package/lib/Defaults/phonenumber-mcc.json +223 -0
  62. package/lib/Defaults/prefix.js +12 -0
  63. package/lib/Function/Download/tiktok.js +19 -0
  64. package/lib/Function/Tools/bypass.js +19 -0
  65. package/lib/Function/index.js +13 -0
  66. package/lib/Signal/Group/ciphertext-message.js +14 -0
  67. package/lib/Signal/Group/group-session-builder.js +46 -0
  68. package/lib/Signal/Group/group_cipher.js +104 -0
  69. package/lib/Signal/Group/index.js +42 -0
  70. package/lib/Signal/Group/keyhelper.js +21 -0
  71. package/lib/Signal/Group/queue-job.js +57 -0
  72. package/lib/Signal/Group/sender-chain-key.js +34 -0
  73. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  74. package/lib/Signal/Group/sender-key-message.js +78 -0
  75. package/lib/Signal/Group/sender-key-name.js +49 -0
  76. package/lib/Signal/Group/sender-key-record.js +45 -0
  77. package/lib/Signal/Group/sender-key-state.js +100 -0
  78. package/lib/Signal/Group/sender-message-key.js +28 -0
  79. package/lib/Signal/libsignal.js +364 -0
  80. package/lib/Signal/lid-mapping.js +164 -0
  81. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  82. package/lib/Socket/Client/index.js +31 -0
  83. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  84. package/lib/Socket/Client/types.js +12 -0
  85. package/lib/Socket/Client/web-socket-client.js +62 -0
  86. package/lib/Socket/Client/websocket.js +67 -0
  87. package/lib/Socket/business.js +291 -0
  88. package/lib/Socket/chats.js +874 -0
  89. package/lib/Socket/community.js +454 -0
  90. package/lib/Socket/dugong.js +658 -0
  91. package/lib/Socket/groups.js +357 -0
  92. package/lib/Socket/index.js +13 -0
  93. package/lib/Socket/messages-recv.js +1509 -0
  94. package/lib/Socket/messages-send.js +1505 -0
  95. package/lib/Socket/mex.js +54 -0
  96. package/lib/Socket/newsletter.js +171 -0
  97. package/lib/Socket/registration.js +167 -0
  98. package/lib/Socket/rich-content.js +279 -0
  99. package/lib/Socket/socket.js +905 -0
  100. package/lib/Socket/username.js +157 -0
  101. package/lib/Socket/usync.js +70 -0
  102. package/lib/Store/index.js +37 -0
  103. package/lib/Store/keyed-db.js +114 -0
  104. package/lib/Store/make-cache-manager-store.js +77 -0
  105. package/lib/Store/make-in-memory-store.js +423 -0
  106. package/lib/Store/make-ordered-dictionary.js +78 -0
  107. package/lib/Store/object-repository.js +26 -0
  108. package/lib/Types/Auth.js +2 -0
  109. package/lib/Types/Bussines.js +2 -0
  110. package/lib/Types/Call.js +2 -0
  111. package/lib/Types/Chat.js +10 -0
  112. package/lib/Types/Contact.js +2 -0
  113. package/lib/Types/Events.js +2 -0
  114. package/lib/Types/GroupMetadata.js +2 -0
  115. package/lib/Types/Label.js +25 -0
  116. package/lib/Types/LabelAssociation.js +4 -0
  117. package/lib/Types/Message.js +11 -0
  118. package/lib/Types/Mex.js +40 -0
  119. package/lib/Types/MexUpdates.js +15 -0
  120. package/lib/Types/Newsletter.js +32 -0
  121. package/lib/Types/Product.js +2 -0
  122. package/lib/Types/Signal.js +2 -0
  123. package/lib/Types/Socket.js +2 -0
  124. package/lib/Types/State.js +9 -0
  125. package/lib/Types/USync.js +2 -0
  126. package/lib/Types/index.js +60 -0
  127. package/lib/Utils/auth-utils.js +256 -0
  128. package/lib/Utils/baileys-event-stream.js +63 -0
  129. package/lib/Utils/bot-toolkit.js +455 -0
  130. package/lib/Utils/browser-utils.js +29 -0
  131. package/lib/Utils/business.js +233 -0
  132. package/lib/Utils/chat-utils.js +904 -0
  133. package/lib/Utils/companion-reg-client-utils.js +41 -0
  134. package/lib/Utils/crypto.js +144 -0
  135. package/lib/Utils/decode-wa-message.js +305 -0
  136. package/lib/Utils/event-buffer.js +555 -0
  137. package/lib/Utils/generics.js +411 -0
  138. package/lib/Utils/history.js +100 -0
  139. package/lib/Utils/identity-change-handler.js +53 -0
  140. package/lib/Utils/index.js +57 -0
  141. package/lib/Utils/link-preview.js +76 -0
  142. package/lib/Utils/logger.js +4 -0
  143. package/lib/Utils/lt-hash.js +45 -0
  144. package/lib/Utils/make-mutex.js +33 -0
  145. package/lib/Utils/message-composer.js +289 -0
  146. package/lib/Utils/message-retry-manager.js +134 -0
  147. package/lib/Utils/messages-media.js +806 -0
  148. package/lib/Utils/messages.js +1908 -0
  149. package/lib/Utils/noise-handler.js +157 -0
  150. package/lib/Utils/offline-node-processor.js +42 -0
  151. package/lib/Utils/pre-key-manager.js +86 -0
  152. package/lib/Utils/process-message.js +814 -0
  153. package/lib/Utils/reporting-utils.js +264 -0
  154. package/lib/Utils/signal.js +183 -0
  155. package/lib/Utils/stanza-ack.js +36 -0
  156. package/lib/Utils/sync-action-utils.js +52 -0
  157. package/lib/Utils/tc-token-utils.js +167 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +104 -0
  159. package/lib/Utils/validate-connection.js +229 -0
  160. package/lib/Utils/vialeys-event-stream.js +41 -0
  161. package/lib/WABinary/constants.js +1308 -0
  162. package/lib/WABinary/decode.js +233 -0
  163. package/lib/WABinary/encode.js +212 -0
  164. package/lib/WABinary/generic-utils.js +124 -0
  165. package/lib/WABinary/index.js +36 -0
  166. package/lib/WABinary/jid-utils.js +101 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.js +12 -0
  169. package/lib/WAM/constants.js +20491 -0
  170. package/lib/WAM/encode.js +148 -0
  171. package/lib/WAM/index.js +34 -0
  172. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
  176. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  179. package/lib/WAUSync/Protocols/index.js +38 -0
  180. package/lib/WAUSync/USyncQuery.js +97 -0
  181. package/lib/WAUSync/USyncUser.js +33 -0
  182. package/lib/WAUSync/index.js +34 -0
  183. package/lib/index.js +113 -0
  184. package/lib/messages-send.js +1496 -0
  185. package/package.json +100 -0
@@ -0,0 +1,904 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { Boom: Boom } = require("@hapi/boom");
4
+ const { proto: proto } = require("../../WAProto");
5
+ const { LabelAssociationType: LabelAssociationType } = require("../Types/LabelAssociation");
6
+ const {
7
+ getBinaryNodeChild: getBinaryNodeChild,
8
+ getBinaryNodeChildren: getBinaryNodeChildren,
9
+ isJidGroup: isJidGroup,
10
+ jidNormalizedUser: jidNormalizedUser,
11
+ isLidUser: isLidUser,
12
+ isPnUser: isPnUser,
13
+ } = require("../WABinary");
14
+ const {
15
+ hkdf: hkdf,
16
+ hmacSign: hmacSign,
17
+ aesEncrypt: aesEncrypt,
18
+ aesDecrypt: aesDecrypt,
19
+ } = require("./crypto");
20
+ const { toNumber: toNumber } = require("./generics");
21
+ const { LT_HASH_ANTI_TAMPERING: LT_HASH_ANTI_TAMPERING } = require("./lt-hash");
22
+ const { downloadContentFromMessage: downloadContentFromMessage } = require("./messages-media");
23
+ const mutationKeys = async (keydata) => {
24
+ const expanded = await hkdf(keydata, 160, { info: "WhatsApp Mutation Keys" });
25
+ return {
26
+ indexKey: expanded.slice(0, 32),
27
+ valueEncryptionKey: expanded.slice(32, 64),
28
+ valueMacKey: expanded.slice(64, 96),
29
+ snapshotMacKey: expanded.slice(96, 128),
30
+ patchMacKey: expanded.slice(128, 160),
31
+ };
32
+ };
33
+ const generateMac = (operation, data, keyId, key) => {
34
+ const getKeyData = () => {
35
+ let r;
36
+ switch (operation) {
37
+ case proto.SyncdMutation.SyncdOperation.SET:
38
+ r = 1;
39
+ break;
40
+ case proto.SyncdMutation.SyncdOperation.REMOVE:
41
+ r = 2;
42
+ break;
43
+ }
44
+ const buff = Buffer.from([r]);
45
+ return Buffer.concat([buff, Buffer.from(keyId, "base64")]);
46
+ };
47
+ const keyData = getKeyData();
48
+ const last = Buffer.alloc(8);
49
+ last.set([keyData.length], last.length - 1);
50
+ const total = Buffer.concat([keyData, data, last]);
51
+ const hmac = hmacSign(total, key, "sha512");
52
+ return hmac.slice(0, 32);
53
+ };
54
+ const to64BitNetworkOrder = (e) => {
55
+ const buff = Buffer.alloc(8);
56
+ buff.writeUint32BE(e, 4);
57
+ return buff;
58
+ };
59
+ const makeLtHashGenerator = ({ indexValueMap: indexValueMap, hash: hash }) => {
60
+ indexValueMap = { ...indexValueMap };
61
+ const addBuffs = [];
62
+ const subBuffs = [];
63
+ return {
64
+ mix: ({ indexMac: indexMac, valueMac: valueMac, operation: operation }) => {
65
+ const indexMacBase64 = Buffer.from(indexMac).toString("base64");
66
+ const prevOp = indexValueMap[indexMacBase64];
67
+ if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
68
+ if (!prevOp) {
69
+ throw new Boom("tried remove, but no previous op", {
70
+ data: { indexMac: indexMac, valueMac: valueMac },
71
+ });
72
+ }
73
+ delete indexValueMap[indexMacBase64];
74
+ } else {
75
+ addBuffs.push(new Uint8Array(valueMac).buffer);
76
+ indexValueMap[indexMacBase64] = { valueMac: valueMac };
77
+ }
78
+ if (prevOp) {
79
+ subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
80
+ }
81
+ },
82
+ finish: async () => {
83
+ const hashArrayBuffer = new Uint8Array(hash).buffer;
84
+ const result = await LT_HASH_ANTI_TAMPERING.subtractThenAdd(
85
+ hashArrayBuffer,
86
+ addBuffs,
87
+ subBuffs
88
+ );
89
+ const buffer = Buffer.from(result);
90
+ return { hash: buffer, indexValueMap: indexValueMap };
91
+ },
92
+ };
93
+ };
94
+ const generateSnapshotMac = (lthash, version, name, key) => {
95
+ const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, "utf-8")]);
96
+ return hmacSign(total, key, "sha256");
97
+ };
98
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
99
+ const total = Buffer.concat([
100
+ snapshotMac,
101
+ ...valueMacs,
102
+ to64BitNetworkOrder(version),
103
+ Buffer.from(type, "utf-8"),
104
+ ]);
105
+ return hmacSign(total, key);
106
+ };
107
+ const newLTHashState = () => ({
108
+ version: 0,
109
+ hash: Buffer.alloc(128),
110
+ indexValueMap: {},
111
+ });
112
+ const encodeSyncdPatch = async (
113
+ {
114
+ type: type,
115
+ index: index,
116
+ syncAction: syncAction,
117
+ apiVersion: apiVersion,
118
+ operation: operation,
119
+ },
120
+ myAppStateKeyId,
121
+ state,
122
+ getAppStateSyncKey
123
+ ) => {
124
+ const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
125
+ if (!key) {
126
+ throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, {
127
+ statusCode: 404,
128
+ });
129
+ }
130
+ const encKeyId = Buffer.from(myAppStateKeyId, "base64");
131
+ state = { ...state, indexValueMap: { ...state.indexValueMap } };
132
+ const indexBuffer = Buffer.from(JSON.stringify(index));
133
+ const dataProto = proto.SyncActionData.fromObject({
134
+ index: indexBuffer,
135
+ value: syncAction,
136
+ padding: new Uint8Array(0),
137
+ version: apiVersion,
138
+ });
139
+ const encoded = proto.SyncActionData.encode(dataProto).finish();
140
+ const keyValue = await mutationKeys(key.keyData);
141
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey);
142
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
143
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey);
144
+ const generator = makeLtHashGenerator(state);
145
+ generator.mix({
146
+ indexMac: indexMac,
147
+ valueMac: valueMac,
148
+ operation: operation,
149
+ });
150
+ Object.assign(state, await generator.finish());
151
+ state.version += 1;
152
+ const snapshotMac = generateSnapshotMac(
153
+ state.hash,
154
+ state.version,
155
+ type,
156
+ keyValue.snapshotMacKey
157
+ );
158
+ const patch = {
159
+ patchMac: generatePatchMac(
160
+ snapshotMac,
161
+ [valueMac],
162
+ state.version,
163
+ type,
164
+ keyValue.patchMacKey
165
+ ),
166
+ snapshotMac: snapshotMac,
167
+ keyId: { id: encKeyId },
168
+ mutations: [
169
+ {
170
+ operation: operation,
171
+ record: {
172
+ index: { blob: indexMac },
173
+ value: { blob: Buffer.concat([encValue, valueMac]) },
174
+ keyId: { id: encKeyId },
175
+ },
176
+ },
177
+ ],
178
+ };
179
+ const base64Index = indexMac.toString("base64");
180
+ state.indexValueMap[base64Index] = { valueMac: valueMac };
181
+ return { patch: patch, state: state };
182
+ };
183
+ const decodeSyncdMutations = async (
184
+ msgMutations,
185
+ initialState,
186
+ getAppStateSyncKey,
187
+ onMutation,
188
+ validateMacs
189
+ ) => {
190
+ const ltGenerator = makeLtHashGenerator(initialState);
191
+ for (const msgMutation of msgMutations) {
192
+ const operation =
193
+ "operation" in msgMutation
194
+ ? msgMutation.operation
195
+ : proto.SyncdMutation.SyncdOperation.SET;
196
+ const record =
197
+ "record" in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
198
+ const key = await getKey(record.keyId.id);
199
+ const content = Buffer.from(record.value.blob);
200
+ const encContent = content.slice(0, -32);
201
+ const ogValueMac = content.slice(-32);
202
+ if (validateMacs) {
203
+ const contentHmac = generateMac(
204
+ operation,
205
+ encContent,
206
+ record.keyId.id,
207
+ key.valueMacKey
208
+ );
209
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
210
+ throw new Boom("HMAC content verification failed");
211
+ }
212
+ }
213
+ const result = aesDecrypt(encContent, key.valueEncryptionKey);
214
+ const syncAction = proto.SyncActionData.decode(result);
215
+ if (validateMacs) {
216
+ const hmac = hmacSign(syncAction.index, key.indexKey);
217
+ if (Buffer.compare(hmac, record.index.blob) !== 0) {
218
+ throw new Boom("HMAC index verification failed");
219
+ }
220
+ }
221
+ const indexStr = Buffer.from(syncAction.index).toString();
222
+ onMutation({ syncAction: syncAction, index: JSON.parse(indexStr) });
223
+ ltGenerator.mix({
224
+ indexMac: record.index.blob,
225
+ valueMac: ogValueMac,
226
+ operation: operation,
227
+ });
228
+ }
229
+ return await ltGenerator.finish();
230
+ async function getKey(keyId) {
231
+ const base64Key = Buffer.from(keyId).toString("base64");
232
+ const keyEnc = await getAppStateSyncKey(base64Key);
233
+ if (!keyEnc) {
234
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
235
+ statusCode: 404,
236
+ data: { msgMutations: msgMutations },
237
+ });
238
+ }
239
+ return mutationKeys(keyEnc.keyData);
240
+ }
241
+ };
242
+ const decodeSyncdPatch = async (
243
+ msg,
244
+ name,
245
+ initialState,
246
+ getAppStateSyncKey,
247
+ onMutation,
248
+ validateMacs
249
+ ) => {
250
+ if (validateMacs) {
251
+ const base64Key = Buffer.from(msg.keyId.id).toString("base64");
252
+ const mainKeyObj = await getAppStateSyncKey(base64Key);
253
+ if (!mainKeyObj) {
254
+ throw new Boom(`failed to find key "${base64Key}" to decode patch`, {
255
+ statusCode: 404,
256
+ data: { msg: msg },
257
+ });
258
+ }
259
+ const mainKey = await mutationKeys(mainKeyObj.keyData);
260
+ const mutationmacs = msg.mutations.map((mutation) => mutation.record.value.blob.slice(-32));
261
+ const patchMac = generatePatchMac(
262
+ msg.snapshotMac,
263
+ mutationmacs,
264
+ toNumber(msg.version.version),
265
+ name,
266
+ mainKey.patchMacKey
267
+ );
268
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
269
+ throw new Boom("Invalid patch mac");
270
+ }
271
+ }
272
+ const result = await decodeSyncdMutations(
273
+ msg.mutations,
274
+ initialState,
275
+ getAppStateSyncKey,
276
+ onMutation,
277
+ validateMacs
278
+ );
279
+ return result;
280
+ };
281
+ const extractSyncdPatches = async (result, options) => {
282
+ const syncNode = getBinaryNodeChild(result, "sync");
283
+ const collectionNodes = getBinaryNodeChildren(syncNode, "collection");
284
+ const final = {};
285
+ await Promise.all(
286
+ collectionNodes.map(async (collectionNode) => {
287
+ const patchesNode = getBinaryNodeChild(collectionNode, "patches");
288
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, "patch");
289
+ const snapshotNode = getBinaryNodeChild(collectionNode, "snapshot");
290
+ const syncds = [];
291
+ const name = collectionNode.attrs.name;
292
+ const hasMorePatches = collectionNode.attrs.has_more_patches === "true";
293
+ let snapshot = undefined;
294
+ if (snapshotNode && !!snapshotNode.content) {
295
+ if (!Buffer.isBuffer(snapshotNode)) {
296
+ snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
297
+ }
298
+ const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content);
299
+ const data = await downloadExternalBlob(blobRef, options);
300
+ snapshot = proto.SyncdSnapshot.decode(data);
301
+ }
302
+ for (let { content: content } of patches) {
303
+ if (content) {
304
+ if (!Buffer.isBuffer(content)) {
305
+ content = Buffer.from(Object.values(content));
306
+ }
307
+ const syncd = proto.SyncdPatch.decode(content);
308
+ if (!syncd.version) {
309
+ syncd.version = { version: +collectionNode.attrs.version + 1 };
310
+ }
311
+ syncds.push(syncd);
312
+ }
313
+ }
314
+ final[name] = {
315
+ patches: syncds,
316
+ hasMorePatches: hasMorePatches,
317
+ snapshot: snapshot,
318
+ };
319
+ })
320
+ );
321
+ return final;
322
+ };
323
+ const downloadExternalBlob = async (blob, options) => {
324
+ const stream = await downloadContentFromMessage(blob, "md-app-state", {
325
+ options: options,
326
+ });
327
+ const bufferArray = [];
328
+ for await (const chunk of stream) {
329
+ bufferArray.push(chunk);
330
+ }
331
+ return Buffer.concat(bufferArray);
332
+ };
333
+ const downloadExternalPatch = async (blob, options) => {
334
+ const buffer = await downloadExternalBlob(blob, options);
335
+ const syncData = proto.SyncdMutations.decode(buffer);
336
+ return syncData;
337
+ };
338
+ const decodeSyncdSnapshot = async (
339
+ name,
340
+ snapshot,
341
+ getAppStateSyncKey,
342
+ minimumVersionNumber,
343
+ validateMacs = true
344
+ ) => {
345
+ const newState = newLTHashState();
346
+ newState.version = toNumber(snapshot.version.version);
347
+ const mutationMap = {};
348
+ const areMutationsRequired =
349
+ typeof minimumVersionNumber === "undefined" || newState.version > minimumVersionNumber;
350
+ const { hash: hash, indexValueMap: indexValueMap } = await decodeSyncdMutations(
351
+ snapshot.records,
352
+ newState,
353
+ getAppStateSyncKey,
354
+ areMutationsRequired
355
+ ? (mutation) => {
356
+ const index = mutation.syncAction.index?.toString();
357
+ mutationMap[index] = mutation;
358
+ }
359
+ : () => {},
360
+ validateMacs
361
+ );
362
+ newState.hash = hash;
363
+ newState.indexValueMap = indexValueMap;
364
+ if (validateMacs) {
365
+ const base64Key = Buffer.from(snapshot.keyId.id).toString("base64");
366
+ const keyEnc = await getAppStateSyncKey(base64Key);
367
+ if (!keyEnc) {
368
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
369
+ }
370
+ const result = await mutationKeys(keyEnc.keyData);
371
+ const computedSnapshotMac = generateSnapshotMac(
372
+ newState.hash,
373
+ newState.version,
374
+ name,
375
+ result.snapshotMacKey
376
+ );
377
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
378
+ throw new Boom(
379
+ `failed to verify LTHash at ${newState.version} of ${name} from snapshot`
380
+ );
381
+ }
382
+ }
383
+ return { state: newState, mutationMap: mutationMap };
384
+ };
385
+ const decodePatches = async (
386
+ name,
387
+ syncds,
388
+ initial,
389
+ getAppStateSyncKey,
390
+ options,
391
+ minimumVersionNumber,
392
+ logger,
393
+ validateMacs = true
394
+ ) => {
395
+ const newState = { ...initial, indexValueMap: { ...initial.indexValueMap } };
396
+ const mutationMap = {};
397
+ for (const syncd of syncds) {
398
+ const { version: version, keyId: keyId, snapshotMac: snapshotMac } = syncd;
399
+ if (syncd.externalMutations) {
400
+ logger?.trace({ name: name, version: version }, "downloading external patch");
401
+ const ref = await downloadExternalPatch(syncd.externalMutations, options);
402
+ logger?.debug(
403
+ { name: name, version: version, mutations: ref.mutations.length },
404
+ "downloaded external patch"
405
+ );
406
+ syncd.mutations?.push(...ref.mutations);
407
+ }
408
+ const patchVersion = toNumber(version.version);
409
+ newState.version = patchVersion;
410
+ const shouldMutate =
411
+ typeof minimumVersionNumber === "undefined" || patchVersion > minimumVersionNumber;
412
+ const decodeResult = await decodeSyncdPatch(
413
+ syncd,
414
+ name,
415
+ newState,
416
+ getAppStateSyncKey,
417
+ shouldMutate
418
+ ? (mutation) => {
419
+ const index = mutation.syncAction.index?.toString();
420
+ mutationMap[index] = mutation;
421
+ }
422
+ : () => {},
423
+ true
424
+ );
425
+ newState.hash = decodeResult.hash;
426
+ newState.indexValueMap = decodeResult.indexValueMap;
427
+ if (validateMacs) {
428
+ const base64Key = Buffer.from(keyId.id).toString("base64");
429
+ const keyEnc = await getAppStateSyncKey(base64Key);
430
+ if (!keyEnc) {
431
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
432
+ }
433
+ const result = await mutationKeys(keyEnc.keyData);
434
+ const computedSnapshotMac = generateSnapshotMac(
435
+ newState.hash,
436
+ newState.version,
437
+ name,
438
+ result.snapshotMacKey
439
+ );
440
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
441
+ throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
442
+ }
443
+ }
444
+ syncd.mutations = [];
445
+ }
446
+ return { state: newState, mutationMap: mutationMap };
447
+ };
448
+ const chatModificationToAppPatch = (mod, jid) => {
449
+ const OP = proto.SyncdMutation.SyncdOperation;
450
+ const getMessageRange = (lastMessages) => {
451
+ let messageRange;
452
+ if (Array.isArray(lastMessages)) {
453
+ const lastMsg = lastMessages[lastMessages.length - 1];
454
+ messageRange = {
455
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
456
+ messages: lastMessages?.length
457
+ ? lastMessages.map((m) => {
458
+ if (!m.key?.id || !m.key?.remoteJid) {
459
+ throw new Boom("Incomplete key", { statusCode: 400, data: m });
460
+ }
461
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
462
+ throw new Boom("Expected not from me message to have participant", {
463
+ statusCode: 400,
464
+ data: m,
465
+ });
466
+ }
467
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
468
+ throw new Boom("Missing timestamp in last message list", {
469
+ statusCode: 400,
470
+ data: m,
471
+ });
472
+ }
473
+ if (m.key.participant) {
474
+ m.key.participant = jidNormalizedUser(m.key.participant);
475
+ }
476
+ return m;
477
+ })
478
+ : undefined,
479
+ };
480
+ } else {
481
+ messageRange = lastMessages;
482
+ }
483
+ return messageRange;
484
+ };
485
+ let patch;
486
+ if ("mute" in mod) {
487
+ patch = {
488
+ syncAction: {
489
+ muteAction: {
490
+ muted: !!mod.mute,
491
+ muteEndTimestamp: mod.mute || undefined,
492
+ },
493
+ },
494
+ index: ["mute", jid],
495
+ type: "regular_high",
496
+ apiVersion: 2,
497
+ operation: OP.SET,
498
+ };
499
+ } else if ("archive" in mod) {
500
+ patch = {
501
+ syncAction: {
502
+ archiveChatAction: {
503
+ archived: !!mod.archive,
504
+ messageRange: getMessageRange(mod.lastMessages),
505
+ },
506
+ },
507
+ index: ["archive", jid],
508
+ type: "regular_low",
509
+ apiVersion: 3,
510
+ operation: OP.SET,
511
+ };
512
+ } else if ("markRead" in mod) {
513
+ patch = {
514
+ syncAction: {
515
+ markChatAsReadAction: {
516
+ read: mod.markRead,
517
+ messageRange: getMessageRange(mod.lastMessages),
518
+ },
519
+ },
520
+ index: ["markChatAsRead", jid],
521
+ type: "regular_low",
522
+ apiVersion: 3,
523
+ operation: OP.SET,
524
+ };
525
+ } else if ("deleteForMe" in mod) {
526
+ const { timestamp: timestamp, key: key, deleteMedia: deleteMedia } = mod.deleteForMe;
527
+ patch = {
528
+ syncAction: {
529
+ deleteMessageForMeAction: {
530
+ deleteMedia: deleteMedia,
531
+ messageTimestamp: timestamp,
532
+ },
533
+ },
534
+ index: ["deleteMessageForMe", jid, key.id, key.fromMe ? "1" : "0", "0"],
535
+ type: "regular_high",
536
+ apiVersion: 3,
537
+ operation: OP.SET,
538
+ };
539
+ } else if ("clear" in mod) {
540
+ patch = {
541
+ syncAction: {
542
+ clearChatAction: { messageRange: getMessageRange(mod.lastMessages) },
543
+ },
544
+ index: ["clearChat", jid, "1", "0"],
545
+ type: "regular_high",
546
+ apiVersion: 6,
547
+ operation: OP.SET,
548
+ };
549
+ } else if ("pin" in mod) {
550
+ patch = {
551
+ syncAction: { pinAction: { pinned: !!mod.pin } },
552
+ index: ["pin_v1", jid],
553
+ type: "regular_low",
554
+ apiVersion: 5,
555
+ operation: OP.SET,
556
+ };
557
+ } else if ("contact" in mod) {
558
+ patch = {
559
+ syncAction: { contactAction: mod.contact || {} },
560
+ index: ["contact", jid],
561
+ type: "critical_unblock_low",
562
+ apiVersion: 2,
563
+ operation: mod.contact ? OP.SET : OP.REMOVE,
564
+ };
565
+ } else if ("disableLinkPreviews" in mod) {
566
+ patch = {
567
+ syncAction: {
568
+ privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {},
569
+ },
570
+ index: ["setting_disableLinkPreviews"],
571
+ type: "regular",
572
+ apiVersion: 8,
573
+ operation: OP.SET,
574
+ };
575
+ } else if ("star" in mod) {
576
+ const key = mod.star.messages[0];
577
+ patch = {
578
+ syncAction: { starAction: { starred: !!mod.star.star } },
579
+ index: ["star", jid, key.id, key.fromMe ? "1" : "0", "0"],
580
+ type: "regular_low",
581
+ apiVersion: 2,
582
+ operation: OP.SET,
583
+ };
584
+ } else if ("delete" in mod) {
585
+ patch = {
586
+ syncAction: {
587
+ deleteChatAction: { messageRange: getMessageRange(mod.lastMessages) },
588
+ },
589
+ index: ["deleteChat", jid, "1"],
590
+ type: "regular_high",
591
+ apiVersion: 6,
592
+ operation: OP.SET,
593
+ };
594
+ } else if ("pushNameSetting" in mod) {
595
+ patch = {
596
+ syncAction: { pushNameSetting: { name: mod.pushNameSetting } },
597
+ index: ["setting_pushName"],
598
+ type: "critical_block",
599
+ apiVersion: 1,
600
+ operation: OP.SET,
601
+ };
602
+ } else if ("quickReply" in mod) {
603
+ patch = {
604
+ syncAction: {
605
+ quickReplyAction: {
606
+ count: 0,
607
+ deleted: mod.quickReply.deleted || false,
608
+ keywords: [],
609
+ message: mod.quickReply.message || "",
610
+ shortcut: mod.quickReply.shortcut || "",
611
+ },
612
+ },
613
+ index: [
614
+ "quick_reply",
615
+ mod.quickReply.timestamp || String(Math.floor(Date.now() / 1e3)),
616
+ ],
617
+ type: "regular",
618
+ apiVersion: 2,
619
+ operation: OP.SET,
620
+ };
621
+ } else if ("addLabel" in mod) {
622
+ patch = {
623
+ syncAction: {
624
+ labelEditAction: {
625
+ name: mod.addLabel.name,
626
+ color: mod.addLabel.color,
627
+ predefinedId: mod.addLabel.predefinedId,
628
+ deleted: mod.addLabel.deleted,
629
+ },
630
+ },
631
+ index: ["label_edit", mod.addLabel.id],
632
+ type: "regular",
633
+ apiVersion: 3,
634
+ operation: OP.SET,
635
+ };
636
+ } else if ("addChatLabel" in mod) {
637
+ patch = {
638
+ syncAction: { labelAssociationAction: { labeled: true } },
639
+ index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
640
+ type: "regular",
641
+ apiVersion: 3,
642
+ operation: OP.SET,
643
+ };
644
+ } else if ("removeChatLabel" in mod) {
645
+ patch = {
646
+ syncAction: { labelAssociationAction: { labeled: false } },
647
+ index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
648
+ type: "regular",
649
+ apiVersion: 3,
650
+ operation: OP.SET,
651
+ };
652
+ } else if ("addMessageLabel" in mod) {
653
+ patch = {
654
+ syncAction: { labelAssociationAction: { labeled: true } },
655
+ index: [
656
+ LabelAssociationType.Message,
657
+ mod.addMessageLabel.labelId,
658
+ jid,
659
+ mod.addMessageLabel.messageId,
660
+ "0",
661
+ "0",
662
+ ],
663
+ type: "regular",
664
+ apiVersion: 3,
665
+ operation: OP.SET,
666
+ };
667
+ } else if ("removeMessageLabel" in mod) {
668
+ patch = {
669
+ syncAction: { labelAssociationAction: { labeled: false } },
670
+ index: [
671
+ LabelAssociationType.Message,
672
+ mod.removeMessageLabel.labelId,
673
+ jid,
674
+ mod.removeMessageLabel.messageId,
675
+ "0",
676
+ "0",
677
+ ],
678
+ type: "regular",
679
+ apiVersion: 3,
680
+ operation: OP.SET,
681
+ };
682
+ } else {
683
+ throw new Boom("not supported");
684
+ }
685
+ patch.syncAction.timestamp = Date.now();
686
+ return patch;
687
+ };
688
+ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
689
+ const isInitialSync = !!initialSyncOpts;
690
+ const accountSettings = initialSyncOpts?.accountSettings;
691
+ logger?.trace(
692
+ { syncAction: syncAction, initialSync: !!initialSyncOpts },
693
+ "processing sync action"
694
+ );
695
+ const {
696
+ syncAction: { value: action },
697
+ index: [type, id, msgId, fromMe],
698
+ } = syncAction;
699
+ if (action?.muteAction) {
700
+ ev.emit("chats.update", [
701
+ {
702
+ id: id,
703
+ muteEndTime: action.muteAction?.muted
704
+ ? toNumber(action.muteAction.muteEndTimestamp)
705
+ : null,
706
+ conditional: getChatUpdateConditional(id, undefined),
707
+ },
708
+ ]);
709
+ } else if (action?.archiveChatAction || type === "archive" || type === "unarchive") {
710
+ const archiveAction = action?.archiveChatAction;
711
+ const isArchived = archiveAction ? archiveAction.archived : type === "archive";
712
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
713
+ ev.emit("chats.update", [
714
+ {
715
+ id: id,
716
+ archived: isArchived,
717
+ conditional: getChatUpdateConditional(id, msgRange),
718
+ },
719
+ ]);
720
+ } else if (action?.markChatAsReadAction) {
721
+ const markReadAction = action.markChatAsReadAction;
722
+ const isNullUpdate = isInitialSync && markReadAction.read;
723
+ ev.emit("chats.update", [
724
+ {
725
+ id: id,
726
+ unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
727
+ conditional: getChatUpdateConditional(id, markReadAction?.messageRange),
728
+ },
729
+ ]);
730
+ } else if (action?.deleteMessageForMeAction || type === "deleteMessageForMe") {
731
+ ev.emit("messages.delete", {
732
+ keys: [{ remoteJid: id, id: msgId, fromMe: fromMe === "1" }],
733
+ });
734
+ } else if (action?.contactAction) {
735
+ const lidJid = action.contactAction.lidJid;
736
+ const idIsPn = isPnUser(id);
737
+ ev.emit("contacts.upsert", [
738
+ {
739
+ id: id,
740
+ name: action.contactAction.fullName,
741
+ lid: action.contactAction.lidJid || undefined,
742
+ phoneNumber: action.contactAction.pnJid || (idIsPn ? id : undefined),
743
+ },
744
+ ]);
745
+ // Added for AsepXyz Baileys (ported from PouCode): keep LID<->PN mapping in sync
746
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
747
+ ev.emit("lid-mapping.update", { lid: lidJid, pn: id });
748
+ }
749
+ } else if (action?.pushNameSetting) {
750
+ const name = action?.pushNameSetting?.name;
751
+ if (name && me?.name !== name) {
752
+ ev.emit("creds.update", { me: { ...me, name: name } });
753
+ }
754
+ } else if (action?.pinAction) {
755
+ ev.emit("chats.update", [
756
+ {
757
+ id: id,
758
+ pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
759
+ conditional: getChatUpdateConditional(id, undefined),
760
+ },
761
+ ]);
762
+ } else if (action?.unarchiveChatsSetting) {
763
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
764
+ ev.emit("creds.update", {
765
+ accountSettings: { unarchiveChats: unarchiveChats },
766
+ });
767
+ logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
768
+ if (accountSettings) {
769
+ accountSettings.unarchiveChats = unarchiveChats;
770
+ }
771
+ } else if (action?.starAction || type === "star") {
772
+ let starred = action?.starAction?.starred;
773
+ if (typeof starred !== "boolean") {
774
+ starred = syncAction.index[syncAction.index.length - 1] === "1";
775
+ }
776
+ ev.emit("messages.update", [
777
+ {
778
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === "1" },
779
+ update: { starred: starred },
780
+ },
781
+ ]);
782
+ } else if (action?.deleteChatAction || type === "deleteChat") {
783
+ if (!isInitialSync) {
784
+ ev.emit("chats.delete", [id]);
785
+ }
786
+ } else if (action?.labelEditAction) {
787
+ const {
788
+ name: name,
789
+ color: color,
790
+ deleted: deleted,
791
+ predefinedId: predefinedId,
792
+ } = action.labelEditAction;
793
+ ev.emit("labels.edit", {
794
+ id: id,
795
+ name: name,
796
+ color: color,
797
+ deleted: deleted,
798
+ predefinedId: predefinedId ? String(predefinedId) : undefined,
799
+ });
800
+ } else if (action?.labelAssociationAction) {
801
+ ev.emit("labels.association", {
802
+ type: action.labelAssociationAction.labeled ? "add" : "remove",
803
+ association:
804
+ type === LabelAssociationType.Chat
805
+ ? {
806
+ type: LabelAssociationType.Chat,
807
+ chatId: syncAction.index[2],
808
+ labelId: syncAction.index[1],
809
+ }
810
+ : {
811
+ type: LabelAssociationType.Message,
812
+ chatId: syncAction.index[2],
813
+ messageId: syncAction.index[3],
814
+ labelId: syncAction.index[1],
815
+ },
816
+ });
817
+ } else if (action?.localeSetting?.locale) {
818
+ ev.emit("settings.update", {
819
+ setting: "locale",
820
+ value: action.localeSetting.locale,
821
+ });
822
+ } else if (action?.timeFormatAction) {
823
+ ev.emit("settings.update", {
824
+ setting: "timeFormat",
825
+ value: action.timeFormatAction,
826
+ });
827
+ } else if (action?.pnForLidChatAction) {
828
+ if (action.pnForLidChatAction.pnJid) {
829
+ ev.emit("lid-mapping.update", {
830
+ lid: id,
831
+ pn: action.pnForLidChatAction.pnJid,
832
+ });
833
+ }
834
+ } else if (action?.privacySettingRelayAllCalls) {
835
+ ev.emit("settings.update", {
836
+ setting: "privacySettingRelayAllCalls",
837
+ value: action.privacySettingRelayAllCalls,
838
+ });
839
+ } else if (action?.statusPrivacy) {
840
+ ev.emit("settings.update", {
841
+ setting: "statusPrivacy",
842
+ value: action.statusPrivacy,
843
+ });
844
+ } else if (action?.lockChatAction) {
845
+ ev.emit("chats.lock", { id: id, locked: !!action.lockChatAction.locked });
846
+ } else if (action?.privacySettingDisableLinkPreviewsAction) {
847
+ ev.emit("settings.update", {
848
+ setting: "disableLinkPreviews",
849
+ value: action.privacySettingDisableLinkPreviewsAction,
850
+ });
851
+ } else if (action?.notificationActivitySettingAction?.notificationActivitySetting) {
852
+ ev.emit("settings.update", {
853
+ setting: "notificationActivitySetting",
854
+ value: action.notificationActivitySettingAction.notificationActivitySetting,
855
+ });
856
+ } else if (action?.lidContactAction) {
857
+ ev.emit("contacts.upsert", [
858
+ {
859
+ id: id,
860
+ name: action.lidContactAction.fullName,
861
+ lid: id,
862
+ phoneNumber: undefined,
863
+ },
864
+ ]);
865
+ } else if (action?.privacySettingChannelsPersonalisedRecommendationAction) {
866
+ ev.emit("settings.update", {
867
+ setting: "channelsPersonalisedRecommendation",
868
+ value: action.privacySettingChannelsPersonalisedRecommendationAction,
869
+ });
870
+ } else {
871
+ logger?.debug({ syncAction: syncAction, id: id }, "unprocessable update");
872
+ }
873
+ function getChatUpdateConditional(id, msgRange) {
874
+ return isInitialSync
875
+ ? (data) => {
876
+ const chat = data.historySets.chats[id] || data.chatUpserts[id];
877
+ if (chat) {
878
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
879
+ }
880
+ }
881
+ : undefined;
882
+ }
883
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
884
+ const lastMsgTimestamp = Number(
885
+ msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0
886
+ );
887
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
888
+ return lastMsgTimestamp >= chatLastMsgTimestamp;
889
+ }
890
+ };
891
+ module.exports = {
892
+ mutationKeys: mutationKeys,
893
+ newLTHashState: newLTHashState,
894
+ encodeSyncdPatch: encodeSyncdPatch,
895
+ decodeSyncdMutations: decodeSyncdMutations,
896
+ decodeSyncdPatch: decodeSyncdPatch,
897
+ extractSyncdPatches: extractSyncdPatches,
898
+ downloadExternalBlob: downloadExternalBlob,
899
+ downloadExternalPatch: downloadExternalPatch,
900
+ decodeSyncdSnapshot: decodeSyncdSnapshot,
901
+ decodePatches: decodePatches,
902
+ chatModificationToAppPatch: chatModificationToAppPatch,
903
+ processSyncAction: processSyncAction,
904
+ };