@badzz88/baileys 8.5.4 → 8.5.5

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 (107) hide show
  1. package/README.md +1 -1
  2. package/WAProto/WAProto.proto +75 -1256
  3. package/WAProto/index.d.ts +19729 -36122
  4. package/WAProto/index.js +132193 -178538
  5. package/engine-requirements.js +15 -7
  6. package/lib/Defaults/index.js +14 -22
  7. package/lib/Signal/Group/group_cipher.js +5 -5
  8. package/lib/Signal/Group/keyhelper.js +4 -4
  9. package/lib/Signal/Group/sender-chain-key.js +2 -2
  10. package/lib/Signal/Group/sender-key-distribution-message.js +1 -1
  11. package/lib/Signal/Group/sender-key-message.js +3 -3
  12. package/lib/Signal/Group/sender-key-record.js +1 -1
  13. package/lib/Signal/Group/sender-message-key.js +5 -5
  14. package/lib/Signal/libsignal.js +28 -39
  15. package/lib/Signal/lid-mapping.js +8 -28
  16. package/lib/Socket/aigroups.js +5 -5
  17. package/lib/Socket/business.js +11 -3
  18. package/lib/Socket/chats.js +319 -668
  19. package/lib/Socket/communities.js +89 -85
  20. package/lib/Socket/graphql.js +228 -435
  21. package/lib/Socket/groups.js +211 -132
  22. package/lib/Socket/index.js +7 -9
  23. package/lib/Socket/interactive-handler.js +60 -117
  24. package/lib/Socket/interop.js +175 -56
  25. package/lib/Socket/luxu.js +387 -0
  26. package/lib/Socket/managed-account.js +48 -79
  27. package/lib/Socket/messages-recv.js +340 -898
  28. package/lib/Socket/messages-send.js +160 -462
  29. package/lib/Socket/mex.js +53 -40
  30. package/lib/Socket/newsletter.js +295 -291
  31. package/lib/Socket/privacy.js +265 -77
  32. package/lib/Socket/registration.js +157 -164
  33. package/lib/Socket/socket.js +199 -181
  34. package/lib/Socket/text-router.js +83 -0
  35. package/lib/Socket/username.js +227 -144
  36. package/lib/Store/keyed-db.js +108 -0
  37. package/lib/Store/make-cache-manager-store.js +2 -2
  38. package/lib/Store/make-in-memory-store.js +141 -25
  39. package/lib/Types/Auth.js +3 -3
  40. package/lib/Types/Label.js +1 -1
  41. package/lib/Types/LabelAssociation.js +1 -1
  42. package/lib/Types/Mex.js +112 -0
  43. package/lib/Types/Newsletter.js +65 -96
  44. package/lib/Types/State.js +4 -4
  45. package/lib/Types/index.js +1 -1
  46. package/lib/Utils/auth-utils.js +57 -52
  47. package/lib/Utils/browser-utils.js +1 -1
  48. package/lib/Utils/business.js +6 -2
  49. package/lib/Utils/chat-utils.js +38 -102
  50. package/lib/Utils/command-loader.d.ts +31 -0
  51. package/lib/Utils/command-loader.js +100 -0
  52. package/lib/Utils/companion-reg-client-utils.js +42 -0
  53. package/lib/Utils/crypto.js +84 -54
  54. package/lib/Utils/curve25519-js.js +275 -0
  55. package/lib/Utils/decode-wa-message.js +83 -316
  56. package/lib/Utils/event-buffer.js +61 -37
  57. package/lib/Utils/generics.js +103 -157
  58. package/lib/Utils/group-history.js +12 -3
  59. package/lib/Utils/history.js +15 -15
  60. package/lib/Utils/index.js +5 -1
  61. package/lib/Utils/link-preview.js +8 -3
  62. package/lib/Utils/lt-hash.js +35 -2
  63. package/lib/Utils/make-mutex.js +1 -1
  64. package/lib/Utils/message-retry-manager.js +92 -27
  65. package/lib/Utils/messages-media.js +130 -159
  66. package/lib/Utils/messages.js +566 -144
  67. package/lib/Utils/meta-ai-msmsg.js +202 -62
  68. package/lib/Utils/native-bridge.js +82 -0
  69. package/lib/Utils/noise-handler.js +21 -19
  70. package/lib/Utils/offline-node-processor.js +8 -3
  71. package/lib/Utils/pre-key-manager.js +23 -13
  72. package/lib/Utils/process-message.js +106 -197
  73. package/lib/Utils/reporting-utils.js +2 -2
  74. package/lib/Utils/session-pool.d.ts +16 -0
  75. package/lib/Utils/session-pool.js +94 -0
  76. package/lib/Utils/signal.js +63 -28
  77. package/lib/Utils/stanza-ack.js +12 -39
  78. package/lib/Utils/sticker.d.ts +17 -0
  79. package/lib/Utils/sticker.js +145 -0
  80. package/lib/Utils/sync-action-utils.js +7 -4
  81. package/lib/Utils/tc-token-utils.js +25 -20
  82. package/lib/Utils/use-multi-file-auth-state.js +14 -30
  83. package/lib/Utils/validate-connection.js +19 -59
  84. package/lib/Utils/view-once-cache.d.ts +9 -0
  85. package/lib/Utils/view-once-cache.js +79 -0
  86. package/lib/WABinary/decode.js +16 -50
  87. package/lib/WABinary/encode.js +224 -54
  88. package/lib/WABinary/generic-utils.js +97 -7
  89. package/lib/WABinary/jid-utils.js +14 -27
  90. package/lib/WAM/encode.js +7 -7
  91. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +1 -58
  92. package/lib/WAUSync/Protocols/USyncContactProtocol.js +1 -7
  93. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +5 -13
  94. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +4 -1
  95. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +7 -20
  96. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +1 -1
  97. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +2 -2
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +2 -7
  99. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +1 -1
  100. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +1 -2
  101. package/lib/WAUSync/Protocols/index.js +0 -1
  102. package/lib/WAUSync/USyncQuery.js +6 -77
  103. package/lib/WAUSync/USyncUser.js +8 -16
  104. package/lib/WAUSync/index.js +0 -1
  105. package/lib/antiban.js +854 -608
  106. package/lib/index.js +1 -1
  107. package/package.json +20 -16
@@ -1,122 +1,262 @@
1
1
  'use strict'
2
2
 
3
- const rb = require('whatsapp-rust-bridge')
3
+ const Crypto_1 = require('./crypto')
4
4
  const { proto } = require('../../WAProto')
5
5
 
6
6
  const BOT_MESSAGE_INFO = 'Bot Message'
7
7
  const KEY_LENGTH = 32
8
+ const AUTH_TAG_LENGTH = 16
9
+
10
+ const MSG_ID_HEX_RE = /^[0-9A-Fa-f]{32}$/
8
11
 
9
12
  const unpadRandomMax16 = value => {
10
13
  const bytes = new Uint8Array(value)
11
14
  if (!bytes.length) {
12
15
  throw new Error('unpadPkcs7 given empty bytes')
13
16
  }
17
+
14
18
  const padLength = bytes[bytes.length - 1]
15
19
  if (padLength > bytes.length) {
16
20
  throw new Error(`unpad given ${bytes.length} bytes, but pad is ${padLength}`)
17
21
  }
22
+
18
23
  return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length - padLength)
19
24
  }
20
25
 
21
26
  const toBuffer = value => {
22
- if (Buffer.isBuffer(value)) return value
23
- if (value instanceof Uint8Array) return Buffer.from(value.buffer, value.byteOffset, value.byteLength)
24
- return Buffer.from(value)
25
- }
27
+ if (Buffer.isBuffer(value)) {
28
+ return value
29
+ }
26
30
 
31
+ if (value instanceof Uint8Array) {
32
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength)
33
+ }
27
34
 
35
+ return Buffer.from(value)
36
+ }
28
37
 
29
38
  const normalizeLidJid = jid => {
30
- if (!jid || !jid.endsWith('@lid') || !jid.includes(':')) return jid
39
+ if (!jid || !jid.endsWith('@lid') || !jid.includes(':')) {
40
+ return jid
41
+ }
42
+
31
43
  return `${jid.split(':')[0]}@lid`
32
44
  }
33
45
 
46
+ const buildMessageIdRepresentations = messageId => {
47
+ const ascii = Buffer.from(messageId)
48
+ const binary = MSG_ID_HEX_RE.test(messageId) ? Buffer.from(messageId, 'hex') : ascii
49
+ return [
50
+ { label: 'msgIdAscii', value: ascii },
51
+ ...(binary.equals(ascii) ? [] : [{ label: 'msgIdBinary', value: binary }])
52
+ ]
53
+ }
34
54
 
55
+ const pushUnique = (items, seen, item) => {
56
+ const key = JSON.stringify([
57
+ item.messageId,
58
+ item.idSource,
59
+ item.idSources,
60
+ item.infoSource,
61
+ item.aadSource,
62
+ item.info.toString('hex'),
63
+ item.aad.toString('hex')
64
+ ])
35
65
 
36
- const selectMsgIdCandidates = messageKey => {
37
- const seen = new Set()
38
- const result = []
39
- for (const id of [messageKey?.botEditTargetId, messageKey?.stanzaId, messageKey?.metaTargetId]) {
40
- const s = id ? String(id) : ''
41
- if (s && !seen.has(s)) {
42
- seen.add(s)
43
- result.push(s)
66
+ if (!seen.has(key)) {
67
+ seen.add(key)
68
+ items.push(item)
69
+ }
70
+ }
71
+
72
+ const getCandidateIds = messageKey => {
73
+ const orderedCandidates = [
74
+ messageKey?.botType === 'full'
75
+ ? { source: 'stanzaId', messageId: messageKey?.stanzaId }
76
+ : { source: 'botEditTargetId', messageId: messageKey?.botEditTargetId },
77
+ { source: 'targetId', messageId: messageKey?.targetId },
78
+ { source: 'metaTargetId', messageId: messageKey?.metaTargetId },
79
+ { source: 'stanzaId', messageId: messageKey?.stanzaId }
80
+ ]
81
+
82
+ const targetIdCandidates = Array.isArray(messageKey?.targetIdCandidates) ? messageKey.targetIdCandidates : []
83
+ for (let index = 0; index < targetIdCandidates.length; index += 1) {
84
+ orderedCandidates.push({
85
+ source: `targetIdCandidates[${index}]`,
86
+ messageId: targetIdCandidates[index]
87
+ })
88
+ }
89
+
90
+ const grouped = new Map()
91
+ for (const candidate of orderedCandidates) {
92
+ if (!candidate.messageId) {
93
+ continue
94
+ }
95
+
96
+ const messageId = String(candidate.messageId)
97
+ const existing = grouped.get(messageId)
98
+ if (existing) {
99
+ if (!existing.idSources.includes(candidate.source)) {
100
+ existing.idSources.push(candidate.source)
101
+ }
102
+ } else {
103
+ grouped.set(messageId, {
104
+ messageId,
105
+ idSource: candidate.source,
106
+ idSources: [candidate.source]
107
+ })
44
108
  }
45
109
  }
46
- return result
110
+
111
+ return Array.from(grouped.values())
47
112
  }
48
113
 
114
+ const getJidCandidates = messageKey => {
115
+ const ordered = [
116
+ { source: 'meId', jid: messageKey?.meId },
117
+ { source: 'conversationJid', jid: messageKey?.conversationJid },
118
+ { source: 'senderJid', jid: messageKey?.senderJid },
119
+ { source: 'meLidNormalized', jid: normalizeLidJid(messageKey?.meLid) }
120
+ ]
49
121
 
122
+ const seen = new Set()
123
+ const candidates = []
124
+ for (const candidate of ordered) {
125
+ if (!candidate.jid) {
126
+ continue
127
+ }
50
128
 
51
- const selectTargetJidCandidates = messageKey => {
129
+ const jid = String(candidate.jid)
130
+ if (!seen.has(jid)) {
131
+ seen.add(jid)
132
+ candidates.push({ source: candidate.source, jid, value: Buffer.from(jid) })
133
+ }
134
+ }
135
+
136
+ return candidates
137
+ }
138
+
139
+ const buildMsmsgDecryptionStrategies = messageKey => {
140
+ const botJid = String(messageKey?.participant || '')
141
+ const botJidBuffer = Buffer.from(botJid)
142
+ const targetIds = getCandidateIds(messageKey)
143
+ const jidCandidates = getJidCandidates(messageKey)
144
+ const primaryJid = jidCandidates[0]
145
+ const alternateJid = jidCandidates.find(
146
+ candidate => candidate.source !== primaryJid?.source && candidate.jid !== botJid
147
+ )
148
+ const strategies = []
52
149
  const seen = new Set()
53
- const result = []
54
- for (const jid of [normalizeLidJid(messageKey?.meId), normalizeLidJid(messageKey?.meLid)]) {
55
- const s = jid ? String(jid) : ''
56
- if (s && !seen.has(s)) {
57
- seen.add(s)
58
- result.push(s)
150
+
151
+ for (const idCandidate of targetIds) {
152
+ const idForms = buildMessageIdRepresentations(idCandidate.messageId)
153
+ for (const idForm of idForms) {
154
+ pushUnique(strategies, seen, {
155
+ mode: '2step',
156
+ idSource: idCandidate.idSource,
157
+ idSources: idCandidate.idSources,
158
+ infoSource: `${idForm.label}+meId+botJid`,
159
+ aadSource: `${idForm.label}+0+botJid`,
160
+ authTagLayout: 'trailing',
161
+ messageId: idCandidate.messageId,
162
+ info: Buffer.concat([idForm.value, primaryJid.value, botJidBuffer, Buffer.alloc(0)]),
163
+ aad: Buffer.concat([idForm.value, Buffer.from([0]), botJidBuffer]),
164
+ attemptLabel: `${idCandidate.idSource}:${idForm.label}:primary`
165
+ })
166
+
167
+ if (alternateJid) {
168
+ pushUnique(strategies, seen, {
169
+ mode: '2step',
170
+ idSource: idCandidate.idSource,
171
+ idSources: idCandidate.idSources,
172
+ infoSource: `${idForm.label}+${alternateJid.source}+botJid`,
173
+ aadSource: `${idForm.label}+0+${alternateJid.source}`,
174
+ authTagLayout: 'trailing',
175
+ messageId: idCandidate.messageId,
176
+ info: Buffer.concat([idForm.value, alternateJid.value, botJidBuffer, Buffer.alloc(0)]),
177
+ aad: Buffer.concat([idForm.value, Buffer.from([0]), alternateJid.value]),
178
+ attemptLabel: `${idCandidate.idSource}:${idForm.label}:${alternateJid.source}`
179
+ })
180
+ }
59
181
  }
60
182
  }
61
- return result
183
+
184
+ return strategies.slice(0, 12)
185
+ }
186
+
187
+ const assertRequired = (value, label) => {
188
+ if (
189
+ !value ||
190
+ (Buffer.isBuffer(value) && value.length === 0) ||
191
+ (value instanceof Uint8Array && value.byteLength === 0)
192
+ ) {
193
+ throw new Error(`Missing required ${label} for msmsg decryption`)
194
+ }
195
+ }
196
+
197
+ const decryptWithStrategy = (messageSecret, msMsg, strategy) => {
198
+ const baseSecret = Buffer.from(Crypto_1.hkdf(toBuffer(messageSecret), KEY_LENGTH, { info: BOT_MESSAGE_INFO }))
199
+ const key = Buffer.from(Crypto_1.hkdf(baseSecret, KEY_LENGTH, { info: strategy.info }))
200
+ const payload = toBuffer(msMsg.encPayload)
201
+ // ciphertext = payload without last 16 bytes (auth tag) + auth tag appended → standard GCM layout
202
+ const ciphertextWithTag = Buffer.concat([payload.slice(0, -AUTH_TAG_LENGTH), payload.slice(-AUTH_TAG_LENGTH)])
203
+ return Buffer.from(Crypto_1.aesDecryptGCM(ciphertextWithTag, key, toBuffer(msMsg.encIv), strategy.aad))
62
204
  }
63
205
 
64
206
  const decodeDecryptedMsmsgMessage = decrypted => {
65
- const buf = toBuffer(decrypted)
207
+ const messageBuffer = toBuffer(decrypted)
208
+
66
209
  try {
67
- const unpadded = Buffer.from(unpadRandomMax16(buf))
210
+ const unpadded = Buffer.from(unpadRandomMax16(messageBuffer))
68
211
  const decoded = proto.Message.decode(unpadded)
69
- const hasContent = Object.keys(decoded).some(k => k !== 'messageContextInfo' && decoded[k] != null)
70
- if (hasContent) return decoded
212
+ const hasContent = Object.keys(decoded).some(key => key !== 'messageContextInfo' && decoded[key] != null)
213
+ if (hasContent) {
214
+ return decoded
215
+ }
71
216
  } catch {}
72
- return proto.Message.decode(buf)
73
- }
74
217
 
218
+ return proto.Message.decode(messageBuffer)
219
+ }
75
220
 
76
221
  const decryptMsmsgBotMessage = async (messageSecret, messageKey, msMsg) => {
77
- if (!messageSecret || (messageSecret instanceof Uint8Array && !messageSecret.byteLength)) {
78
- throw new Error('Missing required messageSecret for msmsg decryption')
222
+ assertRequired(messageSecret, 'messageSecret')
223
+ assertRequired(messageKey?.participant, 'participant')
224
+ assertRequired(messageKey?.meId, 'meId')
225
+ assertRequired(msMsg?.encIv, 'encIv')
226
+ assertRequired(msMsg?.encPayload, 'encPayload')
227
+ if (getCandidateIds(messageKey).length === 0) {
228
+ throw new Error('Missing required target message id for msmsg decryption')
79
229
  }
80
- if (!messageKey?.participant) throw new Error('Missing required participant for msmsg decryption')
81
- if (!messageKey?.meId) throw new Error('Missing required meId for msmsg decryption')
82
- if (!msMsg?.encIv) throw new Error('Missing required encIv for msmsg decryption')
83
- if (!msMsg?.encPayload) throw new Error('Missing required encPayload for msmsg decryption')
84
-
85
- const msgIdCandidates = selectMsgIdCandidates(messageKey)
86
- if (!msgIdCandidates.length) throw new Error('Missing required target message id for msmsg decryption')
87
230
 
88
- const targetJidCandidates = selectTargetJidCandidates(messageKey)
89
- if (!targetJidCandidates.length) throw new Error('Missing required target JID for msmsg decryption')
90
-
91
- const botJidBuf = Buffer.from(String(messageKey.participant))
92
- const payload = toBuffer(msMsg.encPayload)
93
- const iv = toBuffer(msMsg.encIv)
231
+ const strategies = buildMsmsgDecryptionStrategies(messageKey)
232
+ const attemptedStrategies = []
233
+ let lastError
94
234
 
95
-
96
- const baseKey = Buffer.from(rb.hkdf(toBuffer(messageSecret), KEY_LENGTH, { info: BOT_MESSAGE_INFO }))
235
+ for (const strategy of strategies) {
236
+ const attempt = {
237
+ idSource: strategy.idSource,
238
+ idSources: strategy.idSources,
239
+ infoSource: strategy.infoSource,
240
+ aadSource: strategy.aadSource,
241
+ messageId: strategy.messageId
242
+ }
97
243
 
98
- let lastError
99
- for (const msgId of msgIdCandidates) {
100
-
101
- const idBuf = Buffer.from(msgId)
102
- for (const targetJid of targetJidCandidates) {
103
- const info = Buffer.concat([idBuf, Buffer.from(targetJid), botJidBuf])
104
- const key = Buffer.from(rb.hkdf(baseKey, KEY_LENGTH, { info }))
105
- const aad = Buffer.concat([idBuf, Buffer.from([0x00]), botJidBuf])
106
- try {
107
- return Buffer.from(rb.aesDecryptGCM(payload, key, iv, aad))
108
- } catch (e) {
109
- lastError = e
110
- }
244
+ try {
245
+ return await decryptWithStrategy(messageSecret, msMsg, strategy)
246
+ } catch (error) {
247
+ attemptedStrategies.push(attempt)
248
+ lastError = error
111
249
  }
112
250
  }
113
251
 
114
- const err = new Error('msmsg decryption failed: all key derivation candidates exhausted')
115
- err.cause = lastError
116
- throw err
252
+ const error = new Error('Failed to decrypt msmsg with bounded deterministic strategies')
253
+ error.attemptedStrategies = attemptedStrategies
254
+ error.cause = lastError
255
+ throw error
117
256
  }
118
257
 
119
258
  module.exports = {
259
+ buildMsmsgDecryptionStrategies,
120
260
  decodeDecryptedMsmsgMessage,
121
261
  decryptMsmsgBotMessage
122
262
  }
@@ -0,0 +1,82 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.loadRustBridge = void 0
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+
7
+ const BRIDGE_NAME = 'whatsapp-rust-bridge'
8
+ let cached
9
+ let attempted = false
10
+
11
+ /**
12
+ * Finds the installed package directory for `pkgName` by walking the same
13
+ * node_modules search path Node itself would use, without going through
14
+ * Node's package "exports" resolution gate.
15
+ */
16
+ const findPackageDir = pkgName => {
17
+ let searchPaths
18
+ try {
19
+ searchPaths = require.resolve.paths(pkgName) || []
20
+ } catch {
21
+ searchPaths = []
22
+ }
23
+ for (const dir of searchPaths) {
24
+ const candidate = path.join(dir, pkgName)
25
+ if (fs.existsSync(path.join(candidate, 'package.json'))) {
26
+ return candidate
27
+ }
28
+ }
29
+ return null
30
+ }
31
+
32
+ /**
33
+ * Loads whatsapp-rust-bridge, tolerating published versions/forks whose
34
+ * package.json ships an "exports" map with no "." entry (or an otherwise
35
+ * broken one) -- which makes a plain `require('whatsapp-rust-bridge')` throw
36
+ * ERR_PACKAGE_PATH_NOT_EXPORTED even though the module's files are present
37
+ * and perfectly usable. In that case, we locate the package directory
38
+ * ourselves and require its real entry file directly, bypassing the broken
39
+ * "exports" gate. Returns the loaded module, or null if it's unavailable.
40
+ */
41
+ const loadRustBridge = () => {
42
+ if (attempted) return cached
43
+ attempted = true
44
+ try {
45
+ cached = require(BRIDGE_NAME)
46
+ return cached
47
+ } catch (error) {
48
+ const recoverableCodes = new Set(['ERR_PACKAGE_PATH_NOT_EXPORTED', 'ERR_PACKAGE_IMPORT_NOT_DEFINED'])
49
+ if (!recoverableCodes.has(error?.code)) {
50
+ cached = null
51
+ return null
52
+ }
53
+ try {
54
+ const dir = findPackageDir(BRIDGE_NAME)
55
+ if (!dir) {
56
+ cached = null
57
+ return null
58
+ }
59
+ const pkgJson = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'))
60
+ const candidates = [
61
+ pkgJson.main,
62
+ 'index.js',
63
+ 'index.node',
64
+ 'dist/index.js',
65
+ 'lib/index.js',
66
+ 'build/index.js'
67
+ ].filter(Boolean)
68
+ for (const rel of candidates) {
69
+ const fullPath = path.join(dir, rel)
70
+ if (fs.existsSync(fullPath)) {
71
+ cached = require(fullPath)
72
+ return cached
73
+ }
74
+ }
75
+ } catch {
76
+ // fall through to returning null below
77
+ }
78
+ cached = null
79
+ return null
80
+ }
81
+ }
82
+ exports.loadRustBridge = loadRustBridge
@@ -4,15 +4,15 @@ exports.makeNoiseHandler = void 0
4
4
  const boom_1 = require('@hapi/boom')
5
5
  const index_js_1 = require('../../WAProto/index.js')
6
6
  const Defaults_1 = require('../Defaults')
7
- const rb = require('whatsapp-rust-bridge')
8
-
7
+ const rb = require('./native-bridge').loadRustBridge()
9
8
 
9
+ // rustNodeToJs mirrors the one in decode.js — converts InternalBinaryNode to plain JS object
10
10
  const rustNodeToJs = node => {
11
11
  if (!node || typeof node !== 'object') return node
12
12
  const result = { tag: node.tag, attrs: node.attrs || {} }
13
13
  const content = node.content
14
14
  if (content === undefined || content === null) {
15
-
15
+ // no content
16
16
  } else if (content instanceof Uint8Array) {
17
17
  result.content = Buffer.from(content)
18
18
  } else if (typeof content === 'string') {
@@ -33,6 +33,14 @@ const makeNoiseHandler = ({
33
33
  }) => {
34
34
  logger = logger.child({ class: 'ns' })
35
35
 
36
+ if (!rb) {
37
+ throw new Error(
38
+ 'Establishing a WhatsApp connection requires the "whatsapp-rust-bridge" native module ' +
39
+ '(Noise protocol handshake + session), which failed to load. Make sure it is installed: ' +
40
+ 'npm install whatsapp-rust-bridge@0.5.4'
41
+ )
42
+ }
43
+
36
44
  const session = new rb.NoiseSession(
37
45
  publicKey instanceof Uint8Array ? publicKey : new Uint8Array(publicKey),
38
46
  NOISE_HEADER instanceof Uint8Array ? NOISE_HEADER : new Uint8Array(NOISE_HEADER),
@@ -44,7 +52,7 @@ const makeNoiseHandler = ({
44
52
  let pendingBytes = null
45
53
 
46
54
  const processFrames = async onFrame => {
47
-
55
+ // decodeFrame returns an Array of InternalBinaryNode (post-handshake) or Uint8Array (handshake)
48
56
  const frames = session.decodeFrame(new Uint8Array(0))
49
57
  for (let i = 0; i < frames.length; i++) {
50
58
  const item = frames[i]
@@ -85,7 +93,7 @@ const makeNoiseHandler = ({
85
93
  } else {
86
94
  try {
87
95
  frame = rustNodeToJs(item.toJSON())
88
- } catch {
96
+ } catch (e) {
89
97
  continue
90
98
  }
91
99
  }
@@ -111,7 +119,7 @@ const makeNoiseHandler = ({
111
119
  },
112
120
  finishInit,
113
121
  processHandshake: ({ serverHello }, noiseKey) => {
114
-
122
+ // Rust handles the crypto: authenticate ephemeral, ECDH, decrypt static+payload
115
123
  const certPayload = session.processHandshakeInit(
116
124
  serverHello.ephemeral,
117
125
  serverHello.static,
@@ -119,7 +127,7 @@ const makeNoiseHandler = ({
119
127
  privateKey instanceof Uint8Array ? privateKey : new Uint8Array(privateKey)
120
128
  )
121
129
 
122
-
130
+ // Certificate validation stays in JS (uses protobuf + WA-specific constants)
123
131
  const { intermediate: certIntermediate, leaf } = index_js_1.proto.CertChain.decode(certPayload)
124
132
  if (!leaf?.details || !leaf?.signature) {
125
133
  throw new boom_1.Boom('invalid noise leaf certificate', { statusCode: 400 })
@@ -140,20 +148,13 @@ const makeNoiseHandler = ({
140
148
  throw new boom_1.Boom('certification match failed', { statusCode: 400 })
141
149
  }
142
150
 
143
-
144
- let serverStaticPub
145
- try {
146
- const leafDetails = index_js_1.proto.CertChain.NoiseCertificate.Details.decode(leaf.details)
147
- if (leafDetails.key?.length === 32) serverStaticPub = Buffer.from(leafDetails.key)
148
- } catch {}
149
-
150
-
151
+ // Encrypt our static key and do final ECDH
151
152
  const keyEnc = session.processHandshakeFinish(
152
153
  noiseKey.public instanceof Uint8Array ? noiseKey.public : new Uint8Array(noiseKey.public),
153
154
  noiseKey.private instanceof Uint8Array ? noiseKey.private : new Uint8Array(noiseKey.private),
154
155
  serverHello.ephemeral
155
156
  )
156
- return { keyEnc: Buffer.from(keyEnc), serverStaticPub }
157
+ return Buffer.from(keyEnc)
157
158
  },
158
159
  encodeFrame: data => {
159
160
  const u8 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
@@ -161,13 +162,14 @@ const makeNoiseHandler = ({
161
162
  },
162
163
  decodeFrame: async (newData, onFrame) => {
163
164
  if (isWaitingForTransport) {
164
- pendingBytes = pendingBytes ? Buffer.concat([pendingBytes, Buffer.from(newData)]) : Buffer.from(newData)
165
+ pendingBytes = pendingBytes
166
+ ? Buffer.concat([pendingBytes, Buffer.from(newData)])
167
+ : Buffer.from(newData)
165
168
  pendingOnFrame = onFrame
166
169
  return
167
170
  }
168
171
 
169
- const u8 =
170
- newData instanceof Uint8Array ? newData : new Uint8Array(newData.buffer, newData.byteOffset, newData.byteLength)
172
+ const u8 = newData instanceof Uint8Array ? newData : new Uint8Array(newData.buffer, newData.byteOffset, newData.byteLength)
171
173
  const frames = session.decodeFrame(u8)
172
174
 
173
175
  for (let i = 0; i < frames.length; i++) {
@@ -1,7 +1,12 @@
1
1
  'use strict'
2
2
  Object.defineProperty(exports, '__esModule', { value: true })
3
3
  exports.makeOfflineNodeProcessor = makeOfflineNodeProcessor
4
-
4
+ /**
5
+ * Creates a processor for offline stanza nodes that:
6
+ * - Queues nodes for sequential processing
7
+ * - Yields to the event loop periodically to avoid blocking
8
+ * - Catches handler errors to prevent the processing loop from crashing
9
+ */
5
10
  function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
6
11
  const nodes = []
7
12
  let isProcessing = false
@@ -22,8 +27,8 @@ function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
22
27
  }
23
28
  await nodeProcessor(node).catch(err => deps.onUnexpectedError(err, `processing offline ${type}`))
24
29
  processedInBatch++
25
-
26
-
30
+ // Yield to event loop after processing a batch
31
+ // This prevents blocking the event loop for too long when there are many offline nodes
27
32
  if (processedInBatch >= batchSize) {
28
33
  processedInBatch = 0
29
34
  await deps.yieldToEventLoop()
@@ -7,29 +7,35 @@ var __importDefault =
7
7
  Object.defineProperty(exports, '__esModule', { value: true })
8
8
  exports.PreKeyManager = void 0
9
9
  const p_queue_1 = __importDefault(require('p-queue'))
10
-
10
+ /**
11
+ * Manages pre-key operations with proper concurrency control
12
+ */
11
13
  class PreKeyManager {
12
14
  constructor(store, logger) {
13
15
  this.store = store
14
16
  this.logger = logger
15
17
  this.queues = new Map()
16
18
  }
17
-
19
+ /**
20
+ * Get or create a queue for a specific key type
21
+ */
18
22
  getQueue(keyType) {
19
23
  if (!this.queues.has(keyType)) {
20
24
  this.queues.set(keyType, new p_queue_1.default({ concurrency: 1 }))
21
25
  }
22
26
  return this.queues.get(keyType)
23
27
  }
24
-
28
+ /**
29
+ * Process pre-key operations (updates and deletions)
30
+ */
25
31
  async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
26
32
  const keyData = data[keyType]
27
33
  if (!keyData) return
28
34
  return this.getQueue(keyType).add(async () => {
29
-
35
+ // Ensure structures exist
30
36
  transactionCache[keyType] = transactionCache[keyType] || {}
31
37
  mutations[keyType] = mutations[keyType] || {}
32
-
38
+ // Separate deletions from updates
33
39
  const deletions = []
34
40
  const updates = {}
35
41
  for (const keyId in keyData) {
@@ -39,21 +45,23 @@ class PreKeyManager {
39
45
  updates[keyId] = keyData[keyId]
40
46
  }
41
47
  }
42
-
48
+ // Process updates (no validation needed)
43
49
  if (Object.keys(updates).length > 0) {
44
50
  Object.assign(transactionCache[keyType], updates)
45
51
  Object.assign(mutations[keyType], updates)
46
52
  }
47
-
53
+ // Process deletions with validation
48
54
  if (deletions.length > 0) {
49
55
  await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction)
50
56
  }
51
57
  })
52
58
  }
53
-
59
+ /**
60
+ * Process deletions with validation
61
+ */
54
62
  async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
55
63
  if (isInTransaction) {
56
-
64
+ // In transaction, only allow deletion if key exists in cache
57
65
  for (const keyId of ids) {
58
66
  if (transactionCache[keyType]?.[keyId]) {
59
67
  transactionCache[keyType][keyId] = null
@@ -63,7 +71,7 @@ class PreKeyManager {
63
71
  }
64
72
  }
65
73
  } else {
66
-
74
+ // Outside transaction, validate against store
67
75
  const existingKeys = await this.store.get(keyType, ids)
68
76
  for (const keyId of ids) {
69
77
  if (existingKeys[keyId]) {
@@ -75,15 +83,17 @@ class PreKeyManager {
75
83
  }
76
84
  }
77
85
  }
78
-
86
+ /**
87
+ * Validate and process pre-key deletions outside transactions
88
+ */
79
89
  async validateDeletions(data, keyType) {
80
90
  const keyData = data[keyType]
81
91
  if (!keyData) return
82
92
  return this.getQueue(keyType).add(async () => {
83
-
93
+ // Find all deletion requests
84
94
  const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null)
85
95
  if (deletionIds.length === 0) return
86
-
96
+ // Validate deletions
87
97
  const existingKeys = await this.store.get(keyType, deletionIds)
88
98
  for (const keyId of deletionIds) {
89
99
  if (!existingKeys[keyId]) {