@badzz88/baileys 8.4.7 → 8.4.9

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 (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +347 -6
  4. package/WAProto/fix-import.js +38 -0
  5. package/WAProto/fix-imports.js +86 -85
  6. package/WAProto/index.d.ts +4913 -25
  7. package/WAProto/index.js +14074 -98
  8. package/package.json +50 -90
  9. package/src/Defaults/index.js +201 -0
  10. package/src/Defaults/phonenumber-mcc.json +223 -0
  11. package/src/Signal/Group/ciphertext-message.js +15 -0
  12. package/src/Signal/Group/group-session-builder.js +92 -0
  13. package/src/Signal/Group/group_cipher.js +89 -0
  14. package/src/Signal/Group/index.js +136 -0
  15. package/src/Signal/Group/keyhelper.js +73 -0
  16. package/src/Signal/Group/sender-chain-key.js +32 -0
  17. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/src/Signal/Group/sender-key-message.js +69 -0
  19. package/src/Signal/Group/sender-key-name.js +50 -0
  20. package/src/Signal/Group/sender-key-record.js +44 -0
  21. package/src/Signal/Group/sender-key-state.js +97 -0
  22. package/src/Signal/Group/sender-message-key.js +30 -0
  23. package/src/Signal/libsignal.js +470 -0
  24. package/src/Signal/lid-mapping.js +262 -0
  25. package/src/Socket/Client/index.js +30 -0
  26. package/src/Socket/Client/types.js +13 -0
  27. package/src/Socket/Client/websocket.js +62 -0
  28. package/src/Socket/aigroups.js +240 -0
  29. package/src/Socket/business.js +422 -0
  30. package/src/Socket/chats.js +2374 -0
  31. package/src/Socket/communities.js +580 -0
  32. package/src/Socket/graphql.js +915 -0
  33. package/src/Socket/groups.js +812 -0
  34. package/src/Socket/index.js +37 -0
  35. package/src/Socket/interactive-handler.js +579 -0
  36. package/src/Socket/interop.js +566 -0
  37. package/src/Socket/managed-account.js +214 -0
  38. package/src/Socket/messages-recv.js +3012 -0
  39. package/src/Socket/messages-send.js +2163 -0
  40. package/{lib → src}/Socket/mex.js +11 -5
  41. package/src/Socket/newsletter.js +1057 -0
  42. package/src/Socket/privacy.js +452 -0
  43. package/src/Socket/registration.js +434 -0
  44. package/src/Socket/socket.js +1079 -0
  45. package/src/Socket/text-router.js +67 -0
  46. package/src/Socket/username.js +234 -0
  47. package/src/Store/index.js +36 -0
  48. package/src/Store/make-cache-manager-store.js +90 -0
  49. package/src/Store/make-in-memory-store.js +506 -0
  50. package/src/Store/make-ordered-dictionary.js +81 -0
  51. package/src/Store/object-repository.js +29 -0
  52. package/src/Types/Auth.js +38 -0
  53. package/src/Types/Bussines.js +2 -0
  54. package/src/Types/Call.js +2 -0
  55. package/src/Types/Chat.js +4 -0
  56. package/src/Types/Contact.js +2 -0
  57. package/src/Types/Events.js +2 -0
  58. package/src/Types/GroupMetadata.js +2 -0
  59. package/src/Types/Label.js +27 -0
  60. package/src/Types/LabelAssociation.js +9 -0
  61. package/src/Types/Message.js +95 -0
  62. package/src/Types/Newsletter.js +152 -0
  63. package/src/Types/Product.js +2 -0
  64. package/src/Types/Signal.js +2 -0
  65. package/src/Types/Socket.js +2 -0
  66. package/src/Types/State.js +70 -0
  67. package/src/Types/USync.js +2 -0
  68. package/src/Types/index.js +54 -0
  69. package/src/Utils/auth-utils.js +306 -0
  70. package/src/Utils/browser-utils.js +114 -0
  71. package/src/Utils/business.js +247 -0
  72. package/src/Utils/chat-utils.js +1272 -0
  73. package/src/Utils/consumer-application.js +107 -0
  74. package/src/Utils/crypto.js +125 -0
  75. package/src/Utils/decode-wa-message.js +808 -0
  76. package/src/Utils/event-buffer.js +586 -0
  77. package/src/Utils/generics.js +640 -0
  78. package/src/Utils/group-history.js +60 -0
  79. package/src/Utils/history.js +244 -0
  80. package/src/Utils/identity-change-handler.js +52 -0
  81. package/src/Utils/index.js +53 -0
  82. package/src/Utils/jid-display-normalization.js +218 -0
  83. package/src/Utils/link-preview.js +143 -0
  84. package/src/Utils/logger.js +9 -0
  85. package/src/Utils/lt-hash.js +10 -0
  86. package/src/Utils/make-mutex.js +36 -0
  87. package/src/Utils/message-composer.js +479 -0
  88. package/src/Utils/message-inspect.js +400 -0
  89. package/src/Utils/message-retry-manager.js +231 -0
  90. package/src/Utils/messages-media.js +943 -0
  91. package/src/Utils/messages.js +2490 -0
  92. package/src/Utils/meta-ai-msmsg.js +133 -0
  93. package/src/Utils/noise-handler.js +194 -0
  94. package/src/Utils/offline-node-processor.js +42 -0
  95. package/src/Utils/pre-key-manager.js +107 -0
  96. package/src/Utils/process-message.js +1047 -0
  97. package/src/Utils/reporting-utils.js +262 -0
  98. package/src/Utils/signal.js +192 -0
  99. package/src/Utils/stanza-ack.js +74 -0
  100. package/src/Utils/sync-action-utils.js +54 -0
  101. package/src/Utils/tc-token-utils.js +161 -0
  102. package/src/Utils/use-multi-file-auth-state.js +121 -0
  103. package/src/Utils/validate-connection.js +248 -0
  104. package/src/Utils/voip-rekey.js +22 -0
  105. package/src/WABinary/constants.js +1304 -0
  106. package/src/WABinary/decode.js +377 -0
  107. package/src/WABinary/encode.js +58 -0
  108. package/src/WABinary/generic-utils.js +148 -0
  109. package/src/WABinary/index.js +33 -0
  110. package/src/WABinary/jid-utils.js +374 -0
  111. package/src/WABinary/types.js +2 -0
  112. package/src/WAM/BinaryInfo.js +13 -0
  113. package/src/WAM/constants.js +39486 -0
  114. package/src/WAM/encode.js +142 -0
  115. package/src/WAM/index.js +31 -0
  116. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  117. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  118. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  119. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  120. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  121. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  122. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  123. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  124. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  125. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  126. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  127. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  128. package/src/WAUSync/Protocols/index.js +40 -0
  129. package/src/WAUSync/USyncBackoff.js +31 -0
  130. package/src/WAUSync/USyncQuery.js +204 -0
  131. package/src/WAUSync/USyncUser.js +58 -0
  132. package/src/WAUSync/index.js +32 -0
  133. package/src/antiban.js +4726 -0
  134. package/{lib → src}/index.js +48 -15
  135. package/lib/Defaults/index.js +0 -130
  136. package/lib/Signal/Group/ciphertext-message.js +0 -12
  137. package/lib/Signal/Group/group-session-builder.js +0 -30
  138. package/lib/Signal/Group/group_cipher.js +0 -82
  139. package/lib/Signal/Group/index.js +0 -12
  140. package/lib/Signal/Group/keyhelper.js +0 -18
  141. package/lib/Signal/Group/sender-chain-key.js +0 -26
  142. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  143. package/lib/Signal/Group/sender-key-message.js +0 -66
  144. package/lib/Signal/Group/sender-key-name.js +0 -48
  145. package/lib/Signal/Group/sender-key-record.js +0 -41
  146. package/lib/Signal/Group/sender-key-state.js +0 -84
  147. package/lib/Signal/Group/sender-message-key.js +0 -26
  148. package/lib/Signal/libsignal.js +0 -431
  149. package/lib/Signal/lid-mapping.js +0 -277
  150. package/lib/Socket/Client/index.js +0 -3
  151. package/lib/Socket/Client/types.js +0 -11
  152. package/lib/Socket/Client/websocket.js +0 -54
  153. package/lib/Socket/business.js +0 -379
  154. package/lib/Socket/chats.js +0 -1193
  155. package/lib/Socket/communities.js +0 -431
  156. package/lib/Socket/groups.js +0 -374
  157. package/lib/Socket/index.js +0 -12
  158. package/lib/Socket/luxu.js +0 -386
  159. package/lib/Socket/messages-recv.js +0 -1916
  160. package/lib/Socket/messages-send.js +0 -1453
  161. package/lib/Socket/newsletter.js +0 -251
  162. package/lib/Socket/socket.js +0 -980
  163. package/lib/Socket/username.js +0 -146
  164. package/lib/Store/index.js +0 -10
  165. package/lib/Store/keyed-db.js +0 -108
  166. package/lib/Store/make-cache-manager-store.js +0 -85
  167. package/lib/Store/make-in-memory-store.js +0 -198
  168. package/lib/Store/make-ordered-dictionary.js +0 -75
  169. package/lib/Store/object-repository.js +0 -32
  170. package/lib/Types/Auth.js +0 -2
  171. package/lib/Types/Bussines.js +0 -2
  172. package/lib/Types/Call.js +0 -2
  173. package/lib/Types/Chat.js +0 -8
  174. package/lib/Types/Contact.js +0 -2
  175. package/lib/Types/Events.js +0 -2
  176. package/lib/Types/GroupMetadata.js +0 -2
  177. package/lib/Types/Label.js +0 -25
  178. package/lib/Types/LabelAssociation.js +0 -7
  179. package/lib/Types/Message.js +0 -11
  180. package/lib/Types/Mex.js +0 -37
  181. package/lib/Types/Product.js +0 -2
  182. package/lib/Types/Signal.js +0 -2
  183. package/lib/Types/Socket.js +0 -3
  184. package/lib/Types/State.js +0 -56
  185. package/lib/Types/USync.js +0 -2
  186. package/lib/Types/index.js +0 -26
  187. package/lib/Utils/auth-utils.js +0 -302
  188. package/lib/Utils/browser-utils.js +0 -49
  189. package/lib/Utils/business.js +0 -231
  190. package/lib/Utils/chat-utils.js +0 -872
  191. package/lib/Utils/companion-reg-client-utils.js +0 -35
  192. package/lib/Utils/crypto.js +0 -118
  193. package/lib/Utils/decode-wa-message.js +0 -350
  194. package/lib/Utils/event-buffer.js +0 -622
  195. package/lib/Utils/generics.js +0 -403
  196. package/lib/Utils/history.js +0 -134
  197. package/lib/Utils/identity-change-handler.js +0 -50
  198. package/lib/Utils/index.js +0 -23
  199. package/lib/Utils/link-preview.js +0 -85
  200. package/lib/Utils/logger.js +0 -3
  201. package/lib/Utils/lt-hash.js +0 -8
  202. package/lib/Utils/make-mutex.js +0 -33
  203. package/lib/Utils/message-composer.js +0 -273
  204. package/lib/Utils/message-retry-manager.js +0 -265
  205. package/lib/Utils/messages-media.js +0 -788
  206. package/lib/Utils/messages.js +0 -1260
  207. package/lib/Utils/noise-handler.js +0 -201
  208. package/lib/Utils/offline-node-processor.js +0 -40
  209. package/lib/Utils/pre-key-manager.js +0 -106
  210. package/lib/Utils/process-message.js +0 -630
  211. package/lib/Utils/reporting-utils.js +0 -258
  212. package/lib/Utils/signal.js +0 -201
  213. package/lib/Utils/stanza-ack.js +0 -38
  214. package/lib/Utils/sync-action-utils.js +0 -49
  215. package/lib/Utils/tc-token-utils.js +0 -163
  216. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  217. package/lib/Utils/validate-connection.js +0 -203
  218. package/lib/WABinary/constants.js +0 -1301
  219. package/lib/WABinary/decode.js +0 -262
  220. package/lib/WABinary/encode.js +0 -220
  221. package/lib/WABinary/generic-utils.js +0 -204
  222. package/lib/WABinary/index.js +0 -6
  223. package/lib/WABinary/jid-utils.js +0 -98
  224. package/lib/WABinary/types.js +0 -2
  225. package/lib/WAM/BinaryInfo.js +0 -10
  226. package/lib/WAM/constants.js +0 -22853
  227. package/lib/WAM/encode.js +0 -150
  228. package/lib/WAM/index.js +0 -4
  229. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  230. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  231. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  232. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  233. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  234. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  235. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  236. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  237. package/lib/WAUSync/Protocols/index.js +0 -6
  238. package/lib/WAUSync/USyncQuery.js +0 -98
  239. package/lib/WAUSync/USyncUser.js +0 -31
  240. package/lib/WAUSync/index.js +0 -4
@@ -0,0 +1,2374 @@
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ exports.makeChatsSocket = void 0
9
+ const node_cache_1 = __importDefault(require('@cacheable/node-cache'))
10
+ const boom_1 = require('@hapi/boom')
11
+ const index_js_1 = require('../../WAProto/index.js')
12
+ const Defaults_1 = require('../Defaults')
13
+ const Types_1 = require('../Types')
14
+ const State_1 = require('../Types/State')
15
+ const Utils_1 = require('../Utils')
16
+ const make_mutex_1 = require('../Utils/make-mutex')
17
+ const process_message_1 = __importDefault(require('../Utils/process-message'))
18
+ const tc_token_utils_1 = require('../Utils/tc-token-utils')
19
+ const WABinary_1 = require('../WABinary')
20
+ const WAUSync_1 = require('../WAUSync')
21
+ const socket_js_1 = require('./socket.js')
22
+ const interop_js_1 = require('./interop.js')
23
+ const makeChatsSocket = config => {
24
+ const {
25
+ logger,
26
+ markOnlineOnConnect,
27
+ fireInitQueries,
28
+ appStateMacVerification,
29
+ shouldIgnoreJid,
30
+ shouldSyncHistoryMessage,
31
+ getMessage
32
+ } = config
33
+ const sock = (0, interop_js_1.makeInteropSocket)((0, socket_js_1.makeSocket)(config))
34
+ const {
35
+ ev,
36
+ ws,
37
+ authState,
38
+ generateMessageTag,
39
+ sendNode,
40
+ query,
41
+ signalRepository,
42
+ onUnexpectedError,
43
+ sendUnifiedSession,
44
+ initInterop,
45
+ fetchIntegrators,
46
+ acceptInteropTOS,
47
+ optInIntegrators,
48
+ optOutIntegrators,
49
+ resolveInteropUser,
50
+ resolveInteropUsers,
51
+ getReachabilitySettings,
52
+ setReachabilitySettings,
53
+ blockInteropUser,
54
+ unblockInteropUser,
55
+ reportInteropSpam,
56
+ trustInteropContact,
57
+ createInteropGroup,
58
+ leaveInteropGroup,
59
+ getInteropGroupAddPrivacy,
60
+ INTEGRATOR_BIRDYCHAT,
61
+ INTEGRATOR_HAIKET
62
+ } = sock
63
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
64
+ let privacySettings
65
+ /** Server-assigned AB props for protocol behavior. */
66
+ const serverProps = {
67
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
68
+ privacyTokenOn1to1: true,
69
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
70
+ profilePicPrivacyToken: true,
71
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
72
+ lidTrustedTokenIssueToLid: false
73
+ }
74
+ let syncState = State_1.SyncState.Connecting
75
+ /** this mutex ensures that messages are processed in order */
76
+ const messageMutex = (0, make_mutex_1.makeMutex)()
77
+ /** this mutex ensures that receipts are processed in order */
78
+ const receiptMutex = (0, make_mutex_1.makeMutex)()
79
+ /** this mutex ensures that app state patches are processed in order */
80
+ const appStatePatchMutex = (0, make_mutex_1.makeMutex)()
81
+ /** this mutex ensures that notifications are processed in order */
82
+ const notificationMutex = (0, make_mutex_1.makeMutex)()
83
+ // Timeout for AwaitingInitialSync state
84
+ let awaitingSyncTimeout
85
+ // In-memory history sync completion tracking (resets on reconnection)
86
+ const historySyncStatus = {
87
+ initialBootstrapComplete: false,
88
+ recentSyncComplete: false
89
+ }
90
+ let historySyncPausedTimeout
91
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
92
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
93
+ const blockedCollections = new Set()
94
+ /** messageId → numeric server_id for newsletter messages (persists within session) */
95
+ const _nlServerIdCache = new Map()
96
+ const placeholderResendCache =
97
+ config.placeholderResendCache ||
98
+ new node_cache_1.default({
99
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
100
+ useClones: false
101
+ })
102
+ if (!config.placeholderResendCache) {
103
+ config.placeholderResendCache = placeholderResendCache
104
+ }
105
+ /** helper function to fetch the given app state sync key */
106
+ const getAppStateSyncKey = async keyId => {
107
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
108
+ return key
109
+ }
110
+ const fetchPrivacySettings = async (force = false) => {
111
+ if (!privacySettings || force) {
112
+ const { content } = await query({
113
+ tag: 'iq',
114
+ attrs: {
115
+ xmlns: 'privacy',
116
+ to: WABinary_1.S_WHATSAPP_NET,
117
+ type: 'get'
118
+ },
119
+ content: [{ tag: 'privacy', attrs: {} }]
120
+ })
121
+ const privacyNode = content?.[0]
122
+ privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(privacyNode, 'category')
123
+
124
+ // A. Online Privacy Mode — may arrive as <category name="online" value="..."/> or
125
+ // as a dedicated <online_privacy_setting value="..."/> child node.
126
+ const onlinePrivacy =
127
+ privacySettings['online'] ||
128
+ (0, WABinary_1.getBinaryNodeChild)(privacyNode, 'online_privacy_setting')?.attrs?.value ||
129
+ 'all'
130
+
131
+ // C. Enhanced Block — root attrs or dedicated child node.
132
+ const enhancedBlockEnabled =
133
+ privacyNode?.attrs?.enhanced_block_enabled === 'true' ||
134
+ (0, WABinary_1.getBinaryNodeChild)(privacyNode, 'enhanced_block')?.attrs?.enabled === 'true'
135
+
136
+ // E. MD Privacy V2 flag.
137
+ const mdPrivacyV2 =
138
+ privacyNode?.attrs?.md_privacy_v2 === 'true' ||
139
+ (0, WABinary_1.getBinaryNodeChild)(privacyNode, 'md_privacy_v2')?.attrs?.value === 'true'
140
+
141
+ // F. Syncd clear-chat / delete-chat flag.
142
+ const syncdClearChatDeleteChatEnabled =
143
+ privacyNode?.attrs?.syncd_clear_chat_delete_chat_enabled === 'true' ||
144
+ (0, WABinary_1.getBinaryNodeChild)(privacyNode, 'syncd_clear_chat')?.attrs?.delete_chat_enabled === 'true'
145
+
146
+ // A. Syncd anti-tampering fatal-exception gate.
147
+ const syncdAntiTamperingEnabled =
148
+ privacyNode?.attrs?.syncd_anti_tampering_fatal_exception_enabled === 'true' ||
149
+ (0, WABinary_1.getBinaryNodeChild)(privacyNode, 'syncd_anti_tampering')?.attrs?.fatal_exception_enabled ===
150
+ 'true'
151
+
152
+ // B. Syncd key-index rotation gate.
153
+ const keyRotationEnabled =
154
+ privacyNode?.attrs?.syncd_key_rotation_enabled === 'true' ||
155
+ (0, WABinary_1.getBinaryNodeChild)(privacyNode, 'syncd_key_rotation')?.attrs?.enabled === 'true'
156
+
157
+ // Emit combined settings update so consumers can react without parsing raw creds.
158
+ ev.emit('settings.update', {
159
+ onlinePrivacy,
160
+ enhancedBlockEnabled,
161
+ mdPrivacyV2,
162
+ syncdClearChatDeleteChatEnabled,
163
+ ...(syncdAntiTamperingEnabled ? { syncdAntiTamperingEnabled: true } : {}),
164
+ keyRotationEnabled
165
+ })
166
+
167
+ // Persist extended privacy flags in credentials.
168
+ ev.emit('creds.update', {
169
+ privacySettings: {
170
+ onlinePrivacy,
171
+ enhancedBlockEnabled,
172
+ mdPrivacyV2,
173
+ syncdClearChatDeleteChatEnabled,
174
+ syncdAntiTamperingEnabled,
175
+ keyRotationEnabled
176
+ }
177
+ })
178
+ }
179
+ return privacySettings
180
+ }
181
+ /** helper function to run a privacy IQ query */
182
+ const privacyQuery = async (name, value) => {
183
+ await query({
184
+ tag: 'iq',
185
+ attrs: {
186
+ xmlns: 'privacy',
187
+ to: WABinary_1.S_WHATSAPP_NET,
188
+ type: 'set'
189
+ },
190
+ content: [
191
+ {
192
+ tag: 'privacy',
193
+ attrs: {},
194
+ content: [
195
+ {
196
+ tag: 'category',
197
+ attrs: { name, value }
198
+ }
199
+ ]
200
+ }
201
+ ]
202
+ })
203
+ }
204
+ const updateMessagesPrivacy = async value => {
205
+ await privacyQuery('messages', value)
206
+ }
207
+ const updateCallPrivacy = async value => {
208
+ await privacyQuery('calladd', value)
209
+ }
210
+ const updateLastSeenPrivacy = async value => {
211
+ await privacyQuery('last', value)
212
+ }
213
+ const updateOnlinePrivacy = async value => {
214
+ await privacyQuery('online', value)
215
+ }
216
+ const updateProfilePicturePrivacy = async value => {
217
+ await privacyQuery('profile', value)
218
+ }
219
+ const updateStatusPrivacy = async value => {
220
+ await privacyQuery('status', value)
221
+ }
222
+ /**
223
+ * Fetch status privacy settings via `xmlns="status"` IQ GET.
224
+ * Returns the current distribution type and any custom lists.
225
+ * Source: GetStatusPrivacyJob.java, feature flag 3843 controls retry.
226
+ */
227
+ const getStatusPrivacy = async () => {
228
+ const result = await query({
229
+ tag: 'iq',
230
+ attrs: {
231
+ xmlns: 'status',
232
+ to: WABinary_1.S_WHATSAPP_NET,
233
+ type: 'get'
234
+ },
235
+ content: [{ tag: 'privacy', attrs: {} }]
236
+ })
237
+ const privacyNode = result?.content?.[0]
238
+ if (!privacyNode) return null
239
+ const lists = []
240
+ for (const listNode of privacyNode.content || []) {
241
+ const { type, id, listname, emoji, selected, deleted } = listNode.attrs || {}
242
+ const members = (listNode.content || []).map(u => u.attrs?.jid).filter(Boolean)
243
+ lists.push({ type, id, listname, emoji, selected: selected === 'true', deleted: deleted === 'true', members })
244
+ }
245
+ return lists
246
+ }
247
+ /**
248
+ * Set status privacy via `xmlns="status"` IQ SET.
249
+ * Supports simple distribution types and contact-level whitelist/blacklist/customlist.
250
+ *
251
+ * @param {'contacts'|'whitelist'|'blacklist'|'null'} type - Distribution type
252
+ * @param {string[]} [jids] - JIDs for the list (whitelist/blacklist)
253
+ * @param {Array<{id: string, listname: string, emoji?: string, selected?: boolean, deleted?: boolean, members?: string[]}>} [customLists]
254
+ */
255
+ const setStatusPrivacy = async (type, jids = [], customLists = []) => {
256
+ const content = []
257
+ // main distribution list
258
+ const mainList = {
259
+ tag: 'list',
260
+ attrs: { type },
261
+ content: jids.map(jid => ({ tag: 'user', attrs: { jid }, content: [] }))
262
+ }
263
+ content.push(mainList)
264
+ // custom named lists
265
+ for (const cl of customLists) {
266
+ const attrs = { type: 'customlist', id: cl.id, listname: cl.listname }
267
+ if (cl.emoji) attrs.emoji = cl.emoji
268
+ if (cl.selected) attrs.selected = 'true'
269
+ if (cl.deleted) attrs.deleted = 'true'
270
+ content.push({
271
+ tag: 'list',
272
+ attrs,
273
+ content: (cl.members || []).map(jid => ({ tag: 'user', attrs: { jid }, content: [] }))
274
+ })
275
+ }
276
+ await query({
277
+ tag: 'iq',
278
+ attrs: {
279
+ xmlns: 'status',
280
+ to: WABinary_1.S_WHATSAPP_NET,
281
+ type: 'set'
282
+ },
283
+ content: [{ tag: 'privacy', attrs: {}, content }]
284
+ })
285
+ }
286
+ const updateReadReceiptsPrivacy = async value => {
287
+ await privacyQuery('readreceipts', value)
288
+ }
289
+ const updateGroupsAddPrivacy = async value => {
290
+ await privacyQuery('groupadd', value)
291
+ }
292
+ const updateDefaultDisappearingMode = async duration => {
293
+ await query({
294
+ tag: 'iq',
295
+ attrs: {
296
+ xmlns: 'disappearing_mode',
297
+ to: WABinary_1.S_WHATSAPP_NET,
298
+ type: 'set'
299
+ },
300
+ content: [
301
+ {
302
+ tag: 'disappearing_mode',
303
+ attrs: {
304
+ duration: duration.toString()
305
+ }
306
+ }
307
+ ]
308
+ })
309
+ }
310
+ /**
311
+ * Fetch broadcast list quota from the server.
312
+ * Source: BroadcastListQuotaProtocol.java — IQ xmlns="w:biz", 32s timeout.
313
+ *
314
+ * Returns: { messagesLeft, totalLimit, isHeavySender, startTs, endTs, resetTs }
315
+ */
316
+ const fetchBroadcastListQuota = async () => {
317
+ const result = await query(
318
+ {
319
+ tag: 'iq',
320
+ attrs: {
321
+ xmlns: 'w:biz',
322
+ to: WABinary_1.S_WHATSAPP_NET,
323
+ type: 'get'
324
+ },
325
+ content: [{ tag: 'broadcast_list_quota', attrs: {}, content: [] }]
326
+ },
327
+ 32000
328
+ )
329
+ const limitsNode = (0, WABinary_1.getBinaryNodeChild)(result, 'limits')
330
+ const timeframeNode = (0, WABinary_1.getBinaryNodeChild)(result, 'timeframe')
331
+ if (!limitsNode) return null
332
+ return {
333
+ messagesLeft: parseInt(
334
+ limitsNode.attrs?.messages_left ??
335
+ (0, WABinary_1.getBinaryNodeChild)(limitsNode, 'messages_left')?.content ??
336
+ '0',
337
+ 10
338
+ ),
339
+ totalLimit: parseInt(
340
+ limitsNode.attrs?.total_limit ?? (0, WABinary_1.getBinaryNodeChild)(limitsNode, 'total_limit')?.content ?? '0',
341
+ 10
342
+ ),
343
+ isHeavySender:
344
+ (limitsNode.attrs?.is_heavy_sender ??
345
+ (0, WABinary_1.getBinaryNodeChild)(limitsNode, 'is_heavy_sender')?.content) === 'true',
346
+ startTs: parseInt(
347
+ timeframeNode?.attrs?.start_ts_s ??
348
+ (0, WABinary_1.getBinaryNodeChild)(timeframeNode, 'start_ts_s')?.content ??
349
+ '0',
350
+ 10
351
+ ),
352
+ endTs: parseInt(
353
+ timeframeNode?.attrs?.end_ts_s ?? (0, WABinary_1.getBinaryNodeChild)(timeframeNode, 'end_ts_s')?.content ?? '0',
354
+ 10
355
+ ),
356
+ resetTs: parseInt(
357
+ timeframeNode?.attrs?.reset_ts_s ??
358
+ (0, WABinary_1.getBinaryNodeChild)(timeframeNode, 'reset_ts_s')?.content ??
359
+ '0',
360
+ 10
361
+ )
362
+ }
363
+ }
364
+
365
+ const getBotListV2 = async () => {
366
+ const resp = await query({
367
+ tag: 'iq',
368
+ attrs: {
369
+ xmlns: 'bot',
370
+ to: WABinary_1.S_WHATSAPP_NET,
371
+ type: 'get'
372
+ },
373
+ content: [
374
+ {
375
+ tag: 'bot',
376
+ attrs: {
377
+ v: '2'
378
+ }
379
+ }
380
+ ]
381
+ })
382
+ const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot')
383
+ const botList = []
384
+ for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
385
+ if (section.attrs.type === 'all') {
386
+ for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
387
+ botList.push({
388
+ jid: bot.attrs.jid,
389
+ personaId: bot.attrs['persona_id']
390
+ })
391
+ }
392
+ }
393
+ }
394
+ return botList
395
+ }
396
+ /**
397
+ * Get the global chat-blocking status (block messages from unknown accounts).
398
+ * Ported from WhatsApp Web's WASmaxPsaChatBlockGetRPC (xmlns `w:comms:chat`).
399
+ * @returns {Promise<'blocked' | 'unblocked' | undefined>}
400
+ */
401
+ const getChatBlockingStatus = async () => {
402
+ const result = await query({
403
+ tag: 'iq',
404
+ attrs: {
405
+ to: WABinary_1.S_WHATSAPP_NET,
406
+ xmlns: 'w:comms:chat',
407
+ type: 'get'
408
+ },
409
+ content: [{ tag: 'query', attrs: {}, content: [{ tag: 'blocking_status', attrs: {} }] }]
410
+ })
411
+ const blocking =
412
+ (0, WABinary_1.getBinaryNodeChild)(result, 'blocking') ||
413
+ (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(result, 'query'), 'blocking')
414
+ return blocking?.attrs?.status
415
+ }
416
+ /**
417
+ * Set the global chat-blocking status (block messages from unknown accounts).
418
+ * Ported from WhatsApp Web's WASmaxPsaChatBlockSetRPC (xmlns `w:comms:chat`).
419
+ * @param {'block' | 'unblock'} action
420
+ * @returns {Promise<'blocked' | 'unblocked' | undefined>} the resulting status
421
+ */
422
+ const updateChatBlockingStatus = async action => {
423
+ const result = await query({
424
+ tag: 'iq',
425
+ attrs: {
426
+ to: WABinary_1.S_WHATSAPP_NET,
427
+ xmlns: 'w:comms:chat',
428
+ type: 'set'
429
+ },
430
+ content: [{ tag: 'blocking', attrs: { action } }]
431
+ })
432
+ const blocking = (0, WABinary_1.getBinaryNodeChild)(result, 'blocking')
433
+ return blocking?.attrs?.status
434
+ }
435
+ /**
436
+ * Get the user's pending TOS disclosures / notices.
437
+ * Ported from WhatsApp Web's WASmaxUserNoticeGetDisclosuresRPC (xmlns `tos`).
438
+ * @param {number} [t] last-seen disclosure timestamp
439
+ * @returns {Promise<Array<Record<string, string>>>} the `<notice>` attributes
440
+ */
441
+ const getUserDisclosures = async (t = 0) => {
442
+ const result = await query({
443
+ tag: 'iq',
444
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'tos', type: 'get' },
445
+ content: [{ tag: 'get_user_disclosures', attrs: { t: String(t) } }]
446
+ })
447
+ return (0, WABinary_1.getBinaryNodeChildren)(result, 'notice').map(n => ({ ...n.attrs }))
448
+ }
449
+ /**
450
+ * Accept a TOS/disclosure notice (`xmlns="tos"` set with `<trackable>`).
451
+ * Mirrors WASmaxUserNoticeTrackDisclosureRPC from WA Web.
452
+ * @param {string} noticeId the notice id (e.g. "20250211")
453
+ * @param {string|number} result the result code (e.g. "105")
454
+ */
455
+ const acceptTosNotice = async (noticeId, result = '105') => {
456
+ await query({
457
+ tag: 'iq',
458
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'tos', type: 'set' },
459
+ content: [{ tag: 'trackable', attrs: { id: String(noticeId), result: String(result) } }]
460
+ })
461
+ }
462
+ /**
463
+ * Report spam for a chat/group with sample messages.
464
+ * Mirrors WASmaxReportSpamRPC (xmlns="spam", type="set").
465
+ * @param {string} jid the JID of the chat or group being reported
466
+ * @param {Array<{id:string, from:string, t:number}>} messages up to ~5 recent messages as evidence
467
+ * @param {string} [spamFlow] e.g. "group_info_report" or "contact_info_report"
468
+ * @param {string} [subject] human-readable subject string (group name or contact name)
469
+ */
470
+ const reportSpam = async (jid, messages, spamFlow = 'contact_info_report', subject) => {
471
+ const msgNodes = (messages || []).map(m => ({
472
+ tag: 'message',
473
+ attrs: {
474
+ from: String(jid),
475
+ t: String(m.t),
476
+ id: String(m.id)
477
+ }
478
+ }))
479
+ await query({
480
+ tag: 'iq',
481
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'spam', type: 'set' },
482
+ content: [
483
+ {
484
+ tag: 'spam_list',
485
+ attrs: {
486
+ jid: String(jid),
487
+ spam_flow: String(spamFlow),
488
+ ...(subject ? { subject: String(subject) } : {})
489
+ },
490
+ content: msgNodes
491
+ }
492
+ ]
493
+ })
494
+ }
495
+ /**
496
+ * Get the account opt-out list (`optoutlist` IQ). Returns the raw result node.
497
+ */
498
+ const getOptOutList = async () => {
499
+ return query({
500
+ tag: 'iq',
501
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'optoutlist', type: 'get' }
502
+ })
503
+ }
504
+ /**
505
+ * Sign a blinded credential for privacy-preserving anonymous stats.
506
+ * Mirrors WASmaxPrivateStatsSignCredentialRPC (xmlns `privatestats`).
507
+ * @param {Buffer} blindedCredential 32-byte blinded credential
508
+ * @returns {Promise<Buffer|undefined>} signed credential bytes from server
509
+ */
510
+ const signPrivateCredential = async blindedCredential => {
511
+ const result = await query({
512
+ tag: 'iq',
513
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'privatestats', type: 'get' },
514
+ content: [
515
+ {
516
+ tag: 'sign_credential',
517
+ attrs: { version: '1' },
518
+ content: [{ tag: 'blinded_credential', attrs: {}, content: blindedCredential }]
519
+ }
520
+ ]
521
+ })
522
+ const signedNode = (0, WABinary_1.getBinaryNodeChild)(result, 'sign_credential')
523
+ const signedBytes = (0, WABinary_1.getBinaryNodeChild)(signedNode, 'signed_credential')
524
+ return signedBytes?.content instanceof Uint8Array ? Buffer.from(signedBytes.content) : undefined
525
+ }
526
+ /**
527
+ * Get push-notification settings (`urn:xmpp:whatsapp:push`).
528
+ */
529
+ const getPushConfig = async () => {
530
+ const result = await query({
531
+ tag: 'iq',
532
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'urn:xmpp:whatsapp:push', type: 'get' },
533
+ content: [{ tag: 'settings', attrs: {} }]
534
+ })
535
+ return (0, WABinary_1.getBinaryNodeChild)(result, 'settings')
536
+ }
537
+ /**
538
+ * Set push-notification config (`urn:xmpp:whatsapp:push`). Mainly web push —
539
+ * pass the FCM-style config (platform / endpoint / auth / p256dh).
540
+ * @param {Record<string, string>} config
541
+ */
542
+ const setPushConfig = async config => {
543
+ await query({
544
+ tag: 'iq',
545
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'urn:xmpp:whatsapp:push', type: 'set' },
546
+ content: [{ tag: 'config', attrs: config }]
547
+ })
548
+ }
549
+ const fetchStatus = async (...jids) => {
550
+ const usyncQuery = new WAUSync_1.USyncQuery().withStatusProtocol()
551
+ for (const jid of jids) {
552
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
553
+ }
554
+ const result = await executeUSyncQuery(usyncQuery)
555
+ if (result) {
556
+ return result.list
557
+ }
558
+ }
559
+ const fetchDisappearingDuration = async (...jids) => {
560
+ const usyncQuery = new WAUSync_1.USyncQuery().withDisappearingModeProtocol()
561
+ for (const jid of jids) {
562
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
563
+ }
564
+ const result = await executeUSyncQuery(usyncQuery)
565
+ if (result) {
566
+ return result.list
567
+ }
568
+ }
569
+ /** update the profile picture for yourself or a group */
570
+ const updateProfilePicture = async (jid, content, dimensions) => {
571
+ let targetJid
572
+ if (!jid) {
573
+ throw new boom_1.Boom(
574
+ 'Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update'
575
+ )
576
+ }
577
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
578
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid) // in case it is someone other than us
579
+ } else {
580
+ targetJid = undefined
581
+ }
582
+ const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions)
583
+ await query({
584
+ tag: 'iq',
585
+ attrs: {
586
+ to: WABinary_1.S_WHATSAPP_NET,
587
+ type: 'set',
588
+ xmlns: 'w:profile:picture',
589
+ ...(targetJid ? { target: targetJid } : {})
590
+ },
591
+ content: [
592
+ {
593
+ tag: 'picture',
594
+ attrs: { type: 'image' },
595
+ content: img
596
+ }
597
+ ]
598
+ })
599
+ }
600
+ /** remove the profile picture for yourself or a group */
601
+ const removeProfilePicture = async jid => {
602
+ let targetJid
603
+ if (!jid) {
604
+ throw new boom_1.Boom(
605
+ 'Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update'
606
+ )
607
+ }
608
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
609
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid) // in case it is someone other than us
610
+ } else {
611
+ targetJid = undefined
612
+ }
613
+ await query({
614
+ tag: 'iq',
615
+ attrs: {
616
+ to: WABinary_1.S_WHATSAPP_NET,
617
+ type: 'set',
618
+ xmlns: 'w:profile:picture',
619
+ ...(targetJid ? { target: targetJid } : {})
620
+ }
621
+ })
622
+ }
623
+ /** update the profile status for yourself */
624
+ const updateProfileStatus = async status => {
625
+ await query({
626
+ tag: 'iq',
627
+ attrs: {
628
+ to: WABinary_1.S_WHATSAPP_NET,
629
+ type: 'set',
630
+ xmlns: 'status'
631
+ },
632
+ content: [
633
+ {
634
+ tag: 'status',
635
+ attrs: {},
636
+ content: Buffer.from(status, 'utf-8')
637
+ }
638
+ ]
639
+ })
640
+ }
641
+ const updateProfileName = async name => {
642
+ await chatModify({ pushNameSetting: name }, '')
643
+ }
644
+ // dhash: previously-seen blocklist delta-hash, for incremental sync — server returns
645
+ // the current dhash unconditionally, and a fresh list only when it doesn't match.
646
+ // Confirmed from live capture: content is null for a full fetch, or a single
647
+ // <item dhash="..."/> child for the incremental check — never a <blocklist/> child.
648
+ const fetchBlocklist = async (dhash = null) => {
649
+ const result = await query({
650
+ tag: 'iq',
651
+ attrs: {
652
+ xmlns: 'blocklist',
653
+ to: WABinary_1.S_WHATSAPP_NET,
654
+ type: 'get'
655
+ },
656
+ content: dhash ? [{ tag: 'item', attrs: { dhash } }] : null
657
+ })
658
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list')
659
+ const jids = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item').map(n => n.attrs.jid)
660
+ ev.emit('blocklist.set', { blocklist: jids })
661
+ return jids
662
+ }
663
+ const updateBlockStatus = async (jid, action) => {
664
+ await query({
665
+ tag: 'iq',
666
+ attrs: {
667
+ xmlns: 'blocklist',
668
+ to: WABinary_1.S_WHATSAPP_NET,
669
+ type: 'set'
670
+ },
671
+ content: [
672
+ {
673
+ tag: 'item',
674
+ attrs: {
675
+ action,
676
+ jid
677
+ }
678
+ }
679
+ ]
680
+ })
681
+ }
682
+ const getBusinessProfile = async jid => {
683
+ // Confirmed from live capture: business_profile uses v="116" (not "244"), and
684
+ // verified_name is always its own separate w:biz iq — { jid } attr, no xmlns
685
+ // child attr — never bundled into the business_profile request.
686
+ const [results, verifiedNameResult] = await Promise.all([
687
+ query({
688
+ tag: 'iq',
689
+ attrs: {
690
+ to: 's.whatsapp.net',
691
+ xmlns: 'w:biz',
692
+ type: 'get'
693
+ },
694
+ content: [
695
+ {
696
+ tag: 'business_profile',
697
+ attrs: { v: '116' },
698
+ content: [
699
+ {
700
+ tag: 'profile',
701
+ attrs: { jid }
702
+ }
703
+ ]
704
+ }
705
+ ]
706
+ }),
707
+ query({
708
+ tag: 'iq',
709
+ attrs: {
710
+ to: 's.whatsapp.net',
711
+ xmlns: 'w:biz',
712
+ type: 'get'
713
+ },
714
+ content: [
715
+ {
716
+ tag: 'verified_name',
717
+ attrs: { jid }
718
+ }
719
+ ]
720
+ })
721
+ ])
722
+ // Parse verified_name certificate if present in the response
723
+ const verifiedNameNode = (0, WABinary_1.getBinaryNodeChild)(verifiedNameResult, 'verified_name')
724
+ let verifiedNameCert
725
+ if (verifiedNameNode) {
726
+ const certNode = (0, WABinary_1.getBinaryNodeChild)(verifiedNameNode, 'certificate')
727
+ if (certNode) {
728
+ const detailsNode = (0, WABinary_1.getBinaryNodeChild)(certNode, 'details')
729
+ const localizedNames = (0, WABinary_1.getBinaryNodeChildren)(certNode, 'localized_name').map(n => ({
730
+ lg: n.attrs?.lg,
731
+ lc: n.attrs?.lc,
732
+ verifiedName: n.attrs?.verified_name || n.content?.toString()
733
+ }))
734
+ verifiedNameCert = {
735
+ certSerial: certNode.attrs?.serial ? +certNode.attrs.serial : undefined,
736
+ issuer: certNode.attrs?.issuer,
737
+ details: {
738
+ verifiedName: detailsNode?.attrs?.verified_name || detailsNode?.content?.toString(),
739
+ localizedNames
740
+ }
741
+ }
742
+ }
743
+ }
744
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile')
745
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile')
746
+ if (profiles) {
747
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address')
748
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description')
749
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website')
750
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email')
751
+ const category = (0, WABinary_1.getBinaryNodeChild)(
752
+ (0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'),
753
+ 'category'
754
+ )
755
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours')
756
+ const businessHoursConfig = businessHours
757
+ ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
758
+ : undefined
759
+ const websiteStr = website?.content?.toString()
760
+
761
+ // Catalog status from profile attrs
762
+ const catalogStatus = {
763
+ exists: profiles.attrs?.catalog_exists === 'true' || profiles.attrs?.catalog_exists === true || false,
764
+ sendAll: profiles.attrs?.catalog_send_all === 'true' || profiles.attrs?.catalog_send_all === true || false
765
+ }
766
+
767
+ // Cart flags from profile attrs
768
+ const cartEnabled =
769
+ profiles.attrs?.cart_enabled !== undefined
770
+ ? profiles.attrs.cart_enabled === 'true' || profiles.attrs.cart_enabled === true
771
+ : undefined
772
+ const webCartEnabled =
773
+ profiles.attrs?.web_cart_enabled !== undefined
774
+ ? profiles.attrs.web_cart_enabled === 'true' || profiles.attrs.web_cart_enabled === true
775
+ : undefined
776
+ const webCartOnOff = profiles.attrs?.web_cart_on_off
777
+
778
+ // Commerce experience from profile attrs
779
+ const commerceExperience = profiles.attrs?.commerce_experience
780
+
781
+ return {
782
+ wid: profiles.attrs?.jid,
783
+ address: address?.content?.toString(),
784
+ businessAddress: address?.content?.toString(),
785
+ description: description?.content?.toString() || '',
786
+ website: websiteStr ? [websiteStr] : [],
787
+ email: email?.content?.toString(),
788
+ category: category?.content?.toString(),
789
+ business_hours: {
790
+ timezone: businessHours?.attrs?.timezone,
791
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
792
+ },
793
+ businessHours: businessHoursConfig
794
+ ? {
795
+ timezone: businessHours?.attrs?.timezone ?? null,
796
+ config: businessHoursConfig.map(({ attrs }) => ({
797
+ dayOfWeek: attrs?.day_of_week ?? null,
798
+ openTime: attrs?.open_time ?? null,
799
+ closeTime: attrs?.close_time ?? null,
800
+ mode: attrs?.mode ?? null
801
+ }))
802
+ }
803
+ : null,
804
+ catalogStatus,
805
+ cartEnabled,
806
+ webCartEnabled,
807
+ webCartOnOff,
808
+ commerceExperience,
809
+ verifiedNameCert
810
+ }
811
+ }
812
+ }
813
+ const cleanDirtyBits = async (type, fromTimestamp) => {
814
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
815
+ await sendNode({
816
+ tag: 'iq',
817
+ attrs: {
818
+ to: WABinary_1.S_WHATSAPP_NET,
819
+ type: 'set',
820
+ xmlns: 'urn:xmpp:whatsapp:dirty',
821
+ id: generateMessageTag()
822
+ },
823
+ content: [
824
+ {
825
+ tag: 'clean',
826
+ attrs: {
827
+ type,
828
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
829
+ }
830
+ }
831
+ ]
832
+ })
833
+ }
834
+ const newAppStateChunkHandler = isInitialSync => {
835
+ return {
836
+ onMutation(mutation) {
837
+ ;(0, Utils_1.processSyncAction)(
838
+ mutation,
839
+ ev,
840
+ authState.creds.me,
841
+ isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined,
842
+ logger
843
+ )
844
+ // Persist NCT salt received via App-State-Sync (SyncActionValue field 80)
845
+ const _nctSalt = mutation?.syncAction?.value?.nctSaltSyncAction?.salt
846
+ if (_nctSalt?.length) {
847
+ authState.keys
848
+ .set({ 'nct-salt': { default: Buffer.from(_nctSalt) } })
849
+ .catch(err => logger.debug({ err: err?.message }, 'nct: failed to persist salt'))
850
+ }
851
+ }
852
+ }
853
+ }
854
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
855
+ const appStateSyncKeyCache = new Map()
856
+ const getCachedAppStateSyncKey = async keyId => {
857
+ if (appStateSyncKeyCache.has(keyId)) {
858
+ return appStateSyncKeyCache.get(keyId)
859
+ }
860
+ const key = await getAppStateSyncKey(keyId)
861
+ appStateSyncKeyCache.set(keyId, key ?? null)
862
+ return key
863
+ }
864
+ // we use this to determine which events to fire
865
+ // otherwise when we resync from scratch -- all notifications will fire
866
+ const initialVersionMap = {}
867
+ const globalMutationMap = {}
868
+ await authState.keys.transaction(async () => {
869
+ const collectionsToHandle = new Set(collections)
870
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
871
+ const attemptsMap = {}
872
+ const forceSnapshotCollections = new Set()
873
+ // keep executing till all collections are done
874
+ // sometimes a single patch request will not return all the patches (God knows why)
875
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
876
+ while (collectionsToHandle.size) {
877
+ const states = {}
878
+ const nodes = []
879
+ for (const name of collectionsToHandle) {
880
+ const result = await authState.keys.get('app-state-sync-version', [name])
881
+ let state = result[name]
882
+ if (state) {
883
+ if (initialVersionMap[name] === undefined) {
884
+ initialVersionMap[name] = state.version
885
+ }
886
+ } else {
887
+ state = (0, Utils_1.newLTHashState)()
888
+ }
889
+ states[name] = state
890
+ const shouldForceSnapshot = forceSnapshotCollections.has(name)
891
+ if (shouldForceSnapshot) {
892
+ forceSnapshotCollections.delete(name)
893
+ }
894
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`)
895
+ nodes.push({
896
+ tag: 'collection',
897
+ attrs: {
898
+ name,
899
+ version: state.version.toString(),
900
+ // return snapshot if syncing from scratch or forcing after a failed attempt
901
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
902
+ }
903
+ })
904
+ }
905
+ const result = await query({
906
+ tag: 'iq',
907
+ attrs: {
908
+ to: WABinary_1.S_WHATSAPP_NET,
909
+ xmlns: 'w:sync:app:state',
910
+ type: 'set'
911
+ },
912
+ content: [
913
+ {
914
+ tag: 'sync',
915
+ attrs: {},
916
+ content: nodes
917
+ }
918
+ ]
919
+ })
920
+ // extract from binary node
921
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config?.options)
922
+ for (const key in decoded) {
923
+ const name = key
924
+ const { patches, hasMorePatches, snapshot } = decoded[name]
925
+ try {
926
+ if (snapshot) {
927
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(
928
+ name,
929
+ snapshot,
930
+ getCachedAppStateSyncKey,
931
+ initialVersionMap[name],
932
+ appStateMacVerification.snapshot
933
+ )
934
+ states[name] = newState
935
+ Object.assign(globalMutationMap, mutationMap)
936
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
937
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
938
+ }
939
+ // only process if there are syncd patches
940
+ if (patches.length) {
941
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(
942
+ name,
943
+ patches,
944
+ states[name],
945
+ getCachedAppStateSyncKey,
946
+ config.options,
947
+ initialVersionMap[name],
948
+ logger,
949
+ appStateMacVerification.patch
950
+ )
951
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
952
+ logger.info(`synced ${name} to v${newState.version}`)
953
+ initialVersionMap[name] = newState.version
954
+ Object.assign(globalMutationMap, mutationMap)
955
+ }
956
+ if (hasMorePatches) {
957
+ logger.info(`${name} has more patches...`)
958
+ } else {
959
+ // collection is done with sync
960
+ collectionsToHandle.delete(name)
961
+ }
962
+ } catch (error) {
963
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
964
+ const logData = {
965
+ name,
966
+ attempt: attemptsMap[name],
967
+ version: states[name].version,
968
+ statusCode: error.output?.statusCode,
969
+ errorType: error.name,
970
+ error: error.stack
971
+ }
972
+ if ((0, Utils_1.isMissingKeyError)(error) && attemptsMap[name] >= Utils_1.MAX_SYNC_ATTEMPTS) {
973
+ logger.warn(
974
+ logData,
975
+ `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`
976
+ )
977
+ blockedCollections.add(name)
978
+ collectionsToHandle.delete(name)
979
+ } else if ((0, Utils_1.isMissingKeyError)(error)) {
980
+ logger.info(
981
+ logData,
982
+ `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`
983
+ )
984
+ forceSnapshotCollections.add(name)
985
+ } else if ((0, Utils_1.isAppStateSyncIrrecoverable)(error, attemptsMap[name])) {
986
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`)
987
+ collectionsToHandle.delete(name)
988
+ } else {
989
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`)
990
+ forceSnapshotCollections.add(name)
991
+ }
992
+ }
993
+ }
994
+ }
995
+ }, authState?.creds?.me?.id || 'resync-app-state')
996
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
997
+ for (const key in globalMutationMap) {
998
+ onMutation(globalMutationMap[key])
999
+ }
1000
+ })
1001
+ /**
1002
+ * fetch the profile picture of a user/group
1003
+ * type = "preview" for a low res picture
1004
+ * type = "image" for the high res picture URL (adds query="url")
1005
+ * type = "avatar" for the avatar variant (no query attr, confirmed from interop logs)
1006
+ */
1007
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
1008
+ // Confirmed from live capture: query="url" is always present, for both
1009
+ // "preview" and "image" — not image-only as previously assumed.
1010
+ const picAttrs = { type, query: 'url' }
1011
+ const baseContent = [{ tag: 'picture', attrs: picAttrs }]
1012
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
1013
+ // and never for own profile pic (Chat model for self has no tcToken).
1014
+ // Including tctoken for own JID causes the server to never respond.
1015
+ const normalizedJid = (0, WABinary_1.jidNormalizedUser)(jid)
1016
+ const isUserJid = (0, WABinary_1.isPnUser)(normalizedJid) || (0, WABinary_1.isLidUser)(normalizedJid)
1017
+ const me = authState.creds.me
1018
+ const isSelf =
1019
+ me &&
1020
+ (normalizedJid === (0, WABinary_1.jidNormalizedUser)(me.id) ||
1021
+ (me.lid && normalizedJid === (0, WABinary_1.jidNormalizedUser)(me.lid)))
1022
+ let content = baseContent
1023
+ if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
1024
+ content = await (0, tc_token_utils_1.buildTcTokenFromJid)({
1025
+ authState,
1026
+ jid: normalizedJid,
1027
+ baseContent,
1028
+ getLIDForPN
1029
+ })
1030
+ }
1031
+ jid = (0, WABinary_1.jidNormalizedUser)(jid)
1032
+ const result = await query(
1033
+ {
1034
+ tag: 'iq',
1035
+ attrs: {
1036
+ target: jid,
1037
+ to: WABinary_1.S_WHATSAPP_NET,
1038
+ type: 'get',
1039
+ xmlns: 'w:profile:picture'
1040
+ },
1041
+ content
1042
+ },
1043
+ timeoutMs
1044
+ )
1045
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture')
1046
+ return child?.attrs?.url
1047
+ }
1048
+ const createCallLink = async (type, event, timeoutMs) => {
1049
+ const result = await query(
1050
+ {
1051
+ tag: 'call',
1052
+ attrs: {
1053
+ id: generateMessageTag(),
1054
+ to: '@call'
1055
+ },
1056
+ content: [
1057
+ {
1058
+ tag: 'link_create',
1059
+ attrs: { media: type },
1060
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
1061
+ }
1062
+ ]
1063
+ },
1064
+ timeoutMs
1065
+ )
1066
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'link_create')
1067
+ return child?.attrs?.token
1068
+ }
1069
+ /**
1070
+ * Toggle the waiting room on an existing call link.
1071
+ * Ported from WhatsApp Web's WASmaxVoipWaitingRoomToggleCallLinkRPC.
1072
+ * @param {string} linkToken the call link token (from createCallLink)
1073
+ * @param {boolean} enabled
1074
+ * @param {'audio' | 'video'} [media]
1075
+ */
1076
+ const toggleCallLinkWaitingRoom = async (linkToken, enabled, media = 'audio') => {
1077
+ const result = await query({
1078
+ tag: 'call',
1079
+ attrs: { id: generateMessageTag(), to: '@call' },
1080
+ content: [
1081
+ {
1082
+ tag: 'waiting_room_toggle',
1083
+ attrs: { enabled: enabled ? '1' : '0', 'link-token': linkToken, media }
1084
+ }
1085
+ ]
1086
+ })
1087
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'waiting_room_toggle')
1088
+ return child?.attrs
1089
+ }
1090
+ const sendPresenceUpdate = async (type, toJid) => {
1091
+ const me = authState.creds.me
1092
+ const isAvailableType = type === 'available'
1093
+ if (isAvailableType || type === 'unavailable') {
1094
+ if (!me.name) {
1095
+ logger.warn('no name present, ignoring presence update request...')
1096
+ return
1097
+ }
1098
+ ev.emit('connection.update', { isOnline: isAvailableType })
1099
+ if (isAvailableType) {
1100
+ void sendUnifiedSession()
1101
+ }
1102
+ await sendNode({
1103
+ tag: 'presence',
1104
+ attrs: {
1105
+ name: me.name.replace(/@/g, ''),
1106
+ type
1107
+ }
1108
+ })
1109
+ } else {
1110
+ const { server } = (0, WABinary_1.jidDecode)(toJid)
1111
+ const isLid = server === 'lid'
1112
+ await sendNode({
1113
+ tag: 'chatstate',
1114
+ attrs: {
1115
+ from: isLid ? me.lid : me.id,
1116
+ to: toJid
1117
+ },
1118
+ content: [
1119
+ {
1120
+ tag: type === 'recording' ? 'composing' : type,
1121
+ attrs: type === 'recording' ? { media: 'audio' } : {}
1122
+ }
1123
+ ]
1124
+ })
1125
+ }
1126
+ }
1127
+ /**
1128
+ * Store privacy tokens received from a usync response per-contact.
1129
+ * Called externally when a USyncQuery result includes privacy_token data.
1130
+ *
1131
+ * @param {Array<{jid: string, privacyToken: Buffer, privacyModeTs: number|string}>} entries
1132
+ */
1133
+ const storePrivacyTokens = async entries => {
1134
+ if (!entries?.length) return
1135
+ const write = {}
1136
+ for (const { jid, privacyToken, privacyModeTs } of entries) {
1137
+ if (!jid || !privacyToken?.length) continue
1138
+ write[jid] = {
1139
+ token: Buffer.isBuffer(privacyToken) ? privacyToken : Buffer.from(privacyToken),
1140
+ ts: String(privacyModeTs || '')
1141
+ }
1142
+ }
1143
+ if (Object.keys(write).length) {
1144
+ await authState.keys.set({ 'privacy-token': write })
1145
+ }
1146
+ }
1147
+
1148
+ /**
1149
+ * Wrapper around sock.executeUSyncQuery that automatically persists any per-contact
1150
+ * privacy tokens (privacy_mode_ts + privacy_token) present in the usync result list,
1151
+ * and emits contacts.update for any entries flagged isBlockedByContact.
1152
+ *
1153
+ * @param {import('../WAUSync/USyncQuery').USyncQuery} usyncQuery
1154
+ */
1155
+ const executeUSyncQuery = async usyncQuery => {
1156
+ const result = await sock.executeUSyncQuery(usyncQuery)
1157
+ if (!result) return result
1158
+
1159
+ // B. Auto-persist privacy tokens found in any usync response.
1160
+ const privacyEntries = []
1161
+ const blockedContacts = []
1162
+ for (const entry of [...(result.list || []), ...(result.sideList || [])]) {
1163
+ if (entry.privacy?.token) {
1164
+ privacyEntries.push({
1165
+ jid: entry.id,
1166
+ privacyToken: entry.privacy.token,
1167
+ privacyModeTs: entry.privacy.modeTs
1168
+ })
1169
+ }
1170
+ // G. Emit contacts.update for contacts that blocked us.
1171
+ if (entry.isBlockedByContact) {
1172
+ blockedContacts.push({ id: entry.id, isBlockedByContact: true })
1173
+ }
1174
+ }
1175
+ if (privacyEntries.length) {
1176
+ storePrivacyTokens(privacyEntries).catch(err => logger.warn({ err }, 'failed to store privacy tokens from usync'))
1177
+ }
1178
+ if (blockedContacts.length) {
1179
+ ev.emit('contacts.update', blockedContacts)
1180
+ }
1181
+ return result
1182
+ }
1183
+
1184
+ /**
1185
+ * @param toJid the jid to subscribe to
1186
+ * @param options.presenceType optional presenceType attribute stored for the contact
1187
+ * @param options.presenceName optional presenceName attribute for the subscribe stanza
1188
+ * @param options.groupJid optional group JID — when set adds context="group" attribute
1189
+ */
1190
+ const presenceSubscribe = async (toJid, { presenceType, presenceName, groupJid } = {}) => {
1191
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
1192
+ const normalizedToJid = (0, WABinary_1.jidNormalizedUser)(toJid)
1193
+ const isUserJid = (0, WABinary_1.isPnUser)(normalizedToJid) || (0, WABinary_1.isLidUser)(normalizedToJid)
1194
+
1195
+ // Build presence attributes
1196
+ const presenceAttrs = {
1197
+ to: toJid,
1198
+ id: generateMessageTag(),
1199
+ type: 'subscribe'
1200
+ }
1201
+
1202
+ // Accumulate child nodes for the presence stanza
1203
+ const presenceContent = []
1204
+
1205
+ // A. TC Token as attribute: fetch stored token and attach as base64 tc_token attr
1206
+ if (isUserJid) {
1207
+ try {
1208
+ const storageJid = await (0, tc_token_utils_1.resolveTcTokenJid)(normalizedToJid, getLIDForPN)
1209
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid])
1210
+ const entry = tcTokenData?.[storageJid]
1211
+ const tcTokenBuffer = entry?.token
1212
+ if (tcTokenBuffer?.length && !(0, tc_token_utils_1.isTcTokenExpired)(entry?.timestamp)) {
1213
+ presenceAttrs.tc_token = tcTokenBuffer.toString('base64')
1214
+ }
1215
+ } catch (e) {
1216
+ // best-effort — proceed without tc_token if lookup fails
1217
+ }
1218
+
1219
+ // B. Privacy Token — include per-contact privacy token when available.
1220
+ // This token is issued by the contact's device via usync and gates presence
1221
+ // visibility when their online privacy is set to "contacts" or "contact_blacklist".
1222
+ try {
1223
+ const privTokenData = await authState.keys.get('privacy-token', [normalizedToJid])
1224
+ const privEntry = privTokenData?.[normalizedToJid]
1225
+ if (privEntry?.token?.length) {
1226
+ const privTokenAttrs = {}
1227
+ if (privEntry.ts) privTokenAttrs.t = privEntry.ts
1228
+ presenceContent.push({
1229
+ tag: 'privacy_token',
1230
+ attrs: privTokenAttrs,
1231
+ content: privEntry.token
1232
+ })
1233
+ }
1234
+ } catch (e) {
1235
+ // best-effort — proceed without privacy_token if lookup fails
1236
+ }
1237
+ }
1238
+
1239
+ // C. presenceType and presenceName attributes
1240
+ if (presenceType) {
1241
+ presenceAttrs.presenceType = presenceType
1242
+ }
1243
+ if (presenceName) {
1244
+ presenceAttrs.presenceName = presenceName
1245
+ }
1246
+
1247
+ // D. Group presence context
1248
+ if (groupJid) {
1249
+ presenceAttrs.context = 'group'
1250
+ presenceAttrs.group_jid = (0, WABinary_1.jidNormalizedUser)(groupJid)
1251
+ }
1252
+
1253
+ return sendNode({
1254
+ tag: 'presence',
1255
+ attrs: presenceAttrs,
1256
+ content: presenceContent.length ? presenceContent : undefined
1257
+ })
1258
+ }
1259
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
1260
+ let presence
1261
+ const jid = attrs.from
1262
+ const participant = attrs.participant || attrs.from
1263
+ if (shouldIgnoreJid(jid) && jid !== WABinary_1.S_WHATSAPP_NET) {
1264
+ return
1265
+ }
1266
+ if (tag === 'presence') {
1267
+ presence = {
1268
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
1269
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
1270
+ }
1271
+ } else if (Array.isArray(content)) {
1272
+ const [firstChild] = content
1273
+ let type = firstChild.tag
1274
+ if (type === 'paused') {
1275
+ type = 'available'
1276
+ }
1277
+ if (firstChild.attrs?.media === 'audio') {
1278
+ type = 'recording'
1279
+ }
1280
+ presence = { lastKnownPresence: type }
1281
+ } else {
1282
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
1283
+ }
1284
+ if (presence) {
1285
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
1286
+ }
1287
+ }
1288
+ const appPatch = async patchCreate => {
1289
+ const name = patchCreate.type
1290
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
1291
+ if (!myAppStateKeyId) {
1292
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 })
1293
+ }
1294
+ let initial
1295
+ let encodeResult
1296
+ await appStatePatchMutex.mutex(async () => {
1297
+ await authState.keys.transaction(async () => {
1298
+ logger.debug({ patch: patchCreate }, 'applying app patch')
1299
+ await resyncAppState([name], false)
1300
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
1301
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)()
1302
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
1303
+ const { patch, state } = encodeResult
1304
+ const node = {
1305
+ tag: 'iq',
1306
+ attrs: {
1307
+ to: WABinary_1.S_WHATSAPP_NET,
1308
+ type: 'set',
1309
+ xmlns: 'w:sync:app:state'
1310
+ },
1311
+ content: [
1312
+ {
1313
+ tag: 'sync',
1314
+ attrs: {},
1315
+ content: [
1316
+ {
1317
+ tag: 'collection',
1318
+ attrs: {
1319
+ name,
1320
+ version: (state.version - 1).toString(),
1321
+ return_snapshot: 'false'
1322
+ },
1323
+ content: [
1324
+ {
1325
+ tag: 'patch',
1326
+ attrs: {},
1327
+ content: index_js_1.proto.SyncdPatch.encode(patch).finish()
1328
+ }
1329
+ ]
1330
+ }
1331
+ ]
1332
+ }
1333
+ ]
1334
+ }
1335
+ await query(node)
1336
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
1337
+ }, authState?.creds?.me?.id || 'app-patch')
1338
+ })
1339
+ if (config.emitOwnEvents) {
1340
+ const { onMutation } = newAppStateChunkHandler(false)
1341
+ const { mutationMap } = await (0, Utils_1.decodePatches)(
1342
+ name,
1343
+ [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }],
1344
+ initial,
1345
+ getAppStateSyncKey,
1346
+ config.options,
1347
+ undefined,
1348
+ logger
1349
+ )
1350
+ for (const key in mutationMap) {
1351
+ onMutation(mutationMap[key])
1352
+ }
1353
+ }
1354
+ }
1355
+ /** sending non-abt props may fix QR scan fail if server expects */
1356
+ const fetchProps = async () => {
1357
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
1358
+ const resultNode = await query({
1359
+ tag: 'iq',
1360
+ attrs: {
1361
+ to: WABinary_1.S_WHATSAPP_NET,
1362
+ xmlns: 'w',
1363
+ type: 'get'
1364
+ },
1365
+ content: [
1366
+ {
1367
+ tag: 'props',
1368
+ attrs: {
1369
+ protocol: '2',
1370
+ hash: authState?.creds?.lastPropHash || ''
1371
+ }
1372
+ }
1373
+ ]
1374
+ })
1375
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props')
1376
+ let props = {}
1377
+ if (propsNode) {
1378
+ if (propsNode.attrs?.hash) {
1379
+ // on some clients, the hash is returning as undefined
1380
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
1381
+ ev.emit('creds.update', authState.creds)
1382
+ }
1383
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop')
1384
+ }
1385
+ // Extract protocol-relevant AB props (only the ones we need)
1386
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages']
1387
+ if (privacyTokenProp !== undefined) {
1388
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1'
1389
+ }
1390
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq']
1391
+ if (profilePicProp !== undefined) {
1392
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1'
1393
+ }
1394
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid']
1395
+ if (lidIssueProp !== undefined) {
1396
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1'
1397
+ }
1398
+ logger.debug({ serverProps }, 'fetched props')
1399
+ return props
1400
+ }
1401
+ /**
1402
+ * modify a chat -- mark unread, read etc.
1403
+ * lastMessages must be sorted in reverse chronologically
1404
+ * requires the last messages till the last message received; required for archive & unread
1405
+ */
1406
+ const chatModify = (mod, jid) => {
1407
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid)
1408
+ return appPatch(patch)
1409
+ }
1410
+ /**
1411
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
1412
+ */
1413
+ const updateDisableLinkPreviewsPrivacy = isPreviewsDisabled => {
1414
+ return chatModify(
1415
+ {
1416
+ disableLinkPreviews: { isPreviewsDisabled }
1417
+ },
1418
+ ''
1419
+ )
1420
+ }
1421
+ /**
1422
+ * Star or Unstar a message
1423
+ */
1424
+ const star = (jid, messages, star) => {
1425
+ return chatModify(
1426
+ {
1427
+ star: {
1428
+ messages,
1429
+ star
1430
+ }
1431
+ },
1432
+ jid
1433
+ )
1434
+ }
1435
+ /**
1436
+ * Add or Edit Contact
1437
+ */
1438
+ const addOrEditContact = (jid, contact) => {
1439
+ return chatModify(
1440
+ {
1441
+ contact
1442
+ },
1443
+ jid
1444
+ )
1445
+ }
1446
+ /**
1447
+ * Remove Contact
1448
+ */
1449
+ const removeContact = jid => {
1450
+ return chatModify(
1451
+ {
1452
+ contact: null
1453
+ },
1454
+ jid
1455
+ )
1456
+ }
1457
+ /**
1458
+ * Adds label
1459
+ */
1460
+ const addLabel = (jid, labels) => {
1461
+ return chatModify(
1462
+ {
1463
+ addLabel: {
1464
+ ...labels
1465
+ }
1466
+ },
1467
+ jid
1468
+ )
1469
+ }
1470
+ /**
1471
+ * Adds label for the chats
1472
+ */
1473
+ const addChatLabel = (jid, labelId) => {
1474
+ return chatModify(
1475
+ {
1476
+ addChatLabel: {
1477
+ labelId
1478
+ }
1479
+ },
1480
+ jid
1481
+ )
1482
+ }
1483
+ /**
1484
+ * Removes label for the chat
1485
+ */
1486
+ const removeChatLabel = (jid, labelId) => {
1487
+ return chatModify(
1488
+ {
1489
+ removeChatLabel: {
1490
+ labelId
1491
+ }
1492
+ },
1493
+ jid
1494
+ )
1495
+ }
1496
+ /**
1497
+ * Adds label for the message
1498
+ */
1499
+ const addMessageLabel = (jid, messageId, labelId) => {
1500
+ return chatModify(
1501
+ {
1502
+ addMessageLabel: {
1503
+ messageId,
1504
+ labelId
1505
+ }
1506
+ },
1507
+ jid
1508
+ )
1509
+ }
1510
+ /**
1511
+ * Removes label for the message
1512
+ */
1513
+ const removeMessageLabel = (jid, messageId, labelId) => {
1514
+ return chatModify(
1515
+ {
1516
+ removeMessageLabel: {
1517
+ messageId,
1518
+ labelId
1519
+ }
1520
+ },
1521
+ jid
1522
+ )
1523
+ }
1524
+ /**
1525
+ * Add or Edit Quick Reply
1526
+ */
1527
+ const addOrEditQuickReply = quickReply => {
1528
+ return chatModify(
1529
+ {
1530
+ quickReply
1531
+ },
1532
+ ''
1533
+ )
1534
+ }
1535
+ /**
1536
+ * Remove Quick Reply
1537
+ */
1538
+ const removeQuickReply = timestamp => {
1539
+ return chatModify(
1540
+ {
1541
+ quickReply: { timestamp, deleted: true }
1542
+ },
1543
+ ''
1544
+ )
1545
+ }
1546
+ /**
1547
+ * Rename an AI chat thread
1548
+ */
1549
+ const renameAIThread = (jid, title) => {
1550
+ return chatModify({ aiThreadRename: { title } }, jid)
1551
+ }
1552
+ /**
1553
+ * Pin or unpin a message in a thread/AI chat
1554
+ */
1555
+ const pinThreadMessage = (jid, messageId, pinned = true) => {
1556
+ return chatModify({ threadPin: { pinned, messageId } }, jid)
1557
+ }
1558
+ /**
1559
+ * Toggle AI private processing (end-to-end encrypted AI processing)
1560
+ */
1561
+ const updatePrivateProcessingSetting = enabled => {
1562
+ return chatModify({ privateProcessingSetting: enabled ? 'enabled' : 'disabled' }, '')
1563
+ }
1564
+ /**
1565
+ * Update Meta AI features control
1566
+ * @param status 'enabled' | 'enabled_has_learning' | 'disabled'
1567
+ * @param replyMode 'muted' | 'ai_agent' | 'suggestions'
1568
+ */
1569
+ const updateAIFeatures = (status = 'enabled', replyMode = 'suggestions') => {
1570
+ const statusEnum =
1571
+ require('../../WAProto/index.js').proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIFeatureStatus
1572
+ const replyModeEnum =
1573
+ require('../../WAProto/index.js').proto.SyncActionValue.MaibaAIFeaturesControlAction.MaibaAIReplyMode
1574
+ const statusMap = {
1575
+ enabled: statusEnum.ENABLED,
1576
+ enabled_has_learning: statusEnum.ENABLED_HAS_LEARNING,
1577
+ disabled: statusEnum.DISABLED
1578
+ }
1579
+ const replyModeMap = {
1580
+ muted: replyModeEnum.MUTED,
1581
+ ai_agent: replyModeEnum.AI_AGENT,
1582
+ suggestions: replyModeEnum.SUGGESTIONS
1583
+ }
1584
+ return chatModify(
1585
+ {
1586
+ maibaAIFeatures: {
1587
+ status: statusMap[status] ?? statusEnum.ENABLED,
1588
+ replyMode: replyModeMap[replyMode] ?? replyModeEnum.SUGGESTIONS
1589
+ }
1590
+ },
1591
+ ''
1592
+ )
1593
+ }
1594
+ /**
1595
+ * Update bio/about privacy (who can see your About text)
1596
+ * @param value 'all' | 'contacts' | 'contact_blacklist' | 'none'
1597
+ */
1598
+ const updateBioPrivacy = async value => {
1599
+ await privacyQuery('about', value)
1600
+ }
1601
+ /**
1602
+ * Block a bot JID
1603
+ */
1604
+ const blockBot = async botJid => {
1605
+ await query({
1606
+ tag: 'iq',
1607
+ attrs: {
1608
+ xmlns: 'disappearing_mode',
1609
+ to: WABinary_1.S_WHATSAPP_NET,
1610
+ type: 'set'
1611
+ },
1612
+ content: [
1613
+ {
1614
+ tag: 'block',
1615
+ attrs: { jid: botJid }
1616
+ }
1617
+ ]
1618
+ })
1619
+ }
1620
+ /**
1621
+ * Unblock a bot JID
1622
+ */
1623
+ const unblockBot = async botJid => {
1624
+ await updateBlockStatus(botJid, 'unblock')
1625
+ }
1626
+ /**
1627
+ * Mute or unmute a contact's status updates
1628
+ */
1629
+ const muteContactStatus = (jid, muted = true) => {
1630
+ return chatModify({ muteStatus: { muted } }, jid)
1631
+ }
1632
+ /**
1633
+ * Add or remove a contact from favorites
1634
+ */
1635
+ const toggleFavorite = (jid, isFavorite = true) => {
1636
+ return chatModify({ favorite: { isFavorite } }, jid)
1637
+ }
1638
+ /**
1639
+ * Reorder labels
1640
+ * @param sortedLabelIds ordered array of label IDs
1641
+ */
1642
+ const reorderLabels = sortedLabelIds => {
1643
+ return chatModify({ reorderLabel: { sortedLabelIds } }, '')
1644
+ }
1645
+ /**
1646
+ * Delete an individual call log entry
1647
+ */
1648
+ const deleteCallLog = (callId, jid = '') => {
1649
+ return chatModify({ deleteCallLog: { callId } }, jid)
1650
+ }
1651
+ /**
1652
+ * Create or update a note/draft for a chat
1653
+ */
1654
+ const setChatNote = (jid, note) => {
1655
+ return chatModify({ noteEdit: { note } }, jid)
1656
+ }
1657
+ /**
1658
+ * Delete the note/draft for a chat
1659
+ */
1660
+ const deleteChatNote = jid => {
1661
+ return chatModify({ noteEdit: { note: '', deleted: true } }, jid)
1662
+ }
1663
+ /**
1664
+ * Explicitly mark a chat as unread (shows unread dot even if read)
1665
+ */
1666
+ const markChatAsUnread = (jid, lastMessages) => {
1667
+ return chatModify({ markAsUnread: true, lastMessages }, jid)
1668
+ }
1669
+ /**
1670
+ * Set per-chat ephemeral message duration
1671
+ * @param duration seconds (0 = off, 86400 = 1d, 604800 = 7d, 7776000 = 90d)
1672
+ */
1673
+ const setChatEphemeral = (jid, duration) => {
1674
+ return chatModify({ setChatEphemeral: duration }, jid)
1675
+ }
1676
+ /**
1677
+ * Silence a chat (mute without timestamp = permanent, or provide until timestamp)
1678
+ */
1679
+ const silenceChat = (jid, silent = true, until = null) => {
1680
+ return chatModify({ silenceChat: { silent, until } }, jid)
1681
+ }
1682
+ /**
1683
+ * Clear all messages in a chat
1684
+ */
1685
+ const clearChat = (jid, lastMessages) => {
1686
+ return chatModify({ clear: true, lastMessages }, jid)
1687
+ }
1688
+ /**
1689
+ * Pin or unpin a chat to the top
1690
+ */
1691
+ const pinChat = (jid, pinned = true) => {
1692
+ return chatModify({ pin: { pinned } }, jid)
1693
+ }
1694
+ /**
1695
+ * Star or unstar messages
1696
+ */
1697
+ const starMessages = (jid, messageIds, starred = true) => {
1698
+ return chatModify({ star: { messages: messageIds, star: starred } }, jid)
1699
+ }
1700
+ /**
1701
+ * Set up a quick reply
1702
+ */
1703
+ const setQuickReply = (text, shortcut) => {
1704
+ return chatModify({ quickReply: { text, shortcut } }, '')
1705
+ }
1706
+ /**
1707
+ * Fetch bot profiles for a list of JIDs using USyncBotProfileProtocol
1708
+ */
1709
+ const fetchBotProfiles = async jids => {
1710
+ const { USyncQuery, USyncUser, USyncBotProfileProtocol } = require('../WAUSync')
1711
+ const q = new USyncQuery()
1712
+ q.protocols.push(new USyncBotProfileProtocol())
1713
+ for (const jid of jids) {
1714
+ q.withUser(new USyncUser().withId(jid))
1715
+ }
1716
+ const result = await executeUSyncQuery(q)
1717
+ return result?.list || []
1718
+ }
1719
+ /**
1720
+ * Lock or unlock a chat with an optional secret code
1721
+ */
1722
+ const updateChatLock = (jid, locked) => {
1723
+ return chatModify({ chatLock: { locked } }, jid)
1724
+ }
1725
+ /**
1726
+ * Set a custom wallpaper for a chat
1727
+ * @param jid the chat JID
1728
+ * @param wallpaper wallpaper data or null to remove
1729
+ */
1730
+ const updateChatWallpaper = (jid, wallpaper) => {
1731
+ if (!wallpaper) {
1732
+ return chatModify({ wallpaper: { remove: true } }, jid)
1733
+ }
1734
+ return chatModify({ wallpaper }, jid)
1735
+ }
1736
+ /**
1737
+ * Set media visibility (auto-download) for a chat
1738
+ * @param jid the chat JID
1739
+ * @param visibility 'default' | 'on' | 'off'
1740
+ */
1741
+ const updateChatMediaVisibility = (jid, visibility) => {
1742
+ return chatModify({ mediaVisibility: visibility }, jid)
1743
+ }
1744
+ /**
1745
+ * Fetch details for a specific bot by JID
1746
+ */
1747
+ const getBotProfile = async botJid => {
1748
+ const resp = await query({
1749
+ tag: 'iq',
1750
+ attrs: {
1751
+ xmlns: 'bot',
1752
+ to: WABinary_1.S_WHATSAPP_NET,
1753
+ type: 'get'
1754
+ },
1755
+ content: [
1756
+ {
1757
+ tag: 'bot',
1758
+ attrs: { v: '2', jid: botJid }
1759
+ }
1760
+ ]
1761
+ })
1762
+ const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot')
1763
+ if (!botNode) return null
1764
+ return {
1765
+ jid: botNode.attrs.jid,
1766
+ personaId: botNode.attrs['persona_id'],
1767
+ name: botNode.attrs.name,
1768
+ description: botNode.attrs.description
1769
+ }
1770
+ }
1771
+ /**
1772
+ * Fetch AB-test (abt) props from server.
1773
+ * Mirrors ABPropsProtocolHelper — protocol 1 or 2, optional hash/refresh_id/group.
1774
+ * Confirmed from live capture: group-scoped queries send only { group }, never combined
1775
+ * with protocol/hash/refresh_id; the account-level default protocol is "1", not "2".
1776
+ */
1777
+ const fetchABProps = async (protocol = '1', hash = '', refreshId = null, group = null) => {
1778
+ const propAttrs =
1779
+ group != null
1780
+ ? { group: String(group) }
1781
+ : {
1782
+ protocol,
1783
+ ...(hash ? { hash } : {}),
1784
+ ...(refreshId != null ? { refresh_id: String(refreshId) } : {})
1785
+ }
1786
+ const result = await query({
1787
+ tag: 'iq',
1788
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'abt', type: 'get' },
1789
+ content: [{ tag: 'props', attrs: propAttrs }]
1790
+ })
1791
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(result, 'props')
1792
+ if (!propsNode) return {}
1793
+ return (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop')
1794
+ }
1795
+ /**
1796
+ * Remove a companion (linked) device from the account.
1797
+ * Mirrors CompanionDeviceRemovalJob — xmlns="md", child tag "remove-companion-device".
1798
+ * jid: full device JID of the companion to remove (e.g. "1234567890:5@s.whatsapp.net").
1799
+ * reason: "user_initiated" | "unknown_companion" | any WA-defined reason string.
1800
+ * Confirmed from live capture — the previous { platform, id: keyIndex } attrs never
1801
+ * identified a device at all; the server needs the companion's full jid.
1802
+ */
1803
+ const removeCompanionDevice = async (jid, reason = 'user_initiated') => {
1804
+ await query({
1805
+ tag: 'iq',
1806
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'md', type: 'set' },
1807
+ content: [
1808
+ {
1809
+ tag: 'remove-companion-device',
1810
+ attrs: { jid, reason }
1811
+ }
1812
+ ]
1813
+ })
1814
+ }
1815
+ /**
1816
+ * Push an updated key-index-list to the server (multi-device key announcement).
1817
+ * Mirrors KeyIndexListJob — xmlns="md", child tag "key-index-list" with a binary proto body.
1818
+ * ts: unix timestamp seconds (string or number).
1819
+ * content: Buffer — serialized proto KeyIndexList.
1820
+ */
1821
+ const updateKeyIndexList = async (ts, content) => {
1822
+ await query({
1823
+ tag: 'iq',
1824
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'md', type: 'set' },
1825
+ content: [
1826
+ {
1827
+ tag: 'key-index-list',
1828
+ attrs: { ts: String(ts) },
1829
+ content
1830
+ }
1831
+ ]
1832
+ })
1833
+ }
1834
+ /**
1835
+ * Build and push the companion's signed key-index-list on (re)connect.
1836
+ *
1837
+ * The official client sends this within ~0.8s of every session start (xmlns="md").
1838
+ * A companion that never re-asserts its ADV key index is treated as unverified and
1839
+ * gets <conflict type="device_removed"/>.
1840
+ *
1841
+ * Payload construction mirrors CompanionDeviceAdvUtil.A02 (C19350ud) from the APK:
1842
+ * details = proto ADVKeyIndexList { rawId, timestamp, currentIndex, validIndexes, accountType }
1843
+ * accountSignature = Curve.sign(signedIdentityKey.private, [6,2] || details)
1844
+ * accountSignatureKey = only attached for HOSTED accounts (skipped for consumer E2EE)
1845
+ * The signature uses our own device identity key (the same key that produces the ADV
1846
+ * deviceSignature during pairing) — a companion cannot re-sign with the account key.
1847
+ */
1848
+ const sendKeyIndexList = async () => {
1849
+ const account = authState.creds.account
1850
+ const signedIdentityKey = authState.creds.signedIdentityKey
1851
+ if (!account?.details || !signedIdentityKey?.private) {
1852
+ logger.debug('no ADV account / signed identity key, skipping key-index-list')
1853
+ return
1854
+ }
1855
+ const deviceIdentity = index_js_1.proto.ADVDeviceIdentity.decode(account.details)
1856
+ const keyIndex = deviceIdentity.keyIndex || 0
1857
+ const accountType = deviceIdentity.accountType ?? index_js_1.proto.ADVEncryptionType.E2EE
1858
+ const isHosted = accountType === index_js_1.proto.ADVEncryptionType.HOSTED
1859
+ const ts = Math.floor(Date.now() / 1000)
1860
+ const details = index_js_1.proto.ADVKeyIndexList.encode({
1861
+ rawId: deviceIdentity.rawId || 0,
1862
+ timestamp: ts,
1863
+ currentIndex: keyIndex,
1864
+ validIndexes: [keyIndex],
1865
+ accountType
1866
+ }).finish()
1867
+ const sigPrefix = isHosted
1868
+ ? Defaults_1.WA_ADV_HOSTED_KEY_INDEX_LIST_SIG_PREFIX
1869
+ : Defaults_1.WA_ADV_KEY_INDEX_LIST_SIG_PREFIX
1870
+ const accountSignature = Utils_1.Curve.sign(signedIdentityKey.private, Buffer.concat([sigPrefix, details]))
1871
+ const signedKeyIndexList = { details, accountSignature }
1872
+ if (isHosted && account.accountSignatureKey?.length) {
1873
+ signedKeyIndexList.accountSignatureKey = account.accountSignatureKey
1874
+ }
1875
+ const content = index_js_1.proto.ADVSignedKeyIndexList.encode(signedKeyIndexList).finish()
1876
+ await updateKeyIndexList(ts, Buffer.from(content))
1877
+ logger.info({ ts, keyIndex }, 'sent key-index-list')
1878
+ }
1879
+ /**
1880
+ * Request a media upload connection token from the server.
1881
+ * Mirrors MediaConnFetcher — xmlns="w:m", type="set", optional last_id.
1882
+ * Returns the raw media_conn node.
1883
+ */
1884
+ const fetchMediaConn = async (lastId = null) => {
1885
+ const attrs = {}
1886
+ if (lastId != null) attrs.last_id = String(lastId)
1887
+ const result = await query({
1888
+ tag: 'iq',
1889
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'w:m', type: 'set' },
1890
+ content: [{ tag: 'media_conn', attrs }]
1891
+ })
1892
+ return (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn') || null
1893
+ }
1894
+ /**
1895
+ * Delete a broadcast list by ID.
1896
+ * Mirrors BroadcastListDeleteJob — xmlns="w:b", wraps <delete><list id="..."/></delete>.
1897
+ */
1898
+ const deleteBroadcastList = async listId => {
1899
+ await query({
1900
+ tag: 'iq',
1901
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'w:b', type: 'set' },
1902
+ content: [
1903
+ {
1904
+ tag: 'delete',
1905
+ attrs: {},
1906
+ content: [{ tag: 'list', attrs: { id: String(listId) } }]
1907
+ }
1908
+ ]
1909
+ })
1910
+ }
1911
+ /**
1912
+ * Fetch a QR code from the server (e.g. for linked-device linking).
1913
+ * Mirrors QRCodeFetcher — xmlns="w:qr", type="get".
1914
+ * addressingMode: "lid" | undefined — set to "lid" for LID-addressed QR.
1915
+ */
1916
+ const fetchQRCode = async (code, addressingMode = null) => {
1917
+ const attrs = { code }
1918
+ if (addressingMode) attrs.addressing_mode = addressingMode
1919
+ const result = await query({
1920
+ tag: 'iq',
1921
+ attrs: { to: WABinary_1.S_WHATSAPP_NET, xmlns: 'w:qr', type: 'get' },
1922
+ content: [{ tag: 'qr', attrs }]
1923
+ })
1924
+ return (0, WABinary_1.getBinaryNodeChild)(result, 'qr') || null
1925
+ }
1926
+ /**
1927
+ * Confirm or deny a device-logout request from the server.
1928
+ * Mirrors AccountDefenceDeviceLogoutJob — xmlns="w:account_defence", smax_id=87.
1929
+ * approve: true to confirm the logout, false to deny.
1930
+ */
1931
+ const confirmDeviceLogout = async (id, approve = true) => {
1932
+ await query({
1933
+ tag: 'iq',
1934
+ attrs: {
1935
+ // reuse the challenge id at the iq level too, matching AccountDefenceDeviceLogoutJob
1936
+ id: String(id),
1937
+ to: WABinary_1.S_WHATSAPP_NET,
1938
+ xmlns: 'w:account_defence',
1939
+ type: 'set',
1940
+ smax_id: '87'
1941
+ },
1942
+ content: [
1943
+ {
1944
+ tag: 'device_logout',
1945
+ attrs: { approve: approve ? 'true' : 'false', id: String(id) }
1946
+ }
1947
+ ]
1948
+ })
1949
+ }
1950
+ /**
1951
+ * queries need to be fired on connection open
1952
+ * help ensure parity with WA Web
1953
+ * */
1954
+ const executeInitQueries = async () => {
1955
+ // Gate initInterop on previously-persisted flag: undefined = first connection (always run);
1956
+ // false = account has interop disabled, skip the TOS/opt-in flow on reconnect.
1957
+ const shouldInitInterop = authState.creds.interopEnabled !== false
1958
+ const [, , , abProps] = await Promise.all([
1959
+ fetchProps(),
1960
+ fetchBlocklist(),
1961
+ fetchPrivacySettings(),
1962
+ fetchABProps(),
1963
+ ...(shouldInitInterop ? [initInterop()] : [])
1964
+ ])
1965
+ const INTEROP_FLAGS = ['stella_interop_enabled', 'stella_ios_enabled']
1966
+ for (const flag of INTEROP_FLAGS) {
1967
+ if (flag in abProps) {
1968
+ const enabled = abProps[flag] === 'true' || abProps[flag] === '1'
1969
+ ev.emit('interop.feature-update', { feature: flag, enabled })
1970
+ }
1971
+ }
1972
+ // Persist AB prop feature flags into connection credentials so they survive reconnect.
1973
+ const abCredsUpdate = {}
1974
+ if ('stella_interop_enabled' in abProps) {
1975
+ abCredsUpdate.interopEnabled =
1976
+ abProps['stella_interop_enabled'] === 'true' || abProps['stella_interop_enabled'] === '1'
1977
+ }
1978
+ if ('stella_ios_enabled' in abProps) {
1979
+ abCredsUpdate.interopIosEnabled =
1980
+ abProps['stella_ios_enabled'] === 'true' || abProps['stella_ios_enabled'] === '1'
1981
+ }
1982
+ if ('md_privacy_v2' in abProps) {
1983
+ abCredsUpdate.mdPrivacyV2 = abProps['md_privacy_v2'] === 'true' || abProps['md_privacy_v2'] === '1'
1984
+ }
1985
+ // Persist media feature-flag AB props so upload/download paths can gate on them.
1986
+ const MEDIA_AB_PROPS = [
1987
+ 'hd_image_dual_upload',
1988
+ 'hd_video_dual_upload',
1989
+ 'hevc_video_dual_upload',
1990
+ 'partial_pjpeg_enabled',
1991
+ 'multi_scan_pjpeg',
1992
+ 'media_poll'
1993
+ ]
1994
+ const mediaAbProps = {}
1995
+ for (const prop of MEDIA_AB_PROPS) {
1996
+ if (prop in abProps) {
1997
+ mediaAbProps[prop] = abProps[prop] === 'true' || abProps[prop] === '1'
1998
+ }
1999
+ }
2000
+ if (Object.keys(mediaAbProps).length) {
2001
+ abCredsUpdate.mediaAbProps = { ...(authState.creds.mediaAbProps || {}), ...mediaAbProps }
2002
+ }
2003
+ if (Object.keys(abCredsUpdate).length) {
2004
+ ev.emit('creds.update', abCredsUpdate)
2005
+ }
2006
+ }
2007
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
2008
+ // Cache newsletter server_id for use when this message is later quoted
2009
+ if (msg.newsletter && msg.newsletter_server_id && msg.key?.id) {
2010
+ _nlServerIdCache.set(msg.key.id, msg.newsletter_server_id)
2011
+ }
2012
+ // If this message quotes a newsletter post, enrich it with the cached server_id
2013
+ if (msg.message) {
2014
+ const ci = Object.values(msg.message).find(v => v?.contextInfo)?.contextInfo
2015
+ if (ci?.stanzaId && (0, WABinary_1.isJidNewsletter)(ci.remoteJid)) {
2016
+ const sid = _nlServerIdCache.get(ci.stanzaId)
2017
+ if (sid != null) msg.quotedNewsletterServerId = sid
2018
+ }
2019
+ }
2020
+ ev.emit('messages.upsert', { messages: [msg], type })
2021
+ if (!!msg.pushName) {
2022
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid
2023
+ jid = (0, WABinary_1.jidNormalizedUser)(jid)
2024
+ if (!msg.key.fromMe) {
2025
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
2026
+ }
2027
+ // update our pushname too
2028
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
2029
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
2030
+ }
2031
+ }
2032
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message)
2033
+ const shouldProcessHistoryMsg = historyMsg
2034
+ ? shouldSyncHistoryMessage(historyMsg) && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
2035
+ : false
2036
+ if (historyMsg && shouldProcessHistoryMsg) {
2037
+ const syncType = historyMsg.syncType
2038
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check
2039
+ if (
2040
+ syncType === index_js_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
2041
+ !historySyncStatus.initialBootstrapComplete
2042
+ ) {
2043
+ historySyncStatus.initialBootstrapComplete = true
2044
+ ev.emit('messaging-history.status', {
2045
+ syncType,
2046
+ status: 'complete',
2047
+ explicit: true
2048
+ })
2049
+ }
2050
+ // RECENT with progress === 100 — explicit completion
2051
+ if (
2052
+ syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT &&
2053
+ historyMsg.progress === 100 &&
2054
+ !historySyncStatus.recentSyncComplete
2055
+ ) {
2056
+ historySyncStatus.recentSyncComplete = true
2057
+ clearTimeout(historySyncPausedTimeout)
2058
+ historySyncPausedTimeout = undefined
2059
+ ev.emit('messaging-history.status', {
2060
+ syncType,
2061
+ status: 'complete',
2062
+ explicit: true
2063
+ })
2064
+ }
2065
+ // Reset 120s paused timeout on any RECENT chunk
2066
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
2067
+ clearTimeout(historySyncPausedTimeout)
2068
+ historySyncPausedTimeout = setTimeout(() => {
2069
+ if (!historySyncStatus.recentSyncComplete) {
2070
+ historySyncStatus.recentSyncComplete = true
2071
+ ev.emit('messaging-history.status', {
2072
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT,
2073
+ status: 'paused',
2074
+ explicit: false
2075
+ })
2076
+ }
2077
+ historySyncPausedTimeout = undefined
2078
+ }, Defaults_1.HISTORY_SYNC_PAUSED_TIMEOUT_MS)
2079
+ }
2080
+ }
2081
+ // State machine: decide on sync and flush
2082
+ if (historyMsg && syncState === State_1.SyncState.AwaitingInitialSync) {
2083
+ if (awaitingSyncTimeout) {
2084
+ clearTimeout(awaitingSyncTimeout)
2085
+ awaitingSyncTimeout = undefined
2086
+ }
2087
+ if (shouldProcessHistoryMsg) {
2088
+ syncState = State_1.SyncState.Syncing
2089
+ logger.info('Transitioned to Syncing state')
2090
+ // Let doAppStateSync handle the final flush after it's done
2091
+ } else {
2092
+ syncState = State_1.SyncState.Online
2093
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
2094
+ ev.flush()
2095
+ }
2096
+ }
2097
+ const doAppStateSync = async () => {
2098
+ if (syncState === State_1.SyncState.Syncing) {
2099
+ // All collections will be synced, so clear any blocked ones
2100
+ blockedCollections.clear()
2101
+ logger.info('Doing app state sync')
2102
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true)
2103
+ // Sync is complete, go online and flush everything
2104
+ syncState = State_1.SyncState.Online
2105
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
2106
+ ev.flush()
2107
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
2108
+ ev.emit('creds.update', { accountSyncCounter })
2109
+ }
2110
+ }
2111
+ await Promise.all([
2112
+ (async () => {
2113
+ if (shouldProcessHistoryMsg) {
2114
+ await doAppStateSync()
2115
+ }
2116
+ })(),
2117
+ (0, process_message_1.default)(msg, {
2118
+ signalRepository,
2119
+ shouldProcessHistoryMsg,
2120
+ placeholderResendCache,
2121
+ ev,
2122
+ creds: authState.creds,
2123
+ keyStore: authState.keys,
2124
+ logger,
2125
+ options: config.options,
2126
+ getMessage
2127
+ })
2128
+ ])
2129
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
2130
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === State_1.SyncState.Syncing) {
2131
+ logger.info('App state sync key arrived, triggering app state sync')
2132
+ await doAppStateSync()
2133
+ }
2134
+ })
2135
+ ws.on('CB:presence', handlePresenceUpdate)
2136
+ ws.on('CB:chatstate', handlePresenceUpdate)
2137
+ // Server device-legitimacy challenge (w:account_defence). Fires a few seconds after the
2138
+ // companion sends its first message; if we don't approve within ~20s the device is removed
2139
+ // with <conflict type="device_removed"/>. Wire the inbound challenge to confirmDeviceLogout.
2140
+ ws.on('CB:iq,xmlns:w:account_defence', async node => {
2141
+ const deviceLogout = (0, WABinary_1.getBinaryNodeChild)(node, 'device_logout')
2142
+ if (!deviceLogout) return
2143
+ const id = node.attrs.id
2144
+ logger.info({ id }, 'received account_defence device_logout challenge, approving')
2145
+ try {
2146
+ await confirmDeviceLogout(id, true)
2147
+ } catch (error) {
2148
+ onUnexpectedError(error, 'account_defence device_logout approve')
2149
+ }
2150
+ })
2151
+ ws.on('CB:ib,,dirty', async node => {
2152
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty')
2153
+ const type = attrs.type
2154
+ switch (type) {
2155
+ case 'account_sync':
2156
+ if (attrs.timestamp) {
2157
+ let { lastAccountSyncTimestamp } = authState.creds
2158
+ if (lastAccountSyncTimestamp) {
2159
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
2160
+ }
2161
+ lastAccountSyncTimestamp = +attrs.timestamp
2162
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
2163
+ }
2164
+ break
2165
+ case 'groups':
2166
+ // handled in groups.ts
2167
+ break
2168
+ default:
2169
+ logger.info({ node }, 'received unknown sync')
2170
+ break
2171
+ }
2172
+ })
2173
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
2174
+ if (connection === 'close') {
2175
+ blockedCollections.clear()
2176
+ clearTimeout(historySyncPausedTimeout)
2177
+ historySyncPausedTimeout = undefined
2178
+ }
2179
+ if (connection === 'open') {
2180
+ if (fireInitQueries) {
2181
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
2182
+ }
2183
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error =>
2184
+ onUnexpectedError(error, 'presence update requests')
2185
+ )
2186
+ // Re-assert our ADV key index to the server on every (re)connect, or the companion
2187
+ // is treated as unverified and removed. Best-effort: never block the open flow.
2188
+ sendKeyIndexList().catch(error => onUnexpectedError(error, 'send key-index-list'))
2189
+ }
2190
+ if (!receivedPendingNotifications || syncState !== State_1.SyncState.Connecting) {
2191
+ return
2192
+ }
2193
+ historySyncStatus.initialBootstrapComplete = false
2194
+ historySyncStatus.recentSyncComplete = false
2195
+ clearTimeout(historySyncPausedTimeout)
2196
+ historySyncPausedTimeout = undefined
2197
+ syncState = State_1.SyncState.AwaitingInitialSync
2198
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
2199
+ ev.buffer()
2200
+ const willSyncHistory = shouldSyncHistoryMessage(
2201
+ index_js_1.proto.Message.HistorySyncNotification.create({
2202
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT
2203
+ })
2204
+ )
2205
+ if (!willSyncHistory) {
2206
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
2207
+ syncState = State_1.SyncState.Online
2208
+ setTimeout(() => ev.flush(), 0)
2209
+ return
2210
+ }
2211
+ // On reconnection (accountSyncCounter > 0), the server does not push
2212
+ // history sync notifications — the device already has its data.
2213
+ // Skip the 20s wait and go online immediately.
2214
+ if (authState.creds.accountSyncCounter > 0) {
2215
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.')
2216
+ syncState = State_1.SyncState.Online
2217
+ setTimeout(() => ev.flush(), 0)
2218
+ return
2219
+ }
2220
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.')
2221
+ if (awaitingSyncTimeout) {
2222
+ clearTimeout(awaitingSyncTimeout)
2223
+ }
2224
+ awaitingSyncTimeout = setTimeout(() => {
2225
+ if (syncState === State_1.SyncState.AwaitingInitialSync) {
2226
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
2227
+ syncState = State_1.SyncState.Online
2228
+ ev.flush()
2229
+ // Increment so subsequent reconnections skip the 20s wait.
2230
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
2231
+ ev.emit('creds.update', { accountSyncCounter })
2232
+ }
2233
+ }, 20000)
2234
+ })
2235
+ // When an app state sync key arrives and there are collections blocked on a missing key, re-sync them.
2236
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
2237
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
2238
+ return
2239
+ }
2240
+ // If we're in the middle of a full sync, doAppStateSync handles all collections
2241
+ if (syncState === State_1.SyncState.Syncing) {
2242
+ blockedCollections.clear()
2243
+ return
2244
+ }
2245
+ const collections = [...blockedCollections]
2246
+ blockedCollections.clear()
2247
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections')
2248
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'))
2249
+ })
2250
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
2251
+ try {
2252
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }])
2253
+ } catch (error) {
2254
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping')
2255
+ }
2256
+ })
2257
+ return {
2258
+ ...sock,
2259
+ serverProps,
2260
+ createCallLink,
2261
+ toggleCallLinkWaitingRoom,
2262
+ getBotListV2,
2263
+ getChatBlockingStatus,
2264
+ updateChatBlockingStatus,
2265
+ getUserDisclosures,
2266
+ acceptTosNotice,
2267
+ reportSpam,
2268
+ getOptOutList,
2269
+ getPushConfig,
2270
+ setPushConfig,
2271
+ signPrivateCredential,
2272
+ messageMutex,
2273
+ receiptMutex,
2274
+ appStatePatchMutex,
2275
+ notificationMutex,
2276
+ fetchPrivacySettings,
2277
+ upsertMessage,
2278
+ appPatch,
2279
+ sendPresenceUpdate,
2280
+ presenceSubscribe,
2281
+ profilePictureUrl,
2282
+ fetchBlocklist,
2283
+ fetchStatus,
2284
+ fetchDisappearingDuration,
2285
+ updateProfilePicture,
2286
+ removeProfilePicture,
2287
+ updateProfileStatus,
2288
+ updateProfileName,
2289
+ updateBlockStatus,
2290
+ updateDisableLinkPreviewsPrivacy,
2291
+ updateCallPrivacy,
2292
+ updateMessagesPrivacy,
2293
+ updateLastSeenPrivacy,
2294
+ updateOnlinePrivacy,
2295
+ updateProfilePicturePrivacy,
2296
+ updateStatusPrivacy,
2297
+ getStatusPrivacy,
2298
+ setStatusPrivacy,
2299
+ updateReadReceiptsPrivacy,
2300
+ updateGroupsAddPrivacy,
2301
+ updateDefaultDisappearingMode,
2302
+ fetchBroadcastListQuota,
2303
+ getBusinessProfile,
2304
+ resyncAppState,
2305
+ chatModify,
2306
+ cleanDirtyBits,
2307
+ addOrEditContact,
2308
+ removeContact,
2309
+ addLabel,
2310
+ addChatLabel,
2311
+ removeChatLabel,
2312
+ addMessageLabel,
2313
+ removeMessageLabel,
2314
+ star,
2315
+ addOrEditQuickReply,
2316
+ removeQuickReply,
2317
+ renameAIThread,
2318
+ pinThreadMessage,
2319
+ updatePrivateProcessingSetting,
2320
+ updateAIFeatures,
2321
+ updateBioPrivacy,
2322
+ blockBot,
2323
+ unblockBot,
2324
+ getBotProfile,
2325
+ muteContactStatus,
2326
+ toggleFavorite,
2327
+ reorderLabels,
2328
+ deleteCallLog,
2329
+ setChatNote,
2330
+ deleteChatNote,
2331
+ markChatAsUnread,
2332
+ setChatEphemeral,
2333
+ silenceChat,
2334
+ clearChat,
2335
+ pinChat,
2336
+ starMessages,
2337
+ setQuickReply,
2338
+ fetchBotProfiles,
2339
+ updateChatLock,
2340
+ updateChatWallpaper,
2341
+ updateChatMediaVisibility,
2342
+ fetchIntegrators,
2343
+ acceptInteropTOS,
2344
+ optInIntegrators,
2345
+ optOutIntegrators,
2346
+ resolveInteropUser,
2347
+ resolveInteropUsers,
2348
+ getReachabilitySettings,
2349
+ setReachabilitySettings,
2350
+ blockInteropUser,
2351
+ unblockInteropUser,
2352
+ reportInteropSpam,
2353
+ trustInteropContact,
2354
+ initInterop,
2355
+ createInteropGroup,
2356
+ leaveInteropGroup,
2357
+ getInteropGroupAddPrivacy,
2358
+ INTEGRATOR_BIRDYCHAT,
2359
+ INTEGRATOR_HAIKET,
2360
+ fetchABProps,
2361
+ removeCompanionDevice,
2362
+ updateKeyIndexList,
2363
+ fetchMediaConn,
2364
+ deleteBroadcastList,
2365
+ fetchQRCode,
2366
+ confirmDeviceLogout,
2367
+ updateKeyIndexList,
2368
+ sendKeyIndexList,
2369
+ storePrivacyTokens,
2370
+ executeUSyncQuery,
2371
+ newsletterServerIdCache: _nlServerIdCache
2372
+ }
2373
+ }
2374
+ exports.makeChatsSocket = makeChatsSocket