@d0v3riz/baileys 7.0.0-rc.8 → 7.0.0-rc13
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/README.md +21 -15
- package/WAProto/fix-imports.js +74 -18
- package/WAProto/index.js +201 -160
- package/lib/Defaults/index.d.ts +19 -6
- package/lib/Defaults/index.d.ts.map +1 -1
- package/lib/Defaults/index.js +24 -10
- package/lib/Defaults/index.js.map +1 -1
- package/lib/Signal/libsignal.d.ts.map +1 -1
- package/lib/Signal/libsignal.js +105 -16
- package/lib/Signal/libsignal.js.map +1 -1
- package/lib/Signal/lid-mapping.d.ts +8 -8
- package/lib/Signal/lid-mapping.d.ts.map +1 -1
- package/lib/Signal/lid-mapping.js +176 -70
- package/lib/Signal/lid-mapping.js.map +1 -1
- package/lib/Socket/Client/websocket.d.ts +1 -1
- package/lib/Socket/Client/websocket.d.ts.map +1 -1
- package/lib/Socket/Client/websocket.js +5 -1
- package/lib/Socket/Client/websocket.js.map +1 -1
- package/lib/Socket/business.d.ts +36 -8
- package/lib/Socket/business.d.ts.map +1 -1
- package/lib/Socket/business.js +11 -8
- package/lib/Socket/business.js.map +1 -1
- package/lib/Socket/chats.d.ts +29 -5
- package/lib/Socket/chats.d.ts.map +1 -1
- package/lib/Socket/chats.js +292 -63
- package/lib/Socket/chats.js.map +1 -1
- package/lib/Socket/communities.d.ts +36 -8
- package/lib/Socket/communities.d.ts.map +1 -1
- package/lib/Socket/groups.d.ts +27 -5
- package/lib/Socket/groups.d.ts.map +1 -1
- package/lib/Socket/groups.js +20 -0
- package/lib/Socket/groups.js.map +1 -1
- package/lib/Socket/index.d.ts +36 -8
- package/lib/Socket/index.d.ts.map +1 -1
- package/lib/Socket/index.js +0 -6
- package/lib/Socket/index.js.map +1 -1
- package/lib/Socket/messages-recv.d.ts +40 -11
- package/lib/Socket/messages-recv.d.ts.map +1 -1
- package/lib/Socket/messages-recv.js +841 -354
- package/lib/Socket/messages-recv.js.map +1 -1
- package/lib/Socket/messages-send.d.ts +35 -6
- package/lib/Socket/messages-send.d.ts.map +1 -1
- package/lib/Socket/messages-send.js +263 -92
- package/lib/Socket/messages-send.js.map +1 -1
- package/lib/Socket/mex.d.ts.map +1 -1
- package/lib/Socket/mex.js +2 -0
- package/lib/Socket/mex.js.map +1 -1
- package/lib/Socket/newsletter.d.ts +27 -5
- package/lib/Socket/newsletter.d.ts.map +1 -1
- package/lib/Socket/newsletter.js +35 -3
- package/lib/Socket/newsletter.js.map +1 -1
- package/lib/Socket/socket.d.ts +9 -3
- package/lib/Socket/socket.d.ts.map +1 -1
- package/lib/Socket/socket.js +124 -39
- package/lib/Socket/socket.js.map +1 -1
- package/lib/Types/Auth.d.ts +2 -0
- package/lib/Types/Auth.d.ts.map +1 -1
- package/lib/Types/Call.d.ts +2 -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 +60 -6
- 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 +20 -5
- package/lib/Types/Message.d.ts.map +1 -1
- package/lib/Types/Message.js.map +1 -1
- package/lib/Types/{Newsletter.d.ts → Mex.d.ts} +13 -5
- package/lib/Types/Mex.d.ts.map +1 -0
- package/lib/Types/{Newsletter.js → Mex.js} +11 -3
- 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 +1 -1
- package/lib/Types/index.d.ts.map +1 -1
- package/lib/Types/index.js +1 -1
- 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 +65 -20
- package/lib/Utils/auth-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 +180 -71
- 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/crypto.d.ts +4 -8
- package/lib/Utils/crypto.d.ts.map +1 -1
- package/lib/Utils/crypto.js +2 -26
- package/lib/Utils/crypto.js.map +1 -1
- 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 +82 -8
- package/lib/Utils/event-buffer.js.map +1 -1
- package/lib/Utils/generics.d.ts +2 -0
- package/lib/Utils/generics.d.ts.map +1 -1
- package/lib/Utils/generics.js +13 -1
- package/lib/Utils/generics.js.map +1 -1
- package/lib/Utils/history.d.ts +8 -3
- package/lib/Utils/history.d.ts.map +1 -1
- package/lib/Utils/history.js +58 -14
- package/lib/Utils/history.js.map +1 -1
- package/lib/Utils/identity-change-handler.d.ts +44 -0
- package/lib/Utils/identity-change-handler.d.ts.map +1 -0
- package/lib/Utils/identity-change-handler.js +50 -0
- package/lib/Utils/identity-change-handler.js.map +1 -0
- package/lib/Utils/index.d.ts +3 -0
- package/lib/Utils/index.d.ts.map +1 -1
- package/lib/Utils/index.js +3 -0
- 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/lt-hash.d.ts +7 -12
- package/lib/Utils/lt-hash.d.ts.map +1 -1
- package/lib/Utils/lt-hash.js +2 -42
- package/lib/Utils/lt-hash.js.map +1 -1
- package/lib/Utils/make-mutex.d.ts +1 -0
- package/lib/Utils/make-mutex.d.ts.map +1 -1
- package/lib/Utils/make-mutex.js +20 -27
- package/lib/Utils/make-mutex.js.map +1 -1
- package/lib/Utils/message-retry-manager.d.ts +35 -2
- package/lib/Utils/message-retry-manager.d.ts.map +1 -1
- package/lib/Utils/message-retry-manager.js +98 -5
- package/lib/Utils/message-retry-manager.js.map +1 -1
- package/lib/Utils/messages-media.d.ts +22 -3
- package/lib/Utils/messages-media.d.ts.map +1 -1
- package/lib/Utils/messages-media.js +169 -44
- package/lib/Utils/messages-media.js.map +1 -1
- package/lib/Utils/messages.d.ts +2 -0
- package/lib/Utils/messages.d.ts.map +1 -1
- package/lib/Utils/messages.js +70 -27
- package/lib/Utils/messages.js.map +1 -1
- package/lib/Utils/noise-handler.d.ts +4 -4
- package/lib/Utils/noise-handler.d.ts.map +1 -1
- package/lib/Utils/noise-handler.js +139 -85
- package/lib/Utils/noise-handler.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 +165 -15
- package/lib/Utils/process-message.js.map +1 -1
- package/lib/Utils/reporting-utils.d.ts +11 -0
- package/lib/Utils/reporting-utils.d.ts.map +1 -0
- package/lib/Utils/reporting-utils.js +258 -0
- package/lib/Utils/reporting-utils.js.map +1 -0
- 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 +19 -0
- package/lib/Utils/sync-action-utils.d.ts.map +1 -0
- package/lib/Utils/sync-action-utils.js +49 -0
- package/lib/Utils/sync-action-utils.js.map +1 -0
- package/lib/Utils/tc-token-utils.d.ts +37 -0
- package/lib/Utils/tc-token-utils.d.ts.map +1 -0
- package/lib/Utils/tc-token-utils.js +163 -0
- package/lib/Utils/tc-token-utils.js.map +1 -0
- package/lib/Utils/validate-connection.d.ts.map +1 -1
- package/lib/Utils/validate-connection.js +4 -1
- package/lib/Utils/validate-connection.js.map +1 -1
- package/lib/WABinary/decode.d.ts.map +1 -1
- package/lib/WABinary/decode.js +24 -0
- package/lib/WABinary/decode.js.map +1 -1
- package/lib/WABinary/encode.js +5 -1
- package/lib/WABinary/encode.js.map +1 -1
- package/lib/WABinary/generic-utils.d.ts +1 -1
- package/lib/WABinary/generic-utils.d.ts.map +1 -1
- package/lib/WABinary/generic-utils.js +19 -8
- package/lib/WABinary/generic-utils.js.map +1 -1
- 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 +1 -0
- 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/package.json +39 -8
- package/lib/Types/Newsletter.d.ts.map +0 -1
- package/lib/Types/Newsletter.js.map +0 -1
|
@@ -3,17 +3,25 @@ import { Boom } from '@hapi/boom';
|
|
|
3
3
|
import { randomBytes } from 'crypto';
|
|
4
4
|
import Long from 'long';
|
|
5
5
|
import { proto } from '../../WAProto/index.js';
|
|
6
|
-
import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT } 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, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
|
|
6
|
+
import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/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';
|
|
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
|
+
}
|
|
13
20
|
export const makeMessagesRecvSocket = (config) => {
|
|
14
21
|
const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
|
|
15
22
|
const sock = makeMessagesSocket(config);
|
|
16
|
-
const { ev, authState, ws,
|
|
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);
|
|
17
25
|
/** this mutex ensures that each retryRequest will wait for the previous one to finish */
|
|
18
26
|
const retryMutex = makeMutex();
|
|
19
27
|
const msgRetryCache = config.msgRetryCounterCache ||
|
|
@@ -26,11 +34,6 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
26
34
|
stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
|
|
27
35
|
useClones: false
|
|
28
36
|
});
|
|
29
|
-
const placeholderResendCache = config.placeholderResendCache ||
|
|
30
|
-
new NodeCache({
|
|
31
|
-
stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
|
|
32
|
-
useClones: false
|
|
33
|
-
});
|
|
34
37
|
// Debounce identity-change session refreshes per JID to avoid bursts
|
|
35
38
|
const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
|
|
36
39
|
let sendActiveReceipts = false;
|
|
@@ -50,19 +53,21 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
50
53
|
};
|
|
51
54
|
return sendPeerDataOperationMessage(pdoMessage);
|
|
52
55
|
};
|
|
53
|
-
const requestPlaceholderResend = async (messageKey) => {
|
|
56
|
+
const requestPlaceholderResend = async (messageKey, msgData) => {
|
|
54
57
|
if (!authState.creds.me?.id) {
|
|
55
58
|
throw new Boom('Not authenticated');
|
|
56
59
|
}
|
|
57
|
-
if (placeholderResendCache.get(messageKey?.id)) {
|
|
60
|
+
if (await placeholderResendCache.get(messageKey?.id)) {
|
|
58
61
|
logger.debug({ messageKey }, 'already requested resend');
|
|
59
62
|
return;
|
|
60
63
|
}
|
|
61
64
|
else {
|
|
62
|
-
|
|
65
|
+
// Store original message data so PDO response handler can preserve
|
|
66
|
+
// metadata (LID details, timestamps, etc.) that the phone may omit
|
|
67
|
+
await placeholderResendCache.set(messageKey?.id, msgData || true);
|
|
63
68
|
}
|
|
64
|
-
await delay(
|
|
65
|
-
if (!placeholderResendCache.get(messageKey?.id)) {
|
|
69
|
+
await delay(2000);
|
|
70
|
+
if (!(await placeholderResendCache.get(messageKey?.id))) {
|
|
66
71
|
logger.debug({ messageKey }, 'message received while resend requested');
|
|
67
72
|
return 'RESOLVED';
|
|
68
73
|
}
|
|
@@ -75,32 +80,147 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
75
80
|
peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
|
|
76
81
|
};
|
|
77
82
|
setTimeout(async () => {
|
|
78
|
-
if (placeholderResendCache.get(messageKey?.id)) {
|
|
79
|
-
logger.debug({ messageKey }, 'PDO message without response after
|
|
83
|
+
if (await placeholderResendCache.get(messageKey?.id)) {
|
|
84
|
+
logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline');
|
|
80
85
|
await placeholderResendCache.del(messageKey?.id);
|
|
81
86
|
}
|
|
82
|
-
},
|
|
87
|
+
}, 8000);
|
|
83
88
|
return sendPeerDataOperationMessage(pdoMessage);
|
|
84
89
|
};
|
|
85
|
-
|
|
86
|
-
|
|
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) => {
|
|
87
193
|
const mexNode = getBinaryNodeChild(node, 'mex');
|
|
88
|
-
|
|
89
|
-
|
|
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');
|
|
90
198
|
return;
|
|
91
199
|
}
|
|
92
200
|
let data;
|
|
93
201
|
try {
|
|
94
|
-
|
|
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());
|
|
95
209
|
}
|
|
96
210
|
catch (error) {
|
|
97
|
-
logger.error({ err: error, node }, '
|
|
211
|
+
logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
|
|
98
212
|
return;
|
|
99
213
|
}
|
|
100
|
-
const operation = data?.operation;
|
|
101
|
-
|
|
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
|
+
}
|
|
102
222
|
if (!updates || !operation) {
|
|
103
|
-
logger.warn({ data }, '
|
|
223
|
+
logger.warn({ data }, 'invalid mex newsletter notification content');
|
|
104
224
|
return;
|
|
105
225
|
}
|
|
106
226
|
logger.info({ operation, updates }, 'got mex newsletter notification');
|
|
@@ -128,119 +248,119 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
128
248
|
}
|
|
129
249
|
}
|
|
130
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;
|
|
131
267
|
default:
|
|
132
|
-
logger.info({ operation, data }, '
|
|
268
|
+
logger.info({ operation, data }, 'unhandled mex newsletter notification');
|
|
133
269
|
break;
|
|
134
270
|
}
|
|
135
271
|
};
|
|
136
272
|
// Handles newsletter notifications
|
|
137
273
|
const handleNewsletterNotification = async (node) => {
|
|
138
274
|
const from = node.attrs.from;
|
|
139
|
-
const
|
|
275
|
+
const children = getAllBinaryNodeChildren(node);
|
|
140
276
|
const author = node.attrs.participant;
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
server_id: child.attrs.message_id,
|
|
147
|
-
reaction: {
|
|
148
|
-
code: getBinaryNodeChildString(child, 'reaction'),
|
|
149
|
-
count: 1
|
|
150
|
-
}
|
|
151
|
-
};
|
|
152
|
-
ev.emit('newsletter.reaction', reactionUpdate);
|
|
153
|
-
break;
|
|
154
|
-
case 'view':
|
|
155
|
-
const viewUpdate = {
|
|
156
|
-
id: from,
|
|
157
|
-
server_id: child.attrs.message_id,
|
|
158
|
-
count: parseInt(child.content?.toString() || '0', 10)
|
|
159
|
-
};
|
|
160
|
-
ev.emit('newsletter.view', viewUpdate);
|
|
161
|
-
break;
|
|
162
|
-
case 'participant':
|
|
163
|
-
const participantUpdate = {
|
|
164
|
-
id: from,
|
|
165
|
-
author,
|
|
166
|
-
user: child.attrs.jid,
|
|
167
|
-
action: child.attrs.action,
|
|
168
|
-
new_role: child.attrs.role
|
|
169
|
-
};
|
|
170
|
-
ev.emit('newsletter-participants.update', participantUpdate);
|
|
171
|
-
break;
|
|
172
|
-
case 'update':
|
|
173
|
-
const settingsNode = getBinaryNodeChild(child, 'settings');
|
|
174
|
-
if (settingsNode) {
|
|
175
|
-
const update = {};
|
|
176
|
-
const nameNode = getBinaryNodeChild(settingsNode, 'name');
|
|
177
|
-
if (nameNode?.content)
|
|
178
|
-
update.name = nameNode.content.toString();
|
|
179
|
-
const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
|
|
180
|
-
if (descriptionNode?.content)
|
|
181
|
-
update.description = descriptionNode.content.toString();
|
|
182
|
-
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 = {
|
|
183
282
|
id: from,
|
|
184
|
-
|
|
185
|
-
|
|
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;
|
|
186
291
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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
|
+
});
|
|
207
326
|
}
|
|
208
|
-
|
|
209
|
-
|
|
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
|
+
}
|
|
210
352
|
}
|
|
353
|
+
break;
|
|
211
354
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
break;
|
|
216
|
-
}
|
|
217
|
-
};
|
|
218
|
-
const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
|
|
219
|
-
const stanza = {
|
|
220
|
-
tag: 'ack',
|
|
221
|
-
attrs: {
|
|
222
|
-
id: attrs.id,
|
|
223
|
-
to: attrs.from,
|
|
224
|
-
class: tag
|
|
355
|
+
default:
|
|
356
|
+
logger.warn({ node, child }, 'Unknown newsletter notification child');
|
|
357
|
+
break;
|
|
225
358
|
}
|
|
226
|
-
};
|
|
227
|
-
if (!!errorCode) {
|
|
228
|
-
stanza.attrs.error = errorCode.toString();
|
|
229
|
-
}
|
|
230
|
-
if (!!attrs.participant) {
|
|
231
|
-
stanza.attrs.participant = attrs.participant;
|
|
232
|
-
}
|
|
233
|
-
if (!!attrs.recipient) {
|
|
234
|
-
stanza.attrs.recipient = attrs.recipient;
|
|
235
|
-
}
|
|
236
|
-
if (!!attrs.type &&
|
|
237
|
-
(tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
|
|
238
|
-
stanza.attrs.type = attrs.type;
|
|
239
359
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
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');
|
|
244
364
|
await sendNode(stanza);
|
|
245
365
|
};
|
|
246
366
|
const rejectCall = async (callId, callFrom) => {
|
|
@@ -300,12 +420,12 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
300
420
|
// Check if we should recreate the session
|
|
301
421
|
let shouldRecreateSession = false;
|
|
302
422
|
let recreateReason = '';
|
|
303
|
-
if (enableAutoSessionRecreation && messageRetryManager) {
|
|
423
|
+
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
|
|
304
424
|
try {
|
|
305
425
|
// Check if we have a session with this JID
|
|
306
426
|
const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
|
|
307
427
|
const hasSession = await signalRepository.validateSession(fromJid);
|
|
308
|
-
const result = messageRetryManager.shouldRecreateSession(fromJid,
|
|
428
|
+
const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
|
|
309
429
|
shouldRecreateSession = result.recreate;
|
|
310
430
|
recreateReason = result.reason;
|
|
311
431
|
if (shouldRecreateSession) {
|
|
@@ -395,34 +515,71 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
395
515
|
logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
|
|
396
516
|
}, authState?.creds?.me?.id || 'sendRetryRequest');
|
|
397
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
|
+
};
|
|
398
549
|
const handleEncryptNotification = async (node) => {
|
|
399
550
|
const from = node.attrs.from;
|
|
400
551
|
if (from === S_WHATSAPP_NET) {
|
|
552
|
+
const stanzaId = node.attrs.id;
|
|
553
|
+
if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
401
556
|
const countChild = getBinaryNodeChild(node, 'count');
|
|
402
557
|
const count = +countChild.attrs.value;
|
|
403
558
|
const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
|
|
404
559
|
logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
|
|
405
560
|
if (shouldUploadMorePreKeys) {
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
}
|
|
409
|
-
else {
|
|
410
|
-
const identityNode = getBinaryNodeChild(node, 'identity');
|
|
411
|
-
if (identityNode) {
|
|
412
|
-
logger.info({ jid: from }, 'identity changed');
|
|
413
|
-
if (identityAssertDebounce.get(from)) {
|
|
414
|
-
logger.debug({ jid: from }, 'skipping identity assert (debounced)');
|
|
415
|
-
return;
|
|
416
|
-
}
|
|
417
|
-
identityAssertDebounce.set(from, true);
|
|
561
|
+
if (stanzaId)
|
|
562
|
+
inFlightPreKeyLow.add(stanzaId);
|
|
418
563
|
try {
|
|
419
|
-
await
|
|
564
|
+
await uploadPreKeys();
|
|
420
565
|
}
|
|
421
|
-
|
|
422
|
-
|
|
566
|
+
finally {
|
|
567
|
+
if (stanzaId)
|
|
568
|
+
inFlightPreKeyLow.delete(stanzaId);
|
|
423
569
|
}
|
|
424
570
|
}
|
|
425
|
-
|
|
571
|
+
}
|
|
572
|
+
else {
|
|
573
|
+
const result = await handleIdentityChange(node, {
|
|
574
|
+
meId: authState.creds.me?.id,
|
|
575
|
+
meLid: authState.creds.me?.lid,
|
|
576
|
+
validateSession: signalRepository.validateSession,
|
|
577
|
+
assertSessions,
|
|
578
|
+
debounceCache: identityAssertDebounce,
|
|
579
|
+
logger,
|
|
580
|
+
onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
|
|
581
|
+
});
|
|
582
|
+
if (result.action === 'no_identity_node') {
|
|
426
583
|
logger.info({ node }, 'unknown encrypt notification');
|
|
427
584
|
}
|
|
428
585
|
}
|
|
@@ -431,6 +588,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
431
588
|
// TODO: Support PN/LID (Here is only LID now)
|
|
432
589
|
const actingParticipantLid = fullNode.attrs.participant;
|
|
433
590
|
const actingParticipantPn = fullNode.attrs.participant_pn;
|
|
591
|
+
const actingParticipantUsername = fullNode.attrs.participant_username;
|
|
434
592
|
const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
|
|
435
593
|
const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
|
|
436
594
|
switch (child?.tag) {
|
|
@@ -450,7 +608,8 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
450
608
|
{
|
|
451
609
|
...metadata,
|
|
452
610
|
author: actingParticipantLid,
|
|
453
|
-
authorPn: actingParticipantPn
|
|
611
|
+
authorPn: actingParticipantPn,
|
|
612
|
+
authorUsername: actingParticipantUsername
|
|
454
613
|
}
|
|
455
614
|
]);
|
|
456
615
|
break;
|
|
@@ -481,6 +640,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
481
640
|
id: attrs.jid,
|
|
482
641
|
phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
|
|
483
642
|
lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
|
|
643
|
+
username: attrs.participant_username || attrs.username || undefined,
|
|
484
644
|
admin: (attrs.type || null)
|
|
485
645
|
};
|
|
486
646
|
});
|
|
@@ -550,30 +710,100 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
550
710
|
break;
|
|
551
711
|
}
|
|
552
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
|
+
};
|
|
553
796
|
const processNotification = async (node) => {
|
|
554
797
|
const result = {};
|
|
555
798
|
const [child] = getAllBinaryNodeChildren(node);
|
|
556
799
|
const nodeType = node.attrs.type;
|
|
557
800
|
const from = jidNormalizedUser(node.attrs.from);
|
|
558
801
|
switch (nodeType) {
|
|
559
|
-
case 'privacy_token':
|
|
560
|
-
const tokenList = getBinaryNodeChildren(child, 'token');
|
|
561
|
-
for (const { attrs, content } of tokenList) {
|
|
562
|
-
const jid = attrs.jid;
|
|
563
|
-
ev.emit('chats.update', [
|
|
564
|
-
{
|
|
565
|
-
id: jid,
|
|
566
|
-
tcToken: content
|
|
567
|
-
}
|
|
568
|
-
]);
|
|
569
|
-
logger.debug({ jid }, 'got privacy token update');
|
|
570
|
-
}
|
|
571
|
-
break;
|
|
572
802
|
case 'newsletter':
|
|
573
803
|
await handleNewsletterNotification(node);
|
|
574
804
|
break;
|
|
575
805
|
case 'mex':
|
|
576
|
-
await
|
|
806
|
+
await handleMexNotification(node);
|
|
577
807
|
break;
|
|
578
808
|
case 'w:gp2':
|
|
579
809
|
// TODO: HANDLE PARTICIPANT_PN
|
|
@@ -587,13 +817,12 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
587
817
|
await handleEncryptNotification(node);
|
|
588
818
|
break;
|
|
589
819
|
case 'devices':
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
logger.
|
|
820
|
+
try {
|
|
821
|
+
await handleDevicesNotification(node);
|
|
822
|
+
}
|
|
823
|
+
catch (error) {
|
|
824
|
+
logger.error({ error, node }, 'failed to handle devices notification');
|
|
595
825
|
}
|
|
596
|
-
//TODO: drop a new event, add hashes
|
|
597
826
|
break;
|
|
598
827
|
case 'server_sync':
|
|
599
828
|
const update = getBinaryNodeChild(node, 'collection');
|
|
@@ -605,6 +834,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
605
834
|
case 'picture':
|
|
606
835
|
const setPicture = getBinaryNodeChild(node, 'set');
|
|
607
836
|
const delPicture = getBinaryNodeChild(node, 'delete');
|
|
837
|
+
// TODO: WAJIDHASH stuff proper support inhouse
|
|
608
838
|
ev.emit('contacts.update', [
|
|
609
839
|
{
|
|
610
840
|
id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
|
|
@@ -657,7 +887,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
657
887
|
const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
|
|
658
888
|
const random = randomBytes(32);
|
|
659
889
|
const linkCodeSalt = randomBytes(32);
|
|
660
|
-
const linkCodePairingExpanded =
|
|
890
|
+
const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
|
|
661
891
|
salt: linkCodeSalt,
|
|
662
892
|
info: 'link_code_pairing_key_bundle_encryption_key'
|
|
663
893
|
});
|
|
@@ -671,7 +901,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
671
901
|
const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
|
|
672
902
|
const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
|
|
673
903
|
const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
|
|
674
|
-
authState.creds.advSecretKey = (
|
|
904
|
+
authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
|
|
675
905
|
await query({
|
|
676
906
|
tag: 'iq',
|
|
677
907
|
attrs: {
|
|
@@ -718,27 +948,70 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
718
948
|
return result;
|
|
719
949
|
}
|
|
720
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
|
+
}
|
|
721
996
|
const handlePrivacyTokenNotification = async (node) => {
|
|
722
997
|
const tokensNode = getBinaryNodeChild(node, 'tokens');
|
|
723
|
-
const from = jidNormalizedUser(node.attrs.from);
|
|
724
998
|
if (!tokensNode)
|
|
725
999
|
return;
|
|
726
|
-
const
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
}
|
|
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
|
+
});
|
|
742
1015
|
};
|
|
743
1016
|
async function decipherLinkPublicKey(data) {
|
|
744
1017
|
const buffer = toRequiredBuffer(data);
|
|
@@ -764,10 +1037,11 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
764
1037
|
const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
|
|
765
1038
|
await msgRetryCache.set(key, newValue);
|
|
766
1039
|
};
|
|
767
|
-
const sendMessagesAgain = async (key, ids, retryNode) => {
|
|
1040
|
+
const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
|
|
768
1041
|
const remoteJid = key.remoteJid;
|
|
769
1042
|
const participant = key.participant || remoteJid;
|
|
770
1043
|
const retryCount = +retryNode.attrs.count || 1;
|
|
1044
|
+
const msgId = ids[0];
|
|
771
1045
|
// Try to get messages from cache first, then fallback to getMessage
|
|
772
1046
|
const msgs = [];
|
|
773
1047
|
for (const id of ids) {
|
|
@@ -799,14 +1073,51 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
799
1073
|
// just re-send the message to everyone
|
|
800
1074
|
// prevents the first message decryption failure
|
|
801
1075
|
const sendToAll = !jidDecode(participant)?.device;
|
|
802
|
-
|
|
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
|
+
}
|
|
803
1115
|
let shouldRecreateSession = false;
|
|
804
1116
|
let recreateReason = '';
|
|
805
|
-
if (enableAutoSessionRecreation && messageRetryManager) {
|
|
1117
|
+
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
|
|
806
1118
|
try {
|
|
807
|
-
const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
|
|
808
1119
|
const hasSession = await signalRepository.validateSession(participant);
|
|
809
|
-
const result = messageRetryManager.shouldRecreateSession(participant,
|
|
1120
|
+
const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
|
|
810
1121
|
shouldRecreateSession = result.recreate;
|
|
811
1122
|
recreateReason = result.reason;
|
|
812
1123
|
if (shouldRecreateSession) {
|
|
@@ -818,11 +1129,13 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
818
1129
|
logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
|
|
819
1130
|
}
|
|
820
1131
|
}
|
|
821
|
-
|
|
1132
|
+
if (!injectedFromBundle) {
|
|
1133
|
+
await assertSessions([participant], true);
|
|
1134
|
+
}
|
|
822
1135
|
if (isJidGroup(remoteJid)) {
|
|
823
1136
|
await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
|
|
824
1137
|
}
|
|
825
|
-
logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, '
|
|
1138
|
+
logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
|
|
826
1139
|
for (const [i, msg] of msgs.entries()) {
|
|
827
1140
|
if (!ids[i])
|
|
828
1141
|
continue;
|
|
@@ -857,11 +1170,6 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
857
1170
|
fromMe,
|
|
858
1171
|
participant: attrs.participant
|
|
859
1172
|
};
|
|
860
|
-
if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
|
|
861
|
-
logger.debug({ remoteJid }, 'ignoring receipt from jid');
|
|
862
|
-
await sendMessageAck(node);
|
|
863
|
-
return;
|
|
864
|
-
}
|
|
865
1173
|
const ids = [attrs.id];
|
|
866
1174
|
if (Array.isArray(content)) {
|
|
867
1175
|
const items = getBinaryNodeChildren(content[0], 'item');
|
|
@@ -869,7 +1177,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
869
1177
|
}
|
|
870
1178
|
try {
|
|
871
1179
|
await Promise.all([
|
|
872
|
-
|
|
1180
|
+
receiptMutex.mutex(async () => {
|
|
873
1181
|
const status = getStatusFromReceiptType(attrs.type);
|
|
874
1182
|
if (typeof status !== 'undefined' &&
|
|
875
1183
|
// basically, we only want to know when a message from us has been delivered to/read by the other person
|
|
@@ -890,7 +1198,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
890
1198
|
else {
|
|
891
1199
|
ev.emit('messages.update', ids.map(id => ({
|
|
892
1200
|
key: { ...key, id },
|
|
893
|
-
update: { status }
|
|
1201
|
+
update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) }
|
|
894
1202
|
})));
|
|
895
1203
|
}
|
|
896
1204
|
}
|
|
@@ -903,7 +1211,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
903
1211
|
try {
|
|
904
1212
|
await updateSendMessageAgainCount(ids[0], key.participant);
|
|
905
1213
|
logger.debug({ attrs, key }, 'recv retry request');
|
|
906
|
-
await sendMessagesAgain(key, ids, retryNode);
|
|
1214
|
+
await sendMessagesAgain(key, ids, retryNode, node);
|
|
907
1215
|
}
|
|
908
1216
|
catch (error) {
|
|
909
1217
|
logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
|
|
@@ -921,19 +1229,14 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
921
1229
|
]);
|
|
922
1230
|
}
|
|
923
1231
|
finally {
|
|
924
|
-
await sendMessageAck(node);
|
|
1232
|
+
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
|
|
925
1233
|
}
|
|
926
1234
|
};
|
|
927
1235
|
const handleNotification = async (node) => {
|
|
928
1236
|
const remoteJid = node.attrs.from;
|
|
929
|
-
if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
|
|
930
|
-
logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
|
|
931
|
-
await sendMessageAck(node);
|
|
932
|
-
return;
|
|
933
|
-
}
|
|
934
1237
|
try {
|
|
935
1238
|
await Promise.all([
|
|
936
|
-
|
|
1239
|
+
notificationMutex.mutex(async () => {
|
|
937
1240
|
const msg = await processNotification(node);
|
|
938
1241
|
if (msg) {
|
|
939
1242
|
const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
|
|
@@ -943,6 +1246,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
943
1246
|
fromMe,
|
|
944
1247
|
participant: node.attrs.participant,
|
|
945
1248
|
participantAlt,
|
|
1249
|
+
participantUsername: node.attrs.participant_username,
|
|
946
1250
|
addressingMode,
|
|
947
1251
|
id: node.attrs.id,
|
|
948
1252
|
...(msg.key || {})
|
|
@@ -956,99 +1260,139 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
956
1260
|
]);
|
|
957
1261
|
}
|
|
958
1262
|
finally {
|
|
959
|
-
await sendMessageAck(node);
|
|
1263
|
+
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
|
|
960
1264
|
}
|
|
961
1265
|
};
|
|
962
1266
|
const handleMessage = async (node) => {
|
|
963
|
-
if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
|
|
964
|
-
logger.debug({ key: node.attrs.key }, 'ignored message');
|
|
965
|
-
await sendMessageAck(node, NACK_REASONS.UnhandledError);
|
|
966
|
-
return;
|
|
967
|
-
}
|
|
968
1267
|
const encNode = getBinaryNodeChild(node, 'enc');
|
|
969
1268
|
// TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
|
|
970
|
-
if (encNode
|
|
1269
|
+
if (encNode?.attrs.type === 'msmsg') {
|
|
971
1270
|
logger.debug({ key: node.attrs.key }, 'ignored msmsg');
|
|
972
1271
|
await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
|
|
973
1272
|
return;
|
|
974
1273
|
}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
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);
|
|
985
1291
|
}
|
|
986
1292
|
}
|
|
987
|
-
|
|
988
|
-
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
|
|
989
|
-
await signalRepository.migrateSession(alt, primaryJid);
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
|
|
993
|
-
messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
|
|
994
|
-
logger.debug({
|
|
995
|
-
jid: msg.key.remoteJid,
|
|
996
|
-
id: msg.key.id
|
|
997
|
-
}, 'Added message to recent cache for retry receipts');
|
|
998
|
-
}
|
|
999
|
-
try {
|
|
1000
|
-
await processingMutex.mutex(async () => {
|
|
1293
|
+
await messageMutex.mutex(async () => {
|
|
1001
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
|
+
}
|
|
1002
1298
|
// message failed to decrypt
|
|
1003
1299
|
if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
|
|
1004
1300
|
if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
|
|
1301
|
+
acked = true;
|
|
1005
1302
|
return sendMessageAck(node, NACK_REASONS.ParsingError);
|
|
1006
1303
|
}
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1304
|
+
if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
|
|
1305
|
+
// Message arrived without encryption (e.g. CTWA ads messages).
|
|
1306
|
+
// Check if this is eligible for placeholder resend (matching WA Web filters).
|
|
1307
|
+
const unavailableNode = getBinaryNodeChild(node, 'unavailable');
|
|
1308
|
+
const unavailableType = unavailableNode?.attrs?.type;
|
|
1309
|
+
if (unavailableType === 'bot_unavailable_fanout' ||
|
|
1310
|
+
unavailableType === 'hosted_unavailable_fanout' ||
|
|
1311
|
+
unavailableType === 'view_once_unavailable_fanout') {
|
|
1312
|
+
logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
|
|
1313
|
+
acked = true;
|
|
1314
|
+
return sendMessageAck(node);
|
|
1315
|
+
}
|
|
1316
|
+
const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
|
|
1317
|
+
if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
|
|
1318
|
+
logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
|
|
1319
|
+
acked = true;
|
|
1320
|
+
return sendMessageAck(node);
|
|
1321
|
+
}
|
|
1322
|
+
// Request the real content from the phone via placeholder resend PDO.
|
|
1323
|
+
// Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
|
|
1324
|
+
// and store the requestId in stubParameters[1] so users can correlate
|
|
1325
|
+
// with the incoming PDO response event.
|
|
1326
|
+
const cleanKey = {
|
|
1327
|
+
remoteJid: msg.key.remoteJid,
|
|
1328
|
+
fromMe: msg.key.fromMe,
|
|
1329
|
+
id: msg.key.id,
|
|
1330
|
+
participant: msg.key.participant
|
|
1331
|
+
};
|
|
1332
|
+
// Cache the original message metadata so the PDO response handler
|
|
1333
|
+
// can preserve key fields (LID details etc.) that the phone may omit
|
|
1334
|
+
const msgData = {
|
|
1335
|
+
key: msg.key,
|
|
1336
|
+
messageTimestamp: msg.messageTimestamp,
|
|
1337
|
+
pushName: msg.pushName,
|
|
1338
|
+
participant: msg.participant,
|
|
1339
|
+
verifiedBizName: msg.verifiedBizName
|
|
1340
|
+
};
|
|
1341
|
+
requestPlaceholderResend(cleanKey, msgData)
|
|
1342
|
+
.then(requestId => {
|
|
1343
|
+
if (requestId && requestId !== 'RESOLVED') {
|
|
1344
|
+
logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message');
|
|
1345
|
+
ev.emit('messages.update', [
|
|
1346
|
+
{
|
|
1347
|
+
key: msg.key,
|
|
1348
|
+
update: { messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId] }
|
|
1349
|
+
}
|
|
1350
|
+
]);
|
|
1029
1351
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1352
|
+
})
|
|
1353
|
+
.catch(err => {
|
|
1354
|
+
logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
|
|
1355
|
+
});
|
|
1356
|
+
acked = true;
|
|
1357
|
+
await sendMessageAck(node);
|
|
1358
|
+
// Don't return — fall through to upsertMessage so the stub is emitted
|
|
1359
|
+
}
|
|
1360
|
+
else {
|
|
1361
|
+
// Skip retry for expired status messages (>24h old)
|
|
1362
|
+
if (isJidStatusBroadcast(msg.key.remoteJid)) {
|
|
1363
|
+
const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
|
|
1364
|
+
if (messageAge > STATUS_EXPIRY_SECONDS) {
|
|
1365
|
+
logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
|
|
1366
|
+
acked = true;
|
|
1367
|
+
return sendMessageAck(node);
|
|
1034
1368
|
}
|
|
1035
1369
|
}
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1370
|
+
logger.debug('[handleMessage] Attempting retry request for failed decryption');
|
|
1371
|
+
// WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
|
|
1372
|
+
await retryMutex.mutex(async () => {
|
|
1039
1373
|
try {
|
|
1374
|
+
if (!ws.isOpen) {
|
|
1375
|
+
logger.debug({ node }, 'Connection closed, skipping retry');
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1040
1378
|
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1041
1379
|
await sendRetryRequest(node, !encNode);
|
|
1380
|
+
if (retryRequestDelayMs) {
|
|
1381
|
+
await delay(retryRequestDelayMs);
|
|
1382
|
+
}
|
|
1042
1383
|
}
|
|
1043
|
-
catch (
|
|
1044
|
-
logger.error({
|
|
1384
|
+
catch (err) {
|
|
1385
|
+
logger.error({ err }, 'Failed to send retry');
|
|
1045
1386
|
}
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1387
|
+
acked = true;
|
|
1388
|
+
await sendMessageAck(node, NACK_REASONS.UnhandledError);
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1049
1391
|
}
|
|
1050
1392
|
else {
|
|
1051
|
-
|
|
1393
|
+
if (messageRetryManager && msg.key.id) {
|
|
1394
|
+
messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
|
|
1395
|
+
}
|
|
1052
1396
|
const isNewsletter = isJidNewsletter(msg.key.remoteJid);
|
|
1053
1397
|
if (!isNewsletter) {
|
|
1054
1398
|
// no type in the receipt => message delivered
|
|
@@ -1069,15 +1413,18 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1069
1413
|
else if (!sendActiveReceipts) {
|
|
1070
1414
|
type = 'inactive';
|
|
1071
1415
|
}
|
|
1416
|
+
acked = true;
|
|
1072
1417
|
await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
|
|
1073
1418
|
// send ack for history message
|
|
1074
1419
|
const isAnyHistoryMsg = getHistoryMsg(msg.message);
|
|
1075
1420
|
if (isAnyHistoryMsg) {
|
|
1076
1421
|
const jid = jidNormalizedUser(msg.key.remoteJid);
|
|
1077
|
-
await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
|
|
1422
|
+
await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
|
|
1078
1423
|
}
|
|
1079
1424
|
}
|
|
1080
1425
|
else {
|
|
1426
|
+
acked = true;
|
|
1427
|
+
await sendMessageAck(node);
|
|
1081
1428
|
logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
|
|
1082
1429
|
}
|
|
1083
1430
|
}
|
|
@@ -1087,43 +1434,62 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1087
1434
|
}
|
|
1088
1435
|
catch (error) {
|
|
1089
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
|
+
}
|
|
1090
1440
|
}
|
|
1091
1441
|
};
|
|
1092
1442
|
const handleCall = async (node) => {
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
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
|
+
}
|
|
1127
1493
|
};
|
|
1128
1494
|
const handleBadAck = async ({ attrs }) => {
|
|
1129
1495
|
const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
|
|
@@ -1143,29 +1509,61 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1143
1509
|
// error in acknowledgement,
|
|
1144
1510
|
// device could not display the message
|
|
1145
1511
|
if (attrs.error) {
|
|
1146
|
-
|
|
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
|
+
}
|
|
1147
1558
|
ev.emit('messages.update', [
|
|
1148
1559
|
{
|
|
1149
1560
|
key,
|
|
1150
1561
|
update: {
|
|
1151
1562
|
status: WAMessageStatus.ERROR,
|
|
1152
|
-
messageStubParameters: [attrs.error]
|
|
1563
|
+
messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
|
|
1153
1564
|
}
|
|
1154
1565
|
}
|
|
1155
1566
|
]);
|
|
1156
|
-
// resend the message with device_fanout=false, use at your own risk
|
|
1157
|
-
// if (attrs.error === '475') {
|
|
1158
|
-
// const msg = await getMessage(key)
|
|
1159
|
-
// if (msg) {
|
|
1160
|
-
// await relayMessage(key.remoteJid!, msg, {
|
|
1161
|
-
// messageId: key.id!,
|
|
1162
|
-
// useUserDevicesCache: false,
|
|
1163
|
-
// additionalAttributes: {
|
|
1164
|
-
// device_fanout: 'false'
|
|
1165
|
-
// }
|
|
1166
|
-
// })
|
|
1167
|
-
// }
|
|
1168
|
-
// }
|
|
1169
1567
|
}
|
|
1170
1568
|
};
|
|
1171
1569
|
/// processes a node with the given function
|
|
@@ -1178,39 +1576,30 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1178
1576
|
return exec(node, false).catch(err => onUnexpectedError(err, identifier));
|
|
1179
1577
|
}
|
|
1180
1578
|
};
|
|
1181
|
-
const
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
nodes.push({ type, node });
|
|
1192
|
-
if (isProcessing) {
|
|
1193
|
-
return;
|
|
1194
|
-
}
|
|
1195
|
-
isProcessing = true;
|
|
1196
|
-
const promise = async () => {
|
|
1197
|
-
while (nodes.length && ws.isOpen) {
|
|
1198
|
-
const { type, node } = nodes.shift();
|
|
1199
|
-
const nodeProcessor = nodeProcessorMap.get(type);
|
|
1200
|
-
if (!nodeProcessor) {
|
|
1201
|
-
onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
|
|
1202
|
-
continue;
|
|
1203
|
-
}
|
|
1204
|
-
await nodeProcessor(node);
|
|
1205
|
-
}
|
|
1206
|
-
isProcessing = false;
|
|
1207
|
-
};
|
|
1208
|
-
promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
|
|
1209
|
-
};
|
|
1210
|
-
return { enqueue };
|
|
1211
|
-
};
|
|
1212
|
-
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
|
+
});
|
|
1213
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
|
+
}
|
|
1214
1603
|
const isOffline = !!node.attrs.offline;
|
|
1215
1604
|
if (isOffline) {
|
|
1216
1605
|
offlineNodeProcessor.enqueue(type, node);
|
|
@@ -1266,12 +1655,110 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1266
1655
|
await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
|
|
1267
1656
|
}
|
|
1268
1657
|
});
|
|
1269
|
-
|
|
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 }) => {
|
|
1270
1663
|
if (typeof isOnline !== 'undefined') {
|
|
1271
1664
|
sendActiveReceipts = isOnline;
|
|
1272
1665
|
logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
|
|
1273
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
|
+
}
|
|
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;
|
|
1274
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
|
+
}
|
|
1275
1762
|
return {
|
|
1276
1763
|
...sock,
|
|
1277
1764
|
sendMessageAck,
|