@nerxa/socketon 0.0.0-stage → 1.21.0

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 (289) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +24 -0
  3. package/README.md +6317 -2
  4. package/WAProto/index.d.ts +17301 -0
  5. package/WAProto/index.js +125088 -0
  6. package/engine-requirements.js +14 -0
  7. package/package.json +100 -4
  8. package/src/Defaults/index.d.ts +152 -0
  9. package/src/Defaults/index.js +164 -0
  10. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  11. package/src/MessageBuilder/bot-signature.js +122 -0
  12. package/src/MessageBuilder/extras.d.ts +449 -0
  13. package/src/MessageBuilder/extras.js +1356 -0
  14. package/src/MessageBuilder/index.d.ts +210 -0
  15. package/src/MessageBuilder/index.js +3594 -0
  16. package/src/MessageBuilder/metaai.d.ts +438 -0
  17. package/src/MessageBuilder/metaai.js +890 -0
  18. package/src/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/src/Signal/Group/ciphertext-message.js +11 -0
  20. package/src/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/src/Signal/Group/group-session-builder.js +27 -0
  22. package/src/Signal/Group/group_cipher.d.ts +11 -0
  23. package/src/Signal/Group/group_cipher.js +78 -0
  24. package/src/Signal/Group/index.d.ts +11 -0
  25. package/src/Signal/Group/index.js +11 -0
  26. package/src/Signal/Group/keyhelper.d.ts +6 -0
  27. package/src/Signal/Group/keyhelper.js +17 -0
  28. package/src/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/src/Signal/Group/sender-chain-key.js +25 -0
  30. package/src/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/src/Signal/Group/sender-key-distribution-message.js +62 -0
  32. package/src/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/src/Signal/Group/sender-key-message.js +65 -0
  34. package/src/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/src/Signal/Group/sender-key-name.js +47 -0
  36. package/src/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/src/Signal/Group/sender-key-record.js +40 -0
  38. package/src/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/src/Signal/Group/sender-key-state.js +83 -0
  40. package/src/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/src/Signal/Group/sender-message-key.js +25 -0
  42. package/src/Signal/libsignal.d.ts +54 -0
  43. package/src/Signal/libsignal.js +427 -0
  44. package/src/Signal/lid-mapping.d.ts +20 -0
  45. package/src/Signal/lid-mapping.js +274 -0
  46. package/src/Socket/Client/index.d.ts +2 -0
  47. package/src/Socket/Client/index.js +3 -0
  48. package/src/Socket/Client/tcp.js +177 -0
  49. package/src/Socket/Client/types.d.ts +5 -0
  50. package/src/Socket/Client/types.js +9 -0
  51. package/src/Socket/Client/websocket.d.ts +12 -0
  52. package/src/Socket/Client/websocket.js +53 -0
  53. package/src/Socket/business.d.ts +431 -0
  54. package/src/Socket/business.js +379 -0
  55. package/src/Socket/chats.d.ts +247 -0
  56. package/src/Socket/chats.js +1484 -0
  57. package/src/Socket/communities.d.ts +598 -0
  58. package/src/Socket/communities.js +421 -0
  59. package/src/Socket/email.js +145 -0
  60. package/src/Socket/groups.d.ts +298 -0
  61. package/src/Socket/groups.js +339 -0
  62. package/src/Socket/index.d.ts +581 -0
  63. package/src/Socket/index.js +37 -0
  64. package/src/Socket/messages-recv.d.ts +370 -0
  65. package/src/Socket/messages-recv.js +1864 -0
  66. package/src/Socket/messages-send.d.ts +390 -0
  67. package/src/Socket/messages-send.js +1574 -0
  68. package/src/Socket/mex.d.ts +1 -0
  69. package/src/Socket/mex.js +44 -0
  70. package/src/Socket/mobile-builders.js +72 -0
  71. package/src/Socket/mobile.js +424 -0
  72. package/src/Socket/newsletter.d.ts +468 -0
  73. package/src/Socket/newsletter.js +671 -0
  74. package/src/Socket/socket.d.ts +77 -0
  75. package/src/Socket/socket.js +1106 -0
  76. package/src/Store/index.d.ts +3 -0
  77. package/src/Store/index.js +3 -0
  78. package/src/Store/make-in-memory-store.d.ts +62 -0
  79. package/src/Store/make-in-memory-store.js +396 -0
  80. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  81. package/src/Store/make-ordered-dictionary.js +78 -0
  82. package/src/Store/object-repository.d.ts +10 -0
  83. package/src/Store/object-repository.js +23 -0
  84. package/src/Types/Auth.d.ts +1 -0
  85. package/src/Types/Auth.js +1 -0
  86. package/src/Types/Bussines.d.ts +1 -0
  87. package/src/Types/Bussines.js +1 -0
  88. package/src/Types/Call.d.ts +1 -0
  89. package/src/Types/Call.js +1 -0
  90. package/src/Types/Chat.d.ts +2 -0
  91. package/src/Types/Chat.js +24 -0
  92. package/src/Types/Contact.d.ts +1 -0
  93. package/src/Types/Contact.js +1 -0
  94. package/src/Types/Events.d.ts +1 -0
  95. package/src/Types/Events.js +0 -0
  96. package/src/Types/GroupMetadata.d.ts +5 -0
  97. package/src/Types/GroupMetadata.js +6 -0
  98. package/src/Types/Label.d.ts +2 -0
  99. package/src/Types/Label.js +24 -0
  100. package/src/Types/LabelAssociation.d.ts +2 -0
  101. package/src/Types/LabelAssociation.js +6 -0
  102. package/src/Types/Message.d.ts +13 -0
  103. package/src/Types/Message.js +23 -0
  104. package/src/Types/Mex.d.ts +2 -0
  105. package/src/Types/Mex.js +95 -0
  106. package/src/Types/Product.d.ts +1 -0
  107. package/src/Types/Product.js +1 -0
  108. package/src/Types/Signal.d.ts +1 -0
  109. package/src/Types/Signal.js +0 -0
  110. package/src/Types/Socket.d.ts +1 -0
  111. package/src/Types/Socket.js +0 -0
  112. package/src/Types/State.d.ts +5 -0
  113. package/src/Types/State.js +54 -0
  114. package/src/Types/USync.d.ts +1 -0
  115. package/src/Types/USync.js +0 -0
  116. package/src/Types/index.d.ts +13 -0
  117. package/src/Types/index.js +25 -0
  118. package/src/Utils/auth-store.d.ts +29 -0
  119. package/src/Utils/auth-store.js +76 -0
  120. package/src/Utils/auth-utils.d.ts +58 -0
  121. package/src/Utils/auth-utils.js +273 -0
  122. package/src/Utils/browser-utils.d.ts +9 -0
  123. package/src/Utils/browser-utils.js +28 -0
  124. package/src/Utils/business.d.ts +49 -0
  125. package/src/Utils/business.js +226 -0
  126. package/src/Utils/chat-utils.d.ts +408 -0
  127. package/src/Utils/chat-utils.js +846 -0
  128. package/src/Utils/companion-reg-client-utils.d.ts +4 -0
  129. package/src/Utils/companion-reg-client-utils.js +39 -0
  130. package/src/Utils/crypto.d.ts +39 -0
  131. package/src/Utils/crypto.js +110 -0
  132. package/src/Utils/decode-wa-message.d.ts +99 -0
  133. package/src/Utils/decode-wa-message.js +373 -0
  134. package/src/Utils/event-buffer.d.ts +22 -0
  135. package/src/Utils/event-buffer.js +624 -0
  136. package/src/Utils/generics.d.ts +63 -0
  137. package/src/Utils/generics.js +375 -0
  138. package/src/Utils/group-metadata-cache.d.ts +4 -0
  139. package/src/Utils/group-metadata-cache.js +25 -0
  140. package/src/Utils/history.d.ts +75 -0
  141. package/src/Utils/history.js +131 -0
  142. package/src/Utils/html-app.d.ts +19 -0
  143. package/src/Utils/html-app.js +96 -0
  144. package/src/Utils/html-multiplayer.d.ts +10 -0
  145. package/src/Utils/html-multiplayer.js +94 -0
  146. package/src/Utils/identity-change-handler.d.ts +13 -0
  147. package/src/Utils/identity-change-handler.js +48 -0
  148. package/src/Utils/index.d.ts +44 -0
  149. package/src/Utils/index.js +44 -0
  150. package/src/Utils/link-preview-metadata.d.ts +47 -0
  151. package/src/Utils/link-preview-metadata.js +88 -0
  152. package/src/Utils/link-preview.d.ts +12 -0
  153. package/src/Utils/link-preview.js +79 -0
  154. package/src/Utils/logger.d.ts +2 -0
  155. package/src/Utils/logger.js +2 -0
  156. package/src/Utils/lt-hash.d.ts +6 -0
  157. package/src/Utils/lt-hash.js +3 -0
  158. package/src/Utils/make-mutex.d.ts +6 -0
  159. package/src/Utils/make-mutex.js +32 -0
  160. package/src/Utils/message-retry-manager.d.ts +79 -0
  161. package/src/Utils/message-retry-manager.js +255 -0
  162. package/src/Utils/messages-media.d.ts +136 -0
  163. package/src/Utils/messages-media.js +814 -0
  164. package/src/Utils/messages.d.ts +62 -0
  165. package/src/Utils/messages.js +2223 -0
  166. package/src/Utils/mobile-companion-crypto.js +191 -0
  167. package/src/Utils/modern-messages.d.ts +150 -0
  168. package/src/Utils/modern-messages.js +496 -0
  169. package/src/Utils/native-flow.d.ts +11 -0
  170. package/src/Utils/native-flow.js +115 -0
  171. package/src/Utils/newsletter-status.d.ts +158 -0
  172. package/src/Utils/newsletter-status.js +651 -0
  173. package/src/Utils/noise-handler.d.ts +20 -0
  174. package/src/Utils/noise-handler.js +200 -0
  175. package/src/Utils/offline-node-processor.d.ts +9 -0
  176. package/src/Utils/offline-node-processor.js +33 -0
  177. package/src/Utils/optional-media.d.ts +3 -0
  178. package/src/Utils/optional-media.js +45 -0
  179. package/src/Utils/payment-messages.d.ts +66 -0
  180. package/src/Utils/payment-messages.js +160 -0
  181. package/src/Utils/pre-key-manager.d.ts +25 -0
  182. package/src/Utils/pre-key-manager.js +95 -0
  183. package/src/Utils/process-message.d.ts +60 -0
  184. package/src/Utils/process-message.js +688 -0
  185. package/src/Utils/reporting-utils.d.ts +12 -0
  186. package/src/Utils/reporting-utils.js +256 -0
  187. package/src/Utils/scheduled-message.d.ts +51 -0
  188. package/src/Utils/scheduled-message.js +112 -0
  189. package/src/Utils/sender-key-memory.d.ts +19 -0
  190. package/src/Utils/sender-key-memory.js +51 -0
  191. package/src/Utils/signal.d.ts +82 -0
  192. package/src/Utils/signal.js +193 -0
  193. package/src/Utils/stanza-ack.d.ts +16 -0
  194. package/src/Utils/stanza-ack.js +30 -0
  195. package/src/Utils/status-stickers.d.ts +127 -0
  196. package/src/Utils/status-stickers.js +260 -0
  197. package/src/Utils/sync-action-utils.d.ts +2 -0
  198. package/src/Utils/sync-action-utils.js +44 -0
  199. package/src/Utils/tc-token-utils.d.ts +29 -0
  200. package/src/Utils/tc-token-utils.js +155 -0
  201. package/src/Utils/ttl-cache.d.ts +28 -0
  202. package/src/Utils/ttl-cache.js +120 -0
  203. package/src/Utils/use-mongo-auth-state.d.ts +21 -0
  204. package/src/Utils/use-mongo-auth-state.js +67 -0
  205. package/src/Utils/use-multi-file-auth-state.d.ts +11 -0
  206. package/src/Utils/use-multi-file-auth-state.js +106 -0
  207. package/src/Utils/use-mysql-auth-state.d.ts +19 -0
  208. package/src/Utils/use-mysql-auth-state.js +79 -0
  209. package/src/Utils/use-postgres-auth-state.d.ts +19 -0
  210. package/src/Utils/use-postgres-auth-state.js +79 -0
  211. package/src/Utils/use-redis-auth-state.d.ts +19 -0
  212. package/src/Utils/use-redis-auth-state.js +89 -0
  213. package/src/Utils/use-single-file-auth-state.d.ts +10 -0
  214. package/src/Utils/use-single-file-auth-state.js +108 -0
  215. package/src/Utils/use-sqlite-auth-state.d.ts +12 -0
  216. package/src/Utils/use-sqlite-auth-state.js +120 -0
  217. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  218. package/src/Utils/useNekoDBAuth.js +111 -0
  219. package/src/Utils/username.d.ts +12 -0
  220. package/src/Utils/username.js +58 -0
  221. package/src/Utils/validate-connection.d.ts +43 -0
  222. package/src/Utils/validate-connection.js +277 -0
  223. package/src/Utils/voice-recognition.d.ts +53 -0
  224. package/src/Utils/voice-recognition.js +219 -0
  225. package/src/Voip/audio-feeder.d.ts +24 -0
  226. package/src/Voip/audio-feeder.js +268 -0
  227. package/src/Voip/index.d.ts +88 -0
  228. package/src/Voip/index.js +936 -0
  229. package/src/Voip/relay-transport.d.ts +5 -0
  230. package/src/Voip/relay-transport.js +824 -0
  231. package/src/Voip/signaling.d.ts +11 -0
  232. package/src/Voip/signaling.js +1099 -0
  233. package/src/Voip/types.d.ts +2 -0
  234. package/src/Voip/types.js +12 -0
  235. package/src/Voip/video-feeder.d.ts +24 -0
  236. package/src/Voip/video-feeder.js +268 -0
  237. package/src/Voip/wasm-engine.d.ts +26 -0
  238. package/src/Voip/wasm-engine.js +1307 -0
  239. package/src/Voip/worker-bootstrap.js +1023 -0
  240. package/src/WABinary/constants.d.ts +22 -0
  241. package/src/WABinary/constants.js +1300 -0
  242. package/src/WABinary/decode.d.ts +9 -0
  243. package/src/WABinary/decode.js +261 -0
  244. package/src/WABinary/encode.d.ts +2 -0
  245. package/src/WABinary/encode.js +219 -0
  246. package/src/WABinary/generic-utils.d.ts +76 -0
  247. package/src/WABinary/generic-utils.js +214 -0
  248. package/src/WABinary/index.d.ts +5 -0
  249. package/src/WABinary/index.js +5 -0
  250. package/src/WABinary/jid-utils.d.ts +30 -0
  251. package/src/WABinary/jid-utils.js +97 -0
  252. package/src/WABinary/types.d.ts +1 -0
  253. package/src/WABinary/types.js +0 -0
  254. package/src/WAM/BinaryInfo.d.ts +7 -0
  255. package/src/WAM/BinaryInfo.js +9 -0
  256. package/src/WAM/constants.d.ts +34926 -0
  257. package/src/WAM/constants.js +22852 -0
  258. package/src/WAM/encode.d.ts +1 -0
  259. package/src/WAM/encode.js +148 -0
  260. package/src/WAM/index.d.ts +3 -0
  261. package/src/WAM/index.js +3 -0
  262. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +50 -0
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  265. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +51 -0
  266. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  267. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  268. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  269. package/src/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  270. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  271. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  272. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  273. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  274. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  275. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  276. package/src/WAUSync/Protocols/index.d.ts +5 -0
  277. package/src/WAUSync/Protocols/index.js +5 -0
  278. package/src/WAUSync/USyncQuery.d.ts +20 -0
  279. package/src/WAUSync/USyncQuery.js +93 -0
  280. package/src/WAUSync/USyncUser.d.ts +16 -0
  281. package/src/WAUSync/USyncUser.js +30 -0
  282. package/src/WAUSync/index.d.ts +3 -0
  283. package/src/WAUSync/index.js +3 -0
  284. package/src/assets/wasm/README.md +76 -0
  285. package/src/assets/wasm/loader.js +5 -0
  286. package/src/assets/wasm/whatsapp.wasm +0 -0
  287. package/src/assets/wasm/worker-modules.js +273 -0
  288. package/src/index.d.ts +43 -0
  289. package/src/index.js +48 -0
@@ -0,0 +1,846 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { expandAppStateKeys } from '@rexxhayanasi/wangcap-id-bridge';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { GroupHistoryToggleMode } from '../Types/GroupMetadata.js';
5
+ import { LabelAssociationType } from '../Types/LabelAssociation.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
+ import { emitSyncActionResults, processContactAction } from './sync-action-utils.js';
12
+ const mutationKeys = (keydata) => {
13
+ const keys = expandAppStateKeys(keydata);
14
+ return {
15
+ indexKey: keys.indexKey,
16
+ valueEncryptionKey: keys.valueEncryptionKey,
17
+ valueMacKey: keys.valueMacKey,
18
+ snapshotMacKey: keys.snapshotMacKey,
19
+ patchMacKey: keys.patchMacKey
20
+ };
21
+ };
22
+ const generateMac = (operation, data, keyId, key) => {
23
+ const opByte = operation === proto.SyncdMutation.SyncdOperation.SET ? 0x01 : 0x02;
24
+ const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId;
25
+ const keyData = new Uint8Array(1 + keyIdBuffer.length);
26
+ keyData[0] = opByte;
27
+ keyData.set(keyIdBuffer, 1);
28
+ const last = new Uint8Array(8);
29
+ last[7] = keyData.length;
30
+ const total = new Uint8Array(keyData.length + data.length + last.length);
31
+ total.set(keyData, 0);
32
+ total.set(data, keyData.length);
33
+ total.set(last, keyData.length + data.length);
34
+ const hmac = hmacSign(total, key, 'sha512');
35
+ return hmac.subarray(0, 32);
36
+ };
37
+ const to64BitNetworkOrder = (e) => {
38
+ const buff = Buffer.alloc(8);
39
+ buff.writeUint32BE(e, 4);
40
+ return buff;
41
+ };
42
+ export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
43
+ indexValueMap = { ...indexValueMap };
44
+ const addBuffs = [];
45
+ const subBuffs = [];
46
+ return {
47
+ mix: ({ indexMac, valueMac, operation }) => {
48
+ const indexMacBase64 = Buffer.from(indexMac).toString('base64');
49
+ const prevOp = indexValueMap[indexMacBase64];
50
+ if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
51
+ if (!prevOp) {
52
+
53
+ return;
54
+ }
55
+
56
+ delete indexValueMap[indexMacBase64];
57
+ }
58
+ else {
59
+ addBuffs.push(valueMac);
60
+
61
+ indexValueMap[indexMacBase64] = { valueMac };
62
+ }
63
+ if (prevOp) {
64
+ subBuffs.push(prevOp.valueMac);
65
+ }
66
+ },
67
+ finish: () => {
68
+ const result = LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs);
69
+ return {
70
+ hash: Buffer.from(result),
71
+ indexValueMap
72
+ };
73
+ }
74
+ };
75
+ };
76
+ const generateSnapshotMac = (lthash, version, name, key) => {
77
+ const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]);
78
+ return hmacSign(total, key, 'sha256');
79
+ };
80
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
81
+ const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]);
82
+ return hmacSign(total, key);
83
+ };
84
+ export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
85
+ export const ensureLTHashStateVersion = (state) => {
86
+ if (typeof state.version !== 'number' || isNaN(state.version)) {
87
+ state.version = 0;
88
+ }
89
+ return state;
90
+ };
91
+ export const MAX_SYNC_ATTEMPTS = 2;
92
+
93
+ export const isMissingKeyError = (error) => {
94
+ return error?.data?.isMissingKey === true;
95
+ };
96
+
97
+ export const isAppStateSyncIrrecoverable = (error, attempts) => {
98
+ return attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError';
99
+ };
100
+ export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
101
+ const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
102
+ if (!key) {
103
+ throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } });
104
+ }
105
+ const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
106
+ state = { ...state, indexValueMap: { ...state.indexValueMap } };
107
+ const indexBuffer = Buffer.from(JSON.stringify(index));
108
+ const dataProto = proto.SyncActionData.fromObject({
109
+ index: indexBuffer,
110
+ value: syncAction,
111
+ padding: new Uint8Array(0),
112
+ version: apiVersion
113
+ });
114
+ const encoded = proto.SyncActionData.encode(dataProto).finish();
115
+ const keyValue = mutationKeys(key.keyData);
116
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey);
117
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
118
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey);
119
+
120
+ const generator = makeLtHashGenerator(state);
121
+ generator.mix({ indexMac, valueMac, operation });
122
+ Object.assign(state, generator.finish());
123
+ state.version += 1;
124
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
125
+ const patch = {
126
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
127
+ snapshotMac: snapshotMac,
128
+ keyId: { id: encKeyId },
129
+ mutations: [
130
+ {
131
+ operation: operation,
132
+ record: {
133
+ index: {
134
+ blob: indexMac
135
+ },
136
+ value: {
137
+ blob: Buffer.concat([encValue, valueMac])
138
+ },
139
+ keyId: { id: encKeyId }
140
+ }
141
+ }
142
+ ]
143
+ };
144
+ const base64Index = indexMac.toString('base64');
145
+ state.indexValueMap[base64Index] = { valueMac };
146
+ return { patch, state };
147
+ };
148
+ export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
149
+ const ltGenerator = makeLtHashGenerator(initialState);
150
+ const derivedKeyCache = new Map();
151
+
152
+ for (const msgMutation of msgMutations) {
153
+
154
+ const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
155
+ const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
156
+ let key;
157
+ try {
158
+ key = await getKey(record.keyId.id);
159
+ }
160
+ catch (err) {
161
+
162
+ if (isMissingKeyError(err))
163
+ throw err;
164
+ continue;
165
+ }
166
+ const content = record.value.blob;
167
+ const encContent = content.subarray(0, -32);
168
+ const ogValueMac = content.subarray(-32);
169
+ if (validateMacs) {
170
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
171
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
172
+
173
+ continue;
174
+ }
175
+ }
176
+ let result;
177
+ try {
178
+ result = aesDecrypt(encContent, key.valueEncryptionKey);
179
+ }
180
+ catch {
181
+
182
+ continue;
183
+ }
184
+ const syncAction = proto.SyncActionData.decode(result);
185
+ if (validateMacs) {
186
+ const hmac = hmacSign(syncAction.index, key.indexKey);
187
+ if (Buffer.compare(hmac, record.index.blob) !== 0) {
188
+ throw new Boom('HMAC index verification failed');
189
+ }
190
+ }
191
+ const indexStr = Buffer.from(syncAction.index).toString();
192
+ onMutation({ syncAction, index: JSON.parse(indexStr) });
193
+ ltGenerator.mix({
194
+ indexMac: record.index.blob,
195
+ valueMac: ogValueMac,
196
+ operation: operation
197
+ });
198
+ }
199
+ return ltGenerator.finish();
200
+ async function getKey(keyId) {
201
+ const base64Key = Buffer.from(keyId).toString('base64');
202
+ const cached = derivedKeyCache.get(base64Key);
203
+ if (cached) {
204
+ return cached;
205
+ }
206
+ const keyEnc = await getAppStateSyncKey(base64Key);
207
+ if (!keyEnc) {
208
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
209
+ data: { isMissingKey: true, msgMutations }
210
+ });
211
+ }
212
+ const keys = mutationKeys(keyEnc.keyData);
213
+ derivedKeyCache.set(base64Key, keys);
214
+ return keys;
215
+ }
216
+ };
217
+ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
218
+ if (validateMacs) {
219
+ const base64Key = Buffer.from(msg.keyId.id).toString('base64');
220
+ const mainKeyObj = await getAppStateSyncKey(base64Key);
221
+ if (!mainKeyObj) {
222
+ throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } });
223
+ }
224
+ const mainKey = mutationKeys(mainKeyObj.keyData);
225
+ const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
226
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey);
227
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
228
+ throw new Boom('Invalid patch mac');
229
+ }
230
+ }
231
+ const result = await decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
232
+ return result;
233
+ };
234
+ export const extractSyncdPatches = async (result, options) => {
235
+ const syncNode = getBinaryNodeChild(result, 'sync');
236
+ const collectionNodes = getBinaryNodeChildren(syncNode, 'collection');
237
+ const final = {};
238
+ await Promise.all(collectionNodes.map(async (collectionNode) => {
239
+ const patchesNode = getBinaryNodeChild(collectionNode, 'patches');
240
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch');
241
+ const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot');
242
+ const syncds = [];
243
+ const name = collectionNode.attrs.name;
244
+ const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
245
+ let snapshot = undefined;
246
+ if (snapshotNode && !!snapshotNode.content) {
247
+ if (!Buffer.isBuffer(snapshotNode)) {
248
+ snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
249
+ }
250
+ const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content);
251
+ const data = await downloadExternalBlob(blobRef, options);
252
+ snapshot = proto.SyncdSnapshot.decode(data);
253
+ }
254
+ for (let { content } of patches) {
255
+ if (content) {
256
+ if (!Buffer.isBuffer(content)) {
257
+ content = Buffer.from(Object.values(content));
258
+ }
259
+ const syncd = proto.SyncdPatch.decode(content);
260
+ if (!syncd.version) {
261
+ syncd.version = { version: +collectionNode.attrs.version + 1 };
262
+ }
263
+ syncds.push(syncd);
264
+ }
265
+ }
266
+ final[name] = { patches: syncds, hasMorePatches, snapshot };
267
+ }));
268
+ return final;
269
+ };
270
+ export const downloadExternalBlob = async (blob, options) => {
271
+ const stream = await downloadContentFromMessage(blob, 'md-app-state', { options });
272
+ const bufferArray = [];
273
+ for await (const chunk of stream) {
274
+ bufferArray.push(chunk);
275
+ }
276
+ return Buffer.concat(bufferArray);
277
+ };
278
+ export const downloadExternalPatch = async (blob, options) => {
279
+ const buffer = await downloadExternalBlob(blob, options);
280
+ const syncData = proto.SyncdMutations.decode(buffer);
281
+ return syncData;
282
+ };
283
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
284
+ const newState = newLTHashState();
285
+ newState.version = toNumber(snapshot.version.version);
286
+ const mutationMap = {};
287
+ const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber;
288
+ const { hash, indexValueMap } = await decodeSyncdMutations(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
289
+ ? mutation => {
290
+ const index = mutation.syncAction.index?.toString();
291
+ mutationMap[index] = mutation;
292
+ }
293
+ : () => { }, validateMacs);
294
+ newState.hash = hash;
295
+ newState.indexValueMap = indexValueMap;
296
+ if (validateMacs) {
297
+ const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
298
+ const keyEnc = await getAppStateSyncKey(base64Key);
299
+ if (!keyEnc) {
300
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
301
+ }
302
+ const result = mutationKeys(keyEnc.keyData);
303
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
304
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
305
+
306
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state');
307
+ }
308
+ }
309
+ return {
310
+ state: newState,
311
+ mutationMap
312
+ };
313
+ };
314
+ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
315
+ const newState = {
316
+ ...initial,
317
+ indexValueMap: { ...initial.indexValueMap }
318
+ };
319
+ const mutationMap = {};
320
+ for (const syncd of syncds) {
321
+ const { version, keyId, snapshotMac } = syncd;
322
+ if (syncd.externalMutations) {
323
+ logger?.trace({ name, version }, 'downloading external patch');
324
+ const ref = await downloadExternalPatch(syncd.externalMutations, options);
325
+ logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
326
+ syncd.mutations?.push(...ref.mutations);
327
+ }
328
+ const patchVersion = toNumber(version.version);
329
+ newState.version = patchVersion;
330
+ const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
331
+ let decodeResult;
332
+ try {
333
+ decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
334
+ ? mutation => {
335
+ const index = mutation.syncAction.index?.toString();
336
+ mutationMap[index] = mutation;
337
+ }
338
+ : () => { }, validateMacs);
339
+ }
340
+ catch (err) {
341
+ if (isMissingKeyError(err))
342
+ throw err;
343
+ logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping');
344
+ continue;
345
+ }
346
+ newState.hash = decodeResult.hash;
347
+ newState.indexValueMap = decodeResult.indexValueMap;
348
+ if (validateMacs) {
349
+ const base64Key = Buffer.from(keyId.id).toString('base64');
350
+ const keyEnc = await getAppStateSyncKey(base64Key);
351
+ if (!keyEnc) {
352
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
353
+ }
354
+ const result = mutationKeys(keyEnc.keyData);
355
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
356
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
357
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches');
358
+ break;
359
+ }
360
+ }
361
+
362
+ syncd.mutations = [];
363
+ }
364
+ return { state: newState, mutationMap };
365
+ };
366
+ export const chatModificationToAppPatch = (mod, jid) => {
367
+ const OP = proto.SyncdMutation.SyncdOperation;
368
+ const getMessageRange = (lastMessages) => {
369
+ let messageRange;
370
+ if (Array.isArray(lastMessages)) {
371
+ const lastMsg = lastMessages[lastMessages.length - 1];
372
+ messageRange = {
373
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
374
+ messages: lastMessages?.length
375
+ ? lastMessages.map(m => {
376
+ if (!m.key?.id || !m.key?.remoteJid) {
377
+ throw new Boom('Incomplete key', { statusCode: 400, data: m });
378
+ }
379
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
380
+ throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
381
+ }
382
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
383
+ throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
384
+ }
385
+ if (m.key.participant) {
386
+ m.key.participant = jidNormalizedUser(m.key.participant);
387
+ }
388
+ return m;
389
+ })
390
+ : undefined
391
+ };
392
+ }
393
+ else {
394
+ messageRange = lastMessages;
395
+ }
396
+ return messageRange;
397
+ };
398
+ let patch;
399
+ if ('mute' in mod) {
400
+ patch = {
401
+ syncAction: {
402
+ muteAction: {
403
+ muted: !!mod.mute,
404
+ muteEndTimestamp: mod.mute || undefined
405
+ }
406
+ },
407
+ index: ['mute', jid],
408
+ type: 'regular_high',
409
+ apiVersion: 2,
410
+ operation: OP.SET
411
+ };
412
+ }
413
+ else if ('archive' in mod) {
414
+ patch = {
415
+ syncAction: {
416
+ archiveChatAction: {
417
+ archived: !!mod.archive,
418
+ messageRange: getMessageRange(mod.lastMessages)
419
+ }
420
+ },
421
+ index: ['archive', jid],
422
+ type: 'regular_low',
423
+ apiVersion: 3,
424
+ operation: OP.SET
425
+ };
426
+ }
427
+ else if ('markRead' in mod) {
428
+ patch = {
429
+ syncAction: {
430
+ markChatAsReadAction: {
431
+ read: mod.markRead,
432
+ messageRange: getMessageRange(mod.lastMessages)
433
+ }
434
+ },
435
+ index: ['markChatAsRead', jid],
436
+ type: 'regular_low',
437
+ apiVersion: 3,
438
+ operation: OP.SET
439
+ };
440
+ }
441
+ else if ('deleteForMe' in mod) {
442
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
443
+ patch = {
444
+ syncAction: {
445
+ deleteMessageForMeAction: {
446
+ deleteMedia,
447
+ messageTimestamp: timestamp
448
+ }
449
+ },
450
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
451
+ type: 'regular_high',
452
+ apiVersion: 3,
453
+ operation: OP.SET
454
+ };
455
+ }
456
+ else if ('clear' in mod) {
457
+ patch = {
458
+ syncAction: {
459
+ clearChatAction: {
460
+ messageRange: getMessageRange(mod.lastMessages)
461
+ }
462
+ },
463
+ index: ['clearChat', jid, '1' , '0'],
464
+ type: 'regular_high',
465
+ apiVersion: 6,
466
+ operation: OP.SET
467
+ };
468
+ }
469
+ else if ('pin' in mod) {
470
+ patch = {
471
+ syncAction: {
472
+ pinAction: {
473
+ pinned: !!mod.pin
474
+ }
475
+ },
476
+ index: ['pin_v1', jid],
477
+ type: 'regular_low',
478
+ apiVersion: 5,
479
+ operation: OP.SET
480
+ };
481
+ }
482
+ else if ('contact' in mod) {
483
+ patch = {
484
+ syncAction: {
485
+ contactAction: mod.contact || {}
486
+ },
487
+ index: ['contact', jid],
488
+ type: 'critical_unblock_low',
489
+ apiVersion: 2,
490
+ operation: mod.contact ? OP.SET : OP.REMOVE
491
+ };
492
+ }
493
+ else if ('disableLinkPreviews' in mod) {
494
+ patch = {
495
+ syncAction: {
496
+ privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
497
+ },
498
+ index: ['setting_disableLinkPreviews'],
499
+ type: 'regular',
500
+ apiVersion: 8,
501
+ operation: OP.SET
502
+ };
503
+ }
504
+ else if ('star' in mod) {
505
+ const key = mod.star.messages[0];
506
+ patch = {
507
+ syncAction: {
508
+ starAction: {
509
+ starred: !!mod.star.star
510
+ }
511
+ },
512
+ index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
513
+ type: 'regular_low',
514
+ apiVersion: 2,
515
+ operation: OP.SET
516
+ };
517
+ }
518
+ else if ('delete' in mod) {
519
+ patch = {
520
+ syncAction: {
521
+ deleteChatAction: {
522
+ messageRange: getMessageRange(mod.lastMessages)
523
+ }
524
+ },
525
+ index: ['deleteChat', jid, '1'],
526
+ type: 'regular_high',
527
+ apiVersion: 6,
528
+ operation: OP.SET
529
+ };
530
+ }
531
+ else if ('pushNameSetting' in mod) {
532
+ patch = {
533
+ syncAction: {
534
+ pushNameSetting: {
535
+ name: mod.pushNameSetting
536
+ }
537
+ },
538
+ index: ['setting_pushName'],
539
+ type: 'critical_block',
540
+ apiVersion: 1,
541
+ operation: OP.SET
542
+ };
543
+ }
544
+ else if ('quickReply' in mod) {
545
+ patch = {
546
+ syncAction: {
547
+ quickReplyAction: {
548
+ count: 0,
549
+ deleted: mod.quickReply.deleted || false,
550
+ keywords: [],
551
+ message: mod.quickReply.message || '',
552
+ shortcut: mod.quickReply.shortcut || ''
553
+ }
554
+ },
555
+ index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
556
+ type: 'regular',
557
+ apiVersion: 2,
558
+ operation: OP.SET
559
+ };
560
+ }
561
+ else if ('addLabel' in mod) {
562
+ patch = {
563
+ syncAction: {
564
+ labelEditAction: {
565
+ name: mod.addLabel.name,
566
+ color: mod.addLabel.color,
567
+ predefinedId: mod.addLabel.predefinedId,
568
+ deleted: mod.addLabel.deleted
569
+ }
570
+ },
571
+ index: ['label_edit', mod.addLabel.id],
572
+ type: 'regular',
573
+ apiVersion: 3,
574
+ operation: OP.SET
575
+ };
576
+ }
577
+ else if ('addChatLabel' in mod) {
578
+ patch = {
579
+ syncAction: {
580
+ labelAssociationAction: {
581
+ labeled: true
582
+ }
583
+ },
584
+ index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
585
+ type: 'regular',
586
+ apiVersion: 3,
587
+ operation: OP.SET
588
+ };
589
+ }
590
+ else if ('removeChatLabel' in mod) {
591
+ patch = {
592
+ syncAction: {
593
+ labelAssociationAction: {
594
+ labeled: false
595
+ }
596
+ },
597
+ index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
598
+ type: 'regular',
599
+ apiVersion: 3,
600
+ operation: OP.SET
601
+ };
602
+ }
603
+ else if ('addMessageLabel' in mod) {
604
+ patch = {
605
+ syncAction: {
606
+ labelAssociationAction: {
607
+ labeled: true
608
+ }
609
+ },
610
+ index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
611
+ type: 'regular',
612
+ apiVersion: 3,
613
+ operation: OP.SET
614
+ };
615
+ }
616
+ else if ('removeMessageLabel' in mod) {
617
+ patch = {
618
+ syncAction: {
619
+ labelAssociationAction: {
620
+ labeled: false
621
+ }
622
+ },
623
+ index: [
624
+ LabelAssociationType.Message,
625
+ mod.removeMessageLabel.labelId,
626
+ jid,
627
+ mod.removeMessageLabel.messageId,
628
+ '0',
629
+ '0'
630
+ ],
631
+ type: 'regular',
632
+ apiVersion: 3,
633
+ operation: OP.SET
634
+ };
635
+ }
636
+ else {
637
+ throw new Boom('not supported');
638
+ }
639
+ patch.syncAction.timestamp = Date.now();
640
+ return patch;
641
+ };
642
+ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
643
+ const isInitialSync = !!initialSyncOpts;
644
+ const accountSettings = initialSyncOpts?.accountSettings;
645
+ logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
646
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
647
+ if (action?.muteAction) {
648
+ ev.emit('chats.update', [
649
+ {
650
+ id,
651
+ muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
652
+ conditional: getChatUpdateConditional(id, undefined)
653
+ }
654
+ ]);
655
+ }
656
+ else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
657
+
658
+ const archiveAction = action?.archiveChatAction;
659
+ const isArchived = archiveAction ? archiveAction.archived : type === 'archive';
660
+
661
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
662
+
663
+ ev.emit('chats.update', [
664
+ {
665
+ id,
666
+ archived: isArchived,
667
+ conditional: getChatUpdateConditional(id, msgRange)
668
+ }
669
+ ]);
670
+ }
671
+ else if (action?.markChatAsReadAction) {
672
+ const markReadAction = action.markChatAsReadAction;
673
+
674
+ const isNullUpdate = isInitialSync && markReadAction.read;
675
+ ev.emit('chats.update', [
676
+ {
677
+ id,
678
+ unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
679
+ conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
680
+ }
681
+ ]);
682
+ }
683
+ else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
684
+ ev.emit('messages.delete', {
685
+ keys: [
686
+ {
687
+ remoteJid: id,
688
+ id: msgId,
689
+ fromMe: fromMe === '1'
690
+ }
691
+ ]
692
+ });
693
+ }
694
+ else if (action?.contactAction) {
695
+ const results = processContactAction(action.contactAction, id, logger);
696
+ emitSyncActionResults(ev, results);
697
+ }
698
+ else if (action?.pushNameSetting) {
699
+ const name = action?.pushNameSetting?.name;
700
+ if (name && me?.name !== name) {
701
+ ev.emit('creds.update', { me: { ...me, name } });
702
+ }
703
+ }
704
+ else if (action?.pinAction) {
705
+ ev.emit('chats.update', [
706
+ {
707
+ id,
708
+ pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
709
+ conditional: getChatUpdateConditional(id, undefined)
710
+ }
711
+ ]);
712
+ }
713
+ else if (action?.unarchiveChatsSetting) {
714
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
715
+ ev.emit('creds.update', { accountSettings: { unarchiveChats } });
716
+ logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
717
+ if (accountSettings) {
718
+ accountSettings.unarchiveChats = unarchiveChats;
719
+ }
720
+ }
721
+ else if (action?.starAction || type === 'star') {
722
+ let starred = action?.starAction?.starred;
723
+ if (typeof starred !== 'boolean') {
724
+ starred = syncAction.index[syncAction.index.length - 1] === '1';
725
+ }
726
+ ev.emit('messages.update', [
727
+ {
728
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
729
+ update: { starred }
730
+ }
731
+ ]);
732
+ }
733
+ else if (action?.deleteChatAction || type === 'deleteChat') {
734
+ if (!isInitialSync) {
735
+ ev.emit('chats.delete', [id]);
736
+ }
737
+ }
738
+ else if (action?.labelEditAction) {
739
+ const { name, color, deleted, predefinedId } = action.labelEditAction;
740
+ ev.emit('labels.edit', {
741
+ id: id,
742
+ name: name,
743
+ color: color,
744
+ deleted: deleted,
745
+ predefinedId: predefinedId ? String(predefinedId) : undefined
746
+ });
747
+ }
748
+ else if (action?.labelAssociationAction) {
749
+ ev.emit('labels.association', {
750
+ type: action.labelAssociationAction.labeled ? 'add' : 'remove',
751
+ association: type === LabelAssociationType.Chat
752
+ ? {
753
+ type: LabelAssociationType.Chat,
754
+ chatId: syncAction.index[2],
755
+ labelId: syncAction.index[1]
756
+ }
757
+ : {
758
+ type: LabelAssociationType.Message,
759
+ chatId: syncAction.index[2],
760
+ messageId: syncAction.index[3],
761
+ labelId: syncAction.index[1]
762
+ }
763
+ });
764
+ }
765
+ else if (action?.localeSetting?.locale) {
766
+ ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale });
767
+ }
768
+ else if (action?.timeFormatAction) {
769
+ ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction });
770
+ }
771
+ else if (action?.pnForLidChatAction) {
772
+ if (action.pnForLidChatAction.pnJid) {
773
+ ev.emit('lid-mapping.update', { lid: id, pn: action.pnForLidChatAction.pnJid });
774
+ }
775
+ }
776
+ else if (action?.privacySettingRelayAllCalls) {
777
+ ev.emit('settings.update', {
778
+ setting: 'privacySettingRelayAllCalls',
779
+ value: action.privacySettingRelayAllCalls
780
+ });
781
+ }
782
+ else if (action?.statusPrivacy) {
783
+ ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy });
784
+ }
785
+ else if (action?.lockChatAction) {
786
+ ev.emit('chats.lock', { id: id, locked: !!action.lockChatAction.locked });
787
+ }
788
+ else if (action?.privacySettingDisableLinkPreviewsAction) {
789
+ ev.emit('settings.update', {
790
+ setting: 'disableLinkPreviews',
791
+ value: action.privacySettingDisableLinkPreviewsAction
792
+ });
793
+ }
794
+ else if (action?.notificationActivitySettingAction?.notificationActivitySetting) {
795
+ ev.emit('settings.update', {
796
+ setting: 'notificationActivitySetting',
797
+ value: action.notificationActivitySettingAction.notificationActivitySetting
798
+ });
799
+ }
800
+ else if (action?.lidContactAction) {
801
+ ev.emit('contacts.upsert', [
802
+ {
803
+ id: id,
804
+ name: action.lidContactAction.fullName ||
805
+ action.lidContactAction.firstName ||
806
+ action.lidContactAction.username ||
807
+ undefined,
808
+ username: action.lidContactAction.username || undefined,
809
+ lid: id,
810
+ phoneNumber: undefined
811
+ }
812
+ ]);
813
+ }
814
+ else if (action?.privacySettingChannelsPersonalisedRecommendationAction) {
815
+ ev.emit('settings.update', {
816
+ setting: 'channelsPersonalisedRecommendation',
817
+ value: action.privacySettingChannelsPersonalisedRecommendationAction
818
+ });
819
+ }
820
+ else if (action?.groupHistoryToggleAction) {
821
+ ev.emit('groups.update', [
822
+ {
823
+ id,
824
+ groupHistoryToggleMode: action.groupHistoryToggleAction.groupHistoryToggleMode ?? GroupHistoryToggleMode.DEFAULT
825
+ }
826
+ ]);
827
+ }
828
+ else {
829
+ logger?.debug({ syncAction, id }, 'unprocessable update');
830
+ }
831
+ function getChatUpdateConditional(id, msgRange) {
832
+ return isInitialSync
833
+ ? data => {
834
+ const chat = data.historySets.chats[id] || data.chatUpserts[id];
835
+ if (chat) {
836
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
837
+ }
838
+ }
839
+ : undefined;
840
+ }
841
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
842
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0);
843
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
844
+ return lastMsgTimestamp >= chatLastMsgTimestamp;
845
+ }
846
+ };