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