@zervonexx/baileys 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +4113 -3
  3. package/WAProto/WAProtoCompile.js +323 -0
  4. package/WAProto/fetcher.js +68 -0
  5. package/WAProto/index.js +96 -0
  6. package/WAProto/parser.js +334 -0
  7. package/lib/Builders/AIRich.js +674 -0
  8. package/lib/Builders/auto.js +50 -0
  9. package/lib/Builders/base.js +145 -0
  10. package/lib/Builders/builders.js +589 -0
  11. package/lib/Builders/index.js +4 -0
  12. package/lib/Defaults/index.js +248 -0
  13. package/lib/Signal/index.js +2 -0
  14. package/lib/Signal/libsignal.js +527 -0
  15. package/lib/Signal/lid-mapping.js +283 -0
  16. package/lib/Socket/Client/index.js +2 -0
  17. package/lib/Socket/Client/types.js +10 -0
  18. package/lib/Socket/Client/websocket.js +84 -0
  19. package/lib/Socket/business.js +152 -0
  20. package/lib/Socket/chats.js +855 -0
  21. package/lib/Socket/communities.js +147 -0
  22. package/lib/Socket/groups.js +294 -0
  23. package/lib/Socket/index.js +15 -0
  24. package/lib/Socket/messages-recv.js +994 -0
  25. package/lib/Socket/messages-send.js +723 -0
  26. package/lib/Socket/mex.js +34 -0
  27. package/lib/Socket/newsletter.js +784 -0
  28. package/lib/Socket/registration.js +155 -0
  29. package/lib/Socket/socket.js +798 -0
  30. package/lib/Socket/spam-report.js +144 -0
  31. package/lib/Socket/username.js +82 -0
  32. package/lib/Socket/zervonex-handler.js +58 -0
  33. package/lib/Store/index.js +6 -0
  34. package/lib/Store/make-cache-manager-store.js +80 -0
  35. package/lib/Store/make-in-memory-store.js +426 -0
  36. package/lib/Store/make-ordered-dictionary.js +82 -0
  37. package/lib/Store/object-repository.js +31 -0
  38. package/lib/Store/reporting-info-store.js +38 -0
  39. package/lib/Types/Auth.js +2 -0
  40. package/lib/Types/Bussines.js +2 -0
  41. package/lib/Types/Call.js +2 -0
  42. package/lib/Types/Chat.js +8 -0
  43. package/lib/Types/Contact.js +2 -0
  44. package/lib/Types/Events.js +2 -0
  45. package/lib/Types/GroupMetadata.js +2 -0
  46. package/lib/Types/Label.js +25 -0
  47. package/lib/Types/LabelAssociation.js +7 -0
  48. package/lib/Types/Message.js +15 -0
  49. package/lib/Types/Newsletter.js +100 -0
  50. package/lib/Types/Product.js +2 -0
  51. package/lib/Types/Signal.js +2 -0
  52. package/lib/Types/Socket.js +14 -0
  53. package/lib/Types/State.js +26 -0
  54. package/lib/Types/USync.js +2 -0
  55. package/lib/Types/index.js +30 -0
  56. package/lib/Utils/auth-utils.js +159 -0
  57. package/lib/Utils/baileys-event-stream.js +33 -0
  58. package/lib/Utils/bot-capabilities.js +41 -0
  59. package/lib/Utils/bot-planning-replay.js +44 -0
  60. package/lib/Utils/browser-utils.js +30 -0
  61. package/lib/Utils/business.js +75 -0
  62. package/lib/Utils/chat-utils.js +317 -0
  63. package/lib/Utils/companion-reg-client-utils.js +20 -0
  64. package/lib/Utils/consumer-application.js +38 -0
  65. package/lib/Utils/crypto.js +53 -0
  66. package/lib/Utils/cstoken.js +15 -0
  67. package/lib/Utils/decode-wa-message.js +200 -0
  68. package/lib/Utils/event-buffer.js +273 -0
  69. package/lib/Utils/extras.js +186 -0
  70. package/lib/Utils/generics.js +195 -0
  71. package/lib/Utils/history.js +51 -0
  72. package/lib/Utils/identity-change-handler.js +19 -0
  73. package/lib/Utils/index.js +40 -0
  74. package/lib/Utils/link-preview.js +51 -0
  75. package/lib/Utils/logger.js +3 -0
  76. package/lib/Utils/lt-hash.js +3 -0
  77. package/lib/Utils/make-mutex.js +16 -0
  78. package/lib/Utils/message-composer.js +62 -0
  79. package/lib/Utils/message-retry-manager.js +48 -0
  80. package/lib/Utils/messages-media.js +502 -0
  81. package/lib/Utils/messages.js +943 -0
  82. package/lib/Utils/meta-ai-msmsg.js +122 -0
  83. package/lib/Utils/meta-compositing.js +75 -0
  84. package/lib/Utils/modern-messages.js +235 -0
  85. package/lib/Utils/native-flow.js +81 -0
  86. package/lib/Utils/noise-handler.js +161 -0
  87. package/lib/Utils/pre-key-manager.js +76 -0
  88. package/lib/Utils/process-message.js +401 -0
  89. package/lib/Utils/reporting-utils.js +171 -0
  90. package/lib/Utils/signal.js +167 -0
  91. package/lib/Utils/spam-report-utils.js +166 -0
  92. package/lib/Utils/sync-action-utils.js +33 -0
  93. package/lib/Utils/tc-token-utils.js +154 -0
  94. package/lib/Utils/use-keyv-auth-state.js +200 -0
  95. package/lib/Utils/use-multi-file-auth-state.js +84 -0
  96. package/lib/Utils/validate-connection.js +172 -0
  97. package/lib/WABinary/constants.js +1321 -0
  98. package/lib/WABinary/decode.js +152 -0
  99. package/lib/WABinary/encode.js +140 -0
  100. package/lib/WABinary/generic-utils.js +203 -0
  101. package/lib/WABinary/index.js +6 -0
  102. package/lib/WABinary/jid-utils.js +235 -0
  103. package/lib/WABinary/types.js +4 -0
  104. package/lib/WAM/BinaryInfo.js +10 -0
  105. package/lib/WAM/constants.js +22853 -0
  106. package/lib/WAM/encode.js +150 -0
  107. package/lib/WAM/index.js +3 -0
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
  120. package/lib/WAUSync/Protocols/index.js +12 -0
  121. package/lib/WAUSync/USyncQuery.js +88 -0
  122. package/lib/WAUSync/USyncUser.js +20 -0
  123. package/lib/WAUSync/index.js +3 -0
  124. package/lib/index.js +67 -0
  125. package/package.json +191 -5
@@ -0,0 +1,527 @@
1
+ import {
2
+ SessionCipher,
3
+ SessionBuilder,
4
+ SessionRecord,
5
+ ProtocolAddress,
6
+ GroupCipher,
7
+ GroupSessionBuilder,
8
+ SenderKeyName,
9
+ SenderKeyDistributionMessage,
10
+ SenderKeyRecord,
11
+ } from 'whatsapp-rust-bridge'
12
+ import { proto } from '../../WAProto/index.js'
13
+ import { LRUCache } from 'lru-cache'
14
+ import { generateSignalPubKey } from '../Utils/index.js'
15
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, transferDevice, WAJIDDomains } from '../WABinary/index.js'
16
+ import { LIDMappingStore } from './lid-mapping.js'
17
+
18
+ // ─── Address Helpers ──────────────────────────────────────────────────────────
19
+
20
+ const jidToAddr = (jid) => {
21
+ const { user, device, server, domainType } = jidDecode(jid)
22
+ if (!user) throw new Error(`Invalid JID: "${jid}"`)
23
+ if (device === 99 && server !== 'hosted' && server !== 'hosted.lid') throw new Error('Invalid device 99: ' + jid)
24
+ return new ProtocolAddress(
25
+ domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user,
26
+ device || 0
27
+ )
28
+ }
29
+
30
+ const jidToSenderKeyName = (group, user) => new SenderKeyName(group, jidToAddr(user))
31
+
32
+ // ─── Buffer Utils ─────────────────────────────────────────────────────────────
33
+
34
+ const toBuffer = (raw) => {
35
+ if (!raw) return null
36
+ if (raw instanceof Uint8Array) return raw
37
+ if (Buffer.isBuffer(raw)) return raw
38
+ if (raw?.type === 'Buffer' && Array.isArray(raw?.data)) return Buffer.from(raw.data)
39
+ if (Array.isArray(raw)) return Buffer.from(raw)
40
+ if (typeof raw === 'string') return Buffer.from(raw, 'base64')
41
+ if (raw?.data) return Buffer.from(raw.data)
42
+ return null
43
+ }
44
+
45
+ const toU8 = (raw) => {
46
+ const buf = toBuffer(raw)
47
+ if (!buf) return null
48
+ return buf instanceof Uint8Array && buf.constructor === Uint8Array
49
+ ? buf
50
+ : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)
51
+ }
52
+
53
+ const isOldJson = (raw) => {
54
+ if (!raw || raw instanceof Uint8Array || Buffer.isBuffer(raw)) return false
55
+ if (typeof raw === 'object') return 'version' in raw || '_sessions' in raw
56
+ if (typeof raw === 'string') {
57
+ try { const p = JSON.parse(raw); return 'version' in p || '_sessions' in p } catch { return false }
58
+ }
59
+ return false
60
+ }
61
+
62
+ const bufEqual = (a, b) =>
63
+ a && b && a.length === b.length && a.every((byte, i) => byte === b[i])
64
+
65
+ // ─── Identity Key Extraction ──────────────────────────────────────────────────
66
+
67
+ const extractIdentityFromPkmsg = (ciphertext) => {
68
+ try {
69
+ if (!ciphertext || ciphertext.length < 2) return undefined
70
+ if ((ciphertext[0] & 0xf) !== 3) return undefined
71
+ const decoded = proto.PreKeySignalMessage.decode(ciphertext.subarray(1))
72
+ const key = decoded.identityKey
73
+ if (key && key.length === 33) return new Uint8Array(key)
74
+ return undefined
75
+ } catch {
76
+ return undefined
77
+ }
78
+ }
79
+
80
+ // ─── Main Factory ─────────────────────────────────────────────────────────────
81
+
82
+ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
83
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc)
84
+ const parsedKeys = auth.keys
85
+
86
+ // LRU cache for PN→LID address resolution to avoid repeated DB lookups
87
+ const lidCache = new LRUCache({ max: 500, ttl: 5 * 60 * 1000 })
88
+
89
+ // Per-address session read cache: avoids a DB round-trip on every decrypt.
90
+ // Keyed by resolved LID addr string. Value is Uint8Array | null.
91
+ const sessionReadCache = new LRUCache({ max: 1000, ttl: 5 * 60 * 1000, ttlAutopurge: true })
92
+
93
+ // Per-address identity read cache: avoids a DB round-trip on every encrypt.
94
+ const identityReadCache = new LRUCache({ max: 1000, ttl: 5 * 60 * 1000, ttlAutopurge: true })
95
+
96
+ const resolveLID = async (id) => {
97
+ if (!id.includes('.')) return id
98
+ const cached = lidCache.get(id)
99
+ if (cached) return cached
100
+ const [deviceId, device] = id.split('.')
101
+ const [user, dt] = deviceId.split('_')
102
+ const domainType = parseInt(dt || '0')
103
+ if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID) return id
104
+ const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`
105
+ const lid = await lidMapping.getLIDForPN(pnJid)
106
+ const result = lid ? jidToAddr(lid).toString() : id
107
+ lidCache.set(id, result)
108
+ return result
109
+ }
110
+
111
+ const storage = signalStorage(auth, lidMapping, logger, lidCache, sessionReadCache, identityReadCache, resolveLID)
112
+
113
+ // Tracks which PN→LID session migrations have already been done this process
114
+ // lifetime so migrateSession is idempotent even if called repeatedly.
115
+ const migratedCache = new LRUCache({ max: 5000, ttl: 7 * 24 * 60 * 60 * 1000, ttlAutopurge: true, updateAgeOnGet: true })
116
+
117
+ const txn = (fn, key) => parsedKeys.transaction(fn, key)
118
+
119
+ return {
120
+ // ── Group messaging ───────────────────────────────────────────────────────
121
+
122
+ decryptGroupMessage({ group, authorJid, msg }) {
123
+ return txn(
124
+ () => new GroupCipher(storage, group, jidToAddr(authorJid)).decrypt(toU8(msg)),
125
+ group
126
+ )
127
+ },
128
+
129
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
130
+ if (!item.groupId) throw new Error('Group ID required')
131
+ const senderName = jidToSenderKeyName(item.groupId, authorJid)
132
+ const senderMsg = SenderKeyDistributionMessage.deserialize(
133
+ toU8(item.axolotlSenderKeyDistributionMessage)
134
+ )
135
+ return txn(() => new GroupSessionBuilder(storage).process(senderName, senderMsg), item.groupId)
136
+ },
137
+
138
+ encryptGroupMessage({ group, meId, data }) {
139
+ return txn(async () => {
140
+ const senderName = jidToSenderKeyName(group, meId)
141
+ const name = senderName.toString()
142
+ const { [name]: raw } = await parsedKeys.get('sender-key', [name])
143
+ const hasKey = raw ? (() => { try { return !SenderKeyRecord.deserialize(toU8(raw)).isEmpty() } catch { return false } })() : false
144
+ const skdm = await new GroupSessionBuilder(storage).create(senderName)
145
+ const ciphertext = await new GroupCipher(storage, group, jidToAddr(meId)).encrypt(toU8(data))
146
+ return { ciphertext, senderKeyDistributionMessage: hasKey ? undefined : skdm.serialize() }
147
+ }, group)
148
+ },
149
+
150
+ getSenderKeyDistributionMessage({ group, meId }) {
151
+ return txn(async () => {
152
+ const senderName = jidToSenderKeyName(group, meId)
153
+ return (await new GroupSessionBuilder(storage).create(senderName)).serialize()
154
+ }, group)
155
+ },
156
+
157
+ async hasSenderKey({ group, meId }) {
158
+ const name = jidToSenderKeyName(group, meId).toString()
159
+ const { [name]: raw } = await parsedKeys.get('sender-key', [name])
160
+ const buf = toU8(raw)
161
+ if (!buf) return false
162
+ try {
163
+ return !SenderKeyRecord.deserialize(buf).isEmpty()
164
+ } catch {
165
+ return false
166
+ }
167
+ },
168
+
169
+ deleteSenderKey(group, authorJid) {
170
+ return parsedKeys.set({ 'sender-key': { [jidToSenderKeyName(group, authorJid).toString()]: null } })
171
+ },
172
+
173
+ // ── 1:1 messaging ─────────────────────────────────────────────────────────
174
+
175
+ async decryptMessage({ jid, type, ciphertext }) {
176
+ const addr = jidToAddr(jid)
177
+ const addrStr = addr.toString()
178
+ const cipher = new SessionCipher(storage, addr)
179
+
180
+ try {
181
+ return await txn(async () => {
182
+ if (type === 'pkmsg') {
183
+ const identityKey = extractIdentityFromPkmsg(ciphertext)
184
+ if (identityKey) {
185
+ const changed = await storage.saveIdentity(addrStr, identityKey)
186
+ if (changed) logger?.info?.({ jid }, '[Signal] Identity key changed — session cleared for re-handshake')
187
+ } else {
188
+ logger?.warn?.({ jid }, '[Signal] pkmsg: could not extract identity key from envelope')
189
+ }
190
+ return cipher.decryptPreKeyWhisperMessage(toU8(ciphertext))
191
+ }
192
+ if (type === 'msg') {
193
+ return cipher.decryptWhisperMessage(toU8(ciphertext))
194
+ }
195
+ throw new Error(`[Signal] Unknown message type: ${type}`)
196
+ }, jid)
197
+ } catch (e) {
198
+ if (e?.message?.includes('DuplicatedMessage')) {
199
+ logger?.debug?.({ jid }, '[Signal] Duplicate message ignored')
200
+ return null
201
+ }
202
+ if (e?.message?.includes('UntrustedIdentity') || e?.message?.includes('InvalidMessage') || e?.message?.includes('BadMac')) {
203
+ logger?.warn?.({ jid, err: e.message }, '[Signal] Session error — wiping session for re-handshake')
204
+ await storage.wipeSession(addrStr)
205
+ sessionReadCache.delete(addrStr)
206
+ }
207
+ throw e
208
+ }
209
+ },
210
+
211
+ encryptMessage({ jid, data }) {
212
+ return txn(async () => {
213
+ const { type: sigType, body } = await new SessionCipher(storage, jidToAddr(jid)).encrypt(toU8(data))
214
+ return { type: sigType === 3 ? 'pkmsg' : 'msg', ciphertext: Buffer.from(body) }
215
+ }, jid)
216
+ },
217
+
218
+ injectE2ESession({ jid, session }) {
219
+ return txn(() => new SessionBuilder(storage, jidToAddr(jid)).processPreKeyBundle(session), jid)
220
+ },
221
+
222
+ // ── Session utilities ──────────────────────────────────────────────────────
223
+
224
+ jidToSignalProtocolAddress: (jid) => jidToAddr(jid).toString(),
225
+
226
+ lidMapping,
227
+
228
+ async validateSession(jid) {
229
+ try {
230
+ const addr = jidToAddr(jid).toString()
231
+ const raw = await storage.loadSession(addr)
232
+ if (!raw) return { exists: false, reason: 'no session' }
233
+ try {
234
+ return SessionRecord.deserialize(raw).haveOpenSession()
235
+ ? { exists: true }
236
+ : { exists: false, reason: 'no open session' }
237
+ } catch {
238
+ return { exists: false, reason: 'deserialize error' }
239
+ }
240
+ } catch {
241
+ return { exists: false, reason: 'error' }
242
+ }
243
+ },
244
+
245
+ async deleteSession(jids) {
246
+ if (!jids?.length) return
247
+ return txn(async () => {
248
+ const updates = {}
249
+ for (const jid of jids) {
250
+ const addr = jidToAddr(jid).toString()
251
+ updates[addr] = null
252
+ sessionReadCache.delete(addr)
253
+ }
254
+ await parsedKeys.set({ session: updates })
255
+ }, `del-${jids.length}`)
256
+ },
257
+
258
+ // ── Session migration (PN → LID) ──────────────────────────────────────────
259
+
260
+ async migrateSession(fromJid, toJid) {
261
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid))) return { migrated: 0, skipped: 0, total: 0 }
262
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) return { migrated: 0, skipped: 0, total: 1 }
263
+ const { user } = jidDecode(fromJid)
264
+
265
+ const { [user]: userDevices_ } = await parsedKeys.get('device-list', [user])
266
+ const userDevices = userDevices_ ? [...userDevices_] : []
267
+ const fromDeviceStr = jidDecode(fromJid).device?.toString() || '0'
268
+ if (!userDevices.includes(fromDeviceStr)) userDevices.push(fromDeviceStr)
269
+
270
+ // Build addr strings for each device, skip already-migrated
271
+ const candidates = userDevices
272
+ .filter(d => !migratedCache.has(`${user}.${d}`))
273
+ .map(d => {
274
+ const num = parseInt(d)
275
+ const jid = num === 99 ? `${user}:99@hosted`
276
+ : num === 0 ? `${user}@s.whatsapp.net`
277
+ : `${user}:${num}@s.whatsapp.net`
278
+ return { cacheKey: `${user}.${d}`, jid, addr: jidToAddr(jid).toString() }
279
+ })
280
+
281
+ if (!candidates.length) return { migrated: 0, skipped: 0, total: 0 }
282
+
283
+ // Bulk-fetch only the session keys we actually need
284
+ const addrs = candidates.map(c => c.addr)
285
+ const existing = await parsedKeys.get('session', addrs)
286
+
287
+ const toMigrate = candidates.filter(c => {
288
+ const raw = toU8(existing[c.addr])
289
+ return raw && !isOldJson(raw)
290
+ })
291
+
292
+ if (!toMigrate.length) return { migrated: 0, skipped: candidates.length, total: candidates.length }
293
+
294
+ return txn(async () => {
295
+ // Re-fetch inside txn for freshness
296
+ const fresh = await parsedKeys.get('session', toMigrate.map(c => c.addr))
297
+ const updates = {}
298
+ let migrated = 0
299
+
300
+ for (const { jid, addr, cacheKey } of toMigrate) {
301
+ const raw = toU8(fresh[addr])
302
+ if (!raw || isOldJson(raw)) continue
303
+ let sess
304
+ try { sess = SessionRecord.deserialize(raw) } catch { continue }
305
+ if (!sess.haveOpenSession()) continue
306
+ const lidAddr = jidToAddr(transferDevice(jid, toJid)).toString()
307
+ updates[lidAddr] = sess.serialize()
308
+ updates[addr] = null
309
+ lidCache.delete(addr)
310
+ sessionReadCache.delete(addr)
311
+ migrated++
312
+ migratedCache.set(cacheKey, true)
313
+ }
314
+
315
+ if (migrated > 0) {
316
+ await parsedKeys.set({ session: updates })
317
+ }
318
+ return { migrated, skipped: toMigrate.length - migrated, total: candidates.length }
319
+ }, `migrate-${jidDecode(toJid)?.user}`)
320
+ },
321
+
322
+ async warmLIDCache(mappings) {
323
+ for (const { pn, lid } of mappings) {
324
+ try {
325
+ const pnAddr = jidToAddr(pn).toString()
326
+ const lidAddr = jidToAddr(lid).toString()
327
+ lidCache.set(pnAddr, lidAddr)
328
+ } catch { }
329
+ }
330
+ },
331
+
332
+ async preLoadKeys(jids) {
333
+ if (!jids?.length) return
334
+ try {
335
+ const addrs = await Promise.all(
336
+ jids.map(jid => resolveLID(jidToAddr(jid).toString()))
337
+ )
338
+ const [sessions, identityKeys] = await Promise.all([
339
+ parsedKeys.get('session', addrs),
340
+ parsedKeys.get('identity-key', addrs)
341
+ ])
342
+ for (const addr of addrs) {
343
+ if (sessions[addr] !== undefined) {
344
+ sessionReadCache.set(addr, sessions[addr] ? toU8(sessions[addr]) : null)
345
+ }
346
+ if (identityKeys[addr] !== undefined) {
347
+ identityReadCache.set(addr, identityKeys[addr] ? toU8(identityKeys[addr]) : null)
348
+ }
349
+ }
350
+ } catch (error) {
351
+ logger?.warn?.({ err: error?.message || error }, '[Signal] preLoadKeys failed')
352
+ }
353
+ },
354
+
355
+ close() {
356
+ migratedCache.clear()
357
+ sessionReadCache.clear()
358
+ identityReadCache.clear()
359
+ lidCache.clear()
360
+ lidMapping.close?.()
361
+ }
362
+ }
363
+ }
364
+
365
+ // ─── Storage Adapter ──────────────────────────────────────────────────────────
366
+ // Implements the SignalStorage interface consumed by whatsapp-rust-bridge WASM.
367
+ //
368
+ // One key per record — exactly as original Baileys does:
369
+ // session: addr string → Uint8Array (SessionRecord.serialize())
370
+ // identity-key: addr string → Uint8Array (33-byte identity key)
371
+ // pre-key: id string → { public, private }
372
+ // sender-key: keyId string → Buffer
373
+
374
+ function signalStorage({ creds, keys }, lidMapping, logger, lidCache, sessionReadCache, identityReadCache, resolveLID) {
375
+
376
+ return {
377
+ // ── Sessions ─────────────────────────────────────────────────────────────
378
+
379
+ loadSession: async (id) => {
380
+ try {
381
+ const addr = await resolveLID(id)
382
+ const cached = sessionReadCache.get(addr)
383
+ if (cached !== undefined) return cached === null ? null : toU8(cached)
384
+ const { [addr]: raw } = await keys.get('session', [addr])
385
+ if (!raw || isOldJson(raw)) {
386
+ sessionReadCache.set(addr, null)
387
+ return null
388
+ }
389
+ const buf = toU8(raw)
390
+ sessionReadCache.set(addr, buf)
391
+ return buf
392
+ } catch (e) {
393
+ logger?.error?.(`[Signal] loadSession error for ${id}: ${e.message}`)
394
+ return null
395
+ }
396
+ },
397
+
398
+ storeSession: async (id, record) => {
399
+ const addr = await resolveLID(id)
400
+ const serialized = record.serialize()
401
+ sessionReadCache.set(addr, toU8(serialized))
402
+ await keys.set({ session: { [addr]: serialized } })
403
+ },
404
+
405
+ // ── Identity keys ─────────────────────────────────────────────────────────
406
+
407
+ isTrustedIdentity: async (id, identityKey) => {
408
+ try {
409
+ const addr = await resolveLID(id)
410
+ let existing = identityReadCache.get(addr)
411
+ if (existing === undefined) {
412
+ const { [addr]: raw } = await keys.get('identity-key', [addr])
413
+ existing = toU8(raw) ?? null
414
+ identityReadCache.set(addr, existing)
415
+ }
416
+ if (!existing) return true
417
+ const a = existing
418
+ const b = identityKey instanceof Uint8Array ? identityKey : toU8(identityKey)
419
+ return !!bufEqual(a, b)
420
+ } catch {
421
+ return true
422
+ }
423
+ },
424
+
425
+ loadIdentityKey: async (id) => {
426
+ const addr = await resolveLID(id)
427
+ let key = identityReadCache.get(addr)
428
+ if (key === undefined) {
429
+ const { [addr]: raw } = await keys.get('identity-key', [addr])
430
+ key = toU8(raw) ?? null
431
+ identityReadCache.set(addr, key)
432
+ }
433
+ return key === null ? undefined : key
434
+ },
435
+
436
+ saveIdentity: async (id, identityKey) => {
437
+ const addr = await resolveLID(id)
438
+ let existing = identityReadCache.get(addr)
439
+ if (existing === undefined) {
440
+ const { [addr]: raw } = await keys.get('identity-key', [addr])
441
+ existing = toU8(raw) ?? null
442
+ identityReadCache.set(addr, existing)
443
+ }
444
+ const a = existing
445
+ const b = identityKey instanceof Uint8Array ? identityKey : toU8(identityKey)
446
+ if (a && !bufEqual(a, b)) {
447
+ // Identity changed — wipe session and update key atomically
448
+ sessionReadCache.delete(addr)
449
+ identityReadCache.set(addr, b)
450
+ lidCache.delete(id)
451
+ await keys.set({
452
+ session: { [addr]: null },
453
+ 'identity-key': { [addr]: b }
454
+ })
455
+ return true
456
+ }
457
+ if (!a) {
458
+ identityReadCache.set(addr, b)
459
+ await keys.set({ 'identity-key': { [addr]: b } })
460
+ return true
461
+ }
462
+ return false
463
+ },
464
+
465
+ wipeSession: async (addr) => {
466
+ sessionReadCache.delete(addr)
467
+ await keys.set({ session: { [addr]: null } })
468
+ },
469
+
470
+ // ── PreKeys ───────────────────────────────────────────────────────────────
471
+
472
+ loadPreKey: async (id) => {
473
+ const { [id.toString()]: key } = await keys.get('pre-key', [id.toString()])
474
+ if (!key) return null
475
+ return {
476
+ pubKey: new Uint8Array(Buffer.from(key.public)),
477
+ privKey: new Uint8Array(Buffer.from(key.private))
478
+ }
479
+ },
480
+
481
+ removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
482
+
483
+ loadSignedPreKey: (id) => {
484
+ const key = creds.signedPreKey
485
+ if (key.keyId !== id) {
486
+ logger?.warn?.({ requested: id, current: key.keyId }, '[Signal] loadSignedPreKey id mismatch')
487
+ return null
488
+ }
489
+ return {
490
+ keyId: key.keyId,
491
+ keyPair: {
492
+ pubKey: new Uint8Array(Buffer.from(key.keyPair.public)),
493
+ privKey: new Uint8Array(Buffer.from(key.keyPair.private))
494
+ },
495
+ signature: new Uint8Array(Buffer.from(key.signature))
496
+ }
497
+ },
498
+
499
+ // ── Sender keys ───────────────────────────────────────────────────────────
500
+
501
+ loadSenderKey: async (keyId) => {
502
+ try {
503
+ const id = keyId.toString()
504
+ const { [id]: key } = await keys.get('sender-key', [id])
505
+ return toU8(key) ?? null
506
+ } catch (e) {
507
+ logger?.error?.(`[Signal] loadSenderKey error: ${e.message}`)
508
+ return null
509
+ }
510
+ },
511
+
512
+ storeSenderKey: async (keyId, record) => {
513
+ await keys.set({ 'sender-key': { [keyId.toString()]: Buffer.from(record) } })
514
+ },
515
+
516
+ // ── Own identity ──────────────────────────────────────────────────────────
517
+
518
+ getOurRegistrationId: () => creds.registrationId,
519
+
520
+ getOurIdentity: () => ({
521
+ pubKey: new Uint8Array(generateSignalPubKey(Buffer.from(creds.signedIdentityKey.public))),
522
+ privKey: new Uint8Array(Buffer.from(creds.signedIdentityKey.private))
523
+ })
524
+ }
525
+ }
526
+
527
+ export default makeLibSignalRepository