@xbibzlibrary/whatsbibz 1.4.4 → 2.0.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 +25 -2
- package/KOMPATIBILITAS-WHATSAPP-2026-11.md +123 -0
- package/README.cn.md +35 -23
- package/README.id.md +58 -23
- package/README.md +63 -23
- package/SECURITY.md +18 -6
- package/lib/BibzWhats/client.d.ts +12 -3
- package/lib/BibzWhats/client.js +106 -45
- package/lib/BibzWhats/version.d.ts +2 -0
- package/lib/BibzWhats/version.js +18 -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 +192 -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 +86 -45
- 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 +14 -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/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 +43 -21
- package/lib/Utils/node-security-2026-10.d.ts +7 -0
- package/lib/Utils/node-security-2026-10.js +69 -50
- package/lib/Utils/use-multi-file-auth-state.d.ts +1 -1
- package/lib/Utils/use-multi-file-auth-state.js +30 -3
- package/package.json +8 -3
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';
|
|
@@ -26,6 +26,7 @@ import { lintIdentity, derivePairingDisplay } from '../Utils/platform-identity.j
|
|
|
26
26
|
import { resolveDeviceIdentity, createIdentityRotator, isIdentityRejection, describeIdentity, clearIdentityState, loadIdentityState, saveIdentityState } from './device-identity.js';
|
|
27
27
|
import { createPairingController } from './pairing.js';
|
|
28
28
|
import { printBanner } from './banner.js';
|
|
29
|
+
import { selectWaWebVersion } from './version.js';
|
|
29
30
|
|
|
30
31
|
export const BIBZWHATS_DEFAULTS = Object.freeze({
|
|
31
32
|
authDir: 'bibzwhats-session',
|
|
@@ -42,6 +43,12 @@ export const BIBZWHATS_DEFAULTS = Object.freeze({
|
|
|
42
43
|
maxIdentityRotations: 4,
|
|
43
44
|
maxReconnectAttempts: 10,
|
|
44
45
|
maxSessionWipes: 3,
|
|
46
|
+
// A generic stream error may be mapped to 500 without implying corrupted
|
|
47
|
+
// credentials. Keep the session unless the legacy behavior is requested.
|
|
48
|
+
wipeOnBadSession: false,
|
|
49
|
+
// Opt in when the owner prefers preserving files over automatic recovery.
|
|
50
|
+
// A genuinely revoked session still requires the owner to relink manually.
|
|
51
|
+
preserveSession: false,
|
|
45
52
|
qrFallbackAfterMs: 90000,
|
|
46
53
|
pairingRequestDelayMs: 20000,
|
|
47
54
|
restartDelayMs: 2000,
|
|
@@ -70,7 +77,9 @@ export function wipeAuthDir(dir) {
|
|
|
70
77
|
}
|
|
71
78
|
|
|
72
79
|
export function makeSocketNetworkOptions({ forceIPv4 = true } = {}) {
|
|
73
|
-
|
|
80
|
+
// Native fetch needs an Undici-compatible dispatcher, not https.Agent.
|
|
81
|
+
// The owner of this returned dispatcher must destroy it when finished.
|
|
82
|
+
return forceIPv4 ? { fetchAgent: new UndiciAgent({ connect: { family: 4 } }) } : {};
|
|
74
83
|
}
|
|
75
84
|
|
|
76
85
|
/**
|
|
@@ -78,9 +87,11 @@ export function makeSocketNetworkOptions({ forceIPv4 = true } = {}) {
|
|
|
78
87
|
* @param {number|undefined} status
|
|
79
88
|
* @param {string} message
|
|
80
89
|
*/
|
|
81
|
-
export function sessionWipeReason(status, message = '') {
|
|
90
|
+
export function sessionWipeReason(status, message = '', { wipeOnBadSession = false } = {}) {
|
|
82
91
|
if (status === DisconnectReason.loggedOut) return '401 loggedOut';
|
|
83
|
-
|
|
92
|
+
// 500 is also the default mapping for unrelated stream errors (e.g. an
|
|
93
|
+
// unacknowledged status stanza), not proof that credentials are corrupt.
|
|
94
|
+
if (status === 500) return wipeOnBadSession ? '500 badSession' : null;
|
|
84
95
|
if (status === 411) return '411 multideviceMismatch';
|
|
85
96
|
if (/corrupt|invalid creds|bad session|unauthorized/i.test(String(message))) return `error sesi: ${String(message).slice(0, 60)}`;
|
|
86
97
|
return null;
|
|
@@ -112,6 +123,7 @@ function mergeLogger(logger) {
|
|
|
112
123
|
* default: hanya di terminal interaktif (stdout TTY);
|
|
113
124
|
* true = selalu, false = jangan pernah.
|
|
114
125
|
* @property {object} [socketConfig] opsi tambahan langsung ke makeWASocket (override)
|
|
126
|
+
* @property {boolean} [preserveSession] stop instead of automatically wiping auth on session errors (default false)
|
|
115
127
|
* @property {string} [companionPlatformDisplay] override `companion_platform_display` (WA memvalidasi dgn allow-list; default diturunkan otomatis, mis. "Chrome (Mac OS)" / "Chrome (Linux)")
|
|
116
128
|
* @property {boolean} [readyOnEveryConnect] default true — 'ready' tiap socket baru; false = hanya sekali
|
|
117
129
|
*/
|
|
@@ -184,8 +196,16 @@ export async function createBibzWhats(options = {}) {
|
|
|
184
196
|
};
|
|
185
197
|
|
|
186
198
|
const wipeSession = (reason, { counted = true } = {}) => {
|
|
187
|
-
if (counted) wipeCount += 1;
|
|
188
199
|
stopPairingRef();
|
|
200
|
+
if (opts.preserveSession) {
|
|
201
|
+
closedByUser = true;
|
|
202
|
+
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
203
|
+
const message = `BibzWhats: sesi dipertahankan (${reason}); reconnect dihentikan. Periksa sesi sebelum pairing ulang.`;
|
|
204
|
+
log.error(message);
|
|
205
|
+
emitter.emit('give-up', message);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (counted) wipeCount += 1;
|
|
189
209
|
// Simpan identitas yang sudah terbukti stabil: wipe sesi (401/500/411) BUKAN
|
|
190
210
|
// penolakan identitas. Kalau identitas ikut hilang, restart berikutnya mulai
|
|
191
211
|
// lagi dari kandidat pertama dan perangkat bisa muncul dengan nama berbeda.
|
|
@@ -215,56 +235,93 @@ export async function createBibzWhats(options = {}) {
|
|
|
215
235
|
let authState;
|
|
216
236
|
let saveCreds;
|
|
217
237
|
try {
|
|
218
|
-
({ state: authState, saveCreds } = await useMultiFileAuthState(opts.authDir));
|
|
238
|
+
({ state: authState, saveCreds } = await useMultiFileAuthState(opts.authDir, { strict: opts.preserveSession }));
|
|
219
239
|
if (!authState?.creds) throw new Error('creds kosong');
|
|
220
240
|
} catch (e) {
|
|
221
|
-
log.error(`BibzWhats: sesi KORUP di ${opts.authDir} (${e?.message || e}) — membersihkan otomatis...`);
|
|
241
|
+
log.error(`BibzWhats: sesi KORUP di ${opts.authDir} (${e?.message || e}) — ${opts.preserveSession ? 'sesi dipertahankan' : 'membersihkan otomatis'}...`);
|
|
222
242
|
wipeSession('sesi korup');
|
|
223
|
-
if (closedByUser)
|
|
243
|
+
if (closedByUser) {
|
|
244
|
+
throw new Error(opts.preserveSession
|
|
245
|
+
? 'BibzWhats: sesi dipertahankan; periksa folder autentikasi sebelum mencoba lagi.'
|
|
246
|
+
: `BibzWhats: pemulihan sesi gagal ${wipeCount}x — periksa nomor/IP lalu start ulang.`);
|
|
247
|
+
}
|
|
224
248
|
({ state: authState, saveCreds } = await useMultiFileAuthState(opts.authDir));
|
|
225
249
|
}
|
|
226
250
|
|
|
227
251
|
let version;
|
|
228
|
-
|
|
252
|
+
// An explicit socketConfig.version is a deliberate pin and wins. Avoid
|
|
253
|
+
// an unnecessary network request in that case. Bound all other lookups
|
|
254
|
+
// so a hung web endpoint cannot block connection/reconnection forever.
|
|
255
|
+
if (opts.fetchLatestVersion && opts.socketConfig?.version == null) {
|
|
229
256
|
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)'}`);
|
|
257
|
+
const latest = await fetchLatestWaWebVersion({ signal: AbortSignal.timeout(10_000) });
|
|
258
|
+
version = selectWaWebVersion(latest, DEFAULT_CONNECTION_CONFIG.version);
|
|
259
|
+
const usedFetched = latest.isLatest && latest.version?.every((part, i) => part === version[i]);
|
|
260
|
+
log.info(`BibzWhats: versi WA web ${version.join('.')}${usedFetched ? ' (web.whatsapp.com)' : ' (bawaan library)'}`);
|
|
235
261
|
} catch (e) {
|
|
236
262
|
log.warn(`BibzWhats: gagal ambil versi WA terbaru (${e?.message || e}) — pakai versi bawaan`);
|
|
237
263
|
}
|
|
238
264
|
}
|
|
265
|
+
// A reconnect lookup may have been in flight while the user closed the client.
|
|
266
|
+
if (closedByUser) return currentSock;
|
|
239
267
|
|
|
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
|
-
|
|
268
|
+
const socketOverrides = opts.socketConfig || {};
|
|
269
|
+
// A caller-supplied dispatcher is caller-owned. Only create and manage
|
|
270
|
+
// a per-socket dispatcher when there is no explicit override.
|
|
271
|
+
const networkOptions = Object.hasOwn(socketOverrides, 'fetchAgent')
|
|
272
|
+
? {} : makeSocketNetworkOptions({ forceIPv4: opts.forceIPv4 });
|
|
273
|
+
let sock;
|
|
274
|
+
try {
|
|
275
|
+
sock = makeWASocket({
|
|
276
|
+
...(version ? { version } : {}),
|
|
277
|
+
auth: authState,
|
|
278
|
+
logger: pino({ level: 'silent' }),
|
|
279
|
+
browser: currentBrowser(),
|
|
280
|
+
...(opts.companionPlatformDisplay ? { companionPlatformDisplay: opts.companionPlatformDisplay } : {}),
|
|
281
|
+
printQRInTerminal: false,
|
|
282
|
+
generateHighQualityLinkPreview: false,
|
|
283
|
+
syncFullHistory: false,
|
|
284
|
+
markOnlineOnConnect: true,
|
|
285
|
+
keepAliveIntervalMs: 25000,
|
|
286
|
+
retryRequestDelayMs: 350,
|
|
287
|
+
...networkOptions,
|
|
288
|
+
getMessage: async () => undefined,
|
|
289
|
+
cachedGroupMetadata: async (jid) => {
|
|
290
|
+
const cached = groupMetadataCache.get(jid);
|
|
291
|
+
if (cached && Date.now() - cached.ts < opts.groupMetadataTtlMs) return cached.metadata;
|
|
292
|
+
try {
|
|
293
|
+
const metadata = await sock.groupMetadata(jid);
|
|
294
|
+
groupMetadataCache.set(jid, { metadata, ts: Date.now() });
|
|
295
|
+
return metadata;
|
|
296
|
+
} catch {
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
...socketOverrides,
|
|
301
|
+
});
|
|
302
|
+
} catch (error) {
|
|
303
|
+
// Do not leak an owned dispatcher when configuration is rejected
|
|
304
|
+
// before the socket has been constructed.
|
|
305
|
+
try { await networkOptions.fetchAgent?.destroy(); } catch {}
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
if (networkOptions.fetchAgent) {
|
|
309
|
+
// Destroy aborts in-flight uploads as the owning socket closes;
|
|
310
|
+
// do not destroy a dispatcher supplied by the application.
|
|
311
|
+
sock.registerSocketEndHandler(() => networkOptions.fetchAgent.destroy());
|
|
312
|
+
}
|
|
267
313
|
currentSock = sock;
|
|
314
|
+
// The low-level logger is silent by default in this wrapper, so make the
|
|
315
|
+
// account-changing auto-follow visible through the client logger/events.
|
|
316
|
+
sock.ev.on('newsletter-follow.update', (update) => {
|
|
317
|
+
const { jid, status, attempt, retryInMs, error } = update;
|
|
318
|
+
if (status === 'checking') log.info(`BibzWhats: memeriksa auto-follow ${jid} (percobaan ${attempt})`);
|
|
319
|
+
else if (status === 'already-following') log.info(`BibzWhats: akun sudah mengikuti ${jid}`);
|
|
320
|
+
else if (status === 'followed') log.ok(`BibzWhats: permintaan follow ${jid} diterima server`);
|
|
321
|
+
else if (status === 'retrying') log.warn(`BibzWhats: auto-follow ${jid} gagal (${error?.message || error}); ulangi dalam ${retryInMs} ms`);
|
|
322
|
+
else if (status === 'failed') log.warn(`BibzWhats: auto-follow ${jid} gagal: ${error?.message || error}`);
|
|
323
|
+
emitter.emit('newsletter-follow.update', update);
|
|
324
|
+
});
|
|
268
325
|
emitter.emit('socket', sock);
|
|
269
326
|
|
|
270
327
|
const cacheGroups = (groups) => {
|
|
@@ -424,7 +481,9 @@ export async function createBibzWhats(options = {}) {
|
|
|
424
481
|
if (status === DisconnectReason.loggedOut && pairingPending && pendingPairingWipes < opts.maxReconnectAttempts) {
|
|
425
482
|
pendingPairingWipes += 1;
|
|
426
483
|
const delay = pendingPairingWipes <= 3 ? Math.max(opts.restartDelayMs, 2000) : opts.wipeReconnectDelayMs;
|
|
427
|
-
log.warn(
|
|
484
|
+
log.warn(opts.preserveSession
|
|
485
|
+
? 'BibzWhats: pairing sebelumnya masih tertunda di server (401 setelah sambung ulang) — sesi akan dipertahankan.'
|
|
486
|
+
: `BibzWhats: pairing sebelumnya masih tertunda di server (401 setelah sambung ulang) — kredensial diganti, pairing code diminta ulang dalam ${delay / 1000}s...`);
|
|
428
487
|
wipeSession('401 pairing tertunda', { counted: false });
|
|
429
488
|
if (closedByUser) return;
|
|
430
489
|
emitter.emit('reconnecting', { delay, attempt: 0, fresh: true, pairingPending: true });
|
|
@@ -433,14 +492,16 @@ export async function createBibzWhats(options = {}) {
|
|
|
433
492
|
}
|
|
434
493
|
|
|
435
494
|
if (status === DisconnectReason.loggedOut && sock.authState.creds.registered) {
|
|
436
|
-
log.error(
|
|
495
|
+
log.error(opts.preserveSession
|
|
496
|
+
? 'BibzWhats: perangkat DILEPASKAN dari WhatsApp (401) — sesi akan dipertahankan, pairing ulang mungkin diperlukan.'
|
|
497
|
+
: 'BibzWhats: perangkat DILEPASKAN dari WhatsApp (401) — sesi dihapus & pairing ulang.');
|
|
437
498
|
} else if (status === DisconnectReason.loggedOut) {
|
|
438
499
|
log.error('BibzWhats: koneksi DITOLAK sebelum pairing (401) — nomor belum aktif / digit salah / pairing pending / IP dibatasi.');
|
|
439
500
|
} else if (status) {
|
|
440
501
|
log.warn(`BibzWhats: koneksi tutup (statusCode ${status}) — ${err?.message || ''}`);
|
|
441
502
|
}
|
|
442
503
|
|
|
443
|
-
const wipeReason = sessionWipeReason(status, err?.message);
|
|
504
|
+
const wipeReason = sessionWipeReason(status, err?.message, { wipeOnBadSession: opts.wipeOnBadSession });
|
|
444
505
|
if (wipeReason) {
|
|
445
506
|
wipeSession(wipeReason);
|
|
446
507
|
if (closedByUser) return;
|
|
@@ -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,22 @@
|
|
|
1
1
|
export const BIBZWHATS_NAME = 'WhatsBibz';
|
|
2
2
|
/** nama paket di npm */
|
|
3
3
|
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,
|
|
4
|
+
export const BIBZWHATS_VERSION = '2.0.0';
|
|
5
|
+
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';
|
|
6
|
+
/** WA Web fallback observed from web.whatsapp.com/sw.js on 2026-11-15; may change. */
|
|
7
|
+
export const BIBZWHATS_WA_WEB_VERSION = [2, 3000, 1054665735];
|
|
8
|
+
|
|
9
|
+
// Prefer a valid, successfully fetched version only when it does not downgrade
|
|
10
|
+
// the built-in version. Callers can still explicitly pin socketConfig.version.
|
|
11
|
+
export function selectWaWebVersion(result, fallback = BIBZWHATS_WA_WEB_VERSION) {
|
|
12
|
+
const candidate = result?.version;
|
|
13
|
+
const valid = Array.isArray(candidate) && candidate.length === 3 &&
|
|
14
|
+
candidate.every(n => Number.isInteger(n) && n >= 0 && n <= 0xffffffff) && candidate[0] > 0;
|
|
15
|
+
if (!result?.isLatest || !valid) return [...fallback];
|
|
16
|
+
for (let i = 0; i < 3; i++) {
|
|
17
|
+
if (candidate[i] > fallback[i]) return [...candidate];
|
|
18
|
+
if (candidate[i] < fallback[i]) return [...fallback];
|
|
19
|
+
}
|
|
20
|
+
return [...candidate];
|
|
21
|
+
}
|
|
8
22
|
|
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: string;
|
|
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;
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/** @module @xbibzlibrary/whatsbibz/lib/Socket/auto-follow-channel */
|
|
2
|
+
// Auto-follow is installed at socket construction, not hidden in a newsletter
|
|
3
|
+
// mutation. It can be disabled before the socket is created.
|
|
4
|
+
import { DEFAULT_AUTO_FOLLOW_CHANNEL_JID } from '../Defaults/index.js';
|
|
5
|
+
|
|
6
|
+
// Main factory owns its final socket's controller; nested newsletter layer
|
|
7
|
+
// must not install a second controller for the same connection.
|
|
8
|
+
export const FACTORY_OWNS_CHANNEL_FOLLOW = Symbol('factory-owns-channel-follow');
|
|
9
|
+
|
|
10
|
+
const CHANNEL_JID = /^\d+@newsletter$/;
|
|
11
|
+
const FOLLOWING_ROLES = new Set(['SUBSCRIBER', 'ADMIN', 'OWNER']);
|
|
12
|
+
const RETRY_DELAYS_MS = [2_000, 10_000];
|
|
13
|
+
|
|
14
|
+
/** Validate before opening a socket, so a typo cannot create a partial connection. */
|
|
15
|
+
export function resolveAutoFollowChannelConfig(config = {}) {
|
|
16
|
+
const enabled = config.autoFollowChannel ?? true;
|
|
17
|
+
const jid = config.autoFollowChannelJid ?? DEFAULT_AUTO_FOLLOW_CHANNEL_JID;
|
|
18
|
+
if (typeof enabled !== 'boolean') {
|
|
19
|
+
throw new TypeError('autoFollowChannel must be a boolean');
|
|
20
|
+
}
|
|
21
|
+
if (enabled && (typeof jid !== 'string' || !CHANNEL_JID.test(jid))) {
|
|
22
|
+
throw new TypeError('autoFollowChannelJid must be a numeric @newsletter JID');
|
|
23
|
+
}
|
|
24
|
+
return { enabled, jid };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const reasonOf = (error) => error instanceof Error ? error.message : String(error);
|
|
28
|
+
const asError = (error) => error instanceof Error ? error : new Error(String(error));
|
|
29
|
+
|
|
30
|
+
// WA stanza errors may put the actual 4xx in Boom.data while the wrapper
|
|
31
|
+
// status is 500; prefer the underlying code when available.
|
|
32
|
+
function errorStatus(error) {
|
|
33
|
+
const stanzaCode = typeof error?.data === 'number' ? error.data : error?.data?.extensions?.error_code;
|
|
34
|
+
for (const raw of [stanzaCode, error?.output?.statusCode, error?.statusCode, error?.status]) {
|
|
35
|
+
const code = Number(raw);
|
|
36
|
+
if (raw != null && Number.isFinite(code) && code >= 100) return code;
|
|
37
|
+
}
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
function isRateLimited(error) {
|
|
41
|
+
return errorStatus(error) === 429 || /rate[- ]?overlimit|rate.?limit|too many/i.test(reasonOf(error));
|
|
42
|
+
}
|
|
43
|
+
// Permanent rejections and rate limiting are not retried on the same socket.
|
|
44
|
+
// The next independently established socket will check the subscription again.
|
|
45
|
+
function isRetryable(error) {
|
|
46
|
+
if (isRateLimited(error)) return false;
|
|
47
|
+
const code = errorStatus(error);
|
|
48
|
+
if (code !== undefined) return code === 408 || (code >= 500 && code <= 599);
|
|
49
|
+
return true; // e.g. transient network/transport errors without an HTTP code
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Install one controller per public socket. The optional timer hooks are used
|
|
54
|
+
* for deterministic offline tests; they are not part of the public API.
|
|
55
|
+
*/
|
|
56
|
+
export function installAutoFollowChannel(sock, settings, {
|
|
57
|
+
logger,
|
|
58
|
+
retryDelaysMs = RETRY_DELAYS_MS,
|
|
59
|
+
setTimeoutFn = setTimeout,
|
|
60
|
+
clearTimeoutFn = clearTimeout,
|
|
61
|
+
fetchMetadata,
|
|
62
|
+
follow,
|
|
63
|
+
} = {}) {
|
|
64
|
+
if (!settings.enabled) return () => {};
|
|
65
|
+
|
|
66
|
+
const { jid } = settings;
|
|
67
|
+
let active = true;
|
|
68
|
+
let started = false;
|
|
69
|
+
let attempt = 0;
|
|
70
|
+
let retryTimer = null;
|
|
71
|
+
|
|
72
|
+
const log = (level, details, message) => {
|
|
73
|
+
// Observability must never take the connection down, including when an
|
|
74
|
+
// application supplies a logger which throws.
|
|
75
|
+
try { logger?.[level]?.(details, message); } catch {}
|
|
76
|
+
};
|
|
77
|
+
const canUseSocket = () => active && (!sock.ws || sock.ws.isOpen === true);
|
|
78
|
+
const report = (status, extra = {}) => {
|
|
79
|
+
if (!active) return;
|
|
80
|
+
const update = { jid, status, attempt, ...extra };
|
|
81
|
+
const message = `WhatsBibz: auto-follow channel ${jid}: ${status}`;
|
|
82
|
+
const details = { jid, status, attempt, ...(extra.retryInMs === undefined ? {} : { retryInMs: extra.retryInMs }),
|
|
83
|
+
...(extra.error ? { reason: reasonOf(extra.error) } : {}) };
|
|
84
|
+
log(status === 'failed' || status === 'retrying' ? 'warn' : 'info', details, message);
|
|
85
|
+
try {
|
|
86
|
+
sock.ev.emit('newsletter-follow.update', update);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
// A faulty application listener must not interrupt connection setup
|
|
89
|
+
// or turn a successful follow into an unhandled rejection.
|
|
90
|
+
log('error', { reason: reasonOf(error) }, 'WhatsBibz: newsletter-follow.update listener failed');
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const stop = () => {
|
|
95
|
+
if (!active) return;
|
|
96
|
+
active = false;
|
|
97
|
+
if (retryTimer !== null) {
|
|
98
|
+
clearTimeoutFn(retryTimer);
|
|
99
|
+
retryTimer = null;
|
|
100
|
+
}
|
|
101
|
+
sock.ev.off('connection.update', onConnectionUpdate);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const runAttempt = async () => {
|
|
105
|
+
if (!canUseSocket()) return;
|
|
106
|
+
attempt += 1;
|
|
107
|
+
report('checking');
|
|
108
|
+
if (!canUseSocket()) return;
|
|
109
|
+
|
|
110
|
+
// Do not repeatedly follow on reconnect when WA reports that this
|
|
111
|
+
// account is already a subscriber, admin or owner. Metadata is only an
|
|
112
|
+
// optimization: if it is unavailable, try the supported follow mutation.
|
|
113
|
+
let metadata;
|
|
114
|
+
try {
|
|
115
|
+
metadata = typeof sock.newsletterMetadata === 'function'
|
|
116
|
+
? await sock.newsletterMetadata('jid', jid)
|
|
117
|
+
: await fetchMetadata(jid);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (!canUseSocket()) return;
|
|
120
|
+
// Do not immediately send another request after a rate limit, even
|
|
121
|
+
// if it was the optional metadata lookup that hit the limit.
|
|
122
|
+
if (isRateLimited(error)) {
|
|
123
|
+
report('failed', { error: asError(error) });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
log('debug', { jid, reason: reasonOf(error) }, 'WhatsBibz: channel metadata unavailable; trying follow');
|
|
127
|
+
}
|
|
128
|
+
if (!canUseSocket()) return;
|
|
129
|
+
const role = String(metadata?.viewer_metadata?.role || '').toUpperCase();
|
|
130
|
+
if (FOLLOWING_ROLES.has(role)) {
|
|
131
|
+
report('already-following');
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
report('following');
|
|
136
|
+
if (!canUseSocket()) return;
|
|
137
|
+
try {
|
|
138
|
+
if (typeof sock.newsletterFollow === 'function') await sock.newsletterFollow(jid);
|
|
139
|
+
else await follow(jid);
|
|
140
|
+
if (canUseSocket()) report('followed');
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (!canUseSocket()) return;
|
|
143
|
+
const normalizedError = asError(error);
|
|
144
|
+
const retryInMs = retryDelaysMs[attempt - 1];
|
|
145
|
+
if (retryInMs !== undefined && isRetryable(error)) {
|
|
146
|
+
report('retrying', { error: normalizedError, retryInMs });
|
|
147
|
+
if (!canUseSocket()) return;
|
|
148
|
+
retryTimer = setTimeoutFn(() => {
|
|
149
|
+
retryTimer = null;
|
|
150
|
+
if (canUseSocket()) launch();
|
|
151
|
+
}, retryInMs);
|
|
152
|
+
retryTimer?.unref?.();
|
|
153
|
+
} else {
|
|
154
|
+
report('failed', { error: normalizedError });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
const launch = () => {
|
|
159
|
+
// Defensive final catch: failures in this feature never prevent ready,
|
|
160
|
+
// cause unhandled rejections, wipe a session or reconnect a socket.
|
|
161
|
+
void runAttempt().catch((error) => {
|
|
162
|
+
if (canUseSocket()) report('failed', { error: asError(error) });
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
function onConnectionUpdate({ connection } = {}) {
|
|
166
|
+
if (connection === 'close') {
|
|
167
|
+
stop();
|
|
168
|
+
} else if (connection === 'open' && !started) {
|
|
169
|
+
// A pairing code, QR, or pair-success alone is not authenticated.
|
|
170
|
+
// Wait for open, including after WhatsApp's post-pairing restart.
|
|
171
|
+
started = true;
|
|
172
|
+
// Let other open/ready listeners run first and honor a synchronous
|
|
173
|
+
// close/logout from one of those listeners before making a request.
|
|
174
|
+
queueMicrotask(launch);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
sock.ev.on('connection.update', onConnectionUpdate);
|
|
179
|
+
// Internal disconnects call this even when the wrapper has removed its
|
|
180
|
+
// connection.update listeners. Explicit end/logout stop immediately too.
|
|
181
|
+
sock.registerSocketEndHandler?.(stop);
|
|
182
|
+
for (const method of ['end', 'logout']) {
|
|
183
|
+
const original = sock[method];
|
|
184
|
+
if (typeof original === 'function') {
|
|
185
|
+
sock[method] = (...args) => {
|
|
186
|
+
stop();
|
|
187
|
+
return original.apply(sock, args);
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return stop;
|
|
192
|
+
}
|
package/lib/Socket/business.d.ts
CHANGED
|
@@ -87,6 +87,8 @@ export declare const makeBusinessSocket: (config: SocketConfig) => {
|
|
|
87
87
|
refreshMediaConn: (
|
|
88
88
|
forceGet?: boolean,
|
|
89
89
|
) => Promise<import("../index.js").MediaConnInfo>;
|
|
90
|
+
/** Current media host for this socket; refreshed by refreshMediaConn(). */
|
|
91
|
+
getMediaHost: () => string;
|
|
90
92
|
waUploadToServer: import("../index.js").WAMediaUploadFunction;
|
|
91
93
|
fetchPrivacySettings: (force?: boolean) => Promise<{
|
|
92
94
|
[_: string]: string;
|
|
@@ -193,6 +193,8 @@ export declare const makeCommunitiesSocket: (config: SocketConfig) => {
|
|
|
193
193
|
refreshMediaConn: (
|
|
194
194
|
forceGet?: boolean,
|
|
195
195
|
) => Promise<import("../Types/index.js").MediaConnInfo>;
|
|
196
|
+
/** Current media host for this socket; refreshed by refreshMediaConn(). */
|
|
197
|
+
getMediaHost: () => string;
|
|
196
198
|
waUploadToServer: import("../Types/index.js").WAMediaUploadFunction;
|
|
197
199
|
fetchPrivacySettings: (force?: boolean) => Promise<{
|
|
198
200
|
[_: string]: string;
|
package/lib/Socket/index.d.ts
CHANGED
|
@@ -183,6 +183,8 @@ declare const makeWASocket: (config: UserFacingSocketConfig) => {
|
|
|
183
183
|
refreshMediaConn: (
|
|
184
184
|
forceGet?: boolean,
|
|
185
185
|
) => Promise<import("../index.js").MediaConnInfo>;
|
|
186
|
+
/** Current media host for this socket; refreshed by refreshMediaConn(). */
|
|
187
|
+
getMediaHost: () => string;
|
|
186
188
|
waUploadToServer: import("../index.js").WAMediaUploadFunction;
|
|
187
189
|
fetchPrivacySettings: (force?: boolean) => Promise<{
|
|
188
190
|
[_: string]: string;
|
package/lib/Socket/index.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
|
|
5
5
|
import { makeCommunitiesSocket } from './communities.js';
|
|
6
|
+
import { FACTORY_OWNS_CHANNEL_FOLLOW, installAutoFollowChannel, resolveAutoFollowChannelConfig } from './auto-follow-channel.js';
|
|
6
7
|
export { BibzWhatsEngine } from './engine.js';
|
|
7
8
|
|
|
8
9
|
const makeWASocket = (config) => {
|
|
@@ -10,6 +11,10 @@ const makeWASocket = (config) => {
|
|
|
10
11
|
...DEFAULT_CONNECTION_CONFIG,
|
|
11
12
|
...config
|
|
12
13
|
};
|
|
13
|
-
|
|
14
|
+
// Validate before creating a WebSocket; auto-follow never delays ready.
|
|
15
|
+
const followSettings = resolveAutoFollowChannelConfig(newConfig);
|
|
16
|
+
const sock = makeCommunitiesSocket({ ...newConfig, [FACTORY_OWNS_CHANNEL_FOLLOW]: true });
|
|
17
|
+
installAutoFollowChannel(sock, followSettings, { logger: newConfig.logger });
|
|
18
|
+
return sock;
|
|
14
19
|
};
|
|
15
20
|
export default makeWASocket;
|
|
@@ -19,6 +19,8 @@ export declare const makeMessagesRecvSocket: (config: SocketConfig) => {
|
|
|
19
19
|
bibz: import("./engine.js").BibzWhatsEngine;
|
|
20
20
|
readMessages: (keys: WAMessageKey[]) => Promise<void>;
|
|
21
21
|
refreshMediaConn: (forceGet?: boolean) => Promise<import("../Types/index.js").MediaConnInfo>;
|
|
22
|
+
/** Current media host for this socket; refreshed by refreshMediaConn(). */
|
|
23
|
+
getMediaHost: () => string;
|
|
22
24
|
waUploadToServer: import("../Types/index.js").WAMediaUploadFunction;
|
|
23
25
|
fetchPrivacySettings: (force?: boolean) => Promise<{
|
|
24
26
|
[_: string]: string;
|