@itznomo/baileys 0.0.0-stage → 0.0.3

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 (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,635 @@
1
+ import * as libsignal from './libsignal.js'
2
+ import { PreKeyWhisperMessage } from './libsignal.js'
3
+ import { Cache } from '../foundation/cache.js'
4
+ import { generateSignalPubKey } from '../utils/wa-protocol-core.js'
5
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, transferDevice, WAJIDDomains } from '../binary/wa-binary.js'
6
+ import { SenderKeyName, SenderKeyRecord, GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } from './signal-group.js'
7
+
8
+ export class LIDMappingStore {
9
+ constructor(keys, logger, pnToLIDFunc) {
10
+ this.mappingCache = new Cache({ ttl: 3 * 24 * 60 * 60 * 1000, max: 5000, updateAgeOnGet: true })
11
+ this.inflightLIDLookups = new Map()
12
+ this.inflightPNLookups = new Map()
13
+ this.keys = keys
14
+ this.pnToLIDFunc = pnToLIDFunc
15
+ this.logger = logger
16
+ }
17
+
18
+ async storeLIDPNMappings(pairs) {
19
+ if (pairs.length === 0) return
20
+ const validatedPairs = []
21
+ for (const { lid, pn } of pairs) {
22
+ if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
23
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`)
24
+ continue
25
+ }
26
+ const lidDecoded = jidDecode(lid)
27
+ const pnDecoded = jidDecode(pn)
28
+ if (!lidDecoded || !pnDecoded) continue
29
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user })
30
+ }
31
+ if (validatedPairs.length === 0) return
32
+
33
+ const cacheMissSet = new Set()
34
+ const existingMappings = new Map()
35
+ for (const { pnUser } of validatedPairs) {
36
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
37
+ if (cached) existingMappings.set(pnUser, cached)
38
+ else cacheMissSet.add(pnUser)
39
+ }
40
+
41
+ if (cacheMissSet.size > 0) {
42
+ const cacheMisses = [...cacheMissSet]
43
+ this.logger.trace(`Batch fetching ${cacheMisses.length} LID mappings from database`)
44
+ const stored = await this.keys.get('lid-mapping', cacheMisses)
45
+ for (const pnUser of cacheMisses) {
46
+ const existingLidUser = stored[pnUser]
47
+ if (existingLidUser) {
48
+ existingMappings.set(pnUser, existingLidUser)
49
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser)
50
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser)
51
+ }
52
+ }
53
+ }
54
+
55
+ const pairMap = {}
56
+ for (const { pnUser, lidUser } of validatedPairs) {
57
+ const existingLidUser = existingMappings.get(pnUser)
58
+ if (existingLidUser === lidUser) {
59
+ this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping')
60
+ continue
61
+ }
62
+ pairMap[pnUser] = lidUser
63
+ }
64
+ if (Object.keys(pairMap).length === 0) return
65
+
66
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`)
67
+ const batchData = {}
68
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
69
+ batchData[pnUser] = lidUser
70
+ batchData[`${lidUser}_reverse`] = pnUser
71
+ }
72
+ await this.keys.transaction(async () => {
73
+ await this.keys.set({ 'lid-mapping': batchData })
74
+ }, 'lid-mapping')
75
+
76
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
77
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
78
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
79
+ }
80
+ }
81
+
82
+ async getLIDForPN(pn) {
83
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null
84
+ }
85
+
86
+ async getLIDsForPNs(pns) {
87
+ if (pns.length === 0) return null
88
+ const sortedPns = [...new Set(pns)].sort()
89
+ const cacheKey = sortedPns.join(',')
90
+ const inflight = this.inflightLIDLookups.get(cacheKey)
91
+ if (inflight) {
92
+ this.logger.trace(`Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`)
93
+ return inflight
94
+ }
95
+ const promise = this._getLIDsForPNsImpl(pns)
96
+ this.inflightLIDLookups.set(cacheKey, promise)
97
+ try {
98
+ return await promise
99
+ } finally {
100
+ this.inflightLIDLookups.delete(cacheKey)
101
+ }
102
+ }
103
+
104
+ async _getLIDsForPNsImpl(pns) {
105
+ const usyncFetch = {}
106
+ const successfulPairs = {}
107
+ const pending = []
108
+
109
+ const addResolvedPair = (pn, decoded, lidUser) => {
110
+ const normalizedLidUser = lidUser.toString()
111
+ if (!normalizedLidUser) {
112
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`)
113
+ return false
114
+ }
115
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0
116
+ const deviceSpecificLid = `${normalizedLidUser}${pnDevice ? `:${pnDevice}` : ''}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`
117
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`)
118
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn }
119
+ return true
120
+ }
121
+
122
+ for (const pn of pns) {
123
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) continue
124
+ const decoded = jidDecode(pn)
125
+ if (!decoded) continue
126
+ const pnUser = decoded.user
127
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
128
+ if (cached && typeof cached === 'string') {
129
+ if (!addResolvedPair(pn, decoded, cached)) {
130
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`)
131
+ continue
132
+ }
133
+ continue
134
+ }
135
+ pending.push({ pn, pnUser, decoded })
136
+ }
137
+
138
+ if (pending.length) {
139
+ const pnUsers = [...new Set(pending.map(item => item.pnUser))]
140
+ const stored = await this.keys.get('lid-mapping', pnUsers)
141
+ for (const pnUser of pnUsers) {
142
+ const lidUser = stored[pnUser]
143
+ if (lidUser && typeof lidUser === 'string') {
144
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
145
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
146
+ }
147
+ }
148
+ for (const { pn, pnUser, decoded } of pending) {
149
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
150
+ if (cached && typeof cached === 'string') {
151
+ if (!addResolvedPair(pn, decoded, cached)) {
152
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`)
153
+ continue
154
+ }
155
+ } else {
156
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`)
157
+ const device = decoded.device || 0
158
+ let normalizedPn = jidNormalizedUser(pn)
159
+ if (isHostedPnUser(normalizedPn)) normalizedPn = `${pnUser}@s.whatsapp.net`
160
+ if (!usyncFetch[normalizedPn]) usyncFetch[normalizedPn] = [device]
161
+ else usyncFetch[normalizedPn]?.push(device)
162
+ }
163
+ }
164
+ }
165
+
166
+ if (Object.keys(usyncFetch).length > 0) {
167
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch))
168
+ if (result && result.length > 0) {
169
+ await this.storeLIDPNMappings(result)
170
+ for (const pair of result) {
171
+ const pnDecoded = jidDecode(pair.pn)
172
+ const pnUser = pnDecoded?.user
173
+ if (!pnUser) continue
174
+ const lidUser = jidDecode(pair.lid)?.user
175
+ if (!lidUser) continue
176
+ for (const device of usyncFetch[pair.pn]) {
177
+ const deviceSpecificLid = `${lidUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted.lid' : 'lid'}`
178
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`)
179
+ const deviceSpecificPn = `${pnUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`
180
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn }
181
+ }
182
+ }
183
+ } else {
184
+ this.logger.warn('USync fetch yielded no results for pending PNs')
185
+ }
186
+ }
187
+
188
+ return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null
189
+ }
190
+
191
+ async getPNForLID(lid) {
192
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null
193
+ }
194
+
195
+ async getPNsForLIDs(lids) {
196
+ if (lids.length === 0) return null
197
+ const sortedLids = [...new Set(lids)].sort()
198
+ const cacheKey = sortedLids.join(',')
199
+ const inflight = this.inflightPNLookups.get(cacheKey)
200
+ if (inflight) {
201
+ this.logger.trace(`Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`)
202
+ return inflight
203
+ }
204
+ const promise = this._getPNsForLIDsImpl(lids)
205
+ this.inflightPNLookups.set(cacheKey, promise)
206
+ try {
207
+ return await promise
208
+ } finally {
209
+ this.inflightPNLookups.delete(cacheKey)
210
+ }
211
+ }
212
+
213
+ async _getPNsForLIDsImpl(lids) {
214
+ const successfulPairs = {}
215
+ const pending = []
216
+
217
+ const addResolvedPair = (lid, decoded, pnUser) => {
218
+ if (!pnUser || typeof pnUser !== 'string') return false
219
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0
220
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`
221
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`)
222
+ successfulPairs[lid] = { lid, pn: pnJid }
223
+ return true
224
+ }
225
+
226
+ for (const lid of lids) {
227
+ if (!isLidUser(lid)) continue
228
+ const decoded = jidDecode(lid)
229
+ if (!decoded) continue
230
+ const lidUser = decoded.user
231
+ const cached = this.mappingCache.get(`lid:${lidUser}`)
232
+ if (cached && typeof cached === 'string') {
233
+ addResolvedPair(lid, decoded, cached)
234
+ continue
235
+ }
236
+ pending.push({ lid, lidUser, decoded })
237
+ }
238
+
239
+ if (pending.length) {
240
+ const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))]
241
+ const stored = await this.keys.get('lid-mapping', reverseKeys)
242
+ for (const { lid, lidUser, decoded } of pending) {
243
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`)
244
+ if (!pnUser || typeof pnUser !== 'string') {
245
+ pnUser = stored[`${lidUser}_reverse`]
246
+ if (pnUser && typeof pnUser === 'string') {
247
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
248
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
249
+ }
250
+ }
251
+ if (pnUser && typeof pnUser === 'string') {
252
+ addResolvedPair(lid, decoded, pnUser)
253
+ } else {
254
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`)
255
+ }
256
+ }
257
+ }
258
+
259
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null
260
+ }
261
+
262
+ close() {
263
+ this.mappingCache.clear()
264
+ }
265
+ }
266
+
267
+ function extractIdentityFromPkmsg(ciphertext) {
268
+ try {
269
+ if (!ciphertext || ciphertext.length < 2) return undefined
270
+ const version = ciphertext[0]
271
+ if ((version & 0xf) !== 3) return undefined
272
+ const preKeyProto = PreKeyWhisperMessage.decode(ciphertext.slice(1))
273
+ if (preKeyProto.identityKey?.length === 33) return new Uint8Array(preKeyProto.identityKey)
274
+ return undefined
275
+ } catch {
276
+ return undefined
277
+ }
278
+ }
279
+
280
+ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
281
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc)
282
+ const storage = signalStorage(auth, lidMapping)
283
+ const parsedKeys = auth.keys
284
+ const migratedSessionCache = new Cache({ ttl: 3 * 24 * 60 * 60 * 1000, max: 5000, updateAgeOnGet: true })
285
+
286
+ const ensureSenderKeyAndCreateSkdm = async (group, meId) => {
287
+ const senderName = jidToSignalSenderKeyName(group, meId)
288
+ const senderNameStr = senderName.toString()
289
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
290
+ if (!senderKey) await storage.storeSenderKey(senderName, new SenderKeyRecord())
291
+ const skdm = await new GroupSessionBuilder(storage).create(senderName)
292
+ return { senderName, skdm }
293
+ }
294
+
295
+ const repository = {
296
+ decryptGroupMessage({ group, authorJid, msg }) {
297
+ const senderName = jidToSignalSenderKeyName(group, authorJid)
298
+ const cipher = new GroupCipher(storage, senderName)
299
+ return parsedKeys.transaction(async () => cipher.decrypt(msg), group)
300
+ },
301
+
302
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
303
+ const builder = new GroupSessionBuilder(storage)
304
+ if (!item.groupId) throw new Error('Group ID is required for sender key distribution message')
305
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid)
306
+ const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage)
307
+ const senderNameStr = senderName.toString()
308
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr])
309
+ if (!senderKey) await storage.storeSenderKey(senderName, new SenderKeyRecord())
310
+ return parsedKeys.transaction(async () => {
311
+ const { [senderNameStr]: senderKey2 } = await auth.keys.get('sender-key', [senderNameStr])
312
+ if (!senderKey2) await storage.storeSenderKey(senderName, new SenderKeyRecord())
313
+ await builder.process(senderName, senderMsg)
314
+ }, item.groupId)
315
+ },
316
+
317
+ async decryptMessage({ jid, type, ciphertext }) {
318
+ const addr = jidToSignalProtocolAddress(jid)
319
+ const session = new libsignal.SessionCipher(storage, addr)
320
+
321
+ if (type === 'pkmsg') {
322
+ const identityKey = extractIdentityFromPkmsg(ciphertext)
323
+ if (identityKey) {
324
+ const addrStr = addr.toString()
325
+ const identityChanged = await storage.saveIdentity(addrStr, identityKey)
326
+ if (identityChanged) {
327
+ logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established')
328
+ }
329
+ }
330
+ }
331
+
332
+ async function doDecrypt() {
333
+ switch (type) {
334
+ case 'pkmsg':
335
+ return session.decryptPreKeyWhisperMessage(ciphertext)
336
+ case 'msg':
337
+ return session.decryptWhisperMessage(ciphertext)
338
+ }
339
+ }
340
+
341
+ return parsedKeys.transaction(async () => doDecrypt(), jid)
342
+ },
343
+
344
+ async encryptMessage({ jid, data }) {
345
+ const addr = jidToSignalProtocolAddress(jid)
346
+ const cipher = new libsignal.SessionCipher(storage, addr)
347
+ return parsedKeys.transaction(async () => {
348
+ const { type: sigType, body } = await cipher.encrypt(data)
349
+ const type = sigType === 3 ? 'pkmsg' : 'msg'
350
+ return { type, ciphertext: Buffer.from(body, 'binary') }
351
+ }, jid)
352
+ },
353
+
354
+ async encryptGroupMessage({ group, meId, data }) {
355
+ return parsedKeys.transaction(async () => {
356
+ const { senderName, skdm } = await ensureSenderKeyAndCreateSkdm(group, meId)
357
+ const ciphertext = await new GroupCipher(storage, senderName).encrypt(data)
358
+ return { ciphertext, senderKeyDistributionMessage: skdm.serialize() }
359
+ }, group)
360
+ },
361
+
362
+ async getSenderKeyDistributionMessage({ group, meId }) {
363
+ return parsedKeys.transaction(async () => {
364
+ const { skdm } = await ensureSenderKeyAndCreateSkdm(group, meId)
365
+ return skdm.serialize()
366
+ }, group)
367
+ },
368
+
369
+ async hasSenderKey({ group, meId }) {
370
+ const senderName = jidToSignalSenderKeyName(group, meId).toString()
371
+ const { [senderName]: key } = await auth.keys.get('sender-key', [senderName])
372
+ return !!key
373
+ },
374
+
375
+ async getSessionInfo(jid) {
376
+ const addr = jidToSignalProtocolAddress(jid).toString()
377
+ const session = await storage.loadSession(addr)
378
+ if (!session) return null
379
+ const open = session.getOpenSession?.()
380
+ const baseKey = open?.indexInfo?.baseKey
381
+ const registrationId = open?.registrationId
382
+ if (!baseKey || typeof registrationId !== 'number') return null
383
+ return { baseKey: new Uint8Array(baseKey), registrationId }
384
+ },
385
+
386
+ async injectE2ESession({ jid, session }) {
387
+ logger.trace({ jid }, 'injecting E2EE session')
388
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid))
389
+ return parsedKeys.transaction(async () => {
390
+
391
+ await cipher.initOutgoing(session)
392
+ }, jid)
393
+ },
394
+
395
+ jidToSignalProtocolAddress(jid) {
396
+ return jidToSignalProtocolAddress(jid).toString()
397
+ },
398
+
399
+ lidMapping,
400
+
401
+ async validateSession(jid) {
402
+ try {
403
+ const addr = jidToSignalProtocolAddress(jid)
404
+ const session = await storage.loadSession(addr.toString())
405
+ if (!session) return { exists: false, reason: 'no session' }
406
+ if (!session.haveOpenSession()) return { exists: false, reason: 'no open session' }
407
+ return { exists: true }
408
+ } catch {
409
+ return { exists: false, reason: 'validation error' }
410
+ }
411
+ },
412
+
413
+ async deleteSession(jids) {
414
+ if (!jids.length) return
415
+ const sessionUpdates = {}
416
+ jids.forEach(jid => {
417
+ const addr = jidToSignalProtocolAddress(jid)
418
+ sessionUpdates[addr.toString()] = null
419
+ })
420
+ return parsedKeys.transaction(async () => {
421
+ await auth.keys.set({ session: sessionUpdates })
422
+ }, `delete-${jids.length}-sessions`)
423
+ },
424
+
425
+ close() {
426
+ migratedSessionCache.clear()
427
+ lidMapping.close()
428
+ },
429
+
430
+ async migrateSession(fromJid, toJid) {
431
+
432
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid))) return { migrated: 0, skipped: 0, total: 0 }
433
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) return { migrated: 0, skipped: 0, total: 1 }
434
+
435
+ const { user } = jidDecode(fromJid)
436
+ logger.debug({ fromJid }, 'bulk device migration - loading all user devices')
437
+ const { [user]: userDevices } = await parsedKeys.get('device-list', [user])
438
+ if (!userDevices) return { migrated: 0, skipped: 0, total: 0 }
439
+
440
+ const { device: fromDevice } = jidDecode(fromJid)
441
+ const fromDeviceStr = fromDevice?.toString() || '0'
442
+ if (!userDevices.includes(fromDeviceStr)) userDevices.push(fromDeviceStr)
443
+
444
+ const uncachedDevices = userDevices.filter(device => !migratedSessionCache.has(`${user}.${device}`))
445
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`)
446
+ const existingSessions = await parsedKeys.get('session', deviceSessionKeys)
447
+
448
+ const deviceJids = []
449
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
450
+ if (sessionData) {
451
+ const deviceStr = sessionKey.split('.')[1]
452
+ if (!deviceStr) continue
453
+ const deviceNum = parseInt(deviceStr)
454
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`
455
+ if (deviceNum === 99) jid = `${user}:99@hosted`
456
+ deviceJids.push(jid)
457
+ }
458
+ }
459
+ logger.debug(
460
+ { fromJid, totalDevices: userDevices.length, devicesWithSessions: deviceJids.length, devices: deviceJids },
461
+ 'bulk device migration complete - all user devices processed'
462
+ )
463
+
464
+ return parsedKeys.transaction(async () => {
465
+ const migrationOps = deviceJids.map(jid => {
466
+ const lidWithDevice = transferDevice(jid, toJid)
467
+ const fromDecoded = jidDecode(jid)
468
+ const toDecoded = jidDecode(lidWithDevice)
469
+ return {
470
+ fromJid: jid,
471
+ toJid: lidWithDevice,
472
+ pnUser: fromDecoded.user,
473
+ lidUser: toDecoded.user,
474
+ deviceId: fromDecoded.device || 0,
475
+ fromAddr: jidToSignalProtocolAddress(jid),
476
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
477
+ }
478
+ })
479
+ const totalOps = migrationOps.length
480
+ let migratedCount = 0
481
+
482
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())))
483
+ const pnSessions = await parsedKeys.get('session', pnAddrStrings)
484
+
485
+ const sessionUpdates = {}
486
+ for (const op of migrationOps) {
487
+ const pnAddrStr = op.fromAddr.toString()
488
+ const lidAddrStr = op.toAddr.toString()
489
+ const pnSession = pnSessions[pnAddrStr]
490
+ if (pnSession) {
491
+ const fromSession = libsignal.SessionRecord.deserialize(pnSession)
492
+ if (fromSession.haveOpenSession()) {
493
+ sessionUpdates[lidAddrStr] = fromSession.serialize()
494
+ sessionUpdates[pnAddrStr] = null
495
+ migratedCount++
496
+ }
497
+ }
498
+ }
499
+
500
+ if (Object.keys(sessionUpdates).length > 0) {
501
+ await parsedKeys.set({ session: sessionUpdates })
502
+ logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete')
503
+ for (const op of migrationOps) {
504
+ if (sessionUpdates[op.toAddr.toString()]) {
505
+ migratedSessionCache.set(`${op.pnUser}.${op.deviceId}`, true)
506
+ }
507
+ }
508
+ }
509
+
510
+ const skippedCount = totalOps - migratedCount
511
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps }
512
+ }, `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`)
513
+ }
514
+ }
515
+
516
+ return repository
517
+ }
518
+
519
+ const jidToSignalProtocolAddress = jid => {
520
+ const decoded = jidDecode(jid)
521
+ const { user, device, server, domainType } = decoded
522
+ if (!user) throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`)
523
+ const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user
524
+ const finalDevice = device || 0
525
+ if (device === 99 && decoded.server !== 'hosted' && decoded.server !== 'hosted.lid') {
526
+ throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid)
527
+ }
528
+ return new libsignal.ProtocolAddress(signalUser, finalDevice)
529
+ }
530
+
531
+ const jidToSignalSenderKeyName = (group, user) => new SenderKeyName(group, jidToSignalProtocolAddress(user))
532
+
533
+ function signalStorage({ creds, keys }, lidMapping) {
534
+ const senderKeyCache = new Cache({ max: 1000, ttl: 5 * 60 * 1000 })
535
+
536
+ const resolveLIDSignalAddress = async id => {
537
+ if (id.includes('.')) {
538
+ const [deviceId, device] = id.split('.')
539
+ const [user, domainType_] = deviceId.split('_')
540
+ const domainType = parseInt(domainType_ || '0')
541
+ if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID) return id
542
+ const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`
543
+ const lidForPN = await lidMapping.getLIDForPN(pnJid)
544
+ if (lidForPN) {
545
+ const lidAddr = jidToSignalProtocolAddress(lidForPN)
546
+ return lidAddr.toString()
547
+ }
548
+ }
549
+ return id
550
+ }
551
+
552
+ return {
553
+ loadSession: async id => {
554
+ try {
555
+ const wireJid = await resolveLIDSignalAddress(id)
556
+ const { [wireJid]: sess } = await keys.get('session', [wireJid])
557
+ if (sess) return libsignal.SessionRecord.deserialize(sess)
558
+ } catch {
559
+ return null
560
+ }
561
+ return null
562
+ },
563
+
564
+ storeSession: async (id, session) => {
565
+ const wireJid = await resolveLIDSignalAddress(id)
566
+ await keys.set({ session: { [wireJid]: session.serialize() } })
567
+ },
568
+
569
+ isTrustedIdentity: () => true,
570
+
571
+ loadIdentityKey: async id => {
572
+ const wireJid = await resolveLIDSignalAddress(id)
573
+ const { [wireJid]: key } = await keys.get('identity-key', [wireJid])
574
+ return key || undefined
575
+ },
576
+
577
+ saveIdentity: async (id, identityKey) => {
578
+ const wireJid = await resolveLIDSignalAddress(id)
579
+ const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid])
580
+ const keysMatch = existingKey?.length === identityKey.length && existingKey.every((byte, i) => byte === identityKey[i])
581
+ if (existingKey && !keysMatch) {
582
+ await keys.set({ session: { [wireJid]: null }, 'identity-key': { [wireJid]: identityKey } })
583
+ return true
584
+ }
585
+ if (!existingKey) {
586
+ await keys.set({ 'identity-key': { [wireJid]: identityKey } })
587
+ return true
588
+ }
589
+ return false
590
+ },
591
+
592
+ loadPreKey: async id => {
593
+ const keyId = id.toString()
594
+ const { [keyId]: key } = await keys.get('pre-key', [keyId])
595
+ if (key) return { privKey: Buffer.from(key.private), pubKey: Buffer.from(key.public) }
596
+ },
597
+
598
+ removePreKey: id => keys.set({ 'pre-key': { [id]: null } }),
599
+
600
+ loadSignedPreKey: () => {
601
+ const key = creds.signedPreKey
602
+ return { privKey: Buffer.from(key.keyPair.private), pubKey: Buffer.from(key.keyPair.public) }
603
+ },
604
+
605
+ loadSenderKey: async senderKeyName => {
606
+ const keyId = senderKeyName.toString()
607
+ const cached = senderKeyCache.get(keyId)
608
+ if (cached) return cached
609
+ const { [keyId]: key } = await keys.get('sender-key', [keyId])
610
+ if (key) {
611
+ const record = SenderKeyRecord.deserialize(key)
612
+ senderKeyCache.set(keyId, record)
613
+ return record
614
+ }
615
+ return new SenderKeyRecord()
616
+ },
617
+
618
+ storeSenderKey: async (senderKeyName, key) => {
619
+ const keyId = senderKeyName.toString()
620
+ senderKeyCache.set(keyId, key)
621
+ const serialized = JSON.stringify(key.serialize())
622
+ await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } })
623
+ },
624
+
625
+ getOurRegistrationId: () => creds.registrationId,
626
+
627
+ getOurIdentity: () => {
628
+ const { signedIdentityKey } = creds
629
+ return {
630
+ privKey: Buffer.from(signedIdentityKey.private),
631
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
632
+ }
633
+ }
634
+ }
635
+ }