@vinzsocket/baileys 2.8.10 → 2.8.30

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