@bellaxchuu/flowred 0.8.6

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/LICENSE +21 -0
  2. package/README.md +214 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +6902 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.js +242946 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +190 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +92 -0
  12. package/lib/Signal/Group/group_cipher.js +89 -0
  13. package/lib/Signal/Group/index.js +136 -0
  14. package/lib/Signal/Group/keyhelper.js +73 -0
  15. package/lib/Signal/Group/sender-chain-key.js +32 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-message.js +69 -0
  18. package/lib/Signal/Group/sender-key-name.js +50 -0
  19. package/lib/Signal/Group/sender-key-record.js +44 -0
  20. package/lib/Signal/Group/sender-key-state.js +97 -0
  21. package/lib/Signal/Group/sender-message-key.js +30 -0
  22. package/lib/Signal/libsignal.js +490 -0
  23. package/lib/Signal/lid-mapping.js +262 -0
  24. package/lib/Socket/Client/index.js +30 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +62 -0
  27. package/lib/Socket/aigroups.js +240 -0
  28. package/lib/Socket/business.js +422 -0
  29. package/lib/Socket/chats.js +1816 -0
  30. package/lib/Socket/communities.js +549 -0
  31. package/lib/Socket/graphql.js +656 -0
  32. package/lib/Socket/groups.js +764 -0
  33. package/lib/Socket/index.js +39 -0
  34. package/lib/Socket/interactive-handler.js +522 -0
  35. package/lib/Socket/interop.js +549 -0
  36. package/lib/Socket/luxu.js +387 -0
  37. package/lib/Socket/managed-account.js +183 -0
  38. package/lib/Socket/messages-recv.js +2440 -0
  39. package/lib/Socket/messages-send.js +1853 -0
  40. package/lib/Socket/mex.js +60 -0
  41. package/lib/Socket/newsletter.js +820 -0
  42. package/lib/Socket/privacy.js +449 -0
  43. package/lib/Socket/registration.js +427 -0
  44. package/lib/Socket/socket.js +1092 -0
  45. package/lib/Socket/text-router.js +83 -0
  46. package/lib/Socket/username.js +243 -0
  47. package/lib/Store/index.js +36 -0
  48. package/lib/Store/keyed-db.js +108 -0
  49. package/lib/Store/make-cache-manager-store.js +90 -0
  50. package/lib/Store/make-in-memory-store.js +604 -0
  51. package/lib/Store/make-ordered-dictionary.js +81 -0
  52. package/lib/Store/object-repository.js +29 -0
  53. package/lib/Types/Auth.js +38 -0
  54. package/lib/Types/Bussines.js +2 -0
  55. package/lib/Types/Call.js +2 -0
  56. package/lib/Types/Chat.js +4 -0
  57. package/lib/Types/Contact.js +2 -0
  58. package/lib/Types/Events.js +2 -0
  59. package/lib/Types/GroupMetadata.js +2 -0
  60. package/lib/Types/Label.js +27 -0
  61. package/lib/Types/LabelAssociation.js +9 -0
  62. package/lib/Types/Message.js +95 -0
  63. package/lib/Types/Mex.js +112 -0
  64. package/lib/Types/Newsletter.js +121 -0
  65. package/lib/Types/Product.js +2 -0
  66. package/lib/Types/Signal.js +2 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +70 -0
  69. package/lib/Types/USync.js +2 -0
  70. package/lib/Types/index.js +55 -0
  71. package/lib/Utils/auth-utils.js +306 -0
  72. package/lib/Utils/browser-utils.js +114 -0
  73. package/lib/Utils/business.js +247 -0
  74. package/lib/Utils/chat-utils.js +1208 -0
  75. package/lib/Utils/command-loader.js +100 -0
  76. package/lib/Utils/companion-reg-client-utils.js +42 -0
  77. package/lib/Utils/consumer-application.js +107 -0
  78. package/lib/Utils/crypto.js +155 -0
  79. package/lib/Utils/curve25519-js.js +275 -0
  80. package/lib/Utils/decode-wa-message.js +560 -0
  81. package/lib/Utils/event-buffer.js +607 -0
  82. package/lib/Utils/generics.js +563 -0
  83. package/lib/Utils/group-history.js +60 -0
  84. package/lib/Utils/history.js +244 -0
  85. package/lib/Utils/identity-change-handler.js +52 -0
  86. package/lib/Utils/index.js +57 -0
  87. package/lib/Utils/jid-display-normalization.js +218 -0
  88. package/lib/Utils/link-preview.js +143 -0
  89. package/lib/Utils/logger.js +9 -0
  90. package/lib/Utils/lt-hash.js +39 -0
  91. package/lib/Utils/make-mutex.js +36 -0
  92. package/lib/Utils/message-composer.js +479 -0
  93. package/lib/Utils/message-retry-manager.js +270 -0
  94. package/lib/Utils/messages-media.js +896 -0
  95. package/lib/Utils/messages.js +2904 -0
  96. package/lib/Utils/meta-ai-msmsg.js +262 -0
  97. package/lib/Utils/native-bridge.js +82 -0
  98. package/lib/Utils/noise-handler.js +196 -0
  99. package/lib/Utils/offline-node-processor.js +42 -0
  100. package/lib/Utils/pre-key-manager.js +107 -0
  101. package/lib/Utils/process-message.js +1048 -0
  102. package/lib/Utils/reporting-utils.js +262 -0
  103. package/lib/Utils/session-pool.js +94 -0
  104. package/lib/Utils/signal.js +224 -0
  105. package/lib/Utils/stanza-ack.js +40 -0
  106. package/lib/Utils/sticker.js +145 -0
  107. package/lib/Utils/sync-action-utils.js +54 -0
  108. package/lib/Utils/tc-token-utils.js +161 -0
  109. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  110. package/lib/Utils/validate-connection.js +219 -0
  111. package/lib/Utils/view-once-cache.js +79 -0
  112. package/lib/Utils/voip-rekey.js +22 -0
  113. package/lib/WABinary/constants.js +1304 -0
  114. package/lib/WABinary/decode.js +343 -0
  115. package/lib/WABinary/encode.js +228 -0
  116. package/lib/WABinary/generic-utils.js +240 -0
  117. package/lib/WABinary/index.js +33 -0
  118. package/lib/WABinary/jid-utils.js +361 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +13 -0
  121. package/lib/WAM/constants.js +39486 -0
  122. package/lib/WAM/encode.js +142 -0
  123. package/lib/WAM/index.js +31 -0
  124. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  125. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  128. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  129. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  130. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  131. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  132. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  134. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  135. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  136. package/lib/WAUSync/Protocols/index.js +39 -0
  137. package/lib/WAUSync/USyncQuery.js +133 -0
  138. package/lib/WAUSync/USyncUser.js +50 -0
  139. package/lib/WAUSync/index.js +31 -0
  140. package/lib/antiban.js +4637 -0
  141. package/lib/index.js +45 -0
  142. package/package.json +107 -0
@@ -0,0 +1,490 @@
1
+ 'use strict'
2
+ var __createBinding =
3
+ (this && this.__createBinding) ||
4
+ (Object.create
5
+ ? function (o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k
7
+ var desc = Object.getOwnPropertyDescriptor(m, k)
8
+ if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = {
10
+ enumerable: true,
11
+ get: function () {
12
+ return m[k]
13
+ }
14
+ }
15
+ }
16
+ Object.defineProperty(o, k2, desc)
17
+ }
18
+ : function (o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k
20
+ o[k2] = m[k]
21
+ })
22
+ var __setModuleDefault =
23
+ (this && this.__setModuleDefault) ||
24
+ (Object.create
25
+ ? function (o, v) {
26
+ Object.defineProperty(o, 'default', { enumerable: true, value: v })
27
+ }
28
+ : function (o, v) {
29
+ o['default'] = v
30
+ })
31
+ var __importStar =
32
+ (this && this.__importStar) ||
33
+ (function () {
34
+ var ownKeys = function (o) {
35
+ ownKeys =
36
+ Object.getOwnPropertyNames ||
37
+ function (o) {
38
+ var ar = []
39
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k
40
+ return ar
41
+ }
42
+ return ownKeys(o)
43
+ }
44
+ return function (mod) {
45
+ if (mod && mod.__esModule) return mod
46
+ var result = {}
47
+ if (mod != null)
48
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== 'default') __createBinding(result, mod, k[i])
49
+ __setModuleDefault(result, mod)
50
+ return result
51
+ }
52
+ })()
53
+ Object.defineProperty(exports, '__esModule', { value: true })
54
+ exports.makeLibSignalRepository = makeLibSignalRepository
55
+ const rb = require('../Utils/native-bridge').loadRustBridge()
56
+ const lru_cache_1 = require('lru-cache')
57
+ const Utils_1 = require('../Utils')
58
+ const WABinary_1 = require('../WABinary')
59
+ const sender_key_name_1 = require('./Group/sender-key-name')
60
+ const sender_key_record_1 = require('./Group/sender-key-record')
61
+ const Group_1 = require('./Group')
62
+ const lid_mapping_1 = require('./lid-mapping')
63
+ /** Extract identity key from PreKeyWhisperMessage for identity change detection */
64
+ function extractIdentityFromPkmsg(ciphertext) {
65
+ try {
66
+ if (!ciphertext || ciphertext.length < 2) {
67
+ return undefined
68
+ }
69
+ // Version byte check (version 3)
70
+ const version = ciphertext[0]
71
+ if ((version & 0xf) !== 3) {
72
+ return undefined
73
+ }
74
+ // Parse protobuf (skip version byte)
75
+ const identityKeyArr = rb.getPreKeyMessageIdentityKey(ciphertext)
76
+ if (identityKeyArr) {
77
+ return identityKeyArr
78
+ }
79
+ return undefined
80
+ } catch {
81
+ return undefined
82
+ }
83
+ }
84
+ function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
85
+ if (!rb) {
86
+ throw new Error(
87
+ 'The Signal session (Double Ratchet encryption) requires the "whatsapp-rust-bridge" native ' +
88
+ 'module, which failed to load. Make sure it is installed: npm install whatsapp-rust-bridge@0.5.4'
89
+ )
90
+ }
91
+ const lidMapping = new lid_mapping_1.LIDMappingStore(auth.keys, logger, pnToLIDFunc)
92
+ const storage = signalStorage(auth, lidMapping)
93
+ const parsedKeys = auth.keys
94
+ const migratedSessionCache = new lru_cache_1.LRUCache({
95
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
96
+ ttlAutopurge: true,
97
+ updateAgeOnGet: true
98
+ })
99
+ const repository = {
100
+ decryptGroupMessage({ group, authorJid, msg }) {
101
+ const senderName = jidToSignalSenderKeyName(group, authorJid)
102
+ const cipher = new Group_1.GroupCipher(storage, senderName)
103
+ // Use transaction to ensure atomicity
104
+ return parsedKeys.transaction(async () => {
105
+ return cipher.decrypt(msg)
106
+ }, group)
107
+ },
108
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
109
+ const builder = new Group_1.GroupSessionBuilder(storage)
110
+ if (!item.groupId) {
111
+ throw new Error('Group ID is required for sender key distribution message')
112
+ }
113
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid)
114
+ const senderMsg = new Group_1.SenderKeyDistributionMessage(
115
+ null,
116
+ null,
117
+ null,
118
+ null,
119
+ item.axolotlSenderKeyDistributionMessage
120
+ )
121
+ const senderNameStr = senderName.toString()
122
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
123
+ if (!senderKey) {
124
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord())
125
+ }
126
+ return parsedKeys.transaction(async () => {
127
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
128
+ if (!senderKey) {
129
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord())
130
+ }
131
+ await builder.process(senderName, senderMsg)
132
+ }, item.groupId)
133
+ },
134
+ async decryptMessage({ jid, type, ciphertext }) {
135
+ const addr = jidToSignalProtocolAddress(jid)
136
+ const session = new rb.SessionCipher(storage, addr)
137
+ // Extract and save sender's identity key before decryption for identity change detection
138
+ if (type === 'pkmsg') {
139
+ const identityKey = extractIdentityFromPkmsg(ciphertext)
140
+ if (identityKey) {
141
+ const addrStr = addr.toString()
142
+ const identityChanged = await storage.saveIdentity(addrStr, identityKey)
143
+ if (identityChanged) {
144
+ logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established')
145
+ }
146
+ }
147
+ }
148
+ async function doDecrypt() {
149
+ let result
150
+ switch (type) {
151
+ case 'pkmsg':
152
+ result = await session.decryptPreKeyWhisperMessage(ciphertext)
153
+ break
154
+ case 'msg':
155
+ result = await session.decryptWhisperMessage(ciphertext)
156
+ break
157
+ }
158
+ return result
159
+ }
160
+ // If it's not a sync message, we need to ensure atomicity
161
+ // For regular messages, we use a transaction to ensure atomicity
162
+ return parsedKeys.transaction(async () => {
163
+ return await doDecrypt()
164
+ }, jid)
165
+ },
166
+ async encryptMessage({ jid, data }) {
167
+ const addr = jidToSignalProtocolAddress(jid)
168
+ const cipher = new rb.SessionCipher(storage, addr)
169
+ // Use transaction to ensure atomicity
170
+ return parsedKeys.transaction(async () => {
171
+ const { type: sigType, body } = await cipher.encrypt(data)
172
+ const type = sigType === 3 ? 'pkmsg' : 'msg'
173
+ return { type, ciphertext: Buffer.from(body, 'binary') }
174
+ }, jid)
175
+ },
176
+ async encryptGroupMessage({ group, meId, data }) {
177
+ const senderName = jidToSignalSenderKeyName(group, meId)
178
+ const builder = new Group_1.GroupSessionBuilder(storage)
179
+ const senderNameStr = senderName.toString()
180
+ return parsedKeys.transaction(async () => {
181
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
182
+ if (!senderKey) {
183
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord())
184
+ }
185
+ const senderKeyDistributionMessage = await builder.create(senderName)
186
+ const session = new Group_1.GroupCipher(storage, senderName)
187
+ const ciphertext = await session.encrypt(data)
188
+ return {
189
+ ciphertext,
190
+ senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
191
+ }
192
+ }, group)
193
+ },
194
+ async injectE2ESession({ jid, session }) {
195
+ logger.trace({ jid }, 'injecting E2EE session')
196
+ const cipher = new rb.SessionBuilder(storage, jidToSignalProtocolAddress(jid))
197
+ return parsedKeys.transaction(async () => {
198
+ await cipher.initOutgoing(session)
199
+ }, jid)
200
+ },
201
+ async getSessionInfo(jid) {
202
+ try {
203
+ const addr = jidToSignalProtocolAddress(jid)
204
+ const sessBytes = await storage.loadSession(addr.toString())
205
+ if (!sessBytes) return null
206
+ const session = rb.SessionRecord.deserialize(sessBytes)
207
+ const open = session.getOpenSession?.()
208
+ const baseKey = open?.indexInfo?.baseKey
209
+ const registrationId = open?.registrationId
210
+ if (!baseKey || typeof registrationId !== 'number') return null
211
+ return { baseKey: new Uint8Array(baseKey), registrationId }
212
+ } catch (error) {
213
+ return null
214
+ }
215
+ },
216
+ jidToSignalProtocolAddress(jid) {
217
+ return jidToSignalProtocolAddress(jid).toString()
218
+ },
219
+ // Optimized direct access to LID mapping store
220
+ lidMapping,
221
+ async validateSession(jid) {
222
+ try {
223
+ const addr = jidToSignalProtocolAddress(jid)
224
+ const sessBytes = await storage.loadSession(addr.toString())
225
+ if (!sessBytes) return { exists: false, reason: 'no session' }
226
+ const session = rb.SessionRecord.deserialize(sessBytes)
227
+ if (!session.haveOpenSession()) return { exists: false, reason: 'no open session' }
228
+ return { exists: true }
229
+ } catch (error) {
230
+ return { exists: false, reason: 'validation error' }
231
+ }
232
+ },
233
+ async deleteSession(jids) {
234
+ if (!jids.length) return
235
+ // Convert JIDs to signal addresses and prepare for bulk deletion
236
+ const sessionUpdates = {}
237
+ jids.forEach(jid => {
238
+ const addr = jidToSignalProtocolAddress(jid)
239
+ sessionUpdates[addr.toString()] = null
240
+ })
241
+ // Single transaction for all deletions
242
+ return parsedKeys.transaction(async () => {
243
+ await auth.keys.set({ session: sessionUpdates })
244
+ }, `delete-${jids.length}-sessions`)
245
+ },
246
+ async migrateSession(fromJid, toJid) {
247
+ // TODO: use usync to handle this entire mess
248
+ if (!fromJid || (!(0, WABinary_1.isLidUser)(toJid) && !(0, WABinary_1.isHostedLidUser)(toJid)))
249
+ return { migrated: 0, skipped: 0, total: 0 }
250
+ // Only support PN to LID migration
251
+ if (!(0, WABinary_1.isPnUser)(fromJid) && !(0, WABinary_1.isHostedPnUser)(fromJid)) {
252
+ return { migrated: 0, skipped: 0, total: 1 }
253
+ }
254
+ const { user } = (0, WABinary_1.jidDecode)(fromJid)
255
+ logger.debug({ fromJid }, 'bulk device migration - loading all user devices')
256
+ // Get user's device list from storage
257
+ const { [user]: userDevices } = await parsedKeys.get('device-list', [user])
258
+ if (!userDevices) {
259
+ return { migrated: 0, skipped: 0, total: 0 }
260
+ }
261
+ const { device: fromDevice } = (0, WABinary_1.jidDecode)(fromJid)
262
+ const fromDeviceStr = fromDevice?.toString() || '0'
263
+ if (!userDevices.includes(fromDeviceStr)) {
264
+ userDevices.push(fromDeviceStr)
265
+ }
266
+ // Filter out cached devices before database fetch
267
+ const uncachedDevices = userDevices.filter(device => {
268
+ const deviceKey = `${user}.${device}`
269
+ return !migratedSessionCache.has(deviceKey)
270
+ })
271
+ // Bulk check session existence only for uncached devices
272
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`)
273
+ const existingSessions = await parsedKeys.get('session', deviceSessionKeys)
274
+ // Step 3: Convert existing sessions to JIDs (only migrate sessions that exist)
275
+ const deviceJids = []
276
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
277
+ if (sessionData) {
278
+ // Session exists in storage
279
+ const deviceStr = sessionKey.split('.')[1]
280
+ if (!deviceStr) continue
281
+ const deviceNum = parseInt(deviceStr)
282
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`
283
+ if (deviceNum === 99) {
284
+ jid = `${user}:99@hosted`
285
+ }
286
+ deviceJids.push(jid)
287
+ }
288
+ }
289
+ logger.debug(
290
+ {
291
+ fromJid,
292
+ totalDevices: userDevices.length,
293
+ devicesWithSessions: deviceJids.length,
294
+ devices: deviceJids
295
+ },
296
+ 'bulk device migration complete - all user devices processed'
297
+ )
298
+ // Single transaction for all migrations
299
+ return parsedKeys.transaction(
300
+ async () => {
301
+ const migrationOps = deviceJids.map(jid => {
302
+ const lidWithDevice = (0, WABinary_1.transferDevice)(jid, toJid)
303
+ const fromDecoded = (0, WABinary_1.jidDecode)(jid)
304
+ const toDecoded = (0, WABinary_1.jidDecode)(lidWithDevice)
305
+ return {
306
+ fromJid: jid,
307
+ toJid: lidWithDevice,
308
+ pnUser: fromDecoded.user,
309
+ lidUser: toDecoded.user,
310
+ deviceId: fromDecoded.device || 0,
311
+ fromAddr: jidToSignalProtocolAddress(jid),
312
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
313
+ }
314
+ })
315
+ const totalOps = migrationOps.length
316
+ let migratedCount = 0
317
+ // Bulk fetch PN sessions - already exist (verified during device discovery)
318
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())))
319
+ const pnSessions = await parsedKeys.get('session', pnAddrStrings)
320
+ // Prepare bulk session updates (PN → LID migration + deletion)
321
+ const sessionUpdates = {}
322
+ for (const op of migrationOps) {
323
+ const pnAddrStr = op.fromAddr.toString()
324
+ const lidAddrStr = op.toAddr.toString()
325
+ const pnSession = pnSessions[pnAddrStr]
326
+ if (pnSession) {
327
+ // Session exists (guaranteed from device discovery)
328
+ const fromSession = rb.SessionRecord.deserialize(pnSession)
329
+ if (fromSession.haveOpenSession()) {
330
+ // Queue for bulk update: copy to LID, delete from PN
331
+ sessionUpdates[lidAddrStr] = fromSession.serialize()
332
+ sessionUpdates[pnAddrStr] = null
333
+ migratedCount++
334
+ }
335
+ }
336
+ }
337
+ // Single bulk session update for all migrations
338
+ if (Object.keys(sessionUpdates).length > 0) {
339
+ await parsedKeys.set({ session: sessionUpdates })
340
+ logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete')
341
+ // Cache device-level migrations
342
+ for (const op of migrationOps) {
343
+ if (sessionUpdates[op.toAddr.toString()]) {
344
+ const deviceKey = `${op.pnUser}.${op.deviceId}`
345
+ migratedSessionCache.set(deviceKey, true)
346
+ }
347
+ }
348
+ }
349
+ const skippedCount = totalOps - migratedCount
350
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps }
351
+ },
352
+ `migrate-${deviceJids.length}-sessions-${(0, WABinary_1.jidDecode)(toJid)?.user}`
353
+ )
354
+ }
355
+ }
356
+ return repository
357
+ }
358
+ const jidToSignalProtocolAddress = jid => {
359
+ const decoded = (0, WABinary_1.jidDecode)(jid)
360
+ const { user, device, server, domainType } = decoded
361
+ if (!user) {
362
+ throw new Error(
363
+ `JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`
364
+ )
365
+ }
366
+ const signalUser = domainType !== WABinary_1.WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user
367
+ const finalDevice = device || 0
368
+ if (device === 99 && decoded.server !== 'hosted' && decoded.server !== 'hosted.lid') {
369
+ throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid)
370
+ }
371
+ return new rb.ProtocolAddress(signalUser, finalDevice)
372
+ }
373
+ const jidToSignalSenderKeyName = (group, user) => {
374
+ return new sender_key_name_1.SenderKeyName(group, jidToSignalProtocolAddress(user))
375
+ }
376
+ function signalStorage({ creds, keys }, lidMapping) {
377
+ // Shared function to resolve PN signal address to LID if mapping exists
378
+ const resolveLIDSignalAddress = async id => {
379
+ if (id.includes('.')) {
380
+ const [deviceId, device] = id.split('.')
381
+ const [user, domainType_] = deviceId.split('_')
382
+ const domainType = parseInt(domainType_ || '0')
383
+ if (
384
+ domainType === WABinary_1.WAJIDDomains.LID ||
385
+ domainType === WABinary_1.WAJIDDomains.HOSTED_LID ||
386
+ user.includes('-')
387
+ )
388
+ return id
389
+ const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WABinary_1.WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`
390
+ const lidForPN = await lidMapping.getLIDForPN(pnJid)
391
+ if (lidForPN) {
392
+ const lidAddr = jidToSignalProtocolAddress(lidForPN)
393
+ return lidAddr.toString()
394
+ }
395
+ }
396
+ return id
397
+ }
398
+ return {
399
+ loadSession: async id => {
400
+ try {
401
+ const wireJid = await resolveLIDSignalAddress(id)
402
+ const keysToFetch = wireJid !== id ? [wireJid, id] : [id]
403
+ const fetched = await keys.get('session', keysToFetch)
404
+ const sess = fetched[wireJid] || fetched[id]
405
+ if (!sess) return null
406
+ // Detect old libsignal-node JSON format → treat as no session
407
+ if (typeof sess === 'object' && !Buffer.isBuffer(sess) && !ArrayBuffer.isView(sess) && sess._sessions) {
408
+ return null
409
+ }
410
+ // Return raw bytes — Rust storage adapter expects Uint8Array, not SessionRecord object
411
+ return Buffer.isBuffer(sess) ? sess : Buffer.from(sess)
412
+ } catch (e) {
413
+ return null
414
+ }
415
+ },
416
+ storeSession: async (id, session) => {
417
+ // Store under raw ID so it's always findable regardless of LID mapping state
418
+ await keys.set({ session: { [id]: session.serialize() } })
419
+ },
420
+ isTrustedIdentity: () => {
421
+ return true // TOFU - Trust on First Use (same as WhatsApp Web)
422
+ },
423
+ loadIdentityKey: async id => {
424
+ const wireJid = await resolveLIDSignalAddress(id)
425
+ const { [wireJid]: key } = await keys.get('identity-key', [wireJid])
426
+ return key || undefined
427
+ },
428
+ saveIdentity: async (id, identityKey) => {
429
+ const wireJid = await resolveLIDSignalAddress(id)
430
+ const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid])
431
+ const keysMatch =
432
+ existingKey &&
433
+ existingKey.length === identityKey.length &&
434
+ existingKey.every((byte, i) => byte === identityKey[i])
435
+ if (existingKey && !keysMatch) {
436
+ // Identity changed - clear session and update key
437
+ await keys.set({
438
+ session: { [wireJid]: null },
439
+ 'identity-key': { [wireJid]: identityKey }
440
+ })
441
+ return true
442
+ }
443
+ if (!existingKey) {
444
+ // New contact - Trust on First Use (TOFU)
445
+ await keys.set({ 'identity-key': { [wireJid]: identityKey } })
446
+ return true
447
+ }
448
+ return false
449
+ },
450
+ loadPreKey: async id => {
451
+ const keyId = id.toString()
452
+ const { [keyId]: key } = await keys.get('pre-key', [keyId])
453
+ if (key) {
454
+ return {
455
+ privKey: Buffer.from(key.private),
456
+ pubKey: Buffer.from(key.public)
457
+ }
458
+ }
459
+ },
460
+ removePreKey: id => keys.set({ 'pre-key': { [id]: null } }),
461
+ loadSignedPreKey: () => {
462
+ const key = creds.signedPreKey
463
+ return {
464
+ privKey: Buffer.from(key.keyPair.private),
465
+ pubKey: Buffer.from(key.keyPair.public)
466
+ }
467
+ },
468
+ loadSenderKey: async senderKeyName => {
469
+ const keyId = senderKeyName.toString()
470
+ const { [keyId]: key } = await keys.get('sender-key', [keyId])
471
+ if (key) {
472
+ return sender_key_record_1.SenderKeyRecord.deserialize(key)
473
+ }
474
+ return new sender_key_record_1.SenderKeyRecord()
475
+ },
476
+ storeSenderKey: async (senderKeyName, key) => {
477
+ const keyId = senderKeyName.toString()
478
+ const serialized = JSON.stringify(key.serialize())
479
+ await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } })
480
+ },
481
+ getOurRegistrationId: () => creds.registrationId,
482
+ getOurIdentity: () => {
483
+ const { signedIdentityKey } = creds
484
+ return {
485
+ privKey: Buffer.from(signedIdentityKey.private),
486
+ pubKey: Buffer.from((0, Utils_1.generateSignalPubKey)(signedIdentityKey.public))
487
+ }
488
+ }
489
+ }
490
+ }