@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.
Files changed (330) hide show
  1. package/WAProto/GenerateStatics.sh +2 -2
  2. package/WAProto/WAProto.proto +1339 -493
  3. package/WAProto/fix-imports.js +79 -14
  4. package/WAProto/index.d.ts +5274 -1945
  5. package/WAProto/index.js +97691 -1
  6. package/lib/Defaults/index.d.ts +25 -8
  7. package/lib/Defaults/index.d.ts.map +1 -1
  8. package/lib/Defaults/index.js +124 -109
  9. package/lib/Defaults/index.js.map +1 -1
  10. package/lib/Signal/Group/ciphertext-message.js +11 -15
  11. package/lib/Signal/Group/group-session-builder.js +27 -32
  12. package/lib/Signal/Group/group_cipher.d.ts +1 -2
  13. package/lib/Signal/Group/group_cipher.d.ts.map +1 -1
  14. package/lib/Signal/Group/group_cipher.js +75 -92
  15. package/lib/Signal/Group/group_cipher.js.map +1 -1
  16. package/lib/Signal/Group/index.js +12 -77
  17. package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
  18. package/lib/Signal/Group/keyhelper.js +16 -24
  19. package/lib/Signal/Group/keyhelper.js.map +1 -1
  20. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  21. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -1
  22. package/lib/Signal/Group/sender-chain-key.js +24 -34
  23. package/lib/Signal/Group/sender-chain-key.js.map +1 -1
  24. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -1
  25. package/lib/Signal/Group/sender-key-distribution-message.js +62 -58
  26. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -1
  27. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -1
  28. package/lib/Signal/Group/sender-key-message.js +64 -65
  29. package/lib/Signal/Group/sender-key-message.js.map +1 -1
  30. package/lib/Signal/Group/sender-key-name.js +41 -44
  31. package/lib/Signal/Group/sender-key-record.d.ts +1 -1
  32. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -1
  33. package/lib/Signal/Group/sender-key-record.js +36 -47
  34. package/lib/Signal/Group/sender-key-record.js.map +1 -1
  35. package/lib/Signal/Group/sender-key-state.d.ts +4 -4
  36. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -1
  37. package/lib/Signal/Group/sender-key-state.js +76 -93
  38. package/lib/Signal/Group/sender-key-state.js.map +1 -1
  39. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -1
  40. package/lib/Signal/Group/sender-message-key.js +25 -31
  41. package/lib/Signal/Group/sender-message-key.js.map +1 -1
  42. package/lib/Signal/libsignal.d.ts +4 -7
  43. package/lib/Signal/libsignal.d.ts.map +1 -1
  44. package/lib/Signal/libsignal.js +417 -401
  45. package/lib/Signal/libsignal.js.map +1 -1
  46. package/lib/Signal/lid-mapping.d.ts +16 -23
  47. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  48. package/lib/Signal/lid-mapping.js +273 -108
  49. package/lib/Signal/lid-mapping.js.map +1 -1
  50. package/lib/Socket/Client/index.js +3 -25
  51. package/lib/Socket/Client/types.d.ts +2 -2
  52. package/lib/Socket/Client/types.d.ts.map +1 -1
  53. package/lib/Socket/Client/types.js +10 -14
  54. package/lib/Socket/Client/websocket.d.ts +1 -1
  55. package/lib/Socket/Client/websocket.d.ts.map +1 -1
  56. package/lib/Socket/Client/websocket.js +53 -54
  57. package/lib/Socket/Client/websocket.js.map +1 -1
  58. package/lib/Socket/business.d.ts +45 -16
  59. package/lib/Socket/business.d.ts.map +1 -1
  60. package/lib/Socket/business.js +374 -360
  61. package/lib/Socket/business.js.map +1 -1
  62. package/lib/Socket/chats.d.ts +34 -8
  63. package/lib/Socket/chats.d.ts.map +1 -1
  64. package/lib/Socket/chats.js +1162 -1038
  65. package/lib/Socket/chats.js.map +1 -1
  66. package/lib/Socket/communities.d.ts +56 -16
  67. package/lib/Socket/communities.d.ts.map +1 -1
  68. package/lib/Socket/communities.js +418 -466
  69. package/lib/Socket/communities.js.map +1 -1
  70. package/lib/Socket/groups.d.ts +32 -8
  71. package/lib/Socket/groups.d.ts.map +1 -1
  72. package/lib/Socket/groups.js +337 -390
  73. package/lib/Socket/groups.js.map +1 -1
  74. package/lib/Socket/index.d.ts +56 -16
  75. package/lib/Socket/index.d.ts.map +1 -1
  76. package/lib/Socket/index.js +10 -18
  77. package/lib/Socket/index.js.map +1 -1
  78. package/lib/Socket/messages-recv.d.ts +49 -19
  79. package/lib/Socket/messages-recv.d.ts.map +1 -1
  80. package/lib/Socket/messages-recv.js +1738 -1391
  81. package/lib/Socket/messages-recv.js.map +1 -1
  82. package/lib/Socket/messages-send.d.ts +45 -15
  83. package/lib/Socket/messages-send.d.ts.map +1 -1
  84. package/lib/Socket/messages-send.js +1101 -1242
  85. package/lib/Socket/messages-send.js.map +1 -1
  86. package/lib/Socket/mex.js +38 -48
  87. package/lib/Socket/newsletter.d.ts +30 -7
  88. package/lib/Socket/newsletter.d.ts.map +1 -1
  89. package/lib/Socket/newsletter.js +175 -222
  90. package/lib/Socket/newsletter.js.map +1 -1
  91. package/lib/Socket/socket.d.ts +15 -6
  92. package/lib/Socket/socket.d.ts.map +1 -1
  93. package/lib/Socket/socket.js +932 -913
  94. package/lib/Socket/socket.js.map +1 -1
  95. package/lib/Types/Auth.d.ts +12 -0
  96. package/lib/Types/Auth.d.ts.map +1 -1
  97. package/lib/Types/Auth.js +2 -3
  98. package/lib/Types/Bussines.js +2 -3
  99. package/lib/Types/Call.d.ts +2 -1
  100. package/lib/Types/Call.d.ts.map +1 -1
  101. package/lib/Types/Call.js +2 -3
  102. package/lib/Types/Chat.d.ts +1 -0
  103. package/lib/Types/Chat.d.ts.map +1 -1
  104. package/lib/Types/Chat.js +8 -5
  105. package/lib/Types/Contact.d.ts +2 -0
  106. package/lib/Types/Contact.d.ts.map +1 -1
  107. package/lib/Types/Contact.js +2 -3
  108. package/lib/Types/Events.d.ts +66 -9
  109. package/lib/Types/Events.d.ts.map +1 -1
  110. package/lib/Types/Events.js +2 -1
  111. package/lib/Types/GroupMetadata.d.ts +5 -0
  112. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  113. package/lib/Types/GroupMetadata.js +2 -3
  114. package/lib/Types/Label.js +23 -26
  115. package/lib/Types/LabelAssociation.js +5 -8
  116. package/lib/Types/Message.d.ts +31 -11
  117. package/lib/Types/Message.d.ts.map +1 -1
  118. package/lib/Types/Message.js +9 -18
  119. package/lib/Types/Message.js.map +1 -1
  120. package/lib/Types/{Newsletter.d.ts → Mex.d.ts} +11 -5
  121. package/lib/Types/Mex.d.ts.map +1 -0
  122. package/lib/Types/Mex.js +37 -0
  123. package/lib/Types/Mex.js.map +1 -0
  124. package/lib/Types/Product.js +2 -3
  125. package/lib/Types/Signal.d.ts +21 -16
  126. package/lib/Types/Signal.d.ts.map +1 -1
  127. package/lib/Types/Signal.js +2 -1
  128. package/lib/Types/Socket.d.ts +23 -17
  129. package/lib/Types/Socket.d.ts.map +1 -1
  130. package/lib/Types/Socket.js +3 -2
  131. package/lib/Types/Socket.js.map +1 -1
  132. package/lib/Types/State.d.ts +58 -0
  133. package/lib/Types/State.d.ts.map +1 -1
  134. package/lib/Types/State.js +55 -15
  135. package/lib/Types/State.js.map +1 -1
  136. package/lib/Types/USync.js +2 -1
  137. package/lib/Types/index.d.ts +1 -1
  138. package/lib/Types/index.d.ts.map +1 -1
  139. package/lib/Types/index.js +25 -163
  140. package/lib/Types/index.js.map +1 -1
  141. package/lib/Utils/auth-utils.d.ts +7 -2
  142. package/lib/Utils/auth-utils.d.ts.map +1 -1
  143. package/lib/Utils/auth-utils.js +272 -458
  144. package/lib/Utils/auth-utils.js.map +1 -1
  145. package/lib/Utils/browser-utils.d.ts +4 -0
  146. package/lib/Utils/browser-utils.d.ts.map +1 -0
  147. package/lib/Utils/browser-utils.js +28 -0
  148. package/lib/Utils/browser-utils.js.map +1 -0
  149. package/lib/Utils/business.js +208 -221
  150. package/lib/Utils/chat-utils.d.ts +35 -6
  151. package/lib/Utils/chat-utils.d.ts.map +1 -1
  152. package/lib/Utils/chat-utils.js +828 -800
  153. package/lib/Utils/chat-utils.js.map +1 -1
  154. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  155. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  156. package/lib/Utils/companion-reg-client-utils.js +35 -0
  157. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  158. package/lib/Utils/crypto.d.ts +7 -11
  159. package/lib/Utils/crypto.d.ts.map +1 -1
  160. package/lib/Utils/crypto.js +88 -142
  161. package/lib/Utils/crypto.js.map +1 -1
  162. package/lib/Utils/decode-wa-message.d.ts +22 -2
  163. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  164. package/lib/Utils/decode-wa-message.js +293 -261
  165. package/lib/Utils/decode-wa-message.js.map +1 -1
  166. package/lib/Utils/event-buffer.d.ts +2 -0
  167. package/lib/Utils/event-buffer.d.ts.map +1 -1
  168. package/lib/Utils/event-buffer.js +599 -558
  169. package/lib/Utils/event-buffer.js.map +1 -1
  170. package/lib/Utils/generics.d.ts +6 -7
  171. package/lib/Utils/generics.d.ts.map +1 -1
  172. package/lib/Utils/generics.js +331 -362
  173. package/lib/Utils/generics.js.map +1 -1
  174. package/lib/Utils/history.d.ts +14 -10
  175. package/lib/Utils/history.d.ts.map +1 -1
  176. package/lib/Utils/history.js +129 -93
  177. package/lib/Utils/history.js.map +1 -1
  178. package/lib/Utils/identity-change-handler.d.ts +44 -0
  179. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  180. package/lib/Utils/identity-change-handler.js +50 -0
  181. package/lib/Utils/identity-change-handler.js.map +1 -0
  182. package/lib/Utils/index.d.ts +4 -4
  183. package/lib/Utils/index.d.ts.map +1 -1
  184. package/lib/Utils/index.js +22 -234
  185. package/lib/Utils/index.js.map +1 -1
  186. package/lib/Utils/link-preview.d.ts +1 -2
  187. package/lib/Utils/link-preview.d.ts.map +1 -1
  188. package/lib/Utils/link-preview.js +69 -83
  189. package/lib/Utils/link-preview.js.map +1 -1
  190. package/lib/Utils/logger.js +3 -9
  191. package/lib/Utils/lt-hash.d.ts +7 -12
  192. package/lib/Utils/lt-hash.d.ts.map +1 -1
  193. package/lib/Utils/lt-hash.js +3 -50
  194. package/lib/Utils/lt-hash.js.map +1 -1
  195. package/lib/Utils/make-mutex.d.ts +1 -0
  196. package/lib/Utils/make-mutex.d.ts.map +1 -1
  197. package/lib/Utils/make-mutex.js +30 -40
  198. package/lib/Utils/make-mutex.js.map +1 -1
  199. package/lib/Utils/message-retry-manager.d.ts +38 -5
  200. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  201. package/lib/Utils/message-retry-manager.js +259 -159
  202. package/lib/Utils/message-retry-manager.js.map +1 -1
  203. package/lib/Utils/messages-media.d.ts +30 -10
  204. package/lib/Utils/messages-media.d.ts.map +1 -1
  205. package/lib/Utils/messages-media.js +734 -710
  206. package/lib/Utils/messages-media.js.map +1 -1
  207. package/lib/Utils/messages.d.ts +19 -4
  208. package/lib/Utils/messages.d.ts.map +1 -1
  209. package/lib/Utils/messages.js +817 -800
  210. package/lib/Utils/messages.js.map +1 -1
  211. package/lib/Utils/noise-handler.d.ts +4 -4
  212. package/lib/Utils/noise-handler.d.ts.map +1 -1
  213. package/lib/Utils/noise-handler.js +195 -165
  214. package/lib/Utils/noise-handler.js.map +1 -1
  215. package/lib/Utils/offline-node-processor.d.ts +17 -0
  216. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  217. package/lib/Utils/offline-node-processor.js +40 -0
  218. package/lib/Utils/offline-node-processor.js.map +1 -0
  219. package/lib/Utils/pre-key-manager.d.ts +28 -0
  220. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  221. package/lib/Utils/pre-key-manager.js +106 -0
  222. package/lib/Utils/pre-key-manager.js.map +1 -0
  223. package/lib/Utils/process-message.d.ts +26 -9
  224. package/lib/Utils/process-message.d.ts.map +1 -1
  225. package/lib/Utils/process-message.js +601 -422
  226. package/lib/Utils/process-message.js.map +1 -1
  227. package/lib/Utils/reporting-utils.d.ts +11 -0
  228. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  229. package/lib/Utils/reporting-utils.js +258 -0
  230. package/lib/Utils/reporting-utils.js.map +1 -0
  231. package/lib/Utils/signal.d.ts +17 -4
  232. package/lib/Utils/signal.d.ts.map +1 -1
  233. package/lib/Utils/signal.js +180 -203
  234. package/lib/Utils/signal.js.map +1 -1
  235. package/lib/Utils/stanza-ack.d.ts +11 -0
  236. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  237. package/lib/Utils/stanza-ack.js +38 -0
  238. package/lib/Utils/stanza-ack.js.map +1 -0
  239. package/lib/Utils/sync-action-utils.d.ts +19 -0
  240. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  241. package/lib/Utils/sync-action-utils.js +49 -0
  242. package/lib/Utils/sync-action-utils.js.map +1 -0
  243. package/lib/Utils/tc-token-utils.d.ts +37 -0
  244. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  245. package/lib/Utils/tc-token-utils.js +163 -0
  246. package/lib/Utils/tc-token-utils.js.map +1 -0
  247. package/lib/Utils/use-multi-file-auth-state.js +98 -98
  248. package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
  249. package/lib/Utils/validate-connection.d.ts.map +1 -1
  250. package/lib/Utils/validate-connection.js +191 -185
  251. package/lib/Utils/validate-connection.js.map +1 -1
  252. package/lib/WABinary/constants.js +1297 -35
  253. package/lib/WABinary/decode.d.ts.map +1 -1
  254. package/lib/WABinary/decode.js +254 -229
  255. package/lib/WABinary/decode.js.map +1 -1
  256. package/lib/WABinary/encode.js +210 -209
  257. package/lib/WABinary/encode.js.map +1 -1
  258. package/lib/WABinary/generic-utils.d.ts +1 -1
  259. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  260. package/lib/WABinary/generic-utils.js +99 -105
  261. package/lib/WABinary/generic-utils.js.map +1 -1
  262. package/lib/WABinary/index.js +6 -58
  263. package/lib/WABinary/jid-utils.d.ts +12 -1
  264. package/lib/WABinary/jid-utils.d.ts.map +1 -1
  265. package/lib/WABinary/jid-utils.js +83 -67
  266. package/lib/WABinary/jid-utils.js.map +1 -1
  267. package/lib/WABinary/types.js +2 -2
  268. package/lib/WAM/BinaryInfo.js +9 -13
  269. package/lib/WAM/constants.d.ts +1 -1
  270. package/lib/WAM/constants.d.ts.map +1 -1
  271. package/lib/WAM/constants.js +22853 -1
  272. package/lib/WAM/constants.js.map +1 -1
  273. package/lib/WAM/encode.js +135 -132
  274. package/lib/WAM/index.js +4 -36
  275. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  276. package/lib/WAUSync/Protocols/USyncContactProtocol.js +50 -31
  277. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  278. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -58
  279. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -29
  280. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +35 -37
  281. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +4 -2
  282. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  283. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +23 -27
  284. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  285. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +47 -61
  286. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +2 -1
  287. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -1
  288. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +27 -23
  289. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -1
  290. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  291. package/lib/WAUSync/Protocols/index.js +6 -58
  292. package/lib/WAUSync/Protocols/index.js.map +1 -1
  293. package/lib/WAUSync/USyncQuery.d.ts +1 -1
  294. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  295. package/lib/WAUSync/USyncQuery.js +94 -94
  296. package/lib/WAUSync/USyncQuery.js.map +1 -1
  297. package/lib/WAUSync/USyncUser.d.ts +4 -0
  298. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  299. package/lib/WAUSync/USyncUser.js +30 -26
  300. package/lib/WAUSync/USyncUser.js.map +1 -1
  301. package/lib/WAUSync/index.js +4 -36
  302. package/lib/index.d.ts +0 -1
  303. package/lib/index.js +11 -112
  304. package/package.json +49 -22
  305. package/README.md +0 -1315
  306. package/lib/Signal/Group/queue-job.d.ts +0 -2
  307. package/lib/Signal/Group/queue-job.js +0 -59
  308. package/lib/Store/index.d.ts +0 -4
  309. package/lib/Store/index.js +0 -47
  310. package/lib/Store/make-cache-manager-store.d.ts +0 -17
  311. package/lib/Store/make-cache-manager-store.js +0 -104
  312. package/lib/Store/make-in-memory-store.d.ts +0 -118
  313. package/lib/Store/make-in-memory-store.js +0 -490
  314. package/lib/Store/make-ordered-dictionary.d.ts +0 -14
  315. package/lib/Store/make-ordered-dictionary.js +0 -81
  316. package/lib/Store/object-repository.d.ts +0 -10
  317. package/lib/Store/object-repository.js +0 -30
  318. package/lib/Types/Newsletter.d.ts.map +0 -1
  319. package/lib/Types/Newsletter.js +0 -34
  320. package/lib/Types/Newsletter.js.map +0 -1
  321. package/lib/Utils/baileys-event-stream.d.ts +0 -17
  322. package/lib/Utils/baileys-event-stream.d.ts.map +0 -1
  323. package/lib/Utils/baileys-event-stream.js +0 -71
  324. package/lib/Utils/baileys-event-stream.js.map +0 -1
  325. package/lib/Utils/extended-messages.d.ts +0 -73
  326. package/lib/Utils/extended-messages.js +0 -283
  327. package/lib/Utils/lid-resolver.d.ts +0 -17
  328. package/lib/Utils/lid-resolver.js +0 -79
  329. package/lib/Utils/mention.d.ts +0 -27
  330. package/lib/Utils/mention.js +0 -135
@@ -1,1286 +1,1145 @@
1
- Object.defineProperty(exports, "__esModule", {
2
- value: true
3
- });
4
- exports.makeMessagesSocket = void 0;
5
- var _nodeCache = _interopRequireDefault(require("@cacheable/node-cache"));
6
- var _boom = require("@hapi/boom");
7
- var _index = require("../../WAProto/index.js");
8
- var _index2 = require("../Defaults/index.js");
9
- var _index3 = require("../Types/index.js");
10
- var _index4 = require("../Utils/index.js");
11
- var _extendedMessages = require("../Utils/extended-messages.js");
12
- var _linkPreview = require("../Utils/link-preview.js");
13
- var _makeMutex = require("../Utils/make-mutex.js");
14
- var _index5 = require("../WABinary/index.js");
15
- var _index6 = require("../WAUSync/index.js");
16
- var _newsletter = require("./newsletter.js");
17
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
18
- const makeMessagesSocket = config => {
19
- const {
20
- logger,
21
- linkPreviewImageThumbnailWidth,
22
- generateHighQualityLinkPreview,
23
- options: axiosOptions,
24
- patchMessageBeforeSending,
25
- cachedGroupMetadata,
26
- enableRecentMessageCache,
27
- maxMsgRetryCount
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
- const mediaConnNode = (0, _index5.getBinaryNodeChild)(result, 'media_conn');
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
- hosts: (0, _index5.getBinaryNodeChildren)(mediaConnNode, 'host').map(({
71
- attrs
72
- }) => ({
73
- hostname: attrs.hostname,
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
- logger.debug('fetched media conn');
81
- return node;
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
- filteredJids.push(jid);
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
- } else {
223
- toFetch.push(jid);
224
- }
225
- }
226
- if (!toFetch.length) {
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
- for (const key in deviceMap) {
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
- // Add to fetch list if no session exists
305
- if (!hasSession) {
306
- if (jid.includes('@lid')) {
307
- logger.debug({
308
- jid
309
- }, 'No LID session found, will create new LID session');
310
- }
311
- jidsRequiringFetch.push(jid);
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
- // Process all JIDs
315
- for (const jid of jids) {
316
- await checkJidSession(jid);
317
- }
318
- } else {
319
- const lidMapping = signalRepository.getLIDMappingStore();
320
- const addrs = jids.map(jid => signalRepository.jidToSignalProtocolAddress(jid));
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
- userGroups.get(user).push(jid);
330
- }
331
- // Helper to check LID mapping for a user
332
- const checkUserLidMapping = async (user, userJids) => {
333
- if (!userJids.some(jid => jid.includes('@s.whatsapp.net'))) {
334
- return {
335
- shouldMigrate: false,
336
- lidForPN: undefined
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
- try {
340
- const mapping = await lidMapping.getLIDForPN(user);
341
- if (mapping?.includes('@lid')) {
342
- logger.debug({
343
- user,
344
- lidForPN: mapping,
345
- deviceCount: userJids.length
346
- }, 'User has LID mapping - preparing bulk migration');
347
- return {
348
- shouldMigrate: true,
349
- lidForPN: mapping
350
- };
351
- }
352
- } catch (error) {
353
- logger.debug({
354
- user,
355
- error
356
- }, 'Failed to check LID mapping for user');
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
- return {
359
- shouldMigrate: false,
360
- lidForPN: undefined
361
- };
362
- };
363
- // Helper to migrate a single device
364
- const migrateDeviceToLid = async (jid, lidForPN) => {
365
- if (!jid.includes('@s.whatsapp.net')) return;
366
- try {
367
- const lidWithDevice = (0, _index5.transferDevice)(jid, lidForPN);
368
- await signalRepository.migrateSession(jid, lidWithDevice);
369
- logger.debug({
370
- fromJid: jid,
371
- toJid: lidWithDevice
372
- }, 'Migrated device session to LID');
373
- // Delete PN session after successful migration
374
- try {
375
- await signalRepository.deleteSession(jid);
376
- logger.debug({
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
- // Process each user group for potential bulk LID migration
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
- // Helper to check session for migrated user
410
- const checkMigratedSession = async jid => {
411
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
412
- let hasSession = !!sessions[signalId];
413
- let jidToFetch = jid;
414
- // Check if we should use migrated LID session instead
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
- if (jidsRequiringFetch.length) {
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
- // Find overlaps
465
- const overlapping = Array.from(pnUsersBeingFetched).filter(user => lidUsersBeingFetched.has(user));
466
- if (overlapping.length > 0) {
467
- logger.warn({
468
- overlapping,
469
- lidUsersBeingFetched: Array.from(lidUsersBeingFetched),
470
- pnUsersBeingFetched: Array.from(pnUsersBeingFetched)
471
- }, 'Fetching both LID and PN sessions for same users');
472
- }
473
- const result = await query({
474
- tag: 'iq',
475
- attrs: {
476
- xmlns: 'encrypt',
477
- type: 'get',
478
- to: _index5.S_WHATSAPP_NET
479
- },
480
- content: [{
481
- tag: 'key',
482
- attrs: {},
483
- content: jidsRequiringFetch.map(jid => ({
484
- tag: 'user',
485
- attrs: {
486
- jid
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
- await (0, _index4.parseAndInjectE2ESessions)(result, signalRepository);
492
- didFetchNewSession = true;
493
- }
494
- return didFetchNewSession;
495
- };
496
- const sendPeerDataOperationMessage = async pdoMessage => {
497
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
498
- if (!authState.creds.me?.id) {
499
- throw new _boom.Boom('Not authenticated');
500
- }
501
- const protocolMessage = {
502
- protocolMessage: {
503
- peerDataOperationRequestMessage: pdoMessage,
504
- type: _index.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
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
- const meJid = (0, _index5.jidNormalizedUser)(authState.creds.me.id);
508
- const msgId = await relayMessage(meJid, protocolMessage, {
509
- additionalAttributes: {
510
- category: 'peer',
511
- push_priority: 'high_force'
512
- }
513
- });
514
- return msgId;
515
- };
516
- const createParticipantNodes = async (jids, message, extraAttrs, dsmMessage) => {
517
- let patched = await patchMessageBeforeSending(message, jids);
518
- if (!Array.isArray(patched)) {
519
- patched = jids ? jids.map(jid => ({
520
- recipientJid: jid,
521
- ...patched
522
- })) : [patched];
523
- }
524
- let shouldIncludeDeviceIdentity = false;
525
- const meId = authState.creds.me.id;
526
- const meLid = authState.creds.me?.lid;
527
- const meLidUser = meLid ? (0, _index5.jidDecode)(meLid)?.user : null;
528
- const devicesByUser = new Map();
529
- for (const patchedMessageWithJid of patched) {
530
- const {
531
- recipientJid: wireJid,
532
- ...patchedMessage
533
- } = patchedMessageWithJid;
534
- if (!wireJid) continue;
535
- // Extract user from JID for grouping
536
- const decoded = (0, _index5.jidDecode)(wireJid);
537
- const user = decoded?.user;
538
- if (!user) continue;
539
- if (!devicesByUser.has(user)) {
540
- devicesByUser.set(user, []);
541
- }
542
- devicesByUser.get(user).push({
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
- return lidWithDevice;
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
- // Encrypt to this user's devices sequentially to prevent session corruption
606
- for (const {
607
- recipientJid: wireJid,
608
- patchedMessage
609
- } of userDevices) {
610
- // DSM logic: Use DSM for own other devices (following whatsmeow implementation)
611
- let messageToEncrypt = patchedMessage;
612
- if (dsmMessage) {
613
- const {
614
- user: targetUser
615
- } = (0, _index5.jidDecode)(wireJid);
616
- const {
617
- user: ownPnUser
618
- } = (0, _index5.jidDecode)(meId);
619
- const ownLidUser = meLidUser;
620
- // Check if this is our device (same user, different device)
621
- const isOwnUser = targetUser === ownPnUser || ownLidUser && targetUser === ownLidUser;
622
- // Exclude exact sender device (whatsmeow: if jid == ownJID || jid == ownLID { continue })
623
- const isExactSenderDevice = wireJid === meId || authState.creds.me?.lid && wireJid === authState.creds.me.lid;
624
- if (isOwnUser && !isExactSenderDevice) {
625
- messageToEncrypt = dsmMessage;
626
- logger.debug({
627
- wireJid,
628
- targetUser
629
- }, 'Using DSM for own device');
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
- const bytes = (0, _index4.encodeWAMessage)(messageToEncrypt);
633
- // Get encryption JID with LID migration
634
- const encryptionJid = await getEncryptionJid(wireJid);
635
- // ENCRYPT: Use the determined encryption identity (prefers migrated LID)
636
- const {
637
- type,
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 node = {
648
- tag: 'to',
649
- attrs: {
650
- jid: wireJid
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
- userNodes.push(node);
664
- }
665
- logger.debug({
666
- user,
667
- nodesCreated: userNodes.length
668
- }, 'Releasing encryption lock for user devices');
669
- return userNodes;
670
- }));
671
- // Wait for all users to complete (users are processed in parallel)
672
- const userNodesArrays = await Promise.all(userEncryptionPromises);
673
- const nodes = userNodesArrays.flat();
674
- return {
675
- nodes,
676
- shouldIncludeDeviceIdentity
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 extraAttrs = {};
732
- if (participant) {
733
- // when the retry request is not for a group
734
- // only send to the specific device that asked for a retry
735
- // otherwise the message is sent out to every device that should be a recipient
736
- if (!isGroup && !isStatus) {
737
- additionalAttributes = {
738
- ...additionalAttributes,
739
- device_fanout: 'false'
740
- };
741
- }
742
- const {
743
- user,
744
- device
745
- } = (0, _index5.jidDecode)(participant.jid);
746
- devices.push({
747
- user,
748
- device,
749
- wireJid: participant.jid // Use the participant JID as wire JID
750
- });
751
- }
752
- await authState.keys.transaction(async () => {
753
- const mediaType = getMediaType(message);
754
- if (mediaType) {
755
- extraAttrs['mediatype'] = mediaType;
756
- }
757
- if (isNewsletter) {
758
- // Patch message if needed, then encode as plaintext
759
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
760
- const bytes = (0, _index4.encodeNewsletterMessage)(patched);
761
- binaryNodeContent.push({
762
- tag: 'plaintext',
763
- attrs: {},
764
- content: bytes
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 stanza = {
767
- tag: 'message',
768
- attrs: {
769
- to: jid,
770
- id: msgId,
771
- type: getMessageType(message),
772
- ...(additionalAttributes || {})
773
- },
774
- content: binaryNodeContent
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
- logger.debug({
777
- msgId
778
- }, `sending newsletter message to ${jid}`);
779
- await sendNode(stanza);
780
- return;
781
- }
782
- if ((0, _index4.normalizeMessageContent)(message)?.pinInChatMessage) {
783
- extraAttrs['decrypt-fail'] = 'hide';
784
- }
785
- if (isGroup || isStatus) {
786
- const [groupData, senderKeyMap] = await Promise.all([(async () => {
787
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
788
- if (groupData && Array.isArray(groupData?.participants)) {
789
- logger.trace({
790
- jid,
791
- participants: groupData.participants.length
792
- }, 'using cached group metadata');
793
- } else if (!isStatus) {
794
- groupData = await groupMetadata(jid);
795
- }
796
- return groupData;
797
- })(), (async () => {
798
- if (!participant && !isStatus) {
799
- const result = await authState.keys.get('sender-key-memory', [jid]);
800
- return result[jid] || {};
801
- }
802
- return {};
803
- })()]);
804
- if (!participant) {
805
- const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
806
- if (isStatus && statusJidList) {
807
- participantsList.push(...statusJidList);
808
- }
809
- if (!isStatus) {
810
- const groupAddressingMode = groupData?.addressingMode || (isLid ? _index3.WAMessageAddressingMode.LID : _index3.WAMessageAddressingMode.PN);
811
- additionalAttributes = {
812
- ...additionalAttributes,
813
- addressing_mode: groupAddressingMode
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
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
817
- devices.push(...additionalDevices);
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
- const patched = await patchMessageBeforeSending(message);
820
- if (Array.isArray(patched)) {
821
- throw new _boom.Boom('Per-jid patching is not supported in groups');
892
+ if (normalizedMessage.pollCreationMessage ||
893
+ normalizedMessage.pollCreationMessageV2 ||
894
+ normalizedMessage.pollCreationMessageV3 ||
895
+ normalizedMessage.pollUpdateMessage) {
896
+ return 'poll';
822
897
  }
823
- const bytes = (0, _index4.encodeWAMessage)(patched);
824
- // This should match the group's addressing mode and conversation context
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
- // if there are some participants with whom the session has not been established
848
- // if there are, we re-send the senderkey
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
- binaryNodeContent.push({
865
- tag: 'enc',
866
- attrs: {
867
- v: '2',
868
- type: 'skmsg'
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
- const allJids = [];
913
- const meJids = [];
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
- await assertSessions([...otherJids, ...meJids], false);
947
- const [{
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
- const stanza = {
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
- } else {
998
- stanza.attrs.to = destinationJid;
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
- if (error) {
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
- return message;
1162
- },
1163
- sendMessage: async (jid, content, options = {}) => {
1164
- const userJid = authState.creds.me.id;
1165
- const extendedType = (0, _extendedMessages.detectExtendedMessageType)(content);
1166
- if (extendedType) {
1167
- const msgId = options.messageId || (0, _index4.generateMessageIDV2)(sock.user?.id);
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
- if (typeof content === 'object' && 'disappearingMessagesInChat' in content && typeof content['disappearingMessagesInChat'] !== 'undefined' && (0, _index5.isJidGroup)(jid)) {
1205
- const {
1206
- disappearingMessagesInChat
1207
- } = content;
1208
- const value = typeof disappearingMessagesInChat === 'boolean' ? disappearingMessagesInChat ? _index2.WA_DEFAULT_EPHEMERAL : 0 : disappearingMessagesInChat;
1209
- await groupToggleEphemeral(jid, value);
1210
- } else {
1211
- const fullMsg = await (0, _index4.generateWAMessage)(jid, content, {
1212
- logger,
1213
- userJid,
1214
- getUrlInfo: text => (0, _linkPreview.getUrlInfo)(text, {
1215
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1216
- fetchOpts: {
1217
- timeout: 3000,
1218
- ...(axiosOptions || {})
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
- logger,
1221
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1222
- }),
1223
- //TODO: CACHE
1224
- getProfilePicUrl: sock.profilePictureUrl,
1225
- getCallLink: sock.createCallLink,
1226
- upload: waUploadToServer,
1227
- mediaCache: config.mediaCache,
1228
- options: config.options,
1229
- messageId: (0, _index4.generateMessageIDV2)(sock.user?.id),
1230
- ...options
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
- const isEventMsg = 'event' in content && !!content.event;
1233
- const isDeleteMsg = 'delete' in content && !!content.delete;
1234
- const isEditMsg = 'edit' in content && !!content.edit;
1235
- const isPinMsg = 'pin' in content && !!content.pin;
1236
- const isPollMessage = 'poll' in content && !!content.poll;
1237
- const additionalAttributes = {};
1238
- const additionalNodes = [];
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
- if ('cachedGroupMetadata' in options) {
1267
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
986
+ mediaConn = undefined;
987
+ if (messageRetryManager) {
988
+ messageRetryManager.clear();
1268
989
  }
1269
- await relayMessage(jid, fullMsg.message, {
1270
- messageId: fullMsg.key.id,
1271
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1272
- additionalAttributes,
1273
- statusJidList: options.statusJidList,
1274
- additionalNodes
1275
- });
1276
- if (config.emitOwnEvents) {
1277
- process.nextTick(() => {
1278
- processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
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
- return fullMsg;
1282
- }
1283
- }
1284
- };
1143
+ };
1285
1144
  };
1286
- exports.makeMessagesSocket = makeMessagesSocket;
1145
+ //# sourceMappingURL=messages-send.js.map