@neelegirl/baileys 1.5.3 → 1.5.5

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 (224) hide show
  1. package/README.md +16 -195
  2. package/index.js +38 -0
  3. package/package.json +16 -96
  4. package/LICENSE +0 -21
  5. package/WAProto/WAProto.proto +0 -5308
  6. package/WAProto/index.d.ts +0 -61295
  7. package/WAProto/index.js +0 -189754
  8. package/lib/Defaults/baileys-version.json +0 -3
  9. package/lib/Defaults/index.d.ts +0 -78
  10. package/lib/Defaults/index.js +0 -149
  11. package/lib/Defaults/phonenumber-mcc.json +0 -223
  12. package/lib/Signal/WASignalGroup/GroupProtocol.js +0 -1909
  13. package/lib/Signal/WASignalGroup/ciphertext-message.d.ts +0 -9
  14. package/lib/Signal/WASignalGroup/ciphertext-message.js +0 -19
  15. package/lib/Signal/WASignalGroup/ciphertext_message.js +0 -16
  16. package/lib/Signal/WASignalGroup/generate-proto.sh +0 -1
  17. package/lib/Signal/WASignalGroup/group-session-builder.d.ts +0 -17
  18. package/lib/Signal/WASignalGroup/group-session-builder.js +0 -72
  19. package/lib/Signal/WASignalGroup/group.proto +0 -42
  20. package/lib/Signal/WASignalGroup/group_cipher.d.ts +0 -19
  21. package/lib/Signal/WASignalGroup/group_cipher.js +0 -111
  22. package/lib/Signal/WASignalGroup/group_session_builder.js +0 -46
  23. package/lib/Signal/WASignalGroup/index.d.ts +0 -11
  24. package/lib/Signal/WASignalGroup/index.js +0 -61
  25. package/lib/Signal/WASignalGroup/keyhelper.d.ts +0 -16
  26. package/lib/Signal/WASignalGroup/keyhelper.js +0 -66
  27. package/lib/Signal/WASignalGroup/protobufs.js +0 -3
  28. package/lib/Signal/WASignalGroup/queue_job.js +0 -69
  29. package/lib/Signal/WASignalGroup/readme.md +0 -6
  30. package/lib/Signal/WASignalGroup/sender-chain-key.d.ts +0 -14
  31. package/lib/Signal/WASignalGroup/sender-chain-key.js +0 -47
  32. package/lib/Signal/WASignalGroup/sender-key-distribution-message.d.ts +0 -17
  33. package/lib/Signal/WASignalGroup/sender-key-distribution-message.js +0 -71
  34. package/lib/Signal/WASignalGroup/sender-key-message.d.ts +0 -19
  35. package/lib/Signal/WASignalGroup/sender-key-message.js +0 -73
  36. package/lib/Signal/WASignalGroup/sender-key-name.d.ts +0 -19
  37. package/lib/Signal/WASignalGroup/sender-key-name.js +0 -59
  38. package/lib/Signal/WASignalGroup/sender-key-record.d.ts +0 -32
  39. package/lib/Signal/WASignalGroup/sender-key-record.js +0 -58
  40. package/lib/Signal/WASignalGroup/sender-key-state.d.ts +0 -44
  41. package/lib/Signal/WASignalGroup/sender-key-state.js +0 -147
  42. package/lib/Signal/WASignalGroup/sender-message-key.d.ts +0 -11
  43. package/lib/Signal/WASignalGroup/sender-message-key.js +0 -33
  44. package/lib/Signal/WASignalGroup/sender_chain_key.js +0 -50
  45. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +0 -78
  46. package/lib/Signal/WASignalGroup/sender_key_message.js +0 -92
  47. package/lib/Signal/WASignalGroup/sender_key_name.js +0 -70
  48. package/lib/Signal/WASignalGroup/sender_key_record.js +0 -56
  49. package/lib/Signal/WASignalGroup/sender_key_state.js +0 -129
  50. package/lib/Signal/WASignalGroup/sender_message_key.js +0 -39
  51. package/lib/Signal/libsignal.d.ts +0 -8
  52. package/lib/Signal/libsignal.js +0 -391
  53. package/lib/Signal/lid-mapping.d.ts +0 -28
  54. package/lib/Signal/lid-mapping.js +0 -184
  55. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -15
  56. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  57. package/lib/Socket/Client/index.d.ts +0 -2
  58. package/lib/Socket/Client/index.js +0 -22
  59. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -12
  60. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  61. package/lib/Socket/Client/types.d.ts +0 -16
  62. package/lib/Socket/Client/types.js +0 -18
  63. package/lib/Socket/Client/websocket.d.ts +0 -13
  64. package/lib/Socket/Client/websocket.js +0 -62
  65. package/lib/Socket/business.d.ts +0 -187
  66. package/lib/Socket/business.js +0 -415
  67. package/lib/Socket/chats.d.ts +0 -97
  68. package/lib/Socket/chats.js +0 -1118
  69. package/lib/Socket/communities.d.ts +0 -223
  70. package/lib/Socket/communities.js +0 -433
  71. package/lib/Socket/groups.d.ts +0 -129
  72. package/lib/Socket/groups.js +0 -360
  73. package/lib/Socket/index.d.ts +0 -191
  74. package/lib/Socket/index.js +0 -24
  75. package/lib/Socket/messages-recv.d.ts +0 -174
  76. package/lib/Socket/messages-recv.js +0 -1506
  77. package/lib/Socket/messages-send.d.ts +0 -165
  78. package/lib/Socket/messages-send.js +0 -1785
  79. package/lib/Socket/mex.d.ts +0 -2
  80. package/lib/Socket/mex.js +0 -47
  81. package/lib/Socket/newsletter.d.ts +0 -145
  82. package/lib/Socket/newsletter.js +0 -295
  83. package/lib/Socket/socket.d.ts +0 -45
  84. package/lib/Socket/socket.js +0 -934
  85. package/lib/Socket/usync.d.ts +0 -37
  86. package/lib/Socket/usync.js +0 -83
  87. package/lib/Store/index.d.ts +0 -4
  88. package/lib/Store/index.js +0 -24
  89. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  90. package/lib/Store/make-cache-manager-store.js +0 -90
  91. package/lib/Store/make-in-memory-store.d.ts +0 -123
  92. package/lib/Store/make-in-memory-store.js +0 -429
  93. package/lib/Store/make-ordered-dictionary.d.ts +0 -12
  94. package/lib/Store/make-ordered-dictionary.js +0 -86
  95. package/lib/Store/object-repository.d.ts +0 -10
  96. package/lib/Store/object-repository.js +0 -31
  97. package/lib/Types/Auth.d.ts +0 -121
  98. package/lib/Types/Auth.js +0 -3
  99. package/lib/Types/Bussines.js +0 -3
  100. package/lib/Types/Bussiness.d.ts +0 -28
  101. package/lib/Types/Call.d.ts +0 -14
  102. package/lib/Types/Call.js +0 -3
  103. package/lib/Types/Chat.d.ts +0 -143
  104. package/lib/Types/Chat.js +0 -9
  105. package/lib/Types/Contact.d.ts +0 -23
  106. package/lib/Types/Contact.js +0 -3
  107. package/lib/Types/Events.d.ts +0 -226
  108. package/lib/Types/Events.js +0 -3
  109. package/lib/Types/GroupMetadata.d.ts +0 -66
  110. package/lib/Types/GroupMetadata.js +0 -3
  111. package/lib/Types/Label.d.ts +0 -48
  112. package/lib/Types/Label.js +0 -31
  113. package/lib/Types/LabelAssociation.d.ts +0 -35
  114. package/lib/Types/LabelAssociation.js +0 -13
  115. package/lib/Types/Message.d.ts +0 -484
  116. package/lib/Types/Message.js +0 -19
  117. package/lib/Types/MexUpdates.d.ts +0 -9
  118. package/lib/Types/MexUpdates.js +0 -18
  119. package/lib/Types/Newsletter.d.ts +0 -109
  120. package/lib/Types/Newsletter.js +0 -40
  121. package/lib/Types/Product.d.ts +0 -92
  122. package/lib/Types/Product.js +0 -3
  123. package/lib/Types/Signal.d.ts +0 -98
  124. package/lib/Types/Signal.js +0 -3
  125. package/lib/Types/Socket.d.ts +0 -141
  126. package/lib/Types/Socket.js +0 -3
  127. package/lib/Types/State.d.ts +0 -41
  128. package/lib/Types/State.js +0 -14
  129. package/lib/Types/USync.d.ts +0 -26
  130. package/lib/Types/USync.js +0 -3
  131. package/lib/Types/index.d.ts +0 -80
  132. package/lib/Types/index.js +0 -50
  133. package/lib/Utils/auth-utils.d.ts +0 -21
  134. package/lib/Utils/auth-utils.js +0 -528
  135. package/lib/Utils/baileys-event-stream.d.ts +0 -18
  136. package/lib/Utils/baileys-event-stream.js +0 -70
  137. package/lib/Utils/business.d.ts +0 -29
  138. package/lib/Utils/business.js +0 -255
  139. package/lib/Utils/chat-utils.d.ts +0 -82
  140. package/lib/Utils/chat-utils.js +0 -809
  141. package/lib/Utils/crypto.d.ts +0 -56
  142. package/lib/Utils/crypto.js +0 -189
  143. package/lib/Utils/decode-wa-message.d.ts +0 -53
  144. package/lib/Utils/decode-wa-message.js +0 -323
  145. package/lib/Utils/event-buffer.d.ts +0 -39
  146. package/lib/Utils/event-buffer.js +0 -595
  147. package/lib/Utils/generics.d.ts +0 -131
  148. package/lib/Utils/generics.js +0 -630
  149. package/lib/Utils/history.d.ts +0 -23
  150. package/lib/Utils/history.js +0 -104
  151. package/lib/Utils/index.d.ts +0 -20
  152. package/lib/Utils/index.js +0 -40
  153. package/lib/Utils/link-preview.d.ts +0 -23
  154. package/lib/Utils/link-preview.js +0 -120
  155. package/lib/Utils/logger.d.ts +0 -13
  156. package/lib/Utils/logger.js +0 -7
  157. package/lib/Utils/lt-hash.d.ts +0 -14
  158. package/lib/Utils/lt-hash.js +0 -58
  159. package/lib/Utils/make-mutex.d.ts +0 -9
  160. package/lib/Utils/make-mutex.js +0 -49
  161. package/lib/Utils/message-retry-manager.d.ts +0 -88
  162. package/lib/Utils/message-retry-manager.js +0 -160
  163. package/lib/Utils/messages-media.d.ts +0 -135
  164. package/lib/Utils/messages-media.js +0 -869
  165. package/lib/Utils/messages.d.ts +0 -105
  166. package/lib/Utils/messages.js +0 -1745
  167. package/lib/Utils/noise-handler.d.ts +0 -21
  168. package/lib/Utils/noise-handler.js +0 -165
  169. package/lib/Utils/process-message.d.ts +0 -49
  170. package/lib/Utils/process-message.js +0 -427
  171. package/lib/Utils/signal.d.ts +0 -42
  172. package/lib/Utils/signal.js +0 -166
  173. package/lib/Utils/use-mongo-file-auth-state.d.ts +0 -6
  174. package/lib/Utils/use-mongo-file-auth-state.js +0 -84
  175. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -18
  176. package/lib/Utils/use-multi-file-auth-state.js +0 -238
  177. package/lib/Utils/use-single-file-auth-state.d.ts +0 -13
  178. package/lib/Utils/use-single-file-auth-state.js +0 -80
  179. package/lib/Utils/validate-connection.d.ts +0 -13
  180. package/lib/Utils/validate-connection.js +0 -220
  181. package/lib/WABinary/constants.d.ts +0 -30
  182. package/lib/WABinary/constants.js +0 -1316
  183. package/lib/WABinary/decode.d.ts +0 -9
  184. package/lib/WABinary/decode.js +0 -288
  185. package/lib/WABinary/encode.d.ts +0 -3
  186. package/lib/WABinary/encode.js +0 -265
  187. package/lib/WABinary/generic-utils.d.ts +0 -28
  188. package/lib/WABinary/generic-utils.js +0 -142
  189. package/lib/WABinary/index.d.ts +0 -5
  190. package/lib/WABinary/index.js +0 -25
  191. package/lib/WABinary/jid-utils.d.ts +0 -58
  192. package/lib/WABinary/jid-utils.js +0 -104
  193. package/lib/WABinary/types.d.ts +0 -22
  194. package/lib/WABinary/types.js +0 -3
  195. package/lib/WAM/BinaryInfo.d.ts +0 -16
  196. package/lib/WAM/BinaryInfo.js +0 -17
  197. package/lib/WAM/constants.d.ts +0 -47
  198. package/lib/WAM/constants.js +0 -15371
  199. package/lib/WAM/encode.d.ts +0 -3
  200. package/lib/WAM/encode.js +0 -164
  201. package/lib/WAM/index.d.ts +0 -3
  202. package/lib/WAM/index.js +0 -23
  203. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +0 -28
  204. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -69
  205. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  206. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -36
  207. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -26
  208. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -62
  209. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -14
  210. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -35
  211. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +0 -10
  212. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -38
  213. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -14
  214. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -46
  215. package/lib/WAUSync/Protocols/index.d.ts +0 -6
  216. package/lib/WAUSync/Protocols/index.js +0 -26
  217. package/lib/WAUSync/USyncQuery.d.ts +0 -31
  218. package/lib/WAUSync/USyncQuery.js +0 -92
  219. package/lib/WAUSync/USyncUser.d.ts +0 -12
  220. package/lib/WAUSync/USyncUser.js +0 -30
  221. package/lib/WAUSync/index.d.ts +0 -3
  222. package/lib/WAUSync/index.js +0 -23
  223. package/lib/index.d.ts +0 -13
  224. package/lib/index.js +0 -33
@@ -1,809 +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: {
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
809
- }