@itznomo/baileys 0.0.0-stage → 0.0.3

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