@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,163 @@
1
+ "use strict";
2
+ // ── deffa-baileys: sessionGuard ───────────────────────────────────────────────
3
+ // Fitur keamanan opsional — lock session ke IP server pertama kali connect
4
+ // Cara pakai:
5
+ // import { sessionGuard } from 'deffa-baileys'
6
+ // sessionGuard() ← aktifkan sebelum makeWASocket
7
+ //
8
+ // Kalau tidak dipanggil → tidak ada proteksi (default)
9
+ // ─────────────────────────────────────────────────────────────────────────────
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ var __importDefault = (this && this.__importDefault) || function (mod) {
44
+ return (mod && mod.__esModule) ? mod : { "default": mod };
45
+ };
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.sessionGuard = sessionGuard;
48
+ exports.isGuardActive = isGuardActive;
49
+ exports.resetGuard = resetGuard;
50
+ const promises_1 = require("fs/promises");
51
+ const crypto_1 = require("crypto");
52
+ const https_1 = __importDefault(require("https"));
53
+ const path_1 = __importDefault(require("path"));
54
+ const GUARD_FILE = '.deffa_guard';
55
+ let _guardActive = false;
56
+ // ── Ambil IP publik server ────────────────────────────────────────────────────
57
+ function getPublicIP() {
58
+ return new Promise((resolve) => {
59
+ const req = https_1.default.get('https://api.ipify.org?format=text', (res) => {
60
+ let data = '';
61
+ res.on('data', chunk => data += chunk);
62
+ res.on('end', () => resolve(data.trim()));
63
+ });
64
+ req.on('error', () => {
65
+ // Fallback: pakai hostname jika gagal ambil IP publik
66
+ Promise.resolve().then(() => __importStar(require('os'))).then(os => resolve(os.hostname()));
67
+ });
68
+ req.setTimeout(5000, () => {
69
+ req.destroy();
70
+ Promise.resolve().then(() => __importStar(require('os'))).then(os => resolve(os.hostname()));
71
+ });
72
+ });
73
+ }
74
+ // ── Hash IP biar gak tersimpan plaintext ─────────────────────────────────────
75
+ function hashIP(ip) {
76
+ return (0, crypto_1.createHash)('sha256').update(ip + 'deffa-guard-salt-2025').digest('hex');
77
+ }
78
+ // ── Baca guard file ───────────────────────────────────────────────────────────
79
+ async function readGuard(guardPath) {
80
+ try {
81
+ const raw = await (0, promises_1.readFile)(guardPath, 'utf-8');
82
+ return JSON.parse(raw);
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ // ── Tulis guard file ──────────────────────────────────────────────────────────
89
+ async function writeGuard(guardPath, data) {
90
+ await (0, promises_1.writeFile)(guardPath, JSON.stringify(data, null, 2));
91
+ }
92
+ // ── sessionGuard: fungsi utama yang dipanggil user ───────────────────────────
93
+ async function sessionGuard(options = {}) {
94
+ const { sessionFile = './auth_state.json', // path session WA
95
+ onBlock = null, // callback kalau diblok
96
+ silent = false, // sembunyikan log
97
+ } = options;
98
+ _guardActive = true;
99
+ const guardPath = path_1.default.resolve(path_1.default.dirname(path_1.default.resolve(sessionFile)), GUARD_FILE);
100
+ const log = (...args) => {
101
+ if (!silent)
102
+ console.log('[ ✦ ] DEFFA GUARD:', ...args);
103
+ };
104
+ log('Mengaktifkan proteksi session...');
105
+ // Ambil IP sekarang
106
+ const currentIP = await getPublicIP();
107
+ const currentHash = hashIP(currentIP);
108
+ log(`IP Server: ${currentIP}`);
109
+ // Baca guard file lama
110
+ const existing = await readGuard(guardPath);
111
+ if (!existing) {
112
+ // Pertama kali → simpan IP hash
113
+ await writeGuard(guardPath, {
114
+ ipHash: currentHash,
115
+ createdAt: new Date().toISOString(),
116
+ version: '1.0.0',
117
+ });
118
+ log('Session terdaftar di server ini ✅');
119
+ return true;
120
+ }
121
+ // Cek apakah IP match
122
+ if (existing.ipHash !== currentHash) {
123
+ // IP beda → BLOCK
124
+ const msg = `
125
+ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
126
+ ┃ ⚠️ DEFFA GUARD — SESSION BLOCK
127
+ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
128
+ Session ini tidak bisa digunakan
129
+ di server ini karena IP berbeda.
130
+
131
+ Session hanya bisa berjalan di
132
+ server tempat session dibuat.
133
+
134
+ Jika ini server kamu sendiri,
135
+ hapus file: ${GUARD_FILE}
136
+ lalu jalankan ulang bot.
137
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`;
138
+ console.error(msg);
139
+ if (typeof onBlock === 'function') {
140
+ await onBlock({ currentIP, guardPath });
141
+ }
142
+ process.exit(1); // Paksa stop bot
143
+ }
144
+ log('IP cocok, session aman ✅');
145
+ return true;
146
+ }
147
+ // ── isGuardActive: cek apakah guard aktif ────────────────────────────────────
148
+ function isGuardActive() {
149
+ return _guardActive;
150
+ }
151
+ // ── resetGuard: hapus guard file (kalau mau pindah server secara sah) ────────
152
+ async function resetGuard(sessionFile = './auth_state.json') {
153
+ const guardPath = path_1.default.resolve(path_1.default.dirname(path_1.default.resolve(sessionFile)), GUARD_FILE);
154
+ try {
155
+ const { unlink } = await Promise.resolve().then(() => __importStar(require('fs/promises')));
156
+ await unlink(guardPath);
157
+ console.log('[ ✦ ] DEFFA GUARD: Guard direset, silakan jalankan ulang bot.');
158
+ return true;
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ }
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.extractE2ESessionFromRetryReceipt = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const index_js_1 = require("../Defaults/index.cjs");
5
+ const index_js_2 = require("../WABinary/index.cjs");
6
+ const crypto_js_1 = require("./crypto.cjs");
7
+ const generics_js_1 = require("./generics.cjs");
8
+ function chunk(array, size) {
9
+ const chunks = [];
10
+ for (let i = 0; i < array.length; i += size) {
11
+ chunks.push(array.slice(i, i + size));
12
+ }
13
+ return chunks;
14
+ }
15
+ const createSignalIdentity = (wid, accountSignatureKey) => {
16
+ return {
17
+ identifier: { name: wid, deviceId: 0 },
18
+ identifierKey: (0, crypto_js_1.generateSignalPubKey)(accountSignatureKey)
19
+ };
20
+ };
21
+ exports.createSignalIdentity = createSignalIdentity;
22
+ const getPreKeys = async ({ get }, min, limit) => {
23
+ const idList = [];
24
+ for (let id = min; id < limit; id++) {
25
+ idList.push(id.toString());
26
+ }
27
+ return get('pre-key', idList);
28
+ };
29
+ exports.getPreKeys = getPreKeys;
30
+ const generateOrGetPreKeys = (creds, range) => {
31
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
32
+ const remaining = range - avaliable;
33
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
34
+ const newPreKeys = {};
35
+ if (remaining > 0) {
36
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
37
+ newPreKeys[i] = crypto_js_1.Curve.generateKeyPair();
38
+ }
39
+ }
40
+ return {
41
+ newPreKeys,
42
+ lastPreKeyId,
43
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
44
+ };
45
+ };
46
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
47
+ const xmppSignedPreKey = (key) => ({
48
+ tag: 'skey',
49
+ attrs: {},
50
+ content: [
51
+ { tag: 'id', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(key.keyId, 3) },
52
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
53
+ { tag: 'signature', attrs: {}, content: key.signature }
54
+ ]
55
+ });
56
+ exports.xmppSignedPreKey = xmppSignedPreKey;
57
+ const xmppPreKey = (pair, id) => ({
58
+ tag: 'key',
59
+ attrs: {},
60
+ content: [
61
+ { tag: 'id', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(id, 3) },
62
+ { tag: 'value', attrs: {}, content: pair.public }
63
+ ]
64
+ });
65
+ exports.xmppPreKey = xmppPreKey;
66
+ const isValidUInt = (n) => typeof n === 'number' && Number.isInteger(n);
67
+ const extractE2ESessionFromRetryReceipt = (receipt) => {
68
+ const keysNode = (0, index_js_2.getBinaryNodeChild)(receipt, 'keys');
69
+ if (!keysNode)
70
+ return null;
71
+ const typeBuf = (0, index_js_2.getBinaryNodeChildBuffer)(keysNode, 'type');
72
+ if (!typeBuf || typeBuf.length !== 1 || typeBuf[0] !== index_js_1.KEY_BUNDLE_TYPE[0])
73
+ return null;
74
+ const identity = (0, index_js_2.getBinaryNodeChildBuffer)(keysNode, 'identity');
75
+ const skey = (0, index_js_2.getBinaryNodeChild)(keysNode, 'skey');
76
+ if (!identity || identity.length !== 32 || !skey)
77
+ return null;
78
+ const registrationId = (0, index_js_2.getBinaryNodeChildUInt)(receipt, 'registration', 4);
79
+ if (!isValidUInt(registrationId))
80
+ return null;
81
+ const signedPubKey = (0, index_js_2.getBinaryNodeChildBuffer)(skey, 'value');
82
+ const signedSig = (0, index_js_2.getBinaryNodeChildBuffer)(skey, 'signature');
83
+ const signedKeyId = (0, index_js_2.getBinaryNodeChildUInt)(skey, 'id', 3);
84
+ if (!signedPubKey || signedPubKey.length !== 32 || !signedSig || !isValidUInt(signedKeyId)) {
85
+ return null;
86
+ }
87
+ const preKeyNode = (0, index_js_2.getBinaryNodeChild)(keysNode, 'key');
88
+ let preKey;
89
+ if (preKeyNode) {
90
+ const preKeyPub = (0, index_js_2.getBinaryNodeChildBuffer)(preKeyNode, 'value');
91
+ const preKeyId = (0, index_js_2.getBinaryNodeChildUInt)(preKeyNode, 'id', 3);
92
+ if (!preKeyPub || preKeyPub.length !== 32 || !isValidUInt(preKeyId)) {
93
+ return null;
94
+ }
95
+ preKey = { keyId: preKeyId, publicKey: (0, crypto_js_1.generateSignalPubKey)(preKeyPub) };
96
+ }
97
+ return {
98
+ registrationId,
99
+ identityKey: (0, crypto_js_1.generateSignalPubKey)(identity),
100
+ signedPreKey: {
101
+ keyId: signedKeyId,
102
+ publicKey: (0, crypto_js_1.generateSignalPubKey)(signedPubKey),
103
+ signature: signedSig
104
+ },
105
+ preKey
106
+ };
107
+ };
108
+ exports.extractE2ESessionFromRetryReceipt = extractE2ESessionFromRetryReceipt;
109
+ const parseAndInjectE2ESessions = async (node, repository) => {
110
+ const extractKey = (key) => key
111
+ ? {
112
+ keyId: (0, index_js_2.getBinaryNodeChildUInt)(key, 'id', 3),
113
+ publicKey: (0, crypto_js_1.generateSignalPubKey)((0, index_js_2.getBinaryNodeChildBuffer)(key, 'value')),
114
+ signature: (0, index_js_2.getBinaryNodeChildBuffer)(key, 'signature')
115
+ }
116
+ : undefined;
117
+ const nodes = (0, index_js_2.getBinaryNodeChildren)((0, index_js_2.getBinaryNodeChild)(node, 'list'), 'user');
118
+ for (const node of nodes) {
119
+ (0, index_js_2.assertNodeErrorFree)(node);
120
+ }
121
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
122
+ // So Promise.all doesn't really help here,
123
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
124
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
125
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
126
+ const chunkSize = 100;
127
+ const chunks = chunk(nodes, chunkSize);
128
+ for (const nodesChunk of chunks) {
129
+ for (const node of nodesChunk) {
130
+ const signedKey = (0, index_js_2.getBinaryNodeChild)(node, 'skey');
131
+ const key = (0, index_js_2.getBinaryNodeChild)(node, 'key');
132
+ const identity = (0, index_js_2.getBinaryNodeChildBuffer)(node, 'identity');
133
+ const jid = node.attrs.jid;
134
+ const registrationId = (0, index_js_2.getBinaryNodeChildUInt)(node, 'registration', 4);
135
+ await repository.injectE2ESession({
136
+ jid,
137
+ session: {
138
+ registrationId: registrationId,
139
+ identityKey: (0, crypto_js_1.generateSignalPubKey)(identity),
140
+ signedPreKey: extractKey(signedKey),
141
+ preKey: extractKey(key)
142
+ }
143
+ });
144
+ }
145
+ }
146
+ };
147
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
148
+ const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
149
+ const { user: myUser, device: myDevice } = (0, index_js_2.jidDecode)(myJid);
150
+ const extracted = [];
151
+ for (const userResult of result) {
152
+ const { devices, id } = userResult;
153
+ const decoded = (0, index_js_2.jidDecode)(id), { user, server } = decoded;
154
+ let { domainType } = decoded;
155
+ const deviceList = devices?.deviceList;
156
+ if (!Array.isArray(deviceList))
157
+ continue;
158
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
159
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
160
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
161
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
162
+ ) {
163
+ if (isHosted) {
164
+ domainType = domainType === index_js_2.WAJIDDomains.LID ? index_js_2.WAJIDDomains.HOSTED_LID : index_js_2.WAJIDDomains.HOSTED;
165
+ }
166
+ extracted.push({
167
+ user,
168
+ device,
169
+ domainType,
170
+ server: (0, index_js_2.getServerFromDomainType)(server, domainType)
171
+ });
172
+ }
173
+ }
174
+ }
175
+ return extracted;
176
+ };
177
+ exports.extractDeviceJids = extractDeviceJids;
178
+ /**
179
+ * get the next N keys for upload or processing
180
+ * @param count number of pre-keys to get or generate
181
+ */
182
+ const getNextPreKeys = async ({ creds, keys }, count) => {
183
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
184
+ const update = {
185
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
186
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
187
+ };
188
+ await keys.set({ 'pre-key': newPreKeys });
189
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
190
+ return { update, preKeys };
191
+ };
192
+ exports.getNextPreKeys = getNextPreKeys;
193
+ const getNextPreKeysNode = async (state, count) => {
194
+ const { creds } = state;
195
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
196
+ const node = {
197
+ tag: 'iq',
198
+ attrs: {
199
+ xmlns: 'encrypt',
200
+ type: 'set',
201
+ to: index_js_2.S_WHATSAPP_NET
202
+ },
203
+ content: [
204
+ { tag: 'registration', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(creds.registrationId) },
205
+ { tag: 'type', attrs: {}, content: index_js_1.KEY_BUNDLE_TYPE },
206
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
207
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
208
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
209
+ ]
210
+ };
211
+ return { update, node };
212
+ };
213
+ exports.getNextPreKeysNode = getNextPreKeysNode;
214
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildAckStanza = buildAckStanza;
4
+ /**
5
+ * Builds an ACK stanza for a received node.
6
+ * Pure function -- no I/O, no side effects.
7
+ *
8
+ * Mirrors WhatsApp Web's ACK construction:
9
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
10
+ * - WAWebCreateNackFromStanza.createNackFromStanza
11
+ */
12
+ function buildAckStanza(node, errorCode, meId) {
13
+ const { tag, attrs } = node;
14
+ const stanza = {
15
+ tag: 'ack',
16
+ attrs: {
17
+ id: attrs.id,
18
+ to: attrs.from,
19
+ class: tag
20
+ }
21
+ };
22
+ if (errorCode) {
23
+ stanza.attrs.error = errorCode.toString();
24
+ }
25
+ if (attrs.participant) {
26
+ stanza.attrs.participant = attrs.participant;
27
+ }
28
+ if (attrs.recipient) {
29
+ stanza.attrs.recipient = attrs.recipient;
30
+ }
31
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
32
+ if (attrs.type) {
33
+ stanza.attrs.type = attrs.type;
34
+ }
35
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
36
+ if (tag === 'message' && meId) {
37
+ stanza.attrs.from = meId;
38
+ }
39
+ return stanza;
40
+ }
41
+ //# sourceMappingURL=stanza-ack.js.map
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.emitSyncActionResults = exports.processContactAction = void 0;
4
+ const index_js_1 = require("../../WAProto/index.cjs");
5
+ const index_js_2 = require("../WABinary/index.cjs");
6
+ /**
7
+ * Process contactAction and return events to emit.
8
+ * Pure function - no side effects.
9
+ */
10
+ const processContactAction = (action, id, logger) => {
11
+ const results = [];
12
+ if (!id) {
13
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
14
+ return results;
15
+ }
16
+ const lidJid = action.lidJid;
17
+ const idIsPn = (0, index_js_2.isPnUser)(id);
18
+ // PN is in index[1], not in contactAction.pnJid which is usually null
19
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
20
+ // Always emit contacts.upsert
21
+ results.push({
22
+ event: 'contacts.upsert',
23
+ data: [
24
+ {
25
+ id,
26
+ name: action.fullName || action.firstName || action.username || undefined,
27
+ username: action.username || undefined,
28
+ lid: lidJid || undefined,
29
+ phoneNumber
30
+ }
31
+ ]
32
+ });
33
+ // Emit lid-mapping.update if we have valid LID-PN pair
34
+ if (lidJid && (0, index_js_2.isLidUser)(lidJid) && idIsPn) {
35
+ results.push({
36
+ event: 'lid-mapping.update',
37
+ data: { lid: lidJid, pn: id }
38
+ });
39
+ }
40
+ return results;
41
+ };
42
+ exports.processContactAction = processContactAction;
43
+ const emitSyncActionResults = (ev, results) => {
44
+ for (const result of results) {
45
+ if (result.event === 'contacts.upsert') {
46
+ ev.emit('contacts.upsert', result.data);
47
+ }
48
+ else {
49
+ ev.emit('lid-mapping.update', result.data);
50
+ }
51
+ }
52
+ };
53
+ exports.emitSyncActionResults = emitSyncActionResults;
54
+ //# sourceMappingURL=sync-action-utils.js.map
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TC_TOKEN_INDEX_KEY = void 0;
4
+ exports.readTcTokenIndex = readTcTokenIndex;
5
+ exports.buildMergedTcTokenIndexWrite = buildMergedTcTokenIndexWrite;
6
+ exports.isTcTokenExpired = isTcTokenExpired;
7
+ exports.shouldSendNewTcToken = shouldSendNewTcToken;
8
+ exports.resolveTcTokenJid = resolveTcTokenJid;
9
+ exports.resolveIssuanceJid = resolveIssuanceJid;
10
+ exports.buildTcTokenFromJid = buildTcTokenFromJid;
11
+ exports.storeTcTokensFromIqResult = storeTcTokensFromIqResult;
12
+ const index_js_1 = require("../WABinary/index.cjs");
13
+ // Same phone-number pattern as WABinary's isJidBot, applied against the user
14
+ // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
15
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
16
+ /**
17
+ * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
18
+ * storage against malformed notifications — WA Web filters server-side but we
19
+ * defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
20
+ * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
21
+ */
22
+ function isRegularUser(jid) {
23
+ if (!jid)
24
+ return false;
25
+ const user = jid.split('@')[0] ?? '';
26
+ if (user === '0')
27
+ return false; // PSA
28
+ if (BOT_PHONE_REGEX.test(user))
29
+ return false; // Bot by phone pattern
30
+ if ((0, index_js_1.isJidMetaAI)(jid))
31
+ return false; // MetaAI (@bot server)
32
+ return !!((0, index_js_1.isPnUser)(jid) || (0, index_js_1.isLidUser)(jid) || (0, index_js_1.isHostedPnUser)(jid) || (0, index_js_1.isHostedLidUser)(jid) || jid.endsWith('@c.us'));
33
+ }
34
+ const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
35
+ const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
36
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
37
+ exports.TC_TOKEN_INDEX_KEY = '__index';
38
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
39
+ async function readTcTokenIndex(keys) {
40
+ const data = await keys.get('tctoken', [exports.TC_TOKEN_INDEX_KEY]);
41
+ const entry = data[exports.TC_TOKEN_INDEX_KEY];
42
+ if (!entry?.token?.length)
43
+ return [];
44
+ try {
45
+ const parsed = JSON.parse(Buffer.from(entry.token).toString());
46
+ if (!Array.isArray(parsed))
47
+ return [];
48
+ return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== exports.TC_TOKEN_INDEX_KEY);
49
+ }
50
+ catch {
51
+ return [];
52
+ }
53
+ }
54
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
55
+ async function buildMergedTcTokenIndexWrite(keys, addedJids) {
56
+ const persisted = await readTcTokenIndex(keys);
57
+ const merged = new Set(persisted);
58
+ for (const jid of addedJids) {
59
+ if (jid && jid !== exports.TC_TOKEN_INDEX_KEY)
60
+ merged.add(jid);
61
+ }
62
+ return {
63
+ [exports.TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
64
+ };
65
+ }
66
+ // WA Web has separate sender/receiver AB props for these but they're identical today
67
+ function isTcTokenExpired(timestamp) {
68
+ if (timestamp === null || timestamp === undefined)
69
+ return true;
70
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
71
+ if (isNaN(ts))
72
+ return true;
73
+ const now = Math.floor(Date.now() / 1000);
74
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
75
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
76
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
77
+ return ts < cutoffTimestamp;
78
+ }
79
+ function shouldSendNewTcToken(senderTimestamp) {
80
+ if (senderTimestamp === undefined)
81
+ return true;
82
+ const now = Math.floor(Date.now() / 1000);
83
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
84
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
85
+ return currentBucket > senderBucket;
86
+ }
87
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
88
+ async function resolveTcTokenJid(jid, getLIDForPN) {
89
+ if ((0, index_js_1.isLidUser)(jid))
90
+ return jid;
91
+ const lid = await getLIDForPN(jid);
92
+ return lid ?? jid;
93
+ }
94
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
95
+ async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
96
+ if (issueToLid) {
97
+ if ((0, index_js_1.isLidUser)(jid))
98
+ return jid;
99
+ const lid = await getLIDForPN(jid);
100
+ return lid ?? jid;
101
+ }
102
+ if (!(0, index_js_1.isLidUser)(jid))
103
+ return jid;
104
+ if (getPNForLID) {
105
+ const pn = await getPNForLID(jid);
106
+ return pn ?? jid;
107
+ }
108
+ return jid;
109
+ }
110
+ async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
111
+ try {
112
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
113
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
114
+ const entry = tcTokenData?.[storageJid];
115
+ const tcTokenBuffer = entry?.token;
116
+ if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
117
+ if (tcTokenBuffer) {
118
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
119
+ // after we drop the unusable peer token. Only wipe the record entirely when
120
+ // there's nothing worth keeping.
121
+ const cleared = entry?.senderTimestamp !== undefined
122
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
123
+ : null;
124
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
125
+ }
126
+ return baseContent.length > 0 ? baseContent : undefined;
127
+ }
128
+ baseContent.push({
129
+ tag: 'tctoken',
130
+ attrs: {},
131
+ content: tcTokenBuffer
132
+ });
133
+ return baseContent;
134
+ }
135
+ catch (error) {
136
+ return baseContent.length > 0 ? baseContent : undefined;
137
+ }
138
+ }
139
+ async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
140
+ const tokensNode = (0, index_js_1.getBinaryNodeChild)(result, 'tokens');
141
+ if (!tokensNode)
142
+ return;
143
+ const tokenNodes = (0, index_js_1.getBinaryNodeChildren)(tokensNode, 'token');
144
+ for (const tokenNode of tokenNodes) {
145
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
146
+ continue;
147
+ }
148
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
149
+ const rawJid = (0, index_js_1.jidNormalizedUser)(fallbackJid || tokenNode.attrs.jid);
150
+ if (!isRegularUser(rawJid))
151
+ continue;
152
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
153
+ const existingTcData = await keys.get('tctoken', [storageJid]);
154
+ const existingEntry = existingTcData[storageJid];
155
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
156
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
157
+ // timestamp-less tokens would be immediately expired
158
+ if (!incomingTs)
159
+ continue;
160
+ if (existingTs > 0 && existingTs > incomingTs)
161
+ continue;
162
+ await keys.set({
163
+ tctoken: {
164
+ [storageJid]: {
165
+ ...existingEntry,
166
+ token: Buffer.from(tokenNode.content),
167
+ timestamp: tokenNode.attrs.t
168
+ }
169
+ }
170
+ });
171
+ onNewJidStored?.(storageJid);
172
+ }
173
+ }
174
+ //# sourceMappingURL=tc-token-utils.js.map