astrabail 1.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/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +5479 -0
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +89351 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +7 -0
  8. package/lib/Defaults/astrabail-version.json +8 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.js +166 -0
  11. package/lib/Defaults/phonenumber-mcc.json +223 -0
  12. package/lib/Defaults/update-wa-version.js +75 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  16. package/lib/Signal/Group/group-session-builder.js +66 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +85 -0
  19. package/lib/Signal/Group/index.d.ts +12 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  25. package/lib/Signal/Group/sender-chain-key.js +29 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  33. package/lib/Signal/Group/sender-key-record.js +44 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  35. package/lib/Signal/Group/sender-key-state.js +87 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +5 -0
  39. package/lib/Signal/libsignal.js +478 -0
  40. package/lib/Signal/lid-mapping.d.ts +19 -0
  41. package/lib/Signal/lid-mapping.js +274 -0
  42. package/lib/Socket/Client/index.d.ts +3 -0
  43. package/lib/Socket/Client/index.js +18 -0
  44. package/lib/Socket/Client/types.d.ts +16 -0
  45. package/lib/Socket/Client/types.js +14 -0
  46. package/lib/Socket/Client/websocket.d.ts +13 -0
  47. package/lib/Socket/Client/websocket.js +60 -0
  48. package/lib/Socket/business.d.ts +202 -0
  49. package/lib/Socket/business.js +382 -0
  50. package/lib/Socket/chats.d.ts +111 -0
  51. package/lib/Socket/chats.js +1155 -0
  52. package/lib/Socket/communities.d.ts +258 -0
  53. package/lib/Socket/communities.js +438 -0
  54. package/lib/Socket/community.js +333 -0
  55. package/lib/Socket/groups.d.ts +150 -0
  56. package/lib/Socket/groups.js +470 -0
  57. package/lib/Socket/index.d.ts +245 -0
  58. package/lib/Socket/index.js +13 -0
  59. package/lib/Socket/messages-recv.d.ts +187 -0
  60. package/lib/Socket/messages-recv.js +1708 -0
  61. package/lib/Socket/messages-send.d.ts +183 -0
  62. package/lib/Socket/messages-send.js +1692 -0
  63. package/lib/Socket/mex.d.ts +3 -0
  64. package/lib/Socket/mex.js +45 -0
  65. package/lib/Socket/newsletter.d.ts +160 -0
  66. package/lib/Socket/newsletter.js +293 -0
  67. package/lib/Socket/socket.d.ts +55 -0
  68. package/lib/Socket/socket.js +947 -0
  69. package/lib/Socket/usync.js +70 -0
  70. package/lib/Store/index.js +20 -0
  71. package/lib/Store/make-cache-manager-store.js +83 -0
  72. package/lib/Store/make-in-memory-store.js +398 -0
  73. package/lib/Store/make-ordered-dictionary.js +81 -0
  74. package/lib/Store/object-repository.js +27 -0
  75. package/lib/Types/Auth.d.ts +116 -0
  76. package/lib/Types/Auth.js +2 -0
  77. package/lib/Types/Bussines.d.ts +25 -0
  78. package/lib/Types/Bussines.js +2 -0
  79. package/lib/Types/Call.d.ts +15 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +123 -0
  82. package/lib/Types/Chat.js +10 -0
  83. package/lib/Types/Contact.d.ts +24 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +237 -0
  86. package/lib/Types/Events.js +3 -0
  87. package/lib/Types/GroupMetadata.d.ts +67 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +47 -0
  90. package/lib/Types/Label.js +25 -0
  91. package/lib/Types/LabelAssociation.d.ts +30 -0
  92. package/lib/Types/LabelAssociation.js +7 -0
  93. package/lib/Types/Message.d.ts +305 -0
  94. package/lib/Types/Message.js +11 -0
  95. package/lib/Types/MexUpdates.js +11 -0
  96. package/lib/Types/Newsletter.d.ts +135 -0
  97. package/lib/Types/Newsletter.js +43 -0
  98. package/lib/Types/Product.d.ts +79 -0
  99. package/lib/Types/Product.js +2 -0
  100. package/lib/Types/Signal.d.ts +76 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +133 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +39 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +65 -0
  109. package/lib/Types/index.js +42 -0
  110. package/lib/Utils/astrabail-event-stream.js +3 -0
  111. package/lib/Utils/audioToBuffer.js +31 -0
  112. package/lib/Utils/auth-utils.d.ts +19 -0
  113. package/lib/Utils/auth-utils.js +298 -0
  114. package/lib/Utils/baileys-event-stream.js +60 -0
  115. package/lib/Utils/bridge-runtime.d.ts +1 -0
  116. package/lib/Utils/bridge-runtime.js +14 -0
  117. package/lib/Utils/browser-utils.d.ts +4 -0
  118. package/lib/Utils/browser-utils.js +44 -0
  119. package/lib/Utils/business.d.ts +23 -0
  120. package/lib/Utils/business.js +240 -0
  121. package/lib/Utils/chat-utils.d.ts +70 -0
  122. package/lib/Utils/chat-utils.js +825 -0
  123. package/lib/Utils/crypto.d.ts +37 -0
  124. package/lib/Utils/crypto.js +168 -0
  125. package/lib/Utils/decode-wa-message.d.ts +48 -0
  126. package/lib/Utils/decode-wa-message.js +287 -0
  127. package/lib/Utils/event-buffer.d.ts +34 -0
  128. package/lib/Utils/event-buffer.js +580 -0
  129. package/lib/Utils/generics.d.ts +91 -0
  130. package/lib/Utils/generics.js +483 -0
  131. package/lib/Utils/history.d.ts +22 -0
  132. package/lib/Utils/history.js +137 -0
  133. package/lib/Utils/identity-change-handler.d.ts +37 -0
  134. package/lib/Utils/identity-change-handler.js +54 -0
  135. package/lib/Utils/index.d.ts +22 -0
  136. package/lib/Utils/index.js +48 -0
  137. package/lib/Utils/link-preview.d.ts +21 -0
  138. package/lib/Utils/link-preview.js +121 -0
  139. package/lib/Utils/logger.d.ts +13 -0
  140. package/lib/Utils/logger.js +7 -0
  141. package/lib/Utils/lt-hash.d.ts +8 -0
  142. package/lib/Utils/lt-hash.js +10 -0
  143. package/lib/Utils/make-mutex.d.ts +9 -0
  144. package/lib/Utils/make-mutex.js +37 -0
  145. package/lib/Utils/message-retry-manager.d.ts +110 -0
  146. package/lib/Utils/message-retry-manager.js +226 -0
  147. package/lib/Utils/messages-media.d.ts +130 -0
  148. package/lib/Utils/messages-media.js +887 -0
  149. package/lib/Utils/messages-newsletter.d.ts +84 -0
  150. package/lib/Utils/messages-newsletter.js +295 -0
  151. package/lib/Utils/messages.d.ts +92 -0
  152. package/lib/Utils/messages.js +1752 -0
  153. package/lib/Utils/noise-handler.d.ts +20 -0
  154. package/lib/Utils/noise-handler.js +204 -0
  155. package/lib/Utils/pre-key-manager.d.ts +28 -0
  156. package/lib/Utils/pre-key-manager.js +112 -0
  157. package/lib/Utils/process-message.d.ts +60 -0
  158. package/lib/Utils/process-message.js +536 -0
  159. package/lib/Utils/reporting-utils.d.ts +11 -0
  160. package/lib/Utils/reporting-utils.js +262 -0
  161. package/lib/Utils/resolve-jid.d.ts +43 -0
  162. package/lib/Utils/resolve-jid.js +95 -0
  163. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  164. package/lib/Utils/rust-bridge-shim.js +70 -0
  165. package/lib/Utils/serial-task-queue.js +29 -0
  166. package/lib/Utils/signal.d.ts +34 -0
  167. package/lib/Utils/signal.js +170 -0
  168. package/lib/Utils/streamToBuffer.js +17 -0
  169. package/lib/Utils/sync-action-utils.d.ts +19 -0
  170. package/lib/Utils/sync-action-utils.js +52 -0
  171. package/lib/Utils/tc-token-utils.d.ts +12 -0
  172. package/lib/Utils/tc-token-utils.js +20 -0
  173. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  174. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  175. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  176. package/lib/Utils/use-single-file-auth-state.js +73 -0
  177. package/lib/Utils/validate-connection.d.ts +11 -0
  178. package/lib/Utils/validate-connection.js +206 -0
  179. package/lib/WABinary/constants.d.ts +28 -0
  180. package/lib/WABinary/constants.js +1303 -0
  181. package/lib/WABinary/decode.d.ts +7 -0
  182. package/lib/WABinary/decode.js +300 -0
  183. package/lib/WABinary/encode.d.ts +3 -0
  184. package/lib/WABinary/encode.js +256 -0
  185. package/lib/WABinary/generic-utils.d.ts +15 -0
  186. package/lib/WABinary/generic-utils.js +138 -0
  187. package/lib/WABinary/index.d.ts +6 -0
  188. package/lib/WABinary/index.js +25 -0
  189. package/lib/WABinary/jid-utils.d.ts +48 -0
  190. package/lib/WABinary/jid-utils.js +115 -0
  191. package/lib/WABinary/types.d.ts +19 -0
  192. package/lib/WABinary/types.js +36 -0
  193. package/lib/WAM/BinaryInfo.d.ts +9 -0
  194. package/lib/WAM/BinaryInfo.js +13 -0
  195. package/lib/WAM/constants.d.ts +40 -0
  196. package/lib/WAM/constants.js +22855 -0
  197. package/lib/WAM/encode.d.ts +3 -0
  198. package/lib/WAM/encode.js +153 -0
  199. package/lib/WAM/index.d.ts +4 -0
  200. package/lib/WAM/index.js +19 -0
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  202. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  203. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  204. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  205. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  206. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  207. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  208. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +41 -0
  209. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  210. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +54 -0
  211. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  212. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +32 -0
  213. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  214. package/lib/WAUSync/Protocols/index.js +22 -0
  215. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  216. package/lib/WAUSync/USyncQuery.js +97 -0
  217. package/lib/WAUSync/USyncUser.d.ts +13 -0
  218. package/lib/WAUSync/USyncUser.js +26 -0
  219. package/lib/WAUSync/index.d.ts +4 -0
  220. package/lib/WAUSync/index.js +19 -0
  221. package/lib/index.d.ts +12 -0
  222. package/lib/index.js +124 -0
  223. package/package.json +120 -0
  224. package/readme.md +1956 -0
@@ -0,0 +1,170 @@
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 index_js_1 = require("../Defaults/index.js");
5
+ const index_js_2 = require("../WABinary/index.js");
6
+ const crypto_js_1 = require("./crypto.js");
7
+ const generics_js_1 = require("./generics.js");
8
+ function chunk(array, size) {
9
+ const chunks = [];
10
+ for (let i = 0; i < array.length; i += size) {
11
+ chunks.push(array.slice(i, i + size));
12
+ }
13
+ return chunks;
14
+ }
15
+ const createSignalIdentity = (wid, accountSignatureKey) => {
16
+ return {
17
+ identifier: { name: wid, deviceId: 0 },
18
+ identifierKey: (0, crypto_js_1.generateSignalPubKey)(accountSignatureKey)
19
+ };
20
+ };
21
+ exports.createSignalIdentity = createSignalIdentity;
22
+ const getPreKeys = async ({ get }, min, limit) => {
23
+ const idList = [];
24
+ for (let id = min; id < limit; id++) {
25
+ idList.push(id.toString());
26
+ }
27
+ return get('pre-key', idList);
28
+ };
29
+ exports.getPreKeys = getPreKeys;
30
+ const generateOrGetPreKeys = (creds, range) => {
31
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
32
+ const remaining = range - avaliable;
33
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
34
+ const newPreKeys = {};
35
+ if (remaining > 0) {
36
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
37
+ newPreKeys[i] = crypto_js_1.Curve.generateKeyPair();
38
+ }
39
+ }
40
+ return {
41
+ newPreKeys,
42
+ lastPreKeyId,
43
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
44
+ };
45
+ };
46
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
47
+ const xmppSignedPreKey = (key) => ({
48
+ tag: 'skey',
49
+ attrs: {},
50
+ content: [
51
+ { tag: 'id', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(key.keyId, 3) },
52
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
53
+ { tag: 'signature', attrs: {}, content: key.signature }
54
+ ]
55
+ });
56
+ exports.xmppSignedPreKey = xmppSignedPreKey;
57
+ const xmppPreKey = (pair, id) => ({
58
+ tag: 'key',
59
+ attrs: {},
60
+ content: [
61
+ { tag: 'id', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(id, 3) },
62
+ { tag: 'value', attrs: {}, content: pair.public }
63
+ ]
64
+ });
65
+ exports.xmppPreKey = xmppPreKey;
66
+ const parseAndInjectE2ESessions = async (node, repository) => {
67
+ const extractKey = (key) => key
68
+ ? {
69
+ keyId: (0, index_js_2.getBinaryNodeChildUInt)(key, 'id', 3),
70
+ publicKey: (0, crypto_js_1.generateSignalPubKey)((0, index_js_2.getBinaryNodeChildBuffer)(key, 'value')),
71
+ signature: (0, index_js_2.getBinaryNodeChildBuffer)(key, 'signature')
72
+ }
73
+ : undefined;
74
+ const nodes = (0, index_js_2.getBinaryNodeChildren)((0, index_js_2.getBinaryNodeChild)(node, 'list'), 'user');
75
+ for (const node of nodes) {
76
+ (0, index_js_2.assertNodeErrorFree)(node);
77
+ }
78
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
79
+ // So Promise.all doesn't really help here,
80
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
81
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
82
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
83
+ const chunkSize = 100;
84
+ const chunks = chunk(nodes, chunkSize);
85
+ for (const nodesChunk of chunks) {
86
+ for (const node of nodesChunk) {
87
+ const signedKey = (0, index_js_2.getBinaryNodeChild)(node, 'skey');
88
+ const key = (0, index_js_2.getBinaryNodeChild)(node, 'key');
89
+ const identity = (0, index_js_2.getBinaryNodeChildBuffer)(node, 'identity');
90
+ const jid = node.attrs.jid;
91
+ const registrationId = (0, index_js_2.getBinaryNodeChildUInt)(node, 'registration', 4);
92
+ await repository.injectE2ESession({
93
+ jid,
94
+ session: {
95
+ registrationId: registrationId,
96
+ identityKey: (0, crypto_js_1.generateSignalPubKey)(identity),
97
+ signedPreKey: extractKey(signedKey),
98
+ preKey: extractKey(key)
99
+ }
100
+ });
101
+ }
102
+ }
103
+ };
104
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
105
+ const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
106
+ const { user: myUser, device: myDevice } = (0, index_js_2.jidDecode)(myJid);
107
+ const extracted = [];
108
+ for (const userResult of result) {
109
+ const { devices, id } = userResult;
110
+ const decoded = (0, index_js_2.jidDecode)(id), { user, server } = decoded;
111
+ let { domainType } = decoded;
112
+ const deviceList = devices?.deviceList;
113
+ if (!Array.isArray(deviceList))
114
+ continue;
115
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
116
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
117
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
118
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
119
+ ) {
120
+ if (isHosted) {
121
+ domainType = domainType === index_js_2.WAJIDDomains.LID ? index_js_2.WAJIDDomains.HOSTED_LID : index_js_2.WAJIDDomains.HOSTED;
122
+ }
123
+ extracted.push({
124
+ user,
125
+ device,
126
+ domainType,
127
+ server: (0, index_js_2.getServerFromDomainType)(server, domainType)
128
+ });
129
+ }
130
+ }
131
+ }
132
+ return extracted;
133
+ };
134
+ exports.extractDeviceJids = extractDeviceJids;
135
+ /**
136
+ * get the next N keys for upload or processing
137
+ * @param count number of pre-keys to get or generate
138
+ */
139
+ const getNextPreKeys = async ({ creds, keys }, count) => {
140
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
141
+ const update = {
142
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
143
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
144
+ };
145
+ await keys.set({ 'pre-key': newPreKeys });
146
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
147
+ return { update, preKeys };
148
+ };
149
+ exports.getNextPreKeys = getNextPreKeys;
150
+ const getNextPreKeysNode = async (state, count) => {
151
+ const { creds } = state;
152
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
153
+ const node = {
154
+ tag: 'iq',
155
+ attrs: {
156
+ xmlns: 'encrypt',
157
+ type: 'set',
158
+ to: index_js_2.S_WHATSAPP_NET
159
+ },
160
+ content: [
161
+ { tag: 'registration', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(creds.registrationId) },
162
+ { tag: 'type', attrs: {}, content: index_js_1.KEY_BUNDLE_TYPE },
163
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
164
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
165
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
166
+ ]
167
+ };
168
+ return { update, node };
169
+ };
170
+ exports.getNextPreKeysNode = getNextPreKeysNode;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.streamToBuffer = streamToBuffer;
4
+ const stream_1 = require("stream");
5
+ /**
6
+ * Mengonversi Node.js Readable Stream menjadi Buffer.
7
+ * @param {Readable} stream Aliran data yang dapat dibaca.
8
+ * @returns {Promise<Buffer>} Promise yang diselesaikan dengan Buffer berisi semua data dari aliran.
9
+ */
10
+ async function streamToBuffer(stream) {
11
+ const chunks = [];
12
+ return new Promise((resolve, reject) => {
13
+ stream.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
14
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
15
+ stream.on('error', reject);
16
+ });
17
+ }
@@ -0,0 +1,19 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { BaileysEventEmitter, BaileysEventMap, Contact } from '../Types/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export type ContactsUpsertResult = {
5
+ event: 'contacts.upsert';
6
+ data: Contact[];
7
+ };
8
+ export type LidMappingUpdateResult = {
9
+ event: 'lid-mapping.update';
10
+ data: BaileysEventMap['lid-mapping.update'];
11
+ };
12
+ export type SyncActionResult = ContactsUpsertResult | LidMappingUpdateResult;
13
+ /**
14
+ * Process contactAction and return events to emit.
15
+ * Pure function - no side effects.
16
+ */
17
+ export declare const processContactAction: (action: proto.SyncActionValue.IContactAction, id: string | undefined, logger?: ILogger) => SyncActionResult[];
18
+ export declare const emitSyncActionResults: (ev: BaileysEventEmitter, results: SyncActionResult[]) => void;
19
+ //# sourceMappingURL=sync-action-utils.d.ts.map
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.emitSyncActionResults = exports.processContactAction = void 0;
4
+ const index_js_1 = require("../../WAProto/index.js");
5
+ const index_js_2 = require("../WABinary/index.js");
6
+ /**
7
+ * Process contactAction and return events to emit.
8
+ * Pure function - no side effects.
9
+ */
10
+ const processContactAction = (action, id, logger) => {
11
+ const results = [];
12
+ if (!id) {
13
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
14
+ return results;
15
+ }
16
+ const lidJid = action.lidJid;
17
+ const idIsPn = (0, index_js_2.isPnUser)(id);
18
+ // PN is in index[1], not in contactAction.pnJid which is usually null
19
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
20
+ // Always emit contacts.upsert
21
+ results.push({
22
+ event: 'contacts.upsert',
23
+ data: [
24
+ {
25
+ id,
26
+ name: action.fullName || action.firstName || action.username || undefined,
27
+ lid: lidJid || undefined,
28
+ phoneNumber
29
+ }
30
+ ]
31
+ });
32
+ // Emit lid-mapping.update if we have valid LID-PN pair
33
+ if (lidJid && (0, index_js_2.isLidUser)(lidJid) && idIsPn) {
34
+ results.push({
35
+ event: 'lid-mapping.update',
36
+ data: { lid: lidJid, pn: id }
37
+ });
38
+ }
39
+ return results;
40
+ };
41
+ exports.processContactAction = processContactAction;
42
+ const emitSyncActionResults = (ev, results) => {
43
+ for (const result of results) {
44
+ if (result.event === 'contacts.upsert') {
45
+ ev.emit('contacts.upsert', result.data);
46
+ }
47
+ else {
48
+ ev.emit('lid-mapping.update', result.data);
49
+ }
50
+ }
51
+ };
52
+ exports.emitSyncActionResults = emitSyncActionResults;
@@ -0,0 +1,12 @@
1
+ import type { SignalKeyStoreWithTransaction } from '../Types/index.js';
2
+ import type { BinaryNode } from '../WABinary/index.js';
3
+ type TcTokenParams = {
4
+ jid: string;
5
+ baseContent?: BinaryNode[];
6
+ authState: {
7
+ keys: SignalKeyStoreWithTransaction;
8
+ };
9
+ };
10
+ export declare function buildTcTokenFromJid({ authState, jid, baseContent }: TcTokenParams): Promise<BinaryNode[] | undefined>;
11
+ export {};
12
+ //# sourceMappingURL=tc-token-utils.d.ts.map
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildTcTokenFromJid = buildTcTokenFromJid;
4
+ async function buildTcTokenFromJid({ authState, jid, baseContent = [] }) {
5
+ try {
6
+ const tcTokenData = await authState.keys.get('tctoken', [jid]);
7
+ const tcTokenBuffer = tcTokenData?.[jid]?.token;
8
+ if (!tcTokenBuffer)
9
+ return baseContent.length > 0 ? baseContent : undefined;
10
+ baseContent.push({
11
+ tag: 'tctoken',
12
+ attrs: {},
13
+ content: tcTokenBuffer
14
+ });
15
+ return baseContent;
16
+ }
17
+ catch (error) {
18
+ return baseContent.length > 0 ? baseContent : undefined;
19
+ }
20
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useMongoFileAuthState = void 0;
4
+ const index_js_1 = require("../../WAProto/index.js");
5
+ const auth_utils_js_1 = require("./auth-utils.js");
6
+ const generics_js_1 = require("./generics.js");
7
+ /*
8
+ code from amiruldev readjusted by @irull2nd, don't delete WM!
9
+ */
10
+ const useMongoFileAuthState = async (collection) => {
11
+ const writeData = (data, id) => {
12
+ const informationToStore = JSON.parse(JSON.stringify(data, generics_js_1.BufferJSON.replacer));
13
+ const update = {
14
+ $set: {
15
+ ...informationToStore,
16
+ },
17
+ };
18
+ return collection.updateOne({ _id: id }, update, { upsert: true });
19
+ };
20
+ const readData = async (id) => {
21
+ try {
22
+ const data = JSON.stringify(await collection.findOne({ _id: id }));
23
+ return JSON.parse(data, generics_js_1.BufferJSON.reviver);
24
+ }
25
+ catch (err) {
26
+ console.log(err);
27
+ }
28
+ };
29
+ const removeData = async (id) => {
30
+ try {
31
+ await collection.deleteOne({ _id: id });
32
+ }
33
+ catch (err) {
34
+ console.log('error', err);
35
+ }
36
+ };
37
+ const creds = (await readData('creds')) || (0, auth_utils_js_1.initAuthCreds)();
38
+ return {
39
+ state: {
40
+ creds,
41
+ keys: {
42
+ get: async (type, ids) => {
43
+ const data = {};
44
+ await Promise.all(ids.map(async (id) => {
45
+ let value = await readData(`${type}-${id}`);
46
+ if (type === 'app-state-sync-key') {
47
+ value = index_js_1.proto.Message.AppStateSyncKeyData.fromObject(data);
48
+ }
49
+ data[id] = value;
50
+ }));
51
+ return data;
52
+ },
53
+ set: async (data) => {
54
+ const tasks = [];
55
+ for (const category of Object.keys(data)) {
56
+ for (const id of Object.keys(data[category])) {
57
+ const value = data[category][id];
58
+ const key = `${category}-${id}`;
59
+ tasks.push(value ? writeData(value, key) : removeData(key));
60
+ }
61
+ }
62
+ await Promise.all(tasks);
63
+ },
64
+ },
65
+ },
66
+ saveCreds: () => {
67
+ return writeData(creds, 'creds');
68
+ }
69
+ };
70
+ };
71
+ exports.useMongoFileAuthState = useMongoFileAuthState;
@@ -0,0 +1,13 @@
1
+ import type { AuthenticationState } from '../Types/index.js';
2
+ /**
3
+ * stores the full authentication state in a single folder.
4
+ * Far more efficient than singlefileauthstate
5
+ *
6
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
7
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
8
+ * */
9
+ export declare const useMultiFileAuthState: (folder: string) => Promise<{
10
+ state: AuthenticationState;
11
+ saveCreds: () => Promise<void>;
12
+ }>;
13
+ //# sourceMappingURL=use-multi-file-auth-state.d.ts.map
@@ -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 index_js_1 = require("../../WAProto/index.js");
8
+ const auth_utils_js_1 = require("./auth-utils.js");
9
+ const generics_js_1 = require("./generics.js");
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/Baileys/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
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const writeData = async (data, file) => {
34
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
35
+ const mutex = getFileLock(filePath);
36
+ return mutex.acquire().then(async (release) => {
37
+ try {
38
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_js_1.BufferJSON.replacer));
39
+ }
40
+ finally {
41
+ release();
42
+ }
43
+ });
44
+ };
45
+ const readData = async (file) => {
46
+ try {
47
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
48
+ const mutex = getFileLock(filePath);
49
+ return await mutex.acquire().then(async (release) => {
50
+ try {
51
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
52
+ return JSON.parse(data, generics_js_1.BufferJSON.reviver);
53
+ }
54
+ finally {
55
+ release();
56
+ }
57
+ });
58
+ }
59
+ catch (error) {
60
+ return null;
61
+ }
62
+ };
63
+ const removeData = async (file) => {
64
+ try {
65
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
66
+ const mutex = getFileLock(filePath);
67
+ return mutex.acquire().then(async (release) => {
68
+ try {
69
+ await (0, promises_1.unlink)(filePath);
70
+ }
71
+ catch {
72
+ }
73
+ finally {
74
+ release();
75
+ }
76
+ });
77
+ }
78
+ catch { }
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) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
90
+ const creds = (await readData('creds.json')) || (0, auth_utils_js_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 = index_js_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;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useSingleFileAuthState = void 0;
4
+ const index_js_1 = require("../../WAProto/index.js");
5
+ const auth_utils_js_1 = require("./auth-utils.js");
6
+ const generics_js_1 = require("./generics.js");
7
+ // useless key map only there to maintain backwards compatibility
8
+ // do not use in your own systems please
9
+ const KEY_MAP = {
10
+ 'pre-key': 'preKeys',
11
+ 'session': 'sessions',
12
+ 'sender-key': 'senderKeys',
13
+ 'app-state-sync-key': 'appStateSyncKeys',
14
+ 'app-state-sync-version': 'appStateVersions',
15
+ 'sender-key-memory': 'senderKeyMemory'
16
+ };
17
+ /**
18
+ * @deprecated use multi file auth state instead please
19
+ * stores the full authentication state in a single JSON file
20
+ *
21
+ * DO NOT USE IN A PROD ENVIRONMENT, only meant to serve as an example
22
+ * */
23
+ const useSingleFileAuthState = (filename, logger) => {
24
+ const { readFileSync, writeFileSync, existsSync } = require('fs');
25
+ let creds;
26
+ let keys = {};
27
+ // save the authentication state to a file
28
+ const saveState = () => {
29
+ logger && logger.trace('saving auth state');
30
+ writeFileSync(filename,
31
+ // BufferJSON replacer utility saves buffers nicely
32
+ JSON.stringify({ creds, keys }, generics_js_1.BufferJSON.replacer, 2));
33
+ };
34
+ if (existsSync(filename)) {
35
+ const result = JSON.parse(readFileSync(filename, { encoding: 'utf-8' }), generics_js_1.BufferJSON.reviver);
36
+ creds = result.creds;
37
+ keys = result.keys;
38
+ }
39
+ else {
40
+ creds = (0, auth_utils_js_1.initAuthCreds)();
41
+ keys = {};
42
+ }
43
+ return {
44
+ state: {
45
+ creds,
46
+ keys: {
47
+ get: (type, ids) => {
48
+ const key = KEY_MAP[type];
49
+ return ids.reduce((dict, id) => {
50
+ let value = keys[key]?.[id];
51
+ if (value) {
52
+ if (type === 'app-state-sync-key') {
53
+ value = index_js_1.proto.Message.AppStateSyncKeyData.fromObject(value);
54
+ }
55
+ dict[id] = value;
56
+ }
57
+ return dict;
58
+ }, {});
59
+ },
60
+ set: (data) => {
61
+ for (const _key in data) {
62
+ const key = KEY_MAP[_key];
63
+ keys[key] = keys[key] || {};
64
+ Object.assign(keys[key], data[_key]);
65
+ }
66
+ saveState();
67
+ }
68
+ }
69
+ },
70
+ saveState
71
+ };
72
+ };
73
+ exports.useSingleFileAuthState = useSingleFileAuthState;
@@ -0,0 +1,11 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types/index.js';
3
+ import { type BinaryNode } from '../WABinary/index.js';
4
+ export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload;
5
+ export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload;
6
+ export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, "advSecretKey" | "signedIdentityKey" | "signalIdentities">) => {
7
+ creds: Partial<AuthenticationCreds>;
8
+ reply: BinaryNode;
9
+ };
10
+ export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array<ArrayBufferLike>;
11
+ //# sourceMappingURL=validate-connection.d.ts.map