@mdsockets/baileys 0.0.0-stage → 4.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +214 -2
  2. package/WAProto/index.js +169661 -0
  3. package/engine-requirements.js +10 -0
  4. package/lib/Defaults/baileys-version.json +1 -0
  5. package/lib/Defaults/index.d.ts +53 -0
  6. package/lib/Defaults/index.js +147 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  9. package/lib/Signal/Group/ciphertext-message.js +15 -0
  10. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  11. package/lib/Signal/Group/group-session-builder.js +64 -0
  12. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  13. package/lib/Signal/Group/group_cipher.js +96 -0
  14. package/lib/Signal/Group/index.d.ts +11 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  17. package/lib/Signal/Group/keyhelper.js +55 -0
  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 +13 -0
  21. package/lib/Signal/Group/sender-chain-key.js +34 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  24. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  25. package/lib/Signal/Group/sender-key-message.js +69 -0
  26. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-name.js +51 -0
  28. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  29. package/lib/Signal/Group/sender-key-record.js +53 -0
  30. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  31. package/lib/Signal/Group/sender-key-state.js +99 -0
  32. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  33. package/lib/Signal/Group/sender-message-key.js +29 -0
  34. package/lib/Signal/libsignal.d.ts +3 -0
  35. package/lib/Signal/libsignal.js +453 -0
  36. package/lib/Signal/lid-mapping.js +293 -0
  37. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  38. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  39. package/lib/Socket/Client/index.d.ts +3 -0
  40. package/lib/Socket/Client/index.js +19 -0
  41. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  42. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  43. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  44. package/lib/Socket/Client/web-socket-client.js +62 -0
  45. package/lib/Socket/business.d.ts +171 -0
  46. package/lib/Socket/business.js +260 -0
  47. package/lib/Socket/chats.d.ts +267 -0
  48. package/lib/Socket/chats.js +970 -0
  49. package/lib/Socket/groups.d.ts +115 -0
  50. package/lib/Socket/groups.js +332 -0
  51. package/lib/Socket/index.d.ts +173 -0
  52. package/lib/Socket/index.js +11 -0
  53. package/lib/Socket/luxu.d.ts +268 -0
  54. package/lib/Socket/luxu.js +591 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1126 -0
  57. package/lib/Socket/messages-send.d.ts +149 -0
  58. package/lib/Socket/messages-send.js +913 -0
  59. package/lib/Socket/newsletter.d.ts +134 -0
  60. package/lib/Socket/newsletter.js +304 -0
  61. package/lib/Socket/registration.d.ts +267 -0
  62. package/lib/Socket/registration.js +166 -0
  63. package/lib/Socket/socket.d.ts +43 -0
  64. package/lib/Socket/socket.js +681 -0
  65. package/lib/Socket/usync.d.ts +36 -0
  66. package/lib/Socket/usync.js +70 -0
  67. package/lib/Store/index.d.ts +3 -0
  68. package/lib/Store/index.js +10 -0
  69. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  70. package/lib/Store/make-cache-manager-store.js +83 -0
  71. package/lib/Store/make-in-memory-store.d.ts +118 -0
  72. package/lib/Store/make-in-memory-store.js +427 -0
  73. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  74. package/lib/Store/make-ordered-dictionary.js +81 -0
  75. package/lib/Store/object-repository.d.ts +10 -0
  76. package/lib/Store/object-repository.js +27 -0
  77. package/lib/Types/Auth.d.ts +110 -0
  78. package/lib/Types/Auth.js +2 -0
  79. package/lib/Types/Call.d.ts +13 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +102 -0
  82. package/lib/Types/Chat.js +4 -0
  83. package/lib/Types/Contact.d.ts +19 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +157 -0
  86. package/lib/Types/Events.js +2 -0
  87. package/lib/Types/GroupMetadata.d.ts +55 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +35 -0
  90. package/lib/Types/Label.js +27 -0
  91. package/lib/Types/LabelAssociation.d.ts +29 -0
  92. package/lib/Types/LabelAssociation.js +9 -0
  93. package/lib/Types/Message.d.ts +273 -0
  94. package/lib/Types/Message.js +9 -0
  95. package/lib/Types/Newsletter.d.ts +103 -0
  96. package/lib/Types/Newsletter.js +38 -0
  97. package/lib/Types/Product.d.ts +78 -0
  98. package/lib/Types/Product.js +2 -0
  99. package/lib/Types/Signal.d.ts +57 -0
  100. package/lib/Types/Signal.js +2 -0
  101. package/lib/Types/Socket.d.ts +111 -0
  102. package/lib/Types/Socket.js +2 -0
  103. package/lib/Types/State.d.ts +27 -0
  104. package/lib/Types/State.js +2 -0
  105. package/lib/Types/USync.d.ts +25 -0
  106. package/lib/Types/USync.js +2 -0
  107. package/lib/Types/index.d.ts +57 -0
  108. package/lib/Types/index.js +42 -0
  109. package/lib/Utils/auth-utils.d.ts +18 -0
  110. package/lib/Utils/auth-utils.js +219 -0
  111. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  112. package/lib/Utils/baileys-event-stream.js +63 -0
  113. package/lib/Utils/business.d.ts +22 -0
  114. package/lib/Utils/business.js +234 -0
  115. package/lib/Utils/chat-utils.d.ts +71 -0
  116. package/lib/Utils/chat-utils.js +729 -0
  117. package/lib/Utils/crypto.d.ts +41 -0
  118. package/lib/Utils/crypto.js +151 -0
  119. package/lib/Utils/decode-wa-message.d.ts +19 -0
  120. package/lib/Utils/decode-wa-message.js +292 -0
  121. package/lib/Utils/event-buffer.d.ts +35 -0
  122. package/lib/Utils/event-buffer.js +514 -0
  123. package/lib/Utils/generics.d.ts +92 -0
  124. package/lib/Utils/generics.js +406 -0
  125. package/lib/Utils/history.d.ts +15 -0
  126. package/lib/Utils/history.js +96 -0
  127. package/lib/Utils/identity-change-handler.js +68 -0
  128. package/lib/Utils/index.d.ts +17 -0
  129. package/lib/Utils/index.js +41 -0
  130. package/lib/Utils/link-preview.d.ts +21 -0
  131. package/lib/Utils/link-preview.js +93 -0
  132. package/lib/Utils/logger.d.ts +4 -0
  133. package/lib/Utils/logger.js +7 -0
  134. package/lib/Utils/lt-hash.d.ts +12 -0
  135. package/lib/Utils/lt-hash.js +51 -0
  136. package/lib/Utils/make-mutex.d.ts +7 -0
  137. package/lib/Utils/make-mutex.js +43 -0
  138. package/lib/Utils/message-retry-manager.js +192 -0
  139. package/lib/Utils/messages-media.d.ts +116 -0
  140. package/lib/Utils/messages-media.js +819 -0
  141. package/lib/Utils/messages.d.ts +77 -0
  142. package/lib/Utils/messages.js +816 -0
  143. package/lib/Utils/noise-handler.d.ts +21 -0
  144. package/lib/Utils/noise-handler.js +155 -0
  145. package/lib/Utils/offline-node-processor.js +55 -0
  146. package/lib/Utils/pre-key-manager.js +95 -0
  147. package/lib/Utils/process-message.d.ts +41 -0
  148. package/lib/Utils/process-message.js +321 -0
  149. package/lib/Utils/signal.d.ts +32 -0
  150. package/lib/Utils/signal.js +158 -0
  151. package/lib/Utils/stanza-ack.js +47 -0
  152. package/lib/Utils/tc-token-utils.js +173 -0
  153. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  154. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  155. package/lib/Utils/validate-connection.d.ts +11 -0
  156. package/lib/Utils/validate-connection.js +229 -0
  157. package/lib/WABinary/constants.d.ts +30 -0
  158. package/lib/WABinary/constants.js +40 -0
  159. package/lib/WABinary/decode.d.ts +7 -0
  160. package/lib/WABinary/decode.js +252 -0
  161. package/lib/WABinary/encode.d.ts +3 -0
  162. package/lib/WABinary/encode.js +265 -0
  163. package/lib/WABinary/generic-utils.d.ts +17 -0
  164. package/lib/WABinary/generic-utils.js +198 -0
  165. package/lib/WABinary/index.d.ts +5 -0
  166. package/lib/WABinary/index.js +21 -0
  167. package/lib/WABinary/jid-utils.d.ts +31 -0
  168. package/lib/WABinary/jid-utils.js +138 -0
  169. package/lib/WABinary/types.d.ts +18 -0
  170. package/lib/WABinary/types.js +2 -0
  171. package/lib/WAM/BinaryInfo.d.ts +17 -0
  172. package/lib/WAM/BinaryInfo.js +13 -0
  173. package/lib/WAM/constants.d.ts +38 -0
  174. package/lib/WAM/constants.js +15350 -0
  175. package/lib/WAM/encode.d.ts +3 -0
  176. package/lib/WAM/encode.js +155 -0
  177. package/lib/WAM/index.d.ts +3 -0
  178. package/lib/WAM/index.js +19 -0
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  182. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  183. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  184. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  186. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  187. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  188. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  189. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  190. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  191. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  192. package/lib/WAUSync/Protocols/index.js +20 -0
  193. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  194. package/lib/WAUSync/USyncQuery.js +89 -0
  195. package/lib/WAUSync/USyncUser.d.ts +12 -0
  196. package/lib/WAUSync/USyncUser.js +26 -0
  197. package/lib/WAUSync/index.js +19 -0
  198. package/lib/index.d.ts +12 -0
  199. package/lib/index.js +35 -0
  200. package/package.json +107 -5
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyState = void 0;
4
+ const sender_chain_key_1 = require("./sender-chain-key");
5
+ const sender_message_key_1 = require("./sender-message-key");
6
+ class SenderKeyState {
7
+ constructor(id, iteration, chainKey, signatureKeyPair, signatureKeyPublic, signatureKeyPrivate, senderKeyStateStructure) {
8
+ this.MAX_MESSAGE_KEYS = 2000;
9
+ if (senderKeyStateStructure) {
10
+ this.senderKeyStateStructure = senderKeyStateStructure;
11
+ }
12
+ else {
13
+ if (signatureKeyPair) {
14
+ signatureKeyPublic = signatureKeyPair.public;
15
+ signatureKeyPrivate = signatureKeyPair.private;
16
+ }
17
+ chainKey = typeof chainKey === 'string' ? Buffer.from(chainKey, 'base64') : chainKey;
18
+ const senderChainKeyStructure = {
19
+ iteration: iteration || 0,
20
+ seed: chainKey || Buffer.alloc(0)
21
+ };
22
+ const signingKeyStructure = {
23
+ public: typeof signatureKeyPublic === 'string'
24
+ ? Buffer.from(signatureKeyPublic, 'base64')
25
+ : signatureKeyPublic || Buffer.alloc(0)
26
+ };
27
+ if (signatureKeyPrivate) {
28
+ signingKeyStructure.private =
29
+ typeof signatureKeyPrivate === 'string' ? Buffer.from(signatureKeyPrivate, 'base64') : signatureKeyPrivate;
30
+ }
31
+ this.senderKeyStateStructure = {
32
+ senderKeyId: id || 0,
33
+ senderChainKey: senderChainKeyStructure,
34
+ senderSigningKey: signingKeyStructure,
35
+ senderMessageKeys: []
36
+ };
37
+ }
38
+ }
39
+ getKeyId() {
40
+ return this.senderKeyStateStructure.senderKeyId;
41
+ }
42
+ getSenderChainKey() {
43
+ return new sender_chain_key_1.SenderChainKey(this.senderKeyStateStructure.senderChainKey.iteration, this.senderKeyStateStructure.senderChainKey.seed);
44
+ }
45
+ setSenderChainKey(chainKey) {
46
+ this.senderKeyStateStructure.senderChainKey = {
47
+ iteration: chainKey.getIteration(),
48
+ seed: chainKey.getSeed()
49
+ };
50
+ }
51
+ getSigningKeyPublic() {
52
+ const publicKey = this.senderKeyStateStructure.senderSigningKey.public;
53
+ if (publicKey instanceof Buffer) {
54
+ return publicKey;
55
+ }
56
+ else if (typeof publicKey === 'string') {
57
+ return Buffer.from(publicKey, 'base64');
58
+ }
59
+ return Buffer.from(publicKey || []);
60
+ }
61
+ getSigningKeyPrivate() {
62
+ const privateKey = this.senderKeyStateStructure.senderSigningKey.private;
63
+ if (!privateKey) {
64
+ return undefined;
65
+ }
66
+ if (privateKey instanceof Buffer) {
67
+ return privateKey;
68
+ }
69
+ else if (typeof privateKey === 'string') {
70
+ return Buffer.from(privateKey, 'base64');
71
+ }
72
+ return Buffer.from(privateKey || []);
73
+ }
74
+ hasSenderMessageKey(iteration) {
75
+ return this.senderKeyStateStructure.senderMessageKeys.some(key => key.iteration === iteration);
76
+ }
77
+ addSenderMessageKey(senderMessageKey) {
78
+ this.senderKeyStateStructure.senderMessageKeys.push({
79
+ iteration: senderMessageKey.getIteration(),
80
+ seed: senderMessageKey.getSeed()
81
+ });
82
+ if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
83
+ this.senderKeyStateStructure.senderMessageKeys.shift();
84
+ }
85
+ }
86
+ removeSenderMessageKey(iteration) {
87
+ const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(key => key.iteration === iteration);
88
+ if (index !== -1) {
89
+ const messageKey = this.senderKeyStateStructure.senderMessageKeys[index];
90
+ this.senderKeyStateStructure.senderMessageKeys.splice(index, 1);
91
+ return new sender_message_key_1.SenderMessageKey(messageKey.iteration, messageKey.seed);
92
+ }
93
+ return null;
94
+ }
95
+ getStructure() {
96
+ return this.senderKeyStateStructure;
97
+ }
98
+ }
99
+ exports.SenderKeyState = SenderKeyState;
@@ -0,0 +1,11 @@
1
+ export declare class SenderMessageKey {
2
+ private readonly iteration;
3
+ private readonly iv;
4
+ private readonly cipherKey;
5
+ private readonly seed;
6
+ constructor(iteration: number, seed: Uint8Array);
7
+ getIteration(): number;
8
+ getIv(): Uint8Array;
9
+ getCipherKey(): Uint8Array;
10
+ getSeed(): Uint8Array;
11
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderMessageKey = void 0;
4
+ const crypto_1 = require("libsignal/src/crypto");
5
+ class SenderMessageKey {
6
+ constructor(iteration, seed) {
7
+ const derivative = (0, crypto_1.deriveSecrets)(seed, Buffer.alloc(32), Buffer.from('WhisperGroup'));
8
+ const keys = new Uint8Array(32);
9
+ keys.set(new Uint8Array(derivative[0].slice(16)));
10
+ keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
11
+ this.iv = Buffer.from(derivative[0].slice(0, 16));
12
+ this.cipherKey = Buffer.from(keys.buffer);
13
+ this.iteration = iteration;
14
+ this.seed = seed;
15
+ }
16
+ getIteration() {
17
+ return this.iteration;
18
+ }
19
+ getIv() {
20
+ return this.iv;
21
+ }
22
+ getCipherKey() {
23
+ return this.cipherKey;
24
+ }
25
+ getSeed() {
26
+ return this.seed;
27
+ }
28
+ }
29
+ exports.SenderMessageKey = SenderMessageKey;
@@ -0,0 +1,3 @@
1
+ import { SignalAuthState } from '../Types';
2
+ import { SignalRepository } from '../Types/Signal';
3
+ export declare function makeLibSignalRepository(auth: SignalAuthState): SignalRepository;
@@ -0,0 +1,453 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const libsignal = require('libsignal');
4
+ const { LRUCache } = require('lru-cache');
5
+ const { generateSignalPubKey } = require('../Utils');
6
+ const { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, transferDevice, WAJIDDomains } = require('../WABinary');
7
+ const { SenderKeyName } = require('./Group/sender-key-name');
8
+ const { SenderKeyRecord } = require('./Group/sender-key-record');
9
+ const { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } = require('./Group');
10
+ const { LIDMappingStore } = require('./lid-mapping');
11
+
12
+ // protobufs.js only exists in some libsignal builds -> optional, with a manual fallback
13
+ let PreKeyWhisperMessage;
14
+ try { ({ PreKeyWhisperMessage } = require('libsignal/src/protobufs.js')); } catch { PreKeyWhisperMessage = undefined; }
15
+ /** Extract identity key from PreKeyWhisperMessage for identity change detection */
16
+ function extractIdentityFromPkmsg(ciphertext) {
17
+ try {
18
+ if (!ciphertext || ciphertext.length < 2) {
19
+ return undefined;
20
+ }
21
+ // Version byte check (version 3)
22
+ const version = ciphertext[0];
23
+ if ((version & 0xf) !== 3) {
24
+ return undefined;
25
+ }
26
+ if (PreKeyWhisperMessage) {
27
+ const preKeyProto = PreKeyWhisperMessage.decode(ciphertext.slice(1));
28
+ if (preKeyProto.identityKey?.length === 33) {
29
+ return new Uint8Array(preKeyProto.identityKey);
30
+ }
31
+ return undefined;
32
+ }
33
+ // Fallback: minimal protobuf walk. PreKeyWhisperMessage.identityKey is field 3 (NOT 4 - field 4 is the inner message)
34
+ const data = ciphertext.slice(1);
35
+ let i = 0;
36
+ while (i < data.length) {
37
+ const tag = data[i] >> 3, wt = data[i] & 7;
38
+ i++;
39
+ if (wt === 2) {
40
+ let len = 0, shift = 0;
41
+ while (i < data.length) { const b = data[i++]; len |= (b & 0x7f) << shift; if (!(b & 0x80)) break; shift += 7; }
42
+ if (tag === 3 && len === 33) return new Uint8Array(data.slice(i, i + len));
43
+ i += len;
44
+ } else if (wt === 0) { while (i < data.length && (data[i++] & 0x80)); }
45
+ else if (wt === 5) i += 4;
46
+ else if (wt === 1) i += 8;
47
+ else break;
48
+ }
49
+ return undefined;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
56
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
57
+ const storage = signalStorage(auth, lidMapping);
58
+ const parsedKeys = auth.keys;
59
+ const migratedSessionCache = new LRUCache({
60
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
61
+ ttlAutopurge: true,
62
+ updateAgeOnGet: true
63
+ });
64
+ const ensureSenderKeyAndCreateSkdm = async (group, meId) => {
65
+ const senderName = jidToSignalSenderKeyName(group, meId);
66
+ const senderNameStr = senderName.toString();
67
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
68
+ if (!senderKey) {
69
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
70
+ }
71
+ const skdm = await new GroupSessionBuilder(storage).create(senderName);
72
+ return { senderName, skdm };
73
+ };
74
+ const repository = {
75
+ decryptGroupMessage({ group, authorJid, msg }) {
76
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
77
+ const cipher = new GroupCipher(storage, senderName);
78
+ // Use transaction to ensure atomicity
79
+ return parsedKeys.transaction(async () => {
80
+ return cipher.decrypt(msg);
81
+ }, group);
82
+ },
83
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
84
+ const builder = new GroupSessionBuilder(storage);
85
+ if (!item.groupId) {
86
+ throw new Error('Group ID is required for sender key distribution message');
87
+ }
88
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
89
+ const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
90
+ const senderNameStr = senderName.toString();
91
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
92
+ if (!senderKey) {
93
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
94
+ }
95
+ return parsedKeys.transaction(async () => {
96
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
97
+ if (!senderKey) {
98
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
99
+ }
100
+ await builder.process(senderName, senderMsg);
101
+ }, item.groupId);
102
+ },
103
+ async decryptMessage({ jid, type, ciphertext }) {
104
+ const addr = jidToSignalProtocolAddress(jid);
105
+ const session = new libsignal.SessionCipher(storage, addr);
106
+ // Extract and save sender's identity key before decryption for identity change detection
107
+ if (type === 'pkmsg') {
108
+ const identityKey = extractIdentityFromPkmsg(ciphertext);
109
+ if (identityKey) {
110
+ const addrStr = addr.toString();
111
+ const identityChanged = await storage.saveIdentity(addrStr, identityKey);
112
+ if (identityChanged) {
113
+ logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established');
114
+ }
115
+ }
116
+ }
117
+ async function doDecrypt() {
118
+ let result;
119
+ switch (type) {
120
+ case 'pkmsg':
121
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
122
+ break;
123
+ case 'msg':
124
+ result = await session.decryptWhisperMessage(ciphertext);
125
+ break;
126
+ }
127
+ return result;
128
+ }
129
+ // If it's not a sync message, we need to ensure atomicity
130
+ // For regular messages, we use a transaction to ensure atomicity
131
+ return parsedKeys.transaction(async () => {
132
+ return await doDecrypt();
133
+ }, jid);
134
+ },
135
+ async encryptMessage({ jid, data }) {
136
+ const addr = jidToSignalProtocolAddress(jid);
137
+ const cipher = new libsignal.SessionCipher(storage, addr);
138
+ // Use transaction to ensure atomicity
139
+ return parsedKeys.transaction(async () => {
140
+ const { type: sigType, body } = await cipher.encrypt(data);
141
+ const type = sigType === 3 ? 'pkmsg' : 'msg';
142
+ return { type, ciphertext: Buffer.from(body, 'binary') };
143
+ }, jid);
144
+ },
145
+ async encryptGroupMessage({ group, meId, data }) {
146
+ return parsedKeys.transaction(async () => {
147
+ const { senderName, skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
148
+ const ciphertext = await new GroupCipher(storage, senderName).encrypt(data);
149
+ return { ciphertext, senderKeyDistributionMessage: skdm.serialize() };
150
+ }, group);
151
+ },
152
+ async getSenderKeyDistributionMessage({ group, meId }) {
153
+ return parsedKeys.transaction(async () => {
154
+ const { skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
155
+ return skdm.serialize();
156
+ }, group);
157
+ },
158
+ async hasSenderKey({ group, meId }) {
159
+ const senderName = jidToSignalSenderKeyName(group, meId).toString();
160
+ const { [senderName]: key } = await auth.keys.get('sender-key', [senderName]);
161
+ return !!key;
162
+ },
163
+ async getSessionInfo(jid) {
164
+ const addr = jidToSignalProtocolAddress(jid).toString();
165
+ const session = (await storage.loadSession(addr));
166
+ if (!session) {
167
+ return null;
168
+ }
169
+ const open = session.getOpenSession?.();
170
+ const baseKey = open?.indexInfo?.baseKey;
171
+ const registrationId = open?.registrationId;
172
+ if (!baseKey || typeof registrationId !== 'number') {
173
+ return null;
174
+ }
175
+ return { baseKey: new Uint8Array(baseKey), registrationId };
176
+ },
177
+ async injectE2ESession({ jid, session }) {
178
+ logger.trace({ jid }, 'injecting E2EE session');
179
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
180
+ return parsedKeys.transaction(async () => {
181
+ // libsignal runtime accepts an absent prekey (initOutgoing checks `device.preKey && ...`)
182
+ // but the bundled .d.ts marks it required.
183
+ await cipher.initOutgoing(session);
184
+ }, jid);
185
+ },
186
+ jidToSignalProtocolAddress(jid) {
187
+ return jidToSignalProtocolAddress(jid).toString();
188
+ },
189
+ // Optimized direct access to LID mapping store
190
+ lidMapping,
191
+ async validateSession(jid) {
192
+ try {
193
+ const addr = jidToSignalProtocolAddress(jid);
194
+ const session = await storage.loadSession(addr.toString());
195
+ if (!session) {
196
+ return { exists: false, reason: 'no session' };
197
+ }
198
+ if (!session.haveOpenSession()) {
199
+ return { exists: false, reason: 'no open session' };
200
+ }
201
+ return { exists: true };
202
+ }
203
+ catch (error) {
204
+ return { exists: false, reason: 'validation error' };
205
+ }
206
+ },
207
+ async deleteSession(jids) {
208
+ if (!jids.length)
209
+ return;
210
+ // Convert JIDs to signal addresses and prepare for bulk deletion
211
+ const sessionUpdates = {};
212
+ jids.forEach(jid => {
213
+ const addr = jidToSignalProtocolAddress(jid);
214
+ sessionUpdates[addr.toString()] = null;
215
+ });
216
+ // Single transaction for all deletions
217
+ return parsedKeys.transaction(async () => {
218
+ await auth.keys.set({ session: sessionUpdates });
219
+ }, `delete-${jids.length}-sessions`);
220
+ },
221
+ close() {
222
+ migratedSessionCache.clear();
223
+ lidMapping.close();
224
+ },
225
+ async migrateSession(fromJid, toJid) {
226
+ // TODO: use usync to handle this entire mess
227
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
228
+ return { migrated: 0, skipped: 0, total: 0 };
229
+ // Only support PN to LID migration
230
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
231
+ return { migrated: 0, skipped: 0, total: 1 };
232
+ }
233
+ const { user } = jidDecode(fromJid);
234
+ logger.debug({ fromJid }, 'bulk device migration - loading all user devices');
235
+ // Get user's device list from storage
236
+ const { [user]: userDevices } = await parsedKeys.get('device-list', [user]);
237
+ if (!userDevices) {
238
+ return { migrated: 0, skipped: 0, total: 0 };
239
+ }
240
+ const { device: fromDevice } = jidDecode(fromJid);
241
+ const fromDeviceStr = fromDevice?.toString() || '0';
242
+ if (!userDevices.includes(fromDeviceStr)) {
243
+ userDevices.push(fromDeviceStr);
244
+ }
245
+ // Filter out cached devices before database fetch
246
+ const uncachedDevices = userDevices.filter(device => {
247
+ const deviceKey = `${user}.${device}`;
248
+ return !migratedSessionCache.has(deviceKey);
249
+ });
250
+ // Bulk check session existence only for uncached devices
251
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
252
+ const existingSessions = await parsedKeys.get('session', deviceSessionKeys);
253
+ // Step 3: Convert existing sessions to JIDs (only migrate sessions that exist)
254
+ const deviceJids = [];
255
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
256
+ if (sessionData) {
257
+ // Session exists in storage
258
+ const deviceStr = sessionKey.split('.')[1];
259
+ if (!deviceStr)
260
+ continue;
261
+ const deviceNum = parseInt(deviceStr);
262
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
263
+ if (deviceNum === 99) {
264
+ jid = `${user}:99@hosted`;
265
+ }
266
+ deviceJids.push(jid);
267
+ }
268
+ }
269
+ logger.debug({
270
+ fromJid,
271
+ totalDevices: userDevices.length,
272
+ devicesWithSessions: deviceJids.length,
273
+ devices: deviceJids
274
+ }, 'bulk device migration complete - all user devices processed');
275
+ // Single transaction for all migrations
276
+ return parsedKeys.transaction(async () => {
277
+ const migrationOps = deviceJids.map(jid => {
278
+ const lidWithDevice = transferDevice(jid, toJid);
279
+ const fromDecoded = jidDecode(jid);
280
+ const toDecoded = jidDecode(lidWithDevice);
281
+ return {
282
+ fromJid: jid,
283
+ toJid: lidWithDevice,
284
+ pnUser: fromDecoded.user,
285
+ lidUser: toDecoded.user,
286
+ deviceId: fromDecoded.device || 0,
287
+ fromAddr: jidToSignalProtocolAddress(jid),
288
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
289
+ };
290
+ });
291
+ const totalOps = migrationOps.length;
292
+ let migratedCount = 0;
293
+ // Bulk fetch PN sessions - already exist (verified during device discovery)
294
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
295
+ const pnSessions = await parsedKeys.get('session', pnAddrStrings);
296
+ // Prepare bulk session updates (PN → LID migration + deletion)
297
+ const sessionUpdates = {};
298
+ for (const op of migrationOps) {
299
+ const pnAddrStr = op.fromAddr.toString();
300
+ const lidAddrStr = op.toAddr.toString();
301
+ const pnSession = pnSessions[pnAddrStr];
302
+ if (pnSession) {
303
+ // Session exists (guaranteed from device discovery)
304
+ const fromSession = libsignal.SessionRecord.deserialize(pnSession);
305
+ if (fromSession.haveOpenSession()) {
306
+ // Queue for bulk update: copy to LID, delete from PN
307
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
308
+ sessionUpdates[pnAddrStr] = null;
309
+ migratedCount++;
310
+ }
311
+ }
312
+ }
313
+ // Single bulk session update for all migrations
314
+ if (Object.keys(sessionUpdates).length > 0) {
315
+ await parsedKeys.set({ session: sessionUpdates });
316
+ logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete');
317
+ // Cache device-level migrations
318
+ for (const op of migrationOps) {
319
+ if (sessionUpdates[op.toAddr.toString()]) {
320
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
321
+ migratedSessionCache.set(deviceKey, true);
322
+ }
323
+ }
324
+ }
325
+ const skippedCount = totalOps - migratedCount;
326
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
327
+ }, `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`);
328
+ }
329
+ };
330
+ return repository;
331
+ }
332
+ const jidToSignalProtocolAddress = (jid) => {
333
+ const decoded = jidDecode(jid);
334
+ const { user, device, server, domainType } = decoded;
335
+ if (!user) {
336
+ throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
337
+ }
338
+ const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
339
+ const finalDevice = device || 0;
340
+ if (device === 99 && decoded.server !== 'hosted' && decoded.server !== 'hosted.lid') {
341
+ throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid);
342
+ }
343
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
344
+ };
345
+ const jidToSignalSenderKeyName = (group, user) => {
346
+ return new SenderKeyName(group, jidToSignalProtocolAddress(user));
347
+ };
348
+ function signalStorage({ creds, keys }, lidMapping) {
349
+ // Shared function to resolve PN signal address to LID if mapping exists
350
+ const resolveLIDSignalAddress = async (id) => {
351
+ if (id.includes('.')) {
352
+ const [deviceId, device] = id.split('.');
353
+ const [user, domainType_] = deviceId.split('_');
354
+ const domainType = parseInt(domainType_ || '0');
355
+ if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID)
356
+ return id;
357
+ const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`;
358
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
359
+ if (lidForPN) {
360
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
361
+ return lidAddr.toString();
362
+ }
363
+ }
364
+ return id;
365
+ };
366
+ return {
367
+ loadSession: async (id) => {
368
+ try {
369
+ const wireJid = await resolveLIDSignalAddress(id);
370
+ const { [wireJid]: sess } = await keys.get('session', [wireJid]);
371
+ if (sess) {
372
+ return libsignal.SessionRecord.deserialize(sess);
373
+ }
374
+ }
375
+ catch (e) {
376
+ return null;
377
+ }
378
+ return null;
379
+ },
380
+ storeSession: async (id, session) => {
381
+ const wireJid = await resolveLIDSignalAddress(id);
382
+ await keys.set({ session: { [wireJid]: session.serialize() } });
383
+ },
384
+ isTrustedIdentity: () => {
385
+ return true; // TOFU - Trust on First Use (same as WhatsApp Web)
386
+ },
387
+ loadIdentityKey: async (id) => {
388
+ const wireJid = await resolveLIDSignalAddress(id);
389
+ const { [wireJid]: key } = await keys.get('identity-key', [wireJid]);
390
+ return key || undefined;
391
+ },
392
+ saveIdentity: async (id, identityKey) => {
393
+ const wireJid = await resolveLIDSignalAddress(id);
394
+ const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid]);
395
+ const keysMatch = existingKey?.length === identityKey.length && existingKey.every((byte, i) => byte === identityKey[i]);
396
+ if (existingKey && !keysMatch) {
397
+ // Identity changed - clear session and update key
398
+ await keys.set({
399
+ session: { [wireJid]: null },
400
+ 'identity-key': { [wireJid]: identityKey }
401
+ });
402
+ return true;
403
+ }
404
+ if (!existingKey) {
405
+ // New contact - Trust on First Use (TOFU)
406
+ await keys.set({ 'identity-key': { [wireJid]: identityKey } });
407
+ return true;
408
+ }
409
+ return false;
410
+ },
411
+ loadPreKey: async (id) => {
412
+ const keyId = id.toString();
413
+ const { [keyId]: key } = await keys.get('pre-key', [keyId]);
414
+ if (key) {
415
+ return {
416
+ privKey: Buffer.from(key.private),
417
+ pubKey: Buffer.from(key.public)
418
+ };
419
+ }
420
+ },
421
+ removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
422
+ loadSignedPreKey: () => {
423
+ const key = creds.signedPreKey;
424
+ return {
425
+ privKey: Buffer.from(key.keyPair.private),
426
+ pubKey: Buffer.from(key.keyPair.public)
427
+ };
428
+ },
429
+ loadSenderKey: async (senderKeyName) => {
430
+ const keyId = senderKeyName.toString();
431
+ const { [keyId]: key } = await keys.get('sender-key', [keyId]);
432
+ if (key) {
433
+ return SenderKeyRecord.deserialize(key);
434
+ }
435
+ return new SenderKeyRecord();
436
+ },
437
+ storeSenderKey: async (senderKeyName, key) => {
438
+ const keyId = senderKeyName.toString();
439
+ const serialized = JSON.stringify(key.serialize());
440
+ await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } });
441
+ },
442
+ getOurRegistrationId: () => creds.registrationId,
443
+ getOurIdentity: () => {
444
+ const { signedIdentityKey } = creds;
445
+ return {
446
+ privKey: Buffer.from(signedIdentityKey.private),
447
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
448
+ };
449
+ }
450
+ };
451
+ }
452
+
453
+ exports.makeLibSignalRepository = makeLibSignalRepository;