@prototypevip/baileys 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.
Files changed (118) hide show
  1. package/LICENSE +23 -0
  2. package/WAProto/index.js +131118 -0
  3. package/engine-requirements.js +1 -0
  4. package/lib/Defaults/index.js +187 -0
  5. package/lib/Signal/Group/ciphertext-message.js +11 -0
  6. package/lib/Signal/Group/group-session-builder.js +41 -0
  7. package/lib/Signal/Group/group_cipher.js +108 -0
  8. package/lib/Signal/Group/index.js +11 -0
  9. package/lib/Signal/Group/keyhelper.js +14 -0
  10. package/lib/Signal/Group/sender-chain-key.js +31 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  12. package/lib/Signal/Group/sender-key-message.js +79 -0
  13. package/lib/Signal/Group/sender-key-name.js +49 -0
  14. package/lib/Signal/Group/sender-key-record.js +46 -0
  15. package/lib/Signal/Group/sender-key-state.js +104 -0
  16. package/lib/Signal/Group/sender-message-key.js +29 -0
  17. package/lib/Signal/libsignal.js +532 -0
  18. package/lib/Signal/lid-mapping.js +312 -0
  19. package/lib/Socket/Client/index.js +2 -0
  20. package/lib/Socket/Client/types.js +10 -0
  21. package/lib/Socket/Client/websocket.js +64 -0
  22. package/lib/Socket/business.js +293 -0
  23. package/lib/Socket/chats.js +1124 -0
  24. package/lib/Socket/communities.js +528 -0
  25. package/lib/Socket/groups.js +465 -0
  26. package/lib/Socket/index.js +14 -0
  27. package/lib/Socket/messages-recv.js +2325 -0
  28. package/lib/Socket/messages-send.js +1746 -0
  29. package/lib/Socket/mex.js +55 -0
  30. package/lib/Socket/newsletter.js +317 -0
  31. package/lib/Socket/socket.js +1185 -0
  32. package/lib/Store/cache-factory.js +20 -0
  33. package/lib/Store/index.js +5 -0
  34. package/lib/Store/make-in-memory-store.js +523 -0
  35. package/lib/Store/make-ordered-dictionary.js +203 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Store/prototype-store.js +958 -0
  38. package/lib/Types/Auth.js +1 -0
  39. package/lib/Types/Bussines.js +1 -0
  40. package/lib/Types/Call.js +1 -0
  41. package/lib/Types/Chat.js +7 -0
  42. package/lib/Types/Contact.js +1 -0
  43. package/lib/Types/Events.js +1 -0
  44. package/lib/Types/GroupMetadata.js +1 -0
  45. package/lib/Types/Label.js +24 -0
  46. package/lib/Types/LabelAssociation.js +6 -0
  47. package/lib/Types/Message.js +18 -0
  48. package/lib/Types/Mex.js +37 -0
  49. package/lib/Types/Newsletter.js +36 -0
  50. package/lib/Types/Product.js +1 -0
  51. package/lib/Types/RichType.js +25 -0
  52. package/lib/Types/Signal.js +1 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +78 -0
  55. package/lib/Types/USync.js +1 -0
  56. package/lib/Types/index.js +33 -0
  57. package/lib/Utils/auth-utils.js +303 -0
  58. package/lib/Utils/browser-utils.js +32 -0
  59. package/lib/Utils/business.js +245 -0
  60. package/lib/Utils/chat-utils.js +971 -0
  61. package/lib/Utils/companion-reg-client-utils.js +54 -0
  62. package/lib/Utils/constants.js +24 -0
  63. package/lib/Utils/crypto.js +133 -0
  64. package/lib/Utils/cstoken-utils.js +41 -0
  65. package/lib/Utils/decode-wa-message.js +406 -0
  66. package/lib/Utils/event-buffer.js +616 -0
  67. package/lib/Utils/generics.js +438 -0
  68. package/lib/Utils/history.js +147 -0
  69. package/lib/Utils/identity-change-handler.js +63 -0
  70. package/lib/Utils/index.js +29 -0
  71. package/lib/Utils/interactive-message-handler.js +478 -0
  72. package/lib/Utils/link-preview.js +91 -0
  73. package/lib/Utils/logger.js +2 -0
  74. package/lib/Utils/lt-hash.js +6 -0
  75. package/lib/Utils/make-mutex.js +31 -0
  76. package/lib/Utils/message-retry-manager.js +291 -0
  77. package/lib/Utils/messages-media.js +881 -0
  78. package/lib/Utils/messages.js +1434 -0
  79. package/lib/Utils/noise-handler.js +229 -0
  80. package/lib/Utils/normalize-message-identity.js +73 -0
  81. package/lib/Utils/offline-node-processor.js +50 -0
  82. package/lib/Utils/pre-key-manager.js +119 -0
  83. package/lib/Utils/process-message.js +648 -0
  84. package/lib/Utils/reporting-utils.js +355 -0
  85. package/lib/Utils/rich-message-utils.js +264 -0
  86. package/lib/Utils/signal.js +233 -0
  87. package/lib/Utils/stanza-ack.js +33 -0
  88. package/lib/Utils/sticker-utils.js +221 -0
  89. package/lib/Utils/sync-action-utils.js +53 -0
  90. package/lib/Utils/tc-token-utils.js +182 -0
  91. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  92. package/lib/Utils/use-prototype-auth-state.js +217 -0
  93. package/lib/Utils/use-single-file-auth-state.js +94 -0
  94. package/lib/Utils/validate-connection.js +235 -0
  95. package/lib/WABinary/constants.js +1468 -0
  96. package/lib/WABinary/decode.js +258 -0
  97. package/lib/WABinary/encode.js +219 -0
  98. package/lib/WABinary/generic-utils.js +202 -0
  99. package/lib/WABinary/index.js +5 -0
  100. package/lib/WABinary/jid-utils.js +94 -0
  101. package/lib/WABinary/types.js +1 -0
  102. package/lib/WAM/BinaryInfo.js +9 -0
  103. package/lib/WAM/constants.js +20669 -0
  104. package/lib/WAM/encode.js +151 -0
  105. package/lib/WAM/index.js +3 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  113. package/lib/WAUSync/Protocols/index.js +4 -0
  114. package/lib/WAUSync/USyncQuery.js +133 -0
  115. package/lib/WAUSync/USyncUser.js +22 -0
  116. package/lib/WAUSync/index.js +3 -0
  117. package/lib/index.js +12 -0
  118. package/package.json +78 -0
@@ -0,0 +1,104 @@
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 = 2e3;
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] = 5;
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
+ }
@@ -0,0 +1,29 @@
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
+ }
@@ -0,0 +1,532 @@
1
+ // @ts-ignore
2
+ import * as libsignal from "libsignal";
3
+ // @ts-ignore
4
+ import { PreKeyWhisperMessage } from "libsignal/src/protobufs.js";
5
+ import { LRUCache } from "lru-cache";
6
+ import { generateSignalPubKey } from "../Utils/index.js";
7
+ import {
8
+ isHostedLidUser,
9
+ isHostedPnUser,
10
+ isLidUser,
11
+ isPnUser,
12
+ jidDecode,
13
+ transferDevice,
14
+ WAJIDDomains,
15
+ } from "../WABinary/index.js";
16
+ import { SenderKeyName } from "./Group/sender-key-name.js";
17
+ import { SenderKeyRecord } from "./Group/sender-key-record.js";
18
+ import {
19
+ GroupCipher,
20
+ GroupSessionBuilder,
21
+ SenderKeyDistributionMessage,
22
+ } from "./Group/index.js";
23
+ import { LIDMappingStore } from "./lid-mapping.js";
24
+ /** Extract identity key from PreKeyWhisperMessage for identity change detection */ function extractIdentityFromPkmsg(
25
+ ciphertext,
26
+ ) {
27
+ try {
28
+ if (!ciphertext || ciphertext.length < 2) {
29
+ return undefined;
30
+ }
31
+ // Version byte check (version 3)
32
+ const version = ciphertext[0];
33
+ if ((version & 15) !== 3) {
34
+ return undefined;
35
+ }
36
+ // Parse protobuf (skip version byte)
37
+ const preKeyProto = PreKeyWhisperMessage.decode(ciphertext.slice(1));
38
+ if (preKeyProto.identityKey?.length === 33) {
39
+ return new Uint8Array(preKeyProto.identityKey);
40
+ }
41
+ return undefined;
42
+ } catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ export function makeLibSignalRepository(
47
+ auth,
48
+ logger,
49
+ pnToLIDFunc,
50
+ fetchDevices,
51
+ ) {
52
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
53
+ const storage = signalStorage(auth, lidMapping);
54
+ const parsedKeys = auth.keys;
55
+ const migratedSessionCache = new LRUCache({
56
+ ttl: 3 * 24 * 60 * 60 * 1e3, // 7 days
57
+ ttlAutopurge: true,
58
+ updateAgeOnGet: true,
59
+ });
60
+ const repository = {
61
+ decryptGroupMessage({ group, authorJid, msg }) {
62
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
63
+ const cipher = new GroupCipher(storage, senderName);
64
+ // Use transaction to ensure atomicity
65
+ return parsedKeys.transaction(async () => {
66
+ return cipher.decrypt(msg);
67
+ }, group);
68
+ },
69
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
70
+ const builder = new GroupSessionBuilder(storage);
71
+ if (!item.groupId) {
72
+ throw new Error(
73
+ "Group ID is required for sender key distribution message",
74
+ );
75
+ }
76
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
77
+ const senderMsg = new SenderKeyDistributionMessage(
78
+ null,
79
+ null,
80
+ null,
81
+ null,
82
+ item.axolotlSenderKeyDistributionMessage,
83
+ );
84
+ const senderNameStr = senderName.toString();
85
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [
86
+ senderNameStr,
87
+ ]);
88
+ if (!senderKey) {
89
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
90
+ }
91
+ return parsedKeys.transaction(async () => {
92
+ const { [senderNameStr]: senderKey } = await auth.keys.get(
93
+ "sender-key",
94
+ [senderNameStr],
95
+ );
96
+ if (!senderKey) {
97
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
98
+ }
99
+ await builder.process(senderName, senderMsg);
100
+ }, item.groupId);
101
+ },
102
+ async decryptMessage({ jid, type, ciphertext }) {
103
+ const addr = jidToSignalProtocolAddress(jid);
104
+ const session = new libsignal.SessionCipher(storage, addr);
105
+
106
+ if (type === "pkmsg") {
107
+ const identityKey = extractIdentityFromPkmsg(ciphertext);
108
+ if (identityKey) {
109
+ const addrStr = addr.toString();
110
+ const identityChanged = await storage.saveIdentity(
111
+ addrStr,
112
+ identityKey,
113
+ );
114
+ if (identityChanged) {
115
+ logger.info(
116
+ { jid: jid, addr: addrStr },
117
+ "Identity key changed or new contact, session will be re-established",
118
+ );
119
+ }
120
+ }
121
+ }
122
+
123
+ async function doDecrypt() {
124
+ switch (type) {
125
+ case "pkmsg":
126
+ return await session.decryptPreKeyWhisperMessage(ciphertext);
127
+ case "msg":
128
+ return await session.decryptWhisperMessage(ciphertext);
129
+ }
130
+ }
131
+
132
+ return parsedKeys.transaction(async () => {
133
+ let retried = false;
134
+
135
+ while (true) {
136
+ try {
137
+ return await doDecrypt();
138
+ } catch (err) {
139
+ if (err?.name === "MessageCounterError") {
140
+ if (retried) {
141
+ logger.error(
142
+ { jid, err },
143
+ "MessageCounterError retry already attempted, throwing error",
144
+ );
145
+ throw err;
146
+ }
147
+ retried = true;
148
+ logger.warn(
149
+ { jid },
150
+ "MessageCounterError detected, deleting session and retrying",
151
+ );
152
+ try {
153
+ await repository.deleteSession([jid]);
154
+ logger.info({ jid }, "Session deleted, retrying decryption");
155
+ } catch (deleteErr) {
156
+ logger.error(
157
+ { jid, deleteErr },
158
+ "Failed to delete session during retry",
159
+ );
160
+ throw deleteErr;
161
+ }
162
+ } else {
163
+ throw err;
164
+ }
165
+ }
166
+ }
167
+ }, jid);
168
+ },
169
+
170
+ async encryptMessage({ jid, data }) {
171
+ const addr = jidToSignalProtocolAddress(jid);
172
+ const cipher = new libsignal.SessionCipher(storage, addr);
173
+ // Use transaction to ensure atomicity
174
+ return parsedKeys.transaction(async () => {
175
+ const { type: sigType, body } = await cipher.encrypt(data);
176
+ const type = sigType === 3 ? "pkmsg" : "msg";
177
+ return { type: type, ciphertext: Buffer.from(body, "binary") };
178
+ }, jid);
179
+ },
180
+ async encryptGroupMessage({ group, meId, data }) {
181
+ const senderName = jidToSignalSenderKeyName(group, meId);
182
+ const builder = new GroupSessionBuilder(storage);
183
+ const senderNameStr = senderName.toString();
184
+ return parsedKeys.transaction(async () => {
185
+ const { [senderNameStr]: senderKey } = await auth.keys.get(
186
+ "sender-key",
187
+ [senderNameStr],
188
+ );
189
+ if (!senderKey) {
190
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
191
+ }
192
+ const senderKeyDistributionMessage = await builder.create(senderName);
193
+ const session = new GroupCipher(storage, senderName);
194
+ const ciphertext = await session.encrypt(data);
195
+ return {
196
+ ciphertext: ciphertext,
197
+ senderKeyDistributionMessage:
198
+ senderKeyDistributionMessage.serialize(),
199
+ };
200
+ }, group);
201
+ },
202
+ async injectE2ESession({ jid, session }) {
203
+ logger.trace({ jid: jid }, "injecting E2EE session");
204
+ const cipher = new libsignal.SessionBuilder(
205
+ storage,
206
+ jidToSignalProtocolAddress(jid),
207
+ );
208
+ return parsedKeys.transaction(async () => {
209
+ await cipher.initOutgoing(session);
210
+ }, jid);
211
+ },
212
+ jidToSignalProtocolAddress(jid) {
213
+ return jidToSignalProtocolAddress(jid).toString();
214
+ },
215
+ // Optimized direct access to LID mapping store
216
+ lidMapping: lidMapping,
217
+ async validateSession(jid) {
218
+ try {
219
+ const addr = jidToSignalProtocolAddress(jid);
220
+ const session = await storage.loadSession(addr.toString());
221
+ if (!session) {
222
+ return { exists: false, reason: "no session" };
223
+ }
224
+ if (!session.haveOpenSession()) {
225
+ return { exists: false, reason: "no open session" };
226
+ }
227
+ return { exists: true };
228
+ } catch (error) {
229
+ return { exists: false, reason: "validation error" };
230
+ }
231
+ },
232
+ async deleteSession(jids) {
233
+ if (!jids.length) return;
234
+ // Convert JIDs to signal addresses and prepare for bulk deletion
235
+ const sessionUpdates = {};
236
+ jids.forEach((jid) => {
237
+ const addr = jidToSignalProtocolAddress(jid);
238
+ sessionUpdates[addr.toString()] = null;
239
+ });
240
+ // Single transaction for all deletions
241
+ return parsedKeys.transaction(async () => {
242
+ await auth.keys.set({ session: sessionUpdates });
243
+ }, `delete-${jids.length}-sessions`);
244
+ },
245
+ async migrateSession(fromJid, toJid) {
246
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
247
+ return { migrated: 0, skipped: 0, total: 0 };
248
+ // Only support PN to LID migration
249
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
250
+ return { migrated: 0, skipped: 0, total: 1 };
251
+ }
252
+ const { user } = jidDecode(fromJid);
253
+ logger.debug(
254
+ { fromJid: fromJid },
255
+ "bulk device migration - loading all user devices",
256
+ );
257
+
258
+ let deviceJids = [];
259
+ if (fetchDevices) {
260
+ deviceJids = await fetchDevices([fromJid]);
261
+ } else {
262
+ // Get user's device list from storage
263
+ const { [user]: userDevices } = await parsedKeys.get("device-list", [
264
+ user,
265
+ ]);
266
+ if (!userDevices) {
267
+ return { migrated: 0, skipped: 0, total: 0 };
268
+ }
269
+ const { device: fromDevice } = jidDecode(fromJid);
270
+ const fromDeviceStr = fromDevice?.toString() || "0";
271
+ if (!userDevices.includes(fromDeviceStr)) {
272
+ userDevices.push(fromDeviceStr);
273
+ }
274
+ // Filter out cached devices before database fetch
275
+ const uncachedDevices = userDevices.filter((device) => {
276
+ const deviceKey = `${user}.${device}`;
277
+ return !migratedSessionCache.has(deviceKey);
278
+ });
279
+ // Bulk check session existence only for uncached devices
280
+ const deviceSessionKeys = uncachedDevices.map(
281
+ (device) => `${user}.${device}`,
282
+ );
283
+ const existingSessions = await parsedKeys.get(
284
+ "session",
285
+ deviceSessionKeys,
286
+ );
287
+ // Step 3: Convert existing sessions to JIDs (only migrate sessions that exist)
288
+ for (const [sessionKey, sessionData] of Object.entries(
289
+ existingSessions,
290
+ )) {
291
+ if (sessionData) {
292
+ // Session exists in storage
293
+ const deviceStr = sessionKey.split(".")[1];
294
+ if (!deviceStr) continue;
295
+ const deviceNum = parseInt(deviceStr);
296
+ let jid =
297
+ deviceNum === 0
298
+ ? `${user}@s.whatsapp.net`
299
+ : `${user}:${deviceNum}@s.whatsapp.net`;
300
+ if (deviceNum === 99) {
301
+ jid = `${user}:99@hosted`;
302
+ }
303
+ deviceJids.push(jid);
304
+ }
305
+ }
306
+ }
307
+
308
+ logger.debug(
309
+ {
310
+ fromJid: fromJid,
311
+ devicesWithSessions: deviceJids.length,
312
+ devices: deviceJids,
313
+ },
314
+ "bulk device migration complete - all user devices processed",
315
+ );
316
+ // Single transaction for all migrations
317
+ return parsedKeys.transaction(
318
+ async () => {
319
+ const migrationOps = deviceJids.map((jid) => {
320
+ const lidWithDevice = transferDevice(jid, toJid);
321
+ const fromDecoded = jidDecode(jid);
322
+ const toDecoded = jidDecode(lidWithDevice);
323
+ return {
324
+ fromJid: jid,
325
+ toJid: lidWithDevice,
326
+ pnUser: fromDecoded.user,
327
+ lidUser: toDecoded.user,
328
+ deviceId: fromDecoded.device || 0,
329
+ fromAddr: jidToSignalProtocolAddress(jid),
330
+ toAddr: jidToSignalProtocolAddress(lidWithDevice),
331
+ };
332
+ });
333
+ const totalOps = migrationOps.length;
334
+ let migratedCount = 0;
335
+ // Bulk fetch PN sessions - already exist (verified during device discovery)
336
+ const pnAddrStrings = Array.from(
337
+ new Set(migrationOps.map((op) => op.fromAddr.toString())),
338
+ );
339
+ const pnSessions = await parsedKeys.get("session", pnAddrStrings);
340
+ // Prepare bulk session updates (PN → LID migration + deletion)
341
+ const sessionUpdates = {};
342
+ for (const op of migrationOps) {
343
+ const pnAddrStr = op.fromAddr.toString();
344
+ const lidAddrStr = op.toAddr.toString();
345
+ const pnSession = pnSessions[pnAddrStr];
346
+ if (pnSession) {
347
+ // Session exists (guaranteed from device discovery)
348
+ const fromSession =
349
+ libsignal.SessionRecord.deserialize(pnSession);
350
+ if (fromSession.haveOpenSession()) {
351
+ // Queue for bulk update: copy to LID, delete from PN
352
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
353
+ sessionUpdates[pnAddrStr] = null;
354
+ migratedCount++;
355
+ }
356
+ }
357
+ }
358
+ // Single bulk session update for all migrations
359
+ if (Object.keys(sessionUpdates).length > 0) {
360
+ await parsedKeys.set({ session: sessionUpdates });
361
+ logger.debug(
362
+ { migratedSessions: migratedCount },
363
+ "bulk session migration complete",
364
+ );
365
+ // Cache device-level migrations
366
+ for (const op of migrationOps) {
367
+ if (sessionUpdates[op.toAddr.toString()]) {
368
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
369
+ migratedSessionCache.set(deviceKey, true);
370
+ }
371
+ }
372
+ }
373
+ const skippedCount = totalOps - migratedCount;
374
+ return {
375
+ migrated: migratedCount,
376
+ skipped: skippedCount,
377
+ total: totalOps,
378
+ };
379
+ },
380
+ `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`,
381
+ );
382
+ },
383
+ };
384
+ return repository;
385
+ }
386
+ const jidToSignalProtocolAddress = (jid) => {
387
+ const decoded = jidDecode(jid);
388
+ const { user, device, server, domainType } = decoded;
389
+ if (!user) {
390
+ throw new Error(
391
+ `JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`,
392
+ );
393
+ }
394
+ const signalUser =
395
+ domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
396
+ const finalDevice = device || 0;
397
+ if (
398
+ device === 99 &&
399
+ decoded.server !== "hosted" &&
400
+ decoded.server !== "hosted.lid"
401
+ ) {
402
+ throw new Error(
403
+ "Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:" +
404
+ jid,
405
+ );
406
+ }
407
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
408
+ };
409
+ const jidToSignalSenderKeyName = (group, user) => {
410
+ return new SenderKeyName(group, jidToSignalProtocolAddress(user));
411
+ };
412
+ function signalStorage({ creds, keys }, lidMapping) {
413
+ // Shared function to resolve PN signal address to LID if mapping exists
414
+ const resolveLIDSignalAddress = async (id) => {
415
+ if (id.includes(".")) {
416
+ const [deviceId, device] = id.split(".");
417
+ const [user, domainType_] = deviceId.split("_");
418
+ const domainType = parseInt(domainType_ || "0");
419
+ if (
420
+ domainType === WAJIDDomains.LID ||
421
+ domainType === WAJIDDomains.HOSTED_LID
422
+ )
423
+ return id;
424
+ const pnJid = `${user}${device !== "0" ? `:${device}` : ""}@${domainType === WAJIDDomains.HOSTED ? "hosted" : "s.whatsapp.net"}`;
425
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
426
+ if (lidForPN) {
427
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
428
+ return lidAddr.toString();
429
+ }
430
+ }
431
+ return id;
432
+ };
433
+ return {
434
+ loadSession: async (id) => {
435
+ try {
436
+ const wireJid = await resolveLIDSignalAddress(id);
437
+ let { [wireJid]: sess } = await keys.get("session", [wireJid]);
438
+ if (!sess && wireJid !== id) {
439
+ const { [id]: fallbackSess } = await keys.get("session", [id]);
440
+ sess = fallbackSess;
441
+ }
442
+ if (sess) {
443
+ return libsignal.SessionRecord.deserialize(sess);
444
+ }
445
+ } catch (e) {
446
+ return null;
447
+ }
448
+ return null;
449
+ },
450
+ storeSession: async (id, session) => {
451
+ const wireJid = await resolveLIDSignalAddress(id);
452
+ await keys.set({ session: { [wireJid]: session.serialize() } });
453
+ },
454
+ isTrustedIdentity: () => {
455
+ return true; // TOFU - Trust on First Use (same as WhatsApp Web)
456
+ },
457
+ loadIdentityKey: async (id) => {
458
+ const wireJid = await resolveLIDSignalAddress(id);
459
+ let { [wireJid]: key } = await keys.get("identity-key", [wireJid]);
460
+ if (!key && wireJid !== id) {
461
+ const { [id]: fallbackKey } = await keys.get("identity-key", [id]);
462
+ key = fallbackKey;
463
+ }
464
+ return key || undefined;
465
+ },
466
+ saveIdentity: async (id, identityKey) => {
467
+ const wireJid = await resolveLIDSignalAddress(id);
468
+ const { [wireJid]: existingKey } = await keys.get("identity-key", [
469
+ wireJid,
470
+ ]);
471
+ const keysMatch =
472
+ existingKey &&
473
+ existingKey.length === identityKey.length &&
474
+ existingKey.every((byte, i) => byte === identityKey[i]);
475
+ if (existingKey && !keysMatch) {
476
+ // Identity changed - clear session and update key
477
+ await keys.set({
478
+ session: { [wireJid]: null },
479
+ "identity-key": { [wireJid]: identityKey },
480
+ });
481
+ return true;
482
+ }
483
+ if (!existingKey) {
484
+ // New contact - Trust on First Use (TOFU)
485
+ await keys.set({ "identity-key": { [wireJid]: identityKey } });
486
+ return true;
487
+ }
488
+ return false;
489
+ },
490
+ loadPreKey: async (id) => {
491
+ const keyId = id.toString();
492
+ const { [keyId]: key } = await keys.get("pre-key", [keyId]);
493
+ if (key) {
494
+ return {
495
+ privKey: Buffer.from(key.private),
496
+ pubKey: Buffer.from(key.public),
497
+ };
498
+ }
499
+ },
500
+ removePreKey: (id) => keys.set({ "pre-key": { [id]: null } }),
501
+ loadSignedPreKey: () => {
502
+ const key = creds.signedPreKey;
503
+ return {
504
+ privKey: Buffer.from(key.keyPair.private),
505
+ pubKey: Buffer.from(key.keyPair.public),
506
+ };
507
+ },
508
+ loadSenderKey: async (senderKeyName) => {
509
+ const keyId = senderKeyName.toString();
510
+ const { [keyId]: key } = await keys.get("sender-key", [keyId]);
511
+ if (key) {
512
+ return SenderKeyRecord.deserialize(key);
513
+ }
514
+ return new SenderKeyRecord();
515
+ },
516
+ storeSenderKey: async (senderKeyName, key) => {
517
+ const keyId = senderKeyName.toString();
518
+ const serialized = JSON.stringify(key.serialize());
519
+ await keys.set({
520
+ "sender-key": { [keyId]: Buffer.from(serialized, "utf-8") },
521
+ });
522
+ },
523
+ getOurRegistrationId: () => creds.registrationId,
524
+ getOurIdentity: () => {
525
+ const { signedIdentityKey } = creds;
526
+ return {
527
+ privKey: Buffer.from(signedIdentityKey.private),
528
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public)),
529
+ };
530
+ },
531
+ };
532
+ }