@sixcore/baileys 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +21 -13
  2. package/WAProto/WAProto.proto +5311 -0
  3. package/WAProto/index.js +65813 -141372
  4. package/lib/Defaults/index.js +120 -133
  5. package/lib/KeyDB/BinarySearch.js +30 -0
  6. package/lib/KeyDB/KeyedDB.js +178 -0
  7. package/lib/KeyDB/index.js +14 -0
  8. package/lib/Signal/Group/ciphertext-message.js +22 -14
  9. package/lib/Signal/Group/group-session-builder.js +21 -42
  10. package/lib/Signal/Group/group_cipher.js +85 -87
  11. package/lib/Signal/Group/index.js +23 -57
  12. package/lib/Signal/Group/keyhelper.js +28 -52
  13. package/lib/Signal/Group/sender-chain-key.js +37 -33
  14. package/lib/Signal/Group/sender-key-distribution-message.js +73 -63
  15. package/lib/Signal/Group/sender-key-message.js +75 -66
  16. package/lib/Signal/Group/sender-key-name.js +55 -44
  17. package/lib/Signal/Group/sender-key-record.js +49 -49
  18. package/lib/Signal/Group/sender-key-state.js +90 -93
  19. package/lib/Signal/Group/sender-message-key.js +37 -28
  20. package/lib/Signal/libsignal.js +324 -163
  21. package/lib/Signal/lid-mapping.js +166 -0
  22. package/lib/Socket/Client/index.js +14 -19
  23. package/lib/Socket/Client/types.js +13 -0
  24. package/lib/Socket/Client/websocket.js +62 -0
  25. package/lib/Socket/business.js +359 -242
  26. package/lib/Socket/chats.js +850 -935
  27. package/lib/Socket/communities.js +413 -0
  28. package/lib/Socket/groups.js +304 -309
  29. package/lib/Socket/index.js +25 -10
  30. package/lib/Socket/messages-recv.js +1107 -1054
  31. package/lib/Socket/messages-send.js +639 -448
  32. package/lib/Socket/mex.js +45 -0
  33. package/lib/Socket/newsletter.js +226 -306
  34. package/lib/Socket/socket.js +803 -638
  35. package/lib/Store/index.js +18 -10
  36. package/lib/Store/make-cache-manager-store.js +73 -81
  37. package/lib/Store/make-in-memory-store.js +286 -423
  38. package/lib/Store/make-ordered-dictionary.js +77 -79
  39. package/lib/Store/object-repository.js +24 -26
  40. package/lib/Types/Auth.js +13 -2
  41. package/lib/Types/Bussines.js +13 -0
  42. package/lib/Types/Call.js +13 -2
  43. package/lib/Types/Chat.js +19 -4
  44. package/lib/Types/Contact.js +13 -2
  45. package/lib/Types/Events.js +13 -2
  46. package/lib/Types/GroupMetadata.js +13 -2
  47. package/lib/Types/Label.js +43 -26
  48. package/lib/Types/Label.js.bak +25 -0
  49. package/lib/Types/LabelAssociation.js +16 -8
  50. package/lib/Types/Message.js +22 -9
  51. package/lib/Types/Newsletter.js +42 -37
  52. package/lib/Types/Product.js +13 -2
  53. package/lib/Types/Signal.js +13 -2
  54. package/lib/Types/Socket.js +14 -2
  55. package/lib/Types/State.js +21 -2
  56. package/lib/Types/USync.js +13 -2
  57. package/lib/Types/index.js +37 -41
  58. package/lib/Utils/auth-utils.js +219 -196
  59. package/lib/Utils/baileys-event-stream.js +50 -59
  60. package/lib/Utils/browser-utils.js +25 -0
  61. package/lib/Utils/business.js +213 -214
  62. package/lib/Utils/chat-utils.js +710 -687
  63. package/lib/Utils/crypto.js +112 -133
  64. package/lib/Utils/decode-wa-message.js +252 -183
  65. package/lib/Utils/event-buffer.js +510 -496
  66. package/lib/Utils/generics.js +319 -387
  67. package/lib/Utils/history.js +83 -92
  68. package/lib/Utils/index.js +31 -33
  69. package/lib/Utils/link-preview.js +71 -83
  70. package/lib/Utils/logger.js +5 -7
  71. package/lib/Utils/lt-hash.js +40 -46
  72. package/lib/Utils/make-mutex.js +34 -41
  73. package/lib/Utils/message-retry-manager.js +113 -0
  74. package/lib/Utils/messages-media.js +553 -768
  75. package/lib/Utils/messages-media.js.bak2 +602 -0
  76. package/lib/Utils/messages.js +354 -263
  77. package/lib/Utils/noise-handler.js +138 -149
  78. package/lib/Utils/pre-key-manager.js +95 -0
  79. package/lib/Utils/process-message.js +333 -303
  80. package/lib/Utils/signal.js +159 -141
  81. package/lib/Utils/use-multi-file-auth-state.js +105 -103
  82. package/lib/Utils/validate-connection.js +184 -203
  83. package/lib/WABinary/constants.js +1308 -35
  84. package/lib/WABinary/decode.js +247 -249
  85. package/lib/WABinary/encode.js +221 -258
  86. package/lib/WABinary/generic-utils.js +68 -65
  87. package/lib/WABinary/index.js +17 -21
  88. package/lib/WABinary/jid-utils.js +99 -58
  89. package/lib/WABinary/types.js +13 -2
  90. package/lib/WAM/BinaryInfo.js +20 -12
  91. package/lib/WAM/constants.js +22863 -15348
  92. package/lib/WAM/encode.js +145 -136
  93. package/lib/WAM/index.js +15 -19
  94. package/lib/WAUSync/Protocols/USyncContactProtocol.js +39 -31
  95. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +61 -54
  96. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +39 -29
  97. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +48 -40
  98. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -51
  99. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +38 -21
  100. package/lib/WAUSync/Protocols/index.js +17 -20
  101. package/lib/WAUSync/USyncQuery.js +98 -86
  102. package/lib/WAUSync/USyncUser.js +35 -26
  103. package/lib/WAUSync/index.js +16 -19
  104. package/lib/index.js +26 -94
  105. package/lib/index.js.bak +23 -0
  106. package/package.json +97 -113
  107. package/jessica.js +0 -91
  108. package/lib/Defaults/baileys-version.json +0 -3
  109. package/lib/Defaults/index.d.ts +0 -53
  110. package/lib/Defaults/phonenumber-mcc.json +0 -223
  111. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  112. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  113. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  114. package/lib/Signal/Group/index.d.ts +0 -11
  115. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  116. package/lib/Signal/Group/queue-job.d.ts +0 -1
  117. package/lib/Signal/Group/queue-job.js +0 -57
  118. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  119. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  120. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  121. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  122. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  123. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  124. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  125. package/lib/Signal/libsignal.d.ts +0 -3
  126. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  127. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  128. package/lib/Socket/Client/index.d.ts +0 -3
  129. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  130. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  131. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  132. package/lib/Socket/Client/web-socket-client.js +0 -62
  133. package/lib/Socket/business.d.ts +0 -171
  134. package/lib/Socket/chats.d.ts +0 -267
  135. package/lib/Socket/dugong.d.ts +0 -254
  136. package/lib/Socket/dugong.js +0 -484
  137. package/lib/Socket/groups.d.ts +0 -115
  138. package/lib/Socket/index.d.ts +0 -173
  139. package/lib/Socket/messages-recv.d.ts +0 -161
  140. package/lib/Socket/messages-send.d.ts +0 -149
  141. package/lib/Socket/newsletter.d.ts +0 -134
  142. package/lib/Socket/registration.d.ts +0 -267
  143. package/lib/Socket/registration.js +0 -166
  144. package/lib/Socket/socket.d.ts +0 -43
  145. package/lib/Socket/usync.d.ts +0 -36
  146. package/lib/Socket/usync.js +0 -70
  147. package/lib/Store/index.d.ts +0 -3
  148. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  149. package/lib/Store/make-in-memory-store.d.ts +0 -118
  150. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  151. package/lib/Store/object-repository.d.ts +0 -10
  152. package/lib/Types/Auth.d.ts +0 -110
  153. package/lib/Types/Call.d.ts +0 -13
  154. package/lib/Types/Chat.d.ts +0 -102
  155. package/lib/Types/Contact.d.ts +0 -19
  156. package/lib/Types/Events.d.ts +0 -157
  157. package/lib/Types/GroupMetadata.d.ts +0 -55
  158. package/lib/Types/Label.d.ts +0 -35
  159. package/lib/Types/LabelAssociation.d.ts +0 -29
  160. package/lib/Types/Message.d.ts +0 -273
  161. package/lib/Types/Newsletter.d.ts +0 -103
  162. package/lib/Types/Product.d.ts +0 -78
  163. package/lib/Types/Signal.d.ts +0 -57
  164. package/lib/Types/Socket.d.ts +0 -111
  165. package/lib/Types/State.d.ts +0 -27
  166. package/lib/Types/USync.d.ts +0 -25
  167. package/lib/Types/index.d.ts +0 -57
  168. package/lib/Utils/auth-utils.d.ts +0 -18
  169. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  170. package/lib/Utils/business.d.ts +0 -22
  171. package/lib/Utils/chat-utils.d.ts +0 -71
  172. package/lib/Utils/crypto.d.ts +0 -41
  173. package/lib/Utils/decode-wa-message.d.ts +0 -19
  174. package/lib/Utils/event-buffer.d.ts +0 -35
  175. package/lib/Utils/generics.d.ts +0 -92
  176. package/lib/Utils/history.d.ts +0 -15
  177. package/lib/Utils/index.d.ts +0 -17
  178. package/lib/Utils/link-preview.d.ts +0 -21
  179. package/lib/Utils/logger.d.ts +0 -4
  180. package/lib/Utils/lt-hash.d.ts +0 -12
  181. package/lib/Utils/make-mutex.d.ts +0 -7
  182. package/lib/Utils/messages-media.d.ts +0 -116
  183. package/lib/Utils/messages.d.ts +0 -77
  184. package/lib/Utils/noise-handler.d.ts +0 -21
  185. package/lib/Utils/process-message.d.ts +0 -41
  186. package/lib/Utils/signal.d.ts +0 -32
  187. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  188. package/lib/Utils/validate-connection.d.ts +0 -11
  189. package/lib/WABinary/constants.d.ts +0 -30
  190. package/lib/WABinary/decode.d.ts +0 -7
  191. package/lib/WABinary/encode.d.ts +0 -3
  192. package/lib/WABinary/generic-utils.d.ts +0 -17
  193. package/lib/WABinary/index.d.ts +0 -5
  194. package/lib/WABinary/jid-utils.d.ts +0 -31
  195. package/lib/WABinary/types.d.ts +0 -18
  196. package/lib/WAM/BinaryInfo.d.ts +0 -17
  197. package/lib/WAM/constants.d.ts +0 -38
  198. package/lib/WAM/encode.d.ts +0 -3
  199. package/lib/WAM/index.d.ts +0 -3
  200. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  201. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  202. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  203. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  204. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  205. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  206. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  207. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  208. package/lib/WAUSync/USyncUser.d.ts +0 -12
  209. package/lib/WAUSync/index.d.ts +0 -3
  210. package/lib/index.d.ts +0 -12
@@ -1,174 +1,335 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
1
+ //========================================//
2
+ /**
3
+ * @project @sixcore/baileys
4
+ * @author Sixx.js </>🌿
5
+ * @version 1.0.3
6
+ * @license MIT
7
+ * @country Mozambique 🇲🇿♥️
8
+ * @chamadas || sms +258860817689
9
+ * @whatsApp +55889616-2417 || +258851907875
10
+ * @description Biblioteca Node.js para integração e automação no WhatsApp usando Baileys
11
+ */
12
+
13
+
14
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, transferDevice, WAJIDDomains } from "../WABinary/index.js";
15
+ import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } from "./Group/index.js";
16
+ import { SenderKeyRecord } from "./Group/sender-key-record.js";
17
+ import { SenderKeyName } from "./Group/sender-key-name.js";
18
+ import { generateSignalPubKey } from "../Utils/index.js";
19
+ import { LIDMappingStore } from "./lid-mapping.js";
20
+ import * as libsignal from "libsignal-xeuka";
21
+ import { LRUCache } from "lru-cache";
22
+
23
+ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
24
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
25
+ const storage = signalStorage(auth, lidMapping);
26
+ const parsedKeys = auth.keys;
27
+ const migratedSessionCache = new LRUCache({
28
+ ttl: 7 * 24 * 60 * 60 * 1000,
29
+ ttlAutopurge: true,
30
+ updateAgeOnGet: true
31
+ });
32
+ const repository = {
33
+ decryptGroupMessage({ group, authorJid, msg }) {
34
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
35
+ const cipher = new GroupCipher(storage, senderName);
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("Group ID is required for sender key distribution message");
44
+ }
45
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
46
+ const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
47
+ const senderNameStr = senderName.toString();
48
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
49
+ if (!senderKey) {
50
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
51
+ }
52
+ return parsedKeys.transaction(async () => {
53
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
54
+ if (!senderKey) {
55
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
56
+ }
57
+ await builder.process(senderName, senderMsg);
58
+ }, item.groupId);
59
+ },
60
+ async decryptMessage({ jid, type, ciphertext }) {
61
+ const addr = jidToSignalProtocolAddress(jid);
62
+ const session = new libsignal.SessionCipher(storage, addr);
63
+ async function doDecrypt() {
64
+ let result;
65
+ switch (type) {
66
+ case "pkmsg":
67
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
68
+ break;
69
+ case "msg":
70
+ result = await session.decryptWhisperMessage(ciphertext);
71
+ break;
72
+ }
32
73
  return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.makeLibSignalRepository = makeLibSignalRepository;
37
- const libsignal = __importStar(require("libsignal"));
38
- const Utils_1 = require("../Utils");
39
- const WABinary_1 = require("../WABinary");
40
- const sender_key_name_1 = require("./Group/sender-key-name");
41
- const sender_key_record_1 = require("./Group/sender-key-record");
42
- const Group_1 = require("./Group");
43
- function makeLibSignalRepository(auth) {
44
- const storage = signalStorage(auth);
45
- return {
46
- decryptGroupMessage({ group, authorJid, msg }) {
47
- const senderName = jidToSignalSenderKeyName(group, authorJid);
48
- const cipher = new Group_1.GroupCipher(storage, senderName);
49
- return cipher.decrypt(msg);
50
- },
51
- async processSenderKeyDistributionMessage({ item, authorJid }) {
52
- const builder = new Group_1.GroupSessionBuilder(storage);
53
- if (!item.groupId) {
54
- throw new Error('Group ID is required for sender key distribution message');
55
- }
56
- const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
57
- const senderMsg = new Group_1.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
58
- const senderNameStr = senderName.toString();
59
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
60
- if (!senderKey) {
61
- await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
62
- }
63
- await builder.process(senderName, senderMsg);
64
- },
65
- async decryptMessage({ jid, type, ciphertext }) {
66
- const addr = jidToSignalProtocolAddress(jid);
67
- const session = new libsignal.SessionCipher(storage, addr);
68
- let result;
69
- switch (type) {
70
- case 'pkmsg':
71
- result = await session.decryptPreKeyWhisperMessage(ciphertext);
72
- break;
73
- case 'msg':
74
- result = await session.decryptWhisperMessage(ciphertext);
75
- break;
76
- default:
77
- throw new Error(`Unknown message type: ${type}`);
74
+ }
75
+ return parsedKeys.transaction(async () => {
76
+ return await doDecrypt();
77
+ }, jid);
78
+ },
79
+ async encryptMessage({ jid, data }) {
80
+ const addr = jidToSignalProtocolAddress(jid);
81
+ const cipher = new libsignal.SessionCipher(storage, addr);
82
+ return parsedKeys.transaction(async () => {
83
+ const { type: sigType, body } = await cipher.encrypt(data);
84
+ const type = sigType === 3 ? "pkmsg" : "msg";
85
+ return { type, ciphertext: Buffer.from(body, "binary") };
86
+ }, jid);
87
+ },
88
+ async encryptGroupMessage({ group, meId, data }) {
89
+ const senderName = jidToSignalSenderKeyName(group, meId);
90
+ const builder = new GroupSessionBuilder(storage);
91
+ const senderNameStr = senderName.toString();
92
+ return parsedKeys.transaction(async () => {
93
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
94
+ if (!senderKey) {
95
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
96
+ }
97
+ const senderKeyDistributionMessage = await builder.create(senderName);
98
+ const session = new GroupCipher(storage, senderName);
99
+ const ciphertext = await session.encrypt(data);
100
+ return {
101
+ ciphertext,
102
+ senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
103
+ };
104
+ }, group);
105
+ },
106
+ async injectE2ESession({ jid, session }) {
107
+ logger.trace({ jid }, "injecting E2EE session");
108
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
109
+ return parsedKeys.transaction(async () => {
110
+ await cipher.initOutgoing(session);
111
+ }, jid);
112
+ },
113
+ jidToSignalProtocolAddress(jid) {
114
+ return jidToSignalProtocolAddress(jid).toString();
115
+ },
116
+ lidMapping,
117
+ async validateSession(jid) {
118
+ try {
119
+ const addr = jidToSignalProtocolAddress(jid);
120
+ const session = await storage.loadSession(addr.toString());
121
+ if (!session) {
122
+ return { exists: false, reason: "no session" };
123
+ }
124
+ if (!session.haveOpenSession()) {
125
+ return { exists: false, reason: "no open session" };
126
+ }
127
+ return { exists: true };
128
+ }
129
+ catch (error) {
130
+ return { exists: false, reason: "validation error" };
131
+ }
132
+ },
133
+ async deleteSession(jids) {
134
+ if (!jids.length)
135
+ return;
136
+ const sessionUpdates = {};
137
+ jids.forEach(jid => {
138
+ const addr = jidToSignalProtocolAddress(jid);
139
+ sessionUpdates[addr.toString()] = null;
140
+ });
141
+ return parsedKeys.transaction(async () => {
142
+ await auth.keys.set({ session: sessionUpdates });
143
+ }, `delete-${jids.length}-sessions`);
144
+ },
145
+ async migrateSession(fromJid, toJid) {
146
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
147
+ return { migrated: 0, skipped: 0, total: 0 };
148
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
149
+ return { migrated: 0, skipped: 0, total: 1 };
150
+ }
151
+ const { user } = jidDecode(fromJid);
152
+ logger.debug({ fromJid }, "bulk device migration - loading all user devices");
153
+ const { [user]: userDevices } = await parsedKeys.get("device-list", [user]);
154
+ if (!userDevices) {
155
+ return { migrated: 0, skipped: 0, total: 0 };
156
+ }
157
+ const { device: fromDevice } = jidDecode(fromJid);
158
+ const fromDeviceStr = fromDevice?.toString() || "0";
159
+ if (!userDevices.includes(fromDeviceStr)) {
160
+ userDevices.push(fromDeviceStr);
161
+ }
162
+ const uncachedDevices = userDevices.filter(device => {
163
+ const deviceKey = `${user}.${device}`;
164
+ return !migratedSessionCache.has(deviceKey);
165
+ });
166
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
167
+ const existingSessions = await parsedKeys.get("session", deviceSessionKeys);
168
+ const deviceJids = [];
169
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
170
+ if (sessionData) {
171
+ const deviceStr = sessionKey.split(".")[1];
172
+ if (!deviceStr)
173
+ continue;
174
+ const deviceNum = parseInt(deviceStr);
175
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
176
+ if (deviceNum === 99) {
177
+ jid = `${user}:99@hosted`;
178
+ }
179
+ deviceJids.push(jid);
180
+ }
181
+ }
182
+ logger.debug({
183
+ fromJid,
184
+ totalDevices: userDevices.length,
185
+ devicesWithSessions: deviceJids.length,
186
+ devices: deviceJids
187
+ }, "bulk device migration complete - all user devices processed");
188
+ return parsedKeys.transaction(async () => {
189
+ const migrationOps = deviceJids.map(jid => {
190
+ const lidWithDevice = transferDevice(jid, toJid);
191
+ const fromDecoded = jidDecode(jid);
192
+ const toDecoded = jidDecode(lidWithDevice);
193
+ return {
194
+ fromJid: jid,
195
+ toJid: lidWithDevice,
196
+ pnUser: fromDecoded.user,
197
+ lidUser: toDecoded.user,
198
+ deviceId: fromDecoded.device || 0,
199
+ fromAddr: jidToSignalProtocolAddress(jid),
200
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
201
+ };
202
+ });
203
+ const totalOps = migrationOps.length;
204
+ let migratedCount = 0;
205
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
206
+ const pnSessions = await parsedKeys.get("session", pnAddrStrings);
207
+ const sessionUpdates = {};
208
+ for (const op of migrationOps) {
209
+ const pnAddrStr = op.fromAddr.toString();
210
+ const lidAddrStr = op.toAddr.toString();
211
+ const pnSession = pnSessions[pnAddrStr];
212
+ if (pnSession) {
213
+ const fromSession = libsignal.SessionRecord.deserialize(pnSession);
214
+ if (fromSession.haveOpenSession()) {
215
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
216
+ sessionUpdates[pnAddrStr] = null;
217
+ migratedCount++;
78
218
  }
79
- return result;
80
- },
81
- async encryptMessage({ jid, data }) {
82
- const addr = jidToSignalProtocolAddress(jid);
83
- const cipher = new libsignal.SessionCipher(storage, addr);
84
- const { type: sigType, body } = await cipher.encrypt(data);
85
- const type = sigType === 3 ? 'pkmsg' : 'msg';
86
- return { type, ciphertext: Buffer.from(body, 'binary') };
87
- },
88
- async encryptGroupMessage({ group, meId, data }) {
89
- const senderName = jidToSignalSenderKeyName(group, meId);
90
- const builder = new Group_1.GroupSessionBuilder(storage);
91
- const senderNameStr = senderName.toString();
92
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
93
- if (!senderKey) {
94
- await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
219
+ }
220
+ }
221
+ if (Object.keys(sessionUpdates).length > 0) {
222
+ await parsedKeys.set({ session: sessionUpdates });
223
+ logger.debug({ migratedSessions: migratedCount }, "bulk session migration complete");
224
+ for (const op of migrationOps) {
225
+ if (sessionUpdates[op.toAddr.toString()]) {
226
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
227
+ migratedSessionCache.set(deviceKey, true);
95
228
  }
96
- const senderKeyDistributionMessage = await builder.create(senderName);
97
- const session = new Group_1.GroupCipher(storage, senderName);
98
- const ciphertext = await session.encrypt(data);
99
- return {
100
- ciphertext,
101
- senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
102
- };
103
- },
104
- async injectE2ESession({ jid, session }) {
105
- const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
106
- await cipher.initOutgoing(session);
107
- },
108
- jidToSignalProtocolAddress(jid) {
109
- return jidToSignalProtocolAddress(jid).toString();
229
+ }
110
230
  }
111
- };
231
+ const skippedCount = totalOps - migratedCount;
232
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
233
+ }, `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`);
234
+ }
235
+ };
236
+ return repository;
112
237
  }
238
+
113
239
  const jidToSignalProtocolAddress = (jid) => {
114
- const { user, device } = (0, WABinary_1.jidDecode)(jid);
115
- return new libsignal.ProtocolAddress(user, device || 0);
240
+ const decoded = jidDecode(jid);
241
+ const { user, device, server, domainType } = decoded;
242
+ if (!user) {
243
+ throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
244
+ }
245
+ const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
246
+ const finalDevice = device || 0;
247
+ if (device === 99 && decoded.server !== "hosted" && decoded.server !== "hosted.lid") {
248
+ throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:" + jid);
249
+ }
250
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
116
251
  };
252
+
117
253
  const jidToSignalSenderKeyName = (group, user) => {
118
- return new sender_key_name_1.SenderKeyName(group, jidToSignalProtocolAddress(user));
254
+ return new SenderKeyName(group, jidToSignalProtocolAddress(user));
119
255
  };
120
- function signalStorage({ creds, keys }) {
121
- return {
122
- loadSession: async (id) => {
123
- const { [id]: sess } = await keys.get('session', [id]);
124
- if (sess) {
125
- return libsignal.SessionRecord.deserialize(sess);
126
- }
127
- },
128
- storeSession: async (id, session) => {
129
- await keys.set({ session: { [id]: session.serialize() } });
130
- },
131
- isTrustedIdentity: () => {
132
- return true;
133
- },
134
- loadPreKey: async (id) => {
135
- const keyId = id.toString();
136
- const { [keyId]: key } = await keys.get('pre-key', [keyId]);
137
- if (key) {
138
- return {
139
- privKey: Buffer.from(key.private),
140
- pubKey: Buffer.from(key.public)
141
- };
142
- }
143
- },
144
- removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
145
- loadSignedPreKey: () => {
146
- const key = creds.signedPreKey;
147
- return {
148
- privKey: Buffer.from(key.keyPair.private),
149
- pubKey: Buffer.from(key.keyPair.public)
150
- };
151
- },
152
- loadSenderKey: async (senderKeyName) => {
153
- const keyId = senderKeyName.toString();
154
- const { [keyId]: key } = await keys.get('sender-key', [keyId]);
155
- if (key) {
156
- return sender_key_record_1.SenderKeyRecord.deserialize(key);
157
- }
158
- return new sender_key_record_1.SenderKeyRecord();
159
- },
160
- storeSenderKey: async (senderKeyName, key) => {
161
- const keyId = senderKeyName.toString();
162
- const serialized = JSON.stringify(key.serialize());
163
- await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } });
164
- },
165
- getOurRegistrationId: () => creds.registrationId,
166
- getOurIdentity: () => {
167
- const { signedIdentityKey } = creds;
168
- return {
169
- privKey: Buffer.from(signedIdentityKey.private),
170
- pubKey: (0, Utils_1.generateSignalPubKey)(signedIdentityKey.public)
171
- };
256
+
257
+ function signalStorage({ creds, keys }, lidMapping) {
258
+ const resolveLIDSignalAddress = async (id) => {
259
+ if (id.includes(".")) {
260
+ const [deviceId, device] = id.split(".");
261
+ const [user, domainType_] = deviceId.split("_");
262
+ const domainType = parseInt(domainType_ || "0");
263
+ if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID)
264
+ return id;
265
+ const pnJid = `${user}${device !== "0" ? `:${device}` : ""}@${domainType === WAJIDDomains.HOSTED ? "hosted" : "s.whatsapp.net"}`;
266
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
267
+ if (lidForPN) {
268
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
269
+ return lidAddr.toString();
270
+ }
271
+ }
272
+ return id;
273
+ };
274
+ return {
275
+ loadSession: async (id) => {
276
+ try {
277
+ const wireJid = await resolveLIDSignalAddress(id);
278
+ const { [wireJid]: sess } = await keys.get("session", [wireJid]);
279
+ if (sess) {
280
+ return libsignal.SessionRecord.deserialize(sess);
172
281
  }
173
- };
282
+ }
283
+ catch (e) {
284
+ return null;
285
+ }
286
+ return null;
287
+ },
288
+ storeSession: async (id, session) => {
289
+ const wireJid = await resolveLIDSignalAddress(id);
290
+ await keys.set({ session: { [wireJid]: session.serialize() } });
291
+ },
292
+ isTrustedIdentity: () => {
293
+ return true;
294
+ },
295
+ loadPreKey: async (id) => {
296
+ const keyId = id.toString();
297
+ const { [keyId]: key } = await keys.get("pre-key", [keyId]);
298
+ if (key) {
299
+ return {
300
+ privKey: Buffer.from(key.private),
301
+ pubKey: Buffer.from(key.public)
302
+ };
303
+ }
304
+ },
305
+ removePreKey: (id) => keys.set({ "pre-key": { [id]: null } }),
306
+ loadSignedPreKey: () => {
307
+ const key = creds.signedPreKey;
308
+ return {
309
+ privKey: Buffer.from(key.keyPair.private),
310
+ pubKey: Buffer.from(key.keyPair.public)
311
+ };
312
+ },
313
+ loadSenderKey: async (senderKeyName) => {
314
+ const keyId = senderKeyName.toString();
315
+ const { [keyId]: key } = await keys.get("sender-key", [keyId]);
316
+ if (key) {
317
+ return SenderKeyRecord.deserialize(key);
318
+ }
319
+ return new SenderKeyRecord();
320
+ },
321
+ storeSenderKey: async (senderKeyName, key) => {
322
+ const keyId = senderKeyName.toString();
323
+ const serialized = JSON.stringify(key.serialize());
324
+ await keys.set({ "sender-key": { [keyId]: Buffer.from(serialized, "utf-8") } });
325
+ },
326
+ getOurRegistrationId: () => creds.registrationId,
327
+ getOurIdentity: () => {
328
+ const { signedIdentityKey } = creds;
329
+ return {
330
+ privKey: Buffer.from(signedIdentityKey.private),
331
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
332
+ };
333
+ }
334
+ };
174
335
  }
@@ -0,0 +1,166 @@
1
+ //========================================//
2
+ /**
3
+ * @project @sixcore/baileys
4
+ * @author Sixx.js </>🌿
5
+ * @version 1.0.3
6
+ * @license MIT
7
+ * @country Mozambique 🇲🇿♥️
8
+ * @chamadas || sms +258860817689
9
+ * @whatsApp +55889616-2417 || +258851907875
10
+ * @description Biblioteca Node.js para integração e automação no WhatsApp usando Baileys
11
+ */
12
+
13
+
14
+ import { isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, WAJIDDomains } from "../WABinary/index.js";
15
+ import { LRUCache } from "lru-cache";
16
+
17
+ export class LIDMappingStore {
18
+ constructor(keys, logger, pnToLIDFunc) {
19
+ this.mappingCache = new LRUCache({
20
+ ttl: 7 * 24 * 60 * 60 * 1000,
21
+ ttlAutopurge: true,
22
+ updateAgeOnGet: true
23
+ });
24
+ this.keys = keys;
25
+ this.pnToLIDFunc = pnToLIDFunc;
26
+ this.logger = logger;
27
+ }
28
+ async storeLIDPNMappings(pairs) {
29
+ const pairMap = {};
30
+ for (const { lid, pn } of pairs) {
31
+ if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
32
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
33
+ continue;
34
+ }
35
+ const lidDecoded = jidDecode(lid);
36
+ const pnDecoded = jidDecode(pn);
37
+ if (!lidDecoded || !pnDecoded)
38
+ return;
39
+ const pnUser = pnDecoded.user;
40
+ const lidUser = lidDecoded.user;
41
+ let existingLidUser = this.mappingCache.get(`pn:${pnUser}`);
42
+ if (!existingLidUser) {
43
+ this.logger.trace(`Cache miss for PN user ${pnUser}; checking database`);
44
+ const stored = await this.keys.get("lid-mapping", [pnUser]);
45
+ existingLidUser = stored[pnUser];
46
+ if (existingLidUser) {
47
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
48
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
49
+ }
50
+ }
51
+ if (existingLidUser === lidUser) {
52
+ this.logger.debug({ pnUser, lidUser }, "LID mapping already exists, skipping");
53
+ continue;
54
+ }
55
+ pairMap[pnUser] = lidUser;
56
+ }
57
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
58
+ await this.keys.transaction(async () => {
59
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
60
+ await this.keys.set({
61
+ "lid-mapping": {
62
+ [pnUser]: lidUser,
63
+ [`${lidUser}_reverse`]: pnUser
64
+ }
65
+ });
66
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
67
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
68
+ }
69
+ }, "lid-mapping");
70
+ }
71
+ async getLIDForPN(pn) {
72
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
73
+ }
74
+ async getLIDsForPNs(pns) {
75
+ const usyncFetch = {};
76
+ const successfulPairs = {};
77
+ for (const pn of pns) {
78
+ if (!isPnUser(pn) && !isHostedPnUser(pn))
79
+ continue;
80
+ const decoded = jidDecode(pn);
81
+ if (!decoded)
82
+ continue;
83
+ const pnUser = decoded.user;
84
+ let lidUser = this.mappingCache.get(`pn:${pnUser}`);
85
+ if (!lidUser) {
86
+ const stored = await this.keys.get("lid-mapping", [pnUser]);
87
+ lidUser = stored[pnUser];
88
+ if (lidUser) {
89
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
90
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
91
+ }
92
+ else {
93
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
94
+ const device = decoded.device || 0;
95
+ let normalizedPn = jidNormalizedUser(pn);
96
+ if (isHostedPnUser(normalizedPn)) {
97
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
98
+ }
99
+ if (!usyncFetch[normalizedPn]) {
100
+ usyncFetch[normalizedPn] = [device];
101
+ }
102
+ else {
103
+ usyncFetch[normalizedPn]?.push(device);
104
+ }
105
+ continue;
106
+ }
107
+ }
108
+ lidUser = lidUser.toString();
109
+ if (!lidUser) {
110
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
111
+ return null;
112
+ }
113
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
114
+ const deviceSpecificLid = `${lidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === "hosted" ? "hosted.lid" : "lid"}`;
115
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
116
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn };
117
+ }
118
+ if (Object.keys(usyncFetch).length > 0) {
119
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch));
120
+ if (result && result.length > 0) {
121
+ this.storeLIDPNMappings(result);
122
+ for (const pair of result) {
123
+ const pnDecoded = jidDecode(pair.pn);
124
+ const pnUser = pnDecoded?.user;
125
+ if (!pnUser)
126
+ continue;
127
+ const lidUser = jidDecode(pair.lid)?.user;
128
+ if (!lidUser)
129
+ continue;
130
+ for (const device of usyncFetch[pair.pn]) {
131
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted.lid" : "lid"}`;
132
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
133
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted" : "s.whatsapp.net"}`;
134
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
135
+ }
136
+ }
137
+ }
138
+ else {
139
+ return null;
140
+ }
141
+ }
142
+ return Object.values(successfulPairs);
143
+ }
144
+ async getPNForLID(lid) {
145
+ if (!isLidUser(lid))
146
+ return null;
147
+ const decoded = jidDecode(lid);
148
+ if (!decoded)
149
+ return null;
150
+ const lidUser = decoded.user;
151
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
152
+ if (!pnUser || typeof pnUser !== "string") {
153
+ const stored = await this.keys.get("lid-mapping", [`${lidUser}_reverse`]);
154
+ pnUser = stored[`${lidUser}_reverse`];
155
+ if (!pnUser || typeof pnUser !== "string") {
156
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
157
+ return null;
158
+ }
159
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
160
+ }
161
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
162
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? "hosted" : "s.whatsapp.net"}`;
163
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
164
+ return pnJid;
165
+ }
166
+ }