@skycodee/baileys 8.0.4 → 8.0.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 (224) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +352 -520
  3. package/WAProto/index.js +558 -4154
  4. package/lib/Defaults/index.js +123 -0
  5. package/lib/Defaults/index.js.bak +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +13 -0
  10. package/lib/Signal/Group/group-session-builder.js +32 -0
  11. package/lib/Signal/Group/group_cipher.js +84 -0
  12. package/lib/Signal/Group/index.js +13 -0
  13. package/lib/Signal/Group/keyhelper.js +20 -0
  14. package/lib/Signal/Group/sender-chain-key.js +28 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-message.js +68 -0
  17. package/lib/Signal/Group/sender-key-name.js +52 -0
  18. package/lib/Signal/Group/sender-key-record.js +43 -0
  19. package/lib/Signal/Group/sender-key-state.js +86 -0
  20. package/lib/Signal/Group/sender-message-key.js +28 -0
  21. package/lib/Signal/libsignal.js +324 -0
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -0
  24. package/lib/Socket/Client/types.js +13 -0
  25. package/lib/Socket/Client/websocket.js +52 -0
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +377 -0
  28. package/lib/Socket/chats.js +885 -0
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/groups.js +312 -0
  31. package/lib/Socket/index.js +16 -0
  32. package/lib/Socket/messages-recv.js +1163 -0
  33. package/lib/Socket/messages-send.js +1100 -0
  34. package/lib/Socket/mex.js +45 -0
  35. package/lib/Socket/newsletter.js +247 -0
  36. package/lib/Socket/socket.js +820 -0
  37. package/lib/Store/index.js +6 -0
  38. package/lib/Store/make-cache-manager-store.js +75 -0
  39. package/lib/Store/make-in-memory-store.js +290 -0
  40. package/lib/Store/make-ordered-dictionary.js +79 -0
  41. package/lib/Store/object-repository.js +25 -0
  42. package/lib/Types/Auth.js +3 -0
  43. package/lib/Types/Bussines.js +3 -0
  44. package/lib/Types/Call.js +3 -0
  45. package/lib/Types/Chat.js +9 -0
  46. package/lib/Types/Contact.js +3 -0
  47. package/lib/Types/Events.js +3 -0
  48. package/lib/Types/GroupMetadata.js +3 -0
  49. package/lib/Types/Label.js +25 -0
  50. package/lib/Types/LabelAssociation.js +7 -0
  51. package/lib/Types/Message.js +12 -0
  52. package/lib/Types/Newsletter.js +33 -0
  53. package/lib/Types/Newsletter.js.bak +33 -0
  54. package/lib/Types/Product.js +3 -0
  55. package/lib/Types/Signal.js +3 -0
  56. package/lib/Types/Socket.js +4 -0
  57. package/lib/Types/State.js +11 -0
  58. package/lib/Types/USync.js +3 -0
  59. package/lib/Types/index.js +28 -0
  60. package/lib/Utils/auth-utils.js +219 -0
  61. package/lib/Utils/baileys-event-stream.js +44 -0
  62. package/lib/Utils/browser-utils.js +25 -0
  63. package/lib/Utils/business.js +233 -0
  64. package/lib/Utils/chat-utils.js +752 -0
  65. package/lib/Utils/crypto.js +130 -0
  66. package/lib/Utils/decode-wa-message.js +267 -0
  67. package/lib/Utils/event-buffer.js +528 -0
  68. package/lib/Utils/generics.js +355 -0
  69. package/lib/Utils/history.js +87 -0
  70. package/lib/Utils/index.js +21 -0
  71. package/lib/Utils/link-preview.js +81 -0
  72. package/lib/Utils/logger.js +5 -0
  73. package/lib/Utils/lt-hash.js +45 -0
  74. package/lib/Utils/make-mutex.js +36 -0
  75. package/lib/Utils/message-retry-manager.js +113 -0
  76. package/lib/Utils/messages-media.js +627 -0
  77. package/lib/Utils/messages.js +909 -0
  78. package/lib/Utils/noise-handler.js +144 -0
  79. package/lib/Utils/pre-key-manager.js +85 -0
  80. package/lib/Utils/process-message.js +341 -0
  81. package/lib/Utils/signal.js +161 -0
  82. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  83. package/lib/Utils/validate-connection.js +200 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +240 -0
  86. package/lib/WABinary/encode.js +218 -0
  87. package/lib/WABinary/generic-utils.js +189 -0
  88. package/lib/WABinary/index.js +7 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +3 -0
  91. package/lib/WAM/BinaryInfo.js +11 -0
  92. package/lib/WAM/constants.js +22853 -0
  93. package/lib/WAM/encode.js +154 -0
  94. package/lib/WAM/index.js +5 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/index.js +6 -0
  102. package/lib/WAUSync/USyncQuery.js +90 -0
  103. package/lib/WAUSync/USyncUser.js +24 -0
  104. package/lib/WAUSync/index.js +5 -0
  105. package/lib/index.js +21 -0
  106. package/package.json +84 -57
  107. package/README.md +0 -1312
  108. package/WAProto/GenerateStatics.sh +0 -3
  109. package/WAProto/fix-imports.js +0 -81
  110. package/WAProto/index.d.ts +0 -14017
  111. package/engine-requirements.js +0 -10
  112. package/src/Defaults/baileys-version.json +0 -1
  113. package/src/Defaults/index.ts +0 -149
  114. package/src/Signal/Group/ciphertext-message.ts +0 -9
  115. package/src/Signal/Group/group-session-builder.ts +0 -56
  116. package/src/Signal/Group/group_cipher.ts +0 -117
  117. package/src/Signal/Group/index.ts +0 -11
  118. package/src/Signal/Group/keyhelper.ts +0 -28
  119. package/src/Signal/Group/sender-chain-key.ts +0 -34
  120. package/src/Signal/Group/sender-key-distribution-message.ts +0 -95
  121. package/src/Signal/Group/sender-key-message.ts +0 -96
  122. package/src/Signal/Group/sender-key-name.ts +0 -66
  123. package/src/Signal/Group/sender-key-record.ts +0 -69
  124. package/src/Signal/Group/sender-key-state.ts +0 -134
  125. package/src/Signal/Group/sender-message-key.ts +0 -36
  126. package/src/Signal/libsignal.ts +0 -521
  127. package/src/Signal/lid-mapping.ts +0 -328
  128. package/src/Socket/Client/index.ts +0 -2
  129. package/src/Socket/Client/types.ts +0 -22
  130. package/src/Socket/Client/websocket.ts +0 -63
  131. package/src/Socket/business.ts +0 -424
  132. package/src/Socket/chats.ts +0 -1272
  133. package/src/Socket/communities.ts +0 -477
  134. package/src/Socket/groups.ts +0 -361
  135. package/src/Socket/index.ts +0 -15
  136. package/src/Socket/messages-recv.ts +0 -1668
  137. package/src/Socket/messages-send.ts +0 -1296
  138. package/src/Socket/mex.ts +0 -58
  139. package/src/Socket/newsletter.ts +0 -229
  140. package/src/Socket/socket.ts +0 -1184
  141. package/src/Types/Auth.ts +0 -116
  142. package/src/Types/Bussines.ts +0 -20
  143. package/src/Types/Call.ts +0 -15
  144. package/src/Types/Chat.ts +0 -138
  145. package/src/Types/Contact.ts +0 -24
  146. package/src/Types/Events.ts +0 -159
  147. package/src/Types/GroupMetadata.ts +0 -70
  148. package/src/Types/Label.ts +0 -48
  149. package/src/Types/LabelAssociation.ts +0 -35
  150. package/src/Types/Message.ts +0 -380
  151. package/src/Types/Newsletter.ts +0 -98
  152. package/src/Types/Product.ts +0 -85
  153. package/src/Types/Signal.ts +0 -76
  154. package/src/Types/Socket.ts +0 -150
  155. package/src/Types/State.ts +0 -43
  156. package/src/Types/USync.ts +0 -27
  157. package/src/Types/globals.d.ts +0 -8
  158. package/src/Types/index.ts +0 -67
  159. package/src/Utils/auth-utils.ts +0 -368
  160. package/src/Utils/browser-utils.ts +0 -31
  161. package/src/Utils/business.ts +0 -286
  162. package/src/Utils/chat-utils.ts +0 -974
  163. package/src/Utils/crypto.ts +0 -147
  164. package/src/Utils/decode-wa-message.ts +0 -355
  165. package/src/Utils/event-buffer.ts +0 -692
  166. package/src/Utils/generics.ts +0 -474
  167. package/src/Utils/history.ts +0 -161
  168. package/src/Utils/identity-change-handler.ts +0 -83
  169. package/src/Utils/index.ts +0 -19
  170. package/src/Utils/link-preview.ts +0 -111
  171. package/src/Utils/logger.ts +0 -13
  172. package/src/Utils/lt-hash.ts +0 -8
  173. package/src/Utils/make-mutex.ts +0 -42
  174. package/src/Utils/message-retry-manager.ts +0 -295
  175. package/src/Utils/messages-media.ts +0 -984
  176. package/src/Utils/messages.ts +0 -1097
  177. package/src/Utils/noise-handler.ts +0 -268
  178. package/src/Utils/pre-key-manager.ts +0 -126
  179. package/src/Utils/process-message.ts +0 -670
  180. package/src/Utils/reporting-utils.ts +0 -344
  181. package/src/Utils/signal.ts +0 -214
  182. package/src/Utils/sync-action-utils.ts +0 -74
  183. package/src/Utils/tc-token-utils.ts +0 -34
  184. package/src/Utils/use-multi-file-auth-state.ts +0 -136
  185. package/src/Utils/validate-connection.ts +0 -253
  186. package/src/WABinary/constants.ts +0 -1305
  187. package/src/WABinary/decode.ts +0 -308
  188. package/src/WABinary/encode.ts +0 -258
  189. package/src/WABinary/generic-utils.ts +0 -141
  190. package/src/WABinary/index.ts +0 -5
  191. package/src/WABinary/jid-utils.ts +0 -128
  192. package/src/WABinary/types.ts +0 -17
  193. package/src/WAM/BinaryInfo.ts +0 -12
  194. package/src/WAM/constants.ts +0 -22889
  195. package/src/WAM/encode.ts +0 -169
  196. package/src/WAM/index.ts +0 -3
  197. package/src/WAUSync/Protocols/USyncContactProtocol.ts +0 -32
  198. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +0 -78
  199. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +0 -35
  200. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +0 -44
  201. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +0 -76
  202. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +0 -33
  203. package/src/WAUSync/Protocols/index.ts +0 -4
  204. package/src/WAUSync/USyncQuery.ts +0 -133
  205. package/src/WAUSync/USyncUser.ts +0 -32
  206. package/src/WAUSync/index.ts +0 -3
  207. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +0 -22
  208. package/src/__tests__/Signal/lid-mapping.test.ts +0 -47
  209. package/src/__tests__/Socket/identity-change-handling.test.ts +0 -207
  210. package/src/__tests__/TestUtils/session.ts +0 -47
  211. package/src/__tests__/Utils/generics.test.ts +0 -70
  212. package/src/__tests__/Utils/history.test.ts +0 -362
  213. package/src/__tests__/Utils/messages-media.test.ts +0 -405
  214. package/src/__tests__/Utils/noise-handler.test.ts +0 -339
  215. package/src/__tests__/Utils/process-message.test.ts +0 -138
  216. package/src/__tests__/Utils/process-sync-action.test.ts +0 -359
  217. package/src/__tests__/Utils/reporting-utils.test.ts +0 -160
  218. package/src/__tests__/Utils/signal.test.ts +0 -69
  219. package/src/__tests__/Utils/sync-action-utils.test.ts +0 -183
  220. package/src/__tests__/binary/connection-deadlock.test.ts +0 -54
  221. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +0 -60
  222. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +0 -644
  223. package/src/__tests__/proto-tojson-long.test.ts +0 -31
  224. package/src/index.ts +0 -13
@@ -1,474 +0,0 @@
1
- import { Boom } from '@hapi/boom'
2
- import { createHash, randomBytes } from 'crypto'
3
- import { proto } from '../../WAProto/index.js'
4
- const baileysVersion = [2, 3000, 1033846690]
5
- import type {
6
- BaileysEventEmitter,
7
- BaileysEventMap,
8
- ConnectionState,
9
- WACallUpdateType,
10
- WAMessageKey,
11
- WAVersion
12
- } from '../Types'
13
- import { DisconnectReason } from '../Types'
14
- import { type BinaryNode, getAllBinaryNodeChildren, jidDecode } from '../WABinary'
15
- import { sha256 } from './crypto'
16
-
17
- export const BufferJSON = {
18
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
- replacer: (k: any, value: any) => {
20
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
21
- return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
22
- }
23
-
24
- return value
25
- },
26
-
27
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
- reviver: (_: any, value: any) => {
29
- if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
30
- return Buffer.from(value.data, 'base64')
31
- }
32
-
33
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
34
- const keys = Object.keys(value)
35
- if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
36
- const values = Object.values(value)
37
- if (values.every(v => typeof v === 'number')) {
38
- return Buffer.from(values)
39
- }
40
- }
41
- }
42
-
43
- return value
44
- }
45
- }
46
-
47
- export const getKeyAuthor = (key: WAMessageKey | undefined | null, meId = 'me') =>
48
- (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || ''
49
-
50
- export const isStringNullOrEmpty = (value: string | null | undefined): value is null | undefined | '' =>
51
- // eslint-disable-next-line eqeqeq
52
- value == null || value === ''
53
-
54
- export const writeRandomPadMax16 = (msg: Uint8Array) => {
55
- const pad = randomBytes(1)
56
- const padLength = (pad[0]! & 0x0f) + 1
57
-
58
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)])
59
- }
60
-
61
- export const unpadRandomMax16 = (e: Uint8Array | Buffer) => {
62
- const t = new Uint8Array(e)
63
- if (0 === t.length) {
64
- throw new Error('unpadPkcs7 given empty bytes')
65
- }
66
-
67
- var r = t[t.length - 1]!
68
- if (r > t.length) {
69
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
70
- }
71
-
72
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
73
- }
74
-
75
- // code is inspired by whatsmeow
76
- export const generateParticipantHashV2 = (participants: string[]): string => {
77
- participants.sort()
78
- const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64')
79
- return '2:' + sha256Hash.slice(0, 6)
80
- }
81
-
82
- export const encodeWAMessage = (message: proto.IMessage) => writeRandomPadMax16(proto.Message.encode(message).finish())
83
-
84
- export const generateRegistrationId = (): number => {
85
- return Uint16Array.from(randomBytes(2))[0]! & 16383
86
- }
87
-
88
- export const encodeBigEndian = (e: number, t = 4) => {
89
- let r = e
90
- const a = new Uint8Array(t)
91
- for (let i = t - 1; i >= 0; i--) {
92
- a[i] = 255 & r
93
- r >>>= 8
94
- }
95
-
96
- return a
97
- }
98
-
99
- export const toNumber = (t: Long | number | null | undefined): number =>
100
- typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : (t as Long).low) : t || 0
101
-
102
- /** unix timestamp of a date in seconds */
103
- export const unixTimestampSeconds = (date: Date = new Date()) => Math.floor(date.getTime() / 1000)
104
-
105
- export type DebouncedTimeout = ReturnType<typeof debouncedTimeout>
106
-
107
- export const debouncedTimeout = (intervalMs = 1000, task?: () => void) => {
108
- let timeout: NodeJS.Timeout | undefined
109
- return {
110
- start: (newIntervalMs?: number, newTask?: () => void) => {
111
- task = newTask || task
112
- intervalMs = newIntervalMs || intervalMs
113
- timeout && clearTimeout(timeout)
114
- timeout = setTimeout(() => task?.(), intervalMs)
115
- },
116
- cancel: () => {
117
- timeout && clearTimeout(timeout)
118
- timeout = undefined
119
- },
120
- setTask: (newTask: () => void) => (task = newTask),
121
- setInterval: (newInterval: number) => (intervalMs = newInterval)
122
- }
123
- }
124
-
125
- export const delay = (ms: number) => delayCancellable(ms).delay
126
-
127
- export const delayCancellable = (ms: number) => {
128
- const stack = new Error().stack
129
- let timeout: NodeJS.Timeout
130
- let reject: (error: any) => void
131
- const delay: Promise<void> = new Promise((resolve, _reject) => {
132
- timeout = setTimeout(resolve, ms)
133
- reject = _reject
134
- })
135
- const cancel = () => {
136
- clearTimeout(timeout)
137
- reject(
138
- new Boom('Cancelled', {
139
- statusCode: 500,
140
- data: {
141
- stack
142
- }
143
- })
144
- )
145
- }
146
-
147
- return { delay, cancel }
148
- }
149
-
150
- export async function promiseTimeout<T>(
151
- ms: number | undefined,
152
- promise: (resolve: (v: T) => void, reject: (error: any) => void) => void
153
- ) {
154
- if (!ms) {
155
- return new Promise(promise)
156
- }
157
-
158
- const stack = new Error().stack
159
- // Create a promise that rejects in <ms> milliseconds
160
- const { delay, cancel } = delayCancellable(ms)
161
- const p = new Promise((resolve, reject) => {
162
- delay
163
- .then(() =>
164
- reject(
165
- new Boom('Timed Out', {
166
- statusCode: DisconnectReason.timedOut,
167
- data: {
168
- stack
169
- }
170
- })
171
- )
172
- )
173
- .catch(err => reject(err))
174
-
175
- promise(resolve, reject)
176
- }).finally(cancel)
177
- return p as Promise<T>
178
- }
179
-
180
- // inspired from whatsmeow code
181
- // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
182
- export const generateMessageIDV2 = (userId?: string): string => {
183
- const data = Buffer.alloc(8 + 20 + 16)
184
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
185
-
186
- if (userId) {
187
- const id = jidDecode(userId)
188
- if (id?.user) {
189
- data.write(id.user, 8)
190
- data.write('@c.us', 8 + id.user.length)
191
- }
192
- }
193
-
194
- const random = randomBytes(16)
195
- random.copy(data, 28)
196
-
197
- const hash = createHash('sha256').update(data).digest()
198
- return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18)
199
- }
200
-
201
- // generate a random ID to attach to a message
202
- export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase()
203
-
204
- export function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T) {
205
- return async (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => {
206
- let listener: (item: BaileysEventMap[T]) => void
207
- let closeListener: (state: Partial<ConnectionState>) => void
208
- await promiseTimeout<void>(timeoutMs, (resolve, reject) => {
209
- closeListener = ({ connection, lastDisconnect }) => {
210
- if (connection === 'close') {
211
- reject(
212
- lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
213
- )
214
- }
215
- }
216
-
217
- ev.on('connection.update', closeListener)
218
- listener = async update => {
219
- if (await check(update)) {
220
- resolve()
221
- }
222
- }
223
-
224
- ev.on(event, listener)
225
- }).finally(() => {
226
- ev.off(event, listener)
227
- ev.off('connection.update', closeListener)
228
- })
229
- }
230
- }
231
-
232
- export const bindWaitForConnectionUpdate = (ev: BaileysEventEmitter) => bindWaitForEvent(ev, 'connection.update')
233
-
234
- /**
235
- * utility that fetches latest baileys version from the master branch.
236
- * Use to ensure your WA connection is always on the latest version
237
- */
238
- export const fetchLatestBaileysVersion = async (options: RequestInit = {}) => {
239
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts'
240
- try {
241
- const response = await fetch(URL, {
242
- dispatcher: options.dispatcher,
243
- method: 'GET',
244
- headers: options.headers
245
- })
246
- if (!response.ok) {
247
- throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status })
248
- }
249
-
250
- const text = await response.text()
251
- // Extract version from line 7 (const version = [...])
252
- const lines = text.split('\n')
253
- const versionLine = lines[6] // Line 7 (0-indexed)
254
- const versionMatch = versionLine!.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/)
255
-
256
- if (versionMatch) {
257
- const version = [parseInt(versionMatch[1]!), parseInt(versionMatch[2]!), parseInt(versionMatch[3]!)] as WAVersion
258
-
259
- return {
260
- version,
261
- isLatest: true
262
- }
263
- } else {
264
- throw new Error('Could not parse version from Defaults/index.ts')
265
- }
266
- } catch (error) {
267
- return {
268
- version: baileysVersion as WAVersion,
269
- isLatest: false,
270
- error
271
- }
272
- }
273
- }
274
-
275
- /**
276
- * A utility that fetches the latest web version of whatsapp.
277
- * Use to ensure your WA connection is always on the latest version
278
- */
279
- export const fetchLatestWaWebVersion = async (options: RequestInit = {}) => {
280
- try {
281
- // Absolute minimal headers required to bypass anti-bot detection
282
- const defaultHeaders = {
283
- 'sec-fetch-site': 'none',
284
- 'user-agent':
285
- 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
286
- }
287
-
288
- const headers = { ...defaultHeaders, ...options.headers }
289
-
290
- const response = await fetch('https://web.whatsapp.com/sw.js', {
291
- ...options,
292
- method: 'GET',
293
- headers
294
- })
295
-
296
- if (!response.ok) {
297
- throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status })
298
- }
299
-
300
- const data = await response.text()
301
-
302
- const regex = /\\?"client_revision\\?":\s*(\d+)/
303
- const match = data.match(regex)
304
-
305
- if (!match?.[1]) {
306
- return {
307
- version: baileysVersion as WAVersion,
308
- isLatest: false,
309
- error: {
310
- message: 'Could not find client revision in the fetched content'
311
- }
312
- }
313
- }
314
-
315
- const clientRevision = match[1]
316
-
317
- return {
318
- version: [2, 3000, +clientRevision] as WAVersion,
319
- isLatest: true
320
- }
321
- } catch (error) {
322
- return {
323
- version: baileysVersion as WAVersion,
324
- isLatest: false,
325
- error
326
- }
327
- }
328
- }
329
-
330
- /** unique message tag prefix for MD clients */
331
- export const generateMdTagPrefix = () => {
332
- const bytes = randomBytes(4)
333
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
334
- }
335
-
336
- const STATUS_MAP: { [_: string]: proto.WebMessageInfo.Status } = {
337
- sender: proto.WebMessageInfo.Status.SERVER_ACK,
338
- played: proto.WebMessageInfo.Status.PLAYED,
339
- read: proto.WebMessageInfo.Status.READ,
340
- 'read-self': proto.WebMessageInfo.Status.READ
341
- }
342
- /**
343
- * Given a type of receipt, returns what the new status of the message should be
344
- * @param type type from receipt
345
- */
346
- export const getStatusFromReceiptType = (type: string | undefined) => {
347
- const status = STATUS_MAP[type!]
348
- if (typeof type === 'undefined') {
349
- return proto.WebMessageInfo.Status.DELIVERY_ACK
350
- }
351
-
352
- return status
353
- }
354
-
355
- const CODE_MAP: { [_: string]: DisconnectReason } = {
356
- conflict: DisconnectReason.connectionReplaced
357
- }
358
-
359
- /**
360
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
361
- * @param reason the string reason given, eg. "conflict"
362
- */
363
- export const getErrorCodeFromStreamError = (node: BinaryNode) => {
364
- const [reasonNode] = getAllBinaryNodeChildren(node)
365
- let reason = reasonNode?.tag || 'unknown'
366
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession)
367
-
368
- if (statusCode === DisconnectReason.restartRequired) {
369
- reason = 'restart required'
370
- }
371
-
372
- return {
373
- reason,
374
- statusCode
375
- }
376
- }
377
-
378
- export const getCallStatusFromNode = ({ tag, attrs }: BinaryNode) => {
379
- let status: WACallUpdateType
380
- switch (tag) {
381
- case 'offer':
382
- case 'offer_notice':
383
- status = 'offer'
384
- break
385
- case 'terminate':
386
- if (attrs.reason === 'timeout') {
387
- status = 'timeout'
388
- } else {
389
- //fired when accepted/rejected/timeout/caller hangs up
390
- status = 'terminate'
391
- }
392
-
393
- break
394
- case 'reject':
395
- status = 'reject'
396
- break
397
- case 'accept':
398
- status = 'accept'
399
- break
400
- default:
401
- status = 'ringing'
402
- break
403
- }
404
-
405
- return status
406
- }
407
-
408
- const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
409
-
410
- export const getCodeFromWSError = (error: Error) => {
411
- let statusCode = 500
412
- if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
413
- const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length)
414
- if (!Number.isNaN(code) && code >= 400) {
415
- statusCode = code
416
- }
417
- } else if (
418
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
419
- (error as any)?.code?.startsWith('E') ||
420
- error?.message?.includes('timed out')
421
- ) {
422
- // handle ETIMEOUT, ENOTFOUND etc
423
- statusCode = 408
424
- }
425
-
426
- return statusCode
427
- }
428
-
429
- /**
430
- * Is the given platform WA business
431
- * @param platform AuthenticationCreds.platform
432
- */
433
- export const isWABusinessPlatform = (platform: string) => {
434
- return platform === 'smbi' || platform === 'smba'
435
- }
436
-
437
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
438
- export function trimUndefined(obj: { [_: string]: any }) {
439
- for (const key in obj) {
440
- if (typeof obj[key] === 'undefined') {
441
- delete obj[key]
442
- }
443
- }
444
-
445
- return obj
446
- }
447
-
448
- const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ'
449
-
450
- export function bytesToCrockford(buffer: Buffer): string {
451
- let value = 0
452
- let bitCount = 0
453
- const crockford: string[] = []
454
-
455
- for (const element of buffer) {
456
- value = (value << 8) | (element & 0xff)
457
- bitCount += 8
458
-
459
- while (bitCount >= 5) {
460
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
461
- bitCount -= 5
462
- }
463
- }
464
-
465
- if (bitCount > 0) {
466
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
467
- }
468
-
469
- return crockford.join('')
470
- }
471
-
472
- export function encodeNewsletterMessage(message: proto.IMessage): Uint8Array {
473
- return proto.Message.encode(message).finish()
474
- }
@@ -1,161 +0,0 @@
1
- import { promisify } from 'util'
2
- import { inflate } from 'zlib'
3
- import { proto } from '../../WAProto/index.js'
4
- import type { Chat, Contact, LIDMapping, WAMessage } from '../Types'
5
- import { WAMessageStubType } from '../Types'
6
- import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary'
7
- import { toNumber } from './generics'
8
- import type { ILogger } from './logger.js'
9
- import { normalizeMessageContent } from './messages'
10
- import { downloadContentFromMessage } from './messages-media'
11
-
12
- const inflatePromise = promisify(inflate)
13
-
14
- const extractPnFromMessages = (messages: proto.IHistorySyncMsg[]): string | undefined => {
15
- for (const msgItem of messages) {
16
- const message = msgItem.message
17
- // Only extract from outgoing messages (fromMe: true) in 1:1 chats
18
- // because userReceipt.userJid is the recipient's JID
19
- if (!message?.key?.fromMe || !message.userReceipt?.length) {
20
- continue
21
- }
22
-
23
- const userJid = message.userReceipt[0]?.userJid
24
- if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
25
- return userJid
26
- }
27
- }
28
-
29
- return undefined
30
- }
31
-
32
- export const downloadHistory = async (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => {
33
- const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
34
- const bufferArray: Buffer[] = []
35
- for await (const chunk of stream) {
36
- bufferArray.push(chunk)
37
- }
38
-
39
- let buffer: Buffer = Buffer.concat(bufferArray)
40
-
41
- // decompress buffer
42
- buffer = await inflatePromise(buffer)
43
-
44
- const syncData = proto.HistorySync.decode(buffer)
45
- return syncData
46
- }
47
-
48
- export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger) => {
49
- const messages: WAMessage[] = []
50
- const contacts: Contact[] = []
51
- const chats: Chat[] = []
52
- const lidPnMappings: LIDMapping[] = []
53
-
54
- logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString())
55
-
56
- // Extract LID-PN mappings for all sync types
57
- for (const m of item.phoneNumberToLidMappings || []) {
58
- if (m.lidJid && m.pnJid) {
59
- lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid })
60
- }
61
- }
62
-
63
- switch (item.syncType) {
64
- case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
65
- case proto.HistorySync.HistorySyncType.RECENT:
66
- case proto.HistorySync.HistorySyncType.FULL:
67
- case proto.HistorySync.HistorySyncType.ON_DEMAND:
68
- for (const chat of item.conversations! as Chat[]) {
69
- contacts.push({
70
- id: chat.id!,
71
- name: chat.displayName || chat.name || chat.username || undefined,
72
- lid: chat.lidJid || chat.accountLid || undefined,
73
- phoneNumber: chat.pnJid || undefined
74
- })
75
-
76
- const chatId = chat.id!
77
- const isLid = isLidUser(chatId) || isHostedLidUser(chatId)
78
- const isPn = isPnUser(chatId) || isHostedPnUser(chatId)
79
- if (isLid && chat.pnJid) {
80
- lidPnMappings.push({ lid: chatId, pn: chat.pnJid })
81
- } else if (isPn && chat.lidJid) {
82
- lidPnMappings.push({ lid: chat.lidJid, pn: chatId })
83
- } else if (isLid && !chat.pnJid) {
84
- // Fallback: extract PN from userReceipt in messages when pnJid is missing
85
- const pnFromReceipt = extractPnFromMessages(chat.messages || [])
86
- if (pnFromReceipt) {
87
- lidPnMappings.push({ lid: chatId, pn: pnFromReceipt })
88
- }
89
- }
90
-
91
- const msgs = chat.messages || []
92
- delete chat.messages
93
-
94
- for (const item of msgs) {
95
- const message = item.message! as WAMessage
96
- messages.push(message)
97
-
98
- if (!chat.messages?.length) {
99
- // keep only the most recent message in the chat array
100
- chat.messages = [{ message }]
101
- }
102
-
103
- if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
104
- chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
105
- }
106
-
107
- if (
108
- (message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
109
- message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
110
- message.messageStubParameters?.[0]
111
- ) {
112
- contacts.push({
113
- id: message.key.participant || message.key.remoteJid!,
114
- verifiedName: message.messageStubParameters?.[0]
115
- })
116
- }
117
- }
118
-
119
- chats.push({ ...chat })
120
- }
121
-
122
- break
123
- case proto.HistorySync.HistorySyncType.PUSH_NAME:
124
- for (const c of item.pushnames!) {
125
- contacts.push({ id: c.id!, notify: c.pushname! })
126
- }
127
-
128
- break
129
- }
130
-
131
- return {
132
- chats,
133
- contacts,
134
- messages,
135
- lidPnMappings,
136
- syncType: item.syncType,
137
- progress: item.progress
138
- }
139
- }
140
-
141
- export const downloadAndProcessHistorySyncNotification = async (
142
- msg: proto.Message.IHistorySyncNotification,
143
- options: RequestInit,
144
- logger?: ILogger
145
- ) => {
146
- let historyMsg: proto.HistorySync
147
- if (msg.initialHistBootstrapInlinePayload) {
148
- historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload))
149
- } else {
150
- historyMsg = await downloadHistory(msg, options)
151
- }
152
-
153
- return processHistoryMessage(historyMsg, logger)
154
- }
155
-
156
- export const getHistoryMsg = (message: proto.IMessage) => {
157
- const normalizedContent = !!message ? normalizeMessageContent(message) : undefined
158
- const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification!
159
-
160
- return anyHistoryMsg
161
- }
@@ -1,83 +0,0 @@
1
- import NodeCache from '@cacheable/node-cache'
2
- import { areJidsSameUser, type BinaryNode, getBinaryNodeChild, jidDecode } from '../WABinary'
3
- import { isStringNullOrEmpty } from './generics'
4
- import type { ILogger } from './logger'
5
-
6
- export type IdentityChangeResult =
7
- | { action: 'no_identity_node' }
8
- | { action: 'invalid_notification' }
9
- | { action: 'skipped_companion_device'; device: number }
10
- | { action: 'skipped_self_primary' }
11
- | { action: 'debounced' }
12
- | { action: 'skipped_offline' }
13
- | { action: 'skipped_no_session' }
14
- | { action: 'session_refreshed' }
15
- | { action: 'session_refresh_failed'; error: unknown }
16
-
17
- export type IdentityChangeContext = {
18
- meId: string | undefined
19
- meLid: string | undefined
20
- validateSession: (jid: string) => Promise<{ exists: boolean; reason?: string }>
21
- assertSessions: (jids: string[], force?: boolean) => Promise<boolean>
22
- debounceCache: NodeCache<boolean>
23
- logger: ILogger
24
- }
25
-
26
- export async function handleIdentityChange(
27
- node: BinaryNode,
28
- ctx: IdentityChangeContext
29
- ): Promise<IdentityChangeResult> {
30
- const from = node.attrs.from
31
- if (!from) {
32
- return { action: 'invalid_notification' }
33
- }
34
-
35
- const identityNode = getBinaryNodeChild(node, 'identity')
36
- if (!identityNode) {
37
- return { action: 'no_identity_node' }
38
- }
39
-
40
- ctx.logger.info({ jid: from }, 'identity changed')
41
-
42
- const decoded = jidDecode(from)
43
- if (decoded?.device && decoded.device !== 0) {
44
- ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device')
45
- return { action: 'skipped_companion_device', device: decoded.device }
46
- }
47
-
48
- const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)))
49
- if (isSelfPrimary) {
50
- ctx.logger.info({ jid: from }, 'self primary identity changed')
51
- return { action: 'skipped_self_primary' }
52
- }
53
-
54
- if (ctx.debounceCache.get(from)) {
55
- ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)')
56
- return { action: 'debounced' }
57
- }
58
-
59
- ctx.debounceCache.set(from, true)
60
-
61
- const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline)
62
- const hasExistingSession = await ctx.validateSession(from)
63
-
64
- if (!hasExistingSession.exists) {
65
- ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh')
66
- return { action: 'skipped_no_session' }
67
- }
68
-
69
- ctx.logger.debug({ jid: from }, 'old session exists, will refresh session')
70
-
71
- if (isOfflineNotification) {
72
- ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing')
73
- return { action: 'skipped_offline' }
74
- }
75
-
76
- try {
77
- await ctx.assertSessions([from], true)
78
- return { action: 'session_refreshed' }
79
- } catch (error) {
80
- ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change')
81
- return { action: 'session_refresh_failed', error }
82
- }
83
- }