@mrlegendbot/baileys 1.2.3 → 1.2.4
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.upstream.md +1312 -0
- package/WAProto/WAProto.json +1 -0
- package/WAProto/WAProto.proto +6275 -0
- package/WAProto/compiler.js +550 -0
- package/WAProto/index.js +2 -97691
- package/lib/Defaults/index.js +89 -92
- package/lib/Signal/Group/ciphertext-message.js +9 -10
- package/lib/Signal/Group/group-session-builder.js +21 -22
- package/lib/Signal/Group/group_cipher.js +75 -69
- package/lib/Signal/Group/index.js +0 -1
- package/lib/Signal/Group/keyhelper.js +9 -10
- package/lib/Signal/Group/sender-chain-key.js +21 -22
- package/lib/Signal/Group/sender-key-distribution-message.js +51 -60
- package/lib/Signal/Group/sender-key-message.js +56 -62
- package/lib/Signal/Group/sender-key-name.js +38 -40
- package/lib/Signal/Group/sender-key-record.js +33 -34
- package/lib/Signal/Group/sender-key-state.js +72 -76
- package/lib/Signal/Group/sender-message-key.js +22 -23
- package/lib/Signal/libsignal.js +506 -405
- package/lib/Signal/lid-mapping.js +276 -258
- package/lib/Socket/Client/index.js +0 -1
- package/lib/Socket/Client/types.js +6 -7
- package/lib/Socket/Client/websocket.js +48 -49
- package/lib/Socket/business.js +349 -369
- package/lib/Socket/chats.js +1172 -1148
- package/lib/Socket/communities.js +473 -413
- package/lib/Socket/groups.js +387 -331
- package/lib/Socket/index.js +6 -8
- package/lib/Socket/messages-recv.js +1782 -1719
- package/lib/Socket/messages-send.js +1503 -2450
- package/lib/Socket/mex.js +40 -35
- package/lib/Socket/newsletter.js +239 -191
- package/lib/Socket/socket.js +992 -923
- package/lib/Store/index.js +8 -0
- package/lib/Store/keyed-db.js +108 -0
- package/lib/Store/make-cache-manager-store.js +70 -0
- package/lib/Store/make-in-memory-store.js +417 -0
- package/lib/Store/make-ordered-dictionary.js +69 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.js +0 -1
- package/lib/Types/Bussines.js +0 -1
- package/lib/Types/Call.js +0 -1
- package/lib/Types/Chat.js +1 -8
- package/lib/Types/Contact.js +0 -1
- package/lib/Types/Events.js +1 -2
- package/lib/Types/GroupMetadata.js +0 -1
- package/lib/Types/Label.js +20 -22
- package/lib/Types/LabelAssociation.js +2 -4
- package/lib/Types/Message.js +3 -5
- package/lib/Types/Mex.js +26 -31
- package/lib/Types/Product.js +0 -1
- package/lib/Types/Signal.js +1 -2
- package/lib/Types/Socket.js +2 -3
- package/lib/Types/State.js +4 -52
- package/lib/Types/USync.js +0 -1
- package/lib/Types/index.js +10 -11
- package/lib/Utils/auth-utils.js +240 -277
- package/lib/Utils/browser-utils.js +20 -23
- package/lib/Utils/business.js +200 -204
- package/lib/Utils/chat-utils.js +836 -810
- package/lib/Utils/companion-reg-client-utils.js +23 -25
- package/lib/Utils/crypto.js +70 -86
- package/lib/Utils/decode-wa-message.js +277 -284
- package/lib/Utils/event-buffer.js +592 -595
- package/lib/Utils/generics.js +312 -335
- package/lib/Utils/history.js +123 -115
- package/lib/Utils/index.js +1 -2
- package/lib/Utils/link-preview.js +74 -73
- package/lib/Utils/logger.js +3 -2
- package/lib/Utils/lt-hash.js +0 -6
- package/lib/Utils/make-mutex.js +27 -27
- package/lib/Utils/message-retry-manager.js +213 -254
- package/lib/Utils/messages-media.js +741 -715
- package/lib/Utils/messages.js +791 -827
- package/lib/Utils/noise-handler.js +215 -187
- package/lib/Utils/pre-key-manager.js +69 -98
- package/lib/Utils/process-message.js +617 -586
- package/lib/Utils/reporting-utils.js +553 -234
- package/lib/Utils/signal.js +217 -170
- package/lib/Utils/stanza-ack.js +27 -35
- package/lib/Utils/sync-action-utils.js +37 -41
- package/lib/Utils/tc-token-utils.js +120 -141
- package/lib/Utils/use-multi-file-auth-state.js +87 -105
- package/lib/Utils/use-sqlite-auth-state.js +162 -0
- package/lib/Utils/validate-connection.js +190 -188
- package/lib/WABinary/constants.js +28 -1294
- package/lib/WABinary/decode.js +245 -249
- package/lib/WABinary/encode.js +201 -206
- package/lib/WABinary/generic-utils.js +86 -89
- package/lib/WABinary/index.js +0 -1
- package/lib/WABinary/jid-utils.js +68 -77
- package/lib/WABinary/types.js +0 -1
- package/lib/WAM/BinaryInfo.js +7 -8
- package/lib/WAM/constants.js +19892 -22853
- package/lib/WAM/encode.js +121 -132
- package/lib/WAM/index.js +0 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +46 -43
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +47 -48
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +22 -23
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +30 -33
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +19 -20
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -44
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -24
- package/lib/WAUSync/Protocols/index.js +0 -1
- package/lib/WAUSync/USyncQuery.js +79 -88
- package/lib/WAUSync/USyncUser.js +28 -29
- package/lib/WAUSync/index.js +0 -1
- package/lib/index.js +2 -2
- package/package.json +22 -86
- package/WAProto/GenerateStatics.sh +0 -3
- package/WAProto/fix-imports.js +0 -85
- package/WAProto/index.d.ts +0 -14017
- package/lib/Defaults/index.d.ts +0 -75
- package/lib/Signal/Group/ciphertext-message.d.ts +0 -10
- package/lib/Signal/Group/group-session-builder.d.ts +0 -15
- package/lib/Signal/Group/group_cipher.d.ts +0 -17
- package/lib/Signal/Group/index.d.ts +0 -12
- package/lib/Signal/Group/keyhelper.d.ts +0 -11
- package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
- package/lib/Signal/Group/sender-key-message.d.ts +0 -19
- package/lib/Signal/Group/sender-key-name.d.ts +0 -18
- package/lib/Signal/Group/sender-key-record.d.ts +0 -31
- package/lib/Signal/Group/sender-key-state.d.ts +0 -39
- package/lib/Signal/Group/sender-message-key.d.ts +0 -12
- package/lib/Signal/libsignal.d.ts +0 -5
- package/lib/Signal/lid-mapping.d.ts +0 -23
- package/lib/Socket/Client/index.d.ts +0 -3
- package/lib/Socket/Client/types.d.ts +0 -16
- package/lib/Socket/Client/websocket.d.ts +0 -13
- package/lib/Socket/business.d.ts +0 -217
- package/lib/Socket/chats.d.ts +0 -125
- package/lib/Socket/communities.d.ts +0 -273
- package/lib/Socket/groups.d.ts +0 -161
- package/lib/Socket/index.d.ts +0 -260
- package/lib/Socket/messages-recv.d.ts +0 -203
- package/lib/Socket/messages-send.d.ts +0 -199
- package/lib/Socket/mex.d.ts +0 -3
- package/lib/Socket/newsletter.d.ts +0 -170
- package/lib/Socket/socket.d.ts +0 -59
- package/lib/Types/Auth.d.ts +0 -117
- package/lib/Types/Bussines.d.ts +0 -25
- package/lib/Types/Call.d.ts +0 -15
- package/lib/Types/Chat.d.ts +0 -124
- package/lib/Types/Contact.d.ts +0 -26
- package/lib/Types/Events.d.ts +0 -256
- package/lib/Types/GroupMetadata.d.ts +0 -71
- package/lib/Types/Label.d.ts +0 -47
- package/lib/Types/LabelAssociation.d.ts +0 -30
- package/lib/Types/Message.d.ts +0 -320
- package/lib/Types/Mex.d.ts +0 -141
- package/lib/Types/Product.d.ts +0 -79
- package/lib/Types/Signal.d.ts +0 -87
- package/lib/Types/Socket.d.ts +0 -136
- package/lib/Types/State.d.ts +0 -97
- package/lib/Types/USync.d.ts +0 -26
- package/lib/Types/index.d.ts +0 -66
- package/lib/Utils/auth-utils.d.ts +0 -24
- package/lib/Utils/browser-utils.d.ts +0 -4
- package/lib/Utils/business.d.ts +0 -23
- package/lib/Utils/chat-utils.d.ts +0 -100
- package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
- package/lib/Utils/crypto.d.ts +0 -37
- package/lib/Utils/decode-wa-message.d.ts +0 -66
- package/lib/Utils/event-buffer.d.ts +0 -36
- package/lib/Utils/generics.d.ts +0 -92
- package/lib/Utils/history.d.ts +0 -24
- package/lib/Utils/identity-change-handler.d.ts +0 -44
- package/lib/Utils/identity-change-handler.js +0 -50
- package/lib/Utils/index.d.ts +0 -22
- package/lib/Utils/link-preview.d.ts +0 -21
- package/lib/Utils/logger.d.ts +0 -12
- package/lib/Utils/lt-hash.d.ts +0 -8
- package/lib/Utils/make-mutex.d.ts +0 -9
- package/lib/Utils/message-retry-manager.d.ts +0 -115
- package/lib/Utils/messages-media.d.ts +0 -133
- package/lib/Utils/messages.d.ts +0 -91
- package/lib/Utils/noise-handler.d.ts +0 -20
- package/lib/Utils/offline-node-processor.d.ts +0 -17
- package/lib/Utils/offline-node-processor.js +0 -40
- package/lib/Utils/pre-key-manager.d.ts +0 -28
- package/lib/Utils/process-message.d.ts +0 -60
- package/lib/Utils/reporting-utils.d.ts +0 -11
- package/lib/Utils/signal.d.ts +0 -47
- package/lib/Utils/stanza-ack.d.ts +0 -11
- package/lib/Utils/sync-action-utils.d.ts +0 -19
- package/lib/Utils/tc-token-utils.d.ts +0 -37
- package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
- package/lib/Utils/validate-connection.d.ts +0 -11
- package/lib/WABinary/constants.d.ts +0 -28
- package/lib/WABinary/decode.d.ts +0 -7
- package/lib/WABinary/encode.d.ts +0 -3
- package/lib/WABinary/generic-utils.d.ts +0 -15
- package/lib/WABinary/index.d.ts +0 -6
- package/lib/WABinary/jid-utils.d.ts +0 -48
- package/lib/WABinary/types.d.ts +0 -19
- package/lib/WAM/BinaryInfo.d.ts +0 -9
- package/lib/WAM/constants.d.ts +0 -40
- package/lib/WAM/encode.d.ts +0 -3
- package/lib/WAM/index.d.ts +0 -4
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -23
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -13
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -13
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -26
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -10
- package/lib/WAUSync/Protocols/index.d.ts +0 -6
- package/lib/WAUSync/USyncQuery.d.ts +0 -30
- package/lib/WAUSync/USyncUser.d.ts +0 -17
- package/lib/WAUSync/index.d.ts +0 -4
- package/lib/index.d.ts +0 -12
|
@@ -2,1771 +2,1834 @@ import NodeCache from '@cacheable/node-cache';
|
|
|
2
2
|
import { Boom } from '@hapi/boom';
|
|
3
3
|
import { randomBytes } from 'crypto';
|
|
4
4
|
import Long from 'long';
|
|
5
|
-
import { proto } from '../../WAProto/
|
|
5
|
+
import { proto } from '../../WAProto/compiler.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 {
|
|
8
|
-
import {
|
|
7
|
+
import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
|
|
8
|
+
import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, extractE2ESessionFromRetryReceipt, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, 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 { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
|
|
11
10
|
import { buildAckStanza } from '../Utils/stanza-ack.js';
|
|
12
11
|
import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
|
|
13
12
|
import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
|
|
14
13
|
import { extractGroupMetadata } from './groups.js';
|
|
15
14
|
import { makeMessagesSocket } from './messages-send.js';
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
15
|
+
export const makeMessagesRecvSocket = config => {
|
|
16
|
+
const {
|
|
17
|
+
logger,
|
|
18
|
+
retryRequestDelayMs,
|
|
19
|
+
maxMsgRetryCount,
|
|
20
|
+
getMessage,
|
|
21
|
+
shouldIgnoreJid,
|
|
22
|
+
ignoreOfflineMessages,
|
|
23
|
+
enableAutoSessionRecreation
|
|
24
|
+
} = config;
|
|
25
|
+
const sock = makeMessagesSocket(config);
|
|
26
|
+
const {
|
|
27
|
+
userDevicesCache,
|
|
28
|
+
devicesMutex,
|
|
29
|
+
ev,
|
|
30
|
+
authState,
|
|
31
|
+
ws,
|
|
32
|
+
messageMutex,
|
|
33
|
+
notificationMutex,
|
|
34
|
+
receiptMutex,
|
|
35
|
+
signalRepository,
|
|
36
|
+
query,
|
|
37
|
+
upsertMessage,
|
|
38
|
+
resyncAppState,
|
|
39
|
+
onUnexpectedError,
|
|
40
|
+
assertSessions,
|
|
41
|
+
sendNode,
|
|
42
|
+
relayMessage,
|
|
43
|
+
sendReceipt,
|
|
44
|
+
uploadPreKeys,
|
|
45
|
+
sendPeerDataOperationMessage,
|
|
46
|
+
messageRetryManager,
|
|
47
|
+
registerSocketEndHandler,
|
|
48
|
+
issuePrivacyTokens,
|
|
49
|
+
placeholderResendCache
|
|
50
|
+
} = sock;
|
|
51
|
+
const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
|
|
52
|
+
const retryMutex = makeMutex();
|
|
53
|
+
const msgRetryCache = config.msgRetryCounterCache || new NodeCache({
|
|
54
|
+
stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
|
|
55
|
+
useClones: false
|
|
56
|
+
});
|
|
57
|
+
const callOfferCache = config.callOfferCache || new NodeCache({
|
|
58
|
+
stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER,
|
|
59
|
+
useClones: false
|
|
60
|
+
});
|
|
61
|
+
let sendActiveReceipts = false;
|
|
62
|
+
const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
|
|
63
|
+
if (!authState.creds.me?.id) {
|
|
64
|
+
throw new Boom('Not authenticated');
|
|
65
|
+
}
|
|
66
|
+
const pdoMessage = {
|
|
67
|
+
historySyncOnDemandRequest: {
|
|
68
|
+
chatJid: oldestMsgKey.remoteJid,
|
|
69
|
+
oldestMsgFromMe: oldestMsgKey.fromMe,
|
|
70
|
+
oldestMsgId: oldestMsgKey.id,
|
|
71
|
+
oldestMsgTimestampMs: oldestMsgTimestamp,
|
|
72
|
+
onDemandMsgCount: count
|
|
73
|
+
},
|
|
74
|
+
peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
|
|
55
75
|
};
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
await placeholderResendCache.del(messageKey?.id);
|
|
86
|
-
}
|
|
87
|
-
}, 8000);
|
|
88
|
-
return sendPeerDataOperationMessage(pdoMessage);
|
|
76
|
+
return sendPeerDataOperationMessage(pdoMessage);
|
|
77
|
+
};
|
|
78
|
+
const requestPlaceholderResend = async (messageKey, msgData) => {
|
|
79
|
+
if (ignoreOfflineMessages) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (!authState.creds.me?.id) {
|
|
83
|
+
throw new Boom('Not authenticated');
|
|
84
|
+
}
|
|
85
|
+
if (await placeholderResendCache.get(messageKey?.id)) {
|
|
86
|
+
logger.debug({
|
|
87
|
+
messageKey
|
|
88
|
+
}, 'already requested resend');
|
|
89
|
+
return;
|
|
90
|
+
} else {
|
|
91
|
+
await placeholderResendCache.set(messageKey?.id, msgData || true);
|
|
92
|
+
}
|
|
93
|
+
await delay(2000);
|
|
94
|
+
if (!(await placeholderResendCache.get(messageKey?.id))) {
|
|
95
|
+
logger.debug({
|
|
96
|
+
messageKey
|
|
97
|
+
}, 'message received while resend requested');
|
|
98
|
+
return 'RESOLVED';
|
|
99
|
+
}
|
|
100
|
+
const pdoMessage = {
|
|
101
|
+
placeholderMessageResendRequest: [{
|
|
102
|
+
messageKey
|
|
103
|
+
}],
|
|
104
|
+
peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
|
|
89
105
|
};
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
}
|
|
106
|
+
setTimeout(async () => {
|
|
107
|
+
if (await placeholderResendCache.get(messageKey?.id)) {
|
|
108
|
+
logger.debug({
|
|
109
|
+
messageKey
|
|
110
|
+
}, 'PDO message without response after 8 seconds. Phone possibly offline');
|
|
111
|
+
await placeholderResendCache.del(messageKey?.id);
|
|
112
|
+
}
|
|
113
|
+
}, 8000);
|
|
114
|
+
return sendPeerDataOperationMessage(pdoMessage);
|
|
115
|
+
};
|
|
116
|
+
const handleMexNotification = async node => {
|
|
117
|
+
const updateNode = getBinaryNodeChild(node, 'update');
|
|
118
|
+
if (updateNode) {
|
|
119
|
+
const opName = updateNode.attrs?.op_name;
|
|
120
|
+
if (!opName) {
|
|
121
|
+
logger.warn({
|
|
122
|
+
node: binaryNodeToString(node)
|
|
123
|
+
}, 'mex notification missing op_name, fallback to legacy');
|
|
149
124
|
await handleLegacyMexNewsletterNotification(node);
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
let mexResponse;
|
|
128
|
+
try {
|
|
129
|
+
mexResponse = JSON.parse(updateNode.content.toString());
|
|
130
|
+
} catch (error) {
|
|
131
|
+
logger.error({
|
|
132
|
+
err: error,
|
|
133
|
+
opName
|
|
134
|
+
}, 'failed to parse mex notification JSON');
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (mexResponse.errors?.length) {
|
|
138
|
+
logger.warn({
|
|
139
|
+
errors: mexResponse.errors,
|
|
140
|
+
opName
|
|
141
|
+
}, 'mex notification has GQL errors');
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const data = mexResponse.data;
|
|
145
|
+
if (!data) {
|
|
146
|
+
logger.warn({
|
|
147
|
+
opName
|
|
148
|
+
}, 'mex notification has null data');
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
logger.debug({
|
|
152
|
+
opName
|
|
153
|
+
}, 'processing mex notification');
|
|
154
|
+
switch (opName) {
|
|
155
|
+
case 'NotificationNewsletterUpdate':
|
|
156
|
+
case 'NotificationLinkedProfilesUpdates':
|
|
157
|
+
case 'NotificationNewsletterAdminPromote':
|
|
158
|
+
case 'NotificationNewsletterAdminDemote':
|
|
159
|
+
case 'NotificationNewsletterUserSettingChange':
|
|
160
|
+
case 'NotificationNewsletterJoin':
|
|
161
|
+
case 'NotificationNewsletterLeave':
|
|
162
|
+
case 'NotificationNewsletterStateChange':
|
|
163
|
+
case 'NotificationNewsletterAdminMetadataUpdate':
|
|
164
|
+
case 'NotificationNewsletterOwnerUpdate':
|
|
165
|
+
case 'NotificationNewsletterAdminInviteRevoke':
|
|
166
|
+
case 'NotificationNewsletterWamoSubStatusChange':
|
|
167
|
+
case 'NotificationNewsletterBlockUser':
|
|
168
|
+
case 'NotificationNewsletterPaidPartnership':
|
|
169
|
+
case 'NotificationNewsletterMilestone':
|
|
170
|
+
case 'NewsletterResponseStateUpdate':
|
|
171
|
+
await handleLegacyMexNewsletterNotification(node);
|
|
172
|
+
break;
|
|
173
|
+
default:
|
|
174
|
+
logger.debug({
|
|
175
|
+
opName
|
|
176
|
+
}, 'unhandled mex notification');
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
await handleLegacyMexNewsletterNotification(node);
|
|
182
|
+
};
|
|
183
|
+
const handleLegacyMexNewsletterNotification = async node => {
|
|
184
|
+
const mexNode = getBinaryNodeChild(node, 'mex');
|
|
185
|
+
const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0];
|
|
186
|
+
const payloadNode = mexNode?.content ? mexNode : updateNode;
|
|
187
|
+
if (!payloadNode?.content) {
|
|
188
|
+
logger.warn({
|
|
189
|
+
node: binaryNodeToString(node)
|
|
190
|
+
}, 'invalid mex newsletter notification');
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
let data;
|
|
194
|
+
try {
|
|
195
|
+
const payloadContent = payloadNode.content;
|
|
196
|
+
if (Array.isArray(payloadContent)) {
|
|
197
|
+
logger.warn({
|
|
198
|
+
payloadNode
|
|
199
|
+
}, 'invalid mex newsletter notification payload format');
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
|
|
203
|
+
data = JSON.parse(contentBuf.toString());
|
|
204
|
+
} catch (error) {
|
|
205
|
+
logger.error({
|
|
206
|
+
err: error,
|
|
207
|
+
node: binaryNodeToString(node)
|
|
208
|
+
}, 'failed to parse mex newsletter notification');
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const operation = data?.operation ?? payloadNode?.attrs?.op_name;
|
|
212
|
+
let updates = data?.updates;
|
|
213
|
+
if (!updates) {
|
|
214
|
+
const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
|
|
215
|
+
if (linkedProfiles) {
|
|
216
|
+
updates = [linkedProfiles];
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (!updates || !operation) {
|
|
220
|
+
logger.warn({
|
|
221
|
+
data
|
|
222
|
+
}, 'invalid mex newsletter notification content');
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
logger.info({
|
|
226
|
+
operation,
|
|
227
|
+
updates
|
|
228
|
+
}, 'got mex newsletter notification');
|
|
229
|
+
switch (operation) {
|
|
230
|
+
case 'NotificationNewsletterUpdate':
|
|
231
|
+
for (const update of updates) {
|
|
232
|
+
if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
|
|
233
|
+
ev.emit('newsletter-settings.update', {
|
|
234
|
+
id: update.jid,
|
|
235
|
+
update: update.settings
|
|
164
236
|
});
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const payloadNode = mexNode?.content ? mexNode : updateNode;
|
|
196
|
-
if (!payloadNode?.content) {
|
|
197
|
-
logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification');
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
let data;
|
|
201
|
-
try {
|
|
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());
|
|
209
|
-
}
|
|
210
|
-
catch (error) {
|
|
211
|
-
logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
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
|
-
}
|
|
222
|
-
if (!updates || !operation) {
|
|
223
|
-
logger.warn({ data }, 'invalid mex newsletter notification content');
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
logger.info({ operation, updates }, 'got mex newsletter notification');
|
|
227
|
-
switch (operation) {
|
|
228
|
-
case 'NotificationNewsletterUpdate':
|
|
229
|
-
for (const update of updates) {
|
|
230
|
-
if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
|
|
231
|
-
ev.emit('newsletter-settings.update', {
|
|
232
|
-
id: update.jid,
|
|
233
|
-
update: update.settings
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
break;
|
|
238
|
-
case 'NotificationNewsletterAdminPromote':
|
|
239
|
-
for (const update of updates) {
|
|
240
|
-
if (update.jid && update.user) {
|
|
241
|
-
ev.emit('newsletter-participants.update', {
|
|
242
|
-
id: update.jid,
|
|
243
|
-
author: node.attrs.from,
|
|
244
|
-
user: update.user,
|
|
245
|
-
new_role: 'ADMIN',
|
|
246
|
-
action: 'promote'
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
}
|
|
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;
|
|
267
|
-
default:
|
|
268
|
-
logger.info({ operation, data }, 'unhandled mex newsletter notification');
|
|
269
|
-
break;
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
// Handles newsletter notifications
|
|
273
|
-
const handleNewsletterNotification = async (node) => {
|
|
274
|
-
const from = node.attrs.from;
|
|
275
|
-
const children = getAllBinaryNodeChildren(node);
|
|
276
|
-
const author = node.attrs.participant;
|
|
277
|
-
for (const child of children) {
|
|
278
|
-
logger.debug({ from, child }, 'got newsletter notification');
|
|
279
|
-
switch (child.tag) {
|
|
280
|
-
case 'reaction': {
|
|
281
|
-
const reactionUpdate = {
|
|
282
|
-
id: from,
|
|
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;
|
|
291
|
-
}
|
|
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
|
-
});
|
|
326
|
-
}
|
|
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
|
-
}
|
|
352
|
-
}
|
|
353
|
-
break;
|
|
354
|
-
}
|
|
355
|
-
default:
|
|
356
|
-
logger.warn({ node, child }, 'Unknown newsletter notification child');
|
|
357
|
-
break;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
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');
|
|
364
|
-
await sendNode(stanza);
|
|
365
|
-
};
|
|
366
|
-
const rejectCall = async (callId, callFrom) => {
|
|
367
|
-
const stanza = {
|
|
368
|
-
tag: 'call',
|
|
369
|
-
attrs: {
|
|
370
|
-
from: authState.creds.me.id,
|
|
371
|
-
to: callFrom
|
|
372
|
-
},
|
|
373
|
-
content: [
|
|
374
|
-
{
|
|
375
|
-
tag: 'reject',
|
|
376
|
-
attrs: {
|
|
377
|
-
'call-id': callId,
|
|
378
|
-
'call-creator': callFrom,
|
|
379
|
-
count: '0'
|
|
380
|
-
},
|
|
381
|
-
content: undefined
|
|
382
|
-
}
|
|
383
|
-
]
|
|
384
|
-
};
|
|
385
|
-
await query(stanza);
|
|
386
|
-
};
|
|
387
|
-
const sendRetryRequest = async (node, forceIncludeKeys = false) => {
|
|
388
|
-
const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
|
|
389
|
-
const { key: msgKey } = fullMessage;
|
|
390
|
-
const msgId = msgKey.id;
|
|
391
|
-
if (messageRetryManager) {
|
|
392
|
-
// Check if we've exceeded max retries using the new system
|
|
393
|
-
if (messageRetryManager.hasExceededMaxRetries(msgId)) {
|
|
394
|
-
logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
|
|
395
|
-
messageRetryManager.markRetryFailed(msgId);
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
// Increment retry count using new system
|
|
399
|
-
const retryCount = messageRetryManager.incrementRetryCount(msgId);
|
|
400
|
-
// Use the new retry count for the rest of the logic
|
|
401
|
-
const key = `${msgId}:${msgKey?.participant}`;
|
|
402
|
-
await msgRetryCache.set(key, retryCount);
|
|
403
|
-
}
|
|
404
|
-
else {
|
|
405
|
-
// Fallback to old system
|
|
406
|
-
const key = `${msgId}:${msgKey?.participant}`;
|
|
407
|
-
let retryCount = (await msgRetryCache.get(key)) || 0;
|
|
408
|
-
if (retryCount >= maxMsgRetryCount) {
|
|
409
|
-
logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
|
|
410
|
-
await msgRetryCache.del(key);
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
retryCount += 1;
|
|
414
|
-
await msgRetryCache.set(key, retryCount);
|
|
415
|
-
}
|
|
416
|
-
const key = `${msgId}:${msgKey?.participant}`;
|
|
417
|
-
const retryCount = (await msgRetryCache.get(key)) || 1;
|
|
418
|
-
const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
|
|
419
|
-
const fromJid = node.attrs.from;
|
|
420
|
-
// Check if we should recreate the session
|
|
421
|
-
let shouldRecreateSession = false;
|
|
422
|
-
let recreateReason = '';
|
|
423
|
-
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
|
|
424
|
-
try {
|
|
425
|
-
// Check if we have a session with this JID
|
|
426
|
-
const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
|
|
427
|
-
const hasSession = await signalRepository.validateSession(fromJid);
|
|
428
|
-
const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
|
|
429
|
-
shouldRecreateSession = result.recreate;
|
|
430
|
-
recreateReason = result.reason;
|
|
431
|
-
if (shouldRecreateSession) {
|
|
432
|
-
logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
|
|
433
|
-
// Delete existing session to force recreation
|
|
434
|
-
await authState.keys.set({ session: { [sessionId]: null } });
|
|
435
|
-
forceIncludeKeys = true;
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
catch (error) {
|
|
439
|
-
logger.warn({ error, fromJid }, 'failed to check session recreation');
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
if (retryCount <= 2) {
|
|
443
|
-
// Use new retry manager for phone requests if available
|
|
444
|
-
if (messageRetryManager) {
|
|
445
|
-
// Schedule phone request with delay (like whatsmeow)
|
|
446
|
-
messageRetryManager.schedulePhoneRequest(msgId, async () => {
|
|
447
|
-
try {
|
|
448
|
-
const requestId = await requestPlaceholderResend(msgKey);
|
|
449
|
-
logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
|
|
450
|
-
}
|
|
451
|
-
catch (error) {
|
|
452
|
-
logger.warn({ error, msgId }, 'failed to send scheduled phone request');
|
|
453
|
-
}
|
|
454
|
-
});
|
|
455
|
-
}
|
|
456
|
-
else {
|
|
457
|
-
// Fallback to immediate request
|
|
458
|
-
const msgId = await requestPlaceholderResend(msgKey);
|
|
459
|
-
logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
break;
|
|
240
|
+
case 'NotificationNewsletterAdminPromote':
|
|
241
|
+
for (const update of updates) {
|
|
242
|
+
if (update.jid && update.user) {
|
|
243
|
+
ev.emit('newsletter-participants.update', {
|
|
244
|
+
id: update.jid,
|
|
245
|
+
author: node.attrs.from,
|
|
246
|
+
user: update.user,
|
|
247
|
+
new_role: 'ADMIN',
|
|
248
|
+
action: 'promote'
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
break;
|
|
253
|
+
case 'NotificationLinkedProfilesUpdates':
|
|
254
|
+
for (const update of updates) {
|
|
255
|
+
const lid = update?.jid;
|
|
256
|
+
const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
|
|
257
|
+
const mappings = [];
|
|
258
|
+
for (const profile of addedProfiles) {
|
|
259
|
+
const pn = typeof profile === 'string' ? profile : profile?.pn ?? profile?.jid ?? null;
|
|
260
|
+
if (lid && pn) {
|
|
261
|
+
const mapping = {
|
|
262
|
+
lid,
|
|
263
|
+
pn
|
|
264
|
+
};
|
|
265
|
+
ev.emit('lid-mapping.update', mapping);
|
|
266
|
+
mappings.push(mapping);
|
|
460
267
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
268
|
+
}
|
|
269
|
+
await signalRepository.lidMapping.storeLIDPNMappings(mappings);
|
|
270
|
+
}
|
|
271
|
+
break;
|
|
272
|
+
default:
|
|
273
|
+
logger.info({
|
|
274
|
+
operation,
|
|
275
|
+
data
|
|
276
|
+
}, 'unhandled mex newsletter notification');
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
const handleNewsletterNotification = async node => {
|
|
281
|
+
const from = node.attrs.from;
|
|
282
|
+
const children = getAllBinaryNodeChildren(node);
|
|
283
|
+
const author = node.attrs.participant;
|
|
284
|
+
for (const child of children) {
|
|
285
|
+
logger.debug({
|
|
286
|
+
from,
|
|
287
|
+
child
|
|
288
|
+
}, 'got newsletter notification');
|
|
289
|
+
switch (child.tag) {
|
|
290
|
+
case 'reaction':
|
|
291
|
+
{
|
|
292
|
+
const reactionUpdate = {
|
|
293
|
+
id: from,
|
|
294
|
+
server_id: child.attrs.message_id,
|
|
295
|
+
reaction: {
|
|
296
|
+
code: getBinaryNodeChildString(child, 'reaction'),
|
|
297
|
+
count: 1
|
|
298
|
+
}
|
|
489
299
|
};
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
300
|
+
ev.emit('newsletter.reaction', reactionUpdate);
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
case 'view':
|
|
304
|
+
{
|
|
305
|
+
const viewUpdate = {
|
|
306
|
+
id: from,
|
|
307
|
+
server_id: child.attrs.message_id,
|
|
308
|
+
count: parseInt(child.content?.toString() || '0', 10)
|
|
309
|
+
};
|
|
310
|
+
ev.emit('newsletter.view', viewUpdate);
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
case 'participant':
|
|
314
|
+
{
|
|
315
|
+
const participantUpdate = {
|
|
316
|
+
id: from,
|
|
317
|
+
author,
|
|
318
|
+
user: child.attrs.jid,
|
|
319
|
+
action: child.attrs.action,
|
|
320
|
+
new_role: child.attrs.role
|
|
321
|
+
};
|
|
322
|
+
ev.emit('newsletter-participants.update', participantUpdate);
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
case 'update':
|
|
326
|
+
{
|
|
327
|
+
const settingsNode = getBinaryNodeChild(child, 'settings');
|
|
328
|
+
if (settingsNode) {
|
|
329
|
+
const update = {};
|
|
330
|
+
const nameNode = getBinaryNodeChild(settingsNode, 'name');
|
|
331
|
+
if (nameNode?.content) update.name = nameNode.content.toString();
|
|
332
|
+
const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
|
|
333
|
+
if (descriptionNode?.content) update.description = descriptionNode.content.toString();
|
|
334
|
+
ev.emit('newsletter-settings.update', {
|
|
335
|
+
id: from,
|
|
336
|
+
update
|
|
337
|
+
});
|
|
495
338
|
}
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
339
|
+
break;
|
|
340
|
+
}
|
|
341
|
+
case 'message':
|
|
342
|
+
{
|
|
343
|
+
const plaintextNode = getBinaryNodeChild(child, 'plaintext');
|
|
344
|
+
if (plaintextNode?.content) {
|
|
345
|
+
try {
|
|
346
|
+
const contentBuf = typeof plaintextNode.content === 'string' ? Buffer.from(plaintextNode.content, 'binary') : Buffer.from(plaintextNode.content);
|
|
347
|
+
const messageProto = proto.Message.decode(contentBuf).toJSON();
|
|
348
|
+
const fullMessage = proto.WebMessageInfo.fromObject({
|
|
349
|
+
key: {
|
|
350
|
+
remoteJid: from,
|
|
351
|
+
id: child.attrs.message_id || child.attrs.server_id,
|
|
352
|
+
fromMe: false
|
|
353
|
+
},
|
|
354
|
+
message: messageProto,
|
|
355
|
+
messageTimestamp: +child.attrs.t
|
|
356
|
+
}).toJSON();
|
|
357
|
+
await upsertMessage(fullMessage, 'append');
|
|
358
|
+
logger.debug('Processed plaintext newsletter message');
|
|
359
|
+
} catch (error) {
|
|
360
|
+
logger.error({
|
|
361
|
+
error
|
|
362
|
+
}, 'Failed to decode plaintext newsletter message');
|
|
363
|
+
}
|
|
513
364
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
default:
|
|
368
|
+
logger.warn({
|
|
369
|
+
node,
|
|
370
|
+
child
|
|
371
|
+
}, 'Unknown newsletter notification child');
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
const sendMessageAck = async (node, errorCode) => {
|
|
377
|
+
const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
|
|
378
|
+
logger.debug({
|
|
379
|
+
recv: {
|
|
380
|
+
tag: node.tag,
|
|
381
|
+
attrs: node.attrs
|
|
382
|
+
},
|
|
383
|
+
sent: stanza.attrs
|
|
384
|
+
}, 'sent ack');
|
|
385
|
+
await sendNode(stanza);
|
|
386
|
+
};
|
|
387
|
+
const rejectCall = async (callId, callFrom) => {
|
|
388
|
+
const stanza = {
|
|
389
|
+
tag: 'call',
|
|
390
|
+
attrs: {
|
|
391
|
+
from: authState.creds.me.id,
|
|
392
|
+
to: callFrom
|
|
393
|
+
},
|
|
394
|
+
content: [{
|
|
395
|
+
tag: 'reject',
|
|
396
|
+
attrs: {
|
|
397
|
+
'call-id': callId,
|
|
398
|
+
'call-creator': callFrom,
|
|
399
|
+
count: '0'
|
|
400
|
+
},
|
|
401
|
+
content: undefined
|
|
402
|
+
}]
|
|
517
403
|
};
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
404
|
+
await query(stanza);
|
|
405
|
+
};
|
|
406
|
+
const sendRetryRequest = async (node, forceIncludeKeys = false) => {
|
|
407
|
+
const {
|
|
408
|
+
fullMessage
|
|
409
|
+
} = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
|
|
410
|
+
const {
|
|
411
|
+
key: msgKey
|
|
412
|
+
} = fullMessage;
|
|
413
|
+
const msgId = msgKey.id;
|
|
414
|
+
if (messageRetryManager) {
|
|
415
|
+
if (messageRetryManager.hasExceededMaxRetries(msgId)) {
|
|
416
|
+
logger.debug({
|
|
417
|
+
msgId
|
|
418
|
+
}, 'reached retry limit with new retry manager, clearing');
|
|
419
|
+
messageRetryManager.markRetryFailed(msgId);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
const retryCount = messageRetryManager.incrementRetryCount(msgId);
|
|
423
|
+
const key = `${msgId}:${msgKey?.participant}`;
|
|
424
|
+
await msgRetryCache.set(key, retryCount);
|
|
425
|
+
} else {
|
|
426
|
+
const key = `${msgId}:${msgKey?.participant}`;
|
|
427
|
+
let retryCount = (await msgRetryCache.get(key)) || 0;
|
|
428
|
+
if (retryCount >= maxMsgRetryCount) {
|
|
429
|
+
logger.debug({
|
|
430
|
+
retryCount,
|
|
431
|
+
msgId
|
|
432
|
+
}, 'reached retry limit, clearing');
|
|
433
|
+
await msgRetryCache.del(key);
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
retryCount += 1;
|
|
437
|
+
await msgRetryCache.set(key, retryCount);
|
|
438
|
+
}
|
|
439
|
+
const key = `${msgId}:${msgKey?.participant}`;
|
|
440
|
+
const retryCount = (await msgRetryCache.get(key)) || 1;
|
|
441
|
+
const {
|
|
442
|
+
account,
|
|
443
|
+
signedPreKey,
|
|
444
|
+
signedIdentityKey: identityKey
|
|
445
|
+
} = authState.creds;
|
|
446
|
+
const fromJid = node.attrs.from;
|
|
447
|
+
let shouldRecreateSession = false;
|
|
448
|
+
let recreateReason = '';
|
|
449
|
+
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
|
|
450
|
+
try {
|
|
451
|
+
const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
|
|
452
|
+
const hasSession = await signalRepository.validateSession(fromJid);
|
|
453
|
+
const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
|
|
454
|
+
shouldRecreateSession = result.recreate;
|
|
455
|
+
recreateReason = result.reason;
|
|
456
|
+
if (shouldRecreateSession) {
|
|
457
|
+
logger.debug({
|
|
458
|
+
fromJid,
|
|
459
|
+
retryCount,
|
|
460
|
+
reason: recreateReason
|
|
461
|
+
}, 'recreating session for retry');
|
|
462
|
+
await authState.keys.set({
|
|
463
|
+
session: {
|
|
464
|
+
[sessionId]: null
|
|
533
465
|
}
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
466
|
+
});
|
|
467
|
+
forceIncludeKeys = true;
|
|
468
|
+
}
|
|
469
|
+
} catch (error) {
|
|
470
|
+
logger.warn({
|
|
471
|
+
error,
|
|
472
|
+
fromJid
|
|
473
|
+
}, 'failed to check session recreation');
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (retryCount <= 2) {
|
|
477
|
+
if (messageRetryManager) {
|
|
478
|
+
messageRetryManager.schedulePhoneRequest(msgId, async () => {
|
|
479
|
+
try {
|
|
480
|
+
const requestId = await requestPlaceholderResend(msgKey);
|
|
481
|
+
logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
|
|
482
|
+
} catch (error) {
|
|
483
|
+
logger.warn({
|
|
484
|
+
error,
|
|
485
|
+
msgId
|
|
486
|
+
}, 'failed to send scheduled phone request');
|
|
487
|
+
}
|
|
547
488
|
});
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
const
|
|
590
|
-
const
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
ev.emit('groups.upsert', [
|
|
608
|
-
{
|
|
609
|
-
...metadata,
|
|
610
|
-
author: actingParticipantLid,
|
|
611
|
-
authorPn: actingParticipantPn,
|
|
612
|
-
authorUsername: actingParticipantUsername
|
|
613
|
-
}
|
|
614
|
-
]);
|
|
615
|
-
break;
|
|
616
|
-
case 'ephemeral':
|
|
617
|
-
case 'not_ephemeral':
|
|
618
|
-
msg.message = {
|
|
619
|
-
protocolMessage: {
|
|
620
|
-
type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
|
|
621
|
-
ephemeralExpiration: +(child.attrs.expiration || 0)
|
|
622
|
-
}
|
|
623
|
-
};
|
|
624
|
-
break;
|
|
625
|
-
case 'modify':
|
|
626
|
-
const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
|
|
627
|
-
msg.messageStubParameters = oldNumber || [];
|
|
628
|
-
msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
|
|
629
|
-
break;
|
|
630
|
-
case 'promote':
|
|
631
|
-
case 'demote':
|
|
632
|
-
case 'remove':
|
|
633
|
-
case 'add':
|
|
634
|
-
case 'leave':
|
|
635
|
-
const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
|
|
636
|
-
msg.messageStubType = WAMessageStubType[stubType];
|
|
637
|
-
const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
|
|
638
|
-
// TODO: Store LID MAPPINGS
|
|
639
|
-
return {
|
|
640
|
-
id: attrs.jid,
|
|
641
|
-
phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
|
|
642
|
-
lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
|
|
643
|
-
username: attrs.participant_username || attrs.username || undefined,
|
|
644
|
-
admin: (attrs.type || null)
|
|
645
|
-
};
|
|
646
|
-
});
|
|
647
|
-
if (participants.length === 1 &&
|
|
648
|
-
// if recv. "remove" message and sender removed themselves
|
|
649
|
-
// mark as left
|
|
650
|
-
(areJidsSameUser(participants[0].id, actingParticipantLid) ||
|
|
651
|
-
areJidsSameUser(participants[0].id, actingParticipantPn)) &&
|
|
652
|
-
child.tag === 'remove') {
|
|
653
|
-
msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
|
|
654
|
-
}
|
|
655
|
-
msg.messageStubParameters = participants.map(a => JSON.stringify(a));
|
|
656
|
-
break;
|
|
657
|
-
case 'subject':
|
|
658
|
-
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
|
|
659
|
-
msg.messageStubParameters = [child.attrs.subject];
|
|
660
|
-
break;
|
|
661
|
-
case 'description':
|
|
662
|
-
const description = getBinaryNodeChild(child, 'body')?.content?.toString();
|
|
663
|
-
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
|
|
664
|
-
msg.messageStubParameters = description ? [description] : undefined;
|
|
665
|
-
break;
|
|
666
|
-
case 'announcement':
|
|
667
|
-
case 'not_announcement':
|
|
668
|
-
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
|
|
669
|
-
msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
|
|
670
|
-
break;
|
|
671
|
-
case 'locked':
|
|
672
|
-
case 'unlocked':
|
|
673
|
-
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
|
|
674
|
-
msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
|
|
675
|
-
break;
|
|
676
|
-
case 'invite':
|
|
677
|
-
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
|
|
678
|
-
msg.messageStubParameters = [child.attrs.code];
|
|
679
|
-
break;
|
|
680
|
-
case 'member_add_mode':
|
|
681
|
-
const addMode = child.content;
|
|
682
|
-
if (addMode) {
|
|
683
|
-
msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
|
|
684
|
-
msg.messageStubParameters = [addMode.toString()];
|
|
685
|
-
}
|
|
686
|
-
break;
|
|
687
|
-
case 'membership_approval_mode':
|
|
688
|
-
const approvalMode = getBinaryNodeChild(child, 'group_join');
|
|
689
|
-
if (approvalMode) {
|
|
690
|
-
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
|
|
691
|
-
msg.messageStubParameters = [approvalMode.attrs.state];
|
|
692
|
-
}
|
|
693
|
-
break;
|
|
694
|
-
case 'created_membership_requests':
|
|
695
|
-
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
|
|
696
|
-
msg.messageStubParameters = [
|
|
697
|
-
JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
|
|
698
|
-
'created',
|
|
699
|
-
child.attrs.request_method
|
|
700
|
-
];
|
|
701
|
-
break;
|
|
702
|
-
case 'revoked_membership_requests':
|
|
703
|
-
const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
|
|
704
|
-
// TODO: LIDMAPPING SUPPORT
|
|
705
|
-
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
|
|
706
|
-
msg.messageStubParameters = [
|
|
707
|
-
JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
|
|
708
|
-
isDenied ? 'revoked' : 'rejected'
|
|
709
|
-
];
|
|
710
|
-
break;
|
|
711
|
-
}
|
|
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
|
-
}
|
|
489
|
+
} else {
|
|
490
|
+
const msgId = await requestPlaceholderResend(msgKey);
|
|
491
|
+
logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
const deviceIdentity = encodeSignedDeviceIdentity(account, true);
|
|
495
|
+
await authState.keys.transaction(async () => {
|
|
496
|
+
const receipt = {
|
|
497
|
+
tag: 'receipt',
|
|
498
|
+
attrs: {
|
|
499
|
+
id: msgId,
|
|
500
|
+
type: 'retry',
|
|
501
|
+
to: node.attrs.from
|
|
502
|
+
},
|
|
503
|
+
content: [{
|
|
504
|
+
tag: 'retry',
|
|
505
|
+
attrs: {
|
|
506
|
+
count: retryCount.toString(),
|
|
507
|
+
id: node.attrs.id,
|
|
508
|
+
t: node.attrs.t,
|
|
509
|
+
v: '1',
|
|
510
|
+
error: '0'
|
|
511
|
+
}
|
|
512
|
+
}, {
|
|
513
|
+
tag: 'registration',
|
|
514
|
+
attrs: {},
|
|
515
|
+
content: encodeBigEndian(authState.creds.registrationId)
|
|
516
|
+
}]
|
|
517
|
+
};
|
|
518
|
+
if (node.attrs.recipient) {
|
|
519
|
+
receipt.attrs.recipient = node.attrs.recipient;
|
|
520
|
+
}
|
|
521
|
+
if (node.attrs.participant) {
|
|
522
|
+
receipt.attrs.participant = node.attrs.participant;
|
|
523
|
+
}
|
|
524
|
+
if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
|
|
525
|
+
const {
|
|
526
|
+
update,
|
|
527
|
+
preKeys
|
|
528
|
+
} = await getNextPreKeys(authState, 1);
|
|
529
|
+
const [keyId] = Object.keys(preKeys);
|
|
530
|
+
const key = preKeys[+keyId];
|
|
531
|
+
const content = receipt.content;
|
|
532
|
+
content.push({
|
|
533
|
+
tag: 'keys',
|
|
534
|
+
attrs: {},
|
|
535
|
+
content: [{
|
|
536
|
+
tag: 'type',
|
|
537
|
+
attrs: {},
|
|
538
|
+
content: Buffer.from(KEY_BUNDLE_TYPE)
|
|
539
|
+
}, {
|
|
540
|
+
tag: 'identity',
|
|
541
|
+
attrs: {},
|
|
542
|
+
content: identityKey.public
|
|
543
|
+
}, xmppPreKey(key, +keyId), xmppSignedPreKey(signedPreKey), {
|
|
544
|
+
tag: 'device-identity',
|
|
545
|
+
attrs: {},
|
|
546
|
+
content: deviceIdentity
|
|
547
|
+
}]
|
|
794
548
|
});
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
result.key = {
|
|
852
|
-
...(result.key || {}),
|
|
853
|
-
participant: setPicture?.attrs.author
|
|
854
|
-
};
|
|
855
|
-
}
|
|
856
|
-
break;
|
|
857
|
-
case 'account_sync':
|
|
858
|
-
if (child.tag === 'disappearing_mode') {
|
|
859
|
-
const newDuration = +child.attrs.duration;
|
|
860
|
-
const timestamp = +child.attrs.t;
|
|
861
|
-
logger.info({ newDuration }, 'updated account disappearing mode');
|
|
862
|
-
ev.emit('creds.update', {
|
|
863
|
-
accountSettings: {
|
|
864
|
-
...authState.creds.accountSettings,
|
|
865
|
-
defaultDisappearingMode: {
|
|
866
|
-
ephemeralExpiration: newDuration,
|
|
867
|
-
ephemeralSettingTimestamp: timestamp
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
});
|
|
871
|
-
}
|
|
872
|
-
else if (child.tag === 'blocklist') {
|
|
873
|
-
const blocklists = getBinaryNodeChildren(child, 'item');
|
|
874
|
-
for (const { attrs } of blocklists) {
|
|
875
|
-
const blocklist = [attrs.jid];
|
|
876
|
-
const type = attrs.action === 'block' ? 'add' : 'remove';
|
|
877
|
-
ev.emit('blocklist.update', { blocklist, type });
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
break;
|
|
881
|
-
case 'link_code_companion_reg':
|
|
882
|
-
const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
|
|
883
|
-
const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
|
|
884
|
-
const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
|
|
885
|
-
const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
|
|
886
|
-
const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
|
|
887
|
-
const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
|
|
888
|
-
const random = randomBytes(32);
|
|
889
|
-
const linkCodeSalt = randomBytes(32);
|
|
890
|
-
const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
|
|
891
|
-
salt: linkCodeSalt,
|
|
892
|
-
info: 'link_code_pairing_key_bundle_encryption_key'
|
|
893
|
-
});
|
|
894
|
-
const encryptPayload = Buffer.concat([
|
|
895
|
-
Buffer.from(authState.creds.signedIdentityKey.public),
|
|
896
|
-
primaryIdentityPublicKey,
|
|
897
|
-
random
|
|
898
|
-
]);
|
|
899
|
-
const encryptIv = randomBytes(12);
|
|
900
|
-
const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
|
|
901
|
-
const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
|
|
902
|
-
const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
|
|
903
|
-
const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
|
|
904
|
-
authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
|
|
905
|
-
await query({
|
|
906
|
-
tag: 'iq',
|
|
907
|
-
attrs: {
|
|
908
|
-
to: S_WHATSAPP_NET,
|
|
909
|
-
type: 'set',
|
|
910
|
-
id: sock.generateMessageTag(),
|
|
911
|
-
xmlns: 'md'
|
|
912
|
-
},
|
|
913
|
-
content: [
|
|
914
|
-
{
|
|
915
|
-
tag: 'link_code_companion_reg',
|
|
916
|
-
attrs: {
|
|
917
|
-
jid: authState.creds.me.id,
|
|
918
|
-
stage: 'companion_finish'
|
|
919
|
-
},
|
|
920
|
-
content: [
|
|
921
|
-
{
|
|
922
|
-
tag: 'link_code_pairing_wrapped_key_bundle',
|
|
923
|
-
attrs: {},
|
|
924
|
-
content: encryptedPayload
|
|
925
|
-
},
|
|
926
|
-
{
|
|
927
|
-
tag: 'companion_identity_public',
|
|
928
|
-
attrs: {},
|
|
929
|
-
content: authState.creds.signedIdentityKey.public
|
|
930
|
-
},
|
|
931
|
-
{
|
|
932
|
-
tag: 'link_code_pairing_ref',
|
|
933
|
-
attrs: {},
|
|
934
|
-
content: ref
|
|
935
|
-
}
|
|
936
|
-
]
|
|
937
|
-
}
|
|
938
|
-
]
|
|
939
|
-
});
|
|
940
|
-
authState.creds.registered = true;
|
|
941
|
-
ev.emit('creds.update', authState.creds);
|
|
942
|
-
break;
|
|
943
|
-
case 'privacy_token':
|
|
944
|
-
await handlePrivacyTokenNotification(node);
|
|
945
|
-
break;
|
|
946
|
-
}
|
|
947
|
-
if (Object.keys(result).length) {
|
|
948
|
-
return result;
|
|
949
|
-
}
|
|
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 () => {
|
|
549
|
+
ev.emit('creds.update', update);
|
|
550
|
+
}
|
|
551
|
+
await sendNode(receipt);
|
|
552
|
+
logger.info({
|
|
553
|
+
msgAttrs: node.attrs,
|
|
554
|
+
retryCount
|
|
555
|
+
}, 'sent retry receipt');
|
|
556
|
+
}, authState?.creds?.me?.id || 'sendRetryRequest');
|
|
557
|
+
};
|
|
558
|
+
const inFlightPreKeyLow = new Set();
|
|
559
|
+
const reissueTcTokenAfterIdentityChange = from => {
|
|
560
|
+
void (async () => {
|
|
561
|
+
const normalizedJid = jidNormalizedUser(from);
|
|
562
|
+
const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN);
|
|
563
|
+
const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
|
|
564
|
+
const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
|
|
565
|
+
if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) {
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
logger.debug({
|
|
569
|
+
jid: normalizedJid,
|
|
570
|
+
senderTimestamp: senderTs
|
|
571
|
+
}, 'identity changed, re-issuing tctoken');
|
|
572
|
+
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
|
|
573
|
+
const issueJid = await resolveIssuanceJid(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
|
|
574
|
+
const result = await issuePrivacyTokens([issueJid], senderTs);
|
|
575
|
+
await storeTcTokensFromIqResult({
|
|
576
|
+
result,
|
|
577
|
+
fallbackJid: tcJid,
|
|
578
|
+
keys: authState.keys,
|
|
579
|
+
getLIDForPN,
|
|
580
|
+
onNewJidStored: trackTcTokenJid
|
|
581
|
+
});
|
|
582
|
+
})().catch(err => {
|
|
583
|
+
logger.debug({
|
|
584
|
+
jid: from,
|
|
585
|
+
err: err?.message
|
|
586
|
+
}, 'failed to re-issue tctoken after identity change');
|
|
587
|
+
});
|
|
588
|
+
};
|
|
589
|
+
const handleEncryptNotification = async node => {
|
|
590
|
+
const from = node.attrs.from;
|
|
591
|
+
if (from === S_WHATSAPP_NET) {
|
|
592
|
+
const stanzaId = node.attrs.id;
|
|
593
|
+
if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
const countChild = getBinaryNodeChild(node, 'count');
|
|
597
|
+
const count = +countChild.attrs.value;
|
|
598
|
+
const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
|
|
599
|
+
logger.debug({
|
|
600
|
+
count,
|
|
601
|
+
shouldUploadMorePreKeys
|
|
602
|
+
}, 'recv pre-key count');
|
|
603
|
+
if (shouldUploadMorePreKeys) {
|
|
604
|
+
if (stanzaId) inFlightPreKeyLow.add(stanzaId);
|
|
958
605
|
try {
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
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 });
|
|
606
|
+
await uploadPreKeys();
|
|
607
|
+
} finally {
|
|
608
|
+
if (stanzaId) inFlightPreKeyLow.delete(stanzaId);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
} else {
|
|
612
|
+
logger.debug({
|
|
613
|
+
node
|
|
614
|
+
}, 'recv encrypt notification (identity change)');
|
|
978
615
|
}
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
616
|
+
};
|
|
617
|
+
const handleGroupNotification = (fullNode, child, msg) => {
|
|
618
|
+
const actingParticipantLid = fullNode.attrs.participant;
|
|
619
|
+
const actingParticipantPn = fullNode.attrs.participant_pn;
|
|
620
|
+
const actingParticipantUsername = fullNode.attrs.participant_username;
|
|
621
|
+
const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
|
|
622
|
+
const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
|
|
623
|
+
switch (child?.tag) {
|
|
624
|
+
case 'create':
|
|
625
|
+
const metadata = extractGroupMetadata(child);
|
|
626
|
+
msg.messageStubType = WAMessageStubType.GROUP_CREATE;
|
|
627
|
+
msg.messageStubParameters = [metadata.subject];
|
|
628
|
+
msg.key = {
|
|
629
|
+
participant: metadata.owner,
|
|
630
|
+
participantAlt: metadata.ownerPn
|
|
631
|
+
};
|
|
632
|
+
ev.emit('chats.upsert', [{
|
|
633
|
+
id: metadata.id,
|
|
634
|
+
name: metadata.subject,
|
|
635
|
+
conversationTimestamp: metadata.creation
|
|
636
|
+
}]);
|
|
637
|
+
ev.emit('groups.upsert', [{
|
|
638
|
+
...metadata,
|
|
639
|
+
author: actingParticipantLid,
|
|
640
|
+
authorPn: actingParticipantPn,
|
|
641
|
+
authorUsername: actingParticipantUsername
|
|
642
|
+
}]);
|
|
643
|
+
break;
|
|
644
|
+
case 'ephemeral':
|
|
645
|
+
case 'not_ephemeral':
|
|
646
|
+
msg.message = {
|
|
647
|
+
protocolMessage: {
|
|
648
|
+
type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
|
|
649
|
+
ephemeralExpiration: +(child.attrs.expiration || 0)
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
break;
|
|
653
|
+
case 'modify':
|
|
654
|
+
const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
|
|
655
|
+
msg.messageStubParameters = oldNumber || [];
|
|
656
|
+
msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
|
|
657
|
+
break;
|
|
658
|
+
case 'promote':
|
|
659
|
+
case 'demote':
|
|
660
|
+
case 'remove':
|
|
661
|
+
case 'add':
|
|
662
|
+
case 'leave':
|
|
663
|
+
const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
|
|
664
|
+
msg.messageStubType = WAMessageStubType[stubType];
|
|
665
|
+
const participants = getBinaryNodeChildren(child, 'participant').map(({
|
|
666
|
+
attrs
|
|
667
|
+
}) => {
|
|
668
|
+
return {
|
|
669
|
+
id: attrs.jid,
|
|
670
|
+
phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
|
|
671
|
+
lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
|
|
672
|
+
username: attrs.participant_username || attrs.username || undefined,
|
|
673
|
+
admin: attrs.type || null
|
|
674
|
+
};
|
|
675
|
+
});
|
|
676
|
+
if (participants.length === 1 && (areJidsSameUser(participants[0].id, actingParticipantLid) || areJidsSameUser(participants[0].id, actingParticipantPn)) && child.tag === 'remove') {
|
|
677
|
+
msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
|
|
678
|
+
}
|
|
679
|
+
msg.messageStubParameters = participants.map(a => JSON.stringify(a));
|
|
680
|
+
break;
|
|
681
|
+
case 'subject':
|
|
682
|
+
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
|
|
683
|
+
msg.messageStubParameters = [child.attrs.subject];
|
|
684
|
+
break;
|
|
685
|
+
case 'description':
|
|
686
|
+
const description = getBinaryNodeChild(child, 'body')?.content?.toString();
|
|
687
|
+
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
|
|
688
|
+
msg.messageStubParameters = description ? [description] : undefined;
|
|
689
|
+
break;
|
|
690
|
+
case 'announcement':
|
|
691
|
+
case 'not_announcement':
|
|
692
|
+
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
|
|
693
|
+
msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
|
|
694
|
+
break;
|
|
695
|
+
case 'locked':
|
|
696
|
+
case 'unlocked':
|
|
697
|
+
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
|
|
698
|
+
msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
|
|
699
|
+
break;
|
|
700
|
+
case 'invite':
|
|
701
|
+
msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
|
|
702
|
+
msg.messageStubParameters = [child.attrs.code];
|
|
703
|
+
break;
|
|
704
|
+
case 'member_add_mode':
|
|
705
|
+
const addMode = child.content;
|
|
706
|
+
if (addMode) {
|
|
707
|
+
msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
|
|
708
|
+
msg.messageStubParameters = [addMode.toString()];
|
|
709
|
+
}
|
|
710
|
+
break;
|
|
711
|
+
case 'membership_approval_mode':
|
|
712
|
+
const approvalMode = getBinaryNodeChild(child, 'group_join');
|
|
713
|
+
if (approvalMode) {
|
|
714
|
+
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
|
|
715
|
+
msg.messageStubParameters = [approvalMode.attrs.state];
|
|
716
|
+
}
|
|
717
|
+
break;
|
|
718
|
+
case 'created_membership_requests':
|
|
719
|
+
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
|
|
720
|
+
msg.messageStubParameters = [JSON.stringify({
|
|
721
|
+
lid: affectedParticipantLid,
|
|
722
|
+
pn: affectedParticipantPn
|
|
723
|
+
}), 'created', child.attrs.request_method];
|
|
724
|
+
break;
|
|
725
|
+
case 'revoked_membership_requests':
|
|
726
|
+
const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
|
|
727
|
+
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
|
|
728
|
+
msg.messageStubParameters = [JSON.stringify({
|
|
729
|
+
lid: affectedParticipantLid,
|
|
730
|
+
pn: affectedParticipantPn
|
|
731
|
+
}), isDenied ? 'revoked' : 'rejected'];
|
|
732
|
+
break;
|
|
733
|
+
}
|
|
734
|
+
};
|
|
735
|
+
const handleDevicesNotification = async node => {
|
|
736
|
+
const [child] = getAllBinaryNodeChildren(node);
|
|
737
|
+
const from = jidNormalizedUser(node.attrs.from);
|
|
738
|
+
if (!child) {
|
|
739
|
+
logger.debug({
|
|
740
|
+
from
|
|
741
|
+
}, 'devices notification missing child, skipping');
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
const tag = child.tag;
|
|
745
|
+
const deviceHash = child.attrs.device_hash;
|
|
746
|
+
const devices = getBinaryNodeChildren(child, 'device');
|
|
747
|
+
if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) {
|
|
748
|
+
const deviceJids = devices.map(d => d.attrs.jid);
|
|
749
|
+
logger.info({
|
|
750
|
+
deviceJids
|
|
751
|
+
}, 'got my own devices');
|
|
752
|
+
}
|
|
753
|
+
if (!devices.length) {
|
|
754
|
+
logger.debug({
|
|
755
|
+
from,
|
|
756
|
+
tag
|
|
757
|
+
}, 'no devices in notification, skipping');
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
const decoded = [];
|
|
761
|
+
for (const d of devices) {
|
|
762
|
+
const jid = d.attrs.jid;
|
|
763
|
+
if (!jid) continue;
|
|
764
|
+
const parts = jidDecode(jid);
|
|
765
|
+
if (!parts) {
|
|
766
|
+
logger.debug({
|
|
767
|
+
jid
|
|
768
|
+
}, 'failed to decode device jid, skipping');
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
decoded.push({
|
|
772
|
+
jid,
|
|
773
|
+
user: parts.user,
|
|
774
|
+
server: parts.server,
|
|
775
|
+
device: parts.device
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
if (!decoded.length) return;
|
|
779
|
+
await devicesMutex.mutex(async () => {
|
|
780
|
+
const byUser = new Map();
|
|
781
|
+
for (const d of decoded) {
|
|
782
|
+
const list = byUser.get(d.user) || [];
|
|
783
|
+
list.push(d);
|
|
784
|
+
byUser.set(d.user, list);
|
|
785
|
+
}
|
|
786
|
+
for (const [user, entries] of byUser) {
|
|
787
|
+
if (tag === 'update') {
|
|
788
|
+
logger.debug({
|
|
789
|
+
user
|
|
790
|
+
}, `${user}'s device list updated, dropping cached devices`);
|
|
791
|
+
await userDevicesCache?.del(user);
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
if (tag === 'remove') {
|
|
795
|
+
await signalRepository.deleteSession(entries.map(e => e.jid));
|
|
796
|
+
}
|
|
797
|
+
const existingCache = (await userDevicesCache?.get(user)) || [];
|
|
798
|
+
if (!existingCache.length) {
|
|
799
|
+
logger.debug({
|
|
800
|
+
user,
|
|
801
|
+
tag
|
|
802
|
+
}, 'device list not cached, deferring to USync refresh');
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
const affected = new Set(entries.map(e => e.device));
|
|
806
|
+
let updatedDevices;
|
|
807
|
+
switch (tag) {
|
|
808
|
+
case 'add':
|
|
809
|
+
logger.info({
|
|
810
|
+
deviceHash,
|
|
811
|
+
count: entries.length
|
|
812
|
+
}, 'devices added');
|
|
813
|
+
updatedDevices = [...existingCache.filter(d => !affected.has(d.device)), ...entries.map(e => ({
|
|
814
|
+
user: e.user,
|
|
815
|
+
server: e.server,
|
|
816
|
+
device: e.device
|
|
817
|
+
}))];
|
|
818
|
+
break;
|
|
819
|
+
case 'remove':
|
|
820
|
+
logger.info({
|
|
821
|
+
deviceHash,
|
|
822
|
+
count: entries.length
|
|
823
|
+
}, 'devices removed');
|
|
824
|
+
updatedDevices = existingCache.filter(d => !affected.has(d.device));
|
|
825
|
+
break;
|
|
826
|
+
default:
|
|
827
|
+
logger.debug({
|
|
828
|
+
tag
|
|
829
|
+
}, 'Unknown device list change tag');
|
|
830
|
+
continue;
|
|
831
|
+
}
|
|
832
|
+
if (updatedDevices.length === 0) {
|
|
833
|
+
await userDevicesCache?.del(user);
|
|
834
|
+
} else {
|
|
835
|
+
await userDevicesCache?.set(user, updatedDevices);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
};
|
|
840
|
+
const processNotification = async node => {
|
|
841
|
+
const result = {};
|
|
842
|
+
const [child] = getAllBinaryNodeChildren(node);
|
|
843
|
+
const nodeType = node.attrs.type;
|
|
844
|
+
const from = jidNormalizedUser(node.attrs.from);
|
|
845
|
+
switch (nodeType) {
|
|
846
|
+
case 'newsletter':
|
|
847
|
+
await handleNewsletterNotification(node);
|
|
848
|
+
break;
|
|
849
|
+
case 'mex':
|
|
850
|
+
await handleMexNotification(node);
|
|
851
|
+
break;
|
|
852
|
+
case 'w:gp2':
|
|
853
|
+
handleGroupNotification(node, child, result);
|
|
854
|
+
break;
|
|
855
|
+
case 'mediaretry':
|
|
856
|
+
const event = decodeMediaRetryNode(node);
|
|
857
|
+
ev.emit('messages.media-update', [event]);
|
|
858
|
+
break;
|
|
859
|
+
case 'encrypt':
|
|
860
|
+
await handleEncryptNotification(node);
|
|
861
|
+
break;
|
|
862
|
+
case 'devices':
|
|
863
|
+
try {
|
|
864
|
+
await handleDevicesNotification(node);
|
|
865
|
+
} catch (error) {
|
|
866
|
+
logger.error({
|
|
867
|
+
error,
|
|
868
|
+
node
|
|
869
|
+
}, 'failed to handle devices notification');
|
|
870
|
+
}
|
|
871
|
+
break;
|
|
872
|
+
case 'server_sync':
|
|
873
|
+
const update = getBinaryNodeChild(node, 'collection');
|
|
874
|
+
if (update) {
|
|
875
|
+
const name = update.attrs.name;
|
|
876
|
+
await resyncAppState([name], false);
|
|
877
|
+
}
|
|
878
|
+
break;
|
|
879
|
+
case 'picture':
|
|
880
|
+
const setPicture = getBinaryNodeChild(node, 'set');
|
|
881
|
+
const delPicture = getBinaryNodeChild(node, 'delete');
|
|
882
|
+
ev.emit('contacts.update', [{
|
|
883
|
+
id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
|
|
884
|
+
imgUrl: setPicture ? 'changed' : 'removed'
|
|
885
|
+
}]);
|
|
886
|
+
if (isJidGroup(from)) {
|
|
887
|
+
const node = setPicture || delPicture;
|
|
888
|
+
result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
|
|
889
|
+
if (setPicture) {
|
|
890
|
+
result.messageStubParameters = [setPicture.attrs.id];
|
|
891
|
+
}
|
|
892
|
+
result.participant = node?.attrs.author;
|
|
893
|
+
result.key = {
|
|
894
|
+
...(result.key || {}),
|
|
895
|
+
participant: setPicture?.attrs.author
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
break;
|
|
899
|
+
case 'account_sync':
|
|
900
|
+
if (child.tag === 'disappearing_mode') {
|
|
901
|
+
const newDuration = +child.attrs.duration;
|
|
902
|
+
const timestamp = +child.attrs.t;
|
|
903
|
+
logger.info({
|
|
904
|
+
newDuration
|
|
905
|
+
}, 'updated account disappearing mode');
|
|
906
|
+
ev.emit('creds.update', {
|
|
907
|
+
accountSettings: {
|
|
908
|
+
...authState.creds.accountSettings,
|
|
909
|
+
defaultDisappearingMode: {
|
|
910
|
+
ephemeralExpiration: newDuration,
|
|
911
|
+
ephemeralSettingTimestamp: timestamp
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
} else if (child.tag === 'blocklist') {
|
|
916
|
+
const blocklists = getBinaryNodeChildren(child, 'item');
|
|
917
|
+
for (const {
|
|
918
|
+
attrs
|
|
919
|
+
} of blocklists) {
|
|
920
|
+
const blocklist = [attrs.jid];
|
|
921
|
+
const type = attrs.action === 'block' ? 'add' : 'remove';
|
|
922
|
+
ev.emit('blocklist.update', {
|
|
923
|
+
blocklist,
|
|
924
|
+
type
|
|
987
925
|
});
|
|
988
|
-
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
break;
|
|
929
|
+
case 'link_code_companion_reg':
|
|
930
|
+
const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
|
|
931
|
+
const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
|
|
932
|
+
const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
|
|
933
|
+
const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
|
|
934
|
+
const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
|
|
935
|
+
const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
|
|
936
|
+
const random = randomBytes(32);
|
|
937
|
+
const linkCodeSalt = randomBytes(32);
|
|
938
|
+
const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
|
|
939
|
+
salt: linkCodeSalt,
|
|
940
|
+
info: 'link_code_pairing_key_bundle_encryption_key'
|
|
941
|
+
});
|
|
942
|
+
const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
|
|
943
|
+
const encryptIv = randomBytes(12);
|
|
944
|
+
const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
|
|
945
|
+
const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
|
|
946
|
+
const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
|
|
947
|
+
const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
|
|
948
|
+
authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, {
|
|
949
|
+
info: 'adv_secret'
|
|
950
|
+
})).toString('base64');
|
|
951
|
+
await query({
|
|
952
|
+
tag: 'iq',
|
|
953
|
+
attrs: {
|
|
954
|
+
to: S_WHATSAPP_NET,
|
|
955
|
+
type: 'set',
|
|
956
|
+
id: sock.generateMessageTag(),
|
|
957
|
+
xmlns: 'md'
|
|
958
|
+
},
|
|
959
|
+
content: [{
|
|
960
|
+
tag: 'link_code_companion_reg',
|
|
961
|
+
attrs: {
|
|
962
|
+
jid: authState.creds.me.id,
|
|
963
|
+
stage: 'companion_finish'
|
|
964
|
+
},
|
|
965
|
+
content: [{
|
|
966
|
+
tag: 'link_code_pairing_wrapped_key_bundle',
|
|
967
|
+
attrs: {},
|
|
968
|
+
content: encryptedPayload
|
|
969
|
+
}, {
|
|
970
|
+
tag: 'companion_identity_public',
|
|
971
|
+
attrs: {},
|
|
972
|
+
content: authState.creds.signedIdentityKey.public
|
|
973
|
+
}, {
|
|
974
|
+
tag: 'link_code_pairing_ref',
|
|
975
|
+
attrs: {},
|
|
976
|
+
content: ref
|
|
977
|
+
}]
|
|
978
|
+
}]
|
|
979
|
+
});
|
|
980
|
+
authState.creds.registered = true;
|
|
981
|
+
ev.emit('creds.update', authState.creds);
|
|
982
|
+
break;
|
|
983
|
+
case 'privacy_token':
|
|
984
|
+
await handlePrivacyTokenNotification(node);
|
|
985
|
+
break;
|
|
989
986
|
}
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
987
|
+
if (Object.keys(result).length) {
|
|
988
|
+
return result;
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
const tcTokenKnownJids = new Set();
|
|
992
|
+
const tcTokenIndexLoaded = (async () => {
|
|
993
|
+
try {
|
|
994
|
+
const jids = await readTcTokenIndex(authState.keys);
|
|
995
|
+
for (const jid of jids) tcTokenKnownJids.add(jid);
|
|
996
|
+
logger.debug({
|
|
997
|
+
count: tcTokenKnownJids.size
|
|
998
|
+
}, 'loaded tctoken index');
|
|
999
|
+
} catch (err) {
|
|
1000
|
+
logger.warn({
|
|
1001
|
+
err: err?.message
|
|
1002
|
+
}, 'failed to load tctoken index');
|
|
1003
|
+
}
|
|
1004
|
+
})();
|
|
1005
|
+
let tcTokenIndexTimer;
|
|
1006
|
+
async function flushTcTokenIndex() {
|
|
1007
|
+
if (tcTokenIndexTimer) {
|
|
1008
|
+
clearTimeout(tcTokenIndexTimer);
|
|
1009
|
+
tcTokenIndexTimer = undefined;
|
|
1010
|
+
}
|
|
1011
|
+
const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids);
|
|
1012
|
+
return authState.keys.set({
|
|
1013
|
+
tctoken: write
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
function scheduleTcTokenIndexSave() {
|
|
1017
|
+
if (tcTokenIndexTimer) {
|
|
1018
|
+
clearTimeout(tcTokenIndexTimer);
|
|
995
1019
|
}
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1020
|
+
tcTokenIndexTimer = setTimeout(() => {
|
|
1021
|
+
tcTokenIndexTimer = undefined;
|
|
1022
|
+
flushTcTokenIndex().catch(err => {
|
|
1023
|
+
logger.warn({
|
|
1024
|
+
err: err?.message
|
|
1025
|
+
}, 'failed to save tctoken index');
|
|
1026
|
+
});
|
|
1027
|
+
}, 5000);
|
|
1028
|
+
}
|
|
1029
|
+
function trackTcTokenJid(jid) {
|
|
1030
|
+
if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
|
|
1031
|
+
tcTokenKnownJids.add(jid);
|
|
1032
|
+
scheduleTcTokenIndexSave();
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
const handlePrivacyTokenNotification = async node => {
|
|
1036
|
+
const tokensNode = getBinaryNodeChild(node, 'tokens');
|
|
1037
|
+
if (!tokensNode) return;
|
|
1038
|
+
const from = jidNormalizedUser(node.attrs.from);
|
|
1039
|
+
const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid)) ? jidNormalizedUser(node.attrs.sender_lid) : undefined;
|
|
1040
|
+
const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN));
|
|
1041
|
+
logger.debug({
|
|
1042
|
+
from,
|
|
1043
|
+
storageJid: fallbackJid
|
|
1044
|
+
}, 'processing privacy token notification');
|
|
1045
|
+
await storeTcTokensFromIqResult({
|
|
1046
|
+
result: node,
|
|
1047
|
+
fallbackJid,
|
|
1048
|
+
keys: authState.keys,
|
|
1049
|
+
getLIDForPN,
|
|
1050
|
+
onNewJidStored: trackTcTokenJid
|
|
1051
|
+
});
|
|
1052
|
+
};
|
|
1053
|
+
async function decipherLinkPublicKey(data) {
|
|
1054
|
+
const buffer = toRequiredBuffer(data);
|
|
1055
|
+
const salt = buffer.slice(0, 32);
|
|
1056
|
+
const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
|
|
1057
|
+
const iv = buffer.slice(32, 48);
|
|
1058
|
+
const payload = buffer.slice(48, 80);
|
|
1059
|
+
return aesDecryptCTR(payload, secretKey, iv);
|
|
1060
|
+
}
|
|
1061
|
+
function toRequiredBuffer(data) {
|
|
1062
|
+
if (data === undefined) {
|
|
1063
|
+
throw new Boom('Invalid buffer', {
|
|
1064
|
+
statusCode: 400
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
return data instanceof Buffer ? data : Buffer.from(data);
|
|
1068
|
+
}
|
|
1069
|
+
const willSendMessageAgain = async (id, participant) => {
|
|
1070
|
+
const key = `${id}:${participant}`;
|
|
1071
|
+
const retryCount = (await msgRetryCache.get(key)) || 0;
|
|
1072
|
+
return retryCount < maxMsgRetryCount;
|
|
1073
|
+
};
|
|
1074
|
+
const updateSendMessageAgainCount = async (id, participant) => {
|
|
1075
|
+
const key = `${id}:${participant}`;
|
|
1076
|
+
const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
|
|
1077
|
+
await msgRetryCache.set(key, newValue);
|
|
1078
|
+
};
|
|
1079
|
+
const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
|
|
1080
|
+
const remoteJid = key.remoteJid;
|
|
1081
|
+
const participant = key.participant || remoteJid;
|
|
1082
|
+
const retryCount = +retryNode.attrs.count || 1;
|
|
1083
|
+
const msgId = ids[0];
|
|
1084
|
+
const msgs = [];
|
|
1085
|
+
for (const id of ids) {
|
|
1086
|
+
let msg;
|
|
1087
|
+
if (messageRetryManager) {
|
|
1088
|
+
const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
|
|
1089
|
+
if (cachedMsg) {
|
|
1090
|
+
msg = cachedMsg.message;
|
|
1091
|
+
logger.debug({
|
|
1092
|
+
jid: remoteJid,
|
|
1093
|
+
id
|
|
1094
|
+
}, 'found message in retry cache');
|
|
1095
|
+
messageRetryManager.markRetrySuccess(id);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
if (!msg) {
|
|
1099
|
+
msg = await getMessage({
|
|
1100
|
+
...key,
|
|
1101
|
+
id
|
|
1014
1102
|
});
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1103
|
+
if (msg) {
|
|
1104
|
+
logger.debug({
|
|
1105
|
+
jid: remoteJid,
|
|
1106
|
+
id
|
|
1107
|
+
}, 'found message via getMessage');
|
|
1108
|
+
if (messageRetryManager) {
|
|
1109
|
+
messageRetryManager.markRetrySuccess(id);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
msgs.push(msg);
|
|
1023
1114
|
}
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1115
|
+
const sendToAll = !jidDecode(participant)?.device;
|
|
1116
|
+
const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
|
|
1117
|
+
let injectedFromBundle = false;
|
|
1118
|
+
const bundle = extractE2ESessionFromRetryReceipt(receiptNode);
|
|
1119
|
+
if (bundle) {
|
|
1120
|
+
try {
|
|
1121
|
+
await signalRepository.injectE2ESession({
|
|
1122
|
+
jid: participant,
|
|
1123
|
+
session: bundle
|
|
1124
|
+
});
|
|
1125
|
+
injectedFromBundle = true;
|
|
1126
|
+
logger.debug({
|
|
1127
|
+
participant,
|
|
1128
|
+
retryCount
|
|
1129
|
+
}, 'injected session from retry receipt key bundle');
|
|
1130
|
+
} catch (error) {
|
|
1131
|
+
logger.warn({
|
|
1132
|
+
error,
|
|
1133
|
+
participant
|
|
1134
|
+
}, 'failed to inject session from retry receipt');
|
|
1135
|
+
}
|
|
1029
1136
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
const retryCount = +retryNode.attrs.count || 1;
|
|
1044
|
-
const msgId = ids[0];
|
|
1045
|
-
// Try to get messages from cache first, then fallback to getMessage
|
|
1046
|
-
const msgs = [];
|
|
1047
|
-
for (const id of ids) {
|
|
1048
|
-
let msg;
|
|
1049
|
-
// Try to get from retry cache first if enabled
|
|
1050
|
-
if (messageRetryManager) {
|
|
1051
|
-
const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
|
|
1052
|
-
if (cachedMsg) {
|
|
1053
|
-
msg = cachedMsg.message;
|
|
1054
|
-
logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
|
|
1055
|
-
// Mark retry as successful since we found the message
|
|
1056
|
-
messageRetryManager.markRetrySuccess(id);
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
// Fallback to getMessage if not found in cache
|
|
1060
|
-
if (!msg) {
|
|
1061
|
-
msg = await getMessage({ ...key, id });
|
|
1062
|
-
if (msg) {
|
|
1063
|
-
logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
|
|
1064
|
-
// Also mark as successful if found via getMessage
|
|
1065
|
-
if (messageRetryManager) {
|
|
1066
|
-
messageRetryManager.markRetrySuccess(id);
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
msgs.push(msg);
|
|
1071
|
-
}
|
|
1072
|
-
// if it's the primary jid sending the request
|
|
1073
|
-
// just re-send the message to everyone
|
|
1074
|
-
// prevents the first message decryption failure
|
|
1075
|
-
const sendToAll = !jidDecode(participant)?.device;
|
|
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');
|
|
1137
|
+
if (!injectedFromBundle) {
|
|
1138
|
+
const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4);
|
|
1139
|
+
if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
|
|
1140
|
+
const info = await signalRepository.getSessionInfo(participant);
|
|
1141
|
+
if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
|
|
1142
|
+
logger.info({
|
|
1143
|
+
participant,
|
|
1144
|
+
stored: info.registrationId,
|
|
1145
|
+
received: receivedRegId
|
|
1146
|
+
}, 'reg id mismatch on retry without bundle, deleting session');
|
|
1147
|
+
await authState.keys.set({
|
|
1148
|
+
session: {
|
|
1149
|
+
[sessionId]: null
|
|
1087
1150
|
}
|
|
1151
|
+
});
|
|
1088
1152
|
}
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
}
|
|
1111
|
-
messageRetryManager.deleteBaseKey(sessionId, msgId);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
const BASE_KEY_CHECK_RETRY = 2;
|
|
1156
|
+
if (msgId && messageRetryManager) {
|
|
1157
|
+
const info = await signalRepository.getSessionInfo(participant);
|
|
1158
|
+
if (info) {
|
|
1159
|
+
if (retryCount === BASE_KEY_CHECK_RETRY) {
|
|
1160
|
+
messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
|
|
1161
|
+
} else if (retryCount > BASE_KEY_CHECK_RETRY) {
|
|
1162
|
+
if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
|
|
1163
|
+
logger.warn({
|
|
1164
|
+
participant,
|
|
1165
|
+
retryCount
|
|
1166
|
+
}, 'base key collision on retry, forcing fresh session');
|
|
1167
|
+
await authState.keys.set({
|
|
1168
|
+
session: {
|
|
1169
|
+
[sessionId]: null
|
|
1170
|
+
}
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
messageRetryManager.deleteBaseKey(sessionId, msgId);
|
|
1114
1174
|
}
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
let shouldRecreateSession = false;
|
|
1178
|
+
let recreateReason = '';
|
|
1179
|
+
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
|
|
1180
|
+
try {
|
|
1181
|
+
const hasSession = await signalRepository.validateSession(participant);
|
|
1182
|
+
const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
|
|
1183
|
+
shouldRecreateSession = result.recreate;
|
|
1184
|
+
recreateReason = result.reason;
|
|
1185
|
+
if (shouldRecreateSession) {
|
|
1186
|
+
logger.debug({
|
|
1187
|
+
participant,
|
|
1188
|
+
retryCount,
|
|
1189
|
+
reason: recreateReason
|
|
1190
|
+
}, 'recreating session for outgoing retry');
|
|
1191
|
+
await authState.keys.set({
|
|
1192
|
+
session: {
|
|
1193
|
+
[sessionId]: null
|
|
1130
1194
|
}
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
} catch (error) {
|
|
1198
|
+
logger.warn({
|
|
1199
|
+
error,
|
|
1200
|
+
participant
|
|
1201
|
+
}, 'failed to check session recreation for outgoing retry');
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
if (!injectedFromBundle) {
|
|
1205
|
+
await assertSessions([participant], true);
|
|
1206
|
+
}
|
|
1207
|
+
if (isJidGroup(remoteJid)) {
|
|
1208
|
+
await authState.keys.set({
|
|
1209
|
+
'sender-key-memory': {
|
|
1210
|
+
[remoteJid]: null
|
|
1131
1211
|
}
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
logger.debug({
|
|
1215
|
+
participant,
|
|
1216
|
+
sendToAll,
|
|
1217
|
+
shouldRecreateSession,
|
|
1218
|
+
recreateReason,
|
|
1219
|
+
injectedFromBundle
|
|
1220
|
+
}, 'prepared session for retry resend');
|
|
1221
|
+
for (const [i, msg] of msgs.entries()) {
|
|
1222
|
+
if (!ids[i]) continue;
|
|
1223
|
+
if (msg && (await willSendMessageAgain(ids[i], participant))) {
|
|
1224
|
+
await updateSendMessageAgainCount(ids[i], participant);
|
|
1225
|
+
const msgRelayOpts = {
|
|
1226
|
+
messageId: ids[i]
|
|
1227
|
+
};
|
|
1228
|
+
if (sendToAll) {
|
|
1229
|
+
msgRelayOpts.useUserDevicesCache = false;
|
|
1230
|
+
} else {
|
|
1231
|
+
msgRelayOpts.participants = {
|
|
1232
|
+
jid: participant,
|
|
1233
|
+
count: +retryNode.attrs.count
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
await relayMessage(key.remoteJid, msg, msgRelayOpts);
|
|
1237
|
+
} else {
|
|
1238
|
+
logger.debug({
|
|
1239
|
+
jid: key.remoteJid,
|
|
1240
|
+
id: ids[i]
|
|
1241
|
+
}, 'recv retry request, but message not available');
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
const handleReceipt = async node => {
|
|
1246
|
+
const {
|
|
1247
|
+
attrs,
|
|
1248
|
+
content
|
|
1249
|
+
} = node;
|
|
1250
|
+
const isLid = attrs.from.includes('lid');
|
|
1251
|
+
const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
|
|
1252
|
+
const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
|
|
1253
|
+
const fromMe = !attrs.recipient || (attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe;
|
|
1254
|
+
const key = {
|
|
1255
|
+
remoteJid,
|
|
1256
|
+
id: '',
|
|
1257
|
+
fromMe,
|
|
1258
|
+
participant: attrs.participant
|
|
1259
|
+
};
|
|
1260
|
+
const ids = [attrs.id];
|
|
1261
|
+
if (Array.isArray(content)) {
|
|
1262
|
+
const items = getBinaryNodeChildren(content[0], 'item');
|
|
1263
|
+
ids.push(...items.map(i => i.attrs.id));
|
|
1264
|
+
}
|
|
1265
|
+
try {
|
|
1266
|
+
await Promise.all([receiptMutex.mutex(async () => {
|
|
1267
|
+
const status = getStatusFromReceiptType(attrs.type);
|
|
1268
|
+
if (typeof status !== 'undefined' && (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
|
|
1269
|
+
if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
|
|
1270
|
+
if (attrs.participant) {
|
|
1271
|
+
const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
|
|
1272
|
+
ev.emit('message-receipt.update', ids.map(id => ({
|
|
1273
|
+
key: {
|
|
1274
|
+
...key,
|
|
1275
|
+
id
|
|
1276
|
+
},
|
|
1277
|
+
receipt: {
|
|
1278
|
+
userJid: jidNormalizedUser(attrs.participant),
|
|
1279
|
+
[updateKey]: +attrs.t
|
|
1153
1280
|
}
|
|
1154
|
-
|
|
1281
|
+
})));
|
|
1155
1282
|
}
|
|
1156
|
-
|
|
1157
|
-
|
|
1283
|
+
} else {
|
|
1284
|
+
ev.emit('messages.update', ids.map(id => ({
|
|
1285
|
+
key: {
|
|
1286
|
+
...key,
|
|
1287
|
+
id
|
|
1288
|
+
},
|
|
1289
|
+
update: {
|
|
1290
|
+
status,
|
|
1291
|
+
messageTimestamp: toNumber(+(attrs.t ?? 0))
|
|
1292
|
+
}
|
|
1293
|
+
})));
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
if (attrs.type === 'retry') {
|
|
1297
|
+
key.participant = key.participant || attrs.from;
|
|
1298
|
+
const retryNode = getBinaryNodeChild(node, 'retry');
|
|
1299
|
+
if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
|
|
1300
|
+
if (key.fromMe) {
|
|
1301
|
+
try {
|
|
1302
|
+
await updateSendMessageAgainCount(ids[0], key.participant);
|
|
1303
|
+
logger.debug({
|
|
1304
|
+
attrs,
|
|
1305
|
+
key
|
|
1306
|
+
}, 'recv retry request');
|
|
1307
|
+
await sendMessagesAgain(key, ids, retryNode, node);
|
|
1308
|
+
} catch (error) {
|
|
1309
|
+
logger.error({
|
|
1310
|
+
key,
|
|
1311
|
+
ids,
|
|
1312
|
+
trace: error instanceof Error ? error.stack : 'Unknown error'
|
|
1313
|
+
}, 'error in sending message again');
|
|
1314
|
+
}
|
|
1315
|
+
} else {
|
|
1316
|
+
logger.info({
|
|
1317
|
+
attrs,
|
|
1318
|
+
key
|
|
1319
|
+
}, 'recv retry for not fromMe message');
|
|
1158
1320
|
}
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1321
|
+
} else {
|
|
1322
|
+
logger.info({
|
|
1323
|
+
attrs,
|
|
1324
|
+
key
|
|
1325
|
+
}, 'will not send message again, as sent too many times');
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
})]);
|
|
1329
|
+
} finally {
|
|
1330
|
+
await sendMessageAck(node).catch(ackErr => logger.error({
|
|
1331
|
+
ackErr
|
|
1332
|
+
}, 'failed to ack receipt'));
|
|
1333
|
+
}
|
|
1334
|
+
};
|
|
1335
|
+
const handleNotification = async node => {
|
|
1336
|
+
const remoteJid = node.attrs.from;
|
|
1337
|
+
try {
|
|
1338
|
+
await Promise.all([notificationMutex.mutex(async () => {
|
|
1339
|
+
const msg = await processNotification(node);
|
|
1340
|
+
if (msg) {
|
|
1341
|
+
const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
|
|
1342
|
+
const {
|
|
1343
|
+
senderAlt: participantAlt,
|
|
1344
|
+
addressingMode
|
|
1345
|
+
} = extractAddressingContext(node);
|
|
1346
|
+
msg.key = {
|
|
1168
1347
|
remoteJid,
|
|
1169
|
-
id: '',
|
|
1170
1348
|
fromMe,
|
|
1171
|
-
participant: attrs.participant
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
notificationMutex.mutex(async () => {
|
|
1240
|
-
const msg = await processNotification(node);
|
|
1241
|
-
if (msg) {
|
|
1242
|
-
const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
|
|
1243
|
-
const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
|
|
1244
|
-
msg.key = {
|
|
1245
|
-
remoteJid,
|
|
1246
|
-
fromMe,
|
|
1247
|
-
participant: node.attrs.participant,
|
|
1248
|
-
participantAlt,
|
|
1249
|
-
participantUsername: node.attrs.participant_username,
|
|
1250
|
-
addressingMode,
|
|
1251
|
-
id: node.attrs.id,
|
|
1252
|
-
...(msg.key || {})
|
|
1253
|
-
};
|
|
1254
|
-
msg.participant ?? (msg.participant = node.attrs.participant);
|
|
1255
|
-
msg.messageTimestamp = +node.attrs.t;
|
|
1256
|
-
const fullMsg = proto.WebMessageInfo.fromObject(msg);
|
|
1257
|
-
await upsertMessage(fullMsg, 'append');
|
|
1258
|
-
}
|
|
1259
|
-
})
|
|
1260
|
-
]);
|
|
1261
|
-
}
|
|
1262
|
-
finally {
|
|
1263
|
-
await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
|
|
1264
|
-
}
|
|
1265
|
-
};
|
|
1266
|
-
const handleMessage = async (node) => {
|
|
1267
|
-
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1268
|
-
// TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
|
|
1269
|
-
if (encNode?.attrs.type === 'msmsg') {
|
|
1270
|
-
logger.debug({ key: node.attrs.key }, 'ignored msmsg');
|
|
1271
|
-
await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
|
|
1272
|
-
return;
|
|
1273
|
-
}
|
|
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);
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
await messageMutex.mutex(async () => {
|
|
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
|
-
}
|
|
1298
|
-
// message failed to decrypt
|
|
1299
|
-
if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
|
|
1300
|
-
if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
|
|
1301
|
-
acked = true;
|
|
1302
|
-
return sendMessageAck(node, NACK_REASONS.ParsingError);
|
|
1303
|
-
}
|
|
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
|
-
]);
|
|
1351
|
-
}
|
|
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);
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
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 () => {
|
|
1373
|
-
try {
|
|
1374
|
-
if (!ws.isOpen) {
|
|
1375
|
-
logger.debug({ node }, 'Connection closed, skipping retry');
|
|
1376
|
-
return;
|
|
1377
|
-
}
|
|
1378
|
-
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1379
|
-
await sendRetryRequest(node, !encNode);
|
|
1380
|
-
if (retryRequestDelayMs) {
|
|
1381
|
-
await delay(retryRequestDelayMs);
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
catch (err) {
|
|
1385
|
-
logger.error({ err }, 'Failed to send retry');
|
|
1386
|
-
}
|
|
1387
|
-
acked = true;
|
|
1388
|
-
await sendMessageAck(node, NACK_REASONS.UnhandledError);
|
|
1389
|
-
});
|
|
1390
|
-
}
|
|
1391
|
-
}
|
|
1392
|
-
else {
|
|
1393
|
-
if (messageRetryManager && msg.key.id) {
|
|
1394
|
-
messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
|
|
1395
|
-
}
|
|
1396
|
-
const isNewsletter = isJidNewsletter(msg.key.remoteJid);
|
|
1397
|
-
if (!isNewsletter) {
|
|
1398
|
-
// no type in the receipt => message delivered
|
|
1399
|
-
let type = undefined;
|
|
1400
|
-
let participant = msg.key.participant;
|
|
1401
|
-
if (category === 'peer') {
|
|
1402
|
-
// special peer message
|
|
1403
|
-
type = 'peer_msg';
|
|
1404
|
-
}
|
|
1405
|
-
else if (msg.key.fromMe) {
|
|
1406
|
-
// message was sent by us from a different device
|
|
1407
|
-
type = 'sender';
|
|
1408
|
-
// need to specially handle this case
|
|
1409
|
-
if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
|
|
1410
|
-
participant = author; // TODO: investigate sending receipts to LIDs and not PNs
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
else if (!sendActiveReceipts) {
|
|
1414
|
-
type = 'inactive';
|
|
1415
|
-
}
|
|
1416
|
-
acked = true;
|
|
1417
|
-
await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
|
|
1418
|
-
// send ack for history message
|
|
1419
|
-
const isAnyHistoryMsg = getHistoryMsg(msg.message);
|
|
1420
|
-
if (isAnyHistoryMsg) {
|
|
1421
|
-
const jid = jidNormalizedUser(msg.key.remoteJid);
|
|
1422
|
-
await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
|
|
1423
|
-
}
|
|
1424
|
-
}
|
|
1425
|
-
else {
|
|
1426
|
-
acked = true;
|
|
1427
|
-
await sendMessageAck(node);
|
|
1428
|
-
logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
|
|
1432
|
-
await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
|
|
1433
|
-
});
|
|
1434
|
-
}
|
|
1435
|
-
catch (error) {
|
|
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'));
|
|
1349
|
+
participant: node.attrs.participant,
|
|
1350
|
+
participantAlt,
|
|
1351
|
+
participantUsername: node.attrs.participant_username,
|
|
1352
|
+
addressingMode,
|
|
1353
|
+
id: node.attrs.id,
|
|
1354
|
+
...(msg.key || {})
|
|
1355
|
+
};
|
|
1356
|
+
msg.participant ?? (msg.participant = node.attrs.participant);
|
|
1357
|
+
msg.messageTimestamp = +node.attrs.t;
|
|
1358
|
+
const fullMsg = proto.WebMessageInfo.fromObject(msg);
|
|
1359
|
+
await upsertMessage(fullMsg, 'append');
|
|
1360
|
+
}
|
|
1361
|
+
})]);
|
|
1362
|
+
} finally {
|
|
1363
|
+
await sendMessageAck(node).catch(ackErr => logger.error({
|
|
1364
|
+
ackErr
|
|
1365
|
+
}, 'failed to ack notification'));
|
|
1366
|
+
}
|
|
1367
|
+
};
|
|
1368
|
+
const handleMessage = async node => {
|
|
1369
|
+
let acked = false;
|
|
1370
|
+
try {
|
|
1371
|
+
const {
|
|
1372
|
+
fullMessage: msg,
|
|
1373
|
+
category,
|
|
1374
|
+
author,
|
|
1375
|
+
decrypt
|
|
1376
|
+
} = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
|
|
1377
|
+
const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
|
|
1378
|
+
if (!!alt) {
|
|
1379
|
+
const altServer = jidDecode(alt)?.server;
|
|
1380
|
+
const primaryJid = msg.key.participant || msg.key.remoteJid;
|
|
1381
|
+
if (altServer === 'lid') {
|
|
1382
|
+
if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
|
|
1383
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{
|
|
1384
|
+
lid: alt,
|
|
1385
|
+
pn: primaryJid
|
|
1386
|
+
}]);
|
|
1387
|
+
await signalRepository.migrateSession(primaryJid, alt);
|
|
1388
|
+
}
|
|
1389
|
+
} else {
|
|
1390
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{
|
|
1391
|
+
lid: primaryJid,
|
|
1392
|
+
pn: alt
|
|
1393
|
+
}]);
|
|
1394
|
+
await signalRepository.migrateSession(alt, primaryJid);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
await messageMutex.mutex(async () => {
|
|
1398
|
+
await decrypt();
|
|
1399
|
+
if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
|
|
1400
|
+
messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
|
|
1401
|
+
}
|
|
1402
|
+
if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
|
|
1403
|
+
if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
|
|
1404
|
+
acked = true;
|
|
1405
|
+
return sendMessageAck(node, NACK_REASONS.ParsingError);
|
|
1406
|
+
}
|
|
1407
|
+
if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
|
|
1408
|
+
const unavailableNode = getBinaryNodeChild(node, 'unavailable');
|
|
1409
|
+
const unavailableType = unavailableNode?.attrs?.type;
|
|
1410
|
+
if (unavailableType === 'bot_unavailable_fanout' || unavailableType === 'hosted_unavailable_fanout' || unavailableType === 'view_once_unavailable_fanout') {
|
|
1411
|
+
logger.debug({
|
|
1412
|
+
msgId: msg.key.id,
|
|
1413
|
+
unavailableType
|
|
1414
|
+
}, 'skipping placeholder resend for excluded unavailable type');
|
|
1415
|
+
acked = true;
|
|
1416
|
+
return sendMessageAck(node);
|
|
1439
1417
|
}
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1418
|
+
const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
|
|
1419
|
+
if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
|
|
1420
|
+
logger.debug({
|
|
1421
|
+
msgId: msg.key.id,
|
|
1422
|
+
messageAge
|
|
1423
|
+
}, 'skipping placeholder resend for old message');
|
|
1424
|
+
acked = true;
|
|
1425
|
+
return sendMessageAck(node);
|
|
1448
1426
|
}
|
|
1449
|
-
const
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
from,
|
|
1455
|
-
callerPn: infoChild.attrs['caller_pn'],
|
|
1456
|
-
id: callId,
|
|
1457
|
-
date: new Date(+attrs.t * 1000),
|
|
1458
|
-
offline: !!attrs.offline,
|
|
1459
|
-
status
|
|
1427
|
+
const cleanKey = {
|
|
1428
|
+
remoteJid: msg.key.remoteJid,
|
|
1429
|
+
fromMe: msg.key.fromMe,
|
|
1430
|
+
id: msg.key.id,
|
|
1431
|
+
participant: msg.key.participant
|
|
1460
1432
|
};
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
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
|
-
}
|
|
1493
|
-
};
|
|
1494
|
-
const handleBadAck = async ({ attrs }) => {
|
|
1495
|
-
const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
|
|
1496
|
-
// WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
|
|
1497
|
-
// // current hypothesis is that if pash is sent in the ack
|
|
1498
|
-
// // it means -- the message hasn't reached all devices yet
|
|
1499
|
-
// // we'll retry sending the message here
|
|
1500
|
-
// if(attrs.phash) {
|
|
1501
|
-
// logger.info({ attrs }, 'received phash in ack, resending message...')
|
|
1502
|
-
// const msg = await getMessage(key)
|
|
1503
|
-
// if(msg) {
|
|
1504
|
-
// await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
|
|
1505
|
-
// } else {
|
|
1506
|
-
// logger.warn({ attrs }, 'could not send message again, as it was not found')
|
|
1507
|
-
// }
|
|
1508
|
-
// }
|
|
1509
|
-
// error in acknowledgement,
|
|
1510
|
-
// device could not display the message
|
|
1511
|
-
if (attrs.error) {
|
|
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
|
-
}
|
|
1558
|
-
ev.emit('messages.update', [
|
|
1559
|
-
{
|
|
1560
|
-
key,
|
|
1561
|
-
update: {
|
|
1562
|
-
status: WAMessageStatus.ERROR,
|
|
1563
|
-
messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
]);
|
|
1567
|
-
}
|
|
1568
|
-
};
|
|
1569
|
-
/// processes a node with the given function
|
|
1570
|
-
/// and adds the task to the existing buffer if we're buffering events
|
|
1571
|
-
const processNodeWithBuffer = async (node, identifier, exec) => {
|
|
1572
|
-
ev.buffer();
|
|
1573
|
-
await execTask();
|
|
1574
|
-
ev.flush();
|
|
1575
|
-
function execTask() {
|
|
1576
|
-
return exec(node, false).catch(err => onUnexpectedError(err, identifier));
|
|
1577
|
-
}
|
|
1578
|
-
};
|
|
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
|
-
});
|
|
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
|
-
}
|
|
1603
|
-
const isOffline = !!node.attrs.offline;
|
|
1604
|
-
if (isOffline) {
|
|
1605
|
-
offlineNodeProcessor.enqueue(type, node);
|
|
1606
|
-
}
|
|
1607
|
-
else {
|
|
1608
|
-
await processNodeWithBuffer(node, identifier, exec);
|
|
1609
|
-
}
|
|
1610
|
-
};
|
|
1611
|
-
// recv a message
|
|
1612
|
-
ws.on('CB:message', async (node) => {
|
|
1613
|
-
await processNode('message', node, 'processing message', handleMessage);
|
|
1614
|
-
});
|
|
1615
|
-
ws.on('CB:call', async (node) => {
|
|
1616
|
-
await processNode('call', node, 'handling call', handleCall);
|
|
1617
|
-
});
|
|
1618
|
-
ws.on('CB:receipt', async (node) => {
|
|
1619
|
-
await processNode('receipt', node, 'handling receipt', handleReceipt);
|
|
1620
|
-
});
|
|
1621
|
-
ws.on('CB:notification', async (node) => {
|
|
1622
|
-
await processNode('notification', node, 'handling notification', handleNotification);
|
|
1623
|
-
});
|
|
1624
|
-
ws.on('CB:ack,class:message', (node) => {
|
|
1625
|
-
handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
|
|
1626
|
-
});
|
|
1627
|
-
ev.on('call', async ([call]) => {
|
|
1628
|
-
if (!call) {
|
|
1629
|
-
return;
|
|
1630
|
-
}
|
|
1631
|
-
// missed call + group call notification message generation
|
|
1632
|
-
if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
|
|
1633
|
-
const msg = {
|
|
1634
|
-
key: {
|
|
1635
|
-
remoteJid: call.chatId,
|
|
1636
|
-
id: call.id,
|
|
1637
|
-
fromMe: false
|
|
1638
|
-
},
|
|
1639
|
-
messageTimestamp: unixTimestampSeconds(call.date)
|
|
1433
|
+
const msgData = {
|
|
1434
|
+
key: msg.key,
|
|
1435
|
+
messageTimestamp: msg.messageTimestamp,
|
|
1436
|
+
pushName: msg.pushName,
|
|
1437
|
+
participant: msg.participant,
|
|
1438
|
+
verifiedBizName: msg.verifiedBizName
|
|
1640
1439
|
};
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1440
|
+
requestPlaceholderResend(cleanKey, msgData).then(requestId => {
|
|
1441
|
+
if (requestId && requestId !== 'RESOLVED') {
|
|
1442
|
+
logger.debug({
|
|
1443
|
+
msgId: msg.key.id,
|
|
1444
|
+
requestId
|
|
1445
|
+
}, 'requested placeholder resend for unavailable message');
|
|
1446
|
+
ev.emit('messages.update', [{
|
|
1447
|
+
key: msg.key,
|
|
1448
|
+
update: {
|
|
1449
|
+
messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId]
|
|
1450
|
+
}
|
|
1451
|
+
}]);
|
|
1452
|
+
}
|
|
1453
|
+
}).catch(err => {
|
|
1454
|
+
logger.warn({
|
|
1455
|
+
err,
|
|
1456
|
+
msgId: msg.key.id
|
|
1457
|
+
}, 'failed to request placeholder resend for unavailable message');
|
|
1458
|
+
});
|
|
1459
|
+
acked = true;
|
|
1460
|
+
await sendMessageAck(node);
|
|
1461
|
+
} else {
|
|
1462
|
+
if (isJidStatusBroadcast(msg.key.remoteJid)) {
|
|
1463
|
+
const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
|
|
1464
|
+
if (messageAge > STATUS_EXPIRY_SECONDS) {
|
|
1465
|
+
logger.debug({
|
|
1466
|
+
msgId: msg.key.id,
|
|
1467
|
+
messageAge,
|
|
1468
|
+
remoteJid: msg.key.remoteJid
|
|
1469
|
+
}, 'skipping retry for expired status message');
|
|
1470
|
+
acked = true;
|
|
1471
|
+
return sendMessageAck(node);
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
logger.debug('[handleMessage] Attempting retry request for failed decryption');
|
|
1475
|
+
await retryMutex.mutex(async () => {
|
|
1476
|
+
try {
|
|
1477
|
+
if (!ws.isOpen) {
|
|
1478
|
+
logger.debug({
|
|
1479
|
+
node
|
|
1480
|
+
}, 'Connection closed, skipping retry');
|
|
1481
|
+
return;
|
|
1646
1482
|
}
|
|
1647
|
-
|
|
1648
|
-
|
|
1483
|
+
const encNode = getBinaryNodeChild(node, 'enc');
|
|
1484
|
+
await sendRetryRequest(node, !encNode);
|
|
1485
|
+
if (retryRequestDelayMs) {
|
|
1486
|
+
await delay(retryRequestDelayMs);
|
|
1649
1487
|
}
|
|
1488
|
+
} catch (err) {
|
|
1489
|
+
logger.error({
|
|
1490
|
+
err
|
|
1491
|
+
}, 'Failed to send retry');
|
|
1492
|
+
}
|
|
1493
|
+
acked = true;
|
|
1494
|
+
await sendMessageAck(node, NACK_REASONS.UnhandledError);
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
} else {
|
|
1498
|
+
if (messageRetryManager && msg.key.id) {
|
|
1499
|
+
messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
|
|
1500
|
+
}
|
|
1501
|
+
const isNewsletter = isJidNewsletter(msg.key.remoteJid);
|
|
1502
|
+
if (!isNewsletter) {
|
|
1503
|
+
let type = undefined;
|
|
1504
|
+
let participant = msg.key.participant;
|
|
1505
|
+
if (category === 'peer') {
|
|
1506
|
+
type = 'peer_msg';
|
|
1507
|
+
} else if (msg.key.fromMe) {
|
|
1508
|
+
type = 'sender';
|
|
1509
|
+
if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
|
|
1510
|
+
participant = author;
|
|
1511
|
+
}
|
|
1512
|
+
} else if (!sendActiveReceipts) {
|
|
1513
|
+
type = 'inactive';
|
|
1650
1514
|
}
|
|
1651
|
-
|
|
1652
|
-
|
|
1515
|
+
acked = true;
|
|
1516
|
+
await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
|
|
1517
|
+
const isAnyHistoryMsg = getHistoryMsg(msg.message);
|
|
1518
|
+
if (isAnyHistoryMsg) {
|
|
1519
|
+
const jid = jidNormalizedUser(msg.key.remoteJid);
|
|
1520
|
+
await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
|
|
1653
1521
|
}
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
if (
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1522
|
+
} else {
|
|
1523
|
+
acked = true;
|
|
1524
|
+
await sendMessageAck(node);
|
|
1525
|
+
logger.debug({
|
|
1526
|
+
key: msg.key
|
|
1527
|
+
}, 'processed newsletter message without receipts');
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
|
|
1531
|
+
if (!(ignoreOfflineMessages && node.attrs.offline)) {
|
|
1532
|
+
await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
|
|
1533
|
+
}
|
|
1534
|
+
});
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
logger.error({
|
|
1537
|
+
error,
|
|
1538
|
+
node: binaryNodeToString(node)
|
|
1539
|
+
}, 'error in handling message');
|
|
1540
|
+
if (!acked) {
|
|
1541
|
+
await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({
|
|
1542
|
+
ackErr
|
|
1543
|
+
}, 'failed to ack message after error'));
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
const handleCall = async node => {
|
|
1548
|
+
try {
|
|
1549
|
+
const {
|
|
1550
|
+
attrs
|
|
1551
|
+
} = node;
|
|
1552
|
+
const [infoChild] = getAllBinaryNodeChildren(node);
|
|
1553
|
+
if (!infoChild) {
|
|
1554
|
+
throw new Boom('Missing call info in call node');
|
|
1555
|
+
}
|
|
1556
|
+
const status = getCallStatusFromNode(infoChild);
|
|
1557
|
+
const callId = infoChild.attrs['call-id'];
|
|
1558
|
+
const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
|
|
1559
|
+
const call = {
|
|
1560
|
+
chatId: attrs.from,
|
|
1561
|
+
from,
|
|
1562
|
+
callerPn: infoChild.attrs['caller_pn'],
|
|
1563
|
+
id: callId,
|
|
1564
|
+
date: new Date(+attrs.t * 1000),
|
|
1565
|
+
offline: !!attrs.offline,
|
|
1566
|
+
status
|
|
1567
|
+
};
|
|
1568
|
+
if (status === 'relaylatency') {
|
|
1569
|
+
const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
|
|
1570
|
+
const latencyMs = latencyValue ? Number(latencyValue) : undefined;
|
|
1571
|
+
if (Number.isFinite(latencyMs)) {
|
|
1572
|
+
call.latencyMs = latencyMs;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
if (status === 'offer') {
|
|
1576
|
+
call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
|
|
1577
|
+
call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
|
|
1578
|
+
call.groupJid = infoChild.attrs['group-jid'];
|
|
1579
|
+
await callOfferCache.set(call.id, call);
|
|
1580
|
+
}
|
|
1581
|
+
const existingCall = await callOfferCache.get(call.id);
|
|
1582
|
+
if (existingCall) {
|
|
1583
|
+
call.isVideo = existingCall.isVideo;
|
|
1584
|
+
call.isGroup = existingCall.isGroup;
|
|
1585
|
+
call.callerPn = call.callerPn || existingCall.callerPn;
|
|
1586
|
+
}
|
|
1587
|
+
if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
|
|
1588
|
+
await callOfferCache.del(call.id);
|
|
1589
|
+
}
|
|
1590
|
+
ev.emit('call', [call]);
|
|
1591
|
+
} catch (error) {
|
|
1592
|
+
logger.error({
|
|
1593
|
+
error,
|
|
1594
|
+
node: binaryNodeToString(node)
|
|
1595
|
+
}, 'error in handling call');
|
|
1596
|
+
} finally {
|
|
1597
|
+
await sendMessageAck(node).catch(ackErr => logger.error({
|
|
1598
|
+
ackErr
|
|
1599
|
+
}, 'failed to ack call'));
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
const handleBadAck = async ({
|
|
1603
|
+
attrs
|
|
1604
|
+
}) => {
|
|
1605
|
+
const key = {
|
|
1606
|
+
remoteJid: attrs.from,
|
|
1607
|
+
fromMe: true,
|
|
1608
|
+
id: attrs.id
|
|
1609
|
+
};
|
|
1610
|
+
if (attrs.error) {
|
|
1611
|
+
if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
|
|
1612
|
+
logger.warn({
|
|
1613
|
+
msgId: attrs.id,
|
|
1614
|
+
from: attrs.from
|
|
1615
|
+
}, 'error 463: account restricted or missing tctoken for contact');
|
|
1616
|
+
const ackFrom = attrs.from;
|
|
1617
|
+
if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
|
|
1618
|
+
inFlight463Recoveries.add(ackFrom);
|
|
1619
|
+
void (async () => {
|
|
1672
1620
|
try {
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
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
|
-
}
|
|
1621
|
+
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
|
|
1622
|
+
const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN);
|
|
1623
|
+
const issueJid = await resolveIssuanceJid(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
|
|
1624
|
+
const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds());
|
|
1625
|
+
await storeTcTokensFromIqResult({
|
|
1626
|
+
result,
|
|
1627
|
+
fallbackJid: tcStorageJid,
|
|
1628
|
+
keys: authState.keys,
|
|
1629
|
+
getLIDForPN,
|
|
1630
|
+
onNewJidStored: trackTcTokenJid
|
|
1631
|
+
});
|
|
1632
|
+
logger.debug({
|
|
1633
|
+
from: ackFrom
|
|
1634
|
+
}, 'completed 463 token recovery issuance');
|
|
1635
|
+
} catch (err) {
|
|
1636
|
+
logger.debug({
|
|
1637
|
+
from: ackFrom,
|
|
1638
|
+
err: err?.message
|
|
1639
|
+
}, 'failed 463 token recovery issuance');
|
|
1640
|
+
} finally {
|
|
1641
|
+
inFlight463Recoveries.delete(ackFrom);
|
|
1742
1642
|
}
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
}
|
|
1643
|
+
})();
|
|
1644
|
+
}
|
|
1645
|
+
} else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
|
|
1646
|
+
logger.warn({
|
|
1647
|
+
msgId: attrs.id,
|
|
1648
|
+
from: attrs.from
|
|
1649
|
+
}, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
|
|
1650
|
+
} else {
|
|
1651
|
+
logger.warn({
|
|
1652
|
+
attrs
|
|
1653
|
+
}, 'received error in ack');
|
|
1654
|
+
}
|
|
1655
|
+
ev.emit('messages.update', [{
|
|
1656
|
+
key,
|
|
1657
|
+
update: {
|
|
1658
|
+
status: WAMessageStatus.ERROR,
|
|
1659
|
+
messageStubParameters: [attrs.error]
|
|
1660
|
+
}
|
|
1661
|
+
}]);
|
|
1761
1662
|
}
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1663
|
+
};
|
|
1664
|
+
const processNodeWithBuffer = async (node, identifier, exec) => {
|
|
1665
|
+
ev.buffer();
|
|
1666
|
+
await execTask();
|
|
1667
|
+
ev.flush();
|
|
1668
|
+
function execTask() {
|
|
1669
|
+
return exec(node, false).catch(err => onUnexpectedError(err, identifier));
|
|
1670
|
+
}
|
|
1671
|
+
};
|
|
1672
|
+
const processNode = async (type, node, identifier, exec) => {
|
|
1673
|
+
const from = node.attrs.from;
|
|
1674
|
+
let ignoreJid = from;
|
|
1675
|
+
if (type === 'receipt' && from) {
|
|
1676
|
+
const attrs = node.attrs;
|
|
1677
|
+
const isLid = attrs.from.includes('lid');
|
|
1678
|
+
const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
|
|
1679
|
+
ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
|
|
1680
|
+
}
|
|
1681
|
+
if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
|
|
1682
|
+
await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined);
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
await processNodeWithBuffer(node, identifier, exec);
|
|
1686
|
+
};
|
|
1687
|
+
ws.on('CB:message', async node => {
|
|
1688
|
+
await processNode('message', node, 'processing message', handleMessage);
|
|
1689
|
+
});
|
|
1690
|
+
ws.on('CB:call', async node => {
|
|
1691
|
+
await processNode('call', node, 'handling call', handleCall);
|
|
1692
|
+
});
|
|
1693
|
+
ws.on('CB:receipt', async node => {
|
|
1694
|
+
await processNode('receipt', node, 'handling receipt', handleReceipt);
|
|
1695
|
+
});
|
|
1696
|
+
ws.on('CB:notification', async node => {
|
|
1697
|
+
await processNode('notification', node, 'handling notification', handleNotification);
|
|
1698
|
+
});
|
|
1699
|
+
ws.on('CB:ack,class:message', node => {
|
|
1700
|
+
handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
|
|
1701
|
+
});
|
|
1702
|
+
ev.on('call', async ([call]) => {
|
|
1703
|
+
if (!call) {
|
|
1704
|
+
return;
|
|
1705
|
+
}
|
|
1706
|
+
if (call.status === 'timeout' || call.status === 'offer' && call.isGroup) {
|
|
1707
|
+
const msg = {
|
|
1708
|
+
key: {
|
|
1709
|
+
remoteJid: call.chatId,
|
|
1710
|
+
id: call.id,
|
|
1711
|
+
fromMe: false
|
|
1712
|
+
},
|
|
1713
|
+
messageTimestamp: unixTimestampSeconds(call.date)
|
|
1714
|
+
};
|
|
1715
|
+
if (call.status === 'timeout') {
|
|
1716
|
+
if (call.isGroup) {
|
|
1717
|
+
msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
|
|
1718
|
+
} else {
|
|
1719
|
+
msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
|
|
1720
|
+
}
|
|
1721
|
+
} else {
|
|
1722
|
+
msg.message = {
|
|
1723
|
+
call: {
|
|
1724
|
+
callKey: Buffer.from(call.id)
|
|
1725
|
+
}
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
const protoMsg = proto.WebMessageInfo.fromObject(msg);
|
|
1729
|
+
await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
|
|
1730
|
+
}
|
|
1731
|
+
});
|
|
1732
|
+
let lastTcTokenPruneTs = 0;
|
|
1733
|
+
const inFlight463Recoveries = new Set();
|
|
1734
|
+
ev.on('connection.update', ({
|
|
1735
|
+
isOnline,
|
|
1736
|
+
connection
|
|
1737
|
+
}) => {
|
|
1738
|
+
if (typeof isOnline !== 'undefined') {
|
|
1739
|
+
sendActiveReceipts = isOnline;
|
|
1740
|
+
logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
|
|
1741
|
+
}
|
|
1742
|
+
if (connection === 'close' && tcTokenIndexTimer) {
|
|
1743
|
+
clearTimeout(tcTokenIndexTimer);
|
|
1744
|
+
tcTokenIndexTimer = undefined;
|
|
1745
|
+
try {
|
|
1746
|
+
void Promise.resolve(flushTcTokenIndex()).catch(() => {});
|
|
1747
|
+
} catch {}
|
|
1748
|
+
}
|
|
1749
|
+
if (isOnline) {
|
|
1750
|
+
const now = Date.now();
|
|
1751
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1752
|
+
if (now - lastTcTokenPruneTs >= DAY_MS) {
|
|
1753
|
+
lastTcTokenPruneTs = now;
|
|
1754
|
+
void pruneExpiredTcTokens();
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
});
|
|
1758
|
+
registerSocketEndHandler(() => {
|
|
1759
|
+
if (!config.msgRetryCounterCache && msgRetryCache.close) {
|
|
1760
|
+
msgRetryCache.close();
|
|
1761
|
+
}
|
|
1762
|
+
if (!config.callOfferCache && callOfferCache.close) {
|
|
1763
|
+
callOfferCache.close();
|
|
1764
|
+
}
|
|
1765
|
+
sendActiveReceipts = false;
|
|
1766
|
+
});
|
|
1767
|
+
async function pruneExpiredTcTokens() {
|
|
1768
|
+
try {
|
|
1769
|
+
await tcTokenIndexLoaded;
|
|
1770
|
+
const persisted = await readTcTokenIndex(authState.keys);
|
|
1771
|
+
const allJids = new Set(tcTokenKnownJids);
|
|
1772
|
+
for (const jid of persisted) allJids.add(jid);
|
|
1773
|
+
if (!allJids.size) return;
|
|
1774
|
+
const jids = [...allJids];
|
|
1775
|
+
const allTokens = await authState.keys.get('tctoken', jids);
|
|
1776
|
+
const writes = {};
|
|
1777
|
+
const survivors = new Set();
|
|
1778
|
+
let mutated = 0;
|
|
1779
|
+
for (const jid of jids) {
|
|
1780
|
+
const entry = allTokens[jid];
|
|
1781
|
+
if (!entry) {
|
|
1782
|
+
mutated++;
|
|
1783
|
+
continue;
|
|
1784
|
+
}
|
|
1785
|
+
const hasPeerToken = !!entry.token?.length;
|
|
1786
|
+
const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp);
|
|
1787
|
+
const hasSenderTs = entry.senderTimestamp !== undefined;
|
|
1788
|
+
const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp);
|
|
1789
|
+
const keepPeerToken = hasPeerToken && !peerTokenExpired;
|
|
1790
|
+
const keepSenderTs = hasSenderTs && !senderTsExpired;
|
|
1791
|
+
if (!keepPeerToken && !keepSenderTs) {
|
|
1792
|
+
writes[jid] = null;
|
|
1793
|
+
mutated++;
|
|
1794
|
+
} else if (peerTokenExpired && keepSenderTs) {
|
|
1795
|
+
writes[jid] = {
|
|
1796
|
+
token: Buffer.alloc(0),
|
|
1797
|
+
senderTimestamp: entry.senderTimestamp
|
|
1798
|
+
};
|
|
1799
|
+
survivors.add(jid);
|
|
1800
|
+
mutated++;
|
|
1801
|
+
} else {
|
|
1802
|
+
survivors.add(jid);
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
if (mutated === 0) return;
|
|
1806
|
+
await authState.keys.set({
|
|
1807
|
+
tctoken: {
|
|
1808
|
+
...writes,
|
|
1809
|
+
[TC_TOKEN_INDEX_KEY]: {
|
|
1810
|
+
token: Buffer.from(JSON.stringify([...survivors]))
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
});
|
|
1814
|
+
tcTokenKnownJids.clear();
|
|
1815
|
+
for (const jid of survivors) tcTokenKnownJids.add(jid);
|
|
1816
|
+
logger.debug({
|
|
1817
|
+
mutated,
|
|
1818
|
+
remaining: survivors.size
|
|
1819
|
+
}, 'pruned expired tctokens');
|
|
1820
|
+
} catch (err) {
|
|
1821
|
+
logger.warn({
|
|
1822
|
+
err: err?.message
|
|
1823
|
+
}, 'failed to prune expired tctokens');
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
return {
|
|
1827
|
+
...sock,
|
|
1828
|
+
sendMessageAck,
|
|
1829
|
+
sendRetryRequest,
|
|
1830
|
+
rejectCall,
|
|
1831
|
+
fetchMessageHistory,
|
|
1832
|
+
requestPlaceholderResend,
|
|
1833
|
+
messageRetryManager
|
|
1834
|
+
};
|
|
1771
1835
|
};
|
|
1772
|
-
//# sourceMappingURL=messages-recv.js.map
|