socketon 1.31.2-rc → 1.51.17

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