@vinzsocket/baileys 3.0.0 → 3.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/WAProto/GenerateStatics.sh +2 -2
- package/WAProto/WAProto.proto +1339 -493
- package/WAProto/fix-imports.js +79 -14
- package/WAProto/index.d.ts +5274 -1945
- package/WAProto/index.js +97691 -1
- package/lib/Defaults/index.d.ts +25 -8
- package/lib/Defaults/index.d.ts.map +1 -1
- package/lib/Defaults/index.js +124 -109
- package/lib/Defaults/index.js.map +1 -1
- package/lib/Signal/Group/ciphertext-message.js +11 -15
- package/lib/Signal/Group/group-session-builder.js +27 -32
- package/lib/Signal/Group/group_cipher.d.ts +1 -2
- package/lib/Signal/Group/group_cipher.d.ts.map +1 -1
- package/lib/Signal/Group/group_cipher.js +75 -92
- package/lib/Signal/Group/group_cipher.js.map +1 -1
- package/lib/Signal/Group/index.js +12 -77
- package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
- package/lib/Signal/Group/keyhelper.js +16 -24
- package/lib/Signal/Group/keyhelper.js.map +1 -1
- package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
- package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -1
- package/lib/Signal/Group/sender-chain-key.js +24 -34
- package/lib/Signal/Group/sender-chain-key.js.map +1 -1
- package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -1
- package/lib/Signal/Group/sender-key-distribution-message.js +62 -58
- package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -1
- package/lib/Signal/Group/sender-key-message.d.ts.map +1 -1
- package/lib/Signal/Group/sender-key-message.js +64 -65
- package/lib/Signal/Group/sender-key-message.js.map +1 -1
- package/lib/Signal/Group/sender-key-name.js +41 -44
- package/lib/Signal/Group/sender-key-record.d.ts +1 -1
- package/lib/Signal/Group/sender-key-record.d.ts.map +1 -1
- package/lib/Signal/Group/sender-key-record.js +36 -47
- package/lib/Signal/Group/sender-key-record.js.map +1 -1
- package/lib/Signal/Group/sender-key-state.d.ts +4 -4
- package/lib/Signal/Group/sender-key-state.d.ts.map +1 -1
- package/lib/Signal/Group/sender-key-state.js +76 -93
- package/lib/Signal/Group/sender-key-state.js.map +1 -1
- package/lib/Signal/Group/sender-message-key.d.ts.map +1 -1
- package/lib/Signal/Group/sender-message-key.js +25 -31
- package/lib/Signal/Group/sender-message-key.js.map +1 -1
- package/lib/Signal/libsignal.d.ts +4 -7
- package/lib/Signal/libsignal.d.ts.map +1 -1
- package/lib/Signal/libsignal.js +417 -401
- package/lib/Signal/libsignal.js.map +1 -1
- package/lib/Signal/lid-mapping.d.ts +16 -23
- package/lib/Signal/lid-mapping.d.ts.map +1 -1
- package/lib/Signal/lid-mapping.js +273 -108
- package/lib/Signal/lid-mapping.js.map +1 -1
- package/lib/Socket/Client/index.js +3 -25
- package/lib/Socket/Client/types.d.ts +2 -2
- package/lib/Socket/Client/types.d.ts.map +1 -1
- package/lib/Socket/Client/types.js +10 -14
- package/lib/Socket/Client/websocket.d.ts +1 -1
- package/lib/Socket/Client/websocket.d.ts.map +1 -1
- package/lib/Socket/Client/websocket.js +53 -54
- package/lib/Socket/Client/websocket.js.map +1 -1
- package/lib/Socket/business.d.ts +45 -16
- package/lib/Socket/business.d.ts.map +1 -1
- package/lib/Socket/business.js +374 -360
- package/lib/Socket/business.js.map +1 -1
- package/lib/Socket/chats.d.ts +34 -8
- package/lib/Socket/chats.d.ts.map +1 -1
- package/lib/Socket/chats.js +1162 -1038
- package/lib/Socket/chats.js.map +1 -1
- package/lib/Socket/communities.d.ts +56 -16
- package/lib/Socket/communities.d.ts.map +1 -1
- package/lib/Socket/communities.js +418 -466
- package/lib/Socket/communities.js.map +1 -1
- package/lib/Socket/groups.d.ts +32 -8
- package/lib/Socket/groups.d.ts.map +1 -1
- package/lib/Socket/groups.js +337 -390
- package/lib/Socket/groups.js.map +1 -1
- package/lib/Socket/index.d.ts +56 -16
- package/lib/Socket/index.d.ts.map +1 -1
- package/lib/Socket/index.js +10 -18
- package/lib/Socket/index.js.map +1 -1
- package/lib/Socket/messages-recv.d.ts +49 -19
- package/lib/Socket/messages-recv.d.ts.map +1 -1
- package/lib/Socket/messages-recv.js +1738 -1391
- package/lib/Socket/messages-recv.js.map +1 -1
- package/lib/Socket/messages-send.d.ts +45 -15
- package/lib/Socket/messages-send.d.ts.map +1 -1
- package/lib/Socket/messages-send.js +1101 -1242
- package/lib/Socket/messages-send.js.map +1 -1
- package/lib/Socket/mex.js +38 -48
- package/lib/Socket/newsletter.d.ts +30 -7
- package/lib/Socket/newsletter.d.ts.map +1 -1
- package/lib/Socket/newsletter.js +175 -222
- package/lib/Socket/newsletter.js.map +1 -1
- package/lib/Socket/socket.d.ts +15 -6
- package/lib/Socket/socket.d.ts.map +1 -1
- package/lib/Socket/socket.js +932 -913
- package/lib/Socket/socket.js.map +1 -1
- package/lib/Types/Auth.d.ts +12 -0
- package/lib/Types/Auth.d.ts.map +1 -1
- package/lib/Types/Auth.js +2 -3
- package/lib/Types/Bussines.js +2 -3
- package/lib/Types/Call.d.ts +2 -1
- package/lib/Types/Call.d.ts.map +1 -1
- package/lib/Types/Call.js +2 -3
- package/lib/Types/Chat.d.ts +1 -0
- package/lib/Types/Chat.d.ts.map +1 -1
- package/lib/Types/Chat.js +8 -5
- package/lib/Types/Contact.d.ts +2 -0
- package/lib/Types/Contact.d.ts.map +1 -1
- package/lib/Types/Contact.js +2 -3
- package/lib/Types/Events.d.ts +66 -9
- package/lib/Types/Events.d.ts.map +1 -1
- package/lib/Types/Events.js +2 -1
- package/lib/Types/GroupMetadata.d.ts +5 -0
- package/lib/Types/GroupMetadata.d.ts.map +1 -1
- package/lib/Types/GroupMetadata.js +2 -3
- package/lib/Types/Label.js +23 -26
- package/lib/Types/LabelAssociation.js +5 -8
- package/lib/Types/Message.d.ts +31 -11
- package/lib/Types/Message.d.ts.map +1 -1
- package/lib/Types/Message.js +9 -18
- package/lib/Types/Message.js.map +1 -1
- package/lib/Types/{Newsletter.d.ts → Mex.d.ts} +11 -5
- package/lib/Types/Mex.d.ts.map +1 -0
- package/lib/Types/Mex.js +37 -0
- package/lib/Types/Mex.js.map +1 -0
- package/lib/Types/Product.js +2 -3
- package/lib/Types/Signal.d.ts +21 -16
- package/lib/Types/Signal.d.ts.map +1 -1
- package/lib/Types/Signal.js +2 -1
- package/lib/Types/Socket.d.ts +23 -17
- package/lib/Types/Socket.d.ts.map +1 -1
- package/lib/Types/Socket.js +3 -2
- package/lib/Types/Socket.js.map +1 -1
- package/lib/Types/State.d.ts +58 -0
- package/lib/Types/State.d.ts.map +1 -1
- package/lib/Types/State.js +55 -15
- package/lib/Types/State.js.map +1 -1
- package/lib/Types/USync.js +2 -1
- package/lib/Types/index.d.ts +1 -1
- package/lib/Types/index.d.ts.map +1 -1
- package/lib/Types/index.js +25 -163
- package/lib/Types/index.js.map +1 -1
- package/lib/Utils/auth-utils.d.ts +7 -2
- package/lib/Utils/auth-utils.d.ts.map +1 -1
- package/lib/Utils/auth-utils.js +272 -458
- package/lib/Utils/auth-utils.js.map +1 -1
- package/lib/Utils/browser-utils.d.ts +4 -0
- package/lib/Utils/browser-utils.d.ts.map +1 -0
- package/lib/Utils/browser-utils.js +28 -0
- package/lib/Utils/browser-utils.js.map +1 -0
- package/lib/Utils/business.js +208 -221
- package/lib/Utils/chat-utils.d.ts +35 -6
- package/lib/Utils/chat-utils.d.ts.map +1 -1
- package/lib/Utils/chat-utils.js +828 -800
- package/lib/Utils/chat-utils.js.map +1 -1
- package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
- package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
- package/lib/Utils/companion-reg-client-utils.js +35 -0
- package/lib/Utils/companion-reg-client-utils.js.map +1 -0
- package/lib/Utils/crypto.d.ts +7 -11
- package/lib/Utils/crypto.d.ts.map +1 -1
- package/lib/Utils/crypto.js +88 -142
- package/lib/Utils/crypto.js.map +1 -1
- package/lib/Utils/decode-wa-message.d.ts +22 -2
- package/lib/Utils/decode-wa-message.d.ts.map +1 -1
- package/lib/Utils/decode-wa-message.js +293 -261
- package/lib/Utils/decode-wa-message.js.map +1 -1
- package/lib/Utils/event-buffer.d.ts +2 -0
- package/lib/Utils/event-buffer.d.ts.map +1 -1
- package/lib/Utils/event-buffer.js +599 -558
- package/lib/Utils/event-buffer.js.map +1 -1
- package/lib/Utils/generics.d.ts +6 -7
- package/lib/Utils/generics.d.ts.map +1 -1
- package/lib/Utils/generics.js +331 -362
- package/lib/Utils/generics.js.map +1 -1
- package/lib/Utils/history.d.ts +14 -10
- package/lib/Utils/history.d.ts.map +1 -1
- package/lib/Utils/history.js +129 -93
- package/lib/Utils/history.js.map +1 -1
- package/lib/Utils/identity-change-handler.d.ts +44 -0
- package/lib/Utils/identity-change-handler.d.ts.map +1 -0
- package/lib/Utils/identity-change-handler.js +50 -0
- package/lib/Utils/identity-change-handler.js.map +1 -0
- package/lib/Utils/index.d.ts +4 -4
- package/lib/Utils/index.d.ts.map +1 -1
- package/lib/Utils/index.js +22 -234
- package/lib/Utils/index.js.map +1 -1
- package/lib/Utils/link-preview.d.ts +1 -2
- package/lib/Utils/link-preview.d.ts.map +1 -1
- package/lib/Utils/link-preview.js +69 -83
- package/lib/Utils/link-preview.js.map +1 -1
- package/lib/Utils/logger.js +3 -9
- package/lib/Utils/lt-hash.d.ts +7 -12
- package/lib/Utils/lt-hash.d.ts.map +1 -1
- package/lib/Utils/lt-hash.js +3 -50
- package/lib/Utils/lt-hash.js.map +1 -1
- package/lib/Utils/make-mutex.d.ts +1 -0
- package/lib/Utils/make-mutex.d.ts.map +1 -1
- package/lib/Utils/make-mutex.js +30 -40
- package/lib/Utils/make-mutex.js.map +1 -1
- package/lib/Utils/message-retry-manager.d.ts +38 -5
- package/lib/Utils/message-retry-manager.d.ts.map +1 -1
- package/lib/Utils/message-retry-manager.js +259 -159
- package/lib/Utils/message-retry-manager.js.map +1 -1
- package/lib/Utils/messages-media.d.ts +30 -10
- package/lib/Utils/messages-media.d.ts.map +1 -1
- package/lib/Utils/messages-media.js +734 -710
- package/lib/Utils/messages-media.js.map +1 -1
- package/lib/Utils/messages.d.ts +19 -4
- package/lib/Utils/messages.d.ts.map +1 -1
- package/lib/Utils/messages.js +817 -800
- package/lib/Utils/messages.js.map +1 -1
- package/lib/Utils/noise-handler.d.ts +4 -4
- package/lib/Utils/noise-handler.d.ts.map +1 -1
- package/lib/Utils/noise-handler.js +195 -165
- package/lib/Utils/noise-handler.js.map +1 -1
- package/lib/Utils/offline-node-processor.d.ts +17 -0
- package/lib/Utils/offline-node-processor.d.ts.map +1 -0
- package/lib/Utils/offline-node-processor.js +40 -0
- package/lib/Utils/offline-node-processor.js.map +1 -0
- package/lib/Utils/pre-key-manager.d.ts +28 -0
- package/lib/Utils/pre-key-manager.d.ts.map +1 -0
- package/lib/Utils/pre-key-manager.js +106 -0
- package/lib/Utils/pre-key-manager.js.map +1 -0
- package/lib/Utils/process-message.d.ts +26 -9
- package/lib/Utils/process-message.d.ts.map +1 -1
- package/lib/Utils/process-message.js +601 -422
- package/lib/Utils/process-message.js.map +1 -1
- package/lib/Utils/reporting-utils.d.ts +11 -0
- package/lib/Utils/reporting-utils.d.ts.map +1 -0
- package/lib/Utils/reporting-utils.js +258 -0
- package/lib/Utils/reporting-utils.js.map +1 -0
- package/lib/Utils/signal.d.ts +17 -4
- package/lib/Utils/signal.d.ts.map +1 -1
- package/lib/Utils/signal.js +180 -203
- package/lib/Utils/signal.js.map +1 -1
- package/lib/Utils/stanza-ack.d.ts +11 -0
- package/lib/Utils/stanza-ack.d.ts.map +1 -0
- package/lib/Utils/stanza-ack.js +38 -0
- package/lib/Utils/stanza-ack.js.map +1 -0
- package/lib/Utils/sync-action-utils.d.ts +19 -0
- package/lib/Utils/sync-action-utils.d.ts.map +1 -0
- package/lib/Utils/sync-action-utils.js +49 -0
- package/lib/Utils/sync-action-utils.js.map +1 -0
- package/lib/Utils/tc-token-utils.d.ts +37 -0
- package/lib/Utils/tc-token-utils.d.ts.map +1 -0
- package/lib/Utils/tc-token-utils.js +163 -0
- package/lib/Utils/tc-token-utils.js.map +1 -0
- package/lib/Utils/use-multi-file-auth-state.js +98 -98
- package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
- package/lib/Utils/validate-connection.d.ts.map +1 -1
- package/lib/Utils/validate-connection.js +191 -185
- package/lib/Utils/validate-connection.js.map +1 -1
- package/lib/WABinary/constants.js +1297 -35
- package/lib/WABinary/decode.d.ts.map +1 -1
- package/lib/WABinary/decode.js +254 -229
- package/lib/WABinary/decode.js.map +1 -1
- package/lib/WABinary/encode.js +210 -209
- package/lib/WABinary/encode.js.map +1 -1
- package/lib/WABinary/generic-utils.d.ts +1 -1
- package/lib/WABinary/generic-utils.d.ts.map +1 -1
- package/lib/WABinary/generic-utils.js +99 -105
- package/lib/WABinary/generic-utils.js.map +1 -1
- package/lib/WABinary/index.js +6 -58
- package/lib/WABinary/jid-utils.d.ts +12 -1
- package/lib/WABinary/jid-utils.d.ts.map +1 -1
- package/lib/WABinary/jid-utils.js +83 -67
- package/lib/WABinary/jid-utils.js.map +1 -1
- package/lib/WABinary/types.js +2 -2
- package/lib/WAM/BinaryInfo.js +9 -13
- package/lib/WAM/constants.d.ts +1 -1
- package/lib/WAM/constants.d.ts.map +1 -1
- package/lib/WAM/constants.js +22853 -1
- package/lib/WAM/constants.js.map +1 -1
- package/lib/WAM/encode.js +135 -132
- package/lib/WAM/index.js +4 -36
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +50 -31
- package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -58
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -29
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +35 -37
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +4 -2
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +23 -27
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +47 -61
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +2 -1
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +27 -23
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -1
- package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/index.js +6 -58
- package/lib/WAUSync/Protocols/index.js.map +1 -1
- package/lib/WAUSync/USyncQuery.d.ts +1 -1
- package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
- package/lib/WAUSync/USyncQuery.js +94 -94
- package/lib/WAUSync/USyncQuery.js.map +1 -1
- package/lib/WAUSync/USyncUser.d.ts +4 -0
- package/lib/WAUSync/USyncUser.d.ts.map +1 -1
- package/lib/WAUSync/USyncUser.js +30 -26
- package/lib/WAUSync/USyncUser.js.map +1 -1
- package/lib/WAUSync/index.js +4 -36
- package/lib/index.d.ts +0 -1
- package/lib/index.js +11 -112
- package/package.json +49 -22
- package/README.md +0 -1315
- package/lib/Signal/Group/queue-job.d.ts +0 -2
- package/lib/Signal/Group/queue-job.js +0 -59
- package/lib/Store/index.d.ts +0 -4
- package/lib/Store/index.js +0 -47
- package/lib/Store/make-cache-manager-store.d.ts +0 -17
- package/lib/Store/make-cache-manager-store.js +0 -104
- package/lib/Store/make-in-memory-store.d.ts +0 -118
- package/lib/Store/make-in-memory-store.js +0 -490
- package/lib/Store/make-ordered-dictionary.d.ts +0 -14
- package/lib/Store/make-ordered-dictionary.js +0 -81
- package/lib/Store/object-repository.d.ts +0 -10
- package/lib/Store/object-repository.js +0 -30
- package/lib/Types/Newsletter.d.ts.map +0 -1
- package/lib/Types/Newsletter.js +0 -34
- package/lib/Types/Newsletter.js.map +0 -1
- package/lib/Utils/baileys-event-stream.d.ts +0 -17
- package/lib/Utils/baileys-event-stream.d.ts.map +0 -1
- package/lib/Utils/baileys-event-stream.js +0 -71
- package/lib/Utils/baileys-event-stream.js.map +0 -1
- package/lib/Utils/extended-messages.d.ts +0 -73
- package/lib/Utils/extended-messages.js +0 -283
- package/lib/Utils/lid-resolver.d.ts +0 -17
- package/lib/Utils/lid-resolver.js +0 -79
- package/lib/Utils/mention.d.ts +0 -27
- package/lib/Utils/mention.js +0 -135
|
@@ -1,1286 +1,1145 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
}
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
} = config;
|
|
29
|
-
const sock = (0, _newsletter.makeNewsletterSocket)(config);
|
|
30
|
-
const {
|
|
31
|
-
ev,
|
|
32
|
-
authState,
|
|
33
|
-
processingMutex,
|
|
34
|
-
signalRepository,
|
|
35
|
-
upsertMessage,
|
|
36
|
-
query,
|
|
37
|
-
fetchPrivacySettings,
|
|
38
|
-
sendNode,
|
|
39
|
-
groupMetadata,
|
|
40
|
-
groupToggleEphemeral
|
|
41
|
-
} = sock;
|
|
42
|
-
const userDevicesCache = config.userDevicesCache || new _nodeCache.default({
|
|
43
|
-
stdTTL: _index2.DEFAULT_CACHE_TTLS.USER_DEVICES,
|
|
44
|
-
// 5 minutes
|
|
45
|
-
useClones: false
|
|
46
|
-
});
|
|
47
|
-
// Initialize message retry manager if enabled
|
|
48
|
-
const messageRetryManager = enableRecentMessageCache ? new _index4.MessageRetryManager(logger, maxMsgRetryCount) : null;
|
|
49
|
-
// Prevent race conditions in Signal session encryption by user
|
|
50
|
-
const encryptionMutex = (0, _makeMutex.makeKeyedMutex)();
|
|
51
|
-
let mediaConn;
|
|
52
|
-
const refreshMediaConn = async (forceGet = false) => {
|
|
53
|
-
const media = await mediaConn;
|
|
54
|
-
if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
|
|
55
|
-
mediaConn = (async () => {
|
|
56
|
-
const result = await query({
|
|
57
|
-
tag: 'iq',
|
|
58
|
-
attrs: {
|
|
59
|
-
type: 'set',
|
|
60
|
-
xmlns: 'w:m',
|
|
61
|
-
to: _index5.S_WHATSAPP_NET
|
|
62
|
-
},
|
|
63
|
-
content: [{
|
|
64
|
-
tag: 'media_conn',
|
|
65
|
-
attrs: {}
|
|
66
|
-
}]
|
|
1
|
+
import NodeCache from '@cacheable/node-cache';
|
|
2
|
+
import { Boom } from '@hapi/boom';
|
|
3
|
+
import { proto } from '../../WAProto/index.js';
|
|
4
|
+
import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
|
|
5
|
+
import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
|
|
6
|
+
import { getUrlInfo } from '../Utils/link-preview.js';
|
|
7
|
+
import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
|
|
8
|
+
import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
|
|
9
|
+
import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
|
|
10
|
+
import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
|
|
11
|
+
import { USyncQuery, USyncUser } from '../WAUSync/index.js';
|
|
12
|
+
import { makeNewsletterSocket } from './newsletter.js';
|
|
13
|
+
export const makeMessagesSocket = (config) => {
|
|
14
|
+
const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
|
|
15
|
+
const sock = makeNewsletterSocket(config);
|
|
16
|
+
const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
|
|
17
|
+
const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
|
|
18
|
+
/**
|
|
19
|
+
* Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
|
|
20
|
+
* Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
|
|
21
|
+
* Entries are always removed in `.finally()`, so the set is bounded by concurrency.
|
|
22
|
+
*/
|
|
23
|
+
const inFlightTcTokenIssuance = new Set();
|
|
24
|
+
const userDevicesCache = config.userDevicesCache ||
|
|
25
|
+
new NodeCache({
|
|
26
|
+
stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
|
|
27
|
+
useClones: false
|
|
67
28
|
});
|
|
68
|
-
|
|
29
|
+
/** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
|
|
30
|
+
const devicesMutex = makeMutex();
|
|
31
|
+
// Initialize message retry manager if enabled
|
|
32
|
+
const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
|
|
33
|
+
// Prevent race conditions in Signal session encryption by user
|
|
34
|
+
const encryptionMutex = makeKeyedMutex();
|
|
35
|
+
let mediaConn;
|
|
36
|
+
/** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
|
|
37
|
+
let mediaHost = DEF_MEDIA_HOST;
|
|
38
|
+
const refreshMediaConn = async (forceGet = false) => {
|
|
39
|
+
const media = await mediaConn;
|
|
40
|
+
if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
|
|
41
|
+
mediaConn = (async () => {
|
|
42
|
+
const result = await query({
|
|
43
|
+
tag: 'iq',
|
|
44
|
+
attrs: {
|
|
45
|
+
type: 'set',
|
|
46
|
+
xmlns: 'w:m',
|
|
47
|
+
to: S_WHATSAPP_NET
|
|
48
|
+
},
|
|
49
|
+
content: [{ tag: 'media_conn', attrs: {} }]
|
|
50
|
+
});
|
|
51
|
+
const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
|
|
52
|
+
// TODO: explore full length of data that whatsapp provides
|
|
53
|
+
const node = {
|
|
54
|
+
hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
|
|
55
|
+
hostname: attrs.hostname,
|
|
56
|
+
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
|
57
|
+
})),
|
|
58
|
+
auth: mediaConnNode.attrs.auth,
|
|
59
|
+
ttl: +mediaConnNode.attrs.ttl,
|
|
60
|
+
fetchDate: new Date()
|
|
61
|
+
};
|
|
62
|
+
logger.debug('fetched media conn');
|
|
63
|
+
if (node.hosts[0]) {
|
|
64
|
+
mediaHost = node.hosts[0].hostname;
|
|
65
|
+
}
|
|
66
|
+
return node;
|
|
67
|
+
})();
|
|
68
|
+
}
|
|
69
|
+
return mediaConn;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* generic send receipt function
|
|
73
|
+
* used for receipts of phone call, read, delivery etc.
|
|
74
|
+
* */
|
|
75
|
+
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
76
|
+
if (!messageIds || messageIds.length === 0) {
|
|
77
|
+
throw new Boom('missing ids in receipt');
|
|
78
|
+
}
|
|
69
79
|
const node = {
|
|
70
|
-
|
|
71
|
-
attrs
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
maxContentLengthBytes: +attrs.maxContentLengthBytes
|
|
75
|
-
})),
|
|
76
|
-
auth: mediaConnNode.attrs.auth,
|
|
77
|
-
ttl: +mediaConnNode.attrs.ttl,
|
|
78
|
-
fetchDate: new Date()
|
|
80
|
+
tag: 'receipt',
|
|
81
|
+
attrs: {
|
|
82
|
+
id: messageIds[0]
|
|
83
|
+
}
|
|
79
84
|
};
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
return mediaConn;
|
|
85
|
-
};
|
|
86
|
-
/**
|
|
87
|
-
* generic send receipt function
|
|
88
|
-
* used for receipts of phone call, read, delivery etc.
|
|
89
|
-
* */
|
|
90
|
-
const sendReceipt = async (jid, participant, messageIds, type) => {
|
|
91
|
-
if (!messageIds || messageIds.length === 0) {
|
|
92
|
-
throw new _boom.Boom('missing ids in receipt');
|
|
93
|
-
}
|
|
94
|
-
const node = {
|
|
95
|
-
tag: 'receipt',
|
|
96
|
-
attrs: {
|
|
97
|
-
id: messageIds[0]
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
const isReadReceipt = type === 'read' || type === 'read-self';
|
|
101
|
-
if (isReadReceipt) {
|
|
102
|
-
node.attrs.t = (0, _index4.unixTimestampSeconds)().toString();
|
|
103
|
-
}
|
|
104
|
-
if (type === 'sender' && (0, _index5.isPnUser)(jid)) {
|
|
105
|
-
node.attrs.recipient = jid;
|
|
106
|
-
node.attrs.to = participant;
|
|
107
|
-
} else {
|
|
108
|
-
node.attrs.to = jid;
|
|
109
|
-
if (participant) {
|
|
110
|
-
node.attrs.participant = participant;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
if (type) {
|
|
114
|
-
node.attrs.type = type;
|
|
115
|
-
}
|
|
116
|
-
const remainingMessageIds = messageIds.slice(1);
|
|
117
|
-
if (remainingMessageIds.length) {
|
|
118
|
-
node.content = [{
|
|
119
|
-
tag: 'list',
|
|
120
|
-
attrs: {},
|
|
121
|
-
content: remainingMessageIds.map(id => ({
|
|
122
|
-
tag: 'item',
|
|
123
|
-
attrs: {
|
|
124
|
-
id
|
|
125
|
-
}
|
|
126
|
-
}))
|
|
127
|
-
}];
|
|
128
|
-
}
|
|
129
|
-
logger.debug({
|
|
130
|
-
attrs: node.attrs,
|
|
131
|
-
messageIds
|
|
132
|
-
}, 'sending receipt for messages');
|
|
133
|
-
await sendNode(node);
|
|
134
|
-
};
|
|
135
|
-
/** Correctly bulk send receipts to multiple chats, participants */
|
|
136
|
-
const sendReceipts = async (keys, type) => {
|
|
137
|
-
const recps = (0, _index4.aggregateMessageKeysNotFromMe)(keys);
|
|
138
|
-
for (const {
|
|
139
|
-
jid,
|
|
140
|
-
participant,
|
|
141
|
-
messageIds
|
|
142
|
-
} of recps) {
|
|
143
|
-
await sendReceipt(jid, participant, messageIds, type);
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
/** Bulk read messages. Keys can be from different chats & participants */
|
|
147
|
-
const readMessages = async keys => {
|
|
148
|
-
const privacySettings = await fetchPrivacySettings();
|
|
149
|
-
// based on privacy settings, we have to change the read type
|
|
150
|
-
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
|
|
151
|
-
await sendReceipts(keys, readType);
|
|
152
|
-
};
|
|
153
|
-
/**
|
|
154
|
-
* Deduplicate JIDs when both LID and PN versions exist for same user
|
|
155
|
-
* Prefers LID over PN to maintain single encryption layer
|
|
156
|
-
*/
|
|
157
|
-
const deduplicateLidPnJids = jids => {
|
|
158
|
-
const lidUsers = new Set();
|
|
159
|
-
const filteredJids = [];
|
|
160
|
-
// Collect all LID users
|
|
161
|
-
for (const jid of jids) {
|
|
162
|
-
if (jid.includes('@lid')) {
|
|
163
|
-
const user = (0, _index5.jidDecode)(jid)?.user;
|
|
164
|
-
if (user) lidUsers.add(user);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
// Filter out PN versions when LID exists
|
|
168
|
-
for (const jid of jids) {
|
|
169
|
-
if (jid.includes('@s.whatsapp.net')) {
|
|
170
|
-
const user = (0, _index5.jidDecode)(jid)?.user;
|
|
171
|
-
if (user && lidUsers.has(user)) {
|
|
172
|
-
logger.debug({
|
|
173
|
-
jid
|
|
174
|
-
}, 'Skipping PN - LID version exists');
|
|
175
|
-
continue;
|
|
85
|
+
const isReadReceipt = type === 'read' || type === 'read-self';
|
|
86
|
+
if (isReadReceipt) {
|
|
87
|
+
node.attrs.t = unixTimestampSeconds().toString();
|
|
176
88
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
return filteredJids;
|
|
181
|
-
};
|
|
182
|
-
/** Fetch all the devices we've to send a message to */
|
|
183
|
-
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
184
|
-
const deviceResults = [];
|
|
185
|
-
if (!useCache) {
|
|
186
|
-
logger.debug('not using cache for devices');
|
|
187
|
-
}
|
|
188
|
-
const toFetch = [];
|
|
189
|
-
// Deduplicate and normalize JIDs
|
|
190
|
-
jids = deduplicateLidPnJids(Array.from(new Set(jids)));
|
|
191
|
-
for (let jid of jids) {
|
|
192
|
-
const decoded = (0, _index5.jidDecode)(jid);
|
|
193
|
-
const user = decoded?.user;
|
|
194
|
-
const device = decoded?.device;
|
|
195
|
-
const isExplicitDevice = typeof device === 'number' && device >= 0;
|
|
196
|
-
// Handle explicit device JIDs directly
|
|
197
|
-
if (isExplicitDevice && user) {
|
|
198
|
-
deviceResults.push({
|
|
199
|
-
user,
|
|
200
|
-
device,
|
|
201
|
-
wireJid: jid // Preserve exact JID format for wire protocol
|
|
202
|
-
});
|
|
203
|
-
continue;
|
|
204
|
-
}
|
|
205
|
-
// For user JIDs, normalize and prepare for device enumeration
|
|
206
|
-
jid = (0, _index5.jidNormalizedUser)(jid);
|
|
207
|
-
if (useCache) {
|
|
208
|
-
const devices = userDevicesCache.get(user);
|
|
209
|
-
if (devices) {
|
|
210
|
-
const isLidJid = jid.includes('@lid');
|
|
211
|
-
const devicesWithWire = devices.map(d => ({
|
|
212
|
-
...d,
|
|
213
|
-
wireJid: isLidJid ? (0, _index5.jidEncode)(d.user, 'lid', d.device) : (0, _index5.jidEncode)(d.user, 's.whatsapp.net', d.device)
|
|
214
|
-
}));
|
|
215
|
-
deviceResults.push(...devicesWithWire);
|
|
216
|
-
logger.trace({
|
|
217
|
-
user
|
|
218
|
-
}, 'using cache for devices');
|
|
219
|
-
} else {
|
|
220
|
-
toFetch.push(jid);
|
|
89
|
+
if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
|
|
90
|
+
node.attrs.recipient = jid;
|
|
91
|
+
node.attrs.to = participant;
|
|
221
92
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
return deviceResults;
|
|
228
|
-
}
|
|
229
|
-
const requestedLidUsers = new Set();
|
|
230
|
-
for (const jid of toFetch) {
|
|
231
|
-
if (jid.includes('@lid')) {
|
|
232
|
-
const user = (0, _index5.jidDecode)(jid)?.user;
|
|
233
|
-
if (user) requestedLidUsers.add(user);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
const query = new _index6.USyncQuery().withContext('message').withDeviceProtocol();
|
|
237
|
-
for (const jid of toFetch) {
|
|
238
|
-
query.withUser(new _index6.USyncUser().withId(jid));
|
|
239
|
-
}
|
|
240
|
-
const result = await sock.executeUSyncQuery(query);
|
|
241
|
-
if (result) {
|
|
242
|
-
const extracted = (0, _index4.extractDeviceJids)(result?.list, authState.creds.me.id, ignoreZeroDevices);
|
|
243
|
-
const deviceMap = {};
|
|
244
|
-
for (const item of extracted) {
|
|
245
|
-
deviceMap[item.user] = deviceMap[item.user] || [];
|
|
246
|
-
deviceMap[item.user]?.push(item);
|
|
247
|
-
}
|
|
248
|
-
// Process each user's devices as a group for bulk LID migration
|
|
249
|
-
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
250
|
-
const isLidUser = requestedLidUsers.has(user);
|
|
251
|
-
// Process all devices for this user
|
|
252
|
-
for (const item of userDevices) {
|
|
253
|
-
const finalWireJid = isLidUser ? (0, _index5.jidEncode)(user, 'lid', item.device) : (0, _index5.jidEncode)(item.user, 's.whatsapp.net', item.device);
|
|
254
|
-
deviceResults.push({
|
|
255
|
-
...item,
|
|
256
|
-
wireJid: finalWireJid
|
|
257
|
-
});
|
|
258
|
-
logger.debug({
|
|
259
|
-
user: item.user,
|
|
260
|
-
device: item.device,
|
|
261
|
-
finalWireJid,
|
|
262
|
-
usedLid: isLidUser
|
|
263
|
-
}, 'Processed device with LID priority');
|
|
93
|
+
else {
|
|
94
|
+
node.attrs.to = jid;
|
|
95
|
+
if (participant) {
|
|
96
|
+
node.attrs.participant = participant;
|
|
97
|
+
}
|
|
264
98
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
userDevicesCache.set(key, deviceMap[key]);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
return deviceResults;
|
|
271
|
-
};
|
|
272
|
-
// Helper to check if JID has migrated LID session
|
|
273
|
-
const checkForMigratedLidSession = async jid => {
|
|
274
|
-
if (!jid.includes('@s.whatsapp.net')) return false;
|
|
275
|
-
const lidMapping = signalRepository.getLIDMappingStore();
|
|
276
|
-
const lidForPN = await lidMapping.getLIDForPN(jid);
|
|
277
|
-
if (!lidForPN?.includes('@lid')) return false;
|
|
278
|
-
const lidSignalId = signalRepository.jidToSignalProtocolAddress(lidForPN);
|
|
279
|
-
const lidSessions = await authState.keys.get('session', [lidSignalId]);
|
|
280
|
-
return !!lidSessions[lidSignalId];
|
|
281
|
-
};
|
|
282
|
-
const assertSessions = async (jids, force) => {
|
|
283
|
-
let didFetchNewSession = false;
|
|
284
|
-
const jidsRequiringFetch = [];
|
|
285
|
-
// Apply same deduplication as in getUSyncDevices
|
|
286
|
-
jids = deduplicateLidPnJids(jids);
|
|
287
|
-
if (force) {
|
|
288
|
-
// Check which sessions are missing (with LID migration check)
|
|
289
|
-
const addrs = jids.map(jid => signalRepository.jidToSignalProtocolAddress(jid));
|
|
290
|
-
const sessions = await authState.keys.get('session', addrs);
|
|
291
|
-
// Helper to check session for a JID
|
|
292
|
-
const checkJidSession = async jid => {
|
|
293
|
-
const signalId = signalRepository.jidToSignalProtocolAddress(jid);
|
|
294
|
-
let hasSession = !!sessions[signalId];
|
|
295
|
-
// Check for migrated LID session if PN session missing
|
|
296
|
-
if (!hasSession) {
|
|
297
|
-
hasSession = await checkForMigratedLidSession(jid);
|
|
298
|
-
if (hasSession) {
|
|
299
|
-
logger.debug({
|
|
300
|
-
jid
|
|
301
|
-
}, 'Found migrated LID session during force assert, skipping PN fetch');
|
|
302
|
-
}
|
|
99
|
+
if (type) {
|
|
100
|
+
node.attrs.type = type;
|
|
303
101
|
}
|
|
304
|
-
|
|
305
|
-
if (
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
102
|
+
const remainingMessageIds = messageIds.slice(1);
|
|
103
|
+
if (remainingMessageIds.length) {
|
|
104
|
+
node.content = [
|
|
105
|
+
{
|
|
106
|
+
tag: 'list',
|
|
107
|
+
attrs: {},
|
|
108
|
+
content: remainingMessageIds.map(id => ({
|
|
109
|
+
tag: 'item',
|
|
110
|
+
attrs: { id }
|
|
111
|
+
}))
|
|
112
|
+
}
|
|
113
|
+
];
|
|
312
114
|
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
const sessions = await authState.keys.get('session', addrs);
|
|
322
|
-
// Group JIDs by user for bulk migration
|
|
323
|
-
const userGroups = new Map();
|
|
324
|
-
for (const jid of jids) {
|
|
325
|
-
const user = (0, _index5.jidNormalizedUser)(jid);
|
|
326
|
-
if (!userGroups.has(user)) {
|
|
327
|
-
userGroups.set(user, []);
|
|
115
|
+
logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
|
|
116
|
+
await sendNode(node);
|
|
117
|
+
};
|
|
118
|
+
/** Correctly bulk send receipts to multiple chats, participants */
|
|
119
|
+
const sendReceipts = async (keys, type) => {
|
|
120
|
+
const recps = aggregateMessageKeysNotFromMe(keys);
|
|
121
|
+
for (const { jid, participant, messageIds } of recps) {
|
|
122
|
+
await sendReceipt(jid, participant, messageIds, type);
|
|
328
123
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
124
|
+
};
|
|
125
|
+
/** Bulk read messages. Keys can be from different chats & participants */
|
|
126
|
+
const readMessages = async (keys) => {
|
|
127
|
+
const privacySettings = await fetchPrivacySettings();
|
|
128
|
+
// based on privacy settings, we have to change the read type
|
|
129
|
+
const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
|
|
130
|
+
await sendReceipts(keys, readType);
|
|
131
|
+
};
|
|
132
|
+
/** Fetch all the devices we've to send a message to */
|
|
133
|
+
const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
|
|
134
|
+
const deviceResults = [];
|
|
135
|
+
if (!useCache) {
|
|
136
|
+
logger.debug('not using cache for devices');
|
|
338
137
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
138
|
+
const toFetch = [];
|
|
139
|
+
const jidsWithUser = jids
|
|
140
|
+
.map(jid => {
|
|
141
|
+
const decoded = jidDecode(jid);
|
|
142
|
+
const user = decoded?.user;
|
|
143
|
+
const device = decoded?.device;
|
|
144
|
+
const isExplicitDevice = typeof device === 'number' && device >= 0;
|
|
145
|
+
if (isExplicitDevice && user) {
|
|
146
|
+
deviceResults.push({
|
|
147
|
+
user,
|
|
148
|
+
device,
|
|
149
|
+
jid
|
|
150
|
+
});
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
jid = jidNormalizedUser(jid);
|
|
154
|
+
return { jid, user };
|
|
155
|
+
})
|
|
156
|
+
.filter(jid => jid !== null);
|
|
157
|
+
let mgetDevices;
|
|
158
|
+
if (useCache && userDevicesCache.mget) {
|
|
159
|
+
const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
|
|
160
|
+
mgetDevices = await userDevicesCache.mget(usersToFetch);
|
|
357
161
|
}
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
deletedPNSession: jid
|
|
378
|
-
}, 'Deleted PN session after migration');
|
|
379
|
-
} catch (deleteError) {
|
|
380
|
-
logger.warn({
|
|
381
|
-
jid,
|
|
382
|
-
error: deleteError
|
|
383
|
-
}, 'Failed to delete PN session');
|
|
384
|
-
}
|
|
385
|
-
} catch (migrationError) {
|
|
386
|
-
logger.warn({
|
|
387
|
-
jid,
|
|
388
|
-
error: migrationError
|
|
389
|
-
}, 'Failed to migrate device session');
|
|
162
|
+
for (const { jid, user } of jidsWithUser) {
|
|
163
|
+
if (useCache) {
|
|
164
|
+
const devices = mgetDevices?.[user] ||
|
|
165
|
+
(userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
|
|
166
|
+
if (devices) {
|
|
167
|
+
const devicesWithJid = devices.map(d => ({
|
|
168
|
+
...d,
|
|
169
|
+
jid: jidEncode(d.user, d.server, d.device)
|
|
170
|
+
}));
|
|
171
|
+
deviceResults.push(...devicesWithJid);
|
|
172
|
+
logger.trace({ user }, 'using cache for devices');
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
toFetch.push(jid);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
toFetch.push(jid);
|
|
180
|
+
}
|
|
390
181
|
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
for (const [user, userJids] of userGroups) {
|
|
394
|
-
const mappingResult = await checkUserLidMapping(user, userJids);
|
|
395
|
-
const shouldMigrateUser = mappingResult.shouldMigrate;
|
|
396
|
-
const lidForPN = mappingResult.lidForPN;
|
|
397
|
-
// Migrate all devices for this user if LID mapping exists
|
|
398
|
-
if (shouldMigrateUser && lidForPN) {
|
|
399
|
-
// Migrate each device individually
|
|
400
|
-
for (const jid of userJids) {
|
|
401
|
-
await migrateDeviceToLid(jid, lidForPN);
|
|
402
|
-
}
|
|
403
|
-
logger.info({
|
|
404
|
-
user,
|
|
405
|
-
lidMapping: lidForPN,
|
|
406
|
-
deviceCount: userJids.length
|
|
407
|
-
}, 'Completed migration attempt for user devices');
|
|
182
|
+
if (!toFetch.length) {
|
|
183
|
+
return deviceResults;
|
|
408
184
|
}
|
|
409
|
-
|
|
410
|
-
const
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
if (shouldMigrateUser && lidForPN && jid.includes('@s.whatsapp.net')) {
|
|
416
|
-
const originalDecoded = (0, _index5.jidDecode)(jid);
|
|
417
|
-
const deviceId = originalDecoded?.device || 0;
|
|
418
|
-
const lidDecoded = (0, _index5.jidDecode)(lidForPN);
|
|
419
|
-
const lidWithDevice = (0, _index5.jidEncode)(lidDecoded?.user, 'lid', deviceId);
|
|
420
|
-
// Check if LID session exists
|
|
421
|
-
const lidSignalId = signalRepository.jidToSignalProtocolAddress(lidWithDevice);
|
|
422
|
-
const lidSessions = await authState.keys.get('session', [lidSignalId]);
|
|
423
|
-
hasSession = !!lidSessions[lidSignalId];
|
|
424
|
-
jidToFetch = lidWithDevice;
|
|
425
|
-
if (hasSession) {
|
|
426
|
-
logger.debug({
|
|
427
|
-
originalJid: jid,
|
|
428
|
-
lidJid: lidWithDevice
|
|
429
|
-
}, '✅ Found bulk-migrated LID session');
|
|
185
|
+
const requestedLidUsers = new Set();
|
|
186
|
+
for (const jid of toFetch) {
|
|
187
|
+
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
|
188
|
+
const user = jidDecode(jid)?.user;
|
|
189
|
+
if (user)
|
|
190
|
+
requestedLidUsers.add(user);
|
|
430
191
|
}
|
|
431
|
-
}
|
|
432
|
-
// Add to fetch list if no session exists
|
|
433
|
-
if (!hasSession) {
|
|
434
|
-
jidsRequiringFetch.push(jidToFetch);
|
|
435
|
-
logger.debug({
|
|
436
|
-
jid: jidToFetch,
|
|
437
|
-
originalJid: jid !== jidToFetch ? jid : undefined
|
|
438
|
-
}, 'Adding to session fetch list');
|
|
439
|
-
}
|
|
440
|
-
};
|
|
441
|
-
// Now check which sessions need to be fetched for this user
|
|
442
|
-
for (const jid of userJids) {
|
|
443
|
-
await checkMigratedSession(jid);
|
|
444
192
|
}
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
logger.debug({
|
|
449
|
-
jidsRequiringFetch
|
|
450
|
-
}, 'fetching sessions');
|
|
451
|
-
// DEBUG: Check if there are PN versions of LID users being fetched
|
|
452
|
-
const lidUsersBeingFetched = new Set();
|
|
453
|
-
const pnUsersBeingFetched = new Set();
|
|
454
|
-
for (const jid of jidsRequiringFetch) {
|
|
455
|
-
const user = (0, _index5.jidDecode)(jid)?.user;
|
|
456
|
-
if (user) {
|
|
457
|
-
if (jid.includes('@lid')) {
|
|
458
|
-
lidUsersBeingFetched.add(user);
|
|
459
|
-
} else if (jid.includes('@s.whatsapp.net')) {
|
|
460
|
-
pnUsersBeingFetched.add(user);
|
|
461
|
-
}
|
|
193
|
+
const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
|
|
194
|
+
for (const jid of toFetch) {
|
|
195
|
+
query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
|
|
462
196
|
}
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
197
|
+
const result = await sock.executeUSyncQuery(query);
|
|
198
|
+
if (result) {
|
|
199
|
+
// TODO: LID MAP this stuff (lid protocol will now return lid with devices)
|
|
200
|
+
const lidResults = result.list.filter(a => !!a.lid);
|
|
201
|
+
if (lidResults.length > 0) {
|
|
202
|
+
logger.trace('Storing LID maps from device call');
|
|
203
|
+
await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
|
|
204
|
+
// Force-refresh sessions for newly mapped LIDs to align identity addressing
|
|
205
|
+
try {
|
|
206
|
+
const lids = lidResults.map(a => a.lid);
|
|
207
|
+
if (lids.length) {
|
|
208
|
+
await assertSessions(lids, true);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
catch (e) {
|
|
212
|
+
logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
|
|
216
|
+
const deviceMap = {};
|
|
217
|
+
for (const item of extracted) {
|
|
218
|
+
deviceMap[item.user] = deviceMap[item.user] || [];
|
|
219
|
+
deviceMap[item.user]?.push(item);
|
|
220
|
+
}
|
|
221
|
+
// Process each user's devices as a group for bulk LID migration
|
|
222
|
+
for (const [user, userDevices] of Object.entries(deviceMap)) {
|
|
223
|
+
const isLidUser = requestedLidUsers.has(user);
|
|
224
|
+
// Process all devices for this user
|
|
225
|
+
for (const item of userDevices) {
|
|
226
|
+
const finalJid = isLidUser
|
|
227
|
+
? jidEncode(user, item.server, item.device)
|
|
228
|
+
: jidEncode(item.user, item.server, item.device);
|
|
229
|
+
deviceResults.push({
|
|
230
|
+
...item,
|
|
231
|
+
jid: finalJid
|
|
232
|
+
});
|
|
233
|
+
logger.debug({
|
|
234
|
+
user: item.user,
|
|
235
|
+
device: item.device,
|
|
236
|
+
finalJid,
|
|
237
|
+
usedLid: isLidUser
|
|
238
|
+
}, 'Processed device with LID priority');
|
|
239
|
+
}
|
|
487
240
|
}
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
241
|
+
await devicesMutex.mutex(async () => {
|
|
242
|
+
if (userDevicesCache.mset) {
|
|
243
|
+
// if the cache supports mset, we can set all devices in one go
|
|
244
|
+
await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
for (const key in deviceMap) {
|
|
248
|
+
if (deviceMap[key])
|
|
249
|
+
await userDevicesCache.set(key, deviceMap[key]);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
const userDeviceUpdates = {};
|
|
254
|
+
for (const [userId, devices] of Object.entries(deviceMap)) {
|
|
255
|
+
if (devices && devices.length > 0) {
|
|
256
|
+
userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (Object.keys(userDeviceUpdates).length > 0) {
|
|
260
|
+
try {
|
|
261
|
+
await authState.keys.set({ 'device-list': userDeviceUpdates });
|
|
262
|
+
logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
logger.warn({ error }, 'failed to store user device lists');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return deviceResults;
|
|
506
270
|
};
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
recipientJid: wireJid,
|
|
544
|
-
patchedMessage
|
|
545
|
-
});
|
|
546
|
-
}
|
|
547
|
-
// Process each user's devices sequentially, but different users in parallel
|
|
548
|
-
const userEncryptionPromises = Array.from(devicesByUser.entries()).map(([user, userDevices]) => encryptionMutex.mutex(user, async () => {
|
|
549
|
-
logger.debug({
|
|
550
|
-
user,
|
|
551
|
-
deviceCount: userDevices.length
|
|
552
|
-
}, 'Acquiring encryption lock for user devices');
|
|
553
|
-
const userNodes = [];
|
|
554
|
-
// Helper to get encryption JID with LID migration
|
|
555
|
-
const getEncryptionJid = async wireJid => {
|
|
556
|
-
if (!wireJid.includes('@s.whatsapp.net')) return wireJid;
|
|
557
|
-
try {
|
|
558
|
-
const lidMapping = signalRepository.getLIDMappingStore();
|
|
559
|
-
const lidForPN = await lidMapping.getLIDForPN(wireJid);
|
|
560
|
-
if (!lidForPN?.includes('@lid')) return wireJid;
|
|
561
|
-
// Preserve device ID from original wire JID
|
|
562
|
-
const wireDecoded = (0, _index5.jidDecode)(wireJid);
|
|
563
|
-
const deviceId = wireDecoded?.device || 0;
|
|
564
|
-
const lidDecoded = (0, _index5.jidDecode)(lidForPN);
|
|
565
|
-
const lidWithDevice = (0, _index5.jidEncode)(lidDecoded?.user, 'lid', deviceId);
|
|
566
|
-
// Migrate session to LID for unified encryption layer
|
|
567
|
-
try {
|
|
568
|
-
await signalRepository.migrateSession(wireJid, lidWithDevice);
|
|
569
|
-
const recipientUser = (0, _index5.jidNormalizedUser)(wireJid);
|
|
570
|
-
const ownPnUser = (0, _index5.jidNormalizedUser)(meId);
|
|
571
|
-
const isOwnDevice = recipientUser === ownPnUser;
|
|
572
|
-
logger.info({
|
|
573
|
-
wireJid,
|
|
574
|
-
lidWithDevice,
|
|
575
|
-
isOwnDevice
|
|
576
|
-
}, 'Migrated to LID encryption');
|
|
577
|
-
// Delete PN session after successful migration
|
|
578
|
-
try {
|
|
579
|
-
await signalRepository.deleteSession(wireJid);
|
|
580
|
-
logger.debug({
|
|
581
|
-
deletedPNSession: wireJid
|
|
582
|
-
}, 'Deleted PN session');
|
|
583
|
-
} catch (deleteError) {
|
|
584
|
-
logger.warn({
|
|
585
|
-
wireJid,
|
|
586
|
-
error: deleteError
|
|
587
|
-
}, 'Failed to delete PN session');
|
|
271
|
+
/**
|
|
272
|
+
* Update Member Label
|
|
273
|
+
*/
|
|
274
|
+
const updateMemberLabel = (jid, memberLabel) => {
|
|
275
|
+
return relayMessage(jid, {
|
|
276
|
+
protocolMessage: {
|
|
277
|
+
type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
|
|
278
|
+
memberLabel: {
|
|
279
|
+
label: memberLabel?.slice(0, 30),
|
|
280
|
+
labelTimestamp: unixTimestampSeconds()
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}, {
|
|
284
|
+
additionalNodes: [
|
|
285
|
+
{
|
|
286
|
+
tag: 'meta',
|
|
287
|
+
attrs: {
|
|
288
|
+
tag_reason: 'user_update',
|
|
289
|
+
appdata: 'member_tag'
|
|
290
|
+
},
|
|
291
|
+
content: undefined
|
|
292
|
+
}
|
|
293
|
+
]
|
|
294
|
+
});
|
|
295
|
+
};
|
|
296
|
+
const assertSessions = async (jids, force) => {
|
|
297
|
+
let didFetchNewSession = false;
|
|
298
|
+
const uniqueJids = [...new Set(jids)];
|
|
299
|
+
const jidsRequiringFetch = [];
|
|
300
|
+
logger.debug({ jids }, 'assertSessions call with jids');
|
|
301
|
+
for (const jid of uniqueJids) {
|
|
302
|
+
if (!force) {
|
|
303
|
+
const sessionValidation = await signalRepository.validateSession(jid);
|
|
304
|
+
if (sessionValidation.exists) {
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
588
307
|
}
|
|
589
|
-
|
|
590
|
-
} catch (migrationError) {
|
|
591
|
-
logger.warn({
|
|
592
|
-
wireJid,
|
|
593
|
-
error: migrationError
|
|
594
|
-
}, 'Failed to migrate session');
|
|
595
|
-
return wireJid;
|
|
596
|
-
}
|
|
597
|
-
} catch (error) {
|
|
598
|
-
logger.debug({
|
|
599
|
-
wireJid,
|
|
600
|
-
error
|
|
601
|
-
}, 'Failed to check LID mapping');
|
|
602
|
-
return wireJid;
|
|
308
|
+
jidsRequiringFetch.push(jid);
|
|
603
309
|
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
310
|
+
if (jidsRequiringFetch.length) {
|
|
311
|
+
// LID if mapped, otherwise original
|
|
312
|
+
const wireJids = [
|
|
313
|
+
...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
|
|
314
|
+
...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
|
|
315
|
+
];
|
|
316
|
+
logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
|
|
317
|
+
const result = await query({
|
|
318
|
+
tag: 'iq',
|
|
319
|
+
attrs: {
|
|
320
|
+
xmlns: 'encrypt',
|
|
321
|
+
type: 'get',
|
|
322
|
+
to: S_WHATSAPP_NET
|
|
323
|
+
},
|
|
324
|
+
content: [
|
|
325
|
+
{
|
|
326
|
+
tag: 'key',
|
|
327
|
+
attrs: {},
|
|
328
|
+
content: wireJids.map(jid => {
|
|
329
|
+
const attrs = { jid };
|
|
330
|
+
if (force)
|
|
331
|
+
attrs.reason = 'identity';
|
|
332
|
+
return { tag: 'user', attrs };
|
|
333
|
+
})
|
|
334
|
+
}
|
|
335
|
+
]
|
|
336
|
+
});
|
|
337
|
+
await parseAndInjectE2ESessions(result, signalRepository);
|
|
338
|
+
didFetchNewSession = true;
|
|
631
339
|
}
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
//
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
ciphertext
|
|
639
|
-
} = await signalRepository.encryptMessage({
|
|
640
|
-
jid: encryptionJid,
|
|
641
|
-
// Unified encryption layer (LID when available)
|
|
642
|
-
data: bytes
|
|
643
|
-
});
|
|
644
|
-
if (type === 'pkmsg') {
|
|
645
|
-
shouldIncludeDeviceIdentity = true;
|
|
340
|
+
return didFetchNewSession;
|
|
341
|
+
};
|
|
342
|
+
const sendPeerDataOperationMessage = async (pdoMessage) => {
|
|
343
|
+
//TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
|
|
344
|
+
if (!authState.creds.me?.id) {
|
|
345
|
+
throw new Boom('Not authenticated');
|
|
646
346
|
}
|
|
647
|
-
const
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
// Always use original wire identity in envelope
|
|
653
|
-
content: [{
|
|
654
|
-
tag: 'enc',
|
|
655
|
-
attrs: {
|
|
656
|
-
v: '2',
|
|
657
|
-
type,
|
|
658
|
-
...(extraAttrs || {})
|
|
659
|
-
},
|
|
660
|
-
content: ciphertext
|
|
661
|
-
}]
|
|
347
|
+
const protocolMessage = {
|
|
348
|
+
protocolMessage: {
|
|
349
|
+
peerDataOperationRequestMessage: pdoMessage,
|
|
350
|
+
type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
|
|
351
|
+
}
|
|
662
352
|
};
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
};
|
|
678
|
-
};
|
|
679
|
-
const relayMessage = async (jid, message, {
|
|
680
|
-
messageId: msgId,
|
|
681
|
-
participant,
|
|
682
|
-
additionalAttributes,
|
|
683
|
-
additionalNodes,
|
|
684
|
-
useUserDevicesCache,
|
|
685
|
-
useCachedGroupMetadata,
|
|
686
|
-
statusJidList
|
|
687
|
-
}) => {
|
|
688
|
-
const meId = authState.creds.me.id;
|
|
689
|
-
const meLid = authState.creds.me?.lid;
|
|
690
|
-
// ADDRESSING CONSISTENCY: Keep envelope addressing as user provided, handle LID migration in encryption
|
|
691
|
-
let shouldIncludeDeviceIdentity = false;
|
|
692
|
-
const {
|
|
693
|
-
user,
|
|
694
|
-
server
|
|
695
|
-
} = (0, _index5.jidDecode)(jid);
|
|
696
|
-
const statusJid = 'status@broadcast';
|
|
697
|
-
const isGroup = server === 'g.us';
|
|
698
|
-
const isStatus = jid === statusJid;
|
|
699
|
-
const isLid = server === 'lid';
|
|
700
|
-
const isNewsletter = server === 'newsletter';
|
|
701
|
-
// Keep user's original JID choice for envelope addressing
|
|
702
|
-
const finalJid = jid;
|
|
703
|
-
// ADDRESSING CONSISTENCY: Match own identity to conversation context
|
|
704
|
-
let ownId = meId;
|
|
705
|
-
if (isLid && meLid) {
|
|
706
|
-
ownId = meLid;
|
|
707
|
-
logger.debug({
|
|
708
|
-
to: jid,
|
|
709
|
-
ownId
|
|
710
|
-
}, 'Using LID identity for @lid conversation');
|
|
711
|
-
} else {
|
|
712
|
-
logger.debug({
|
|
713
|
-
to: jid,
|
|
714
|
-
ownId
|
|
715
|
-
}, 'Using PN identity for @s.whatsapp.net conversation');
|
|
716
|
-
}
|
|
717
|
-
msgId = msgId || (0, _index4.generateMessageIDV2)(sock.user?.id);
|
|
718
|
-
useUserDevicesCache = useUserDevicesCache !== false;
|
|
719
|
-
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
|
|
720
|
-
const participants = [];
|
|
721
|
-
const destinationJid = !isStatus ? finalJid : statusJid;
|
|
722
|
-
const binaryNodeContent = [];
|
|
723
|
-
const devices = [];
|
|
724
|
-
const meMsg = {
|
|
725
|
-
deviceSentMessage: {
|
|
726
|
-
destinationJid,
|
|
727
|
-
message
|
|
728
|
-
},
|
|
729
|
-
messageContextInfo: message.messageContextInfo
|
|
353
|
+
const meJid = jidNormalizedUser(authState.creds.me.id);
|
|
354
|
+
const msgId = await relayMessage(meJid, protocolMessage, {
|
|
355
|
+
additionalAttributes: {
|
|
356
|
+
category: 'peer',
|
|
357
|
+
push_priority: 'high_force'
|
|
358
|
+
},
|
|
359
|
+
additionalNodes: [
|
|
360
|
+
{
|
|
361
|
+
tag: 'meta',
|
|
362
|
+
attrs: { appdata: 'default' }
|
|
363
|
+
}
|
|
364
|
+
]
|
|
365
|
+
});
|
|
366
|
+
return msgId;
|
|
730
367
|
};
|
|
731
|
-
const
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
368
|
+
const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
|
|
369
|
+
if (!recipientJids.length) {
|
|
370
|
+
return { nodes: [], shouldIncludeDeviceIdentity: false };
|
|
371
|
+
}
|
|
372
|
+
const patched = await patchMessageBeforeSending(message, recipientJids);
|
|
373
|
+
const patchedMessages = Array.isArray(patched)
|
|
374
|
+
? patched
|
|
375
|
+
: recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
|
|
376
|
+
let shouldIncludeDeviceIdentity = false;
|
|
377
|
+
const meId = authState.creds.me.id;
|
|
378
|
+
const meLid = authState.creds.me?.lid;
|
|
379
|
+
const meLidUser = meLid ? jidDecode(meLid)?.user : null;
|
|
380
|
+
const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
|
|
381
|
+
try {
|
|
382
|
+
if (!jid)
|
|
383
|
+
return null;
|
|
384
|
+
let msgToEncrypt = patchedMessage;
|
|
385
|
+
if (dsmMessage) {
|
|
386
|
+
const { user: targetUser } = jidDecode(jid);
|
|
387
|
+
const { user: ownPnUser } = jidDecode(meId);
|
|
388
|
+
const ownLidUser = meLidUser;
|
|
389
|
+
const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
|
|
390
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
391
|
+
if (isOwnUser && !isExactSenderDevice) {
|
|
392
|
+
msgToEncrypt = dsmMessage;
|
|
393
|
+
logger.debug({ jid, targetUser }, 'Using DSM for own device');
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const bytes = encodeWAMessage(msgToEncrypt);
|
|
397
|
+
const mutexKey = jid;
|
|
398
|
+
const node = await encryptionMutex.mutex(mutexKey, async () => {
|
|
399
|
+
const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
|
|
400
|
+
if (type === 'pkmsg') {
|
|
401
|
+
shouldIncludeDeviceIdentity = true;
|
|
402
|
+
}
|
|
403
|
+
return {
|
|
404
|
+
tag: 'to',
|
|
405
|
+
attrs: { jid },
|
|
406
|
+
content: [
|
|
407
|
+
{
|
|
408
|
+
tag: 'enc',
|
|
409
|
+
attrs: { v: '2', type, ...(extraAttrs || {}) },
|
|
410
|
+
content: ciphertext
|
|
411
|
+
}
|
|
412
|
+
]
|
|
413
|
+
};
|
|
414
|
+
});
|
|
415
|
+
return node;
|
|
416
|
+
}
|
|
417
|
+
catch (err) {
|
|
418
|
+
logger.error({ jid, err }, 'Failed to encrypt for recipient');
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
765
421
|
});
|
|
766
|
-
const
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
422
|
+
const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
|
|
423
|
+
if (recipientJids.length > 0 && nodes.length === 0) {
|
|
424
|
+
throw new Boom('All encryptions failed', { statusCode: 500 });
|
|
425
|
+
}
|
|
426
|
+
return { nodes, shouldIncludeDeviceIdentity };
|
|
427
|
+
};
|
|
428
|
+
const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
|
|
429
|
+
const meId = assertMeId(authState.creds);
|
|
430
|
+
const meLid = authState.creds.me?.lid;
|
|
431
|
+
const isRetryResend = Boolean(participant?.jid);
|
|
432
|
+
let shouldIncludeDeviceIdentity = isRetryResend;
|
|
433
|
+
const statusJid = 'status@broadcast';
|
|
434
|
+
const { user, server } = jidDecode(jid);
|
|
435
|
+
const isGroup = server === 'g.us';
|
|
436
|
+
const isStatus = jid === statusJid;
|
|
437
|
+
const isLid = server === 'lid';
|
|
438
|
+
const isNewsletter = server === 'newsletter';
|
|
439
|
+
const isGroupOrStatus = isGroup || isStatus;
|
|
440
|
+
const finalJid = jid;
|
|
441
|
+
msgId = msgId || generateMessageIDV2(meId);
|
|
442
|
+
useUserDevicesCache = useUserDevicesCache !== false;
|
|
443
|
+
useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
|
|
444
|
+
const participants = [];
|
|
445
|
+
const destinationJid = !isStatus ? finalJid : statusJid;
|
|
446
|
+
const binaryNodeContent = [];
|
|
447
|
+
const devices = [];
|
|
448
|
+
let reportingMessage;
|
|
449
|
+
const meMsg = {
|
|
450
|
+
deviceSentMessage: {
|
|
451
|
+
destinationJid,
|
|
452
|
+
message
|
|
453
|
+
},
|
|
454
|
+
messageContextInfo: message.messageContextInfo
|
|
775
455
|
};
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
456
|
+
const extraAttrs = {};
|
|
457
|
+
if (participant) {
|
|
458
|
+
if (!isGroup && !isStatus) {
|
|
459
|
+
additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
|
|
460
|
+
}
|
|
461
|
+
const { user, device } = jidDecode(participant.jid);
|
|
462
|
+
devices.push({
|
|
463
|
+
user,
|
|
464
|
+
device,
|
|
465
|
+
jid: participant.jid
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
await authState.keys.transaction(async () => {
|
|
469
|
+
const mediaType = getMediaType(message);
|
|
470
|
+
if (mediaType) {
|
|
471
|
+
extraAttrs['mediatype'] = mediaType;
|
|
472
|
+
}
|
|
473
|
+
if (isNewsletter) {
|
|
474
|
+
const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
|
|
475
|
+
const bytes = encodeNewsletterMessage(patched);
|
|
476
|
+
binaryNodeContent.push({
|
|
477
|
+
tag: 'plaintext',
|
|
478
|
+
attrs: {},
|
|
479
|
+
content: bytes
|
|
480
|
+
});
|
|
481
|
+
const stanza = {
|
|
482
|
+
tag: 'message',
|
|
483
|
+
attrs: {
|
|
484
|
+
to: jid,
|
|
485
|
+
id: msgId,
|
|
486
|
+
type: getMessageType(message),
|
|
487
|
+
...(additionalAttributes || {})
|
|
488
|
+
},
|
|
489
|
+
content: binaryNodeContent
|
|
490
|
+
};
|
|
491
|
+
logger.debug({ msgId }, `sending newsletter message to ${jid}`);
|
|
492
|
+
await sendNode(stanza);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
|
|
496
|
+
extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
|
|
497
|
+
}
|
|
498
|
+
if (isGroupOrStatus && !isRetryResend) {
|
|
499
|
+
const [groupData, senderKeyMap] = await Promise.all([
|
|
500
|
+
(async () => {
|
|
501
|
+
let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
|
|
502
|
+
if (groupData && Array.isArray(groupData?.participants)) {
|
|
503
|
+
logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
|
|
504
|
+
}
|
|
505
|
+
else if (!isStatus) {
|
|
506
|
+
groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
|
|
507
|
+
}
|
|
508
|
+
return groupData;
|
|
509
|
+
})(),
|
|
510
|
+
(async () => {
|
|
511
|
+
if (!participant && !isStatus) {
|
|
512
|
+
// what if sender memory is less accurate than the cached metadata
|
|
513
|
+
// on participant change in group, we should do sender memory manipulation
|
|
514
|
+
const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
|
|
515
|
+
return result[jid] || {};
|
|
516
|
+
}
|
|
517
|
+
return {};
|
|
518
|
+
})()
|
|
519
|
+
]);
|
|
520
|
+
const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
|
|
521
|
+
if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
|
|
522
|
+
additionalAttributes = {
|
|
523
|
+
...additionalAttributes,
|
|
524
|
+
expiration: groupData.ephemeralDuration.toString()
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
if (isStatus && statusJidList) {
|
|
528
|
+
participantsList.push(...statusJidList);
|
|
529
|
+
}
|
|
530
|
+
const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
|
|
531
|
+
devices.push(...additionalDevices);
|
|
532
|
+
if (isGroup) {
|
|
533
|
+
additionalAttributes = {
|
|
534
|
+
...additionalAttributes,
|
|
535
|
+
addressing_mode: groupData?.addressingMode || 'lid'
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
const patched = await patchMessageBeforeSending(message);
|
|
539
|
+
if (Array.isArray(patched)) {
|
|
540
|
+
throw new Boom('Per-jid patching is not supported in groups');
|
|
541
|
+
}
|
|
542
|
+
const bytes = encodeWAMessage(patched);
|
|
543
|
+
reportingMessage = patched;
|
|
544
|
+
const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
|
|
545
|
+
const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
|
|
546
|
+
const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
|
|
547
|
+
group: destinationJid,
|
|
548
|
+
data: bytes,
|
|
549
|
+
meId: groupSenderIdentity
|
|
550
|
+
});
|
|
551
|
+
const senderKeyRecipients = [];
|
|
552
|
+
for (const device of devices) {
|
|
553
|
+
const deviceJid = device.jid;
|
|
554
|
+
const hasKey = !!senderKeyMap[deviceJid];
|
|
555
|
+
if ((!hasKey || !!participant) &&
|
|
556
|
+
!isHostedLidUser(deviceJid) &&
|
|
557
|
+
!isHostedPnUser(deviceJid) &&
|
|
558
|
+
device.device !== 99) {
|
|
559
|
+
//todo: revamp all this logic
|
|
560
|
+
// the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
|
|
561
|
+
senderKeyRecipients.push(deviceJid);
|
|
562
|
+
senderKeyMap[deviceJid] = true;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
if (senderKeyRecipients.length) {
|
|
566
|
+
logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
|
|
567
|
+
const senderKeyMsg = {
|
|
568
|
+
senderKeyDistributionMessage: {
|
|
569
|
+
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
570
|
+
groupId: destinationJid
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
const senderKeySessionTargets = senderKeyRecipients;
|
|
574
|
+
await assertSessions(senderKeySessionTargets);
|
|
575
|
+
const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
|
|
576
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
577
|
+
participants.push(...result.nodes);
|
|
578
|
+
}
|
|
579
|
+
binaryNodeContent.push({
|
|
580
|
+
tag: 'enc',
|
|
581
|
+
attrs: { v: '2', type: 'skmsg', ...extraAttrs },
|
|
582
|
+
content: ciphertext
|
|
583
|
+
});
|
|
584
|
+
await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
|
|
585
|
+
}
|
|
586
|
+
else {
|
|
587
|
+
// ADDRESSING CONSISTENCY: Match own identity to conversation context
|
|
588
|
+
// TODO: investigate if this is true
|
|
589
|
+
let ownId = meId;
|
|
590
|
+
if (isLid && meLid) {
|
|
591
|
+
ownId = meLid;
|
|
592
|
+
logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
|
|
593
|
+
}
|
|
594
|
+
else {
|
|
595
|
+
logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
|
|
596
|
+
}
|
|
597
|
+
const { user: ownUser } = jidDecode(ownId);
|
|
598
|
+
if (!participant) {
|
|
599
|
+
const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
|
|
600
|
+
reportingMessage = Array.isArray(patchedForReporting)
|
|
601
|
+
? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
|
|
602
|
+
: patchedForReporting;
|
|
603
|
+
}
|
|
604
|
+
if (!isRetryResend) {
|
|
605
|
+
const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
606
|
+
devices.push({
|
|
607
|
+
user,
|
|
608
|
+
device: 0,
|
|
609
|
+
jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
|
|
610
|
+
});
|
|
611
|
+
if (user !== ownUser) {
|
|
612
|
+
const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
613
|
+
const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
|
|
614
|
+
devices.push({
|
|
615
|
+
user: ownUserForAddressing,
|
|
616
|
+
device: 0,
|
|
617
|
+
jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
if (additionalAttributes?.['category'] !== 'peer') {
|
|
621
|
+
// Clear placeholders and enumerate actual devices
|
|
622
|
+
devices.length = 0;
|
|
623
|
+
// Use conversation-appropriate sender identity
|
|
624
|
+
const senderIdentity = isLid && meLid
|
|
625
|
+
? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
|
|
626
|
+
: jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
|
|
627
|
+
// Enumerate devices for sender and target with consistent addressing
|
|
628
|
+
const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
|
|
629
|
+
devices.push(...sessionDevices);
|
|
630
|
+
logger.debug({
|
|
631
|
+
deviceCount: devices.length,
|
|
632
|
+
devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
|
|
633
|
+
}, 'Device enumeration complete with unified addressing');
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
const allRecipients = [];
|
|
637
|
+
const meRecipients = [];
|
|
638
|
+
const otherRecipients = [];
|
|
639
|
+
const { user: mePnUser } = jidDecode(meId);
|
|
640
|
+
const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
|
|
641
|
+
for (const { user, jid } of devices) {
|
|
642
|
+
const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
|
|
643
|
+
if (isExactSenderDevice) {
|
|
644
|
+
logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
// Check if this is our device (could match either PN or LID user)
|
|
648
|
+
const isMe = user === mePnUser || user === meLidUser;
|
|
649
|
+
if (isMe) {
|
|
650
|
+
meRecipients.push(jid);
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
otherRecipients.push(jid);
|
|
654
|
+
}
|
|
655
|
+
allRecipients.push(jid);
|
|
656
|
+
}
|
|
657
|
+
await assertSessions(allRecipients);
|
|
658
|
+
const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
|
|
659
|
+
// For own devices: use DSM if available (1:1 chats only)
|
|
660
|
+
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
|
661
|
+
createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
|
|
662
|
+
]);
|
|
663
|
+
participants.push(...meNodes);
|
|
664
|
+
participants.push(...otherNodes);
|
|
665
|
+
if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
|
666
|
+
extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
|
|
667
|
+
}
|
|
668
|
+
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
|
|
669
|
+
}
|
|
670
|
+
if (isRetryResend) {
|
|
671
|
+
const isParticipantLid = isLidUser(participant.jid);
|
|
672
|
+
const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
|
|
673
|
+
let messageToSend = message;
|
|
674
|
+
if (isGroupOrStatus) {
|
|
675
|
+
let groupSenderIdentity;
|
|
676
|
+
if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
|
|
677
|
+
groupSenderIdentity = meLid;
|
|
678
|
+
}
|
|
679
|
+
else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
|
|
680
|
+
groupSenderIdentity = meId;
|
|
681
|
+
}
|
|
682
|
+
if (groupSenderIdentity) {
|
|
683
|
+
try {
|
|
684
|
+
const skdm = await signalRepository.getSenderKeyDistributionMessage({
|
|
685
|
+
group: destinationJid,
|
|
686
|
+
meId: groupSenderIdentity
|
|
687
|
+
});
|
|
688
|
+
messageToSend = {
|
|
689
|
+
...message,
|
|
690
|
+
senderKeyDistributionMessage: {
|
|
691
|
+
groupId: destinationJid,
|
|
692
|
+
axolotlSenderKeyDistributionMessage: skdm
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
catch (err) {
|
|
697
|
+
logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const encodedMessageToSend = isMe
|
|
702
|
+
? encodeWAMessage({
|
|
703
|
+
deviceSentMessage: {
|
|
704
|
+
destinationJid,
|
|
705
|
+
message: messageToSend
|
|
706
|
+
}
|
|
707
|
+
})
|
|
708
|
+
: encodeWAMessage(messageToSend);
|
|
709
|
+
const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
|
|
710
|
+
data: encodedMessageToSend,
|
|
711
|
+
jid: participant.jid
|
|
712
|
+
});
|
|
713
|
+
binaryNodeContent.push({
|
|
714
|
+
tag: 'enc',
|
|
715
|
+
attrs: {
|
|
716
|
+
v: '2',
|
|
717
|
+
type,
|
|
718
|
+
count: participant.count.toString()
|
|
719
|
+
},
|
|
720
|
+
content: encryptedContent
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
if (participants.length) {
|
|
724
|
+
if (additionalAttributes?.['category'] === 'peer') {
|
|
725
|
+
const peerNode = participants[0]?.content?.[0];
|
|
726
|
+
if (peerNode) {
|
|
727
|
+
binaryNodeContent.push(peerNode); // push only enc
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
else {
|
|
731
|
+
binaryNodeContent.push({
|
|
732
|
+
tag: 'participants',
|
|
733
|
+
attrs: {},
|
|
734
|
+
content: participants
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
const stanza = {
|
|
739
|
+
tag: 'message',
|
|
740
|
+
attrs: {
|
|
741
|
+
id: msgId,
|
|
742
|
+
to: destinationJid,
|
|
743
|
+
type: getMessageType(message),
|
|
744
|
+
...(additionalAttributes || {})
|
|
745
|
+
},
|
|
746
|
+
content: binaryNodeContent
|
|
814
747
|
};
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
748
|
+
// if the participant to send to is explicitly specified (generally retry recp)
|
|
749
|
+
// ensure the message is only sent to that person
|
|
750
|
+
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
|
751
|
+
if (participant) {
|
|
752
|
+
if (isJidGroup(destinationJid)) {
|
|
753
|
+
stanza.attrs.to = destinationJid;
|
|
754
|
+
stanza.attrs.participant = participant.jid;
|
|
755
|
+
}
|
|
756
|
+
else if (areJidsSameUser(participant.jid, meId)) {
|
|
757
|
+
stanza.attrs.to = participant.jid;
|
|
758
|
+
stanza.attrs.recipient = destinationJid;
|
|
759
|
+
}
|
|
760
|
+
else {
|
|
761
|
+
stanza.attrs.to = participant.jid;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
else {
|
|
765
|
+
stanza.attrs.to = destinationJid;
|
|
766
|
+
}
|
|
767
|
+
if (shouldIncludeDeviceIdentity) {
|
|
768
|
+
;
|
|
769
|
+
stanza.content.push({
|
|
770
|
+
tag: 'device-identity',
|
|
771
|
+
attrs: {},
|
|
772
|
+
content: encodeSignedDeviceIdentity(authState.creds.account, true)
|
|
773
|
+
});
|
|
774
|
+
logger.debug({ jid }, 'adding device identity');
|
|
775
|
+
}
|
|
776
|
+
if (!isNewsletter &&
|
|
777
|
+
!isRetryResend &&
|
|
778
|
+
reportingMessage?.messageContextInfo?.messageSecret &&
|
|
779
|
+
shouldIncludeReportingToken(reportingMessage)) {
|
|
780
|
+
try {
|
|
781
|
+
const encoded = encodeWAMessage(reportingMessage);
|
|
782
|
+
const reportingKey = {
|
|
783
|
+
id: msgId,
|
|
784
|
+
fromMe: true,
|
|
785
|
+
remoteJid: destinationJid,
|
|
786
|
+
participant: participant?.jid
|
|
787
|
+
};
|
|
788
|
+
const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
|
|
789
|
+
if (reportingNode) {
|
|
790
|
+
;
|
|
791
|
+
stanza.content.push(reportingNode);
|
|
792
|
+
logger.trace({ jid }, 'added reporting token to message');
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
catch (error) {
|
|
796
|
+
logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
// WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
|
|
800
|
+
const isPeerMessage = additionalAttributes?.['category'] === 'peer';
|
|
801
|
+
const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
|
|
802
|
+
// Resolve destination to LID for tctoken storage — matches Signal session key pattern
|
|
803
|
+
const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
|
|
804
|
+
const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
|
|
805
|
+
const existingTokenEntry = contactTcTokenData[tcTokenJid];
|
|
806
|
+
let tcTokenBuffer = existingTokenEntry?.token;
|
|
807
|
+
// Treat expired tokens the same as missing — clear from cache
|
|
808
|
+
if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
|
|
809
|
+
logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
|
|
810
|
+
tcTokenBuffer = undefined;
|
|
811
|
+
// Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
|
|
812
|
+
const cleared = existingTokenEntry?.senderTimestamp !== undefined
|
|
813
|
+
? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
|
|
814
|
+
: null;
|
|
815
|
+
try {
|
|
816
|
+
await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
|
|
817
|
+
}
|
|
818
|
+
catch (err) {
|
|
819
|
+
logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
|
|
823
|
+
;
|
|
824
|
+
stanza.content.push({
|
|
825
|
+
tag: 'tctoken',
|
|
826
|
+
attrs: {},
|
|
827
|
+
content: tcTokenBuffer
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
if (additionalNodes && additionalNodes.length > 0) {
|
|
831
|
+
;
|
|
832
|
+
stanza.content.push(...additionalNodes);
|
|
833
|
+
}
|
|
834
|
+
logger.debug({ msgId }, `sending message to ${participants.length} devices`);
|
|
835
|
+
await sendNode(stanza);
|
|
836
|
+
// Fire-and-forget: issue our token to the contact AFTER message send.
|
|
837
|
+
// WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
|
|
838
|
+
const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
|
|
839
|
+
const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
|
|
840
|
+
if (is1on1Send &&
|
|
841
|
+
!isProtocolMsg &&
|
|
842
|
+
!isBotOrPSA &&
|
|
843
|
+
shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
|
|
844
|
+
!inFlightTcTokenIssuance.has(tcTokenJid)) {
|
|
845
|
+
inFlightTcTokenIssuance.add(tcTokenJid);
|
|
846
|
+
const issueTimestamp = unixTimestampSeconds();
|
|
847
|
+
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
|
|
848
|
+
resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
|
|
849
|
+
.then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
|
|
850
|
+
.then(async (result) => {
|
|
851
|
+
await storeTcTokensFromIqResult({
|
|
852
|
+
result,
|
|
853
|
+
fallbackJid: tcTokenJid,
|
|
854
|
+
keys: authState.keys,
|
|
855
|
+
getLIDForPN
|
|
856
|
+
});
|
|
857
|
+
const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
|
|
858
|
+
const currentEntry = currentData[tcTokenJid];
|
|
859
|
+
const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
|
|
860
|
+
await authState.keys.set({
|
|
861
|
+
tctoken: {
|
|
862
|
+
[tcTokenJid]: {
|
|
863
|
+
token: Buffer.alloc(0),
|
|
864
|
+
...currentEntry,
|
|
865
|
+
senderTimestamp: issueTimestamp
|
|
866
|
+
},
|
|
867
|
+
...indexWrite
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
})
|
|
871
|
+
.catch(err => {
|
|
872
|
+
logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
|
|
873
|
+
})
|
|
874
|
+
.finally(() => {
|
|
875
|
+
inFlightTcTokenIssuance.delete(tcTokenJid);
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
// Add message to retry cache if enabled
|
|
879
|
+
if (messageRetryManager && !participant) {
|
|
880
|
+
messageRetryManager.addRecentMessage(destinationJid, msgId, message);
|
|
881
|
+
}
|
|
882
|
+
}, meId);
|
|
883
|
+
return msgId;
|
|
884
|
+
};
|
|
885
|
+
const getMessageType = (message) => {
|
|
886
|
+
const normalizedMessage = normalizeMessageContent(message);
|
|
887
|
+
if (!normalizedMessage)
|
|
888
|
+
return 'text';
|
|
889
|
+
if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
|
|
890
|
+
return 'reaction';
|
|
818
891
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
892
|
+
if (normalizedMessage.pollCreationMessage ||
|
|
893
|
+
normalizedMessage.pollCreationMessageV2 ||
|
|
894
|
+
normalizedMessage.pollCreationMessageV3 ||
|
|
895
|
+
normalizedMessage.pollUpdateMessage) {
|
|
896
|
+
return 'poll';
|
|
822
897
|
}
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
const groupAddressingMode = groupData?.addressingMode || (isLid ? 'lid' : 'pn');
|
|
826
|
-
const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
|
|
827
|
-
const {
|
|
828
|
-
ciphertext,
|
|
829
|
-
senderKeyDistributionMessage
|
|
830
|
-
} = await signalRepository.encryptGroupMessage({
|
|
831
|
-
group: destinationJid,
|
|
832
|
-
data: bytes,
|
|
833
|
-
meId: groupSenderIdentity
|
|
834
|
-
});
|
|
835
|
-
const senderKeyJids = [];
|
|
836
|
-
// ensure a connection is established with every device
|
|
837
|
-
for (const device of devices) {
|
|
838
|
-
// This preserves the LID migration results from getUSyncDevices
|
|
839
|
-
const deviceJid = device.wireJid;
|
|
840
|
-
const hasKey = !!senderKeyMap[deviceJid];
|
|
841
|
-
if (!hasKey || !!participant) {
|
|
842
|
-
senderKeyJids.push(deviceJid);
|
|
843
|
-
// store that this person has had the sender keys sent to them
|
|
844
|
-
senderKeyMap[deviceJid] = true;
|
|
845
|
-
}
|
|
898
|
+
if (normalizedMessage.eventMessage) {
|
|
899
|
+
return 'event';
|
|
846
900
|
}
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
if (senderKeyJids.length) {
|
|
850
|
-
logger.debug({
|
|
851
|
-
senderKeyJids
|
|
852
|
-
}, 'sending new sender key');
|
|
853
|
-
const senderKeyMsg = {
|
|
854
|
-
senderKeyDistributionMessage: {
|
|
855
|
-
axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
|
|
856
|
-
groupId: destinationJid
|
|
857
|
-
}
|
|
858
|
-
};
|
|
859
|
-
await assertSessions(senderKeyJids, false);
|
|
860
|
-
const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
|
|
861
|
-
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
|
|
862
|
-
participants.push(...result.nodes);
|
|
901
|
+
if (getMediaType(normalizedMessage) !== '') {
|
|
902
|
+
return 'media';
|
|
863
903
|
}
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
},
|
|
870
|
-
content: ciphertext
|
|
871
|
-
});
|
|
872
|
-
await authState.keys.set({
|
|
873
|
-
'sender-key-memory': {
|
|
874
|
-
[jid]: senderKeyMap
|
|
875
|
-
}
|
|
876
|
-
});
|
|
877
|
-
} else {
|
|
878
|
-
const {
|
|
879
|
-
user: ownUser
|
|
880
|
-
} = (0, _index5.jidDecode)(ownId);
|
|
881
|
-
if (!participant) {
|
|
882
|
-
const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
883
|
-
devices.push({
|
|
884
|
-
user,
|
|
885
|
-
device: 0,
|
|
886
|
-
wireJid: (0, _index5.jidEncode)(user, targetUserServer, 0)
|
|
887
|
-
});
|
|
888
|
-
// Own user matches conversation addressing mode
|
|
889
|
-
if (user !== ownUser) {
|
|
890
|
-
const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
|
|
891
|
-
const ownUserForAddressing = isLid && meLid ? (0, _index5.jidDecode)(meLid).user : (0, _index5.jidDecode)(meId).user;
|
|
892
|
-
devices.push({
|
|
893
|
-
user: ownUserForAddressing,
|
|
894
|
-
device: 0,
|
|
895
|
-
wireJid: (0, _index5.jidEncode)(ownUserForAddressing, ownUserServer, 0)
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
if (additionalAttributes?.['category'] !== 'peer') {
|
|
899
|
-
// Clear placeholders and enumerate actual devices
|
|
900
|
-
devices.length = 0;
|
|
901
|
-
// Use conversation-appropriate sender identity
|
|
902
|
-
const senderIdentity = isLid && meLid ? (0, _index5.jidEncode)((0, _index5.jidDecode)(meLid)?.user, 'lid', undefined) : (0, _index5.jidEncode)((0, _index5.jidDecode)(meId)?.user, 's.whatsapp.net', undefined);
|
|
903
|
-
// Enumerate devices for sender and target with consistent addressing
|
|
904
|
-
const sessionDevices = await getUSyncDevices([senderIdentity, jid], false, false);
|
|
905
|
-
devices.push(...sessionDevices);
|
|
906
|
-
logger.debug({
|
|
907
|
-
deviceCount: devices.length,
|
|
908
|
-
devices: devices.map(d => `${d.user}:${d.device}@${(0, _index5.jidDecode)(d.wireJid)?.server}`)
|
|
909
|
-
}, 'Device enumeration complete with unified addressing');
|
|
910
|
-
}
|
|
904
|
+
return 'text';
|
|
905
|
+
};
|
|
906
|
+
const getMediaType = (message) => {
|
|
907
|
+
if (message.imageMessage) {
|
|
908
|
+
return 'image';
|
|
911
909
|
}
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
const otherJids = [];
|
|
915
|
-
const {
|
|
916
|
-
user: mePnUser
|
|
917
|
-
} = (0, _index5.jidDecode)(meId);
|
|
918
|
-
const {
|
|
919
|
-
user: meLidUser
|
|
920
|
-
} = meLid ? (0, _index5.jidDecode)(meLid) : {
|
|
921
|
-
user: null
|
|
922
|
-
};
|
|
923
|
-
for (const {
|
|
924
|
-
user,
|
|
925
|
-
wireJid
|
|
926
|
-
} of devices) {
|
|
927
|
-
const isExactSenderDevice = wireJid === meId || meLid && wireJid === meLid;
|
|
928
|
-
if (isExactSenderDevice) {
|
|
929
|
-
logger.debug({
|
|
930
|
-
wireJid,
|
|
931
|
-
meId,
|
|
932
|
-
meLid
|
|
933
|
-
}, 'Skipping exact sender device (whatsmeow pattern)');
|
|
934
|
-
continue;
|
|
935
|
-
}
|
|
936
|
-
// Check if this is our device (could match either PN or LID user)
|
|
937
|
-
const isMe = user === mePnUser || meLidUser && user === meLidUser;
|
|
938
|
-
const jid = wireJid;
|
|
939
|
-
if (isMe) {
|
|
940
|
-
meJids.push(jid);
|
|
941
|
-
} else {
|
|
942
|
-
otherJids.push(jid);
|
|
943
|
-
}
|
|
944
|
-
allJids.push(jid);
|
|
910
|
+
else if (message.videoMessage) {
|
|
911
|
+
return message.videoMessage.gifPlayback ? 'gif' : 'video';
|
|
945
912
|
}
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
nodes: meNodes,
|
|
949
|
-
shouldIncludeDeviceIdentity: s1
|
|
950
|
-
}, {
|
|
951
|
-
nodes: otherNodes,
|
|
952
|
-
shouldIncludeDeviceIdentity: s2
|
|
953
|
-
}] = await Promise.all([
|
|
954
|
-
// For own devices: use DSM if available (1:1 chats only)
|
|
955
|
-
createParticipantNodes(meJids, meMsg || message, extraAttrs), createParticipantNodes(otherJids, message, extraAttrs, meMsg)]);
|
|
956
|
-
participants.push(...meNodes);
|
|
957
|
-
participants.push(...otherNodes);
|
|
958
|
-
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
|
|
959
|
-
}
|
|
960
|
-
if (participants.length) {
|
|
961
|
-
if (additionalAttributes?.['category'] === 'peer') {
|
|
962
|
-
const peerNode = participants[0]?.content?.[0];
|
|
963
|
-
if (peerNode) {
|
|
964
|
-
binaryNodeContent.push(peerNode); // push only enc
|
|
965
|
-
}
|
|
966
|
-
} else {
|
|
967
|
-
binaryNodeContent.push({
|
|
968
|
-
tag: 'participants',
|
|
969
|
-
attrs: {},
|
|
970
|
-
content: participants
|
|
971
|
-
});
|
|
913
|
+
else if (message.audioMessage) {
|
|
914
|
+
return message.audioMessage.ptt ? 'ptt' : 'audio';
|
|
972
915
|
}
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
tag: 'message',
|
|
976
|
-
attrs: {
|
|
977
|
-
id: msgId,
|
|
978
|
-
to: destinationJid,
|
|
979
|
-
type: getMessageType(message),
|
|
980
|
-
...(additionalAttributes || {})
|
|
981
|
-
},
|
|
982
|
-
content: binaryNodeContent
|
|
983
|
-
};
|
|
984
|
-
// if the participant to send to is explicitly specified (generally retry recp)
|
|
985
|
-
// ensure the message is only sent to that person
|
|
986
|
-
// if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
|
|
987
|
-
if (participant) {
|
|
988
|
-
if ((0, _index5.isJidGroup)(destinationJid)) {
|
|
989
|
-
stanza.attrs.to = destinationJid;
|
|
990
|
-
stanza.attrs.participant = participant.jid;
|
|
991
|
-
} else if ((0, _index5.areJidsSameUser)(participant.jid, meId)) {
|
|
992
|
-
stanza.attrs.to = participant.jid;
|
|
993
|
-
stanza.attrs.recipient = destinationJid;
|
|
994
|
-
} else {
|
|
995
|
-
stanza.attrs.to = participant.jid;
|
|
916
|
+
else if (message.contactMessage) {
|
|
917
|
+
return 'vcard';
|
|
996
918
|
}
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
}
|
|
1000
|
-
if (shouldIncludeDeviceIdentity) {
|
|
1001
|
-
;
|
|
1002
|
-
stanza.content.push({
|
|
1003
|
-
tag: 'device-identity',
|
|
1004
|
-
attrs: {},
|
|
1005
|
-
content: (0, _index4.encodeSignedDeviceIdentity)(authState.creds.account, true)
|
|
1006
|
-
});
|
|
1007
|
-
logger.debug({
|
|
1008
|
-
jid
|
|
1009
|
-
}, 'adding device identity');
|
|
1010
|
-
}
|
|
1011
|
-
if (additionalNodes && additionalNodes.length > 0) {
|
|
1012
|
-
;
|
|
1013
|
-
stanza.content.push(...additionalNodes);
|
|
1014
|
-
}
|
|
1015
|
-
logger.debug({
|
|
1016
|
-
msgId
|
|
1017
|
-
}, `sending message to ${participants.length} devices`);
|
|
1018
|
-
await sendNode(stanza);
|
|
1019
|
-
// Add message to retry cache if enabled
|
|
1020
|
-
if (messageRetryManager && !participant) {
|
|
1021
|
-
messageRetryManager.addRecentMessage(destinationJid, msgId, message);
|
|
1022
|
-
}
|
|
1023
|
-
}, meId);
|
|
1024
|
-
return msgId;
|
|
1025
|
-
};
|
|
1026
|
-
const getMessageType = message => {
|
|
1027
|
-
if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
|
|
1028
|
-
return 'poll';
|
|
1029
|
-
}
|
|
1030
|
-
if (message.eventMessage) {
|
|
1031
|
-
return 'event';
|
|
1032
|
-
}
|
|
1033
|
-
return 'text';
|
|
1034
|
-
};
|
|
1035
|
-
const getMediaType = message => {
|
|
1036
|
-
if (message.imageMessage) {
|
|
1037
|
-
return 'image';
|
|
1038
|
-
} else if (message.videoMessage) {
|
|
1039
|
-
return message.videoMessage.gifPlayback ? 'gif' : 'video';
|
|
1040
|
-
} else if (message.audioMessage) {
|
|
1041
|
-
return message.audioMessage.ptt ? 'ptt' : 'audio';
|
|
1042
|
-
} else if (message.contactMessage) {
|
|
1043
|
-
return 'vcard';
|
|
1044
|
-
} else if (message.documentMessage) {
|
|
1045
|
-
return 'document';
|
|
1046
|
-
} else if (message.contactsArrayMessage) {
|
|
1047
|
-
return 'contact_array';
|
|
1048
|
-
} else if (message.liveLocationMessage) {
|
|
1049
|
-
return 'livelocation';
|
|
1050
|
-
} else if (message.stickerMessage) {
|
|
1051
|
-
return 'sticker';
|
|
1052
|
-
} else if (message.listMessage) {
|
|
1053
|
-
return 'list';
|
|
1054
|
-
} else if (message.listResponseMessage) {
|
|
1055
|
-
return 'list_response';
|
|
1056
|
-
} else if (message.buttonsResponseMessage) {
|
|
1057
|
-
return 'buttons_response';
|
|
1058
|
-
} else if (message.orderMessage) {
|
|
1059
|
-
return 'order';
|
|
1060
|
-
} else if (message.productMessage) {
|
|
1061
|
-
return 'product';
|
|
1062
|
-
} else if (message.interactiveResponseMessage) {
|
|
1063
|
-
return 'native_flow_response';
|
|
1064
|
-
} else if (message.groupInviteMessage) {
|
|
1065
|
-
return 'url';
|
|
1066
|
-
}
|
|
1067
|
-
};
|
|
1068
|
-
const getPrivacyTokens = async jids => {
|
|
1069
|
-
const t = (0, _index4.unixTimestampSeconds)().toString();
|
|
1070
|
-
const result = await query({
|
|
1071
|
-
tag: 'iq',
|
|
1072
|
-
attrs: {
|
|
1073
|
-
to: _index5.S_WHATSAPP_NET,
|
|
1074
|
-
type: 'set',
|
|
1075
|
-
xmlns: 'privacy'
|
|
1076
|
-
},
|
|
1077
|
-
content: [{
|
|
1078
|
-
tag: 'tokens',
|
|
1079
|
-
attrs: {},
|
|
1080
|
-
content: jids.map(jid => ({
|
|
1081
|
-
tag: 'token',
|
|
1082
|
-
attrs: {
|
|
1083
|
-
jid: (0, _index5.jidNormalizedUser)(jid),
|
|
1084
|
-
t,
|
|
1085
|
-
type: 'trusted_contact'
|
|
1086
|
-
}
|
|
1087
|
-
}))
|
|
1088
|
-
}]
|
|
1089
|
-
});
|
|
1090
|
-
return result;
|
|
1091
|
-
};
|
|
1092
|
-
const waUploadToServer = (0, _index4.getWAUploadToServer)(config, refreshMediaConn);
|
|
1093
|
-
const extendedMessages = (0, _extendedMessages.makeExtendedMessageHandlers)({
|
|
1094
|
-
generateWAMessage: _index4.generateWAMessage,
|
|
1095
|
-
generateWAMessageContent: _index4.generateWAMessageContent,
|
|
1096
|
-
generateWAMessageFromContent: _index4.generateWAMessageFromContent,
|
|
1097
|
-
generateMessageID: _index4.generateMessageID,
|
|
1098
|
-
prepareWAMessageMedia: _index4.prepareWAMessageMedia,
|
|
1099
|
-
waUploadToServer,
|
|
1100
|
-
relayMessage
|
|
1101
|
-
});
|
|
1102
|
-
const waitForMsgMediaUpdate = (0, _index4.bindWaitForEvent)(ev, 'messages.media-update');
|
|
1103
|
-
return {
|
|
1104
|
-
...sock,
|
|
1105
|
-
getPrivacyTokens,
|
|
1106
|
-
assertSessions,
|
|
1107
|
-
relayMessage,
|
|
1108
|
-
sendReceipt,
|
|
1109
|
-
sendReceipts,
|
|
1110
|
-
readMessages,
|
|
1111
|
-
refreshMediaConn,
|
|
1112
|
-
waUploadToServer,
|
|
1113
|
-
fetchPrivacySettings,
|
|
1114
|
-
sendPeerDataOperationMessage,
|
|
1115
|
-
createParticipantNodes,
|
|
1116
|
-
getUSyncDevices,
|
|
1117
|
-
messageRetryManager,
|
|
1118
|
-
updateMediaMessage: async message => {
|
|
1119
|
-
const content = (0, _index4.assertMediaContent)(message.message);
|
|
1120
|
-
const mediaKey = content.mediaKey;
|
|
1121
|
-
const meId = authState.creds.me.id;
|
|
1122
|
-
const node = await (0, _index4.encryptMediaRetryRequest)(message.key, mediaKey, meId);
|
|
1123
|
-
let error = undefined;
|
|
1124
|
-
await Promise.all([sendNode(node), waitForMsgMediaUpdate(async update => {
|
|
1125
|
-
const result = update.find(c => c.key.id === message.key.id);
|
|
1126
|
-
if (result) {
|
|
1127
|
-
if (result.error) {
|
|
1128
|
-
error = result.error;
|
|
1129
|
-
} else {
|
|
1130
|
-
try {
|
|
1131
|
-
const media = await (0, _index4.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
|
|
1132
|
-
if (media.result !== _index.proto.MediaRetryNotification.ResultType.SUCCESS) {
|
|
1133
|
-
const resultStr = _index.proto.MediaRetryNotification.ResultType[media.result];
|
|
1134
|
-
throw new _boom.Boom(`Media re-upload failed by device (${resultStr})`, {
|
|
1135
|
-
data: media,
|
|
1136
|
-
statusCode: (0, _index4.getStatusCodeForMediaRetry)(media.result) || 404
|
|
1137
|
-
});
|
|
1138
|
-
}
|
|
1139
|
-
content.directPath = media.directPath;
|
|
1140
|
-
content.url = (0, _index4.getUrlFromDirectPath)(content.directPath);
|
|
1141
|
-
logger.debug({
|
|
1142
|
-
directPath: media.directPath,
|
|
1143
|
-
key: result.key
|
|
1144
|
-
}, 'media update successful');
|
|
1145
|
-
} catch (err) {
|
|
1146
|
-
error = err;
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
return true;
|
|
919
|
+
else if (message.documentMessage) {
|
|
920
|
+
return 'document';
|
|
1150
921
|
}
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
throw error;
|
|
1154
|
-
}
|
|
1155
|
-
ev.emit('messages.update', [{
|
|
1156
|
-
key: message.key,
|
|
1157
|
-
update: {
|
|
1158
|
-
message: message.message
|
|
922
|
+
else if (message.contactsArrayMessage) {
|
|
923
|
+
return 'contact_array';
|
|
1159
924
|
}
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
switch (extendedType) {
|
|
1169
|
-
case 'PAYMENT':
|
|
1170
|
-
{
|
|
1171
|
-
const paymentContent = await extendedMessages.handlePayment(content, options.quoted);
|
|
1172
|
-
await relayMessage(jid, paymentContent, {
|
|
1173
|
-
messageId: msgId
|
|
1174
|
-
});
|
|
1175
|
-
return {
|
|
1176
|
-
key: {
|
|
1177
|
-
id: msgId,
|
|
1178
|
-
remoteJid: jid,
|
|
1179
|
-
fromMe: true
|
|
1180
|
-
},
|
|
1181
|
-
message: paymentContent
|
|
1182
|
-
};
|
|
1183
|
-
}
|
|
1184
|
-
case 'INTERACTIVE':
|
|
1185
|
-
{
|
|
1186
|
-
const interactiveContent = await extendedMessages.buildInteractiveContent(content, options);
|
|
1187
|
-
const interactiveMsg = (0, _index4.generateWAMessageFromContent)(jid, interactiveContent, {
|
|
1188
|
-
quoted: options.quoted,
|
|
1189
|
-
userJid
|
|
1190
|
-
});
|
|
1191
|
-
await relayMessage(jid, interactiveMsg.message, {
|
|
1192
|
-
messageId: interactiveMsg.key.id
|
|
1193
|
-
});
|
|
1194
|
-
return interactiveMsg;
|
|
1195
|
-
}
|
|
1196
|
-
case 'ALBUM':
|
|
1197
|
-
return await extendedMessages.sendAlbumMessage(jid, content, options.quoted);
|
|
1198
|
-
case 'POLL_RESULT':
|
|
1199
|
-
return await extendedMessages.sendPollResultMessage(jid, content, options.quoted);
|
|
1200
|
-
case 'GROUP_STORY':
|
|
1201
|
-
return await extendedMessages.sendGroupStoryMessage(jid, content, options.quoted);
|
|
925
|
+
else if (message.liveLocationMessage) {
|
|
926
|
+
return 'livelocation';
|
|
927
|
+
}
|
|
928
|
+
else if (message.stickerMessage) {
|
|
929
|
+
return 'sticker';
|
|
930
|
+
}
|
|
931
|
+
else if (message.listMessage) {
|
|
932
|
+
return 'list';
|
|
1202
933
|
}
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
934
|
+
else if (message.listResponseMessage) {
|
|
935
|
+
return 'list_response';
|
|
936
|
+
}
|
|
937
|
+
else if (message.buttonsResponseMessage) {
|
|
938
|
+
return 'buttons_response';
|
|
939
|
+
}
|
|
940
|
+
else if (message.orderMessage) {
|
|
941
|
+
return 'order';
|
|
942
|
+
}
|
|
943
|
+
else if (message.productMessage) {
|
|
944
|
+
return 'product';
|
|
945
|
+
}
|
|
946
|
+
else if (message.interactiveResponseMessage) {
|
|
947
|
+
return 'native_flow_response';
|
|
948
|
+
}
|
|
949
|
+
else if (message.groupInviteMessage) {
|
|
950
|
+
return 'url';
|
|
951
|
+
}
|
|
952
|
+
return '';
|
|
953
|
+
};
|
|
954
|
+
const issuePrivacyTokens = async (jids, timestamp) => {
|
|
955
|
+
const t = (timestamp ?? unixTimestampSeconds()).toString();
|
|
956
|
+
const result = await query({
|
|
957
|
+
tag: 'iq',
|
|
958
|
+
attrs: {
|
|
959
|
+
to: S_WHATSAPP_NET,
|
|
960
|
+
type: 'set',
|
|
961
|
+
xmlns: 'privacy'
|
|
1219
962
|
},
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
963
|
+
content: [
|
|
964
|
+
{
|
|
965
|
+
tag: 'tokens',
|
|
966
|
+
attrs: {},
|
|
967
|
+
content: jids.map(jid => ({
|
|
968
|
+
tag: 'token',
|
|
969
|
+
attrs: {
|
|
970
|
+
jid: jidNormalizedUser(jid),
|
|
971
|
+
t,
|
|
972
|
+
type: 'trusted_contact'
|
|
973
|
+
}
|
|
974
|
+
}))
|
|
975
|
+
}
|
|
976
|
+
]
|
|
1231
977
|
});
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
// required for delete
|
|
1240
|
-
if (isDeleteMsg) {
|
|
1241
|
-
// if the chat is a group, and I am not the author, then delete the message as an admin
|
|
1242
|
-
if ((0, _index5.isJidGroup)(content.delete?.remoteJid) && !content.delete?.fromMe) {
|
|
1243
|
-
additionalAttributes.edit = '8';
|
|
1244
|
-
} else {
|
|
1245
|
-
additionalAttributes.edit = '7';
|
|
1246
|
-
}
|
|
1247
|
-
} else if (isEditMsg) {
|
|
1248
|
-
additionalAttributes.edit = '1';
|
|
1249
|
-
} else if (isPinMsg) {
|
|
1250
|
-
additionalAttributes.edit = '2';
|
|
1251
|
-
} else if (isPollMessage) {
|
|
1252
|
-
additionalNodes.push({
|
|
1253
|
-
tag: 'meta',
|
|
1254
|
-
attrs: {
|
|
1255
|
-
polltype: 'creation'
|
|
1256
|
-
}
|
|
1257
|
-
});
|
|
1258
|
-
} else if (isEventMsg) {
|
|
1259
|
-
additionalNodes.push({
|
|
1260
|
-
tag: 'meta',
|
|
1261
|
-
attrs: {
|
|
1262
|
-
event_type: 'creation'
|
|
1263
|
-
}
|
|
1264
|
-
});
|
|
978
|
+
return result;
|
|
979
|
+
};
|
|
980
|
+
const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
|
|
981
|
+
const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
|
|
982
|
+
registerSocketEndHandler(() => {
|
|
983
|
+
if (!config.userDevicesCache && userDevicesCache.close) {
|
|
984
|
+
userDevicesCache.close();
|
|
1265
985
|
}
|
|
1266
|
-
|
|
1267
|
-
|
|
986
|
+
mediaConn = undefined;
|
|
987
|
+
if (messageRetryManager) {
|
|
988
|
+
messageRetryManager.clear();
|
|
1268
989
|
}
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
990
|
+
});
|
|
991
|
+
return {
|
|
992
|
+
...sock,
|
|
993
|
+
userDevicesCache,
|
|
994
|
+
devicesMutex,
|
|
995
|
+
issuePrivacyTokens,
|
|
996
|
+
assertSessions,
|
|
997
|
+
relayMessage,
|
|
998
|
+
sendReceipt,
|
|
999
|
+
sendReceipts,
|
|
1000
|
+
readMessages,
|
|
1001
|
+
refreshMediaConn,
|
|
1002
|
+
// Function (not getter) so the spread in chats.ts preserves the live closure binding.
|
|
1003
|
+
getMediaHost: () => mediaHost,
|
|
1004
|
+
waUploadToServer,
|
|
1005
|
+
fetchPrivacySettings,
|
|
1006
|
+
sendPeerDataOperationMessage,
|
|
1007
|
+
createParticipantNodes,
|
|
1008
|
+
getUSyncDevices,
|
|
1009
|
+
messageRetryManager,
|
|
1010
|
+
updateMemberLabel,
|
|
1011
|
+
updateMediaMessage: async (message) => {
|
|
1012
|
+
const content = assertMediaContent(message.message);
|
|
1013
|
+
const mediaKey = content.mediaKey;
|
|
1014
|
+
const meId = authState.creds.me.id;
|
|
1015
|
+
const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
|
|
1016
|
+
let error = undefined;
|
|
1017
|
+
await Promise.all([
|
|
1018
|
+
sendNode(node),
|
|
1019
|
+
waitForMsgMediaUpdate(async (update) => {
|
|
1020
|
+
const result = update.find(c => c.key.id === message.key.id);
|
|
1021
|
+
if (result) {
|
|
1022
|
+
if (result.error) {
|
|
1023
|
+
error = result.error;
|
|
1024
|
+
}
|
|
1025
|
+
else {
|
|
1026
|
+
try {
|
|
1027
|
+
const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
|
|
1028
|
+
if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
|
|
1029
|
+
const resultStr = proto.MediaRetryNotification.ResultType[media.result];
|
|
1030
|
+
throw new Boom(`Media re-upload failed by device (${resultStr})`, {
|
|
1031
|
+
data: media,
|
|
1032
|
+
statusCode: getStatusCodeForMediaRetry(media.result) || 404
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
content.directPath = media.directPath;
|
|
1036
|
+
content.url = getUrlFromDirectPath(content.directPath, mediaHost);
|
|
1037
|
+
logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
|
|
1038
|
+
}
|
|
1039
|
+
catch (err) {
|
|
1040
|
+
error = err;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
return true;
|
|
1044
|
+
}
|
|
1045
|
+
})
|
|
1046
|
+
]);
|
|
1047
|
+
if (error) {
|
|
1048
|
+
throw error;
|
|
1049
|
+
}
|
|
1050
|
+
ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
|
|
1051
|
+
return message;
|
|
1052
|
+
},
|
|
1053
|
+
sendMessage: async (jid, content, options = {}) => {
|
|
1054
|
+
const userJid = authState.creds.me.id;
|
|
1055
|
+
if (typeof content === 'object' &&
|
|
1056
|
+
'disappearingMessagesInChat' in content &&
|
|
1057
|
+
typeof content['disappearingMessagesInChat'] !== 'undefined' &&
|
|
1058
|
+
isJidGroup(jid)) {
|
|
1059
|
+
const { disappearingMessagesInChat } = content;
|
|
1060
|
+
const value = typeof disappearingMessagesInChat === 'boolean'
|
|
1061
|
+
? disappearingMessagesInChat
|
|
1062
|
+
? WA_DEFAULT_EPHEMERAL
|
|
1063
|
+
: 0
|
|
1064
|
+
: disappearingMessagesInChat;
|
|
1065
|
+
await groupToggleEphemeral(jid, value);
|
|
1066
|
+
}
|
|
1067
|
+
else {
|
|
1068
|
+
const fullMsg = await generateWAMessage(jid, content, {
|
|
1069
|
+
logger,
|
|
1070
|
+
userJid,
|
|
1071
|
+
getUrlInfo: text => getUrlInfo(text, {
|
|
1072
|
+
thumbnailWidth: linkPreviewImageThumbnailWidth,
|
|
1073
|
+
fetchOpts: {
|
|
1074
|
+
timeout: 3000,
|
|
1075
|
+
...(httpRequestOptions || {})
|
|
1076
|
+
},
|
|
1077
|
+
logger,
|
|
1078
|
+
uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
|
|
1079
|
+
}),
|
|
1080
|
+
//TODO: CACHE
|
|
1081
|
+
getProfilePicUrl: sock.profilePictureUrl,
|
|
1082
|
+
getCallLink: sock.createCallLink,
|
|
1083
|
+
upload: waUploadToServer,
|
|
1084
|
+
mediaCache: config.mediaCache,
|
|
1085
|
+
options: config.options,
|
|
1086
|
+
messageId: generateMessageIDV2(sock.user?.id),
|
|
1087
|
+
...options
|
|
1088
|
+
});
|
|
1089
|
+
const isEventMsg = 'event' in content && !!content.event;
|
|
1090
|
+
const isDeleteMsg = 'delete' in content && !!content.delete;
|
|
1091
|
+
const isEditMsg = 'edit' in content && !!content.edit;
|
|
1092
|
+
const isPinMsg = 'pin' in content && !!content.pin;
|
|
1093
|
+
const isPollMessage = 'poll' in content && !!content.poll;
|
|
1094
|
+
const additionalAttributes = {};
|
|
1095
|
+
const additionalNodes = [];
|
|
1096
|
+
// required for delete
|
|
1097
|
+
if (isDeleteMsg) {
|
|
1098
|
+
// if the chat is a group, and I am not the author, then delete the message as an admin
|
|
1099
|
+
if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
|
|
1100
|
+
additionalAttributes.edit = '8';
|
|
1101
|
+
}
|
|
1102
|
+
else {
|
|
1103
|
+
additionalAttributes.edit = '7';
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
else if (isEditMsg) {
|
|
1107
|
+
additionalAttributes.edit = '1';
|
|
1108
|
+
}
|
|
1109
|
+
else if (isPinMsg) {
|
|
1110
|
+
additionalAttributes.edit = '2';
|
|
1111
|
+
}
|
|
1112
|
+
else if (isPollMessage) {
|
|
1113
|
+
additionalNodes.push({
|
|
1114
|
+
tag: 'meta',
|
|
1115
|
+
attrs: {
|
|
1116
|
+
polltype: 'creation'
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
else if (isEventMsg) {
|
|
1121
|
+
additionalNodes.push({
|
|
1122
|
+
tag: 'meta',
|
|
1123
|
+
attrs: {
|
|
1124
|
+
event_type: 'creation'
|
|
1125
|
+
}
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
await relayMessage(jid, fullMsg.message, {
|
|
1129
|
+
messageId: fullMsg.key.id,
|
|
1130
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
1131
|
+
additionalAttributes,
|
|
1132
|
+
statusJidList: options.statusJidList,
|
|
1133
|
+
additionalNodes
|
|
1134
|
+
});
|
|
1135
|
+
if (config.emitOwnEvents) {
|
|
1136
|
+
process.nextTick(async () => {
|
|
1137
|
+
await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
return fullMsg;
|
|
1141
|
+
}
|
|
1280
1142
|
}
|
|
1281
|
-
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
};
|
|
1143
|
+
};
|
|
1285
1144
|
};
|
|
1286
|
-
|
|
1145
|
+
//# sourceMappingURL=messages-send.js.map
|