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