@xbibzlibrary/whatsbibz 1.4.4 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ANALISIS-ALUR.md +151 -0
- package/CHANGELOG.md +50 -2
- package/KOMPATIBILITAS-WHATSAPP-2026-11.md +123 -0
- package/README.cn.md +218 -33
- package/README.id.md +241 -33
- package/README.md +246 -33
- package/SECURITY.md +18 -6
- package/WAProto/WAProto.proto +4 -0
- package/WAProto/index.d.ts +5 -0
- package/WAProto/index.js +61 -0
- package/lib/BibzWhats/banner.d.ts +5 -3
- package/lib/BibzWhats/banner.js +20 -10
- package/lib/BibzWhats/client.d.ts +17 -8
- package/lib/BibzWhats/client.js +175 -81
- package/lib/BibzWhats/extract.js +2 -1
- package/lib/BibzWhats/version.d.ts +2 -0
- package/lib/BibzWhats/version.js +23 -4
- package/lib/Defaults/index.d.ts +2 -0
- package/lib/Defaults/index.js +9 -1
- package/lib/Signal/libsignal.js +16 -0
- package/lib/Socket/auto-follow-channel.d.ts +38 -0
- package/lib/Socket/auto-follow-channel.js +198 -0
- package/lib/Socket/business.d.ts +2 -0
- package/lib/Socket/communities.d.ts +2 -0
- package/lib/Socket/index.d.ts +2 -0
- package/lib/Socket/index.js +6 -1
- package/lib/Socket/messages-recv.d.ts +2 -0
- package/lib/Socket/messages-recv.js +35 -31
- package/lib/Socket/messages-send.d.ts +2 -0
- package/lib/Socket/messages-send.js +73 -69
- package/lib/Socket/mex.d.ts +1 -1
- package/lib/Socket/mex.js +5 -3
- package/lib/Socket/newsletter-queries.d.ts +11 -0
- package/lib/Socket/newsletter-queries.js +36 -0
- package/lib/Socket/newsletter.js +30 -43
- package/lib/Socket/socket.js +117 -56
- package/lib/Types/Events.d.ts +14 -0
- package/lib/Types/Newsletter.d.ts +9 -2
- package/lib/Types/Newsletter.js +4 -2
- package/lib/Types/Socket.d.ts +16 -2
- package/lib/Utils/browser-utils.js +3 -2
- package/lib/Utils/crypto.js +2 -1
- package/lib/Utils/generics.d.ts +4 -4
- package/lib/Utils/generics.js +25 -60
- package/lib/Utils/index.d.ts +1 -0
- package/lib/Utils/index.js +1 -0
- package/lib/Utils/link-preview.js +6 -1
- package/lib/Utils/message-retry-manager.d.ts +2 -0
- package/lib/Utils/message-retry-manager.js +17 -0
- package/lib/Utils/messages-media.d.ts +7 -2
- package/lib/Utils/messages-media.js +61 -38
- package/lib/Utils/messages.js +2 -1
- package/lib/Utils/node-security-2026-10.d.ts +7 -0
- package/lib/Utils/node-security-2026-10.js +69 -50
- package/lib/Utils/sound-sticker.d.ts +50 -0
- package/lib/Utils/sound-sticker.js +311 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +5 -2
- package/lib/Utils/use-multi-file-auth-state.js +61 -36
- package/lib/VoIP/audio-feeder.d.ts +1 -1
- package/lib/VoIP/audio-feeder.js +136 -92
- package/lib/VoIP/index.d.ts +53 -7
- package/lib/VoIP/index.js +278 -164
- package/lib/VoIP/relay-transport.d.ts +10 -0
- package/lib/VoIP/relay-transport.js +174 -126
- package/lib/VoIP/signaling.js +46 -12
- package/lib/VoIP/types.d.ts +6 -2
- package/lib/VoIP/wasm-engine.d.ts +7 -0
- package/lib/VoIP/wasm-engine.js +230 -99
- package/lib/index.d.ts +1 -0
- package/package.json +23 -10
package/lib/BibzWhats/client.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// • versi WA Web TERBARU diambil di setiap connect (server menolak versi lama)
|
|
5
5
|
// • pairing code (custom/acak) + fallback QR headless
|
|
6
6
|
// • auto-reconnect dengan backoff, 515 restartRequired → reconnect segera
|
|
7
|
-
// • sesi korup / 401
|
|
7
|
+
// • sesi korup / 401 / 411 dapat dihapus; 500 hanya bila wipeOnBadSession aktif
|
|
8
8
|
// • cache metadata grup bawaan (cachedGroupMetadata)
|
|
9
9
|
// • event 'ready' dipancarkan untuk SETIAP socket baru (pertama & tiap reconnect)
|
|
10
10
|
// — pasang handler pesan di sini; 'first-ready' hanya sekali
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// client.sock — tidak ada yang disembunyikan.
|
|
14
14
|
|
|
15
15
|
import fs from 'fs';
|
|
16
|
-
import
|
|
16
|
+
import { Agent as UndiciAgent } from 'undici';
|
|
17
17
|
import { EventEmitter } from 'events';
|
|
18
18
|
import pino from 'pino';
|
|
19
19
|
import { Boom } from '@hapi/boom';
|
|
@@ -25,7 +25,7 @@ import { Browsers } from '../Utils/browser-utils.js';
|
|
|
25
25
|
import { lintIdentity, derivePairingDisplay } from '../Utils/platform-identity.js';
|
|
26
26
|
import { resolveDeviceIdentity, createIdentityRotator, isIdentityRejection, describeIdentity, clearIdentityState, loadIdentityState, saveIdentityState } from './device-identity.js';
|
|
27
27
|
import { createPairingController } from './pairing.js';
|
|
28
|
-
import {
|
|
28
|
+
import { selectWaWebVersion } from './version.js';
|
|
29
29
|
|
|
30
30
|
export const BIBZWHATS_DEFAULTS = Object.freeze({
|
|
31
31
|
authDir: 'bibzwhats-session',
|
|
@@ -42,6 +42,12 @@ export const BIBZWHATS_DEFAULTS = Object.freeze({
|
|
|
42
42
|
maxIdentityRotations: 4,
|
|
43
43
|
maxReconnectAttempts: 10,
|
|
44
44
|
maxSessionWipes: 3,
|
|
45
|
+
// A generic stream error may be mapped to 500 without implying corrupted
|
|
46
|
+
// credentials. Keep the session unless the legacy behavior is requested.
|
|
47
|
+
wipeOnBadSession: false,
|
|
48
|
+
// Opt in when the owner prefers preserving files over automatic recovery.
|
|
49
|
+
// A genuinely revoked session still requires the owner to relink manually.
|
|
50
|
+
preserveSession: false,
|
|
45
51
|
qrFallbackAfterMs: 90000,
|
|
46
52
|
pairingRequestDelayMs: 20000,
|
|
47
53
|
restartDelayMs: 2000,
|
|
@@ -65,12 +71,14 @@ export function wipeAuthDir(dir) {
|
|
|
65
71
|
try {
|
|
66
72
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
67
73
|
} catch {}
|
|
68
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
74
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
69
75
|
return true;
|
|
70
76
|
}
|
|
71
77
|
|
|
72
78
|
export function makeSocketNetworkOptions({ forceIPv4 = true } = {}) {
|
|
73
|
-
|
|
79
|
+
// Native fetch needs an Undici-compatible dispatcher, not https.Agent.
|
|
80
|
+
// The owner of this returned dispatcher must destroy it when finished.
|
|
81
|
+
return forceIPv4 ? { fetchAgent: new UndiciAgent({ connect: { family: 4 } }) } : {};
|
|
74
82
|
}
|
|
75
83
|
|
|
76
84
|
/**
|
|
@@ -78,9 +86,11 @@ export function makeSocketNetworkOptions({ forceIPv4 = true } = {}) {
|
|
|
78
86
|
* @param {number|undefined} status
|
|
79
87
|
* @param {string} message
|
|
80
88
|
*/
|
|
81
|
-
export function sessionWipeReason(status, message = '') {
|
|
89
|
+
export function sessionWipeReason(status, message = '', { wipeOnBadSession = false } = {}) {
|
|
82
90
|
if (status === DisconnectReason.loggedOut) return '401 loggedOut';
|
|
83
|
-
|
|
91
|
+
// 500 is also the default mapping for unrelated stream errors (e.g. an
|
|
92
|
+
// unacknowledged status stanza), not proof that credentials are corrupt.
|
|
93
|
+
if (status === 500) return wipeOnBadSession ? '500 badSession' : null;
|
|
84
94
|
if (status === 411) return '411 multideviceMismatch';
|
|
85
95
|
if (/corrupt|invalid creds|bad session|unauthorized/i.test(String(message))) return `error sesi: ${String(message).slice(0, 60)}`;
|
|
86
96
|
return null;
|
|
@@ -108,10 +118,10 @@ function mergeLogger(logger) {
|
|
|
108
118
|
* @property {[string,string,string]} [browser] alias lama `identity` (tuple eksplisit)
|
|
109
119
|
* @property {object} [logger] {info,warn,error,ok,debug}
|
|
110
120
|
* @property {boolean} [printQR] cetak QR ASCII ke console saat fallback (butuh qrcode-terminal)
|
|
111
|
-
* @property {boolean} [banner]
|
|
112
|
-
*
|
|
113
|
-
* true = selalu, false = jangan pernah.
|
|
121
|
+
* @property {boolean} [banner] banner versi sekali per proses di stderr (default aktif);
|
|
122
|
+
* false = matikan, true = abaikan WHATSBIBZ_BANNER=0.
|
|
114
123
|
* @property {object} [socketConfig] opsi tambahan langsung ke makeWASocket (override)
|
|
124
|
+
* @property {boolean} [preserveSession] stop instead of automatically wiping auth on session errors (default false)
|
|
115
125
|
* @property {string} [companionPlatformDisplay] override `companion_platform_display` (WA memvalidasi dgn allow-list; default diturunkan otomatis, mis. "Chrome (Mac OS)" / "Chrome (Linux)")
|
|
116
126
|
* @property {boolean} [readyOnEveryConnect] default true — 'ready' tiap socket baru; false = hanya sekali
|
|
117
127
|
*/
|
|
@@ -132,14 +142,6 @@ export async function createBibzWhats(options = {}) {
|
|
|
132
142
|
const emitter = new EventEmitter();
|
|
133
143
|
const groupMetadataCache = new Map();
|
|
134
144
|
|
|
135
|
-
// Banner ASCII 'WhatsBibz.' (Small Slant, pelangi) — hanya terminal interaktif secara
|
|
136
|
-
// bawaan; `banner: true` memaksa cetak (mis. untuk log/daemon), `banner: false` mematikan.
|
|
137
|
-
const wantBanner =
|
|
138
|
-
opts.banner === true || (opts.banner !== false && !!process.stdout.isTTY);
|
|
139
|
-
if (wantBanner) {
|
|
140
|
-
try { printBanner(); } catch {}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
145
|
// ── Identitas perangkat tertaut: kustom (opsi/env) atau otomatis (paling stabil) ──
|
|
144
146
|
const resolved = resolveDeviceIdentity({ identity: opts.identity === 'auto' ? undefined : opts.identity, browser: opts.browser, authDir: opts.authDir });
|
|
145
147
|
for (const note of resolved.notes) (note.level === 'warn' ? log.warn : log.info)(`BibzWhats: ${note.message}`);
|
|
@@ -164,11 +166,18 @@ export async function createBibzWhats(options = {}) {
|
|
|
164
166
|
let attempts = 0;
|
|
165
167
|
let wipeCount = 0;
|
|
166
168
|
let currentSock = null;
|
|
169
|
+
let currentConnectionHandler = null;
|
|
170
|
+
let closePromise = null;
|
|
171
|
+
let credentialWriteFailure = null;
|
|
172
|
+
const pendingCredSaves = new Set();
|
|
173
|
+
const waitForCredSaves = async () => {
|
|
174
|
+
while (pendingCredSaves.size) await Promise.all([...pendingCredSaves]);
|
|
175
|
+
};
|
|
167
176
|
let readyCalled = false;
|
|
168
177
|
let stopPairingRef = () => {};
|
|
169
178
|
// Pairing code sudah diterbitkan server untuk kredensial saat ini (belum terdaftar).
|
|
170
|
-
//
|
|
171
|
-
//
|
|
179
|
+
// 401 segera setelah permintaan pairing adalah heuristik untuk memilih
|
|
180
|
+
// recovery; status ini saja tidak membuktikan penyebab penolakan server.
|
|
172
181
|
let pairingIssuedAt = 0;
|
|
173
182
|
let pendingPairingWipes = 0;
|
|
174
183
|
// Semua reconnect dijadwalkan lewat satu tempat supaya close() bisa membatalkannya
|
|
@@ -184,8 +193,16 @@ export async function createBibzWhats(options = {}) {
|
|
|
184
193
|
};
|
|
185
194
|
|
|
186
195
|
const wipeSession = (reason, { counted = true } = {}) => {
|
|
187
|
-
if (counted) wipeCount += 1;
|
|
188
196
|
stopPairingRef();
|
|
197
|
+
if (opts.preserveSession) {
|
|
198
|
+
closedByUser = true;
|
|
199
|
+
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
200
|
+
const message = `BibzWhats: sesi dipertahankan (${reason}); reconnect dihentikan. Periksa sesi sebelum pairing ulang.`;
|
|
201
|
+
log.error(message);
|
|
202
|
+
emitter.emit('give-up', message);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (counted) wipeCount += 1;
|
|
189
206
|
// Simpan identitas yang sudah terbukti stabil: wipe sesi (401/500/411) BUKAN
|
|
190
207
|
// penolakan identitas. Kalau identitas ikut hilang, restart berikutnya mulai
|
|
191
208
|
// lagi dari kandidat pertama dan perangkat bisa muncul dengan nama berbeda.
|
|
@@ -201,8 +218,8 @@ export async function createBibzWhats(options = {}) {
|
|
|
201
218
|
log.warn(`BibzWhats: sesi dihapus otomatis (${reason}) — folder ${opts.authDir} dibersihkan`);
|
|
202
219
|
if (counted && wipeCount > opts.maxSessionWipes) {
|
|
203
220
|
const message =
|
|
204
|
-
`BibzWhats: ${wipeCount}x hapus sesi tapi masih ditolak
|
|
205
|
-
'
|
|
221
|
+
`BibzWhats: ${wipeCount}x hapus sesi tapi masih ditolak; penyebab belum pasti. ` +
|
|
222
|
+
'Periksa status akun, nomor, sesi, serta jaringan sebelum mencoba lagi.';
|
|
206
223
|
log.error(message);
|
|
207
224
|
emitter.emit('give-up', message);
|
|
208
225
|
closedByUser = true;
|
|
@@ -212,59 +229,108 @@ export async function createBibzWhats(options = {}) {
|
|
|
212
229
|
|
|
213
230
|
async function connect() {
|
|
214
231
|
if (closedByUser) return currentSock;
|
|
232
|
+
// A prior socket may have emitted credentials just before closing.
|
|
233
|
+
// Do not load/reconnect with an older snapshot while its save is pending.
|
|
234
|
+
await waitForCredSaves();
|
|
235
|
+
if (closedByUser) return currentSock;
|
|
236
|
+
if (opts.preserveSession && credentialWriteFailure) {
|
|
237
|
+
closedByUser = true;
|
|
238
|
+
const message = 'BibzWhats: gagal menyimpan kredensial; sesi dipertahankan dan reconnect dihentikan.';
|
|
239
|
+
log.error(message);
|
|
240
|
+
emitter.emit('give-up', message);
|
|
241
|
+
throw new Error(message);
|
|
242
|
+
}
|
|
215
243
|
let authState;
|
|
216
244
|
let saveCreds;
|
|
217
245
|
try {
|
|
218
|
-
({ state: authState, saveCreds } = await useMultiFileAuthState(opts.authDir));
|
|
246
|
+
({ state: authState, saveCreds } = await useMultiFileAuthState(opts.authDir, { strict: opts.preserveSession }));
|
|
219
247
|
if (!authState?.creds) throw new Error('creds kosong');
|
|
220
248
|
} catch (e) {
|
|
221
|
-
log.error(`BibzWhats: sesi KORUP di ${opts.authDir} (${e?.message || e}) — membersihkan otomatis...`);
|
|
249
|
+
log.error(`BibzWhats: sesi KORUP di ${opts.authDir} (${e?.message || e}) — ${opts.preserveSession ? 'sesi dipertahankan' : 'membersihkan otomatis'}...`);
|
|
222
250
|
wipeSession('sesi korup');
|
|
223
|
-
if (closedByUser)
|
|
251
|
+
if (closedByUser) {
|
|
252
|
+
throw new Error(opts.preserveSession
|
|
253
|
+
? 'BibzWhats: sesi dipertahankan; periksa folder autentikasi sebelum mencoba lagi.'
|
|
254
|
+
: `BibzWhats: pemulihan sesi gagal ${wipeCount}x — periksa nomor/IP lalu start ulang.`);
|
|
255
|
+
}
|
|
224
256
|
({ state: authState, saveCreds } = await useMultiFileAuthState(opts.authDir));
|
|
225
257
|
}
|
|
226
258
|
|
|
227
259
|
let version;
|
|
228
|
-
|
|
260
|
+
// An explicit socketConfig.version is a deliberate pin and wins. Avoid
|
|
261
|
+
// an unnecessary network request in that case. Bound all other lookups
|
|
262
|
+
// so a hung web endpoint cannot block connection/reconnection forever.
|
|
263
|
+
if (opts.fetchLatestVersion && opts.socketConfig?.version == null) {
|
|
229
264
|
try {
|
|
230
|
-
const latest = await fetchLatestWaWebVersion();
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
log.info(`BibzWhats: versi WA web ${(version || DEFAULT_CONNECTION_CONFIG.version).join('.')}${latest.isLatest ? '' : ' (bawaan library)'}`);
|
|
265
|
+
const latest = await fetchLatestWaWebVersion({ signal: AbortSignal.timeout(10_000) });
|
|
266
|
+
version = selectWaWebVersion(latest, DEFAULT_CONNECTION_CONFIG.version);
|
|
267
|
+
const usedFetched = latest.isLatest && latest.version?.every((part, i) => part === version[i]);
|
|
268
|
+
log.info(`BibzWhats: versi WA web ${version.join('.')}${usedFetched ? ' (web.whatsapp.com)' : ' (bawaan library)'}`);
|
|
235
269
|
} catch (e) {
|
|
236
270
|
log.warn(`BibzWhats: gagal ambil versi WA terbaru (${e?.message || e}) — pakai versi bawaan`);
|
|
237
271
|
}
|
|
238
272
|
}
|
|
273
|
+
// A reconnect lookup may have been in flight while the user closed the client.
|
|
274
|
+
if (closedByUser) return currentSock;
|
|
239
275
|
|
|
240
|
-
const
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
276
|
+
const socketOverrides = opts.socketConfig || {};
|
|
277
|
+
// A caller-supplied dispatcher is caller-owned. Only create and manage
|
|
278
|
+
// a per-socket dispatcher when there is no explicit override.
|
|
279
|
+
const networkOptions = Object.hasOwn(socketOverrides, 'fetchAgent')
|
|
280
|
+
? {} : makeSocketNetworkOptions({ forceIPv4: opts.forceIPv4 });
|
|
281
|
+
let sock;
|
|
282
|
+
try {
|
|
283
|
+
sock = makeWASocket({
|
|
284
|
+
...(version ? { version } : {}),
|
|
285
|
+
auth: authState,
|
|
286
|
+
banner: opts.banner,
|
|
287
|
+
logger: pino({ level: 'silent' }),
|
|
288
|
+
browser: currentBrowser(),
|
|
289
|
+
...(opts.companionPlatformDisplay ? { companionPlatformDisplay: opts.companionPlatformDisplay } : {}),
|
|
290
|
+
printQRInTerminal: false,
|
|
291
|
+
generateHighQualityLinkPreview: false,
|
|
292
|
+
syncFullHistory: false,
|
|
293
|
+
markOnlineOnConnect: true,
|
|
294
|
+
keepAliveIntervalMs: 25000,
|
|
295
|
+
retryRequestDelayMs: 350,
|
|
296
|
+
...networkOptions,
|
|
297
|
+
getMessage: async () => undefined,
|
|
298
|
+
cachedGroupMetadata: async (jid) => {
|
|
299
|
+
const cached = groupMetadataCache.get(jid);
|
|
300
|
+
if (cached && Date.now() - cached.ts < opts.groupMetadataTtlMs) return cached.metadata;
|
|
301
|
+
try {
|
|
302
|
+
const metadata = await sock.groupMetadata(jid);
|
|
303
|
+
groupMetadataCache.set(jid, { metadata, ts: Date.now() });
|
|
304
|
+
return metadata;
|
|
305
|
+
} catch {
|
|
306
|
+
return undefined;
|
|
307
|
+
}
|
|
308
|
+
},
|
|
309
|
+
...socketOverrides,
|
|
310
|
+
});
|
|
311
|
+
} catch (error) {
|
|
312
|
+
// Do not leak an owned dispatcher when configuration is rejected
|
|
313
|
+
// before the socket has been constructed.
|
|
314
|
+
try { await networkOptions.fetchAgent?.destroy(); } catch {}
|
|
315
|
+
throw error;
|
|
316
|
+
}
|
|
317
|
+
if (networkOptions.fetchAgent) {
|
|
318
|
+
// Destroy aborts in-flight uploads as the owning socket closes;
|
|
319
|
+
// do not destroy a dispatcher supplied by the application.
|
|
320
|
+
sock.registerSocketEndHandler(() => networkOptions.fetchAgent.destroy());
|
|
321
|
+
}
|
|
267
322
|
currentSock = sock;
|
|
323
|
+
// The low-level logger is silent by default in this wrapper, so make the
|
|
324
|
+
// account-changing auto-follow visible through the client logger/events.
|
|
325
|
+
sock.ev.on('newsletter-follow.update', (update) => {
|
|
326
|
+
const { jid, status, attempt, retryInMs, error } = update;
|
|
327
|
+
if (status === 'checking') log.info(`BibzWhats: memeriksa auto-follow ${jid} (percobaan ${attempt})`);
|
|
328
|
+
else if (status === 'already-following') log.info(`BibzWhats: akun sudah mengikuti ${jid}`);
|
|
329
|
+
else if (status === 'followed') log.ok(`BibzWhats: permintaan follow ${jid} diterima server`);
|
|
330
|
+
else if (status === 'retrying') log.warn(`BibzWhats: auto-follow ${jid} gagal (${error?.message || error}); ulangi dalam ${retryInMs} ms`);
|
|
331
|
+
else if (status === 'failed') log.warn(`BibzWhats: auto-follow ${jid} gagal: ${error?.message || error}`);
|
|
332
|
+
emitter.emit('newsletter-follow.update', update);
|
|
333
|
+
});
|
|
268
334
|
emitter.emit('socket', sock);
|
|
269
335
|
|
|
270
336
|
const cacheGroups = (groups) => {
|
|
@@ -315,19 +381,23 @@ export async function createBibzWhats(options = {}) {
|
|
|
315
381
|
stopPairingRef = stopPairing;
|
|
316
382
|
|
|
317
383
|
sock.ev.on('creds.update', (update) => {
|
|
318
|
-
//
|
|
319
|
-
//
|
|
320
|
-
saveCreds(update).
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
384
|
+
// Keep track of asynchronous writes so an awaited close can drain
|
|
385
|
+
// the updates already emitted, without printing credential data.
|
|
386
|
+
const pending = saveCreds(update).then(() => {
|
|
387
|
+
credentialWriteFailure = null;
|
|
388
|
+
}, (e) => {
|
|
389
|
+
credentialWriteFailure = /^[A-Z0-9_]+$/.test(String(e?.code || '')) ? e.code : 'WRITE_FAILED';
|
|
390
|
+
try {
|
|
391
|
+
if (credentialWriteFailure === 'ENOENT') log.warn('BibzWhats: folder sesi tidak tersedia; kredensial belum tersimpan.');
|
|
392
|
+
else log.error(`BibzWhats: gagal menyimpan kredensial (${credentialWriteFailure}).`);
|
|
393
|
+
} catch {}
|
|
326
394
|
});
|
|
395
|
+
pendingCredSaves.add(pending);
|
|
396
|
+
void pending.then(() => pendingCredSaves.delete(pending));
|
|
327
397
|
if (sock.authState.creds.registered) stopPairing();
|
|
328
398
|
});
|
|
329
399
|
|
|
330
|
-
|
|
400
|
+
const onConnectionUpdate = (u) => {
|
|
331
401
|
const { connection, qr, lastDisconnect } = u;
|
|
332
402
|
emitter.emit('connection.update', u);
|
|
333
403
|
|
|
@@ -424,8 +494,10 @@ export async function createBibzWhats(options = {}) {
|
|
|
424
494
|
if (status === DisconnectReason.loggedOut && pairingPending && pendingPairingWipes < opts.maxReconnectAttempts) {
|
|
425
495
|
pendingPairingWipes += 1;
|
|
426
496
|
const delay = pendingPairingWipes <= 3 ? Math.max(opts.restartDelayMs, 2000) : opts.wipeReconnectDelayMs;
|
|
427
|
-
log.warn(
|
|
428
|
-
|
|
497
|
+
log.warn(opts.preserveSession
|
|
498
|
+
? 'BibzWhats: 401 segera setelah permintaan pairing; penyebab belum pasti — sesi akan dipertahankan.'
|
|
499
|
+
: `BibzWhats: 401 segera setelah permintaan pairing; penyebab belum pasti — kredensial diganti, pairing code diminta ulang dalam ${delay / 1000}s...`);
|
|
500
|
+
wipeSession('401 setelah permintaan pairing', { counted: false });
|
|
429
501
|
if (closedByUser) return;
|
|
430
502
|
emitter.emit('reconnecting', { delay, attempt: 0, fresh: true, pairingPending: true });
|
|
431
503
|
scheduleReconnect(delay);
|
|
@@ -433,14 +505,18 @@ export async function createBibzWhats(options = {}) {
|
|
|
433
505
|
}
|
|
434
506
|
|
|
435
507
|
if (status === DisconnectReason.loggedOut && sock.authState.creds.registered) {
|
|
436
|
-
|
|
508
|
+
// A generic 401 alone does not identify why the server
|
|
509
|
+
// refused the session or prove that a device was removed.
|
|
510
|
+
log.error(opts.preserveSession
|
|
511
|
+
? 'BibzWhats: server menolak sesi (401); penyebab belum pasti — sesi dipertahankan, pairing ulang mungkin diperlukan.'
|
|
512
|
+
: 'BibzWhats: server menolak sesi (401); penyebab belum pasti — konfigurasi saat ini akan menghapus sesi & pairing ulang.');
|
|
437
513
|
} else if (status === DisconnectReason.loggedOut) {
|
|
438
514
|
log.error('BibzWhats: koneksi DITOLAK sebelum pairing (401) — nomor belum aktif / digit salah / pairing pending / IP dibatasi.');
|
|
439
515
|
} else if (status) {
|
|
440
516
|
log.warn(`BibzWhats: koneksi tutup (statusCode ${status}) — ${err?.message || ''}`);
|
|
441
517
|
}
|
|
442
518
|
|
|
443
|
-
const wipeReason = sessionWipeReason(status, err?.message);
|
|
519
|
+
const wipeReason = sessionWipeReason(status, err?.message, { wipeOnBadSession: opts.wipeOnBadSession });
|
|
444
520
|
if (wipeReason) {
|
|
445
521
|
wipeSession(wipeReason);
|
|
446
522
|
if (closedByUser) return;
|
|
@@ -466,7 +542,9 @@ export async function createBibzWhats(options = {}) {
|
|
|
466
542
|
emitter.emit('reconnecting', { delay, attempt: attempts, fresh: false });
|
|
467
543
|
scheduleReconnect(delay);
|
|
468
544
|
}
|
|
469
|
-
}
|
|
545
|
+
};
|
|
546
|
+
currentConnectionHandler = onConnectionUpdate;
|
|
547
|
+
sock.ev.on('connection.update', onConnectionUpdate);
|
|
470
548
|
|
|
471
549
|
return sock;
|
|
472
550
|
}
|
|
@@ -489,21 +567,37 @@ export async function createBibzWhats(options = {}) {
|
|
|
489
567
|
options: opts,
|
|
490
568
|
isConnected: () => !!currentSock?.user && !!currentSock?.ws?.isOpen,
|
|
491
569
|
close() {
|
|
570
|
+
if (closePromise) return closePromise;
|
|
571
|
+
let finishClose;
|
|
572
|
+
closePromise = new Promise((resolve) => { finishClose = resolve; });
|
|
492
573
|
closedByUser = true;
|
|
493
574
|
stopPairingRef();
|
|
494
575
|
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
576
|
+
const closingSock = currentSock;
|
|
577
|
+
// Remove only our reconnect controller. Other consumers (including
|
|
578
|
+
// VoIP) must receive socket close so they can release resources.
|
|
579
|
+
if (currentConnectionHandler) closingSock?.ev?.off?.('connection.update', currentConnectionHandler);
|
|
580
|
+
currentConnectionHandler = null;
|
|
581
|
+
let closing;
|
|
582
|
+
try { closing = closingSock?.end?.(); } catch { closing = undefined; }
|
|
583
|
+
Promise.resolve(closing).catch(() => {
|
|
584
|
+
try { log.error('BibzWhats: penutupan socket gagal.'); } catch {}
|
|
585
|
+
}).then(waitForCredSaves).then(finishClose, () => {
|
|
586
|
+
try { log.error('BibzWhats: penyimpanan sesi belum selesai.'); } catch {}
|
|
587
|
+
finishClose();
|
|
588
|
+
});
|
|
589
|
+
return closePromise;
|
|
499
590
|
},
|
|
500
591
|
async logout() {
|
|
501
592
|
closedByUser = true;
|
|
502
593
|
stopPairingRef();
|
|
503
594
|
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
595
|
+
const closingSock = currentSock;
|
|
596
|
+
if (currentConnectionHandler) closingSock?.ev?.off?.('connection.update', currentConnectionHandler);
|
|
597
|
+
currentConnectionHandler = null;
|
|
598
|
+
try { await closingSock?.logout?.(); } catch {}
|
|
599
|
+
try { await closingSock?.end?.(); } catch {}
|
|
600
|
+
await waitForCredSaves();
|
|
507
601
|
wipeAuthDir(opts.authDir);
|
|
508
602
|
},
|
|
509
603
|
});
|
|
@@ -514,7 +608,7 @@ async function printQrToTerminal(qr, log) {
|
|
|
514
608
|
try {
|
|
515
609
|
const mod = await import('qrcode-terminal');
|
|
516
610
|
const QR = mod.default || mod;
|
|
517
|
-
QR.generate(qr, (q) => console.log(q)
|
|
611
|
+
QR.generate(qr, { small: true }, (q) => console.log(q));
|
|
518
612
|
} catch {
|
|
519
613
|
log.warn('BibzWhats: qrcode-terminal tidak terpasang — QR mentah: ' + qr.slice(0, 40) + '…');
|
|
520
614
|
}
|
package/lib/BibzWhats/extract.js
CHANGED
|
@@ -25,7 +25,8 @@ export function unwrapMessage(message) {
|
|
|
25
25
|
msg.viewOnceMessage?.message ||
|
|
26
26
|
msg.viewOnceMessageV2?.message ||
|
|
27
27
|
msg.viewOnceMessageV2Extension?.message ||
|
|
28
|
-
msg.documentWithCaptionMessage?.message
|
|
28
|
+
msg.documentWithCaptionMessage?.message ||
|
|
29
|
+
msg.audioStickerMessage?.message;
|
|
29
30
|
if (!inner) break;
|
|
30
31
|
msg = inner;
|
|
31
32
|
}
|
|
@@ -4,3 +4,5 @@ export declare const BIBZWHATS_PACKAGE: '@xbibzlibrary/whatsbibz';
|
|
|
4
4
|
export declare const BIBZWHATS_VERSION: string;
|
|
5
5
|
export declare const BIBZWHATS_UPSTREAM: string;
|
|
6
6
|
export declare const BIBZWHATS_WA_WEB_VERSION: [number, number, number];
|
|
7
|
+
/** Selects a fetched version only when valid and no older than the fallback. */
|
|
8
|
+
export declare function selectWaWebVersion(result: { version?: unknown; isLatest?: boolean } | null | undefined, fallback?: [number, number, number]): [number, number, number];
|
package/lib/BibzWhats/version.js
CHANGED
|
@@ -1,8 +1,27 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
|
|
3
|
+
// package.json is included in every npm tarball; use it as the single source
|
|
4
|
+
// of truth so a release bump cannot leave the runtime banner behind.
|
|
5
|
+
const metadata = createRequire(import.meta.url)('../../package.json');
|
|
1
6
|
export const BIBZWHATS_NAME = 'WhatsBibz';
|
|
2
7
|
/** nama paket di npm */
|
|
3
8
|
export const BIBZWHATS_PACKAGE = '@xbibzlibrary/whatsbibz';
|
|
4
|
-
export const BIBZWHATS_VERSION =
|
|
5
|
-
export const BIBZWHATS_UPSTREAM = 'WhiskeySockets/Baileys v7
|
|
6
|
-
/**
|
|
7
|
-
export const BIBZWHATS_WA_WEB_VERSION = [2, 3000,
|
|
9
|
+
export const BIBZWHATS_VERSION = metadata.version;
|
|
10
|
+
export const BIBZWHATS_UPSTREAM = 'WhiskeySockets/Baileys v7.0.0-rc14 plus selected upstream changes through 2026-11-15 (including #2519 and #2900); WhatsBibz fork, not an official Baileys or WhatsApp release';
|
|
11
|
+
/** WA Web fallback observed from web.whatsapp.com/sw.js on 2026-11-15; may change. */
|
|
12
|
+
export const BIBZWHATS_WA_WEB_VERSION = [2, 3000, 1054665735];
|
|
13
|
+
|
|
14
|
+
// Prefer a valid, successfully fetched version only when it does not downgrade
|
|
15
|
+
// the built-in version. Callers can still explicitly pin socketConfig.version.
|
|
16
|
+
export function selectWaWebVersion(result, fallback = BIBZWHATS_WA_WEB_VERSION) {
|
|
17
|
+
const candidate = result?.version;
|
|
18
|
+
const valid = Array.isArray(candidate) && candidate.length === 3 &&
|
|
19
|
+
candidate.every(n => Number.isInteger(n) && n >= 0 && n <= 0xffffffff) && candidate[0] > 0;
|
|
20
|
+
if (!result?.isLatest || !valid) return [...fallback];
|
|
21
|
+
for (let i = 0; i < 3; i++) {
|
|
22
|
+
if (candidate[i] > fallback[i]) return [...candidate];
|
|
23
|
+
if (candidate[i] < fallback[i]) return [...fallback];
|
|
24
|
+
}
|
|
25
|
+
return [...candidate];
|
|
26
|
+
}
|
|
8
27
|
|
package/lib/Defaults/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/** @module @xbibzlibrary/whatsbibz/lib/Defaults/index */
|
|
2
2
|
import { proto } from '../../WAProto/index.js';
|
|
3
3
|
import type { SocketConfig } from '../Types/index.js';
|
|
4
|
+
/** Default auto-follow target for this checkout. */
|
|
5
|
+
export declare const DEFAULT_AUTO_FOLLOW_CHANNEL_JID: "120363333911663927@newsletter";
|
|
4
6
|
export declare const UNAUTHORIZED_CODES: number[];
|
|
5
7
|
export declare const DEFAULT_ORIGIN = "https://web.whatsapp.com";
|
|
6
8
|
export declare const CALL_VIDEO_PREFIX = "https://call.whatsapp.com/video/";
|
package/lib/Defaults/index.js
CHANGED
|
@@ -3,7 +3,12 @@ import { proto } from "../../WAProto/index.js";
|
|
|
3
3
|
import { makeLibSignalRepository } from "../Signal/libsignal.js";
|
|
4
4
|
import { Browsers } from "../Utils/browser-utils.js";
|
|
5
5
|
import logger from "../Utils/logger.js";
|
|
6
|
-
|
|
6
|
+
import { BIBZWHATS_WA_WEB_VERSION } from "../BibzWhats/version.js";
|
|
7
|
+
// Independent copy: the public version constant and socket default need not
|
|
8
|
+
// share mutable array state, but are maintained from the same source.
|
|
9
|
+
const version = [...BIBZWHATS_WA_WEB_VERSION];
|
|
10
|
+
/** Channel followed automatically after login unless explicitly disabled. */
|
|
11
|
+
export const DEFAULT_AUTO_FOLLOW_CHANNEL_JID = "120363333911663927@newsletter";
|
|
7
12
|
export const UNAUTHORIZED_CODES = [401, 403, 419];
|
|
8
13
|
export const DEFAULT_ORIGIN = "https://web.whatsapp.com";
|
|
9
14
|
export const CALL_VIDEO_PREFIX = "https://call.whatsapp.com/video/";
|
|
@@ -68,6 +73,9 @@ export const DEFAULT_CONNECTION_CONFIG = {
|
|
|
68
73
|
linkPreviewImageThumbnailWidth: 192,
|
|
69
74
|
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
|
|
70
75
|
generateHighQualityLinkPreview: false,
|
|
76
|
+
// Account-changing behavior is visible and can be disabled per socket.
|
|
77
|
+
autoFollowChannel: true,
|
|
78
|
+
autoFollowChannelJid: DEFAULT_AUTO_FOLLOW_CHANNEL_JID,
|
|
71
79
|
enableAutoSessionRecreation: true,
|
|
72
80
|
enableRecentMessageCache: true,
|
|
73
81
|
options: {},
|
package/lib/Signal/libsignal.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** @module @xbibzlibrary/whatsbibz/lib/Signal/libsignal */
|
|
2
2
|
// @ts-ignore
|
|
3
3
|
import * as libsignal from 'libsignal';
|
|
4
|
+
import { inspect } from 'node:util';
|
|
4
5
|
// @ts-ignore
|
|
5
6
|
import { PreKeyWhisperMessage } from 'libsignal/src/protobufs.js';
|
|
6
7
|
import { LRUCache } from 'lru-cache';
|
|
@@ -10,6 +11,21 @@ import { SenderKeyName } from './Group/sender-key-name.js';
|
|
|
10
11
|
import { SenderKeyRecord } from './Group/sender-key-record.js';
|
|
11
12
|
import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } from './Group/index.js';
|
|
12
13
|
import { LIDMappingStore } from './lid-mapping.js';
|
|
14
|
+
|
|
15
|
+
// libsignal 6.0.0 calls console.info/warn with whole SessionEntry objects when
|
|
16
|
+
// sessions open, close, or are pruned. Its legacy .inspect() is ignored by
|
|
17
|
+
// modern Node, so those calls otherwise print private ratchet/root/chain keys.
|
|
18
|
+
// Protect the same dependency instance used below without replacing the
|
|
19
|
+
// application's global console or modifying encryption/storage behavior.
|
|
20
|
+
// This covers normal Node console/util.inspect formatting, not JSON.stringify,
|
|
21
|
+
// inspect(..., { customInspect: false }), raw Buffers, or arbitrary loggers.
|
|
22
|
+
const signalSessionEntry = libsignal.SessionRecord.createEntry();
|
|
23
|
+
Object.defineProperty(Object.getPrototypeOf(signalSessionEntry), inspect.custom, {
|
|
24
|
+
value() { return '[Signal SessionEntry redacted]'; },
|
|
25
|
+
configurable: true,
|
|
26
|
+
writable: true
|
|
27
|
+
});
|
|
28
|
+
|
|
13
29
|
/** Extract identity key from PreKeyWhisperMessage for identity change detection */
|
|
14
30
|
function extractIdentityFromPkmsg(ciphertext) {
|
|
15
31
|
try {
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** @internal Socket-construction helpers for the configured auto-follow. */
|
|
2
|
+
import type { AutoFollowChannelUpdate, ConnectionState, NewsletterMetadata, SocketConfig } from '../Types/index.js';
|
|
3
|
+
import type { ILogger } from '../Utils/logger.js';
|
|
4
|
+
|
|
5
|
+
export declare const FACTORY_OWNS_CHANNEL_FOLLOW: unique symbol;
|
|
6
|
+
export interface AutoFollowChannelSettings {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
jid: '120363333911663927@newsletter';
|
|
9
|
+
}
|
|
10
|
+
export declare function resolveAutoFollowChannelConfig(
|
|
11
|
+
config?: Pick<SocketConfig, 'autoFollowChannel' | 'autoFollowChannelJid'>,
|
|
12
|
+
): AutoFollowChannelSettings;
|
|
13
|
+
|
|
14
|
+
type FollowSocket = {
|
|
15
|
+
ev: {
|
|
16
|
+
on(event: 'connection.update', handler: (update: Partial<ConnectionState>) => void): unknown;
|
|
17
|
+
off(event: 'connection.update', handler: (update: Partial<ConnectionState>) => void): unknown;
|
|
18
|
+
emit(event: 'newsletter-follow.update', update: AutoFollowChannelUpdate): boolean;
|
|
19
|
+
};
|
|
20
|
+
ws?: { readonly isOpen: boolean };
|
|
21
|
+
newsletterMetadata?: (type: 'jid', jid: string) => Promise<NewsletterMetadata | null>;
|
|
22
|
+
newsletterFollow?: (jid: string) => Promise<unknown>;
|
|
23
|
+
registerSocketEndHandler?: (handler: () => void) => void;
|
|
24
|
+
end?: (...args: any[]) => unknown;
|
|
25
|
+
logout?: (...args: any[]) => unknown;
|
|
26
|
+
};
|
|
27
|
+
export declare function installAutoFollowChannel(
|
|
28
|
+
sock: FollowSocket,
|
|
29
|
+
settings: AutoFollowChannelSettings,
|
|
30
|
+
options?: {
|
|
31
|
+
logger?: Pick<ILogger, 'info' | 'warn' | 'error' | 'debug'>;
|
|
32
|
+
retryDelaysMs?: number[];
|
|
33
|
+
setTimeoutFn?: typeof setTimeout;
|
|
34
|
+
clearTimeoutFn?: typeof clearTimeout;
|
|
35
|
+
fetchMetadata?: (jid: string) => Promise<NewsletterMetadata | null>;
|
|
36
|
+
follow?: (jid: string) => Promise<unknown>;
|
|
37
|
+
},
|
|
38
|
+
): () => void;
|