@ikyyjee/ikyysinggle 1.7.7

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.
Files changed (142) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +8083 -0
  3. package/WAProto/fix-imports.js +85 -0
  4. package/WAProto/index.d.ts +29095 -0
  5. package/WAProto/index.js +172336 -0
  6. package/engine-requirements.js +10 -0
  7. package/lib/Defaults/index.js +194 -0
  8. package/lib/Signal/Group/ciphertext-message.js +12 -0
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/lib/Signal/Group/group_cipher.js +82 -0
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/lib/Signal/Group/sender-chain-key.js +26 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  15. package/lib/Signal/Group/sender-key-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-name.js +48 -0
  17. package/lib/Signal/Group/sender-key-record.js +41 -0
  18. package/lib/Signal/Group/sender-key-state.js +84 -0
  19. package/lib/Signal/Group/sender-message-key.js +26 -0
  20. package/lib/Signal/libsignal.js +431 -0
  21. package/lib/Signal/lid-mapping.js +277 -0
  22. package/lib/Socket/Client/index.js +3 -0
  23. package/lib/Socket/Client/types.js +11 -0
  24. package/lib/Socket/Client/websocket.js +102 -0
  25. package/lib/Socket/aigroups.js +221 -0
  26. package/lib/Socket/business.js +379 -0
  27. package/lib/Socket/chats.js +1193 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +524 -0
  30. package/lib/Socket/groups.js +408 -0
  31. package/lib/Socket/index.js +49 -0
  32. package/lib/Socket/interop.js +341 -0
  33. package/lib/Socket/luxu.js +510 -0
  34. package/lib/Socket/managed-account.js +99 -0
  35. package/lib/Socket/messages-recv.js +2009 -0
  36. package/lib/Socket/messages-send.js +1608 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +399 -0
  39. package/lib/Socket/privacy.js +128 -0
  40. package/lib/Socket/registration.js +238 -0
  41. package/lib/Socket/socket.js +1000 -0
  42. package/lib/Socket/text-router.js +67 -0
  43. package/lib/Socket/username.js +234 -0
  44. package/lib/Store/index.js +10 -0
  45. package/lib/Store/keyed-db.js +108 -0
  46. package/lib/Store/make-cache-manager-store.js +85 -0
  47. package/lib/Store/make-in-memory-store.js +198 -0
  48. package/lib/Store/make-ordered-dictionary.js +75 -0
  49. package/lib/Store/object-repository.js +32 -0
  50. package/lib/Types/Auth.js +2 -0
  51. package/lib/Types/Bussines.js +2 -0
  52. package/lib/Types/Call.js +2 -0
  53. package/lib/Types/Chat.js +8 -0
  54. package/lib/Types/Contact.js +2 -0
  55. package/lib/Types/Events.js +2 -0
  56. package/lib/Types/GroupMetadata.js +2 -0
  57. package/lib/Types/Label.js +25 -0
  58. package/lib/Types/LabelAssociation.js +7 -0
  59. package/lib/Types/Message.js +11 -0
  60. package/lib/Types/Mex.js +114 -0
  61. package/lib/Types/Product.js +2 -0
  62. package/lib/Types/Signal.js +2 -0
  63. package/lib/Types/Socket.js +3 -0
  64. package/lib/Types/State.js +56 -0
  65. package/lib/Types/USync.js +2 -0
  66. package/lib/Types/index.js +26 -0
  67. package/lib/Utils/adaptive-healing.js +53 -0
  68. package/lib/Utils/auth-utils.js +302 -0
  69. package/lib/Utils/browser-utils.js +50 -0
  70. package/lib/Utils/business.js +231 -0
  71. package/lib/Utils/chat-utils.js +872 -0
  72. package/lib/Utils/command-loader.js +108 -0
  73. package/lib/Utils/companion-reg-client-utils.js +35 -0
  74. package/lib/Utils/consumer-application.js +106 -0
  75. package/lib/Utils/crypto.js +137 -0
  76. package/lib/Utils/curve25519-js.js +262 -0
  77. package/lib/Utils/decode-wa-message.js +498 -0
  78. package/lib/Utils/event-buffer.js +622 -0
  79. package/lib/Utils/generics.js +403 -0
  80. package/lib/Utils/group-history.js +47 -0
  81. package/lib/Utils/history.js +134 -0
  82. package/lib/Utils/identity-change-handler.js +50 -0
  83. package/lib/Utils/index.js +38 -0
  84. package/lib/Utils/jid-display-normalization.js +198 -0
  85. package/lib/Utils/link-preview.js +85 -0
  86. package/lib/Utils/logger.js +3 -0
  87. package/lib/Utils/lt-hash.js +8 -0
  88. package/lib/Utils/make-mutex.js +33 -0
  89. package/lib/Utils/message-composer.js +273 -0
  90. package/lib/Utils/message-retry-manager.js +267 -0
  91. package/lib/Utils/messages-media.js +791 -0
  92. package/lib/Utils/messages.js +1260 -0
  93. package/lib/Utils/meta-ai-msmsg.js +271 -0
  94. package/lib/Utils/native-bridge.js +77 -0
  95. package/lib/Utils/noise-handler.js +201 -0
  96. package/lib/Utils/offline-node-processor.js +40 -0
  97. package/lib/Utils/optimizer.js +90 -0
  98. package/lib/Utils/pre-key-manager.js +106 -0
  99. package/lib/Utils/process-message.js +630 -0
  100. package/lib/Utils/reporting-utils.js +258 -0
  101. package/lib/Utils/session-pool.js +73 -0
  102. package/lib/Utils/signal.js +207 -0
  103. package/lib/Utils/stanza-ack.js +38 -0
  104. package/lib/Utils/sticker.js +139 -0
  105. package/lib/Utils/sync-action-utils.js +49 -0
  106. package/lib/Utils/tc-token-utils.js +163 -0
  107. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  108. package/lib/Utils/use-sqlite-auth-state.js +168 -0
  109. package/lib/Utils/validate-connection.js +203 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +25 -0
  112. package/lib/Utils/warmup.js +117 -0
  113. package/lib/WABinary/constants.js +1301 -0
  114. package/lib/WABinary/decode.js +262 -0
  115. package/lib/WABinary/encode.js +220 -0
  116. package/lib/WABinary/generic-utils.js +204 -0
  117. package/lib/WABinary/index.js +6 -0
  118. package/lib/WABinary/jid-utils.js +98 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +10 -0
  121. package/lib/WAM/constants.js +22853 -0
  122. package/lib/WAM/encode.js +150 -0
  123. package/lib/WAM/index.js +4 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +41 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +52 -0
  129. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +26 -0
  131. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  132. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +35 -0
  133. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  135. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  136. package/lib/WAUSync/Protocols/index.js +13 -0
  137. package/lib/WAUSync/USyncQuery.js +127 -0
  138. package/lib/WAUSync/USyncUser.js +31 -0
  139. package/lib/WAUSync/index.js +4 -0
  140. package/lib/antiban.js +4083 -0
  141. package/lib/index.js +24 -0
  142. package/package.json +147 -0
@@ -0,0 +1,1608 @@
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, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateIOSMessageID, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, NumberWarmUp, parseAndInjectE2ESessions, resolveOptimizerConfig, unixTimestampSeconds, setBotMessageSecret } 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, isJidBroadcast, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET, getAdditionalNode, getBinaryNodeFilter, getBinaryFilteredBizBot, isInteropUser } from '../WABinary/index.js';
11
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
+ import { makeUsernameSocket } from './username.js';
13
+ import imup from './luxu.js';
14
+ import * as Utils_1 from '../Utils/index.js';
15
+ import { randomBytes } from 'crypto';
16
+ export const makeMessagesSocket = (config) => {
17
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount, aiLabel } = config;
18
+ const sock = makeUsernameSocket(config);
19
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
20
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
21
+
22
+ /**
23
+ * "AntiBanned" fresh-number throttle — OFF by default, opt-in via config.
24
+ * See lib/Utils/warmup.js and README.md → "AntiBanned" for the full picture.
25
+ * This only ramps daily send limits up for numbers that recently started
26
+ * using this socket; it never touches message content or connection
27
+ * behavior, and numbers past `warmUpDays` (or with `antiBanned` unset)
28
+ * send exactly as before.
29
+ */
30
+ const antiBannedConfig = config.antiBanned;
31
+ const antiBannedEnabled = !!(antiBannedConfig && antiBannedConfig.enabled);
32
+ const numberWarmUp = antiBannedEnabled
33
+ ? new NumberWarmUp(antiBannedConfig, antiBannedConfig.state)
34
+ : null;
35
+ const antiBannedAction = antiBannedConfig?.action === 'block' ? 'block' : 'delay';
36
+
37
+ /** optiMazer, if enabled, tightens the cache/log caps below — see lib/Utils/optimizer.js. */
38
+ const optimizerLimits = resolveOptimizerConfig(config.optiMazer);
39
+ const resolvedUserDevicesCacheMax = config.userDevicesCacheMaxKeys ?? optimizerLimits?.userDevicesCacheMaxKeys ?? 10000;
40
+ const resolvedGuardLogMax = config.guardLogMax ?? optimizerLimits?.guardLogMax ?? 200;
41
+
42
+ /**
43
+ * Unknown-recipient guard for direct messages (@s.whatsapp.net / @lid).
44
+ *
45
+ * This is deliberately NOT deny-by-default like the channel-follow and
46
+ * group-join guards. Sending a first message to someone who hasn't
47
+ * messaged you yet is completely normal for a lot of legitimate bots
48
+ * (OTPs, opted-in broadcasts, outbound sales/support) — blocking that by
49
+ * default would break real, intended usage, not just a hidden/injected
50
+ * send. So by default this only *flags* (console + logger) the first
51
+ * time in this session `sendMessage` targets a JID that has never
52
+ * messaged you and isn't allowlisted — so you always see when something
53
+ * you didn't write starts DMing new people. Groups/broadcasts/channels/
54
+ * bots are exempt (handled by their own guards or not applicable).
55
+ *
56
+ * If your bot genuinely never initiates DMs to brand-new contacts, set
57
+ * `blockUnknownRecipients: true` and this can safely deny instead of
58
+ * just flagging. See README.md → "Guard against unexpected group-joins
59
+ * and DMs".
60
+ */
61
+ const recipientGuardEnabled = config.flagUnknownRecipients !== false;
62
+ const blockUnknownRecipients = !!config.blockUnknownRecipients;
63
+ const knownRecipients = new Set(Array.isArray(config.allowedRecipients) ? config.allowedRecipients : []);
64
+ const flaggedRecipients = [];
65
+ if (recipientGuardEnabled) {
66
+ ev.on('messages.upsert', ({ messages }) => {
67
+ for (const m of messages) {
68
+ const from = m.key?.remoteJid;
69
+ if (from && !m.key.fromMe) {
70
+ knownRecipients.add(from);
71
+ if (m.key.participant) {
72
+ knownRecipients.add(m.key.participant);
73
+ }
74
+ }
75
+ }
76
+ });
77
+ }
78
+ /**
79
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
80
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
81
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
82
+ */
83
+ const inFlightTcTokenIssuance = new Set();
84
+ const userDevicesCache = config.userDevicesCache ||
85
+ new NodeCache({
86
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
87
+ useClones: false,
88
+ // Hard cap so a long-running / high-traffic bot can't grow this
89
+ // cache unbounded between TTL sweeps; oldest-inserted entries are
90
+ // evicted first once the limit is hit. Override via
91
+ // `userDevicesCache` in config if you need something different.
92
+ maxKeys: resolvedUserDevicesCacheMax
93
+ });
94
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
95
+ const devicesMutex = makeMutex();
96
+ // Initialize message retry manager if enabled
97
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount, optimizerLimits ?? {}) : null;
98
+ // Prevent race conditions in Signal session encryption by user
99
+ const encryptionMutex = makeKeyedMutex();
100
+ let mediaConn;
101
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
102
+ let mediaHost = DEF_MEDIA_HOST;
103
+ const refreshMediaConn = async (forceGet = false) => {
104
+ const media = await mediaConn;
105
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
106
+ mediaConn = (async () => {
107
+ const result = await query({
108
+ tag: 'iq',
109
+ attrs: {
110
+ type: 'set',
111
+ xmlns: 'w:m',
112
+ to: S_WHATSAPP_NET
113
+ },
114
+ content: [{ tag: 'media_conn', attrs: {} }]
115
+ });
116
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
117
+ // TODO: explore full length of data that whatsapp provides
118
+ const node = {
119
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
120
+ hostname: attrs.hostname,
121
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
122
+ })),
123
+ auth: mediaConnNode.attrs.auth,
124
+ ttl: +mediaConnNode.attrs.ttl,
125
+ fetchDate: new Date()
126
+ };
127
+ logger.debug('fetched media conn');
128
+ if (node.hosts[0]) {
129
+ mediaHost = node.hosts[0].hostname;
130
+ }
131
+ return node;
132
+ })();
133
+ }
134
+ return mediaConn;
135
+ };
136
+ /**
137
+ * generic send receipt function
138
+ * used for receipts of phone call, read, delivery etc.
139
+ * */
140
+ const sendReceipt = async (jid, participant, messageIds, type) => {
141
+ if (!messageIds || messageIds.length === 0) {
142
+ throw new Boom('missing ids in receipt');
143
+ }
144
+ const node = {
145
+ tag: 'receipt',
146
+ attrs: {
147
+ id: messageIds[0]
148
+ }
149
+ };
150
+ const isReadReceipt = type === 'read' || type === 'read-self';
151
+ if (isReadReceipt) {
152
+ node.attrs.t = unixTimestampSeconds().toString();
153
+ }
154
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
155
+ node.attrs.recipient = jid;
156
+ node.attrs.to = participant;
157
+ }
158
+ else {
159
+ node.attrs.to = jid;
160
+ if (participant) {
161
+ node.attrs.participant = participant;
162
+ }
163
+ }
164
+ if (type) {
165
+ node.attrs.type = type;
166
+ }
167
+ const remainingMessageIds = messageIds.slice(1);
168
+ if (remainingMessageIds.length) {
169
+ node.content = [
170
+ {
171
+ tag: 'list',
172
+ attrs: {},
173
+ content: remainingMessageIds.map(id => ({
174
+ tag: 'item',
175
+ attrs: { id }
176
+ }))
177
+ }
178
+ ];
179
+ }
180
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
181
+ await sendNode(node);
182
+ };
183
+ /** Correctly bulk send receipts to multiple chats, participants */
184
+ const sendReceipts = async (keys, type) => {
185
+ const recps = aggregateMessageKeysNotFromMe(keys);
186
+ for (const { jid, participant, messageIds } of recps) {
187
+ await sendReceipt(jid, participant, messageIds, type);
188
+ }
189
+ };
190
+ /** Bulk read messages. Keys can be from different chats & participants */
191
+ const readMessages = async (keys) => {
192
+ const privacySettings = await fetchPrivacySettings();
193
+ // based on privacy settings, we have to change the read type
194
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
195
+ await sendReceipts(keys, readType);
196
+ };
197
+ /** Fetch all the devices we've to send a message to */
198
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
199
+ const deviceResults = [];
200
+ if (!useCache) {
201
+ logger.debug('not using cache for devices');
202
+ }
203
+ const toFetch = [];
204
+ const jidsWithUser = jids
205
+ .map(jid => {
206
+ const decoded = jidDecode(jid);
207
+ const user = decoded?.user;
208
+ const device = decoded?.device;
209
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
210
+ if (isExplicitDevice && user) {
211
+ deviceResults.push({
212
+ user,
213
+ device,
214
+ jid
215
+ });
216
+ return null;
217
+ }
218
+ jid = jidNormalizedUser(jid);
219
+ return { jid, user };
220
+ })
221
+ .filter(jid => jid !== null);
222
+ let mgetDevices;
223
+ if (useCache && userDevicesCache.mget) {
224
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
225
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
226
+ }
227
+ for (const { jid, user } of jidsWithUser) {
228
+ if (useCache) {
229
+ const devices = mgetDevices?.[user] ||
230
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
231
+ if (devices) {
232
+ const devicesWithJid = devices.map(d => ({
233
+ ...d,
234
+ jid: jidEncode(d.user, d.server, d.device)
235
+ }));
236
+ deviceResults.push(...devicesWithJid);
237
+ logger.trace({ user }, 'using cache for devices');
238
+ }
239
+ else {
240
+ toFetch.push(jid);
241
+ }
242
+ }
243
+ else {
244
+ toFetch.push(jid);
245
+ }
246
+ }
247
+ if (!toFetch.length) {
248
+ return deviceResults;
249
+ }
250
+ const requestedLidUsers = new Set();
251
+ for (const jid of toFetch) {
252
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
253
+ const user = jidDecode(jid)?.user;
254
+ if (user)
255
+ requestedLidUsers.add(user);
256
+ }
257
+ }
258
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
259
+ for (const jid of toFetch) {
260
+ 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
261
+ }
262
+ const result = await sock.executeUSyncQuery(query);
263
+ if (result) {
264
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
265
+ const lidResults = result.list.filter(a => !!a.lid);
266
+ if (lidResults.length > 0) {
267
+ logger.trace('Storing LID maps from device call');
268
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
269
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
270
+ try {
271
+ const lids = lidResults.map(a => a.lid);
272
+ if (lids.length) {
273
+ await assertSessions(lids, true);
274
+ }
275
+ }
276
+ catch (e) {
277
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
278
+ }
279
+ }
280
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
281
+ const deviceMap = {};
282
+ for (const item of extracted) {
283
+ deviceMap[item.user] = deviceMap[item.user] || [];
284
+ deviceMap[item.user]?.push(item);
285
+ }
286
+ // Process each user's devices as a group for bulk LID migration
287
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
288
+ const isLidUser = requestedLidUsers.has(user);
289
+ // Process all devices for this user
290
+ for (const item of userDevices) {
291
+ const finalJid = isLidUser
292
+ ? jidEncode(user, item.server, item.device)
293
+ : jidEncode(item.user, item.server, item.device);
294
+ deviceResults.push({
295
+ ...item,
296
+ jid: finalJid
297
+ });
298
+ logger.debug({
299
+ user: item.user,
300
+ device: item.device,
301
+ finalJid,
302
+ usedLid: isLidUser
303
+ }, 'Processed device with LID priority');
304
+ }
305
+ }
306
+ await devicesMutex.mutex(async () => {
307
+ if (userDevicesCache.mset) {
308
+ // if the cache supports mset, we can set all devices in one go
309
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
310
+ }
311
+ else {
312
+ for (const key in deviceMap) {
313
+ if (deviceMap[key])
314
+ await userDevicesCache.set(key, deviceMap[key]);
315
+ }
316
+ }
317
+ });
318
+ const userDeviceUpdates = {};
319
+ for (const [userId, devices] of Object.entries(deviceMap)) {
320
+ if (devices && devices.length > 0) {
321
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
322
+ }
323
+ }
324
+ if (Object.keys(userDeviceUpdates).length > 0) {
325
+ try {
326
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
327
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
328
+ }
329
+ catch (error) {
330
+ logger.warn({ error }, 'failed to store user device lists');
331
+ }
332
+ }
333
+ }
334
+ return deviceResults;
335
+ };
336
+ /**
337
+ * Update Member Label
338
+ */
339
+ const updateMemberLabel = (jid, memberLabel) => {
340
+ return relayMessage(jid, {
341
+ protocolMessage: {
342
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
343
+ memberLabel: {
344
+ label: memberLabel?.slice(0, 30),
345
+ labelTimestamp: unixTimestampSeconds()
346
+ }
347
+ }
348
+ }, {
349
+ additionalNodes: [
350
+ {
351
+ tag: 'meta',
352
+ attrs: {
353
+ tag_reason: 'user_update',
354
+ appdata: 'member_tag'
355
+ },
356
+ content: undefined
357
+ }
358
+ ]
359
+ });
360
+ };
361
+ const assertSessions = async (jids, force) => {
362
+ let didFetchNewSession = false;
363
+ const uniqueJids = [...new Set(jids.filter(Boolean))];
364
+ const jidsRequiringFetch = [];
365
+ logger.debug({ jids: uniqueJids, force: !!force }, 'assertSessions call with jids');
366
+ for (const jid of uniqueJids) {
367
+ if (!force) {
368
+ const sessionValidation = await signalRepository.validateSession(jid);
369
+ if (sessionValidation.exists) {
370
+ continue;
371
+ }
372
+ }
373
+ jidsRequiringFetch.push(jid);
374
+ }
375
+ if (jidsRequiringFetch.length) {
376
+ const lidJids = jidsRequiringFetch.filter(jid => isLidUser(jid) || isHostedLidUser(jid));
377
+ const pnJids = jidsRequiringFetch.filter(jid => isPnUser(jid) || isHostedPnUser(jid));
378
+ // Resolve LID mappings (may USync on miss) so cold contacts work without a prior chat
379
+ const mapped = (pnJids.length ? await signalRepository.lidMapping.getLIDsForPNs(pnJids) : null) || [];
380
+ const mappedPnUsers = new Set(mapped.map(a => jidDecode(a.pn)?.user).filter(Boolean));
381
+ // Fallback to PN wire JIDs when LID map is still missing — required for
382
+ // first-contact sends. Without this, a PN jid that doesn't resolve to a
383
+ // LID (e.g. a contact you've never chatted with before) was silently
384
+ // dropped from the session-fetch request entirely, rather than falling
385
+ // back to fetching by its raw PN jid — which meant the very first
386
+ // message to a brand-new contact could fail to encrypt correctly.
387
+ const unmappedPnJids = pnJids.filter(jid => {
388
+ const user = jidDecode(jid)?.user;
389
+ return !!user && !mappedPnUsers.has(user);
390
+ });
391
+ const wireJids = [...new Set([
392
+ ...lidJids,
393
+ ...mapped.map(a => a.lid).filter(Boolean),
394
+ ...unmappedPnJids
395
+ ])];
396
+ if (!wireJids.length) {
397
+ logger.warn({ jidsRequiringFetch }, 'assertSessions: no wire JIDs resolved — cannot fetch E2E sessions for first contact');
398
+ return false;
399
+ }
400
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
401
+ const result = await query({
402
+ tag: 'iq',
403
+ attrs: {
404
+ xmlns: 'encrypt',
405
+ type: 'get',
406
+ to: S_WHATSAPP_NET
407
+ },
408
+ content: [
409
+ {
410
+ tag: 'key',
411
+ attrs: {},
412
+ content: wireJids.map(jid => {
413
+ const attrs = { jid };
414
+ if (force)
415
+ attrs.reason = 'identity';
416
+ return { tag: 'user', attrs };
417
+ })
418
+ }
419
+ ]
420
+ });
421
+ await parseAndInjectE2ESessions(result, signalRepository);
422
+ didFetchNewSession = true;
423
+ }
424
+ return didFetchNewSession;
425
+ };
426
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
427
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
428
+ if (!authState.creds.me?.id) {
429
+ throw new Boom('Not authenticated');
430
+ }
431
+ const protocolMessage = {
432
+ protocolMessage: {
433
+ peerDataOperationRequestMessage: pdoMessage,
434
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
435
+ }
436
+ };
437
+ const meJid = jidNormalizedUser(authState.creds.me.id);
438
+ const msgId = await relayMessage(meJid, protocolMessage, {
439
+ additionalAttributes: {
440
+ category: 'peer',
441
+ push_priority: 'high_force'
442
+ },
443
+ additionalNodes: [
444
+ {
445
+ tag: 'meta',
446
+ attrs: { appdata: 'default' }
447
+ }
448
+ ]
449
+ });
450
+ return msgId;
451
+ };
452
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
453
+ if (!recipientJids.length) {
454
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
455
+ }
456
+ const patched = await patchMessageBeforeSending(message, recipientJids);
457
+ const patchedMessages = Array.isArray(patched)
458
+ ? patched
459
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
460
+ let shouldIncludeDeviceIdentity = false;
461
+ const meId = authState.creds.me.id;
462
+ const meLid = authState.creds.me?.lid;
463
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
464
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
465
+ try {
466
+ if (!jid)
467
+ return null;
468
+ let msgToEncrypt = patchedMessage;
469
+ if (dsmMessage) {
470
+ const { user: targetUser } = jidDecode(jid);
471
+ const { user: ownPnUser } = jidDecode(meId);
472
+ const ownLidUser = meLidUser;
473
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
474
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
475
+ if (isOwnUser && !isExactSenderDevice) {
476
+ msgToEncrypt = dsmMessage;
477
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
478
+ }
479
+ }
480
+ const bytes = encodeWAMessage(msgToEncrypt);
481
+ const mutexKey = jid;
482
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
483
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
484
+ if (type === 'pkmsg') {
485
+ shouldIncludeDeviceIdentity = true;
486
+ }
487
+ return {
488
+ tag: 'to',
489
+ attrs: { jid },
490
+ content: [
491
+ {
492
+ tag: 'enc',
493
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
494
+ content: ciphertext
495
+ }
496
+ ]
497
+ };
498
+ });
499
+ return node;
500
+ }
501
+ catch (err) {
502
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
503
+ return null;
504
+ }
505
+ });
506
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
507
+ if (recipientJids.length > 0 && nodes.length === 0) {
508
+ throw new Boom('All encryptions failed', { statusCode: 500 });
509
+ }
510
+ return { nodes, shouldIncludeDeviceIdentity };
511
+ };
512
+ const relayMessage = async (
513
+ jid,
514
+ message,
515
+ {
516
+ messageId: msgId,
517
+ participant = false,
518
+ noSelfSync = false,
519
+ additionalAttributes,
520
+ additionalNodes,
521
+ useUserDevicesCache,
522
+ useCachedGroupMetadata,
523
+ statusJidList
524
+ }
525
+ ) => {
526
+ const meId = authState.creds.me.id
527
+ const meLid = authState.creds.me?.lid
528
+ const isRetryResend = Boolean(participant?.jid)
529
+ let shouldIncludeDeviceIdentity = isRetryResend
530
+ const statusJid = 'status@broadcast'
531
+ const { user, server } = jidDecode(jid)
532
+ const isGroup = server === 'g.us'
533
+ const isStatus = jid === statusJid
534
+ const isLid = server === 'lid'
535
+ const isNewsletter = server === 'newsletter'
536
+ const isInterop = isInteropUser(jid)
537
+ const isGroupOrStatus = isGroup || isStatus
538
+ const finalJid = jid
539
+ const iosBros = config.browser[0] === "iOS" || config.browser[1] === "Safari";
540
+ msgId = iosBros ? generateIOSMessageID() : msgId ?? generateMessageIDV2(meId)
541
+ useUserDevicesCache = useUserDevicesCache!== false
542
+ useCachedGroupMetadata = useCachedGroupMetadata!== false &&!isStatus
543
+ const participants = []
544
+ const destinationJid =!isStatus? finalJid : statusJid
545
+ const binaryNodeContent = []
546
+ const devices = []
547
+ let reportingMessage
548
+ const messages = normalizeMessageContent(message)
549
+ const buttonType = getButtonType(messages)
550
+ /**
551
+ * aiWatermark — separate from aiLabel. Adds WhatsApp's "AI" badge
552
+ * (MessageContextInfo.isSupportAiMessage) ONLY on messages that have
553
+ * buttons/interactive content (matches the "AI ♦ <time>" badge WhatsApp
554
+ * shows next to button/template messages). Plain messages without
555
+ * buttons are left untouched — this runs before `meMsg` below is built,
556
+ * so the flag is present in both the self-sync copy and the actual
557
+ * outgoing stanza. See README.md → "AI watermark on button messages".
558
+ */
559
+ if (config.aiWatermark && buttonType) {
560
+ message.messageContextInfo = {
561
+ ...(message.messageContextInfo || {}),
562
+ isSupportAiMessage: true
563
+ }
564
+ }
565
+ const meMsg = {
566
+ deviceSentMessage: { destinationJid, message },
567
+ messageContextInfo: message.messageContextInfo
568
+ }
569
+ const extraAttrs = {}
570
+ const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
571
+ const pollMessage =
572
+ messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
573
+ await authState.keys.transaction(async () => {
574
+ const mediaType = getMediaType(message)
575
+ if (mediaType) extraAttrs.mediatype = mediaType
576
+ if (isNewsletter) {
577
+ const patched = patchMessageBeforeSending? await patchMessageBeforeSending(message, []) : message
578
+ const bytes = encodeNewsletterMessage(patched)
579
+ binaryNodeContent.push({ tag: 'plaintext', attrs: {}, content: bytes })
580
+ const stanza = {
581
+ tag: 'message',
582
+ attrs: {
583
+ to: jid,
584
+ id: msgId,
585
+ type: getMessageType(message),
586
+ ...(additionalAttributes || {})
587
+ },
588
+ content: binaryNodeContent
589
+ }
590
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`)
591
+ await sendNode(stanza)
592
+ return
593
+ }
594
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
595
+ extraAttrs['decrypt-fail'] = 'hide'
596
+ }
597
+ if (isGroupOrStatus &&!isRetryResend) {
598
+ const [groupData, senderKeyMap] = await Promise.all([
599
+ (async () => {
600
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata? await cachedGroupMetadata(jid) : undefined
601
+ if (groupData && Array.isArray(groupData?.participants)) {
602
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
603
+ } else if (!isStatus) {
604
+ groupData = await groupMetadata(jid)
605
+ }
606
+ return groupData
607
+ })(),
608
+ (async () => {
609
+ if (!participant &&!isStatus) {
610
+ const result = await authState.keys.get('sender-key-memory', [jid])
611
+ return result[jid] || {}
612
+ }
613
+ return {}
614
+ })()
615
+ ])
616
+ const participantsList = groupData? groupData.participants.map(p => p.id) : []
617
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
618
+ additionalAttributes = {...additionalAttributes, expiration: groupData.ephemeralDuration.toString() }
619
+ }
620
+ if (isStatus && statusJidList) participantsList.push(...statusJidList)
621
+ const additionalDevices = await getUSyncDevices(participantsList,!!useUserDevicesCache, false)
622
+ devices.push(...additionalDevices)
623
+ if (isGroup) {
624
+ additionalAttributes = {
625
+ ...additionalAttributes,
626
+ addressing_mode: groupData?.addressingMode || 'lid'
627
+ }
628
+ }
629
+ if (message?.groupStatusMessageV2 &&!message?.messageContextInfo?.messageSecret) {
630
+ message = {
631
+ ...message,
632
+ messageContextInfo: {
633
+ ...(message.messageContextInfo || {}),
634
+ messageSecret: randomBytes(32)
635
+ },
636
+ groupStatusMessageV2: {
637
+ ...message.groupStatusMessageV2,
638
+ message: {
639
+ ...(message.groupStatusMessageV2.message || {}),
640
+ messageContextInfo: {
641
+ ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
642
+ messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
643
+ }
644
+ }
645
+ }
646
+ }
647
+ }
648
+ // list/buttons/template -> interactiveMessage
649
+ if (message.listMessage) {
650
+ const list = message.listMessage
651
+ message = {
652
+ interactiveMessage: {
653
+ nativeFlowMessage: {
654
+ buttons: [
655
+ {
656
+ name: 'single_select',
657
+ buttonParamsJson: JSON.stringify({
658
+ title: list.buttonText || 'Select',
659
+ sections: (list.sections || []).map(section => ({
660
+ title: section.title || '',
661
+ highlight_label: '',
662
+ rows: (section.rows || []).map(row => ({
663
+ header: '',
664
+ title: row.title || '',
665
+ description: row.description || '',
666
+ id: row.rowId || row.id || ''
667
+ }))
668
+ }))
669
+ })
670
+ }
671
+ ],
672
+ messageParamsJson: '',
673
+ messageVersion: 1
674
+ },
675
+ body: { text: list.description || '' },
676
+ footer: list.footerText? { text: list.footerText } : undefined,
677
+ header: list.title? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
678
+ contextInfo: list.contextInfo
679
+ }
680
+ }
681
+ } else if (message.buttonsMessage) {
682
+ const bMsg = message.buttonsMessage
683
+ const buttons = (bMsg.buttons || []).map(btn => ({
684
+ name: 'quick_reply',
685
+ buttonParamsJson: JSON.stringify({
686
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
687
+ id: btn.buttonId || btn.buttonText?.displayText || ''
688
+ })
689
+ }))
690
+ message = {
691
+ interactiveMessage: {
692
+ nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
693
+ body: { text: bMsg.contentText || bMsg.text || '' },
694
+ footer: bMsg.footerText? { text: bMsg.footerText } : undefined,
695
+ header: bMsg.text
696
+ ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
697
+ : bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
698
+ ? { hasMediaAttachment: true,...(bMsg.imageMessage? { imageMessage: bMsg.imageMessage } : {}),...(bMsg.videoMessage? { videoMessage: bMsg.videoMessage } : {}) }
699
+ : undefined,
700
+ contextInfo: bMsg.contextInfo
701
+ }
702
+ }
703
+ } else if (message.templateMessage) {
704
+ const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate
705
+ if (tmpl) {
706
+ const buttons = (tmpl.hydratedButtons || [])
707
+ .map(hBtn => {
708
+ if (hBtn.quickReplyButton) {
709
+ return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: hBtn.quickReplyButton.displayText || '', id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || '' }) }
710
+ } else if (hBtn.urlButton) {
711
+ return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: hBtn.urlButton.displayText || '', url: hBtn.urlButton.url || '', merchant_url: hBtn.urlButton.url || '' }) }
712
+ } else if (hBtn.callButton) {
713
+ return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: hBtn.callButton.displayText || '', phone_number: hBtn.callButton.phoneNumber || '' }) }
714
+ }
715
+ return null
716
+ })
717
+ .filter(Boolean)
718
+ message = {
719
+ interactiveMessage: {
720
+ nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
721
+ body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
722
+ footer: tmpl.hydratedFooterText? { text: tmpl.hydratedFooterText } : undefined,
723
+ header: tmpl.hydratedTitleText
724
+ ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
725
+ : tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
726
+ ? { hasMediaAttachment: true,...(tmpl.imageMessage? { imageMessage: tmpl.imageMessage } : {}),...(tmpl.videoMessage? { videoMessage: tmpl.videoMessage } : {}) }
727
+ : undefined,
728
+ contextInfo: tmpl.contextInfo
729
+ }
730
+ }
731
+ }
732
+ }
733
+
734
+ const patched = await patchMessageBeforeSending(message)
735
+ if (Array.isArray(patched)) throw new Boom('Per-jid patching is not supported in groups')
736
+ const bytes = encodeWAMessage(patched)
737
+ reportingMessage = patched
738
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
739
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid? meLid : meId
740
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
741
+ group: destinationJid,
742
+ data: bytes,
743
+ meId: groupSenderIdentity
744
+ })
745
+ const senderKeyRecipients = []
746
+ for (const device of devices) {
747
+ const deviceJid = device.jid
748
+ const hasKey =!!senderKeyMap[deviceJid]
749
+ if (!hasKey ||!!participant &&!isHostedLidUser(deviceJid) &&!isHostedPnUser(deviceJid) && device.device!== 99) {
750
+ senderKeyRecipients.push(deviceJid)
751
+ senderKeyMap[deviceJid] = true
752
+ }
753
+ }
754
+ if (senderKeyRecipients.length) {
755
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
756
+ const senderKeyMsg = {
757
+ senderKeyDistributionMessage: {
758
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
759
+ groupId: destinationJid
760
+ }
761
+ }
762
+ await assertSessions(senderKeyRecipients)
763
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
764
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
765
+ participants.push(...result.nodes)
766
+ }
767
+ binaryNodeContent.push({ tag: 'enc', attrs: { v: '2', type: 'skmsg',...extraAttrs }, content: ciphertext })
768
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
769
+ } else {
770
+ let ownId = meId
771
+ if (isLid && meLid) {
772
+ ownId = meLid
773
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
774
+ } else {
775
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
776
+ }
777
+ const { user: ownUser } = jidDecode(ownId)
778
+ if (!participant) {
779
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid])
780
+ reportingMessage = Array.isArray(patchedForReporting)
781
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
782
+ : patchedForReporting
783
+ }
784
+ if (!isRetryResend) {
785
+ const targetUserServer = isLid? 'lid' : isInterop? 'interop' : 's.whatsapp.net'
786
+ devices.push({ user, device: 0, jid: jidEncode(user, targetUserServer, 0) })
787
+ if (user!== ownUser &&!isInterop) {
788
+ const ownUserServer = isLid? 'lid' : 's.whatsapp.net'
789
+ const ownUserForAddressing = isLid && meLid? jidDecode(meLid).user : jidDecode(meId).user
790
+ devices.push({ user: ownUserForAddressing, device: 0, jid: jidEncode(ownUserForAddressing, ownUserServer, 0) })
791
+ }
792
+ if (additionalAttributes?.['category']!== 'peer' &&!isInterop) {
793
+ devices.length = 0
794
+ const senderIdentity = isLid && meLid
795
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
796
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined)
797
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
798
+ devices.push(...sessionDevices)
799
+ logger.debug({ deviceCount: devices.length, devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`) }, 'Device enumeration complete with unified addressing')
800
+ }
801
+ }
802
+ const allRecipients = []
803
+ const meRecipients = []
804
+ const otherRecipients = []
805
+ const { user: mePnUser } = jidDecode(meId)
806
+ const { user: meLidUser } = meLid? jidDecode(meLid) : { user: null }
807
+ for (const { user, jid } of devices) {
808
+ /** noSelfSync: opsi untuk skip sync pesan ke device lain milik akun sendiri (private chat) */
809
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
810
+ if (isExactSenderDevice) {
811
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
812
+ continue
813
+ }
814
+ const isMe = user === mePnUser || user === meLidUser
815
+ let ptcp = false
816
+ if (noSelfSync) {
817
+ if (!isJidGroup(jid) && !isStatus) {
818
+ if (!(!isMe)) ptcp = true
819
+ } else {
820
+ ptcp = false
821
+ }
822
+ }
823
+ if (!ptcp) {
824
+ if (isMe) {
825
+ meRecipients.push(jid)
826
+ } else {
827
+ otherRecipients.push(jid)
828
+ }
829
+ allRecipients.push(jid)
830
+ }
831
+ }
832
+ // Fix: detect silent delivery failure — if the destination is genuinely
833
+ // someone else (not our own number) and device resolution produced zero
834
+ // recipient devices for them, don't proceed as if the send succeeded.
835
+ const isSelfChatDestination = user === mePnUser || user === meLidUser
836
+ if (!isRetryResend && !isSelfChatDestination && otherRecipients.length === 0) {
837
+ logger.warn({ jid, deviceCount: devices.length, noSelfSync }, 'relayMessage: no recipient devices resolved for the other party; aborting to avoid a silent no-op send')
838
+ throw new Boom('No devices resolved for recipient — message was not delivered to the other party', { statusCode: 421, data: { jid } })
839
+ }
840
+ await assertSessions(allRecipients)
841
+ const [
842
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
843
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
844
+ ] = await Promise.all([
845
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
846
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
847
+ ])
848
+ participants.push(...meNodes,...otherNodes)
849
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
850
+ extraAttrs.phash = generateParticipantHashV2([...meRecipients,...otherRecipients])
851
+ }
852
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
853
+ }
854
+ if (isRetryResend) {
855
+ const isParticipantLid = jidDecode(participant.jid).server === 'lid'
856
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid? meLid : meId)
857
+ const encodedMessageToSend = isMe
858
+ ? encodeWAMessage({ deviceSentMessage: { destinationJid, message } })
859
+ : encodeWAMessage(message)
860
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
861
+ data: encodedMessageToSend,
862
+ jid: participant.jid
863
+ })
864
+ binaryNodeContent.push({
865
+ tag: 'enc',
866
+ attrs: { v: '2', type, count: (participant.count?? 0).toString() },
867
+ content: encryptedContent
868
+ })
869
+ }
870
+ if (participants.length) {
871
+ if (additionalAttributes?.['category'] === 'peer') {
872
+ const peerNode = participants[0]?.content?.[0]
873
+ if (peerNode) binaryNodeContent.push(peerNode)
874
+ } else if (isInterop) {
875
+ const recipientNode = participants.find(p => isInteropUser(p?.attrs?.jid))
876
+ const encNode = (recipientNode?? participants[0])?.content?.[0]
877
+ if (encNode) binaryNodeContent.push(encNode)
878
+ } else {
879
+ binaryNodeContent.push({ tag: 'participants', attrs: {}, content: participants })
880
+ }
881
+ }
882
+ const stanza = {
883
+ tag: 'message',
884
+ attrs: { id: msgId, to: destinationJid, type: getMessageType(message),...(additionalAttributes || {}) },
885
+ content: binaryNodeContent
886
+ }
887
+ if (shouldIncludeDeviceIdentity) {
888
+ stanza.content.push({ tag: 'device-identity', attrs: {}, content: encodeSignedDeviceIdentity(authState.creds.account, true) })
889
+ logger.debug({ jid }, 'adding device identity')
890
+ }
891
+
892
+ if (isGroup && regexGroupOld.test(jid) &&!message.reactionMessage) {
893
+ stanza.content.push({ tag: 'multicast', attrs: {} })
894
+ }
895
+ if (pollMessage || messages.eventMessage) {
896
+ stanza.content.push({
897
+ tag: 'meta',
898
+ attrs: messages.eventMessage
899
+ ? { event_type: 'creation' }
900
+ : isNewsletter
901
+ ? { polltype: 'creation', contenttype: pollMessage?.pollContentType === 2? 'image' : 'text' }
902
+ : { polltype: 'creation' }
903
+ })
904
+ }
905
+ if (!isNewsletter &&!isRetryResend && reportingMessage?.messageContextInfo?.messageSecret && shouldIncludeReportingToken(reportingMessage)) {
906
+ try {
907
+ const encoded = encodeWAMessage(reportingMessage)
908
+ const reportingKey = { id: msgId, fromMe: true, remoteJid: destinationJid, participant: participant?.jid }
909
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey)
910
+ if (reportingNode) {
911
+ stanza.content.push(reportingNode)
912
+ logger.trace({ jid }, 'added reporting token to message')
913
+ }
914
+ } catch (error) {
915
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token')
916
+ }
917
+ }
918
+ let didPushAdditional = false
919
+ if (!isNewsletter && buttonType) {
920
+ const buttonsNode = getButtonArgs(messages)
921
+ const filteredButtons = getBinaryNodeFilter(additionalNodes? additionalNodes : [])
922
+ if (filteredButtons) {
923
+ stanza.content.push(...additionalNodes)
924
+ didPushAdditional = true
925
+ } else {
926
+ stanza.content.push(buttonsNode)
927
+ }
928
+ }
929
+ if (!aiLabel && isPnUser(destinationJid)) {
930
+ const alreadyHasBizBot = getBinaryFilteredBizBot(additionalNodes || []) || getBinaryFilteredBizBot(stanza.content)
931
+ if (!alreadyHasBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
932
+ } else if (aiLabel &&!isGroup &&!isStatus &&!isNewsletter) {
933
+ const existingBizBot = getBinaryFilteredBizBot(additionalNodes || [])
934
+ if (!existingBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
935
+ }
936
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer'
937
+ const is1on1Send =!isGroup &&!isRetryResend &&!isStatus &&!isNewsletter &&!isPeerMessage
938
+ const tcTokenJid = is1on1Send? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid
939
+ const contactTcTokenData = is1on1Send? await authState.keys.get('tctoken', [tcTokenJid]) : {}
940
+ const existingTokenEntry = contactTcTokenData[tcTokenJid]
941
+ let tcTokenBuffer = existingTokenEntry?.token
942
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
943
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing')
944
+ tcTokenBuffer = undefined
945
+ const cleared = existingTokenEntry?.senderTimestamp!== undefined? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp } : null
946
+ try {
947
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } })
948
+ } catch (err) {
949
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup')
950
+ }
951
+ }
952
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
953
+ stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
954
+ }
955
+ if (additionalNodes && additionalNodes.length > 0 &&!didPushAdditional) {
956
+ stanza.content.push(...additionalNodes)
957
+ }
958
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`)
959
+ await sendNode(stanza)
960
+ if (message.messageContextInfo?.messageSecret) {
961
+ setBotMessageSecret(msgId, message.messageContextInfo.messageSecret, destinationJid)
962
+ }
963
+ const isProtocolMsg =!!normalizeMessageContent(message)?.protocolMessage
964
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid)
965
+ if (is1on1Send &&!isProtocolMsg &&!isBotOrPSA && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&!inFlightTcTokenIssuance.has(tcTokenJid)) {
966
+ inFlightTcTokenIssuance.add(tcTokenJid)
967
+ const issueTimestamp = unixTimestampSeconds()
968
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
969
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
970
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
971
+ .then(async result => {
972
+ await storeTcTokensFromIqResult({ result, fallbackJid: tcTokenJid, keys: authState.keys, getLIDForPN })
973
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid])
974
+ const currentEntry = currentData[tcTokenJid]
975
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
976
+ await authState.keys.set({
977
+ tctoken: {
978
+ [tcTokenJid]: { token: Buffer.alloc(0),...currentEntry, senderTimestamp: issueTimestamp },
979
+ ...indexWrite
980
+ }
981
+ })
982
+ })
983
+ .catch(err => logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed'))
984
+ .finally(() => inFlightTcTokenIssuance.delete(tcTokenJid))
985
+ }
986
+ if (messageRetryManager &&!participant) {
987
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message)
988
+ }
989
+ if (isInterop &&!isRetryResend) {
990
+ await trustInteropContact(destinationJid).catch(err => logger.debug({ err, jid: destinationJid }, 'failed to trust interop contact'))
991
+ }
992
+ }, meId)
993
+ return msgId
994
+ }
995
+ const getMessageType = (message) => {
996
+ const normalizedMessage = normalizeMessageContent(message);
997
+ if (!normalizedMessage)
998
+ return 'text';
999
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
1000
+ return 'reaction';
1001
+ }
1002
+ if (normalizedMessage.pollCreationMessage ||
1003
+ normalizedMessage.pollCreationMessageV2 ||
1004
+ normalizedMessage.pollCreationMessageV3 ||
1005
+ normalizedMessage.pollCreationMessageV4 ||
1006
+ normalizedMessage.pollCreationMessageV5 ||
1007
+ normalizedMessage.pollUpdateMessage) {
1008
+ return 'poll';
1009
+ }
1010
+ if (normalizedMessage.eventMessage) {
1011
+ return 'event';
1012
+ }
1013
+ if (getMediaType(normalizedMessage) !== '') {
1014
+ return 'media';
1015
+ }
1016
+ return 'text';
1017
+ };
1018
+ const getMediaType = (message) => {
1019
+ if (message.imageMessage) {
1020
+ return 'image';
1021
+ }
1022
+ else if (message.videoMessage) {
1023
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1024
+ }
1025
+ else if (message.audioMessage) {
1026
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1027
+ }
1028
+ else if (message.contactMessage) {
1029
+ return 'vcard';
1030
+ }
1031
+ else if (message.documentMessage) {
1032
+ return 'document';
1033
+ }
1034
+ else if (message.contactsArrayMessage) {
1035
+ return 'contact_array';
1036
+ }
1037
+ else if (message.liveLocationMessage) {
1038
+ return 'livelocation';
1039
+ }
1040
+ else if (message.stickerMessage) {
1041
+ return 'sticker';
1042
+ }
1043
+ else if (message.listMessage) {
1044
+ return 'list';
1045
+ }
1046
+ else if (message.listResponseMessage) {
1047
+ return 'list_response';
1048
+ }
1049
+ else if (message.buttonsResponseMessage) {
1050
+ return 'buttons_response';
1051
+ }
1052
+ else if (message.orderMessage) {
1053
+ return 'order';
1054
+ }
1055
+ else if (message.productMessage) {
1056
+ return 'product';
1057
+ }
1058
+ else if (message.interactiveResponseMessage) {
1059
+ return 'native_flow_response';
1060
+ }
1061
+ else if (message.groupInviteMessage) {
1062
+ return 'url';
1063
+ }
1064
+ return '';
1065
+ };
1066
+ const getButtonType = (message) => {
1067
+ if (message.listMessage) {
1068
+ return 'list'
1069
+ }
1070
+ else if (message.buttonsMessage) {
1071
+ return 'buttons'
1072
+ }
1073
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
1074
+ return 'review_and_pay'
1075
+ }
1076
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
1077
+ return 'review_order'
1078
+ }
1079
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
1080
+ return 'payment_info'
1081
+ } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_key_info') {
1082
+ return 'payment_key_info'
1083
+ } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
1084
+ return 'payment_status'
1085
+ }
1086
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
1087
+ return 'payment_method'
1088
+ }
1089
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'catalog_message') {
1090
+ return 'catalog_message'
1091
+ }
1092
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
1093
+ return 'interactive'
1094
+ }
1095
+ else if (message.interactiveMessage?.nativeFlowMessage) {
1096
+ return 'native_flow'
1097
+ }
1098
+ };
1099
+ const getButtonArgs = (message) => {
1100
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage
1101
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name
1102
+ const nativeFlowSpecials = [
1103
+ 'mpm',
1104
+ 'cta_catalog',
1105
+ 'send_location',
1106
+ 'call_permission_request',
1107
+ 'wa_payment_transaction_details',
1108
+ 'automated_greeting_message_view_catalog'
1109
+ ]
1110
+
1111
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1112
+ return {
1113
+ tag: 'biz',
1114
+ attrs: {
1115
+ native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
1116
+ }
1117
+ }
1118
+ } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1119
+ // Only works for WhatsApp Original, not WhatsApp Business
1120
+ return {
1121
+ tag: 'biz',
1122
+ attrs: {
1123
+ actual_actors: '2',
1124
+ host_storage: '2',
1125
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1126
+ },
1127
+ content: [
1128
+ {
1129
+ tag: 'interactive',
1130
+ attrs: {
1131
+ type: 'native_flow',
1132
+ v: '1'
1133
+ },
1134
+ content: [
1135
+ {
1136
+ tag: 'native_flow',
1137
+ attrs: {
1138
+ v: '2',
1139
+ name: firstButtonName
1140
+ }
1141
+ }
1142
+ ]
1143
+ },
1144
+ {
1145
+ tag: 'quality_control',
1146
+ attrs: {
1147
+ source_type: 'third_party'
1148
+ }
1149
+ }
1150
+ ]
1151
+ }
1152
+ } else if (nativeFlow || message.buttonsMessage) {
1153
+ // It works for whatsapp original and whatsapp business
1154
+ return {
1155
+ tag: 'biz',
1156
+ attrs: {
1157
+ actual_actors: '2',
1158
+ host_storage: '2',
1159
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1160
+ },
1161
+ content: [
1162
+ {
1163
+ tag: 'interactive',
1164
+ attrs: {
1165
+ type: 'native_flow',
1166
+ v: '1'
1167
+ },
1168
+ content: [
1169
+ {
1170
+ tag: 'native_flow',
1171
+ attrs: {
1172
+ v: '9',
1173
+ name: 'mixed'
1174
+ }
1175
+ }
1176
+ ]
1177
+ },
1178
+ {
1179
+ tag: 'quality_control',
1180
+ attrs: {
1181
+ source_type: 'third_party'
1182
+ }
1183
+ }
1184
+ ]
1185
+ }
1186
+ } else if (message.listMessage) {
1187
+ return {
1188
+ tag: 'biz',
1189
+ attrs: {
1190
+ actual_actors: '2',
1191
+ host_storage: '2',
1192
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1193
+ },
1194
+ content: [
1195
+ {
1196
+ tag: 'list',
1197
+ attrs: {
1198
+ v: '2',
1199
+ type: 'product_list'
1200
+ }
1201
+ },
1202
+ {
1203
+ tag: 'quality_control',
1204
+ attrs: {
1205
+ source_type: 'third_party'
1206
+ }
1207
+ }
1208
+ ]
1209
+ }
1210
+ } else {
1211
+ return {
1212
+ tag: 'biz',
1213
+ attrs: {
1214
+ actual_actors: '2',
1215
+ host_storage: '2',
1216
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1217
+ }
1218
+ }
1219
+ }
1220
+ }
1221
+ const issuePrivacyTokens = async (jids, timestamp) => {
1222
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1223
+ const result = await query({
1224
+ tag: 'iq',
1225
+ attrs: {
1226
+ to: S_WHATSAPP_NET,
1227
+ type: 'set',
1228
+ xmlns: 'privacy'
1229
+ },
1230
+ content: [
1231
+ {
1232
+ tag: 'tokens',
1233
+ attrs: {},
1234
+ content: jids.map(jid => ({
1235
+ tag: 'token',
1236
+ attrs: {
1237
+ jid: jidNormalizedUser(jid),
1238
+ t,
1239
+ type: 'trusted_contact'
1240
+ }
1241
+ }))
1242
+ }
1243
+ ]
1244
+ });
1245
+ return result;
1246
+ };
1247
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1248
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1249
+ registerSocketEndHandler(() => {
1250
+ if (!config.userDevicesCache && userDevicesCache.close) {
1251
+ userDevicesCache.close();
1252
+ }
1253
+ mediaConn = undefined;
1254
+ if (messageRetryManager) {
1255
+ messageRetryManager.clear();
1256
+ }
1257
+ });
1258
+ return {
1259
+ ...sock,
1260
+ userDevicesCache,
1261
+ devicesMutex,
1262
+ issuePrivacyTokens,
1263
+ assertSessions,
1264
+ /** Current AntiBanned warm-up status for this number, or null if antiBanned isn't enabled. */
1265
+ getAntiBannedStatus: () => numberWarmUp ? numberWarmUp.getStatus() : null,
1266
+ /** Persist alongside your auth state to keep the warm-up ramp across restarts. */
1267
+ exportAntiBannedState: () => numberWarmUp ? numberWarmUp.exportState() : null,
1268
+ /** Every "first-time DM" the recipient guard has flagged (or blocked) so far. */
1269
+ getFlaggedRecipients: () => [...flaggedRecipients],
1270
+ /**
1271
+ * Post a WhatsApp Status (story) and notify specific people/groups that
1272
+ * they were mentioned in it (group JIDs are expanded to their members).
1273
+ * See README.md → "Posting a Status with mentions".
1274
+ */
1275
+ sendStatusWhatsApp: async (content, jids = []) => {
1276
+ const luki = new imup(Utils_1, waUploadToServer, relayMessage, {
1277
+ authState,
1278
+ groupMetadata,
1279
+ logger,
1280
+ linkPreviewImageThumbnailWidth,
1281
+ generateHighQualityLinkPreview,
1282
+ mediaCache: config.mediaCache,
1283
+ options: httpRequestOptions
1284
+ });
1285
+ return luki.sendStatusWhatsApp(content, jids);
1286
+ },
1287
+ relayMessage,
1288
+ sendReceipt,
1289
+ sendReceipts,
1290
+ readMessages,
1291
+ refreshMediaConn,
1292
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1293
+ getMediaHost: () => mediaHost,
1294
+ waUploadToServer,
1295
+ fetchPrivacySettings,
1296
+ sendPeerDataOperationMessage,
1297
+ createParticipantNodes,
1298
+ getUSyncDevices,
1299
+ messageRetryManager,
1300
+ updateMemberLabel,
1301
+ updateMediaMessage: async (message) => {
1302
+ const content = assertMediaContent(message.message);
1303
+ const mediaKey = content.mediaKey;
1304
+ const meId = authState.creds.me.id;
1305
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1306
+ let error = undefined;
1307
+ await Promise.all([
1308
+ sendNode(node),
1309
+ waitForMsgMediaUpdate(async (update) => {
1310
+ const result = update.find(c => c.key.id === message.key.id);
1311
+ if (result) {
1312
+ if (result.error) {
1313
+ error = result.error;
1314
+ }
1315
+ else {
1316
+ try {
1317
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1318
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1319
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1320
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1321
+ data: media,
1322
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1323
+ });
1324
+ }
1325
+ content.directPath = media.directPath;
1326
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1327
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1328
+ }
1329
+ catch (err) {
1330
+ error = err;
1331
+ }
1332
+ }
1333
+ return true;
1334
+ }
1335
+ })
1336
+ ]);
1337
+ if (error) {
1338
+ throw error;
1339
+ }
1340
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1341
+ return message;
1342
+ },
1343
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1344
+ const { message, messageId } = Utils_1.generateTableContent(title, headers, rows, quoted, options)
1345
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1346
+ return { message, messageId }
1347
+ },
1348
+ sendList: async (jid, title, items, quoted, options = {}) => {
1349
+ const { message, messageId } = Utils_1.generateListContent(title, items, quoted, options)
1350
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1351
+ return { message, messageId }
1352
+ },
1353
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1354
+ const { message, messageId } = Utils_1.generateCodeBlockContent(code, quoted, options)
1355
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1356
+ return { message, messageId }
1357
+ },
1358
+ sendLatex: async (jid, quoted, options) => {
1359
+ const { message, messageId } = Utils_1.generateLatexContent(quoted, options)
1360
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1361
+ return { message, messageId }
1362
+ },
1363
+ sendLatexImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1364
+ const { message, messageId } = await Utils_1.generateLatexImageContent(
1365
+ quoted,
1366
+ options,
1367
+ uploadFn,
1368
+ renderLatexToPng
1369
+ )
1370
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1371
+ return { message, messageId }
1372
+ },
1373
+ sendLatexInlineImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1374
+ const { message, messageId } = await Utils_1.generateLatexInlineImageContent(
1375
+ quoted,
1376
+ options,
1377
+ uploadFn,
1378
+ renderLatexToPng
1379
+ )
1380
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1381
+ return { message, messageId }
1382
+ },
1383
+ captureUnifiedResponse: Utils_1.captureUnifiedResponse,
1384
+ sendUnifiedResponse: async (jid, quoted, captured) => {
1385
+ const { message, messageId } = Utils_1.generateUnifiedResponseContent(quoted, captured)
1386
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1387
+ return { message, messageId }
1388
+ },
1389
+ sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1390
+ const { message, messageId } = Utils_1.generateRichMessageContent(submessages, quoted, options)
1391
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1392
+ return { message, messageId }
1393
+ },
1394
+ sendMessage: async (jid, content, options = {}) => {
1395
+ if (numberWarmUp && !isJidGroup(jid) && !isJidBot(jid)) {
1396
+ if (!numberWarmUp.canSend()) {
1397
+ const status = numberWarmUp.getStatus();
1398
+ logger?.warn?.({ jid, status }, 'antiBanned: daily warm-up limit reached for this number');
1399
+ if (antiBannedAction === 'block') {
1400
+ console.warn(`[xayz-baileys] \u{1F6E1} AntiBanned: message to ${jid} blocked — warm-up day ${status.day}/${status.totalWarmUpDays}, limit ${status.todayLimit}/day reached.`);
1401
+ return { blocked: true, reason: 'antiBanned-warmup', status };
1402
+ }
1403
+ console.warn(`[xayz-baileys] \u{1F6E1} AntiBanned: pausing before sending to ${jid} — warm-up day ${status.day}/${status.totalWarmUpDays}, limit ${status.todayLimit}/day reached.`);
1404
+ await delay(antiBannedConfig?.delayMs ?? 60000);
1405
+ }
1406
+ numberWarmUp.record();
1407
+ }
1408
+ if (recipientGuardEnabled && !isJidGroup(jid) && !isJidBroadcast(jid) && !isJidNewsletter(jid) && !isJidBot(jid) && !isJidMetaAI(jid)) {
1409
+ if (!knownRecipients.has(jid)) {
1410
+ flaggedRecipients.push({ jid, at: new Date().toISOString() });
1411
+ if (flaggedRecipients.length > resolvedGuardLogMax) {
1412
+ flaggedRecipients.shift();
1413
+ }
1414
+ logger?.info?.({ jid }, 'recipientGuard: first-time outgoing DM to a JID that has not messaged you');
1415
+ console.warn(`[xayz-baileys] \u{1F440} First-time DM to ${jid} — hasn't messaged you first and isn't allowlisted.`);
1416
+ if (blockUnknownRecipients) {
1417
+ console.warn(`[xayz-baileys] \u{1F6E1} Blocked (blockUnknownRecipients: true). Set { allowedRecipients: ['${jid}'] } to allow it.`);
1418
+ return { blocked: true, jid, reason: 'unknown-recipient' };
1419
+ }
1420
+ knownRecipients.add(jid);
1421
+ }
1422
+ }
1423
+ const userJid = authState.creds.me.id;
1424
+ const luki = new imup(Utils_1, waUploadToServer, relayMessage, {
1425
+ authState,
1426
+ groupMetadata,
1427
+ logger,
1428
+ linkPreviewImageThumbnailWidth,
1429
+ generateHighQualityLinkPreview,
1430
+ mediaCache: config.mediaCache,
1431
+ options: httpRequestOptions
1432
+ })
1433
+ const { quoted, participant = false } = options;
1434
+ const messageType = luki.detectType(content);
1435
+ if (typeof content === 'object' &&
1436
+ 'disappearingMessagesInChat' in content &&
1437
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1438
+ isJidGroup(jid)) {
1439
+ const { disappearingMessagesInChat } = content;
1440
+ const value = typeof disappearingMessagesInChat === 'boolean'
1441
+ ? disappearingMessagesInChat
1442
+ ? WA_DEFAULT_EPHEMERAL
1443
+ : 0
1444
+ : disappearingMessagesInChat;
1445
+ await groupToggleEphemeral(jid, value);
1446
+ }
1447
+ else {
1448
+ if (messageType) {
1449
+ switch(messageType) {
1450
+ case 'PAYMENT':
1451
+ const paymentContent = await luki.handlePayment(content, quoted);
1452
+ return await relayMessage(jid, paymentContent, {
1453
+ messageId: Utils_1.generateMessageID(),
1454
+ noSelfSync: options.noSelfSync
1455
+ });
1456
+ case 'PRODUCT':
1457
+ const productContent = await luki.handleProduct(content, jid, quoted);
1458
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
1459
+ return await relayMessage(jid, productMsg.message, {
1460
+ messageId: productMsg.key.id,
1461
+ noSelfSync: options.noSelfSync
1462
+ });
1463
+
1464
+ case 'ALBUM':
1465
+ return await luki.handleAlbum(content, jid, quoted)
1466
+ case 'EVENT':
1467
+ return await luki.handleEvent(content, jid, quoted)
1468
+ case 'POLL_RESULT':
1469
+ return await luki.handlePollResult(content, jid, quoted)
1470
+ case 'ORDER':
1471
+ return await luki.handleOrderMessage(content, jid, quoted)
1472
+ case 'GROUP_STATUS':
1473
+ return await luki.handleGroupStory(content, jid, quoted)
1474
+ case 'GROUP_LABEL':
1475
+ return await luki.handleGbLabel(content, jid)
1476
+ }
1477
+ }
1478
+ const fullMsg = await generateWAMessage(jid, content, {
1479
+ logger,
1480
+ userJid,
1481
+ getUrlInfo: text => getUrlInfo(text, {
1482
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1483
+ fetchOpts: {
1484
+ timeout: 3000,
1485
+ ...(httpRequestOptions || {})
1486
+ },
1487
+ logger,
1488
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1489
+ }),
1490
+ //TODO: CACHE
1491
+ getProfilePicUrl: sock.profilePictureUrl,
1492
+ getCallLink: sock.createCallLink,
1493
+ upload: waUploadToServer,
1494
+ mediaCache: config.mediaCache,
1495
+ options: config.options,
1496
+ messageId: generateMessageIDV2(sock.user?.id),
1497
+ ...options
1498
+ });
1499
+ const isEventMsg = 'event' in content && !!content.event;
1500
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1501
+ const isEditMsg = 'edit' in content && !!content.edit;
1502
+ const isPinMsg = 'pin' in content && !!content.pin;
1503
+ const isPollMessage = 'poll' in content && !!content.poll;
1504
+ const additionalAttributes = {};
1505
+ const additionalNodes = [];
1506
+ // required for delete
1507
+ if (isDeleteMsg) {
1508
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1509
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1510
+ additionalAttributes.edit = '8';
1511
+ }
1512
+ else {
1513
+ additionalAttributes.edit = '7';
1514
+ }
1515
+ }
1516
+ else if (isEditMsg) {
1517
+ additionalAttributes.edit = '1';
1518
+ }
1519
+ else if (isPinMsg) {
1520
+ additionalAttributes.edit = '2';
1521
+ }
1522
+ else if (isPollMessage) {
1523
+ additionalNodes.push({
1524
+ tag: 'meta',
1525
+ attrs: {
1526
+ polltype: 'creation'
1527
+ }
1528
+ });
1529
+ }
1530
+ else if (isEventMsg) {
1531
+ additionalNodes.push({
1532
+ tag: 'meta',
1533
+ attrs: {
1534
+ event_type: 'creation'
1535
+ }
1536
+ });
1537
+ }
1538
+ await relayMessage(jid, fullMsg.message, {
1539
+ messageId: fullMsg.key.id,
1540
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1541
+ additionalAttributes,
1542
+ statusJidList: options.statusJidList,
1543
+ additionalNodes: aiLabel ? additionalNodes : options.additionalNodes,
1544
+ participant,
1545
+ noSelfSync: options.noSelfSync
1546
+ });
1547
+ if (config.emitOwnEvents) {
1548
+ process.nextTick(async () => {
1549
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1550
+ });
1551
+ }
1552
+ return fullMsg;
1553
+ }
1554
+ },
1555
+ sendMessageMembers: async (jid, message, options = {}) => {
1556
+ const {
1557
+ messageId: idm,
1558
+ quoted,
1559
+ delayMs = 1500,
1560
+ useUserDevicesCache = true,
1561
+ cachedGroupMetadata,
1562
+ onlyMember = true
1563
+ } = options;
1564
+ const { server } = jidDecode(jid);
1565
+ if (server !== "g.us") throw new Error("@g.us server required");
1566
+ const meId = authState.creds.me.id;
1567
+ const messages = Utils_1.normalizeMessageContent(message);
1568
+ const groupData = cachedGroupMetadata? await cachedGroupMetadata(jid) : await groupMetadata(jid);
1569
+ const isLid = groupData.addressingMode === "lid";
1570
+ const adminJids = groupData.participants.filter((x) => x.admin !== null).map((y) => y.id)
1571
+ let participantJids = groupData.participants.map(z => z.id);
1572
+ if (onlyMember) {
1573
+ // Fix: array selalu truthy di JS meski kosong ([] ? true).
1574
+ // Cek .length supaya fallback ke semua member beneran jalan
1575
+ // kalau data admin kosong, bukan diam-diam kirim ke 0 orang.
1576
+ participantJids = adminJids.length ? adminJids : participantJids;
1577
+ }
1578
+ logger.info(`Sending message to ${participantJids.length} members from ${jid}`);
1579
+ for (let i = 0; i < participantJids.length; i++) {
1580
+ const jid = participantJids[i];
1581
+ if (areJidsSameUser(jid, meId)) continue;
1582
+ try {
1583
+ const msgId = `${idm || Utils_1.generateMessageID()}_${i}`;
1584
+ const fullMsg = await Utils_1.generateWAMessageFromContent(jid, message, {
1585
+ messageId: msgId,
1586
+ quoted
1587
+ })
1588
+ await relayMessage(jid, fullMsg.message, {
1589
+ messageId: fullMsg.key.id,
1590
+ useUserDevicesCache,
1591
+ noSelfSync: options.noSelfSync
1592
+ });
1593
+ logger.debug(`Message successfully sent to ${jid}`);
1594
+ if (delayMs && i < participantJids.length - 1) {
1595
+ await new Promise(z => setTimeout(z, delayMs));
1596
+ }
1597
+ } catch (e) {
1598
+ logger.error({ jid, e }, "Error sending message to");
1599
+ }
1600
+ }
1601
+ return JSON.stringify({
1602
+ members_total: participantJids.length,
1603
+ message
1604
+ }, null, 4);
1605
+ }
1606
+ };
1607
+ };
1608
+ //# sourceMappingURL=messages-send.js.map