rixleys 1.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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/README.MD +2969 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/index.js +97692 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +120 -0
  9. package/lib/Defaults/rixleys-version.json +3 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +64 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.js +57 -0
  14. package/lib/Signal/Group/keyhelper.js +55 -0
  15. package/lib/Signal/Group/queue-job.js +57 -0
  16. package/lib/Signal/Group/sender-chain-key.js +34 -0
  17. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/lib/Signal/Group/sender-key-message.js +69 -0
  19. package/lib/Signal/Group/sender-key-name.js +51 -0
  20. package/lib/Signal/Group/sender-key-record.js +53 -0
  21. package/lib/Signal/Group/sender-key-state.js +99 -0
  22. package/lib/Signal/Group/sender-message-key.js +29 -0
  23. package/lib/Signal/core/.eslintrc.json +31 -0
  24. package/lib/Signal/core/CODE_OF_CONDUCT.md +102 -0
  25. package/lib/Signal/core/LICENSE +621 -0
  26. package/lib/Signal/core/README.md +64 -0
  27. package/lib/Signal/core/SECURITY.md +78 -0
  28. package/lib/Signal/core/generate-proto.sh +1 -0
  29. package/lib/Signal/core/index.d.ts +55 -0
  30. package/lib/Signal/core/index.js +10 -0
  31. package/lib/Signal/core/protos/WhisperTextProtocol.proto +28 -0
  32. package/lib/Signal/core/src/.eslintrc.json +31 -0
  33. package/lib/Signal/core/src/WhisperTextProtocol.js +933 -0
  34. package/lib/Signal/core/src/base_key_type.js +7 -0
  35. package/lib/Signal/core/src/chain_type.js +6 -0
  36. package/lib/Signal/core/src/crypto.d.ts +19 -0
  37. package/lib/Signal/core/src/crypto.js +98 -0
  38. package/lib/Signal/core/src/curve.d.ts +22 -0
  39. package/lib/Signal/core/src/curve.js +142 -0
  40. package/lib/Signal/core/src/errors.js +33 -0
  41. package/lib/Signal/core/src/keyhelper.js +45 -0
  42. package/lib/Signal/core/src/numeric_fingerprint.js +72 -0
  43. package/lib/Signal/core/src/protobufs.js +10 -0
  44. package/lib/Signal/core/src/protocol_address.js +40 -0
  45. package/lib/Signal/core/src/queue_job.js +69 -0
  46. package/lib/Signal/core/src/session_builder.js +164 -0
  47. package/lib/Signal/core/src/session_cipher.js +336 -0
  48. package/lib/Signal/core/src/session_record.js +316 -0
  49. package/lib/Signal/libsignal.js +184 -0
  50. package/lib/Socket/Client/index.js +18 -0
  51. package/lib/Socket/Client/types.js +13 -0
  52. package/lib/Socket/Client/websocket.js +72 -0
  53. package/lib/Socket/business.js +260 -0
  54. package/lib/Socket/chats.js +997 -0
  55. package/lib/Socket/groups.js +418 -0
  56. package/lib/Socket/index.js +238 -0
  57. package/lib/Socket/messages-recv.js +1106 -0
  58. package/lib/Socket/messages-send.js +882 -0
  59. package/lib/Socket/newsletter.js +250 -0
  60. package/lib/Socket/socket.js +646 -0
  61. package/lib/Socket/usync.js +70 -0
  62. package/lib/Store/index.js +8 -0
  63. package/lib/Store/make-in-memory-store.js +439 -0
  64. package/lib/Store/make-ordered-dictionary.js +81 -0
  65. package/lib/Store/object-repository.js +27 -0
  66. package/lib/Types/Auth.js +2 -0
  67. package/lib/Types/Call.js +2 -0
  68. package/lib/Types/Chat.js +4 -0
  69. package/lib/Types/Contact.js +2 -0
  70. package/lib/Types/Events.js +2 -0
  71. package/lib/Types/GroupMetadata.js +2 -0
  72. package/lib/Types/Label.js +27 -0
  73. package/lib/Types/LabelAssociation.js +9 -0
  74. package/lib/Types/Message.js +7 -0
  75. package/lib/Types/Newsletter.js +18 -0
  76. package/lib/Types/Product.js +2 -0
  77. package/lib/Types/Signal.js +2 -0
  78. package/lib/Types/Socket.js +2 -0
  79. package/lib/Types/State.js +2 -0
  80. package/lib/Types/USync.js +2 -0
  81. package/lib/Types/index.js +42 -0
  82. package/lib/Utils/auth-utils.js +199 -0
  83. package/lib/Utils/browser-utils.js +35 -0
  84. package/lib/Utils/business.js +234 -0
  85. package/lib/Utils/chat-utils.js +730 -0
  86. package/lib/Utils/crypto.js +193 -0
  87. package/lib/Utils/decode-wa-message.js +217 -0
  88. package/lib/Utils/event-buffer.js +518 -0
  89. package/lib/Utils/generics.js +467 -0
  90. package/lib/Utils/history.js +94 -0
  91. package/lib/Utils/index.js +36 -0
  92. package/lib/Utils/link-preview.js +151 -0
  93. package/lib/Utils/logger.js +7 -0
  94. package/lib/Utils/lt-hash.js +51 -0
  95. package/lib/Utils/make-mutex.js +43 -0
  96. package/lib/Utils/message-retry-manager.js +185 -0
  97. package/lib/Utils/messages-media.js +879 -0
  98. package/lib/Utils/messages.js +1049 -0
  99. package/lib/Utils/noise-handler.js +150 -0
  100. package/lib/Utils/process-message.js +404 -0
  101. package/lib/Utils/rixleys-event-stream.js +63 -0
  102. package/lib/Utils/serializer.js +238 -0
  103. package/lib/Utils/signal.js +153 -0
  104. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  105. package/lib/Utils/validate-connection.js +229 -0
  106. package/lib/WABinary/constants.js +1303 -0
  107. package/lib/WABinary/decode.js +265 -0
  108. package/lib/WABinary/encode.js +250 -0
  109. package/lib/WABinary/generic-utils.js +110 -0
  110. package/lib/WABinary/index.js +21 -0
  111. package/lib/WABinary/jid-utils.js +85 -0
  112. package/lib/WABinary/types.js +2 -0
  113. package/lib/WAM/BinaryInfo.js +13 -0
  114. package/lib/WAM/constants.js +15350 -0
  115. package/lib/WAM/encode.js +155 -0
  116. package/lib/WAM/index.js +19 -0
  117. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  118. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  119. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  120. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  121. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  122. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  123. package/lib/WAUSync/Protocols/index.js +20 -0
  124. package/lib/WAUSync/USyncQuery.js +89 -0
  125. package/lib/WAUSync/USyncUser.js +26 -0
  126. package/lib/WAUSync/index.js +19 -0
  127. package/lib/index.js +54 -0
  128. package/package.json +113 -0
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.serialize = serialize;
5
+ exports.smsg = serialize;
6
+ exports.getContentType = getContentType;
7
+ exports.getDevice = getDevice;
8
+ exports.extractText = extractText;
9
+
10
+ const jid_utils_1 = require("../WABinary/jid-utils");
11
+
12
+ /**
13
+ * Buffer stream helper
14
+ */
15
+ const toBuffer = async (stream) => {
16
+ let buffer = Buffer.from([]);
17
+ for await (const chunk of stream) buffer = Buffer.concat([buffer, chunk]);
18
+ return buffer;
19
+ };
20
+
21
+ /**
22
+ * Extract plain text / caption from message object
23
+ */
24
+ function extractText(msg = {}, type = "") {
25
+ return (
26
+ msg?.conversation ||
27
+ msg?.[type]?.text ||
28
+ msg?.[type]?.caption ||
29
+ msg?.[type]?.contentText ||
30
+ msg?.[type]?.selectedDisplayText ||
31
+ ""
32
+ );
33
+ }
34
+
35
+ /**
36
+ * Get content type of message
37
+ */
38
+ function getContentType(content) {
39
+ if (content) {
40
+ const keys = Object.keys(content);
41
+ const key = keys.find(
42
+ (k) =>
43
+ (k === "conversation" || k.endsWith("Message") || k.includes("V2")) &&
44
+ k !== "senderKeyDistributionMessage"
45
+ );
46
+ return key;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Device detector from Stanza ID
52
+ */
53
+ function getDevice(id) {
54
+ if (!id) return "UNKNOWN";
55
+ if (id.length > 21) return "ANDROID";
56
+ if (id.substring(0, 2) === "3A") return "IOS";
57
+ if (id.substring(0, 4) === "3EB0") return "WEB";
58
+ if (id.startsWith("BAE5") || id.startsWith("3EB0") || id.startsWith("B1E") || id.startsWith("3F8")) return "BOT";
59
+ return "UNKNOWN";
60
+ }
61
+
62
+ /**
63
+ * Serialize WhatsApp Message
64
+ * @param {any} sock Baileys / Rixleys socket instance (optional)
65
+ * @param {any} m Raw message payload from messages.upsert
66
+ * @returns {any} Serialized message
67
+ */
68
+ function serialize(sock, m) {
69
+ if (!m) {
70
+ m = sock;
71
+ sock = null;
72
+ }
73
+ if (!m) return null;
74
+
75
+ const msg = m.messages?.[0] || m;
76
+ if (!msg?.message) return m;
77
+
78
+ // Chat JID & Group Flag
79
+ m.chat = msg.key?.remoteJid || "";
80
+ m.isGroup = (0, jid_utils_1.isJidGroup)(m.chat) || m.chat.endsWith("@g.us");
81
+ m.fromMe = !!msg.key?.fromMe;
82
+ m.id = msg.key?.id || "";
83
+ m.pushName = msg.pushName || "";
84
+ m.device = getDevice(m.id);
85
+
86
+ // ==========================================
87
+ // SENDER RESOLVER (m.senderJid & m.senderLid)
88
+ // ==========================================
89
+ const rawParticipant =
90
+ msg.key?.participantAlt ||
91
+ msg.key?.participantPn ||
92
+ msg.key?.participant ||
93
+ msg.key?.remoteJidAlt ||
94
+ msg.key?.remoteJid ||
95
+ "";
96
+
97
+ const normalizedSender = (0, jid_utils_1.jidNormalizedUser)(rawParticipant);
98
+
99
+ if (normalizedSender.endsWith("@lid")) {
100
+ m.senderLid = normalizedSender;
101
+ const altPn = msg.key?.participantPn || msg.key?.participantAlt;
102
+ m.senderJid = altPn ? (0, jid_utils_1.jidNormalizedUser)(altPn) : normalizedSender;
103
+ } else {
104
+ m.senderJid = normalizedSender;
105
+ const altLid = msg.key?.participantAlt?.endsWith("@lid")
106
+ ? (0, jid_utils_1.jidNormalizedUser)(msg.key.participantAlt)
107
+ : null;
108
+ m.senderLid = altLid || null;
109
+ }
110
+
111
+ m.sender = m.senderJid;
112
+ m.Pn = m.senderJid ? m.senderJid.replace(/[^0-9]/g, "") : "";
113
+
114
+ // Content Type & Body
115
+ m.mtype = getContentType(msg.message) || "";
116
+ m.text = extractText(msg.message, m.mtype);
117
+ m.body = m.text;
118
+
119
+ // Context Info & Quoted
120
+ const ctx =
121
+ msg.message?.extendedTextMessage?.contextInfo ||
122
+ msg.message?.[m.mtype]?.contextInfo ||
123
+ null;
124
+
125
+ m.mentionedJid = ctx?.mentionedJid || [];
126
+ m.quoted = null;
127
+
128
+ // ==========================================
129
+ // QUOTED MESSAGE WRAPPER (m.quoted)
130
+ // ==========================================
131
+ if (ctx?.quotedMessage) {
132
+ const qMsg = ctx.quotedMessage;
133
+ const qType = getContentType(qMsg) || "";
134
+ const qInner = qMsg?.[qType] || {};
135
+
136
+ const qRawParticipant = ctx.participant || "";
137
+ const qNormalizedSender = (0, jid_utils_1.jidNormalizedUser)(qRawParticipant);
138
+
139
+ let qSenderJid = qNormalizedSender;
140
+ let qSenderLid = null;
141
+
142
+ if (qNormalizedSender.endsWith("@lid")) {
143
+ qSenderLid = qNormalizedSender;
144
+ qSenderJid = qNormalizedSender;
145
+ } else {
146
+ qSenderJid = qNormalizedSender;
147
+ }
148
+
149
+ m.quoted = {
150
+ id: ctx.stanzaId || "",
151
+ chat: m.chat,
152
+ sender: qSenderJid,
153
+ senderJid: qSenderJid,
154
+ senderLid: qSenderLid,
155
+ fromMe:
156
+ qNormalizedSender ===
157
+ (0, jid_utils_1.jidNormalizedUser)(msg.key?.fromMe ? m.senderJid : (sock?.user?.id || "")),
158
+ mtype: qType,
159
+ text: extractText(qMsg, qType),
160
+ body: extractText(qMsg, qType),
161
+ message: qMsg,
162
+ key: {
163
+ remoteJid: m.chat,
164
+ fromMe:
165
+ qNormalizedSender ===
166
+ (0, jid_utils_1.jidNormalizedUser)(msg.key?.fromMe ? m.senderJid : (sock?.user?.id || "")),
167
+ id: ctx.stanzaId,
168
+ participant: m.isGroup ? ctx.participant : undefined
169
+ },
170
+ mentionedJid: qInner?.contextInfo?.mentionedJid || [],
171
+ device: getDevice(ctx.stanzaId),
172
+
173
+ // Method: Delete Quoted
174
+ delete: async (customSock = sock) => {
175
+ if (!customSock) throw new Error("Socket instance is required for delete");
176
+ return customSock.sendMessage(m.chat, { delete: m.quoted.key });
177
+ },
178
+
179
+ // Method: Download Quoted Media
180
+ download: async () => {
181
+ const mediaContent =
182
+ qMsg.imageMessage ||
183
+ qMsg.videoMessage ||
184
+ qMsg.audioMessage ||
185
+ qMsg.stickerMessage ||
186
+ qMsg.documentMessage ||
187
+ qMsg.viewOnceMessage?.message?.imageMessage ||
188
+ qMsg.viewOnceMessage?.message?.videoMessage ||
189
+ qMsg.viewOnceMessageV2?.message?.imageMessage ||
190
+ qMsg.viewOnceMessageV2?.message?.videoMessage;
191
+
192
+ if (!mediaContent) throw new Error("Quoted message is not a media message");
193
+
194
+ const messages_media = require("./messages-media");
195
+ const mediaType = qMsg.imageMessage
196
+ ? "image"
197
+ : qMsg.videoMessage
198
+ ? "video"
199
+ : qMsg.audioMessage
200
+ ? "audio"
201
+ : qMsg.stickerMessage
202
+ ? "sticker"
203
+ : "document";
204
+
205
+ const stream = await messages_media.downloadContentFromMessage(mediaContent, mediaType);
206
+ return toBuffer(stream);
207
+ }
208
+ };
209
+ }
210
+
211
+ // Attach shortcut action helpers to m if sock is passed
212
+ if (sock) {
213
+ m.reply = (text, options = {}) => {
214
+ return sock.sendMessage(
215
+ m.chat,
216
+ {
217
+ text,
218
+ mentions: options.mentions || [m.senderJid],
219
+ ...options
220
+ },
221
+ { quoted: options.quoted || msg }
222
+ );
223
+ };
224
+
225
+ m.react = (emoji) => {
226
+ return sock.sendMessage(m.chat, {
227
+ react: {
228
+ text: emoji,
229
+ key: msg.key
230
+ }
231
+ });
232
+ };
233
+ }
234
+
235
+ return m;
236
+ }
237
+
238
+ exports.default = serialize;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const lodash_1 = require("lodash");
5
+ const Defaults_1 = require("../Defaults");
6
+ const WABinary_1 = require("../WABinary");
7
+ const crypto_1 = require("./crypto");
8
+ const generics_1 = require("./generics");
9
+ const createSignalIdentity = (wid, accountSignatureKey) => {
10
+ return {
11
+ identifier: { name: wid, deviceId: 0 },
12
+ identifierKey: (0, crypto_1.generateSignalPubKey)(accountSignatureKey)
13
+ };
14
+ };
15
+ exports.createSignalIdentity = createSignalIdentity;
16
+ const getPreKeys = async ({ get }, min, limit) => {
17
+ const idList = [];
18
+ for (let id = min; id < limit; id++) {
19
+ idList.push(id.toString());
20
+ }
21
+ return get('pre-key', idList);
22
+ };
23
+ exports.getPreKeys = getPreKeys;
24
+ const generateOrGetPreKeys = (creds, range) => {
25
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
26
+ const remaining = range - avaliable;
27
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
28
+ const newPreKeys = {};
29
+ if (remaining > 0) {
30
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
31
+ newPreKeys[i] = crypto_1.Curve.generateKeyPair();
32
+ }
33
+ }
34
+ return {
35
+ newPreKeys,
36
+ lastPreKeyId,
37
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range],
38
+ };
39
+ };
40
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
41
+ const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ exports.xmppSignedPreKey = xmppSignedPreKey;
51
+ const xmppPreKey = (pair, id) => ({
52
+ tag: 'key',
53
+ attrs: {},
54
+ content: [
55
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(id, 3) },
56
+ { tag: 'value', attrs: {}, content: pair.public }
57
+ ]
58
+ });
59
+ exports.xmppPreKey = xmppPreKey;
60
+ const parseAndInjectE2ESessions = async (node, repository) => {
61
+ const extractKey = (key) => (key ? ({
62
+ keyId: (0, WABinary_1.getBinaryNodeChildUInt)(key, 'id', 3),
63
+ publicKey: (0, crypto_1.generateSignalPubKey)((0, WABinary_1.getBinaryNodeChildBuffer)(key, 'value')),
64
+ signature: (0, WABinary_1.getBinaryNodeChildBuffer)(key, 'signature'),
65
+ }) : undefined);
66
+ const nodes = (0, WABinary_1.getBinaryNodeChildren)((0, WABinary_1.getBinaryNodeChild)(node, 'list'), 'user');
67
+ for (const node of nodes) {
68
+ (0, WABinary_1.assertNodeErrorFree)(node);
69
+ }
70
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
71
+ // So Promise.all doesn't really help here,
72
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
73
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
74
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
75
+ const chunkSize = 100;
76
+ const chunks = (0, lodash_1.chunk)(nodes, chunkSize);
77
+ for (const nodesChunk of chunks) {
78
+ await Promise.all(nodesChunk.map(async (node) => {
79
+ const signedKey = (0, WABinary_1.getBinaryNodeChild)(node, 'skey');
80
+ const key = (0, WABinary_1.getBinaryNodeChild)(node, 'key');
81
+ const identity = (0, WABinary_1.getBinaryNodeChildBuffer)(node, 'identity');
82
+ const jid = node.attrs.jid;
83
+ const registrationId = (0, WABinary_1.getBinaryNodeChildUInt)(node, 'registration', 4);
84
+ await repository.injectE2ESession({
85
+ jid,
86
+ session: {
87
+ registrationId: registrationId,
88
+ identityKey: (0, crypto_1.generateSignalPubKey)(identity),
89
+ signedPreKey: extractKey(signedKey),
90
+ preKey: extractKey(key)
91
+ }
92
+ });
93
+ }));
94
+ }
95
+ };
96
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
97
+ const extractDeviceJids = (result, myJid, excludeZeroDevices) => {
98
+ const { user: myUser, device: myDevice } = (0, WABinary_1.jidDecode)(myJid);
99
+ const extracted = [];
100
+ for (const userResult of result) {
101
+ const { devices, id } = userResult;
102
+ const { user } = (0, WABinary_1.jidDecode)(id);
103
+ const deviceList = devices === null || devices === void 0 ? void 0 : devices.deviceList;
104
+ if (Array.isArray(deviceList)) {
105
+ for (const { id: device, keyIndex } of deviceList) {
106
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
107
+ (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
108
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
109
+ ) {
110
+ extracted.push({ user, device });
111
+ }
112
+ }
113
+ }
114
+ }
115
+ return extracted;
116
+ };
117
+ exports.extractDeviceJids = extractDeviceJids;
118
+ /**
119
+ * get the next N keys for upload or processing
120
+ * @param count number of pre-keys to get or generate
121
+ */
122
+ const getNextPreKeys = async ({ creds, keys }, count) => {
123
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
124
+ const update = {
125
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
126
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
127
+ };
128
+ await keys.set({ 'pre-key': newPreKeys });
129
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
130
+ return { update, preKeys };
131
+ };
132
+ exports.getNextPreKeys = getNextPreKeys;
133
+ const getNextPreKeysNode = async (state, count) => {
134
+ const { creds } = state;
135
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
136
+ const node = {
137
+ tag: 'iq',
138
+ attrs: {
139
+ xmlns: 'encrypt',
140
+ type: 'set',
141
+ to: WABinary_1.S_WHATSAPP_NET,
142
+ },
143
+ content: [
144
+ { tag: 'registration', attrs: {}, content: (0, generics_1.encodeBigEndian)(creds.registrationId) },
145
+ { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
146
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
147
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
148
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
149
+ ]
150
+ };
151
+ return { update, node };
152
+ };
153
+ exports.getNextPreKeysNode = getNextPreKeysNode;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useMultiFileAuthState = void 0;
4
+ const async_mutex_1 = require("async-mutex");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const WAProto_1 = require("../../WAProto");
8
+ const auth_utils_1 = require("./auth-utils");
9
+ const generics_1 = require("./generics");
10
+ // We need to lock files due to the fact that we are using async functions to read and write files
11
+ // https://github.com/WhiskeySockets/Rixleys/issues/794
12
+ // https://github.com/nodejs/node/issues/26338
13
+ // Use a Map to store mutexes for each file path
14
+ const fileLocks = new Map();
15
+ // Get or create a mutex for a specific file path
16
+ const getFileLock = (path) => {
17
+ let mutex = fileLocks.get(path);
18
+ if (!mutex) {
19
+ mutex = new async_mutex_1.Mutex();
20
+ fileLocks.set(path, mutex);
21
+ }
22
+ return mutex;
23
+ };
24
+ /**
25
+ * stores the full authentication state in a single folder.
26
+ * Far more efficient than singlefileauthstate
27
+ *
28
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
29
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
30
+ * */
31
+ const useMultiFileAuthState = async (folder) => {
32
+ const writeData = async (data, file) => {
33
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
34
+ const mutex = getFileLock(filePath);
35
+ return mutex.acquire().then(async (release) => {
36
+ try {
37
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer));
38
+ }
39
+ finally {
40
+ release();
41
+ }
42
+ });
43
+ };
44
+ const readData = async (file) => {
45
+ try {
46
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
47
+ const mutex = getFileLock(filePath);
48
+ return await mutex.acquire().then(async (release) => {
49
+ try {
50
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
51
+ return JSON.parse(data, generics_1.BufferJSON.reviver);
52
+ }
53
+ finally {
54
+ release();
55
+ }
56
+ });
57
+ }
58
+ catch (error) {
59
+ return null;
60
+ }
61
+ };
62
+ const removeData = async (file) => {
63
+ try {
64
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
65
+ const mutex = getFileLock(filePath);
66
+ return mutex.acquire().then(async (release) => {
67
+ try {
68
+ await (0, promises_1.unlink)(filePath);
69
+ }
70
+ catch (_a) {
71
+ }
72
+ finally {
73
+ release();
74
+ }
75
+ });
76
+ }
77
+ catch (_a) {
78
+ }
79
+ };
80
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
81
+ if (folderInfo) {
82
+ if (!folderInfo.isDirectory()) {
83
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
84
+ }
85
+ }
86
+ else {
87
+ await (0, promises_1.mkdir)(folder, { recursive: true });
88
+ }
89
+ const fixFileName = (file) => { var _a; return (_a = file === null || file === void 0 ? void 0 : file.replace(/\//g, '__')) === null || _a === void 0 ? void 0 : _a.replace(/:/g, '-'); };
90
+ const creds = await readData('creds.json') || (0, auth_utils_1.initAuthCreds)();
91
+ return {
92
+ state: {
93
+ creds,
94
+ keys: {
95
+ get: async (type, ids) => {
96
+ const data = {};
97
+ await Promise.all(ids.map(async (id) => {
98
+ let value = await readData(`${type}-${id}.json`);
99
+ if (type === 'app-state-sync-key' && value) {
100
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
101
+ }
102
+ data[id] = value;
103
+ }));
104
+ return data;
105
+ },
106
+ set: async (data) => {
107
+ const tasks = [];
108
+ for (const category in data) {
109
+ for (const id in data[category]) {
110
+ const value = data[category][id];
111
+ const file = `${category}-${id}.json`;
112
+ tasks.push(value ? writeData(value, file) : removeData(file));
113
+ }
114
+ }
115
+ await Promise.all(tasks);
116
+ }
117
+ }
118
+ },
119
+ saveCreds: async () => {
120
+ return writeData(creds, 'creds.json');
121
+ }
122
+ };
123
+ };
124
+ exports.useMultiFileAuthState = useMultiFileAuthState;