@badzz88/baileys 8.4.7 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/index.js +5 -5
  4. package/lib/Defaults/index.js +187 -127
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +14 -11
  7. package/lib/Signal/Group/group-session-builder.js +91 -29
  8. package/lib/Signal/Group/group_cipher.js +88 -81
  9. package/lib/Signal/Group/index.js +136 -12
  10. package/lib/Signal/Group/keyhelper.js +70 -15
  11. package/lib/Signal/Group/sender-chain-key.js +31 -25
  12. package/lib/Signal/Group/sender-key-distribution-message.js +65 -62
  13. package/lib/Signal/Group/sender-key-message.js +68 -65
  14. package/lib/Signal/Group/sender-key-name.js +43 -41
  15. package/lib/Signal/Group/sender-key-record.js +43 -40
  16. package/lib/Signal/Group/sender-key-state.js +96 -83
  17. package/lib/Signal/Group/sender-message-key.js +29 -25
  18. package/lib/Signal/libsignal.js +483 -424
  19. package/lib/Signal/lid-mapping.js +261 -276
  20. package/lib/Socket/Client/index.js +30 -3
  21. package/lib/Socket/Client/types.js +12 -10
  22. package/lib/Socket/Client/websocket.js +61 -53
  23. package/lib/Socket/aigroups.js +240 -0
  24. package/lib/Socket/business.js +422 -379
  25. package/lib/Socket/chats.js +1816 -1193
  26. package/lib/Socket/communities.js +549 -431
  27. package/lib/Socket/graphql.js +656 -0
  28. package/lib/Socket/groups.js +764 -374
  29. package/lib/Socket/index.js +38 -11
  30. package/lib/Socket/interactive-handler.js +522 -0
  31. package/lib/Socket/interop.js +549 -0
  32. package/lib/Socket/luxu.js +6 -5
  33. package/lib/Socket/managed-account.js +183 -0
  34. package/lib/Socket/messages-recv.js +2439 -1915
  35. package/lib/Socket/messages-send.js +1642 -1242
  36. package/lib/Socket/mex.js +59 -40
  37. package/lib/Socket/newsletter.js +812 -249
  38. package/lib/Socket/privacy.js +449 -0
  39. package/lib/Socket/registration.js +427 -0
  40. package/lib/Socket/socket.js +1077 -965
  41. package/lib/Socket/text-router.js +83 -0
  42. package/lib/Socket/username.js +237 -140
  43. package/lib/Store/index.js +36 -10
  44. package/lib/Store/make-cache-manager-store.js +85 -80
  45. package/lib/Store/make-in-memory-store.js +591 -185
  46. package/lib/Store/make-ordered-dictionary.js +78 -72
  47. package/lib/Store/object-repository.js +25 -28
  48. package/lib/Types/Auth.js +38 -2
  49. package/lib/Types/Bussines.js +2 -2
  50. package/lib/Types/Call.js +2 -2
  51. package/lib/Types/Chat.js +4 -8
  52. package/lib/Types/Contact.js +2 -2
  53. package/lib/Types/Events.js +2 -2
  54. package/lib/Types/GroupMetadata.js +2 -2
  55. package/lib/Types/Label.js +26 -24
  56. package/lib/Types/LabelAssociation.js +8 -6
  57. package/lib/Types/Message.js +95 -11
  58. package/lib/Types/Mex.js +112 -37
  59. package/lib/Types/Newsletter.js +121 -0
  60. package/lib/Types/Product.js +2 -2
  61. package/lib/Types/Signal.js +2 -2
  62. package/lib/Types/Socket.js +2 -3
  63. package/lib/Types/State.js +70 -56
  64. package/lib/Types/USync.js +2 -2
  65. package/lib/Types/index.js +55 -26
  66. package/lib/Utils/auth-utils.js +292 -288
  67. package/lib/Utils/browser-utils.js +113 -48
  68. package/lib/Utils/business.js +240 -224
  69. package/lib/Utils/chat-utils.js +1205 -869
  70. package/lib/Utils/command-loader.d.ts +31 -0
  71. package/lib/Utils/command-loader.js +100 -0
  72. package/lib/Utils/companion-reg-client-utils.js +41 -34
  73. package/lib/Utils/consumer-application.js +107 -0
  74. package/lib/Utils/crypto.js +144 -107
  75. package/lib/Utils/curve25519-js.js +275 -0
  76. package/lib/Utils/decode-wa-message.js +518 -308
  77. package/lib/Utils/event-buffer.js +596 -611
  78. package/lib/Utils/generics.js +514 -354
  79. package/lib/Utils/group-history.js +60 -0
  80. package/lib/Utils/history.js +244 -134
  81. package/lib/Utils/identity-change-handler.js +51 -49
  82. package/lib/Utils/index.js +57 -23
  83. package/lib/Utils/jid-display-normalization.js +218 -0
  84. package/lib/Utils/link-preview.js +135 -77
  85. package/lib/Utils/logger.js +9 -3
  86. package/lib/Utils/lt-hash.js +37 -6
  87. package/lib/Utils/make-mutex.js +36 -33
  88. package/lib/Utils/message-composer.js +439 -233
  89. package/lib/Utils/message-retry-manager.js +265 -260
  90. package/lib/Utils/messages-media.js +855 -747
  91. package/lib/Utils/messages.js +2528 -884
  92. package/lib/Utils/meta-ai-msmsg.js +262 -0
  93. package/lib/Utils/native-bridge.js +82 -0
  94. package/lib/Utils/noise-handler.js +195 -200
  95. package/lib/Utils/offline-node-processor.js +35 -33
  96. package/lib/Utils/pre-key-manager.js +103 -102
  97. package/lib/Utils/process-message.js +978 -560
  98. package/lib/Utils/reporting-utils.js +257 -253
  99. package/lib/Utils/session-pool.d.ts +16 -0
  100. package/lib/Utils/session-pool.js +94 -0
  101. package/lib/Utils/signal.js +218 -195
  102. package/lib/Utils/stanza-ack.js +31 -29
  103. package/lib/Utils/sticker.d.ts +17 -0
  104. package/lib/Utils/sticker.js +145 -0
  105. package/lib/Utils/sync-action-utils.js +50 -45
  106. package/lib/Utils/tc-token-utils.js +137 -139
  107. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  108. package/lib/Utils/validate-connection.js +218 -202
  109. package/lib/Utils/view-once-cache.d.ts +9 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +22 -0
  112. package/lib/WABinary/constants.js +1302 -1299
  113. package/lib/WABinary/decode.js +343 -262
  114. package/lib/WABinary/encode.js +12 -4
  115. package/lib/WABinary/generic-utils.js +223 -187
  116. package/lib/WABinary/index.js +33 -6
  117. package/lib/WABinary/jid-utils.js +351 -88
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.js +12 -9
  120. package/lib/WAM/constants.js +39486 -22853
  121. package/lib/WAM/encode.js +132 -140
  122. package/lib/WAM/index.js +31 -4
  123. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -51
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +56 -53
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -26
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  129. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  131. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -37
  133. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  134. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +26 -24
  135. package/lib/WAUSync/Protocols/index.js +39 -6
  136. package/lib/WAUSync/USyncQuery.js +132 -97
  137. package/lib/WAUSync/USyncUser.js +49 -30
  138. package/lib/WAUSync/index.js +31 -4
  139. package/lib/antiban.js +4637 -0
  140. package/lib/index.js +48 -15
  141. package/package.json +55 -92
  142. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  143. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  144. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
@@ -1,78 +1,86 @@
1
- import NodeCache from '@cacheable/node-cache';
2
- import { Boom } from '@hapi/boom';
3
- import { AsyncLocalStorage } from 'async_hooks';
4
- import { Mutex } from 'async-mutex';
5
- import { randomBytes } from 'crypto';
6
- import PQueue from 'p-queue';
7
- import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js';
8
- import { Curve, signedKeyPair } from './crypto.js';
9
- import { delay, generateRegistrationId } from './generics.js';
10
- import { PreKeyManager } from './pre-key-manager.js';
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ exports.initAuthCreds = exports.addTransactionCapability = void 0
9
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore
10
+ const node_cache_1 = __importDefault(require('@cacheable/node-cache'))
11
+ const async_hooks_1 = require('async_hooks')
12
+ const async_mutex_1 = require('async-mutex')
13
+ const crypto_1 = require('crypto')
14
+ const p_queue_1 = __importDefault(require('p-queue'))
15
+ const Defaults_1 = require('../Defaults')
16
+ const crypto_2 = require('./crypto')
17
+ const generics_1 = require('./generics')
18
+ const pre_key_manager_1 = require('./pre-key-manager')
11
19
  /**
12
20
  * Adds caching capability to a SignalKeyStore
13
21
  * @param store the store to add caching to
14
22
  * @param logger to log trace events
15
23
  * @param _cache cache store to use
16
24
  */
17
- export function makeCacheableSignalKeyStore(store, logger, _cache) {
18
- const cache = _cache ||
19
- new NodeCache({
20
- stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
21
- useClones: false,
22
- deleteOnExpire: true
23
- });
24
- // Mutex for protecting cache operations
25
- const cacheMutex = new Mutex();
26
- function getUniqueId(type, id) {
27
- return `${type}.${id}`;
28
- }
29
- return {
30
- async get(type, ids) {
31
- return cacheMutex.runExclusive(async () => {
32
- const data = {};
33
- const idsToFetch = [];
34
- for (const id of ids) {
35
- const item = (await cache.get(getUniqueId(type, id)));
36
- if (typeof item !== 'undefined') {
37
- data[id] = item;
38
- }
39
- else {
40
- idsToFetch.push(id);
41
- }
42
- }
43
- if (idsToFetch.length) {
44
- logger?.trace({ items: idsToFetch.length }, 'loading from store');
45
- const fetched = await store.get(type, idsToFetch);
46
- for (const id of idsToFetch) {
47
- const item = fetched[id];
48
- if (item) {
49
- data[id] = item;
50
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
51
- await cache.set(getUniqueId(type, id), item);
52
- }
53
- }
54
- }
55
- return data;
56
- });
57
- },
58
- async set(data) {
59
- return cacheMutex.runExclusive(async () => {
60
- let keys = 0;
61
- for (const type in data) {
62
- for (const id in data[type]) {
63
- await cache.set(getUniqueId(type, id), data[type][id]);
64
- keys += 1;
65
- }
66
- }
67
- logger?.trace({ keys }, 'updated cache');
68
- await store.set(data);
69
- });
70
- },
71
- async clear() {
72
- await cache.flushAll();
73
- await store.clear?.();
74
- }
75
- };
25
+ function makeCacheableSignalKeyStore(store, logger, _cache) {
26
+ const cache =
27
+ _cache ||
28
+ new node_cache_1.default({
29
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
30
+ useClones: false,
31
+ deleteOnExpire: true
32
+ })
33
+ // Mutex for protecting cache operations
34
+ const cacheMutex = new async_mutex_1.Mutex()
35
+ function getUniqueId(type, id) {
36
+ return `${type}.${id}`
37
+ }
38
+ return {
39
+ async get(type, ids) {
40
+ return cacheMutex.runExclusive(async () => {
41
+ const data = {}
42
+ const idsToFetch = []
43
+ for (const id of ids) {
44
+ const item = await cache.get(getUniqueId(type, id))
45
+ if (typeof item !== 'undefined') {
46
+ data[id] = item
47
+ } else {
48
+ idsToFetch.push(id)
49
+ }
50
+ }
51
+ if (idsToFetch.length) {
52
+ logger?.trace({ items: idsToFetch.length }, 'loading from store')
53
+ const fetched = await store.get(type, idsToFetch)
54
+ for (const id of idsToFetch) {
55
+ const item = fetched[id]
56
+ if (item) {
57
+ data[id] = item
58
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
59
+ await cache.set(getUniqueId(type, id), item)
60
+ }
61
+ }
62
+ }
63
+ return data
64
+ })
65
+ },
66
+ async set(data) {
67
+ return cacheMutex.runExclusive(async () => {
68
+ let keys = 0
69
+ for (const type in data) {
70
+ for (const id in data[type]) {
71
+ await cache.set(getUniqueId(type, id), data[type][id])
72
+ keys += 1
73
+ }
74
+ }
75
+ logger?.trace({ keys }, 'updated cache')
76
+ await store.set(data)
77
+ })
78
+ },
79
+ async clear() {
80
+ await cache.flushAll()
81
+ await store.clear?.()
82
+ }
83
+ }
76
84
  }
77
85
  /**
78
86
  * Adds DB-like transaction capability to the SignalKeyStore
@@ -81,222 +89,218 @@ export function makeCacheableSignalKeyStore(store, logger, _cache) {
81
89
  * @param logger logger to log events
82
90
  * @returns SignalKeyStore with transaction capability
83
91
  */
84
- export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
85
- const txStorage = new AsyncLocalStorage();
86
- // Queues for concurrency control (keyed by signal data type - bounded set)
87
- const keyQueues = new Map();
88
- // Transaction mutexes with reference counting for cleanup
89
- const txMutexes = new Map();
90
- const txMutexRefCounts = new Map();
91
- // Pre-key manager for specialized operations
92
- const preKeyManager = new PreKeyManager(state, logger);
93
- /**
94
- * Get or create a queue for a specific key type
95
- */
96
- function getQueue(key) {
97
- if (!keyQueues.has(key)) {
98
- keyQueues.set(key, new PQueue({ concurrency: 1 }));
99
- }
100
- return keyQueues.get(key);
101
- }
102
- /**
103
- * Get or create a transaction mutex
104
- */
105
- function getTxMutex(key) {
106
- if (!txMutexes.has(key)) {
107
- txMutexes.set(key, new Mutex());
108
- txMutexRefCounts.set(key, 0);
109
- }
110
- return txMutexes.get(key);
111
- }
112
- /**
113
- * Acquire a reference to a transaction mutex
114
- */
115
- function acquireTxMutexRef(key) {
116
- const count = txMutexRefCounts.get(key) ?? 0;
117
- txMutexRefCounts.set(key, count + 1);
118
- }
119
- /**
120
- * Release a reference to a transaction mutex and cleanup if no longer needed
121
- */
122
- function releaseTxMutexRef(key) {
123
- const count = (txMutexRefCounts.get(key) ?? 1) - 1;
124
- txMutexRefCounts.set(key, count);
125
- // Cleanup if no more references and mutex is not locked
126
- if (count <= 0) {
127
- const mutex = txMutexes.get(key);
128
- if (mutex && !mutex.isLocked()) {
129
- txMutexes.delete(key);
130
- txMutexRefCounts.delete(key);
131
- }
132
- }
133
- }
134
- /**
135
- * Check if currently in a transaction
136
- */
137
- function isInTransaction() {
138
- return !!txStorage.getStore();
139
- }
140
- /**
141
- * Commit transaction with retries
142
- */
143
- async function commitWithRetry(mutations) {
144
- if (Object.keys(mutations).length === 0) {
145
- logger.trace('no mutations in transaction');
146
- return;
147
- }
148
- logger.trace('committing transaction');
149
- for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
150
- try {
151
- await state.set(mutations);
152
- logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction');
153
- return;
154
- }
155
- catch (error) {
156
- const retriesLeft = maxCommitRetries - attempt - 1;
157
- logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
158
- if (retriesLeft === 0) {
159
- throw error;
160
- }
161
- await delay(delayBetweenTriesMs);
162
- }
163
- }
164
- }
165
- return {
166
- get: async (type, ids) => {
167
- const ctx = txStorage.getStore();
168
- if (!ctx) {
169
- // No transaction - direct read without exclusive lock for concurrency
170
- return state.get(type, ids);
171
- }
172
- // In transaction - check cache first
173
- const cached = ctx.cache[type] || {};
174
- const missing = ids.filter(id => !(id in cached));
175
- if (missing.length > 0) {
176
- ctx.dbQueries++;
177
- logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction');
178
- const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
179
- // Update cache
180
- ctx.cache[type] = ctx.cache[type] || {};
181
- Object.assign(ctx.cache[type], fetched);
182
- }
183
- // Return requested ids from cache
184
- const result = {};
185
- for (const id of ids) {
186
- const value = ctx.cache[type]?.[id];
187
- if (value !== undefined && value !== null) {
188
- result[id] = value;
189
- }
190
- }
191
- return result;
192
- },
193
- set: async (data) => {
194
- const ctx = txStorage.getStore();
195
- if (!ctx) {
196
- // No transaction - direct write with queue protection
197
- const types = Object.keys(data);
198
- // Process pre-keys with validation
199
- for (const type_ of types) {
200
- const type = type_;
201
- if (type === 'pre-key') {
202
- await preKeyManager.validateDeletions(data, type);
203
- }
204
- }
205
- // Write all data in parallel
206
- await Promise.all(types.map(type => getQueue(type).add(async () => {
207
- const typeData = { [type]: data[type] };
208
- await state.set(typeData);
209
- })));
210
- return;
211
- }
212
- // In transaction - update cache and mutations
213
- logger.trace({ types: Object.keys(data) }, 'caching in transaction');
214
- for (const key_ in data) {
215
- const key = key_;
216
- // Ensure structures exist
217
- ctx.cache[key] = ctx.cache[key] || {};
218
- ctx.mutations[key] = ctx.mutations[key] || {};
219
- // Special handling for pre-keys
220
- if (key === 'pre-key') {
221
- await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
222
- }
223
- else {
224
- // Normal key types
225
- Object.assign(ctx.cache[key], data[key]);
226
- Object.assign(ctx.mutations[key], data[key]);
227
- }
228
- }
229
- },
230
- isInTransaction,
231
- transaction: async (work, key) => {
232
- const existing = txStorage.getStore();
233
- // Nested transaction - reuse existing context
234
- if (existing) {
235
- logger.trace('reusing existing transaction context');
236
- return work();
237
- }
238
- // New transaction - acquire mutex and create context
239
- const mutex = getTxMutex(key);
240
- acquireTxMutexRef(key);
241
- try {
242
- return await mutex.runExclusive(async () => {
243
- const ctx = {
244
- cache: {},
245
- mutations: {},
246
- dbQueries: 0
247
- };
248
- logger.trace('entering transaction');
249
- try {
250
- const result = await txStorage.run(ctx, work);
251
- // Commit mutations
252
- await commitWithRetry(ctx.mutations);
253
- logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed');
254
- return result;
255
- }
256
- catch (error) {
257
- logger.error({ error }, 'transaction failed, rolling back');
258
- throw error;
259
- }
260
- });
261
- }
262
- finally {
263
- releaseTxMutexRef(key);
264
- }
265
- }
266
- };
267
- };
268
- /**
269
- * Returns the authenticated user's JID, or throws a Boom-401 if creds are not yet authenticated.
270
- * Use this anywhere we'd otherwise reach for `creds.me!.id` to fail fast with a descriptive error.
271
- */
272
- export const assertMeId = (creds) => {
273
- const id = creds.me?.id;
274
- if (!id) {
275
- throw new Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 });
276
- }
277
- return id;
278
- };
279
- export const initAuthCreds = () => {
280
- const identityKey = Curve.generateKeyPair();
281
- return {
282
- noiseKey: Curve.generateKeyPair(),
283
- pairingEphemeralKeyPair: Curve.generateKeyPair(),
284
- signedIdentityKey: identityKey,
285
- signedPreKey: signedKeyPair(identityKey, 1),
286
- registrationId: generateRegistrationId(),
287
- advSecretKey: randomBytes(32).toString('base64'),
288
- processedHistoryMessages: [],
289
- nextPreKeyId: 1,
290
- firstUnuploadedPreKeyId: 1,
291
- accountSyncCounter: 0,
292
- accountSettings: {
293
- unarchiveChats: false
294
- },
295
- registered: false,
296
- pairingCode: undefined,
297
- lastPropHash: undefined,
298
- routingInfo: undefined,
299
- additionalData: undefined
300
- };
301
- };
302
- //# sourceMappingURL=auth-utils.js.map
92
+ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
93
+ const txStorage = new async_hooks_1.AsyncLocalStorage()
94
+ // Queues for concurrency control (keyed by signal data type - bounded set)
95
+ const keyQueues = new Map()
96
+ // Transaction mutexes with reference counting for cleanup
97
+ const txMutexes = new Map()
98
+ const txMutexRefCounts = new Map()
99
+ // Pre-key manager for specialized operations
100
+ const preKeyManager = new pre_key_manager_1.PreKeyManager(state, logger)
101
+ /**
102
+ * Get or create a queue for a specific key type
103
+ */
104
+ function getQueue(key) {
105
+ if (!keyQueues.has(key)) {
106
+ keyQueues.set(key, new p_queue_1.default({ concurrency: 1 }))
107
+ }
108
+ return keyQueues.get(key)
109
+ }
110
+ /**
111
+ * Get or create a transaction mutex
112
+ */
113
+ function getTxMutex(key) {
114
+ if (!txMutexes.has(key)) {
115
+ txMutexes.set(key, new async_mutex_1.Mutex())
116
+ txMutexRefCounts.set(key, 0)
117
+ }
118
+ return txMutexes.get(key)
119
+ }
120
+ /**
121
+ * Acquire a reference to a transaction mutex
122
+ */
123
+ function acquireTxMutexRef(key) {
124
+ const count = txMutexRefCounts.get(key) ?? 0
125
+ txMutexRefCounts.set(key, count + 1)
126
+ }
127
+ /**
128
+ * Release a reference to a transaction mutex and cleanup if no longer needed
129
+ */
130
+ function releaseTxMutexRef(key) {
131
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1
132
+ txMutexRefCounts.set(key, count)
133
+ // Cleanup if no more references and mutex is not locked
134
+ if (count <= 0) {
135
+ const mutex = txMutexes.get(key)
136
+ if (mutex && !mutex.isLocked()) {
137
+ txMutexes.delete(key)
138
+ txMutexRefCounts.delete(key)
139
+ }
140
+ }
141
+ }
142
+ /**
143
+ * Check if currently in a transaction
144
+ */
145
+ function isInTransaction() {
146
+ return !!txStorage.getStore()
147
+ }
148
+ /**
149
+ * Commit transaction with retries
150
+ */
151
+ async function commitWithRetry(mutations) {
152
+ if (Object.keys(mutations).length === 0) {
153
+ logger.trace('no mutations in transaction')
154
+ return
155
+ }
156
+ logger.trace('committing transaction')
157
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
158
+ try {
159
+ await state.set(mutations)
160
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction')
161
+ return
162
+ } catch (error) {
163
+ const retriesLeft = maxCommitRetries - attempt - 1
164
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`)
165
+ if (retriesLeft === 0) {
166
+ throw error
167
+ }
168
+ await (0, generics_1.delay)(delayBetweenTriesMs)
169
+ }
170
+ }
171
+ }
172
+ return {
173
+ get: async (type, ids) => {
174
+ const ctx = txStorage.getStore()
175
+ if (!ctx) {
176
+ // No transaction - direct read without exclusive lock for concurrency
177
+ return state.get(type, ids)
178
+ }
179
+ // In transaction - check cache first
180
+ const cached = ctx.cache[type] || {}
181
+ const missing = ids.filter(id => !(id in cached))
182
+ if (missing.length > 0) {
183
+ ctx.dbQueries++
184
+ logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction')
185
+ const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing))
186
+ // Update cache
187
+ ctx.cache[type] = ctx.cache[type] || {}
188
+ Object.assign(ctx.cache[type], fetched)
189
+ }
190
+ // Return requested ids from cache
191
+ const result = {}
192
+ for (const id of ids) {
193
+ const value = ctx.cache[type]?.[id]
194
+ if (value !== undefined && value !== null) {
195
+ result[id] = value
196
+ }
197
+ }
198
+ return result
199
+ },
200
+ set: async data => {
201
+ const ctx = txStorage.getStore()
202
+ if (!ctx) {
203
+ // No transaction - direct write with queue protection
204
+ const types = Object.keys(data)
205
+ // Process pre-keys with validation
206
+ for (const type_ of types) {
207
+ const type = type_
208
+ if (type === 'pre-key') {
209
+ await preKeyManager.validateDeletions(data, type)
210
+ }
211
+ }
212
+ // Write all data in parallel
213
+ await Promise.all(
214
+ types.map(type =>
215
+ getQueue(type).add(async () => {
216
+ const typeData = { [type]: data[type] }
217
+ await state.set(typeData)
218
+ })
219
+ )
220
+ )
221
+ return
222
+ }
223
+ // In transaction - update cache and mutations
224
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction')
225
+ for (const key_ in data) {
226
+ const key = key_
227
+ // Ensure structures exist
228
+ ctx.cache[key] = ctx.cache[key] || {}
229
+ ctx.mutations[key] = ctx.mutations[key] || {}
230
+ // Special handling for pre-keys
231
+ if (key === 'pre-key') {
232
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true)
233
+ } else {
234
+ // Normal key types
235
+ Object.assign(ctx.cache[key], data[key])
236
+ Object.assign(ctx.mutations[key], data[key])
237
+ }
238
+ }
239
+ },
240
+ isInTransaction,
241
+ transaction: async (work, key) => {
242
+ const existing = txStorage.getStore()
243
+ // Nested transaction - reuse existing context
244
+ if (existing) {
245
+ logger.trace('reusing existing transaction context')
246
+ return work()
247
+ }
248
+ // New transaction - acquire mutex and create context
249
+ const mutex = getTxMutex(key)
250
+ acquireTxMutexRef(key)
251
+ try {
252
+ return await mutex.runExclusive(async () => {
253
+ const ctx = {
254
+ cache: {},
255
+ mutations: {},
256
+ dbQueries: 0
257
+ }
258
+ logger.trace('entering transaction')
259
+ try {
260
+ const result = await txStorage.run(ctx, work)
261
+ // Commit mutations
262
+ await commitWithRetry(ctx.mutations)
263
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed')
264
+ return result
265
+ } catch (error) {
266
+ logger.error({ error }, 'transaction failed, rolling back')
267
+ throw error
268
+ }
269
+ })
270
+ } finally {
271
+ releaseTxMutexRef(key)
272
+ }
273
+ }
274
+ }
275
+ }
276
+ exports.addTransactionCapability = addTransactionCapability
277
+ const initAuthCreds = () => {
278
+ const identityKey = crypto_2.Curve.generateKeyPair()
279
+ return {
280
+ noiseKey: crypto_2.Curve.generateKeyPair(),
281
+ pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
282
+ signedIdentityKey: identityKey,
283
+ signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
284
+ registrationId: (0, generics_1.generateRegistrationId)(),
285
+ advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
286
+ processedHistoryMessages: [],
287
+ initialFullSyncDone: false,
288
+ nextPreKeyId: 1,
289
+ firstUnuploadedPreKeyId: 1,
290
+ accountSyncCounter: 0,
291
+ accountSettings: {
292
+ unarchiveChats: false
293
+ },
294
+ deviceId: Buffer.from((0, crypto_1.randomUUID)().replace(/-/g, ''), 'hex').toString('base64url'),
295
+ phoneId: (0, crypto_1.randomUUID)(),
296
+ identityId: (0, crypto_1.randomBytes)(20),
297
+ backupToken: (0, crypto_1.randomBytes)(20),
298
+ registration: {},
299
+ registered: false,
300
+ pairingCode: undefined,
301
+ lastPropHash: undefined,
302
+ routingInfo: undefined,
303
+ additionalData: undefined
304
+ }
305
+ }
306
+ exports.initAuthCreds = initAuthCreds