@badzz88/baileys 8.5.7 → 8.5.8

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 +747 -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,459 +1,431 @@
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')
1
+ // @ts-ignore
2
+ import * as libsignal from 'libsignal';
3
+ // @ts-ignore
4
+ import { PreKeyWhisperMessage } from 'libsignal/src/protobufs.js';
5
+ import { LRUCache } from 'lru-cache';
6
+ import { generateSignalPubKey } from '../Utils/index.js';
7
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, transferDevice, WAJIDDomains } from '../WABinary/index.js';
8
+ import { SenderKeyName } from './Group/sender-key-name.js';
9
+ import { SenderKeyRecord } from './Group/sender-key-record.js';
10
+ import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } from './Group/index.js';
11
+ import { LIDMappingStore } from './lid-mapping.js';
12
+ /** Extract identity key from PreKeyWhisperMessage for identity change detection */
63
13
  function extractIdentityFromPkmsg(ciphertext) {
64
- try {
65
- if (!ciphertext || ciphertext.length < 2) {
66
- return undefined
67
- }
68
- const version = ciphertext[0]
69
- if ((version & 0xf) !== 3) {
70
- return undefined
71
- }
72
- const identityKeyArr = rb.getPreKeyMessageIdentityKey(ciphertext)
73
- if (identityKeyArr) {
74
- return identityKeyArr
75
- }
76
- return undefined
77
- } catch {
78
- return undefined
79
- }
14
+ try {
15
+ if (!ciphertext || ciphertext.length < 2) {
16
+ return undefined;
17
+ }
18
+ // Version byte check (version 3)
19
+ const version = ciphertext[0];
20
+ if ((version & 0xf) !== 3) {
21
+ return undefined;
22
+ }
23
+ // Parse protobuf (skip version byte)
24
+ const preKeyProto = PreKeyWhisperMessage.decode(ciphertext.slice(1));
25
+ if (preKeyProto.identityKey?.length === 33) {
26
+ return new Uint8Array(preKeyProto.identityKey);
27
+ }
28
+ return undefined;
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
80
33
  }
81
- function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
82
- if (!rb) {
83
- throw new Error(
84
- 'The Signal session (Double Ratchet encryption) requires the "whatsapp-rust-bridge" native ' +
85
- 'module, which failed to load. Make sure it is installed: npm install whatsapp-rust-bridge@0.5.4'
86
- )
87
- }
88
- const lidMapping = new lid_mapping_1.LIDMappingStore(auth.keys, logger, pnToLIDFunc)
89
- const storage = signalStorage(auth, lidMapping)
90
- const parsedKeys = auth.keys
91
- const migratedSessionCache = new lru_cache_1.LRUCache({
92
- ttl: 3 * 24 * 60 * 60 * 1000,
93
- ttlAutopurge: true,
94
- updateAgeOnGet: true
95
- })
96
- const repository = {
97
- decryptGroupMessage({ group, authorJid, msg }) {
98
- const senderName = jidToSignalSenderKeyName(group, authorJid)
99
- const cipher = new Group_1.GroupCipher(storage, senderName)
100
- return parsedKeys.transaction(async () => {
101
- return cipher.decrypt(msg)
102
- }, group)
103
- },
104
- async processSenderKeyDistributionMessage({ item, authorJid }) {
105
- const builder = new Group_1.GroupSessionBuilder(storage)
106
- if (!item.groupId) {
107
- throw new Error('Group ID is required for sender key distribution message')
108
- }
109
- const senderName = jidToSignalSenderKeyName(item.groupId, authorJid)
110
- const senderMsg = new Group_1.SenderKeyDistributionMessage(
111
- null,
112
- null,
113
- null,
114
- null,
115
- item.axolotlSenderKeyDistributionMessage
116
- )
117
- const senderNameStr = senderName.toString()
118
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
119
- if (!senderKey) {
120
- await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord())
121
- }
122
- return parsedKeys.transaction(async () => {
123
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
124
- if (!senderKey) {
125
- await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord())
126
- }
127
- await builder.process(senderName, senderMsg)
128
- }, item.groupId)
129
- },
130
- async decryptMessage({ jid, type, ciphertext }) {
131
- const addr = jidToSignalProtocolAddress(jid)
132
- const session = new rb.SessionCipher(storage, addr)
133
- if (type === 'pkmsg') {
134
- const identityKey = extractIdentityFromPkmsg(ciphertext)
135
- if (identityKey) {
136
- const addrStr = addr.toString()
137
- const identityChanged = await storage.saveIdentity(addrStr, identityKey)
138
- if (identityChanged) {
139
- logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established')
140
- }
141
- }
142
- }
143
- async function doDecrypt() {
144
- let result
145
- switch (type) {
146
- case 'pkmsg':
147
- result = await session.decryptPreKeyWhisperMessage(ciphertext)
148
- break
149
- case 'msg':
150
- result = await session.decryptWhisperMessage(ciphertext)
151
- break
152
- }
153
- return result
154
- }
155
- return parsedKeys.transaction(async () => {
156
- return await doDecrypt()
157
- }, jid)
158
- },
159
- async encryptMessage({ jid, data }) {
160
- const addr = jidToSignalProtocolAddress(jid)
161
- const cipher = new rb.SessionCipher(storage, addr)
162
- return parsedKeys.transaction(async () => {
163
- const { type: sigType, body } = await cipher.encrypt(data)
164
- const type = sigType === 3 ? 'pkmsg' : 'msg'
165
- return { type, ciphertext: Buffer.from(body, 'binary') }
166
- }, jid)
167
- },
168
- async encryptGroupMessage({ group, meId, data }) {
169
- const senderName = jidToSignalSenderKeyName(group, meId)
170
- const builder = new Group_1.GroupSessionBuilder(storage)
171
- const senderNameStr = senderName.toString()
172
- return parsedKeys.transaction(async () => {
173
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
174
- if (!senderKey) {
175
- await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord())
176
- }
177
- const senderKeyDistributionMessage = await builder.create(senderName)
178
- const session = new Group_1.GroupCipher(storage, senderName)
179
- const ciphertext = await session.encrypt(data)
180
- return {
181
- ciphertext,
182
- senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
183
- }
184
- }, group)
185
- },
186
- async injectE2ESession({ jid, session }) {
187
- logger.trace({ jid }, 'injecting E2EE session')
188
- const cipher = new rb.SessionBuilder(storage, jidToSignalProtocolAddress(jid))
189
- return parsedKeys.transaction(async () => {
190
- await cipher.initOutgoing(session)
191
- }, jid)
192
- },
193
- async getSessionInfo(jid) {
194
- try {
195
- const addr = jidToSignalProtocolAddress(jid)
196
- const sessBytes = await storage.loadSession(addr.toString())
197
- if (!sessBytes) return null
198
- const session = rb.SessionRecord.deserialize(sessBytes)
199
- const open = session.getOpenSession?.()
200
- const baseKey = open?.indexInfo?.baseKey
201
- const registrationId = open?.registrationId
202
- if (!baseKey || typeof registrationId !== 'number') return null
203
- return { baseKey: new Uint8Array(baseKey), registrationId }
204
- } catch (error) {
205
- return null
206
- }
207
- },
208
- jidToSignalProtocolAddress(jid) {
209
- return jidToSignalProtocolAddress(jid).toString()
210
- },
211
- lidMapping,
212
- async validateSession(jid) {
213
- try {
214
- const addr = jidToSignalProtocolAddress(jid)
215
- const sessBytes = await storage.loadSession(addr.toString())
216
- if (!sessBytes) return { exists: false, reason: 'no session' }
217
- const session = rb.SessionRecord.deserialize(sessBytes)
218
- if (!session.haveOpenSession()) return { exists: false, reason: 'no open session' }
219
- return { exists: true }
220
- } catch (error) {
221
- return { exists: false, reason: 'validation error' }
222
- }
223
- },
224
- async deleteSession(jids) {
225
- if (!jids.length) return
226
- const sessionUpdates = {}
227
- jids.forEach(jid => {
228
- const addr = jidToSignalProtocolAddress(jid)
229
- sessionUpdates[addr.toString()] = null
230
- })
231
- return parsedKeys.transaction(async () => {
232
- await auth.keys.set({ session: sessionUpdates })
233
- }, `delete-${jids.length}-sessions`)
234
- },
235
- async migrateSession(fromJid, toJid) {
236
- if (!fromJid || (!(0, WABinary_1.isLidUser)(toJid) && !(0, WABinary_1.isHostedLidUser)(toJid)))
237
- return { migrated: 0, skipped: 0, total: 0 }
238
- if (!(0, WABinary_1.isPnUser)(fromJid) && !(0, WABinary_1.isHostedPnUser)(fromJid)) {
239
- return { migrated: 0, skipped: 0, total: 1 }
240
- }
241
- const { user } = (0, WABinary_1.jidDecode)(fromJid)
242
- logger.debug({ fromJid }, 'bulk device migration - loading all user devices')
243
- const { [user]: userDevices } = await parsedKeys.get('device-list', [user])
244
- if (!userDevices) {
245
- return { migrated: 0, skipped: 0, total: 0 }
246
- }
247
- const { device: fromDevice } = (0, WABinary_1.jidDecode)(fromJid)
248
- const fromDeviceStr = fromDevice?.toString() || '0'
249
- if (!userDevices.includes(fromDeviceStr)) {
250
- userDevices.push(fromDeviceStr)
251
- }
252
- const uncachedDevices = userDevices.filter(device => {
253
- const deviceKey = `${user}.${device}`
254
- return !migratedSessionCache.has(deviceKey)
255
- })
256
- const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`)
257
- const existingSessions = await parsedKeys.get('session', deviceSessionKeys)
258
- const deviceJids = []
259
- for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
260
- if (sessionData) {
261
- const deviceStr = sessionKey.split('.')[1]
262
- if (!deviceStr) continue
263
- const deviceNum = parseInt(deviceStr)
264
- let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`
265
- if (deviceNum === 99) {
266
- jid = `${user}:99@hosted`
267
- }
268
- deviceJids.push(jid)
269
- }
270
- }
271
- logger.debug(
272
- {
273
- fromJid,
274
- totalDevices: userDevices.length,
275
- devicesWithSessions: deviceJids.length,
276
- devices: deviceJids
277
- },
278
- 'bulk device migration complete - all user devices processed'
279
- )
280
- return parsedKeys.transaction(
281
- async () => {
282
- const migrationOps = deviceJids.map(jid => {
283
- const lidWithDevice = (0, WABinary_1.transferDevice)(jid, toJid)
284
- const fromDecoded = (0, WABinary_1.jidDecode)(jid)
285
- const toDecoded = (0, WABinary_1.jidDecode)(lidWithDevice)
286
- return {
287
- fromJid: jid,
288
- toJid: lidWithDevice,
289
- pnUser: fromDecoded.user,
290
- lidUser: toDecoded.user,
291
- deviceId: fromDecoded.device || 0,
292
- fromAddr: jidToSignalProtocolAddress(jid),
293
- toAddr: jidToSignalProtocolAddress(lidWithDevice)
294
- }
295
- })
296
- const totalOps = migrationOps.length
297
- let migratedCount = 0
298
- const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())))
299
- const pnSessions = await parsedKeys.get('session', pnAddrStrings)
300
- const sessionUpdates = {}
301
- for (const op of migrationOps) {
302
- const pnAddrStr = op.fromAddr.toString()
303
- const lidAddrStr = op.toAddr.toString()
304
- const pnSession = pnSessions[pnAddrStr]
305
- if (pnSession) {
306
- const fromSession = rb.SessionRecord.deserialize(pnSession)
307
- if (fromSession.haveOpenSession()) {
308
- sessionUpdates[lidAddrStr] = fromSession.serialize()
309
- sessionUpdates[pnAddrStr] = null
310
- migratedCount++
311
- }
312
- }
313
- }
314
- if (Object.keys(sessionUpdates).length > 0) {
315
- await parsedKeys.set({ session: sessionUpdates })
316
- logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete')
317
- for (const op of migrationOps) {
318
- if (sessionUpdates[op.toAddr.toString()]) {
319
- const deviceKey = `${op.pnUser}.${op.deviceId}`
320
- migratedSessionCache.set(deviceKey, true)
321
- }
322
- }
323
- }
324
- const skippedCount = totalOps - migratedCount
325
- return { migrated: migratedCount, skipped: skippedCount, total: totalOps }
326
- },
327
- `migrate-${deviceJids.length}-sessions-${(0, WABinary_1.jidDecode)(toJid)?.user}`
328
- )
329
- }
330
- }
331
- return repository
332
- }
333
- const jidToSignalProtocolAddress = jid => {
334
- const decoded = (0, WABinary_1.jidDecode)(jid)
335
- const { user, device, server, domainType } = decoded
336
- if (!user) {
337
- throw new Error(
338
- `JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`
339
- )
340
- }
341
- const signalUser = domainType !== WABinary_1.WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user
342
- const finalDevice = device || 0
343
- if (device === 99 && decoded.server !== 'hosted' && decoded.server !== 'hosted.lid') {
344
- throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid)
345
- }
346
- return new rb.ProtocolAddress(signalUser, finalDevice)
34
+ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
35
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
36
+ const storage = signalStorage(auth, lidMapping);
37
+ const parsedKeys = auth.keys;
38
+ const migratedSessionCache = new LRUCache({
39
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
40
+ ttlAutopurge: true,
41
+ updateAgeOnGet: true
42
+ });
43
+ const ensureSenderKeyAndCreateSkdm = async (group, meId) => {
44
+ const senderName = jidToSignalSenderKeyName(group, meId);
45
+ const senderNameStr = senderName.toString();
46
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
47
+ if (!senderKey) {
48
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
49
+ }
50
+ const skdm = await new GroupSessionBuilder(storage).create(senderName);
51
+ return { senderName, skdm };
52
+ };
53
+ const repository = {
54
+ decryptGroupMessage({ group, authorJid, msg }) {
55
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
56
+ const cipher = new GroupCipher(storage, senderName);
57
+ // Use transaction to ensure atomicity
58
+ return parsedKeys.transaction(async () => {
59
+ return cipher.decrypt(msg);
60
+ }, group);
61
+ },
62
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
63
+ const builder = new GroupSessionBuilder(storage);
64
+ if (!item.groupId) {
65
+ throw new Error('Group ID is required for sender key distribution message');
66
+ }
67
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
68
+ const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
69
+ const senderNameStr = senderName.toString();
70
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
71
+ if (!senderKey) {
72
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
73
+ }
74
+ return parsedKeys.transaction(async () => {
75
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
76
+ if (!senderKey) {
77
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
78
+ }
79
+ await builder.process(senderName, senderMsg);
80
+ }, item.groupId);
81
+ },
82
+ async decryptMessage({ jid, type, ciphertext }) {
83
+ const addr = jidToSignalProtocolAddress(jid);
84
+ const session = new libsignal.SessionCipher(storage, addr);
85
+ // Extract and save sender's identity key before decryption for identity change detection
86
+ if (type === 'pkmsg') {
87
+ const identityKey = extractIdentityFromPkmsg(ciphertext);
88
+ if (identityKey) {
89
+ const addrStr = addr.toString();
90
+ const identityChanged = await storage.saveIdentity(addrStr, identityKey);
91
+ if (identityChanged) {
92
+ logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established');
93
+ }
94
+ }
95
+ }
96
+ async function doDecrypt() {
97
+ let result;
98
+ switch (type) {
99
+ case 'pkmsg':
100
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
101
+ break;
102
+ case 'msg':
103
+ result = await session.decryptWhisperMessage(ciphertext);
104
+ break;
105
+ }
106
+ return result;
107
+ }
108
+ // If it's not a sync message, we need to ensure atomicity
109
+ // For regular messages, we use a transaction to ensure atomicity
110
+ return parsedKeys.transaction(async () => {
111
+ return await doDecrypt();
112
+ }, jid);
113
+ },
114
+ async encryptMessage({ jid, data }) {
115
+ const addr = jidToSignalProtocolAddress(jid);
116
+ const cipher = new libsignal.SessionCipher(storage, addr);
117
+ // Use transaction to ensure atomicity
118
+ return parsedKeys.transaction(async () => {
119
+ const { type: sigType, body } = await cipher.encrypt(data);
120
+ const type = sigType === 3 ? 'pkmsg' : 'msg';
121
+ return { type, ciphertext: Buffer.from(body, 'binary') };
122
+ }, jid);
123
+ },
124
+ async encryptGroupMessage({ group, meId, data }) {
125
+ return parsedKeys.transaction(async () => {
126
+ const { senderName, skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
127
+ const ciphertext = await new GroupCipher(storage, senderName).encrypt(data);
128
+ return { ciphertext, senderKeyDistributionMessage: skdm.serialize() };
129
+ }, group);
130
+ },
131
+ async getSenderKeyDistributionMessage({ group, meId }) {
132
+ return parsedKeys.transaction(async () => {
133
+ const { skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
134
+ return skdm.serialize();
135
+ }, group);
136
+ },
137
+ async hasSenderKey({ group, meId }) {
138
+ const senderName = jidToSignalSenderKeyName(group, meId).toString();
139
+ const { [senderName]: key } = await auth.keys.get('sender-key', [senderName]);
140
+ return !!key;
141
+ },
142
+ async getSessionInfo(jid) {
143
+ const addr = jidToSignalProtocolAddress(jid).toString();
144
+ const session = (await storage.loadSession(addr));
145
+ if (!session) {
146
+ return null;
147
+ }
148
+ const open = session.getOpenSession?.();
149
+ const baseKey = open?.indexInfo?.baseKey;
150
+ const registrationId = open?.registrationId;
151
+ if (!baseKey || typeof registrationId !== 'number') {
152
+ return null;
153
+ }
154
+ return { baseKey: new Uint8Array(baseKey), registrationId };
155
+ },
156
+ async injectE2ESession({ jid, session }) {
157
+ logger.trace({ jid }, 'injecting E2EE session');
158
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
159
+ return parsedKeys.transaction(async () => {
160
+ // libsignal runtime accepts an absent prekey (initOutgoing checks `device.preKey && ...`)
161
+ // but the bundled .d.ts marks it required.
162
+ await cipher.initOutgoing(session);
163
+ }, jid);
164
+ },
165
+ jidToSignalProtocolAddress(jid) {
166
+ return jidToSignalProtocolAddress(jid).toString();
167
+ },
168
+ // Optimized direct access to LID mapping store
169
+ lidMapping,
170
+ async validateSession(jid) {
171
+ try {
172
+ const addr = jidToSignalProtocolAddress(jid);
173
+ const session = await storage.loadSession(addr.toString());
174
+ if (!session) {
175
+ return { exists: false, reason: 'no session' };
176
+ }
177
+ if (!session.haveOpenSession()) {
178
+ return { exists: false, reason: 'no open session' };
179
+ }
180
+ return { exists: true };
181
+ }
182
+ catch (error) {
183
+ return { exists: false, reason: 'validation error' };
184
+ }
185
+ },
186
+ async deleteSession(jids) {
187
+ if (!jids.length)
188
+ return;
189
+ // Convert JIDs to signal addresses and prepare for bulk deletion
190
+ const sessionUpdates = {};
191
+ jids.forEach(jid => {
192
+ const addr = jidToSignalProtocolAddress(jid);
193
+ sessionUpdates[addr.toString()] = null;
194
+ });
195
+ // Single transaction for all deletions
196
+ return parsedKeys.transaction(async () => {
197
+ await auth.keys.set({ session: sessionUpdates });
198
+ }, `delete-${jids.length}-sessions`);
199
+ },
200
+ close() {
201
+ migratedSessionCache.clear();
202
+ lidMapping.close();
203
+ },
204
+ async migrateSession(fromJid, toJid) {
205
+ // TODO: use usync to handle this entire mess
206
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
207
+ return { migrated: 0, skipped: 0, total: 0 };
208
+ // Only support PN to LID migration
209
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
210
+ return { migrated: 0, skipped: 0, total: 1 };
211
+ }
212
+ const { user } = jidDecode(fromJid);
213
+ logger.debug({ fromJid }, 'bulk device migration - loading all user devices');
214
+ // Get user's device list from storage
215
+ const { [user]: userDevices } = await parsedKeys.get('device-list', [user]);
216
+ if (!userDevices) {
217
+ return { migrated: 0, skipped: 0, total: 0 };
218
+ }
219
+ const { device: fromDevice } = jidDecode(fromJid);
220
+ const fromDeviceStr = fromDevice?.toString() || '0';
221
+ if (!userDevices.includes(fromDeviceStr)) {
222
+ userDevices.push(fromDeviceStr);
223
+ }
224
+ // Filter out cached devices before database fetch
225
+ const uncachedDevices = userDevices.filter(device => {
226
+ const deviceKey = `${user}.${device}`;
227
+ return !migratedSessionCache.has(deviceKey);
228
+ });
229
+ // Bulk check session existence only for uncached devices
230
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
231
+ const existingSessions = await parsedKeys.get('session', deviceSessionKeys);
232
+ // Step 3: Convert existing sessions to JIDs (only migrate sessions that exist)
233
+ const deviceJids = [];
234
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
235
+ if (sessionData) {
236
+ // Session exists in storage
237
+ const deviceStr = sessionKey.split('.')[1];
238
+ if (!deviceStr)
239
+ continue;
240
+ const deviceNum = parseInt(deviceStr);
241
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
242
+ if (deviceNum === 99) {
243
+ jid = `${user}:99@hosted`;
244
+ }
245
+ deviceJids.push(jid);
246
+ }
247
+ }
248
+ logger.debug({
249
+ fromJid,
250
+ totalDevices: userDevices.length,
251
+ devicesWithSessions: deviceJids.length,
252
+ devices: deviceJids
253
+ }, 'bulk device migration complete - all user devices processed');
254
+ // Single transaction for all migrations
255
+ return parsedKeys.transaction(async () => {
256
+ const migrationOps = deviceJids.map(jid => {
257
+ const lidWithDevice = transferDevice(jid, toJid);
258
+ const fromDecoded = jidDecode(jid);
259
+ const toDecoded = jidDecode(lidWithDevice);
260
+ return {
261
+ fromJid: jid,
262
+ toJid: lidWithDevice,
263
+ pnUser: fromDecoded.user,
264
+ lidUser: toDecoded.user,
265
+ deviceId: fromDecoded.device || 0,
266
+ fromAddr: jidToSignalProtocolAddress(jid),
267
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
268
+ };
269
+ });
270
+ const totalOps = migrationOps.length;
271
+ let migratedCount = 0;
272
+ // Bulk fetch PN sessions - already exist (verified during device discovery)
273
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
274
+ const pnSessions = await parsedKeys.get('session', pnAddrStrings);
275
+ // Prepare bulk session updates (PN → LID migration + deletion)
276
+ const sessionUpdates = {};
277
+ for (const op of migrationOps) {
278
+ const pnAddrStr = op.fromAddr.toString();
279
+ const lidAddrStr = op.toAddr.toString();
280
+ const pnSession = pnSessions[pnAddrStr];
281
+ if (pnSession) {
282
+ // Session exists (guaranteed from device discovery)
283
+ const fromSession = libsignal.SessionRecord.deserialize(pnSession);
284
+ if (fromSession.haveOpenSession()) {
285
+ // Queue for bulk update: copy to LID, delete from PN
286
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
287
+ sessionUpdates[pnAddrStr] = null;
288
+ migratedCount++;
289
+ }
290
+ }
291
+ }
292
+ // Single bulk session update for all migrations
293
+ if (Object.keys(sessionUpdates).length > 0) {
294
+ await parsedKeys.set({ session: sessionUpdates });
295
+ logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete');
296
+ // Cache device-level migrations
297
+ for (const op of migrationOps) {
298
+ if (sessionUpdates[op.toAddr.toString()]) {
299
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
300
+ migratedSessionCache.set(deviceKey, true);
301
+ }
302
+ }
303
+ }
304
+ const skippedCount = totalOps - migratedCount;
305
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
306
+ }, `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`);
307
+ }
308
+ };
309
+ return repository;
347
310
  }
311
+ const jidToSignalProtocolAddress = (jid) => {
312
+ const decoded = jidDecode(jid);
313
+ const { user, device, server, domainType } = decoded;
314
+ if (!user) {
315
+ throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
316
+ }
317
+ const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
318
+ const finalDevice = device || 0;
319
+ if (device === 99 && decoded.server !== 'hosted' && decoded.server !== 'hosted.lid') {
320
+ throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid);
321
+ }
322
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
323
+ };
348
324
  const jidToSignalSenderKeyName = (group, user) => {
349
- return new sender_key_name_1.SenderKeyName(group, jidToSignalProtocolAddress(user))
350
- }
325
+ return new SenderKeyName(group, jidToSignalProtocolAddress(user));
326
+ };
351
327
  function signalStorage({ creds, keys }, lidMapping) {
352
- const resolveLIDSignalAddress = async id => {
353
- if (id.includes('.')) {
354
- const [deviceId, device] = id.split('.')
355
- const [user, domainType_] = deviceId.split('_')
356
- const domainType = parseInt(domainType_ || '0')
357
- if (
358
- domainType === WABinary_1.WAJIDDomains.LID ||
359
- domainType === WABinary_1.WAJIDDomains.HOSTED_LID ||
360
- user.includes('-')
361
- )
362
- return id
363
- const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WABinary_1.WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`
364
- const lidForPN = await lidMapping.getLIDForPN(pnJid)
365
- if (lidForPN) {
366
- const lidAddr = jidToSignalProtocolAddress(lidForPN)
367
- return lidAddr.toString()
368
- }
369
- }
370
- return id
371
- }
372
- return {
373
- loadSession: async id => {
374
- try {
375
- const wireJid = await resolveLIDSignalAddress(id)
376
- const keysToFetch = wireJid !== id ? [wireJid, id] : [id]
377
- const fetched = await keys.get('session', keysToFetch)
378
- const sess = fetched[wireJid] || fetched[id]
379
- if (!sess) return null
380
- if (typeof sess === 'object' && !Buffer.isBuffer(sess) && !ArrayBuffer.isView(sess) && sess._sessions) {
381
- return null
382
- }
383
- return Buffer.isBuffer(sess) ? sess : Buffer.from(sess)
384
- } catch (e) {
385
- return null
386
- }
387
- },
388
- storeSession: async (id, session) => {
389
- await keys.set({ session: { [id]: session.serialize() } })
390
- },
391
- isTrustedIdentity: () => {
392
- return true
393
- },
394
- loadIdentityKey: async id => {
395
- const wireJid = await resolveLIDSignalAddress(id)
396
- const { [wireJid]: key } = await keys.get('identity-key', [wireJid])
397
- return key || undefined
398
- },
399
- saveIdentity: async (id, identityKey) => {
400
- const wireJid = await resolveLIDSignalAddress(id)
401
- const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid])
402
- const keysMatch =
403
- existingKey &&
404
- existingKey.length === identityKey.length &&
405
- existingKey.every((byte, i) => byte === identityKey[i])
406
- if (existingKey && !keysMatch) {
407
- await keys.set({
408
- session: { [wireJid]: null },
409
- 'identity-key': { [wireJid]: identityKey }
410
- })
411
- return true
412
- }
413
- if (!existingKey) {
414
- await keys.set({ 'identity-key': { [wireJid]: identityKey } })
415
- return true
416
- }
417
- return false
418
- },
419
- loadPreKey: async id => {
420
- const keyId = id.toString()
421
- const { [keyId]: key } = await keys.get('pre-key', [keyId])
422
- if (key) {
423
- return {
424
- privKey: Buffer.from(key.private),
425
- pubKey: Buffer.from(key.public)
426
- }
427
- }
428
- },
429
- removePreKey: id => keys.set({ 'pre-key': { [id]: null } }),
430
- loadSignedPreKey: () => {
431
- const key = creds.signedPreKey
432
- return {
433
- privKey: Buffer.from(key.keyPair.private),
434
- pubKey: Buffer.from(key.keyPair.public)
435
- }
436
- },
437
- loadSenderKey: async senderKeyName => {
438
- const keyId = senderKeyName.toString()
439
- const { [keyId]: key } = await keys.get('sender-key', [keyId])
440
- if (key) {
441
- return sender_key_record_1.SenderKeyRecord.deserialize(key)
442
- }
443
- return new sender_key_record_1.SenderKeyRecord()
444
- },
445
- storeSenderKey: async (senderKeyName, key) => {
446
- const keyId = senderKeyName.toString()
447
- const serialized = JSON.stringify(key.serialize())
448
- await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } })
449
- },
450
- getOurRegistrationId: () => creds.registrationId,
451
- getOurIdentity: () => {
452
- const { signedIdentityKey } = creds
453
- return {
454
- privKey: Buffer.from(signedIdentityKey.private),
455
- pubKey: Buffer.from((0, Utils_1.generateSignalPubKey)(signedIdentityKey.public))
456
- }
457
- }
458
- }
328
+ // Shared function to resolve PN signal address to LID if mapping exists
329
+ const resolveLIDSignalAddress = async (id) => {
330
+ if (id.includes('.')) {
331
+ const [deviceId, device] = id.split('.');
332
+ const [user, domainType_] = deviceId.split('_');
333
+ const domainType = parseInt(domainType_ || '0');
334
+ if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID)
335
+ return id;
336
+ const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`;
337
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
338
+ if (lidForPN) {
339
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
340
+ return lidAddr.toString();
341
+ }
342
+ }
343
+ return id;
344
+ };
345
+ return {
346
+ loadSession: async (id) => {
347
+ try {
348
+ const wireJid = await resolveLIDSignalAddress(id);
349
+ const { [wireJid]: sess } = await keys.get('session', [wireJid]);
350
+ if (sess) {
351
+ return libsignal.SessionRecord.deserialize(sess);
352
+ }
353
+ }
354
+ catch (e) {
355
+ return null;
356
+ }
357
+ return null;
358
+ },
359
+ storeSession: async (id, session) => {
360
+ const wireJid = await resolveLIDSignalAddress(id);
361
+ await keys.set({ session: { [wireJid]: session.serialize() } });
362
+ },
363
+ isTrustedIdentity: () => {
364
+ return true; // TOFU - Trust on First Use (same as WhatsApp Web)
365
+ },
366
+ loadIdentityKey: async (id) => {
367
+ const wireJid = await resolveLIDSignalAddress(id);
368
+ const { [wireJid]: key } = await keys.get('identity-key', [wireJid]);
369
+ return key || undefined;
370
+ },
371
+ saveIdentity: async (id, identityKey) => {
372
+ const wireJid = await resolveLIDSignalAddress(id);
373
+ const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid]);
374
+ const keysMatch = existingKey?.length === identityKey.length && existingKey.every((byte, i) => byte === identityKey[i]);
375
+ if (existingKey && !keysMatch) {
376
+ // Identity changed - clear session and update key
377
+ await keys.set({
378
+ session: { [wireJid]: null },
379
+ 'identity-key': { [wireJid]: identityKey }
380
+ });
381
+ return true;
382
+ }
383
+ if (!existingKey) {
384
+ // New contact - Trust on First Use (TOFU)
385
+ await keys.set({ 'identity-key': { [wireJid]: identityKey } });
386
+ return true;
387
+ }
388
+ return false;
389
+ },
390
+ loadPreKey: async (id) => {
391
+ const keyId = id.toString();
392
+ const { [keyId]: key } = await keys.get('pre-key', [keyId]);
393
+ if (key) {
394
+ return {
395
+ privKey: Buffer.from(key.private),
396
+ pubKey: Buffer.from(key.public)
397
+ };
398
+ }
399
+ },
400
+ removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
401
+ loadSignedPreKey: () => {
402
+ const key = creds.signedPreKey;
403
+ return {
404
+ privKey: Buffer.from(key.keyPair.private),
405
+ pubKey: Buffer.from(key.keyPair.public)
406
+ };
407
+ },
408
+ loadSenderKey: async (senderKeyName) => {
409
+ const keyId = senderKeyName.toString();
410
+ const { [keyId]: key } = await keys.get('sender-key', [keyId]);
411
+ if (key) {
412
+ return SenderKeyRecord.deserialize(key);
413
+ }
414
+ return new SenderKeyRecord();
415
+ },
416
+ storeSenderKey: async (senderKeyName, key) => {
417
+ const keyId = senderKeyName.toString();
418
+ const serialized = JSON.stringify(key.serialize());
419
+ await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } });
420
+ },
421
+ getOurRegistrationId: () => creds.registrationId,
422
+ getOurIdentity: () => {
423
+ const { signedIdentityKey } = creds;
424
+ return {
425
+ privKey: Buffer.from(signedIdentityKey.private),
426
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
427
+ };
428
+ }
429
+ };
459
430
  }
431
+ //# sourceMappingURL=libsignal.js.map