@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
@@ -12,63 +12,66 @@ import { delay, generateRegistrationId } from './generics.js';
12
12
  * @param _cache cache store to use
13
13
  */
14
14
  export function makeCacheableSignalKeyStore(store, logger, _cache) {
15
- const cache = _cache ||
16
- new NodeCache({
17
- stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
18
- useClones: false,
19
- deleteOnExpire: true
20
- });
21
- // Mutex for protecting cache operations
22
- const cacheMutex = new Mutex();
23
- function getUniqueId(type, id) {
24
- return `${type}.${id}`;
25
- }
26
- return {
27
- async get(type, ids) {
28
- return cacheMutex.runExclusive(async () => {
29
- const data = {};
30
- const idsToFetch = [];
31
- for (const id of ids) {
32
- const item = cache.get(getUniqueId(type, id));
33
- if (typeof item !== 'undefined') {
34
- data[id] = item;
35
- }
36
- else {
37
- idsToFetch.push(id);
38
- }
39
- }
40
- if (idsToFetch.length) {
41
- logger?.trace({ items: idsToFetch.length }, 'loading from store');
42
- const fetched = await store.get(type, idsToFetch);
43
- for (const id of idsToFetch) {
44
- const item = fetched[id];
45
- if (item) {
46
- data[id] = item;
47
- cache.set(getUniqueId(type, id), item);
48
- }
49
- }
50
- }
51
- return data;
52
- });
53
- },
54
- async set(data) {
55
- return cacheMutex.runExclusive(async () => {
56
- let keys = 0;
57
- for (const type in data) {
58
- for (const id in data[type]) {
59
- cache.set(getUniqueId(type, id), data[type][id]);
60
- keys += 1;
61
- }
62
- }
63
- logger?.trace({ keys }, 'updated cache');
64
- await store.set(data);
65
- });
66
- },
67
- async clear() {
68
- cache.flushAll();
69
- await store.clear?.();
15
+ const cache = _cache || new NodeCache({
16
+ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE,
17
+ // 5 minutes
18
+ useClones: false,
19
+ deleteOnExpire: true
20
+ });
21
+ // Mutex for protecting cache operations
22
+ const cacheMutex = new Mutex();
23
+ function getUniqueId(type, id) {
24
+ return `${type}.${id}`;
25
+ }
26
+ return {
27
+ async get(type, ids) {
28
+ return cacheMutex.runExclusive(async () => {
29
+ const data = {};
30
+ const idsToFetch = [];
31
+ for (const id of ids) {
32
+ const item = cache.get(getUniqueId(type, id));
33
+ if (typeof item !== 'undefined') {
34
+ data[id] = item;
35
+ } else {
36
+ idsToFetch.push(id);
37
+ }
38
+ }
39
+ if (idsToFetch.length) {
40
+ logger?.trace({
41
+ items: idsToFetch.length
42
+ }, 'loading from store');
43
+ const fetched = await store.get(type, idsToFetch);
44
+ for (const id of idsToFetch) {
45
+ const item = fetched[id];
46
+ if (item) {
47
+ data[id] = item;
48
+ cache.set(getUniqueId(type, id), item);
49
+ }
50
+ }
70
51
  }
71
- };
52
+ return data;
53
+ });
54
+ },
55
+ async set(data) {
56
+ return cacheMutex.runExclusive(async () => {
57
+ let keys = 0;
58
+ for (const type in data) {
59
+ for (const id in data[type]) {
60
+ cache.set(getUniqueId(type, id), data[type][id]);
61
+ keys += 1;
62
+ }
63
+ }
64
+ logger?.trace({
65
+ keys
66
+ }, 'updated cache');
67
+ await store.set(data);
68
+ });
69
+ },
70
+ async clear() {
71
+ cache.flushAll();
72
+ await store.clear?.();
73
+ }
74
+ };
72
75
  }
73
76
  // Module-level specialized mutexes for pre-key operations
74
77
  const preKeyMutex = new Mutex();
@@ -76,138 +79,126 @@ const signedPreKeyMutex = new Mutex();
76
79
  /**
77
80
  * Get the appropriate mutex for the key type
78
81
  */
79
- const getPreKeyMutex = (keyType) => {
80
- return keyType === 'signed-pre-key' ? signedPreKeyMutex : preKeyMutex;
82
+ const getPreKeyMutex = keyType => {
83
+ return keyType === 'signed-pre-key' ? signedPreKeyMutex : preKeyMutex;
81
84
  };
82
85
  /**
83
86
  * Handles pre-key operations with mutex protection
84
87
  */
85
88
  async function handlePreKeyOperations(data, keyType, transactionCache, mutations, logger, isInTransaction, state) {
86
- const mutex = getPreKeyMutex(keyType);
87
- await mutex.runExclusive(async () => {
88
- const keyData = data[keyType];
89
- if (!keyData)
90
- return;
91
- // Ensure structures exist
92
- transactionCache[keyType] = transactionCache[keyType] || {};
93
- mutations[keyType] = mutations[keyType] || {};
94
- // Separate deletions from updates for batch processing
95
- const deletionKeys = [];
96
- const updateKeys = [];
97
- for (const keyId in keyData) {
98
- if (keyData[keyId] === null) {
99
- deletionKeys.push(keyId);
100
- }
101
- else {
102
- updateKeys.push(keyId);
103
- }
104
- }
105
- // Process updates first (no validation needed)
106
- for (const keyId of updateKeys) {
107
- if (transactionCache[keyType]) {
108
- transactionCache[keyType][keyId] = keyData[keyId];
109
- }
110
- if (mutations[keyType]) {
111
- mutations[keyType][keyId] = keyData[keyId];
112
- }
113
- }
114
- // Process deletions with validation
115
- if (deletionKeys.length === 0)
116
- return;
117
- if (isInTransaction) {
118
- // In transaction, only allow deletion if key exists in cache
119
- for (const keyId of deletionKeys) {
120
- if (transactionCache[keyType]) {
121
- transactionCache[keyType][keyId] = null;
122
- if (mutations[keyType]) {
123
- // Mark for deletion in mutations
124
- mutations[keyType][keyId] = null;
125
- }
126
- }
127
- else {
128
- logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`);
129
- }
130
- }
131
- return;
132
- }
133
- // Outside transaction, batch validate all deletions
134
- if (!state)
135
- return;
136
- const existingKeys = await state.get(keyType, deletionKeys);
137
- for (const keyId of deletionKeys) {
138
- if (existingKeys[keyId]) {
139
- if (transactionCache[keyType])
140
- transactionCache[keyType][keyId] = null;
141
- if (mutations[keyType])
142
- mutations[keyType][keyId] = null;
143
- }
144
- else {
145
- logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
146
- }
89
+ const mutex = getPreKeyMutex(keyType);
90
+ await mutex.runExclusive(async () => {
91
+ const keyData = data[keyType];
92
+ if (!keyData) return;
93
+ // Ensure structures exist
94
+ transactionCache[keyType] = transactionCache[keyType] || {};
95
+ mutations[keyType] = mutations[keyType] || {};
96
+ // Separate deletions from updates for batch processing
97
+ const deletionKeys = [];
98
+ const updateKeys = [];
99
+ for (const keyId in keyData) {
100
+ if (keyData[keyId] === null) {
101
+ deletionKeys.push(keyId);
102
+ } else {
103
+ updateKeys.push(keyId);
104
+ }
105
+ }
106
+ // Process updates first (no validation needed)
107
+ for (const keyId of updateKeys) {
108
+ if (transactionCache[keyType]) {
109
+ transactionCache[keyType][keyId] = keyData[keyId];
110
+ }
111
+ if (mutations[keyType]) {
112
+ mutations[keyType][keyId] = keyData[keyId];
113
+ }
114
+ }
115
+ // Process deletions with validation
116
+ if (deletionKeys.length === 0) return;
117
+ if (isInTransaction) {
118
+ // In transaction, only allow deletion if key exists in cache
119
+ for (const keyId of deletionKeys) {
120
+ if (transactionCache[keyType]) {
121
+ transactionCache[keyType][keyId] = null;
122
+ if (mutations[keyType]) {
123
+ // Mark for deletion in mutations
124
+ mutations[keyType][keyId] = null;
125
+ }
126
+ } else {
127
+ logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`);
147
128
  }
148
- });
129
+ }
130
+ return;
131
+ }
132
+ // Outside transaction, batch validate all deletions
133
+ if (!state) return;
134
+ const existingKeys = await state.get(keyType, deletionKeys);
135
+ for (const keyId of deletionKeys) {
136
+ if (existingKeys[keyId]) {
137
+ if (transactionCache[keyType]) transactionCache[keyType][keyId] = null;
138
+ if (mutations[keyType]) mutations[keyType][keyId] = null;
139
+ } else {
140
+ logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
141
+ }
142
+ }
143
+ });
149
144
  }
150
145
  /**
151
146
  * Handles normal key operations for transactions
152
147
  */
153
148
  function handleNormalKeyOperations(data, key, transactionCache, mutations) {
154
- Object.assign(transactionCache[key], data[key]);
155
- mutations[key] = mutations[key] || {};
156
- Object.assign(mutations[key], data[key]);
149
+ Object.assign(transactionCache[key], data[key]);
150
+ mutations[key] = mutations[key] || {};
151
+ Object.assign(mutations[key], data[key]);
157
152
  }
158
153
  /**
159
154
  * Process pre-key deletions with validation
160
155
  */
161
156
  async function processPreKeyDeletions(data, keyType, state, logger) {
162
- const mutex = getPreKeyMutex(keyType);
163
- await mutex.runExclusive(async () => {
164
- const keyData = data[keyType];
165
- if (!keyData)
166
- return;
167
- // Validate deletions
168
- for (const keyId in keyData) {
169
- if (keyData[keyId] === null) {
170
- const existingKeys = await state.get(keyType, [keyId]);
171
- if (!existingKeys[keyId]) {
172
- logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
173
- if (data[keyType])
174
- delete data[keyType][keyId];
175
- }
176
- }
157
+ const mutex = getPreKeyMutex(keyType);
158
+ await mutex.runExclusive(async () => {
159
+ const keyData = data[keyType];
160
+ if (!keyData) return;
161
+ // Validate deletions
162
+ for (const keyId in keyData) {
163
+ if (keyData[keyId] === null) {
164
+ const existingKeys = await state.get(keyType, [keyId]);
165
+ if (!existingKeys[keyId]) {
166
+ logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
167
+ if (data[keyType]) delete data[keyType][keyId];
177
168
  }
178
- });
169
+ }
170
+ }
171
+ });
179
172
  }
180
173
  /**
181
174
  * Executes a function with mutexes acquired for given key types
182
175
  * Uses async-mutex's runExclusive with efficient batching
183
176
  */
184
177
  async function withMutexes(keyTypes, getKeyTypeMutex, fn) {
185
- if (keyTypes.length === 0) {
186
- return fn();
187
- }
188
- if (keyTypes.length === 1) {
189
- return getKeyTypeMutex(keyTypes[0]).runExclusive(fn);
178
+ if (keyTypes.length === 0) {
179
+ return fn();
180
+ }
181
+ if (keyTypes.length === 1) {
182
+ return getKeyTypeMutex(keyTypes[0]).runExclusive(fn);
183
+ }
184
+ // For multiple mutexes, sort by key type to prevent deadlocks
185
+ // Then acquire all mutexes in order using Promise.all for better efficiency
186
+ const sortedKeyTypes = [...keyTypes].sort();
187
+ const mutexes = sortedKeyTypes.map(getKeyTypeMutex);
188
+ // Acquire all mutexes in order to prevent deadlocks
189
+ const releases = [];
190
+ try {
191
+ for (const mutex of mutexes) {
192
+ releases.push(await mutex.acquire());
190
193
  }
191
- // For multiple mutexes, sort by key type to prevent deadlocks
192
- // Then acquire all mutexes in order using Promise.all for better efficiency
193
- const sortedKeyTypes = [...keyTypes].sort();
194
- const mutexes = sortedKeyTypes.map(getKeyTypeMutex);
195
- // Acquire all mutexes in order to prevent deadlocks
196
- const releases = [];
197
- try {
198
- for (const mutex of mutexes) {
199
- releases.push(await mutex.acquire());
200
- }
201
- return await fn();
202
- }
203
- finally {
204
- // Release in reverse order
205
- while (releases.length > 0) {
206
- const release = releases.pop();
207
- if (release)
208
- release();
209
- }
194
+ return await fn();
195
+ } finally {
196
+ // Release in reverse order
197
+ while (releases.length > 0) {
198
+ const release = releases.pop();
199
+ if (release) release();
210
200
  }
201
+ }
211
202
  }
212
203
  /**
213
204
  * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
@@ -216,259 +207,275 @@ async function withMutexes(keyTypes, getKeyTypeMutex, fn) {
216
207
  * @param logger logger to log events
217
208
  * @returns SignalKeyStore with transaction capability
218
209
  */
219
- export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
220
- // number of queries made to the DB during the transaction
221
- // only there for logging purposes
222
- let dbQueriesInTransaction = 0;
223
- let transactionCache = {};
224
- let mutations = {};
225
- // LRU Cache to hold mutexes for different key types
226
- const mutexCache = new LRUCache({
227
- ttl: 60 * 60 * 1000, // 1 hour
228
- ttlAutopurge: true,
229
- updateAgeOnGet: true
230
- });
231
- let transactionsInProgress = 0;
232
- function getKeyTypeMutex(type) {
233
- return getMutex(`keytype:${type}`);
234
- }
235
- function getSenderKeyMutex(senderKeyName) {
236
- return getMutex(`senderkey:${senderKeyName}`);
210
+ export const addTransactionCapability = (state, logger, {
211
+ maxCommitRetries,
212
+ delayBetweenTriesMs
213
+ }) => {
214
+ // number of queries made to the DB during the transaction
215
+ // only there for logging purposes
216
+ let dbQueriesInTransaction = 0;
217
+ let transactionCache = {};
218
+ let mutations = {};
219
+ // LRU Cache to hold mutexes for different key types
220
+ const mutexCache = new LRUCache({
221
+ ttl: 60 * 60 * 1000,
222
+ // 1 hour
223
+ ttlAutopurge: true,
224
+ updateAgeOnGet: true
225
+ });
226
+ let transactionsInProgress = 0;
227
+ function getKeyTypeMutex(type) {
228
+ return getMutex(`keytype:${type}`);
229
+ }
230
+ function getSenderKeyMutex(senderKeyName) {
231
+ return getMutex(`senderkey:${senderKeyName}`);
232
+ }
233
+ function getTransactionMutex(key) {
234
+ return getMutex(`transaction:${key}`);
235
+ }
236
+ // Get or create a mutex for a specific key name
237
+ function getMutex(key) {
238
+ let mutex = mutexCache.get(key);
239
+ if (!mutex) {
240
+ mutex = new Mutex();
241
+ mutexCache.set(key, mutex);
242
+ logger.info({
243
+ key
244
+ }, 'created new mutex');
237
245
  }
238
- function getTransactionMutex(key) {
239
- return getMutex(`transaction:${key}`);
246
+ return mutex;
247
+ }
248
+ // Sender key operations with proper mutex sequencing
249
+ function queueSenderKeyOperation(senderKeyName, operation) {
250
+ return getSenderKeyMutex(senderKeyName).runExclusive(operation);
251
+ }
252
+ // Check if we are currently in a transaction
253
+ function isInTransaction() {
254
+ return transactionsInProgress > 0;
255
+ }
256
+ // Helper function to handle transaction commit with retries
257
+ async function commitTransaction() {
258
+ if (!Object.keys(mutations).length) {
259
+ logger.trace('no mutations in transaction');
260
+ return;
240
261
  }
241
- // Get or create a mutex for a specific key name
242
- function getMutex(key) {
243
- let mutex = mutexCache.get(key);
244
- if (!mutex) {
245
- mutex = new Mutex();
246
- mutexCache.set(key, mutex);
247
- logger.info({ key }, 'created new mutex');
262
+ logger.trace('committing transaction');
263
+ let tries = maxCommitRetries;
264
+ while (tries > 0) {
265
+ tries -= 1;
266
+ try {
267
+ await state.set(mutations);
268
+ logger.trace({
269
+ dbQueriesInTransaction
270
+ }, 'committed transaction');
271
+ return;
272
+ } catch (error) {
273
+ logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
274
+ if (tries > 0) {
275
+ await delay(delayBetweenTriesMs);
248
276
  }
249
- return mutex;
277
+ }
250
278
  }
251
- // Sender key operations with proper mutex sequencing
252
- function queueSenderKeyOperation(senderKeyName, operation) {
253
- return getSenderKeyMutex(senderKeyName).runExclusive(operation);
279
+ }
280
+ // Helper function to clean up transaction state
281
+ function cleanupTransactionState() {
282
+ transactionsInProgress -= 1;
283
+ if (transactionsInProgress === 0) {
284
+ transactionCache = {};
285
+ mutations = {};
286
+ dbQueriesInTransaction = 0;
254
287
  }
255
- // Check if we are currently in a transaction
256
- function isInTransaction() {
257
- return transactionsInProgress > 0;
288
+ }
289
+ // Helper function to execute work within transaction
290
+ async function executeTransactionWork(work) {
291
+ const result = await work();
292
+ // commit if this is the outermost transaction
293
+ if (transactionsInProgress === 1) {
294
+ await commitTransaction();
258
295
  }
259
- // Helper function to handle transaction commit with retries
260
- async function commitTransaction() {
261
- if (!Object.keys(mutations).length) {
262
- logger.trace('no mutations in transaction');
263
- return;
264
- }
265
- logger.trace('committing transaction');
266
- let tries = maxCommitRetries;
267
- while (tries > 0) {
268
- tries -= 1;
269
- try {
270
- await state.set(mutations);
271
- logger.trace({ dbQueriesInTransaction }, 'committed transaction');
272
- return;
273
- }
274
- catch (error) {
275
- logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
276
- if (tries > 0) {
277
- await delay(delayBetweenTriesMs);
278
- }
296
+ return result;
297
+ }
298
+ return {
299
+ get: async (type, ids) => {
300
+ if (isInTransaction()) {
301
+ const dict = transactionCache[type];
302
+ const idsRequiringFetch = dict ? ids.filter(item => typeof dict[item] === 'undefined') : ids;
303
+ // only fetch if there are any items to fetch
304
+ if (idsRequiringFetch.length) {
305
+ dbQueriesInTransaction += 1;
306
+ // Use per-sender-key queue for sender-key operations when possible
307
+ if (type === 'sender-key') {
308
+ logger.info({
309
+ idsRequiringFetch
310
+ }, 'processing sender keys in transaction');
311
+ // For sender keys, process each one with queued operations to maintain serialization
312
+ for (const senderKeyName of idsRequiringFetch) {
313
+ await queueSenderKeyOperation(senderKeyName, async () => {
314
+ logger.info({
315
+ senderKeyName
316
+ }, 'fetching sender key in transaction');
317
+ const result = await state.get(type, [senderKeyName]);
318
+ // Update transaction cache
319
+ transactionCache[type] || (transactionCache[type] = {});
320
+ Object.assign(transactionCache[type], result);
321
+ logger.info({
322
+ senderKeyName,
323
+ hasResult: !!result[senderKeyName]
324
+ }, 'sender key fetch complete');
325
+ });
279
326
  }
327
+ } else {
328
+ // Use runExclusive for cleaner mutex handling
329
+ await getKeyTypeMutex(type).runExclusive(async () => {
330
+ const result = await state.get(type, idsRequiringFetch);
331
+ // Update transaction cache
332
+ transactionCache[type] || (transactionCache[type] = {});
333
+ Object.assign(transactionCache[type], result);
334
+ });
335
+ }
280
336
  }
281
- }
282
- // Helper function to clean up transaction state
283
- function cleanupTransactionState() {
284
- transactionsInProgress -= 1;
285
- if (transactionsInProgress === 0) {
286
- transactionCache = {};
287
- mutations = {};
288
- dbQueriesInTransaction = 0;
337
+ return ids.reduce((dict, id) => {
338
+ const value = transactionCache[type]?.[id];
339
+ if (value) {
340
+ dict[id] = value;
341
+ }
342
+ return dict;
343
+ }, {});
344
+ } else {
345
+ // Not in transaction, fetch directly with queue protection
346
+ if (type === 'sender-key') {
347
+ // For sender keys, use individual queues to maintain per-key serialization
348
+ const results = {};
349
+ for (const senderKeyName of ids) {
350
+ const result = await queueSenderKeyOperation(senderKeyName, async () => await state.get(type, [senderKeyName]));
351
+ Object.assign(results, result);
352
+ }
353
+ return results;
354
+ } else {
355
+ return await getKeyTypeMutex(type).runExclusive(() => state.get(type, ids));
289
356
  }
290
- }
291
- // Helper function to execute work within transaction
292
- async function executeTransactionWork(work) {
293
- const result = await work();
294
- // commit if this is the outermost transaction
295
- if (transactionsInProgress === 1) {
296
- await commitTransaction();
357
+ }
358
+ },
359
+ set: async data => {
360
+ if (isInTransaction()) {
361
+ logger.trace({
362
+ types: Object.keys(data)
363
+ }, 'caching in transaction');
364
+ for (const key_ in data) {
365
+ const key = key_;
366
+ transactionCache[key] = transactionCache[key] || {};
367
+ // Special handling for pre-keys and signed-pre-keys
368
+ if (key === 'pre-key') {
369
+ await handlePreKeyOperations(data, key, transactionCache, mutations, logger, true);
370
+ } else {
371
+ // Normal handling for other key types
372
+ handleNormalKeyOperations(data, key, transactionCache, mutations);
373
+ }
297
374
  }
298
- return result;
299
- }
300
- return {
301
- get: async (type, ids) => {
302
- if (isInTransaction()) {
303
- const dict = transactionCache[type];
304
- const idsRequiringFetch = dict ? ids.filter(item => typeof dict[item] === 'undefined') : ids;
305
- // only fetch if there are any items to fetch
306
- if (idsRequiringFetch.length) {
307
- dbQueriesInTransaction += 1;
308
- // Use per-sender-key queue for sender-key operations when possible
309
- if (type === 'sender-key') {
310
- logger.info({ idsRequiringFetch }, 'processing sender keys in transaction');
311
- // For sender keys, process each one with queued operations to maintain serialization
312
- for (const senderKeyName of idsRequiringFetch) {
313
- await queueSenderKeyOperation(senderKeyName, async () => {
314
- logger.info({ senderKeyName }, 'fetching sender key in transaction');
315
- const result = await state.get(type, [senderKeyName]);
316
- // Update transaction cache
317
- transactionCache[type] || (transactionCache[type] = {});
318
- Object.assign(transactionCache[type], result);
319
- logger.info({ senderKeyName, hasResult: !!result[senderKeyName] }, 'sender key fetch complete');
320
- });
321
- }
322
- }
323
- else {
324
- // Use runExclusive for cleaner mutex handling
325
- await getKeyTypeMutex(type).runExclusive(async () => {
326
- const result = await state.get(type, idsRequiringFetch);
327
- // Update transaction cache
328
- transactionCache[type] || (transactionCache[type] = {});
329
- Object.assign(transactionCache[type], result);
330
- });
331
- }
332
- }
333
- return ids.reduce((dict, id) => {
334
- const value = transactionCache[type]?.[id];
335
- if (value) {
336
- dict[id] = value;
337
- }
338
- return dict;
339
- }, {});
340
- }
341
- else {
342
- // Not in transaction, fetch directly with queue protection
343
- if (type === 'sender-key') {
344
- // For sender keys, use individual queues to maintain per-key serialization
345
- const results = {};
346
- for (const senderKeyName of ids) {
347
- const result = await queueSenderKeyOperation(senderKeyName, async () => await state.get(type, [senderKeyName]));
348
- Object.assign(results, result);
349
- }
350
- return results;
351
- }
352
- else {
353
- return await getKeyTypeMutex(type).runExclusive(() => state.get(type, ids));
375
+ } else {
376
+ // Not in transaction, apply directly with mutex protection
377
+ const hasSenderKeys = 'sender-key' in data;
378
+ const senderKeyNames = hasSenderKeys ? Object.keys(data['sender-key'] || {}) : [];
379
+ if (hasSenderKeys) {
380
+ logger.info({
381
+ senderKeyNames
382
+ }, 'processing sender key set operations');
383
+ // Handle sender key operations with per-key queues
384
+ for (const senderKeyName of senderKeyNames) {
385
+ await queueSenderKeyOperation(senderKeyName, async () => {
386
+ // Create data subset for this specific sender key
387
+ const senderKeyData = {
388
+ 'sender-key': {
389
+ [senderKeyName]: data['sender-key'][senderKeyName]
354
390
  }
355
- }
356
- },
357
- set: async (data) => {
358
- if (isInTransaction()) {
359
- logger.trace({ types: Object.keys(data) }, 'caching in transaction');
360
- for (const key_ in data) {
361
- const key = key_;
362
- transactionCache[key] = transactionCache[key] || {};
363
- // Special handling for pre-keys and signed-pre-keys
364
- if (key === 'pre-key') {
365
- await handlePreKeyOperations(data, key, transactionCache, mutations, logger, true);
366
- }
367
- else {
368
- // Normal handling for other key types
369
- handleNormalKeyOperations(data, key, transactionCache, mutations);
370
- }
371
- }
372
- }
373
- else {
374
- // Not in transaction, apply directly with mutex protection
375
- const hasSenderKeys = 'sender-key' in data;
376
- const senderKeyNames = hasSenderKeys ? Object.keys(data['sender-key'] || {}) : [];
377
- if (hasSenderKeys) {
378
- logger.info({ senderKeyNames }, 'processing sender key set operations');
379
- // Handle sender key operations with per-key queues
380
- for (const senderKeyName of senderKeyNames) {
381
- await queueSenderKeyOperation(senderKeyName, async () => {
382
- // Create data subset for this specific sender key
383
- const senderKeyData = {
384
- 'sender-key': {
385
- [senderKeyName]: data['sender-key'][senderKeyName]
386
- }
387
- };
388
- logger.trace({ senderKeyName }, 'storing sender key');
389
- // Apply changes to the store
390
- await state.set(senderKeyData);
391
- logger.trace({ senderKeyName }, 'sender key stored');
392
- });
393
- }
394
- // Handle any non-sender-key data with regular mutexes
395
- const nonSenderKeyData = { ...data };
396
- delete nonSenderKeyData['sender-key'];
397
- if (Object.keys(nonSenderKeyData).length > 0) {
398
- await withMutexes(Object.keys(nonSenderKeyData), getKeyTypeMutex, async () => {
399
- // Process pre-keys and signed-pre-keys separately with specialized mutexes
400
- for (const key_ in nonSenderKeyData) {
401
- const keyType = key_;
402
- if (keyType === 'pre-key') {
403
- await processPreKeyDeletions(nonSenderKeyData, keyType, state, logger);
404
- }
405
- }
406
- // Apply changes to the store
407
- await state.set(nonSenderKeyData);
408
- });
409
- }
410
- }
411
- else {
412
- // No sender keys - use original logic
413
- await withMutexes(Object.keys(data), getKeyTypeMutex, async () => {
414
- // Process pre-keys and signed-pre-keys separately with specialized mutexes
415
- for (const key_ in data) {
416
- const keyType = key_;
417
- if (keyType === 'pre-key') {
418
- await processPreKeyDeletions(data, keyType, state, logger);
419
- }
420
- }
421
- // Apply changes to the store
422
- await state.set(data);
423
- });
424
- }
425
- }
426
- },
427
- isInTransaction,
428
- async transaction(work, key) {
429
- const releaseTxMutex = await getTransactionMutex(key).acquire();
430
- try {
431
- transactionsInProgress += 1;
432
- if (transactionsInProgress === 1) {
433
- logger.trace('entering transaction');
434
- }
435
- // Release the transaction mutex now that we've updated the counter
436
- // This allows other transactions to start preparing
437
- releaseTxMutex();
438
- try {
439
- return await executeTransactionWork(work);
440
- }
441
- finally {
442
- cleanupTransactionState();
391
+ };
392
+ logger.trace({
393
+ senderKeyName
394
+ }, 'storing sender key');
395
+ // Apply changes to the store
396
+ await state.set(senderKeyData);
397
+ logger.trace({
398
+ senderKeyName
399
+ }, 'sender key stored');
400
+ });
401
+ }
402
+ // Handle any non-sender-key data with regular mutexes
403
+ const nonSenderKeyData = {
404
+ ...data
405
+ };
406
+ delete nonSenderKeyData['sender-key'];
407
+ if (Object.keys(nonSenderKeyData).length > 0) {
408
+ await withMutexes(Object.keys(nonSenderKeyData), getKeyTypeMutex, async () => {
409
+ // Process pre-keys and signed-pre-keys separately with specialized mutexes
410
+ for (const key_ in nonSenderKeyData) {
411
+ const keyType = key_;
412
+ if (keyType === 'pre-key') {
413
+ await processPreKeyDeletions(nonSenderKeyData, keyType, state, logger);
443
414
  }
415
+ }
416
+ // Apply changes to the store
417
+ await state.set(nonSenderKeyData);
418
+ });
419
+ }
420
+ } else {
421
+ // No sender keys - use original logic
422
+ await withMutexes(Object.keys(data), getKeyTypeMutex, async () => {
423
+ // Process pre-keys and signed-pre-keys separately with specialized mutexes
424
+ for (const key_ in data) {
425
+ const keyType = key_;
426
+ if (keyType === 'pre-key') {
427
+ await processPreKeyDeletions(data, keyType, state, logger);
428
+ }
444
429
  }
445
- catch (error) {
446
- releaseTxMutex();
447
- throw error;
448
- }
430
+ // Apply changes to the store
431
+ await state.set(data);
432
+ });
449
433
  }
450
- };
434
+ }
435
+ },
436
+ isInTransaction,
437
+ async transaction(work, key) {
438
+ const releaseTxMutex = await getTransactionMutex(key).acquire();
439
+ try {
440
+ transactionsInProgress += 1;
441
+ if (transactionsInProgress === 1) {
442
+ logger.trace('entering transaction');
443
+ }
444
+ // Release the transaction mutex now that we've updated the counter
445
+ // This allows other transactions to start preparing
446
+ releaseTxMutex();
447
+ try {
448
+ return await executeTransactionWork(work);
449
+ } finally {
450
+ cleanupTransactionState();
451
+ }
452
+ } catch (error) {
453
+ releaseTxMutex();
454
+ throw error;
455
+ }
456
+ }
457
+ };
451
458
  };
452
459
  export const initAuthCreds = () => {
453
- const identityKey = Curve.generateKeyPair();
454
- return {
455
- noiseKey: Curve.generateKeyPair(),
456
- pairingEphemeralKeyPair: Curve.generateKeyPair(),
457
- signedIdentityKey: identityKey,
458
- signedPreKey: signedKeyPair(identityKey, 1),
459
- registrationId: generateRegistrationId(),
460
- advSecretKey: randomBytes(32).toString('base64'),
461
- processedHistoryMessages: [],
462
- nextPreKeyId: 1,
463
- firstUnuploadedPreKeyId: 1,
464
- accountSyncCounter: 0,
465
- accountSettings: {
466
- unarchiveChats: false
467
- },
468
- registered: false,
469
- pairingCode: undefined,
470
- lastPropHash: undefined,
471
- routingInfo: undefined
472
- };
460
+ const identityKey = Curve.generateKeyPair();
461
+ return {
462
+ noiseKey: Curve.generateKeyPair(),
463
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
464
+ signedIdentityKey: identityKey,
465
+ signedPreKey: signedKeyPair(identityKey, 1),
466
+ registrationId: generateRegistrationId(),
467
+ advSecretKey: randomBytes(32).toString('base64'),
468
+ processedHistoryMessages: [],
469
+ nextPreKeyId: 1,
470
+ firstUnuploadedPreKeyId: 1,
471
+ accountSyncCounter: 0,
472
+ accountSettings: {
473
+ unarchiveChats: false
474
+ },
475
+ registered: false,
476
+ pairingCode: undefined,
477
+ lastPropHash: undefined,
478
+ routingInfo: undefined
479
+ };
473
480
  };
474
481
  //# sourceMappingURL=auth-utils.js.map