@itznomo/baileys 0.0.0-stage → 0.0.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 (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,702 @@
1
+ import { proto } from '../../WAProto/index.js'
2
+ import { Boom } from '../foundation/boom.js'
3
+ import { Cache } from '../foundation/cache.js'
4
+ import { makeMutex } from '../foundation/concurrency.js'
5
+ import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../defaults.js'
6
+ import { ALL_WA_PATCH_NAMES, SyncState } from '../constants.js'
7
+ import {
8
+ chatModificationToAppPatch,
9
+ decodePatches,
10
+ decodeSyncdSnapshot,
11
+ encodeSyncdPatch,
12
+ ensureLTHashStateVersion,
13
+ extractSyncdPatches,
14
+ newLTHashState,
15
+ processSyncAction
16
+ } from '../utils/chat-sync.js'
17
+ import { isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS } from '../utils/chat-sync.js'
18
+ import { generateProfilePicture } from '../utils/media.js'
19
+ import processMessage, { getHistoryMsg } from '../utils/message-processing.js'
20
+ import { buildTcTokenFromJid } from '../utils/auth-state-core.js'
21
+ import {
22
+ getBinaryNodeChild,
23
+ getBinaryNodeChildren,
24
+ isHostedLidUser,
25
+ isHostedPnUser,
26
+ isLidUser,
27
+ isPnUser,
28
+ jidDecode,
29
+ jidNormalizedUser,
30
+ reduceBinaryNodeToDictionary,
31
+ S_WHATSAPP_NET
32
+ } from '../binary/wa-binary.js'
33
+ import { USyncQuery, USyncUser } from './usync.js'
34
+ import { makeSocket } from './socket-core.js'
35
+ import { checkStatusWA } from '../utils/check-status.js'
36
+ import {
37
+ buildSpamReportIq,
38
+ buildSimpleReportNode,
39
+ parseSpamReportResponse,
40
+ resolveReportContext
41
+ } from '../utils/spam-report-utils.js'
42
+
43
+ export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
44
+ const picture = { tag: 'picture', attrs: { type, query: 'url' } }
45
+ if (tcTokenContent?.length) picture.content = tcTokenContent
46
+ return [picture]
47
+ }
48
+
49
+ export const makeChatsSocket = config => {
50
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config
51
+ const sock = makeSocket(config)
52
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock
53
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
54
+ let privacySettings
55
+
56
+ const serverProps = {
57
+ privacyTokenOn1to1: true,
58
+ profilePicPrivacyToken: true,
59
+ lidTrustedTokenIssueToLid: false
60
+ }
61
+ let syncState = SyncState.Connecting
62
+ const messageMutex = makeMutex()
63
+ const receiptMutex = makeMutex()
64
+ const appStatePatchMutex = makeMutex()
65
+ const notificationMutex = makeMutex()
66
+ let awaitingSyncTimeout
67
+ const historySyncStatus = { initialBootstrapComplete: false, recentSyncComplete: false }
68
+ let historySyncPausedTimeout
69
+ const blockedCollections = new Set()
70
+ const placeholderResendCache = config.placeholderResendCache || new Cache({ ttl: DEFAULT_CACHE_TTLS.MSG_RETRY * 1000 })
71
+
72
+ const getAppStateSyncKey = async keyId => {
73
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
74
+ return key
75
+ }
76
+ const fetchPrivacySettings = async (force = false) => {
77
+ if (!privacySettings || force) {
78
+ const { content } = await query({ tag: 'iq', attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'get' }, content: [{ tag: 'privacy', attrs: {} }] })
79
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category')
80
+ }
81
+ return privacySettings
82
+ }
83
+ const privacyQuery = async (name, value) => {
84
+ await query({ tag: 'iq', attrs: { xmlns: 'privacy', to: S_WHATSAPP_NET, type: 'set' }, content: [{ tag: 'privacy', attrs: {}, content: [{ tag: 'category', attrs: { name, value } }] }] })
85
+ }
86
+ const updateMessagesPrivacy = async value => privacyQuery('messages', value)
87
+ const updateCallPrivacy = async value => privacyQuery('calladd', value)
88
+ const updateLastSeenPrivacy = async value => privacyQuery('last', value)
89
+ const updateOnlinePrivacy = async value => privacyQuery('online', value)
90
+ const updateProfilePicturePrivacy = async value => privacyQuery('profile', value)
91
+ const updateStatusPrivacy = async value => privacyQuery('status', value)
92
+ const updateReadReceiptsPrivacy = async value => privacyQuery('readreceipts', value)
93
+ const updateGroupsAddPrivacy = async value => privacyQuery('groupadd', value)
94
+ const updateDefaultDisappearingMode = async duration => {
95
+ await query({ tag: 'iq', attrs: { xmlns: 'disappearing_mode', to: S_WHATSAPP_NET, type: 'set' }, content: [{ tag: 'disappearing_mode', attrs: { duration: duration.toString() } }] })
96
+ }
97
+ const getBotListV2 = async () => {
98
+ const resp = await query({ tag: 'iq', attrs: { xmlns: 'bot', to: S_WHATSAPP_NET, type: 'get' }, content: [{ tag: 'bot', attrs: { v: '2' } }] })
99
+ const botNode = getBinaryNodeChild(resp, 'bot')
100
+ const botList = []
101
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
102
+ if (section.attrs.type === 'all') {
103
+ for (const bot of getBinaryNodeChildren(section, 'bot')) botList.push({ jid: bot.attrs.jid, personaId: bot.attrs['persona_id'] })
104
+ }
105
+ }
106
+ return botList
107
+ }
108
+ const fetchStatus = async (...jids) => {
109
+ const usyncQuery = new USyncQuery().withStatusProtocol()
110
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
111
+ const result = await sock.executeUSyncQuery(usyncQuery)
112
+ if (result) return result.list
113
+ }
114
+ const fetchDisappearingDuration = async (...jids) => {
115
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol()
116
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid))
117
+ const result = await sock.executeUSyncQuery(usyncQuery)
118
+ if (result) return result.list
119
+ }
120
+ const findUserId = async pnLid => {
121
+ const normalizedJid = jidNormalizedUser(pnLid)
122
+ const userId = { lid: undefined, phoneNumber: undefined }
123
+ if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
124
+ userId.phoneNumber = normalizedJid
125
+ userId.lid = jidNormalizedUser((await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid)
126
+ } else if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
127
+ userId.lid = normalizedJid
128
+ userId.phoneNumber = jidNormalizedUser((await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn)
129
+ } else {
130
+ throw new Boom('Invalid id input to find user ids', { statusCode: 400 })
131
+ }
132
+ return userId
133
+ }
134
+
135
+ const updateProfilePicture = async (jid, content, dimensions) => {
136
+ let targetJid
137
+ if (!jid) throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
138
+ targetJid = jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id) ? jidNormalizedUser(jid) : undefined
139
+ const { img } = await generateProfilePicture(content, dimensions)
140
+ await query({
141
+ tag: 'iq',
142
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) },
143
+ content: [{ tag: 'picture', attrs: { type: 'image' }, content: img }]
144
+ })
145
+ }
146
+
147
+ const removeProfilePicture = async jid => {
148
+ let targetJid
149
+ if (!jid) throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
150
+ targetJid = jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id) ? jidNormalizedUser(jid) : undefined
151
+ await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:profile:picture', ...(targetJid ? { target: targetJid } : {}) } })
152
+ }
153
+ const updateProfileStatus = async status => {
154
+ await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'status' }, content: [{ tag: 'status', attrs: {}, content: Buffer.from(status, 'utf-8') }] })
155
+ }
156
+ const updateProfileName = async name => chatModify({ pushNameSetting: name }, '')
157
+ const fetchBlocklist = async () => {
158
+ const result = await query({ tag: 'iq', attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'get' } })
159
+ const listNode = getBinaryNodeChild(result, 'list')
160
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid)
161
+ }
162
+ const updateBlockStatus = async (jid, action) => {
163
+ const normalizedJid = jidNormalizedUser(jid)
164
+ let lid, pn_jid
165
+ if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
166
+ lid = normalizedJid
167
+ if (action === 'block') {
168
+ const pn = (await findUserId(normalizedJid)).phoneNumber
169
+ if (!pn) throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 })
170
+ pn_jid = jidNormalizedUser(pn)
171
+ }
172
+ } else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
173
+ const mapped = (await findUserId(normalizedJid)).lid
174
+ if (!mapped) throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 })
175
+ lid = mapped
176
+ if (action === 'block') pn_jid = jidNormalizedUser(normalizedJid)
177
+ } else {
178
+ throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 })
179
+ }
180
+ const itemAttrs = { action, jid: lid }
181
+ if (action === 'block') {
182
+ if (!pn_jid) throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 })
183
+ itemAttrs.pn_jid = pn_jid
184
+ }
185
+ await query({ tag: 'iq', attrs: { xmlns: 'blocklist', to: S_WHATSAPP_NET, type: 'set' }, content: [{ tag: 'item', attrs: itemAttrs }] })
186
+ }
187
+ const getBusinessProfile = async jid => {
188
+ const results = await query({
189
+ tag: 'iq',
190
+ attrs: { to: 's.whatsapp.net', xmlns: 'w:biz', type: 'get' },
191
+ content: [{ tag: 'business_profile', attrs: { v: '244' }, content: [{ tag: 'profile', attrs: { jid } }] }]
192
+ })
193
+ const profileNode = getBinaryNodeChild(results, 'business_profile')
194
+ const profiles = getBinaryNodeChild(profileNode, 'profile')
195
+ if (profiles) {
196
+ const address = getBinaryNodeChild(profiles, 'address')
197
+ const description = getBinaryNodeChild(profiles, 'description')
198
+ const website = getBinaryNodeChild(profiles, 'website')
199
+ const email = getBinaryNodeChild(profiles, 'email')
200
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category')
201
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours')
202
+ const businessHoursConfig = businessHours ? getBinaryNodeChildren(businessHours, 'business_hours_config') : undefined
203
+ const websiteStr = website?.content?.toString()
204
+ return {
205
+ wid: profiles.attrs?.jid,
206
+ address: address?.content?.toString(),
207
+ description: description?.content?.toString() || '',
208
+ website: websiteStr ? [websiteStr] : [],
209
+ email: email?.content?.toString(),
210
+ category: category?.content?.toString(),
211
+ business_hours: { timezone: businessHours?.attrs?.timezone, business_config: businessHoursConfig?.map(({ attrs }) => attrs) }
212
+ }
213
+ }
214
+ }
215
+ const cleanDirtyBits = async (type, fromTimestamp) => {
216
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
217
+ await sendNode({
218
+ tag: 'iq',
219
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'urn:xmpp:whatsapp:dirty', id: generateMessageTag() },
220
+ content: [{ tag: 'clean', attrs: { type, ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null) } }]
221
+ })
222
+ }
223
+ const newAppStateChunkHandler = isInitialSync => ({
224
+ onMutation(mutation) {
225
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
226
+ }
227
+ })
228
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
229
+ const appStateSyncKeyCache = new Map()
230
+ const getCachedAppStateSyncKey = async keyId => {
231
+ if (appStateSyncKeyCache.has(keyId)) return appStateSyncKeyCache.get(keyId) ?? undefined
232
+ const key = await getAppStateSyncKey(keyId)
233
+ appStateSyncKeyCache.set(keyId, key ?? null)
234
+ return key
235
+ }
236
+ const initialVersionMap = {}
237
+ const globalMutationMap = {}
238
+ await authState.keys.transaction(async () => {
239
+ const collectionsToHandle = new Set(collections)
240
+ const attemptsMap = {}
241
+ const forceSnapshotCollections = new Set()
242
+ while (collectionsToHandle.size) {
243
+ const states = {}
244
+ const nodes = []
245
+ for (const name of collectionsToHandle) {
246
+ const result = await authState.keys.get('app-state-sync-version', [name])
247
+ let state = result[name]
248
+ if (state) {
249
+ state = ensureLTHashStateVersion(state)
250
+ if (typeof initialVersionMap[name] === 'undefined') initialVersionMap[name] = state.version
251
+ } else {
252
+ state = newLTHashState()
253
+ }
254
+ states[name] = state
255
+ const shouldForceSnapshot = forceSnapshotCollections.has(name)
256
+ if (shouldForceSnapshot) forceSnapshotCollections.delete(name)
257
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`)
258
+ nodes.push({ tag: 'collection', attrs: { name, version: state.version.toString(), return_snapshot: (shouldForceSnapshot || !state.version).toString() } })
259
+ }
260
+ const result = await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, xmlns: 'w:sync:app:state', type: 'set' }, content: [{ tag: 'sync', attrs: {}, content: nodes }] })
261
+ const decoded = await extractSyncdPatches(result, config?.options)
262
+ for (const key in decoded) {
263
+ const name = key
264
+ const { patches, hasMorePatches, snapshot } = decoded[name]
265
+ try {
266
+ if (snapshot) {
267
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger)
268
+ states[name] = newState
269
+ Object.assign(globalMutationMap, mutationMap)
270
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
271
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
272
+ }
273
+ if (patches.length) {
274
+ const { state: newState, mutationMap } = await decodePatches(
275
+ name,
276
+ patches,
277
+ states[name],
278
+ getCachedAppStateSyncKey,
279
+ config.options,
280
+ initialVersionMap[name],
281
+ logger,
282
+ appStateMacVerification.patch
283
+ )
284
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
285
+ logger.info(`synced ${name} to v${newState.version}`)
286
+ initialVersionMap[name] = newState.version
287
+ Object.assign(globalMutationMap, mutationMap)
288
+ }
289
+ if (hasMorePatches) logger.info(`${name} has more patches...`)
290
+ else collectionsToHandle.delete(name)
291
+ } catch (error) {
292
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
293
+ const logData = { name, attempt: attemptsMap[name], version: states[name].version, statusCode: error.output?.statusCode, errorType: error.name, error: error.stack }
294
+ if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
295
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`)
296
+ blockedCollections.add(name)
297
+ collectionsToHandle.delete(name)
298
+ } else if (isMissingKeyError(error)) {
299
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`)
300
+ forceSnapshotCollections.add(name)
301
+ } else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
302
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`)
303
+ collectionsToHandle.delete(name)
304
+ } else {
305
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`)
306
+ forceSnapshotCollections.add(name)
307
+ }
308
+ }
309
+ }
310
+ }
311
+ }, authState?.creds?.me?.id || 'resync-app-state')
312
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
313
+ for (const key in globalMutationMap) onMutation(globalMutationMap[key])
314
+ })
315
+
316
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = true) => {
317
+ const normalizedJid = jidNormalizedUser(jid)
318
+ const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid)
319
+ const me = authState.creds.me
320
+ const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)))
321
+ let tcTokenContent
322
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
323
+ tcTokenContent = await buildTcTokenFromJid({ authState, jid: normalizedJid, getLIDForPN })
324
+ }
325
+ jid = jidNormalizedUser(jid)
326
+ const result = await query(
327
+ { tag: 'iq', attrs: { target: jid, to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:profile:picture' }, content: buildProfilePictureQueryContent(type, tcTokenContent) },
328
+ timeoutMs
329
+ )
330
+ const child = getBinaryNodeChild(result, 'picture')
331
+ return child?.attrs?.url
332
+ }
333
+ const createCallLink = async (type, event, timeoutMs) => {
334
+ const result = await query(
335
+ { tag: 'call', attrs: { id: generateMessageTag(), to: '@call' }, content: [{ tag: 'link_create', attrs: { media: type }, content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined }] },
336
+ timeoutMs
337
+ )
338
+ const child = getBinaryNodeChild(result, 'link_create')
339
+ return child?.attrs?.token
340
+ }
341
+ const sendPresenceUpdate = async (type, toJid) => {
342
+ const me = authState.creds.me
343
+ const isAvailableType = type === 'available'
344
+ if (isAvailableType || type === 'unavailable') {
345
+ if (!me.name) {
346
+ logger.warn('no name present, ignoring presence update request...')
347
+ return
348
+ }
349
+ ev.emit('connection.update', { isOnline: isAvailableType })
350
+ if (isAvailableType) void sendUnifiedSession()
351
+ await sendNode({ tag: 'presence', attrs: { name: me.name.replace(/@/g, ''), type } })
352
+ } else {
353
+ const { server } = jidDecode(toJid)
354
+ const isLid = server === 'lid'
355
+ await sendNode({ tag: 'chatstate', attrs: { from: isLid ? me.lid : me.id, to: toJid }, content: [{ tag: type === 'recording' ? 'composing' : type, attrs: type === 'recording' ? { media: 'audio' } : {} }] })
356
+ }
357
+ }
358
+ const presenceSubscribe = async toJid => {
359
+ const normalizedToJid = jidNormalizedUser(toJid)
360
+ const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid)
361
+ const tcTokenContent = isUserJid ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN }) : undefined
362
+ return sendNode({ tag: 'presence', attrs: { to: toJid, id: generateMessageTag(), type: 'subscribe' }, content: tcTokenContent })
363
+ }
364
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
365
+ let presence
366
+ const jid = attrs.from
367
+ const participant = attrs.participant || attrs.from
368
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) return
369
+ if (tag === 'presence') {
370
+ presence = { lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available', lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined, groupOnlineCount: attrs.count ? +attrs.count : undefined }
371
+ } else if (Array.isArray(content)) {
372
+ const [firstChild] = content
373
+ let type = firstChild.tag
374
+ if (type === 'paused') type = 'available'
375
+ if (firstChild.attrs?.media === 'audio') type = 'recording'
376
+ presence = { lastKnownPresence: type }
377
+ } else {
378
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
379
+ }
380
+ if (presence) ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
381
+ }
382
+ const appPatch = async patchCreate => {
383
+ const name = patchCreate.type
384
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
385
+ if (!myAppStateKeyId) throw new Boom('App state key not present!', { statusCode: 400 })
386
+ let initial, encodeResult
387
+ await appStatePatchMutex.mutex(async () => {
388
+ await authState.keys.transaction(async () => {
389
+ logger.debug({ patch: patchCreate }, 'applying app patch')
390
+ await resyncAppState([name], false)
391
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
392
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState()
393
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
394
+ const { patch, state } = encodeResult
395
+ const node = {
396
+ tag: 'iq',
397
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'w:sync:app:state' },
398
+ content: [
399
+ {
400
+ tag: 'sync',
401
+ attrs: {},
402
+ content: [{ tag: 'collection', attrs: { name, version: (state.version - 1).toString(), return_snapshot: 'false' }, content: [{ tag: 'patch', attrs: {}, content: proto.SyncdPatch.encode(patch).finish() }] }]
403
+ }
404
+ ]
405
+ }
406
+ await query(node)
407
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
408
+ }, authState?.creds?.me?.id || 'app-patch')
409
+ })
410
+ if (config.emitOwnEvents) {
411
+ const { onMutation } = newAppStateChunkHandler(false)
412
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger)
413
+ for (const key in mutationMap) onMutation(mutationMap[key])
414
+ }
415
+ }
416
+
417
+ const fetchProps = async () => {
418
+ const resultNode = await query({
419
+ tag: 'iq',
420
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'abt', type: 'get' },
421
+ content: [{ tag: 'props', attrs: { protocol: '1', ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {}) } }]
422
+ })
423
+ const propsNode = getBinaryNodeChild(resultNode, 'props')
424
+ let props = {}
425
+ if (propsNode) {
426
+ if (propsNode.attrs?.hash) {
427
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
428
+ ev.emit('creds.update', authState.creds)
429
+ }
430
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop')
431
+ }
432
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages']
433
+ if (privacyTokenProp !== undefined) serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1'
434
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq']
435
+ if (profilePicProp !== undefined) serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1'
436
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid']
437
+ if (lidIssueProp !== undefined) serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1'
438
+ logger.debug({ serverProps }, 'fetched props')
439
+ return props
440
+ }
441
+ const chatModify = (mod, jid) => appPatch(chatModificationToAppPatch(mod, jid))
442
+ const updateDisableLinkPreviewsPrivacy = isPreviewsDisabled => chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '')
443
+ const star = (jid, messages, star) => chatModify({ star: { messages, star } }, jid)
444
+ const addOrEditContact = (jid, contact) => chatModify({ contact }, jid)
445
+ const removeContact = jid => chatModify({ contact: null }, jid)
446
+ const addLabel = (jid, labels) => chatModify({ addLabel: { ...labels } }, jid)
447
+ const addChatLabel = (jid, labelId) => chatModify({ addChatLabel: { labelId } }, jid)
448
+ const removeChatLabel = (jid, labelId) => chatModify({ removeChatLabel: { labelId } }, jid)
449
+ const addMessageLabel = (jid, messageId, labelId) => chatModify({ addMessageLabel: { messageId, labelId } }, jid)
450
+ const removeMessageLabel = (jid, messageId, labelId) => chatModify({ removeMessageLabel: { messageId, labelId } }, jid)
451
+ const addOrEditQuickReply = quickReply => chatModify({ quickReply }, '')
452
+ const removeQuickReply = timestamp => chatModify({ quickReply: { timestamp, deleted: true } }, '')
453
+ const executeInitQueries = async () => {
454
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()])
455
+ }
456
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
457
+ ev.emit('messages.upsert', { messages: [msg], type })
458
+ if (!!msg.pushName) {
459
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid
460
+ jid = jidNormalizedUser(jid)
461
+ if (!msg.key.fromMe) ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
462
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
463
+ }
464
+ const historyMsg = getHistoryMsg(msg.message)
465
+ const shouldProcessHistoryMsg = historyMsg ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType) : false
466
+ if (historyMsg && shouldProcessHistoryMsg) {
467
+ const syncType = historyMsg.syncType
468
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP && !historySyncStatus.initialBootstrapComplete) {
469
+ historySyncStatus.initialBootstrapComplete = true
470
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
471
+ }
472
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && historyMsg.progress === 100 && !historySyncStatus.recentSyncComplete) {
473
+ historySyncStatus.recentSyncComplete = true
474
+ clearTimeout(historySyncPausedTimeout)
475
+ historySyncPausedTimeout = undefined
476
+ ev.emit('messaging-history.status', { syncType, status: 'complete', explicit: true })
477
+ }
478
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
479
+ clearTimeout(historySyncPausedTimeout)
480
+ historySyncPausedTimeout = setTimeout(() => {
481
+ if (!historySyncStatus.recentSyncComplete) {
482
+ historySyncStatus.recentSyncComplete = true
483
+ ev.emit('messaging-history.status', { syncType: proto.HistorySync.HistorySyncType.RECENT, status: 'paused', explicit: false })
484
+ }
485
+ historySyncPausedTimeout = undefined
486
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS)
487
+ }
488
+ }
489
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
490
+ if (awaitingSyncTimeout) {
491
+ clearTimeout(awaitingSyncTimeout)
492
+ awaitingSyncTimeout = undefined
493
+ }
494
+ if (shouldProcessHistoryMsg) {
495
+ syncState = SyncState.Syncing
496
+ logger.info('Transitioned to Syncing state')
497
+ } else {
498
+ syncState = SyncState.Online
499
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
500
+ ev.flush()
501
+ }
502
+ }
503
+ const doAppStateSync = async () => {
504
+ if (syncState === SyncState.Syncing) {
505
+ blockedCollections.clear()
506
+ logger.info('Doing app state sync')
507
+ await resyncAppState(ALL_WA_PATCH_NAMES, true)
508
+ syncState = SyncState.Online
509
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
510
+ ev.flush()
511
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
512
+ ev.emit('creds.update', { accountSyncCounter })
513
+ }
514
+ }
515
+ try {
516
+ await Promise.all([
517
+ (async () => {
518
+ if (shouldProcessHistoryMsg) await doAppStateSync()
519
+ })(),
520
+ processMessage(msg, {
521
+ signalRepository,
522
+ shouldProcessHistoryMsg,
523
+ placeholderResendCache,
524
+ ev,
525
+ creds: authState.creds,
526
+ keyStore: authState.keys,
527
+ logger,
528
+ options: config.options,
529
+ getMessage
530
+ })
531
+ ])
532
+ } catch (err) {
533
+ logger.error({ err, key: msg.key }, 'Error in message post-processing')
534
+ }
535
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
536
+ logger.info('App state sync key arrived, triggering app state sync')
537
+ await doAppStateSync()
538
+ }
539
+ })
540
+ ws.on('CB:presence', handlePresenceUpdate)
541
+ ws.on('CB:chatstate', handlePresenceUpdate)
542
+ ws.on('CB:ib,,dirty', async node => {
543
+ const { attrs } = getBinaryNodeChild(node, 'dirty')
544
+ const type = attrs.type
545
+ switch (type) {
546
+ case 'account_sync':
547
+ if (attrs.timestamp) {
548
+ let { lastAccountSyncTimestamp } = authState.creds
549
+ if (lastAccountSyncTimestamp) await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
550
+ lastAccountSyncTimestamp = +attrs.timestamp
551
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
552
+ }
553
+ break
554
+ case 'groups':
555
+ break
556
+ default:
557
+ logger.info({ node }, 'received unknown sync')
558
+ break
559
+ }
560
+ })
561
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
562
+ if (connection === 'close') {
563
+ blockedCollections.clear()
564
+ clearTimeout(historySyncPausedTimeout)
565
+ historySyncPausedTimeout = undefined
566
+ }
567
+ if (connection === 'open') {
568
+ if (fireInitQueries) executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
569
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'))
570
+ }
571
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) return
572
+ historySyncStatus.initialBootstrapComplete = false
573
+ historySyncStatus.recentSyncComplete = false
574
+ clearTimeout(historySyncPausedTimeout)
575
+ historySyncPausedTimeout = undefined
576
+ syncState = SyncState.AwaitingInitialSync
577
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
578
+ ev.buffer()
579
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({ syncType: proto.HistorySync.HistorySyncType.RECENT }))
580
+ if (!willSyncHistory) {
581
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
582
+ syncState = SyncState.Online
583
+ setTimeout(() => ev.flush(), 0)
584
+ return
585
+ }
586
+ if (authState.creds.accountSyncCounter > 0) {
587
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.')
588
+ syncState = SyncState.Online
589
+ setTimeout(() => ev.flush(), 0)
590
+ return
591
+ }
592
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.')
593
+ if (awaitingSyncTimeout) clearTimeout(awaitingSyncTimeout)
594
+ awaitingSyncTimeout = setTimeout(() => {
595
+ if (syncState === SyncState.AwaitingInitialSync) {
596
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
597
+ syncState = SyncState.Online
598
+ ev.flush()
599
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
600
+ ev.emit('creds.update', { accountSyncCounter })
601
+ }
602
+ }, 20000)
603
+ })
604
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
605
+ if (!myAppStateKeyId || blockedCollections.size === 0) return
606
+ if (syncState === SyncState.Syncing) {
607
+ blockedCollections.clear()
608
+ return
609
+ }
610
+ const collections = [...blockedCollections]
611
+ blockedCollections.clear()
612
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections')
613
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'))
614
+ })
615
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
616
+ try {
617
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }])
618
+ } catch (error) {
619
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping')
620
+ }
621
+ })
622
+ registerSocketEndHandler(() => {
623
+ if (awaitingSyncTimeout) {
624
+ clearTimeout(awaitingSyncTimeout)
625
+ awaitingSyncTimeout = undefined
626
+ }
627
+ if (!config.placeholderResendCache && placeholderResendCache.close) placeholderResendCache.close()
628
+ syncState = SyncState.Connecting
629
+ privacySettings = undefined
630
+ })
631
+
632
+ const reportSpam = async (jid, options = {}) => {
633
+ const { reportJid, spamFlow } = await resolveReportContext(jid, sock.signalRepository?.lidMapping)
634
+ if (options.messages?.length) {
635
+ const iq = buildSpamReportIq(reportJid, options.messages, options.spamFlow || spamFlow, logger)
636
+ const res = await query(iq)
637
+ return parseSpamReportResponse(res)
638
+ }
639
+ const node = buildSimpleReportNode(reportJid, options.messageKeys || [])
640
+ const res = await query({
641
+ tag: 'iq',
642
+ attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
643
+ content: [node]
644
+ })
645
+ return parseSpamReportResponse(res)
646
+ }
647
+
648
+ return {
649
+ ...sock,
650
+ findUserId,
651
+ serverProps,
652
+ createCallLink,
653
+ getBotListV2,
654
+ messageMutex,
655
+ receiptMutex,
656
+ appStatePatchMutex,
657
+ notificationMutex,
658
+ fetchPrivacySettings,
659
+ upsertMessage,
660
+ appPatch,
661
+ sendPresenceUpdate,
662
+ presenceSubscribe,
663
+ profilePictureUrl,
664
+ fetchBlocklist,
665
+ fetchStatus,
666
+ fetchDisappearingDuration,
667
+ updateProfilePicture,
668
+ removeProfilePicture,
669
+ updateProfileStatus,
670
+ updateProfileName,
671
+ updateBlockStatus,
672
+ updateDisableLinkPreviewsPrivacy,
673
+ updateCallPrivacy,
674
+ updateMessagesPrivacy,
675
+ updateLastSeenPrivacy,
676
+ updateOnlinePrivacy,
677
+ updateProfilePicturePrivacy,
678
+ updateStatusPrivacy,
679
+ updateReadReceiptsPrivacy,
680
+ updateGroupsAddPrivacy,
681
+ updateDefaultDisappearingMode,
682
+ reportSpam,
683
+ checkStatusWA,
684
+ getBusinessProfile,
685
+ resyncAppState,
686
+ chatModify,
687
+ cleanDirtyBits,
688
+ addOrEditContact,
689
+ removeContact,
690
+ placeholderResendCache,
691
+ addLabel,
692
+ addChatLabel,
693
+ removeChatLabel,
694
+ addMessageLabel,
695
+ removeMessageLabel,
696
+ star,
697
+ addOrEditQuickReply,
698
+ removeQuickReply
699
+ }
700
+ }
701
+
702
+ export { checkStatusWA }