@nexustechpro/baileys 2.0.2 → 2.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.
- package/LICENSE +1 -1
- package/README.md +924 -1299
- package/WAProto/index.js +22 -18
- package/lib/Defaults/baileys-version.json +6 -2
- package/lib/Defaults/index.js +173 -172
- package/lib/Signal/libsignal.js +395 -292
- package/lib/Signal/lid-mapping.js +264 -171
- package/lib/Socket/Client/index.js +2 -2
- package/lib/Socket/Client/types.js +10 -10
- package/lib/Socket/Client/websocket.js +45 -310
- package/lib/Socket/business.js +375 -375
- package/lib/Socket/chats.js +916 -963
- package/lib/Socket/communities.js +430 -430
- package/lib/Socket/groups.js +342 -342
- package/lib/Socket/index.js +21 -22
- package/lib/Socket/messages-recv.js +963 -743
- package/lib/Socket/messages-send.js +273 -321
- package/lib/Socket/mex.js +50 -50
- package/lib/Socket/newsletter.js +148 -148
- package/lib/Socket/nexus-handler.js +296 -247
- package/lib/Socket/registration.js +50 -33
- package/lib/Socket/socket.js +872 -1201
- package/lib/Store/index.js +5 -5
- package/lib/Store/make-cache-manager-store.js +81 -81
- package/lib/Store/make-in-memory-store.js +416 -416
- package/lib/Store/make-ordered-dictionary.js +81 -81
- package/lib/Store/object-repository.js +30 -30
- package/lib/Types/Auth.js +1 -1
- package/lib/Types/Bussines.js +1 -1
- package/lib/Types/Call.js +1 -1
- package/lib/Types/Chat.js +7 -7
- package/lib/Types/Contact.js +1 -1
- package/lib/Types/Events.js +1 -1
- package/lib/Types/GroupMetadata.js +1 -1
- package/lib/Types/Label.js +24 -24
- package/lib/Types/LabelAssociation.js +6 -6
- package/lib/Types/Message.js +10 -10
- package/lib/Types/Newsletter.js +37 -29
- package/lib/Types/Product.js +1 -1
- package/lib/Types/Signal.js +1 -1
- package/lib/Types/Socket.js +2 -2
- package/lib/Types/State.js +55 -12
- package/lib/Types/USync.js +1 -1
- package/lib/Types/index.js +25 -25
- package/lib/Utils/auth-utils.js +264 -256
- package/lib/Utils/baileys-event-stream.js +55 -55
- package/lib/Utils/browser-utils.js +27 -27
- package/lib/Utils/business.js +228 -230
- package/lib/Utils/chat-utils.js +726 -764
- package/lib/Utils/companion-reg-client-utils.js +34 -0
- package/lib/Utils/crypto.js +109 -135
- package/lib/Utils/decode-wa-message.js +342 -314
- package/lib/Utils/event-buffer.js +547 -547
- package/lib/Utils/generics.js +295 -297
- package/lib/Utils/history.js +91 -83
- package/lib/Utils/index.js +25 -20
- package/lib/Utils/key-store.js +17 -0
- package/lib/Utils/link-preview.js +107 -98
- package/lib/Utils/logger.js +2 -2
- package/lib/Utils/lt-hash.js +47 -47
- package/lib/Utils/make-mutex.js +39 -39
- package/lib/Utils/message-retry-manager.js +148 -148
- package/lib/Utils/messages-media.js +579 -535
- package/lib/Utils/messages.js +821 -706
- package/lib/Utils/noise-handler.js +255 -255
- package/lib/Utils/pre-key-manager.js +105 -105
- package/lib/Utils/process-message.js +430 -412
- package/lib/Utils/reporting-utils.js +155 -0
- package/lib/Utils/signal.js +191 -159
- package/lib/Utils/sync-action-utils.js +33 -0
- package/lib/Utils/tc-token-utils.js +162 -0
- package/lib/Utils/use-multi-file-auth-state.js +120 -120
- package/lib/Utils/validate-connection.js +194 -194
- package/lib/WABinary/constants.js +1306 -1300
- package/lib/WABinary/decode.js +237 -237
- package/lib/WABinary/encode.js +232 -232
- package/lib/WABinary/generic-utils.js +252 -211
- package/lib/WABinary/index.js +6 -5
- package/lib/WABinary/jid-utils.js +279 -95
- package/lib/WABinary/types.js +1 -1
- package/lib/WAM/BinaryInfo.js +9 -9
- package/lib/WAM/constants.js +22852 -22852
- package/lib/WAM/encode.js +149 -149
- package/lib/WAM/index.js +3 -3
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -28
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -53
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -26
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -37
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -28
- package/lib/WAUSync/Protocols/index.js +4 -4
- package/lib/WAUSync/USyncQuery.js +93 -93
- package/lib/WAUSync/USyncUser.js +22 -22
- package/lib/WAUSync/index.js +3 -3
- package/lib/index.js +65 -66
- package/package.json +172 -143
- package/lib/Signal/Group/ciphertext-message.js +0 -12
- package/lib/Signal/Group/group-session-builder.js +0 -30
- package/lib/Signal/Group/group_cipher.js +0 -100
- package/lib/Signal/Group/index.js +0 -12
- package/lib/Signal/Group/keyhelper.js +0 -18
- package/lib/Signal/Group/sender-chain-key.js +0 -26
- package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
- package/lib/Signal/Group/sender-key-message.js +0 -66
- package/lib/Signal/Group/sender-key-name.js +0 -48
- package/lib/Signal/Group/sender-key-record.js +0 -41
- package/lib/Signal/Group/sender-key-state.js +0 -84
- package/lib/Signal/Group/sender-message-key.js +0 -26
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
|
|
2
|
+
// Same phone-number pattern as WABinary's isJidBot, applied against the user
|
|
3
|
+
// part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
|
|
4
|
+
const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
|
|
5
|
+
/**
|
|
6
|
+
* Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
|
|
7
|
+
* storage against malformed notifications — WA Web filters server-side but we
|
|
8
|
+
* defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
|
|
9
|
+
* Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
|
|
10
|
+
*/
|
|
11
|
+
function isRegularUser(jid) {
|
|
12
|
+
if (!jid)
|
|
13
|
+
return false;
|
|
14
|
+
const user = jid.split('@')[0] ?? '';
|
|
15
|
+
if (user === '0')
|
|
16
|
+
return false; // PSA
|
|
17
|
+
if (BOT_PHONE_REGEX.test(user))
|
|
18
|
+
return false; // Bot by phone pattern
|
|
19
|
+
if (isJidMetaAI(jid))
|
|
20
|
+
return false; // MetaAI (@bot server)
|
|
21
|
+
return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
|
|
22
|
+
}
|
|
23
|
+
const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
|
|
24
|
+
const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
|
|
25
|
+
/** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
|
|
26
|
+
export const TC_TOKEN_INDEX_KEY = '__index';
|
|
27
|
+
/** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
|
|
28
|
+
export async function readTcTokenIndex(keys) {
|
|
29
|
+
const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
|
|
30
|
+
const entry = data[TC_TOKEN_INDEX_KEY];
|
|
31
|
+
if (!entry?.token?.length)
|
|
32
|
+
return [];
|
|
33
|
+
try {
|
|
34
|
+
const parsed = JSON.parse(Buffer.from(entry.token).toString());
|
|
35
|
+
if (!Array.isArray(parsed))
|
|
36
|
+
return [];
|
|
37
|
+
return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
|
|
44
|
+
export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
|
|
45
|
+
const persisted = await readTcTokenIndex(keys);
|
|
46
|
+
const merged = new Set(persisted);
|
|
47
|
+
for (const jid of addedJids) {
|
|
48
|
+
if (jid && jid !== TC_TOKEN_INDEX_KEY)
|
|
49
|
+
merged.add(jid);
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
[TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
// WA Web has separate sender/receiver AB props for these but they're identical today
|
|
56
|
+
export function isTcTokenExpired(timestamp) {
|
|
57
|
+
if (timestamp === null || timestamp === undefined)
|
|
58
|
+
return true;
|
|
59
|
+
const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
|
|
60
|
+
if (isNaN(ts))
|
|
61
|
+
return true;
|
|
62
|
+
const now = Math.floor(Date.now() / 1000);
|
|
63
|
+
const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
|
|
64
|
+
const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
|
|
65
|
+
const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
|
|
66
|
+
return ts < cutoffTimestamp;
|
|
67
|
+
}
|
|
68
|
+
export function shouldSendNewTcToken(senderTimestamp) {
|
|
69
|
+
if (senderTimestamp === undefined)
|
|
70
|
+
return true;
|
|
71
|
+
const now = Math.floor(Date.now() / 1000);
|
|
72
|
+
const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
|
|
73
|
+
const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
|
|
74
|
+
return currentBucket > senderBucket;
|
|
75
|
+
}
|
|
76
|
+
/** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
|
|
77
|
+
export async function resolveTcTokenJid(jid, getLIDForPN) {
|
|
78
|
+
if (isLidUser(jid))
|
|
79
|
+
return jid;
|
|
80
|
+
const lid = await getLIDForPN(jid);
|
|
81
|
+
return lid ?? jid;
|
|
82
|
+
}
|
|
83
|
+
/** Resolve target JID for issuing privacy token based on AB prop 14303 */
|
|
84
|
+
export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
|
|
85
|
+
if (issueToLid) {
|
|
86
|
+
if (isLidUser(jid))
|
|
87
|
+
return jid;
|
|
88
|
+
const lid = await getLIDForPN(jid);
|
|
89
|
+
return lid ?? jid;
|
|
90
|
+
}
|
|
91
|
+
if (!isLidUser(jid))
|
|
92
|
+
return jid;
|
|
93
|
+
if (getPNForLID) {
|
|
94
|
+
const pn = await getPNForLID(jid);
|
|
95
|
+
return pn ?? jid;
|
|
96
|
+
}
|
|
97
|
+
return jid;
|
|
98
|
+
}
|
|
99
|
+
export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
|
|
100
|
+
try {
|
|
101
|
+
const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
|
|
102
|
+
const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
|
|
103
|
+
const entry = tcTokenData?.[storageJid];
|
|
104
|
+
const tcTokenBuffer = entry?.token;
|
|
105
|
+
if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
|
|
106
|
+
if (tcTokenBuffer) {
|
|
107
|
+
// Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
|
|
108
|
+
// after we drop the unusable peer token. Only wipe the record entirely when
|
|
109
|
+
// there's nothing worth keeping.
|
|
110
|
+
const cleared = entry?.senderTimestamp !== undefined
|
|
111
|
+
? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
|
|
112
|
+
: null;
|
|
113
|
+
await authState.keys.set({ tctoken: { [storageJid]: cleared } });
|
|
114
|
+
}
|
|
115
|
+
return baseContent.length > 0 ? baseContent : undefined;
|
|
116
|
+
}
|
|
117
|
+
baseContent.push({
|
|
118
|
+
tag: 'tctoken',
|
|
119
|
+
attrs: {},
|
|
120
|
+
content: tcTokenBuffer
|
|
121
|
+
});
|
|
122
|
+
return baseContent;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
return baseContent.length > 0 ? baseContent : undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
|
|
129
|
+
const tokensNode = getBinaryNodeChild(result, 'tokens');
|
|
130
|
+
if (!tokensNode)
|
|
131
|
+
return;
|
|
132
|
+
const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
|
|
133
|
+
for (const tokenNode of tokenNodes) {
|
|
134
|
+
if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
// In notifications tokenNode.attrs.jid is your own device JID, not the sender's
|
|
138
|
+
const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
|
|
139
|
+
if (!isRegularUser(rawJid))
|
|
140
|
+
continue;
|
|
141
|
+
const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
|
|
142
|
+
const existingTcData = await keys.get('tctoken', [storageJid]);
|
|
143
|
+
const existingEntry = existingTcData[storageJid];
|
|
144
|
+
const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
|
|
145
|
+
const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
|
|
146
|
+
// timestamp-less tokens would be immediately expired
|
|
147
|
+
if (!incomingTs)
|
|
148
|
+
continue;
|
|
149
|
+
if (existingTs > 0 && existingTs > incomingTs)
|
|
150
|
+
continue;
|
|
151
|
+
await keys.set({
|
|
152
|
+
tctoken: {
|
|
153
|
+
[storageJid]: {
|
|
154
|
+
...existingEntry,
|
|
155
|
+
token: Buffer.from(tokenNode.content),
|
|
156
|
+
timestamp: tokenNode.attrs.t
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
onNewJidStored?.(storageJid);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -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
|