@deffa5556/bail 1.0.6 → 1.0.7

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