@gara31/void-baileys 7.0.0-rc.10

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/index.js +117292 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.js +116 -0
  5. package/lib/Signal/Group/ciphertext-message.js +12 -0
  6. package/lib/Signal/Group/group-session-builder.js +42 -0
  7. package/lib/Signal/Group/group_cipher.js +109 -0
  8. package/lib/Signal/Group/index.js +12 -0
  9. package/lib/Signal/Group/keyhelper.js +18 -0
  10. package/lib/Signal/Group/sender-chain-key.js +32 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  12. package/lib/Signal/Group/sender-key-message.js +80 -0
  13. package/lib/Signal/Group/sender-key-name.js +50 -0
  14. package/lib/Signal/Group/sender-key-record.js +47 -0
  15. package/lib/Signal/Group/sender-key-state.js +105 -0
  16. package/lib/Signal/Group/sender-message-key.js +30 -0
  17. package/lib/Signal/libsignal.js +416 -0
  18. package/lib/Signal/lid-mapping.js +189 -0
  19. package/lib/Socket/Client/index.js +3 -0
  20. package/lib/Socket/Client/types.js +11 -0
  21. package/lib/Socket/Client/websocket.js +61 -0
  22. package/lib/Socket/business.js +404 -0
  23. package/lib/Socket/chats.js +1146 -0
  24. package/lib/Socket/communities.js +505 -0
  25. package/lib/Socket/groups.js +404 -0
  26. package/lib/Socket/index.js +18 -0
  27. package/lib/Socket/messages-recv.js +1600 -0
  28. package/lib/Socket/messages-send.js +1203 -0
  29. package/lib/Socket/mex.js +56 -0
  30. package/lib/Socket/newsletter.js +240 -0
  31. package/lib/Socket/socket.js +1060 -0
  32. package/lib/Types/Auth.js +2 -0
  33. package/lib/Types/Bussines.js +2 -0
  34. package/lib/Types/Call.js +2 -0
  35. package/lib/Types/Chat.js +8 -0
  36. package/lib/Types/Contact.js +2 -0
  37. package/lib/Types/Events.js +2 -0
  38. package/lib/Types/GroupMetadata.js +2 -0
  39. package/lib/Types/Label.js +25 -0
  40. package/lib/Types/LabelAssociation.js +7 -0
  41. package/lib/Types/Message.js +11 -0
  42. package/lib/Types/Newsletter.js +31 -0
  43. package/lib/Types/Product.js +2 -0
  44. package/lib/Types/Signal.js +2 -0
  45. package/lib/Types/Socket.js +3 -0
  46. package/lib/Types/State.js +13 -0
  47. package/lib/Types/USync.js +2 -0
  48. package/lib/Types/index.js +32 -0
  49. package/lib/Utils/auth-utils.js +276 -0
  50. package/lib/Utils/browser-utils.js +32 -0
  51. package/lib/Utils/business.js +262 -0
  52. package/lib/Utils/chat-utils.js +941 -0
  53. package/lib/Utils/crypto.js +179 -0
  54. package/lib/Utils/decode-wa-message.js +333 -0
  55. package/lib/Utils/event-buffer.js +580 -0
  56. package/lib/Utils/generics.js +436 -0
  57. package/lib/Utils/history.js +103 -0
  58. package/lib/Utils/index.js +19 -0
  59. package/lib/Utils/link-preview.js +105 -0
  60. package/lib/Utils/logger.js +3 -0
  61. package/lib/Utils/lt-hash.js +56 -0
  62. package/lib/Utils/make-mutex.js +38 -0
  63. package/lib/Utils/message-retry-manager.js +181 -0
  64. package/lib/Utils/messages-media.js +727 -0
  65. package/lib/Utils/messages.js +1309 -0
  66. package/lib/Utils/noise-handler.js +162 -0
  67. package/lib/Utils/pre-key-manager.js +125 -0
  68. package/lib/Utils/process-message.js +594 -0
  69. package/lib/Utils/signal.js +194 -0
  70. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  71. package/lib/Utils/validate-connection.js +240 -0
  72. package/lib/WABinary/constants.js +1301 -0
  73. package/lib/WABinary/decode.js +240 -0
  74. package/lib/WABinary/encode.js +216 -0
  75. package/lib/WABinary/generic-utils.js +104 -0
  76. package/lib/WABinary/index.js +6 -0
  77. package/lib/WABinary/jid-utils.js +95 -0
  78. package/lib/WABinary/types.js +2 -0
  79. package/lib/WAM/BinaryInfo.js +10 -0
  80. package/lib/WAM/constants.js +22863 -0
  81. package/lib/WAM/encode.js +152 -0
  82. package/lib/WAM/index.js +4 -0
  83. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  84. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  85. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  86. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +36 -0
  87. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +60 -0
  88. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  89. package/lib/WAUSync/Protocols/index.js +5 -0
  90. package/lib/WAUSync/USyncQuery.js +104 -0
  91. package/lib/WAUSync/USyncUser.js +23 -0
  92. package/lib/WAUSync/index.js +4 -0
  93. package/lib/index.js +11 -0
  94. package/package.json +31 -0
  95. package/readme.md +522 -0
@@ -0,0 +1,105 @@
1
+ import { SenderChainKey } from "./sender-chain-key.js";
2
+ import { SenderMessageKey } from "./sender-message-key.js";
3
+ export class SenderKeyState {
4
+ constructor(
5
+ id,
6
+ iteration,
7
+ chainKey,
8
+ signatureKeyPair,
9
+ signatureKeyPublic,
10
+ signatureKeyPrivate,
11
+ senderKeyStateStructure,
12
+ ) {
13
+ this.MAX_MESSAGE_KEYS = 2000;
14
+ if (senderKeyStateStructure) {
15
+ this.senderKeyStateStructure = {
16
+ ...senderKeyStateStructure,
17
+ senderMessageKeys: Array.isArray(
18
+ senderKeyStateStructure.senderMessageKeys,
19
+ )
20
+ ? senderKeyStateStructure.senderMessageKeys
21
+ : [],
22
+ };
23
+ } else {
24
+ if (signatureKeyPair) {
25
+ signatureKeyPublic = signatureKeyPair.public;
26
+ signatureKeyPrivate = signatureKeyPair.private;
27
+ }
28
+ this.senderKeyStateStructure = {
29
+ senderKeyId: id || 0,
30
+ senderChainKey: {
31
+ iteration: iteration || 0,
32
+ seed: Buffer.from(chainKey || []),
33
+ },
34
+ senderSigningKey: {
35
+ public: Buffer.from(signatureKeyPublic || []),
36
+ private: Buffer.from(signatureKeyPrivate || []),
37
+ },
38
+ senderMessageKeys: [],
39
+ };
40
+ }
41
+ }
42
+ getKeyId() {
43
+ return this.senderKeyStateStructure.senderKeyId;
44
+ }
45
+ getSenderChainKey() {
46
+ return new SenderChainKey(
47
+ this.senderKeyStateStructure.senderChainKey.iteration,
48
+ this.senderKeyStateStructure.senderChainKey.seed,
49
+ );
50
+ }
51
+ setSenderChainKey(chainKey) {
52
+ this.senderKeyStateStructure.senderChainKey = {
53
+ iteration: chainKey.getIteration(),
54
+ seed: chainKey.getSeed(),
55
+ };
56
+ }
57
+ getSigningKeyPublic() {
58
+ const publicKey = Buffer.from(
59
+ this.senderKeyStateStructure.senderSigningKey.public,
60
+ );
61
+ if (publicKey.length === 32) {
62
+ const fixed = Buffer.alloc(33);
63
+ fixed[0] = 0x05;
64
+ publicKey.copy(fixed, 1);
65
+ return fixed;
66
+ }
67
+ return publicKey;
68
+ }
69
+ getSigningKeyPrivate() {
70
+ const privateKey = this.senderKeyStateStructure.senderSigningKey.private;
71
+ return Buffer.from(privateKey || []);
72
+ }
73
+ hasSenderMessageKey(iteration) {
74
+ return this.senderKeyStateStructure.senderMessageKeys.some(
75
+ (key) => key.iteration === iteration,
76
+ );
77
+ }
78
+ addSenderMessageKey(senderMessageKey) {
79
+ this.senderKeyStateStructure.senderMessageKeys.push({
80
+ iteration: senderMessageKey.getIteration(),
81
+ seed: senderMessageKey.getSeed(),
82
+ });
83
+ if (
84
+ this.senderKeyStateStructure.senderMessageKeys.length >
85
+ this.MAX_MESSAGE_KEYS
86
+ ) {
87
+ this.senderKeyStateStructure.senderMessageKeys.shift();
88
+ }
89
+ }
90
+ removeSenderMessageKey(iteration) {
91
+ const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(
92
+ (key) => key.iteration === iteration,
93
+ );
94
+ if (index !== -1) {
95
+ const messageKey = this.senderKeyStateStructure.senderMessageKeys[index];
96
+ this.senderKeyStateStructure.senderMessageKeys.splice(index, 1);
97
+ return new SenderMessageKey(messageKey.iteration, messageKey.seed);
98
+ }
99
+ return null;
100
+ }
101
+ getStructure() {
102
+ return this.senderKeyStateStructure;
103
+ }
104
+ }
105
+ //# sourceMappingURL=sender-key-state.js.map
@@ -0,0 +1,30 @@
1
+ import { deriveSecrets } from "libsignal/src/crypto.js";
2
+ export class SenderMessageKey {
3
+ constructor(iteration, seed) {
4
+ const derivative = deriveSecrets(
5
+ seed,
6
+ Buffer.alloc(32),
7
+ Buffer.from("WhisperGroup"),
8
+ );
9
+ const keys = new Uint8Array(32);
10
+ keys.set(new Uint8Array(derivative[0].slice(16)));
11
+ keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
12
+ this.iv = Buffer.from(derivative[0].slice(0, 16));
13
+ this.cipherKey = Buffer.from(keys.buffer);
14
+ this.iteration = iteration;
15
+ this.seed = seed;
16
+ }
17
+ getIteration() {
18
+ return this.iteration;
19
+ }
20
+ getIv() {
21
+ return this.iv;
22
+ }
23
+ getCipherKey() {
24
+ return this.cipherKey;
25
+ }
26
+ getSeed() {
27
+ return this.seed;
28
+ }
29
+ }
30
+ //# sourceMappingURL=sender-message-key.js.map
@@ -0,0 +1,416 @@
1
+ /* @ts-ignore */
2
+ import * as libsignal from "libsignal";
3
+ import { LRUCache } from "lru-cache";
4
+ import { generateSignalPubKey } from "../Utils/index.js";
5
+ import {
6
+ isHostedLidUser,
7
+ isHostedPnUser,
8
+ isLidUser,
9
+ isPnUser,
10
+ jidDecode,
11
+ transferDevice,
12
+ WAJIDDomains,
13
+ } from "../WABinary/index.js";
14
+ import { SenderKeyName } from "./Group/sender-key-name.js";
15
+ import { SenderKeyRecord } from "./Group/sender-key-record.js";
16
+ import {
17
+ GroupCipher,
18
+ GroupSessionBuilder,
19
+ SenderKeyDistributionMessage,
20
+ } from "./Group/index.js";
21
+ import { LIDMappingStore } from "./lid-mapping.js";
22
+ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
23
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
24
+ const storage = signalStorage(auth, lidMapping);
25
+ const parsedKeys = auth.keys;
26
+ const migratedSessionCache = new LRUCache({
27
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
28
+ ttlAutopurge: true,
29
+ updateAgeOnGet: true,
30
+ });
31
+ const repository = {
32
+ decryptGroupMessage({ group, authorJid, msg }) {
33
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
34
+ const cipher = new GroupCipher(storage, senderName);
35
+ // Use transaction to ensure atomicity
36
+ return parsedKeys.transaction(async () => {
37
+ return cipher.decrypt(msg);
38
+ }, group);
39
+ },
40
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
41
+ const builder = new GroupSessionBuilder(storage);
42
+ if (!item.groupId) {
43
+ throw new Error(
44
+ "Group ID is required for sender key distribution message",
45
+ );
46
+ }
47
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
48
+ const senderMsg = new SenderKeyDistributionMessage(
49
+ null,
50
+ null,
51
+ null,
52
+ null,
53
+ item.axolotlSenderKeyDistributionMessage,
54
+ );
55
+ const senderNameStr = senderName.toString();
56
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [
57
+ senderNameStr,
58
+ ]);
59
+ if (!senderKey) {
60
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
61
+ }
62
+ return parsedKeys.transaction(async () => {
63
+ const { [senderNameStr]: senderKey } = await auth.keys.get(
64
+ "sender-key",
65
+ [senderNameStr],
66
+ );
67
+ if (!senderKey) {
68
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
69
+ }
70
+ await builder.process(senderName, senderMsg);
71
+ }, item.groupId);
72
+ },
73
+ async decryptMessage({ jid, type, ciphertext }) {
74
+ const addr = jidToSignalProtocolAddress(jid);
75
+ const session = new libsignal.SessionCipher(storage, addr);
76
+ async function doDecrypt() {
77
+ let result;
78
+ switch (type) {
79
+ case "pkmsg":
80
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
81
+ break;
82
+ case "msg":
83
+ result = await session.decryptWhisperMessage(ciphertext);
84
+ break;
85
+ }
86
+ return result;
87
+ }
88
+ // If it's not a sync message, we need to ensure atomicity
89
+ // For regular messages, we use a transaction to ensure atomicity
90
+ return parsedKeys.transaction(async () => {
91
+ return await doDecrypt();
92
+ }, jid);
93
+ },
94
+ async encryptMessage({ jid, data }) {
95
+ const addr = jidToSignalProtocolAddress(jid);
96
+ const cipher = new libsignal.SessionCipher(storage, addr);
97
+ // Use transaction to ensure atomicity
98
+ return parsedKeys.transaction(async () => {
99
+ const { type: sigType, body } = await cipher.encrypt(data);
100
+ const type = sigType === 3 ? "pkmsg" : "msg";
101
+ return { type, ciphertext: Buffer.from(body, "binary") };
102
+ }, jid);
103
+ },
104
+ async encryptGroupMessage({ group, meId, data }) {
105
+ const senderName = jidToSignalSenderKeyName(group, meId);
106
+ const builder = new GroupSessionBuilder(storage);
107
+ const senderNameStr = senderName.toString();
108
+ return parsedKeys.transaction(async () => {
109
+ const { [senderNameStr]: senderKey } = await auth.keys.get(
110
+ "sender-key",
111
+ [senderNameStr],
112
+ );
113
+ if (!senderKey) {
114
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
115
+ }
116
+ const senderKeyDistributionMessage = await builder.create(senderName);
117
+ const session = new GroupCipher(storage, senderName);
118
+ const ciphertext = await session.encrypt(data);
119
+ return {
120
+ ciphertext,
121
+ senderKeyDistributionMessage:
122
+ senderKeyDistributionMessage.serialize(),
123
+ };
124
+ }, group);
125
+ },
126
+ async injectE2ESession({ jid, session }) {
127
+ logger.trace({ jid }, "injecting E2EE session");
128
+ const cipher = new libsignal.SessionBuilder(
129
+ storage,
130
+ jidToSignalProtocolAddress(jid),
131
+ );
132
+ return parsedKeys.transaction(async () => {
133
+ await cipher.initOutgoing(session);
134
+ }, jid);
135
+ },
136
+ jidToSignalProtocolAddress(jid) {
137
+ return jidToSignalProtocolAddress(jid).toString();
138
+ },
139
+ // Optimized direct access to LID mapping store
140
+ lidMapping,
141
+ async validateSession(jid) {
142
+ try {
143
+ const addr = jidToSignalProtocolAddress(jid);
144
+ const session = await storage.loadSession(addr.toString());
145
+ if (!session) {
146
+ return { exists: false, reason: "no session" };
147
+ }
148
+ if (!session.haveOpenSession()) {
149
+ return { exists: false, reason: "no open session" };
150
+ }
151
+ return { exists: true };
152
+ } catch (error) {
153
+ return { exists: false, reason: "validation error" };
154
+ }
155
+ },
156
+ async deleteSession(jids) {
157
+ if (!jids.length) return;
158
+ // Convert JIDs to signal addresses and prepare for bulk deletion
159
+ const sessionUpdates = {};
160
+ jids.forEach((jid) => {
161
+ const addr = jidToSignalProtocolAddress(jid);
162
+ sessionUpdates[addr.toString()] = null;
163
+ });
164
+ // Single transaction for all deletions
165
+ return parsedKeys.transaction(async () => {
166
+ await auth.keys.set({ session: sessionUpdates });
167
+ }, `delete-${jids.length}-sessions`);
168
+ },
169
+ async migrateSession(fromJid, toJid) {
170
+ // TODO: use usync to handle this entire mess
171
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
172
+ return { migrated: 0, skipped: 0, total: 0 };
173
+ // Only support PN to LID migration
174
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
175
+ return { migrated: 0, skipped: 0, total: 1 };
176
+ }
177
+ const { user } = jidDecode(fromJid);
178
+ logger.debug(
179
+ { fromJid },
180
+ "bulk device migration - loading all user devices",
181
+ );
182
+ // Get user's device list from storage
183
+ const { [user]: userDevices } = await parsedKeys.get("device-list", [
184
+ user,
185
+ ]);
186
+ if (!userDevices) {
187
+ return { migrated: 0, skipped: 0, total: 0 };
188
+ }
189
+ const { device: fromDevice } = jidDecode(fromJid);
190
+ const fromDeviceStr = fromDevice?.toString() || "0";
191
+ if (!userDevices.includes(fromDeviceStr)) {
192
+ userDevices.push(fromDeviceStr);
193
+ }
194
+ // Filter out cached devices before database fetch
195
+ const uncachedDevices = userDevices.filter((device) => {
196
+ const deviceKey = `${user}.${device}`;
197
+ return !migratedSessionCache.has(deviceKey);
198
+ });
199
+ // Bulk check session existence only for uncached devices
200
+ const deviceSessionKeys = uncachedDevices.map(
201
+ (device) => `${user}.${device}`,
202
+ );
203
+ const existingSessions = await parsedKeys.get(
204
+ "session",
205
+ deviceSessionKeys,
206
+ );
207
+ // Step 3: Convert existing sessions to JIDs (only migrate sessions that exist)
208
+ const deviceJids = [];
209
+ for (const [sessionKey, sessionData] of Object.entries(
210
+ existingSessions,
211
+ )) {
212
+ if (sessionData) {
213
+ // Session exists in storage
214
+ const deviceStr = sessionKey.split(".")[1];
215
+ if (!deviceStr) continue;
216
+ const deviceNum = parseInt(deviceStr);
217
+ let jid =
218
+ deviceNum === 0
219
+ ? `${user}@s.whatsapp.net`
220
+ : `${user}:${deviceNum}@s.whatsapp.net`;
221
+ if (deviceNum === 99) {
222
+ jid = `${user}:99@hosted`;
223
+ }
224
+ deviceJids.push(jid);
225
+ }
226
+ }
227
+ logger.debug(
228
+ {
229
+ fromJid,
230
+ totalDevices: userDevices.length,
231
+ devicesWithSessions: deviceJids.length,
232
+ devices: deviceJids,
233
+ },
234
+ "bulk device migration complete - all user devices processed",
235
+ );
236
+ // Single transaction for all migrations
237
+ return parsedKeys.transaction(
238
+ async () => {
239
+ const migrationOps = deviceJids.map((jid) => {
240
+ const lidWithDevice = transferDevice(jid, toJid);
241
+ const fromDecoded = jidDecode(jid);
242
+ const toDecoded = jidDecode(lidWithDevice);
243
+ return {
244
+ fromJid: jid,
245
+ toJid: lidWithDevice,
246
+ pnUser: fromDecoded.user,
247
+ lidUser: toDecoded.user,
248
+ deviceId: fromDecoded.device || 0,
249
+ fromAddr: jidToSignalProtocolAddress(jid),
250
+ toAddr: jidToSignalProtocolAddress(lidWithDevice),
251
+ };
252
+ });
253
+ const totalOps = migrationOps.length;
254
+ let migratedCount = 0;
255
+ // Bulk fetch PN sessions - already exist (verified during device discovery)
256
+ const pnAddrStrings = Array.from(
257
+ new Set(migrationOps.map((op) => op.fromAddr.toString())),
258
+ );
259
+ const pnSessions = await parsedKeys.get("session", pnAddrStrings);
260
+ // Prepare bulk session updates (PN → LID migration + deletion)
261
+ const sessionUpdates = {};
262
+ for (const op of migrationOps) {
263
+ const pnAddrStr = op.fromAddr.toString();
264
+ const lidAddrStr = op.toAddr.toString();
265
+ const pnSession = pnSessions[pnAddrStr];
266
+ if (pnSession) {
267
+ // Session exists (guaranteed from device discovery)
268
+ const fromSession =
269
+ libsignal.SessionRecord.deserialize(pnSession);
270
+ if (fromSession.haveOpenSession()) {
271
+ // Queue for bulk update: copy to LID, delete from PN
272
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
273
+ sessionUpdates[pnAddrStr] = null;
274
+ migratedCount++;
275
+ }
276
+ }
277
+ }
278
+ // Single bulk session update for all migrations
279
+ if (Object.keys(sessionUpdates).length > 0) {
280
+ await parsedKeys.set({ session: sessionUpdates });
281
+ logger.debug(
282
+ { migratedSessions: migratedCount },
283
+ "bulk session migration complete",
284
+ );
285
+ // Cache device-level migrations
286
+ for (const op of migrationOps) {
287
+ if (sessionUpdates[op.toAddr.toString()]) {
288
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
289
+ migratedSessionCache.set(deviceKey, true);
290
+ }
291
+ }
292
+ }
293
+ const skippedCount = totalOps - migratedCount;
294
+ return {
295
+ migrated: migratedCount,
296
+ skipped: skippedCount,
297
+ total: totalOps,
298
+ };
299
+ },
300
+ `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`,
301
+ );
302
+ },
303
+ };
304
+ return repository;
305
+ }
306
+ const jidToSignalProtocolAddress = (jid) => {
307
+ const decoded = jidDecode(jid);
308
+ const { user, device, server, domainType } = decoded;
309
+ if (!user) {
310
+ throw new Error(
311
+ `JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`,
312
+ );
313
+ }
314
+ const signalUser =
315
+ domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
316
+ const finalDevice = device || 0;
317
+ if (
318
+ device === 99 &&
319
+ decoded.server !== "hosted" &&
320
+ decoded.server !== "hosted.lid"
321
+ ) {
322
+ throw new Error(
323
+ "Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:" +
324
+ jid,
325
+ );
326
+ }
327
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
328
+ };
329
+ const jidToSignalSenderKeyName = (group, user) => {
330
+ return new SenderKeyName(group, jidToSignalProtocolAddress(user));
331
+ };
332
+ function signalStorage({ creds, keys }, lidMapping) {
333
+ // Shared function to resolve PN signal address to LID if mapping exists
334
+ const resolveLIDSignalAddress = async (id) => {
335
+ if (id.includes(".")) {
336
+ const [deviceId, device] = id.split(".");
337
+ const [user, domainType_] = deviceId.split("_");
338
+ const domainType = parseInt(domainType_ || "0");
339
+ if (
340
+ domainType === WAJIDDomains.LID ||
341
+ domainType === WAJIDDomains.HOSTED_LID
342
+ )
343
+ return id;
344
+ const pnJid = `${user}${device !== "0" ? `:${device}` : ""}@${domainType === WAJIDDomains.HOSTED ? "hosted" : "s.whatsapp.net"}`;
345
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
346
+ if (lidForPN) {
347
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
348
+ return lidAddr.toString();
349
+ }
350
+ }
351
+ return id;
352
+ };
353
+ return {
354
+ loadSession: async (id) => {
355
+ try {
356
+ const wireJid = await resolveLIDSignalAddress(id);
357
+ const { [wireJid]: sess } = await keys.get("session", [wireJid]);
358
+ if (sess) {
359
+ return libsignal.SessionRecord.deserialize(sess);
360
+ }
361
+ } catch (e) {
362
+ return null;
363
+ }
364
+ return null;
365
+ },
366
+ storeSession: async (id, session) => {
367
+ const wireJid = await resolveLIDSignalAddress(id);
368
+ await keys.set({ session: { [wireJid]: session.serialize() } });
369
+ },
370
+ isTrustedIdentity: () => {
371
+ return true; // todo: implement
372
+ },
373
+ loadPreKey: async (id) => {
374
+ const keyId = id.toString();
375
+ const { [keyId]: key } = await keys.get("pre-key", [keyId]);
376
+ if (key) {
377
+ return {
378
+ privKey: Buffer.from(key.private),
379
+ pubKey: Buffer.from(key.public),
380
+ };
381
+ }
382
+ },
383
+ removePreKey: (id) => keys.set({ "pre-key": { [id]: null } }),
384
+ loadSignedPreKey: () => {
385
+ const key = creds.signedPreKey;
386
+ return {
387
+ privKey: Buffer.from(key.keyPair.private),
388
+ pubKey: Buffer.from(key.keyPair.public),
389
+ };
390
+ },
391
+ loadSenderKey: async (senderKeyName) => {
392
+ const keyId = senderKeyName.toString();
393
+ const { [keyId]: key } = await keys.get("sender-key", [keyId]);
394
+ if (key) {
395
+ return SenderKeyRecord.deserialize(key);
396
+ }
397
+ return new SenderKeyRecord();
398
+ },
399
+ storeSenderKey: async (senderKeyName, key) => {
400
+ const keyId = senderKeyName.toString();
401
+ const serialized = JSON.stringify(key.serialize());
402
+ await keys.set({
403
+ "sender-key": { [keyId]: Buffer.from(serialized, "utf-8") },
404
+ });
405
+ },
406
+ getOurRegistrationId: () => creds.registrationId,
407
+ getOurIdentity: () => {
408
+ const { signedIdentityKey } = creds;
409
+ return {
410
+ privKey: Buffer.from(signedIdentityKey.private),
411
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public)),
412
+ };
413
+ },
414
+ };
415
+ }
416
+ //# sourceMappingURL=libsignal.js.map