@badzz88/baileys 8.4.6 → 8.4.9

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 (250) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +850 -32
  4. package/WAProto/index.d.ts +4913 -25
  5. package/WAProto/index.js +14074 -98
  6. package/package.json +96 -131
  7. package/src/Defaults/index.js +201 -0
  8. package/src/Defaults/phonenumber-mcc.json +223 -0
  9. package/src/Signal/Group/ciphertext-message.js +15 -0
  10. package/src/Signal/Group/group-session-builder.js +92 -0
  11. package/src/Signal/Group/group_cipher.js +89 -0
  12. package/src/Signal/Group/index.js +136 -0
  13. package/src/Signal/Group/keyhelper.js +73 -0
  14. package/src/Signal/Group/sender-chain-key.js +32 -0
  15. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/src/Signal/Group/sender-key-message.js +69 -0
  17. package/src/Signal/Group/sender-key-name.js +50 -0
  18. package/src/Signal/Group/sender-key-record.js +44 -0
  19. package/src/Signal/Group/sender-key-state.js +97 -0
  20. package/src/Signal/Group/sender-message-key.js +30 -0
  21. package/src/Signal/libsignal.js +470 -0
  22. package/src/Signal/lid-mapping.js +262 -0
  23. package/src/Socket/Client/index.js +30 -0
  24. package/src/Socket/Client/types.js +13 -0
  25. package/src/Socket/Client/websocket.js +62 -0
  26. package/src/Socket/aigroups.js +240 -0
  27. package/src/Socket/business.js +422 -0
  28. package/src/Socket/chats.js +2374 -0
  29. package/src/Socket/communities.js +580 -0
  30. package/src/Socket/graphql.js +915 -0
  31. package/src/Socket/groups.js +812 -0
  32. package/src/Socket/index.js +37 -0
  33. package/src/Socket/interactive-handler.js +579 -0
  34. package/src/Socket/interop.js +566 -0
  35. package/src/Socket/managed-account.js +214 -0
  36. package/src/Socket/messages-recv.js +3012 -0
  37. package/src/Socket/messages-send.js +2163 -0
  38. package/{lib → src}/Socket/mex.js +11 -5
  39. package/src/Socket/newsletter.js +1057 -0
  40. package/src/Socket/privacy.js +452 -0
  41. package/src/Socket/registration.js +434 -0
  42. package/src/Socket/socket.js +1079 -0
  43. package/src/Socket/text-router.js +67 -0
  44. package/src/Socket/username.js +234 -0
  45. package/src/Store/index.js +36 -0
  46. package/src/Store/make-cache-manager-store.js +90 -0
  47. package/src/Store/make-in-memory-store.js +506 -0
  48. package/src/Store/make-ordered-dictionary.js +81 -0
  49. package/src/Store/object-repository.js +29 -0
  50. package/src/Types/Auth.js +38 -0
  51. package/src/Types/Bussines.js +2 -0
  52. package/src/Types/Call.js +2 -0
  53. package/src/Types/Chat.js +4 -0
  54. package/src/Types/Contact.js +2 -0
  55. package/src/Types/Events.js +2 -0
  56. package/src/Types/GroupMetadata.js +2 -0
  57. package/src/Types/Label.js +27 -0
  58. package/src/Types/LabelAssociation.js +9 -0
  59. package/src/Types/Message.js +95 -0
  60. package/src/Types/Newsletter.js +152 -0
  61. package/src/Types/Product.js +2 -0
  62. package/src/Types/Signal.js +2 -0
  63. package/src/Types/Socket.js +2 -0
  64. package/src/Types/State.js +70 -0
  65. package/src/Types/USync.js +2 -0
  66. package/src/Types/index.js +54 -0
  67. package/src/Utils/auth-utils.js +306 -0
  68. package/src/Utils/browser-utils.js +114 -0
  69. package/src/Utils/business.js +247 -0
  70. package/src/Utils/chat-utils.js +1272 -0
  71. package/src/Utils/consumer-application.js +107 -0
  72. package/src/Utils/crypto.js +125 -0
  73. package/src/Utils/decode-wa-message.js +808 -0
  74. package/src/Utils/event-buffer.js +586 -0
  75. package/src/Utils/generics.js +640 -0
  76. package/src/Utils/group-history.js +60 -0
  77. package/src/Utils/history.js +244 -0
  78. package/src/Utils/identity-change-handler.js +52 -0
  79. package/src/Utils/index.js +53 -0
  80. package/src/Utils/jid-display-normalization.js +218 -0
  81. package/src/Utils/link-preview.js +143 -0
  82. package/src/Utils/logger.js +9 -0
  83. package/src/Utils/lt-hash.js +10 -0
  84. package/src/Utils/make-mutex.js +36 -0
  85. package/src/Utils/message-composer.js +479 -0
  86. package/src/Utils/message-inspect.js +400 -0
  87. package/src/Utils/message-retry-manager.js +231 -0
  88. package/src/Utils/messages-media.js +943 -0
  89. package/src/Utils/messages.js +2490 -0
  90. package/src/Utils/meta-ai-msmsg.js +133 -0
  91. package/src/Utils/noise-handler.js +194 -0
  92. package/src/Utils/offline-node-processor.js +42 -0
  93. package/src/Utils/pre-key-manager.js +107 -0
  94. package/src/Utils/process-message.js +1047 -0
  95. package/src/Utils/reporting-utils.js +262 -0
  96. package/src/Utils/signal.js +192 -0
  97. package/src/Utils/stanza-ack.js +74 -0
  98. package/src/Utils/sync-action-utils.js +54 -0
  99. package/src/Utils/tc-token-utils.js +161 -0
  100. package/src/Utils/use-multi-file-auth-state.js +121 -0
  101. package/src/Utils/validate-connection.js +248 -0
  102. package/src/Utils/voip-rekey.js +22 -0
  103. package/src/WABinary/constants.js +1304 -0
  104. package/src/WABinary/decode.js +377 -0
  105. package/src/WABinary/encode.js +58 -0
  106. package/src/WABinary/generic-utils.js +148 -0
  107. package/src/WABinary/index.js +33 -0
  108. package/src/WABinary/jid-utils.js +374 -0
  109. package/src/WABinary/types.js +2 -0
  110. package/src/WAM/BinaryInfo.js +13 -0
  111. package/src/WAM/constants.js +39486 -0
  112. package/src/WAM/encode.js +142 -0
  113. package/src/WAM/index.js +31 -0
  114. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  115. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  116. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  117. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  118. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  119. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  120. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  121. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  122. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  123. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  124. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  125. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  126. package/src/WAUSync/Protocols/index.js +40 -0
  127. package/src/WAUSync/USyncBackoff.js +31 -0
  128. package/src/WAUSync/USyncQuery.js +204 -0
  129. package/src/WAUSync/USyncUser.js +58 -0
  130. package/src/WAUSync/index.js +32 -0
  131. package/src/antiban.js +4726 -0
  132. package/{lib → src}/index.js +48 -16
  133. package/lib/Defaults/baileys-version.json +0 -3
  134. package/lib/Defaults/index.js +0 -137
  135. package/lib/Defaults/phonenumber-mcc.json +0 -223
  136. package/lib/Signal/Group/Protocols.js +0 -269
  137. package/lib/Signal/Group/ciphertext-message.js +0 -12
  138. package/lib/Signal/Group/group-session-builder.js +0 -30
  139. package/lib/Signal/Group/group_cipher.js +0 -82
  140. package/lib/Signal/Group/index.js +0 -12
  141. package/lib/Signal/Group/keyhelper.js +0 -18
  142. package/lib/Signal/Group/queue-job.js +0 -57
  143. package/lib/Signal/Group/sender-chain-key.js +0 -26
  144. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  145. package/lib/Signal/Group/sender-key-message.js +0 -66
  146. package/lib/Signal/Group/sender-key-name.js +0 -48
  147. package/lib/Signal/Group/sender-key-record.js +0 -41
  148. package/lib/Signal/Group/sender-key-state.js +0 -84
  149. package/lib/Signal/Group/sender-message-key.js +0 -26
  150. package/lib/Signal/libsignal.js +0 -432
  151. package/lib/Signal/lid-mapping.js +0 -277
  152. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  153. package/lib/Socket/Client/index.js +0 -3
  154. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  155. package/lib/Socket/Client/types.js +0 -11
  156. package/lib/Socket/Client/web-socket-client.js +0 -62
  157. package/lib/Socket/Client/websocket.js +0 -54
  158. package/lib/Socket/business.js +0 -379
  159. package/lib/Socket/chats.js +0 -1193
  160. package/lib/Socket/communities.js +0 -431
  161. package/lib/Socket/community.js +0 -392
  162. package/lib/Socket/dugong.js +0 -637
  163. package/lib/Socket/groups.js +0 -374
  164. package/lib/Socket/index.js +0 -12
  165. package/lib/Socket/luxu.js +0 -387
  166. package/lib/Socket/messages-recv.js +0 -1916
  167. package/lib/Socket/messages-send.js +0 -1459
  168. package/lib/Socket/newsletter.js +0 -253
  169. package/lib/Socket/registration.js +0 -167
  170. package/lib/Socket/socket.js +0 -950
  171. package/lib/Socket/username.js +0 -146
  172. package/lib/Socket/usync.js +0 -69
  173. package/lib/Store/index.js +0 -10
  174. package/lib/Store/keyed-db.js +0 -108
  175. package/lib/Store/make-cache-manager-store.js +0 -85
  176. package/lib/Store/make-in-memory-store.js +0 -198
  177. package/lib/Store/make-ordered-dictionary.js +0 -75
  178. package/lib/Store/object-repository.js +0 -32
  179. package/lib/Types/Auth.js +0 -2
  180. package/lib/Types/Bussines.js +0 -2
  181. package/lib/Types/Call.js +0 -2
  182. package/lib/Types/Chat.js +0 -8
  183. package/lib/Types/Contact.js +0 -2
  184. package/lib/Types/Events.js +0 -2
  185. package/lib/Types/GroupMetadata.js +0 -2
  186. package/lib/Types/Label.js +0 -25
  187. package/lib/Types/LabelAssociation.js +0 -7
  188. package/lib/Types/Message.js +0 -11
  189. package/lib/Types/Mex.js +0 -37
  190. package/lib/Types/Newsletter.js +0 -38
  191. package/lib/Types/Product.js +0 -2
  192. package/lib/Types/Signal.js +0 -2
  193. package/lib/Types/Socket.js +0 -3
  194. package/lib/Types/State.js +0 -56
  195. package/lib/Types/USync.js +0 -2
  196. package/lib/Types/index.js +0 -26
  197. package/lib/Utils/auth-utils.js +0 -302
  198. package/lib/Utils/baileys-event-stream.js +0 -63
  199. package/lib/Utils/browser-utils.js +0 -48
  200. package/lib/Utils/business.js +0 -231
  201. package/lib/Utils/chat-utils.js +0 -873
  202. package/lib/Utils/companion-reg-client-utils.js +0 -35
  203. package/lib/Utils/crypto.js +0 -118
  204. package/lib/Utils/decode-wa-message.js +0 -350
  205. package/lib/Utils/event-buffer.js +0 -622
  206. package/lib/Utils/generics.js +0 -399
  207. package/lib/Utils/history.js +0 -134
  208. package/lib/Utils/identity-change-handler.js +0 -50
  209. package/lib/Utils/index.js +0 -23
  210. package/lib/Utils/link-preview.js +0 -85
  211. package/lib/Utils/logger.js +0 -3
  212. package/lib/Utils/lt-hash.js +0 -8
  213. package/lib/Utils/make-mutex.js +0 -33
  214. package/lib/Utils/message-composer.js +0 -273
  215. package/lib/Utils/message-retry-manager.js +0 -265
  216. package/lib/Utils/messages-media.js +0 -788
  217. package/lib/Utils/messages.js +0 -1260
  218. package/lib/Utils/noise-handler.js +0 -201
  219. package/lib/Utils/offline-node-processor.js +0 -40
  220. package/lib/Utils/pre-key-manager.js +0 -106
  221. package/lib/Utils/process-message.js +0 -630
  222. package/lib/Utils/reporting-utils.js +0 -258
  223. package/lib/Utils/signal.js +0 -202
  224. package/lib/Utils/stanza-ack.js +0 -38
  225. package/lib/Utils/sync-action-utils.js +0 -49
  226. package/lib/Utils/tc-token-utils.js +0 -163
  227. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  228. package/lib/Utils/validate-connection.js +0 -204
  229. package/lib/WABinary/constants.js +0 -1301
  230. package/lib/WABinary/decode.js +0 -262
  231. package/lib/WABinary/encode.js +0 -220
  232. package/lib/WABinary/generic-utils.js +0 -204
  233. package/lib/WABinary/index.js +0 -6
  234. package/lib/WABinary/jid-utils.js +0 -98
  235. package/lib/WABinary/types.js +0 -2
  236. package/lib/WAM/BinaryInfo.js +0 -10
  237. package/lib/WAM/constants.js +0 -22853
  238. package/lib/WAM/encode.js +0 -150
  239. package/lib/WAM/index.js +0 -4
  240. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  241. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  242. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  243. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  244. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  245. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  247. package/lib/WAUSync/Protocols/index.js +0 -6
  248. package/lib/WAUSync/USyncQuery.js +0 -98
  249. package/lib/WAUSync/USyncUser.js +0 -31
  250. package/lib/WAUSync/index.js +0 -4
@@ -1,48 +0,0 @@
1
- function isNull(str) {
2
- return str === null || str === '';
3
- }
4
- function intValue(num) {
5
- const MAX_VALUE = 0x7fffffff;
6
- const MIN_VALUE = -0x80000000;
7
- if (num > MAX_VALUE || num < MIN_VALUE) {
8
- return num & 0xffffffff;
9
- }
10
- return num;
11
- }
12
- function hashCode(strKey) {
13
- let hash = 0;
14
- if (!isNull(strKey)) {
15
- for (let i = 0; i < strKey.length; i++) {
16
- hash = hash * 31 + strKey.charCodeAt(i);
17
- hash = intValue(hash);
18
- }
19
- }
20
- return hash;
21
- }
22
- export class SenderKeyName {
23
- constructor(groupId, sender) {
24
- this.groupId = groupId;
25
- this.sender = sender;
26
- }
27
- getGroupId() {
28
- return this.groupId;
29
- }
30
- getSender() {
31
- return this.sender;
32
- }
33
- serialize() {
34
- return `${this.groupId}::${this.sender.id}::${this.sender.deviceId}`;
35
- }
36
- toString() {
37
- return this.serialize();
38
- }
39
- equals(other) {
40
- if (other === null)
41
- return false;
42
- return this.groupId === other.groupId && this.sender.toString() === other.sender.toString();
43
- }
44
- hashCode() {
45
- return hashCode(this.groupId) ^ hashCode(this.sender.toString());
46
- }
47
- }
48
- //# sourceMappingURL=sender-key-name.js.map
@@ -1,41 +0,0 @@
1
- import { BufferJSON } from '../../Utils/generics.js';
2
- import { SenderKeyState } from './sender-key-state.js';
3
- export class SenderKeyRecord {
4
- constructor(serialized) {
5
- this.MAX_STATES = 5;
6
- this.senderKeyStates = [];
7
- if (serialized) {
8
- for (const structure of serialized) {
9
- this.senderKeyStates.push(new SenderKeyState(null, null, null, null, null, null, structure));
10
- }
11
- }
12
- }
13
- isEmpty() {
14
- return this.senderKeyStates.length === 0;
15
- }
16
- getSenderKeyState(keyId) {
17
- if (keyId === undefined && this.senderKeyStates.length) {
18
- return this.senderKeyStates[this.senderKeyStates.length - 1];
19
- }
20
- return this.senderKeyStates.find(state => state.getKeyId() === keyId);
21
- }
22
- addSenderKeyState(id, iteration, chainKey, signatureKey) {
23
- this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, null, signatureKey));
24
- if (this.senderKeyStates.length > this.MAX_STATES) {
25
- this.senderKeyStates.shift();
26
- }
27
- }
28
- setSenderKeyState(id, iteration, chainKey, keyPair) {
29
- this.senderKeyStates.length = 0;
30
- this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, keyPair));
31
- }
32
- serialize() {
33
- return this.senderKeyStates.map(state => state.getStructure());
34
- }
35
- static deserialize(data) {
36
- const str = Buffer.from(data).toString('utf-8');
37
- const parsed = JSON.parse(str, BufferJSON.reviver);
38
- return new SenderKeyRecord(parsed);
39
- }
40
- }
41
- //# sourceMappingURL=sender-key-record.js.map
@@ -1,84 +0,0 @@
1
- import { SenderChainKey } from './sender-chain-key.js';
2
- import { SenderMessageKey } from './sender-message-key.js';
3
- export class SenderKeyState {
4
- constructor(id, iteration, chainKey, signatureKeyPair, signatureKeyPublic, signatureKeyPrivate, senderKeyStateStructure) {
5
- this.MAX_MESSAGE_KEYS = 2000;
6
- if (senderKeyStateStructure) {
7
- this.senderKeyStateStructure = {
8
- ...senderKeyStateStructure,
9
- senderMessageKeys: Array.isArray(senderKeyStateStructure.senderMessageKeys)
10
- ? senderKeyStateStructure.senderMessageKeys
11
- : []
12
- };
13
- }
14
- else {
15
- if (signatureKeyPair) {
16
- signatureKeyPublic = signatureKeyPair.public;
17
- signatureKeyPrivate = signatureKeyPair.private;
18
- }
19
- this.senderKeyStateStructure = {
20
- senderKeyId: id || 0,
21
- senderChainKey: {
22
- iteration: iteration || 0,
23
- seed: Buffer.from(chainKey || [])
24
- },
25
- senderSigningKey: {
26
- public: Buffer.from(signatureKeyPublic || []),
27
- private: Buffer.from(signatureKeyPrivate || [])
28
- },
29
- senderMessageKeys: []
30
- };
31
- }
32
- }
33
- getKeyId() {
34
- return this.senderKeyStateStructure.senderKeyId;
35
- }
36
- getSenderChainKey() {
37
- return new SenderChainKey(this.senderKeyStateStructure.senderChainKey.iteration, this.senderKeyStateStructure.senderChainKey.seed);
38
- }
39
- setSenderChainKey(chainKey) {
40
- this.senderKeyStateStructure.senderChainKey = {
41
- iteration: chainKey.getIteration(),
42
- seed: chainKey.getSeed()
43
- };
44
- }
45
- getSigningKeyPublic() {
46
- const publicKey = Buffer.from(this.senderKeyStateStructure.senderSigningKey.public);
47
- if (publicKey.length === 32) {
48
- const fixed = Buffer.alloc(33);
49
- fixed[0] = 0x05;
50
- publicKey.copy(fixed, 1);
51
- return fixed;
52
- }
53
- return publicKey;
54
- }
55
- getSigningKeyPrivate() {
56
- const privateKey = this.senderKeyStateStructure.senderSigningKey.private;
57
- return Buffer.from(privateKey || []);
58
- }
59
- hasSenderMessageKey(iteration) {
60
- return this.senderKeyStateStructure.senderMessageKeys.some(key => key.iteration === iteration);
61
- }
62
- addSenderMessageKey(senderMessageKey) {
63
- this.senderKeyStateStructure.senderMessageKeys.push({
64
- iteration: senderMessageKey.getIteration(),
65
- seed: senderMessageKey.getSeed()
66
- });
67
- if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
68
- this.senderKeyStateStructure.senderMessageKeys.shift();
69
- }
70
- }
71
- removeSenderMessageKey(iteration) {
72
- const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(key => key.iteration === iteration);
73
- if (index !== -1) {
74
- const messageKey = this.senderKeyStateStructure.senderMessageKeys[index];
75
- this.senderKeyStateStructure.senderMessageKeys.splice(index, 1);
76
- return new SenderMessageKey(messageKey.iteration, messageKey.seed);
77
- }
78
- return null;
79
- }
80
- getStructure() {
81
- return this.senderKeyStateStructure;
82
- }
83
- }
84
- //# sourceMappingURL=sender-key-state.js.map
@@ -1,26 +0,0 @@
1
- import { deriveSecrets } from 'libsignal/src/crypto.js';
2
- export class SenderMessageKey {
3
- constructor(iteration, seed) {
4
- const derivative = deriveSecrets(seed, Buffer.alloc(32), Buffer.from('WhisperGroup'));
5
- const keys = new Uint8Array(32);
6
- keys.set(new Uint8Array(derivative[0].slice(16)));
7
- keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
8
- this.iv = Buffer.from(derivative[0].slice(0, 16));
9
- this.cipherKey = Buffer.from(keys.buffer);
10
- this.iteration = iteration;
11
- this.seed = seed;
12
- }
13
- getIteration() {
14
- return this.iteration;
15
- }
16
- getIv() {
17
- return this.iv;
18
- }
19
- getCipherKey() {
20
- return this.cipherKey;
21
- }
22
- getSeed() {
23
- return this.seed;
24
- }
25
- }
26
- //# sourceMappingURL=sender-message-key.js.map
@@ -1,432 +0,0 @@
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;
29
- }
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 };
52
- };
53
- const repository = {
54
- decryptGroupMessage({ group, authorJid, msg }) {
55
- 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);
61
- },
62
- async processSenderKeyDistributionMessage({ item, authorJid }) {
63
- const builder = new GroupSessionBuilder(storage);
64
- if (!item.groupId) {
65
- throw new Error('Group ID is required for sender key distribution message');
66
- }
67
- const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
68
- const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
69
- const senderNameStr = senderName.toString();
70
- const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
71
- if (!senderKey) {
72
- await storage.storeSenderKey(senderName, new SenderKeyRecord());
73
- }
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);
81
- },
82
- async decryptMessage({ jid, type, ciphertext }) {
83
- const addr = jidToSignalProtocolAddress(jid);
84
- 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);
113
- },
114
- async encryptMessage({ jid, data }) {
115
- const addr = jidToSignalProtocolAddress(jid);
116
- 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);
123
- },
124
- 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;
153
- }
154
- return { baseKey: new Uint8Array(baseKey), registrationId };
155
- },
156
- async injectE2ESession({ jid, session }) {
157
- logger.trace({ jid }, 'injecting E2EE session');
158
- 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);
164
- },
165
- jidToSignalProtocolAddress(jid) {
166
- 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
- }
308
- };
309
- return repository;
310
- }
311
- 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);
323
- };
324
- const jidToSignalSenderKeyName = (group, user) => {
325
- return new SenderKeyName(group, jidToSignalProtocolAddress(user));
326
- };
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
- };
345
- return {
346
- 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;
356
- }
357
- return null;
358
- },
359
- storeSession: async (id, session) => {
360
- const wireJid = await resolveLIDSignalAddress(id);
361
- await keys.set({ session: { [wireJid]: session.serialize() } });
362
- },
363
- 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;
389
- },
390
- loadPreKey: async (id) => {
391
- const keyId = id.toString();
392
- const { [keyId]: key } = await keys.get('pre-key', [keyId]);
393
- if (key) {
394
- return {
395
- privKey: Buffer.from(key.private),
396
- pubKey: Buffer.from(key.public)
397
- };
398
- }
399
- },
400
- removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
401
- loadSignedPreKey: () => {
402
- const key = creds.signedPreKey;
403
- return {
404
- privKey: Buffer.from(key.keyPair.private),
405
- pubKey: Buffer.from(key.keyPair.public)
406
- };
407
- },
408
- loadSenderKey: async (senderKeyName) => {
409
- const keyId = senderKeyName.toString();
410
- const { [keyId]: key } = await keys.get('sender-key', [keyId]);
411
- if (key) {
412
- return SenderKeyRecord.deserialize(key);
413
- }
414
- return new SenderKeyRecord();
415
- },
416
- storeSenderKey: async (senderKeyName, key) => {
417
- const keyId = senderKeyName.toString();
418
- const serialized = JSON.stringify(key.serialize());
419
- await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } });
420
- },
421
- getOurRegistrationId: () => creds.registrationId,
422
- getOurIdentity: () => {
423
- const { signedIdentityKey } = creds;
424
- return {
425
- privKey: Buffer.from(signedIdentityKey.private),
426
- pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
427
- };
428
- }
429
- };
430
- }
431
- //# sourceMappingURL=libsignal.js.map
432
- //source baileys github.com/Badzz88/baileys