@rakku-kun/baileys 2.0.15 → 2.0.16
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/WAProto/fix-imports.js +22 -18
- package/WAProto/index.js +22 -18
- package/lib/Defaults/index.d.ts +8 -7
- package/lib/Defaults/index.d.ts.map +1 -1
- package/lib/Defaults/index.js +11 -17
- package/lib/Defaults/index.js.map +1 -1
- package/lib/Signal/libsignal.d.ts.map +1 -1
- package/lib/Signal/libsignal.js +52 -59
- package/lib/Signal/libsignal.js.map +1 -1
- package/lib/Signal/lid-mapping.d.ts.map +1 -1
- package/lib/Signal/lid-mapping.js.map +1 -1
- package/lib/Socket/business.d.ts +18 -3
- package/lib/Socket/business.d.ts.map +1 -1
- package/lib/Socket/chats.d.ts +16 -2
- package/lib/Socket/chats.d.ts.map +1 -1
- package/lib/Socket/chats.js +238 -173
- package/lib/Socket/chats.js.map +1 -1
- package/lib/Socket/communities.d.ts +18 -3
- package/lib/Socket/communities.d.ts.map +1 -1
- package/lib/Socket/groups.d.ts +13 -2
- package/lib/Socket/groups.d.ts.map +1 -1
- package/lib/Socket/groups.js +26 -138
- package/lib/Socket/groups.js.map +1 -1
- package/lib/Socket/index.d.ts +18 -3
- package/lib/Socket/index.d.ts.map +1 -1
- package/lib/Socket/messages-recv.d.ts +22 -6
- package/lib/Socket/messages-recv.d.ts.map +1 -1
- package/lib/Socket/messages-recv.js +736 -647
- package/lib/Socket/messages-recv.js.map +1 -1
- package/lib/Socket/messages-send.d.ts +18 -2
- package/lib/Socket/messages-send.d.ts.map +1 -1
- package/lib/Socket/messages-send.js +152 -642
- package/lib/Socket/messages-send.js.map +1 -1
- package/lib/Socket/newsletter.d.ts +11 -1
- package/lib/Socket/newsletter.d.ts.map +1 -1
- package/lib/Socket/newsletter.js +3 -92
- package/lib/Socket/newsletter.js.map +1 -1
- package/lib/Socket/socket.d.ts +6 -2
- package/lib/Socket/socket.d.ts.map +1 -1
- package/lib/Socket/socket.js +61 -35
- package/lib/Socket/socket.js.map +1 -1
- package/lib/Types/Auth.d.ts +1 -0
- package/lib/Types/Auth.d.ts.map +1 -1
- package/lib/Types/Call.d.ts +1 -1
- package/lib/Types/Call.d.ts.map +1 -1
- package/lib/Types/Chat.d.ts +1 -0
- package/lib/Types/Chat.d.ts.map +1 -1
- package/lib/Types/Contact.d.ts +2 -0
- package/lib/Types/Contact.d.ts.map +1 -1
- package/lib/Types/Events.d.ts +20 -1
- package/lib/Types/Events.d.ts.map +1 -1
- package/lib/Types/GroupMetadata.d.ts +4 -0
- package/lib/Types/GroupMetadata.d.ts.map +1 -1
- package/lib/Types/Message.d.ts +25 -200
- package/lib/Types/Message.d.ts.map +1 -1
- package/lib/Types/Message.js.map +1 -1
- package/lib/Types/Mex.d.ts +141 -0
- package/lib/Types/Mex.d.ts.map +1 -0
- package/lib/Types/Mex.js +37 -0
- package/lib/Types/Mex.js.map +1 -0
- package/lib/Types/Signal.d.ts +12 -1
- package/lib/Types/Signal.d.ts.map +1 -1
- package/lib/Types/Socket.d.ts +3 -0
- package/lib/Types/Socket.d.ts.map +1 -1
- package/lib/Types/State.d.ts +58 -0
- package/lib/Types/State.d.ts.map +1 -1
- package/lib/Types/State.js +43 -0
- package/lib/Types/State.js.map +1 -1
- package/lib/Types/index.d.ts +2 -1
- package/lib/Types/index.d.ts.map +1 -1
- package/lib/Types/index.js +1 -2
- package/lib/Types/index.js.map +1 -1
- package/lib/Utils/auth-utils.d.ts +5 -0
- package/lib/Utils/auth-utils.d.ts.map +1 -1
- package/lib/Utils/auth-utils.js +12 -0
- package/lib/Utils/auth-utils.js.map +1 -1
- package/lib/Utils/browser-utils.d.ts.map +1 -1
- package/lib/Utils/browser-utils.js +21 -33
- package/lib/Utils/browser-utils.js.map +1 -1
- package/lib/Utils/chat-utils.d.ts +31 -1
- package/lib/Utils/chat-utils.d.ts.map +1 -1
- package/lib/Utils/chat-utils.js +80 -20
- package/lib/Utils/chat-utils.js.map +1 -1
- package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
- package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
- package/lib/Utils/companion-reg-client-utils.js +35 -0
- package/lib/Utils/companion-reg-client-utils.js.map +1 -0
- package/lib/Utils/decode-wa-message.d.ts +18 -0
- package/lib/Utils/decode-wa-message.d.ts.map +1 -1
- package/lib/Utils/decode-wa-message.js +34 -0
- package/lib/Utils/decode-wa-message.js.map +1 -1
- package/lib/Utils/event-buffer.d.ts +2 -0
- package/lib/Utils/event-buffer.d.ts.map +1 -1
- package/lib/Utils/event-buffer.js +49 -1
- package/lib/Utils/event-buffer.js.map +1 -1
- package/lib/Utils/generics.d.ts +1 -0
- package/lib/Utils/generics.d.ts.map +1 -1
- package/lib/Utils/generics.js +10 -28
- package/lib/Utils/generics.js.map +1 -1
- package/lib/Utils/history.d.ts +2 -0
- package/lib/Utils/history.d.ts.map +1 -1
- package/lib/Utils/history.js +12 -9
- package/lib/Utils/history.js.map +1 -1
- package/lib/Utils/identity-change-handler.d.ts +7 -0
- package/lib/Utils/identity-change-handler.d.ts.map +1 -1
- package/lib/Utils/identity-change-handler.js +1 -0
- package/lib/Utils/identity-change-handler.js.map +1 -1
- package/lib/Utils/index.d.ts +2 -2
- package/lib/Utils/index.d.ts.map +1 -1
- package/lib/Utils/index.js +2 -7
- package/lib/Utils/index.js.map +1 -1
- package/lib/Utils/link-preview.js +2 -2
- package/lib/Utils/link-preview.js.map +1 -1
- package/lib/Utils/message-retry-manager.d.ts +5 -0
- package/lib/Utils/message-retry-manager.d.ts.map +1 -1
- package/lib/Utils/message-retry-manager.js +40 -0
- package/lib/Utils/message-retry-manager.js.map +1 -1
- package/lib/Utils/messages-media.d.ts +4 -1
- package/lib/Utils/messages-media.d.ts.map +1 -1
- package/lib/Utils/messages-media.js +131 -173
- package/lib/Utils/messages-media.js.map +1 -1
- package/lib/Utils/messages.d.ts +0 -1
- package/lib/Utils/messages.d.ts.map +1 -1
- package/lib/Utils/messages.js +100 -906
- package/lib/Utils/messages.js.map +1 -1
- package/lib/Utils/offline-node-processor.d.ts +17 -0
- package/lib/Utils/offline-node-processor.d.ts.map +1 -0
- package/lib/Utils/offline-node-processor.js +40 -0
- package/lib/Utils/offline-node-processor.js.map +1 -0
- package/lib/Utils/process-message.d.ts.map +1 -1
- package/lib/Utils/process-message.js +103 -1
- package/lib/Utils/process-message.js.map +1 -1
- package/lib/Utils/signal.d.ts +13 -0
- package/lib/Utils/signal.d.ts.map +1 -1
- package/lib/Utils/signal.js +42 -0
- package/lib/Utils/signal.js.map +1 -1
- package/lib/Utils/stanza-ack.d.ts +11 -0
- package/lib/Utils/stanza-ack.d.ts.map +1 -0
- package/lib/Utils/stanza-ack.js +38 -0
- package/lib/Utils/stanza-ack.js.map +1 -0
- package/lib/Utils/sync-action-utils.d.ts.map +1 -1
- package/lib/Utils/sync-action-utils.js +1 -0
- package/lib/Utils/sync-action-utils.js.map +1 -1
- package/lib/Utils/tc-token-utils.d.ts +26 -1
- package/lib/Utils/tc-token-utils.d.ts.map +1 -1
- package/lib/Utils/tc-token-utils.js +151 -5
- package/lib/Utils/tc-token-utils.js.map +1 -1
- package/lib/Utils/validate-connection.d.ts.map +1 -1
- package/lib/Utils/validate-connection.js +12 -2
- package/lib/Utils/validate-connection.js.map +1 -1
- package/lib/WABinary/generic-utils.js +0 -15
- package/lib/WABinary/index.js +0 -1
- package/lib/WABinary/jid-utils.js +0 -2
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
- package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/index.d.ts +1 -0
- package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/index.js +2 -2
- package/lib/WAUSync/Protocols/index.js.map +1 -1
- package/lib/WAUSync/USyncQuery.d.ts +1 -0
- package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
- package/lib/WAUSync/USyncQuery.js +6 -2
- package/lib/WAUSync/USyncQuery.js.map +1 -1
- package/lib/WAUSync/USyncUser.d.ts +4 -0
- package/lib/WAUSync/USyncUser.d.ts.map +1 -1
- package/lib/WAUSync/USyncUser.js +8 -0
- package/lib/WAUSync/USyncUser.js.map +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +10 -24
- package/package.json +1 -1
|
@@ -4,17 +4,24 @@ import { randomBytes } from 'crypto';
|
|
|
4
4
|
import Long from 'long';
|
|
5
5
|
import { proto } from '../../WAProto/index.js';
|
|
6
6
|
import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js';
|
|
7
|
-
import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
|
|
8
|
-
import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
|
|
7
|
+
import { ReachoutTimelockEnforcementType, WAMessageStatus, WAMessageStubType } from '../Types/index.js';
|
|
8
|
+
import { ACCOUNT_RESTRICTED_TEXT, aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, extractE2ESessionFromRetryReceipt, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, SERVER_ERROR_CODES, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
|
|
9
9
|
import { makeMutex } from '../Utils/make-mutex.js';
|
|
10
|
-
import {
|
|
10
|
+
import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
|
|
11
|
+
import { buildAckStanza } from '../Utils/stanza-ack.js';
|
|
12
|
+
import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
|
|
13
|
+
import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
|
|
11
14
|
import { extractGroupMetadata } from './groups.js';
|
|
12
15
|
import { makeMessagesSocket } from './messages-send.js';
|
|
13
|
-
|
|
16
|
+
const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcementType));
|
|
17
|
+
function isValidEnforcementType(value) {
|
|
18
|
+
return typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value);
|
|
19
|
+
}
|
|
14
20
|
export const makeMessagesRecvSocket = (config) => {
|
|
15
21
|
const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
|
|
16
22
|
const sock = makeMessagesSocket(config);
|
|
17
|
-
const { ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
|
|
23
|
+
const { userDevicesCache, devicesMutex, ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager, registerSocketEndHandler, issuePrivacyTokens, fetchAccountReachoutTimelock, placeholderResendCache } = sock;
|
|
24
|
+
const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
|
|
18
25
|
/** this mutex ensures that each retryRequest will wait for the previous one to finish */
|
|
19
26
|
const retryMutex = makeMutex();
|
|
20
27
|
const msgRetryCache = config.msgRetryCounterCache ||
|
|
@@ -27,11 +34,6 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
27
34
|
stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
|
|
28
35
|
useClones: false
|
|
29
36
|
});
|
|
30
|
-
const placeholderResendCache = config.placeholderResendCache ||
|
|
31
|
-
new NodeCache({
|
|
32
|
-
stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
|
|
33
|
-
useClones: false
|
|
34
|
-
});
|
|
35
37
|
// Debounce identity-change session refreshes per JID to avoid bursts
|
|
36
38
|
const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
|
|
37
39
|
let sendActiveReceipts = false;
|
|
@@ -60,8 +62,6 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
60
62
|
return;
|
|
61
63
|
}
|
|
62
64
|
else {
|
|
63
|
-
// AUTO-PATCHED FORCE RETRY
|
|
64
|
-
await placeholderResendCache.set(messageKey?.id, true);
|
|
65
65
|
// Store original message data so PDO response handler can preserve
|
|
66
66
|
// metadata (LID details, timestamps, etc.) that the phone may omit
|
|
67
67
|
await placeholderResendCache.set(messageKey?.id, msgData || true);
|
|
@@ -87,25 +87,140 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
87
87
|
}, 8000);
|
|
88
88
|
return sendPeerDataOperationMessage(pdoMessage);
|
|
89
89
|
};
|
|
90
|
-
|
|
91
|
-
|
|
90
|
+
const handleMexNotification = async (node) => {
|
|
91
|
+
const updateNode = getBinaryNodeChild(node, 'update');
|
|
92
|
+
if (updateNode) {
|
|
93
|
+
const opName = updateNode.attrs?.op_name;
|
|
94
|
+
if (!opName) {
|
|
95
|
+
logger.warn({ node: binaryNodeToString(node) }, 'mex notification missing op_name, fallback to legacy');
|
|
96
|
+
await handleLegacyMexNewsletterNotification(node);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
let mexResponse;
|
|
100
|
+
try {
|
|
101
|
+
mexResponse = JSON.parse(updateNode.content.toString());
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
logger.error({ err: error, opName }, 'failed to parse mex notification JSON');
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (mexResponse.errors?.length) {
|
|
108
|
+
logger.warn({ errors: mexResponse.errors, opName }, 'mex notification has GQL errors');
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const data = mexResponse.data;
|
|
112
|
+
if (!data) {
|
|
113
|
+
logger.warn({ opName }, 'mex notification has null data');
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
logger.debug({ opName }, 'processing mex notification');
|
|
117
|
+
switch (opName) {
|
|
118
|
+
case 'NotificationUserReachoutTimelockUpdate':
|
|
119
|
+
handleReachoutTimelockNotification(data);
|
|
120
|
+
break;
|
|
121
|
+
case 'MessageCappingInfoNotification':
|
|
122
|
+
handleMessageCappingNotification(data);
|
|
123
|
+
break;
|
|
124
|
+
// newsletter ops still use the legacy <mex> child structure
|
|
125
|
+
case 'NotificationNewsletterUpdate':
|
|
126
|
+
case 'NotificationLinkedProfilesUpdates':
|
|
127
|
+
case 'NotificationNewsletterAdminPromote':
|
|
128
|
+
case 'NotificationNewsletterAdminDemote':
|
|
129
|
+
case 'NotificationNewsletterUserSettingChange':
|
|
130
|
+
case 'NotificationNewsletterJoin':
|
|
131
|
+
case 'NotificationNewsletterLeave':
|
|
132
|
+
case 'NotificationNewsletterStateChange':
|
|
133
|
+
case 'NotificationNewsletterAdminMetadataUpdate':
|
|
134
|
+
case 'NotificationNewsletterOwnerUpdate':
|
|
135
|
+
case 'NotificationNewsletterAdminInviteRevoke':
|
|
136
|
+
case 'NotificationNewsletterWamoSubStatusChange':
|
|
137
|
+
case 'NotificationNewsletterBlockUser':
|
|
138
|
+
case 'NotificationNewsletterPaidPartnership':
|
|
139
|
+
case 'NotificationNewsletterMilestone':
|
|
140
|
+
case 'NewsletterResponseStateUpdate':
|
|
141
|
+
await handleLegacyMexNewsletterNotification(node);
|
|
142
|
+
break;
|
|
143
|
+
default:
|
|
144
|
+
logger.debug({ opName }, 'unhandled mex notification');
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
await handleLegacyMexNewsletterNotification(node);
|
|
150
|
+
};
|
|
151
|
+
const handleReachoutTimelockNotification = (data) => {
|
|
152
|
+
const payload = data.xwa2_notify_account_reachout_timelock;
|
|
153
|
+
if (!payload) {
|
|
154
|
+
logger.warn('reachout timelock notification missing payload');
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (!payload.is_active) {
|
|
158
|
+
logger.info('reachout timelock restriction lifted');
|
|
159
|
+
ev.emit('connection.update', {
|
|
160
|
+
reachoutTimeLock: {
|
|
161
|
+
isActive: false,
|
|
162
|
+
enforcementType: ReachoutTimelockEnforcementType.DEFAULT
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
// WA Web defaults to now+60s when the server omits the expiry
|
|
168
|
+
const timeEnforcementEnds = payload.time_enforcement_ends
|
|
169
|
+
? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000)
|
|
170
|
+
: new Date(Date.now() + 60000);
|
|
171
|
+
const enforcementType = isValidEnforcementType(payload.enforcement_type)
|
|
172
|
+
? payload.enforcement_type
|
|
173
|
+
: ReachoutTimelockEnforcementType.DEFAULT;
|
|
174
|
+
logger.info({ enforcementType, timeEnforcementEnds }, 'reachout timelock restriction set');
|
|
175
|
+
ev.emit('connection.update', {
|
|
176
|
+
reachoutTimeLock: {
|
|
177
|
+
isActive: true,
|
|
178
|
+
timeEnforcementEnds,
|
|
179
|
+
enforcementType
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
};
|
|
183
|
+
const handleMessageCappingNotification = (data) => {
|
|
184
|
+
const payload = data.xwa2_notify_new_chat_messages_capping_info_update;
|
|
185
|
+
if (!payload) {
|
|
186
|
+
logger.warn('message capping notification missing payload');
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
logger.info({ payload }, 'received message capping update');
|
|
190
|
+
ev.emit('message-capping.update', payload);
|
|
191
|
+
};
|
|
192
|
+
const handleLegacyMexNewsletterNotification = async (node) => {
|
|
92
193
|
const mexNode = getBinaryNodeChild(node, 'mex');
|
|
93
|
-
|
|
94
|
-
|
|
194
|
+
const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0];
|
|
195
|
+
const payloadNode = mexNode?.content ? mexNode : updateNode;
|
|
196
|
+
if (!payloadNode?.content) {
|
|
197
|
+
logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification');
|
|
95
198
|
return;
|
|
96
199
|
}
|
|
97
200
|
let data;
|
|
98
201
|
try {
|
|
99
|
-
|
|
202
|
+
const payloadContent = payloadNode.content;
|
|
203
|
+
if (Array.isArray(payloadContent)) {
|
|
204
|
+
logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format');
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
|
|
208
|
+
data = JSON.parse(contentBuf.toString());
|
|
100
209
|
}
|
|
101
210
|
catch (error) {
|
|
102
|
-
logger.error({ err: error, node }, '
|
|
211
|
+
logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
|
|
103
212
|
return;
|
|
104
213
|
}
|
|
105
|
-
const operation = data?.operation;
|
|
106
|
-
|
|
214
|
+
const operation = data?.operation ?? payloadNode?.attrs?.op_name;
|
|
215
|
+
let updates = data?.updates;
|
|
216
|
+
if (!updates) {
|
|
217
|
+
const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
|
|
218
|
+
if (linkedProfiles) {
|
|
219
|
+
updates = [linkedProfiles];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
107
222
|
if (!updates || !operation) {
|
|
108
|
-
logger.warn({ data }, '
|
|
223
|
+
logger.warn({ data }, 'invalid mex newsletter notification content');
|
|
109
224
|
return;
|
|
110
225
|
}
|
|
111
226
|
logger.info({ operation, updates }, 'got mex newsletter notification');
|
|
@@ -133,119 +248,119 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
133
248
|
}
|
|
134
249
|
}
|
|
135
250
|
break;
|
|
251
|
+
case 'NotificationLinkedProfilesUpdates':
|
|
252
|
+
for (const update of updates) {
|
|
253
|
+
const lid = update?.jid;
|
|
254
|
+
const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
|
|
255
|
+
const mappings = [];
|
|
256
|
+
for (const profile of addedProfiles) {
|
|
257
|
+
const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null);
|
|
258
|
+
if (lid && pn) {
|
|
259
|
+
const mapping = { lid, pn };
|
|
260
|
+
ev.emit('lid-mapping.update', mapping);
|
|
261
|
+
mappings.push(mapping);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
await signalRepository.lidMapping.storeLIDPNMappings(mappings);
|
|
265
|
+
}
|
|
266
|
+
break;
|
|
136
267
|
default:
|
|
137
|
-
logger.info({ operation, data }, '
|
|
268
|
+
logger.info({ operation, data }, 'unhandled mex newsletter notification');
|
|
138
269
|
break;
|
|
139
270
|
}
|
|
140
271
|
};
|
|
141
272
|
// Handles newsletter notifications
|
|
142
273
|
const handleNewsletterNotification = async (node) => {
|
|
143
274
|
const from = node.attrs.from;
|
|
144
|
-
const
|
|
275
|
+
const children = getAllBinaryNodeChildren(node);
|
|
145
276
|
const author = node.attrs.participant;
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
server_id: child.attrs.message_id,
|
|
152
|
-
reaction: {
|
|
153
|
-
code: getBinaryNodeChildString(child, 'reaction'),
|
|
154
|
-
count: 1
|
|
155
|
-
}
|
|
156
|
-
};
|
|
157
|
-
ev.emit('newsletter.reaction', reactionUpdate);
|
|
158
|
-
break;
|
|
159
|
-
case 'view':
|
|
160
|
-
const viewUpdate = {
|
|
161
|
-
id: from,
|
|
162
|
-
server_id: child.attrs.message_id,
|
|
163
|
-
count: parseInt(child.content?.toString() || '0', 10)
|
|
164
|
-
};
|
|
165
|
-
ev.emit('newsletter.view', viewUpdate);
|
|
166
|
-
break;
|
|
167
|
-
case 'participant':
|
|
168
|
-
const participantUpdate = {
|
|
169
|
-
id: from,
|
|
170
|
-
author,
|
|
171
|
-
user: child.attrs.jid,
|
|
172
|
-
action: child.attrs.action,
|
|
173
|
-
new_role: child.attrs.role
|
|
174
|
-
};
|
|
175
|
-
ev.emit('newsletter-participants.update', participantUpdate);
|
|
176
|
-
break;
|
|
177
|
-
case 'update':
|
|
178
|
-
const settingsNode = getBinaryNodeChild(child, 'settings');
|
|
179
|
-
if (settingsNode) {
|
|
180
|
-
const update = {};
|
|
181
|
-
const nameNode = getBinaryNodeChild(settingsNode, 'name');
|
|
182
|
-
if (nameNode?.content)
|
|
183
|
-
update.name = nameNode.content.toString();
|
|
184
|
-
const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
|
|
185
|
-
if (descriptionNode?.content)
|
|
186
|
-
update.description = descriptionNode.content.toString();
|
|
187
|
-
ev.emit('newsletter-settings.update', {
|
|
277
|
+
for (const child of children) {
|
|
278
|
+
logger.debug({ from, child }, 'got newsletter notification');
|
|
279
|
+
switch (child.tag) {
|
|
280
|
+
case 'reaction': {
|
|
281
|
+
const reactionUpdate = {
|
|
188
282
|
id: from,
|
|
189
|
-
|
|
190
|
-
|
|
283
|
+
server_id: child.attrs.message_id,
|
|
284
|
+
reaction: {
|
|
285
|
+
code: getBinaryNodeChildString(child, 'reaction'),
|
|
286
|
+
count: 1
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
ev.emit('newsletter.reaction', reactionUpdate);
|
|
290
|
+
break;
|
|
191
291
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
292
|
+
case 'view': {
|
|
293
|
+
const viewUpdate = {
|
|
294
|
+
id: from,
|
|
295
|
+
server_id: child.attrs.message_id,
|
|
296
|
+
count: parseInt(child.content?.toString() || '0', 10)
|
|
297
|
+
};
|
|
298
|
+
ev.emit('newsletter.view', viewUpdate);
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
case 'participant': {
|
|
302
|
+
const participantUpdate = {
|
|
303
|
+
id: from,
|
|
304
|
+
author,
|
|
305
|
+
user: child.attrs.jid,
|
|
306
|
+
action: child.attrs.action,
|
|
307
|
+
new_role: child.attrs.role
|
|
308
|
+
};
|
|
309
|
+
ev.emit('newsletter-participants.update', participantUpdate);
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
case 'update': {
|
|
313
|
+
const settingsNode = getBinaryNodeChild(child, 'settings');
|
|
314
|
+
if (settingsNode) {
|
|
315
|
+
const update = {};
|
|
316
|
+
const nameNode = getBinaryNodeChild(settingsNode, 'name');
|
|
317
|
+
if (nameNode?.content)
|
|
318
|
+
update.name = nameNode.content.toString();
|
|
319
|
+
const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
|
|
320
|
+
if (descriptionNode?.content)
|
|
321
|
+
update.description = descriptionNode.content.toString();
|
|
322
|
+
ev.emit('newsletter-settings.update', {
|
|
323
|
+
id: from,
|
|
324
|
+
update
|
|
325
|
+
});
|
|
212
326
|
}
|
|
213
|
-
|
|
214
|
-
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
case 'message': {
|
|
330
|
+
const plaintextNode = getBinaryNodeChild(child, 'plaintext');
|
|
331
|
+
if (plaintextNode?.content) {
|
|
332
|
+
try {
|
|
333
|
+
const contentBuf = typeof plaintextNode.content === 'string'
|
|
334
|
+
? Buffer.from(plaintextNode.content, 'binary')
|
|
335
|
+
: Buffer.from(plaintextNode.content);
|
|
336
|
+
const messageProto = proto.Message.decode(contentBuf).toJSON();
|
|
337
|
+
const fullMessage = proto.WebMessageInfo.fromObject({
|
|
338
|
+
key: {
|
|
339
|
+
remoteJid: from,
|
|
340
|
+
id: child.attrs.message_id || child.attrs.server_id,
|
|
341
|
+
fromMe: false // TODO: is this really true though
|
|
342
|
+
},
|
|
343
|
+
message: messageProto,
|
|
344
|
+
messageTimestamp: +child.attrs.t
|
|
345
|
+
}).toJSON();
|
|
346
|
+
await upsertMessage(fullMessage, 'append');
|
|
347
|
+
logger.debug('Processed plaintext newsletter message');
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
logger.error({ error }, 'Failed to decode plaintext newsletter message');
|
|
351
|
+
}
|
|
215
352
|
}
|
|
353
|
+
break;
|
|
216
354
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
break;
|
|
221
|
-
}
|
|
222
|
-
};
|
|
223
|
-
const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
|
|
224
|
-
const stanza = {
|
|
225
|
-
tag: 'ack',
|
|
226
|
-
attrs: {
|
|
227
|
-
id: attrs.id,
|
|
228
|
-
to: attrs.from,
|
|
229
|
-
class: tag
|
|
355
|
+
default:
|
|
356
|
+
logger.warn({ node, child }, 'Unknown newsletter notification child');
|
|
357
|
+
break;
|
|
230
358
|
}
|
|
231
|
-
};
|
|
232
|
-
if (!!errorCode) {
|
|
233
|
-
stanza.attrs.error = errorCode.toString();
|
|
234
|
-
}
|
|
235
|
-
if (!!attrs.participant) {
|
|
236
|
-
stanza.attrs.participant = attrs.participant;
|
|
237
|
-
}
|
|
238
|
-
if (!!attrs.recipient) {
|
|
239
|
-
stanza.attrs.recipient = attrs.recipient;
|
|
240
|
-
}
|
|
241
|
-
if (!!attrs.type &&
|
|
242
|
-
(tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
|
|
243
|
-
stanza.attrs.type = attrs.type;
|
|
244
359
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
|
|
360
|
+
};
|
|
361
|
+
const sendMessageAck = async (node, errorCode) => {
|
|
362
|
+
const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
|
|
363
|
+
logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
|
|
249
364
|
await sendNode(stanza);
|
|
250
365
|
};
|
|
251
366
|
const rejectCall = async (callId, callFrom) => {
|
|
@@ -400,15 +515,58 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
400
515
|
logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
|
|
401
516
|
}, authState?.creds?.me?.id || 'sendRetryRequest');
|
|
402
517
|
};
|
|
518
|
+
// Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
|
|
519
|
+
const inFlightPreKeyLow = new Set();
|
|
520
|
+
/**
|
|
521
|
+
* Fire-and-forget tctoken re-issuance after a peer's device identity changed.
|
|
522
|
+
* Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
|
|
523
|
+
* the session refresh (not after it).
|
|
524
|
+
*/
|
|
525
|
+
const reissueTcTokenAfterIdentityChange = (from) => {
|
|
526
|
+
void (async () => {
|
|
527
|
+
const normalizedJid = jidNormalizedUser(from);
|
|
528
|
+
const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN);
|
|
529
|
+
const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
|
|
530
|
+
const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
|
|
531
|
+
if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken');
|
|
535
|
+
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
|
|
536
|
+
const issueJid = await resolveIssuanceJid(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
|
|
537
|
+
const result = await issuePrivacyTokens([issueJid], senderTs);
|
|
538
|
+
await storeTcTokensFromIqResult({
|
|
539
|
+
result,
|
|
540
|
+
fallbackJid: tcJid,
|
|
541
|
+
keys: authState.keys,
|
|
542
|
+
getLIDForPN,
|
|
543
|
+
onNewJidStored: trackTcTokenJid
|
|
544
|
+
});
|
|
545
|
+
})().catch(err => {
|
|
546
|
+
logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change');
|
|
547
|
+
});
|
|
548
|
+
};
|
|
403
549
|
const handleEncryptNotification = async (node) => {
|
|
404
550
|
const from = node.attrs.from;
|
|
405
551
|
if (from === S_WHATSAPP_NET) {
|
|
552
|
+
const stanzaId = node.attrs.id;
|
|
553
|
+
if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
406
556
|
const countChild = getBinaryNodeChild(node, 'count');
|
|
407
557
|
const count = +countChild.attrs.value;
|
|
408
558
|
const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
|
|
409
559
|
logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
|
|
410
560
|
if (shouldUploadMorePreKeys) {
|
|
411
|
-
|
|
561
|
+
if (stanzaId)
|
|
562
|
+
inFlightPreKeyLow.add(stanzaId);
|
|
563
|
+
try {
|
|
564
|
+
await uploadPreKeys();
|
|
565
|
+
}
|
|
566
|
+
finally {
|
|
567
|
+
if (stanzaId)
|
|
568
|
+
inFlightPreKeyLow.delete(stanzaId);
|
|
569
|
+
}
|
|
412
570
|
}
|
|
413
571
|
}
|
|
414
572
|
else {
|
|
@@ -418,7 +576,8 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
418
576
|
validateSession: signalRepository.validateSession,
|
|
419
577
|
assertSessions,
|
|
420
578
|
debounceCache: identityAssertDebounce,
|
|
421
|
-
logger
|
|
579
|
+
logger,
|
|
580
|
+
onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
|
|
422
581
|
});
|
|
423
582
|
if (result.action === 'no_identity_node') {
|
|
424
583
|
logger.info({ node }, 'unknown encrypt notification');
|
|
@@ -429,6 +588,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
429
588
|
// TODO: Support PN/LID (Here is only LID now)
|
|
430
589
|
const actingParticipantLid = fullNode.attrs.participant;
|
|
431
590
|
const actingParticipantPn = fullNode.attrs.participant_pn;
|
|
591
|
+
const actingParticipantUsername = fullNode.attrs.participant_username;
|
|
432
592
|
const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
|
|
433
593
|
const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
|
|
434
594
|
switch (child?.tag) {
|
|
@@ -448,7 +608,8 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
448
608
|
{
|
|
449
609
|
...metadata,
|
|
450
610
|
author: actingParticipantLid,
|
|
451
|
-
authorPn: actingParticipantPn
|
|
611
|
+
authorPn: actingParticipantPn,
|
|
612
|
+
authorUsername: actingParticipantUsername
|
|
452
613
|
}
|
|
453
614
|
]);
|
|
454
615
|
break;
|
|
@@ -479,6 +640,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
479
640
|
id: attrs.jid,
|
|
480
641
|
phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
|
|
481
642
|
lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
|
|
643
|
+
username: attrs.participant_username || attrs.username || undefined,
|
|
482
644
|
admin: (attrs.type || null)
|
|
483
645
|
};
|
|
484
646
|
});
|
|
@@ -548,6 +710,89 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
548
710
|
break;
|
|
549
711
|
}
|
|
550
712
|
};
|
|
713
|
+
const handleDevicesNotification = async (node) => {
|
|
714
|
+
const [child] = getAllBinaryNodeChildren(node);
|
|
715
|
+
const from = jidNormalizedUser(node.attrs.from);
|
|
716
|
+
if (!child) {
|
|
717
|
+
logger.debug({ from }, 'devices notification missing child, skipping');
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
const tag = child.tag;
|
|
721
|
+
const deviceHash = child.attrs.device_hash;
|
|
722
|
+
const devices = getBinaryNodeChildren(child, 'device');
|
|
723
|
+
if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) {
|
|
724
|
+
const deviceJids = devices.map(d => d.attrs.jid);
|
|
725
|
+
logger.info({ deviceJids }, 'got my own devices');
|
|
726
|
+
}
|
|
727
|
+
if (!devices.length) {
|
|
728
|
+
logger.debug({ from, tag }, 'no devices in notification, skipping');
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
const decoded = [];
|
|
732
|
+
for (const d of devices) {
|
|
733
|
+
const jid = d.attrs.jid;
|
|
734
|
+
if (!jid)
|
|
735
|
+
continue;
|
|
736
|
+
const parts = jidDecode(jid);
|
|
737
|
+
if (!parts) {
|
|
738
|
+
logger.debug({ jid }, 'failed to decode device jid, skipping');
|
|
739
|
+
continue;
|
|
740
|
+
}
|
|
741
|
+
decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device });
|
|
742
|
+
}
|
|
743
|
+
if (!decoded.length)
|
|
744
|
+
return;
|
|
745
|
+
await devicesMutex.mutex(async () => {
|
|
746
|
+
const byUser = new Map();
|
|
747
|
+
for (const d of decoded) {
|
|
748
|
+
const list = byUser.get(d.user) || [];
|
|
749
|
+
list.push(d);
|
|
750
|
+
byUser.set(d.user, list);
|
|
751
|
+
}
|
|
752
|
+
for (const [user, entries] of byUser) {
|
|
753
|
+
if (tag === 'update') {
|
|
754
|
+
logger.debug({ user }, `${user}'s device list updated, dropping cached devices`);
|
|
755
|
+
await userDevicesCache?.del(user);
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
if (tag === 'remove') {
|
|
759
|
+
await signalRepository.deleteSession(entries.map(e => e.jid));
|
|
760
|
+
}
|
|
761
|
+
const existingCache = (await userDevicesCache?.get(user)) || [];
|
|
762
|
+
if (!existingCache.length) {
|
|
763
|
+
// No baseline yet; skip applying the delta so getUSyncDevices can
|
|
764
|
+
// later fetch the full device list. Caching just the notification
|
|
765
|
+
// entries would make a partial list look authoritative.
|
|
766
|
+
logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh');
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
const affected = new Set(entries.map(e => e.device));
|
|
770
|
+
let updatedDevices;
|
|
771
|
+
switch (tag) {
|
|
772
|
+
case 'add':
|
|
773
|
+
logger.info({ deviceHash, count: entries.length }, 'devices added');
|
|
774
|
+
updatedDevices = [
|
|
775
|
+
...existingCache.filter(d => !affected.has(d.device)),
|
|
776
|
+
...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))
|
|
777
|
+
];
|
|
778
|
+
break;
|
|
779
|
+
case 'remove':
|
|
780
|
+
logger.info({ deviceHash, count: entries.length }, 'devices removed');
|
|
781
|
+
updatedDevices = existingCache.filter(d => !affected.has(d.device));
|
|
782
|
+
break;
|
|
783
|
+
default:
|
|
784
|
+
logger.debug({ tag }, 'Unknown device list change tag');
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
if (updatedDevices.length === 0) {
|
|
788
|
+
await userDevicesCache?.del(user);
|
|
789
|
+
}
|
|
790
|
+
else {
|
|
791
|
+
await userDevicesCache?.set(user, updatedDevices);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
});
|
|
795
|
+
};
|
|
551
796
|
const processNotification = async (node) => {
|
|
552
797
|
const result = {};
|
|
553
798
|
const [child] = getAllBinaryNodeChildren(node);
|
|
@@ -558,7 +803,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
558
803
|
await handleNewsletterNotification(node);
|
|
559
804
|
break;
|
|
560
805
|
case 'mex':
|
|
561
|
-
await
|
|
806
|
+
await handleMexNotification(node);
|
|
562
807
|
break;
|
|
563
808
|
case 'w:gp2':
|
|
564
809
|
// TODO: HANDLE PARTICIPANT_PN
|
|
@@ -572,13 +817,12 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
572
817
|
await handleEncryptNotification(node);
|
|
573
818
|
break;
|
|
574
819
|
case 'devices':
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
logger.
|
|
820
|
+
try {
|
|
821
|
+
await handleDevicesNotification(node);
|
|
822
|
+
}
|
|
823
|
+
catch (error) {
|
|
824
|
+
logger.error({ error, node }, 'failed to handle devices notification');
|
|
580
825
|
}
|
|
581
|
-
//TODO: drop a new event, add hashes
|
|
582
826
|
break;
|
|
583
827
|
case 'server_sync':
|
|
584
828
|
const update = getBinaryNodeChild(node, 'collection');
|
|
@@ -704,27 +948,70 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
704
948
|
return result;
|
|
705
949
|
}
|
|
706
950
|
};
|
|
951
|
+
/**
|
|
952
|
+
* In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
|
|
953
|
+
* Used to coalesce writes during a session; pruning always re-reads the persisted index
|
|
954
|
+
* to cover writes made by other layers (e.g. history sync).
|
|
955
|
+
*/
|
|
956
|
+
const tcTokenKnownJids = new Set();
|
|
957
|
+
const tcTokenIndexLoaded = (async () => {
|
|
958
|
+
try {
|
|
959
|
+
const jids = await readTcTokenIndex(authState.keys);
|
|
960
|
+
for (const jid of jids)
|
|
961
|
+
tcTokenKnownJids.add(jid);
|
|
962
|
+
logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index');
|
|
963
|
+
}
|
|
964
|
+
catch (err) {
|
|
965
|
+
logger.warn({ err: err?.message }, 'failed to load tctoken index');
|
|
966
|
+
}
|
|
967
|
+
})();
|
|
968
|
+
let tcTokenIndexTimer;
|
|
969
|
+
async function flushTcTokenIndex() {
|
|
970
|
+
if (tcTokenIndexTimer) {
|
|
971
|
+
clearTimeout(tcTokenIndexTimer);
|
|
972
|
+
tcTokenIndexTimer = undefined;
|
|
973
|
+
}
|
|
974
|
+
// Merge with whatever is already persisted so we don't clobber writes from other
|
|
975
|
+
// paths (history sync, concurrent sessions on the same store).
|
|
976
|
+
const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids);
|
|
977
|
+
return authState.keys.set({ tctoken: write });
|
|
978
|
+
}
|
|
979
|
+
function scheduleTcTokenIndexSave() {
|
|
980
|
+
if (tcTokenIndexTimer) {
|
|
981
|
+
clearTimeout(tcTokenIndexTimer);
|
|
982
|
+
}
|
|
983
|
+
tcTokenIndexTimer = setTimeout(() => {
|
|
984
|
+
tcTokenIndexTimer = undefined;
|
|
985
|
+
flushTcTokenIndex().catch(err => {
|
|
986
|
+
logger.warn({ err: err?.message }, 'failed to save tctoken index');
|
|
987
|
+
});
|
|
988
|
+
}, 5000);
|
|
989
|
+
}
|
|
990
|
+
function trackTcTokenJid(jid) {
|
|
991
|
+
if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
|
|
992
|
+
tcTokenKnownJids.add(jid);
|
|
993
|
+
scheduleTcTokenIndexSave();
|
|
994
|
+
}
|
|
995
|
+
}
|
|
707
996
|
const handlePrivacyTokenNotification = async (node) => {
|
|
708
997
|
const tokensNode = getBinaryNodeChild(node, 'tokens');
|
|
709
|
-
const from = jidNormalizedUser(node.attrs.from);
|
|
710
998
|
if (!tokensNode)
|
|
711
999
|
return;
|
|
712
|
-
const
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
}
|
|
1000
|
+
const from = jidNormalizedUser(node.attrs.from);
|
|
1001
|
+
// WA Web uses: senderLid ?? toLid(from) for the storage key
|
|
1002
|
+
// The sender_lid attribute provides the LID directly when available
|
|
1003
|
+
const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid))
|
|
1004
|
+
? jidNormalizedUser(node.attrs.sender_lid)
|
|
1005
|
+
: undefined;
|
|
1006
|
+
const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN));
|
|
1007
|
+
logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification');
|
|
1008
|
+
await storeTcTokensFromIqResult({
|
|
1009
|
+
result: node,
|
|
1010
|
+
fallbackJid,
|
|
1011
|
+
keys: authState.keys,
|
|
1012
|
+
getLIDForPN,
|
|
1013
|
+
onNewJidStored: trackTcTokenJid
|
|
1014
|
+
});
|
|
728
1015
|
};
|
|
729
1016
|
async function decipherLinkPublicKey(data) {
|
|
730
1017
|
const buffer = toRequiredBuffer(data);
|
|
@@ -750,10 +1037,11 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
750
1037
|
const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
|
|
751
1038
|
await msgRetryCache.set(key, newValue);
|
|
752
1039
|
};
|
|
753
|
-
const sendMessagesAgain = async (key, ids, retryNode) => {
|
|
1040
|
+
const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
|
|
754
1041
|
const remoteJid = key.remoteJid;
|
|
755
1042
|
const participant = key.participant || remoteJid;
|
|
756
1043
|
const retryCount = +retryNode.attrs.count || 1;
|
|
1044
|
+
const msgId = ids[0];
|
|
757
1045
|
// Try to get messages from cache first, then fallback to getMessage
|
|
758
1046
|
const msgs = [];
|
|
759
1047
|
for (const id of ids) {
|
|
@@ -785,12 +1073,49 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
785
1073
|
// just re-send the message to everyone
|
|
786
1074
|
// prevents the first message decryption failure
|
|
787
1075
|
const sendToAll = !jidDecode(participant)?.device;
|
|
788
|
-
|
|
1076
|
+
const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
|
|
1077
|
+
let injectedFromBundle = false;
|
|
1078
|
+
const bundle = extractE2ESessionFromRetryReceipt(receiptNode);
|
|
1079
|
+
if (bundle) {
|
|
1080
|
+
try {
|
|
1081
|
+
await signalRepository.injectE2ESession({ jid: participant, session: bundle });
|
|
1082
|
+
injectedFromBundle = true;
|
|
1083
|
+
logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle');
|
|
1084
|
+
}
|
|
1085
|
+
catch (error) {
|
|
1086
|
+
logger.warn({ error, participant }, 'failed to inject session from retry receipt');
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
if (!injectedFromBundle) {
|
|
1090
|
+
const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4);
|
|
1091
|
+
if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
|
|
1092
|
+
const info = await signalRepository.getSessionInfo(participant);
|
|
1093
|
+
if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
|
|
1094
|
+
logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session');
|
|
1095
|
+
await authState.keys.set({ session: { [sessionId]: null } });
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
const BASE_KEY_CHECK_RETRY = 2;
|
|
1100
|
+
if (msgId && messageRetryManager) {
|
|
1101
|
+
const info = await signalRepository.getSessionInfo(participant);
|
|
1102
|
+
if (info) {
|
|
1103
|
+
if (retryCount === BASE_KEY_CHECK_RETRY) {
|
|
1104
|
+
messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
|
|
1105
|
+
}
|
|
1106
|
+
else if (retryCount > BASE_KEY_CHECK_RETRY) {
|
|
1107
|
+
if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
|
|
1108
|
+
logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session');
|
|
1109
|
+
await authState.keys.set({ session: { [sessionId]: null } });
|
|
1110
|
+
}
|
|
1111
|
+
messageRetryManager.deleteBaseKey(sessionId, msgId);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
789
1115
|
let shouldRecreateSession = false;
|
|
790
1116
|
let recreateReason = '';
|
|
791
|
-
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
|
|
1117
|
+
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
|
|
792
1118
|
try {
|
|
793
|
-
const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
|
|
794
1119
|
const hasSession = await signalRepository.validateSession(participant);
|
|
795
1120
|
const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
|
|
796
1121
|
shouldRecreateSession = result.recreate;
|
|
@@ -804,11 +1129,13 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
804
1129
|
logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
|
|
805
1130
|
}
|
|
806
1131
|
}
|
|
807
|
-
|
|
1132
|
+
if (!injectedFromBundle) {
|
|
1133
|
+
await assertSessions([participant], true);
|
|
1134
|
+
}
|
|
808
1135
|
if (isJidGroup(remoteJid)) {
|
|
809
1136
|
await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
|
|
810
1137
|
}
|
|
811
|
-
logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, '
|
|
1138
|
+
logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
|
|
812
1139
|
for (const [i, msg] of msgs.entries()) {
|
|
813
1140
|
if (!ids[i])
|
|
814
1141
|
continue;
|
|
@@ -843,11 +1170,6 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
843
1170
|
fromMe,
|
|
844
1171
|
participant: attrs.participant
|
|
845
1172
|
};
|
|
846
|
-
if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
|
|
847
|
-
logger.debug({ remoteJid }, 'ignoring receipt from jid');
|
|
848
|
-
await sendMessageAck(node);
|
|
849
|
-
return;
|
|
850
|
-
}
|
|
851
1173
|
const ids = [attrs.id];
|
|
852
1174
|
if (Array.isArray(content)) {
|
|
853
1175
|
const items = getBinaryNodeChildren(content[0], 'item');
|
|
@@ -889,7 +1211,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
889
1211
|
try {
|
|
890
1212
|
await updateSendMessageAgainCount(ids[0], key.participant);
|
|
891
1213
|
logger.debug({ attrs, key }, 'recv retry request');
|
|
892
|
-
await sendMessagesAgain(key, ids, retryNode);
|
|
1214
|
+
await sendMessagesAgain(key, ids, retryNode, node);
|
|
893
1215
|
}
|
|
894
1216
|
catch (error) {
|
|
895
1217
|
logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
|
|
@@ -907,16 +1229,11 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
907
1229
|
]);
|
|
908
1230
|
}
|
|
909
1231
|
finally {
|
|
910
|
-
await sendMessageAck(node);
|
|
1232
|
+
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
|
|
911
1233
|
}
|
|
912
1234
|
};
|
|
913
1235
|
const handleNotification = async (node) => {
|
|
914
1236
|
const remoteJid = node.attrs.from;
|
|
915
|
-
if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
|
|
916
|
-
logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
|
|
917
|
-
await sendMessageAck(node);
|
|
918
|
-
return;
|
|
919
|
-
}
|
|
920
1237
|
try {
|
|
921
1238
|
await Promise.all([
|
|
922
1239
|
notificationMutex.mutex(async () => {
|
|
@@ -929,6 +1246,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
929
1246
|
fromMe,
|
|
930
1247
|
participant: node.attrs.participant,
|
|
931
1248
|
participantAlt,
|
|
1249
|
+
participantUsername: node.attrs.participant_username,
|
|
932
1250
|
addressingMode,
|
|
933
1251
|
id: node.attrs.id,
|
|
934
1252
|
...(msg.key || {})
|
|
@@ -942,253 +1260,10 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
942
1260
|
]);
|
|
943
1261
|
}
|
|
944
1262
|
finally {
|
|
945
|
-
await sendMessageAck(node);
|
|
946
|
-
}
|
|
947
|
-
};
|
|
948
|
-
const resolveMentionedLIDs = async (msg, lidMapping) => {
|
|
949
|
-
if (msg.key?.participant?.endsWith('@lid')) {
|
|
950
|
-
try {
|
|
951
|
-
const pn = await lidMapping.getPNForLID(msg.key.participant);
|
|
952
|
-
if (pn) {
|
|
953
|
-
logger.debug({ lid: msg.key.participant, pn }, 'resolved key.participant LID → PN');
|
|
954
|
-
msg.key.participant = pn;
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
catch { }
|
|
958
|
-
}
|
|
959
|
-
if (msg.key?.remoteJid?.endsWith('@lid')) {
|
|
960
|
-
try {
|
|
961
|
-
const pn = await lidMapping.getPNForLID(msg.key.remoteJid);
|
|
962
|
-
if (pn) {
|
|
963
|
-
logger.debug({ lid: msg.key.remoteJid, pn }, 'resolved key.remoteJid LID → PN');
|
|
964
|
-
msg.key.remoteJid = pn;
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
catch { }
|
|
968
|
-
}
|
|
969
|
-
const msgContent = msg.message;
|
|
970
|
-
if (!msgContent)
|
|
971
|
-
return;
|
|
972
|
-
const getContextInfo = (content) => {
|
|
973
|
-
if (!content || typeof content !== 'object')
|
|
974
|
-
return null;
|
|
975
|
-
if (content.contextInfo)
|
|
976
|
-
return content.contextInfo;
|
|
977
|
-
for (const val of Object.values(content)) {
|
|
978
|
-
const found = getContextInfo(val);
|
|
979
|
-
if (found)
|
|
980
|
-
return found;
|
|
981
|
-
}
|
|
982
|
-
return null;
|
|
983
|
-
};
|
|
984
|
-
const getTextField = (content) => {
|
|
985
|
-
if (!content || typeof content !== 'object')
|
|
986
|
-
return null;
|
|
987
|
-
for (const key of ['text', 'caption', 'conversation']) {
|
|
988
|
-
if (typeof content[key] === 'string')
|
|
989
|
-
return { obj: content, key };
|
|
990
|
-
}
|
|
991
|
-
for (const val of Object.values(content)) {
|
|
992
|
-
const found = getTextField(val);
|
|
993
|
-
if (found)
|
|
994
|
-
return found;
|
|
995
|
-
}
|
|
996
|
-
return null;
|
|
997
|
-
};
|
|
998
|
-
// Resolve semua contextInfo termasuk yang ada di dalam quotedMessage
|
|
999
|
-
const getAllContextInfos = (content, results = []) => {
|
|
1000
|
-
if (!content || typeof content !== 'object') return results;
|
|
1001
|
-
if (content.contextInfo) {
|
|
1002
|
-
results.push(content.contextInfo);
|
|
1003
|
-
// Juga cari di dalam quotedMessage secara rekursif
|
|
1004
|
-
if (content.contextInfo.quotedMessage) {
|
|
1005
|
-
getAllContextInfos(content.contextInfo.quotedMessage, results);
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
for (const val of Object.values(content)) {
|
|
1009
|
-
if (val && typeof val === 'object' && !results.includes(val)) {
|
|
1010
|
-
getAllContextInfos(val, results);
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
return results;
|
|
1014
|
-
};
|
|
1015
|
-
const contextInfo = getContextInfo(msgContent);
|
|
1016
|
-
// Resolve participant LID di semua contextInfo (termasuk quotedMessage)
|
|
1017
|
-
const allContextInfos = getAllContextInfos(msgContent);
|
|
1018
|
-
for (const ctx of allContextInfos) {
|
|
1019
|
-
if (ctx?.participant?.endsWith('@lid')) {
|
|
1020
|
-
try {
|
|
1021
|
-
const pn = await lidMapping.getPNForLID(ctx.participant);
|
|
1022
|
-
if (pn) {
|
|
1023
|
-
logger.debug({ lid: ctx.participant, pn }, 'resolved nested contextInfo.participant LID → PN');
|
|
1024
|
-
ctx.participant = pn;
|
|
1025
|
-
}
|
|
1026
|
-
} catch { }
|
|
1027
|
-
}
|
|
1028
|
-
// Resolve mentionedJid di quotedMessage contextInfo juga
|
|
1029
|
-
if (ctx !== contextInfo && ctx?.mentionedJid?.length) {
|
|
1030
|
-
const lids = ctx.mentionedJid.filter(j => j?.endsWith('@lid'));
|
|
1031
|
-
for (const lid of lids) {
|
|
1032
|
-
try {
|
|
1033
|
-
const pn = await lidMapping.getPNForLID(lid);
|
|
1034
|
-
if (pn) ctx.mentionedJid = ctx.mentionedJid.map(j => j === lid ? pn : j);
|
|
1035
|
-
} catch { }
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
// resolve contextInfo.participant (sender of quoted message) jika masih LID
|
|
1040
|
-
if (contextInfo?.participant?.endsWith('@lid')) {
|
|
1041
|
-
try {
|
|
1042
|
-
const pn = await lidMapping.getPNForLID(contextInfo.participant);
|
|
1043
|
-
if (pn) {
|
|
1044
|
-
logger.debug({ lid: contextInfo.participant, pn }, 'resolved contextInfo.participant LID → PN');
|
|
1045
|
-
contextInfo.participant = pn;
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
catch { }
|
|
1049
|
-
}
|
|
1050
|
-
if (!contextInfo?.mentionedJid?.length)
|
|
1051
|
-
return;
|
|
1052
|
-
// Fix text yang masih mengandung LID number meskipun mentionedJid sudah resolved ke PN
|
|
1053
|
-
// Kasus: mentionedJid sudah jadi @s.whatsapp.net tapi text masih "@165159209271535" (LID num)
|
|
1054
|
-
const textFieldEarly = getTextField(msgContent);
|
|
1055
|
-
if (textFieldEarly) {
|
|
1056
|
-
let earlyText = textFieldEarly.obj[textFieldEarly.key] || '';
|
|
1057
|
-
// Cek apakah text mengandung @angka panjang (>12 digit = kemungkinan LID number bukan nomor HP)
|
|
1058
|
-
const lidNumPattern = /@(\d{13,20})/g;
|
|
1059
|
-
const lidNumMatches = [...earlyText.matchAll(lidNumPattern)];
|
|
1060
|
-
if (lidNumMatches.length > 0) {
|
|
1061
|
-
// Untuk setiap mentionedJid yang sudah resolved, cek apakah ada LID number di text
|
|
1062
|
-
for (const resolvedJid of contextInfo.mentionedJid) {
|
|
1063
|
-
if (resolvedJid?.endsWith('@lid')) continue; // belum resolved, skip dulu
|
|
1064
|
-
const pnNum = resolvedJid.split('@')[0].split(':')[0];
|
|
1065
|
-
if (!pnNum) continue;
|
|
1066
|
-
// Cari LID number di text yang paling mungkin match (berdasarkan urutan)
|
|
1067
|
-
for (const match of lidNumMatches) {
|
|
1068
|
-
const lidNum = match[1];
|
|
1069
|
-
if (earlyText.includes(`@${lidNum}`)) {
|
|
1070
|
-
earlyText = earlyText.split(`@${lidNum}`).join(`@${pnNum}`);
|
|
1071
|
-
logger.debug({ lidNum, pnNum }, 'replaced LID number in text with PN number');
|
|
1072
|
-
break;
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1076
|
-
textFieldEarly.obj[textFieldEarly.key] = earlyText;
|
|
1077
|
-
}
|
|
1078
|
-
}
|
|
1079
|
-
const hasLid = contextInfo.mentionedJid.some((j) => j?.endsWith('@lid'));
|
|
1080
|
-
if (!hasLid)
|
|
1081
|
-
return;
|
|
1082
|
-
const lidJids = contextInfo.mentionedJid.filter((j) => j?.endsWith('@lid'));
|
|
1083
|
-
const resolveMap = new Map();
|
|
1084
|
-
const stillUnresolved = [];
|
|
1085
|
-
for (const lidJid of lidJids) {
|
|
1086
|
-
try {
|
|
1087
|
-
const pn = await lidMapping.getPNForLID(lidJid);
|
|
1088
|
-
if (pn) {
|
|
1089
|
-
resolveMap.set(lidJid, pn);
|
|
1090
|
-
}
|
|
1091
|
-
else {
|
|
1092
|
-
stillUnresolved.push(lidJid);
|
|
1093
|
-
}
|
|
1094
|
-
}
|
|
1095
|
-
catch {
|
|
1096
|
-
stillUnresolved.push(lidJid);
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
if (stillUnresolved.length > 0) {
|
|
1100
|
-
try {
|
|
1101
|
-
const usyncQ = new USyncQuery()
|
|
1102
|
-
.withContactProtocol()
|
|
1103
|
-
.withContext('background');
|
|
1104
|
-
for (const lidJid of stillUnresolved) {
|
|
1105
|
-
usyncQ.withUser(new USyncUser().withId(lidJid));
|
|
1106
|
-
}
|
|
1107
|
-
const result = await sock.executeUSyncQuery(usyncQ);
|
|
1108
|
-
if (result?.list) {
|
|
1109
|
-
const mappings = [];
|
|
1110
|
-
for (const item of result.list) {
|
|
1111
|
-
// item.id bisa berupa PN (@s.whatsapp.net) atau LID (@lid)
|
|
1112
|
-
// stillUnresolved berisi LID. Match berdasarkan numeric prefix
|
|
1113
|
-
const itemNum = (item.id ?? '').split('@')[0].split(':')[0];
|
|
1114
|
-
const lidJid = stillUnresolved.find(l => {
|
|
1115
|
-
if (l === item.id) return true;
|
|
1116
|
-
const lNum = l.split('@')[0].split(':')[0];
|
|
1117
|
-
return itemNum && lNum && itemNum === lNum;
|
|
1118
|
-
});
|
|
1119
|
-
if (lidJid && item.id && !item.id.endsWith('@lid')) {
|
|
1120
|
-
resolveMap.set(lidJid, item.id);
|
|
1121
|
-
mappings.push({ lid: lidJid, pn: item.id });
|
|
1122
|
-
logger.debug({ lid: lidJid, pn: item.id }, 'USync resolved LID → PN');
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
if (mappings.length > 0) {
|
|
1126
|
-
lidMapping.storeLIDPNMappings(mappings).catch(() => { });
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
catch (e) {
|
|
1131
|
-
logger.debug({ err: e }, 'USync LID resolve failed, using cache only');
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
// ── Text-based PN extraction ─────────────────────────────────────────────
|
|
1135
|
-
// WA kadang sudah resolve nomor HP di text (@6285133801810) tapi mentionedJid
|
|
1136
|
-
// masih berisi LID. Kita ekstrak semua @nomor dari text lalu matching ke LID
|
|
1137
|
-
// yang masih unresolved berdasarkan urutan kemunculan di mentionedJid.
|
|
1138
|
-
const textField = getTextField(msgContent);
|
|
1139
|
-
const stillUnresolvedAfterUSync = lidJids.filter(l => !resolveMap.has(l));
|
|
1140
|
-
if (stillUnresolvedAfterUSync.length > 0 && textField) {
|
|
1141
|
-
const rawText = textField.obj[textField.key] || '';
|
|
1142
|
-
// Ekstrak semua mention @nomor dari text (hanya angka, min 7 digit)
|
|
1143
|
-
const mentionMatches = [...rawText.matchAll(/@(\d{7,15})/g)].map(m => m[1]);
|
|
1144
|
-
if (mentionMatches.length > 0) {
|
|
1145
|
-
// Match LID ke nomor berdasarkan urutan index di mentionedJid
|
|
1146
|
-
const lidOrder = contextInfo.mentionedJid
|
|
1147
|
-
.map((jid, idx) => ({ jid, idx }))
|
|
1148
|
-
.filter(({ jid }) => stillUnresolvedAfterUSync.includes(jid));
|
|
1149
|
-
for (let i = 0; i < lidOrder.length && i < mentionMatches.length; i++) {
|
|
1150
|
-
const lidJid = lidOrder[i].jid;
|
|
1151
|
-
const phoneNum = mentionMatches[i];
|
|
1152
|
-
const pnJid = `${phoneNum}@s.whatsapp.net`;
|
|
1153
|
-
resolveMap.set(lidJid, pnJid);
|
|
1154
|
-
// Simpan mapping baru ini ke store untuk request berikutnya
|
|
1155
|
-
lidMapping.storeLIDPNMappings([{ lid: lidJid, pn: pnJid }]).catch(() => {});
|
|
1156
|
-
logger.debug({ lid: lidJid, pn: pnJid }, 'text-extracted PN for LID → PN');
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
// ── End text-based PN extraction ─────────────────────────────────────────
|
|
1161
|
-
|
|
1162
|
-
contextInfo.mentionedJid = contextInfo.mentionedJid.map((jid) => {
|
|
1163
|
-
if (!jid?.endsWith('@lid'))
|
|
1164
|
-
return jid;
|
|
1165
|
-
const resolved = resolveMap.get(jid);
|
|
1166
|
-
if (resolved) {
|
|
1167
|
-
logger.debug({ lid: jid, pn: resolved }, 'resolved mentionedJid LID → PN');
|
|
1168
|
-
return resolved;
|
|
1169
|
-
}
|
|
1170
|
-
// Tetap kembalikan LID jika benar-benar tidak bisa di-resolve
|
|
1171
|
-
return jid;
|
|
1172
|
-
});
|
|
1173
|
-
if (textField) {
|
|
1174
|
-
let text = textField.obj[textField.key];
|
|
1175
|
-
// Replace LID number di text dengan PN number yang sudah di-resolve
|
|
1176
|
-
for (const [lidJid, pnJid] of resolveMap) {
|
|
1177
|
-
const lidNum = lidJid.split('@')[0].split(':')[0] ?? '';
|
|
1178
|
-
const pnNum = pnJid.replace('@s.whatsapp.net', '').split(':')[0] ?? '';
|
|
1179
|
-
if (lidNum && pnNum && text.includes(lidNum)) {
|
|
1180
|
-
text = text.split(lidNum).join(pnNum);
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
textField.obj[textField.key] = text;
|
|
1263
|
+
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
|
|
1184
1264
|
}
|
|
1185
1265
|
};
|
|
1186
1266
|
const handleMessage = async (node) => {
|
|
1187
|
-
if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
|
|
1188
|
-
logger.debug({ key: node.attrs.key }, 'ignored message');
|
|
1189
|
-
await sendMessageAck(node, NACK_REASONS.UnhandledError);
|
|
1190
|
-
return;
|
|
1191
|
-
}
|
|
1192
1267
|
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1193
1268
|
// TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
|
|
1194
1269
|
if (encNode?.attrs.type === 'msmsg') {
|
|
@@ -1196,36 +1271,34 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1196
1271
|
await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
|
|
1197
1272
|
return;
|
|
1198
1273
|
}
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
await signalRepository.
|
|
1274
|
+
let acked = false;
|
|
1275
|
+
try {
|
|
1276
|
+
const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
|
|
1277
|
+
const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
|
|
1278
|
+
// store new mappings we didn't have before
|
|
1279
|
+
if (!!alt) {
|
|
1280
|
+
const altServer = jidDecode(alt)?.server;
|
|
1281
|
+
const primaryJid = msg.key.participant || msg.key.remoteJid;
|
|
1282
|
+
if (altServer === 'lid') {
|
|
1283
|
+
if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
|
|
1284
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
|
|
1285
|
+
await signalRepository.migrateSession(primaryJid, alt);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
else {
|
|
1289
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
|
|
1290
|
+
await signalRepository.migrateSession(alt, primaryJid);
|
|
1209
1291
|
}
|
|
1210
1292
|
}
|
|
1211
|
-
else {
|
|
1212
|
-
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
|
|
1213
|
-
await signalRepository.migrateSession(alt, primaryJid);
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
|
|
1217
|
-
messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
|
|
1218
|
-
logger.debug({
|
|
1219
|
-
jid: msg.key.remoteJid,
|
|
1220
|
-
id: msg.key.id
|
|
1221
|
-
}, 'Added message to recent cache for retry receipts');
|
|
1222
|
-
}
|
|
1223
|
-
try {
|
|
1224
1293
|
await messageMutex.mutex(async () => {
|
|
1225
1294
|
await decrypt();
|
|
1295
|
+
if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
|
|
1296
|
+
messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
|
|
1297
|
+
}
|
|
1226
1298
|
// message failed to decrypt
|
|
1227
1299
|
if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
|
|
1228
1300
|
if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
|
|
1301
|
+
acked = true;
|
|
1229
1302
|
return sendMessageAck(node, NACK_REASONS.ParsingError);
|
|
1230
1303
|
}
|
|
1231
1304
|
if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
|
|
@@ -1237,11 +1310,13 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1237
1310
|
unavailableType === 'hosted_unavailable_fanout' ||
|
|
1238
1311
|
unavailableType === 'view_once_unavailable_fanout') {
|
|
1239
1312
|
logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
|
|
1313
|
+
acked = true;
|
|
1240
1314
|
return sendMessageAck(node);
|
|
1241
1315
|
}
|
|
1242
1316
|
const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
|
|
1243
1317
|
if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
|
|
1244
1318
|
logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
|
|
1319
|
+
acked = true;
|
|
1245
1320
|
return sendMessageAck(node);
|
|
1246
1321
|
}
|
|
1247
1322
|
// Request the real content from the phone via placeholder resend PDO.
|
|
@@ -1278,6 +1353,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1278
1353
|
.catch(err => {
|
|
1279
1354
|
logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
|
|
1280
1355
|
});
|
|
1356
|
+
acked = true;
|
|
1281
1357
|
await sendMessageAck(node);
|
|
1282
1358
|
// Don't return — fall through to upsertMessage so the stub is emitted
|
|
1283
1359
|
}
|
|
@@ -1287,32 +1363,18 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1287
1363
|
const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
|
|
1288
1364
|
if (messageAge > STATUS_EXPIRY_SECONDS) {
|
|
1289
1365
|
logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
|
|
1366
|
+
acked = true;
|
|
1290
1367
|
return sendMessageAck(node);
|
|
1291
1368
|
}
|
|
1292
1369
|
}
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
|
|
1296
|
-
// Handle both pre-key and normal retries in single mutex
|
|
1370
|
+
logger.debug('[handleMessage] Attempting retry request for failed decryption');
|
|
1371
|
+
// WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
|
|
1297
1372
|
await retryMutex.mutex(async () => {
|
|
1298
1373
|
try {
|
|
1299
1374
|
if (!ws.isOpen) {
|
|
1300
1375
|
logger.debug({ node }, 'Connection closed, skipping retry');
|
|
1301
1376
|
return;
|
|
1302
1377
|
}
|
|
1303
|
-
// Handle pre-key errors with upload and delay
|
|
1304
|
-
if (isPreKeyError) {
|
|
1305
|
-
logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
|
|
1306
|
-
try {
|
|
1307
|
-
logger.debug('Uploading pre-keys for error recovery');
|
|
1308
|
-
await uploadPreKeys(5);
|
|
1309
|
-
logger.debug('Waiting for server to process new pre-keys');
|
|
1310
|
-
await delay(1000);
|
|
1311
|
-
}
|
|
1312
|
-
catch (uploadErr) {
|
|
1313
|
-
logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
1378
|
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1317
1379
|
await sendRetryRequest(node, !encNode);
|
|
1318
1380
|
if (retryRequestDelayMs) {
|
|
@@ -1320,16 +1382,9 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1320
1382
|
}
|
|
1321
1383
|
}
|
|
1322
1384
|
catch (err) {
|
|
1323
|
-
logger.error({ err
|
|
1324
|
-
// Still attempt retry even if pre-key upload failed
|
|
1325
|
-
try {
|
|
1326
|
-
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1327
|
-
await sendRetryRequest(node, !encNode);
|
|
1328
|
-
}
|
|
1329
|
-
catch (retryErr) {
|
|
1330
|
-
logger.error({ retryErr }, 'Failed to send retry after error handling');
|
|
1331
|
-
}
|
|
1385
|
+
logger.error({ err }, 'Failed to send retry');
|
|
1332
1386
|
}
|
|
1387
|
+
acked = true;
|
|
1333
1388
|
await sendMessageAck(node, NACK_REASONS.UnhandledError);
|
|
1334
1389
|
});
|
|
1335
1390
|
}
|
|
@@ -1358,6 +1413,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1358
1413
|
else if (!sendActiveReceipts) {
|
|
1359
1414
|
type = 'inactive';
|
|
1360
1415
|
}
|
|
1416
|
+
acked = true;
|
|
1361
1417
|
await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
|
|
1362
1418
|
// send ack for history message
|
|
1363
1419
|
const isAnyHistoryMsg = getHistoryMsg(msg.message);
|
|
@@ -1367,147 +1423,73 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1367
1423
|
}
|
|
1368
1424
|
}
|
|
1369
1425
|
else {
|
|
1426
|
+
acked = true;
|
|
1370
1427
|
await sendMessageAck(node);
|
|
1371
1428
|
logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
|
|
1372
1429
|
}
|
|
1373
1430
|
}
|
|
1374
1431
|
cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
|
|
1375
|
-
await resolveMentionedLIDs(msg, signalRepository.lidMapping);
|
|
1376
|
-
// ── Post-resolve: fix semua LID yang tersisa di message object ────────
|
|
1377
|
-
// Setelah resolveMentionedLIDs:
|
|
1378
|
-
// 1. Fix text yang masih "@LIDnum" → "@PNnum"
|
|
1379
|
-
// 2. Fix contextInfo.participant yang masih @lid (sender quoted)
|
|
1380
|
-
// 3. Fix mentionedJid & text di dalam quotedMessage
|
|
1381
|
-
try {
|
|
1382
|
-
const _safeSet = (obj, key, val) => {
|
|
1383
|
-
try { obj[key] = val; } catch (_) {
|
|
1384
|
-
// proto readonly fallback
|
|
1385
|
-
const proto = Object.getPrototypeOf(obj);
|
|
1386
|
-
const fresh = Object.assign(Object.create(proto), obj, { [key]: val });
|
|
1387
|
-
// replace reference di parent jika bisa — caller handles
|
|
1388
|
-
return fresh;
|
|
1389
|
-
}
|
|
1390
|
-
return obj;
|
|
1391
|
-
};
|
|
1392
|
-
const _fixTextLid = (innerMsg, mentionedJids, msgTypeLabel) => {
|
|
1393
|
-
const pnNumbers = (mentionedJids || [])
|
|
1394
|
-
.filter(j => j && !j.endsWith('@lid'))
|
|
1395
|
-
.map(j => j.split('@')[0].split(':')[0])
|
|
1396
|
-
.filter(Boolean);
|
|
1397
|
-
if (!pnNumbers.length) return;
|
|
1398
|
-
for (const textKey of ['text', 'caption', 'conversation']) {
|
|
1399
|
-
const originalText = innerMsg[textKey];
|
|
1400
|
-
if (typeof originalText !== 'string') continue;
|
|
1401
|
-
const lidPattern = /@(\d{13,20})/g;
|
|
1402
|
-
let newText = originalText;
|
|
1403
|
-
let match;
|
|
1404
|
-
let pnIdx = 0;
|
|
1405
|
-
while ((match = lidPattern.exec(originalText)) !== null) {
|
|
1406
|
-
if (pnIdx >= pnNumbers.length) break;
|
|
1407
|
-
const lidNum = match[1];
|
|
1408
|
-
const pnNum = pnNumbers[pnIdx++];
|
|
1409
|
-
newText = newText.split(`@${lidNum}`).join(`@${pnNum}`);
|
|
1410
|
-
logger.debug({ lidNum, pnNum, type: msgTypeLabel, textKey }, 'post-resolve: replaced LID num in text');
|
|
1411
|
-
}
|
|
1412
|
-
if (newText !== originalText) _safeSet(innerMsg, textKey, newText);
|
|
1413
|
-
}
|
|
1414
|
-
};
|
|
1415
|
-
const msgObj = msg.message;
|
|
1416
|
-
if (msgObj) {
|
|
1417
|
-
for (const msgType of Object.keys(msgObj)) {
|
|
1418
|
-
const innerMsg = msgObj[msgType];
|
|
1419
|
-
if (!innerMsg || typeof innerMsg !== 'object') continue;
|
|
1420
|
-
const ctxInfo = innerMsg.contextInfo;
|
|
1421
|
-
if (!ctxInfo) continue;
|
|
1422
|
-
// 1. Fix text LID → PN (pesan utama)
|
|
1423
|
-
if (ctxInfo.mentionedJid?.length) {
|
|
1424
|
-
_fixTextLid(innerMsg, ctxInfo.mentionedJid, msgType);
|
|
1425
|
-
}
|
|
1426
|
-
// 2. Fix contextInfo.participant (sender quoted) jika masih LID
|
|
1427
|
-
if (ctxInfo.participant?.endsWith('@lid')) {
|
|
1428
|
-
try {
|
|
1429
|
-
const pn = await signalRepository.lidMapping.getPNForLID(ctxInfo.participant);
|
|
1430
|
-
if (pn) {
|
|
1431
|
-
_safeSet(ctxInfo, 'participant', pn);
|
|
1432
|
-
logger.debug({ lid: ctxInfo.participant, pn }, 'post-resolve: fixed contextInfo.participant LID');
|
|
1433
|
-
}
|
|
1434
|
-
} catch (_) {}
|
|
1435
|
-
}
|
|
1436
|
-
// 3. Fix mentionedJid & text di dalam quotedMessage
|
|
1437
|
-
if (ctxInfo.quotedMessage) {
|
|
1438
|
-
for (const qType of Object.keys(ctxInfo.quotedMessage)) {
|
|
1439
|
-
const qInner = ctxInfo.quotedMessage[qType];
|
|
1440
|
-
if (!qInner || typeof qInner !== 'object') continue;
|
|
1441
|
-
const qCtx = qInner.contextInfo;
|
|
1442
|
-
if (!qCtx?.mentionedJid?.length) continue;
|
|
1443
|
-
// Resolve LID di mentionedJid quoted
|
|
1444
|
-
const resolvedQ = await Promise.all(
|
|
1445
|
-
qCtx.mentionedJid.map(async (jid) => {
|
|
1446
|
-
if (!jid?.endsWith('@lid')) return jid;
|
|
1447
|
-
try {
|
|
1448
|
-
const pn = await signalRepository.lidMapping.getPNForLID(jid);
|
|
1449
|
-
return pn || jid;
|
|
1450
|
-
} catch (_) { return jid; }
|
|
1451
|
-
})
|
|
1452
|
-
);
|
|
1453
|
-
if (resolvedQ.some((j, i) => j !== qCtx.mentionedJid[i])) {
|
|
1454
|
-
_safeSet(qCtx, 'mentionedJid', resolvedQ);
|
|
1455
|
-
logger.debug({ resolvedQ }, 'post-resolve: fixed quotedMessage mentionedJid');
|
|
1456
|
-
}
|
|
1457
|
-
// Fix text LID → PN di quoted
|
|
1458
|
-
_fixTextLid(qInner, resolvedQ, `quoted.${qType}`);
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
}
|
|
1462
|
-
}
|
|
1463
|
-
} catch (lidFixErr) {
|
|
1464
|
-
logger.debug({ err: lidFixErr }, 'post-resolve LID fix failed (non-critical)');
|
|
1465
|
-
}
|
|
1466
|
-
// ── End post-resolve fix ──────────────────────────────────────────────
|
|
1467
1432
|
await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
|
|
1468
1433
|
});
|
|
1469
1434
|
}
|
|
1470
1435
|
catch (error) {
|
|
1471
1436
|
logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
|
|
1437
|
+
if (!acked) {
|
|
1438
|
+
await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'));
|
|
1439
|
+
}
|
|
1472
1440
|
}
|
|
1473
1441
|
};
|
|
1474
1442
|
const handleCall = async (node) => {
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1443
|
+
try {
|
|
1444
|
+
const { attrs } = node;
|
|
1445
|
+
const [infoChild] = getAllBinaryNodeChildren(node);
|
|
1446
|
+
if (!infoChild) {
|
|
1447
|
+
throw new Boom('Missing call info in call node');
|
|
1448
|
+
}
|
|
1449
|
+
const status = getCallStatusFromNode(infoChild);
|
|
1450
|
+
const callId = infoChild.attrs['call-id'];
|
|
1451
|
+
const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
|
|
1452
|
+
const call = {
|
|
1453
|
+
chatId: attrs.from,
|
|
1454
|
+
from,
|
|
1455
|
+
callerPn: infoChild.attrs['caller_pn'],
|
|
1456
|
+
id: callId,
|
|
1457
|
+
date: new Date(+attrs.t * 1000),
|
|
1458
|
+
offline: !!attrs.offline,
|
|
1459
|
+
status
|
|
1460
|
+
};
|
|
1461
|
+
if (status === 'relaylatency') {
|
|
1462
|
+
const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
|
|
1463
|
+
const latencyMs = latencyValue ? Number(latencyValue) : undefined;
|
|
1464
|
+
if (Number.isFinite(latencyMs)) {
|
|
1465
|
+
call.latencyMs = latencyMs;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
if (status === 'offer') {
|
|
1469
|
+
call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
|
|
1470
|
+
call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
|
|
1471
|
+
call.groupJid = infoChild.attrs['group-jid'];
|
|
1472
|
+
await callOfferCache.set(call.id, call);
|
|
1473
|
+
}
|
|
1474
|
+
const existingCall = await callOfferCache.get(call.id);
|
|
1475
|
+
// use existing call info to populate this event
|
|
1476
|
+
if (existingCall) {
|
|
1477
|
+
call.isVideo = existingCall.isVideo;
|
|
1478
|
+
call.isGroup = existingCall.isGroup;
|
|
1479
|
+
call.callerPn = call.callerPn || existingCall.callerPn;
|
|
1480
|
+
}
|
|
1481
|
+
// delete data once call has ended
|
|
1482
|
+
if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
|
|
1483
|
+
await callOfferCache.del(call.id);
|
|
1484
|
+
}
|
|
1485
|
+
ev.emit('call', [call]);
|
|
1486
|
+
}
|
|
1487
|
+
catch (error) {
|
|
1488
|
+
logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call');
|
|
1489
|
+
}
|
|
1490
|
+
finally {
|
|
1491
|
+
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
|
|
1492
|
+
}
|
|
1511
1493
|
};
|
|
1512
1494
|
const handleBadAck = async ({ attrs }) => {
|
|
1513
1495
|
const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
|
|
@@ -1527,29 +1509,61 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1527
1509
|
// error in acknowledgement,
|
|
1528
1510
|
// device could not display the message
|
|
1529
1511
|
if (attrs.error) {
|
|
1530
|
-
|
|
1512
|
+
const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked);
|
|
1513
|
+
if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
|
|
1514
|
+
// 463 = 1:1 message missing privacy token (tctoken). Usually means the
|
|
1515
|
+
// account is restricted: WhatsApp blocks starting new chats but preserves
|
|
1516
|
+
// existing ones, since established chats already carry a tctoken.
|
|
1517
|
+
// WA Web prevents this client-side (disables the compose bar).
|
|
1518
|
+
// No retry — retrying counts as another "reach out" and worsens the restriction.
|
|
1519
|
+
logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact');
|
|
1520
|
+
const ackFrom = attrs.from;
|
|
1521
|
+
if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
|
|
1522
|
+
inFlight463Recoveries.add(ackFrom);
|
|
1523
|
+
void (async () => {
|
|
1524
|
+
try {
|
|
1525
|
+
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
|
|
1526
|
+
const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN);
|
|
1527
|
+
const issueJid = await resolveIssuanceJid(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
|
|
1528
|
+
const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds());
|
|
1529
|
+
await storeTcTokensFromIqResult({
|
|
1530
|
+
result,
|
|
1531
|
+
fallbackJid: tcStorageJid,
|
|
1532
|
+
keys: authState.keys,
|
|
1533
|
+
getLIDForPN,
|
|
1534
|
+
onNewJidStored: trackTcTokenJid
|
|
1535
|
+
});
|
|
1536
|
+
logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance');
|
|
1537
|
+
}
|
|
1538
|
+
catch (err) {
|
|
1539
|
+
logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance');
|
|
1540
|
+
}
|
|
1541
|
+
finally {
|
|
1542
|
+
inFlight463Recoveries.delete(ackFrom);
|
|
1543
|
+
}
|
|
1544
|
+
})();
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
|
|
1548
|
+
logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
|
|
1549
|
+
}
|
|
1550
|
+
else if (isReachoutTimelocked) {
|
|
1551
|
+
// user is temporarily restricted, fetch current restriction details
|
|
1552
|
+
await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'));
|
|
1553
|
+
logger.warn({ attrs }, 'received error in ack');
|
|
1554
|
+
}
|
|
1555
|
+
else {
|
|
1556
|
+
logger.warn({ attrs }, 'received error in ack');
|
|
1557
|
+
}
|
|
1531
1558
|
ev.emit('messages.update', [
|
|
1532
1559
|
{
|
|
1533
1560
|
key,
|
|
1534
1561
|
update: {
|
|
1535
1562
|
status: WAMessageStatus.ERROR,
|
|
1536
|
-
messageStubParameters: [attrs.error]
|
|
1563
|
+
messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
|
|
1537
1564
|
}
|
|
1538
1565
|
}
|
|
1539
1566
|
]);
|
|
1540
|
-
// resend the message with device_fanout=false, use at your own risk
|
|
1541
|
-
// if (attrs.error === '475') {
|
|
1542
|
-
// const msg = await getMessage(key)
|
|
1543
|
-
// if (msg) {
|
|
1544
|
-
// await relayMessage(key.remoteJid!, msg, {
|
|
1545
|
-
// messageId: key.id!,
|
|
1546
|
-
// useUserDevicesCache: false,
|
|
1547
|
-
// additionalAttributes: {
|
|
1548
|
-
// device_fanout: 'false'
|
|
1549
|
-
// }
|
|
1550
|
-
// })
|
|
1551
|
-
// }
|
|
1552
|
-
// }
|
|
1553
1567
|
}
|
|
1554
1568
|
};
|
|
1555
1569
|
/// processes a node with the given function
|
|
@@ -1562,53 +1576,30 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1562
1576
|
return exec(node, false).catch(err => onUnexpectedError(err, identifier));
|
|
1563
1577
|
}
|
|
1564
1578
|
};
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
]);
|
|
1576
|
-
const nodes = [];
|
|
1577
|
-
let isProcessing = false;
|
|
1578
|
-
// Number of nodes to process before yielding to event loop
|
|
1579
|
-
const BATCH_SIZE = 10;
|
|
1580
|
-
const enqueue = (type, node) => {
|
|
1581
|
-
nodes.push({ type, node });
|
|
1582
|
-
if (isProcessing) {
|
|
1583
|
-
return;
|
|
1584
|
-
}
|
|
1585
|
-
isProcessing = true;
|
|
1586
|
-
const promise = async () => {
|
|
1587
|
-
let processedInBatch = 0;
|
|
1588
|
-
while (nodes.length && ws.isOpen) {
|
|
1589
|
-
const { type, node } = nodes.shift();
|
|
1590
|
-
const nodeProcessor = nodeProcessorMap.get(type);
|
|
1591
|
-
if (!nodeProcessor) {
|
|
1592
|
-
onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
|
|
1593
|
-
continue;
|
|
1594
|
-
}
|
|
1595
|
-
await nodeProcessor(node);
|
|
1596
|
-
processedInBatch++;
|
|
1597
|
-
// Yield to event loop after processing a batch
|
|
1598
|
-
// This prevents blocking the event loop for too long when there are many offline nodes
|
|
1599
|
-
if (processedInBatch >= BATCH_SIZE) {
|
|
1600
|
-
processedInBatch = 0;
|
|
1601
|
-
await yieldToEventLoop();
|
|
1602
|
-
}
|
|
1603
|
-
}
|
|
1604
|
-
isProcessing = false;
|
|
1605
|
-
};
|
|
1606
|
-
promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
|
|
1607
|
-
};
|
|
1608
|
-
return { enqueue };
|
|
1609
|
-
};
|
|
1610
|
-
const offlineNodeProcessor = makeOfflineNodeProcessor();
|
|
1579
|
+
const offlineNodeProcessor = makeOfflineNodeProcessor(new Map([
|
|
1580
|
+
['message', handleMessage],
|
|
1581
|
+
['call', handleCall],
|
|
1582
|
+
['receipt', handleReceipt],
|
|
1583
|
+
['notification', handleNotification]
|
|
1584
|
+
]), {
|
|
1585
|
+
isWsOpen: () => ws.isOpen,
|
|
1586
|
+
onUnexpectedError,
|
|
1587
|
+
yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
|
|
1588
|
+
});
|
|
1611
1589
|
const processNode = async (type, node, identifier, exec) => {
|
|
1590
|
+
// Fast path: ack and drop ignored JIDs before entering the buffer/queue
|
|
1591
|
+
const from = node.attrs.from;
|
|
1592
|
+
let ignoreJid = from;
|
|
1593
|
+
if (type === 'receipt' && from) {
|
|
1594
|
+
const attrs = node.attrs;
|
|
1595
|
+
const isLid = attrs.from.includes('lid');
|
|
1596
|
+
const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
|
|
1597
|
+
ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
|
|
1598
|
+
}
|
|
1599
|
+
if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
|
|
1600
|
+
await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined);
|
|
1601
|
+
return;
|
|
1602
|
+
}
|
|
1612
1603
|
const isOffline = !!node.attrs.offline;
|
|
1613
1604
|
if (isOffline) {
|
|
1614
1605
|
offlineNodeProcessor.enqueue(type, node);
|
|
@@ -1664,12 +1655,110 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1664
1655
|
await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
|
|
1665
1656
|
}
|
|
1666
1657
|
});
|
|
1667
|
-
|
|
1658
|
+
/** timestamp of last tctoken prune run — throttles to once per 24h */
|
|
1659
|
+
let lastTcTokenPruneTs = 0;
|
|
1660
|
+
/** dedupe in-flight 463 recovery token issuance by target JID */
|
|
1661
|
+
const inFlight463Recoveries = new Set();
|
|
1662
|
+
ev.on('connection.update', ({ isOnline, connection }) => {
|
|
1668
1663
|
if (typeof isOnline !== 'undefined') {
|
|
1669
1664
|
sendActiveReceipts = isOnline;
|
|
1670
1665
|
logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
|
|
1671
1666
|
}
|
|
1667
|
+
// Flush pending tctoken index save on disconnect to avoid writing after close
|
|
1668
|
+
if (connection === 'close' && tcTokenIndexTimer) {
|
|
1669
|
+
clearTimeout(tcTokenIndexTimer);
|
|
1670
|
+
tcTokenIndexTimer = undefined;
|
|
1671
|
+
// Best-effort flush — may fail if store is already closed
|
|
1672
|
+
try {
|
|
1673
|
+
void Promise.resolve(flushTcTokenIndex()).catch(() => { });
|
|
1674
|
+
}
|
|
1675
|
+
catch {
|
|
1676
|
+
/* ignore sync errors */
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
// Prune expired tctokens when coming online, at most once per 24 hours
|
|
1680
|
+
// Matches WA Web's CLEAN_TC_TOKENS task
|
|
1681
|
+
// Note: don't gate on tcTokenKnownJids.size — the index may still be loading
|
|
1682
|
+
if (isOnline) {
|
|
1683
|
+
const now = Date.now();
|
|
1684
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1685
|
+
if (now - lastTcTokenPruneTs >= DAY_MS) {
|
|
1686
|
+
lastTcTokenPruneTs = now;
|
|
1687
|
+
void pruneExpiredTcTokens();
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1672
1690
|
});
|
|
1691
|
+
registerSocketEndHandler(() => {
|
|
1692
|
+
if (!config.msgRetryCounterCache && msgRetryCache.close) {
|
|
1693
|
+
msgRetryCache.close();
|
|
1694
|
+
}
|
|
1695
|
+
if (!config.callOfferCache && callOfferCache.close) {
|
|
1696
|
+
callOfferCache.close();
|
|
1697
|
+
}
|
|
1698
|
+
identityAssertDebounce.close();
|
|
1699
|
+
sendActiveReceipts = false;
|
|
1700
|
+
});
|
|
1701
|
+
async function pruneExpiredTcTokens() {
|
|
1702
|
+
try {
|
|
1703
|
+
await tcTokenIndexLoaded;
|
|
1704
|
+
// Union with the persisted index picks up JIDs added by other layers
|
|
1705
|
+
// (history sync) without needing inter-module wiring.
|
|
1706
|
+
const persisted = await readTcTokenIndex(authState.keys);
|
|
1707
|
+
const allJids = new Set(tcTokenKnownJids);
|
|
1708
|
+
for (const jid of persisted)
|
|
1709
|
+
allJids.add(jid);
|
|
1710
|
+
if (!allJids.size)
|
|
1711
|
+
return;
|
|
1712
|
+
const jids = [...allJids];
|
|
1713
|
+
const allTokens = await authState.keys.get('tctoken', jids);
|
|
1714
|
+
const writes = {};
|
|
1715
|
+
const survivors = new Set();
|
|
1716
|
+
let mutated = 0;
|
|
1717
|
+
for (const jid of jids) {
|
|
1718
|
+
const entry = allTokens[jid];
|
|
1719
|
+
if (!entry) {
|
|
1720
|
+
// Tracked but nothing in store — drop from index.
|
|
1721
|
+
mutated++;
|
|
1722
|
+
continue;
|
|
1723
|
+
}
|
|
1724
|
+
const hasPeerToken = !!entry.token?.length;
|
|
1725
|
+
const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp);
|
|
1726
|
+
const hasSenderTs = entry.senderTimestamp !== undefined;
|
|
1727
|
+
const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp);
|
|
1728
|
+
const keepPeerToken = hasPeerToken && !peerTokenExpired;
|
|
1729
|
+
const keepSenderTs = hasSenderTs && !senderTsExpired;
|
|
1730
|
+
if (!keepPeerToken && !keepSenderTs) {
|
|
1731
|
+
writes[jid] = null;
|
|
1732
|
+
mutated++;
|
|
1733
|
+
}
|
|
1734
|
+
else if (peerTokenExpired && keepSenderTs) {
|
|
1735
|
+
writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp };
|
|
1736
|
+
survivors.add(jid);
|
|
1737
|
+
mutated++;
|
|
1738
|
+
}
|
|
1739
|
+
else {
|
|
1740
|
+
survivors.add(jid);
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
if (mutated === 0)
|
|
1744
|
+
return;
|
|
1745
|
+
await authState.keys.set({
|
|
1746
|
+
tctoken: {
|
|
1747
|
+
...writes,
|
|
1748
|
+
[TC_TOKEN_INDEX_KEY]: {
|
|
1749
|
+
token: Buffer.from(JSON.stringify([...survivors]))
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
});
|
|
1753
|
+
tcTokenKnownJids.clear();
|
|
1754
|
+
for (const jid of survivors)
|
|
1755
|
+
tcTokenKnownJids.add(jid);
|
|
1756
|
+
logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens');
|
|
1757
|
+
}
|
|
1758
|
+
catch (err) {
|
|
1759
|
+
logger.warn({ err: err?.message }, 'failed to prune expired tctokens');
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1673
1762
|
return {
|
|
1674
1763
|
...sock,
|
|
1675
1764
|
sendMessageAck,
|