kage-baileys 3.0.6 → 3.2.3

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 (216) hide show
  1. package/Example/connection.cjs +4 -0
  2. package/README.MD +4726 -48
  3. package/WAProto/WAProto.proto +3395 -415
  4. package/WAProto/compat.cjs +12 -0
  5. package/WAProto/index.d.ts +47104 -19888
  6. package/WAProto/index.js +131979 -57361
  7. package/lib/Addon/http-error.js +43 -0
  8. package/lib/Addon/index.js +32 -0
  9. package/lib/Addon/keyed-db.js +250 -0
  10. package/lib/Addon/link-preview.js +82 -0
  11. package/lib/Defaults/baileys-version.json +3 -0
  12. package/lib/Defaults/connection.js +110 -0
  13. package/lib/Defaults/constants.js +156 -0
  14. package/lib/Defaults/history.js +46 -0
  15. package/lib/Defaults/index.js +230 -0
  16. package/lib/Defaults/media.js +104 -0
  17. package/lib/Defaults/phonenumber-mcc.json +223 -0
  18. package/lib/Defaults/prefix.js +44 -0
  19. package/lib/Extensions/business-advanced.js +382 -0
  20. package/lib/Extensions/business.js +159 -0
  21. package/lib/Extensions/chats-advanced.js +1106 -0
  22. package/lib/Extensions/chats.js +349 -0
  23. package/lib/Extensions/communities-advanced.js +430 -0
  24. package/lib/Extensions/community.js +94 -0
  25. package/lib/Extensions/groups-advanced.js +343 -0
  26. package/lib/Extensions/index.js +30 -0
  27. package/lib/Extensions/messages-recv-advanced.js +1690 -0
  28. package/lib/Extensions/messages-send-advanced.js +622 -0
  29. package/lib/Extensions/messages-send.js +1380 -0
  30. package/lib/Extensions/newsletter-advanced.js +228 -0
  31. package/lib/Extensions/newsletter.js +72 -0
  32. package/lib/Extensions/socket.js +389 -0
  33. package/lib/Modded/message_builder.js +2084 -4
  34. package/lib/Signal/Group/ciphertext-message.js +54 -0
  35. package/lib/Signal/Group/group-session-builder.js +124 -0
  36. package/lib/Signal/Group/group_cipher.js +216 -0
  37. package/lib/Signal/Group/index.js +124 -0
  38. package/lib/Signal/Group/keyhelper.js +108 -0
  39. package/lib/Signal/Group/sender-chain-key.js +83 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
  41. package/lib/Signal/Group/sender-key-message.js +166 -0
  42. package/lib/Signal/Group/sender-key-name.js +130 -0
  43. package/lib/Signal/Group/sender-key-record.js +113 -0
  44. package/lib/Signal/Group/sender-key-state.js +208 -0
  45. package/lib/Signal/Group/sender-message-key.js +82 -0
  46. package/lib/Signal/libsignal.js +935 -0
  47. package/lib/Signal/lid-mapping.js +545 -1
  48. package/lib/Socket/Client/index.js +60 -0
  49. package/lib/Socket/Client/types.js +51 -0
  50. package/lib/Socket/Client/websocket.js +152 -0
  51. package/lib/Socket/business.js +831 -0
  52. package/lib/Socket/chats.js +2535 -49
  53. package/lib/Socket/communities.js +450 -1
  54. package/lib/Socket/community.js +1022 -0
  55. package/lib/Socket/dugong.js +1 -1
  56. package/lib/Socket/groups.js +747 -0
  57. package/lib/Socket/index.js +60 -2
  58. package/lib/Socket/messages-recv.js +3450 -5
  59. package/lib/Socket/messages-send.js +3123 -0
  60. package/lib/Socket/mex.js +126 -1
  61. package/lib/Socket/newsletter.js +465 -0
  62. package/lib/Socket/socket.js +2217 -1
  63. package/lib/Store/index.js +79 -0
  64. package/lib/Store/make-cache-manager-store.js +186 -0
  65. package/lib/Store/make-in-memory-store.js +878 -0
  66. package/lib/Store/make-ordered-dictionary.js +187 -0
  67. package/lib/Store/object-repository.js +78 -0
  68. package/lib/Types/Auth.js +25 -0
  69. package/lib/Types/Bussines.js +25 -1
  70. package/lib/Types/Call.js +25 -0
  71. package/lib/Types/Chat.js +39 -0
  72. package/lib/Types/Contact.js +25 -0
  73. package/lib/Types/Events.js +25 -0
  74. package/lib/Types/GroupMetadata.js +25 -0
  75. package/lib/Types/Label.js +76 -0
  76. package/lib/Types/LabelAssociation.js +40 -0
  77. package/lib/Types/Message.js +57 -0
  78. package/lib/Types/Mex.js +56 -1
  79. package/lib/Types/MexUpdates.js +46 -0
  80. package/lib/Types/Newsletter.js +56 -0
  81. package/lib/Types/Product.js +25 -0
  82. package/lib/Types/RichType.js +23 -0
  83. package/lib/Types/Signal.js +25 -0
  84. package/lib/Types/Socket.js +25 -0
  85. package/lib/Types/State.js +92 -0
  86. package/lib/Types/USync.js +25 -0
  87. package/lib/Types/index.js +133 -0
  88. package/lib/Utils/auth-utils.js +703 -0
  89. package/lib/Utils/automation-tools.js +51 -16
  90. package/lib/Utils/baileys-event-stream.js +146 -0
  91. package/lib/Utils/browser-utils.js +95 -0
  92. package/lib/Utils/business.js +525 -0
  93. package/lib/Utils/chat-utils.js +1861 -0
  94. package/lib/Utils/companion-reg-client-utils.js +55 -1
  95. package/lib/Utils/crypto.js +355 -0
  96. package/lib/Utils/decode-wa-message.js +709 -0
  97. package/lib/Utils/event-buffer.js +1323 -8
  98. package/lib/Utils/generics.js +945 -1
  99. package/lib/Utils/history.js +266 -0
  100. package/lib/Utils/identity-change-handler.js +62 -1
  101. package/lib/Utils/index.js +114 -0
  102. package/lib/Utils/link-preview.js +179 -0
  103. package/lib/Utils/logger.js +42 -0
  104. package/lib/Utils/lt-hash.js +73 -0
  105. package/lib/Utils/make-mutex.js +104 -0
  106. package/lib/Utils/message-inspector.js +110 -0
  107. package/lib/Utils/message-retry-manager.js +507 -2
  108. package/lib/Utils/messages-media.js +1931 -1
  109. package/lib/Utils/messages.js +3748 -0
  110. package/lib/Utils/noise-handler.js +423 -0
  111. package/lib/Utils/offline-node-processor.js +53 -1
  112. package/lib/Utils/pre-key-manager.js +255 -1
  113. package/lib/Utils/process-message.js +1592 -0
  114. package/lib/Utils/reporting-utils.js +272 -1
  115. package/lib/Utils/rich-message-utils.js +377 -0
  116. package/lib/Utils/rich-messages.js +1 -1
  117. package/lib/Utils/signal.js +437 -0
  118. package/lib/Utils/stanza-ack.js +51 -1
  119. package/lib/Utils/status-refresh.js +37 -0
  120. package/lib/Utils/status-tools.js +4 -2
  121. package/lib/Utils/sync-action-utils.js +63 -1
  122. package/lib/Utils/tc-token-utils.js +185 -1
  123. package/lib/Utils/terminal-banner.js +31 -0
  124. package/lib/Utils/use-multi-file-auth-state.js +271 -0
  125. package/lib/Utils/use-single-file-auth-state.js +108 -0
  126. package/lib/Utils/use-sqlite-auth-state.js +142 -0
  127. package/lib/Utils/validate-connection.js +497 -1
  128. package/lib/Utils/view-once-compat.js +13 -5
  129. package/lib/VoIP/audio-feeder.js +150 -0
  130. package/lib/VoIP/index.js +289 -0
  131. package/lib/VoIP/relay-transport.js +608 -0
  132. package/lib/VoIP/signaling.js +583 -0
  133. package/lib/VoIP/types.js +30 -0
  134. package/lib/VoIP/wasm-engine.js +1261 -2
  135. package/lib/VoIP/worker-bootstrap.js +1090 -2
  136. package/lib/WABinary/constants.js +2805 -0
  137. package/lib/WABinary/decode.js +649 -2
  138. package/lib/WABinary/encode.js +564 -2
  139. package/lib/WABinary/generic-utils.js +401 -0
  140. package/lib/WABinary/index.js +82 -0
  141. package/lib/WABinary/jid-utils.js +290 -0
  142. package/lib/WABinary/types.js +25 -0
  143. package/lib/WAM/BinaryInfo.js +50 -0
  144. package/lib/WAM/constants.js +45747 -0
  145. package/lib/WAM/encode.js +393 -0
  146. package/lib/WAM/index.js +78 -0
  147. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
  148. package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
  149. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
  150. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
  151. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
  152. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
  153. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
  154. package/lib/WAUSync/Protocols/index.js +83 -0
  155. package/lib/WAUSync/USyncQuery.js +241 -2
  156. package/lib/WAUSync/USyncUser.js +86 -0
  157. package/lib/WAUSync/index.js +78 -0
  158. package/lib/assets/wasm/loader.js +1875 -1
  159. package/lib/assets/wasm/worker-modules.js +11047 -1
  160. package/lib/index.d.ts +126 -0
  161. package/lib/index.js +53 -21
  162. package/lib/index.mjs +437 -0
  163. package/licenses/upstream-MIT.txt +22 -0
  164. package/maintenance/api-coverage.json +1642 -0
  165. package/maintenance/archivos-sha256.json +207 -0
  166. package/maintenance/consumer-validation.log +3 -0
  167. package/maintenance/dependency-audit.json +4 -4
  168. package/maintenance/extension-inventory.json +57 -0
  169. package/maintenance/protocol-update.json +1101 -0
  170. package/maintenance/protocol-wire-audit.json +4 -0
  171. package/maintenance/reference-socket-surface.json +209 -0
  172. package/maintenance/resumen-validacion.json +50 -0
  173. package/maintenance/validation.log +2725 -0
  174. package/maintenance/verification.json +566 -0
  175. package/package.json +107 -9
  176. package/scripts/check-imports.cjs +10 -0
  177. package/scripts/check-package.cjs +40 -0
  178. package/scripts/check-syntax.cjs +1 -1
  179. package/scripts/generate-protobuf.cjs +6 -1
  180. package/scripts/generate-public-types.cjs +9 -0
  181. package/scripts/kage-base64-fix.cjs +45 -0
  182. package/scripts/maintenance.cjs +10 -0
  183. package/test/advanced.test.cjs +24 -0
  184. package/test/base64-fix.test.cjs +49 -0
  185. package/test/maintenance.test.cjs +1 -1
  186. package/test/npm-publication.test.cjs +141 -0
  187. package/test/recepcion-reparada.test.cjs +98 -0
  188. package/test/resilience-binary.test.cjs +69 -0
  189. package/test/resilience-transport.test.cjs +34 -0
  190. package/test/types.test.ts +5 -0
  191. package/test/upgrade.test.cjs +104 -0
  192. package/tsconfig.json +20 -0
  193. package/WAProto/p.html +0 -1
  194. package/lib/KageExtra/Modded/message_builder.js +0 -2330
  195. package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
  196. package/lib/KageExtra/VoIP/index.js +0 -282
  197. package/lib/KageExtra/VoIP/relay-transport.js +0 -559
  198. package/lib/KageExtra/VoIP/signaling.js +0 -603
  199. package/lib/KageExtra/VoIP/types.js +0 -17
  200. package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
  201. package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
  202. package/lib/KageExtra/assets/wasm/loader.js +0 -5
  203. package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
  204. package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
  205. package/lib/KageExtra/index.js +0 -3
  206. package/lib/KageExtra/package.json +0 -1
  207. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  209. package/maintenance/revision-full-check.txt +0 -1097
  210. package/maintenance/revision-library-tests.tap +0 -1088
  211. package/maintenance/revision-protobuf.txt +0 -5
  212. package/maintenance/revision-syntax.txt +0 -5
  213. package/maintenance/schema-coverage.json +0 -23
  214. package/maintenance/schema-merge.json +0 -30
  215. package/maintenance/validation-node20.txt +0 -191
  216. package/maintenance/validation-node22.txt +0 -237
@@ -0,0 +1,1106 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.attachAdvanced = exports.buildProfilePictureQueryContent = void 0;
7
+ const index_js_1 = require("../../WAProto/index.js");
8
+ const index_js_2 = require("../Addon/index.js");
9
+ const index_js_3 = require("../Defaults/index.js");
10
+ const index_js_4 = require("../Types/index.js");
11
+ const State_js_1 = require("../Types/State.js");
12
+ const index_js_5 = require("../Utils/index.js");
13
+ const make_mutex_js_1 = require("../Utils/make-mutex.js");
14
+ const process_message_js_1 = __importDefault(require("../Utils/process-message.js"));
15
+ const tc_token_utils_js_1 = require("../Utils/tc-token-utils.js");
16
+ const index_js_6 = require("../WABinary/index.js");
17
+ const index_js_7 = require("../WAUSync/index.js");
18
+ const buildProfilePictureQueryContent = (type, tcTokenContent) => {
19
+ const picture = { tag: 'picture', attrs: { type, query: 'url' } };
20
+ if (tcTokenContent?.length) {
21
+ picture.content = tcTokenContent;
22
+ }
23
+ return [picture];
24
+ };
25
+ exports.buildProfilePictureQueryContent = buildProfilePictureQueryContent;
26
+ const attachAdvanced = (base, config) => {
27
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
28
+ const sock = base;
29
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
30
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
31
+ let privacySettings;
32
+ /** Server-assigned AB props for protocol behavior. */
33
+ const serverProps = {
34
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
35
+ privacyTokenOn1to1: true,
36
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
37
+ profilePicPrivacyToken: true,
38
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
39
+ lidTrustedTokenIssueToLid: false
40
+ };
41
+ let syncState = State_js_1.SyncState.Connecting;
42
+ /** this mutex ensures that messages are processed in order */
43
+ const messageMutex = (0, make_mutex_js_1.makeMutex)();
44
+ /** this mutex ensures that receipts are processed in order */
45
+ const receiptMutex = (0, make_mutex_js_1.makeMutex)();
46
+ /** this mutex ensures that app state patches are processed in order */
47
+ const appStatePatchMutex = (0, make_mutex_js_1.makeMutex)();
48
+ /** this mutex ensures that notifications are processed in order */
49
+ const notificationMutex = (0, make_mutex_js_1.makeMutex)();
50
+ // Timeout for AwaitingInitialSync state
51
+ let awaitingSyncTimeout;
52
+ // In-memory history sync completion tracking (resets on reconnection)
53
+ const historySyncStatus = {
54
+ initialBootstrapComplete: false,
55
+ recentSyncComplete: false
56
+ };
57
+ let historySyncPausedTimeout;
58
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
59
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
60
+ const blockedCollections = new Set();
61
+ const placeholderResendCache = config.placeholderResendCache ||
62
+ (0, index_js_2.createCache)({
63
+ ttl: index_js_3.DEFAULT_CACHE_TTLS.MSG_RETRY // 1 hour
64
+ });
65
+ /** helper function to fetch the given app state sync key */
66
+ const getAppStateSyncKey = async (keyId) => {
67
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
68
+ return key;
69
+ };
70
+ const fetchPrivacySettings = async (force = false) => {
71
+ if (!privacySettings || force) {
72
+ const { content } = await query({
73
+ tag: 'iq',
74
+ attrs: {
75
+ xmlns: 'privacy',
76
+ to: index_js_6.S_WHATSAPP_NET,
77
+ type: 'get'
78
+ },
79
+ content: [{ tag: 'privacy', attrs: {} }]
80
+ });
81
+ privacySettings = (0, index_js_6.reduceBinaryNodeToDictionary)(content?.[0], 'category');
82
+ }
83
+ return privacySettings;
84
+ };
85
+ /** helper function to run a privacy IQ query */
86
+ const privacyQuery = async (name, value) => {
87
+ await query({
88
+ tag: 'iq',
89
+ attrs: {
90
+ xmlns: 'privacy',
91
+ to: index_js_6.S_WHATSAPP_NET,
92
+ type: 'set'
93
+ },
94
+ content: [
95
+ {
96
+ tag: 'privacy',
97
+ attrs: {},
98
+ content: [
99
+ {
100
+ tag: 'category',
101
+ attrs: { name, value }
102
+ }
103
+ ]
104
+ }
105
+ ]
106
+ });
107
+ };
108
+ const updateMessagesPrivacy = async (value) => {
109
+ await privacyQuery('messages', value);
110
+ };
111
+ const updateCallPrivacy = async (value) => {
112
+ await privacyQuery('calladd', value);
113
+ };
114
+ const updateLastSeenPrivacy = async (value) => {
115
+ await privacyQuery('last', value);
116
+ };
117
+ const updateOnlinePrivacy = async (value) => {
118
+ await privacyQuery('online', value);
119
+ };
120
+ const updateProfilePicturePrivacy = async (value) => {
121
+ await privacyQuery('profile', value);
122
+ };
123
+ const updateStatusPrivacy = async (value) => {
124
+ await privacyQuery('status', value);
125
+ };
126
+ const updateReadReceiptsPrivacy = async (value) => {
127
+ await privacyQuery('readreceipts', value);
128
+ };
129
+ const updateGroupsAddPrivacy = async (value) => {
130
+ await privacyQuery('groupadd', value);
131
+ };
132
+ const updateDefaultDisappearingMode = async (duration) => {
133
+ await query({
134
+ tag: 'iq',
135
+ attrs: {
136
+ xmlns: 'disappearing_mode',
137
+ to: index_js_6.S_WHATSAPP_NET,
138
+ type: 'set'
139
+ },
140
+ content: [
141
+ {
142
+ tag: 'disappearing_mode',
143
+ attrs: {
144
+ duration: duration.toString()
145
+ }
146
+ }
147
+ ]
148
+ });
149
+ };
150
+ const getBotListV2 = async () => {
151
+ const resp = await query({
152
+ tag: 'iq',
153
+ attrs: {
154
+ xmlns: 'bot',
155
+ to: index_js_6.S_WHATSAPP_NET,
156
+ type: 'get'
157
+ },
158
+ content: [
159
+ {
160
+ tag: 'bot',
161
+ attrs: {
162
+ v: '2'
163
+ }
164
+ }
165
+ ]
166
+ });
167
+ const botNode = (0, index_js_6.getBinaryNodeChild)(resp, 'bot');
168
+ const botList = [];
169
+ for (const section of (0, index_js_6.getBinaryNodeChildren)(botNode, 'section')) {
170
+ if (section.attrs.type === 'all') {
171
+ for (const bot of (0, index_js_6.getBinaryNodeChildren)(section, 'bot')) {
172
+ botList.push({
173
+ jid: bot.attrs.jid,
174
+ personaId: bot.attrs['persona_id']
175
+ });
176
+ }
177
+ }
178
+ }
179
+ return botList;
180
+ };
181
+ const fetchStatus = async (...jids) => {
182
+ const usyncQuery = new index_js_7.USyncQuery().withStatusProtocol();
183
+ for (const jid of jids) {
184
+ usyncQuery.withUser(new index_js_7.USyncUser().withId(jid));
185
+ }
186
+ const result = await sock.executeUSyncQuery(usyncQuery);
187
+ if (result) {
188
+ return result.list;
189
+ }
190
+ };
191
+ const fetchDisappearingDuration = async (...jids) => {
192
+ const usyncQuery = new index_js_7.USyncQuery().withDisappearingModeProtocol();
193
+ for (const jid of jids) {
194
+ usyncQuery.withUser(new index_js_7.USyncUser().withId(jid));
195
+ }
196
+ const result = await sock.executeUSyncQuery(usyncQuery);
197
+ if (result) {
198
+ return result.list;
199
+ }
200
+ };
201
+ // Lia@Note 06-02-26 --- Quick helper only. This function exists solely for faster lookup with caching.
202
+ const findUserId = async (pnLid) => {
203
+ const normalizedJid = (0, index_js_6.jidNormalizedUser)(pnLid);
204
+ const userId = {
205
+ lid: undefined,
206
+ phoneNumber: undefined
207
+ };
208
+ if ((0, index_js_6.isPnUser)(normalizedJid) || (0, index_js_6.isHostedPnUser)(normalizedJid)) {
209
+ userId.phoneNumber = normalizedJid;
210
+ userId.lid = (0, index_js_6.jidNormalizedUser)((await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid);
211
+ }
212
+ else if ((0, index_js_6.isLidUser)(normalizedJid) || (0, index_js_6.isHostedLidUser)(normalizedJid)) {
213
+ userId.lid = normalizedJid;
214
+ userId.phoneNumber = (0, index_js_6.jidNormalizedUser)((await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn);
215
+ }
216
+ else {
217
+ throw new index_js_2.HttpError('Invalid id input to find user ids', { statusCode: 400 });
218
+ }
219
+ return userId;
220
+ };
221
+ /** update the profile picture for yourself or a group */
222
+ const updateProfilePicture = async (jid, content, dimensions) => {
223
+ let targetJid;
224
+ if (!jid) {
225
+ throw new index_js_2.HttpError('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
226
+ }
227
+ if ((0, index_js_6.jidNormalizedUser)(jid) !== (0, index_js_6.jidNormalizedUser)(authState.creds.me.id)) {
228
+ targetJid = (0, index_js_6.jidNormalizedUser)(jid); // in case it is someone other than us
229
+ }
230
+ else {
231
+ targetJid = undefined;
232
+ }
233
+ const { img } = await (0, index_js_5.generateProfilePicture)(content, dimensions);
234
+ await query({
235
+ tag: 'iq',
236
+ attrs: {
237
+ to: index_js_6.S_WHATSAPP_NET,
238
+ type: 'set',
239
+ xmlns: 'w:profile:picture',
240
+ ...(targetJid ? { target: targetJid } : {})
241
+ },
242
+ content: [
243
+ {
244
+ tag: 'picture',
245
+ attrs: { type: 'image' },
246
+ content: img
247
+ }
248
+ ]
249
+ });
250
+ };
251
+ /** remove the profile picture for yourself or a group */
252
+ const removeProfilePicture = async (jid) => {
253
+ let targetJid;
254
+ if (!jid) {
255
+ throw new index_js_2.HttpError('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
256
+ }
257
+ if ((0, index_js_6.jidNormalizedUser)(jid) !== (0, index_js_6.jidNormalizedUser)(authState.creds.me.id)) {
258
+ targetJid = (0, index_js_6.jidNormalizedUser)(jid); // in case it is someone other than us
259
+ }
260
+ else {
261
+ targetJid = undefined;
262
+ }
263
+ await query({
264
+ tag: 'iq',
265
+ attrs: {
266
+ to: index_js_6.S_WHATSAPP_NET,
267
+ type: 'set',
268
+ xmlns: 'w:profile:picture',
269
+ ...(targetJid ? { target: targetJid } : {})
270
+ }
271
+ });
272
+ };
273
+ /** update the profile status for yourself */
274
+ const updateProfileStatus = async (status) => {
275
+ await query({
276
+ tag: 'iq',
277
+ attrs: {
278
+ to: index_js_6.S_WHATSAPP_NET,
279
+ type: 'set',
280
+ xmlns: 'status'
281
+ },
282
+ content: [
283
+ {
284
+ tag: 'status',
285
+ attrs: {},
286
+ content: Buffer.from(status, 'utf-8')
287
+ }
288
+ ]
289
+ });
290
+ };
291
+ const updateProfileName = async (name) => {
292
+ await chatModify({ pushNameSetting: name }, '');
293
+ };
294
+ const fetchBlocklist = async () => {
295
+ const result = await query({
296
+ tag: 'iq',
297
+ attrs: {
298
+ xmlns: 'blocklist',
299
+ to: index_js_6.S_WHATSAPP_NET,
300
+ type: 'get'
301
+ }
302
+ });
303
+ const listNode = (0, index_js_6.getBinaryNodeChild)(result, 'list');
304
+ return (0, index_js_6.getBinaryNodeChildren)(listNode, 'item').map(n => n.attrs.jid);
305
+ };
306
+ const updateBlockStatus = async (jid, action) => {
307
+ const normalizedJid = (0, index_js_6.jidNormalizedUser)(jid);
308
+ let lid;
309
+ let pn_jid;
310
+ if ((0, index_js_6.isLidUser)(normalizedJid) || (0, index_js_6.isHostedLidUser)(normalizedJid)) {
311
+ lid = normalizedJid;
312
+ if (action === 'block') {
313
+ const pn = (await findUserId(normalizedJid)).phoneNumber;
314
+ if (!pn) {
315
+ throw new index_js_2.HttpError(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
316
+ }
317
+ pn_jid = (0, index_js_6.jidNormalizedUser)(pn);
318
+ }
319
+ }
320
+ else if ((0, index_js_6.isPnUser)(normalizedJid) || (0, index_js_6.isHostedPnUser)(normalizedJid)) {
321
+ const mapped = (await findUserId(normalizedJid)).lid;
322
+ if (!mapped) {
323
+ throw new index_js_2.HttpError(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
324
+ }
325
+ lid = mapped;
326
+ if (action === 'block') {
327
+ pn_jid = (0, index_js_6.jidNormalizedUser)(normalizedJid);
328
+ }
329
+ }
330
+ else {
331
+ throw new index_js_2.HttpError(`Invalid jid: ${jid}`, { statusCode: 400 });
332
+ }
333
+ const itemAttrs = {
334
+ action,
335
+ jid: lid
336
+ };
337
+ if (action === 'block') {
338
+ if (!pn_jid) {
339
+ throw new index_js_2.HttpError(`pn_jid required for block: ${jid}`, { statusCode: 400 });
340
+ }
341
+ itemAttrs.pn_jid = pn_jid;
342
+ }
343
+ await query({
344
+ tag: 'iq',
345
+ attrs: {
346
+ xmlns: 'blocklist',
347
+ to: index_js_6.S_WHATSAPP_NET,
348
+ type: 'set'
349
+ },
350
+ content: [
351
+ {
352
+ tag: 'item',
353
+ attrs: itemAttrs
354
+ }
355
+ ]
356
+ });
357
+ };
358
+ const getBusinessProfile = async (jid) => {
359
+ const results = await query({
360
+ tag: 'iq',
361
+ attrs: {
362
+ to: 's.whatsapp.net',
363
+ xmlns: 'w:biz',
364
+ type: 'get'
365
+ },
366
+ content: [
367
+ {
368
+ tag: 'business_profile',
369
+ attrs: { v: '244' },
370
+ content: [
371
+ {
372
+ tag: 'profile',
373
+ attrs: { jid }
374
+ }
375
+ ]
376
+ }
377
+ ]
378
+ });
379
+ const profileNode = (0, index_js_6.getBinaryNodeChild)(results, 'business_profile');
380
+ const profiles = (0, index_js_6.getBinaryNodeChild)(profileNode, 'profile');
381
+ if (profiles) {
382
+ const address = (0, index_js_6.getBinaryNodeChild)(profiles, 'address');
383
+ const description = (0, index_js_6.getBinaryNodeChild)(profiles, 'description');
384
+ const website = (0, index_js_6.getBinaryNodeChild)(profiles, 'website');
385
+ const email = (0, index_js_6.getBinaryNodeChild)(profiles, 'email');
386
+ const category = (0, index_js_6.getBinaryNodeChild)((0, index_js_6.getBinaryNodeChild)(profiles, 'categories'), 'category');
387
+ const businessHours = (0, index_js_6.getBinaryNodeChild)(profiles, 'business_hours');
388
+ const businessHoursConfig = businessHours
389
+ ? (0, index_js_6.getBinaryNodeChildren)(businessHours, 'business_hours_config')
390
+ : undefined;
391
+ const websiteStr = website?.content?.toString();
392
+ return {
393
+ wid: profiles.attrs?.jid,
394
+ address: address?.content?.toString(),
395
+ description: description?.content?.toString() || '',
396
+ website: websiteStr ? [websiteStr] : [],
397
+ email: email?.content?.toString(),
398
+ category: category?.content?.toString(),
399
+ business_hours: {
400
+ timezone: businessHours?.attrs?.timezone,
401
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
402
+ }
403
+ };
404
+ }
405
+ };
406
+ const cleanDirtyBits = async (type, fromTimestamp) => {
407
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
408
+ await sendNode({
409
+ tag: 'iq',
410
+ attrs: {
411
+ to: index_js_6.S_WHATSAPP_NET,
412
+ type: 'set',
413
+ xmlns: 'urn:xmpp:whatsapp:dirty',
414
+ id: generateMessageTag()
415
+ },
416
+ content: [
417
+ {
418
+ tag: 'clean',
419
+ attrs: {
420
+ type,
421
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
422
+ }
423
+ }
424
+ ]
425
+ });
426
+ };
427
+ const newAppStateChunkHandler = (isInitialSync) => {
428
+ return {
429
+ onMutation(mutation) {
430
+ (0, index_js_5.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
431
+ }
432
+ };
433
+ };
434
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
435
+ const appStateSyncKeyCache = new Map();
436
+ const getCachedAppStateSyncKey = async (keyId) => {
437
+ if (appStateSyncKeyCache.has(keyId)) {
438
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
439
+ }
440
+ const key = await getAppStateSyncKey(keyId);
441
+ appStateSyncKeyCache.set(keyId, key ?? null);
442
+ return key;
443
+ };
444
+ // we use this to determine which events to fire
445
+ // otherwise when we resync from scratch -- all notifications will fire
446
+ const initialVersionMap = {};
447
+ const globalMutationMap = {};
448
+ await authState.keys.transaction(async () => {
449
+ const collectionsToHandle = new Set(collections);
450
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
451
+ const attemptsMap = {};
452
+ // collections that failed and need a full snapshot on retry
453
+ // mirrors WA Web's ErrorFatal -> force snapshot behavior
454
+ const forceSnapshotCollections = new Set();
455
+ // keep executing till all collections are done
456
+ // sometimes a single patch request will not return all the patches (God knows why)
457
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
458
+ while (collectionsToHandle.size) {
459
+ const states = {};
460
+ const nodes = [];
461
+ for (const name of collectionsToHandle) {
462
+ const result = await authState.keys.get('app-state-sync-version', [name]);
463
+ let state = result[name];
464
+ if (state) {
465
+ state = (0, index_js_5.ensureLTHashStateVersion)(state);
466
+ if (typeof initialVersionMap[name] === 'undefined') {
467
+ initialVersionMap[name] = state.version;
468
+ }
469
+ }
470
+ else {
471
+ state = (0, index_js_5.newLTHashState)();
472
+ }
473
+ states[name] = state;
474
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
475
+ if (shouldForceSnapshot) {
476
+ forceSnapshotCollections.delete(name);
477
+ }
478
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
479
+ nodes.push({
480
+ tag: 'collection',
481
+ attrs: {
482
+ name,
483
+ version: state.version.toString(),
484
+ // return snapshot if syncing from scratch or forcing after a failed attempt
485
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
486
+ }
487
+ });
488
+ }
489
+ const result = await query({
490
+ tag: 'iq',
491
+ attrs: {
492
+ to: index_js_6.S_WHATSAPP_NET,
493
+ xmlns: 'w:sync:app:state',
494
+ type: 'set'
495
+ },
496
+ content: [
497
+ {
498
+ tag: 'sync',
499
+ attrs: {},
500
+ content: nodes
501
+ }
502
+ ]
503
+ });
504
+ // extract from binary node
505
+ const decoded = await (0, index_js_5.extractSyncdPatches)(result, config?.options);
506
+ for (const key in decoded) {
507
+ const name = key;
508
+ const { patches, hasMorePatches, snapshot } = decoded[name];
509
+ try {
510
+ if (snapshot) {
511
+ const { state: newState, mutationMap } = await (0, index_js_5.decodeSyncdSnapshot)(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
512
+ states[name] = newState;
513
+ Object.assign(globalMutationMap, mutationMap);
514
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
515
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
516
+ }
517
+ // only process if there are syncd patches
518
+ if (patches.length) {
519
+ const { state: newState, mutationMap } = await (0, index_js_5.decodePatches)(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
520
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
521
+ logger.info(`synced ${name} to v${newState.version}`);
522
+ initialVersionMap[name] = newState.version;
523
+ Object.assign(globalMutationMap, mutationMap);
524
+ }
525
+ if (hasMorePatches) {
526
+ logger.info(`${name} has more patches...`);
527
+ }
528
+ else {
529
+ // collection is done with sync
530
+ collectionsToHandle.delete(name);
531
+ }
532
+ }
533
+ catch (error) {
534
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
535
+ const logData = {
536
+ name,
537
+ attempt: attemptsMap[name],
538
+ version: states[name].version,
539
+ statusCode: error.output?.statusCode,
540
+ errorType: error.name,
541
+ error: error.stack
542
+ };
543
+ if ((0, index_js_5.isMissingKeyError)(error) && attemptsMap[name] >= index_js_5.MAX_SYNC_ATTEMPTS) {
544
+ // WA Web treats missing keys as "Blocked" — park the collection
545
+ // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
546
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
547
+ blockedCollections.add(name);
548
+ collectionsToHandle.delete(name);
549
+ }
550
+ else if ((0, index_js_5.isMissingKeyError)(error)) {
551
+ // Retry with a snapshot which may use a different key.
552
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
553
+ forceSnapshotCollections.add(name);
554
+ }
555
+ else if ((0, index_js_5.isAppStateSyncIrrecoverable)(error, attemptsMap[name])) {
556
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
557
+ collectionsToHandle.delete(name);
558
+ }
559
+ else {
560
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
561
+ // force a full snapshot on retry to recover from
562
+ // corrupted local state (e.g. LTHash MAC mismatch)
563
+ forceSnapshotCollections.add(name);
564
+ }
565
+ }
566
+ }
567
+ }
568
+ }, authState?.creds?.me?.id || 'resync-app-state');
569
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
570
+ for (const key in globalMutationMap) {
571
+ onMutation(globalMutationMap[key]);
572
+ }
573
+ });
574
+ /**
575
+ * fetch the profile picture of a user/group
576
+ * type = "preview" for a low res picture
577
+ * type = "image for the high res picture"
578
+ */
579
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = true) => {
580
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
581
+ // and never for own profile pic (Chat model for self has no tcToken).
582
+ // Including tctoken for own JID causes the server to never respond.
583
+ const normalizedJid = (0, index_js_6.jidNormalizedUser)(jid);
584
+ const isUserJid = (0, index_js_6.isPnUser)(normalizedJid) || (0, index_js_6.isLidUser)(normalizedJid);
585
+ const me = authState.creds.me;
586
+ const isSelf = me && (normalizedJid === (0, index_js_6.jidNormalizedUser)(me.id) || (me.lid && normalizedJid === (0, index_js_6.jidNormalizedUser)(me.lid)));
587
+ let tcTokenContent;
588
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
589
+ tcTokenContent = await (0, tc_token_utils_js_1.buildTcTokenFromJid)({
590
+ authState,
591
+ jid: normalizedJid,
592
+ getLIDForPN
593
+ });
594
+ }
595
+ jid = (0, index_js_6.jidNormalizedUser)(jid);
596
+ const result = await query({
597
+ tag: 'iq',
598
+ attrs: {
599
+ target: jid,
600
+ to: index_js_6.S_WHATSAPP_NET,
601
+ type: 'get',
602
+ xmlns: 'w:profile:picture'
603
+ },
604
+ content: (0, exports.buildProfilePictureQueryContent)(type, tcTokenContent)
605
+ }, timeoutMs);
606
+ const child = (0, index_js_6.getBinaryNodeChild)(result, 'picture');
607
+ return child?.attrs?.url;
608
+ };
609
+ const createCallLink = async (type, event, timeoutMs) => {
610
+ const result = await query({
611
+ tag: 'call',
612
+ attrs: {
613
+ id: generateMessageTag(),
614
+ to: '@call'
615
+ },
616
+ content: [
617
+ {
618
+ tag: 'link_create',
619
+ attrs: { media: type },
620
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
621
+ }
622
+ ]
623
+ }, timeoutMs);
624
+ const child = (0, index_js_6.getBinaryNodeChild)(result, 'link_create');
625
+ return child?.attrs?.token;
626
+ };
627
+ const sendPresenceUpdate = async (type, toJid) => {
628
+ const me = authState.creds.me;
629
+ const isAvailableType = type === 'available';
630
+ if (isAvailableType || type === 'unavailable') {
631
+ if (!me.name) {
632
+ logger.warn('no name present, ignoring presence update request...');
633
+ return;
634
+ }
635
+ ev.emit('connection.update', { isOnline: isAvailableType });
636
+ if (isAvailableType) {
637
+ void sendUnifiedSession();
638
+ }
639
+ await sendNode({
640
+ tag: 'presence',
641
+ attrs: {
642
+ name: me.name.replace(/@/g, ''),
643
+ type
644
+ }
645
+ });
646
+ }
647
+ else {
648
+ const { server } = (0, index_js_6.jidDecode)(toJid);
649
+ const isLid = server === 'lid';
650
+ await sendNode({
651
+ tag: 'chatstate',
652
+ attrs: {
653
+ from: isLid ? me.lid : me.id,
654
+ to: toJid
655
+ },
656
+ content: [
657
+ {
658
+ tag: type === 'recording' ? 'composing' : type,
659
+ attrs: type === 'recording' ? { media: 'audio' } : {}
660
+ }
661
+ ]
662
+ });
663
+ }
664
+ };
665
+ /**
666
+ * @param toJid the jid to subscribe to
667
+ * @param tcToken token for subscription, use if present
668
+ */
669
+ const presenceSubscribe = async (toJid) => {
670
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
671
+ const normalizedToJid = (0, index_js_6.jidNormalizedUser)(toJid);
672
+ const isUserJid = (0, index_js_6.isPnUser)(normalizedToJid) || (0, index_js_6.isLidUser)(normalizedToJid);
673
+ const tcTokenContent = isUserJid
674
+ ? await (0, tc_token_utils_js_1.buildTcTokenFromJid)({ authState, jid: normalizedToJid, getLIDForPN })
675
+ : undefined;
676
+ return sendNode({
677
+ tag: 'presence',
678
+ attrs: {
679
+ to: toJid,
680
+ id: generateMessageTag(),
681
+ type: 'subscribe'
682
+ },
683
+ content: tcTokenContent
684
+ });
685
+ };
686
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
687
+ let presence;
688
+ const jid = attrs.from;
689
+ const participant = attrs.participant || attrs.from;
690
+ if (shouldIgnoreJid(jid) && jid !== index_js_6.S_WHATSAPP_NET) {
691
+ return;
692
+ }
693
+ if (tag === 'presence') {
694
+ presence = {
695
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
696
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
697
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
698
+ };
699
+ }
700
+ else if (Array.isArray(content)) {
701
+ const [firstChild] = content;
702
+ let type = firstChild.tag;
703
+ if (type === 'paused') {
704
+ type = 'available';
705
+ }
706
+ if (firstChild.attrs?.media === 'audio') {
707
+ type = 'recording';
708
+ }
709
+ presence = { lastKnownPresence: type };
710
+ }
711
+ else {
712
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
713
+ }
714
+ if (presence) {
715
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
716
+ }
717
+ };
718
+ const appPatch = async (patchCreate) => {
719
+ const name = patchCreate.type;
720
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
721
+ if (!myAppStateKeyId) {
722
+ throw new index_js_2.HttpError('App state key not present!', { statusCode: 400 });
723
+ }
724
+ let initial;
725
+ let encodeResult;
726
+ await appStatePatchMutex.mutex(async () => {
727
+ await authState.keys.transaction(async () => {
728
+ logger.debug({ patch: patchCreate }, 'applying app patch');
729
+ await resyncAppState([name], false);
730
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
731
+ initial = currentSyncVersion ? (0, index_js_5.ensureLTHashStateVersion)(currentSyncVersion) : (0, index_js_5.newLTHashState)();
732
+ encodeResult = await (0, index_js_5.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
733
+ const { patch, state } = encodeResult;
734
+ const node = {
735
+ tag: 'iq',
736
+ attrs: {
737
+ to: index_js_6.S_WHATSAPP_NET,
738
+ type: 'set',
739
+ xmlns: 'w:sync:app:state'
740
+ },
741
+ content: [
742
+ {
743
+ tag: 'sync',
744
+ attrs: {},
745
+ content: [
746
+ {
747
+ tag: 'collection',
748
+ attrs: {
749
+ name,
750
+ version: (state.version - 1).toString(),
751
+ return_snapshot: 'false'
752
+ },
753
+ content: [
754
+ {
755
+ tag: 'patch',
756
+ attrs: {},
757
+ content: index_js_1.proto.SyncdPatch.encode(patch).finish()
758
+ }
759
+ ]
760
+ }
761
+ ]
762
+ }
763
+ ]
764
+ };
765
+ await query(node);
766
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
767
+ }, authState?.creds?.me?.id || 'app-patch');
768
+ });
769
+ if (config.emitOwnEvents) {
770
+ const { onMutation } = newAppStateChunkHandler(false);
771
+ const { mutationMap } = await (0, index_js_5.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
772
+ for (const key in mutationMap) {
773
+ onMutation(mutationMap[key]);
774
+ }
775
+ }
776
+ };
777
+ /** fetch AB props */
778
+ const fetchProps = async () => {
779
+ const resultNode = await query({
780
+ tag: 'iq',
781
+ attrs: {
782
+ to: index_js_6.S_WHATSAPP_NET,
783
+ xmlns: 'abt',
784
+ type: 'get'
785
+ },
786
+ content: [
787
+ {
788
+ tag: 'props',
789
+ attrs: {
790
+ protocol: '1',
791
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
792
+ }
793
+ }
794
+ ]
795
+ });
796
+ const propsNode = (0, index_js_6.getBinaryNodeChild)(resultNode, 'props');
797
+ let props = {};
798
+ if (propsNode) {
799
+ if (propsNode.attrs?.hash) {
800
+ // on some clients, the hash is returning as undefined
801
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
802
+ ev.emit('creds.update', authState.creds);
803
+ }
804
+ props = (0, index_js_6.reduceBinaryNodeToDictionary)(propsNode, 'prop');
805
+ }
806
+ // Extract protocol-relevant AB props (only the ones we need)
807
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
808
+ if (privacyTokenProp !== undefined) {
809
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
810
+ }
811
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
812
+ if (profilePicProp !== undefined) {
813
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
814
+ }
815
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
816
+ if (lidIssueProp !== undefined) {
817
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
818
+ }
819
+ logger.debug({ serverProps }, 'fetched props');
820
+ return props;
821
+ };
822
+ /**
823
+ * modify a chat -- mark unread, read etc.
824
+ * lastMessages must be sorted in reverse chronologically
825
+ * requires the last messages till the last message received; required for archive & unread
826
+ */
827
+ const chatModify = (mod, jid) => {
828
+ const patch = (0, index_js_5.chatModificationToAppPatch)(mod, jid);
829
+ return appPatch(patch);
830
+ };
831
+ /**
832
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
833
+ */
834
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
835
+ return chatModify({
836
+ disableLinkPreviews: { isPreviewsDisabled }
837
+ }, '');
838
+ };
839
+ /**
840
+ * Star or Unstar a message
841
+ */
842
+ const star = (jid, messages, star) => {
843
+ return chatModify({
844
+ star: {
845
+ messages,
846
+ star
847
+ }
848
+ }, jid);
849
+ };
850
+ /**
851
+ * Add or Edit Contact
852
+ */
853
+ const addOrEditContact = (jid, contact) => {
854
+ return chatModify({
855
+ contact
856
+ }, jid);
857
+ };
858
+ /**
859
+ * Remove Contact
860
+ */
861
+ const removeContact = (jid) => {
862
+ return chatModify({
863
+ contact: null
864
+ }, jid);
865
+ };
866
+ /**
867
+ * Adds label
868
+ */
869
+ const addLabel = (jid, labels) => {
870
+ return chatModify({
871
+ addLabel: {
872
+ ...labels
873
+ }
874
+ }, jid);
875
+ };
876
+ /**
877
+ * Adds label for the chats
878
+ */
879
+ const addChatLabel = (jid, labelId) => {
880
+ return chatModify({
881
+ addChatLabel: {
882
+ labelId
883
+ }
884
+ }, jid);
885
+ };
886
+ /**
887
+ * Removes label for the chat
888
+ */
889
+ const removeChatLabel = (jid, labelId) => {
890
+ return chatModify({
891
+ removeChatLabel: {
892
+ labelId
893
+ }
894
+ }, jid);
895
+ };
896
+ /**
897
+ * Adds label for the message
898
+ */
899
+ const addMessageLabel = (jid, messageId, labelId) => {
900
+ return chatModify({
901
+ addMessageLabel: {
902
+ messageId,
903
+ labelId
904
+ }
905
+ }, jid);
906
+ };
907
+ /**
908
+ * Removes label for the message
909
+ */
910
+ const removeMessageLabel = (jid, messageId, labelId) => {
911
+ return chatModify({
912
+ removeMessageLabel: {
913
+ messageId,
914
+ labelId
915
+ }
916
+ }, jid);
917
+ };
918
+ /**
919
+ * Add or Edit Quick Reply
920
+ */
921
+ const addOrEditQuickReply = (quickReply) => {
922
+ return chatModify({
923
+ quickReply
924
+ }, '');
925
+ };
926
+ /**
927
+ * Remove Quick Reply
928
+ */
929
+ const removeQuickReply = (timestamp) => {
930
+ return chatModify({
931
+ quickReply: { timestamp, deleted: true }
932
+ }, '');
933
+ };
934
+ /**
935
+ * queries need to be fired on connection open
936
+ * help ensure parity with WA Web
937
+ * */
938
+ const executeInitQueries = async () => {
939
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
940
+ };
941
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
942
+ ev.emit('messages.upsert', { messages: [msg], type });
943
+ if (!!msg.pushName) {
944
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
945
+ jid = (0, index_js_6.jidNormalizedUser)(jid);
946
+ if (!msg.key.fromMe) {
947
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
948
+ }
949
+ // update our pushname too
950
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
951
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
952
+ }
953
+ }
954
+ const historyMsg = (0, index_js_5.getHistoryMsg)(msg.message);
955
+ const shouldProcessHistoryMsg = historyMsg
956
+ ? shouldSyncHistoryMessage(historyMsg) &&
957
+ index_js_3.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
958
+ : false;
959
+ if (historyMsg && shouldProcessHistoryMsg) {
960
+ const syncType = historyMsg.syncType;
961
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
962
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
963
+ !historySyncStatus.initialBootstrapComplete) {
964
+ historySyncStatus.initialBootstrapComplete = true;
965
+ ev.emit('messaging-history.status', {
966
+ syncType,
967
+ status: 'complete',
968
+ explicit: true
969
+ });
970
+ }
971
+ // RECENT with progress === 100 — explicit completion
972
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT &&
973
+ historyMsg.progress === 100 &&
974
+ !historySyncStatus.recentSyncComplete) {
975
+ historySyncStatus.recentSyncComplete = true;
976
+ clearTimeout(historySyncPausedTimeout);
977
+ historySyncPausedTimeout = undefined;
978
+ ev.emit('messaging-history.status', {
979
+ syncType,
980
+ status: 'complete',
981
+ explicit: true
982
+ });
983
+ }
984
+ // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
985
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
986
+ clearTimeout(historySyncPausedTimeout);
987
+ historySyncPausedTimeout = setTimeout(() => {
988
+ if (!historySyncStatus.recentSyncComplete) {
989
+ historySyncStatus.recentSyncComplete = true;
990
+ ev.emit('messaging-history.status', {
991
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT,
992
+ status: 'paused',
993
+ explicit: false
994
+ });
995
+ }
996
+ historySyncPausedTimeout = undefined;
997
+ }, index_js_3.HISTORY_SYNC_PAUSED_TIMEOUT_MS);
998
+ }
999
+ }
1000
+ // State machine: decide on sync and flush
1001
+ if (historyMsg && syncState === State_js_1.SyncState.AwaitingInitialSync) {
1002
+ if (awaitingSyncTimeout) {
1003
+ clearTimeout(awaitingSyncTimeout);
1004
+ awaitingSyncTimeout = undefined;
1005
+ }
1006
+ if (shouldProcessHistoryMsg) {
1007
+ syncState = State_js_1.SyncState.Syncing;
1008
+ logger.info('Transitioned to Syncing state');
1009
+ // Let doAppStateSync handle the final flush after it's done
1010
+ }
1011
+ else {
1012
+ syncState = State_js_1.SyncState.Online;
1013
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
1014
+ ev.flush();
1015
+ }
1016
+ }
1017
+ const doAppStateSync = async () => {
1018
+ if (syncState === State_js_1.SyncState.Syncing) {
1019
+ // All collections will be synced, so clear any blocked ones
1020
+ blockedCollections.clear();
1021
+ logger.info('Doing app state sync');
1022
+ await resyncAppState(index_js_4.ALL_WA_PATCH_NAMES, true);
1023
+ // Sync is complete, go online and flush everything
1024
+ syncState = State_js_1.SyncState.Online;
1025
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
1026
+ ev.flush();
1027
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1028
+ ev.emit('creds.update', { accountSyncCounter });
1029
+ }
1030
+ };
1031
+ await Promise.all([
1032
+ (async () => {
1033
+ if (shouldProcessHistoryMsg) {
1034
+ await doAppStateSync();
1035
+ }
1036
+ })(),
1037
+ (0, process_message_js_1.default)(msg, {
1038
+ signalRepository,
1039
+ shouldProcessHistoryMsg,
1040
+ placeholderResendCache,
1041
+ ev,
1042
+ creds: authState.creds,
1043
+ keyStore: authState.keys,
1044
+ logger,
1045
+ options: config.options,
1046
+ getMessage
1047
+ })
1048
+ ]);
1049
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
1050
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === State_js_1.SyncState.Syncing) {
1051
+ logger.info('App state sync key arrived, triggering app state sync');
1052
+ await doAppStateSync();
1053
+ }
1054
+ });
1055
+ return {
1056
+ ...sock,
1057
+ findUserId,
1058
+ serverProps,
1059
+ createCallLink,
1060
+ getBotListV2,
1061
+ messageMutex,
1062
+ receiptMutex,
1063
+ appStatePatchMutex,
1064
+ notificationMutex,
1065
+ fetchPrivacySettings,
1066
+ upsertMessage,
1067
+ appPatch,
1068
+ sendPresenceUpdate,
1069
+ presenceSubscribe,
1070
+ profilePictureUrl,
1071
+ fetchBlocklist,
1072
+ fetchStatus,
1073
+ fetchDisappearingDuration,
1074
+ updateProfilePicture,
1075
+ removeProfilePicture,
1076
+ updateProfileStatus,
1077
+ updateProfileName,
1078
+ updateBlockStatus,
1079
+ updateDisableLinkPreviewsPrivacy,
1080
+ updateCallPrivacy,
1081
+ updateMessagesPrivacy,
1082
+ updateLastSeenPrivacy,
1083
+ updateOnlinePrivacy,
1084
+ updateProfilePicturePrivacy,
1085
+ updateStatusPrivacy,
1086
+ updateReadReceiptsPrivacy,
1087
+ updateGroupsAddPrivacy,
1088
+ updateDefaultDisappearingMode,
1089
+ getBusinessProfile,
1090
+ resyncAppState,
1091
+ chatModify,
1092
+ cleanDirtyBits,
1093
+ addOrEditContact,
1094
+ removeContact,
1095
+ placeholderResendCache,
1096
+ addLabel,
1097
+ addChatLabel,
1098
+ removeChatLabel,
1099
+ addMessageLabel,
1100
+ removeMessageLabel,
1101
+ star,
1102
+ addOrEditQuickReply,
1103
+ removeQuickReply
1104
+ };
1105
+ };
1106
+ exports.attachAdvanced = attachAdvanced;