@baileys-md/baileys 11.2.4 → 12.0.0

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 (74) hide show
  1. package/README.md +113 -2
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +4775 -0
  4. package/WAProto/index.js +14270 -302
  5. package/lib/Defaults/index.js +50 -54
  6. package/lib/Defaults/wileys-version.json +3 -0
  7. package/lib/Signal/Group/ciphertext-message.js +15 -0
  8. package/lib/Signal/Group/group-session-builder.js +64 -0
  9. package/lib/Signal/Group/group_cipher.js +96 -0
  10. package/lib/Signal/Group/index.js +57 -0
  11. package/lib/Signal/Group/keyhelper.js +55 -0
  12. package/lib/Signal/Group/queue-job.js +57 -0
  13. package/lib/Signal/Group/sender-chain-key.js +34 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  15. package/lib/Signal/Group/sender-key-message.js +69 -0
  16. package/lib/Signal/Group/sender-key-name.js +51 -0
  17. package/lib/Signal/Group/sender-key-record.js +53 -0
  18. package/lib/Signal/Group/sender-key-state.js +99 -0
  19. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +6 -16
  20. package/lib/Signal/libsignal.js +33 -20
  21. package/lib/Socket/Client/index.js +2 -3
  22. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +54 -5
  23. package/lib/Socket/chats.js +136 -92
  24. package/lib/Socket/groups.js +16 -11
  25. package/lib/Socket/index.js +2 -2
  26. package/lib/Socket/messages-recv.js +26 -15
  27. package/lib/Socket/messages-send.js +122 -86
  28. package/lib/Socket/newsletter.js +23 -21
  29. package/lib/Socket/socket.js +29 -15
  30. package/lib/Store/make-in-memory-store.js +23 -15
  31. package/lib/Utils/auth-utils.js +0 -7
  32. package/lib/Utils/browser-utils.js +35 -0
  33. package/lib/Utils/chat-utils.js +2 -2
  34. package/lib/Utils/crypto.js +71 -29
  35. package/lib/Utils/decode-wa-message.js +15 -7
  36. package/lib/Utils/event-buffer.js +6 -8
  37. package/lib/Utils/generics.js +38 -16
  38. package/lib/Utils/history.js +1 -1
  39. package/lib/Utils/index.js +3 -1
  40. package/lib/Utils/message-retry-manager.js +128 -0
  41. package/lib/Utils/messages-media.js +212 -57
  42. package/lib/Utils/messages.js +38 -7
  43. package/lib/Utils/noise-handler.js +5 -10
  44. package/lib/Utils/process-message.js +34 -2
  45. package/lib/Utils/signal.js +26 -16
  46. package/lib/Utils/validate-connection.js +88 -66
  47. package/lib/Utils/{baileys-event-stream.js → wileys-event-stream.js} +1 -1
  48. package/lib/WABinary/constants.js +1276 -13
  49. package/lib/WABinary/jid-utils.js +20 -4
  50. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  51. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +3 -3
  52. package/lib/index.js +17 -6
  53. package/package.json +22 -17
  54. package/WASignalGroup/GroupProtocol.js +0 -1697
  55. package/WASignalGroup/ciphertext_message.js +0 -16
  56. package/WASignalGroup/group_cipher.js +0 -120
  57. package/WASignalGroup/group_session_builder.js +0 -46
  58. package/WASignalGroup/index.js +0 -5
  59. package/WASignalGroup/keyhelper.js +0 -21
  60. package/WASignalGroup/protobufs.js +0 -3
  61. package/WASignalGroup/queue_job.js +0 -69
  62. package/WASignalGroup/sender_chain_key.js +0 -50
  63. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  64. package/WASignalGroup/sender_key_message.js +0 -92
  65. package/WASignalGroup/sender_key_name.js +0 -70
  66. package/WASignalGroup/sender_key_record.js +0 -56
  67. package/WASignalGroup/sender_key_state.js +0 -129
  68. package/lib/Defaults/baileys-version.json +0 -3
  69. package/lib/Defaults/phonenumber-mcc.json +0 -223
  70. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  71. package/lib/Socket/registration.js +0 -166
  72. package/lib/Store/make-cache-manager-store.js +0 -83
  73. package/lib/Store/make-mongo-store.js +0 -567
  74. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyMessage = void 0;
4
+ const curve_1 = require("libsignal/src/curve");
5
+ const WAProto_1 = require("../../../WAProto");
6
+ const ciphertext_message_1 = require("./ciphertext-message");
7
+ class SenderKeyMessage extends ciphertext_message_1.CiphertextMessage {
8
+ constructor(keyId, iteration, ciphertext, signatureKey, serialized) {
9
+ super();
10
+ this.SIGNATURE_LENGTH = 64;
11
+ if (serialized) {
12
+ const version = serialized[0];
13
+ const message = serialized.slice(1, serialized.length - this.SIGNATURE_LENGTH);
14
+ const signature = serialized.slice(-1 * this.SIGNATURE_LENGTH);
15
+ const senderKeyMessage = WAProto_1.proto.SenderKeyMessage.decode(message).toJSON();
16
+ this.serialized = serialized;
17
+ this.messageVersion = (version & 0xff) >> 4;
18
+ this.keyId = senderKeyMessage.id;
19
+ this.iteration = senderKeyMessage.iteration;
20
+ this.ciphertext =
21
+ typeof senderKeyMessage.ciphertext === 'string'
22
+ ? Buffer.from(senderKeyMessage.ciphertext, 'base64')
23
+ : senderKeyMessage.ciphertext;
24
+ this.signature = signature;
25
+ }
26
+ else {
27
+ const version = (((this.CURRENT_VERSION << 4) | this.CURRENT_VERSION) & 0xff) % 256;
28
+ const ciphertextBuffer = Buffer.from(ciphertext);
29
+ const message = WAProto_1.proto.SenderKeyMessage.encode(WAProto_1.proto.SenderKeyMessage.create({
30
+ id: keyId,
31
+ iteration: iteration,
32
+ ciphertext: ciphertextBuffer
33
+ })).finish();
34
+ const signature = this.getSignature(signatureKey, Buffer.concat([Buffer.from([version]), message]));
35
+ this.serialized = Buffer.concat([Buffer.from([version]), message, Buffer.from(signature)]);
36
+ this.messageVersion = this.CURRENT_VERSION;
37
+ this.keyId = keyId;
38
+ this.iteration = iteration;
39
+ this.ciphertext = ciphertextBuffer;
40
+ this.signature = signature;
41
+ }
42
+ }
43
+ getKeyId() {
44
+ return this.keyId;
45
+ }
46
+ getIteration() {
47
+ return this.iteration;
48
+ }
49
+ getCipherText() {
50
+ return this.ciphertext;
51
+ }
52
+ verifySignature(signatureKey) {
53
+ const part1 = this.serialized.slice(0, this.serialized.length - this.SIGNATURE_LENGTH);
54
+ const part2 = this.serialized.slice(-1 * this.SIGNATURE_LENGTH);
55
+ const res = (0, curve_1.verifySignature)(signatureKey, part1, part2);
56
+ if (!res)
57
+ throw new Error('Invalid signature!');
58
+ }
59
+ getSignature(signatureKey, serialized) {
60
+ return Buffer.from((0, curve_1.calculateSignature)(signatureKey, serialized));
61
+ }
62
+ serialize() {
63
+ return this.serialized;
64
+ }
65
+ getType() {
66
+ return 4;
67
+ }
68
+ }
69
+ exports.SenderKeyMessage = SenderKeyMessage;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyName = void 0;
4
+ function isNull(str) {
5
+ return str === null || str === '';
6
+ }
7
+ function intValue(num) {
8
+ const MAX_VALUE = 0x7fffffff;
9
+ const MIN_VALUE = -0x80000000;
10
+ if (num > MAX_VALUE || num < MIN_VALUE) {
11
+ return num & 0xffffffff;
12
+ }
13
+ return num;
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
+ class SenderKeyName {
26
+ constructor(groupId, sender) {
27
+ this.groupId = groupId;
28
+ this.sender = sender;
29
+ }
30
+ getGroupId() {
31
+ return this.groupId;
32
+ }
33
+ getSender() {
34
+ return this.sender;
35
+ }
36
+ serialize() {
37
+ return `${this.groupId}::${this.sender.id}::${this.sender.deviceId}`;
38
+ }
39
+ toString() {
40
+ return this.serialize();
41
+ }
42
+ equals(other) {
43
+ if (other === null)
44
+ return false;
45
+ return this.groupId === other.groupId && this.sender.toString() === other.sender.toString();
46
+ }
47
+ hashCode() {
48
+ return hashCode(this.groupId) ^ hashCode(this.sender.toString());
49
+ }
50
+ }
51
+ exports.SenderKeyName = SenderKeyName;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyRecord = void 0;
4
+ const generics_1 = require("../../Utils/generics");
5
+ const sender_key_state_1 = require("./sender-key-state");
6
+ class SenderKeyRecord {
7
+ constructor(serialized) {
8
+ this.MAX_STATES = 5;
9
+ this.senderKeyStates = [];
10
+ if (serialized) {
11
+ for (const structure of serialized) {
12
+ this.senderKeyStates.push(new sender_key_state_1.SenderKeyState(null, null, null, null, null, null, structure));
13
+ }
14
+ }
15
+ }
16
+ isEmpty() {
17
+ return this.senderKeyStates.length === 0;
18
+ }
19
+ getSenderKeyState(keyId) {
20
+ if (keyId === undefined && this.senderKeyStates.length) {
21
+ return this.senderKeyStates[this.senderKeyStates.length - 1];
22
+ }
23
+ return this.senderKeyStates.find(state => state.getKeyId() === keyId);
24
+ }
25
+ addSenderKeyState(id, iteration, chainKey, signatureKey) {
26
+ this.senderKeyStates.push(new sender_key_state_1.SenderKeyState(id, iteration, chainKey, null, signatureKey));
27
+ if (this.senderKeyStates.length > this.MAX_STATES) {
28
+ this.senderKeyStates.shift();
29
+ }
30
+ }
31
+ setSenderKeyState(id, iteration, chainKey, keyPair) {
32
+ this.senderKeyStates.length = 0;
33
+ this.senderKeyStates.push(new sender_key_state_1.SenderKeyState(id, iteration, chainKey, keyPair));
34
+ }
35
+ serialize() {
36
+ return this.senderKeyStates.map(state => state.getStructure());
37
+ }
38
+ static deserialize(data) {
39
+ let parsed;
40
+ if (typeof data === 'string') {
41
+ parsed = JSON.parse(data, generics_1.BufferJSON.reviver);
42
+ }
43
+ else if (data instanceof Uint8Array) {
44
+ const str = Buffer.from(data).toString('utf-8');
45
+ parsed = JSON.parse(str, generics_1.BufferJSON.reviver);
46
+ }
47
+ else {
48
+ parsed = data;
49
+ }
50
+ return new SenderKeyRecord(parsed);
51
+ }
52
+ }
53
+ exports.SenderKeyRecord = SenderKeyRecord;
@@ -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;
@@ -1,39 +1,29 @@
1
- const { deriveSecrets } = require('libsignal/src/crypto');
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderMessageKey = void 0;
4
+ const crypto_1 = require("libsignal/src/crypto");
2
5
  class SenderMessageKey {
3
- iteration = 0;
4
-
5
- iv = Buffer.alloc(0);
6
-
7
- cipherKey = Buffer.alloc(0);
8
-
9
- seed = Buffer.alloc(0);
10
-
11
6
  constructor(iteration, seed) {
12
- const derivative = deriveSecrets(seed, Buffer.alloc(32), Buffer.from('WhisperGroup'));
7
+ const derivative = (0, crypto_1.deriveSecrets)(seed, Buffer.alloc(32), Buffer.from('WhisperGroup'));
13
8
  const keys = new Uint8Array(32);
14
9
  keys.set(new Uint8Array(derivative[0].slice(16)));
15
10
  keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
16
11
  this.iv = Buffer.from(derivative[0].slice(0, 16));
17
12
  this.cipherKey = Buffer.from(keys.buffer);
18
-
19
13
  this.iteration = iteration;
20
14
  this.seed = seed;
21
15
  }
22
-
23
16
  getIteration() {
24
17
  return this.iteration;
25
18
  }
26
-
27
19
  getIv() {
28
20
  return this.iv;
29
21
  }
30
-
31
22
  getCipherKey() {
32
23
  return this.cipherKey;
33
24
  }
34
-
35
25
  getSeed() {
36
26
  return this.seed;
37
27
  }
38
28
  }
39
- module.exports = SenderMessageKey;
29
+ exports.SenderMessageKey = SenderMessageKey;
@@ -35,24 +35,30 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.makeLibSignalRepository = makeLibSignalRepository;
37
37
  const libsignal = __importStar(require("libsignal"));
38
- const WASignalGroup_1 = require("../../WASignalGroup");
39
38
  const Utils_1 = require("../Utils");
40
39
  const WABinary_1 = require("../WABinary");
40
+ const sender_key_name_1 = require("./Group/sender-key-name");
41
+ const sender_key_record_1 = require("./Group/sender-key-record");
42
+ const Group_1 = require("./Group");
41
43
  function makeLibSignalRepository(auth) {
42
44
  const storage = signalStorage(auth);
43
45
  return {
44
46
  decryptGroupMessage({ group, authorJid, msg }) {
45
47
  const senderName = jidToSignalSenderKeyName(group, authorJid);
46
- const cipher = new WASignalGroup_1.GroupCipher(storage, senderName);
48
+ const cipher = new Group_1.GroupCipher(storage, senderName);
47
49
  return cipher.decrypt(msg);
48
50
  },
49
51
  async processSenderKeyDistributionMessage({ item, authorJid }) {
50
- const builder = new WASignalGroup_1.GroupSessionBuilder(storage);
52
+ const builder = new Group_1.GroupSessionBuilder(storage);
53
+ if (!item.groupId) {
54
+ throw new Error('Group ID is required for sender key distribution message');
55
+ }
51
56
  const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
52
- const senderMsg = new WASignalGroup_1.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
53
- const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName]);
57
+ const senderMsg = new Group_1.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
58
+ const senderNameStr = senderName.toString();
59
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
54
60
  if (!senderKey) {
55
- await storage.storeSenderKey(senderName, new WASignalGroup_1.SenderKeyRecord());
61
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
56
62
  }
57
63
  await builder.process(senderName, senderMsg);
58
64
  },
@@ -67,6 +73,8 @@ function makeLibSignalRepository(auth) {
67
73
  case 'msg':
68
74
  result = await session.decryptWhisperMessage(ciphertext);
69
75
  break;
76
+ default:
77
+ throw new Error(`Unknown message type: ${type}`);
70
78
  }
71
79
  return result;
72
80
  },
@@ -79,17 +87,18 @@ function makeLibSignalRepository(auth) {
79
87
  },
80
88
  async encryptGroupMessage({ group, meId, data }) {
81
89
  const senderName = jidToSignalSenderKeyName(group, meId);
82
- const builder = new WASignalGroup_1.GroupSessionBuilder(storage);
83
- const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName]);
90
+ const builder = new Group_1.GroupSessionBuilder(storage);
91
+ const senderNameStr = senderName.toString();
92
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
84
93
  if (!senderKey) {
85
- await storage.storeSenderKey(senderName, new WASignalGroup_1.SenderKeyRecord());
94
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
86
95
  }
87
96
  const senderKeyDistributionMessage = await builder.create(senderName);
88
- const session = new WASignalGroup_1.GroupCipher(storage, senderName);
97
+ const session = new Group_1.GroupCipher(storage, senderName);
89
98
  const ciphertext = await session.encrypt(data);
90
99
  return {
91
100
  ciphertext,
92
- senderKeyDistributionMessage: senderKeyDistributionMessage.serialize(),
101
+ senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
93
102
  };
94
103
  },
95
104
  async injectE2ESession({ jid, session }) {
@@ -98,7 +107,7 @@ function makeLibSignalRepository(auth) {
98
107
  },
99
108
  jidToSignalProtocolAddress(jid) {
100
109
  return jidToSignalProtocolAddress(jid).toString();
101
- },
110
+ }
102
111
  };
103
112
  }
104
113
  const jidToSignalProtocolAddress = (jid) => {
@@ -106,7 +115,7 @@ const jidToSignalProtocolAddress = (jid) => {
106
115
  return new libsignal.ProtocolAddress(user, device || 0);
107
116
  };
108
117
  const jidToSignalSenderKeyName = (group, user) => {
109
- return new WASignalGroup_1.SenderKeyName(group, jidToSignalProtocolAddress(user)).toString();
118
+ return new sender_key_name_1.SenderKeyName(group, jidToSignalProtocolAddress(user));
110
119
  };
111
120
  function signalStorage({ creds, keys }) {
112
121
  return {
@@ -117,7 +126,7 @@ function signalStorage({ creds, keys }) {
117
126
  }
118
127
  },
119
128
  storeSession: async (id, session) => {
120
- await keys.set({ 'session': { [id]: session.serialize() } });
129
+ await keys.set({ session: { [id]: session.serialize() } });
121
130
  },
122
131
  isTrustedIdentity: () => {
123
132
  return true;
@@ -140,21 +149,25 @@ function signalStorage({ creds, keys }) {
140
149
  pubKey: Buffer.from(key.keyPair.public)
141
150
  };
142
151
  },
143
- loadSenderKey: async (keyId) => {
152
+ loadSenderKey: async (senderKeyName) => {
153
+ const keyId = senderKeyName.toString();
144
154
  const { [keyId]: key } = await keys.get('sender-key', [keyId]);
145
155
  if (key) {
146
- return new WASignalGroup_1.SenderKeyRecord(key);
156
+ return sender_key_record_1.SenderKeyRecord.deserialize(key);
147
157
  }
158
+ return new sender_key_record_1.SenderKeyRecord();
148
159
  },
149
- storeSenderKey: async (keyId, key) => {
150
- await keys.set({ 'sender-key': { [keyId]: key.serialize() } });
160
+ storeSenderKey: async (senderKeyName, key) => {
161
+ const keyId = senderKeyName.toString();
162
+ const serialized = JSON.stringify(key.serialize());
163
+ await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } });
151
164
  },
152
- getOurRegistrationId: () => (creds.registrationId),
165
+ getOurRegistrationId: () => creds.registrationId,
153
166
  getOurIdentity: () => {
154
167
  const { signedIdentityKey } = creds;
155
168
  return {
156
169
  privKey: Buffer.from(signedIdentityKey.private),
157
- pubKey: (0, Utils_1.generateSignalPubKey)(signedIdentityKey.public),
170
+ pubKey: (0, Utils_1.generateSignalPubKey)(signedIdentityKey.public)
158
171
  };
159
172
  }
160
173
  };
@@ -14,6 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./abstract-socket-client"), exports);
18
- __exportStar(require("./mobile-socket-client"), exports);
19
- __exportStar(require("./web-socket-client"), exports);
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./websocket"), exports);
@@ -6,11 +6,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.WebSocketClient = void 0;
7
7
  const ws_1 = __importDefault(require("ws"));
8
8
  const Defaults_1 = require("../../Defaults");
9
- const abstract_socket_client_1 = require("./abstract-socket-client");
10
- class WebSocketClient extends abstract_socket_client_1.AbstractSocketClient {
9
+ const types_1 = require("./types");
10
+ class WebSocketClient extends types_1.AbstractSocketClient {
11
11
  constructor() {
12
12
  super(...arguments);
13
13
  this.socket = null;
14
+ // queue & dispatch variables for throttling outgoing messages to avoid rate limits
15
+ this._queue = [];
16
+ this._isDispatching = false;
17
+ this._lastDispatch = 0;
18
+ this._minSendIntervalMs = (Defaults_1.DEFAULT_CONNECTION_CONFIG && Defaults_1.DEFAULT_CONNECTION_CONFIG.minSendIntervalMs) || 50;
14
19
  }
15
20
  get isOpen() {
16
21
  var _a;
@@ -53,10 +58,54 @@ class WebSocketClient extends abstract_socket_client_1.AbstractSocketClient {
53
58
  this.socket.close();
54
59
  this.socket = null;
55
60
  }
61
+ async restart() {
62
+ if (this.socket) {
63
+ await new Promise(resolve => {
64
+ this.socket.once('close', resolve);
65
+ this.socket.terminate();
66
+ });
67
+ this.socket = null;
68
+ }
69
+ await this.connect();
70
+ }
56
71
  send(str, cb) {
57
- var _a;
58
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, cb);
59
- return Boolean(this.socket);
72
+ // throttle sends to reduce rate-limit likelihood
73
+ const doSend = () => {
74
+ var _a;
75
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, cb);
76
+ return Boolean(this.socket);
77
+ };
78
+ this._queue.push(doSend);
79
+ this._dispatch();
80
+ return true;
81
+ }
82
+
83
+ _dispatch() {
84
+ if (this._isDispatching) {
85
+ return;
86
+ }
87
+ this._isDispatching = true;
88
+ const tick = () => {
89
+ const now = Date.now();
90
+ if (this._queue.length === 0) {
91
+ this._isDispatching = false;
92
+ return;
93
+ }
94
+ const delta = now - this._lastDispatch;
95
+ const wait = Math.max(0, this._minSendIntervalMs - delta);
96
+ setTimeout(() => {
97
+ const fn = this._queue.shift();
98
+ this._lastDispatch = Date.now();
99
+ try {
100
+ fn && fn();
101
+ }
102
+ catch (_err) {
103
+ // ignore send errors here; they'll surface elsewhere
104
+ }
105
+ tick();
106
+ }, wait);
107
+ };
108
+ tick();
60
109
  }
61
110
  }
62
111
  exports.WebSocketClient = WebSocketClient;