@bellaxchuu/flowred 0.8.6

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 (142) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +214 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +6902 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.js +242946 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +190 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +92 -0
  12. package/lib/Signal/Group/group_cipher.js +89 -0
  13. package/lib/Signal/Group/index.js +136 -0
  14. package/lib/Signal/Group/keyhelper.js +73 -0
  15. package/lib/Signal/Group/sender-chain-key.js +32 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-message.js +69 -0
  18. package/lib/Signal/Group/sender-key-name.js +50 -0
  19. package/lib/Signal/Group/sender-key-record.js +44 -0
  20. package/lib/Signal/Group/sender-key-state.js +97 -0
  21. package/lib/Signal/Group/sender-message-key.js +30 -0
  22. package/lib/Signal/libsignal.js +490 -0
  23. package/lib/Signal/lid-mapping.js +262 -0
  24. package/lib/Socket/Client/index.js +30 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +62 -0
  27. package/lib/Socket/aigroups.js +240 -0
  28. package/lib/Socket/business.js +422 -0
  29. package/lib/Socket/chats.js +1816 -0
  30. package/lib/Socket/communities.js +549 -0
  31. package/lib/Socket/graphql.js +656 -0
  32. package/lib/Socket/groups.js +764 -0
  33. package/lib/Socket/index.js +39 -0
  34. package/lib/Socket/interactive-handler.js +522 -0
  35. package/lib/Socket/interop.js +549 -0
  36. package/lib/Socket/luxu.js +387 -0
  37. package/lib/Socket/managed-account.js +183 -0
  38. package/lib/Socket/messages-recv.js +2440 -0
  39. package/lib/Socket/messages-send.js +1853 -0
  40. package/lib/Socket/mex.js +60 -0
  41. package/lib/Socket/newsletter.js +820 -0
  42. package/lib/Socket/privacy.js +449 -0
  43. package/lib/Socket/registration.js +427 -0
  44. package/lib/Socket/socket.js +1092 -0
  45. package/lib/Socket/text-router.js +83 -0
  46. package/lib/Socket/username.js +243 -0
  47. package/lib/Store/index.js +36 -0
  48. package/lib/Store/keyed-db.js +108 -0
  49. package/lib/Store/make-cache-manager-store.js +90 -0
  50. package/lib/Store/make-in-memory-store.js +604 -0
  51. package/lib/Store/make-ordered-dictionary.js +81 -0
  52. package/lib/Store/object-repository.js +29 -0
  53. package/lib/Types/Auth.js +38 -0
  54. package/lib/Types/Bussines.js +2 -0
  55. package/lib/Types/Call.js +2 -0
  56. package/lib/Types/Chat.js +4 -0
  57. package/lib/Types/Contact.js +2 -0
  58. package/lib/Types/Events.js +2 -0
  59. package/lib/Types/GroupMetadata.js +2 -0
  60. package/lib/Types/Label.js +27 -0
  61. package/lib/Types/LabelAssociation.js +9 -0
  62. package/lib/Types/Message.js +95 -0
  63. package/lib/Types/Mex.js +112 -0
  64. package/lib/Types/Newsletter.js +121 -0
  65. package/lib/Types/Product.js +2 -0
  66. package/lib/Types/Signal.js +2 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +70 -0
  69. package/lib/Types/USync.js +2 -0
  70. package/lib/Types/index.js +55 -0
  71. package/lib/Utils/auth-utils.js +306 -0
  72. package/lib/Utils/browser-utils.js +114 -0
  73. package/lib/Utils/business.js +247 -0
  74. package/lib/Utils/chat-utils.js +1208 -0
  75. package/lib/Utils/command-loader.js +100 -0
  76. package/lib/Utils/companion-reg-client-utils.js +42 -0
  77. package/lib/Utils/consumer-application.js +107 -0
  78. package/lib/Utils/crypto.js +155 -0
  79. package/lib/Utils/curve25519-js.js +275 -0
  80. package/lib/Utils/decode-wa-message.js +560 -0
  81. package/lib/Utils/event-buffer.js +607 -0
  82. package/lib/Utils/generics.js +563 -0
  83. package/lib/Utils/group-history.js +60 -0
  84. package/lib/Utils/history.js +244 -0
  85. package/lib/Utils/identity-change-handler.js +52 -0
  86. package/lib/Utils/index.js +57 -0
  87. package/lib/Utils/jid-display-normalization.js +218 -0
  88. package/lib/Utils/link-preview.js +143 -0
  89. package/lib/Utils/logger.js +9 -0
  90. package/lib/Utils/lt-hash.js +39 -0
  91. package/lib/Utils/make-mutex.js +36 -0
  92. package/lib/Utils/message-composer.js +479 -0
  93. package/lib/Utils/message-retry-manager.js +270 -0
  94. package/lib/Utils/messages-media.js +896 -0
  95. package/lib/Utils/messages.js +2904 -0
  96. package/lib/Utils/meta-ai-msmsg.js +262 -0
  97. package/lib/Utils/native-bridge.js +82 -0
  98. package/lib/Utils/noise-handler.js +196 -0
  99. package/lib/Utils/offline-node-processor.js +42 -0
  100. package/lib/Utils/pre-key-manager.js +107 -0
  101. package/lib/Utils/process-message.js +1048 -0
  102. package/lib/Utils/reporting-utils.js +262 -0
  103. package/lib/Utils/session-pool.js +94 -0
  104. package/lib/Utils/signal.js +224 -0
  105. package/lib/Utils/stanza-ack.js +40 -0
  106. package/lib/Utils/sticker.js +145 -0
  107. package/lib/Utils/sync-action-utils.js +54 -0
  108. package/lib/Utils/tc-token-utils.js +161 -0
  109. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  110. package/lib/Utils/validate-connection.js +219 -0
  111. package/lib/Utils/view-once-cache.js +79 -0
  112. package/lib/Utils/voip-rekey.js +22 -0
  113. package/lib/WABinary/constants.js +1304 -0
  114. package/lib/WABinary/decode.js +343 -0
  115. package/lib/WABinary/encode.js +228 -0
  116. package/lib/WABinary/generic-utils.js +240 -0
  117. package/lib/WABinary/index.js +33 -0
  118. package/lib/WABinary/jid-utils.js +361 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +13 -0
  121. package/lib/WAM/constants.js +39486 -0
  122. package/lib/WAM/encode.js +142 -0
  123. package/lib/WAM/index.js +31 -0
  124. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  125. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  128. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  129. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  130. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  131. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  132. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  134. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  135. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  136. package/lib/WAUSync/Protocols/index.js +39 -0
  137. package/lib/WAUSync/USyncQuery.js +133 -0
  138. package/lib/WAUSync/USyncUser.js +50 -0
  139. package/lib/WAUSync/index.js +31 -0
  140. package/lib/antiban.js +4637 -0
  141. package/lib/index.js +45 -0
  142. package/package.json +107 -0
@@ -0,0 +1,262 @@
1
+ 'use strict'
2
+
3
+ const Crypto_1 = require('./crypto')
4
+ const { proto } = require('../../WAProto')
5
+
6
+ const BOT_MESSAGE_INFO = 'Bot Message'
7
+ const KEY_LENGTH = 32
8
+ const AUTH_TAG_LENGTH = 16
9
+
10
+ const MSG_ID_HEX_RE = /^[0-9A-Fa-f]{32}$/
11
+
12
+ const unpadRandomMax16 = value => {
13
+ const bytes = new Uint8Array(value)
14
+ if (!bytes.length) {
15
+ throw new Error('unpadPkcs7 given empty bytes')
16
+ }
17
+
18
+ const padLength = bytes[bytes.length - 1]
19
+ if (padLength > bytes.length) {
20
+ throw new Error(`unpad given ${bytes.length} bytes, but pad is ${padLength}`)
21
+ }
22
+
23
+ return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length - padLength)
24
+ }
25
+
26
+ const toBuffer = value => {
27
+ if (Buffer.isBuffer(value)) {
28
+ return value
29
+ }
30
+
31
+ if (value instanceof Uint8Array) {
32
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength)
33
+ }
34
+
35
+ return Buffer.from(value)
36
+ }
37
+
38
+ const normalizeLidJid = jid => {
39
+ if (!jid || !jid.endsWith('@lid') || !jid.includes(':')) {
40
+ return jid
41
+ }
42
+
43
+ return `${jid.split(':')[0]}@lid`
44
+ }
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
+ }
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
+ ])
65
+
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
+ })
108
+ }
109
+ }
110
+
111
+ return Array.from(grouped.values())
112
+ }
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
+ ]
121
+
122
+ const seen = new Set()
123
+ const candidates = []
124
+ for (const candidate of ordered) {
125
+ if (!candidate.jid) {
126
+ continue
127
+ }
128
+
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 = []
149
+ const seen = new Set()
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
+ }
181
+ }
182
+ }
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))
204
+ }
205
+
206
+ const decodeDecryptedMsmsgMessage = decrypted => {
207
+ const messageBuffer = toBuffer(decrypted)
208
+
209
+ try {
210
+ const unpadded = Buffer.from(unpadRandomMax16(messageBuffer))
211
+ const decoded = proto.Message.decode(unpadded)
212
+ const hasContent = Object.keys(decoded).some(key => key !== 'messageContextInfo' && decoded[key] != null)
213
+ if (hasContent) {
214
+ return decoded
215
+ }
216
+ } catch {}
217
+
218
+ return proto.Message.decode(messageBuffer)
219
+ }
220
+
221
+ const decryptMsmsgBotMessage = async (messageSecret, messageKey, msMsg) => {
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')
229
+ }
230
+
231
+ const strategies = buildMsmsgDecryptionStrategies(messageKey)
232
+ const attemptedStrategies = []
233
+ let lastError
234
+
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
+ }
243
+
244
+ try {
245
+ return await decryptWithStrategy(messageSecret, msMsg, strategy)
246
+ } catch (error) {
247
+ attemptedStrategies.push(attempt)
248
+ lastError = error
249
+ }
250
+ }
251
+
252
+ const error = new Error('Failed to decrypt msmsg with bounded deterministic strategies')
253
+ error.attemptedStrategies = attemptedStrategies
254
+ error.cause = lastError
255
+ throw error
256
+ }
257
+
258
+ module.exports = {
259
+ buildMsmsgDecryptionStrategies,
260
+ decodeDecryptedMsmsgMessage,
261
+ decryptMsmsgBotMessage
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
@@ -0,0 +1,196 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.makeNoiseHandler = void 0
4
+ const boom_1 = require('@hapi/boom')
5
+ const index_js_1 = require('../../WAProto/index.js')
6
+ const Defaults_1 = require('../Defaults')
7
+ const rb = require('./native-bridge').loadRustBridge()
8
+
9
+ // rustNodeToJs mirrors the one in decode.js — converts InternalBinaryNode to plain JS object
10
+ const rustNodeToJs = node => {
11
+ if (!node || typeof node !== 'object') return node
12
+ const result = { tag: node.tag, attrs: node.attrs || {} }
13
+ const content = node.content
14
+ if (content === undefined || content === null) {
15
+ // no content
16
+ } else if (content instanceof Uint8Array) {
17
+ result.content = Buffer.from(content)
18
+ } else if (typeof content === 'string') {
19
+ result.content = content
20
+ } else if (Array.isArray(content)) {
21
+ result.content = content.map(rustNodeToJs)
22
+ } else {
23
+ result.content = content
24
+ }
25
+ return result
26
+ }
27
+
28
+ const makeNoiseHandler = ({
29
+ keyPair: { private: privateKey, public: publicKey },
30
+ NOISE_HEADER,
31
+ logger,
32
+ routingInfo
33
+ }) => {
34
+ logger = logger.child({ class: 'ns' })
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
+
44
+ const session = new rb.NoiseSession(
45
+ publicKey instanceof Uint8Array ? publicKey : new Uint8Array(publicKey),
46
+ NOISE_HEADER instanceof Uint8Array ? NOISE_HEADER : new Uint8Array(NOISE_HEADER),
47
+ routingInfo ? (routingInfo instanceof Uint8Array ? routingInfo : new Uint8Array(routingInfo)) : undefined
48
+ )
49
+
50
+ let isWaitingForTransport = false
51
+ let pendingOnFrame = null
52
+ let pendingBytes = null
53
+
54
+ const processFrames = async onFrame => {
55
+ // decodeFrame returns an Array of InternalBinaryNode (post-handshake) or Uint8Array (handshake)
56
+ const frames = session.decodeFrame(new Uint8Array(0))
57
+ for (let i = 0; i < frames.length; i++) {
58
+ const item = frames[i]
59
+ let frame
60
+ if (item instanceof Uint8Array) {
61
+ frame = Buffer.from(item)
62
+ } else {
63
+ try {
64
+ frame = rustNodeToJs(item.toJSON())
65
+ } catch (decodeErr) {
66
+ logger.debug({ err: decodeErr?.message }, '[noise] decode error')
67
+ continue
68
+ }
69
+ }
70
+ if (logger.level === 'trace') {
71
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame')
72
+ }
73
+ onFrame(frame)
74
+ }
75
+ }
76
+
77
+ const finishInit = async () => {
78
+ isWaitingForTransport = true
79
+ session.finishInit()
80
+ isWaitingForTransport = false
81
+ logger.trace('Noise handler transitioned to Transport state (Rust)')
82
+ if (pendingOnFrame && pendingBytes) {
83
+ logger.trace({ length: pendingBytes.length }, 'Flushing buffered frames after transport ready')
84
+ const frames = session.decodeFrame(pendingBytes)
85
+ pendingBytes = null
86
+ const cb = pendingOnFrame
87
+ pendingOnFrame = null
88
+ for (let i = 0; i < frames.length; i++) {
89
+ const item = frames[i]
90
+ let frame
91
+ if (item instanceof Uint8Array) {
92
+ frame = Buffer.from(item)
93
+ } else {
94
+ try {
95
+ frame = rustNodeToJs(item.toJSON())
96
+ } catch (e) {
97
+ continue
98
+ }
99
+ }
100
+ cb(frame)
101
+ }
102
+ }
103
+ }
104
+
105
+ return {
106
+ encrypt: plaintext => {
107
+ const u8 = plaintext instanceof Uint8Array ? plaintext : new Uint8Array(plaintext)
108
+ return Buffer.from(session.encrypt(u8))
109
+ },
110
+ decrypt: ciphertext => {
111
+ const u8 = ciphertext instanceof Uint8Array ? ciphertext : new Uint8Array(ciphertext)
112
+ return Buffer.from(session.decrypt(u8))
113
+ },
114
+ authenticate: data => {
115
+ session.authenticate(data instanceof Uint8Array ? data : new Uint8Array(data))
116
+ },
117
+ mixIntoKey: data => {
118
+ session.mixIntoKey(data instanceof Uint8Array ? data : new Uint8Array(data))
119
+ },
120
+ finishInit,
121
+ processHandshake: ({ serverHello }, noiseKey) => {
122
+ // Rust handles the crypto: authenticate ephemeral, ECDH, decrypt static+payload
123
+ const certPayload = session.processHandshakeInit(
124
+ serverHello.ephemeral,
125
+ serverHello.static,
126
+ serverHello.payload,
127
+ privateKey instanceof Uint8Array ? privateKey : new Uint8Array(privateKey)
128
+ )
129
+
130
+ // Certificate validation stays in JS (uses protobuf + WA-specific constants)
131
+ const { intermediate: certIntermediate, leaf } = index_js_1.proto.CertChain.decode(certPayload)
132
+ if (!leaf?.details || !leaf?.signature) {
133
+ throw new boom_1.Boom('invalid noise leaf certificate', { statusCode: 400 })
134
+ }
135
+ if (!certIntermediate?.details || !certIntermediate?.signature) {
136
+ throw new boom_1.Boom('invalid noise intermediate certificate', { statusCode: 400 })
137
+ }
138
+ const details = index_js_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details)
139
+ const { issuerSerial } = details
140
+ const { Curve } = require('./crypto')
141
+ if (!Curve.verify(details.key, leaf.details, leaf.signature)) {
142
+ throw new boom_1.Boom('noise certificate signature invalid', { statusCode: 400 })
143
+ }
144
+ if (!Curve.verify(Defaults_1.WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature)) {
145
+ throw new boom_1.Boom('noise intermediate certificate signature invalid', { statusCode: 400 })
146
+ }
147
+ if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
148
+ throw new boom_1.Boom('certification match failed', { statusCode: 400 })
149
+ }
150
+
151
+ // Encrypt our static key and do final ECDH
152
+ const keyEnc = session.processHandshakeFinish(
153
+ noiseKey.public instanceof Uint8Array ? noiseKey.public : new Uint8Array(noiseKey.public),
154
+ noiseKey.private instanceof Uint8Array ? noiseKey.private : new Uint8Array(noiseKey.private),
155
+ serverHello.ephemeral
156
+ )
157
+ return Buffer.from(keyEnc)
158
+ },
159
+ encodeFrame: data => {
160
+ const u8 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
161
+ return Buffer.from(session.encodeFrameRaw(u8))
162
+ },
163
+ decodeFrame: async (newData, onFrame) => {
164
+ if (isWaitingForTransport) {
165
+ pendingBytes = pendingBytes
166
+ ? Buffer.concat([pendingBytes, Buffer.from(newData)])
167
+ : Buffer.from(newData)
168
+ pendingOnFrame = onFrame
169
+ return
170
+ }
171
+
172
+ const u8 = newData instanceof Uint8Array ? newData : new Uint8Array(newData.buffer, newData.byteOffset, newData.byteLength)
173
+ const frames = session.decodeFrame(u8)
174
+
175
+ for (let i = 0; i < frames.length; i++) {
176
+ const item = frames[i]
177
+ let frame
178
+ if (item instanceof Uint8Array) {
179
+ frame = Buffer.from(item)
180
+ } else {
181
+ try {
182
+ frame = rustNodeToJs(item.toJSON())
183
+ } catch (decodeErr) {
184
+ logger.debug({ err: decodeErr?.message }, '[noise] decode error')
185
+ continue
186
+ }
187
+ }
188
+ if (logger.level === 'trace') {
189
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame')
190
+ }
191
+ onFrame(frame)
192
+ }
193
+ }
194
+ }
195
+ }
196
+ exports.makeNoiseHandler = makeNoiseHandler
@@ -0,0 +1,42 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.makeOfflineNodeProcessor = makeOfflineNodeProcessor
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
+ */
10
+ function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
11
+ const nodes = []
12
+ let isProcessing = false
13
+ const enqueue = (type, node) => {
14
+ nodes.push({ type, node })
15
+ if (isProcessing) {
16
+ return
17
+ }
18
+ isProcessing = true
19
+ const promise = async () => {
20
+ let processedInBatch = 0
21
+ while (nodes.length && deps.isWsOpen()) {
22
+ const { type, node } = nodes.shift()
23
+ const nodeProcessor = nodeProcessorMap.get(type)
24
+ if (!nodeProcessor) {
25
+ deps.onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node')
26
+ continue
27
+ }
28
+ await nodeProcessor(node).catch(err => deps.onUnexpectedError(err, `processing offline ${type}`))
29
+ processedInBatch++
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
32
+ if (processedInBatch >= batchSize) {
33
+ processedInBatch = 0
34
+ await deps.yieldToEventLoop()
35
+ }
36
+ }
37
+ isProcessing = false
38
+ }
39
+ promise().catch(error => deps.onUnexpectedError(error, 'processing offline nodes'))
40
+ }
41
+ return { enqueue }
42
+ }
@@ -0,0 +1,107 @@
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ exports.PreKeyManager = void 0
9
+ const p_queue_1 = __importDefault(require('p-queue'))
10
+ /**
11
+ * Manages pre-key operations with proper concurrency control
12
+ */
13
+ class PreKeyManager {
14
+ constructor(store, logger) {
15
+ this.store = store
16
+ this.logger = logger
17
+ this.queues = new Map()
18
+ }
19
+ /**
20
+ * Get or create a queue for a specific key type
21
+ */
22
+ getQueue(keyType) {
23
+ if (!this.queues.has(keyType)) {
24
+ this.queues.set(keyType, new p_queue_1.default({ concurrency: 1 }))
25
+ }
26
+ return this.queues.get(keyType)
27
+ }
28
+ /**
29
+ * Process pre-key operations (updates and deletions)
30
+ */
31
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
32
+ const keyData = data[keyType]
33
+ if (!keyData) return
34
+ return this.getQueue(keyType).add(async () => {
35
+ // Ensure structures exist
36
+ transactionCache[keyType] = transactionCache[keyType] || {}
37
+ mutations[keyType] = mutations[keyType] || {}
38
+ // Separate deletions from updates
39
+ const deletions = []
40
+ const updates = {}
41
+ for (const keyId in keyData) {
42
+ if (keyData[keyId] === null) {
43
+ deletions.push(keyId)
44
+ } else {
45
+ updates[keyId] = keyData[keyId]
46
+ }
47
+ }
48
+ // Process updates (no validation needed)
49
+ if (Object.keys(updates).length > 0) {
50
+ Object.assign(transactionCache[keyType], updates)
51
+ Object.assign(mutations[keyType], updates)
52
+ }
53
+ // Process deletions with validation
54
+ if (deletions.length > 0) {
55
+ await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction)
56
+ }
57
+ })
58
+ }
59
+ /**
60
+ * Process deletions with validation
61
+ */
62
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
63
+ if (isInTransaction) {
64
+ // In transaction, only allow deletion if key exists in cache
65
+ for (const keyId of ids) {
66
+ if (transactionCache[keyType]?.[keyId]) {
67
+ transactionCache[keyType][keyId] = null
68
+ mutations[keyType][keyId] = null
69
+ } else {
70
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`)
71
+ }
72
+ }
73
+ } else {
74
+ // Outside transaction, validate against store
75
+ const existingKeys = await this.store.get(keyType, ids)
76
+ for (const keyId of ids) {
77
+ if (existingKeys[keyId]) {
78
+ transactionCache[keyType][keyId] = null
79
+ mutations[keyType][keyId] = null
80
+ } else {
81
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
82
+ }
83
+ }
84
+ }
85
+ }
86
+ /**
87
+ * Validate and process pre-key deletions outside transactions
88
+ */
89
+ async validateDeletions(data, keyType) {
90
+ const keyData = data[keyType]
91
+ if (!keyData) return
92
+ return this.getQueue(keyType).add(async () => {
93
+ // Find all deletion requests
94
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null)
95
+ if (deletionIds.length === 0) return
96
+ // Validate deletions
97
+ const existingKeys = await this.store.get(keyType, deletionIds)
98
+ for (const keyId of deletionIds) {
99
+ if (!existingKeys[keyId]) {
100
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
101
+ delete data[keyType][keyId]
102
+ }
103
+ }
104
+ })
105
+ }
106
+ }
107
+ exports.PreKeyManager = PreKeyManager