@hiroosy/baileys-lite 0.0.1

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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,1283 @@
1
+ /**
2
+ * Core WA protocol utilities. Combines what used to be:
3
+ * crypto.js, generics.js, lt-hash.js, signal.js, validate-connection.js,
4
+ * noise-handler.js, browser-utils.js, companion-reg-client-utils.js,
5
+ * stanza-ack.js, reporting-utils.js
6
+ *
7
+ * md5/hkdf/LTHashAntiTampering come from ../foundation/wa-crypto.js and the
8
+ * curve operations from ../signal/libsignal.js (both native, no npm deps).
9
+ */
10
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomFillSync } from 'node:crypto'
11
+ import { platform, release } from 'node:os'
12
+ import { curve } from '../signal/libsignal.js'
13
+ import { createLogger } from '../foundation/logger.js'
14
+ import { md5, hkdf, LTHashAntiTampering } from '../foundation/wa-crypto.js'
15
+ import { Boom } from '../foundation/boom.js'
16
+ import { proto } from '../../WAProto/index.js'
17
+ import {
18
+ getAllBinaryNodeChildren,
19
+ getBinaryNodeChild,
20
+ getBinaryNodeChildBuffer,
21
+ getBinaryNodeChildUInt,
22
+ getBinaryNodeChildren,
23
+ assertNodeErrorFree,
24
+ jidDecode,
25
+ S_WHATSAPP_NET,
26
+ WAJIDDomains,
27
+ getServerFromDomainType,
28
+ decodeBinaryNode
29
+ } from '../binary/wa-binary.js'
30
+
31
+ export { md5, hkdf }
32
+
33
+ /* ------------------------------------------------------------------ */
34
+ /* Crypto primitives */
35
+ /* ------------------------------------------------------------------ */
36
+
37
+ const KEY_BUNDLE_TYPE = Buffer.from([5])
38
+ export { KEY_BUNDLE_TYPE }
39
+
40
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
41
+ export const generateSignalPubKey = pubKey => (pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]))
42
+
43
+ export const Curve = {
44
+ generateKeyPair: () => {
45
+ const { pubKey, privKey } = curve.generateKeyPair()
46
+ return { private: Buffer.from(privKey), public: Buffer.from(pubKey.slice(1)) } // remove version byte
47
+ },
48
+ sharedKey: (privateKey, publicKey) => {
49
+ const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey)
50
+ return Buffer.from(shared)
51
+ },
52
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
53
+ /**
54
+ * KNOWN UPSTREAM QUIRK (kept for behavioral parity with @whiskeysockets/baileys 7.0.0-rc14): this only
55
+ * catches exceptions. `curve.verifySignature` REPORTS a bad signature by returning `false` (it does not throw),
56
+ * so `verify()` returns `true` for ANY well-formed 64-byte signature — a changed message, a random signature or
57
+ * a different key all "verify". The three call sites (noise certificate chain, account signature at pairing)
58
+ * are therefore not enforcing signatures today. See PROGRESS.md ("Security note") and `Curve.verifyStrict`.
59
+ */
60
+ verify: (pubKey, message, signature) => {
61
+ try {
62
+ curve.verifySignature(generateSignalPubKey(pubKey), message, signature)
63
+ return true
64
+ } catch {
65
+ return false
66
+ }
67
+ },
68
+ /**
69
+ * Correct XEdDSA verification: returns `true` only for a valid signature. NOT used by the library yet —
70
+ * switching the call sites to it is a behavior change that must be validated against real server traffic
71
+ * first (a legitimate certificate that fails strict verification would break connecting).
72
+ */
73
+ verifyStrict: (pubKey, message, signature) => {
74
+ try {
75
+ return curve.verifySignature(generateSignalPubKey(pubKey), message, signature) === true
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+ }
81
+
82
+ export const signedKeyPair = (identityKeyPair, keyId) => {
83
+ const preKey = Curve.generateKeyPair()
84
+ const pubKey = generateSignalPubKey(preKey.public)
85
+ const signature = Curve.sign(identityKeyPair.private, pubKey)
86
+ return { keyPair: preKey, signature, keyId }
87
+ }
88
+
89
+ const GCM_TAG_LENGTH = 128 >> 3
90
+
91
+ /** encrypt AES 256 GCM; the auth tag is suffixed to the ciphertext */
92
+ export function aesEncryptGCM(plaintext, key, iv, additionalData) {
93
+ const cipher = createCipheriv('aes-256-gcm', key, iv)
94
+ cipher.setAAD(additionalData)
95
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()])
96
+ }
97
+
98
+ /** decrypt AES 256 GCM; the auth tag is suffixed to the ciphertext */
99
+ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
100
+ const decipher = createDecipheriv('aes-256-gcm', key, iv)
101
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH)
102
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH)
103
+ decipher.setAAD(additionalData)
104
+ decipher.setAuthTag(tag)
105
+ return Buffer.concat([decipher.update(enc), decipher.final()])
106
+ }
107
+
108
+ export function aesEncryptCTR(plaintext, key, iv) {
109
+ const cipher = createCipheriv('aes-256-ctr', key, iv)
110
+ return Buffer.concat([cipher.update(plaintext), cipher.final()])
111
+ }
112
+
113
+ export function aesDecryptCTR(ciphertext, key, iv) {
114
+ const decipher = createDecipheriv('aes-256-ctr', key, iv)
115
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()])
116
+ }
117
+
118
+ /** decrypt AES 256 CBC; the IV is prefixed to the buffer */
119
+ export function aesDecrypt(buffer, key) {
120
+ return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16))
121
+ }
122
+
123
+ export function aesDecryptWithIV(buffer, key, IV) {
124
+ const aes = createDecipheriv('aes-256-cbc', key, IV)
125
+ return Buffer.concat([aes.update(buffer), aes.final()])
126
+ }
127
+
128
+ /** encrypt AES 256 CBC; a random IV is prefixed to the buffer */
129
+ export function aesEncrypt(buffer, key) {
130
+ const IV = randomBytes(16)
131
+ const aes = createCipheriv('aes-256-cbc', key, IV)
132
+ return Buffer.concat([IV, aes.update(buffer), aes.final()])
133
+ }
134
+
135
+ export function aesEncrypWithIV(buffer, key, IV) {
136
+ const aes = createCipheriv('aes-256-cbc', key, IV)
137
+ return Buffer.concat([aes.update(buffer), aes.final()])
138
+ }
139
+
140
+ export function hmacSign(buffer, key, variant = 'sha256') {
141
+ return createHmac(variant, key).update(buffer).digest()
142
+ }
143
+
144
+ export function sha256(buffer) {
145
+ return createHash('sha256').update(buffer).digest()
146
+ }
147
+
148
+ export async function derivePairingCodeKey(pairingCode, salt) {
149
+ const { subtle } = globalThis.crypto
150
+ const encoder = new TextEncoder()
151
+ const pairingCodeBuffer = encoder.encode(pairingCode)
152
+ const saltBuffer = new Uint8Array(salt instanceof Uint8Array ? salt : new Uint8Array(salt))
153
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, ['deriveBits'])
154
+ const derivedBits = await subtle.deriveBits({ name: 'PBKDF2', salt: saltBuffer, iterations: 2 << 16, hash: 'SHA-256' }, keyMaterial, 32 * 8)
155
+ return Buffer.from(derivedBits)
156
+ }
157
+
158
+ /* ------------------------------------------------------------------ */
159
+ /* LT-Hash (anti-tampering) */
160
+ /* ------------------------------------------------------------------ */
161
+
162
+ /**
163
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
164
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
165
+ * if the same series of mutations was made sequentially.
166
+ */
167
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering()
168
+
169
+ /* ------------------------------------------------------------------ */
170
+ /* Generic helpers */
171
+ /* ------------------------------------------------------------------ */
172
+
173
+ export const BufferJSON = {
174
+ replacer: (k, value) => {
175
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
176
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
177
+ }
178
+ return value
179
+ },
180
+ reviver: (_, value) => {
181
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
182
+ return Buffer.from(value.data, 'base64')
183
+ }
184
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
185
+ const keys = Object.keys(value)
186
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
187
+ const values = Object.values(value)
188
+ if (values.every(v => typeof v === 'number')) return Buffer.from(values)
189
+ }
190
+ }
191
+ return value
192
+ }
193
+ }
194
+
195
+ export const getKeyAuthor = (key, meId = 'me') =>
196
+ (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || ''
197
+
198
+ // eslint-disable-next-line eqeqeq
199
+ export const isStringNullOrEmpty = value => value == null || value === ''
200
+
201
+ export const writeRandomPadMax16 = msg => {
202
+ const pad = randomBytes(1)
203
+ const padLength = (pad[0] & 0x0f) + 1
204
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)])
205
+ }
206
+
207
+ export const unpadRandomMax16 = e => {
208
+ const t = new Uint8Array(e)
209
+ if (t.length === 0) throw new Error('unpadPkcs7 given empty bytes')
210
+ const r = t[t.length - 1]
211
+ if (r > t.length) throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
212
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
213
+ }
214
+
215
+ // code is inspired by whatsmeow
216
+ export const generateParticipantHashV2 = participants => {
217
+ participants.sort()
218
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64')
219
+ return '2:' + sha256Hash.slice(0, 6)
220
+ }
221
+
222
+ export const encodeWAMessage = message => writeRandomPadMax16(proto.Message.encode(message).finish())
223
+
224
+ export const generateRegistrationId = () => Uint16Array.from(randomBytes(2))[0] & 16383
225
+
226
+ export const encodeBigEndian = (e, t = 4) => {
227
+ let r = e
228
+ const a = new Uint8Array(t)
229
+ for (let i = t - 1; i >= 0; i--) {
230
+ a[i] = 255 & r
231
+ r >>>= 8
232
+ }
233
+ return a
234
+ }
235
+
236
+ export const toNumber = t => (typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0)
237
+
238
+ /** unix timestamp of a date in seconds */
239
+ export const unixTimestampSeconds = (date = new Date()) => (date.getTime() / 1000) | 0
240
+
241
+ export const debouncedTimeout = (intervalMs = 1000, task) => {
242
+ let timeout
243
+ return {
244
+ start: (newIntervalMs, newTask) => {
245
+ task = newTask || task
246
+ intervalMs = newIntervalMs || intervalMs
247
+ timeout && clearTimeout(timeout)
248
+ timeout = setTimeout(() => task?.(), intervalMs)
249
+ },
250
+ cancel: () => {
251
+ timeout && clearTimeout(timeout)
252
+ timeout = undefined
253
+ },
254
+ setTask: newTask => (task = newTask),
255
+ setInterval: newInterval => (intervalMs = newInterval)
256
+ }
257
+ }
258
+
259
+ export const delay = ms => delayCancellable(ms).delay
260
+
261
+ export const delayCancellable = ms => {
262
+ const stack = new Error().stack
263
+ let timeout
264
+ let reject
265
+ const delayPromise = new Promise((resolve, _reject) => {
266
+ timeout = setTimeout(resolve, ms)
267
+ reject = _reject
268
+ })
269
+ const cancel = () => {
270
+ clearTimeout(timeout)
271
+ reject(new Boom('Cancelled', { statusCode: 500, data: { stack } }))
272
+ }
273
+ return { delay: delayPromise, cancel }
274
+ }
275
+
276
+ export async function promiseTimeout(ms, promiseExecutor) {
277
+ if (!ms) return new Promise(promiseExecutor)
278
+ const stack = new Error().stack
279
+ const { delay: delayPromise, cancel } = delayCancellable(ms)
280
+ const p = new Promise((resolve, reject) => {
281
+ delayPromise.then(() => reject(new Boom('Timed Out', { statusCode: 408, data: { stack } }))).catch(err => reject(err))
282
+ promiseExecutor(resolve, reject)
283
+ }).finally(cancel)
284
+ return p
285
+ }
286
+
287
+ // inspired from whatsmeow's send.go
288
+ export const generateMessageIDV2 = userId => {
289
+ const data = Buffer.alloc(8 + 20 + 16)
290
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
291
+ if (userId) {
292
+ const id = jidDecode(userId)
293
+ if (id?.user) {
294
+ data.write(id.user, 8)
295
+ data.write('@c.us', 8 + id.user.length)
296
+ }
297
+ }
298
+ const random = randomBytes(16)
299
+ random.copy(data, 28)
300
+ const hash = createHash('sha256').update(data).digest()
301
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18)
302
+ }
303
+
304
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase()
305
+
306
+ export function bindWaitForEvent(ev, event) {
307
+ return async (check, timeoutMs) => {
308
+ let listener
309
+ let closeListener
310
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
311
+ closeListener = ({ connection, lastDisconnect }) => {
312
+ if (connection === 'close') {
313
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: 428 }))
314
+ }
315
+ }
316
+ ev.on('connection.update', closeListener)
317
+ listener = async update => {
318
+ if (await check(update)) resolve()
319
+ }
320
+ ev.on(event, listener)
321
+ }).finally(() => {
322
+ ev.off(event, listener)
323
+ ev.off('connection.update', closeListener)
324
+ })
325
+ }
326
+ }
327
+
328
+ export const bindWaitForConnectionUpdate = ev => bindWaitForEvent(ev, 'connection.update')
329
+
330
+ const baileysVersion = [2, 3000, 1047970367]
331
+
332
+ /** utility that fetches latest baileys version from the master branch. */
333
+ export const fetchLatestBaileysVersion = async (options = {}) => {
334
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts'
335
+ try {
336
+ const response = await fetch(URL, { dispatcher: options.dispatcher, method: 'GET', headers: options.headers })
337
+ if (!response.ok) throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status })
338
+ const text = await response.text()
339
+ // Extract version from the `const version = [...]` line (search all lines: robust to line shifts upstream)
340
+ const versionMatch = text.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/)
341
+ if (versionMatch) {
342
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])]
343
+ return { version, isLatest: true }
344
+ }
345
+ throw new Error('Could not parse version from Defaults/index.ts')
346
+ } catch (error) {
347
+ return { version: baileysVersion, isLatest: false, error }
348
+ }
349
+ }
350
+
351
+ /** fetches the latest web version of whatsapp. */
352
+ export const fetchLatestWaWebVersion = async (options = {}) => {
353
+ try {
354
+ const defaultHeaders = {
355
+ 'sec-fetch-site': 'none',
356
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
357
+ }
358
+ const headers = { ...defaultHeaders, ...options.headers }
359
+ const response = await fetch('https://web.whatsapp.com/sw.js', { ...options, method: 'GET', headers })
360
+ if (!response.ok) throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status })
361
+ const data = await response.text()
362
+ const regex = /\\?"client_revision\\?":\s*(\d+)/
363
+ const match = data.match(regex)
364
+ if (!match?.[1]) {
365
+ return { version: baileysVersion, isLatest: false, error: { message: 'Could not find client revision in the fetched content' } }
366
+ }
367
+ return { version: [2, 3000, +match[1]], isLatest: true }
368
+ } catch (error) {
369
+ return { version: baileysVersion, isLatest: false, error }
370
+ }
371
+ }
372
+
373
+ /** unique message tag prefix for MD clients */
374
+ export const generateMdTagPrefix = () => {
375
+ const bytes = randomBytes(4)
376
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
377
+ }
378
+
379
+ const STATUS_MAP = {
380
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
381
+ played: proto.WebMessageInfo.Status.PLAYED,
382
+ read: proto.WebMessageInfo.Status.READ,
383
+ 'read-self': proto.WebMessageInfo.Status.READ
384
+ }
385
+
386
+ /** Given a type of receipt, returns what the new status of the message should be */
387
+ export const getStatusFromReceiptType = type => {
388
+ const status = STATUS_MAP[type]
389
+ if (typeof type === 'undefined') return proto.WebMessageInfo.Status.DELIVERY_ACK
390
+ return status
391
+ }
392
+
393
+ const CODE_MAP = { conflict: 428 } // DisconnectReason.connectionReplaced
394
+
395
+ /** Stream errors generally provide a reason, map that to a baileys DisconnectReason */
396
+ export const getErrorCodeFromStreamError = node => {
397
+ const [reasonNode] = getAllBinaryNodeChildren(node)
398
+ let reason = reasonNode?.tag || 'unknown'
399
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || 500) // DisconnectReason.badSession
400
+ if (statusCode === 515) reason = 'restart required' // DisconnectReason.restartRequired
401
+ return { reason, statusCode }
402
+ }
403
+
404
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
405
+ switch (tag) {
406
+ case 'offer':
407
+ case 'offer_notice':
408
+ return 'offer'
409
+ case 'terminate':
410
+ return attrs.reason === 'timeout' ? 'timeout' : 'terminate' // fired when accepted/rejected/timeout/caller hangs up
411
+ case 'preaccept':
412
+ return 'preaccept'
413
+ case 'transport':
414
+ return 'transport'
415
+ case 'relaylatency':
416
+ return 'relaylatency'
417
+ case 'reject':
418
+ return 'reject'
419
+ case 'accept':
420
+ return 'accept'
421
+ default:
422
+ return 'ringing'
423
+ }
424
+ }
425
+
426
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
427
+ export const getCodeFromWSError = error => {
428
+ let statusCode = 500
429
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
430
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length)
431
+ if (!Number.isNaN(code) && code >= 400) statusCode = code
432
+ } else if (error?.code?.startsWith('E') || error?.message?.includes('timed out')) {
433
+ statusCode = 408 // ETIMEOUT, ENOTFOUND etc
434
+ }
435
+ return statusCode
436
+ }
437
+
438
+ /** Is the given platform WA business */
439
+ export const isWABusinessPlatform = platform => platform === 'smbi' || platform === 'smba'
440
+
441
+ export function trimUndefined(obj) {
442
+ for (const key in obj) {
443
+ if (typeof obj[key] === 'undefined') delete obj[key]
444
+ }
445
+ return obj
446
+ }
447
+
448
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ'
449
+ export function bytesToCrockford(buffer) {
450
+ let value = 0
451
+ let bitCount = 0
452
+ const crockford = []
453
+ for (const element of buffer) {
454
+ value = (value << 8) | (element & 0xff)
455
+ bitCount += 8
456
+ while (bitCount >= 5) {
457
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
458
+ bitCount -= 5
459
+ }
460
+ }
461
+ if (bitCount > 0) crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
462
+ return crockford.join('')
463
+ }
464
+
465
+ export function encodeNewsletterMessage(message) {
466
+ return proto.Message.encode(message).finish()
467
+ }
468
+
469
+ /* ------------------------------------------------------------------ */
470
+ /* Browser / companion-registration helpers */
471
+ /* ------------------------------------------------------------------ */
472
+
473
+ const PLATFORM_MAP = {
474
+ aix: 'AIX',
475
+ darwin: 'Mac OS',
476
+ win32: 'Windows',
477
+ android: 'Android',
478
+ freebsd: 'FreeBSD',
479
+ openbsd: 'OpenBSD',
480
+ sunos: 'Solaris',
481
+ linux: undefined,
482
+ haiku: undefined,
483
+ cygwin: undefined,
484
+ netbsd: undefined
485
+ }
486
+
487
+ export const Browsers = {
488
+ ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
489
+ macOS: browser => ['Mac OS', browser, '14.4.1'],
490
+ baileys: browser => ['Baileys', browser, '6.5.0'],
491
+ windows: browser => ['Windows', browser, '10.0.22631'],
492
+ android: browser => [browser, 'Android', ''],
493
+ appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
494
+ }
495
+
496
+ export const getPlatformId = browser => {
497
+ const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()]
498
+ return platformType ? platformType.toString() : '1' // chrome
499
+ }
500
+
501
+ export const CompanionWebClientType = {
502
+ UNKNOWN: 0,
503
+ CHROME: 1,
504
+ EDGE: 2,
505
+ FIREFOX: 3,
506
+ IE: 4,
507
+ OPERA: 5,
508
+ SAFARI: 6,
509
+ ELECTRON: 7,
510
+ UWP: 8,
511
+ OTHER_WEB_CLIENT: 9
512
+ }
513
+
514
+ const BROWSER_TO_COMPANION_WEB_CLIENT = {
515
+ Chrome: CompanionWebClientType.CHROME,
516
+ Edge: CompanionWebClientType.EDGE,
517
+ Firefox: CompanionWebClientType.FIREFOX,
518
+ IE: CompanionWebClientType.IE,
519
+ Opera: CompanionWebClientType.OPERA,
520
+ Safari: CompanionWebClientType.SAFARI
521
+ }
522
+
523
+ export const getCompanionWebClientType = ([os, browserName]) => {
524
+ if (browserName === 'Desktop') return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON
525
+ return BROWSER_TO_COMPANION_WEB_CLIENT[browserName] || CompanionWebClientType.OTHER_WEB_CLIENT
526
+ }
527
+
528
+ export const getCompanionPlatformId = browser => getCompanionWebClientType(browser).toString()
529
+
530
+ export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) =>
531
+ 'https://wa.me/settings/linked_devices#' + [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(',')
532
+
533
+ /* ------------------------------------------------------------------ */
534
+ /* Stanza ACK */
535
+ /* ------------------------------------------------------------------ */
536
+
537
+ /**
538
+ * Builds an ACK stanza for a received node. Pure function -- no I/O, no side effects.
539
+ * Mirrors WhatsApp Web's ACK construction (WAWebHandleMsgSendAck.sendAck/sendNack).
540
+ */
541
+ export function buildAckStanza(node, errorCode, meId) {
542
+ const { tag, attrs } = node
543
+ const stanza = { tag: 'ack', attrs: { id: attrs.id, to: attrs.from, class: tag } }
544
+ if (errorCode) stanza.attrs.error = errorCode.toString()
545
+ if (attrs.participant) stanza.attrs.participant = attrs.participant
546
+ if (attrs.recipient) stanza.attrs.recipient = attrs.recipient
547
+ if (attrs.type) stanza.attrs.type = attrs.type // WA Web always includes type when present
548
+ if (tag === 'message' && meId) stanza.attrs.from = meId // WA Web always includes `from` for message-class ACKs
549
+ return stanza
550
+ }
551
+
552
+ /* ------------------------------------------------------------------ */
553
+ /* Signal / prekey helpers */
554
+ /* ------------------------------------------------------------------ */
555
+
556
+ function chunkArray(array, size) {
557
+ const chunks = []
558
+ for (let i = 0; i < array.length; i += size) chunks.push(array.slice(i, i + size))
559
+ return chunks
560
+ }
561
+
562
+ export const createSignalIdentity = (wid, accountSignatureKey) => ({
563
+ identifier: { name: wid, deviceId: 0 },
564
+ identifierKey: generateSignalPubKey(accountSignatureKey)
565
+ })
566
+
567
+ export const getPreKeys = async ({ get }, min, limit) => {
568
+ const idList = []
569
+ for (let id = min; id < limit; id++) idList.push(id.toString())
570
+ return get('pre-key', idList)
571
+ }
572
+
573
+ export const generateOrGetPreKeys = (creds, range) => {
574
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId
575
+ const remaining = range - avaliable
576
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1
577
+ const newPreKeys = {}
578
+ if (remaining > 0) {
579
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) newPreKeys[i] = Curve.generateKeyPair()
580
+ }
581
+ return { newPreKeys, lastPreKeyId, preKeysRange: [creds.firstUnuploadedPreKeyId, range] }
582
+ }
583
+
584
+ export const xmppSignedPreKey = key => ({
585
+ tag: 'skey',
586
+ attrs: {},
587
+ content: [
588
+ { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
589
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
590
+ { tag: 'signature', attrs: {}, content: key.signature }
591
+ ]
592
+ })
593
+
594
+ export const xmppPreKey = (pair, id) => ({
595
+ tag: 'key',
596
+ attrs: {},
597
+ content: [
598
+ { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
599
+ { tag: 'value', attrs: {}, content: pair.public }
600
+ ]
601
+ })
602
+
603
+ const isValidUInt = n => typeof n === 'number' && Number.isInteger(n)
604
+
605
+ export const extractE2ESessionFromRetryReceipt = receipt => {
606
+ const keysNode = getBinaryNodeChild(receipt, 'keys')
607
+ if (!keysNode) return null
608
+ const typeBuf = getBinaryNodeChildBuffer(keysNode, 'type')
609
+ if (!typeBuf || typeBuf.length !== 1 || typeBuf[0] !== KEY_BUNDLE_TYPE[0]) return null
610
+ const identity = getBinaryNodeChildBuffer(keysNode, 'identity')
611
+ const skey = getBinaryNodeChild(keysNode, 'skey')
612
+ if (!identity || identity.length !== 32 || !skey) return null
613
+ const registrationId = getBinaryNodeChildUInt(receipt, 'registration', 4)
614
+ if (!isValidUInt(registrationId)) return null
615
+ const signedPubKey = getBinaryNodeChildBuffer(skey, 'value')
616
+ const signedSig = getBinaryNodeChildBuffer(skey, 'signature')
617
+ const signedKeyId = getBinaryNodeChildUInt(skey, 'id', 3)
618
+ if (!signedPubKey || signedPubKey.length !== 32 || !signedSig || !isValidUInt(signedKeyId)) return null
619
+ const preKeyNode = getBinaryNodeChild(keysNode, 'key')
620
+ let preKey
621
+ if (preKeyNode) {
622
+ const preKeyPub = getBinaryNodeChildBuffer(preKeyNode, 'value')
623
+ const preKeyId = getBinaryNodeChildUInt(preKeyNode, 'id', 3)
624
+ if (!preKeyPub || preKeyPub.length !== 32 || !isValidUInt(preKeyId)) return null
625
+ preKey = { keyId: preKeyId, publicKey: generateSignalPubKey(preKeyPub) }
626
+ }
627
+ return {
628
+ registrationId,
629
+ identityKey: generateSignalPubKey(identity),
630
+ signedPreKey: { keyId: signedKeyId, publicKey: generateSignalPubKey(signedPubKey), signature: signedSig },
631
+ preKey
632
+ }
633
+ }
634
+
635
+ export const parseAndInjectE2ESessions = async (node, repository) => {
636
+ const extractKey = key =>
637
+ key
638
+ ? {
639
+ keyId: getBinaryNodeChildUInt(key, 'id', 3),
640
+ publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
641
+ signature: getBinaryNodeChildBuffer(key, 'signature')
642
+ }
643
+ : undefined
644
+
645
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user')
646
+ for (const n of nodes) assertNodeErrorFree(n)
647
+
648
+ // Chunked to yield to the event loop between batches (injectE2ESession is CPU-heavy, not IO).
649
+ const chunkSize = 100
650
+ const chunks = chunkArray(nodes, chunkSize)
651
+ for (const nodesChunk of chunks) {
652
+ for (const n of nodesChunk) {
653
+ const signedKey = getBinaryNodeChild(n, 'skey')
654
+ const key = getBinaryNodeChild(n, 'key')
655
+ const identity = getBinaryNodeChildBuffer(n, 'identity')
656
+ const jid = n.attrs.jid
657
+ const registrationId = getBinaryNodeChildUInt(n, 'registration', 4)
658
+ await repository.injectE2ESession({
659
+ jid,
660
+ session: {
661
+ registrationId,
662
+ identityKey: generateSignalPubKey(identity),
663
+ signedPreKey: extractKey(signedKey),
664
+ preKey: extractKey(key)
665
+ }
666
+ })
667
+ }
668
+ }
669
+ }
670
+
671
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
672
+ const { user: myUser, device: myDevice } = jidDecode(myJid)
673
+ const extracted = []
674
+ for (const userResult of result) {
675
+ const { devices, id } = userResult
676
+ const decoded = jidDecode(id)
677
+ const { user, server } = decoded
678
+ let { domainType } = decoded
679
+ const deviceList = devices?.deviceList
680
+ if (!Array.isArray(deviceList)) continue
681
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
682
+ if (
683
+ (!excludeZeroDevices || device !== 0) &&
684
+ ((myUser !== user && myLid !== user) || myDevice !== device) &&
685
+ (device === 0 || !!keyIndex)
686
+ ) {
687
+ if (isHosted) domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED
688
+ extracted.push({ user, device, domainType, server: getServerFromDomainType(server, domainType) })
689
+ }
690
+ }
691
+ }
692
+ return extracted
693
+ }
694
+
695
+ /** get the next N keys for upload or processing */
696
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
697
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count)
698
+ const update = {
699
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
700
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
701
+ }
702
+ await keys.set({ 'pre-key': newPreKeys })
703
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1])
704
+ return { update, preKeys }
705
+ }
706
+
707
+ export const getNextPreKeysNode = async (state, count) => {
708
+ const { creds } = state
709
+ const { update, preKeys } = await getNextPreKeys(state, count)
710
+ const node = {
711
+ tag: 'iq',
712
+ attrs: { xmlns: 'encrypt', type: 'set', to: S_WHATSAPP_NET },
713
+ content: [
714
+ { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
715
+ { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
716
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
717
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
718
+ xmppSignedPreKey(creds.signedPreKey)
719
+ ]
720
+ }
721
+ return { update, node }
722
+ }
723
+
724
+ /* ------------------------------------------------------------------ */
725
+ /* Noise protocol handshake handler */
726
+ /* ------------------------------------------------------------------ */
727
+
728
+ const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0'
729
+ const WA_CERT_DETAILS = {
730
+ SERIAL: 0,
731
+ ISSUER: 'WhatsAppLongTerm1',
732
+ PUBLIC_KEY: Buffer.from('142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b', 'hex')
733
+ }
734
+
735
+ const IV_LENGTH = 12
736
+ const EMPTY_BUFFER = Buffer.alloc(0)
737
+ const generateIV = counter => {
738
+ const iv = new ArrayBuffer(IV_LENGTH)
739
+ new DataView(iv).setUint32(8, counter)
740
+ return new Uint8Array(iv)
741
+ }
742
+
743
+ class TransportState {
744
+ constructor(encKey, decKey) {
745
+ this.encKey = encKey
746
+ this.decKey = decKey
747
+ this.readCounter = 0
748
+ this.writeCounter = 0
749
+ this.iv = new Uint8Array(IV_LENGTH)
750
+ }
751
+ encrypt(plaintext) {
752
+ const c = this.writeCounter++
753
+ this.iv[8] = (c >>> 24) & 0xff
754
+ this.iv[9] = (c >>> 16) & 0xff
755
+ this.iv[10] = (c >>> 8) & 0xff
756
+ this.iv[11] = c & 0xff
757
+ return aesEncryptGCM(plaintext, this.encKey, this.iv, EMPTY_BUFFER)
758
+ }
759
+ decrypt(ciphertext) {
760
+ const c = this.readCounter++
761
+ this.iv[8] = (c >>> 24) & 0xff
762
+ this.iv[9] = (c >>> 16) & 0xff
763
+ this.iv[10] = (c >>> 8) & 0xff
764
+ this.iv[11] = c & 0xff
765
+ return aesDecryptGCM(ciphertext, this.decKey, this.iv, EMPTY_BUFFER)
766
+ }
767
+ }
768
+
769
+ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
770
+ // Defense in depth: logger can end up undefined/null if a caller passes
771
+ // it explicitly (e.g. a stale reference during reconnect) — don't crash,
772
+ // fall back to a fresh silent-by-default logger instead.
773
+ logger = (logger || createLogger()).child({ class: 'ns' })
774
+ const data = Buffer.from(NOISE_MODE)
775
+ let hash = data.byteLength === 32 ? data : sha256(data)
776
+ let salt = hash
777
+ let encKey = hash
778
+ let decKey = hash
779
+ let counter = 0
780
+ let sentIntro = false
781
+ let inBytes = Buffer.alloc(0)
782
+ let transport = null
783
+ let isWaitingForTransport = false
784
+ let pendingOnFrame = null
785
+ let introHeader
786
+ let destroyed = false
787
+ // Defense in depth: if data arrives faster than it can be processed (or a peer
788
+ // misbehaves), inBytes would otherwise grow unbounded and eventually OOM the
789
+ // process. Cap it and drop the buffered bytes rather than let it balloon.
790
+ const MAX_IN_BYTES = 10 * 1024 * 1024
791
+
792
+ if (routingInfo) {
793
+ introHeader = Buffer.alloc(7 + routingInfo.byteLength + NOISE_HEADER.length)
794
+ introHeader.write('ED', 0, 'utf8')
795
+ introHeader.writeUint8(0, 2)
796
+ introHeader.writeUint8(1, 3)
797
+ introHeader.writeUint8(routingInfo.byteLength >> 16, 4)
798
+ introHeader.writeUint16BE(routingInfo.byteLength & 65535, 5)
799
+ introHeader.set(routingInfo, 7)
800
+ introHeader.set(NOISE_HEADER, 7 + routingInfo.byteLength)
801
+ } else {
802
+ introHeader = Buffer.from(NOISE_HEADER)
803
+ }
804
+
805
+ const authenticate = data => {
806
+ if (!transport) hash = sha256(Buffer.concat([hash, data]))
807
+ }
808
+ const encrypt = plaintext => {
809
+ if (transport) return transport.encrypt(plaintext)
810
+ const result = aesEncryptGCM(plaintext, encKey, generateIV(counter++), hash)
811
+ authenticate(result)
812
+ return result
813
+ }
814
+ const decrypt = ciphertext => {
815
+ if (transport) return transport.decrypt(ciphertext)
816
+ const result = aesDecryptGCM(ciphertext, decKey, generateIV(counter++), hash)
817
+ authenticate(ciphertext)
818
+ return result
819
+ }
820
+ const localHKDF = data => {
821
+ const key = hkdf(Buffer.from(data), 64, { salt, info: '' })
822
+ return [key.subarray(0, 32), key.subarray(32)]
823
+ }
824
+ const mixIntoKey = data => {
825
+ const [write, read] = localHKDF(data)
826
+ salt = write
827
+ encKey = read
828
+ decKey = read
829
+ counter = 0
830
+ }
831
+ const finishInit = async () => {
832
+ isWaitingForTransport = true
833
+ const [write, read] = localHKDF(new Uint8Array(0))
834
+ transport = new TransportState(write, read)
835
+ isWaitingForTransport = false
836
+ logger.trace('Noise handler transitioned to Transport state')
837
+ if (pendingOnFrame) {
838
+ logger.trace({ length: inBytes.length }, 'Flushing buffered frames after transport ready')
839
+ await processData(pendingOnFrame)
840
+ pendingOnFrame = null
841
+ }
842
+ }
843
+ const processData = async onFrame => {
844
+ let size
845
+ while (true) {
846
+ if (inBytes.length < 3) return
847
+ size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2]
848
+ if (inBytes.length < size + 3) return
849
+ let frame = inBytes.subarray(3, size + 3)
850
+ inBytes = inBytes.subarray(size + 3)
851
+ if (transport) {
852
+ const result = transport.decrypt(frame)
853
+ frame = await decodeBinaryNode(result)
854
+ }
855
+ if (logger.level === 'trace') logger.trace({ msg: frame?.attrs?.id }, 'recv frame')
856
+ onFrame(frame)
857
+ }
858
+ }
859
+
860
+ authenticate(NOISE_HEADER)
861
+ authenticate(publicKey)
862
+
863
+ return {
864
+ encrypt,
865
+ decrypt,
866
+ authenticate,
867
+ mixIntoKey,
868
+ finishInit,
869
+ processHandshake: ({ serverHello }, noiseKey) => {
870
+ authenticate(serverHello.ephemeral)
871
+ mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral))
872
+ const decStaticContent = decrypt(serverHello.static)
873
+ mixIntoKey(Curve.sharedKey(privateKey, decStaticContent))
874
+ const certDecoded = decrypt(serverHello.payload)
875
+ const { intermediate: certIntermediate, leaf } = proto.CertChain.decode(certDecoded)
876
+
877
+ if (!leaf?.details || !leaf?.signature) throw new Boom('invalid noise leaf certificate', { statusCode: 400 })
878
+ if (!certIntermediate?.details || !certIntermediate?.signature) {
879
+ throw new Boom('invalid noise intermediate certificate', { statusCode: 400 })
880
+ }
881
+
882
+ const details = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details)
883
+ const { issuerSerial } = details
884
+ const verify = Curve.verify(details.key, leaf.details, leaf.signature)
885
+ const verifyIntermediate = Curve.verify(WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature)
886
+
887
+ if (!verify) throw new Boom('noise certificate signature invalid', { statusCode: 400 })
888
+ if (!verifyIntermediate) throw new Boom('noise intermediate certificate signature invalid', { statusCode: 400 })
889
+ if (issuerSerial !== WA_CERT_DETAILS.SERIAL) throw new Boom('certification match failed', { statusCode: 400 })
890
+
891
+ const keyEnc = encrypt(noiseKey.public)
892
+ mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral))
893
+ return keyEnc
894
+ },
895
+ encodeFrame: data => {
896
+ if (transport) data = transport.encrypt(data)
897
+ const dataLen = data.byteLength
898
+ const introSize = sentIntro ? 0 : introHeader.length
899
+ const frame = Buffer.allocUnsafe(introSize + 3 + dataLen)
900
+ if (!sentIntro) {
901
+ frame.set(introHeader)
902
+ sentIntro = true
903
+ }
904
+ frame[introSize] = (dataLen >>> 16) & 0xff
905
+ frame[introSize + 1] = (dataLen >>> 8) & 0xff
906
+ frame[introSize + 2] = dataLen & 0xff
907
+ frame.set(data, introSize + 3)
908
+ return frame
909
+ },
910
+ decodeFrame: async (newData, onFrame) => {
911
+ if (destroyed) return
912
+ if (isWaitingForTransport) {
913
+ inBytes = Buffer.concat([inBytes, newData])
914
+ pendingOnFrame = onFrame
915
+ } else {
916
+ inBytes = inBytes.length === 0 ? Buffer.from(newData) : Buffer.concat([inBytes, newData])
917
+ }
918
+ if (inBytes.length > MAX_IN_BYTES) {
919
+ logger.error({ bufferedBytes: inBytes.length, max: MAX_IN_BYTES }, 'noise handler inBytes buffer exceeded cap, clearing')
920
+ inBytes = Buffer.alloc(0)
921
+ pendingOnFrame = null
922
+ return
923
+ }
924
+ if (!isWaitingForTransport) await processData(onFrame)
925
+ },
926
+ /**
927
+ * Release internal state (encryption buffers, transport state, pending frame
928
+ * callbacks) when the connection is torn down, so none of it lingers in memory
929
+ * and no further frames are processed on a dead connection.
930
+ */
931
+ destroy: () => {
932
+ destroyed = true
933
+ inBytes = Buffer.alloc(0)
934
+ pendingOnFrame = null
935
+ transport = null
936
+ }
937
+ }
938
+ }
939
+
940
+ /* ------------------------------------------------------------------ */
941
+ /* Connection validation (login / registration / pairing) */
942
+ /* ------------------------------------------------------------------ */
943
+
944
+ const WA_ADV_ACCOUNT_SIG_PREFIX = Buffer.from([6, 0])
945
+ const WA_ADV_DEVICE_SIG_PREFIX = Buffer.from([6, 1])
946
+ const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5])
947
+
948
+ const getUserAgent = config => ({
949
+ appVersion: { primary: config.version[0], secondary: config.version[1], tertiary: config.version[2] },
950
+ platform: config.browser[1].toLocaleLowerCase().includes('android')
951
+ ? proto.ClientPayload.UserAgent.Platform.ANDROID
952
+ : proto.ClientPayload.UserAgent.Platform.WEB,
953
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
954
+ osVersion: '0.1',
955
+ device: 'Desktop',
956
+ osBuildNumber: '0.1',
957
+ localeLanguageIso6391: 'en',
958
+ mnc: '000',
959
+ mcc: '000',
960
+ localeCountryIso31661Alpha2: config.countryCode
961
+ })
962
+
963
+ const WEB_PLATFORM_MAP = {
964
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
965
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
966
+ }
967
+
968
+ const getWebInfo = config => {
969
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
970
+ if (config.syncFullHistory && WEB_PLATFORM_MAP[config.browser[0]] && config.browser[1] === 'Desktop') {
971
+ webSubPlatform = WEB_PLATFORM_MAP[config.browser[0]]
972
+ }
973
+ return { webSubPlatform }
974
+ }
975
+
976
+ const getClientPayload = config => {
977
+ const payload = {
978
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
979
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
980
+ userAgent: getUserAgent(config)
981
+ }
982
+ if (!config.browser[1].toLocaleLowerCase().includes('android')) payload.webInfo = getWebInfo(config)
983
+ if (config.pushName) payload.pushName = config.pushName
984
+ return payload
985
+ }
986
+
987
+ export const generateLoginNode = (userJid, config) => {
988
+ const { user, device } = jidDecode(userJid)
989
+ const payload = { ...getClientPayload(config), passive: true, pull: true, username: +user, device, lidDbMigrated: false }
990
+ return proto.ClientPayload.fromObject(payload)
991
+ }
992
+
993
+ const getPlatformType = platform => {
994
+ const platformType = platform.toUpperCase()
995
+ if (platformType === 'ANDROID') return proto.DeviceProps.PlatformType.ANDROID_PHONE
996
+ return proto.DeviceProps.PlatformType[platformType] || proto.DeviceProps.PlatformType.CHROME
997
+ }
998
+
999
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
1000
+ const appVersionBuf = createHash('md5').update(config.version.join('.')).digest()
1001
+ const companion = {
1002
+ os: config.browser[0],
1003
+ platformType: getPlatformType(config.browser[1]),
1004
+ requireFullSync: config.syncFullHistory,
1005
+ historySyncConfig: {
1006
+ storageQuotaMb: 10240,
1007
+ inlineInitialPayloadInE2EeMsg: true,
1008
+ recentSyncDaysLimit: undefined,
1009
+ supportCallLogHistory: false,
1010
+ supportBotUserAgentChatHistory: true,
1011
+ supportCagReactionsAndPolls: true,
1012
+ supportBizHostedMsg: true,
1013
+ supportRecentSyncChunkMessageCountTuning: true,
1014
+ supportHostedGroupMsg: true,
1015
+ supportFbidBotChatHistory: true,
1016
+ supportAddOnHistorySyncMigration: undefined,
1017
+ supportMessageAssociation: true,
1018
+ supportGroupHistory: false,
1019
+ onDemandReady: undefined,
1020
+ supportGuestChat: undefined
1021
+ },
1022
+ version: { primary: 10, secondary: 15, tertiary: 7 }
1023
+ }
1024
+ const companionProto = proto.DeviceProps.encode(companion).finish()
1025
+ const registerPayload = {
1026
+ ...getClientPayload(config),
1027
+ passive: false,
1028
+ pull: false,
1029
+ devicePairingData: {
1030
+ buildHash: appVersionBuf,
1031
+ deviceProps: companionProto,
1032
+ eRegid: encodeBigEndian(registrationId),
1033
+ eKeytype: KEY_BUNDLE_TYPE,
1034
+ eIdent: signedIdentityKey.public,
1035
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
1036
+ eSkeyVal: signedPreKey.keyPair.public,
1037
+ eSkeySig: signedPreKey.signature
1038
+ }
1039
+ }
1040
+ return proto.ClientPayload.fromObject(registerPayload)
1041
+ }
1042
+
1043
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
1044
+ const msgId = stanza.attrs.id
1045
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
1046
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity')
1047
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform')
1048
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device')
1049
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz')
1050
+
1051
+ if (!deviceIdentityNode || !deviceNode) throw new Boom('Missing device-identity or device in pair success node', { data: stanza })
1052
+
1053
+ const bizName = businessNode?.attrs.name
1054
+ const jid = deviceNode.attrs.jid
1055
+ const lid = deviceNode.attrs.lid
1056
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content)
1057
+
1058
+ let hmacPrefix = Buffer.from([])
1059
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
1060
+
1061
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'))
1062
+ if (Buffer.compare(hmac, advSign) !== 0) throw new Boom('Invalid account signature')
1063
+
1064
+ const account = proto.ADVSignedDeviceIdentity.decode(details)
1065
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account
1066
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails)
1067
+ const accountSignaturePrefix =
1068
+ deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX : WA_ADV_ACCOUNT_SIG_PREFIX
1069
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public])
1070
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) throw new Boom('Failed to verify account signature')
1071
+
1072
+ const deviceMsg = Buffer.concat([WA_ADV_DEVICE_SIG_PREFIX, deviceDetails, signedIdentityKey.public, accountSignatureKey])
1073
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
1074
+ const identity = createSignalIdentity(lid, accountSignatureKey)
1075
+ const accountEnc = encodeSignedDeviceIdentity(account, false)
1076
+
1077
+ const reply = {
1078
+ tag: 'iq',
1079
+ attrs: { to: S_WHATSAPP_NET, type: 'result', id: msgId },
1080
+ content: [
1081
+ {
1082
+ tag: 'pair-device-sign',
1083
+ attrs: {},
1084
+ content: [{ tag: 'device-identity', attrs: { 'key-index': deviceIdentity.keyIndex.toString() }, content: accountEnc }]
1085
+ }
1086
+ ]
1087
+ }
1088
+ const authUpdate = {
1089
+ account,
1090
+ me: { id: jid, name: bizName, lid },
1091
+ signalIdentities: [...(signalIdentities || []), identity],
1092
+ platform: platformNode?.attrs.name
1093
+ }
1094
+ return { creds: authUpdate, reply }
1095
+ }
1096
+
1097
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
1098
+ account = { ...account }
1099
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) account.accountSignatureKey = null
1100
+ return proto.ADVSignedDeviceIdentity.encode(account).finish()
1101
+ }
1102
+
1103
+ /* ------------------------------------------------------------------ */
1104
+ /* Message reporting token */
1105
+ /* ------------------------------------------------------------------ */
1106
+
1107
+ const reportingFields = [
1108
+ { f: 1 },
1109
+ { f: 3, s: [{ f: 2 }, { f: 3 }, { f: 8 }, { f: 11 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 25 }] },
1110
+ { f: 4, s: [{ f: 1 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
1111
+ { f: 5, s: [{ f: 3 }, { f: 4 }, { f: 5 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
1112
+ { f: 6, s: [{ f: 1 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 30 }] },
1113
+ { f: 7, s: [{ f: 2 }, { f: 7 }, { f: 10 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
1114
+ { f: 8, s: [{ f: 2 }, { f: 7 }, { f: 9 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 21 }] },
1115
+ { f: 9, s: [{ f: 2 }, { f: 6 }, { f: 7 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
1116
+ { f: 12, s: [{ f: 1 }, { f: 2 }, { f: 14, m: true }, { f: 15 }] },
1117
+ { f: 18, s: [{ f: 6 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
1118
+ { f: 26, s: [{ f: 4 }, { f: 5 }, { f: 8 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
1119
+ { f: 28, s: [{ f: 1 }, { f: 2 }, { f: 4 }, { f: 5 }, { f: 6 }, { f: 7, s: [{ f: 21 }, { f: 22 }] }] },
1120
+ { f: 37, s: [{ f: 1, m: true }] },
1121
+ { f: 49, s: [{ f: 2 }, { f: 3, s: [{ f: 1 }, { f: 2 }] }, { f: 5, s: [{ f: 21 }, { f: 22 }] }, { f: 8, s: [{ f: 1 }, { f: 2 }] }] },
1122
+ { f: 53, s: [{ f: 1, m: true }] },
1123
+ { f: 55, s: [{ f: 1, m: true }] },
1124
+ { f: 58, s: [{ f: 1, m: true }] },
1125
+ { f: 59, s: [{ f: 1, m: true }] },
1126
+ { f: 60, s: [{ f: 2 }, { f: 3, s: [{ f: 1 }, { f: 2 }] }, { f: 5, s: [{ f: 21 }, { f: 22 }] }, { f: 8, s: [{ f: 1 }, { f: 2 }] }] },
1127
+ { f: 64, s: [{ f: 2 }, { f: 3, s: [{ f: 1 }, { f: 2 }] }, { f: 5, s: [{ f: 21 }, { f: 22 }] }, { f: 8, s: [{ f: 1 }, { f: 2 }] }] },
1128
+ { f: 66, s: [{ f: 2 }, { f: 6 }, { f: 7 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
1129
+ { f: 74, s: [{ f: 1, m: true }] },
1130
+ { f: 87, s: [{ f: 1, m: true }] },
1131
+ { f: 88, s: [{ f: 1 }, { f: 2, s: [{ f: 1 }] }, { f: 3, s: [{ f: 21 }, { f: 22 }] }] },
1132
+ { f: 92, s: [{ f: 1, m: true }] },
1133
+ { f: 93, s: [{ f: 1, m: true }] },
1134
+ { f: 94, s: [{ f: 1, m: true }] }
1135
+ ]
1136
+
1137
+ const compileReportingFields = fields => {
1138
+ const map = new Map()
1139
+ for (const f of fields) map.set(f.f, { m: f.m, children: f.s ? compileReportingFields(f.s) : undefined })
1140
+ return map
1141
+ }
1142
+ const compiledReportingFields = compileReportingFields(reportingFields)
1143
+ const EMPTY_MAP = new Map()
1144
+ const ENC_SECRET_REPORT_TOKEN = 'Report Token'
1145
+ const WIRE = { VARINT: 0, FIXED64: 1, BYTES: 2, FIXED32: 5 }
1146
+
1147
+ export const shouldIncludeReportingToken = message =>
1148
+ !message.reactionMessage && !message.encReactionMessage && !message.encEventResponseMessage && !message.pollUpdateMessage
1149
+
1150
+ const generateMsgSecretKey = (modificationType, origMsgId, origMsgSender, modificationSender, origMsgSecret) => {
1151
+ const useCaseSecret = Buffer.concat([
1152
+ Buffer.from(origMsgId, 'utf8'),
1153
+ Buffer.from(origMsgSender, 'utf8'),
1154
+ Buffer.from(modificationSender, 'utf8'),
1155
+ Buffer.from(modificationType, 'utf8')
1156
+ ])
1157
+ return hkdf(origMsgSecret, 32, { info: useCaseSecret.toString('latin1') })
1158
+ }
1159
+
1160
+ const decodeVarint = (buffer, offset) => {
1161
+ let value = 0
1162
+ let bytes = 0
1163
+ let shift = 0
1164
+ while (offset + bytes < buffer.length) {
1165
+ const current = buffer[offset + bytes]
1166
+ value |= (current & 0x7f) << shift
1167
+ bytes++
1168
+ if ((current & 0x80) === 0) return { value, bytes, ok: true }
1169
+ shift += 7
1170
+ if (shift > 35) return { value: 0, bytes: 0, ok: false }
1171
+ }
1172
+ return { value: 0, bytes: 0, ok: false }
1173
+ }
1174
+
1175
+ const encodeVarint = value => {
1176
+ const parts = []
1177
+ let remaining = value >>> 0
1178
+ while (remaining > 0x7f) {
1179
+ parts.push((remaining & 0x7f) | 0x80)
1180
+ remaining >>>= 7
1181
+ }
1182
+ parts.push(remaining)
1183
+ return Buffer.from(parts)
1184
+ }
1185
+
1186
+ const extractReportingTokenContent = (data, cfg) => {
1187
+ const out = []
1188
+ let i = 0
1189
+ while (i < data.length) {
1190
+ const tag = decodeVarint(data, i)
1191
+ if (!tag.ok) return null
1192
+ const fieldNum = tag.value >> 3
1193
+ const wireType = tag.value & 0x7
1194
+ const fieldStart = i
1195
+ i += tag.bytes
1196
+ const fieldCfg = cfg.get(fieldNum)
1197
+ const pushSlice = end => {
1198
+ if (end > data.length) return false
1199
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, end) })
1200
+ i = end
1201
+ return true
1202
+ }
1203
+ const skip = end => {
1204
+ if (end > data.length) return false
1205
+ i = end
1206
+ return true
1207
+ }
1208
+ if (wireType === WIRE.VARINT) {
1209
+ const v = decodeVarint(data, i)
1210
+ if (!v.ok) return null
1211
+ const end = i + v.bytes
1212
+ if (!fieldCfg) {
1213
+ if (!skip(end)) return null
1214
+ continue
1215
+ }
1216
+ if (!pushSlice(end)) return null
1217
+ continue
1218
+ }
1219
+ if (wireType === WIRE.FIXED64) {
1220
+ const end = i + 8
1221
+ if (!fieldCfg) {
1222
+ if (!skip(end)) return null
1223
+ continue
1224
+ }
1225
+ if (!pushSlice(end)) return null
1226
+ continue
1227
+ }
1228
+ if (wireType === WIRE.FIXED32) {
1229
+ const end = i + 4
1230
+ if (!fieldCfg) {
1231
+ if (!skip(end)) return null
1232
+ continue
1233
+ }
1234
+ if (!pushSlice(end)) return null
1235
+ continue
1236
+ }
1237
+ if (wireType === WIRE.BYTES) {
1238
+ const len = decodeVarint(data, i)
1239
+ if (!len.ok) return null
1240
+ const valStart = i + len.bytes
1241
+ const valEnd = valStart + len.value
1242
+ if (valEnd > data.length) return null
1243
+ if (!fieldCfg) {
1244
+ i = valEnd
1245
+ continue
1246
+ }
1247
+ if (fieldCfg.m || fieldCfg.children) {
1248
+ const sub = extractReportingTokenContent(data.subarray(valStart, valEnd), fieldCfg.children ?? EMPTY_MAP)
1249
+ if (sub === null) return null
1250
+ if (sub.length > 0) {
1251
+ const newTag = encodeVarint(tag.value)
1252
+ const newLen = encodeVarint(sub.length)
1253
+ out.push({ num: fieldNum, bytes: Buffer.concat([newTag, newLen, sub]) })
1254
+ }
1255
+ i = valEnd
1256
+ continue
1257
+ }
1258
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, valEnd) })
1259
+ i = valEnd
1260
+ continue
1261
+ }
1262
+ return null
1263
+ }
1264
+ if (out.length === 0) return Buffer.alloc(0)
1265
+ out.sort((a, b) => a.num - b.num)
1266
+ return Buffer.concat(out.map(f => f.bytes))
1267
+ }
1268
+
1269
+ export const getMessageReportingToken = async (msgProtobuf, message, key) => {
1270
+ const msgSecret = message.messageContextInfo?.messageSecret
1271
+ if (!msgSecret || !key.id) return null
1272
+ const from = key.fromMe ? key.remoteJid : key.participant || key.remoteJid
1273
+ const to = key.fromMe ? key.participant || key.remoteJid : key.remoteJid
1274
+ const reportingSecret = generateMsgSecretKey(ENC_SECRET_REPORT_TOKEN, key.id, from, to, msgSecret)
1275
+ const content = extractReportingTokenContent(msgProtobuf, compiledReportingFields)
1276
+ if (!content || content.length === 0) return null
1277
+ const reportingToken = createHmac('sha256', reportingSecret).update(content).digest().subarray(0, 16)
1278
+ return {
1279
+ tag: 'reporting',
1280
+ attrs: {},
1281
+ content: [{ tag: 'reporting_token', attrs: { v: '2' }, content: reportingToken }]
1282
+ }
1283
+ }