@aseppxyzz12/baileys 1.1.8

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 (185) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +2579 -0
  3. package/WAProto/AICommon/AICommon.js +19396 -0
  4. package/WAProto/AICommon/AICommon.proto +820 -0
  5. package/WAProto/Adv/Adv.js +1137 -0
  6. package/WAProto/Adv/Adv.proto +42 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +8975 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +484 -0
  9. package/WAProto/Cert/Cert.js +893 -0
  10. package/WAProto/Cert/Cert.proto +30 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +2457 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +103 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
  17. package/WAProto/E2E/E2E.js +78728 -0
  18. package/WAProto/E2E/E2E.proto +1970 -0
  19. package/WAProto/Ephemeral/Ephemeral.js +143 -0
  20. package/WAProto/Ephemeral/Ephemeral.proto +7 -0
  21. package/WAProto/HistorySync/HistorySync.js +95931 -0
  22. package/WAProto/HistorySync/HistorySync.proto +229 -0
  23. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
  24. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
  25. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
  26. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
  27. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
  28. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
  29. package/WAProto/MmsRetry/MmsRetry.js +310 -0
  30. package/WAProto/MmsRetry/MmsRetry.proto +19 -0
  31. package/WAProto/Protocol/Protocol.js +399 -0
  32. package/WAProto/Protocol/Protocol.proto +22 -0
  33. package/WAProto/Reporting/Reporting.js +535 -0
  34. package/WAProto/Reporting/Reporting.proto +22 -0
  35. package/WAProto/ServerSync/ServerSync.js +1830 -0
  36. package/WAProto/ServerSync/ServerSync.proto +70 -0
  37. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
  38. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
  39. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
  40. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
  41. package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
  42. package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
  43. package/WAProto/SyncAction/SyncAction.js +17424 -0
  44. package/WAProto/SyncAction/SyncAction.proto +663 -0
  45. package/WAProto/UserPassword/UserPassword.js +544 -0
  46. package/WAProto/UserPassword/UserPassword.proto +28 -0
  47. package/WAProto/VnameCert/VnameCert.js +1466 -0
  48. package/WAProto/VnameCert/VnameCert.proto +65 -0
  49. package/WAProto/Wa6/Wa6.js +4601 -0
  50. package/WAProto/Wa6/Wa6.proto +241 -0
  51. package/WAProto/Web/Web.js +90819 -0
  52. package/WAProto/Web/Web.proto +605 -0
  53. package/WAProto/index.js +30 -0
  54. package/engine-requirements.js +9 -0
  55. package/lib/Defaults/baileys-version.json +3 -0
  56. package/lib/Defaults/connection.js +39 -0
  57. package/lib/Defaults/constants.js +50 -0
  58. package/lib/Defaults/history.js +13 -0
  59. package/lib/Defaults/index.js +36 -0
  60. package/lib/Defaults/media.js +43 -0
  61. package/lib/Defaults/phonenumber-mcc.json +223 -0
  62. package/lib/Defaults/prefix.js +12 -0
  63. package/lib/Function/Download/tiktok.js +19 -0
  64. package/lib/Function/Tools/bypass.js +19 -0
  65. package/lib/Function/index.js +13 -0
  66. package/lib/Signal/Group/ciphertext-message.js +14 -0
  67. package/lib/Signal/Group/group-session-builder.js +46 -0
  68. package/lib/Signal/Group/group_cipher.js +104 -0
  69. package/lib/Signal/Group/index.js +42 -0
  70. package/lib/Signal/Group/keyhelper.js +21 -0
  71. package/lib/Signal/Group/queue-job.js +57 -0
  72. package/lib/Signal/Group/sender-chain-key.js +34 -0
  73. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  74. package/lib/Signal/Group/sender-key-message.js +78 -0
  75. package/lib/Signal/Group/sender-key-name.js +49 -0
  76. package/lib/Signal/Group/sender-key-record.js +45 -0
  77. package/lib/Signal/Group/sender-key-state.js +100 -0
  78. package/lib/Signal/Group/sender-message-key.js +28 -0
  79. package/lib/Signal/libsignal.js +364 -0
  80. package/lib/Signal/lid-mapping.js +164 -0
  81. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  82. package/lib/Socket/Client/index.js +31 -0
  83. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  84. package/lib/Socket/Client/types.js +12 -0
  85. package/lib/Socket/Client/web-socket-client.js +62 -0
  86. package/lib/Socket/Client/websocket.js +67 -0
  87. package/lib/Socket/business.js +291 -0
  88. package/lib/Socket/chats.js +874 -0
  89. package/lib/Socket/community.js +454 -0
  90. package/lib/Socket/dugong.js +658 -0
  91. package/lib/Socket/groups.js +357 -0
  92. package/lib/Socket/index.js +13 -0
  93. package/lib/Socket/messages-recv.js +1509 -0
  94. package/lib/Socket/messages-send.js +1505 -0
  95. package/lib/Socket/mex.js +54 -0
  96. package/lib/Socket/newsletter.js +171 -0
  97. package/lib/Socket/registration.js +167 -0
  98. package/lib/Socket/rich-content.js +279 -0
  99. package/lib/Socket/socket.js +905 -0
  100. package/lib/Socket/username.js +157 -0
  101. package/lib/Socket/usync.js +70 -0
  102. package/lib/Store/index.js +37 -0
  103. package/lib/Store/keyed-db.js +114 -0
  104. package/lib/Store/make-cache-manager-store.js +77 -0
  105. package/lib/Store/make-in-memory-store.js +423 -0
  106. package/lib/Store/make-ordered-dictionary.js +78 -0
  107. package/lib/Store/object-repository.js +26 -0
  108. package/lib/Types/Auth.js +2 -0
  109. package/lib/Types/Bussines.js +2 -0
  110. package/lib/Types/Call.js +2 -0
  111. package/lib/Types/Chat.js +10 -0
  112. package/lib/Types/Contact.js +2 -0
  113. package/lib/Types/Events.js +2 -0
  114. package/lib/Types/GroupMetadata.js +2 -0
  115. package/lib/Types/Label.js +25 -0
  116. package/lib/Types/LabelAssociation.js +4 -0
  117. package/lib/Types/Message.js +11 -0
  118. package/lib/Types/Mex.js +40 -0
  119. package/lib/Types/MexUpdates.js +15 -0
  120. package/lib/Types/Newsletter.js +32 -0
  121. package/lib/Types/Product.js +2 -0
  122. package/lib/Types/Signal.js +2 -0
  123. package/lib/Types/Socket.js +2 -0
  124. package/lib/Types/State.js +9 -0
  125. package/lib/Types/USync.js +2 -0
  126. package/lib/Types/index.js +60 -0
  127. package/lib/Utils/auth-utils.js +256 -0
  128. package/lib/Utils/baileys-event-stream.js +63 -0
  129. package/lib/Utils/bot-toolkit.js +455 -0
  130. package/lib/Utils/browser-utils.js +29 -0
  131. package/lib/Utils/business.js +233 -0
  132. package/lib/Utils/chat-utils.js +904 -0
  133. package/lib/Utils/companion-reg-client-utils.js +41 -0
  134. package/lib/Utils/crypto.js +144 -0
  135. package/lib/Utils/decode-wa-message.js +305 -0
  136. package/lib/Utils/event-buffer.js +555 -0
  137. package/lib/Utils/generics.js +411 -0
  138. package/lib/Utils/history.js +100 -0
  139. package/lib/Utils/identity-change-handler.js +53 -0
  140. package/lib/Utils/index.js +57 -0
  141. package/lib/Utils/link-preview.js +76 -0
  142. package/lib/Utils/logger.js +4 -0
  143. package/lib/Utils/lt-hash.js +45 -0
  144. package/lib/Utils/make-mutex.js +33 -0
  145. package/lib/Utils/message-composer.js +289 -0
  146. package/lib/Utils/message-retry-manager.js +134 -0
  147. package/lib/Utils/messages-media.js +806 -0
  148. package/lib/Utils/messages.js +1908 -0
  149. package/lib/Utils/noise-handler.js +157 -0
  150. package/lib/Utils/offline-node-processor.js +42 -0
  151. package/lib/Utils/pre-key-manager.js +86 -0
  152. package/lib/Utils/process-message.js +814 -0
  153. package/lib/Utils/reporting-utils.js +264 -0
  154. package/lib/Utils/signal.js +183 -0
  155. package/lib/Utils/stanza-ack.js +36 -0
  156. package/lib/Utils/sync-action-utils.js +52 -0
  157. package/lib/Utils/tc-token-utils.js +167 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +104 -0
  159. package/lib/Utils/validate-connection.js +229 -0
  160. package/lib/Utils/vialeys-event-stream.js +41 -0
  161. package/lib/WABinary/constants.js +1308 -0
  162. package/lib/WABinary/decode.js +233 -0
  163. package/lib/WABinary/encode.js +212 -0
  164. package/lib/WABinary/generic-utils.js +124 -0
  165. package/lib/WABinary/index.js +36 -0
  166. package/lib/WABinary/jid-utils.js +101 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.js +12 -0
  169. package/lib/WAM/constants.js +20491 -0
  170. package/lib/WAM/encode.js +148 -0
  171. package/lib/WAM/index.js +34 -0
  172. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
  176. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  179. package/lib/WAUSync/Protocols/index.js +38 -0
  180. package/lib/WAUSync/USyncQuery.js +97 -0
  181. package/lib/WAUSync/USyncUser.js +33 -0
  182. package/lib/WAUSync/index.js +34 -0
  183. package/lib/index.js +113 -0
  184. package/lib/messages-send.js +1496 -0
  185. package/package.json +100 -0
@@ -0,0 +1,364 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const {
4
+ SessionCipher: SessionCipher,
5
+ SessionBuilder: SessionBuilder,
6
+ SessionRecord: SessionRecord,
7
+ ProtocolAddress: ProtocolAddress,
8
+ } = require("libsignal");
9
+ const { generateSignalPubKey: generateSignalPubKey } = require("../Utils");
10
+ const {
11
+ isHostedLidUser: isHostedLidUser,
12
+ isHostedPnUser: isHostedPnUser,
13
+ isLidUser: isLidUser,
14
+ isPnUser: isPnUser,
15
+ jidDecode: jidDecode,
16
+ transferDevice: transferDevice,
17
+ WAJIDDomains: WAJIDDomains,
18
+ } = require("../WABinary");
19
+ const { SenderKeyName: SenderKeyName } = require("./Group/sender-key-name");
20
+ const { SenderKeyRecord: SenderKeyRecord } = require("./Group/sender-key-record");
21
+ const {
22
+ GroupCipher: GroupCipher,
23
+ GroupSessionBuilder: GroupSessionBuilder,
24
+ SenderKeyDistributionMessage: SenderKeyDistributionMessage,
25
+ } = require("./Group");
26
+ const { LRUCache: LRUCache } = require("lru-cache");
27
+ const { LIDMappingStore: LIDMappingStore } = require("./lid-mapping");
28
+ function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
29
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
30
+ const storage = signalStorage(auth, lidMapping);
31
+ const parsedKeys = auth.keys;
32
+ const migratedSessionCache = new LRUCache({
33
+ ttl: 3 * 24 * 60 * 60 * 1e3,
34
+ ttlAutopurge: true,
35
+ updateAgeOnGet: true,
36
+ });
37
+ const repository = {
38
+ decryptGroupMessage({ group: group, authorJid: authorJid, msg: msg }) {
39
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
40
+ const cipher = new GroupCipher(storage, senderName);
41
+ return parsedKeys.transaction(async () => cipher.decrypt(msg), group);
42
+ },
43
+ async processSenderKeyDistributionMessage({ item: item, authorJid: authorJid }) {
44
+ const builder = new GroupSessionBuilder(storage);
45
+ if (!item.groupId) {
46
+ throw new Error("Group ID is required for sender key distribution message");
47
+ }
48
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
49
+ const senderMsg = new SenderKeyDistributionMessage(
50
+ null,
51
+ null,
52
+ null,
53
+ null,
54
+ item.axolotlSenderKeyDistributionMessage
55
+ );
56
+ const senderNameStr = senderName.toString();
57
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [
58
+ senderNameStr,
59
+ ]);
60
+ if (!senderKey) {
61
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
62
+ }
63
+ return parsedKeys.transaction(async () => {
64
+ const { [senderNameStr]: senderKey } = await auth.keys.get("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: jid, type: type, ciphertext: ciphertext }) {
74
+ const addr = jidToSignalProtocolAddress(jid);
75
+ const session = new 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
+ return parsedKeys.transaction(async () => await doDecrypt(), jid);
89
+ },
90
+ async encryptMessage({ jid: jid, data: data }) {
91
+ const addr = jidToSignalProtocolAddress(jid);
92
+ const cipher = new SessionCipher(storage, addr);
93
+ return parsedKeys.transaction(async () => {
94
+ const { type: sigType, body: body } = await cipher.encrypt(data);
95
+ const type = sigType === 3 ? "pkmsg" : "msg";
96
+ return { type: type, ciphertext: Buffer.from(body, "binary") };
97
+ }, jid);
98
+ },
99
+ async encryptGroupMessage({ group: group, meId: meId, data: data }) {
100
+ const senderName = jidToSignalSenderKeyName(group, meId);
101
+ const builder = new GroupSessionBuilder(storage);
102
+ const senderNameStr = senderName.toString();
103
+ return parsedKeys.transaction(async () => {
104
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [
105
+ senderNameStr,
106
+ ]);
107
+ if (!senderKey) {
108
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
109
+ }
110
+ const senderKeyDistributionMessage = await builder.create(senderName);
111
+ const session = new GroupCipher(storage, senderName);
112
+ const ciphertext = await session.encrypt(data);
113
+ return {
114
+ ciphertext: ciphertext,
115
+ senderKeyDistributionMessage: senderKeyDistributionMessage.serialize(),
116
+ };
117
+ }, group);
118
+ },
119
+ async injectE2ESession({ jid: jid, session: session }) {
120
+ logger.trace({ jid: jid }, "injecting E2EE session");
121
+ const cipher = new SessionBuilder(storage, jidToSignalProtocolAddress(jid));
122
+ return parsedKeys.transaction(async () => {
123
+ await cipher.initOutgoing(session);
124
+ }, jid);
125
+ },
126
+ jidToSignalProtocolAddress(jid) {
127
+ return jidToSignalProtocolAddress(jid).toString();
128
+ },
129
+ lidMapping: lidMapping,
130
+ async validateSession(jid) {
131
+ try {
132
+ const addr = jidToSignalProtocolAddress(jid);
133
+ const session = await storage.loadSession(addr.toString());
134
+ if (!session) {
135
+ return { exists: false, reason: "no session" };
136
+ }
137
+ if (!session.haveOpenSession()) {
138
+ return { exists: false, reason: "no open session" };
139
+ }
140
+ return { exists: true };
141
+ } catch (error) {
142
+ return { exists: false, reason: "validation error" };
143
+ }
144
+ },
145
+ async deleteSession(jids) {
146
+ if (!jids.length) return;
147
+ const sessionUpdates = {};
148
+ jids.forEach((jid) => {
149
+ const addr = jidToSignalProtocolAddress(jid);
150
+ sessionUpdates[addr.toString()] = null;
151
+ });
152
+ return parsedKeys.transaction(async () => {
153
+ await auth.keys.set({ session: sessionUpdates });
154
+ }, `delete-${jids.length}-sessions`);
155
+ },
156
+ async migrateSession(fromJid, toJid) {
157
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid))) {
158
+ return { migrated: 0, skipped: 0, total: 0 };
159
+ }
160
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
161
+ return { migrated: 0, skipped: 0, total: 1 };
162
+ }
163
+ const { user: user } = jidDecode(fromJid);
164
+ logger.debug({ fromJid: fromJid }, "bulk device migration - loading all user devices");
165
+ const { [user]: userDevices } = await parsedKeys.get("device-list", [user]);
166
+ if (!userDevices) {
167
+ return { migrated: 0, skipped: 0, total: 0 };
168
+ }
169
+ const { device: fromDevice } = jidDecode(fromJid);
170
+ const fromDeviceStr = fromDevice?.toString() || "0";
171
+ if (!userDevices.includes(fromDeviceStr)) {
172
+ userDevices.push(fromDeviceStr);
173
+ }
174
+ const uncachedDevices = userDevices.filter((device) => {
175
+ const deviceKey = `${user}.${device}`;
176
+ return !migratedSessionCache.has(deviceKey);
177
+ });
178
+ const deviceSessionKeys = uncachedDevices.map((device) => `${user}.${device}`);
179
+ const existingSessions = await parsedKeys.get("session", deviceSessionKeys);
180
+ const deviceJids = [];
181
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
182
+ if (sessionData) {
183
+ const deviceStr = sessionKey.split(".")[1];
184
+ if (!deviceStr) continue;
185
+ const deviceNum = parseInt(deviceStr);
186
+ let jid =
187
+ deviceNum === 0
188
+ ? `${user}@s.whatsapp.net`
189
+ : `${user}:${deviceNum}@s.whatsapp.net`;
190
+ if (deviceNum === 99) {
191
+ jid = `${user}:99@hosted`;
192
+ }
193
+ deviceJids.push(jid);
194
+ }
195
+ }
196
+ logger.debug(
197
+ {
198
+ fromJid: fromJid,
199
+ totalDevices: userDevices.length,
200
+ devicesWithSessions: deviceJids.length,
201
+ devices: deviceJids,
202
+ },
203
+ "bulk device migration complete - all user devices processed"
204
+ );
205
+ return parsedKeys.transaction(
206
+ async () => {
207
+ const migrationOps = deviceJids.map((jid) => {
208
+ const lidWithDevice = transferDevice(jid, toJid);
209
+ const fromDecoded = jidDecode(jid);
210
+ const toDecoded = jidDecode(lidWithDevice);
211
+ return {
212
+ fromJid: jid,
213
+ toJid: lidWithDevice,
214
+ pnUser: fromDecoded.user,
215
+ lidUser: toDecoded.user,
216
+ deviceId: fromDecoded.device || 0,
217
+ fromAddr: jidToSignalProtocolAddress(jid),
218
+ toAddr: jidToSignalProtocolAddress(lidWithDevice),
219
+ };
220
+ });
221
+ const totalOps = migrationOps.length;
222
+ let migratedCount = 0;
223
+ const pnAddrStrings = Array.from(
224
+ new Set(migrationOps.map((op) => op.fromAddr.toString()))
225
+ );
226
+ const pnSessions = await parsedKeys.get("session", pnAddrStrings);
227
+ const sessionUpdates = {};
228
+ for (const op of migrationOps) {
229
+ const pnAddrStr = op.fromAddr.toString();
230
+ const lidAddrStr = op.toAddr.toString();
231
+ const pnSession = pnSessions[pnAddrStr];
232
+ if (pnSession) {
233
+ const fromSession = SessionRecord.deserialize(pnSession);
234
+ if (fromSession.haveOpenSession()) {
235
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
236
+ sessionUpdates[pnAddrStr] = null;
237
+ migratedCount++;
238
+ }
239
+ }
240
+ }
241
+ if (Object.keys(sessionUpdates).length > 0) {
242
+ await parsedKeys.set({ session: sessionUpdates });
243
+ logger.debug(
244
+ { migratedSessions: migratedCount },
245
+ "bulk session migration complete"
246
+ );
247
+ for (const op of migrationOps) {
248
+ if (sessionUpdates[op.toAddr.toString()]) {
249
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
250
+ migratedSessionCache.set(deviceKey, true);
251
+ }
252
+ }
253
+ }
254
+ const skippedCount = totalOps - migratedCount;
255
+ return {
256
+ migrated: migratedCount,
257
+ skipped: skippedCount,
258
+ total: totalOps,
259
+ };
260
+ },
261
+ `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`
262
+ );
263
+ },
264
+ };
265
+ return repository;
266
+ }
267
+ const jidToSignalProtocolAddress = (jid) => {
268
+ const decoded = jidDecode(jid);
269
+ const { user: user, device: device, server: server, domainType: domainType } = decoded;
270
+ if (!user) {
271
+ throw new Error(
272
+ `JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`
273
+ );
274
+ }
275
+ const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
276
+ const finalDevice = device || 0;
277
+ if (device === 99 && decoded.server !== "hosted" && decoded.server !== "hosted.lid") {
278
+ throw new Error(
279
+ "Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:" + jid
280
+ );
281
+ }
282
+ return new ProtocolAddress(signalUser, finalDevice);
283
+ };
284
+ const jidToSignalSenderKeyName = (group, user) =>
285
+ new SenderKeyName(group, jidToSignalProtocolAddress(user));
286
+ function signalStorage({ creds: creds, keys: keys }, lidMapping) {
287
+ const resolveLIDSignalAddress = async (id) => {
288
+ if (id.includes(".")) {
289
+ const [deviceId, device] = id.split(".");
290
+ const [user, domainType_] = deviceId.split("_");
291
+ const domainType = parseInt(domainType_ || "0");
292
+ if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID)
293
+ return id;
294
+ const pnJid = `${user}${device !== "0" ? `:${device}` : ""}@${domainType === WAJIDDomains.HOSTED ? "hosted" : "s.whatsapp.net"}`;
295
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
296
+ if (lidForPN) {
297
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
298
+ return lidAddr.toString();
299
+ }
300
+ }
301
+ return id;
302
+ };
303
+ return {
304
+ loadSession: async (id) => {
305
+ try {
306
+ const wireJid = await resolveLIDSignalAddress(id);
307
+ const { [wireJid]: sess } = await keys.get("session", [wireJid]);
308
+ if (sess) {
309
+ return SessionRecord.deserialize(sess);
310
+ }
311
+ } catch (e) {
312
+ return null;
313
+ }
314
+ return null;
315
+ },
316
+ storeSession: async (id, session) => {
317
+ const wireJid = await resolveLIDSignalAddress(id);
318
+ await keys.set({ session: { [wireJid]: session.serialize() } });
319
+ },
320
+ isTrustedIdentity: () => true,
321
+ loadPreKey: async (id) => {
322
+ const keyId = id.toString();
323
+ const { [keyId]: key } = await keys.get("pre-key", [keyId]);
324
+ if (key) {
325
+ return {
326
+ privKey: Buffer.from(key.private),
327
+ pubKey: Buffer.from(key.public),
328
+ };
329
+ }
330
+ },
331
+ removePreKey: (id) => keys.set({ "pre-key": { [id]: null } }),
332
+ loadSignedPreKey: () => {
333
+ const key = creds.signedPreKey;
334
+ return {
335
+ privKey: Buffer.from(key.keyPair.private),
336
+ pubKey: Buffer.from(key.keyPair.public),
337
+ };
338
+ },
339
+ loadSenderKey: async (senderKeyName) => {
340
+ const keyId = senderKeyName.toString();
341
+ const { [keyId]: key } = await keys.get("sender-key", [keyId]);
342
+ if (key) {
343
+ return SenderKeyRecord.deserialize(key);
344
+ }
345
+ return new SenderKeyRecord();
346
+ },
347
+ storeSenderKey: async (senderKeyName, key) => {
348
+ const keyId = senderKeyName.toString();
349
+ const serialized = JSON.stringify(key.serialize());
350
+ await keys.set({
351
+ "sender-key": { [keyId]: Buffer.from(serialized, "utf-8") },
352
+ });
353
+ },
354
+ getOurRegistrationId: () => creds.registrationId,
355
+ getOurIdentity: () => {
356
+ const { signedIdentityKey: signedIdentityKey } = creds;
357
+ return {
358
+ privKey: Buffer.from(signedIdentityKey.private),
359
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public)),
360
+ };
361
+ },
362
+ };
363
+ }
364
+ module.exports = { makeLibSignalRepository: makeLibSignalRepository };
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { LRUCache: LRUCache } = require("lru-cache");
4
+ const {
5
+ isHostedPnUser: isHostedPnUser,
6
+ isLidUser: isLidUser,
7
+ isPnUser: isPnUser,
8
+ jidDecode: jidDecode,
9
+ jidNormalizedUser: jidNormalizedUser,
10
+ WAJIDDomains: WAJIDDomains,
11
+ } = require("../WABinary");
12
+ class LIDMappingStore {
13
+ constructor(keys, logger, pnToLIDFunc) {
14
+ this.mappingCache = new LRUCache({
15
+ ttl: 3 * 24 * 60 * 60 * 1e3,
16
+ ttlAutopurge: true,
17
+ updateAgeOnGet: true,
18
+ });
19
+ this.keys = keys;
20
+ this.pnToLIDFunc = pnToLIDFunc;
21
+ this.logger = logger;
22
+ }
23
+ async storeLIDPNMappings(pairs) {
24
+ const pairMap = {};
25
+ for (const { lid: lid, pn: pn } of pairs) {
26
+ if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
27
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
28
+ continue;
29
+ }
30
+ const lidDecoded = jidDecode(lid);
31
+ const pnDecoded = jidDecode(pn);
32
+ if (!lidDecoded || !pnDecoded) return;
33
+ const pnUser = pnDecoded.user;
34
+ const lidUser = lidDecoded.user;
35
+ let existingLidUser = this.mappingCache.get(`pn:${pnUser}`);
36
+ if (!existingLidUser) {
37
+ this.logger.trace(`Cache miss for PN user ${pnUser}; checking database`);
38
+ const stored = await this.keys.get("lid-mapping", [pnUser]);
39
+ existingLidUser = stored[pnUser];
40
+ if (existingLidUser) {
41
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
42
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
43
+ }
44
+ }
45
+ if (existingLidUser === lidUser) {
46
+ this.logger.debug(
47
+ { pnUser: pnUser, lidUser: lidUser },
48
+ "LID mapping already exists, skipping"
49
+ );
50
+ continue;
51
+ }
52
+ pairMap[pnUser] = lidUser;
53
+ }
54
+ this.logger.trace(
55
+ { pairMap: pairMap },
56
+ `Storing ${Object.keys(pairMap).length} pn mappings`
57
+ );
58
+ await this.keys.transaction(async () => {
59
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
60
+ await this.keys.set({
61
+ "lid-mapping": { [pnUser]: lidUser, [`${lidUser}_reverse`]: pnUser },
62
+ });
63
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
64
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
65
+ }
66
+ }, "lid-mapping");
67
+ }
68
+ async getLIDForPN(pn) {
69
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
70
+ }
71
+ async getLIDsForPNs(pns) {
72
+ const usyncFetch = {};
73
+ const successfulPairs = {};
74
+ for (const pn of pns) {
75
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) continue;
76
+ const decoded = jidDecode(pn);
77
+ if (!decoded) continue;
78
+ const pnUser = decoded.user;
79
+ let lidUser = this.mappingCache.get(`pn:${pnUser}`);
80
+ if (!lidUser) {
81
+ const stored = await this.keys.get("lid-mapping", [pnUser]);
82
+ lidUser = stored[pnUser];
83
+ if (lidUser) {
84
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
85
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
86
+ } else {
87
+ this.logger.trace(
88
+ `No LID mapping found for PN user ${pnUser}; batch getting from USync`
89
+ );
90
+ const device = decoded.device || 0;
91
+ let normalizedPn = jidNormalizedUser(pn);
92
+ if (isHostedPnUser(normalizedPn)) {
93
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
94
+ }
95
+ if (!usyncFetch[normalizedPn]) {
96
+ usyncFetch[normalizedPn] = [device];
97
+ } else {
98
+ usyncFetch[normalizedPn]?.push(device);
99
+ }
100
+ continue;
101
+ }
102
+ }
103
+ lidUser = lidUser.toString();
104
+ if (!lidUser) {
105
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
106
+ return null;
107
+ }
108
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
109
+ const deviceSpecificLid = `${lidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === "hosted" ? "hosted.lid" : "lid"}`;
110
+ this.logger.trace(
111
+ `getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`
112
+ );
113
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn: pn };
114
+ }
115
+ if (Object.keys(usyncFetch).length > 0) {
116
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch));
117
+ if (result && result.length > 0) {
118
+ await this.storeLIDPNMappings(result);
119
+ for (const pair of result) {
120
+ const pnDecoded = jidDecode(pair.pn);
121
+ const pnUser = pnDecoded?.user;
122
+ if (!pnUser) continue;
123
+ const lidUser = jidDecode(pair.lid)?.user;
124
+ if (!lidUser) continue;
125
+ for (const device of usyncFetch[pair.pn]) {
126
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted.lid" : "lid"}`;
127
+ this.logger.trace(
128
+ `getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`
129
+ );
130
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted" : "s.whatsapp.net"}`;
131
+ successfulPairs[deviceSpecificPn] = {
132
+ lid: deviceSpecificLid,
133
+ pn: deviceSpecificPn,
134
+ };
135
+ }
136
+ }
137
+ } else {
138
+ return null;
139
+ }
140
+ }
141
+ return Object.values(successfulPairs);
142
+ }
143
+ async getPNForLID(lid) {
144
+ if (!isLidUser(lid)) return null;
145
+ const decoded = jidDecode(lid);
146
+ if (!decoded) return null;
147
+ const lidUser = decoded.user;
148
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
149
+ if (!pnUser || typeof pnUser !== "string") {
150
+ const stored = await this.keys.get("lid-mapping", [`${lidUser}_reverse`]);
151
+ pnUser = stored[`${lidUser}_reverse`];
152
+ if (!pnUser || typeof pnUser !== "string") {
153
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
154
+ return null;
155
+ }
156
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
157
+ }
158
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
159
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? "hosted" : "s.whatsapp.net"}`;
160
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
161
+ return pnJid;
162
+ }
163
+ }
164
+ module.exports = { LIDMappingStore: LIDMappingStore };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AbstractSocketClient = void 0;
4
+ const events_1 = require("events");
5
+ class AbstractSocketClient extends events_1.EventEmitter {
6
+ constructor(url, config) {
7
+ super();
8
+ this.url = url;
9
+ this.config = config;
10
+ this.setMaxListeners(0);
11
+ }
12
+ }
13
+ exports.AbstractSocketClient = AbstractSocketClient;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __createBinding =
3
+ (this && this.__createBinding) ||
4
+ (Object.create
5
+ ? function (o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = {
10
+ enumerable: true,
11
+ get: function () {
12
+ return m[k];
13
+ },
14
+ };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }
18
+ : function (o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ });
22
+ var __exportStar =
23
+ (this && this.__exportStar) ||
24
+ function (m, exports) {
25
+ for (var p in m)
26
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p))
27
+ __createBinding(exports, m, p);
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ __exportStar(require("./types"), exports);
31
+ __exportStar(require("./websocket"), exports);
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MobileSocketClient = void 0;
4
+ const net_1 = require("net");
5
+ const abstract_socket_client_1 = require("./abstract-socket-client");
6
+ class MobileSocketClient extends abstract_socket_client_1.AbstractSocketClient {
7
+ constructor() {
8
+ super(...arguments);
9
+ this.socket = null;
10
+ }
11
+ get isOpen() {
12
+ var _a;
13
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'open';
14
+ }
15
+ get isClosed() {
16
+ var _a;
17
+ return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'closed';
18
+ }
19
+ get isClosing() {
20
+ var _a;
21
+ return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'closed';
22
+ }
23
+ get isConnecting() {
24
+ var _a;
25
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'opening';
26
+ }
27
+ async connect() {
28
+ var _a;
29
+ if (this.socket) {
30
+ return;
31
+ }
32
+ if (this.config.agent) {
33
+ throw new Error('There are not support for proxy agent for mobile connection');
34
+ }
35
+ else {
36
+ this.socket = (0, net_1.connect)({
37
+ host: this.url.hostname,
38
+ port: Number(this.url.port) || 443
39
+ });
40
+ }
41
+ this.socket.setMaxListeners(0);
42
+ const events = ['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'ready', 'timeout'];
43
+ for (const event of events) {
44
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on(event, (...args) => this.emit(event, ...args));
45
+ }
46
+ this.socket.on('data', (...args) => this.emit('message', ...args));
47
+ this.socket.on('ready', (...args) => this.emit('open', ...args));
48
+ }
49
+ async close() {
50
+ if (!this.socket) {
51
+ return;
52
+ }
53
+ return new Promise(resolve => {
54
+ this.socket.end(resolve);
55
+ this.socket = null;
56
+ });
57
+ }
58
+ send(str, cb) {
59
+ if (this.socket === null) {
60
+ return false;
61
+ }
62
+ return this.socket.write(str, undefined, cb);
63
+ }
64
+ }
65
+ exports.MobileSocketClient = MobileSocketClient;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { EventEmitter: EventEmitter } = require("events");
4
+ class AbstractSocketClient extends EventEmitter {
5
+ constructor(url, config) {
6
+ super();
7
+ this.url = url;
8
+ this.config = config;
9
+ this.setMaxListeners(0);
10
+ }
11
+ }
12
+ module.exports = { AbstractSocketClient: AbstractSocketClient };