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