@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,640 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.isWABusinessPlatform =
4
+ exports.getCodeFromWSError =
5
+ exports.getCallStatusFromNode =
6
+ exports.getErrorCodeFromStreamError =
7
+ exports.getStatusFromReceiptType =
8
+ exports.generateMdTagPrefix =
9
+ exports.fetchLatestWaWebVersion =
10
+ exports.fetchLatestBaileysVersion =
11
+ exports.bindWaitForConnectionUpdate =
12
+ exports.generateMessageID =
13
+ exports.generateMessageIDV2 =
14
+ exports.delayCancellable =
15
+ exports.delay =
16
+ exports.debouncedTimeout =
17
+ exports.unixTimestampSeconds =
18
+ exports.toNumber =
19
+ exports.encodeBigEndian =
20
+ exports.generateRegistrationId =
21
+ exports.encodeWAMessage =
22
+ exports.generateParticipantHashV2 =
23
+ exports.unpadRandomMax16 =
24
+ exports.writeRandomPadMax16 =
25
+ exports.isStringNullOrEmpty =
26
+ exports.getKeyAuthor =
27
+ exports.BufferJSON =
28
+ exports.jitterDelay =
29
+ exports.exponentialBackoff =
30
+ exports.bytesToHex =
31
+ exports.hexToBytes =
32
+ exports.bytesToBase64Url =
33
+ exports.sha256Hex =
34
+ exports.hmacSha256 =
35
+ exports.normalizeJidBatch =
36
+ exports.sleep =
37
+ exports.withRetry =
38
+ void 0
39
+ exports.promiseTimeout = promiseTimeout
40
+ exports.bindWaitForEvent = bindWaitForEvent
41
+ exports.trimUndefined = trimUndefined
42
+ exports.bytesToCrockford = bytesToCrockford
43
+ exports.encodeNewsletterMessage = encodeNewsletterMessage
44
+ const boom_1 = require('@hapi/boom')
45
+ const crypto_1 = require('crypto')
46
+ const rb = require('whatsapp-rust-bridge-baron')
47
+ const DEFAULTS_1 = require('../Defaults')
48
+ const index_js_1 = require('../../WAProto/index.js')
49
+ const baileysVersion = DEFAULTS_1.VERSION
50
+ const Types_1 = require('../Types')
51
+ const WABinary_1 = require('../WABinary')
52
+ const crypto_2 = require('./crypto')
53
+ exports.BufferJSON = {
54
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
55
+ replacer: (k, value) => {
56
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
57
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
58
+ }
59
+ return value
60
+ },
61
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
+ reviver: (_, value) => {
63
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
64
+ return Buffer.from(value.data, 'base64')
65
+ }
66
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
67
+ const keys = Object.keys(value)
68
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
69
+ const values = Object.values(value)
70
+ if (values.every(v => typeof v === 'number')) {
71
+ return Buffer.from(values)
72
+ }
73
+ }
74
+ }
75
+ return value
76
+ }
77
+ }
78
+ const getKeyAuthor = (key, meId = 'me') =>
79
+ (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || ''
80
+ exports.getKeyAuthor = getKeyAuthor
81
+ const isStringNullOrEmpty = value =>
82
+ // eslint-disable-next-line eqeqeq
83
+ value == null || value === ''
84
+ exports.isStringNullOrEmpty = isStringNullOrEmpty
85
+ const writeRandomPadMax16 = msg => {
86
+ const pad = (0, crypto_1.randomBytes)(1)
87
+ const padLength = (pad[0] & 0x0f) + 1
88
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)])
89
+ }
90
+ exports.writeRandomPadMax16 = writeRandomPadMax16
91
+ const unpadRandomMax16 = e => {
92
+ const t = new Uint8Array(e)
93
+ if (0 === t.length) {
94
+ throw new Error('unpadPkcs7 given empty bytes')
95
+ }
96
+ var r = t[t.length - 1]
97
+ if (r > t.length) {
98
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
99
+ }
100
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
101
+ }
102
+ exports.unpadRandomMax16 = unpadRandomMax16
103
+ // code is inspired by whatsmeow
104
+ const generateParticipantHashV2 = participants => {
105
+ participants.sort()
106
+ const sha256Hash = (0, crypto_2.sha256)(Buffer.from(participants.join(''))).toString('base64')
107
+ return '2:' + sha256Hash.slice(0, 6)
108
+ }
109
+ exports.generateParticipantHashV2 = generateParticipantHashV2
110
+ const encodeWAMessage = message => (0, exports.writeRandomPadMax16)(index_js_1.proto.Message.encode(message).finish())
111
+ exports.encodeWAMessage = encodeWAMessage
112
+ const generateRegistrationId = () => {
113
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383
114
+ }
115
+ exports.generateRegistrationId = generateRegistrationId
116
+ const encodeBigEndian = (e, t = 4) => {
117
+ let r = e
118
+ const a = new Uint8Array(t)
119
+ for (let i = t - 1; i >= 0; i--) {
120
+ a[i] = 255 & r
121
+ r >>>= 8
122
+ }
123
+ return a
124
+ }
125
+ exports.encodeBigEndian = encodeBigEndian
126
+ const toNumber = t => (typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0)
127
+ exports.toNumber = toNumber
128
+ /** unix timestamp of a date in seconds */
129
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
130
+ exports.unixTimestampSeconds = unixTimestampSeconds
131
+ const debouncedTimeout = (intervalMs = 1000, task) => {
132
+ let timeout
133
+ return {
134
+ start: (newIntervalMs, newTask) => {
135
+ task = newTask || task
136
+ intervalMs = newIntervalMs || intervalMs
137
+ timeout && clearTimeout(timeout)
138
+ timeout = setTimeout(() => task?.(), intervalMs)
139
+ },
140
+ cancel: () => {
141
+ timeout && clearTimeout(timeout)
142
+ timeout = undefined
143
+ },
144
+ setTask: newTask => (task = newTask),
145
+ setInterval: newInterval => (intervalMs = newInterval)
146
+ }
147
+ }
148
+ exports.debouncedTimeout = debouncedTimeout
149
+ const delay = ms => (0, exports.delayCancellable)(ms).delay
150
+ exports.delay = delay
151
+ const delayCancellable = ms => {
152
+ const stack = new Error().stack
153
+ let timeout
154
+ let reject
155
+ const delay = new Promise((resolve, _reject) => {
156
+ timeout = setTimeout(resolve, ms)
157
+ reject = _reject
158
+ })
159
+ const cancel = () => {
160
+ clearTimeout(timeout)
161
+ reject(
162
+ new boom_1.Boom('Cancelled', {
163
+ statusCode: 500,
164
+ data: {
165
+ stack
166
+ }
167
+ })
168
+ )
169
+ }
170
+ return { delay, cancel }
171
+ }
172
+ exports.delayCancellable = delayCancellable
173
+ async function promiseTimeout(ms, promise) {
174
+ if (!ms) {
175
+ return new Promise(promise)
176
+ }
177
+ const stack = new Error().stack
178
+ // Create a promise that rejects in <ms> milliseconds
179
+ const { delay, cancel } = (0, exports.delayCancellable)(ms)
180
+ const p = new Promise((resolve, reject) => {
181
+ delay
182
+ .then(() =>
183
+ reject(
184
+ new boom_1.Boom('Timed Out', {
185
+ statusCode: Types_1.DisconnectReason.timedOut,
186
+ data: {
187
+ stack
188
+ }
189
+ })
190
+ )
191
+ )
192
+ .catch(err => reject(err))
193
+ promise(resolve, reject)
194
+ }).finally(cancel)
195
+ return p
196
+ }
197
+ // inspired from whatsmeow code
198
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
199
+ const generateMessageIDV2 = userId => {
200
+ const data = Buffer.alloc(8 + 20 + 16)
201
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
202
+ if (userId) {
203
+ const id = (0, WABinary_1.jidDecode)(userId)
204
+ if (id?.user) {
205
+ data.write(id.user, 8)
206
+ data.write('@c.us', 8 + id.user.length)
207
+ }
208
+ }
209
+ const random = (0, crypto_1.randomBytes)(16)
210
+ random.copy(data, 28)
211
+ const hash = Buffer.from(rb.sha256(data))
212
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18)
213
+ }
214
+ exports.generateMessageIDV2 = generateMessageIDV2
215
+ // generate a random ID to attach to a message
216
+ const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase()
217
+ exports.generateMessageID = generateMessageID
218
+ function bindWaitForEvent(ev, event) {
219
+ return async (check, timeoutMs) => {
220
+ let listener
221
+ let closeListener
222
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
223
+ closeListener = ({ connection, lastDisconnect }) => {
224
+ if (connection === 'close') {
225
+ reject(
226
+ lastDisconnect?.error ||
227
+ new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed })
228
+ )
229
+ }
230
+ }
231
+ ev.on('connection.update', closeListener)
232
+ listener = async update => {
233
+ if (await check(update)) {
234
+ resolve()
235
+ }
236
+ }
237
+ ev.on(event, listener)
238
+ }).finally(() => {
239
+ ev.off(event, listener)
240
+ ev.off('connection.update', closeListener)
241
+ })
242
+ }
243
+ }
244
+ const bindWaitForConnectionUpdate = ev => bindWaitForEvent(ev, 'connection.update')
245
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate
246
+ /**
247
+ * utility that fetches latest baileys version from the master branch.
248
+ * Use to ensure your WA connection is always on the latest version
249
+ */
250
+ const fetchLatestBaileysVersion = async (options = {}) => {
251
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts'
252
+ try {
253
+ const response = await fetch(URL, {
254
+ dispatcher: options.dispatcher,
255
+ method: 'GET',
256
+ headers: options.headers
257
+ })
258
+ if (!response.ok) {
259
+ throw new boom_1.Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, {
260
+ statusCode: response.status
261
+ })
262
+ }
263
+ const text = await response.text()
264
+ // Extract version from line 7 (const version = [...])
265
+ const lines = text.split('\n')
266
+ const versionLine = lines[6] // Line 7 (0-indexed)
267
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/)
268
+ if (versionMatch) {
269
+ const version = [parseInt(versionMatch[1], 10), parseInt(versionMatch[2], 10), parseInt(versionMatch[3], 10)]
270
+ return {
271
+ version,
272
+ isLatest: true
273
+ }
274
+ } else {
275
+ throw new Error('Could not parse version from Defaults/index.ts')
276
+ }
277
+ } catch (error) {
278
+ return {
279
+ version: baileysVersion,
280
+ isLatest: false,
281
+ error
282
+ }
283
+ }
284
+ }
285
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion
286
+ /**
287
+ * A utility that fetches the latest web version of whatsapp.
288
+ * Use to ensure your WA connection is always on the latest version
289
+ */
290
+ const fetchLatestWaWebVersion = async (options = {}) => {
291
+ try {
292
+ // Absolute minimal headers required to bypass anti-bot detection
293
+ const defaultHeaders = {
294
+ 'sec-fetch-site': 'none',
295
+ 'user-agent':
296
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
297
+ }
298
+ const headers = { ...defaultHeaders, ...options.headers }
299
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
300
+ ...options,
301
+ method: 'GET',
302
+ headers
303
+ })
304
+ if (!response.ok) {
305
+ throw new boom_1.Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status })
306
+ }
307
+ const data = await response.text()
308
+ const regex = /\\?"client_revision\\?":\s*(\d+)/
309
+ const match = data.match(regex)
310
+ if (!match?.[1]) {
311
+ return {
312
+ version: baileysVersion,
313
+ isLatest: false,
314
+ error: {
315
+ message: 'Could not find client revision in the fetched content'
316
+ }
317
+ }
318
+ }
319
+ const clientRevision = match[1]
320
+ return {
321
+ version: [2, 3000, +clientRevision],
322
+ isLatest: true
323
+ }
324
+ } catch (error) {
325
+ return {
326
+ version: baileysVersion,
327
+ isLatest: false,
328
+ error
329
+ }
330
+ }
331
+ }
332
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion
333
+ /** unique message tag prefix for MD clients */
334
+ const generateMdTagPrefix = () => {
335
+ const bytes = (0, crypto_1.randomBytes)(4)
336
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
337
+ }
338
+ exports.generateMdTagPrefix = generateMdTagPrefix
339
+ const STATUS_MAP = {
340
+ sender: index_js_1.proto.WebMessageInfo.Status.SERVER_ACK,
341
+ played: index_js_1.proto.WebMessageInfo.Status.PLAYED,
342
+ 'played-self': index_js_1.proto.WebMessageInfo.Status.PLAYED,
343
+ read: index_js_1.proto.WebMessageInfo.Status.READ,
344
+ 'read-self': index_js_1.proto.WebMessageInfo.Status.READ
345
+ }
346
+ /**
347
+ * Given a type of receipt, returns what the new status of the message should be
348
+ * @param type type from receipt
349
+ */
350
+ const getStatusFromReceiptType = type => {
351
+ const status = STATUS_MAP[type]
352
+ if (typeof type === 'undefined') {
353
+ return index_js_1.proto.WebMessageInfo.Status.DELIVERY_ACK
354
+ }
355
+ return status
356
+ }
357
+ exports.getStatusFromReceiptType = getStatusFromReceiptType
358
+ const CODE_MAP = {
359
+ conflict: Types_1.DisconnectReason.connectionReplaced
360
+ }
361
+ /**
362
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
363
+ * @param reason the string reason given, eg. "conflict"
364
+ */
365
+ const getErrorCodeFromStreamError = node => {
366
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node)
367
+ let reason = reasonNode?.tag || 'unknown'
368
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession)
369
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
370
+ reason = 'restart required'
371
+ }
372
+ return {
373
+ reason,
374
+ statusCode
375
+ }
376
+ }
377
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError
378
+ const getCallStatusFromNode = ({ tag, attrs }) => {
379
+ let status
380
+ switch (tag) {
381
+ case 'offer':
382
+ case 'offer_notice':
383
+ status = 'offer'
384
+ break
385
+ case 'terminate':
386
+ // Map known end-call reasons to distinct statuses
387
+ switch (attrs.reason) {
388
+ case 'timeout':
389
+ case 'Timeout':
390
+ status = 'timeout'
391
+ break
392
+ case 'RejectDoNotDisturb':
393
+ status = 'reject_do_not_disturb'
394
+ break
395
+ case 'MicPermissionDenied':
396
+ status = 'mic_permission_denied'
397
+ break
398
+ case 'CameraPermissionDenied':
399
+ status = 'camera_permission_denied'
400
+ break
401
+ case 'RemoteBusy':
402
+ status = 'remote_busy'
403
+ break
404
+ case 'RemoteOffline':
405
+ status = 'remote_offline'
406
+ break
407
+ default:
408
+ // fired when accepted/rejected/caller hangs up
409
+ status = 'terminate'
410
+ break
411
+ }
412
+ break
413
+ case 'reject':
414
+ status = 'reject'
415
+ break
416
+ case 'accept':
417
+ status = 'accept'
418
+ break
419
+ case 'preaccept':
420
+ status = 'preaccept'
421
+ break
422
+ case 'accept_ack':
423
+ status = 'accept_ack'
424
+ break
425
+ case 'enc-rekey':
426
+ case 'enc_rekey':
427
+ status = 'enc_rekey'
428
+ break
429
+ case 'peer_state':
430
+ status = 'peer_state'
431
+ break
432
+ case 'group_info':
433
+ status = 'group_info'
434
+ break
435
+ case 'video_state':
436
+ status = 'video_state'
437
+ break
438
+ case 'video_state_ack':
439
+ status = 'video_state_ack'
440
+ break
441
+ case 'flow_control':
442
+ status = 'flow_control'
443
+ break
444
+ case 'relaylatency':
445
+ status = 'relaylatency'
446
+ break
447
+ case 'mute_v2':
448
+ status = 'mute'
449
+ break
450
+ case 'waiting_room_request':
451
+ status = 'waiting_room_request'
452
+ break
453
+ case 'signal':
454
+ // Numeric type mapping for <signal type="N"/> child nodes
455
+ switch (attrs.type) {
456
+ case '13':
457
+ status = 'preaccept'
458
+ break
459
+ case '15':
460
+ status = 'video_state'
461
+ break
462
+ case '17':
463
+ status = 'group_info'
464
+ break
465
+ case '20':
466
+ status = 'video_state_ack'
467
+ break
468
+ case '21':
469
+ status = 'flow_control'
470
+ break
471
+ case '23':
472
+ status = 'accept_ack'
473
+ break
474
+ case '1002':
475
+ case '1007':
476
+ status = 'peer_state'
477
+ break
478
+ case '1008':
479
+ status = 'enc_rekey'
480
+ break
481
+ case '12':
482
+ status = 'mute'
483
+ break
484
+ default:
485
+ status = 'ringing'
486
+ break
487
+ }
488
+ break
489
+ default:
490
+ status = 'ringing'
491
+ break
492
+ }
493
+ return status
494
+ }
495
+ exports.getCallStatusFromNode = getCallStatusFromNode
496
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
497
+ const getCodeFromWSError = error => {
498
+ let statusCode = 500
499
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
500
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length)
501
+ if (!Number.isNaN(code) && code >= 400) {
502
+ statusCode = code
503
+ }
504
+ } else if (
505
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
506
+ error?.code?.startsWith('E') ||
507
+ error?.message?.includes('timed out')
508
+ ) {
509
+ // handle ETIMEOUT, ENOTFOUND etc
510
+ statusCode = 408
511
+ }
512
+ return statusCode
513
+ }
514
+ exports.getCodeFromWSError = getCodeFromWSError
515
+ /**
516
+ * Is the given platform WA business
517
+ * @param platform AuthenticationCreds.platform
518
+ */
519
+ const isWABusinessPlatform = platform => {
520
+ return platform === 'smbi' || platform === 'smba'
521
+ }
522
+ exports.isWABusinessPlatform = isWABusinessPlatform
523
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
524
+ function trimUndefined(obj) {
525
+ for (const key in obj) {
526
+ if (typeof obj[key] === 'undefined') {
527
+ delete obj[key]
528
+ }
529
+ }
530
+ return obj
531
+ }
532
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ'
533
+ function bytesToCrockford(buffer) {
534
+ let value = 0
535
+ let bitCount = 0
536
+ const crockford = []
537
+ for (const element of buffer) {
538
+ value = (value << 8) | (element & 0xff)
539
+ bitCount += 8
540
+ while (bitCount >= 5) {
541
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
542
+ bitCount -= 5
543
+ }
544
+ }
545
+ if (bitCount > 0) {
546
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
547
+ }
548
+ return crockford.join('')
549
+ }
550
+ function encodeNewsletterMessage(message) {
551
+ return index_js_1.proto.Message.encode(message).finish()
552
+ }
553
+
554
+ /**
555
+ * Add human-like jitter to a base delay
556
+ * @param baseMs base delay in milliseconds
557
+ * @param varianceFraction fraction of baseMs to use as variance (0–1), default 0.3
558
+ */
559
+ const jitterDelay = (baseMs, varianceFraction = 0.3) => {
560
+ const variance = baseMs * varianceFraction
561
+ return baseMs + (Math.random() * 2 - 1) * variance
562
+ }
563
+ exports.jitterDelay = jitterDelay
564
+
565
+ /**
566
+ * Compute exponential backoff delay for a given attempt number (0-based)
567
+ * @param attempt attempt index (0 = first retry)
568
+ * @param baseMs starting delay in ms (default 500)
569
+ * @param maxMs maximum delay cap in ms (default 30000)
570
+ */
571
+ const exponentialBackoff = (attempt, baseMs = 500, maxMs = 30000) => {
572
+ return Math.min(baseMs * Math.pow(2, attempt), maxMs)
573
+ }
574
+ exports.exponentialBackoff = exponentialBackoff
575
+
576
+ /** Convert buffer/Uint8Array to hex string */
577
+ const bytesToHex = buf => Buffer.from(buf).toString('hex')
578
+ exports.bytesToHex = bytesToHex
579
+
580
+ /** Convert hex string to Buffer */
581
+ const hexToBytes = hex => Buffer.from(hex, 'hex')
582
+ exports.hexToBytes = hexToBytes
583
+
584
+ /** Convert buffer to base64url string */
585
+ const bytesToBase64Url = buf => Buffer.from(buf).toString('base64url')
586
+ exports.bytesToBase64Url = bytesToBase64Url
587
+
588
+ /** Compute SHA-256 hex digest of data */
589
+ const sha256Hex = data => (0, crypto_1.createHash)('sha256').update(data).digest('hex')
590
+ exports.sha256Hex = sha256Hex
591
+
592
+ /** Compute HMAC-SHA-256 of data with key, returns Buffer */
593
+ const hmacSha256 = (data, key) => (0, crypto_1.createHmac)('sha256', key).update(data).digest()
594
+ exports.hmacSha256 = hmacSha256
595
+
596
+ /**
597
+ * Normalize and deduplicate an array of JIDs
598
+ */
599
+ const normalizeJidBatch = (jids, normalizer) => {
600
+ const seen = new Set()
601
+ const result = []
602
+ for (const jid of jids) {
603
+ if (!jid) continue
604
+ const normalized = normalizer ? normalizer(jid) : jid
605
+ if (!seen.has(normalized)) {
606
+ seen.add(normalized)
607
+ result.push(normalized)
608
+ }
609
+ }
610
+ return result
611
+ }
612
+ exports.normalizeJidBatch = normalizeJidBatch
613
+
614
+ /**
615
+ * Sleep for a given number of milliseconds, returns a cancellable promise
616
+ */
617
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
618
+ exports.sleep = sleep
619
+
620
+ /**
621
+ * Run an async function with retry using exponential backoff
622
+ * @param fn async function to retry
623
+ * @param maxAttempts maximum number of attempts
624
+ * @param baseDelayMs base delay between retries
625
+ */
626
+ const withRetry = async (fn, maxAttempts = 3, baseDelayMs = 500) => {
627
+ let lastErr
628
+ for (let i = 0; i < maxAttempts; i++) {
629
+ try {
630
+ return await fn()
631
+ } catch (err) {
632
+ lastErr = err
633
+ if (i < maxAttempts - 1) {
634
+ await sleep(exponentialBackoff(i, baseDelayMs))
635
+ }
636
+ }
637
+ }
638
+ throw lastErr
639
+ }
640
+ exports.withRetry = withRetry
@@ -0,0 +1,60 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.processGroupHistory = exports.decodeGroupHistory = void 0
4
+ const zlib_1 = require('zlib')
5
+ const index_js_1 = require('../../WAProto/index.js')
6
+
7
+ /**
8
+ * Decode a GroupHistory protobuf blob (community/group history container).
9
+ * @param buffer raw bytes, optionally zlib-compressed
10
+ * @param options.inflate try zlib.inflateSync first, falling back to raw bytes (default true)
11
+ * @param options.withMessageBytes decode the GroupHistoryWithMessageBytes variant,
12
+ * expanding each entry's messageBytes into a WebMessageInfo (default false)
13
+ */
14
+ const decodeGroupHistory = (buffer, options = {}) => {
15
+ const { inflate = true, withMessageBytes = false } = options
16
+ if (!Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array)) {
17
+ throw new TypeError('decodeGroupHistory: buffer must be Buffer or Uint8Array')
18
+ }
19
+ let data = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer)
20
+ if (inflate) {
21
+ try {
22
+ data = zlib_1.inflateSync(data)
23
+ } catch {
24
+ // not zlib-compressed — use raw bytes
25
+ }
26
+ }
27
+ if (withMessageBytes) {
28
+ const decoded = index_js_1.proto.GroupHistoryWithMessageBytes.decode(data)
29
+ const expand = list =>
30
+ (list || []).map(entry =>
31
+ entry?.messageBytes ? index_js_1.proto.WebMessageInfo.decode(entry.messageBytes) : { key: entry?.key }
32
+ )
33
+ return {
34
+ messages: expand(decoded.messages),
35
+ commentMessages: expand(decoded.commentMessages),
36
+ outOfWindowPinnedMessages: expand(decoded.outOfWindowPinnedMessages),
37
+ uncountedAssociatedMessageLists: (decoded.uncountedAssociatedMessageLists || []).map(l => ({
38
+ parentMessage: l.parentMessage,
39
+ messages: expand(l.messages)
40
+ }))
41
+ }
42
+ }
43
+ return index_js_1.proto.GroupHistory.decode(data)
44
+ }
45
+ exports.decodeGroupHistory = decodeGroupHistory
46
+
47
+ /**
48
+ * Normalize a decoded GroupHistory into stable message buckets.
49
+ * @param groupHistory a decoded proto.GroupHistory (or the withMessageBytes shape)
50
+ */
51
+ const processGroupHistory = groupHistory => {
52
+ const gh = groupHistory || {}
53
+ return {
54
+ messages: gh.messages || [],
55
+ commentMessages: gh.commentMessages || [],
56
+ outOfWindowPinnedMessages: gh.outOfWindowPinnedMessages || [],
57
+ uncountedAssociatedMessageLists: gh.uncountedAssociatedMessageLists || []
58
+ }
59
+ }
60
+ exports.processGroupHistory = processGroupHistory