@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
|
@@ -0,0 +1,198 @@
|
|
|
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 FOLLOWING_ROLES = new Set(['SUBSCRIBER', 'ADMIN', 'OWNER']);
|
|
11
|
+
const RETRY_DELAYS_MS = [2_000, 10_000];
|
|
12
|
+
|
|
13
|
+
/** Validate before opening a socket, so a typo cannot create a partial connection. */
|
|
14
|
+
export function resolveAutoFollowChannelConfig(config = {}) {
|
|
15
|
+
const enabled = config.autoFollowChannel ?? true;
|
|
16
|
+
const jid = config.autoFollowChannelJid ?? DEFAULT_AUTO_FOLLOW_CHANNEL_JID;
|
|
17
|
+
if (typeof enabled !== 'boolean') {
|
|
18
|
+
throw new TypeError('autoFollowChannel must be a boolean');
|
|
19
|
+
}
|
|
20
|
+
// Never silently redirect an automatic account-changing action. Explicit
|
|
21
|
+
// manual newsletter APIs are separate and are not invoked here.
|
|
22
|
+
if (jid !== DEFAULT_AUTO_FOLLOW_CHANNEL_JID) {
|
|
23
|
+
throw new TypeError(`autoFollowChannelJid is fixed to ${DEFAULT_AUTO_FOLLOW_CHANNEL_JID}`);
|
|
24
|
+
}
|
|
25
|
+
return { enabled, jid: DEFAULT_AUTO_FOLLOW_CHANNEL_JID };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const reasonOf = (error) => error instanceof Error ? error.message : String(error);
|
|
29
|
+
const asError = (error) => error instanceof Error ? error : new Error(String(error));
|
|
30
|
+
|
|
31
|
+
// WA stanza errors may put the actual 4xx in Boom.data while the wrapper
|
|
32
|
+
// status is 500; prefer the underlying code when available.
|
|
33
|
+
function errorStatus(error) {
|
|
34
|
+
const stanzaCode = typeof error?.data === 'number' ? error.data : error?.data?.extensions?.error_code;
|
|
35
|
+
for (const raw of [stanzaCode, error?.output?.statusCode, error?.statusCode, error?.status]) {
|
|
36
|
+
const code = Number(raw);
|
|
37
|
+
if (raw != null && Number.isFinite(code) && code >= 100) return code;
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
function isRateLimited(error) {
|
|
42
|
+
return errorStatus(error) === 429 || /rate[- ]?overlimit|rate.?limit|too many/i.test(reasonOf(error));
|
|
43
|
+
}
|
|
44
|
+
// Permanent rejections and rate limiting are not retried on the same socket.
|
|
45
|
+
// The next independently established socket will check the subscription again.
|
|
46
|
+
function isRetryable(error) {
|
|
47
|
+
if (isRateLimited(error)) return false;
|
|
48
|
+
const code = errorStatus(error);
|
|
49
|
+
if (code !== undefined) return code === 408 || (code >= 500 && code <= 599);
|
|
50
|
+
return true; // e.g. transient network/transport errors without an HTTP code
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Install one controller per public socket. The optional timer hooks are used
|
|
55
|
+
* for deterministic offline tests; they are not part of the public API.
|
|
56
|
+
*/
|
|
57
|
+
export function installAutoFollowChannel(sock, settings, {
|
|
58
|
+
logger,
|
|
59
|
+
retryDelaysMs = RETRY_DELAYS_MS,
|
|
60
|
+
setTimeoutFn = setTimeout,
|
|
61
|
+
clearTimeoutFn = clearTimeout,
|
|
62
|
+
fetchMetadata,
|
|
63
|
+
follow,
|
|
64
|
+
} = {}) {
|
|
65
|
+
// Defence in depth: this module can also be imported directly, bypassing
|
|
66
|
+
// the socket factory. Validate before installing any listener or timer.
|
|
67
|
+
if (!settings || typeof settings.enabled !== 'boolean' || settings.jid !== DEFAULT_AUTO_FOLLOW_CHANNEL_JID) {
|
|
68
|
+
throw new TypeError(`auto-follow settings must use ${DEFAULT_AUTO_FOLLOW_CHANNEL_JID}`);
|
|
69
|
+
}
|
|
70
|
+
if (!settings.enabled) return () => {};
|
|
71
|
+
|
|
72
|
+
const jid = DEFAULT_AUTO_FOLLOW_CHANNEL_JID;
|
|
73
|
+
let active = true;
|
|
74
|
+
let started = false;
|
|
75
|
+
let attempt = 0;
|
|
76
|
+
let retryTimer = null;
|
|
77
|
+
|
|
78
|
+
const log = (level, details, message) => {
|
|
79
|
+
// Observability must never take the connection down, including when an
|
|
80
|
+
// application supplies a logger which throws.
|
|
81
|
+
try { logger?.[level]?.(details, message); } catch {}
|
|
82
|
+
};
|
|
83
|
+
const canUseSocket = () => active && (!sock.ws || sock.ws.isOpen === true);
|
|
84
|
+
const report = (status, extra = {}) => {
|
|
85
|
+
if (!active) return;
|
|
86
|
+
const update = { jid, status, attempt, ...extra };
|
|
87
|
+
const message = `WhatsBibz: auto-follow channel ${jid}: ${status}`;
|
|
88
|
+
const details = { jid, status, attempt, ...(extra.retryInMs === undefined ? {} : { retryInMs: extra.retryInMs }),
|
|
89
|
+
...(extra.error ? { reason: reasonOf(extra.error) } : {}) };
|
|
90
|
+
log(status === 'failed' || status === 'retrying' ? 'warn' : 'info', details, message);
|
|
91
|
+
try {
|
|
92
|
+
sock.ev.emit('newsletter-follow.update', update);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
// A faulty application listener must not interrupt connection setup
|
|
95
|
+
// or turn a successful follow into an unhandled rejection.
|
|
96
|
+
log('error', { reason: reasonOf(error) }, 'WhatsBibz: newsletter-follow.update listener failed');
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const stop = () => {
|
|
101
|
+
if (!active) return;
|
|
102
|
+
active = false;
|
|
103
|
+
if (retryTimer !== null) {
|
|
104
|
+
clearTimeoutFn(retryTimer);
|
|
105
|
+
retryTimer = null;
|
|
106
|
+
}
|
|
107
|
+
sock.ev.off('connection.update', onConnectionUpdate);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const runAttempt = async () => {
|
|
111
|
+
if (!canUseSocket()) return;
|
|
112
|
+
attempt += 1;
|
|
113
|
+
report('checking');
|
|
114
|
+
if (!canUseSocket()) return;
|
|
115
|
+
|
|
116
|
+
// Do not repeatedly follow on reconnect when WA reports that this
|
|
117
|
+
// account is already a subscriber, admin or owner. Metadata is only an
|
|
118
|
+
// optimization: if it is unavailable, try the supported follow mutation.
|
|
119
|
+
let metadata;
|
|
120
|
+
try {
|
|
121
|
+
metadata = typeof sock.newsletterMetadata === 'function'
|
|
122
|
+
? await sock.newsletterMetadata('jid', jid)
|
|
123
|
+
: await fetchMetadata(jid);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (!canUseSocket()) return;
|
|
126
|
+
// Do not immediately send another request after a rate limit, even
|
|
127
|
+
// if it was the optional metadata lookup that hit the limit.
|
|
128
|
+
if (isRateLimited(error)) {
|
|
129
|
+
report('failed', { error: asError(error) });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
log('debug', { jid, reason: reasonOf(error) }, 'WhatsBibz: channel metadata unavailable; trying follow');
|
|
133
|
+
}
|
|
134
|
+
if (!canUseSocket()) return;
|
|
135
|
+
const role = String(metadata?.viewer_metadata?.role || '').toUpperCase();
|
|
136
|
+
if (FOLLOWING_ROLES.has(role)) {
|
|
137
|
+
report('already-following');
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
report('following');
|
|
142
|
+
if (!canUseSocket()) return;
|
|
143
|
+
try {
|
|
144
|
+
if (typeof sock.newsletterFollow === 'function') await sock.newsletterFollow(jid);
|
|
145
|
+
else await follow(jid);
|
|
146
|
+
if (canUseSocket()) report('followed');
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (!canUseSocket()) return;
|
|
149
|
+
const normalizedError = asError(error);
|
|
150
|
+
const retryInMs = retryDelaysMs[attempt - 1];
|
|
151
|
+
if (retryInMs !== undefined && isRetryable(error)) {
|
|
152
|
+
report('retrying', { error: normalizedError, retryInMs });
|
|
153
|
+
if (!canUseSocket()) return;
|
|
154
|
+
retryTimer = setTimeoutFn(() => {
|
|
155
|
+
retryTimer = null;
|
|
156
|
+
if (canUseSocket()) launch();
|
|
157
|
+
}, retryInMs);
|
|
158
|
+
retryTimer?.unref?.();
|
|
159
|
+
} else {
|
|
160
|
+
report('failed', { error: normalizedError });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
const launch = () => {
|
|
165
|
+
// Defensive final catch: failures in this feature never prevent ready,
|
|
166
|
+
// cause unhandled rejections, wipe a session or reconnect a socket.
|
|
167
|
+
void runAttempt().catch((error) => {
|
|
168
|
+
if (canUseSocket()) report('failed', { error: asError(error) });
|
|
169
|
+
});
|
|
170
|
+
};
|
|
171
|
+
function onConnectionUpdate({ connection } = {}) {
|
|
172
|
+
if (connection === 'close') {
|
|
173
|
+
stop();
|
|
174
|
+
} else if (connection === 'open' && !started) {
|
|
175
|
+
// A pairing code, QR, or pair-success alone is not authenticated.
|
|
176
|
+
// Wait for open, including after WhatsApp's post-pairing restart.
|
|
177
|
+
started = true;
|
|
178
|
+
// Let other open/ready listeners run first and honor a synchronous
|
|
179
|
+
// close/logout from one of those listeners before making a request.
|
|
180
|
+
queueMicrotask(launch);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
sock.ev.on('connection.update', onConnectionUpdate);
|
|
185
|
+
// Internal disconnects call this even when the wrapper has removed its
|
|
186
|
+
// connection.update listeners. Explicit end/logout stop immediately too.
|
|
187
|
+
sock.registerSocketEndHandler?.(stop);
|
|
188
|
+
for (const method of ['end', 'logout']) {
|
|
189
|
+
const original = sock[method];
|
|
190
|
+
if (typeof original === 'function') {
|
|
191
|
+
sock[method] = (...args) => {
|
|
192
|
+
stop();
|
|
193
|
+
return original.apply(sock, args);
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return stop;
|
|
198
|
+
}
|
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;
|
|
@@ -377,16 +377,28 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
377
377
|
logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
|
|
378
378
|
}, authState?.creds?.me?.id || 'sendRetryRequest');
|
|
379
379
|
};
|
|
380
|
+
// Ignore the same PreKeyLow notification while it is still in flight.
|
|
381
|
+
const inFlightPreKeyLow = new Set();
|
|
382
|
+
sock.registerSocketEndHandler(() => {
|
|
383
|
+
if (!config.msgRetryCounterCache) msgRetryCache.close?.();
|
|
384
|
+
if (!config.callOfferCache) callOfferCache.close?.();
|
|
385
|
+
if (!config.placeholderResendCache) placeholderResendCache.close?.();
|
|
386
|
+
identityAssertDebounce.close?.();
|
|
387
|
+
inFlightPreKeyLow.clear();
|
|
388
|
+
});
|
|
380
389
|
const handleEncryptNotification = async (node) => {
|
|
381
390
|
const from = node.attrs.from;
|
|
382
391
|
if (from === S_WHATSAPP_NET) {
|
|
383
392
|
const countChild = getBinaryNodeChild(node, 'count');
|
|
384
|
-
const
|
|
393
|
+
const rawCount = countChild?.attrs?.value;
|
|
394
|
+
const count = Number(rawCount);
|
|
395
|
+
if (rawCount == null || String(rawCount).trim() === '' || !Number.isSafeInteger(count) || count < 0) {
|
|
396
|
+
logger.warn({ node }, 'invalid pre-key count notification');
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
385
399
|
const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
|
|
386
400
|
logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
|
|
387
|
-
if (shouldUploadMorePreKeys)
|
|
388
|
-
await uploadPreKeys();
|
|
389
|
-
}
|
|
401
|
+
if (shouldUploadMorePreKeys) await uploadPreKeys();
|
|
390
402
|
}
|
|
391
403
|
else {
|
|
392
404
|
const result = await handleIdentityChange(node, {
|
|
@@ -894,6 +906,14 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
894
906
|
await sendMessageAck(node);
|
|
895
907
|
return;
|
|
896
908
|
}
|
|
909
|
+
// Mark before entering the notification mutex, otherwise a duplicate
|
|
910
|
+
// can sit in the queue until after the first upload has completed.
|
|
911
|
+
const preKeyLowId = node.attrs.type === 'encrypt' && remoteJid === S_WHATSAPP_NET ? node.attrs.id : undefined;
|
|
912
|
+
if (preKeyLowId && inFlightPreKeyLow.has(preKeyLowId)) {
|
|
913
|
+
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack duplicate notification'));
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
if (preKeyLowId) inFlightPreKeyLow.add(preKeyLowId);
|
|
897
917
|
try {
|
|
898
918
|
await Promise.all([
|
|
899
919
|
notificationMutex.mutex(async () => {
|
|
@@ -919,7 +939,12 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
919
939
|
]);
|
|
920
940
|
}
|
|
921
941
|
finally {
|
|
922
|
-
|
|
942
|
+
try {
|
|
943
|
+
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
|
|
944
|
+
}
|
|
945
|
+
finally {
|
|
946
|
+
if (preKeyLowId) inFlightPreKeyLow.delete(preKeyLowId);
|
|
947
|
+
}
|
|
923
948
|
}
|
|
924
949
|
};
|
|
925
950
|
const handleMessage = async (node) => {
|
|
@@ -1036,29 +1061,16 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1036
1061
|
return sendMessageAck(node);
|
|
1037
1062
|
}
|
|
1038
1063
|
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
//
|
|
1064
|
+
logger.debug('[handleMessage] Attempting retry request for failed decryption');
|
|
1065
|
+
// As in WA Web/upstream #2432, send a retry receipt;
|
|
1066
|
+
// low pre-key counts are handled by server notifications.
|
|
1067
|
+
// Eagerly uploading on every decrypt error causes storms.
|
|
1043
1068
|
await retryMutex.mutex(async () => {
|
|
1044
1069
|
try {
|
|
1045
1070
|
if (!ws.isOpen) {
|
|
1046
1071
|
logger.debug({ node }, 'Connection closed, skipping retry');
|
|
1047
1072
|
return;
|
|
1048
1073
|
}
|
|
1049
|
-
// Handle pre-key errors with upload and delay
|
|
1050
|
-
if (isPreKeyError) {
|
|
1051
|
-
logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
|
|
1052
|
-
try {
|
|
1053
|
-
logger.debug('Uploading pre-keys for error recovery');
|
|
1054
|
-
await uploadPreKeys(5);
|
|
1055
|
-
logger.debug('Waiting for server to process new pre-keys');
|
|
1056
|
-
await delay(1000);
|
|
1057
|
-
}
|
|
1058
|
-
catch (uploadErr) {
|
|
1059
|
-
logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
|
|
1060
|
-
}
|
|
1061
|
-
}
|
|
1062
1074
|
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1063
1075
|
await sendRetryRequest(node, !encNode);
|
|
1064
1076
|
if (retryRequestDelayMs) {
|
|
@@ -1066,15 +1078,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1066
1078
|
}
|
|
1067
1079
|
}
|
|
1068
1080
|
catch (err) {
|
|
1069
|
-
logger.error({ err
|
|
1070
|
-
// Still attempt retry even if pre-key upload failed
|
|
1071
|
-
try {
|
|
1072
|
-
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1073
|
-
await sendRetryRequest(node, !encNode);
|
|
1074
|
-
}
|
|
1075
|
-
catch (retryErr) {
|
|
1076
|
-
logger.error({ retryErr }, 'Failed to send retry after error handling');
|
|
1077
|
-
}
|
|
1081
|
+
logger.error({ err }, 'Failed to send retry');
|
|
1078
1082
|
}
|
|
1079
1083
|
acked = true;
|
|
1080
1084
|
await sendMessageAck(node, NACK_REASONS.UnhandledError);
|
|
@@ -63,6 +63,8 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
|
|
|
63
63
|
bibz: BibzWhatsEngine;
|
|
64
64
|
readMessages: (keys: WAMessageKey[]) => Promise<void>;
|
|
65
65
|
refreshMediaConn: (forceGet?: boolean) => Promise<MediaConnInfo>;
|
|
66
|
+
/** Current media host for this socket; refreshed by refreshMediaConn(). */
|
|
67
|
+
getMediaHost: () => string;
|
|
66
68
|
waUploadToServer: import("../Types/index.js").WAMediaUploadFunction;
|
|
67
69
|
fetchPrivacySettings: (force?: boolean) => Promise<{
|
|
68
70
|
[_: string]: string;
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
assertMediaContent,
|
|
9
9
|
bindWaitForEvent,
|
|
10
10
|
decryptMediaRetryData,
|
|
11
|
+
DEF_MEDIA_HOST,
|
|
11
12
|
encodeNewsletterMessage,
|
|
12
13
|
encodeSignedDeviceIdentity,
|
|
13
14
|
encodeWAMessage,
|
|
@@ -166,10 +167,8 @@ export const makeMessagesSocket = (config) => {
|
|
|
166
167
|
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
|
167
168
|
useClones: false,
|
|
168
169
|
});
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
useClones: false,
|
|
172
|
-
});
|
|
170
|
+
// Do not cache session existence independently of Signal's actual store.
|
|
171
|
+
// Sessions can be removed/replaced after identity changes or retries (#2432).
|
|
173
172
|
// Initialize message retry manager if enabled
|
|
174
173
|
const messageRetryManager = enableRecentMessageCache
|
|
175
174
|
? new MessageRetryManager(logger, maxMsgRetryCount)
|
|
@@ -177,41 +176,54 @@ export const makeMessagesSocket = (config) => {
|
|
|
177
176
|
// Prevent race conditions in Signal session encryption by user
|
|
178
177
|
const encryptionMutex = makeKeyedMutex();
|
|
179
178
|
let mediaConn;
|
|
179
|
+
// Media hosts are tied to a socket/account, never shared across accounts.
|
|
180
|
+
let mediaHost = DEF_MEDIA_HOST;
|
|
181
|
+
sock.registerSocketEndHandler(() => {
|
|
182
|
+
if (!config.userDevicesCache) userDevicesCache.close?.();
|
|
183
|
+
messageRetryManager?.destroy();
|
|
184
|
+
mediaConn = undefined;
|
|
185
|
+
});
|
|
180
186
|
const refreshMediaConn = async (forceGet = false) => {
|
|
181
|
-
const
|
|
182
|
-
if (
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
187
|
+
const previous = mediaConn;
|
|
188
|
+
if (!forceGet && previous) {
|
|
189
|
+
try {
|
|
190
|
+
const cached = await previous;
|
|
191
|
+
if (Date.now() - cached.fetchDate.getTime() <= cached.ttl * 1000) return cached;
|
|
192
|
+
} catch {
|
|
193
|
+
// A failed lookup must not poison all subsequent attempts.
|
|
194
|
+
}
|
|
195
|
+
// Another caller may already have started a fresh lookup while we waited.
|
|
196
|
+
if (mediaConn && mediaConn !== previous) return mediaConn;
|
|
197
|
+
}
|
|
198
|
+
const next = (async () => {
|
|
199
|
+
const result = await query({
|
|
200
|
+
tag: "iq",
|
|
201
|
+
attrs: { type: "set", xmlns: "w:m", to: S_WHATSAPP_NET },
|
|
202
|
+
content: [{ tag: "media_conn", attrs: {} }],
|
|
203
|
+
});
|
|
204
|
+
const mediaConnNode = getBinaryNodeChild(result, "media_conn");
|
|
205
|
+
if (!mediaConnNode) throw new Boom("Missing media connection response", { statusCode: 502 });
|
|
206
|
+
const node = {
|
|
207
|
+
hosts: getBinaryNodeChildren(mediaConnNode, "host").map(({ attrs }) => ({
|
|
208
|
+
hostname: attrs.hostname,
|
|
209
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes,
|
|
210
|
+
})),
|
|
211
|
+
auth: mediaConnNode.attrs.auth,
|
|
212
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
213
|
+
fetchDate: new Date(),
|
|
214
|
+
};
|
|
215
|
+
logger.debug("fetched media conn");
|
|
216
|
+
return node;
|
|
217
|
+
})();
|
|
218
|
+
mediaConn = next;
|
|
219
|
+
try {
|
|
220
|
+
const result = await next;
|
|
221
|
+
if (mediaConn === next && result.hosts[0]?.hostname) mediaHost = result.hosts[0].hostname;
|
|
222
|
+
return result;
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if (mediaConn === next) mediaConn = undefined;
|
|
225
|
+
throw error;
|
|
213
226
|
}
|
|
214
|
-
return mediaConn;
|
|
215
227
|
};
|
|
216
228
|
/**
|
|
217
229
|
* generic send receipt function
|
|
@@ -467,38 +479,33 @@ export const makeMessagesSocket = (config) => {
|
|
|
467
479
|
const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
|
|
468
480
|
const jidsRequiringFetch = [];
|
|
469
481
|
logger.debug({ jids }, "assertSessions call with jids");
|
|
470
|
-
//
|
|
482
|
+
// Validate against the current store each time: a cached 'true' may be
|
|
483
|
+
// stale after a peer's identity or Signal session changes.
|
|
471
484
|
for (const jid of uniqueJids) {
|
|
472
|
-
|
|
473
|
-
const cachedSession = peerSessionsCache.get(signalId);
|
|
474
|
-
if (cachedSession !== undefined) {
|
|
475
|
-
if (cachedSession && !force) {
|
|
476
|
-
continue; // Session exists in cache
|
|
477
|
-
}
|
|
478
|
-
} else {
|
|
485
|
+
if (!force) {
|
|
479
486
|
const sessionValidation = await signalRepository.validateSession(jid);
|
|
480
|
-
|
|
481
|
-
peerSessionsCache.set(signalId, hasSession);
|
|
482
|
-
if (hasSession && !force) {
|
|
483
|
-
continue;
|
|
484
|
-
}
|
|
487
|
+
if (sessionValidation.exists) continue;
|
|
485
488
|
}
|
|
486
489
|
jidsRequiringFetch.push(jid);
|
|
487
490
|
}
|
|
488
491
|
if (jidsRequiringFetch.length) {
|
|
489
|
-
//
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
),
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
492
|
+
// Prefer each resolved LID, but retain a PN when no mapping was returned.
|
|
493
|
+
// Otherwise a partial/missing LID lookup silently produced an empty or
|
|
494
|
+
// incomplete encrypt query despite the 'otherwise original' contract.
|
|
495
|
+
const pns = jidsRequiringFetch.filter(
|
|
496
|
+
(jid) => !!isPnUser(jid) || !!isHostedPnUser(jid),
|
|
497
|
+
);
|
|
498
|
+
const mappings = pns.length
|
|
499
|
+
? (await signalRepository.lidMapping.getLIDsForPNs(pns)) || []
|
|
500
|
+
: [];
|
|
501
|
+
const lidsByPn = new Map(mappings.filter((a) => a?.pn && a?.lid).map((a) => [a.pn, a.lid]));
|
|
502
|
+
const wireJids = [...new Set([
|
|
503
|
+
...jidsRequiringFetch.filter((jid) => !!isLidUser(jid) || !!isHostedLidUser(jid)),
|
|
504
|
+
...pns.map((jid) => lidsByPn.get(jid) || jid),
|
|
505
|
+
])];
|
|
506
|
+
if (!wireJids.length) {
|
|
507
|
+
throw new Boom("No supported recipient JIDs for session query", { statusCode: 400 });
|
|
508
|
+
}
|
|
502
509
|
logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
|
|
503
510
|
const result = await query({
|
|
504
511
|
tag: "iq",
|
|
@@ -521,11 +528,6 @@ export const makeMessagesSocket = (config) => {
|
|
|
521
528
|
});
|
|
522
529
|
await parseAndInjectE2ESessions(result, signalRepository);
|
|
523
530
|
didFetchNewSession = true;
|
|
524
|
-
// Cache fetched sessions using wire JIDs
|
|
525
|
-
for (const wireJid of wireJids) {
|
|
526
|
-
const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
|
|
527
|
-
peerSessionsCache.set(signalId, true);
|
|
528
|
-
}
|
|
529
531
|
}
|
|
530
532
|
return didFetchNewSession;
|
|
531
533
|
};
|
|
@@ -1218,6 +1220,8 @@ export const makeMessagesSocket = (config) => {
|
|
|
1218
1220
|
bibz,
|
|
1219
1221
|
readMessages,
|
|
1220
1222
|
refreshMediaConn,
|
|
1223
|
+
// A method survives the object spreads used by the upper socket layers.
|
|
1224
|
+
getMediaHost: () => mediaHost,
|
|
1221
1225
|
waUploadToServer,
|
|
1222
1226
|
fetchPrivacySettings,
|
|
1223
1227
|
sendPeerDataOperationMessage,
|
|
@@ -1261,7 +1265,7 @@ export const makeMessagesSocket = (config) => {
|
|
|
1261
1265
|
);
|
|
1262
1266
|
}
|
|
1263
1267
|
content.directPath = media.directPath;
|
|
1264
|
-
content.url = getUrlFromDirectPath(content.directPath);
|
|
1268
|
+
content.url = getUrlFromDirectPath(content.directPath, mediaHost);
|
|
1265
1269
|
logger.debug(
|
|
1266
1270
|
{ directPath: media.directPath, key: result.key },
|
|
1267
1271
|
"media update successful",
|
package/lib/Socket/mex.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/** @module @xbibzlibrary/whatsbibz/lib/Socket/mex */
|
|
2
2
|
import type { BinaryNode } from '../WABinary/index.js';
|
|
3
|
-
export declare const executeWMexQuery: <T>(variables: Record<string, unknown>, queryId: string, dataPath: string, query: (node: BinaryNode) => Promise<BinaryNode>, generateMessageTag: () => string) => Promise<T>;
|
|
3
|
+
export declare const executeWMexQuery: <T>(variables: Record<string, unknown>, queryId: string, dataPath: string, query: (node: BinaryNode) => Promise<BinaryNode>, generateMessageTag: () => string, options?: { strictDataPath?: boolean }) => Promise<T>;
|
package/lib/Socket/mex.js
CHANGED
|
@@ -19,7 +19,7 @@ const wMexQuery = (variables, queryId, query, generateMessageTag) => {
|
|
|
19
19
|
]
|
|
20
20
|
});
|
|
21
21
|
};
|
|
22
|
-
export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
|
|
22
|
+
export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag, { strictDataPath = false } = {}) => {
|
|
23
23
|
const result = await wMexQuery(variables, queryId, query, generateMessageTag);
|
|
24
24
|
const child = getBinaryNodeChild(result, 'result');
|
|
25
25
|
if (child?.content) {
|
|
@@ -27,11 +27,13 @@ export const executeWMexQuery = async (variables, queryId, dataPath, query, gene
|
|
|
27
27
|
if (data.errors && data.errors.length > 0) {
|
|
28
28
|
const errorMessages = data.errors.map((err) => err.message || 'Unknown error').join(', ');
|
|
29
29
|
const firstError = data.errors[0];
|
|
30
|
-
const
|
|
30
|
+
const rawCode = Number(firstError.extensions?.error_code);
|
|
31
|
+
// WMex can return non-HTTP GraphQL codes; Boom only accepts HTTP errors.
|
|
32
|
+
const errorCode = Number.isInteger(rawCode) && rawCode >= 400 && rawCode <= 599 ? rawCode : 400;
|
|
31
33
|
throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError });
|
|
32
34
|
}
|
|
33
35
|
let response = dataPath ? data?.data?.[dataPath] : data?.data;
|
|
34
|
-
if (typeof response === 'undefined' && dataPath && data?.data) {
|
|
36
|
+
if (!strictDataPath && typeof response === 'undefined' && dataPath && data?.data) {
|
|
35
37
|
const keys = Object.keys(data.data);
|
|
36
38
|
if (keys.length === 1) {
|
|
37
39
|
response = data.data[keys[0]];
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** @internal Shared WMex queries used by complete and partial sockets. */
|
|
2
|
+
import type { BinaryNode, NewsletterMetadata } from '../index.js';
|
|
3
|
+
|
|
4
|
+
export declare function createNewsletterFollowQueries(
|
|
5
|
+
query: (node: BinaryNode) => Promise<unknown>,
|
|
6
|
+
generateMessageTag: () => string,
|
|
7
|
+
): {
|
|
8
|
+
newsletterMetadata(type: 'jid' | 'invite', key: string): Promise<NewsletterMetadata | null>;
|
|
9
|
+
newsletterFollow(jid: string): Promise<unknown>;
|
|
10
|
+
newsletterUnfollow(jid: string): Promise<unknown>;
|
|
11
|
+
};
|