@itznomo/baileys 0.0.0-stage → 0.0.1

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,731 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { randomBytes } from 'node:crypto'
3
+ import { Boom } from '../foundation/boom.js'
4
+ import { Cache } from '../foundation/cache.js'
5
+ import { makeMutex, makeSerialTaskQueue, makeKeyedSerialTaskQueues } from '../foundation/concurrency.js'
6
+ import { proto } from '../../WAProto/index.js'
7
+ import {
8
+ areJidsSameUser,
9
+ getBinaryNodeChild,
10
+ getBinaryNodeChildren,
11
+ isHostedLidUser,
12
+ isHostedPnUser,
13
+ isJidBroadcast,
14
+ isJidGroup,
15
+ isJidMetaAI,
16
+ isJidNewsletter,
17
+ isJidStatusBroadcast,
18
+ isLidUser,
19
+ isPnUser,
20
+ jidDecode,
21
+ jidNormalizedUser
22
+ } from '../binary/wa-binary.js'
23
+ import { Curve, delay, generateRegistrationId, signedKeyPair, unpadRandomMax16 } from './wa-protocol-core.js'
24
+
25
+ const DEFAULT_CACHE_TTLS = {
26
+ SIGNAL_STORE: 5 * 60,
27
+ MSG_RETRY: 60 * 60,
28
+ CALL_OFFER: 5 * 60,
29
+ USER_DEVICES: 5 * 60
30
+ }
31
+
32
+ export class PreKeyManager {
33
+ constructor(store, logger) {
34
+ this.store = store
35
+ this.logger = logger
36
+ this.queues = makeKeyedSerialTaskQueues()
37
+ }
38
+
39
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
40
+ const keyData = data[keyType]
41
+ if (!keyData) return
42
+ return this.queues.get(keyType).add(async () => {
43
+ transactionCache[keyType] = transactionCache[keyType] || {}
44
+ mutations[keyType] = mutations[keyType] || {}
45
+
46
+ const deletions = []
47
+ const updates = {}
48
+ for (const keyId in keyData) {
49
+ if (keyData[keyId] === null) deletions.push(keyId)
50
+ else updates[keyId] = keyData[keyId]
51
+ }
52
+ if (Object.keys(updates).length > 0) {
53
+ Object.assign(transactionCache[keyType], updates)
54
+ Object.assign(mutations[keyType], updates)
55
+ }
56
+ if (deletions.length > 0) {
57
+ await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction)
58
+ }
59
+ })
60
+ }
61
+
62
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
63
+ if (isInTransaction) {
64
+ for (const keyId of ids) {
65
+ if (transactionCache[keyType]?.[keyId]) {
66
+ transactionCache[keyType][keyId] = null
67
+ mutations[keyType][keyId] = null
68
+ } else {
69
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`)
70
+ }
71
+ }
72
+ } else {
73
+ const existingKeys = await this.store.get(keyType, ids)
74
+ for (const keyId of ids) {
75
+ if (existingKeys[keyId]) {
76
+ transactionCache[keyType][keyId] = null
77
+ mutations[keyType][keyId] = null
78
+ } else {
79
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ async validateDeletions(data, keyType) {
86
+ const keyData = data[keyType]
87
+ if (!keyData) return
88
+ return this.queues.get(keyType).add(async () => {
89
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null)
90
+ if (deletionIds.length === 0) return
91
+ const existingKeys = await this.store.get(keyType, deletionIds)
92
+ for (const keyId of deletionIds) {
93
+ if (!existingKeys[keyId]) {
94
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
95
+ delete data[keyType][keyId]
96
+ }
97
+ }
98
+ })
99
+ }
100
+ }
101
+
102
+ const txStorage = new AsyncLocalStorage()
103
+
104
+ export function makeCacheableSignalKeyStore(store, logger, _cache) {
105
+
106
+ const cache = _cache || new Cache({ max: 8192, ttl: DEFAULT_CACHE_TTLS.SIGNAL_STORE * 1000 })
107
+ const cacheMutex = makeMutex()
108
+
109
+ function getUniqueId(type, id) {
110
+ return `${type}.${id}`
111
+ }
112
+
113
+ return {
114
+ async get(type, ids) {
115
+ const data = {}
116
+ const idsToFetch = []
117
+ for (const id of ids) {
118
+ const item = cache.get(getUniqueId(type, id))
119
+ if (typeof item !== 'undefined') data[id] = item
120
+ else idsToFetch.push(id)
121
+ }
122
+ if (!idsToFetch.length) {
123
+ return data
124
+ }
125
+ return cacheMutex.mutex(async () => {
126
+ const stillToFetch = []
127
+ for (const id of idsToFetch) {
128
+ const item = cache.get(getUniqueId(type, id))
129
+ if (typeof item !== 'undefined') data[id] = item
130
+ else stillToFetch.push(id)
131
+ }
132
+ if (stillToFetch.length) {
133
+ logger?.trace({ items: stillToFetch.length }, 'loading from store')
134
+ const fetched = await store.get(type, stillToFetch)
135
+ for (const id of stillToFetch) {
136
+ const item = fetched[id]
137
+ if (item) {
138
+ data[id] = item
139
+ cache.set(getUniqueId(type, id), item)
140
+ }
141
+ }
142
+ }
143
+ return data
144
+ })
145
+ },
146
+ async set(data) {
147
+ return cacheMutex.mutex(async () => {
148
+ let keys = 0
149
+ for (const type in data) {
150
+ for (const id in data[type]) {
151
+ cache.set(getUniqueId(type, id), data[type][id])
152
+ keys += 1
153
+ }
154
+ }
155
+ logger?.trace({ keys }, 'updated cache')
156
+ await store.set(data)
157
+ })
158
+ },
159
+ async clear() {
160
+ cache.clear()
161
+ await store.clear?.()
162
+ }
163
+ }
164
+ }
165
+
166
+ export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
167
+ const keyQueues = new Map()
168
+ const txMutexes = new Map()
169
+ const txMutexRefCounts = new Map()
170
+ const preKeyManager = new PreKeyManager(state, logger)
171
+
172
+ function getQueue(key) {
173
+ if (!keyQueues.has(key)) keyQueues.set(key, makeSerialTaskQueue())
174
+ return keyQueues.get(key)
175
+ }
176
+ function getTxMutex(key) {
177
+ if (!txMutexes.has(key)) {
178
+ txMutexes.set(key, makeMutex())
179
+ txMutexRefCounts.set(key, 0)
180
+ }
181
+ return txMutexes.get(key)
182
+ }
183
+ function acquireTxMutexRef(key) {
184
+ const count = txMutexRefCounts.get(key) ?? 0
185
+ txMutexRefCounts.set(key, count + 1)
186
+ }
187
+ function releaseTxMutexRef(key) {
188
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1
189
+ txMutexRefCounts.set(key, count)
190
+ if (count <= 0) {
191
+ txMutexes.delete(key)
192
+ txMutexRefCounts.delete(key)
193
+ }
194
+ }
195
+ function isInTransaction() {
196
+ return !!txStorage.getStore()
197
+ }
198
+ async function commitWithRetry(mutations) {
199
+ if (Object.keys(mutations).length === 0) {
200
+ logger.trace('no mutations in transaction')
201
+ return
202
+ }
203
+ logger.trace('committing transaction')
204
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
205
+ try {
206
+ await state.set(mutations)
207
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction')
208
+ return
209
+ } catch (error) {
210
+ const retriesLeft = maxCommitRetries - attempt - 1
211
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`)
212
+ if (retriesLeft === 0) throw error
213
+ await delay(delayBetweenTriesMs)
214
+ }
215
+ }
216
+ }
217
+
218
+ return {
219
+ get: async (type, ids) => {
220
+ const ctx = txStorage.getStore()
221
+ if (!ctx) return state.get(type, ids)
222
+
223
+ const cached = ctx.cache[type] || {}
224
+ const missing = ids.filter(id => !(id in cached))
225
+ if (missing.length > 0) {
226
+ ctx.dbQueries++
227
+ logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction')
228
+ const fetched = await getTxMutex(type).mutex(() => state.get(type, missing))
229
+ ctx.cache[type] = ctx.cache[type] || {}
230
+ Object.assign(ctx.cache[type], fetched)
231
+ }
232
+ const result = {}
233
+ for (const id of ids) {
234
+ const value = ctx.cache[type]?.[id]
235
+ if (value !== undefined && value !== null) result[id] = value
236
+ }
237
+ return result
238
+ },
239
+ set: async data => {
240
+ const ctx = txStorage.getStore()
241
+ if (!ctx) {
242
+
243
+ const types = Object.keys(data)
244
+ for (const type of types) {
245
+ if (type === 'pre-key') await preKeyManager.validateDeletions(data, type)
246
+ }
247
+ await Promise.all(
248
+ types.map(type =>
249
+ getQueue(type).add(async () => {
250
+ await state.set({ [type]: data[type] })
251
+ })
252
+ )
253
+ )
254
+ return
255
+ }
256
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction')
257
+ for (const key in data) {
258
+ ctx.cache[key] = ctx.cache[key] || {}
259
+ ctx.mutations[key] = ctx.mutations[key] || {}
260
+ if (key === 'pre-key') {
261
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true)
262
+ } else {
263
+ Object.assign(ctx.cache[key], data[key])
264
+ Object.assign(ctx.mutations[key], data[key])
265
+ }
266
+ }
267
+ },
268
+ isInTransaction,
269
+ transaction: async (work, key) => {
270
+ const existing = txStorage.getStore()
271
+ if (existing) {
272
+ logger.trace('reusing existing transaction context')
273
+ return work()
274
+ }
275
+ const mutex = getTxMutex(key)
276
+ acquireTxMutexRef(key)
277
+ try {
278
+ return await mutex.mutex(async () => {
279
+ const ctx = { cache: {}, mutations: {}, dbQueries: 0 }
280
+ logger.trace('entering transaction')
281
+ try {
282
+ const result = await txStorage.run(ctx, work)
283
+ await commitWithRetry(ctx.mutations)
284
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed')
285
+ return result
286
+ } catch (error) {
287
+ logger.error({ error }, 'transaction failed, rolling back')
288
+ throw error
289
+ }
290
+ })
291
+ } finally {
292
+ releaseTxMutexRef(key)
293
+ }
294
+ }
295
+ }
296
+ }
297
+
298
+ export const assertMeId = creds => {
299
+ const id = creds.me?.id
300
+ if (!id) throw new Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 })
301
+ return id
302
+ }
303
+
304
+ export const initAuthCreds = () => {
305
+ const identityKey = Curve.generateKeyPair()
306
+ return {
307
+ noiseKey: Curve.generateKeyPair(),
308
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
309
+ signedIdentityKey: identityKey,
310
+ signedPreKey: signedKeyPair(identityKey, 1),
311
+ registrationId: generateRegistrationId(),
312
+ advSecretKey: randomBytes(32).toString('base64'),
313
+ processedHistoryMessages: [],
314
+ nextPreKeyId: 1,
315
+ firstUnuploadedPreKeyId: 1,
316
+ accountSyncCounter: 0,
317
+ accountSettings: { unarchiveChats: false },
318
+ registered: false,
319
+ pairingCode: undefined,
320
+ lastPropHash: undefined,
321
+ routingInfo: undefined,
322
+ additionalData: undefined
323
+ }
324
+ }
325
+
326
+ export async function handleIdentityChange(node, ctx) {
327
+ const from = node.attrs.from
328
+ if (!from) return { action: 'invalid_notification' }
329
+
330
+ const identityNode = getBinaryNodeChild(node, 'identity')
331
+ if (!identityNode) return { action: 'no_identity_node' }
332
+
333
+ ctx.logger.info({ jid: from }, 'identity changed')
334
+ const decoded = jidDecode(from)
335
+ if (decoded?.device && decoded.device !== 0) {
336
+ ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device')
337
+ return { action: 'skipped_companion_device', device: decoded.device }
338
+ }
339
+
340
+ const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)))
341
+ if (isSelfPrimary) {
342
+ ctx.logger.info({ jid: from }, 'self primary identity changed')
343
+ return { action: 'skipped_self_primary' }
344
+ }
345
+
346
+ if (ctx.debounceCache.get(from)) {
347
+ ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)')
348
+ return { action: 'debounced' }
349
+ }
350
+ ctx.debounceCache.set(from, true)
351
+
352
+ const isOfflineNotification = !isStringNullOrEmptyLocal(node.attrs.offline)
353
+ const hasExistingSession = await ctx.validateSession(from)
354
+ if (!hasExistingSession.exists) {
355
+ ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh')
356
+ return { action: 'skipped_no_session' }
357
+ }
358
+
359
+ ctx.logger.debug({ jid: from }, 'old session exists, will refresh session')
360
+ if (isOfflineNotification) {
361
+ ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing')
362
+ return { action: 'skipped_offline' }
363
+ }
364
+
365
+ ctx.onBeforeSessionRefresh?.(from)
366
+ try {
367
+ await ctx.assertSessions([from], true)
368
+ return { action: 'session_refreshed' }
369
+ } catch (error) {
370
+ ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change')
371
+ return { action: 'session_refresh_failed', error }
372
+ }
373
+ }
374
+
375
+ function isStringNullOrEmptyLocal(value) {
376
+
377
+ return value == null || value === ''
378
+ }
379
+
380
+ export const getDecryptionJid = async (sender, repository) => {
381
+ if (isLidUser(sender) || isHostedLidUser(sender)) return sender
382
+ const mapped = await repository.lidMapping.getLIDForPN(sender)
383
+ return mapped || sender
384
+ }
385
+
386
+ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
387
+ const { senderAlt } = extractAddressingContext(stanza)
388
+ if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
389
+ try {
390
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }])
391
+ await repository.migrateSession(sender, senderAlt)
392
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope')
393
+ } catch (error) {
394
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping')
395
+ }
396
+ }
397
+ }
398
+
399
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node'
400
+ export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled'
401
+ export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted'
402
+
403
+ export const DECRYPTION_RETRY_CONFIG = {
404
+ maxRetries: 3,
405
+ baseDelayMs: 100,
406
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
407
+ }
408
+
409
+ export const NACK_REASONS = {
410
+ SenderReachoutTimelocked: 463,
411
+ ParsingError: 487,
412
+ UnrecognizedStanza: 488,
413
+ UnrecognizedStanzaClass: 489,
414
+ UnrecognizedStanzaType: 490,
415
+ InvalidProtobuf: 491,
416
+ InvalidHostedCompanionStanza: 493,
417
+ MissingMessageSecret: 495,
418
+ SignalErrorOldCounter: 496,
419
+ MessageDeletedOnPeer: 499,
420
+ UnhandledError: 500,
421
+ UnsupportedAdminRevoke: 550,
422
+ UnsupportedLIDGroup: 551,
423
+ DBOperationFailed: 552
424
+ }
425
+
426
+ export const SERVER_ERROR_CODES = {
427
+ MessageAccountRestriction: '463',
428
+ SmaxInvalid: '479'
429
+ }
430
+
431
+ export const extractAddressingContext = stanza => {
432
+ let senderAlt
433
+ let recipientAlt
434
+ const sender = stanza.attrs.participant || stanza.attrs.from
435
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn')
436
+ if (addressingMode === 'lid') {
437
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn
438
+ recipientAlt = stanza.attrs.recipient_pn
439
+ } else {
440
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid
441
+ recipientAlt = stanza.attrs.recipient_lid
442
+ }
443
+ return { addressingMode, senderAlt, recipientAlt }
444
+ }
445
+
446
+ export function decodeMessageNode(stanza, meId, meLid) {
447
+ let msgType
448
+ let chatId
449
+ let author
450
+ let fromMe = false
451
+ const msgId = stanza.attrs.id
452
+ const from = stanza.attrs.from
453
+ const participant = stanza.attrs.participant
454
+ const recipient = stanza.attrs.recipient
455
+
456
+ if (!msgId) throw new Boom('Invalid message stanza: missing id attribute', { data: stanza })
457
+ if (!from) throw new Boom('Invalid message stanza: missing from attribute', { data: stanza })
458
+
459
+ const addressingContext = extractAddressingContext(stanza)
460
+ const isMe = jid => areJidsSameUser(jid, meId)
461
+ const isMeLid = jid => areJidsSameUser(jid, meLid)
462
+
463
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
464
+ if (recipient && !isJidMetaAI(recipient)) {
465
+ if (!isMe(from) && !isMeLid(from)) throw new Boom('receipient present, but msg not from me', { data: stanza })
466
+ if (isMe(from) || isMeLid(from)) fromMe = true
467
+ chatId = recipient
468
+ } else {
469
+
470
+ if (isMe(from) || isMeLid(from)) fromMe = true
471
+ chatId = from
472
+ }
473
+ msgType = 'chat'
474
+ author = from
475
+ } else if (isJidGroup(from)) {
476
+ if (!participant) throw new Boom('No participant in group message')
477
+ if (isMe(participant) || isMeLid(participant)) fromMe = true
478
+ msgType = 'group'
479
+ author = participant
480
+ chatId = from
481
+ } else if (isJidBroadcast(from)) {
482
+ if (!participant) throw new Boom('No participant in group message')
483
+ const isParticipantMe = isMe(participant)
484
+ msgType = isJidStatusBroadcast(from)
485
+ ? isParticipantMe
486
+ ? 'direct_peer_status'
487
+ : 'other_status'
488
+ : isParticipantMe
489
+ ? 'peer_broadcast'
490
+ : 'other_broadcast'
491
+ fromMe = isParticipantMe
492
+ chatId = from
493
+ author = participant
494
+ } else if (isJidNewsletter(from)) {
495
+ msgType = 'newsletter'
496
+ chatId = from
497
+ author = from
498
+ if (isMe(from) || isMeLid(from)) fromMe = true
499
+ } else {
500
+ throw new Boom('Unknown message type', { data: stanza })
501
+ }
502
+
503
+ const pushname = stanza?.attrs?.notify
504
+ const key = {
505
+ remoteJid: chatId,
506
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
507
+ remoteJidUsername: !isJidGroup(chatId) ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username : undefined,
508
+ fromMe,
509
+ id: msgId,
510
+ participant,
511
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
512
+ participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
513
+ addressingMode: addressingContext.addressingMode,
514
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
515
+ }
516
+ const fullMessage = {
517
+ key,
518
+ category: stanza.attrs.category,
519
+ messageTimestamp: +stanza.attrs.t,
520
+ pushName: pushname,
521
+ broadcast: isJidBroadcast(from)
522
+ }
523
+ if (key.fromMe) fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK
524
+
525
+ return { fullMessage, author, sender: msgType === 'chat' ? author : chatId }
526
+ }
527
+
528
+ function isSessionRecordError(error) {
529
+ const errorMessage = error?.message || error?.toString() || ''
530
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(pattern => errorMessage.includes(pattern))
531
+ }
532
+
533
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
534
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
535
+ return {
536
+ fullMessage,
537
+ category: stanza.attrs.category,
538
+ author,
539
+ async decrypt() {
540
+ let decryptables = 0
541
+ if (Array.isArray(stanza.content)) {
542
+ for (const { tag, attrs, content } of stanza.content) {
543
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
544
+ const cert = proto.VerifiedNameCertificate.decode(content)
545
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details)
546
+ fullMessage.verifiedBizName = details.verifiedName
547
+ }
548
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
549
+ fullMessage.key.isViewOnce = true
550
+ }
551
+ if (attrs.count && tag === 'enc') fullMessage.retryCount = Number(attrs.count)
552
+ if (tag !== 'enc' && tag !== 'plaintext') continue
553
+ if (!(content instanceof Uint8Array)) continue
554
+
555
+ decryptables += 1
556
+ let msgBuffer
557
+ const decryptionJid = await getDecryptionJid(author, repository)
558
+ if (tag !== 'plaintext') {
559
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger)
560
+ }
561
+ try {
562
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type
563
+ switch (e2eType) {
564
+ case 'skmsg':
565
+ msgBuffer = await repository.decryptGroupMessage({ group: sender, authorJid: author, msg: content })
566
+ break
567
+ case 'pkmsg':
568
+ case 'msg':
569
+ msgBuffer = await repository.decryptMessage({ jid: decryptionJid, type: e2eType, ciphertext: content })
570
+ break
571
+ case 'plaintext':
572
+ msgBuffer = content
573
+ break
574
+ default:
575
+ throw new Error(`Unknown e2e type: ${e2eType}`)
576
+ }
577
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer)
578
+ msg = msg.deviceSentMessage?.message || msg
579
+ if (msg.senderKeyDistributionMessage) {
580
+ try {
581
+ await repository.processSenderKeyDistributionMessage({ authorJid: author, item: msg.senderKeyDistributionMessage })
582
+ } catch (err) {
583
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message')
584
+ }
585
+ }
586
+ if (fullMessage.message) Object.assign(fullMessage.message, msg)
587
+ else fullMessage.message = msg
588
+ } catch (err) {
589
+ logger.error(
590
+ {
591
+ key: fullMessage.key,
592
+ err,
593
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
594
+ sender,
595
+ author,
596
+ isSessionRecordError: isSessionRecordError(err)
597
+ },
598
+ 'failed to decrypt message'
599
+ )
600
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
601
+ fullMessage.messageStubParameters = [err.message.toString()]
602
+ }
603
+ }
604
+ }
605
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
606
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT
607
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT]
608
+ }
609
+ }
610
+ }
611
+ }
612
+
613
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
614
+
615
+ function isRegularUser(jid) {
616
+ if (!jid) return false
617
+ const user = jid.split('@')[0] ?? ''
618
+ if (user === '0') return false
619
+ if (BOT_PHONE_REGEX.test(user)) return false
620
+ if (isJidMetaAI(jid)) return false
621
+ return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'))
622
+ }
623
+
624
+ const TC_TOKEN_BUCKET_DURATION = 604800
625
+ const TC_TOKEN_NUM_BUCKETS = 4
626
+
627
+ export const TC_TOKEN_INDEX_KEY = '__index'
628
+
629
+ export async function readTcTokenIndex(keys) {
630
+ const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY])
631
+ const entry = data[TC_TOKEN_INDEX_KEY]
632
+ if (!entry?.token?.length) return []
633
+ try {
634
+ const parsed = JSON.parse(Buffer.from(entry.token).toString())
635
+ if (!Array.isArray(parsed)) return []
636
+ return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY)
637
+ } catch {
638
+ return []
639
+ }
640
+ }
641
+
642
+ export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
643
+ const persisted = await readTcTokenIndex(keys)
644
+ const merged = new Set(persisted)
645
+ for (const jid of addedJids) {
646
+ if (jid && jid !== TC_TOKEN_INDEX_KEY) merged.add(jid)
647
+ }
648
+ return { [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) } }
649
+ }
650
+
651
+ export function isTcTokenExpired(timestamp) {
652
+ if (timestamp === null || timestamp === undefined) return true
653
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
654
+ if (isNaN(ts)) return true
655
+ const now = Math.floor(Date.now() / 1000)
656
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION)
657
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1)
658
+ return ts < cutoffBucket * TC_TOKEN_BUCKET_DURATION
659
+ }
660
+
661
+ export function shouldSendNewTcToken(senderTimestamp) {
662
+ if (senderTimestamp === undefined) return true
663
+ const now = Math.floor(Date.now() / 1000)
664
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION)
665
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION)
666
+ return currentBucket > senderBucket
667
+ }
668
+
669
+ export async function resolveTcTokenJid(jid, getLIDForPN) {
670
+ if (isLidUser(jid)) return jid
671
+ const lid = await getLIDForPN(jid)
672
+ return lid ?? jid
673
+ }
674
+
675
+ export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
676
+ if (issueToLid) {
677
+ if (isLidUser(jid)) return jid
678
+ const lid = await getLIDForPN(jid)
679
+ return lid ?? jid
680
+ }
681
+ if (!isLidUser(jid)) return jid
682
+ if (getPNForLID) {
683
+ const pn = await getPNForLID(jid)
684
+ return pn ?? jid
685
+ }
686
+ return jid
687
+ }
688
+
689
+ export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
690
+ try {
691
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
692
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid])
693
+ const entry = tcTokenData?.[storageJid]
694
+ const tcTokenBuffer = entry?.token
695
+ const timestamp = entry?.timestamp
696
+ if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
697
+ if (tcTokenBuffer) {
698
+ const cleared = entry?.senderTimestamp !== undefined ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp } : null
699
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } })
700
+ }
701
+ return baseContent.length > 0 ? baseContent : undefined
702
+ }
703
+ baseContent.push({ tag: 'tctoken', attrs: { t: String(timestamp) }, content: tcTokenBuffer })
704
+ return baseContent
705
+ } catch {
706
+ return baseContent.length > 0 ? baseContent : undefined
707
+ }
708
+ }
709
+
710
+ export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
711
+ const tokensNode = getBinaryNodeChild(result, 'tokens')
712
+ if (!tokensNode) return
713
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token')
714
+ for (const tokenNode of tokenNodes) {
715
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) continue
716
+
717
+ const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid)
718
+ if (!isRegularUser(rawJid)) continue
719
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
720
+ const existingTcData = await keys.get('tctoken', [storageJid])
721
+ const existingEntry = existingTcData[storageJid]
722
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
723
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
724
+ if (!incomingTs) continue
725
+ if (existingTs > 0 && existingTs > incomingTs) continue
726
+ await keys.set({
727
+ tctoken: { [storageJid]: { ...existingEntry, token: Buffer.from(tokenNode.content), timestamp: tokenNode.attrs.t } }
728
+ })
729
+ onNewJidStored?.(storageJid)
730
+ }
731
+ }