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