@pontasockets/baileys 1.0.1 → 1.0.2
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/lib/Defaults/index.js
CHANGED
|
@@ -79,7 +79,7 @@ exports.DEFAULT_CONNECTION_CONFIG = {
|
|
|
79
79
|
linkPreviewImageThumbnailWidth: 192,
|
|
80
80
|
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
|
|
81
81
|
generateHighQualityLinkPreview: false,
|
|
82
|
-
enableAutoSessionRecreation:
|
|
82
|
+
enableAutoSessionRecreation: true,
|
|
83
83
|
enableRecentMessageCache: false,
|
|
84
84
|
options: {},
|
|
85
85
|
appStateMacVerification: {
|
package/lib/Signal/libsignal.js
CHANGED
|
@@ -111,6 +111,24 @@ function makeLibSignalRepository(auth, onWhatsAppFunc, logger) {
|
|
|
111
111
|
},
|
|
112
112
|
jidToSignalProtocolAddress(jid) {
|
|
113
113
|
return jidToSignalProtocolAddress(jid).toString();
|
|
114
|
+
},
|
|
115
|
+
// Dipakai oleh sendRetryRequest (messages-recv.js) untuk enableAutoSessionRecreation.
|
|
116
|
+
// Sebelumnya dipanggil tapi tidak pernah diimplementasikan di sini, jadi fitur auto
|
|
117
|
+
// session recreation diam-diam selalu gagal (ketangkep try/catch, cuma log warning).
|
|
118
|
+
async validateSession(jid) {
|
|
119
|
+
try {
|
|
120
|
+
const addr = jidToSignalProtocolAddress(jid);
|
|
121
|
+
const session = await storage.loadSession(addr.toString());
|
|
122
|
+
if (!session) {
|
|
123
|
+
return { exists: false, reason: 'no session' };
|
|
124
|
+
}
|
|
125
|
+
if (typeof session.haveOpenSession === 'function' && !session.haveOpenSession()) {
|
|
126
|
+
return { exists: false, reason: 'no open session' };
|
|
127
|
+
}
|
|
128
|
+
return { exists: true };
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return { exists: false, reason: 'validation error' };
|
|
131
|
+
}
|
|
114
132
|
}
|
|
115
133
|
};
|
|
116
134
|
}
|
|
@@ -55,6 +55,13 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
55
55
|
} = sock
|
|
56
56
|
|
|
57
57
|
const retryMutex = make_mutex_1.makeMutex()
|
|
58
|
+
// Mutex terpisah dari processingMutex (dipakai chats.js/messages-send.js) supaya
|
|
59
|
+
// handleMessage/handleReceipt/handleNotification tidak saling antre di satu antrean
|
|
60
|
+
// yang sama. Kalau satu pesan lambat diproses (nunggu plugin/group metadata), receipt
|
|
61
|
+
// & notification lain tetap bisa jalan tanpa nunggu giliran.
|
|
62
|
+
const messageMutex = make_mutex_1.makeMutex()
|
|
63
|
+
const receiptMutex = make_mutex_1.makeMutex()
|
|
64
|
+
const notificationMutex = make_mutex_1.makeMutex()
|
|
58
65
|
|
|
59
66
|
const groupDataCache = new Map()
|
|
60
67
|
global.groupMetadataCache = async (jid) => {
|
|
@@ -1105,7 +1112,7 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1105
1112
|
|
|
1106
1113
|
try {
|
|
1107
1114
|
await Promise.all([
|
|
1108
|
-
|
|
1115
|
+
receiptMutex.mutex(async () => {
|
|
1109
1116
|
const status = Utils_1.getStatusFromReceiptType(attrs.type)
|
|
1110
1117
|
|
|
1111
1118
|
if (typeof status !== 'undefined' && (
|
|
@@ -1195,7 +1202,7 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1195
1202
|
|
|
1196
1203
|
try {
|
|
1197
1204
|
await Promise.all([
|
|
1198
|
-
|
|
1205
|
+
notificationMutex.mutex(async () => {
|
|
1199
1206
|
const msg = await processNotification(node)
|
|
1200
1207
|
|
|
1201
1208
|
if (msg) {
|
|
@@ -1241,7 +1248,13 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1241
1248
|
|
|
1242
1249
|
if (WABinary_1.getBinaryNodeChild(node, 'unavailable') && !encNode) {
|
|
1243
1250
|
await sendMessageAck(node)
|
|
1244
|
-
|
|
1251
|
+
let key
|
|
1252
|
+
try {
|
|
1253
|
+
key = Utils_1.decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage.key
|
|
1254
|
+
} catch (error) {
|
|
1255
|
+
logger.error({ error, node }, 'failed to decode unavailable message node, skipping placeholder resend')
|
|
1256
|
+
return
|
|
1257
|
+
}
|
|
1245
1258
|
response = await requestPlaceholderResend(key);
|
|
1246
1259
|
if (response === 'RESOLVED') {
|
|
1247
1260
|
return
|
|
@@ -1253,12 +1266,30 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1253
1266
|
}
|
|
1254
1267
|
}
|
|
1255
1268
|
|
|
1269
|
+
let decodeResult
|
|
1270
|
+
try {
|
|
1271
|
+
// decryptMessageNode bisa throw sebelum sempat masuk try/catch utama di bawah
|
|
1272
|
+
// (contoh: bug upstream baileys "No participant in group message" pada node
|
|
1273
|
+
// yang malformed/gak lengkap). Kalau gak ditangkep di sini, exception ini lolos
|
|
1274
|
+
// sebagai unhandled rejection dari handleMessage - baik pas diproses langsung
|
|
1275
|
+
// (live message) maupun lewat offline queue.
|
|
1276
|
+
decodeResult = Utils_1.decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger)
|
|
1277
|
+
} catch (error) {
|
|
1278
|
+
logger.error({ error, node }, 'failed to decrypt/decode message node, dropping')
|
|
1279
|
+
try {
|
|
1280
|
+
await sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError)
|
|
1281
|
+
} catch (ackError) {
|
|
1282
|
+
logger.error({ ackError }, 'failed to ack undecodable message node')
|
|
1283
|
+
}
|
|
1284
|
+
return
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1256
1287
|
const {
|
|
1257
1288
|
fullMessage: msg,
|
|
1258
1289
|
category,
|
|
1259
1290
|
author,
|
|
1260
1291
|
decrypt
|
|
1261
|
-
} =
|
|
1292
|
+
} = decodeResult
|
|
1262
1293
|
if (response && msg?.messageStubParameters?.[0] === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
|
|
1263
1294
|
msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response]
|
|
1264
1295
|
}
|
|
@@ -1285,7 +1316,7 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1285
1316
|
|
|
1286
1317
|
try {
|
|
1287
1318
|
await Promise.all([
|
|
1288
|
-
|
|
1319
|
+
messageMutex.mutex(async () => {
|
|
1289
1320
|
await decrypt()
|
|
1290
1321
|
if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
|
|
1291
1322
|
if (msg?.messageStubParameters?.[0] === Utils_1.MISSING_KEYS_ERROR_TEXT) {
|
|
@@ -1296,6 +1327,12 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1296
1327
|
const isPreKeyError = errorMessage.includes('PreKey')
|
|
1297
1328
|
logger.debug(`[handleMessage] Attempting retry request for failed decryption`)
|
|
1298
1329
|
|
|
1330
|
+
// .catch() wajib ada: call ini sengaja tidak di-await (biar retry
|
|
1331
|
+
// request gak ngeblok proses pesan lain), tapi kalau dibiarkan tanpa
|
|
1332
|
+
// .catch() dan mutex-nya reject, itu jadi unhandled promise rejection
|
|
1333
|
+
// yang bisa nge-crash seluruh proses Node (default Node behavior sejak
|
|
1334
|
+
// v15). Ini yang paling mungkin jadi penyebab bot "tiba-tiba disconnect
|
|
1335
|
+
// dan gak recover" setelah jalan beberapa jam.
|
|
1299
1336
|
retryMutex.mutex(async () => {
|
|
1300
1337
|
try {
|
|
1301
1338
|
if (!ws.isOpen) {
|
|
@@ -1345,6 +1382,8 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1345
1382
|
}, 'Failed to send retry after error handling')
|
|
1346
1383
|
}
|
|
1347
1384
|
}
|
|
1385
|
+
}).catch((mutexErr) => {
|
|
1386
|
+
logger.error({ mutexErr }, 'retryMutex task failed unexpectedly')
|
|
1348
1387
|
})
|
|
1349
1388
|
} else {
|
|
1350
1389
|
let type = undefined
|
|
@@ -1493,6 +1532,14 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1493
1532
|
error,
|
|
1494
1533
|
node
|
|
1495
1534
|
}, 'error in handling message')
|
|
1535
|
+
// Kalau exception terjadi sebelum sempat ack (misal error di plugin/group
|
|
1536
|
+
// metadata sebelum baris sendMessageAck), stanza ini wajib tetap di-ack.
|
|
1537
|
+
// Tanpa ini, server WA bisa terus retry/redeliver pesan yang sama berulang-ulang.
|
|
1538
|
+
try {
|
|
1539
|
+
await sendMessageAck(node, Utils_1.NACK_REASONS.UnhandledError)
|
|
1540
|
+
} catch (ackError) {
|
|
1541
|
+
logger.error({ ackError }, 'failed to ack message after error')
|
|
1542
|
+
}
|
|
1496
1543
|
}
|
|
1497
1544
|
}
|
|
1498
1545
|
|
|
@@ -1697,19 +1744,36 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1697
1744
|
isProcessing = true
|
|
1698
1745
|
|
|
1699
1746
|
const promise = async () => {
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1747
|
+
// PENTING: sebelumnya kalau nodeProcessor(node) throw (misal bug upstream
|
|
1748
|
+
// baileys "No participant in group message" pas decrypt node offline yang
|
|
1749
|
+
// malformed), exception itu keluar dari while-loop ini SEBELUM sempat
|
|
1750
|
+
// `isProcessing = false`. Akibatnya isProcessing kepentok true SELAMANYA,
|
|
1751
|
+
// dan enqueue() di bawah selalu langsung `return` tanpa pernah mulai
|
|
1752
|
+
// proses lagi -> semua pesan sesudahnya cuma numpuk di array `nodes` dan
|
|
1753
|
+
// gak pernah diproses lagi sampai bot di-restart total. Ini kemungkinan
|
|
1754
|
+
// besar penyebab "reconnect tapi gak pernah nerima pesan lagi".
|
|
1755
|
+
try {
|
|
1756
|
+
while (nodes.length && ws.isOpen) {
|
|
1757
|
+
const {
|
|
1758
|
+
type,
|
|
1759
|
+
node
|
|
1760
|
+
} = nodes.shift()
|
|
1761
|
+
const nodeProcessor = nodeProcessorMap.get(type)
|
|
1762
|
+
if (!nodeProcessor) {
|
|
1763
|
+
onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node')
|
|
1764
|
+
continue
|
|
1765
|
+
}
|
|
1766
|
+
try {
|
|
1767
|
+
await nodeProcessor(node)
|
|
1768
|
+
} catch (error) {
|
|
1769
|
+
// Satu node gagal (misal pesan corrupt/participant kosong) TIDAK
|
|
1770
|
+
// boleh ngeblok node-node lain di belakangnya dalam antrian.
|
|
1771
|
+
onUnexpectedError(error, 'processing offline node')
|
|
1772
|
+
}
|
|
1709
1773
|
}
|
|
1710
|
-
|
|
1774
|
+
} finally {
|
|
1775
|
+
isProcessing = false
|
|
1711
1776
|
}
|
|
1712
|
-
isProcessing = false
|
|
1713
1777
|
}
|
|
1714
1778
|
promise().catch(error => onUnexpectedError(error, 'processing offline nodes'))
|
|
1715
1779
|
}
|
|
@@ -1721,28 +1785,31 @@ const makeMessagesRecvSocket = (config) => {
|
|
|
1721
1785
|
|
|
1722
1786
|
const offlineNodeProcessor = makeOfflineNodeProcessor()
|
|
1723
1787
|
|
|
1724
|
-
const processNode = (type, node, identifier, exec) => {
|
|
1788
|
+
const processNode = async (type, node, identifier, exec) => {
|
|
1725
1789
|
const isOffline = !!node.attrs.offline
|
|
1726
1790
|
|
|
1727
1791
|
if (isOffline) {
|
|
1728
1792
|
offlineNodeProcessor.enqueue(type, node)
|
|
1729
1793
|
} else {
|
|
1730
|
-
processNodeWithBuffer(node, identifier, exec)
|
|
1794
|
+
await processNodeWithBuffer(node, identifier, exec)
|
|
1731
1795
|
}
|
|
1732
1796
|
}
|
|
1733
1797
|
|
|
1734
1798
|
// recv a message
|
|
1735
|
-
|
|
1736
|
-
|
|
1799
|
+
// Semua handler di-await supaya event 'CB:message'/'CB:call'/'CB:receipt'/'CB:notification'
|
|
1800
|
+
// yang datang beruntun tidak diproses bersamaan tanpa urutan (race condition di state
|
|
1801
|
+
// bersama seperti session & cache).
|
|
1802
|
+
ws.on('CB:message', async (node) => {
|
|
1803
|
+
await processNode('message', node, 'processing message', handleMessage)
|
|
1737
1804
|
})
|
|
1738
1805
|
ws.on('CB:call', async (node) => {
|
|
1739
|
-
processNode('call', node, 'handling call', handleCall)
|
|
1806
|
+
await processNode('call', node, 'handling call', handleCall)
|
|
1740
1807
|
})
|
|
1741
|
-
ws.on('CB:receipt', node => {
|
|
1742
|
-
processNode('receipt', node, 'handling receipt', handleReceipt)
|
|
1808
|
+
ws.on('CB:receipt', async (node) => {
|
|
1809
|
+
await processNode('receipt', node, 'handling receipt', handleReceipt)
|
|
1743
1810
|
})
|
|
1744
1811
|
ws.on('CB:notification', async (node) => {
|
|
1745
|
-
processNode('notification', node, 'handling notification', handleNotification)
|
|
1812
|
+
await processNode('notification', node, 'handling notification', handleNotification)
|
|
1746
1813
|
})
|
|
1747
1814
|
ws.on('CB:ack,class:message', (node) => {
|
|
1748
1815
|
handleBadAck(node)
|
|
@@ -23,13 +23,19 @@ const fileLocks = new Map()
|
|
|
23
23
|
const getFileLock = (path) => {
|
|
24
24
|
let mutex = fileLocks.get(path)
|
|
25
25
|
if (!mutex) {
|
|
26
|
-
mutex = new async_mutex_1.Mutex()
|
|
26
|
+
mutex = new async_mutex_1.Mutex()
|
|
27
27
|
fileLocks.set(path, mutex)
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
return mutex
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
// Lepas mutex dari Map begitu tidak dipakai lagi supaya tidak numpuk terus (memory leak)
|
|
34
|
+
// selama proses hidup lama (bot jalan berbulan-bulan dengan ribuan file sesi berbeda).
|
|
35
|
+
const releaseFileLock = (path) => {
|
|
36
|
+
fileLocks.delete(path)
|
|
37
|
+
}
|
|
38
|
+
|
|
33
39
|
/**
|
|
34
40
|
* stores the full authentication state in a single folder.
|
|
35
41
|
* Far more efficient than singlefileauthstate
|
|
@@ -38,51 +44,56 @@ const getFileLock = (path) => {
|
|
|
38
44
|
* Would recommend writing an auth state for use with a proper SQL or No-SQL DB
|
|
39
45
|
* */
|
|
40
46
|
const useMultiFileAuthState = async (folder) => {
|
|
41
|
-
// Debounce timers per file to avoid rapid successive writes hammering disk
|
|
42
|
-
const writeDebounceTimers = new Map()
|
|
43
|
-
const WRITE_DEBOUNCE_MS = 300
|
|
44
|
-
|
|
45
47
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
46
48
|
const writeData = async (data, file) => {
|
|
47
49
|
const filePath = path_1.join(folder, fixFileName(file))
|
|
48
50
|
const mutex = getFileLock(filePath)
|
|
49
51
|
return mutex.acquire().then(async (release) => {
|
|
50
52
|
try {
|
|
51
|
-
// Atomic write: write to temp file then rename
|
|
53
|
+
// Atomic write: write to temp file then rename, agar file tidak pernah
|
|
54
|
+
// kebaca dalam kondisi setengah tertulis kalau proses mati di tengah jalan.
|
|
52
55
|
const tmpPath = filePath + '.tmp'
|
|
53
56
|
await promises_1.writeFile(tmpPath, JSON.stringify(data, generics_1.BufferJSON.replacer))
|
|
54
57
|
await fsRename(tmpPath, filePath)
|
|
55
58
|
} finally {
|
|
56
59
|
release()
|
|
60
|
+
releaseFileLock(filePath)
|
|
57
61
|
}
|
|
58
62
|
})
|
|
59
63
|
}
|
|
60
64
|
const readData = async (file) => {
|
|
65
|
+
const filePath = path_1.join(folder, fixFileName(file))
|
|
61
66
|
try {
|
|
62
|
-
const filePath = path_1.join(folder, fixFileName(file))
|
|
63
67
|
const mutex = getFileLock(filePath)
|
|
64
68
|
const data = await mutex.acquire().then(async (release) => {
|
|
65
69
|
try {
|
|
66
70
|
return await promises_1.readFile(filePath, { encoding: 'utf-8' })
|
|
67
71
|
} finally {
|
|
68
72
|
release()
|
|
73
|
+
releaseFileLock(filePath)
|
|
69
74
|
}
|
|
70
75
|
})
|
|
71
76
|
|
|
72
77
|
return JSON.parse(data, generics_1.BufferJSON.reviver)
|
|
73
78
|
} catch (error) {
|
|
79
|
+
// ENOENT (file belum ada) itu normal, tapi kalau isinya rusak/corrupt (JSON parse
|
|
80
|
+
// gagal) itu wajib kelihatan di log, bukan diam-diam dianggap "null"/hilang.
|
|
81
|
+
if (error?.code !== 'ENOENT') {
|
|
82
|
+
console.warn(`[useMultiFileAuthState] Gagal membaca/parse ${filePath}:`, error?.message || error)
|
|
83
|
+
}
|
|
74
84
|
return null
|
|
75
85
|
}
|
|
76
86
|
}
|
|
77
87
|
const removeData = async (file) => {
|
|
88
|
+
const filePath = path_1.join(folder, fixFileName(file))
|
|
78
89
|
try {
|
|
79
|
-
const filePath = path_1.join(folder, fixFileName(file))
|
|
80
90
|
const mutex = getFileLock(filePath)
|
|
81
91
|
await mutex.acquire().then(async (release) => {
|
|
82
92
|
try {
|
|
83
93
|
await promises_1.unlink(filePath)
|
|
84
94
|
} finally {
|
|
85
95
|
release()
|
|
96
|
+
releaseFileLock(filePath)
|
|
86
97
|
}
|
|
87
98
|
})
|
|
88
99
|
} catch {}
|
|
@@ -96,9 +107,22 @@ const useMultiFileAuthState = async (folder) => {
|
|
|
96
107
|
else {
|
|
97
108
|
await promises_1.mkdir(folder, { recursive: true })
|
|
98
109
|
}
|
|
99
|
-
const fixFileName = (file) => {
|
|
100
|
-
return file?.replace(/\//g, '__')?.replace(/:/g, '-')
|
|
110
|
+
const fixFileName = (file) => {
|
|
111
|
+
return file?.replace(/\//g, '__')?.replace(/:/g, '-')
|
|
101
112
|
}
|
|
113
|
+
|
|
114
|
+
// Bersihkan file .tmp "yatim" yang tertinggal dari proses sebelumnya yang mati
|
|
115
|
+
// di tengah proses rename (atomic write). File-file ini tidak berguna dan kalau
|
|
116
|
+
// dibiarkan menumpuk, cuma buang-buang disk.
|
|
117
|
+
try {
|
|
118
|
+
const entries = await promises_1.readdir(folder)
|
|
119
|
+
await Promise.all(
|
|
120
|
+
entries
|
|
121
|
+
.filter((name) => name.endsWith('.tmp'))
|
|
122
|
+
.map((name) => promises_1.unlink(path_1.join(folder, name)).catch(() => {}))
|
|
123
|
+
)
|
|
124
|
+
} catch {}
|
|
125
|
+
|
|
102
126
|
const creds = await readData('creds.json') || auth_utils_1.initAuthCreds()
|
|
103
127
|
return {
|
|
104
128
|
state: {
|
|
@@ -128,24 +152,15 @@ const useMultiFileAuthState = async (folder) => {
|
|
|
128
152
|
}
|
|
129
153
|
}
|
|
130
154
|
},
|
|
131
|
-
// saveCreds
|
|
132
|
-
//
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
const timer = setTimeout(() => {
|
|
137
|
-
writeDebounceTimers.delete('creds.json')
|
|
138
|
-
writeData(creds, 'creds.json').catch(err => {
|
|
139
|
-
console.error('[useMultiFileAuthState] Failed to save creds.json:', err)
|
|
140
|
-
})
|
|
141
|
-
}, WRITE_DEBOUNCE_MS)
|
|
142
|
-
writeDebounceTimers.set('creds.json', timer)
|
|
155
|
+
// saveCreds sekarang selalu langsung menulis (tidak didebounce). creds.json adalah
|
|
156
|
+
// file paling kritis — kalau proses mati tepat di jendela debounce, sesi bisa hilang
|
|
157
|
+
// atau balik ke state lama sehingga semua pesan gagal didekripsi setelah reconnect.
|
|
158
|
+
saveCreds: async () => {
|
|
159
|
+
return writeData(creds, 'creds.json')
|
|
143
160
|
},
|
|
144
|
-
//
|
|
161
|
+
// Tetap disediakan sebagai alias untuk kompatibilitas kode lama yang memanggil
|
|
162
|
+
// saveCredsNow() secara eksplisit (misal di handler disconnect/cleanup).
|
|
145
163
|
saveCredsNow: async () => {
|
|
146
|
-
const existing = writeDebounceTimers.get('creds.json')
|
|
147
|
-
if (existing) clearTimeout(existing)
|
|
148
|
-
writeDebounceTimers.delete('creds.json')
|
|
149
164
|
return writeData(creds, 'creds.json')
|
|
150
165
|
}
|
|
151
166
|
}
|