@neelegirl/baileys 1.5.2 → 1.5.3

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +195 -187
  3. package/WAProto/WAProto.proto +537 -236
  4. package/WAProto/index.d.ts +5971 -2388
  5. package/WAProto/index.js +17298 -6513
  6. package/lib/Defaults/baileys-version.json +3 -3
  7. package/lib/Defaults/index.d.ts +77 -67
  8. package/lib/Defaults/index.js +148 -136
  9. package/lib/Defaults/phonenumber-mcc.json +223 -223
  10. package/lib/Signal/WASignalGroup/GroupProtocol.js +1908 -1908
  11. package/lib/Signal/WASignalGroup/ciphertext-message.d.ts +9 -0
  12. package/lib/Signal/WASignalGroup/ciphertext-message.js +19 -0
  13. package/lib/Signal/WASignalGroup/ciphertext_message.js +15 -15
  14. package/lib/Signal/WASignalGroup/group-session-builder.d.ts +17 -0
  15. package/lib/Signal/WASignalGroup/group-session-builder.js +72 -0
  16. package/lib/Signal/WASignalGroup/group.proto +41 -41
  17. package/lib/Signal/WASignalGroup/group_cipher.d.ts +19 -0
  18. package/lib/Signal/WASignalGroup/group_cipher.js +101 -110
  19. package/lib/Signal/WASignalGroup/group_session_builder.js +45 -45
  20. package/lib/Signal/WASignalGroup/index.d.ts +11 -0
  21. package/lib/Signal/WASignalGroup/index.js +61 -6
  22. package/lib/Signal/WASignalGroup/keyhelper.d.ts +16 -0
  23. package/lib/Signal/WASignalGroup/keyhelper.js +58 -13
  24. package/lib/Signal/WASignalGroup/protobufs.js +2 -2
  25. package/lib/Signal/WASignalGroup/queue_job.js +68 -68
  26. package/lib/Signal/WASignalGroup/readme.md +5 -5
  27. package/lib/Signal/WASignalGroup/sender-chain-key.d.ts +14 -0
  28. package/lib/Signal/WASignalGroup/sender-chain-key.js +47 -0
  29. package/lib/Signal/WASignalGroup/sender-key-distribution-message.d.ts +17 -0
  30. package/lib/Signal/WASignalGroup/sender-key-distribution-message.js +71 -0
  31. package/lib/Signal/WASignalGroup/sender-key-message.d.ts +19 -0
  32. package/lib/Signal/WASignalGroup/sender-key-message.js +73 -0
  33. package/lib/Signal/WASignalGroup/sender-key-name.d.ts +19 -0
  34. package/lib/Signal/WASignalGroup/sender-key-name.js +59 -0
  35. package/lib/Signal/WASignalGroup/sender-key-record.d.ts +32 -0
  36. package/lib/Signal/WASignalGroup/sender-key-record.js +58 -0
  37. package/lib/Signal/WASignalGroup/sender-key-state.d.ts +44 -0
  38. package/lib/Signal/WASignalGroup/sender-key-state.js +147 -0
  39. package/lib/Signal/WASignalGroup/sender-message-key.d.ts +11 -0
  40. package/lib/Signal/WASignalGroup/sender-message-key.js +33 -0
  41. package/lib/Signal/WASignalGroup/sender_chain_key.js +49 -49
  42. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +77 -77
  43. package/lib/Signal/WASignalGroup/sender_key_message.js +91 -91
  44. package/lib/Signal/WASignalGroup/sender_key_name.js +69 -69
  45. package/lib/Signal/WASignalGroup/sender_key_record.js +55 -55
  46. package/lib/Signal/WASignalGroup/sender_key_state.js +128 -128
  47. package/lib/Signal/WASignalGroup/sender_message_key.js +38 -38
  48. package/lib/Signal/libsignal.d.ts +5 -1
  49. package/lib/Signal/libsignal.js +390 -161
  50. package/lib/Signal/lid-mapping.d.ts +28 -0
  51. package/lib/Signal/lid-mapping.js +184 -0
  52. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -15
  53. package/lib/Socket/Client/abstract-socket-client.js +13 -13
  54. package/lib/Socket/Client/index.d.ts +2 -2
  55. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -12
  56. package/lib/Socket/Client/mobile-socket-client.js +65 -65
  57. package/lib/Socket/Client/types.d.ts +1 -1
  58. package/lib/Socket/Client/websocket.d.ts +1 -1
  59. package/lib/Socket/business.d.ts +6 -6
  60. package/lib/Socket/business.js +152 -5
  61. package/lib/Socket/chats.d.ts +3 -4
  62. package/lib/Socket/chats.js +31 -26
  63. package/lib/Socket/communities.d.ts +223 -223
  64. package/lib/Socket/communities.js +432 -432
  65. package/lib/Socket/groups.d.ts +2 -4
  66. package/lib/Socket/groups.js +22 -14
  67. package/lib/Socket/index.d.ts +69 -69
  68. package/lib/Socket/index.js +3 -2
  69. package/lib/Socket/messages-recv.d.ts +3 -6
  70. package/lib/Socket/messages-recv.js +1449 -1707
  71. package/lib/Socket/messages-send.d.ts +2 -4
  72. package/lib/Socket/messages-send.js +617 -126
  73. package/lib/Socket/mex.d.ts +2 -2
  74. package/lib/Socket/mex.js +46 -46
  75. package/lib/Socket/newsletter.d.ts +2 -4
  76. package/lib/Socket/newsletter.js +294 -285
  77. package/lib/Socket/socket.js +318 -132
  78. package/lib/Socket/usync.js +3 -3
  79. package/lib/Store/index.d.ts +4 -4
  80. package/lib/Store/index.js +23 -23
  81. package/lib/Store/make-cache-manager-store.d.ts +13 -13
  82. package/lib/Store/make-cache-manager-store.js +89 -89
  83. package/lib/Store/make-in-memory-store.d.ts +122 -122
  84. package/lib/Store/make-in-memory-store.js +428 -428
  85. package/lib/Store/make-ordered-dictionary.d.ts +11 -11
  86. package/lib/Store/make-ordered-dictionary.js +85 -85
  87. package/lib/Store/object-repository.d.ts +9 -9
  88. package/lib/Store/object-repository.js +30 -30
  89. package/lib/Types/Auth.d.ts +5 -4
  90. package/lib/Types/Bussines.js +3 -0
  91. package/lib/Types/Bussiness.d.ts +28 -0
  92. package/lib/Types/Chat.d.ts +13 -8
  93. package/lib/Types/Contact.d.ts +4 -1
  94. package/lib/Types/Events.d.ts +13 -16
  95. package/lib/Types/GroupMetadata.d.ts +1 -1
  96. package/lib/Types/Message.d.ts +18 -7
  97. package/lib/Types/Message.js +7 -1
  98. package/lib/Types/MexUpdates.d.ts +8 -8
  99. package/lib/Types/MexUpdates.js +17 -17
  100. package/lib/Types/Newsletter.d.ts +1 -1
  101. package/lib/Types/Product.d.ts +1 -1
  102. package/lib/Types/Signal.d.ts +31 -1
  103. package/lib/Types/Socket.d.ts +34 -13
  104. package/lib/Types/State.d.ts +1 -1
  105. package/lib/Types/USync.d.ts +2 -2
  106. package/lib/Types/index.d.ts +16 -15
  107. package/lib/Types/index.js +4 -2
  108. package/lib/Utils/auth-utils.d.ts +20 -20
  109. package/lib/Utils/auth-utils.js +527 -204
  110. package/lib/Utils/baileys-event-stream.d.ts +17 -17
  111. package/lib/Utils/baileys-event-stream.js +69 -69
  112. package/lib/Utils/business.d.ts +28 -28
  113. package/lib/Utils/business.js +254 -254
  114. package/lib/Utils/chat-utils.d.ts +81 -81
  115. package/lib/Utils/chat-utils.js +808 -780
  116. package/lib/Utils/crypto.d.ts +55 -55
  117. package/lib/Utils/crypto.js +188 -178
  118. package/lib/Utils/decode-wa-message.d.ts +52 -40
  119. package/lib/Utils/decode-wa-message.js +322 -252
  120. package/lib/Utils/event-buffer.d.ts +38 -38
  121. package/lib/Utils/event-buffer.js +594 -564
  122. package/lib/Utils/generics.d.ts +131 -129
  123. package/lib/Utils/generics.js +629 -623
  124. package/lib/Utils/history.d.ts +22 -22
  125. package/lib/Utils/history.js +103 -109
  126. package/lib/Utils/index.d.ts +20 -19
  127. package/lib/Utils/index.js +39 -38
  128. package/lib/Utils/link-preview.d.ts +22 -22
  129. package/lib/Utils/link-preview.js +119 -119
  130. package/lib/Utils/logger.d.ts +13 -13
  131. package/lib/Utils/logger.js +7 -7
  132. package/lib/Utils/lt-hash.d.ts +13 -13
  133. package/lib/Utils/lt-hash.js +57 -57
  134. package/lib/Utils/make-mutex.d.ts +8 -8
  135. package/lib/Utils/make-mutex.js +48 -48
  136. package/lib/Utils/message-retry-manager.d.ts +88 -0
  137. package/lib/Utils/message-retry-manager.js +160 -0
  138. package/lib/Utils/messages-media.d.ts +134 -128
  139. package/lib/Utils/messages-media.js +868 -805
  140. package/lib/Utils/messages.d.ts +104 -102
  141. package/lib/Utils/messages.js +1744 -1578
  142. package/lib/Utils/noise-handler.d.ts +20 -19
  143. package/lib/Utils/noise-handler.js +164 -154
  144. package/lib/Utils/process-message.d.ts +48 -48
  145. package/lib/Utils/process-message.js +427 -428
  146. package/lib/Utils/signal.d.ts +41 -41
  147. package/lib/Utils/signal.js +165 -165
  148. package/lib/Utils/use-mongo-file-auth-state.d.ts +5 -5
  149. package/lib/Utils/use-mongo-file-auth-state.js +83 -83
  150. package/lib/Utils/use-multi-file-auth-state.d.ts +17 -17
  151. package/lib/Utils/use-multi-file-auth-state.js +237 -237
  152. package/lib/Utils/use-single-file-auth-state.d.ts +12 -12
  153. package/lib/Utils/use-single-file-auth-state.js +79 -79
  154. package/lib/Utils/validate-connection.d.ts +12 -12
  155. package/lib/Utils/validate-connection.js +219 -186
  156. package/lib/WABinary/constants.d.ts +29 -29
  157. package/lib/WABinary/constants.js +1315 -1315
  158. package/lib/WABinary/decode.d.ts +8 -8
  159. package/lib/WABinary/decode.js +287 -287
  160. package/lib/WABinary/encode.d.ts +2 -2
  161. package/lib/WABinary/encode.js +264 -264
  162. package/lib/WABinary/generic-utils.d.ts +27 -27
  163. package/lib/WABinary/generic-utils.js +141 -141
  164. package/lib/WABinary/index.d.ts +5 -5
  165. package/lib/WABinary/index.js +24 -24
  166. package/lib/WABinary/jid-utils.d.ts +58 -53
  167. package/lib/WABinary/jid-utils.js +103 -91
  168. package/lib/WABinary/types.d.ts +21 -21
  169. package/lib/WABinary/types.js +2 -2
  170. package/lib/WAM/BinaryInfo.d.ts +15 -15
  171. package/lib/WAM/BinaryInfo.js +16 -16
  172. package/lib/WAM/constants.d.ts +46 -46
  173. package/lib/WAM/constants.js +15370 -15370
  174. package/lib/WAM/encode.d.ts +2 -2
  175. package/lib/WAM/encode.js +163 -164
  176. package/lib/WAM/index.d.ts +3 -3
  177. package/lib/WAM/index.js +22 -22
  178. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +27 -27
  179. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +68 -68
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -3
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  183. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -8
  184. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +37 -29
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  186. package/lib/WAUSync/Protocols/index.d.ts +6 -6
  187. package/lib/WAUSync/USyncQuery.d.ts +3 -3
  188. package/lib/WAUSync/index.d.ts +3 -3
  189. package/lib/index.d.ts +13 -13
  190. package/lib/index.js +33 -33
  191. package/package.json +96 -94
  192. package/lib/Socket/registration.d.ts +0 -266
  193. package/lib/Socket/registration.js +0 -166
@@ -1,781 +1,809 @@
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: {
444
- messageRange: getMessageRange(mod.lastMessages)
445
- }
446
- },
447
- index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
448
- type: 'regular_high',
449
- apiVersion: 6,
450
- operation: OP.SET
451
- }
452
- }
453
- else if ('pin' in mod) {
454
- patch = {
455
- syncAction: {
456
- pinAction: {
457
- pinned: !!mod.pin
458
- }
459
- },
460
- index: ['pin_v1', jid],
461
- type: 'regular_low',
462
- apiVersion: 5,
463
- operation: OP.SET
464
- }
465
- }
466
- else if ('contact' in mod) {
467
- patch = {
468
- syncAction: {
469
- contactAction: mod?.contact || {}
470
- },
471
- index: ['contact', jid],
472
- type: 'critical_unblock_low',
473
- apiVersion: 2,
474
- operation: mod.contact ? OP.SET : OP.REMOVE
475
- }
476
- }
477
- else if ('star' in mod) {
478
- const key = mod.star.messages[0]
479
- patch = {
480
- syncAction: {
481
- starAction: {
482
- starred: !!mod.star.star
483
- }
484
- },
485
- index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
486
- type: 'regular_low',
487
- apiVersion: 2,
488
- operation: OP.SET
489
- }
490
- }
491
- else if ('delete' in mod) {
492
- patch = {
493
- syncAction: {
494
- deleteChatAction: {
495
- messageRange: getMessageRange(mod.lastMessages),
496
- }
497
- },
498
- index: ['deleteChat', jid, '1'],
499
- type: 'regular_high',
500
- apiVersion: 6,
501
- operation: OP.SET
502
- }
503
- }
504
- else if ('pushNameSetting' in mod) {
505
- patch = {
506
- syncAction: {
507
- pushNameSetting: {
508
- name: mod.pushNameSetting
509
- }
510
- },
511
- index: ['setting_pushName'],
512
- type: 'critical_block',
513
- apiVersion: 1,
514
- operation: OP.SET,
515
- }
516
- }
517
- else if ('addLabel' in mod) {
518
- patch = {
519
- syncAction: {
520
- labelEditAction: {
521
- name: mod.addLabel.name,
522
- color: mod.addLabel.color,
523
- predefinedId: mod.addLabel.predefinedId,
524
- deleted: mod.addLabel.deleted
525
- }
526
- },
527
- index: ['label_edit', mod.addLabel.id],
528
- type: 'regular',
529
- apiVersion: 3,
530
- operation: OP.SET,
531
- }
532
- }
533
- else if ('addChatLabel' in mod) {
534
- patch = {
535
- syncAction: {
536
- labelAssociationAction: {
537
- labeled: true,
538
- }
539
- },
540
- index: [LabelAssociation_1.LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
541
- type: 'regular',
542
- apiVersion: 3,
543
- operation: OP.SET,
544
- }
545
- }
546
- else if ('removeChatLabel' in mod) {
547
- patch = {
548
- syncAction: {
549
- labelAssociationAction: {
550
- labeled: false,
551
- }
552
- },
553
- index: [LabelAssociation_1.LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
554
- type: 'regular',
555
- apiVersion: 3,
556
- operation: OP.SET,
557
- }
558
- }
559
- else if ('addMessageLabel' in mod) {
560
- patch = {
561
- syncAction: {
562
- labelAssociationAction: {
563
- labeled: true,
564
- }
565
- },
566
- index: [
567
- LabelAssociation_1.LabelAssociationType.Message,
568
- mod.addMessageLabel.labelId,
569
- jid,
570
- mod.addMessageLabel.messageId,
571
- '0',
572
- '0'
573
- ],
574
- type: 'regular',
575
- apiVersion: 3,
576
- operation: OP.SET,
577
- }
578
- }
579
- else if ('removeMessageLabel' in mod) {
580
- patch = {
581
- syncAction: {
582
- labelAssociationAction: {
583
- labeled: false,
584
- }
585
- },
586
- index: [
587
- LabelAssociation_1.LabelAssociationType.Message,
588
- mod.removeMessageLabel.labelId,
589
- jid,
590
- mod.removeMessageLabel.messageId,
591
- '0',
592
- '0'
593
- ],
594
- type: 'regular',
595
- apiVersion: 3,
596
- operation: OP.SET,
597
- }
598
- }
599
- else {
600
- throw new boom_1.Boom('not supported')
601
- }
602
- patch.syncAction.timestamp = Date.now()
603
- return patch
604
- }
605
-
606
- const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
607
- const isInitialSync = !!initialSyncOpts
608
- const accountSettings = initialSyncOpts?.accountSettings
609
- logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action')
610
- const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction
611
- if (action?.muteAction) {
612
- ev.emit('chats.update', [
613
- {
614
- id,
615
- muteEndTime: action.muteAction?.muted
616
- ? generics_1.toNumber(action.muteAction.muteEndTimestamp)
617
- : null,
618
- conditional: getChatUpdateConditional(id, undefined)
619
- }
620
- ])
621
- }
622
- else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
623
- // okay so we've to do some annoying computation here
624
- // when we're initially syncing the app state
625
- // there are a few cases we need to handle
626
- // 1. if the account unarchiveChats setting is true
627
- // a. if the chat is archived, and no further messages have been received -- simple, keep archived
628
- // b. if the chat was archived, and the user received messages from the other person afterwards
629
- // then the chat should be marked unarchved --
630
- // we compare the timestamp of latest message from the other person to determine this
631
- // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
632
- // it'll always take an app state action to mark in unarchived -- which we'll get anyway
633
- const archiveAction = action?.archiveChatAction
634
- const isArchived = archiveAction
635
- ? archiveAction.archived
636
- : type === 'archive'
637
- // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
638
- // // this only applies for the initial sync
639
- // if(isInitialSync && !isArchived) {
640
- // isArchived = false
641
- // }
642
- const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange
643
- // logger?.debug({ chat: id, syncAction }, 'message range archive')
644
- ev.emit('chats.update', [{
645
- id,
646
- archived: isArchived,
647
- conditional: getChatUpdateConditional(id, msgRange)
648
- }])
649
- }
650
- else if (action?.markChatAsReadAction) {
651
- const markReadAction = action.markChatAsReadAction
652
- // basically we don't need to fire an "read" update if the chat is being marked as read
653
- // because the chat is read by default
654
- // this only applies for the initial sync
655
- const isNullUpdate = isInitialSync && markReadAction.read
656
- ev.emit('chats.update', [{
657
- id,
658
- unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
659
- conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
660
- }])
661
- }
662
- else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
663
- ev.emit('messages.delete', {
664
- keys: [
665
- {
666
- remoteJid: id,
667
- id: msgId,
668
- fromMe: fromMe === '1'
669
- }
670
- ]
671
- })
672
- }
673
- else if (action?.contactAction) {
674
- ev.emit('contacts.upsert', [{
675
- id,
676
- name: action.contactAction.fullName,
677
- lid: action.contactAction.lidJid || undefined,
678
- jid: WABinary_1.isJidUser(id) ? id : undefined
679
- }])
680
- }
681
- else if (action?.pushNameSetting) {
682
- const name = action?.pushNameSetting?.name
683
- if (name && me?.name !== name) {
684
- ev.emit('creds.update', { me: { ...me, name } })
685
- }
686
- }
687
- else if (action?.pinAction) {
688
- ev.emit('chats.update', [{
689
- id,
690
- pinned: action.pinAction?.pinned ? generics_1.toNumber(action.timestamp) : null,
691
- conditional: getChatUpdateConditional(id, undefined)
692
- }])
693
- }
694
- else if (action?.unarchiveChatsSetting) {
695
- const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats
696
- ev.emit('creds.update', { accountSettings: { unarchiveChats } })
697
- logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`)
698
- if (accountSettings) {
699
- accountSettings.unarchiveChats = unarchiveChats
700
- }
701
- }
702
- else if (action?.starAction || type === 'star') {
703
- let starred = action?.starAction?.starred
704
- if (typeof starred !== 'boolean') {
705
- starred = syncAction.index[syncAction.index.length - 1] === '1'
706
- }
707
- ev.emit('messages.update', [
708
- {
709
- key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
710
- update: { starred }
711
- }
712
- ])
713
- }
714
- else if (action?.deleteChatAction || type === 'deleteChat') {
715
- if (!isInitialSync) {
716
- ev.emit('chats.delete', [id])
717
- }
718
- }
719
- else if (action?.labelEditAction) {
720
- const { name, color, deleted, predefinedId } = action.labelEditAction
721
- ev.emit('labels.edit', {
722
- id,
723
- name: name,
724
- color: color,
725
- deleted: deleted,
726
- predefinedId: predefinedId ? String(predefinedId) : undefined
727
- })
728
- }
729
- else if (action?.labelAssociationAction) {
730
- ev.emit('labels.association', {
731
- type: action.labelAssociationAction.labeled
732
- ? 'add'
733
- : 'remove',
734
- association: type === LabelAssociation_1.LabelAssociationType.Chat
735
- ? {
736
- type: LabelAssociation_1.LabelAssociationType.Chat,
737
- chatId: syncAction.index[2],
738
- labelId: syncAction.index[1]
739
- }
740
- : {
741
- type: LabelAssociation_1.LabelAssociationType.Message,
742
- chatId: syncAction.index[2],
743
- messageId: syncAction.index[3],
744
- labelId: syncAction.index[1]
745
- }
746
- })
747
- }
748
- else {
749
- logger?.debug({ syncAction, id }, 'unprocessable update')
750
- }
751
- function getChatUpdateConditional(id, msgRange) {
752
- return isInitialSync
753
- ? (data) => {
754
- const chat = data.historySets.chats[id] || data.chatUpserts[id]
755
- if (chat) {
756
- return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true
757
- }
758
- }
759
- : undefined
760
- }
761
- function isValidPatchBasedOnMessageRange(chat, msgRange) {
762
- const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
763
- const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0)
764
- return lastMsgTimestamp >= chatLastMsgTimestamp
765
- }
766
- }
767
-
768
- module.exports = {
769
- mutationKeys,
770
- newLTHashState,
771
- encodeSyncdPatch,
772
- decodeSyncdMutations,
773
- decodeSyncdPatch,
774
- extractSyncdPatches,
775
- downloadExternalBlob,
776
- downloadExternalPatch,
777
- decodeSyncdSnapshot,
778
- decodePatches,
779
- chatModificationToAppPatch,
780
- processSyncAction
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: {
444
+ messageRange: getMessageRange(mod.lastMessages)
445
+ }
446
+ },
447
+ index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
448
+ type: 'regular_high',
449
+ apiVersion: 6,
450
+ operation: OP.SET
451
+ }
452
+ }
453
+ else if ('pin' in mod) {
454
+ patch = {
455
+ syncAction: {
456
+ pinAction: {
457
+ pinned: !!mod.pin
458
+ }
459
+ },
460
+ index: ['pin_v1', jid],
461
+ type: 'regular_low',
462
+ apiVersion: 5,
463
+ operation: OP.SET
464
+ }
465
+ }
466
+ else if ('contact' in mod) {
467
+ patch = {
468
+ syncAction: {
469
+ contactAction: mod?.contact || {}
470
+ },
471
+ index: ['contact', jid],
472
+ type: 'critical_unblock_low',
473
+ apiVersion: 2,
474
+ operation: mod.contact ? OP.SET : OP.REMOVE
475
+ }
476
+ }
477
+ else if ('disableLinkPreviews' in mod) {
478
+ patch = {
479
+ syncAction: {
480
+ privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
481
+ },
482
+ index: ['setting_disableLinkPreviews'],
483
+ type: 'regular',
484
+ apiVersion: 8,
485
+ operation: OP.SET
486
+ }
487
+ }
488
+ else if ('star' in mod) {
489
+ const key = mod.star.messages[0]
490
+ patch = {
491
+ syncAction: {
492
+ starAction: {
493
+ starred: !!mod.star.star
494
+ }
495
+ },
496
+ index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
497
+ type: 'regular_low',
498
+ apiVersion: 2,
499
+ operation: OP.SET
500
+ }
501
+ }
502
+ else if ('delete' in mod) {
503
+ patch = {
504
+ syncAction: {
505
+ deleteChatAction: {
506
+ messageRange: getMessageRange(mod.lastMessages),
507
+ }
508
+ },
509
+ index: ['deleteChat', jid, '1'],
510
+ type: 'regular_high',
511
+ apiVersion: 6,
512
+ operation: OP.SET
513
+ }
514
+ }
515
+ else if ('pushNameSetting' in mod) {
516
+ patch = {
517
+ syncAction: {
518
+ pushNameSetting: {
519
+ name: mod.pushNameSetting
520
+ }
521
+ },
522
+ index: ['setting_pushName'],
523
+ type: 'critical_block',
524
+ apiVersion: 1,
525
+ operation: OP.SET,
526
+ }
527
+ }
528
+ else if ('quickReply' in mod) {
529
+ patch = {
530
+ syncAction: {
531
+ quickReplyAction: {
532
+ count: 0,
533
+ deleted: mod.quickReply.deleted || false,
534
+ keywords: [],
535
+ message: mod.quickReply.message || '',
536
+ shortcut: mod.quickReply.shortcut || ''
537
+ }
538
+ },
539
+ index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
540
+ type: 'regular',
541
+ apiVersion: 2,
542
+ operation: OP.SET
543
+ }
544
+ }
545
+ else if ('addLabel' in mod) {
546
+ patch = {
547
+ syncAction: {
548
+ labelEditAction: {
549
+ name: mod.addLabel.name,
550
+ color: mod.addLabel.color,
551
+ predefinedId: mod.addLabel.predefinedId,
552
+ deleted: mod.addLabel.deleted
553
+ }
554
+ },
555
+ index: ['label_edit', mod.addLabel.id],
556
+ type: 'regular',
557
+ apiVersion: 3,
558
+ operation: OP.SET,
559
+ }
560
+ }
561
+ else if ('addChatLabel' in mod) {
562
+ patch = {
563
+ syncAction: {
564
+ labelAssociationAction: {
565
+ labeled: true,
566
+ }
567
+ },
568
+ index: [LabelAssociation_1.LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
569
+ type: 'regular',
570
+ apiVersion: 3,
571
+ operation: OP.SET,
572
+ }
573
+ }
574
+ else if ('removeChatLabel' in mod) {
575
+ patch = {
576
+ syncAction: {
577
+ labelAssociationAction: {
578
+ labeled: false,
579
+ }
580
+ },
581
+ index: [LabelAssociation_1.LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
582
+ type: 'regular',
583
+ apiVersion: 3,
584
+ operation: OP.SET,
585
+ }
586
+ }
587
+ else if ('addMessageLabel' in mod) {
588
+ patch = {
589
+ syncAction: {
590
+ labelAssociationAction: {
591
+ labeled: true,
592
+ }
593
+ },
594
+ index: [
595
+ LabelAssociation_1.LabelAssociationType.Message,
596
+ mod.addMessageLabel.labelId,
597
+ jid,
598
+ mod.addMessageLabel.messageId,
599
+ '0',
600
+ '0'
601
+ ],
602
+ type: 'regular',
603
+ apiVersion: 3,
604
+ operation: OP.SET,
605
+ }
606
+ }
607
+ else if ('removeMessageLabel' in mod) {
608
+ patch = {
609
+ syncAction: {
610
+ labelAssociationAction: {
611
+ labeled: false,
612
+ }
613
+ },
614
+ index: [
615
+ LabelAssociation_1.LabelAssociationType.Message,
616
+ mod.removeMessageLabel.labelId,
617
+ jid,
618
+ mod.removeMessageLabel.messageId,
619
+ '0',
620
+ '0'
621
+ ],
622
+ type: 'regular',
623
+ apiVersion: 3,
624
+ operation: OP.SET,
625
+ }
626
+ }
627
+ else {
628
+ throw new boom_1.Boom('not supported')
629
+ }
630
+ patch.syncAction.timestamp = Date.now()
631
+ return patch
632
+ }
633
+
634
+ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
635
+ const isInitialSync = !!initialSyncOpts
636
+ const accountSettings = initialSyncOpts?.accountSettings
637
+ logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action')
638
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction
639
+ if (action?.muteAction) {
640
+ ev.emit('chats.update', [
641
+ {
642
+ id,
643
+ muteEndTime: action.muteAction?.muted
644
+ ? generics_1.toNumber(action.muteAction.muteEndTimestamp)
645
+ : null,
646
+ conditional: getChatUpdateConditional(id, undefined)
647
+ }
648
+ ])
649
+ }
650
+ else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
651
+ // okay so we've to do some annoying computation here
652
+ // when we're initially syncing the app state
653
+ // there are a few cases we need to handle
654
+ // 1. if the account unarchiveChats setting is true
655
+ // a. if the chat is archived, and no further messages have been received -- simple, keep archived
656
+ // b. if the chat was archived, and the user received messages from the other person afterwards
657
+ // then the chat should be marked unarchved --
658
+ // we compare the timestamp of latest message from the other person to determine this
659
+ // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
660
+ // it'll always take an app state action to mark in unarchived -- which we'll get anyway
661
+ const archiveAction = action?.archiveChatAction
662
+ const isArchived = archiveAction
663
+ ? archiveAction.archived
664
+ : type === 'archive'
665
+ // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
666
+ // // this only applies for the initial sync
667
+ // if(isInitialSync && !isArchived) {
668
+ // isArchived = false
669
+ // }
670
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange
671
+ // logger?.debug({ chat: id, syncAction }, 'message range archive')
672
+ ev.emit('chats.update', [{
673
+ id,
674
+ archived: isArchived,
675
+ conditional: getChatUpdateConditional(id, msgRange)
676
+ }])
677
+ }
678
+ else if (action?.markChatAsReadAction) {
679
+ const markReadAction = action.markChatAsReadAction
680
+ // basically we don't need to fire an "read" update if the chat is being marked as read
681
+ // because the chat is read by default
682
+ // this only applies for the initial sync
683
+ const isNullUpdate = isInitialSync && markReadAction.read
684
+ ev.emit('chats.update', [{
685
+ id,
686
+ unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
687
+ conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
688
+ }])
689
+ }
690
+ else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
691
+ ev.emit('messages.delete', {
692
+ keys: [
693
+ {
694
+ remoteJid: id,
695
+ id: msgId,
696
+ fromMe: fromMe === '1'
697
+ }
698
+ ]
699
+ })
700
+ }
701
+ else if (action?.contactAction) {
702
+ ev.emit('contacts.upsert', [{
703
+ id,
704
+ name: action.contactAction.fullName,
705
+ lid: action.contactAction.lidJid || undefined,
706
+ phoneNumber: action.contactAction.pnJid || undefined
707
+ }])
708
+ }
709
+ else if (action?.pushNameSetting) {
710
+ const name = action?.pushNameSetting?.name
711
+ if (name && me?.name !== name) {
712
+ ev.emit('creds.update', { me: { ...me, name } })
713
+ }
714
+ }
715
+ else if (action?.pinAction) {
716
+ ev.emit('chats.update', [{
717
+ id,
718
+ pinned: action.pinAction?.pinned ? generics_1.toNumber(action.timestamp) : null,
719
+ conditional: getChatUpdateConditional(id, undefined)
720
+ }])
721
+ }
722
+ else if (action?.unarchiveChatsSetting) {
723
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats
724
+ ev.emit('creds.update', { accountSettings: { unarchiveChats } })
725
+ logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`)
726
+ if (accountSettings) {
727
+ accountSettings.unarchiveChats = unarchiveChats
728
+ }
729
+ }
730
+ else if (action?.starAction || type === 'star') {
731
+ let starred = action?.starAction?.starred
732
+ if (typeof starred !== 'boolean') {
733
+ starred = syncAction.index[syncAction.index.length - 1] === '1'
734
+ }
735
+ ev.emit('messages.update', [
736
+ {
737
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
738
+ update: { starred }
739
+ }
740
+ ])
741
+ }
742
+ else if (action?.deleteChatAction || type === 'deleteChat') {
743
+ if (!isInitialSync) {
744
+ ev.emit('chats.delete', [id])
745
+ }
746
+ }
747
+ else if (action?.labelEditAction) {
748
+ const { name, color, deleted, predefinedId } = action.labelEditAction
749
+ ev.emit('labels.edit', {
750
+ id,
751
+ name: name,
752
+ color: color,
753
+ deleted: deleted,
754
+ predefinedId: predefinedId ? String(predefinedId) : undefined
755
+ })
756
+ }
757
+ else if (action?.labelAssociationAction) {
758
+ ev.emit('labels.association', {
759
+ type: action.labelAssociationAction.labeled
760
+ ? 'add'
761
+ : 'remove',
762
+ association: type === LabelAssociation_1.LabelAssociationType.Chat
763
+ ? {
764
+ type: LabelAssociation_1.LabelAssociationType.Chat,
765
+ chatId: syncAction.index[2],
766
+ labelId: syncAction.index[1]
767
+ }
768
+ : {
769
+ type: LabelAssociation_1.LabelAssociationType.Message,
770
+ chatId: syncAction.index[2],
771
+ messageId: syncAction.index[3],
772
+ labelId: syncAction.index[1]
773
+ }
774
+ })
775
+ }
776
+ else {
777
+ logger?.debug({ syncAction, id }, 'unprocessable update')
778
+ }
779
+ function getChatUpdateConditional(id, msgRange) {
780
+ return isInitialSync
781
+ ? (data) => {
782
+ const chat = data.historySets.chats[id] || data.chatUpserts[id]
783
+ if (chat) {
784
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true
785
+ }
786
+ }
787
+ : undefined
788
+ }
789
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
790
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
791
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0)
792
+ return lastMsgTimestamp >= chatLastMsgTimestamp
793
+ }
794
+ }
795
+
796
+ module.exports = {
797
+ mutationKeys,
798
+ newLTHashState,
799
+ encodeSyncdPatch,
800
+ decodeSyncdMutations,
801
+ decodeSyncdPatch,
802
+ extractSyncdPatches,
803
+ downloadExternalBlob,
804
+ downloadExternalPatch,
805
+ decodeSyncdSnapshot,
806
+ decodePatches,
807
+ chatModificationToAppPatch,
808
+ processSyncAction
781
809
  }