@badzz88/baileys 8.5.7 → 8.5.9

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 (142) hide show
  1. package/README.md +337 -1055
  2. package/WAProto/WAProto.proto +284 -264
  3. package/WAProto/index.js +5 -5
  4. package/engine-requirements.js +7 -15
  5. package/lib/Defaults/index.js +130 -187
  6. package/lib/Signal/Group/ciphertext-message.js +11 -14
  7. package/lib/Signal/Group/group-session-builder.js +29 -91
  8. package/lib/Signal/Group/group_cipher.js +81 -88
  9. package/lib/Signal/Group/index.js +12 -136
  10. package/lib/Signal/Group/keyhelper.js +15 -70
  11. package/lib/Signal/Group/sender-chain-key.js +25 -31
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -65
  13. package/lib/Signal/Group/sender-key-message.js +65 -68
  14. package/lib/Signal/Group/sender-key-name.js +41 -43
  15. package/lib/Signal/Group/sender-key-record.js +40 -43
  16. package/lib/Signal/Group/sender-key-state.js +83 -96
  17. package/lib/Signal/Group/sender-message-key.js +25 -29
  18. package/lib/Signal/libsignal.js +425 -453
  19. package/lib/Signal/lid-mapping.js +276 -259
  20. package/lib/Socket/Client/index.js +3 -30
  21. package/lib/Socket/Client/types.js +10 -12
  22. package/lib/Socket/Client/websocket.js +53 -61
  23. package/lib/Socket/business.js +379 -422
  24. package/lib/Socket/chats.js +1193 -1816
  25. package/lib/Socket/communities.js +431 -549
  26. package/lib/Socket/graphql.js +672 -612
  27. package/lib/Socket/groups.js +374 -764
  28. package/lib/Socket/index.js +17 -38
  29. package/lib/Socket/interop.js +417 -503
  30. package/lib/Socket/messages-recv.js +1915 -2441
  31. package/lib/Socket/messages-send.js +1213 -1630
  32. package/lib/Socket/mex.js +9 -15
  33. package/lib/Socket/newsletter.js +746 -808
  34. package/lib/Socket/privacy.js +310 -441
  35. package/lib/Socket/socket.js +1025 -1022
  36. package/lib/Socket/username.js +8 -15
  37. package/lib/Store/index.js +10 -36
  38. package/lib/Store/make-cache-manager-store.js +80 -85
  39. package/lib/Store/make-in-memory-store.js +231 -591
  40. package/lib/Store/make-ordered-dictionary.js +72 -78
  41. package/lib/Store/object-repository.js +28 -25
  42. package/lib/Types/Auth.js +2 -38
  43. package/lib/Types/Bussines.js +2 -2
  44. package/lib/Types/Call.js +2 -2
  45. package/lib/Types/Chat.js +8 -4
  46. package/lib/Types/Contact.js +2 -2
  47. package/lib/Types/Events.js +2 -2
  48. package/lib/Types/GroupMetadata.js +2 -2
  49. package/lib/Types/Label.js +24 -26
  50. package/lib/Types/LabelAssociation.js +6 -8
  51. package/lib/Types/Message.js +11 -95
  52. package/lib/Types/Mex.js +111 -112
  53. package/lib/Types/Product.js +2 -2
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.js +3 -2
  56. package/lib/Types/State.js +56 -70
  57. package/lib/Types/USync.js +2 -2
  58. package/lib/Types/index.js +26 -55
  59. package/lib/Utils/auth-utils.js +288 -292
  60. package/lib/Utils/browser-utils.js +47 -113
  61. package/lib/Utils/business.js +224 -240
  62. package/lib/Utils/chat-utils.js +869 -1205
  63. package/lib/Utils/companion-reg-client-utils.js +34 -41
  64. package/lib/Utils/crypto.js +107 -144
  65. package/lib/Utils/decode-wa-message.js +308 -518
  66. package/lib/Utils/event-buffer.js +611 -596
  67. package/lib/Utils/generics.js +355 -515
  68. package/lib/Utils/history.js +134 -244
  69. package/lib/Utils/identity-change-handler.js +49 -51
  70. package/lib/Utils/index.js +23 -57
  71. package/lib/Utils/link-preview.js +77 -135
  72. package/lib/Utils/logger.js +3 -9
  73. package/lib/Utils/lt-hash.js +6 -37
  74. package/lib/Utils/make-mutex.js +33 -36
  75. package/lib/Utils/message-composer.js +233 -439
  76. package/lib/Utils/message-retry-manager.js +260 -265
  77. package/lib/Utils/messages-media.js +829 -855
  78. package/lib/Utils/messages.js +961 -2528
  79. package/lib/Utils/noise-handler.js +200 -195
  80. package/lib/Utils/offline-node-processor.js +33 -35
  81. package/lib/Utils/pre-key-manager.js +102 -103
  82. package/lib/Utils/process-message.js +560 -978
  83. package/lib/Utils/reporting-utils.js +253 -257
  84. package/lib/Utils/signal.js +195 -218
  85. package/lib/Utils/stanza-ack.js +29 -31
  86. package/lib/Utils/sticker.js +109 -144
  87. package/lib/Utils/sync-action-utils.js +45 -50
  88. package/lib/Utils/tc-token-utils.js +139 -137
  89. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  90. package/lib/Utils/validate-connection.js +202 -218
  91. package/lib/WABinary/constants.js +1299 -1302
  92. package/lib/WABinary/decode.js +262 -343
  93. package/lib/WABinary/encode.js +4 -12
  94. package/lib/WABinary/generic-utils.js +187 -223
  95. package/lib/WABinary/index.js +6 -33
  96. package/lib/WABinary/jid-utils.js +88 -351
  97. package/lib/WABinary/types.js +2 -2
  98. package/lib/WAM/BinaryInfo.js +9 -12
  99. package/lib/WAM/constants.js +22853 -39486
  100. package/lib/WAM/encode.js +140 -132
  101. package/lib/WAM/index.js +4 -31
  102. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +21 -23
  103. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +9 -9
  104. package/lib/WAUSync/Protocols/USyncContactProtocol.js +7 -7
  105. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +10 -10
  106. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +7 -7
  107. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +11 -12
  108. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +4 -5
  109. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +7 -7
  110. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +7 -8
  111. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -7
  112. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +8 -8
  113. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +7 -7
  114. package/lib/WAUSync/Protocols/index.js +12 -39
  115. package/lib/WAUSync/USyncQuery.js +67 -49
  116. package/lib/WAUSync/USyncUser.js +11 -5
  117. package/lib/WAUSync/index.js +3 -31
  118. package/lib/index.js +15 -48
  119. package/package.json +129 -99
  120. package/LICENSE +0 -21
  121. package/lib/Defaults/phonenumber-mcc.json +0 -223
  122. package/lib/Socket/aigroups.js +0 -240
  123. package/lib/Socket/interactive-handler.js +0 -522
  124. package/lib/Socket/managed-account.js +0 -183
  125. package/lib/Socket/registration.js +0 -427
  126. package/lib/Socket/text-router.js +0 -83
  127. package/lib/Types/Newsletter.js +0 -121
  128. package/lib/Utils/command-loader.d.ts +0 -31
  129. package/lib/Utils/command-loader.js +0 -100
  130. package/lib/Utils/consumer-application.js +0 -107
  131. package/lib/Utils/curve25519-js.js +0 -275
  132. package/lib/Utils/group-history.js +0 -60
  133. package/lib/Utils/jid-display-normalization.js +0 -218
  134. package/lib/Utils/meta-ai-msmsg.js +0 -262
  135. package/lib/Utils/native-bridge.js +0 -82
  136. package/lib/Utils/session-pool.d.ts +0 -16
  137. package/lib/Utils/session-pool.js +0 -94
  138. package/lib/Utils/sticker.d.ts +0 -17
  139. package/lib/Utils/view-once-cache.d.ts +0 -9
  140. package/lib/Utils/view-once-cache.js +0 -79
  141. package/lib/Utils/voip-rekey.js +0 -22
  142. package/lib/antiban.js +0 -4637
@@ -1,86 +1,78 @@
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')
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';
19
11
  /**
20
12
  * Adds caching capability to a SignalKeyStore
21
13
  * @param store the store to add caching to
22
14
  * @param logger to log trace events
23
15
  * @param _cache cache store to use
24
16
  */
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
- }
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
+ };
84
76
  }
85
77
  /**
86
78
  * Adds DB-like transaction capability to the SignalKeyStore
@@ -89,218 +81,222 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
89
81
  * @param logger logger to log events
90
82
  * @returns SignalKeyStore with transaction capability
91
83
  */
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
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