@nexustechpro/baileys 2.0.2 → 2.0.5

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 (102) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +924 -1299
  3. package/lib/Defaults/baileys-version.json +6 -2
  4. package/lib/Defaults/index.js +172 -172
  5. package/lib/Signal/libsignal.js +380 -292
  6. package/lib/Signal/lid-mapping.js +264 -171
  7. package/lib/Socket/Client/index.js +2 -2
  8. package/lib/Socket/Client/types.js +10 -10
  9. package/lib/Socket/Client/websocket.js +45 -310
  10. package/lib/Socket/business.js +375 -375
  11. package/lib/Socket/chats.js +909 -963
  12. package/lib/Socket/communities.js +430 -430
  13. package/lib/Socket/groups.js +342 -342
  14. package/lib/Socket/index.js +22 -22
  15. package/lib/Socket/messages-recv.js +777 -743
  16. package/lib/Socket/messages-send.js +295 -305
  17. package/lib/Socket/mex.js +50 -50
  18. package/lib/Socket/newsletter.js +148 -148
  19. package/lib/Socket/nexus-handler.js +75 -261
  20. package/lib/Socket/socket.js +709 -1201
  21. package/lib/Store/index.js +5 -5
  22. package/lib/Store/make-cache-manager-store.js +81 -81
  23. package/lib/Store/make-in-memory-store.js +416 -416
  24. package/lib/Store/make-ordered-dictionary.js +81 -81
  25. package/lib/Store/object-repository.js +30 -30
  26. package/lib/Types/Auth.js +1 -1
  27. package/lib/Types/Bussines.js +1 -1
  28. package/lib/Types/Call.js +1 -1
  29. package/lib/Types/Chat.js +7 -7
  30. package/lib/Types/Contact.js +1 -1
  31. package/lib/Types/Events.js +1 -1
  32. package/lib/Types/GroupMetadata.js +1 -1
  33. package/lib/Types/Label.js +24 -24
  34. package/lib/Types/LabelAssociation.js +6 -6
  35. package/lib/Types/Message.js +10 -10
  36. package/lib/Types/Newsletter.js +28 -28
  37. package/lib/Types/Product.js +1 -1
  38. package/lib/Types/Signal.js +1 -1
  39. package/lib/Types/Socket.js +2 -2
  40. package/lib/Types/State.js +12 -12
  41. package/lib/Types/USync.js +1 -1
  42. package/lib/Types/index.js +25 -25
  43. package/lib/Utils/auth-utils.js +264 -256
  44. package/lib/Utils/baileys-event-stream.js +55 -55
  45. package/lib/Utils/browser-utils.js +27 -27
  46. package/lib/Utils/business.js +228 -230
  47. package/lib/Utils/chat-utils.js +694 -764
  48. package/lib/Utils/crypto.js +109 -135
  49. package/lib/Utils/decode-wa-message.js +310 -314
  50. package/lib/Utils/event-buffer.js +547 -547
  51. package/lib/Utils/generics.js +297 -297
  52. package/lib/Utils/history.js +91 -83
  53. package/lib/Utils/index.js +21 -20
  54. package/lib/Utils/key-store.js +17 -0
  55. package/lib/Utils/link-preview.js +97 -98
  56. package/lib/Utils/logger.js +2 -2
  57. package/lib/Utils/lt-hash.js +47 -47
  58. package/lib/Utils/make-mutex.js +39 -39
  59. package/lib/Utils/message-retry-manager.js +148 -148
  60. package/lib/Utils/messages-media.js +534 -534
  61. package/lib/Utils/messages.js +705 -705
  62. package/lib/Utils/noise-handler.js +255 -255
  63. package/lib/Utils/pre-key-manager.js +105 -105
  64. package/lib/Utils/process-message.js +412 -412
  65. package/lib/Utils/signal.js +160 -158
  66. package/lib/Utils/use-multi-file-auth-state.js +120 -120
  67. package/lib/Utils/validate-connection.js +194 -194
  68. package/lib/WABinary/constants.js +1300 -1300
  69. package/lib/WABinary/decode.js +237 -237
  70. package/lib/WABinary/encode.js +232 -232
  71. package/lib/WABinary/generic-utils.js +252 -211
  72. package/lib/WABinary/index.js +5 -5
  73. package/lib/WABinary/jid-utils.js +279 -95
  74. package/lib/WABinary/types.js +1 -1
  75. package/lib/WAM/BinaryInfo.js +9 -9
  76. package/lib/WAM/constants.js +22852 -22852
  77. package/lib/WAM/encode.js +149 -149
  78. package/lib/WAM/index.js +3 -3
  79. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -28
  80. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -53
  81. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -26
  82. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -37
  83. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  84. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -28
  85. package/lib/WAUSync/Protocols/index.js +4 -4
  86. package/lib/WAUSync/USyncQuery.js +93 -93
  87. package/lib/WAUSync/USyncUser.js +22 -22
  88. package/lib/WAUSync/index.js +3 -3
  89. package/lib/index.js +66 -66
  90. package/package.json +171 -144
  91. package/lib/Signal/Group/ciphertext-message.js +0 -12
  92. package/lib/Signal/Group/group-session-builder.js +0 -30
  93. package/lib/Signal/Group/group_cipher.js +0 -100
  94. package/lib/Signal/Group/index.js +0 -12
  95. package/lib/Signal/Group/keyhelper.js +0 -18
  96. package/lib/Signal/Group/sender-chain-key.js +0 -26
  97. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  98. package/lib/Signal/Group/sender-key-message.js +0 -66
  99. package/lib/Signal/Group/sender-key-name.js +0 -48
  100. package/lib/Signal/Group/sender-key-record.js +0 -41
  101. package/lib/Signal/Group/sender-key-state.js +0 -84
  102. package/lib/Signal/Group/sender-message-key.js +0 -26
@@ -1,159 +1,161 @@
1
- import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
2
- import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from '../WABinary/index.js';
3
- import { Curve, generateSignalPubKey } from './crypto.js';
4
- import { encodeBigEndian } from './generics.js';
5
- function chunk(array, size) {
6
- const chunks = [];
7
- for (let i = 0; i < array.length; i += size) {
8
- chunks.push(array.slice(i, i + size));
9
- }
10
- return chunks;
11
- }
12
- export const createSignalIdentity = (wid, accountSignatureKey) => {
13
- return {
14
- identifier: { name: wid, deviceId: 0 },
15
- identifierKey: generateSignalPubKey(accountSignatureKey)
16
- };
17
- };
18
- export const getPreKeys = async ({ get }, min, limit) => {
19
- const idList = [];
20
- for (let id = min; id < limit; id++) {
21
- idList.push(id.toString());
22
- }
23
- return get('pre-key', idList);
24
- };
25
- export const generateOrGetPreKeys = (creds, range) => {
26
- const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
27
- const remaining = range - avaliable;
28
- const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
29
- const newPreKeys = {};
30
- if (remaining > 0) {
31
- for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
32
- newPreKeys[i] = Curve.generateKeyPair();
33
- }
34
- }
35
- return {
36
- newPreKeys,
37
- lastPreKeyId,
38
- preKeysRange: [creds.firstUnuploadedPreKeyId, range]
39
- };
40
- };
41
- export const xmppSignedPreKey = (key) => ({
42
- tag: 'skey',
43
- attrs: {},
44
- content: [
45
- { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
46
- { tag: 'value', attrs: {}, content: key.keyPair.public },
47
- { tag: 'signature', attrs: {}, content: key.signature }
48
- ]
49
- });
50
- export const xmppPreKey = (pair, id) => ({
51
- tag: 'key',
52
- attrs: {},
53
- content: [
54
- { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
55
- { tag: 'value', attrs: {}, content: pair.public }
56
- ]
57
- });
58
- export const parseAndInjectE2ESessions = async (node, repository) => {
59
- const extractKey = (key) => key
60
- ? {
61
- keyId: getBinaryNodeChildUInt(key, 'id', 3),
62
- publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
63
- signature: getBinaryNodeChildBuffer(key, 'signature')
64
- }
65
- : undefined;
66
- const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user');
67
- for (const node of nodes) {
68
- 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 = chunk(nodes, chunkSize);
77
- for (const nodesChunk of chunks) {
78
- for (const node of nodesChunk) {
79
- const signedKey = getBinaryNodeChild(node, 'skey');
80
- const key = getBinaryNodeChild(node, 'key');
81
- const identity = getBinaryNodeChildBuffer(node, 'identity');
82
- const jid = node.attrs.jid;
83
- const registrationId = getBinaryNodeChildUInt(node, 'registration', 4);
84
- await repository.injectE2ESession({
85
- jid,
86
- session: {
87
- registrationId: registrationId,
88
- identityKey: generateSignalPubKey(identity),
89
- signedPreKey: extractKey(signedKey),
90
- preKey: extractKey(key)
91
- }
92
- });
93
- }
94
- }
95
- };
96
- export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
97
- const { user: myUser, device: myDevice } = jidDecode(myJid);
98
- const extracted = [];
99
- for (const userResult of result) {
100
- const { devices, id } = userResult;
101
- const decoded = jidDecode(id), { user, server } = decoded;
102
- let { domainType } = decoded;
103
- const deviceList = devices?.deviceList;
104
- if (!Array.isArray(deviceList))
105
- continue;
106
- for (const { id: device, keyIndex, isHosted } of deviceList) {
107
- if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
108
- ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
109
- (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
110
- ) {
111
- if (isHosted) {
112
- domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
113
- }
114
- extracted.push({
115
- user,
116
- device,
117
- domainType,
118
- server: getServerFromDomainType(server, domainType)
119
- });
120
- }
121
- }
122
- }
123
- return extracted;
124
- };
125
- /**
126
- * get the next N keys for upload or processing
127
- * @param count number of pre-keys to get or generate
128
- */
129
- export const getNextPreKeys = async ({ creds, keys }, count) => {
130
- const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
131
- const update = {
132
- nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
133
- firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
134
- };
135
- await keys.set({ 'pre-key': newPreKeys });
136
- const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
137
- return { update, preKeys };
138
- };
139
- export const getNextPreKeysNode = async (state, count) => {
140
- const { creds } = state;
141
- const { update, preKeys } = await getNextPreKeys(state, count);
142
- const node = {
143
- tag: 'iq',
144
- attrs: {
145
- xmlns: 'encrypt',
146
- type: 'set',
147
- to: S_WHATSAPP_NET
148
- },
149
- content: [
150
- { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
151
- { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
152
- { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
153
- { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
154
- xmppSignedPreKey(creds.signedPreKey)
155
- ]
156
- };
157
- return { update, node };
158
- };
1
+ import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
2
+ import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from '../WABinary/index.js';
3
+ import { Curve, generateSignalPubKey } from './crypto.js';
4
+ import { encodeBigEndian } from './generics.js';
5
+ function chunk(array, size) {
6
+ const chunks = [];
7
+ for (let i = 0; i < array.length; i += size) {
8
+ chunks.push(array.slice(i, i + size));
9
+ }
10
+ return chunks;
11
+ }
12
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
13
+ return {
14
+ identifier: { name: wid, deviceId: 0 },
15
+ identifierKey: generateSignalPubKey(accountSignatureKey)
16
+ };
17
+ };
18
+ export const getPreKeys = async ({ get }, min, limit) => {
19
+ const idList = [];
20
+ for (let id = min; id < limit; id++) {
21
+ idList.push(id.toString());
22
+ }
23
+ return get('pre-key', idList);
24
+ };
25
+ export const generateOrGetPreKeys = (creds, range) => {
26
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
27
+ const remaining = range - avaliable;
28
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
29
+ const newPreKeys = {};
30
+ if (remaining > 0) {
31
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
32
+ newPreKeys[i] = Curve.generateKeyPair();
33
+ }
34
+ }
35
+ return {
36
+ newPreKeys,
37
+ lastPreKeyId,
38
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
39
+ };
40
+ };
41
+ export const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ export const xmppPreKey = (pair, id) => ({
51
+ tag: 'key',
52
+ attrs: {},
53
+ content: [
54
+ { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
55
+ { tag: 'value', attrs: {}, content: pair.public }
56
+ ]
57
+ });
58
+ export const parseAndInjectE2ESessions = async (node, repository) => {
59
+ const extractKey = (key) => key
60
+ ? {
61
+ keyId: getBinaryNodeChildUInt(key, 'id', 3),
62
+ publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
63
+ signature: getBinaryNodeChildBuffer(key, 'signature')
64
+ }
65
+ : undefined;
66
+ const allNodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user')
67
+ // Filter out error nodes individually instead of aborting everything
68
+ const nodes = allNodes.filter(node => {
69
+ try { assertNodeErrorFree(node); return true }
70
+ catch { return false }
71
+ })
72
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
73
+ // So Promise.all doesn't really help here,
74
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
75
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
76
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
77
+ const chunkSize = 100;
78
+ const chunks = chunk(nodes, chunkSize);
79
+ for (const nodesChunk of chunks) {
80
+ for (const node of nodesChunk) {
81
+ const signedKey = getBinaryNodeChild(node, 'skey');
82
+ const key = getBinaryNodeChild(node, 'key');
83
+ const identity = getBinaryNodeChildBuffer(node, 'identity');
84
+ const jid = node.attrs.jid;
85
+ const registrationId = getBinaryNodeChildUInt(node, 'registration', 4);
86
+ await repository.injectE2ESession({
87
+ jid,
88
+ session: {
89
+ registrationId: registrationId,
90
+ identityKey: generateSignalPubKey(identity),
91
+ signedPreKey: extractKey(signedKey),
92
+ preKey: extractKey(key)
93
+ }
94
+ });
95
+ }
96
+ }
97
+ };
98
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
99
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
100
+ const extracted = [];
101
+ for (const userResult of result) {
102
+ const { devices, id } = userResult;
103
+ const decoded = jidDecode(id), { user, server } = decoded;
104
+ let { domainType } = decoded;
105
+ const deviceList = devices?.deviceList;
106
+ if (!Array.isArray(deviceList))
107
+ continue;
108
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
109
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
110
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
111
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
112
+ ) {
113
+ if (isHosted) {
114
+ domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
115
+ }
116
+ extracted.push({
117
+ user,
118
+ device,
119
+ domainType,
120
+ server: getServerFromDomainType(server, domainType)
121
+ });
122
+ }
123
+ }
124
+ }
125
+ return extracted;
126
+ };
127
+ /**
128
+ * get the next N keys for upload or processing
129
+ * @param count number of pre-keys to get or generate
130
+ */
131
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
132
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
133
+ const update = {
134
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
135
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
136
+ };
137
+ await keys.set({ 'pre-key': newPreKeys });
138
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
139
+ return { update, preKeys };
140
+ };
141
+ export const getNextPreKeysNode = async (state, count) => {
142
+ const { creds } = state;
143
+ const { update, preKeys } = await getNextPreKeys(state, count);
144
+ const node = {
145
+ tag: 'iq',
146
+ attrs: {
147
+ xmlns: 'encrypt',
148
+ type: 'set',
149
+ to: S_WHATSAPP_NET
150
+ },
151
+ content: [
152
+ { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
153
+ { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
154
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
155
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
156
+ xmppSignedPreKey(creds.signedPreKey)
157
+ ]
158
+ };
159
+ return { update, node };
160
+ };
159
161
  //# sourceMappingURL=signal.js.map
@@ -1,121 +1,121 @@
1
- import { Mutex } from 'async-mutex';
2
- import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
- import { join } from 'path';
4
- import { proto } from '../../WAProto/index.js';
5
- import { initAuthCreds } from './auth-utils.js';
6
- import { BufferJSON } from './generics.js';
7
- // We need to lock files due to the fact that we are using async functions to read and write files
8
- // https://github.com/WhiskeySockets/Baileys/issues/794
9
- // https://github.com/nodejs/node/issues/26338
10
- // Use a Map to store mutexes for each file path
11
- const fileLocks = new Map();
12
- // Get or create a mutex for a specific file path
13
- const getFileLock = (path) => {
14
- let mutex = fileLocks.get(path);
15
- if (!mutex) {
16
- mutex = new Mutex();
17
- fileLocks.set(path, mutex);
18
- }
19
- return mutex;
20
- };
21
- /**
22
- * stores the full authentication state in a single folder.
23
- * Far more efficient than singlefileauthstate
24
- *
25
- * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
- * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
- * */
28
- export const useMultiFileAuthState = async (folder) => {
29
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
- const writeData = async (data, file) => {
31
- const filePath = join(folder, fixFileName(file));
32
- const mutex = getFileLock(filePath);
33
- return mutex.acquire().then(async (release) => {
34
- try {
35
- await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
36
- }
37
- finally {
38
- release();
39
- }
40
- });
41
- };
42
- const readData = async (file) => {
43
- try {
44
- const filePath = join(folder, fixFileName(file));
45
- const mutex = getFileLock(filePath);
46
- return await mutex.acquire().then(async (release) => {
47
- try {
48
- const data = await readFile(filePath, { encoding: 'utf-8' });
49
- return JSON.parse(data, BufferJSON.reviver);
50
- }
51
- finally {
52
- release();
53
- }
54
- });
55
- }
56
- catch (error) {
57
- return null;
58
- }
59
- };
60
- const removeData = async (file) => {
61
- try {
62
- const filePath = join(folder, fixFileName(file));
63
- const mutex = getFileLock(filePath);
64
- return mutex.acquire().then(async (release) => {
65
- try {
66
- await unlink(filePath);
67
- }
68
- catch {
69
- }
70
- finally {
71
- release();
72
- }
73
- });
74
- }
75
- catch { }
76
- };
77
- const folderInfo = await stat(folder).catch(() => { });
78
- if (folderInfo) {
79
- if (!folderInfo.isDirectory()) {
80
- throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
81
- }
82
- }
83
- else {
84
- await mkdir(folder, { recursive: true });
85
- }
86
- const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
87
- const creds = (await readData('creds.json')) || initAuthCreds();
88
- return {
89
- state: {
90
- creds,
91
- keys: {
92
- get: async (type, ids) => {
93
- const data = {};
94
- await Promise.all(ids.map(async (id) => {
95
- let value = await readData(`${type}-${id}.json`);
96
- if (type === 'app-state-sync-key' && value) {
97
- value = proto.Message.AppStateSyncKeyData.fromObject(value);
98
- }
99
- data[id] = value;
100
- }));
101
- return data;
102
- },
103
- set: async (data) => {
104
- const tasks = [];
105
- for (const category in data) {
106
- for (const id in data[category]) {
107
- const value = data[category][id];
108
- const file = `${category}-${id}.json`;
109
- tasks.push(value ? writeData(value, file) : removeData(file));
110
- }
111
- }
112
- await Promise.all(tasks);
113
- }
114
- }
115
- },
116
- saveCreds: async () => {
117
- return writeData(creds, 'creds.json');
118
- }
119
- };
120
- };
1
+ import { Mutex } from 'async-mutex';
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { initAuthCreds } from './auth-utils.js';
6
+ import { BufferJSON } from './generics.js';
7
+ // We need to lock files due to the fact that we are using async functions to read and write files
8
+ // https://github.com/WhiskeySockets/Baileys/issues/794
9
+ // https://github.com/nodejs/node/issues/26338
10
+ // Use a Map to store mutexes for each file path
11
+ const fileLocks = new Map();
12
+ // Get or create a mutex for a specific file path
13
+ const getFileLock = (path) => {
14
+ let mutex = fileLocks.get(path);
15
+ if (!mutex) {
16
+ mutex = new Mutex();
17
+ fileLocks.set(path, mutex);
18
+ }
19
+ return mutex;
20
+ };
21
+ /**
22
+ * stores the full authentication state in a single folder.
23
+ * Far more efficient than singlefileauthstate
24
+ *
25
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
+ * */
28
+ export const useMultiFileAuthState = async (folder) => {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ const writeData = async (data, file) => {
31
+ const filePath = join(folder, fixFileName(file));
32
+ const mutex = getFileLock(filePath);
33
+ return mutex.acquire().then(async (release) => {
34
+ try {
35
+ await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
36
+ }
37
+ finally {
38
+ release();
39
+ }
40
+ });
41
+ };
42
+ const readData = async (file) => {
43
+ try {
44
+ const filePath = join(folder, fixFileName(file));
45
+ const mutex = getFileLock(filePath);
46
+ return await mutex.acquire().then(async (release) => {
47
+ try {
48
+ const data = await readFile(filePath, { encoding: 'utf-8' });
49
+ return JSON.parse(data, BufferJSON.reviver);
50
+ }
51
+ finally {
52
+ release();
53
+ }
54
+ });
55
+ }
56
+ catch (error) {
57
+ return null;
58
+ }
59
+ };
60
+ const removeData = async (file) => {
61
+ try {
62
+ const filePath = join(folder, fixFileName(file));
63
+ const mutex = getFileLock(filePath);
64
+ return mutex.acquire().then(async (release) => {
65
+ try {
66
+ await unlink(filePath);
67
+ }
68
+ catch {
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ });
74
+ }
75
+ catch { }
76
+ };
77
+ const folderInfo = await stat(folder).catch(() => { });
78
+ if (folderInfo) {
79
+ if (!folderInfo.isDirectory()) {
80
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
81
+ }
82
+ }
83
+ else {
84
+ await mkdir(folder, { recursive: true });
85
+ }
86
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
87
+ const creds = (await readData('creds.json')) || initAuthCreds();
88
+ return {
89
+ state: {
90
+ creds,
91
+ keys: {
92
+ get: async (type, ids) => {
93
+ const data = {};
94
+ await Promise.all(ids.map(async (id) => {
95
+ let value = await readData(`${type}-${id}.json`);
96
+ if (type === 'app-state-sync-key' && value) {
97
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
98
+ }
99
+ data[id] = value;
100
+ }));
101
+ return data;
102
+ },
103
+ set: async (data) => {
104
+ const tasks = [];
105
+ for (const category in data) {
106
+ for (const id in data[category]) {
107
+ const value = data[category][id];
108
+ const file = `${category}-${id}.json`;
109
+ tasks.push(value ? writeData(value, file) : removeData(file));
110
+ }
111
+ }
112
+ await Promise.all(tasks);
113
+ }
114
+ }
115
+ },
116
+ saveCreds: async () => {
117
+ return writeData(creds, 'creds.json');
118
+ }
119
+ };
120
+ };
121
121
  //# sourceMappingURL=use-multi-file-auth-state.js.map