nrx-bails 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1541 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.d.ts +2 -0
  6. package/WAProto/index.js +169661 -0
  7. package/lib/Defaults/index.d.ts +113 -0
  8. package/lib/Defaults/index.js +156 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Defaults/ye-bail-version.json +3 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/ciphertext-message.js +41 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  14. package/lib/Signal/Group/group-session-builder.js +90 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +12 -0
  16. package/lib/Signal/Group/group_cipher.js +122 -0
  17. package/lib/Signal/Group/index.d.ts +22 -0
  18. package/lib/Signal/Group/index.js +83 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  20. package/lib/Signal/Group/keyhelper.js +81 -0
  21. package/lib/Signal/Group/queue-job.d.ts +3 -0
  22. package/lib/Signal/Group/queue-job.js +83 -0
  23. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  24. package/lib/Signal/Group/sender-chain-key.js +60 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +92 -0
  27. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  28. package/lib/Signal/Group/sender-key-message.js +95 -0
  29. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  30. package/lib/Signal/Group/sender-key-name.js +77 -0
  31. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  32. package/lib/Signal/Group/sender-key-record.js +79 -0
  33. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  34. package/lib/Signal/Group/sender-key-state.js +125 -0
  35. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  36. package/lib/Signal/Group/sender-message-key.js +55 -0
  37. package/lib/Signal/libsignal.d.ts +37 -0
  38. package/lib/Signal/libsignal.js +200 -0
  39. package/lib/Socket/Client/index.d.ts +1 -0
  40. package/lib/Socket/Client/index.js +44 -0
  41. package/lib/Socket/Client/types.d.ts +7 -0
  42. package/lib/Socket/Client/types.js +39 -0
  43. package/lib/Socket/Client/websocket.d.ts +19 -0
  44. package/lib/Socket/Client/websocket.js +137 -0
  45. package/lib/Socket/business.d.ts +329 -0
  46. package/lib/Socket/business.js +286 -0
  47. package/lib/Socket/chats.d.ts +84 -0
  48. package/lib/Socket/chats.js +1022 -0
  49. package/lib/Socket/groups.d.ts +216 -0
  50. package/lib/Socket/groups.js +358 -0
  51. package/lib/Socket/index.d.ts +330 -0
  52. package/lib/Socket/index.js +36 -0
  53. package/lib/Socket/messages-recv.d.ts +271 -0
  54. package/lib/Socket/messages-recv.js +1079 -0
  55. package/lib/Socket/messages-send.d.ts +258 -0
  56. package/lib/Socket/messages-send.js +1190 -0
  57. package/lib/Socket/newsletter.d.ts +253 -0
  58. package/lib/Socket/newsletter.js +362 -0
  59. package/lib/Socket/registration.d.ts +361 -0
  60. package/lib/Socket/registration.js +179 -0
  61. package/lib/Socket/socket.d.ts +33 -0
  62. package/lib/Socket/socket.js +699 -0
  63. package/lib/Socket/usync.d.ts +27 -0
  64. package/lib/Socket/usync.js +96 -0
  65. package/lib/Store/index.d.ts +3 -0
  66. package/lib/Store/index.js +36 -0
  67. package/lib/Store/make-cache-manager-auth-state.d.ts +16 -0
  68. package/lib/Store/make-cache-manager-auth-state.js +118 -0
  69. package/lib/Store/make-in-memory-store.d.ts +64 -0
  70. package/lib/Store/make-in-memory-store.js +465 -0
  71. package/lib/Store/make-ordered-dictionary.d.ts +14 -0
  72. package/lib/Store/make-ordered-dictionary.js +107 -0
  73. package/lib/Store/object-repository.d.ts +11 -0
  74. package/lib/Store/object-repository.js +53 -0
  75. package/lib/Types/Auth.d.ts +1 -0
  76. package/lib/Types/Auth.js +28 -0
  77. package/lib/Types/Call.d.ts +1 -0
  78. package/lib/Types/Call.js +28 -0
  79. package/lib/Types/Chat.d.ts +2 -0
  80. package/lib/Types/Chat.js +30 -0
  81. package/lib/Types/Contact.d.ts +1 -0
  82. package/lib/Types/Contact.js +28 -0
  83. package/lib/Types/Events.d.ts +1 -0
  84. package/lib/Types/Events.js +28 -0
  85. package/lib/Types/GroupMetadata.d.ts +1 -0
  86. package/lib/Types/GroupMetadata.js +28 -0
  87. package/lib/Types/Label.d.ts +2 -0
  88. package/lib/Types/Label.js +53 -0
  89. package/lib/Types/LabelAssociation.d.ts +2 -0
  90. package/lib/Types/LabelAssociation.js +35 -0
  91. package/lib/Types/Message.d.ts +2 -0
  92. package/lib/Types/Message.js +33 -0
  93. package/lib/Types/Newsletter.d.ts +4 -0
  94. package/lib/Types/Newsletter.js +62 -0
  95. package/lib/Types/Product.d.ts +1 -0
  96. package/lib/Types/Product.js +28 -0
  97. package/lib/Types/Signal.d.ts +1 -0
  98. package/lib/Types/Signal.js +28 -0
  99. package/lib/Types/Socket.d.ts +1 -0
  100. package/lib/Types/Socket.js +28 -0
  101. package/lib/Types/State.d.ts +1 -0
  102. package/lib/Types/State.js +28 -0
  103. package/lib/Types/USync.d.ts +1 -0
  104. package/lib/Types/USync.js +28 -0
  105. package/lib/Types/index.d.ts +2 -0
  106. package/lib/Types/index.js +68 -0
  107. package/lib/Utils/auth-utils.d.ts +63 -0
  108. package/lib/Utils/auth-utils.js +248 -0
  109. package/lib/Utils/browser-utils.d.ts +3 -0
  110. package/lib/Utils/browser-utils.js +61 -0
  111. package/lib/Utils/business.d.ts +53 -0
  112. package/lib/Utils/business.js +260 -0
  113. package/lib/Utils/chat-utils.d.ts +253 -0
  114. package/lib/Utils/chat-utils.js +756 -0
  115. package/lib/Utils/crypto.d.ts +43 -0
  116. package/lib/Utils/crypto.js +219 -0
  117. package/lib/Utils/decode-wa-message.d.ts +61 -0
  118. package/lib/Utils/decode-wa-message.js +233 -0
  119. package/lib/Utils/event-buffer.d.ts +17 -0
  120. package/lib/Utils/event-buffer.js +544 -0
  121. package/lib/Utils/generics.d.ts +89 -0
  122. package/lib/Utils/generics.js +471 -0
  123. package/lib/Utils/history.d.ts +59 -0
  124. package/lib/Utils/history.js +120 -0
  125. package/lib/Utils/index.d.ts +1 -0
  126. package/lib/Utils/index.js +61 -0
  127. package/lib/Utils/link-preview.d.ts +19 -0
  128. package/lib/Utils/link-preview.js +152 -0
  129. package/lib/Utils/logger.d.ts +3 -0
  130. package/lib/Utils/logger.js +33 -0
  131. package/lib/Utils/lt-hash.d.ts +13 -0
  132. package/lib/Utils/lt-hash.js +77 -0
  133. package/lib/Utils/make-mutex.d.ts +7 -0
  134. package/lib/Utils/make-mutex.js +69 -0
  135. package/lib/Utils/message-retry-manager.d.ts +34 -0
  136. package/lib/Utils/message-retry-manager.js +154 -0
  137. package/lib/Utils/messages-media.d.ts +137 -0
  138. package/lib/Utils/messages-media.js +1024 -0
  139. package/lib/Utils/messages.d.ts +66 -0
  140. package/lib/Utils/messages.js +1407 -0
  141. package/lib/Utils/noise-handler.d.ts +21 -0
  142. package/lib/Utils/noise-handler.js +176 -0
  143. package/lib/Utils/pre-key-manager.d.ts +13 -0
  144. package/lib/Utils/pre-key-manager.js +93 -0
  145. package/lib/Utils/process-message.d.ts +40 -0
  146. package/lib/Utils/process-message.js +430 -0
  147. package/lib/Utils/signal.d.ts +72 -0
  148. package/lib/Utils/signal.js +179 -0
  149. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  150. package/lib/Utils/use-multi-file-auth-state.js +151 -0
  151. package/lib/Utils/validate-connection.d.ts +43 -0
  152. package/lib/Utils/validate-connection.js +255 -0
  153. package/lib/Utils/ye-bail-event-stream.d.ts +16 -0
  154. package/lib/Utils/ye-bail-event-stream.js +89 -0
  155. package/lib/WABinary/constants.d.ts +23 -0
  156. package/lib/WABinary/constants.js +1328 -0
  157. package/lib/WABinary/decode.d.ts +10 -0
  158. package/lib/WABinary/decode.js +291 -0
  159. package/lib/WABinary/encode.d.ts +2 -0
  160. package/lib/WABinary/encode.js +276 -0
  161. package/lib/WABinary/generic-utils.d.ts +16 -0
  162. package/lib/WABinary/generic-utils.js +155 -0
  163. package/lib/WABinary/index.d.ts +1 -0
  164. package/lib/WABinary/index.js +47 -0
  165. package/lib/WABinary/jid-utils.d.ts +34 -0
  166. package/lib/WABinary/jid-utils.js +111 -0
  167. package/lib/WABinary/types.d.ts +1 -0
  168. package/lib/WABinary/types.js +28 -0
  169. package/lib/WAM/BinaryInfo.d.ts +8 -0
  170. package/lib/WAM/BinaryInfo.js +39 -0
  171. package/lib/WAM/constants.d.ts +35374 -0
  172. package/lib/WAM/constants.js +15376 -0
  173. package/lib/WAM/encode.d.ts +2 -0
  174. package/lib/WAM/encode.js +181 -0
  175. package/lib/WAM/index.d.ts +1 -0
  176. package/lib/WAM/index.js +45 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +14 -0
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +58 -0
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  180. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +83 -0
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +56 -0
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  184. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +68 -0
  185. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  186. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +79 -0
  187. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  188. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +50 -0
  189. package/lib/WAUSync/Protocols/index.d.ts +1 -0
  190. package/lib/WAUSync/Protocols/index.js +46 -0
  191. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  192. package/lib/WAUSync/USyncQuery.js +115 -0
  193. package/lib/WAUSync/USyncUser.d.ts +13 -0
  194. package/lib/WAUSync/USyncUser.js +52 -0
  195. package/lib/WAUSync/index.d.ts +1 -0
  196. package/lib/WAUSync/index.js +45 -0
  197. package/lib/index.js +81 -0
  198. package/package.json +113 -0
  199. package/requirements.js +32 -0
@@ -0,0 +1,756 @@
1
+ /**
2
+ * ╔═══════════════════════════════════════════════════════════╗
3
+ * ║ NEROX - WhatsApp API Library ║
4
+ * ║ Premium Edition ║
5
+ * ╚═══════════════════════════════════════════════════════════╝
6
+ *
7
+ * @package nerox-bails
8
+ * @version 0.1.0
9
+ * @author NEROX Development Team
10
+ * @copyright Copyright (c) 2025 NEROX. All rights reserved.
11
+ * @license MIT License
12
+ *
13
+ * Permission is hereby granted, free of charge, to any person obtaining
14
+ * a copy of this software and associated documentation files (the "Software"),
15
+ * to deal in the Software without restriction, including without limitation
16
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
17
+ * and/or sell copies of the Software, and to permit persons to whom the
18
+ * Software is furnished to do so, subject to the following conditions:
19
+ *
20
+ * The above copyright notice and this permission notice shall be included
21
+ * in all copies or substantial portions of the Software.
22
+ *
23
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
26
+ */
27
+ "use strict";
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.processSyncAction = exports.chatModificationToAppPatch = exports.decodePatches = exports.decodeSyncdSnapshot = exports.downloadExternalPatch = exports.downloadExternalBlob = exports.extractSyncdPatches = exports.decodeSyncdPatch = exports.decodeSyncdMutations = exports.encodeSyncdPatch = exports.newLTHashState = void 0;
30
+ const boom_1 = require("@hapi/boom");
31
+ const WAProto_1 = require("../../WAProto");
32
+ const WABinary_1 = require("../WABinary");
33
+ const LabelAssociation_1 = require("../Types/LabelAssociation");
34
+ const crypto_1 = require("./crypto");
35
+ const generics_1 = require("./generics");
36
+ const lt_hash_1 = require("./lt-hash");
37
+ const messages_media_1 = require("./messages-media");
38
+ const mutationKeys = async (keydata) => {
39
+ const expanded = await (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
40
+ return {
41
+ indexKey: expanded.slice(0, 32),
42
+ valueEncryptionKey: expanded.slice(32, 64),
43
+ valueMacKey: expanded.slice(64, 96),
44
+ snapshotMacKey: expanded.slice(96, 128),
45
+ patchMacKey: expanded.slice(128, 160)
46
+ };
47
+ };
48
+ const generateMac = (operation, data, keyId, key) => {
49
+ const getKeyData = () => {
50
+ let r;
51
+ switch (operation) {
52
+ case WAProto_1.proto.SyncdMutation.SyncdOperation.SET:
53
+ r = 0x01;
54
+ break;
55
+ case WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE:
56
+ r = 0x02;
57
+ break;
58
+ }
59
+ const buff = Buffer.from([r]);
60
+ return Buffer.concat([buff, Buffer.from(keyId, 'base64')]);
61
+ };
62
+ const keyData = getKeyData();
63
+ const last = Buffer.alloc(8);
64
+ last.set([keyData.length], last.length - 1);
65
+ const total = Buffer.concat([keyData, data, last]);
66
+ const hmac = (0, crypto_1.hmacSign)(total, key, 'sha512');
67
+ return hmac.slice(0, 32);
68
+ };
69
+ const to64BitNetworkOrder = (e) => {
70
+ const buff = Buffer.alloc(8);
71
+ buff.writeUint32BE(e, 4);
72
+ return buff;
73
+ };
74
+ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
75
+ indexValueMap = { ...indexValueMap };
76
+ const addBuffs = [];
77
+ const subBuffs = [];
78
+ return {
79
+ mix: ({ indexMac, valueMac, operation }) => {
80
+ const indexMacBase64 = Buffer.from(indexMac).toString('base64');
81
+ const prevOp = indexValueMap[indexMacBase64];
82
+ if (operation === WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE) {
83
+ if (!prevOp) {
84
+ throw new boom_1.Boom('tried remove, but no previous op', { data: { indexMac, valueMac } });
85
+ }
86
+
87
+ delete indexValueMap[indexMacBase64];
88
+ }
89
+ else {
90
+ addBuffs.push(new Uint8Array(valueMac).buffer);
91
+
92
+ indexValueMap[indexMacBase64] = { valueMac };
93
+ }
94
+ if (prevOp) {
95
+ subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
96
+ }
97
+ },
98
+ finish: async () => {
99
+ const hashArrayBuffer = new Uint8Array(hash).buffer;
100
+ const result = await lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
101
+ const buffer = Buffer.from(result);
102
+ return {
103
+ hash: buffer,
104
+ indexValueMap
105
+ };
106
+ }
107
+ };
108
+ };
109
+ const generateSnapshotMac = (lthash, version, name, key) => {
110
+ const total = Buffer.concat([
111
+ lthash,
112
+ to64BitNetworkOrder(version),
113
+ Buffer.from(name, 'utf-8')
114
+ ]);
115
+ return (0, crypto_1.hmacSign)(total, key, 'sha256');
116
+ };
117
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
118
+ const total = Buffer.concat([
119
+ snapshotMac,
120
+ ...valueMacs,
121
+ to64BitNetworkOrder(version),
122
+ Buffer.from(type, 'utf-8')
123
+ ]);
124
+ return (0, crypto_1.hmacSign)(total, key);
125
+ };
126
+ const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
127
+ exports.newLTHashState = newLTHashState;
128
+ const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
129
+ const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
130
+ if (!key) {
131
+ throw new boom_1.Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 });
132
+ }
133
+ const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
134
+ state = { ...state, indexValueMap: { ...state.indexValueMap } };
135
+ const indexBuffer = Buffer.from(JSON.stringify(index));
136
+ const dataProto = WAProto_1.proto.SyncActionData.fromObject({
137
+ index: indexBuffer,
138
+ value: syncAction,
139
+ padding: new Uint8Array(0),
140
+ version: apiVersion
141
+ });
142
+ const encoded = WAProto_1.proto.SyncActionData.encode(dataProto).finish();
143
+ const keyValue = await mutationKeys(key.keyData);
144
+ const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
145
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
146
+ const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
147
+
148
+ const generator = makeLtHashGenerator(state);
149
+ generator.mix({ indexMac, valueMac, operation });
150
+ Object.assign(state, await generator.finish());
151
+ state.version += 1;
152
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
153
+ const patch = {
154
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
155
+ snapshotMac: snapshotMac,
156
+ keyId: { id: encKeyId },
157
+ mutations: [
158
+ {
159
+ operation: operation,
160
+ record: {
161
+ index: {
162
+ blob: indexMac
163
+ },
164
+ value: {
165
+ blob: Buffer.concat([encValue, valueMac])
166
+ },
167
+ keyId: { id: encKeyId }
168
+ }
169
+ }
170
+ ]
171
+ };
172
+ const base64Index = indexMac.toString('base64');
173
+ state.indexValueMap[base64Index] = { valueMac };
174
+ return { patch, state };
175
+ };
176
+ exports.encodeSyncdPatch = encodeSyncdPatch;
177
+ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
178
+ const ltGenerator = makeLtHashGenerator(initialState);
179
+
180
+
181
+
182
+ for (const msgMutation of msgMutations) {
183
+
184
+
185
+ const operation = 'operation' in msgMutation ? msgMutation.operation : WAProto_1.proto.SyncdMutation.SyncdOperation.SET;
186
+ const record = ('record' in msgMutation && !!msgMutation.record) ? msgMutation.record : msgMutation;
187
+ const key = await getKey(record.keyId.id);
188
+ const content = Buffer.from(record.value.blob);
189
+ const encContent = content.slice(0, -32);
190
+ const ogValueMac = content.slice(-32);
191
+ if (validateMacs) {
192
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
193
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
194
+ throw new boom_1.Boom('HMAC content verification failed');
195
+ }
196
+ }
197
+ const result = (0, crypto_1.aesDecrypt)(encContent, key.valueEncryptionKey);
198
+ const syncAction = WAProto_1.proto.SyncActionData.decode(result);
199
+ if (validateMacs) {
200
+ const hmac = (0, crypto_1.hmacSign)(syncAction.index, key.indexKey);
201
+ if (Buffer.compare(hmac, record.index.blob) !== 0) {
202
+ throw new boom_1.Boom('HMAC index verification failed');
203
+ }
204
+ }
205
+ const indexStr = Buffer.from(syncAction.index).toString();
206
+ onMutation({ syncAction, index: JSON.parse(indexStr) });
207
+ ltGenerator.mix({
208
+ indexMac: record.index.blob,
209
+ valueMac: ogValueMac,
210
+ operation: operation
211
+ });
212
+ }
213
+ return await ltGenerator.finish();
214
+ async function getKey(keyId) {
215
+ const base64Key = Buffer.from(keyId).toString('base64');
216
+ const keyEnc = await getAppStateSyncKey(base64Key);
217
+ if (!keyEnc) {
218
+ throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`, { statusCode: 404, data: { msgMutations } });
219
+ }
220
+ return mutationKeys(keyEnc.keyData);
221
+ }
222
+ };
223
+ exports.decodeSyncdMutations = decodeSyncdMutations;
224
+ const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
225
+ if (validateMacs) {
226
+ const base64Key = Buffer.from(msg.keyId.id).toString('base64');
227
+ const mainKeyObj = await getAppStateSyncKey(base64Key);
228
+ if (!mainKeyObj) {
229
+ throw new boom_1.Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
230
+ }
231
+ const mainKey = await mutationKeys(mainKeyObj.keyData);
232
+ const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
233
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, generics_1.toNumber)(msg.version.version), name, mainKey.patchMacKey);
234
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
235
+ throw new boom_1.Boom('Invalid patch mac');
236
+ }
237
+ }
238
+ const result = await (0, exports.decodeSyncdMutations)(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
239
+ return result;
240
+ };
241
+ exports.decodeSyncdPatch = decodeSyncdPatch;
242
+ const extractSyncdPatches = async (result, options) => {
243
+ const syncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'sync');
244
+ const collectionNodes = (0, WABinary_1.getBinaryNodeChildren)(syncNode, 'collection');
245
+ const final = {};
246
+ await Promise.all(collectionNodes.map(async (collectionNode) => {
247
+ const patchesNode = (0, WABinary_1.getBinaryNodeChild)(collectionNode, 'patches');
248
+ const patches = (0, WABinary_1.getBinaryNodeChildren)(patchesNode || collectionNode, 'patch');
249
+ const snapshotNode = (0, WABinary_1.getBinaryNodeChild)(collectionNode, 'snapshot');
250
+ const syncds = [];
251
+ const name = collectionNode.attrs.name;
252
+ const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
253
+ let snapshot = undefined;
254
+ if (snapshotNode && !!snapshotNode.content) {
255
+ if (!Buffer.isBuffer(snapshotNode)) {
256
+ snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
257
+ }
258
+ const blobRef = WAProto_1.proto.ExternalBlobReference.decode(snapshotNode.content);
259
+ const data = await (0, exports.downloadExternalBlob)(blobRef, options);
260
+ snapshot = WAProto_1.proto.SyncdSnapshot.decode(data);
261
+ }
262
+ for (let { content } of patches) {
263
+ if (content) {
264
+ if (!Buffer.isBuffer(content)) {
265
+ content = Buffer.from(Object.values(content));
266
+ }
267
+ const syncd = WAProto_1.proto.SyncdPatch.decode(content);
268
+ if (!syncd.version) {
269
+ syncd.version = { version: +collectionNode.attrs.version + 1 };
270
+ }
271
+ syncds.push(syncd);
272
+ }
273
+ }
274
+ final[name] = { patches: syncds, hasMorePatches, snapshot };
275
+ }));
276
+ return final;
277
+ };
278
+ exports.extractSyncdPatches = extractSyncdPatches;
279
+ const downloadExternalBlob = async (blob, options) => {
280
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(blob, 'md-app-state', { options });
281
+ const bufferArray = [];
282
+ for await (const chunk of stream) {
283
+ bufferArray.push(chunk);
284
+ }
285
+ return Buffer.concat(bufferArray);
286
+ };
287
+ exports.downloadExternalBlob = downloadExternalBlob;
288
+ const downloadExternalPatch = async (blob, options) => {
289
+ const buffer = await (0, exports.downloadExternalBlob)(blob, options);
290
+ const syncData = WAProto_1.proto.SyncdMutations.decode(buffer);
291
+ return syncData;
292
+ };
293
+ exports.downloadExternalPatch = downloadExternalPatch;
294
+ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
295
+ const newState = (0, exports.newLTHashState)();
296
+ newState.version = (0, generics_1.toNumber)(snapshot.version.version);
297
+ const mutationMap = {};
298
+ const areMutationsRequired = typeof minimumVersionNumber === 'undefined'
299
+ || newState.version > minimumVersionNumber;
300
+ const { hash, indexValueMap } = await (0, exports.decodeSyncdMutations)(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
301
+ ? (mutation) => {
302
+ var _a;
303
+ const index = (_a = mutation.syncAction.index) === null || _a === void 0 ? void 0 : _a.toString();
304
+ mutationMap[index] = mutation;
305
+ }
306
+ : () => { }, validateMacs);
307
+ newState.hash = hash;
308
+ newState.indexValueMap = indexValueMap;
309
+ if (validateMacs) {
310
+ const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
311
+ const keyEnc = await getAppStateSyncKey(base64Key);
312
+ if (!keyEnc) {
313
+ throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
314
+ }
315
+ const result = await mutationKeys(keyEnc.keyData);
316
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
317
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
318
+ throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
319
+ }
320
+ }
321
+ return {
322
+ state: newState,
323
+ mutationMap
324
+ };
325
+ };
326
+ exports.decodeSyncdSnapshot = decodeSyncdSnapshot;
327
+ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
328
+ var _a;
329
+ const newState = {
330
+ ...initial,
331
+ indexValueMap: { ...initial.indexValueMap }
332
+ };
333
+ const mutationMap = {};
334
+ for (let i = 0; i < syncds.length; i++) {
335
+ const syncd = syncds[i];
336
+ const { version, keyId, snapshotMac } = syncd;
337
+ if (syncd.externalMutations) {
338
+ logger === null || logger === void 0 ? void 0 : logger.trace({ name, version }, 'downloading external patch');
339
+ const ref = await (0, exports.downloadExternalPatch)(syncd.externalMutations, options);
340
+ logger === null || logger === void 0 ? void 0 : logger.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
341
+ (_a = syncd.mutations) === null || _a === void 0 ? void 0 : _a.push(...ref.mutations);
342
+ }
343
+ const patchVersion = (0, generics_1.toNumber)(version.version);
344
+ newState.version = patchVersion;
345
+ const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
346
+ const decodeResult = await (0, exports.decodeSyncdPatch)(syncd, name, newState, getAppStateSyncKey, shouldMutate
347
+ ? mutation => {
348
+ var _a;
349
+ const index = (_a = mutation.syncAction.index) === null || _a === void 0 ? void 0 : _a.toString();
350
+ mutationMap[index] = mutation;
351
+ }
352
+ : (() => { }), true);
353
+ newState.hash = decodeResult.hash;
354
+ newState.indexValueMap = decodeResult.indexValueMap;
355
+ if (validateMacs) {
356
+ const base64Key = Buffer.from(keyId.id).toString('base64');
357
+ const keyEnc = await getAppStateSyncKey(base64Key);
358
+ if (!keyEnc) {
359
+ throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
360
+ }
361
+ const result = await mutationKeys(keyEnc.keyData);
362
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
363
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
364
+ throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
365
+ }
366
+ }
367
+
368
+ syncd.mutations = [];
369
+ }
370
+ return { state: newState, mutationMap };
371
+ };
372
+ exports.decodePatches = decodePatches;
373
+ const chatModificationToAppPatch = (mod, jid) => {
374
+ const OP = WAProto_1.proto.SyncdMutation.SyncdOperation;
375
+ const getMessageRange = (lastMessages) => {
376
+ let messageRange;
377
+ if (Array.isArray(lastMessages)) {
378
+ const lastMsg = lastMessages[lastMessages.length - 1];
379
+ messageRange = {
380
+ lastMessageTimestamp: lastMsg === null || lastMsg === void 0 ? void 0 : lastMsg.messageTimestamp,
381
+ messages: (lastMessages === null || lastMessages === void 0 ? void 0 : lastMessages.length) ? lastMessages.map(m => {
382
+ var _a, _b;
383
+ if (!((_a = m.key) === null || _a === void 0 ? void 0 : _a.id) || !((_b = m.key) === null || _b === void 0 ? void 0 : _b.remoteJid)) {
384
+ throw new boom_1.Boom('Incomplete key', { statusCode: 400, data: m });
385
+ }
386
+ if ((0, WABinary_1.isJidGroup)(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
387
+ throw new boom_1.Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
388
+ }
389
+ if (!m.messageTimestamp || !(0, generics_1.toNumber)(m.messageTimestamp)) {
390
+ throw new boom_1.Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
391
+ }
392
+ if (m.key.participant) {
393
+ m.key.participant = (0, WABinary_1.jidNormalizedUser)(m.key.participant);
394
+ }
395
+ return m;
396
+ }) : undefined
397
+ };
398
+ }
399
+ else {
400
+ messageRange = lastMessages;
401
+ }
402
+ return messageRange;
403
+ };
404
+ let patch;
405
+ if ('mute' in mod) {
406
+ patch = {
407
+ syncAction: {
408
+ muteAction: {
409
+ muted: !!mod.mute,
410
+ muteEndTimestamp: mod.mute || undefined
411
+ }
412
+ },
413
+ index: ['mute', jid],
414
+ type: 'regular_high',
415
+ apiVersion: 2,
416
+ operation: OP.SET
417
+ };
418
+ }
419
+ else if ('archive' in mod) {
420
+ patch = {
421
+ syncAction: {
422
+ archiveChatAction: {
423
+ archived: !!mod.archive,
424
+ messageRange: getMessageRange(mod.lastMessages)
425
+ }
426
+ },
427
+ index: ['archive', jid],
428
+ type: 'regular_low',
429
+ apiVersion: 3,
430
+ operation: OP.SET
431
+ };
432
+ }
433
+ else if ('markRead' in mod) {
434
+ patch = {
435
+ syncAction: {
436
+ markChatAsReadAction: {
437
+ read: mod.markRead,
438
+ messageRange: getMessageRange(mod.lastMessages)
439
+ }
440
+ },
441
+ index: ['markChatAsRead', jid],
442
+ type: 'regular_low',
443
+ apiVersion: 3,
444
+ operation: OP.SET
445
+ };
446
+ }
447
+ else if ('deleteForMe' in mod) {
448
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
449
+ patch = {
450
+ syncAction: {
451
+ deleteMessageForMeAction: {
452
+ deleteMedia,
453
+ messageTimestamp: timestamp
454
+ }
455
+ },
456
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
457
+ type: 'regular_high',
458
+ apiVersion: 3,
459
+ operation: OP.SET
460
+ };
461
+ }
462
+ else if ('clear' in mod) {
463
+ patch = {
464
+ syncAction: {
465
+ clearChatAction: {}
466
+ },
467
+ index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
468
+ type: 'regular_high',
469
+ apiVersion: 6,
470
+ operation: OP.SET
471
+ };
472
+ }
473
+ else if ('pin' in mod) {
474
+ patch = {
475
+ syncAction: {
476
+ pinAction: {
477
+ pinned: !!mod.pin
478
+ }
479
+ },
480
+ index: ['pin_v1', jid],
481
+ type: 'regular_low',
482
+ apiVersion: 5,
483
+ operation: OP.SET
484
+ };
485
+ }
486
+ else if ('star' in mod) {
487
+ const key = mod.star.messages[0];
488
+ patch = {
489
+ syncAction: {
490
+ starAction: {
491
+ starred: !!mod.star.star
492
+ }
493
+ },
494
+ index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
495
+ type: 'regular_low',
496
+ apiVersion: 2,
497
+ operation: OP.SET
498
+ };
499
+ }
500
+ else if ('delete' in mod) {
501
+ patch = {
502
+ syncAction: {
503
+ deleteChatAction: {
504
+ messageRange: getMessageRange(mod.lastMessages),
505
+ }
506
+ },
507
+ index: ['deleteChat', jid, '1'],
508
+ type: 'regular_high',
509
+ apiVersion: 6,
510
+ operation: OP.SET
511
+ };
512
+ }
513
+ else if ('pushNameSetting' in mod) {
514
+ patch = {
515
+ syncAction: {
516
+ pushNameSetting: {
517
+ name: mod.pushNameSetting
518
+ }
519
+ },
520
+ index: ['setting_pushName'],
521
+ type: 'critical_block',
522
+ apiVersion: 1,
523
+ operation: OP.SET,
524
+ };
525
+ }
526
+ else if ('addChatLabel' in mod) {
527
+ patch = {
528
+ syncAction: {
529
+ labelAssociationAction: {
530
+ labeled: true,
531
+ }
532
+ },
533
+ index: [LabelAssociation_1.LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
534
+ type: 'regular',
535
+ apiVersion: 3,
536
+ operation: OP.SET,
537
+ };
538
+ }
539
+ else if ('removeChatLabel' in mod) {
540
+ patch = {
541
+ syncAction: {
542
+ labelAssociationAction: {
543
+ labeled: false,
544
+ }
545
+ },
546
+ index: [LabelAssociation_1.LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
547
+ type: 'regular',
548
+ apiVersion: 3,
549
+ operation: OP.SET,
550
+ };
551
+ }
552
+ else if ('addMessageLabel' in mod) {
553
+ patch = {
554
+ syncAction: {
555
+ labelAssociationAction: {
556
+ labeled: true,
557
+ }
558
+ },
559
+ index: [
560
+ LabelAssociation_1.LabelAssociationType.Message,
561
+ mod.addMessageLabel.labelId,
562
+ jid,
563
+ mod.addMessageLabel.messageId,
564
+ '0',
565
+ '0'
566
+ ],
567
+ type: 'regular',
568
+ apiVersion: 3,
569
+ operation: OP.SET,
570
+ };
571
+ }
572
+ else if ('removeMessageLabel' in mod) {
573
+ patch = {
574
+ syncAction: {
575
+ labelAssociationAction: {
576
+ labeled: false,
577
+ }
578
+ },
579
+ index: [
580
+ LabelAssociation_1.LabelAssociationType.Message,
581
+ mod.removeMessageLabel.labelId,
582
+ jid,
583
+ mod.removeMessageLabel.messageId,
584
+ '0',
585
+ '0'
586
+ ],
587
+ type: 'regular',
588
+ apiVersion: 3,
589
+ operation: OP.SET,
590
+ };
591
+ }
592
+ else {
593
+ throw new boom_1.Boom('not supported');
594
+ }
595
+ patch.syncAction.timestamp = Date.now();
596
+ return patch;
597
+ };
598
+ exports.chatModificationToAppPatch = chatModificationToAppPatch;
599
+ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
600
+ var _a, _b, _c, _d;
601
+ const isInitialSync = !!initialSyncOpts;
602
+ const accountSettings = initialSyncOpts === null || initialSyncOpts === void 0 ? void 0 : initialSyncOpts.accountSettings;
603
+ logger === null || logger === void 0 ? void 0 : logger.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
604
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
605
+ if (action === null || action === void 0 ? void 0 : action.muteAction) {
606
+ ev.emit('chats.update', [
607
+ {
608
+ id,
609
+ muteEndTime: ((_a = action.muteAction) === null || _a === void 0 ? void 0 : _a.muted)
610
+ ? (0, generics_1.toNumber)(action.muteAction.muteEndTimestamp)
611
+ : null,
612
+ conditional: getChatUpdateConditional(id, undefined)
613
+ }
614
+ ]);
615
+ }
616
+ else if ((action === null || action === void 0 ? void 0 : action.archiveChatAction) || type === 'archive' || type === 'unarchive') {
617
+
618
+
619
+
620
+
621
+
622
+
623
+
624
+
625
+
626
+
627
+ const archiveAction = action === null || action === void 0 ? void 0 : action.archiveChatAction;
628
+ const isArchived = archiveAction
629
+ ? archiveAction.archived
630
+ : type === 'archive';
631
+
632
+
633
+
634
+
635
+
636
+ const msgRange = !(accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats) ? undefined : archiveAction === null || archiveAction === void 0 ? void 0 : archiveAction.messageRange;
637
+
638
+ ev.emit('chats.update', [{
639
+ id,
640
+ archived: isArchived,
641
+ conditional: getChatUpdateConditional(id, msgRange)
642
+ }]);
643
+ }
644
+ else if (action === null || action === void 0 ? void 0 : action.markChatAsReadAction) {
645
+ const markReadAction = action.markChatAsReadAction;
646
+
647
+
648
+
649
+ const isNullUpdate = isInitialSync && markReadAction.read;
650
+ ev.emit('chats.update', [{
651
+ id,
652
+ unreadCount: isNullUpdate ? null : !!(markReadAction === null || markReadAction === void 0 ? void 0 : markReadAction.read) ? 0 : -1,
653
+ conditional: getChatUpdateConditional(id, markReadAction === null || markReadAction === void 0 ? void 0 : markReadAction.messageRange)
654
+ }]);
655
+ }
656
+ else if ((action === null || action === void 0 ? void 0 : action.deleteMessageForMeAction) || type === 'deleteMessageForMe') {
657
+ ev.emit('messages.delete', {
658
+ keys: [
659
+ {
660
+ remoteJid: id,
661
+ id: msgId,
662
+ fromMe: fromMe === '1'
663
+ }
664
+ ]
665
+ });
666
+ }
667
+ else if (action === null || action === void 0 ? void 0 : action.contactAction) {
668
+ ev.emit('contacts.upsert', [{ id, name: action.contactAction.fullName, lid: action.contactAction.lidJid || undefined, jid: (0, WABinary_1.isJidUser)(id) ? id : action.contactAction.pnJid }]);
669
+ }
670
+ else if (action === null || action === void 0 ? void 0 : action.pushNameSetting) {
671
+ const name = (_b = action === null || action === void 0 ? void 0 : action.pushNameSetting) === null || _b === void 0 ? void 0 : _b.name;
672
+ if (name && (me === null || me === void 0 ? void 0 : me.name) !== name) {
673
+ ev.emit('creds.update', { me: { ...me, name } });
674
+ }
675
+ }
676
+ else if (action === null || action === void 0 ? void 0 : action.pinAction) {
677
+ ev.emit('chats.update', [{
678
+ id,
679
+ pinned: ((_c = action.pinAction) === null || _c === void 0 ? void 0 : _c.pinned) ? (0, generics_1.toNumber)(action.timestamp) : null,
680
+ conditional: getChatUpdateConditional(id, undefined)
681
+ }]);
682
+ }
683
+ else if (action === null || action === void 0 ? void 0 : action.unarchiveChatsSetting) {
684
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
685
+ ev.emit('creds.update', { accountSettings: { unarchiveChats } });
686
+ logger === null || logger === void 0 ? void 0 : logger.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
687
+ if (accountSettings) {
688
+ accountSettings.unarchiveChats = unarchiveChats;
689
+ }
690
+ }
691
+ else if ((action === null || action === void 0 ? void 0 : action.starAction) || type === 'star') {
692
+ let starred = (_d = action === null || action === void 0 ? void 0 : action.starAction) === null || _d === void 0 ? void 0 : _d.starred;
693
+ if (typeof starred !== 'boolean') {
694
+ starred = syncAction.index[syncAction.index.length - 1] === '1';
695
+ }
696
+ ev.emit('messages.update', [
697
+ {
698
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
699
+ update: { starred }
700
+ }
701
+ ]);
702
+ }
703
+ else if ((action === null || action === void 0 ? void 0 : action.deleteChatAction) || type === 'deleteChat') {
704
+ if (!isInitialSync) {
705
+ ev.emit('chats.delete', [id]);
706
+ }
707
+ }
708
+ else if (action === null || action === void 0 ? void 0 : action.labelEditAction) {
709
+ const { name, color, deleted, predefinedId } = action.labelEditAction;
710
+ ev.emit('labels.edit', {
711
+ id,
712
+ name: name,
713
+ color: color,
714
+ deleted: deleted,
715
+ predefinedId: predefinedId ? String(predefinedId) : undefined
716
+ });
717
+ }
718
+ else if (action === null || action === void 0 ? void 0 : action.labelAssociationAction) {
719
+ ev.emit('labels.association', {
720
+ type: action.labelAssociationAction.labeled
721
+ ? 'add'
722
+ : 'remove',
723
+ association: type === LabelAssociation_1.LabelAssociationType.Chat
724
+ ? {
725
+ type: LabelAssociation_1.LabelAssociationType.Chat,
726
+ chatId: syncAction.index[2],
727
+ labelId: syncAction.index[1]
728
+ }
729
+ : {
730
+ type: LabelAssociation_1.LabelAssociationType.Message,
731
+ chatId: syncAction.index[2],
732
+ messageId: syncAction.index[3],
733
+ labelId: syncAction.index[1]
734
+ }
735
+ });
736
+ }
737
+ else {
738
+ logger === null || logger === void 0 ? void 0 : logger.debug({ syncAction, id }, 'unprocessable update');
739
+ }
740
+ function getChatUpdateConditional(id, msgRange) {
741
+ return isInitialSync
742
+ ? (data) => {
743
+ const chat = data.historySets.chats[id] || data.chatUpserts[id];
744
+ if (chat) {
745
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
746
+ }
747
+ }
748
+ : undefined;
749
+ }
750
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
751
+ const lastMsgTimestamp = Number((msgRange === null || msgRange === void 0 ? void 0 : msgRange.lastMessageTimestamp) || (msgRange === null || msgRange === void 0 ? void 0 : msgRange.lastSystemMessageTimestamp) || 0);
752
+ const chatLastMsgTimestamp = Number((chat === null || chat === void 0 ? void 0 : chat.lastMessageRecvTimestamp) || 0);
753
+ return lastMsgTimestamp >= chatLastMsgTimestamp;
754
+ }
755
+ };
756
+ exports.processSyncAction = processSyncAction;