@skycodee/baileys 8.0.4 → 8.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 (224) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +352 -520
  3. package/WAProto/index.js +558 -4154
  4. package/lib/Defaults/index.js +123 -0
  5. package/lib/Defaults/index.js.bak +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +13 -0
  10. package/lib/Signal/Group/group-session-builder.js +32 -0
  11. package/lib/Signal/Group/group_cipher.js +84 -0
  12. package/lib/Signal/Group/index.js +13 -0
  13. package/lib/Signal/Group/keyhelper.js +20 -0
  14. package/lib/Signal/Group/sender-chain-key.js +28 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-message.js +68 -0
  17. package/lib/Signal/Group/sender-key-name.js +52 -0
  18. package/lib/Signal/Group/sender-key-record.js +43 -0
  19. package/lib/Signal/Group/sender-key-state.js +86 -0
  20. package/lib/Signal/Group/sender-message-key.js +28 -0
  21. package/lib/Signal/libsignal.js +324 -0
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -0
  24. package/lib/Socket/Client/types.js +13 -0
  25. package/lib/Socket/Client/websocket.js +52 -0
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +377 -0
  28. package/lib/Socket/chats.js +885 -0
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/groups.js +312 -0
  31. package/lib/Socket/index.js +16 -0
  32. package/lib/Socket/messages-recv.js +1163 -0
  33. package/lib/Socket/messages-send.js +1100 -0
  34. package/lib/Socket/mex.js +45 -0
  35. package/lib/Socket/newsletter.js +247 -0
  36. package/lib/Socket/socket.js +820 -0
  37. package/lib/Store/index.js +6 -0
  38. package/lib/Store/make-cache-manager-store.js +75 -0
  39. package/lib/Store/make-in-memory-store.js +290 -0
  40. package/lib/Store/make-ordered-dictionary.js +79 -0
  41. package/lib/Store/object-repository.js +25 -0
  42. package/lib/Types/Auth.js +3 -0
  43. package/lib/Types/Bussines.js +3 -0
  44. package/lib/Types/Call.js +3 -0
  45. package/lib/Types/Chat.js +9 -0
  46. package/lib/Types/Contact.js +3 -0
  47. package/lib/Types/Events.js +3 -0
  48. package/lib/Types/GroupMetadata.js +3 -0
  49. package/lib/Types/Label.js +25 -0
  50. package/lib/Types/LabelAssociation.js +7 -0
  51. package/lib/Types/Message.js +12 -0
  52. package/lib/Types/Newsletter.js +33 -0
  53. package/lib/Types/Newsletter.js.bak +33 -0
  54. package/lib/Types/Product.js +3 -0
  55. package/lib/Types/Signal.js +3 -0
  56. package/lib/Types/Socket.js +4 -0
  57. package/lib/Types/State.js +11 -0
  58. package/lib/Types/USync.js +3 -0
  59. package/lib/Types/index.js +28 -0
  60. package/lib/Utils/auth-utils.js +219 -0
  61. package/lib/Utils/baileys-event-stream.js +44 -0
  62. package/lib/Utils/browser-utils.js +25 -0
  63. package/lib/Utils/business.js +233 -0
  64. package/lib/Utils/chat-utils.js +752 -0
  65. package/lib/Utils/crypto.js +130 -0
  66. package/lib/Utils/decode-wa-message.js +267 -0
  67. package/lib/Utils/event-buffer.js +528 -0
  68. package/lib/Utils/generics.js +355 -0
  69. package/lib/Utils/history.js +87 -0
  70. package/lib/Utils/index.js +21 -0
  71. package/lib/Utils/link-preview.js +81 -0
  72. package/lib/Utils/logger.js +5 -0
  73. package/lib/Utils/lt-hash.js +45 -0
  74. package/lib/Utils/make-mutex.js +36 -0
  75. package/lib/Utils/message-retry-manager.js +113 -0
  76. package/lib/Utils/messages-media.js +627 -0
  77. package/lib/Utils/messages.js +909 -0
  78. package/lib/Utils/noise-handler.js +144 -0
  79. package/lib/Utils/pre-key-manager.js +85 -0
  80. package/lib/Utils/process-message.js +341 -0
  81. package/lib/Utils/signal.js +161 -0
  82. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  83. package/lib/Utils/validate-connection.js +200 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +240 -0
  86. package/lib/WABinary/encode.js +218 -0
  87. package/lib/WABinary/generic-utils.js +189 -0
  88. package/lib/WABinary/index.js +7 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +3 -0
  91. package/lib/WAM/BinaryInfo.js +11 -0
  92. package/lib/WAM/constants.js +22853 -0
  93. package/lib/WAM/encode.js +154 -0
  94. package/lib/WAM/index.js +5 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/index.js +6 -0
  102. package/lib/WAUSync/USyncQuery.js +90 -0
  103. package/lib/WAUSync/USyncUser.js +24 -0
  104. package/lib/WAUSync/index.js +5 -0
  105. package/lib/index.js +21 -0
  106. package/package.json +84 -57
  107. package/README.md +0 -1312
  108. package/WAProto/GenerateStatics.sh +0 -3
  109. package/WAProto/fix-imports.js +0 -81
  110. package/WAProto/index.d.ts +0 -14017
  111. package/engine-requirements.js +0 -10
  112. package/src/Defaults/baileys-version.json +0 -1
  113. package/src/Defaults/index.ts +0 -149
  114. package/src/Signal/Group/ciphertext-message.ts +0 -9
  115. package/src/Signal/Group/group-session-builder.ts +0 -56
  116. package/src/Signal/Group/group_cipher.ts +0 -117
  117. package/src/Signal/Group/index.ts +0 -11
  118. package/src/Signal/Group/keyhelper.ts +0 -28
  119. package/src/Signal/Group/sender-chain-key.ts +0 -34
  120. package/src/Signal/Group/sender-key-distribution-message.ts +0 -95
  121. package/src/Signal/Group/sender-key-message.ts +0 -96
  122. package/src/Signal/Group/sender-key-name.ts +0 -66
  123. package/src/Signal/Group/sender-key-record.ts +0 -69
  124. package/src/Signal/Group/sender-key-state.ts +0 -134
  125. package/src/Signal/Group/sender-message-key.ts +0 -36
  126. package/src/Signal/libsignal.ts +0 -521
  127. package/src/Signal/lid-mapping.ts +0 -328
  128. package/src/Socket/Client/index.ts +0 -2
  129. package/src/Socket/Client/types.ts +0 -22
  130. package/src/Socket/Client/websocket.ts +0 -63
  131. package/src/Socket/business.ts +0 -424
  132. package/src/Socket/chats.ts +0 -1272
  133. package/src/Socket/communities.ts +0 -477
  134. package/src/Socket/groups.ts +0 -361
  135. package/src/Socket/index.ts +0 -15
  136. package/src/Socket/messages-recv.ts +0 -1668
  137. package/src/Socket/messages-send.ts +0 -1296
  138. package/src/Socket/mex.ts +0 -58
  139. package/src/Socket/newsletter.ts +0 -229
  140. package/src/Socket/socket.ts +0 -1184
  141. package/src/Types/Auth.ts +0 -116
  142. package/src/Types/Bussines.ts +0 -20
  143. package/src/Types/Call.ts +0 -15
  144. package/src/Types/Chat.ts +0 -138
  145. package/src/Types/Contact.ts +0 -24
  146. package/src/Types/Events.ts +0 -159
  147. package/src/Types/GroupMetadata.ts +0 -70
  148. package/src/Types/Label.ts +0 -48
  149. package/src/Types/LabelAssociation.ts +0 -35
  150. package/src/Types/Message.ts +0 -380
  151. package/src/Types/Newsletter.ts +0 -98
  152. package/src/Types/Product.ts +0 -85
  153. package/src/Types/Signal.ts +0 -76
  154. package/src/Types/Socket.ts +0 -150
  155. package/src/Types/State.ts +0 -43
  156. package/src/Types/USync.ts +0 -27
  157. package/src/Types/globals.d.ts +0 -8
  158. package/src/Types/index.ts +0 -67
  159. package/src/Utils/auth-utils.ts +0 -368
  160. package/src/Utils/browser-utils.ts +0 -31
  161. package/src/Utils/business.ts +0 -286
  162. package/src/Utils/chat-utils.ts +0 -974
  163. package/src/Utils/crypto.ts +0 -147
  164. package/src/Utils/decode-wa-message.ts +0 -355
  165. package/src/Utils/event-buffer.ts +0 -692
  166. package/src/Utils/generics.ts +0 -474
  167. package/src/Utils/history.ts +0 -161
  168. package/src/Utils/identity-change-handler.ts +0 -83
  169. package/src/Utils/index.ts +0 -19
  170. package/src/Utils/link-preview.ts +0 -111
  171. package/src/Utils/logger.ts +0 -13
  172. package/src/Utils/lt-hash.ts +0 -8
  173. package/src/Utils/make-mutex.ts +0 -42
  174. package/src/Utils/message-retry-manager.ts +0 -295
  175. package/src/Utils/messages-media.ts +0 -984
  176. package/src/Utils/messages.ts +0 -1097
  177. package/src/Utils/noise-handler.ts +0 -268
  178. package/src/Utils/pre-key-manager.ts +0 -126
  179. package/src/Utils/process-message.ts +0 -670
  180. package/src/Utils/reporting-utils.ts +0 -344
  181. package/src/Utils/signal.ts +0 -214
  182. package/src/Utils/sync-action-utils.ts +0 -74
  183. package/src/Utils/tc-token-utils.ts +0 -34
  184. package/src/Utils/use-multi-file-auth-state.ts +0 -136
  185. package/src/Utils/validate-connection.ts +0 -253
  186. package/src/WABinary/constants.ts +0 -1305
  187. package/src/WABinary/decode.ts +0 -308
  188. package/src/WABinary/encode.ts +0 -258
  189. package/src/WABinary/generic-utils.ts +0 -141
  190. package/src/WABinary/index.ts +0 -5
  191. package/src/WABinary/jid-utils.ts +0 -128
  192. package/src/WABinary/types.ts +0 -17
  193. package/src/WAM/BinaryInfo.ts +0 -12
  194. package/src/WAM/constants.ts +0 -22889
  195. package/src/WAM/encode.ts +0 -169
  196. package/src/WAM/index.ts +0 -3
  197. package/src/WAUSync/Protocols/USyncContactProtocol.ts +0 -32
  198. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +0 -78
  199. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +0 -35
  200. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +0 -44
  201. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +0 -76
  202. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +0 -33
  203. package/src/WAUSync/Protocols/index.ts +0 -4
  204. package/src/WAUSync/USyncQuery.ts +0 -133
  205. package/src/WAUSync/USyncUser.ts +0 -32
  206. package/src/WAUSync/index.ts +0 -3
  207. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +0 -22
  208. package/src/__tests__/Signal/lid-mapping.test.ts +0 -47
  209. package/src/__tests__/Socket/identity-change-handling.test.ts +0 -207
  210. package/src/__tests__/TestUtils/session.ts +0 -47
  211. package/src/__tests__/Utils/generics.test.ts +0 -70
  212. package/src/__tests__/Utils/history.test.ts +0 -362
  213. package/src/__tests__/Utils/messages-media.test.ts +0 -405
  214. package/src/__tests__/Utils/noise-handler.test.ts +0 -339
  215. package/src/__tests__/Utils/process-message.test.ts +0 -138
  216. package/src/__tests__/Utils/process-sync-action.test.ts +0 -359
  217. package/src/__tests__/Utils/reporting-utils.test.ts +0 -160
  218. package/src/__tests__/Utils/signal.test.ts +0 -69
  219. package/src/__tests__/Utils/sync-action-utils.test.ts +0 -183
  220. package/src/__tests__/binary/connection-deadlock.test.ts +0 -54
  221. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +0 -60
  222. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +0 -644
  223. package/src/__tests__/proto-tojson-long.test.ts +0 -31
  224. package/src/index.ts +0 -13
@@ -0,0 +1,65 @@
1
+ //=======================================================//
2
+ import { CiphertextMessage } from "./ciphertext-message.js";
3
+ import { proto } from "../../../WAProto/index.js";
4
+ //=======================================================//
5
+ export class SenderKeyDistributionMessage extends CiphertextMessage {
6
+ constructor(id, iteration, chainKey, signatureKey, serialized) {
7
+ super();
8
+ if (serialized) {
9
+ try {
10
+ const message = serialized.slice(1);
11
+ const distributionMessage = proto.SenderKeyDistributionMessage.decode(message).toJSON();
12
+ this.serialized = serialized;
13
+ this.id = distributionMessage.id;
14
+ this.iteration = distributionMessage.iteration;
15
+ this.chainKey =
16
+ typeof distributionMessage.chainKey === "string"
17
+ ? Buffer.from(distributionMessage.chainKey, "base64")
18
+ : distributionMessage.chainKey;
19
+ this.signatureKey =
20
+ typeof distributionMessage.signingKey === "string"
21
+ ? Buffer.from(distributionMessage.signingKey, "base64")
22
+ : distributionMessage.signingKey;
23
+ }
24
+ catch (e) {
25
+ throw new Error(String(e));
26
+ }
27
+ }
28
+ else {
29
+ const version = this.intsToByteHighAndLow(this.CURRENT_VERSION, this.CURRENT_VERSION);
30
+ this.id = id;
31
+ this.iteration = iteration;
32
+ this.chainKey = chainKey;
33
+ this.signatureKey = signatureKey;
34
+ const message = proto.SenderKeyDistributionMessage.encode(proto.SenderKeyDistributionMessage.create({
35
+ id,
36
+ iteration,
37
+ chainKey,
38
+ signingKey: this.signatureKey
39
+ })).finish();
40
+ this.serialized = Buffer.concat([Buffer.from([version]), message]);
41
+ }
42
+ }
43
+ intsToByteHighAndLow(highValue, lowValue) {
44
+ return (((highValue << 4) | lowValue) & 0xff) % 256;
45
+ }
46
+ serialize() {
47
+ return this.serialized;
48
+ }
49
+ getType() {
50
+ return this.SENDERKEY_DISTRIBUTION_TYPE;
51
+ }
52
+ getIteration() {
53
+ return this.iteration;
54
+ }
55
+ getChainKey() {
56
+ return this.chainKey;
57
+ }
58
+ getSignatureKey() {
59
+ return this.signatureKey;
60
+ }
61
+ getId() {
62
+ return this.id;
63
+ }
64
+ }
65
+ //=======================================================//
@@ -0,0 +1,68 @@
1
+ //=======================================================//
2
+ import { calculateSignature, verifySignature } from "@skycodee/libsignal/src/curve.js";
3
+ import { CiphertextMessage } from "./ciphertext-message.js";
4
+ import { proto } from "../../../WAProto/index.js";
5
+ //=======================================================//
6
+ export class SenderKeyMessage extends CiphertextMessage {
7
+ constructor(keyId, iteration, ciphertext, signatureKey, serialized) {
8
+ super();
9
+ this.SIGNATURE_LENGTH = 64;
10
+ if (serialized) {
11
+ const version = serialized[0];
12
+ const message = serialized.slice(1, serialized.length - this.SIGNATURE_LENGTH);
13
+ const signature = serialized.slice(-1 * this.SIGNATURE_LENGTH);
14
+ const senderKeyMessage = proto.SenderKeyMessage.decode(message).toJSON();
15
+ this.serialized = serialized;
16
+ this.messageVersion = (version & 0xff) >> 4;
17
+ this.keyId = senderKeyMessage.id;
18
+ this.iteration = senderKeyMessage.iteration;
19
+ this.ciphertext =
20
+ typeof senderKeyMessage.ciphertext === "string"
21
+ ? Buffer.from(senderKeyMessage.ciphertext, "base64")
22
+ : senderKeyMessage.ciphertext;
23
+ this.signature = signature;
24
+ }
25
+ else {
26
+ const version = (((this.CURRENT_VERSION << 4) | this.CURRENT_VERSION) & 0xff) % 256;
27
+ const ciphertextBuffer = Buffer.from(ciphertext);
28
+ const message = proto.SenderKeyMessage.encode(proto.SenderKeyMessage.create({
29
+ id: keyId,
30
+ iteration: iteration,
31
+ ciphertext: ciphertextBuffer
32
+ })).finish();
33
+ const signature = this.getSignature(signatureKey, Buffer.concat([Buffer.from([version]), message]));
34
+ this.serialized = Buffer.concat([Buffer.from([version]), message, Buffer.from(signature)]);
35
+ this.messageVersion = this.CURRENT_VERSION;
36
+ this.keyId = keyId;
37
+ this.iteration = iteration;
38
+ this.ciphertext = ciphertextBuffer;
39
+ this.signature = signature;
40
+ }
41
+ }
42
+ getKeyId() {
43
+ return this.keyId;
44
+ }
45
+ getIteration() {
46
+ return this.iteration;
47
+ }
48
+ getCipherText() {
49
+ return this.ciphertext;
50
+ }
51
+ verifySignature(signatureKey) {
52
+ const part1 = this.serialized.slice(0, this.serialized.length - this.SIGNATURE_LENGTH);
53
+ const part2 = this.serialized.slice(-1 * this.SIGNATURE_LENGTH);
54
+ const res = verifySignature(signatureKey, part1, part2);
55
+ if (!res)
56
+ throw new Error("Invalid signature!");
57
+ }
58
+ getSignature(signatureKey, serialized) {
59
+ return Buffer.from(calculateSignature(signatureKey, serialized));
60
+ }
61
+ serialize() {
62
+ return this.serialized;
63
+ }
64
+ getType() {
65
+ return 4;
66
+ }
67
+ }
68
+ //=======================================================//
@@ -0,0 +1,52 @@
1
+ //=======================================================//
2
+ function isNull(str) {
3
+ return str === null || str === "";
4
+ }
5
+ //=======================================================//
6
+ function intValue(num) {
7
+ const MAX_VALUE = 0x7fffffff;
8
+ const MIN_VALUE = -0x80000000;
9
+ if (num > MAX_VALUE || num < MIN_VALUE) {
10
+ return num & 0xffffffff;
11
+ }
12
+ return num;
13
+ }
14
+ //=======================================================//
15
+ function hashCode(strKey) {
16
+ let hash = 0;
17
+ if (!isNull(strKey)) {
18
+ for (let i = 0; i < strKey.length; i++) {
19
+ hash = hash * 31 + strKey.charCodeAt(i);
20
+ hash = intValue(hash);
21
+ }
22
+ }
23
+ return hash;
24
+ }
25
+ //=======================================================//
26
+ export class SenderKeyName {
27
+ constructor(groupId, sender) {
28
+ this.groupId = groupId;
29
+ this.sender = sender;
30
+ }
31
+ getGroupId() {
32
+ return this.groupId;
33
+ }
34
+ getSender() {
35
+ return this.sender;
36
+ }
37
+ serialize() {
38
+ return `${this.groupId}::${this.sender.id}::${this.sender.deviceId}`;
39
+ }
40
+ toString() {
41
+ return this.serialize();
42
+ }
43
+ equals(other) {
44
+ if (other === null)
45
+ return false;
46
+ return this.groupId === other.groupId && this.sender.toString() === other.sender.toString();
47
+ }
48
+ hashCode() {
49
+ return hashCode(this.groupId) ^ hashCode(this.sender.toString());
50
+ }
51
+ }
52
+ //=======================================================//
@@ -0,0 +1,43 @@
1
+ //=======================================================//
2
+ import { SenderKeyState } from "./sender-key-state.js";
3
+ import { BufferJSON } from "../../Utils/generics.js";
4
+ //=======================================================//
5
+ export class SenderKeyRecord {
6
+ constructor(serialized) {
7
+ this.MAX_STATES = 5;
8
+ this.senderKeyStates = [];
9
+ if (serialized) {
10
+ for (const structure of serialized) {
11
+ this.senderKeyStates.push(new SenderKeyState(null, null, null, null, null, null, structure));
12
+ }
13
+ }
14
+ }
15
+ isEmpty() {
16
+ return this.senderKeyStates.length === 0;
17
+ }
18
+ getSenderKeyState(keyId) {
19
+ if (keyId === undefined && this.senderKeyStates.length) {
20
+ return this.senderKeyStates[this.senderKeyStates.length - 1];
21
+ }
22
+ return this.senderKeyStates.find(state => state.getKeyId() === keyId);
23
+ }
24
+ addSenderKeyState(id, iteration, chainKey, signatureKey) {
25
+ this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, null, signatureKey));
26
+ if (this.senderKeyStates.length > this.MAX_STATES) {
27
+ this.senderKeyStates.shift();
28
+ }
29
+ }
30
+ setSenderKeyState(id, iteration, chainKey, keyPair) {
31
+ this.senderKeyStates.length = 0;
32
+ this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, keyPair));
33
+ }
34
+ serialize() {
35
+ return this.senderKeyStates.map(state => state.getStructure());
36
+ }
37
+ static deserialize(data) {
38
+ const str = Buffer.from(data).toString("utf-8");
39
+ const parsed = JSON.parse(str, BufferJSON.reviver);
40
+ return new SenderKeyRecord(parsed);
41
+ }
42
+ }
43
+ //=======================================================//
@@ -0,0 +1,86 @@
1
+ //=======================================================//
2
+ import { SenderMessageKey } from "./sender-message-key.js";
3
+ import { SenderChainKey } from "./sender-chain-key.js";
4
+ //=======================================================//
5
+ export class SenderKeyState {
6
+ constructor(id, iteration, chainKey, signatureKeyPair, signatureKeyPublic, signatureKeyPrivate, senderKeyStateStructure) {
7
+ this.MAX_MESSAGE_KEYS = 2000;
8
+ if (senderKeyStateStructure) {
9
+ this.senderKeyStateStructure = {
10
+ ...senderKeyStateStructure,
11
+ senderMessageKeys: Array.isArray(senderKeyStateStructure.senderMessageKeys)
12
+ ? senderKeyStateStructure.senderMessageKeys
13
+ : []
14
+ };
15
+ }
16
+ else {
17
+ if (signatureKeyPair) {
18
+ signatureKeyPublic = signatureKeyPair.public;
19
+ signatureKeyPrivate = signatureKeyPair.private;
20
+ }
21
+ this.senderKeyStateStructure = {
22
+ senderKeyId: id || 0,
23
+ senderChainKey: {
24
+ iteration: iteration || 0,
25
+ seed: Buffer.from(chainKey || [])
26
+ },
27
+ senderSigningKey: {
28
+ public: Buffer.from(signatureKeyPublic || []),
29
+ private: Buffer.from(signatureKeyPrivate || [])
30
+ },
31
+ senderMessageKeys: []
32
+ };
33
+ }
34
+ }
35
+ getKeyId() {
36
+ return this.senderKeyStateStructure.senderKeyId;
37
+ }
38
+ getSenderChainKey() {
39
+ return new SenderChainKey(this.senderKeyStateStructure.senderChainKey.iteration, this.senderKeyStateStructure.senderChainKey.seed);
40
+ }
41
+ setSenderChainKey(chainKey) {
42
+ this.senderKeyStateStructure.senderChainKey = {
43
+ iteration: chainKey.getIteration(),
44
+ seed: chainKey.getSeed()
45
+ };
46
+ }
47
+ getSigningKeyPublic() {
48
+ const publicKey = Buffer.from(this.senderKeyStateStructure.senderSigningKey.public);
49
+ if (publicKey.length === 32) {
50
+ const fixed = Buffer.alloc(33);
51
+ fixed[0] = 0x05;
52
+ publicKey.copy(fixed, 1);
53
+ return fixed;
54
+ }
55
+ return publicKey;
56
+ }
57
+ getSigningKeyPrivate() {
58
+ const privateKey = this.senderKeyStateStructure.senderSigningKey.private;
59
+ return Buffer.from(privateKey || []);
60
+ }
61
+ hasSenderMessageKey(iteration) {
62
+ return this.senderKeyStateStructure.senderMessageKeys.some(key => key.iteration === iteration);
63
+ }
64
+ addSenderMessageKey(senderMessageKey) {
65
+ this.senderKeyStateStructure.senderMessageKeys.push({
66
+ iteration: senderMessageKey.getIteration(),
67
+ seed: senderMessageKey.getSeed()
68
+ });
69
+ if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
70
+ this.senderKeyStateStructure.senderMessageKeys.shift();
71
+ }
72
+ }
73
+ removeSenderMessageKey(iteration) {
74
+ const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(key => key.iteration === iteration);
75
+ if (index !== -1) {
76
+ const messageKey = this.senderKeyStateStructure.senderMessageKeys[index];
77
+ this.senderKeyStateStructure.senderMessageKeys.splice(index, 1);
78
+ return new SenderMessageKey(messageKey.iteration, messageKey.seed);
79
+ }
80
+ return null;
81
+ }
82
+ getStructure() {
83
+ return this.senderKeyStateStructure;
84
+ }
85
+ }
86
+ //=======================================================//
@@ -0,0 +1,28 @@
1
+ //=======================================================//
2
+ import { deriveSecrets } from "@skycodee/libsignal/src/crypto.js";
3
+ //=======================================================//
4
+ export class SenderMessageKey {
5
+ constructor(iteration, seed) {
6
+ const derivative = deriveSecrets(seed, Buffer.alloc(32), Buffer.from("WhisperGroup"));
7
+ const keys = new Uint8Array(32);
8
+ keys.set(new Uint8Array(derivative[0].slice(16)));
9
+ keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
10
+ this.iv = Buffer.from(derivative[0].slice(0, 16));
11
+ this.cipherKey = Buffer.from(keys.buffer);
12
+ this.iteration = iteration;
13
+ this.seed = seed;
14
+ }
15
+ getIteration() {
16
+ return this.iteration;
17
+ }
18
+ getIv() {
19
+ return this.iv;
20
+ }
21
+ getCipherKey() {
22
+ return this.cipherKey;
23
+ }
24
+ getSeed() {
25
+ return this.seed;
26
+ }
27
+ }
28
+ //=======================================================//
@@ -0,0 +1,324 @@
1
+ //=======================================================//
2
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, transferDevice, WAJIDDomains } from "../WABinary/index.js";
3
+ import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } from "./Group/index.js";
4
+ import { SenderKeyRecord } from "./Group/sender-key-record.js";
5
+ import { SenderKeyName } from "./Group/sender-key-name.js";
6
+ import { generateSignalPubKey } from "../Utils/index.js";
7
+ import { LIDMappingStore } from "./lid-mapping.js";
8
+ import * as libsignal from "@skycodee/libsignal";
9
+ import { LRUCache } from "lru-cache";
10
+ //=======================================================//
11
+ export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
12
+ const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
13
+ const storage = signalStorage(auth, lidMapping);
14
+ const parsedKeys = auth.keys;
15
+ const migratedSessionCache = new LRUCache({
16
+ ttl: 7 * 24 * 60 * 60 * 1000,
17
+ ttlAutopurge: true,
18
+ updateAgeOnGet: true
19
+ });
20
+ const repository = {
21
+ decryptGroupMessage({ group, authorJid, msg }) {
22
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
23
+ const cipher = new GroupCipher(storage, senderName);
24
+ return parsedKeys.transaction(async () => {
25
+ return cipher.decrypt(msg);
26
+ }, group);
27
+ },
28
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
29
+ const builder = new GroupSessionBuilder(storage);
30
+ if (!item.groupId) {
31
+ throw new Error("Group ID is required for sender key distribution message");
32
+ }
33
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
34
+ const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
35
+ const senderNameStr = senderName.toString();
36
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
37
+ if (!senderKey) {
38
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
39
+ }
40
+ return parsedKeys.transaction(async () => {
41
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
42
+ if (!senderKey) {
43
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
44
+ }
45
+ await builder.process(senderName, senderMsg);
46
+ }, item.groupId);
47
+ },
48
+ async decryptMessage({ jid, type, ciphertext }) {
49
+ const addr = jidToSignalProtocolAddress(jid);
50
+ const session = new libsignal.SessionCipher(storage, addr);
51
+ async function doDecrypt() {
52
+ let result;
53
+ switch (type) {
54
+ case "pkmsg":
55
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
56
+ break;
57
+ case "msg":
58
+ result = await session.decryptWhisperMessage(ciphertext);
59
+ break;
60
+ }
61
+ return result;
62
+ }
63
+ return parsedKeys.transaction(async () => {
64
+ return await doDecrypt();
65
+ }, jid);
66
+ },
67
+ async encryptMessage({ jid, data }) {
68
+ const addr = jidToSignalProtocolAddress(jid);
69
+ const cipher = new libsignal.SessionCipher(storage, addr);
70
+ return parsedKeys.transaction(async () => {
71
+ const { type: sigType, body } = await cipher.encrypt(data);
72
+ const type = sigType === 3 ? "pkmsg" : "msg";
73
+ return { type, ciphertext: Buffer.from(body, "binary") };
74
+ }, jid);
75
+ },
76
+ async encryptGroupMessage({ group, meId, data }) {
77
+ const senderName = jidToSignalSenderKeyName(group, meId);
78
+ const builder = new GroupSessionBuilder(storage);
79
+ const senderNameStr = senderName.toString();
80
+ return parsedKeys.transaction(async () => {
81
+ const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
82
+ if (!senderKey) {
83
+ await storage.storeSenderKey(senderName, new SenderKeyRecord());
84
+ }
85
+ const senderKeyDistributionMessage = await builder.create(senderName);
86
+ const session = new GroupCipher(storage, senderName);
87
+ const ciphertext = await session.encrypt(data);
88
+ return {
89
+ ciphertext,
90
+ senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
91
+ };
92
+ }, group);
93
+ },
94
+ async injectE2ESession({ jid, session }) {
95
+ logger.trace({ jid }, "injecting E2EE session");
96
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
97
+ return parsedKeys.transaction(async () => {
98
+ await cipher.initOutgoing(session);
99
+ }, jid);
100
+ },
101
+ jidToSignalProtocolAddress(jid) {
102
+ return jidToSignalProtocolAddress(jid).toString();
103
+ },
104
+ lidMapping,
105
+ async validateSession(jid) {
106
+ try {
107
+ const addr = jidToSignalProtocolAddress(jid);
108
+ const session = await storage.loadSession(addr.toString());
109
+ if (!session) {
110
+ return { exists: false, reason: "no session" };
111
+ }
112
+ if (!session.haveOpenSession()) {
113
+ return { exists: false, reason: "no open session" };
114
+ }
115
+ return { exists: true };
116
+ }
117
+ catch (error) {
118
+ return { exists: false, reason: "validation error" };
119
+ }
120
+ },
121
+ async deleteSession(jids) {
122
+ if (!jids.length)
123
+ return;
124
+ const sessionUpdates = {};
125
+ jids.forEach(jid => {
126
+ const addr = jidToSignalProtocolAddress(jid);
127
+ sessionUpdates[addr.toString()] = null;
128
+ });
129
+ return parsedKeys.transaction(async () => {
130
+ await auth.keys.set({ session: sessionUpdates });
131
+ }, `delete-${jids.length}-sessions`);
132
+ },
133
+ async migrateSession(fromJid, toJid) {
134
+ if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
135
+ return { migrated: 0, skipped: 0, total: 0 };
136
+ if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
137
+ return { migrated: 0, skipped: 0, total: 1 };
138
+ }
139
+ const { user } = jidDecode(fromJid);
140
+ logger.debug({ fromJid }, "bulk device migration - loading all user devices");
141
+ const { [user]: userDevices } = await parsedKeys.get("device-list", [user]);
142
+ if (!userDevices) {
143
+ return { migrated: 0, skipped: 0, total: 0 };
144
+ }
145
+ const { device: fromDevice } = jidDecode(fromJid);
146
+ const fromDeviceStr = fromDevice?.toString() || "0";
147
+ if (!userDevices.includes(fromDeviceStr)) {
148
+ userDevices.push(fromDeviceStr);
149
+ }
150
+ const uncachedDevices = userDevices.filter(device => {
151
+ const deviceKey = `${user}.${device}`;
152
+ return !migratedSessionCache.has(deviceKey);
153
+ });
154
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
155
+ const existingSessions = await parsedKeys.get("session", deviceSessionKeys);
156
+ const deviceJids = [];
157
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
158
+ if (sessionData) {
159
+ const deviceStr = sessionKey.split(".")[1];
160
+ if (!deviceStr)
161
+ continue;
162
+ const deviceNum = parseInt(deviceStr);
163
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
164
+ if (deviceNum === 99) {
165
+ jid = `${user}:99@hosted`;
166
+ }
167
+ deviceJids.push(jid);
168
+ }
169
+ }
170
+ logger.debug({
171
+ fromJid,
172
+ totalDevices: userDevices.length,
173
+ devicesWithSessions: deviceJids.length,
174
+ devices: deviceJids
175
+ }, "bulk device migration complete - all user devices processed");
176
+ return parsedKeys.transaction(async () => {
177
+ const migrationOps = deviceJids.map(jid => {
178
+ const lidWithDevice = transferDevice(jid, toJid);
179
+ const fromDecoded = jidDecode(jid);
180
+ const toDecoded = jidDecode(lidWithDevice);
181
+ return {
182
+ fromJid: jid,
183
+ toJid: lidWithDevice,
184
+ pnUser: fromDecoded.user,
185
+ lidUser: toDecoded.user,
186
+ deviceId: fromDecoded.device || 0,
187
+ fromAddr: jidToSignalProtocolAddress(jid),
188
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
189
+ };
190
+ });
191
+ const totalOps = migrationOps.length;
192
+ let migratedCount = 0;
193
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
194
+ const pnSessions = await parsedKeys.get("session", pnAddrStrings);
195
+ const sessionUpdates = {};
196
+ for (const op of migrationOps) {
197
+ const pnAddrStr = op.fromAddr.toString();
198
+ const lidAddrStr = op.toAddr.toString();
199
+ const pnSession = pnSessions[pnAddrStr];
200
+ if (pnSession) {
201
+ const fromSession = libsignal.SessionRecord.deserialize(pnSession);
202
+ if (fromSession.haveOpenSession()) {
203
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
204
+ sessionUpdates[pnAddrStr] = null;
205
+ migratedCount++;
206
+ }
207
+ }
208
+ }
209
+ if (Object.keys(sessionUpdates).length > 0) {
210
+ await parsedKeys.set({ session: sessionUpdates });
211
+ logger.debug({ migratedSessions: migratedCount }, "bulk session migration complete");
212
+ for (const op of migrationOps) {
213
+ if (sessionUpdates[op.toAddr.toString()]) {
214
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
215
+ migratedSessionCache.set(deviceKey, true);
216
+ }
217
+ }
218
+ }
219
+ const skippedCount = totalOps - migratedCount;
220
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
221
+ }, `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`);
222
+ }
223
+ };
224
+ return repository;
225
+ }
226
+ //=======================================================//
227
+ const jidToSignalProtocolAddress = (jid) => {
228
+ const decoded = jidDecode(jid);
229
+ const { user, device, server, domainType } = decoded;
230
+ if (!user) {
231
+ throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
232
+ }
233
+ const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
234
+ const finalDevice = device || 0;
235
+ if (device === 99 && decoded.server !== "hosted" && decoded.server !== "hosted.lid") {
236
+ throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:" + jid);
237
+ }
238
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
239
+ };
240
+ //=======================================================//
241
+ const jidToSignalSenderKeyName = (group, user) => {
242
+ return new SenderKeyName(group, jidToSignalProtocolAddress(user));
243
+ };
244
+ //=======================================================//
245
+ function signalStorage({ creds, keys }, lidMapping) {
246
+ const resolveLIDSignalAddress = async (id) => {
247
+ if (id.includes(".")) {
248
+ const [deviceId, device] = id.split(".");
249
+ const [user, domainType_] = deviceId.split("_");
250
+ const domainType = parseInt(domainType_ || "0");
251
+ if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID)
252
+ return id;
253
+ const pnJid = `${user}${device !== "0" ? `:${device}` : ""}@${domainType === WAJIDDomains.HOSTED ? "hosted" : "s.whatsapp.net"}`;
254
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
255
+ if (lidForPN) {
256
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
257
+ return lidAddr.toString();
258
+ }
259
+ }
260
+ return id;
261
+ };
262
+ return {
263
+ loadSession: async (id) => {
264
+ try {
265
+ const wireJid = await resolveLIDSignalAddress(id);
266
+ const { [wireJid]: sess } = await keys.get("session", [wireJid]);
267
+ if (sess) {
268
+ return libsignal.SessionRecord.deserialize(sess);
269
+ }
270
+ }
271
+ catch (e) {
272
+ return null;
273
+ }
274
+ return null;
275
+ },
276
+ storeSession: async (id, session) => {
277
+ const wireJid = await resolveLIDSignalAddress(id);
278
+ await keys.set({ session: { [wireJid]: session.serialize() } });
279
+ },
280
+ isTrustedIdentity: () => {
281
+ return true;
282
+ },
283
+ loadPreKey: async (id) => {
284
+ const keyId = id.toString();
285
+ const { [keyId]: key } = await keys.get("pre-key", [keyId]);
286
+ if (key) {
287
+ return {
288
+ privKey: Buffer.from(key.private),
289
+ pubKey: Buffer.from(key.public)
290
+ };
291
+ }
292
+ },
293
+ removePreKey: (id) => keys.set({ "pre-key": { [id]: null } }),
294
+ loadSignedPreKey: () => {
295
+ const key = creds.signedPreKey;
296
+ return {
297
+ privKey: Buffer.from(key.keyPair.private),
298
+ pubKey: Buffer.from(key.keyPair.public)
299
+ };
300
+ },
301
+ loadSenderKey: async (senderKeyName) => {
302
+ const keyId = senderKeyName.toString();
303
+ const { [keyId]: key } = await keys.get("sender-key", [keyId]);
304
+ if (key) {
305
+ return SenderKeyRecord.deserialize(key);
306
+ }
307
+ return new SenderKeyRecord();
308
+ },
309
+ storeSenderKey: async (senderKeyName, key) => {
310
+ const keyId = senderKeyName.toString();
311
+ const serialized = JSON.stringify(key.serialize());
312
+ await keys.set({ "sender-key": { [keyId]: Buffer.from(serialized, "utf-8") } });
313
+ },
314
+ getOurRegistrationId: () => creds.registrationId,
315
+ getOurIdentity: () => {
316
+ const { signedIdentityKey } = creds;
317
+ return {
318
+ privKey: Buffer.from(signedIdentityKey.private),
319
+ pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
320
+ };
321
+ }
322
+ };
323
+ }
324
+ //=======================================================//