@badzz88/baileys 8.4.7 → 8.4.9

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 (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +347 -6
  4. package/WAProto/fix-import.js +38 -0
  5. package/WAProto/fix-imports.js +86 -85
  6. package/WAProto/index.d.ts +4913 -25
  7. package/WAProto/index.js +14074 -98
  8. package/package.json +50 -90
  9. package/src/Defaults/index.js +201 -0
  10. package/src/Defaults/phonenumber-mcc.json +223 -0
  11. package/src/Signal/Group/ciphertext-message.js +15 -0
  12. package/src/Signal/Group/group-session-builder.js +92 -0
  13. package/src/Signal/Group/group_cipher.js +89 -0
  14. package/src/Signal/Group/index.js +136 -0
  15. package/src/Signal/Group/keyhelper.js +73 -0
  16. package/src/Signal/Group/sender-chain-key.js +32 -0
  17. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/src/Signal/Group/sender-key-message.js +69 -0
  19. package/src/Signal/Group/sender-key-name.js +50 -0
  20. package/src/Signal/Group/sender-key-record.js +44 -0
  21. package/src/Signal/Group/sender-key-state.js +97 -0
  22. package/src/Signal/Group/sender-message-key.js +30 -0
  23. package/src/Signal/libsignal.js +470 -0
  24. package/src/Signal/lid-mapping.js +262 -0
  25. package/src/Socket/Client/index.js +30 -0
  26. package/src/Socket/Client/types.js +13 -0
  27. package/src/Socket/Client/websocket.js +62 -0
  28. package/src/Socket/aigroups.js +240 -0
  29. package/src/Socket/business.js +422 -0
  30. package/src/Socket/chats.js +2374 -0
  31. package/src/Socket/communities.js +580 -0
  32. package/src/Socket/graphql.js +915 -0
  33. package/src/Socket/groups.js +812 -0
  34. package/src/Socket/index.js +37 -0
  35. package/src/Socket/interactive-handler.js +579 -0
  36. package/src/Socket/interop.js +566 -0
  37. package/src/Socket/managed-account.js +214 -0
  38. package/src/Socket/messages-recv.js +3012 -0
  39. package/src/Socket/messages-send.js +2163 -0
  40. package/{lib → src}/Socket/mex.js +11 -5
  41. package/src/Socket/newsletter.js +1057 -0
  42. package/src/Socket/privacy.js +452 -0
  43. package/src/Socket/registration.js +434 -0
  44. package/src/Socket/socket.js +1079 -0
  45. package/src/Socket/text-router.js +67 -0
  46. package/src/Socket/username.js +234 -0
  47. package/src/Store/index.js +36 -0
  48. package/src/Store/make-cache-manager-store.js +90 -0
  49. package/src/Store/make-in-memory-store.js +506 -0
  50. package/src/Store/make-ordered-dictionary.js +81 -0
  51. package/src/Store/object-repository.js +29 -0
  52. package/src/Types/Auth.js +38 -0
  53. package/src/Types/Bussines.js +2 -0
  54. package/src/Types/Call.js +2 -0
  55. package/src/Types/Chat.js +4 -0
  56. package/src/Types/Contact.js +2 -0
  57. package/src/Types/Events.js +2 -0
  58. package/src/Types/GroupMetadata.js +2 -0
  59. package/src/Types/Label.js +27 -0
  60. package/src/Types/LabelAssociation.js +9 -0
  61. package/src/Types/Message.js +95 -0
  62. package/src/Types/Newsletter.js +152 -0
  63. package/src/Types/Product.js +2 -0
  64. package/src/Types/Signal.js +2 -0
  65. package/src/Types/Socket.js +2 -0
  66. package/src/Types/State.js +70 -0
  67. package/src/Types/USync.js +2 -0
  68. package/src/Types/index.js +54 -0
  69. package/src/Utils/auth-utils.js +306 -0
  70. package/src/Utils/browser-utils.js +114 -0
  71. package/src/Utils/business.js +247 -0
  72. package/src/Utils/chat-utils.js +1272 -0
  73. package/src/Utils/consumer-application.js +107 -0
  74. package/src/Utils/crypto.js +125 -0
  75. package/src/Utils/decode-wa-message.js +808 -0
  76. package/src/Utils/event-buffer.js +586 -0
  77. package/src/Utils/generics.js +640 -0
  78. package/src/Utils/group-history.js +60 -0
  79. package/src/Utils/history.js +244 -0
  80. package/src/Utils/identity-change-handler.js +52 -0
  81. package/src/Utils/index.js +53 -0
  82. package/src/Utils/jid-display-normalization.js +218 -0
  83. package/src/Utils/link-preview.js +143 -0
  84. package/src/Utils/logger.js +9 -0
  85. package/src/Utils/lt-hash.js +10 -0
  86. package/src/Utils/make-mutex.js +36 -0
  87. package/src/Utils/message-composer.js +479 -0
  88. package/src/Utils/message-inspect.js +400 -0
  89. package/src/Utils/message-retry-manager.js +231 -0
  90. package/src/Utils/messages-media.js +943 -0
  91. package/src/Utils/messages.js +2490 -0
  92. package/src/Utils/meta-ai-msmsg.js +133 -0
  93. package/src/Utils/noise-handler.js +194 -0
  94. package/src/Utils/offline-node-processor.js +42 -0
  95. package/src/Utils/pre-key-manager.js +107 -0
  96. package/src/Utils/process-message.js +1047 -0
  97. package/src/Utils/reporting-utils.js +262 -0
  98. package/src/Utils/signal.js +192 -0
  99. package/src/Utils/stanza-ack.js +74 -0
  100. package/src/Utils/sync-action-utils.js +54 -0
  101. package/src/Utils/tc-token-utils.js +161 -0
  102. package/src/Utils/use-multi-file-auth-state.js +121 -0
  103. package/src/Utils/validate-connection.js +248 -0
  104. package/src/Utils/voip-rekey.js +22 -0
  105. package/src/WABinary/constants.js +1304 -0
  106. package/src/WABinary/decode.js +377 -0
  107. package/src/WABinary/encode.js +58 -0
  108. package/src/WABinary/generic-utils.js +148 -0
  109. package/src/WABinary/index.js +33 -0
  110. package/src/WABinary/jid-utils.js +374 -0
  111. package/src/WABinary/types.js +2 -0
  112. package/src/WAM/BinaryInfo.js +13 -0
  113. package/src/WAM/constants.js +39486 -0
  114. package/src/WAM/encode.js +142 -0
  115. package/src/WAM/index.js +31 -0
  116. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  117. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  118. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  119. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  120. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  121. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  122. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  123. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  124. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  125. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  126. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  127. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  128. package/src/WAUSync/Protocols/index.js +40 -0
  129. package/src/WAUSync/USyncBackoff.js +31 -0
  130. package/src/WAUSync/USyncQuery.js +204 -0
  131. package/src/WAUSync/USyncUser.js +58 -0
  132. package/src/WAUSync/index.js +32 -0
  133. package/src/antiban.js +4726 -0
  134. package/{lib → src}/index.js +48 -15
  135. package/lib/Defaults/index.js +0 -130
  136. package/lib/Signal/Group/ciphertext-message.js +0 -12
  137. package/lib/Signal/Group/group-session-builder.js +0 -30
  138. package/lib/Signal/Group/group_cipher.js +0 -82
  139. package/lib/Signal/Group/index.js +0 -12
  140. package/lib/Signal/Group/keyhelper.js +0 -18
  141. package/lib/Signal/Group/sender-chain-key.js +0 -26
  142. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  143. package/lib/Signal/Group/sender-key-message.js +0 -66
  144. package/lib/Signal/Group/sender-key-name.js +0 -48
  145. package/lib/Signal/Group/sender-key-record.js +0 -41
  146. package/lib/Signal/Group/sender-key-state.js +0 -84
  147. package/lib/Signal/Group/sender-message-key.js +0 -26
  148. package/lib/Signal/libsignal.js +0 -431
  149. package/lib/Signal/lid-mapping.js +0 -277
  150. package/lib/Socket/Client/index.js +0 -3
  151. package/lib/Socket/Client/types.js +0 -11
  152. package/lib/Socket/Client/websocket.js +0 -54
  153. package/lib/Socket/business.js +0 -379
  154. package/lib/Socket/chats.js +0 -1193
  155. package/lib/Socket/communities.js +0 -431
  156. package/lib/Socket/groups.js +0 -374
  157. package/lib/Socket/index.js +0 -12
  158. package/lib/Socket/luxu.js +0 -386
  159. package/lib/Socket/messages-recv.js +0 -1916
  160. package/lib/Socket/messages-send.js +0 -1453
  161. package/lib/Socket/newsletter.js +0 -251
  162. package/lib/Socket/socket.js +0 -980
  163. package/lib/Socket/username.js +0 -146
  164. package/lib/Store/index.js +0 -10
  165. package/lib/Store/keyed-db.js +0 -108
  166. package/lib/Store/make-cache-manager-store.js +0 -85
  167. package/lib/Store/make-in-memory-store.js +0 -198
  168. package/lib/Store/make-ordered-dictionary.js +0 -75
  169. package/lib/Store/object-repository.js +0 -32
  170. package/lib/Types/Auth.js +0 -2
  171. package/lib/Types/Bussines.js +0 -2
  172. package/lib/Types/Call.js +0 -2
  173. package/lib/Types/Chat.js +0 -8
  174. package/lib/Types/Contact.js +0 -2
  175. package/lib/Types/Events.js +0 -2
  176. package/lib/Types/GroupMetadata.js +0 -2
  177. package/lib/Types/Label.js +0 -25
  178. package/lib/Types/LabelAssociation.js +0 -7
  179. package/lib/Types/Message.js +0 -11
  180. package/lib/Types/Mex.js +0 -37
  181. package/lib/Types/Product.js +0 -2
  182. package/lib/Types/Signal.js +0 -2
  183. package/lib/Types/Socket.js +0 -3
  184. package/lib/Types/State.js +0 -56
  185. package/lib/Types/USync.js +0 -2
  186. package/lib/Types/index.js +0 -26
  187. package/lib/Utils/auth-utils.js +0 -302
  188. package/lib/Utils/browser-utils.js +0 -49
  189. package/lib/Utils/business.js +0 -231
  190. package/lib/Utils/chat-utils.js +0 -872
  191. package/lib/Utils/companion-reg-client-utils.js +0 -35
  192. package/lib/Utils/crypto.js +0 -118
  193. package/lib/Utils/decode-wa-message.js +0 -350
  194. package/lib/Utils/event-buffer.js +0 -622
  195. package/lib/Utils/generics.js +0 -403
  196. package/lib/Utils/history.js +0 -134
  197. package/lib/Utils/identity-change-handler.js +0 -50
  198. package/lib/Utils/index.js +0 -23
  199. package/lib/Utils/link-preview.js +0 -85
  200. package/lib/Utils/logger.js +0 -3
  201. package/lib/Utils/lt-hash.js +0 -8
  202. package/lib/Utils/make-mutex.js +0 -33
  203. package/lib/Utils/message-composer.js +0 -273
  204. package/lib/Utils/message-retry-manager.js +0 -265
  205. package/lib/Utils/messages-media.js +0 -788
  206. package/lib/Utils/messages.js +0 -1260
  207. package/lib/Utils/noise-handler.js +0 -201
  208. package/lib/Utils/offline-node-processor.js +0 -40
  209. package/lib/Utils/pre-key-manager.js +0 -106
  210. package/lib/Utils/process-message.js +0 -630
  211. package/lib/Utils/reporting-utils.js +0 -258
  212. package/lib/Utils/signal.js +0 -201
  213. package/lib/Utils/stanza-ack.js +0 -38
  214. package/lib/Utils/sync-action-utils.js +0 -49
  215. package/lib/Utils/tc-token-utils.js +0 -163
  216. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  217. package/lib/Utils/validate-connection.js +0 -203
  218. package/lib/WABinary/constants.js +0 -1301
  219. package/lib/WABinary/decode.js +0 -262
  220. package/lib/WABinary/encode.js +0 -220
  221. package/lib/WABinary/generic-utils.js +0 -204
  222. package/lib/WABinary/index.js +0 -6
  223. package/lib/WABinary/jid-utils.js +0 -98
  224. package/lib/WABinary/types.js +0 -2
  225. package/lib/WAM/BinaryInfo.js +0 -10
  226. package/lib/WAM/constants.js +0 -22853
  227. package/lib/WAM/encode.js +0 -150
  228. package/lib/WAM/index.js +0 -4
  229. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  230. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  231. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  232. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  233. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  234. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  235. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  236. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  237. package/lib/WAUSync/Protocols/index.js +0 -6
  238. package/lib/WAUSync/USyncQuery.js +0 -98
  239. package/lib/WAUSync/USyncUser.js +0 -31
  240. package/lib/WAUSync/index.js +0 -4
@@ -0,0 +1,133 @@
1
+ 'use strict'
2
+
3
+ const rb = require('whatsapp-rust-bridge-baron')
4
+ const { proto } = require('../../WAProto')
5
+
6
+ const BOT_MESSAGE_INFO = 'Bot Message'
7
+ const KEY_LENGTH = 32
8
+
9
+ const unpadRandomMax16 = value => {
10
+ const bytes = new Uint8Array(value)
11
+ if (!bytes.length) {
12
+ throw new Error('unpadPkcs7 given empty bytes')
13
+ }
14
+ const padLength = bytes[bytes.length - 1]
15
+ if (padLength > bytes.length) {
16
+ throw new Error(`unpad given ${bytes.length} bytes, but pad is ${padLength}`)
17
+ }
18
+ return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length - padLength)
19
+ }
20
+
21
+ 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
+ }
26
+
27
+ // Strips device suffix from LID JIDs: "user:device@lid" → "user@lid".
28
+ // jidEncode includes ":0" even for device=0 (user/non-AD form), so normalize both meId and meLid.
29
+ const normalizeLidJid = jid => {
30
+ if (!jid || !jid.endsWith('@lid') || !jid.includes(':')) return jid
31
+ return `${jid.split(':')[0]}@lid`
32
+ }
33
+
34
+ // Ordered msgId candidates per the Rust BotMessageContext:
35
+ // botEditTargetId when editing, stanzaId for the normal full response, metaTargetId as fallback.
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)
44
+ }
45
+ }
46
+ return result
47
+ }
48
+
49
+ // Ordered target_sender_user_jid candidates per Rust spec (non-AD user JID = no device suffix).
50
+ // jidEncode produces "user:0@lid" for device=0 LID JIDs, so normalize both meId and meLid.
51
+ const selectTargetJidCandidates = messageKey => {
52
+ 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)
59
+ }
60
+ }
61
+ return result
62
+ }
63
+
64
+ const decodeDecryptedMsmsgMessage = decrypted => {
65
+ const buf = toBuffer(decrypted)
66
+ try {
67
+ const unpadded = Buffer.from(unpadRandomMax16(buf))
68
+ const decoded = proto.Message.decode(unpadded)
69
+ const hasContent = Object.keys(decoded).some(k => k !== 'messageContextInfo' && decoded[k] != null)
70
+ if (hasContent) return decoded
71
+ } catch {}
72
+ return proto.Message.decode(buf)
73
+ }
74
+
75
+ /**
76
+ * Decrypts <enc type="msmsg"> bot messages.
77
+ *
78
+ * Two-pass HKDF — algorithm from bot_message.rs (BotMessageContext):
79
+ * k1 = HKDF(messageSecret, salt=∅, info="Bot Message", 32)
80
+ * k2 = HKDF(k1, salt=∅, info=msgID||target_sender_jid||bot_jid, 32)
81
+ * AAD = msgID || 0x00 || bot_user_jid
82
+ * plain = AES-256-GCM.Decrypt(k2, encIv, encPayload, AAD)
83
+ *
84
+ * k1 is shared across all candidates and derived once.
85
+ * AAD always uses bot_user_jid, never target_sender_jid.
86
+ */
87
+ const decryptMsmsgBotMessage = async (messageSecret, messageKey, msMsg) => {
88
+ if (!messageSecret || (messageSecret instanceof Uint8Array && !messageSecret.byteLength)) {
89
+ throw new Error('Missing required messageSecret for msmsg decryption')
90
+ }
91
+ if (!messageKey?.participant) throw new Error('Missing required participant for msmsg decryption')
92
+ if (!messageKey?.meId) throw new Error('Missing required meId for msmsg decryption')
93
+ if (!msMsg?.encIv) throw new Error('Missing required encIv for msmsg decryption')
94
+ if (!msMsg?.encPayload) throw new Error('Missing required encPayload for msmsg decryption')
95
+
96
+ const msgIdCandidates = selectMsgIdCandidates(messageKey)
97
+ if (!msgIdCandidates.length) throw new Error('Missing required target message id for msmsg decryption')
98
+
99
+ const targetJidCandidates = selectTargetJidCandidates(messageKey)
100
+ if (!targetJidCandidates.length) throw new Error('Missing required target JID for msmsg decryption')
101
+
102
+ const botJidBuf = Buffer.from(String(messageKey.participant))
103
+ const payload = toBuffer(msMsg.encPayload)
104
+ const iv = toBuffer(msMsg.encIv)
105
+
106
+ // k1 depends only on messageSecret — derive once and reuse across all candidates
107
+ const baseKey = Buffer.from(rb.hkdf(toBuffer(messageSecret), KEY_LENGTH, { info: BOT_MESSAGE_INFO }))
108
+
109
+ let lastError
110
+ for (const msgId of msgIdCandidates) {
111
+ // msg_id is always passed as ASCII bytes per Rust spec (msg_id.as_bytes())
112
+ const idBuf = Buffer.from(msgId)
113
+ for (const targetJid of targetJidCandidates) {
114
+ const info = Buffer.concat([idBuf, Buffer.from(targetJid), botJidBuf])
115
+ const key = Buffer.from(rb.hkdf(baseKey, KEY_LENGTH, { info }))
116
+ const aad = Buffer.concat([idBuf, Buffer.from([0x00]), botJidBuf])
117
+ try {
118
+ return Buffer.from(rb.aesDecryptGCM(payload, key, iv, aad))
119
+ } catch (e) {
120
+ lastError = e
121
+ }
122
+ }
123
+ }
124
+
125
+ const err = new Error('msmsg decryption failed: all key derivation candidates exhausted')
126
+ err.cause = lastError
127
+ throw err
128
+ }
129
+
130
+ module.exports = {
131
+ decodeDecryptedMsmsgMessage,
132
+ decryptMsmsgBotMessage
133
+ }
@@ -0,0 +1,194 @@
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('whatsapp-rust-bridge-baron')
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
+ const session = new rb.NoiseSession(
37
+ publicKey instanceof Uint8Array ? publicKey : new Uint8Array(publicKey),
38
+ NOISE_HEADER instanceof Uint8Array ? NOISE_HEADER : new Uint8Array(NOISE_HEADER),
39
+ routingInfo ? (routingInfo instanceof Uint8Array ? routingInfo : new Uint8Array(routingInfo)) : undefined
40
+ )
41
+
42
+ let isWaitingForTransport = false
43
+ let pendingOnFrame = null
44
+ let pendingBytes = null
45
+
46
+ const processFrames = async onFrame => {
47
+ // decodeFrame returns an Array of InternalBinaryNode (post-handshake) or Uint8Array (handshake)
48
+ const frames = session.decodeFrame(new Uint8Array(0))
49
+ for (let i = 0; i < frames.length; i++) {
50
+ const item = frames[i]
51
+ let frame
52
+ if (item instanceof Uint8Array) {
53
+ frame = Buffer.from(item)
54
+ } else {
55
+ try {
56
+ frame = rustNodeToJs(item.toJSON())
57
+ } catch (decodeErr) {
58
+ logger.debug({ err: decodeErr?.message }, '[noise] decode error')
59
+ continue
60
+ }
61
+ }
62
+ if (logger.level === 'trace') {
63
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame')
64
+ }
65
+ onFrame(frame)
66
+ }
67
+ }
68
+
69
+ const finishInit = async () => {
70
+ isWaitingForTransport = true
71
+ session.finishInit()
72
+ isWaitingForTransport = false
73
+ logger.trace('Noise handler transitioned to Transport state (Rust)')
74
+ if (pendingOnFrame && pendingBytes) {
75
+ logger.trace({ length: pendingBytes.length }, 'Flushing buffered frames after transport ready')
76
+ const frames = session.decodeFrame(pendingBytes)
77
+ pendingBytes = null
78
+ const cb = pendingOnFrame
79
+ pendingOnFrame = null
80
+ for (let i = 0; i < frames.length; i++) {
81
+ const item = frames[i]
82
+ let frame
83
+ if (item instanceof Uint8Array) {
84
+ frame = Buffer.from(item)
85
+ } else {
86
+ try {
87
+ frame = rustNodeToJs(item.toJSON())
88
+ } catch {
89
+ continue
90
+ }
91
+ }
92
+ cb(frame)
93
+ }
94
+ }
95
+ }
96
+
97
+ return {
98
+ encrypt: plaintext => {
99
+ const u8 = plaintext instanceof Uint8Array ? plaintext : new Uint8Array(plaintext)
100
+ return Buffer.from(session.encrypt(u8))
101
+ },
102
+ decrypt: ciphertext => {
103
+ const u8 = ciphertext instanceof Uint8Array ? ciphertext : new Uint8Array(ciphertext)
104
+ return Buffer.from(session.decrypt(u8))
105
+ },
106
+ authenticate: data => {
107
+ session.authenticate(data instanceof Uint8Array ? data : new Uint8Array(data))
108
+ },
109
+ mixIntoKey: data => {
110
+ session.mixIntoKey(data instanceof Uint8Array ? data : new Uint8Array(data))
111
+ },
112
+ finishInit,
113
+ processHandshake: ({ serverHello }, noiseKey) => {
114
+ // Rust handles the crypto: authenticate ephemeral, ECDH, decrypt static+payload
115
+ const certPayload = session.processHandshakeInit(
116
+ serverHello.ephemeral,
117
+ serverHello.static,
118
+ serverHello.payload,
119
+ privateKey instanceof Uint8Array ? privateKey : new Uint8Array(privateKey)
120
+ )
121
+
122
+ // Certificate validation stays in JS (uses protobuf + WA-specific constants)
123
+ const { intermediate: certIntermediate, leaf } = index_js_1.proto.CertChain.decode(certPayload)
124
+ if (!leaf?.details || !leaf?.signature) {
125
+ throw new boom_1.Boom('invalid noise leaf certificate', { statusCode: 400 })
126
+ }
127
+ if (!certIntermediate?.details || !certIntermediate?.signature) {
128
+ throw new boom_1.Boom('invalid noise intermediate certificate', { statusCode: 400 })
129
+ }
130
+ const details = index_js_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details)
131
+ const { issuerSerial } = details
132
+ const { Curve } = require('./crypto')
133
+ if (!Curve.verify(details.key, leaf.details, leaf.signature)) {
134
+ throw new boom_1.Boom('noise certificate signature invalid', { statusCode: 400 })
135
+ }
136
+ if (!Curve.verify(Defaults_1.WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature)) {
137
+ throw new boom_1.Boom('noise intermediate certificate signature invalid', { statusCode: 400 })
138
+ }
139
+ if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
140
+ throw new boom_1.Boom('certification match failed', { statusCode: 400 })
141
+ }
142
+
143
+ // Extract server static key from leaf cert — used to cache for NoiseIkSession (fast reconnect)
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
+ // Encrypt our static key and do final ECDH
151
+ const keyEnc = session.processHandshakeFinish(
152
+ noiseKey.public instanceof Uint8Array ? noiseKey.public : new Uint8Array(noiseKey.public),
153
+ noiseKey.private instanceof Uint8Array ? noiseKey.private : new Uint8Array(noiseKey.private),
154
+ serverHello.ephemeral
155
+ )
156
+ return { keyEnc: Buffer.from(keyEnc), serverStaticPub }
157
+ },
158
+ encodeFrame: data => {
159
+ const u8 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
160
+ return Buffer.from(session.encodeFrameRaw(u8))
161
+ },
162
+ decodeFrame: async (newData, onFrame) => {
163
+ if (isWaitingForTransport) {
164
+ pendingBytes = pendingBytes ? Buffer.concat([pendingBytes, Buffer.from(newData)]) : Buffer.from(newData)
165
+ pendingOnFrame = onFrame
166
+ return
167
+ }
168
+
169
+ const u8 =
170
+ newData instanceof Uint8Array ? newData : new Uint8Array(newData.buffer, newData.byteOffset, newData.byteLength)
171
+ const frames = session.decodeFrame(u8)
172
+
173
+ for (let i = 0; i < frames.length; i++) {
174
+ const item = frames[i]
175
+ let frame
176
+ if (item instanceof Uint8Array) {
177
+ frame = Buffer.from(item)
178
+ } else {
179
+ try {
180
+ frame = rustNodeToJs(item.toJSON())
181
+ } catch (decodeErr) {
182
+ logger.debug({ err: decodeErr?.message }, '[noise] decode error')
183
+ continue
184
+ }
185
+ }
186
+ if (logger.level === 'trace') {
187
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame')
188
+ }
189
+ onFrame(frame)
190
+ }
191
+ }
192
+ }
193
+ }
194
+ 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