@zervonexx/baileys 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +191 -192
@@ -1,317 +1,317 @@
1
- import { Boom } from '@hapi/boom'
2
- import { expandAppStateKeys } from 'whatsapp-rust-bridge'
3
- import { proto } from '../../WAProto/index.js'
4
- import { LabelAssociationType } from '../Types/LabelAssociation.js'
5
- import { processContactAction, emitSyncActionResults } from './sync-action-utils.js'
6
- import { getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary/index.js'
7
- import { aesDecrypt, aesEncrypt, hmacSign } from './crypto.js'
8
- import { toNumber } from './generics.js'
9
- import { LT_HASH_ANTI_TAMPERING } from './lt-hash.js'
10
- import { downloadContentFromMessage } from './messages-media.js'
11
-
12
- const OP = proto.SyncdMutation.SyncdOperation
13
-
14
- const mutationKeys = keydata => {
15
- const keys = expandAppStateKeys(keydata)
16
- return { indexKey: keys.indexKey, valueEncryptionKey: keys.valueEncryptionKey, valueMacKey: keys.valueMacKey, snapshotMacKey: keys.snapshotMacKey, patchMacKey: keys.patchMacKey }
17
- }
18
-
19
- const generateMac = (operation, data, keyId, key) => {
20
- const opByte = operation === OP.SET ? 0x01 : 0x02
21
- const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId
22
- const keyData = new Uint8Array(1 + keyIdBuffer.length)
23
- keyData[0] = opByte
24
- keyData.set(keyIdBuffer, 1)
25
- const last = new Uint8Array(8)
26
- last[7] = keyData.length
27
- const total = new Uint8Array(keyData.length + data.length + last.length)
28
- total.set(keyData, 0); total.set(data, keyData.length); total.set(last, keyData.length + data.length)
29
- return hmacSign(total, key, 'sha512').subarray(0, 32)
30
- }
31
-
32
- const to64BitNetworkOrder = e => { const buff = Buffer.alloc(8); buff.writeUint32BE(e, 4); return buff }
33
-
34
- export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
35
- indexValueMap = { ...indexValueMap }
36
- const addBuffs = [], subBuffs = []
37
- return {
38
- mix: ({ indexMac, valueMac, operation }) => {
39
- const key = Buffer.from(indexMac).toString('base64')
40
- const prev = indexValueMap[key]
41
- if (operation === OP.REMOVE) { if (!prev) return; delete indexValueMap[key] }
42
- else { addBuffs.push(valueMac); indexValueMap[key] = { valueMac } }
43
- if (prev) subBuffs.push(prev.valueMac)
44
- },
45
- finish: async () => ({ hash: Buffer.from(LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs)), indexValueMap })
46
- }
47
- }
48
-
49
- const generateSnapshotMac = (lthash, version, name, key) => hmacSign(Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]), key, 'sha256')
50
- const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => hmacSign(Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]), key)
51
-
52
- export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} })
53
- export const ensureLTHashStateVersion = state => { if (typeof state.version !== 'number' || isNaN(state.version)) state.version = 0; return state }
54
-
55
- export const MAX_SYNC_ATTEMPTS = 2
56
- export const isMissingKeyError = error => error?.data?.isMissingKey === true
57
- export const isAppStateSyncIrrecoverable = (error, attempts) => attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError'
58
-
59
- export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
60
- const key = myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined
61
- if (!key) throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } })
62
- const encKeyId = Buffer.from(myAppStateKeyId, 'base64')
63
- state = { ...state, indexValueMap: { ...state.indexValueMap } }
64
- const indexBuffer = Buffer.from(JSON.stringify(index))
65
- const dataProto = proto.SyncActionData.fromObject({ index: indexBuffer, value: syncAction, padding: new Uint8Array(0), version: apiVersion })
66
- const encoded = proto.SyncActionData.encode(dataProto).finish()
67
- const keyValue = mutationKeys(key.keyData)
68
- const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey)
69
- const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey)
70
- const indexMac = hmacSign(indexBuffer, keyValue.indexKey)
71
- const generator = makeLtHashGenerator(state)
72
- generator.mix({ indexMac, valueMac, operation })
73
- Object.assign(state, await generator.finish())
74
- state.version += 1
75
- const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey)
76
- const patch = {
77
- patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
78
- snapshotMac,
79
- keyId: { id: encKeyId },
80
- mutations: [{ operation, record: { index: { blob: indexMac }, value: { blob: Buffer.concat([encValue, valueMac]) }, keyId: { id: encKeyId } } }]
81
- }
82
- state.indexValueMap[indexMac.toString('base64')] = { valueMac }
83
- return { patch, state }
84
- }
85
-
86
- export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
87
- const ltGenerator = makeLtHashGenerator(initialState)
88
- const derivedKeyCache = new Map()
89
-
90
- async function getKey(keyId) {
91
- const base64Key = Buffer.from(keyId).toString('base64')
92
- if (derivedKeyCache.has(base64Key)) return derivedKeyCache.get(base64Key)
93
- const keyEnc = await getAppStateSyncKey(base64Key)
94
- if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true, msgMutations } })
95
- const keys = mutationKeys(keyEnc.keyData)
96
- derivedKeyCache.set(base64Key, keys)
97
- return keys
98
- }
99
-
100
- for (const msgMutation of msgMutations) {
101
- const operation = 'operation' in msgMutation ? msgMutation.operation : OP.SET
102
- const record = 'record' in msgMutation && msgMutation.record ? msgMutation.record : msgMutation
103
- let key
104
- try { key = await getKey(record.keyId.id) } catch (err) { if (isMissingKeyError(err)) throw err; continue }
105
- if (!record?.value?.blob) continue
106
- const content = record.value.blob
107
- const encContent = content.subarray(0, -32)
108
- const ogValueMac = content.subarray(-32)
109
- if (validateMacs) {
110
- const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey)
111
- if (Buffer.compare(contentHmac, ogValueMac) !== 0) continue
112
- }
113
- let result
114
- try { result = aesDecrypt(encContent, key.valueEncryptionKey) } catch { continue }
115
- const syncAction = proto.SyncActionData.decode(result)
116
- if (validateMacs) {
117
- const hmac = hmacSign(syncAction.index, key.indexKey)
118
- if (Buffer.compare(hmac, record.index.blob) !== 0) throw new Boom('HMAC index verification failed')
119
- }
120
- if (syncAction.index) onMutation({ syncAction, index: JSON.parse(Buffer.from(syncAction.index).toString()) })
121
- ltGenerator.mix({ indexMac: record.index.blob, valueMac: ogValueMac, operation })
122
- }
123
- return ltGenerator.finish()
124
- }
125
-
126
- export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
127
- if (validateMacs) {
128
- const base64Key = Buffer.from(msg.keyId.id).toString('base64')
129
- const mainKeyObj = await getAppStateSyncKey(base64Key)
130
- if (!mainKeyObj) throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } })
131
- const mainKey = mutationKeys(mainKeyObj.keyData)
132
- const mutationmacs = msg.mutations.map(m => m.record.value.blob.slice(-32))
133
- const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey)
134
- if (Buffer.compare(patchMac, msg.patchMac) !== 0) throw new Boom('Invalid patch mac')
135
- }
136
- return decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs)
137
- }
138
-
139
- export const extractSyncdPatches = async (result, options) => {
140
- const syncNode = getBinaryNodeChild(result, 'sync')
141
- const collectionNodes = getBinaryNodeChildren(syncNode, 'collection')
142
- const final = {}
143
- await Promise.all(collectionNodes.map(async collectionNode => {
144
- const patchesNode = getBinaryNodeChild(collectionNode, 'patches')
145
- const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch')
146
- const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot')
147
- const syncds = []
148
- const name = collectionNode.attrs.name
149
- const hasMorePatches = collectionNode.attrs.has_more_patches === 'true'
150
- let snapshot
151
- if (snapshotNode?.content) {
152
- if (!Buffer.isBuffer(snapshotNode)) snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
153
- const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content)
154
- snapshot = proto.SyncdSnapshot.decode(await downloadExternalBlob(blobRef, options))
155
- }
156
- for (let { content } of patches) {
157
- if (!content) continue
158
- if (!Buffer.isBuffer(content)) content = Buffer.from(Object.values(content))
159
- const syncd = proto.SyncdPatch.decode(content)
160
- if (!syncd.version) syncd.version = { version: +collectionNode.attrs.version + 1 }
161
- syncds.push(syncd)
162
- }
163
- final[name] = { patches: syncds, hasMorePatches, snapshot }
164
- }))
165
- return final
166
- }
167
-
168
- export const downloadExternalBlob = async (blob, options) => {
169
- const stream = await downloadContentFromMessage(blob, 'md-app-state', { options })
170
- const bufferArray = []
171
- for await (const chunk of stream) bufferArray.push(chunk)
172
- return Buffer.concat(bufferArray)
173
- }
174
-
175
- export const downloadExternalPatch = async (blob, options) => {
176
- const buffer = await downloadExternalBlob(blob, options)
177
- return proto.SyncdMutations.decode(buffer)
178
- }
179
-
180
- export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
181
- const newState = newLTHashState()
182
- newState.version = toNumber(snapshot.version.version)
183
- const mutationMap = {}
184
- const areMutationsRequired = minimumVersionNumber === undefined || newState.version > minimumVersionNumber
185
- const onMutation = areMutationsRequired ? mutation => { const index = mutation.syncAction.index?.toString(); mutationMap[index] = mutation } : () => { }
186
- const { hash, indexValueMap } = await decodeSyncdMutations(snapshot.records, newState, getAppStateSyncKey, onMutation, validateMacs)
187
- newState.hash = hash
188
- newState.indexValueMap = indexValueMap
189
- if (validateMacs) {
190
- const base64Key = Buffer.from(snapshot.keyId.id).toString('base64')
191
- const keyEnc = await getAppStateSyncKey(base64Key)
192
- if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } })
193
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, mutationKeys(keyEnc.keyData).snapshotMacKey)
194
- // soft failure — MAC mismatch on snapshot doesn't abort; state is still usable
195
- if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state')
196
- }
197
- return { state: newState, mutationMap }
198
- }
199
-
200
- export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
201
- const newState = { ...initial, indexValueMap: { ...initial.indexValueMap } }
202
- const mutationMap = {}
203
- for (const syncd of syncds) {
204
- const { version, keyId, snapshotMac } = syncd
205
- if (syncd.externalMutations) {
206
- logger?.trace({ name, version }, 'downloading external patch')
207
- const ref = await downloadExternalPatch(syncd.externalMutations, options)
208
- logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch')
209
- syncd.mutations?.push(...ref.mutations)
210
- }
211
- const patchVersion = toNumber(version.version)
212
- newState.version = patchVersion
213
- const shouldMutate = minimumVersionNumber === undefined || patchVersion > minimumVersionNumber
214
- const onMutation = shouldMutate ? mutation => { const index = mutation.syncAction.index?.toString(); mutationMap[index] = mutation } : () => { }
215
- let decodeResult
216
- try { decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, onMutation, validateMacs) }
217
- catch (err) { if (isMissingKeyError(err)) throw err; logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping'); continue }
218
- newState.hash = decodeResult.hash
219
- newState.indexValueMap = decodeResult.indexValueMap
220
- if (validateMacs) {
221
- const base64Key = Buffer.from(keyId.id).toString('base64')
222
- const keyEnc = await getAppStateSyncKey(base64Key)
223
- if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } })
224
- const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, mutationKeys(keyEnc.keyData).snapshotMacKey)
225
- // MAC mismatch mid-patch-stream means state is corrupted from this point; stop processing
226
- if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) { logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches'); break }
227
- }
228
- syncd.mutations = []
229
- }
230
- return { state: newState, mutationMap }
231
- }
232
-
233
- export const chatModificationToAppPatch = (mod, jid) => {
234
- const getMessageRange = lastMessages => {
235
- if (!Array.isArray(lastMessages)) return lastMessages
236
- const lastMsg = lastMessages[lastMessages.length - 1]
237
- return {
238
- lastMessageTimestamp: lastMsg?.messageTimestamp,
239
- messages: lastMessages?.length ? lastMessages.map(m => {
240
- if (!m.key?.id || !m.key?.remoteJid) throw new Boom('Incomplete key', { statusCode: 400, data: m })
241
- if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m })
242
- if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m })
243
- if (m.key.participant) m.key.participant = jidNormalizedUser(m.key.participant)
244
- return m
245
- }) : undefined
246
- }
247
- }
248
-
249
- let patch
250
- if ('mute' in mod) patch = { syncAction: { muteAction: { muted: !!mod.mute, muteEndTimestamp: mod.mute || undefined } }, index: ['mute', jid], type: 'regular_high', apiVersion: 2, operation: OP.SET }
251
- else if ('archive' in mod) patch = { syncAction: { archiveChatAction: { archived: !!mod.archive, messageRange: getMessageRange(mod.lastMessages) } }, index: ['archive', jid], type: 'regular_low', apiVersion: 3, operation: OP.SET }
252
- else if ('markRead' in mod) patch = { syncAction: { markChatAsReadAction: { read: mod.markRead, messageRange: getMessageRange(mod.lastMessages) } }, index: ['markChatAsRead', jid], type: 'regular_low', apiVersion: 3, operation: OP.SET }
253
- else if ('deleteForMe' in mod) { const { timestamp, key, deleteMedia } = mod.deleteForMe; patch = { syncAction: { deleteMessageForMeAction: { deleteMedia, messageTimestamp: timestamp } }, index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'], type: 'regular_high', apiVersion: 3, operation: OP.SET } }
254
- else if ('clear' in mod) patch = { syncAction: { clearChatAction: { messageRange: getMessageRange(mod.lastMessages) } }, index: ['clearChat', jid, '1', '0'], type: 'regular_high', apiVersion: 6, operation: OP.SET }
255
- else if ('pin' in mod) patch = { syncAction: { pinAction: { pinned: !!mod.pin } }, index: ['pin_v1', jid], type: 'regular_low', apiVersion: 5, operation: OP.SET }
256
- else if ('contact' in mod) patch = { syncAction: { contactAction: mod.contact || {} }, index: ['contact', jid], type: 'critical_unblock_low', apiVersion: 2, operation: mod.contact ? OP.SET : OP.REMOVE }
257
- else if ('disableLinkPreviews' in mod) patch = { syncAction: { privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {} }, index: ['setting_disableLinkPreviews'], type: 'regular', apiVersion: 8, operation: OP.SET }
258
- else if ('star' in mod) { const key = mod.star.messages[0]; patch = { syncAction: { starAction: { starred: !!mod.star.star } }, index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'], type: 'regular_low', apiVersion: 2, operation: OP.SET } }
259
- else if ('delete' in mod) patch = { syncAction: { deleteChatAction: { messageRange: getMessageRange(mod.lastMessages) } }, index: ['deleteChat', jid, '1'], type: 'regular_high', apiVersion: 6, operation: OP.SET }
260
- else if ('pushNameSetting' in mod) patch = { syncAction: { pushNameSetting: { name: mod.pushNameSetting } }, index: ['setting_pushName'], type: 'critical_block', apiVersion: 1, operation: OP.SET }
261
- else if ('quickReply' in mod) patch = { syncAction: { quickReplyAction: { count: 0, deleted: mod.quickReply.deleted || false, keywords: [], message: mod.quickReply.message || '', shortcut: mod.quickReply.shortcut || '' } }, index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))], type: 'regular', apiVersion: 2, operation: OP.SET }
262
- else if ('addLabel' in mod) patch = { syncAction: { labelEditAction: { name: mod.addLabel.name, color: mod.addLabel.color, predefinedId: mod.addLabel.predefinedId, deleted: mod.addLabel.deleted } }, index: ['label_edit', mod.addLabel.id], type: 'regular', apiVersion: 3, operation: OP.SET }
263
- else if ('addChatLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: true } }, index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid], type: 'regular', apiVersion: 3, operation: OP.SET }
264
- else if ('removeChatLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: false } }, index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid], type: 'regular', apiVersion: 3, operation: OP.SET }
265
- else if ('addMessageLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: true } }, index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'], type: 'regular', apiVersion: 3, operation: OP.SET }
266
- else if ('removeMessageLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: false } }, index: [LabelAssociationType.Message, mod.removeMessageLabel.labelId, jid, mod.removeMessageLabel.messageId, '0', '0'], type: 'regular', apiVersion: 3, operation: OP.SET }
267
- else throw new Boom('not supported')
268
-
269
- patch.syncAction.timestamp = Date.now()
270
- return patch
271
- }
272
-
273
- export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
274
- const isInitialSync = !!initialSyncOpts
275
- const accountSettings = initialSyncOpts?.accountSettings
276
- logger?.trace({ syncAction, initialSync: isInitialSync }, 'processing sync action')
277
- const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction
278
-
279
- const getChatUpdateConditional = (id, msgRange) => !isInitialSync ? undefined : data => {
280
- const chat = data.historySets.chats[id] || data.chatUpserts[id]
281
- if (!chat) return false
282
- if (!msgRange) return true
283
- const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
284
- return lastMsgTimestamp >= Number(chat?.lastMessageRecvTimestamp || 0)
285
- }
286
-
287
- if (action?.muteAction) ev.emit('chats.update', [{ id, muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
288
- else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') { const archiveAction = action?.archiveChatAction; ev.emit('chats.update', [{ id, archived: archiveAction ? archiveAction.archived : type === 'archive', conditional: getChatUpdateConditional(id, !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange) }]) }
289
- else if (action?.markChatAsReadAction) ev.emit('chats.update', [{ id, unreadCount: isInitialSync && action.markChatAsReadAction.read ? null : action.markChatAsReadAction?.read ? 0 : -1, conditional: getChatUpdateConditional(id, action.markChatAsReadAction?.messageRange) }])
290
- else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') ev.emit('messages.delete', { keys: [{ remoteJid: id, id: msgId, fromMe: fromMe === '1' }] })
291
- else if (action?.contactAction) emitSyncActionResults(ev, processContactAction(action.contactAction, id, logger))
292
- else if (action?.pushNameSetting) { const name = action?.pushNameSetting?.name; if (name && me?.name !== name) ev.emit('creds.update', { me: { ...me, name } }) }
293
- else if (action?.pinAction) ev.emit('chats.update', [{ id, pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
294
- else if (action?.unarchiveChatsSetting) { const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats; ev.emit('creds.update', { accountSettings: { unarchiveChats } }); if (accountSettings) accountSettings.unarchiveChats = unarchiveChats }
295
- else if (action?.starAction || type === 'star') { let starred = action?.starAction?.starred; if (typeof starred !== 'boolean') starred = syncAction.index[syncAction.index.length - 1] === '1'; ev.emit('messages.update', [{ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' }, update: { starred } }]) }
296
- else if (action?.deleteChatAction || type === 'deleteChat') { if (!isInitialSync) ev.emit('chats.delete', [id]) }
297
- else if (action?.labelEditAction) { const { name, color, deleted, predefinedId } = action.labelEditAction; ev.emit('labels.edit', { id, name, color, deleted, predefinedId: predefinedId ? String(predefinedId) : undefined }) }
298
- else if (action?.labelAssociationAction) ev.emit('labels.association', { type: action.labelAssociationAction.labeled ? 'add' : 'remove', association: type === LabelAssociationType.Chat ? { type: LabelAssociationType.Chat, chatId: syncAction.index[2], labelId: syncAction.index[1] } : { type: LabelAssociationType.Message, chatId: syncAction.index[2], messageId: syncAction.index[3], labelId: syncAction.index[1] } })
299
- else if (action?.localeSetting?.locale) ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale })
300
- else if (action?.timeFormatAction) ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction })
301
- else if (action?.pnForLidChatAction?.pnJid) ev.emit('lid-mapping.update', { lid: id, pn: action.pnForLidChatAction.pnJid })
302
- else if (action?.privacySettingRelayAllCalls) ev.emit('settings.update', { setting: 'privacySettingRelayAllCalls', value: action.privacySettingRelayAllCalls })
303
- else if (action?.statusPrivacy) ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy })
304
- else if (action?.lockChatAction) ev.emit('chats.lock', { id, locked: !!action.lockChatAction.locked })
305
- else if (action?.privacySettingDisableLinkPreviewsAction) ev.emit('settings.update', { setting: 'disableLinkPreviews', value: action.privacySettingDisableLinkPreviewsAction })
306
- else if (action?.notificationActivitySettingAction?.notificationActivitySetting) ev.emit('settings.update', { setting: 'notificationActivitySetting', value: action.notificationActivitySettingAction.notificationActivitySetting })
307
- else if (action?.lidContactAction) ev.emit('contacts.upsert', [{ id, name: action.lidContactAction.fullName || action.lidContactAction.firstName || action.lidContactAction.username || undefined, username: action.lidContactAction.username || undefined, lid: id, phoneNumber: undefined }])
308
- else if (action?.privacySettingChannelsPersonalisedRecommendationAction) ev.emit('settings.update', { setting: 'channelsPersonalisedRecommendation', value: action.privacySettingChannelsPersonalisedRecommendationAction })
309
- else if (action?.aiThreadRenameAction) ev.emit('chats.update', [{ id, name: action.aiThreadRenameAction.newTitle || undefined, conditional: getChatUpdateConditional(id, undefined) }])
310
- else if (action?.threadPinAction) ev.emit('chats.update', [{ id, pinned: action.threadPinAction.pinned ? toNumber(action.timestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
311
- else if (action?.newsletterSavedInterestsAction) ev.emit('settings.update', { setting: 'newsletterSavedInterests', value: action.newsletterSavedInterestsAction.newsletterSavedInterests })
312
- else if (action?.interactiveMessageAction) ev.emit('messages.update', [{ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' }, update: { interactiveMessageAction: action.interactiveMessageAction } }])
313
- else if (action?.deviceCapabilities || action?.deviceCapabilitiesV2) ev.emit('creds.update', { deviceCapabilities: action.deviceCapabilities || action.deviceCapabilitiesV2 })
314
- else if (action?.nctSaltSyncAction) ev.emit('creds.update', { nctSalt: action.nctSaltSyncAction.salt })
315
- else if (action?.bubbleLockMessageAction) ev.emit('messages.update', [{ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' }, update: { bubbleLocked: !!action.bubbleLockMessageAction.locked } }])
316
- else logger?.debug({ syncAction, id }, 'unprocessable update')
1
+ import { Boom } from '@hapi/boom'
2
+ import { expandAppStateKeys } from 'whatsapp-rust-bridge'
3
+ import { proto } from '../../WAProto/index.js'
4
+ import { LabelAssociationType } from '../Types/LabelAssociation.js'
5
+ import { processContactAction, emitSyncActionResults } from './sync-action-utils.js'
6
+ import { getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary/index.js'
7
+ import { aesDecrypt, aesEncrypt, hmacSign } from './crypto.js'
8
+ import { toNumber } from './generics.js'
9
+ import { LT_HASH_ANTI_TAMPERING } from './lt-hash.js'
10
+ import { downloadContentFromMessage } from './messages-media.js'
11
+
12
+ const OP = proto.SyncdMutation.SyncdOperation
13
+
14
+ const mutationKeys = keydata => {
15
+ const keys = expandAppStateKeys(keydata)
16
+ return { indexKey: keys.indexKey, valueEncryptionKey: keys.valueEncryptionKey, valueMacKey: keys.valueMacKey, snapshotMacKey: keys.snapshotMacKey, patchMacKey: keys.patchMacKey }
17
+ }
18
+
19
+ const generateMac = (operation, data, keyId, key) => {
20
+ const opByte = operation === OP.SET ? 0x01 : 0x02
21
+ const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId
22
+ const keyData = new Uint8Array(1 + keyIdBuffer.length)
23
+ keyData[0] = opByte
24
+ keyData.set(keyIdBuffer, 1)
25
+ const last = new Uint8Array(8)
26
+ last[7] = keyData.length
27
+ const total = new Uint8Array(keyData.length + data.length + last.length)
28
+ total.set(keyData, 0); total.set(data, keyData.length); total.set(last, keyData.length + data.length)
29
+ return hmacSign(total, key, 'sha512').subarray(0, 32)
30
+ }
31
+
32
+ const to64BitNetworkOrder = e => { const buff = Buffer.alloc(8); buff.writeUint32BE(e, 4); return buff }
33
+
34
+ export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
35
+ indexValueMap = { ...indexValueMap }
36
+ const addBuffs = [], subBuffs = []
37
+ return {
38
+ mix: ({ indexMac, valueMac, operation }) => {
39
+ const key = Buffer.from(indexMac).toString('base64')
40
+ const prev = indexValueMap[key]
41
+ if (operation === OP.REMOVE) { if (!prev) return; delete indexValueMap[key] }
42
+ else { addBuffs.push(valueMac); indexValueMap[key] = { valueMac } }
43
+ if (prev) subBuffs.push(prev.valueMac)
44
+ },
45
+ finish: async () => ({ hash: Buffer.from(LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs)), indexValueMap })
46
+ }
47
+ }
48
+
49
+ const generateSnapshotMac = (lthash, version, name, key) => hmacSign(Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]), key, 'sha256')
50
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => hmacSign(Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]), key)
51
+
52
+ export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} })
53
+ export const ensureLTHashStateVersion = state => { if (typeof state.version !== 'number' || isNaN(state.version)) state.version = 0; return state }
54
+
55
+ export const MAX_SYNC_ATTEMPTS = 2
56
+ export const isMissingKeyError = error => error?.data?.isMissingKey === true
57
+ export const isAppStateSyncIrrecoverable = (error, attempts) => attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError'
58
+
59
+ export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
60
+ const key = myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined
61
+ if (!key) throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } })
62
+ const encKeyId = Buffer.from(myAppStateKeyId, 'base64')
63
+ state = { ...state, indexValueMap: { ...state.indexValueMap } }
64
+ const indexBuffer = Buffer.from(JSON.stringify(index))
65
+ const dataProto = proto.SyncActionData.fromObject({ index: indexBuffer, value: syncAction, padding: new Uint8Array(0), version: apiVersion })
66
+ const encoded = proto.SyncActionData.encode(dataProto).finish()
67
+ const keyValue = mutationKeys(key.keyData)
68
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey)
69
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey)
70
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey)
71
+ const generator = makeLtHashGenerator(state)
72
+ generator.mix({ indexMac, valueMac, operation })
73
+ Object.assign(state, await generator.finish())
74
+ state.version += 1
75
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey)
76
+ const patch = {
77
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
78
+ snapshotMac,
79
+ keyId: { id: encKeyId },
80
+ mutations: [{ operation, record: { index: { blob: indexMac }, value: { blob: Buffer.concat([encValue, valueMac]) }, keyId: { id: encKeyId } } }]
81
+ }
82
+ state.indexValueMap[indexMac.toString('base64')] = { valueMac }
83
+ return { patch, state }
84
+ }
85
+
86
+ export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
87
+ const ltGenerator = makeLtHashGenerator(initialState)
88
+ const derivedKeyCache = new Map()
89
+
90
+ async function getKey(keyId) {
91
+ const base64Key = Buffer.from(keyId).toString('base64')
92
+ if (derivedKeyCache.has(base64Key)) return derivedKeyCache.get(base64Key)
93
+ const keyEnc = await getAppStateSyncKey(base64Key)
94
+ if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true, msgMutations } })
95
+ const keys = mutationKeys(keyEnc.keyData)
96
+ derivedKeyCache.set(base64Key, keys)
97
+ return keys
98
+ }
99
+
100
+ for (const msgMutation of msgMutations) {
101
+ const operation = 'operation' in msgMutation ? msgMutation.operation : OP.SET
102
+ const record = 'record' in msgMutation && msgMutation.record ? msgMutation.record : msgMutation
103
+ let key
104
+ try { key = await getKey(record.keyId.id) } catch (err) { if (isMissingKeyError(err)) throw err; continue }
105
+ if (!record?.value?.blob) continue
106
+ const content = record.value.blob
107
+ const encContent = content.subarray(0, -32)
108
+ const ogValueMac = content.subarray(-32)
109
+ if (validateMacs) {
110
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey)
111
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) continue
112
+ }
113
+ let result
114
+ try { result = aesDecrypt(encContent, key.valueEncryptionKey) } catch { continue }
115
+ const syncAction = proto.SyncActionData.decode(result)
116
+ if (validateMacs) {
117
+ const hmac = hmacSign(syncAction.index, key.indexKey)
118
+ if (Buffer.compare(hmac, record.index.blob) !== 0) throw new Boom('HMAC index verification failed')
119
+ }
120
+ if (syncAction.index) onMutation({ syncAction, index: JSON.parse(Buffer.from(syncAction.index).toString()) })
121
+ ltGenerator.mix({ indexMac: record.index.blob, valueMac: ogValueMac, operation })
122
+ }
123
+ return ltGenerator.finish()
124
+ }
125
+
126
+ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
127
+ if (validateMacs) {
128
+ const base64Key = Buffer.from(msg.keyId.id).toString('base64')
129
+ const mainKeyObj = await getAppStateSyncKey(base64Key)
130
+ if (!mainKeyObj) throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } })
131
+ const mainKey = mutationKeys(mainKeyObj.keyData)
132
+ const mutationmacs = msg.mutations.map(m => m.record.value.blob.slice(-32))
133
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey)
134
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) throw new Boom('Invalid patch mac')
135
+ }
136
+ return decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs)
137
+ }
138
+
139
+ export const extractSyncdPatches = async (result, options) => {
140
+ const syncNode = getBinaryNodeChild(result, 'sync')
141
+ const collectionNodes = getBinaryNodeChildren(syncNode, 'collection')
142
+ const final = {}
143
+ await Promise.all(collectionNodes.map(async collectionNode => {
144
+ const patchesNode = getBinaryNodeChild(collectionNode, 'patches')
145
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch')
146
+ const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot')
147
+ const syncds = []
148
+ const name = collectionNode.attrs.name
149
+ const hasMorePatches = collectionNode.attrs.has_more_patches === 'true'
150
+ let snapshot
151
+ if (snapshotNode?.content) {
152
+ if (!Buffer.isBuffer(snapshotNode)) snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
153
+ const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content)
154
+ snapshot = proto.SyncdSnapshot.decode(await downloadExternalBlob(blobRef, options))
155
+ }
156
+ for (let { content } of patches) {
157
+ if (!content) continue
158
+ if (!Buffer.isBuffer(content)) content = Buffer.from(Object.values(content))
159
+ const syncd = proto.SyncdPatch.decode(content)
160
+ if (!syncd.version) syncd.version = { version: +collectionNode.attrs.version + 1 }
161
+ syncds.push(syncd)
162
+ }
163
+ final[name] = { patches: syncds, hasMorePatches, snapshot }
164
+ }))
165
+ return final
166
+ }
167
+
168
+ export const downloadExternalBlob = async (blob, options) => {
169
+ const stream = await downloadContentFromMessage(blob, 'md-app-state', { options })
170
+ const bufferArray = []
171
+ for await (const chunk of stream) bufferArray.push(chunk)
172
+ return Buffer.concat(bufferArray)
173
+ }
174
+
175
+ export const downloadExternalPatch = async (blob, options) => {
176
+ const buffer = await downloadExternalBlob(blob, options)
177
+ return proto.SyncdMutations.decode(buffer)
178
+ }
179
+
180
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
181
+ const newState = newLTHashState()
182
+ newState.version = toNumber(snapshot.version.version)
183
+ const mutationMap = {}
184
+ const areMutationsRequired = minimumVersionNumber === undefined || newState.version > minimumVersionNumber
185
+ const onMutation = areMutationsRequired ? mutation => { const index = mutation.syncAction.index?.toString(); mutationMap[index] = mutation } : () => { }
186
+ const { hash, indexValueMap } = await decodeSyncdMutations(snapshot.records, newState, getAppStateSyncKey, onMutation, validateMacs)
187
+ newState.hash = hash
188
+ newState.indexValueMap = indexValueMap
189
+ if (validateMacs) {
190
+ const base64Key = Buffer.from(snapshot.keyId.id).toString('base64')
191
+ const keyEnc = await getAppStateSyncKey(base64Key)
192
+ if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } })
193
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, mutationKeys(keyEnc.keyData).snapshotMacKey)
194
+ // soft failure — MAC mismatch on snapshot doesn't abort; state is still usable
195
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state')
196
+ }
197
+ return { state: newState, mutationMap }
198
+ }
199
+
200
+ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
201
+ const newState = { ...initial, indexValueMap: { ...initial.indexValueMap } }
202
+ const mutationMap = {}
203
+ for (const syncd of syncds) {
204
+ const { version, keyId, snapshotMac } = syncd
205
+ if (syncd.externalMutations) {
206
+ logger?.trace({ name, version }, 'downloading external patch')
207
+ const ref = await downloadExternalPatch(syncd.externalMutations, options)
208
+ logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch')
209
+ syncd.mutations?.push(...ref.mutations)
210
+ }
211
+ const patchVersion = toNumber(version.version)
212
+ newState.version = patchVersion
213
+ const shouldMutate = minimumVersionNumber === undefined || patchVersion > minimumVersionNumber
214
+ const onMutation = shouldMutate ? mutation => { const index = mutation.syncAction.index?.toString(); mutationMap[index] = mutation } : () => { }
215
+ let decodeResult
216
+ try { decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, onMutation, validateMacs) }
217
+ catch (err) { if (isMissingKeyError(err)) throw err; logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping'); continue }
218
+ newState.hash = decodeResult.hash
219
+ newState.indexValueMap = decodeResult.indexValueMap
220
+ if (validateMacs) {
221
+ const base64Key = Buffer.from(keyId.id).toString('base64')
222
+ const keyEnc = await getAppStateSyncKey(base64Key)
223
+ if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } })
224
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, mutationKeys(keyEnc.keyData).snapshotMacKey)
225
+ // MAC mismatch mid-patch-stream means state is corrupted from this point; stop processing
226
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) { logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches'); break }
227
+ }
228
+ syncd.mutations = []
229
+ }
230
+ return { state: newState, mutationMap }
231
+ }
232
+
233
+ export const chatModificationToAppPatch = (mod, jid) => {
234
+ const getMessageRange = lastMessages => {
235
+ if (!Array.isArray(lastMessages)) return lastMessages
236
+ const lastMsg = lastMessages[lastMessages.length - 1]
237
+ return {
238
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
239
+ messages: lastMessages?.length ? lastMessages.map(m => {
240
+ if (!m.key?.id || !m.key?.remoteJid) throw new Boom('Incomplete key', { statusCode: 400, data: m })
241
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m })
242
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m })
243
+ if (m.key.participant) m.key.participant = jidNormalizedUser(m.key.participant)
244
+ return m
245
+ }) : undefined
246
+ }
247
+ }
248
+
249
+ let patch
250
+ if ('mute' in mod) patch = { syncAction: { muteAction: { muted: !!mod.mute, muteEndTimestamp: mod.mute || undefined } }, index: ['mute', jid], type: 'regular_high', apiVersion: 2, operation: OP.SET }
251
+ else if ('archive' in mod) patch = { syncAction: { archiveChatAction: { archived: !!mod.archive, messageRange: getMessageRange(mod.lastMessages) } }, index: ['archive', jid], type: 'regular_low', apiVersion: 3, operation: OP.SET }
252
+ else if ('markRead' in mod) patch = { syncAction: { markChatAsReadAction: { read: mod.markRead, messageRange: getMessageRange(mod.lastMessages) } }, index: ['markChatAsRead', jid], type: 'regular_low', apiVersion: 3, operation: OP.SET }
253
+ else if ('deleteForMe' in mod) { const { timestamp, key, deleteMedia } = mod.deleteForMe; patch = { syncAction: { deleteMessageForMeAction: { deleteMedia, messageTimestamp: timestamp } }, index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'], type: 'regular_high', apiVersion: 3, operation: OP.SET } }
254
+ else if ('clear' in mod) patch = { syncAction: { clearChatAction: { messageRange: getMessageRange(mod.lastMessages) } }, index: ['clearChat', jid, '1', '0'], type: 'regular_high', apiVersion: 6, operation: OP.SET }
255
+ else if ('pin' in mod) patch = { syncAction: { pinAction: { pinned: !!mod.pin } }, index: ['pin_v1', jid], type: 'regular_low', apiVersion: 5, operation: OP.SET }
256
+ else if ('contact' in mod) patch = { syncAction: { contactAction: mod.contact || {} }, index: ['contact', jid], type: 'critical_unblock_low', apiVersion: 2, operation: mod.contact ? OP.SET : OP.REMOVE }
257
+ else if ('disableLinkPreviews' in mod) patch = { syncAction: { privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {} }, index: ['setting_disableLinkPreviews'], type: 'regular', apiVersion: 8, operation: OP.SET }
258
+ else if ('star' in mod) { const key = mod.star.messages[0]; patch = { syncAction: { starAction: { starred: !!mod.star.star } }, index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'], type: 'regular_low', apiVersion: 2, operation: OP.SET } }
259
+ else if ('delete' in mod) patch = { syncAction: { deleteChatAction: { messageRange: getMessageRange(mod.lastMessages) } }, index: ['deleteChat', jid, '1'], type: 'regular_high', apiVersion: 6, operation: OP.SET }
260
+ else if ('pushNameSetting' in mod) patch = { syncAction: { pushNameSetting: { name: mod.pushNameSetting } }, index: ['setting_pushName'], type: 'critical_block', apiVersion: 1, operation: OP.SET }
261
+ else if ('quickReply' in mod) patch = { syncAction: { quickReplyAction: { count: 0, deleted: mod.quickReply.deleted || false, keywords: [], message: mod.quickReply.message || '', shortcut: mod.quickReply.shortcut || '' } }, index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))], type: 'regular', apiVersion: 2, operation: OP.SET }
262
+ else if ('addLabel' in mod) patch = { syncAction: { labelEditAction: { name: mod.addLabel.name, color: mod.addLabel.color, predefinedId: mod.addLabel.predefinedId, deleted: mod.addLabel.deleted } }, index: ['label_edit', mod.addLabel.id], type: 'regular', apiVersion: 3, operation: OP.SET }
263
+ else if ('addChatLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: true } }, index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid], type: 'regular', apiVersion: 3, operation: OP.SET }
264
+ else if ('removeChatLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: false } }, index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid], type: 'regular', apiVersion: 3, operation: OP.SET }
265
+ else if ('addMessageLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: true } }, index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'], type: 'regular', apiVersion: 3, operation: OP.SET }
266
+ else if ('removeMessageLabel' in mod) patch = { syncAction: { labelAssociationAction: { labeled: false } }, index: [LabelAssociationType.Message, mod.removeMessageLabel.labelId, jid, mod.removeMessageLabel.messageId, '0', '0'], type: 'regular', apiVersion: 3, operation: OP.SET }
267
+ else throw new Boom('not supported')
268
+
269
+ patch.syncAction.timestamp = Date.now()
270
+ return patch
271
+ }
272
+
273
+ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
274
+ const isInitialSync = !!initialSyncOpts
275
+ const accountSettings = initialSyncOpts?.accountSettings
276
+ logger?.trace({ syncAction, initialSync: isInitialSync }, 'processing sync action')
277
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction
278
+
279
+ const getChatUpdateConditional = (id, msgRange) => !isInitialSync ? undefined : data => {
280
+ const chat = data.historySets.chats[id] || data.chatUpserts[id]
281
+ if (!chat) return false
282
+ if (!msgRange) return true
283
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
284
+ return lastMsgTimestamp >= Number(chat?.lastMessageRecvTimestamp || 0)
285
+ }
286
+
287
+ if (action?.muteAction) ev.emit('chats.update', [{ id, muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
288
+ else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') { const archiveAction = action?.archiveChatAction; ev.emit('chats.update', [{ id, archived: archiveAction ? archiveAction.archived : type === 'archive', conditional: getChatUpdateConditional(id, !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange) }]) }
289
+ else if (action?.markChatAsReadAction) ev.emit('chats.update', [{ id, unreadCount: isInitialSync && action.markChatAsReadAction.read ? null : action.markChatAsReadAction?.read ? 0 : -1, conditional: getChatUpdateConditional(id, action.markChatAsReadAction?.messageRange) }])
290
+ else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') ev.emit('messages.delete', { keys: [{ remoteJid: id, id: msgId, fromMe: fromMe === '1' }] })
291
+ else if (action?.contactAction) emitSyncActionResults(ev, processContactAction(action.contactAction, id, logger))
292
+ else if (action?.pushNameSetting) { const name = action?.pushNameSetting?.name; if (name && me?.name !== name) ev.emit('creds.update', { me: { ...me, name } }) }
293
+ else if (action?.pinAction) ev.emit('chats.update', [{ id, pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
294
+ else if (action?.unarchiveChatsSetting) { const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats; ev.emit('creds.update', { accountSettings: { unarchiveChats } }); if (accountSettings) accountSettings.unarchiveChats = unarchiveChats }
295
+ else if (action?.starAction || type === 'star') { let starred = action?.starAction?.starred; if (typeof starred !== 'boolean') starred = syncAction.index[syncAction.index.length - 1] === '1'; ev.emit('messages.update', [{ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' }, update: { starred } }]) }
296
+ else if (action?.deleteChatAction || type === 'deleteChat') { if (!isInitialSync) ev.emit('chats.delete', [id]) }
297
+ else if (action?.labelEditAction) { const { name, color, deleted, predefinedId } = action.labelEditAction; ev.emit('labels.edit', { id, name, color, deleted, predefinedId: predefinedId ? String(predefinedId) : undefined }) }
298
+ else if (action?.labelAssociationAction) ev.emit('labels.association', { type: action.labelAssociationAction.labeled ? 'add' : 'remove', association: type === LabelAssociationType.Chat ? { type: LabelAssociationType.Chat, chatId: syncAction.index[2], labelId: syncAction.index[1] } : { type: LabelAssociationType.Message, chatId: syncAction.index[2], messageId: syncAction.index[3], labelId: syncAction.index[1] } })
299
+ else if (action?.localeSetting?.locale) ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale })
300
+ else if (action?.timeFormatAction) ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction })
301
+ else if (action?.pnForLidChatAction?.pnJid) ev.emit('lid-mapping.update', { lid: id, pn: action.pnForLidChatAction.pnJid })
302
+ else if (action?.privacySettingRelayAllCalls) ev.emit('settings.update', { setting: 'privacySettingRelayAllCalls', value: action.privacySettingRelayAllCalls })
303
+ else if (action?.statusPrivacy) ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy })
304
+ else if (action?.lockChatAction) ev.emit('chats.lock', { id, locked: !!action.lockChatAction.locked })
305
+ else if (action?.privacySettingDisableLinkPreviewsAction) ev.emit('settings.update', { setting: 'disableLinkPreviews', value: action.privacySettingDisableLinkPreviewsAction })
306
+ else if (action?.notificationActivitySettingAction?.notificationActivitySetting) ev.emit('settings.update', { setting: 'notificationActivitySetting', value: action.notificationActivitySettingAction.notificationActivitySetting })
307
+ else if (action?.lidContactAction) ev.emit('contacts.upsert', [{ id, name: action.lidContactAction.fullName || action.lidContactAction.firstName || action.lidContactAction.username || undefined, username: action.lidContactAction.username || undefined, lid: id, phoneNumber: undefined }])
308
+ else if (action?.privacySettingChannelsPersonalisedRecommendationAction) ev.emit('settings.update', { setting: 'channelsPersonalisedRecommendation', value: action.privacySettingChannelsPersonalisedRecommendationAction })
309
+ else if (action?.aiThreadRenameAction) ev.emit('chats.update', [{ id, name: action.aiThreadRenameAction.newTitle || undefined, conditional: getChatUpdateConditional(id, undefined) }])
310
+ else if (action?.threadPinAction) ev.emit('chats.update', [{ id, pinned: action.threadPinAction.pinned ? toNumber(action.timestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
311
+ else if (action?.newsletterSavedInterestsAction) ev.emit('settings.update', { setting: 'newsletterSavedInterests', value: action.newsletterSavedInterestsAction.newsletterSavedInterests })
312
+ else if (action?.interactiveMessageAction) ev.emit('messages.update', [{ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' }, update: { interactiveMessageAction: action.interactiveMessageAction } }])
313
+ else if (action?.deviceCapabilities || action?.deviceCapabilitiesV2) ev.emit('creds.update', { deviceCapabilities: action.deviceCapabilities || action.deviceCapabilitiesV2 })
314
+ else if (action?.nctSaltSyncAction) ev.emit('creds.update', { nctSalt: action.nctSaltSyncAction.salt })
315
+ else if (action?.bubbleLockMessageAction) ev.emit('messages.update', [{ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' }, update: { bubbleLocked: !!action.bubbleLockMessageAction.locked } }])
316
+ else logger?.debug({ syncAction, id }, 'unprocessable update')
317
317
  }