@alannxd/baileys 6.0.5 → 6.0.6

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 (234) hide show
  1. package/WAProto/fix-import.js +29 -0
  2. package/WAProto/index.js +160 -201
  3. package/engine-requirements.js +1 -1
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.d.ts +15 -37
  6. package/lib/Defaults/index.js +136 -119
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +0 -1
  9. package/lib/Signal/Group/ciphertext-message.js +5 -2
  10. package/lib/Signal/Group/group-session-builder.d.ts +3 -4
  11. package/lib/Signal/Group/group-session-builder.js +41 -7
  12. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  13. package/lib/Signal/Group/group_cipher.js +51 -37
  14. package/lib/Signal/Group/index.d.ts +11 -12
  15. package/lib/Signal/Group/index.js +57 -12
  16. package/lib/Signal/Group/keyhelper.d.ts +1 -2
  17. package/lib/Signal/Group/keyhelper.js +44 -7
  18. package/lib/Signal/Group/queue-job.d.ts +1 -0
  19. package/lib/Signal/Group/queue-job.js +57 -0
  20. package/lib/Signal/Group/sender-chain-key.d.ts +2 -3
  21. package/lib/Signal/Group/sender-chain-key.js +15 -7
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -2
  23. package/lib/Signal/Group/sender-key-distribution-message.js +11 -8
  24. package/lib/Signal/Group/sender-key-message.d.ts +1 -2
  25. package/lib/Signal/Group/sender-key-message.js +12 -9
  26. package/lib/Signal/Group/sender-key-name.d.ts +0 -1
  27. package/lib/Signal/Group/sender-key-name.js +5 -2
  28. package/lib/Signal/Group/sender-key-record.d.ts +2 -3
  29. package/lib/Signal/Group/sender-key-record.js +21 -9
  30. package/lib/Signal/Group/sender-key-state.d.ts +6 -7
  31. package/lib/Signal/Group/sender-key-state.js +42 -27
  32. package/lib/Signal/Group/sender-message-key.d.ts +0 -1
  33. package/lib/Signal/Group/sender-message-key.js +7 -4
  34. package/lib/Signal/libsignal.d.ts +3 -5
  35. package/lib/Signal/libsignal.js +90 -347
  36. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +5 -4
  37. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  38. package/lib/Socket/Client/index.d.ts +3 -3
  39. package/lib/Socket/Client/index.js +19 -3
  40. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  41. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  42. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +2 -3
  43. package/lib/Socket/Client/web-socket-client.js +62 -0
  44. package/lib/Socket/business.d.ts +108 -154
  45. package/lib/Socket/business.js +43 -162
  46. package/lib/Socket/chats.d.ts +239 -96
  47. package/lib/Socket/chats.js +427 -627
  48. package/lib/Socket/communities.d.ts +146 -239
  49. package/lib/Socket/communities.js +80 -90
  50. package/lib/Socket/groups.d.ts +57 -104
  51. package/lib/Socket/groups.js +161 -154
  52. package/lib/Socket/index.d.ts +115 -202
  53. package/lib/Socket/index.js +10 -11
  54. package/lib/Socket/luxu.d.ts +266 -22
  55. package/lib/Socket/luxu.js +465 -422
  56. package/lib/Socket/messages-recv.d.ts +84 -136
  57. package/lib/Socket/messages-recv.js +615 -1421
  58. package/lib/Socket/messages-send.d.ts +126 -142
  59. package/lib/Socket/messages-send.js +671 -878
  60. package/lib/Socket/newsletter.d.ts +85 -121
  61. package/lib/Socket/newsletter.js +272 -147
  62. package/lib/Socket/registration.d.ts +267 -0
  63. package/lib/Socket/registration.js +166 -0
  64. package/lib/Socket/socket.d.ts +19 -34
  65. package/lib/Socket/socket.js +313 -544
  66. package/lib/Socket/usync.d.ts +36 -0
  67. package/lib/Socket/usync.js +70 -0
  68. package/lib/Store/index.d.ts +3 -10
  69. package/lib/Store/index.js +10 -10
  70. package/lib/Store/make-cache-manager-store.d.ts +11 -17
  71. package/lib/Store/make-cache-manager-store.js +41 -43
  72. package/lib/Store/make-in-memory-store.d.ts +118 -39
  73. package/lib/Store/make-in-memory-store.js +341 -112
  74. package/lib/Store/make-ordered-dictionary.d.ts +10 -11
  75. package/lib/Store/make-ordered-dictionary.js +20 -14
  76. package/lib/Store/object-repository.d.ts +9 -10
  77. package/lib/Store/object-repository.js +6 -11
  78. package/lib/Types/Auth.d.ts +12 -19
  79. package/lib/Types/Auth.js +2 -2
  80. package/lib/Types/Call.d.ts +1 -3
  81. package/lib/Types/Call.js +2 -2
  82. package/lib/Types/Chat.d.ts +13 -35
  83. package/lib/Types/Chat.js +4 -8
  84. package/lib/Types/Contact.d.ts +1 -8
  85. package/lib/Types/Contact.js +2 -2
  86. package/lib/Types/Events.d.ts +17 -116
  87. package/lib/Types/Events.js +2 -2
  88. package/lib/Types/GroupMetadata.d.ts +5 -21
  89. package/lib/Types/GroupMetadata.js +2 -2
  90. package/lib/Types/Label.d.ts +0 -12
  91. package/lib/Types/Label.js +5 -3
  92. package/lib/Types/LabelAssociation.d.ts +0 -1
  93. package/lib/Types/LabelAssociation.js +5 -3
  94. package/lib/Types/Message.d.ts +58 -105
  95. package/lib/Types/Message.js +9 -11
  96. package/lib/Types/Newsletter.d.ts +103 -0
  97. package/lib/Types/Newsletter.js +38 -0
  98. package/lib/Types/Product.d.ts +1 -2
  99. package/lib/Types/Product.js +2 -2
  100. package/lib/Types/Signal.d.ts +2 -32
  101. package/lib/Types/Signal.js +2 -2
  102. package/lib/Types/Socket.d.ts +25 -50
  103. package/lib/Types/Socket.js +2 -3
  104. package/lib/Types/State.d.ts +2 -72
  105. package/lib/Types/State.js +2 -56
  106. package/lib/Types/USync.d.ts +2 -3
  107. package/lib/Types/USync.js +2 -2
  108. package/lib/Types/index.d.ts +14 -22
  109. package/lib/Types/index.js +31 -15
  110. package/lib/Utils/auth-utils.d.ts +6 -12
  111. package/lib/Utils/auth-utils.js +143 -239
  112. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  113. package/lib/Utils/baileys-event-stream.js +63 -0
  114. package/lib/Utils/business.d.ts +2 -3
  115. package/lib/Utils/business.js +69 -66
  116. package/lib/Utils/chat-utils.d.ts +23 -52
  117. package/lib/Utils/chat-utils.js +253 -396
  118. package/lib/Utils/crypto.d.ts +22 -18
  119. package/lib/Utils/crypto.js +90 -57
  120. package/lib/Utils/decode-wa-message.d.ts +8 -55
  121. package/lib/Utils/decode-wa-message.js +84 -203
  122. package/lib/Utils/event-buffer.d.ts +8 -9
  123. package/lib/Utils/event-buffer.js +77 -185
  124. package/lib/Utils/generics.d.ts +29 -28
  125. package/lib/Utils/generics.js +210 -180
  126. package/lib/Utils/history.d.ts +9 -18
  127. package/lib/Utils/history.js +55 -93
  128. package/lib/Utils/index.d.ts +17 -22
  129. package/lib/Utils/index.js +33 -22
  130. package/lib/Utils/link-preview.d.ts +5 -5
  131. package/lib/Utils/link-preview.js +24 -16
  132. package/lib/Utils/logger.d.ts +3 -11
  133. package/lib/Utils/logger.js +7 -3
  134. package/lib/Utils/lt-hash.d.ts +12 -8
  135. package/lib/Utils/lt-hash.js +46 -3
  136. package/lib/Utils/make-mutex.d.ts +2 -4
  137. package/lib/Utils/make-mutex.js +34 -24
  138. package/lib/Utils/messages-media.d.ts +44 -61
  139. package/lib/Utils/messages-media.js +482 -451
  140. package/lib/Utils/messages.d.ts +18 -32
  141. package/lib/Utils/messages.js +369 -458
  142. package/lib/Utils/noise-handler.d.ts +14 -13
  143. package/lib/Utils/noise-handler.js +99 -145
  144. package/lib/Utils/process-message.d.ts +12 -31
  145. package/lib/Utils/process-message.js +150 -459
  146. package/lib/Utils/signal.d.ts +5 -20
  147. package/lib/Utils/signal.js +72 -120
  148. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  149. package/lib/Utils/use-multi-file-auth-state.js +27 -29
  150. package/lib/Utils/validate-connection.d.ts +7 -7
  151. package/lib/Utils/validate-connection.js +99 -73
  152. package/lib/WABinary/constants.d.ts +27 -25
  153. package/lib/WABinary/constants.js +20 -1281
  154. package/lib/WABinary/decode.d.ts +5 -5
  155. package/lib/WABinary/decode.js +42 -52
  156. package/lib/WABinary/encode.d.ts +3 -3
  157. package/lib/WABinary/encode.js +155 -110
  158. package/lib/WABinary/generic-utils.d.ts +7 -8
  159. package/lib/WABinary/generic-utils.js +49 -48
  160. package/lib/WABinary/index.d.ts +5 -6
  161. package/lib/WABinary/index.js +21 -6
  162. package/lib/WABinary/jid-utils.d.ts +8 -25
  163. package/lib/WABinary/jid-utils.js +40 -74
  164. package/lib/WABinary/types.d.ts +1 -2
  165. package/lib/WABinary/types.js +2 -2
  166. package/lib/WAM/BinaryInfo.d.ts +11 -3
  167. package/lib/WAM/BinaryInfo.js +5 -2
  168. package/lib/WAM/constants.d.ts +3 -5
  169. package/lib/WAM/constants.js +11958 -19461
  170. package/lib/WAM/encode.d.ts +3 -3
  171. package/lib/WAM/encode.js +22 -17
  172. package/lib/WAM/index.d.ts +3 -4
  173. package/lib/WAM/index.js +19 -4
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -4
  175. package/lib/WAUSync/Protocols/USyncContactProtocol.js +13 -33
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -3
  177. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -3
  179. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -3
  181. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -4
  183. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -5
  185. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +8 -13
  186. package/lib/WAUSync/Protocols/index.d.ts +4 -6
  187. package/lib/WAUSync/Protocols/index.js +20 -6
  188. package/lib/WAUSync/USyncQuery.d.ts +4 -6
  189. package/lib/WAUSync/USyncQuery.js +35 -44
  190. package/lib/WAUSync/USyncUser.d.ts +5 -10
  191. package/lib/WAUSync/USyncUser.js +5 -10
  192. package/lib/WAUSync/index.js +19 -4
  193. package/lib/index.d.ts +9 -10
  194. package/lib/index.js +34 -12
  195. package/package.json +50 -83
  196. package/WAProto/GenerateStatics.sh +0 -3
  197. package/WAProto/WAProto.proto +0 -5479
  198. package/WAProto/fix-imports.js +0 -85
  199. package/WAProto/index.d.ts +0 -14017
  200. package/lib/Signal/lid-mapping.d.ts +0 -23
  201. package/lib/Signal/lid-mapping.js +0 -277
  202. package/lib/Socket/Client/types.js +0 -11
  203. package/lib/Socket/Client/websocket.js +0 -54
  204. package/lib/Socket/mex.d.ts +0 -3
  205. package/lib/Socket/mex.js +0 -42
  206. package/lib/Store/keyed-db.d.ts +0 -22
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Types/Bussines.d.ts +0 -25
  209. package/lib/Types/Bussines.js +0 -2
  210. package/lib/Types/Mex.d.ts +0 -141
  211. package/lib/Types/Mex.js +0 -37
  212. package/lib/Utils/browser-utils.d.ts +0 -4
  213. package/lib/Utils/browser-utils.js +0 -28
  214. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  215. package/lib/Utils/companion-reg-client-utils.js +0 -35
  216. package/lib/Utils/identity-change-handler.d.ts +0 -44
  217. package/lib/Utils/identity-change-handler.js +0 -50
  218. package/lib/Utils/message-retry-manager.d.ts +0 -115
  219. package/lib/Utils/message-retry-manager.js +0 -265
  220. package/lib/Utils/offline-node-processor.d.ts +0 -17
  221. package/lib/Utils/offline-node-processor.js +0 -40
  222. package/lib/Utils/pre-key-manager.d.ts +0 -28
  223. package/lib/Utils/pre-key-manager.js +0 -106
  224. package/lib/Utils/reporting-utils.d.ts +0 -11
  225. package/lib/Utils/reporting-utils.js +0 -258
  226. package/lib/Utils/stanza-ack.d.ts +0 -11
  227. package/lib/Utils/stanza-ack.js +0 -38
  228. package/lib/Utils/sync-action-utils.d.ts +0 -19
  229. package/lib/Utils/sync-action-utils.js +0 -49
  230. package/lib/Utils/tc-token-utils.d.ts +0 -37
  231. package/lib/Utils/tc-token-utils.js +0 -163
  232. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  233. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  234. package/lib/WAUSync/index.d.ts +0 -4
@@ -1,391 +1,135 @@
1
- // @ts-ignore
2
- import * as libsignal from 'libsignal';
3
- // @ts-ignore
4
- import { PreKeyWhisperMessage } from 'libsignal/src/protobufs.js';
5
- import { LRUCache } from 'lru-cache';
6
- import { generateSignalPubKey } from '../Utils/index.js';
7
- import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, transferDevice, WAJIDDomains } from '../WABinary/index.js';
8
- import { SenderKeyName } from './Group/sender-key-name.js';
9
- import { SenderKeyRecord } from './Group/sender-key-record.js';
10
- import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } from './Group/index.js';
11
- import { LIDMappingStore } from './lid-mapping.js';
12
- /** Extract identity key from PreKeyWhisperMessage for identity change detection */
13
- function extractIdentityFromPkmsg(ciphertext) {
14
- try {
15
- if (!ciphertext || ciphertext.length < 2) {
16
- return undefined;
17
- }
18
- // Version byte check (version 3)
19
- const version = ciphertext[0];
20
- if ((version & 0xf) !== 3) {
21
- return undefined;
22
- }
23
- // Parse protobuf (skip version byte)
24
- const preKeyProto = PreKeyWhisperMessage.decode(ciphertext.slice(1));
25
- if (preKeyProto.identityKey?.length === 33) {
26
- return new Uint8Array(preKeyProto.identityKey);
27
- }
28
- return undefined;
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]; } };
29
7
  }
30
- catch {
31
- return undefined;
32
- }
33
- }
34
- export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
35
- const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
36
- const storage = signalStorage(auth, lidMapping);
37
- const parsedKeys = auth.keys;
38
- const migratedSessionCache = new LRUCache({
39
- ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
40
- ttlAutopurge: true,
41
- updateAgeOnGet: true
42
- });
43
- const ensureSenderKeyAndCreateSkdm = async (group, meId) => {
44
- const senderName = jidToSignalSenderKeyName(group, meId);
45
- const senderNameStr = senderName.toString();
46
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
47
- if (!senderKey) {
48
- await storage.storeSenderKey(senderName, new SenderKeyRecord());
49
- }
50
- const skdm = await new GroupSessionBuilder(storage).create(senderName);
51
- return { senderName, skdm };
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);
32
+ return result;
52
33
  };
53
- const repository = {
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 {
54
46
  decryptGroupMessage({ group, authorJid, msg }) {
55
47
  const senderName = jidToSignalSenderKeyName(group, authorJid);
56
- const cipher = new GroupCipher(storage, senderName);
57
- // Use transaction to ensure atomicity
58
- return parsedKeys.transaction(async () => {
59
- return cipher.decrypt(msg);
60
- }, group);
48
+ const cipher = new Group_1.GroupCipher(storage, senderName);
49
+ return cipher.decrypt(msg);
61
50
  },
62
51
  async processSenderKeyDistributionMessage({ item, authorJid }) {
63
- const builder = new GroupSessionBuilder(storage);
52
+ const builder = new Group_1.GroupSessionBuilder(storage);
64
53
  if (!item.groupId) {
65
54
  throw new Error('Group ID is required for sender key distribution message');
66
55
  }
67
56
  const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
68
- const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
57
+ const senderMsg = new Group_1.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
69
58
  const senderNameStr = senderName.toString();
70
59
  const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
71
60
  if (!senderKey) {
72
- await storage.storeSenderKey(senderName, new SenderKeyRecord());
61
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
73
62
  }
74
- return parsedKeys.transaction(async () => {
75
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
76
- if (!senderKey) {
77
- await storage.storeSenderKey(senderName, new SenderKeyRecord());
78
- }
79
- await builder.process(senderName, senderMsg);
80
- }, item.groupId);
63
+ await builder.process(senderName, senderMsg);
81
64
  },
82
65
  async decryptMessage({ jid, type, ciphertext }) {
83
66
  const addr = jidToSignalProtocolAddress(jid);
84
67
  const session = new libsignal.SessionCipher(storage, addr);
85
- // Extract and save sender's identity key before decryption for identity change detection
86
- if (type === 'pkmsg') {
87
- const identityKey = extractIdentityFromPkmsg(ciphertext);
88
- if (identityKey) {
89
- const addrStr = addr.toString();
90
- const identityChanged = await storage.saveIdentity(addrStr, identityKey);
91
- if (identityChanged) {
92
- logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established');
93
- }
94
- }
95
- }
96
- async function doDecrypt() {
97
- let result;
98
- switch (type) {
99
- case 'pkmsg':
100
- result = await session.decryptPreKeyWhisperMessage(ciphertext);
101
- break;
102
- case 'msg':
103
- result = await session.decryptWhisperMessage(ciphertext);
104
- break;
105
- }
106
- return result;
107
- }
108
- // If it's not a sync message, we need to ensure atomicity
109
- // For regular messages, we use a transaction to ensure atomicity
110
- return parsedKeys.transaction(async () => {
111
- return await doDecrypt();
112
- }, jid);
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}`);
78
+ }
79
+ return result;
113
80
  },
114
81
  async encryptMessage({ jid, data }) {
115
82
  const addr = jidToSignalProtocolAddress(jid);
116
83
  const cipher = new libsignal.SessionCipher(storage, addr);
117
- // Use transaction to ensure atomicity
118
- return parsedKeys.transaction(async () => {
119
- const { type: sigType, body } = await cipher.encrypt(data);
120
- const type = sigType === 3 ? 'pkmsg' : 'msg';
121
- return { type, ciphertext: Buffer.from(body, 'binary') };
122
- }, jid);
84
+ const { type: sigType, body } = await cipher.encrypt(data);
85
+ const type = sigType === 3 ? 'pkmsg' : 'msg';
86
+ return { type, ciphertext: Buffer.from(body, 'binary') };
123
87
  },
124
88
  async encryptGroupMessage({ group, meId, data }) {
125
- return parsedKeys.transaction(async () => {
126
- const { senderName, skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
127
- const ciphertext = await new GroupCipher(storage, senderName).encrypt(data);
128
- return { ciphertext, senderKeyDistributionMessage: skdm.serialize() };
129
- }, group);
130
- },
131
- async getSenderKeyDistributionMessage({ group, meId }) {
132
- return parsedKeys.transaction(async () => {
133
- const { skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
134
- return skdm.serialize();
135
- }, group);
136
- },
137
- async hasSenderKey({ group, meId }) {
138
- const senderName = jidToSignalSenderKeyName(group, meId).toString();
139
- const { [senderName]: key } = await auth.keys.get('sender-key', [senderName]);
140
- return !!key;
141
- },
142
- async getSessionInfo(jid) {
143
- const addr = jidToSignalProtocolAddress(jid).toString();
144
- const session = (await storage.loadSession(addr));
145
- if (!session) {
146
- return null;
147
- }
148
- const open = session.getOpenSession?.();
149
- const baseKey = open?.indexInfo?.baseKey;
150
- const registrationId = open?.registrationId;
151
- if (!baseKey || typeof registrationId !== 'number') {
152
- return null;
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());
153
95
  }
154
- return { baseKey: new Uint8Array(baseKey), registrationId };
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
+ };
155
103
  },
156
104
  async injectE2ESession({ jid, session }) {
157
- logger.trace({ jid }, 'injecting E2EE session');
158
105
  const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
159
- return parsedKeys.transaction(async () => {
160
- // libsignal runtime accepts an absent prekey (initOutgoing checks `device.preKey && ...`)
161
- // but the bundled .d.ts marks it required.
162
- await cipher.initOutgoing(session);
163
- }, jid);
106
+ await cipher.initOutgoing(session);
164
107
  },
165
108
  jidToSignalProtocolAddress(jid) {
166
109
  return jidToSignalProtocolAddress(jid).toString();
167
- },
168
- // Optimized direct access to LID mapping store
169
- lidMapping,
170
- async validateSession(jid) {
171
- try {
172
- const addr = jidToSignalProtocolAddress(jid);
173
- const session = await storage.loadSession(addr.toString());
174
- if (!session) {
175
- return { exists: false, reason: 'no session' };
176
- }
177
- if (!session.haveOpenSession()) {
178
- return { exists: false, reason: 'no open session' };
179
- }
180
- return { exists: true };
181
- }
182
- catch (error) {
183
- return { exists: false, reason: 'validation error' };
184
- }
185
- },
186
- async deleteSession(jids) {
187
- if (!jids.length)
188
- return;
189
- // Convert JIDs to signal addresses and prepare for bulk deletion
190
- const sessionUpdates = {};
191
- jids.forEach(jid => {
192
- const addr = jidToSignalProtocolAddress(jid);
193
- sessionUpdates[addr.toString()] = null;
194
- });
195
- // Single transaction for all deletions
196
- return parsedKeys.transaction(async () => {
197
- await auth.keys.set({ session: sessionUpdates });
198
- }, `delete-${jids.length}-sessions`);
199
- },
200
- close() {
201
- migratedSessionCache.clear();
202
- lidMapping.close();
203
- },
204
- async migrateSession(fromJid, toJid) {
205
- // TODO: use usync to handle this entire mess
206
- if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
207
- return { migrated: 0, skipped: 0, total: 0 };
208
- // Only support PN to LID migration
209
- if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
210
- return { migrated: 0, skipped: 0, total: 1 };
211
- }
212
- const { user } = jidDecode(fromJid);
213
- logger.debug({ fromJid }, 'bulk device migration - loading all user devices');
214
- // Get user's device list from storage
215
- const { [user]: userDevices } = await parsedKeys.get('device-list', [user]);
216
- if (!userDevices) {
217
- return { migrated: 0, skipped: 0, total: 0 };
218
- }
219
- const { device: fromDevice } = jidDecode(fromJid);
220
- const fromDeviceStr = fromDevice?.toString() || '0';
221
- if (!userDevices.includes(fromDeviceStr)) {
222
- userDevices.push(fromDeviceStr);
223
- }
224
- // Filter out cached devices before database fetch
225
- const uncachedDevices = userDevices.filter(device => {
226
- const deviceKey = `${user}.${device}`;
227
- return !migratedSessionCache.has(deviceKey);
228
- });
229
- // Bulk check session existence only for uncached devices
230
- const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
231
- const existingSessions = await parsedKeys.get('session', deviceSessionKeys);
232
- // Step 3: Convert existing sessions to JIDs (only migrate sessions that exist)
233
- const deviceJids = [];
234
- for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
235
- if (sessionData) {
236
- // Session exists in storage
237
- const deviceStr = sessionKey.split('.')[1];
238
- if (!deviceStr)
239
- continue;
240
- const deviceNum = parseInt(deviceStr);
241
- let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
242
- if (deviceNum === 99) {
243
- jid = `${user}:99@hosted`;
244
- }
245
- deviceJids.push(jid);
246
- }
247
- }
248
- logger.debug({
249
- fromJid,
250
- totalDevices: userDevices.length,
251
- devicesWithSessions: deviceJids.length,
252
- devices: deviceJids
253
- }, 'bulk device migration complete - all user devices processed');
254
- // Single transaction for all migrations
255
- return parsedKeys.transaction(async () => {
256
- const migrationOps = deviceJids.map(jid => {
257
- const lidWithDevice = transferDevice(jid, toJid);
258
- const fromDecoded = jidDecode(jid);
259
- const toDecoded = jidDecode(lidWithDevice);
260
- return {
261
- fromJid: jid,
262
- toJid: lidWithDevice,
263
- pnUser: fromDecoded.user,
264
- lidUser: toDecoded.user,
265
- deviceId: fromDecoded.device || 0,
266
- fromAddr: jidToSignalProtocolAddress(jid),
267
- toAddr: jidToSignalProtocolAddress(lidWithDevice)
268
- };
269
- });
270
- const totalOps = migrationOps.length;
271
- let migratedCount = 0;
272
- // Bulk fetch PN sessions - already exist (verified during device discovery)
273
- const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
274
- const pnSessions = await parsedKeys.get('session', pnAddrStrings);
275
- // Prepare bulk session updates (PN → LID migration + deletion)
276
- const sessionUpdates = {};
277
- for (const op of migrationOps) {
278
- const pnAddrStr = op.fromAddr.toString();
279
- const lidAddrStr = op.toAddr.toString();
280
- const pnSession = pnSessions[pnAddrStr];
281
- if (pnSession) {
282
- // Session exists (guaranteed from device discovery)
283
- const fromSession = libsignal.SessionRecord.deserialize(pnSession);
284
- if (fromSession.haveOpenSession()) {
285
- // Queue for bulk update: copy to LID, delete from PN
286
- sessionUpdates[lidAddrStr] = fromSession.serialize();
287
- sessionUpdates[pnAddrStr] = null;
288
- migratedCount++;
289
- }
290
- }
291
- }
292
- // Single bulk session update for all migrations
293
- if (Object.keys(sessionUpdates).length > 0) {
294
- await parsedKeys.set({ session: sessionUpdates });
295
- logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete');
296
- // Cache device-level migrations
297
- for (const op of migrationOps) {
298
- if (sessionUpdates[op.toAddr.toString()]) {
299
- const deviceKey = `${op.pnUser}.${op.deviceId}`;
300
- migratedSessionCache.set(deviceKey, true);
301
- }
302
- }
303
- }
304
- const skippedCount = totalOps - migratedCount;
305
- return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
306
- }, `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`);
307
110
  }
308
111
  };
309
- return repository;
310
112
  }
311
113
  const jidToSignalProtocolAddress = (jid) => {
312
- const decoded = jidDecode(jid);
313
- const { user, device, server, domainType } = decoded;
314
- if (!user) {
315
- throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
316
- }
317
- const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
318
- const finalDevice = device || 0;
319
- if (device === 99 && decoded.server !== 'hosted' && decoded.server !== 'hosted.lid') {
320
- throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid);
321
- }
322
- return new libsignal.ProtocolAddress(signalUser, finalDevice);
114
+ const { user, device } = (0, WABinary_1.jidDecode)(jid);
115
+ return new libsignal.ProtocolAddress(user, device || 0);
323
116
  };
324
117
  const jidToSignalSenderKeyName = (group, user) => {
325
- return new SenderKeyName(group, jidToSignalProtocolAddress(user));
118
+ return new sender_key_name_1.SenderKeyName(group, jidToSignalProtocolAddress(user));
326
119
  };
327
- function signalStorage({ creds, keys }, lidMapping) {
328
- // Shared function to resolve PN signal address to LID if mapping exists
329
- const resolveLIDSignalAddress = async (id) => {
330
- if (id.includes('.')) {
331
- const [deviceId, device] = id.split('.');
332
- const [user, domainType_] = deviceId.split('_');
333
- const domainType = parseInt(domainType_ || '0');
334
- if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID)
335
- return id;
336
- const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`;
337
- const lidForPN = await lidMapping.getLIDForPN(pnJid);
338
- if (lidForPN) {
339
- const lidAddr = jidToSignalProtocolAddress(lidForPN);
340
- return lidAddr.toString();
341
- }
342
- }
343
- return id;
344
- };
120
+ function signalStorage({ creds, keys }) {
345
121
  return {
346
122
  loadSession: async (id) => {
347
- try {
348
- const wireJid = await resolveLIDSignalAddress(id);
349
- const { [wireJid]: sess } = await keys.get('session', [wireJid]);
350
- if (sess) {
351
- return libsignal.SessionRecord.deserialize(sess);
352
- }
353
- }
354
- catch (e) {
355
- return null;
123
+ const { [id]: sess } = await keys.get('session', [id]);
124
+ if (sess) {
125
+ return libsignal.SessionRecord.deserialize(sess);
356
126
  }
357
- return null;
358
127
  },
359
128
  storeSession: async (id, session) => {
360
- const wireJid = await resolveLIDSignalAddress(id);
361
- await keys.set({ session: { [wireJid]: session.serialize() } });
129
+ await keys.set({ session: { [id]: session.serialize() } });
362
130
  },
363
131
  isTrustedIdentity: () => {
364
- return true; // TOFU - Trust on First Use (same as WhatsApp Web)
365
- },
366
- loadIdentityKey: async (id) => {
367
- const wireJid = await resolveLIDSignalAddress(id);
368
- const { [wireJid]: key } = await keys.get('identity-key', [wireJid]);
369
- return key || undefined;
370
- },
371
- saveIdentity: async (id, identityKey) => {
372
- const wireJid = await resolveLIDSignalAddress(id);
373
- const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid]);
374
- const keysMatch = existingKey?.length === identityKey.length && existingKey.every((byte, i) => byte === identityKey[i]);
375
- if (existingKey && !keysMatch) {
376
- // Identity changed - clear session and update key
377
- await keys.set({
378
- session: { [wireJid]: null },
379
- 'identity-key': { [wireJid]: identityKey }
380
- });
381
- return true;
382
- }
383
- if (!existingKey) {
384
- // New contact - Trust on First Use (TOFU)
385
- await keys.set({ 'identity-key': { [wireJid]: identityKey } });
386
- return true;
387
- }
388
- return false;
132
+ return true;
389
133
  },
390
134
  loadPreKey: async (id) => {
391
135
  const keyId = id.toString();
@@ -409,9 +153,9 @@ function signalStorage({ creds, keys }, lidMapping) {
409
153
  const keyId = senderKeyName.toString();
410
154
  const { [keyId]: key } = await keys.get('sender-key', [keyId]);
411
155
  if (key) {
412
- return SenderKeyRecord.deserialize(key);
156
+ return sender_key_record_1.SenderKeyRecord.deserialize(key);
413
157
  }
414
- return new SenderKeyRecord();
158
+ return new sender_key_record_1.SenderKeyRecord();
415
159
  },
416
160
  storeSenderKey: async (senderKeyName, key) => {
417
161
  const keyId = senderKeyName.toString();
@@ -423,9 +167,8 @@ function signalStorage({ creds, keys }, lidMapping) {
423
167
  const { signedIdentityKey } = creds;
424
168
  return {
425
169
  privKey: Buffer.from(signedIdentityKey.private),
426
- pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
170
+ pubKey: (0, Utils_1.generateSignalPubKey)(signedIdentityKey.public)
427
171
  };
428
172
  }
429
173
  };
430
174
  }
431
- //# sourceMappingURL=libsignal.js.map
@@ -1,6 +1,8 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import { EventEmitter } from 'events';
2
4
  import { URL } from 'url';
3
- import type { SocketConfig } from '../../Types/index.js';
5
+ import { SocketConfig } from '../../Types';
4
6
  export declare abstract class AbstractSocketClient extends EventEmitter {
5
7
  url: URL;
6
8
  config: SocketConfig;
@@ -9,8 +11,7 @@ export declare abstract class AbstractSocketClient extends EventEmitter {
9
11
  abstract get isClosing(): boolean;
10
12
  abstract get isConnecting(): boolean;
11
13
  constructor(url: URL, config: SocketConfig);
12
- abstract connect(): void;
13
- abstract close(): void;
14
+ abstract connect(): Promise<void>;
15
+ abstract close(): Promise<void>;
14
16
  abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean;
15
17
  }
16
- //# sourceMappingURL=types.d.ts.map
@@ -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;
@@ -1,3 +1,3 @@
1
- export * from './types.js';
2
- export * from './websocket.js';
3
- //# sourceMappingURL=index.d.ts.map
1
+ export * from './abstract-socket-client';
2
+ export * from './mobile-socket-client';
3
+ export * from './web-socket-client';
@@ -1,3 +1,19 @@
1
- export * from './types.js';
2
- export * from './websocket.js';
3
- //# sourceMappingURL=index.js.map
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./abstract-socket-client"), exports);
18
+ __exportStar(require("./mobile-socket-client"), exports);
19
+ __exportStar(require("./web-socket-client"), exports);
@@ -0,0 +1,13 @@
1
+ /// <reference types="node" />
2
+ import { Socket } from 'net';
3
+ import { AbstractSocketClient } from './abstract-socket-client';
4
+ export declare class MobileSocketClient extends AbstractSocketClient {
5
+ protected socket: Socket | null;
6
+ get isOpen(): boolean;
7
+ get isClosed(): boolean;
8
+ get isClosing(): boolean;
9
+ get isConnecting(): boolean;
10
+ connect(): Promise<void>;
11
+ close(): Promise<void>;
12
+ send(str: string | Uint8Array, cb?: (err?: Error) => void): boolean;
13
+ }
@@ -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;