lordceaser-baileys 2.0.11 → 2.0.13

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