@hiroosy/baileys-lite 0.0.3 → 0.3.0
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.
- package/LICENSE +21 -0
- package/README.md +660 -12
- package/WAProto/index.js +2 -2558
- package/engine-requirements.js +3 -4
- package/package.json +8 -3
- package/src/binary/wa-binary.js +3 -25
- package/src/constants.js +7 -15
- package/src/defaults.js +2 -5
- package/src/foundation/ai-rich.js +530 -0
- package/src/foundation/audio-duration.js +43 -103
- package/src/foundation/audio-samples.js +19 -37
- package/src/foundation/boom.js +0 -7
- package/src/foundation/cache.js +4 -26
- package/src/foundation/concurrency.js +1 -19
- package/src/foundation/curve25519.js +7 -39
- package/src/foundation/link-preview.js +15 -57
- package/src/foundation/logger.js +0 -11
- package/src/foundation/long.js +4 -14
- package/src/foundation/protobuf-minimal.js +21 -53
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +702 -0
- package/src/foundation/wa-crypto.js +2 -31
- package/src/foundation/zip.js +25 -41
- package/src/index.js +8 -18
- package/src/signal/libsignal.js +23 -78
- package/src/signal/signal-group.js +0 -35
- package/src/signal/signal-repository.js +10 -29
- package/src/socket/business-communities.js +12 -31
- package/src/socket/chats.js +5 -8
- package/src/socket/groups-newsletter.js +18 -17
- package/src/socket/messages-recv.js +81 -127
- package/src/socket/messages-send.js +372 -139
- package/src/socket/socket-core.js +227 -157
- package/src/socket/usync.js +2 -6
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +84 -38
- package/src/utils/auth-state-core.js +14 -56
- package/src/utils/auth-state-storage.js +7 -42
- package/src/utils/chat-sync.js +4 -26
- package/src/utils/media.js +15 -71
- package/src/utils/message-compose.js +208 -85
- package/src/utils/message-processing.js +10 -65
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +71 -127
- package/src/vendor/jpeg-js/decoder.js +75 -136
- package/src/vendor/jpeg-js/encoder.js +179 -264
- package/src/vendor/pngjs/bitmapper.js +5 -27
- package/src/vendor/pngjs/bitpacker.js +4 -12
- package/src/vendor/pngjs/constants.js +3 -11
- package/src/vendor/pngjs/crc.js +0 -6
- package/src/vendor/pngjs/filter-pack.js +1 -7
- package/src/vendor/pngjs/filter-parse-sync.js +0 -6
- package/src/vendor/pngjs/filter-parse.js +1 -11
- package/src/vendor/pngjs/format-normaliser.js +5 -11
- package/src/vendor/pngjs/interlace.js +7 -24
- package/src/vendor/pngjs/packer-sync.js +0 -11
- package/src/vendor/pngjs/packer.js +7 -15
- package/src/vendor/pngjs/paeth-predictor.js +0 -6
- package/src/vendor/pngjs/parser-sync.js +0 -8
- package/src/vendor/pngjs/parser.js +5 -29
- package/src/vendor/pngjs/png-sync.js +0 -7
- package/src/vendor/pngjs/sync-inflate.js +7 -16
- package/src/vendor/pngjs/sync-reader.js +4 -11
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1705 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +628 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +0 -1
- package/src/wam/wam.js +2 -7
|
@@ -1,12 +1,3 @@
|
|
|
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
1
|
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomFillSync } from 'node:crypto'
|
|
11
2
|
import { platform, release } from 'node:os'
|
|
12
3
|
import { curve } from '../signal/libsignal.js'
|
|
@@ -14,6 +5,7 @@ import { createLogger } from '../foundation/logger.js'
|
|
|
14
5
|
import { md5, hkdf, LTHashAntiTampering } from '../foundation/wa-crypto.js'
|
|
15
6
|
import { Boom } from '../foundation/boom.js'
|
|
16
7
|
import { proto } from '../../WAProto/index.js'
|
|
8
|
+
import { DisconnectReason } from '../constants.js'
|
|
17
9
|
import {
|
|
18
10
|
getAllBinaryNodeChildren,
|
|
19
11
|
getBinaryNodeChild,
|
|
@@ -30,33 +22,22 @@ import {
|
|
|
30
22
|
|
|
31
23
|
export { md5, hkdf }
|
|
32
24
|
|
|
33
|
-
/* ------------------------------------------------------------------ */
|
|
34
|
-
/* Crypto primitives */
|
|
35
|
-
/* ------------------------------------------------------------------ */
|
|
36
|
-
|
|
37
25
|
const KEY_BUNDLE_TYPE = Buffer.from([5])
|
|
38
26
|
export { KEY_BUNDLE_TYPE }
|
|
39
27
|
|
|
40
|
-
/** prefix version byte to the pub keys, required for some curve crypto functions */
|
|
41
28
|
export const generateSignalPubKey = pubKey => (pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]))
|
|
42
29
|
|
|
43
30
|
export const Curve = {
|
|
44
31
|
generateKeyPair: () => {
|
|
45
32
|
const { pubKey, privKey } = curve.generateKeyPair()
|
|
46
|
-
return { private: Buffer.from(privKey), public: Buffer.from(pubKey.slice(1)) }
|
|
33
|
+
return { private: Buffer.from(privKey), public: Buffer.from(pubKey.slice(1)) }
|
|
47
34
|
},
|
|
48
35
|
sharedKey: (privateKey, publicKey) => {
|
|
49
36
|
const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey)
|
|
50
37
|
return Buffer.from(shared)
|
|
51
38
|
},
|
|
52
39
|
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
|
-
*/
|
|
40
|
+
|
|
60
41
|
verify: (pubKey, message, signature) => {
|
|
61
42
|
try {
|
|
62
43
|
curve.verifySignature(generateSignalPubKey(pubKey), message, signature)
|
|
@@ -65,11 +46,7 @@ export const Curve = {
|
|
|
65
46
|
return false
|
|
66
47
|
}
|
|
67
48
|
},
|
|
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
|
-
*/
|
|
49
|
+
|
|
73
50
|
verifyStrict: (pubKey, message, signature) => {
|
|
74
51
|
try {
|
|
75
52
|
return curve.verifySignature(generateSignalPubKey(pubKey), message, signature) === true
|
|
@@ -88,14 +65,12 @@ export const signedKeyPair = (identityKeyPair, keyId) => {
|
|
|
88
65
|
|
|
89
66
|
const GCM_TAG_LENGTH = 128 >> 3
|
|
90
67
|
|
|
91
|
-
/** encrypt AES 256 GCM; the auth tag is suffixed to the ciphertext */
|
|
92
68
|
export function aesEncryptGCM(plaintext, key, iv, additionalData) {
|
|
93
69
|
const cipher = createCipheriv('aes-256-gcm', key, iv)
|
|
94
70
|
cipher.setAAD(additionalData)
|
|
95
71
|
return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()])
|
|
96
72
|
}
|
|
97
73
|
|
|
98
|
-
/** decrypt AES 256 GCM; the auth tag is suffixed to the ciphertext */
|
|
99
74
|
export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
|
|
100
75
|
const decipher = createDecipheriv('aes-256-gcm', key, iv)
|
|
101
76
|
const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH)
|
|
@@ -115,7 +90,6 @@ export function aesDecryptCTR(ciphertext, key, iv) {
|
|
|
115
90
|
return Buffer.concat([decipher.update(ciphertext), decipher.final()])
|
|
116
91
|
}
|
|
117
92
|
|
|
118
|
-
/** decrypt AES 256 CBC; the IV is prefixed to the buffer */
|
|
119
93
|
export function aesDecrypt(buffer, key) {
|
|
120
94
|
return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16))
|
|
121
95
|
}
|
|
@@ -125,7 +99,6 @@ export function aesDecryptWithIV(buffer, key, IV) {
|
|
|
125
99
|
return Buffer.concat([aes.update(buffer), aes.final()])
|
|
126
100
|
}
|
|
127
101
|
|
|
128
|
-
/** encrypt AES 256 CBC; a random IV is prefixed to the buffer */
|
|
129
102
|
export function aesEncrypt(buffer, key) {
|
|
130
103
|
const IV = randomBytes(16)
|
|
131
104
|
const aes = createCipheriv('aes-256-cbc', key, IV)
|
|
@@ -155,21 +128,8 @@ export async function derivePairingCodeKey(pairingCode, salt) {
|
|
|
155
128
|
return Buffer.from(derivedBits)
|
|
156
129
|
}
|
|
157
130
|
|
|
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
131
|
export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering()
|
|
168
132
|
|
|
169
|
-
/* ------------------------------------------------------------------ */
|
|
170
|
-
/* Generic helpers */
|
|
171
|
-
/* ------------------------------------------------------------------ */
|
|
172
|
-
|
|
173
133
|
export const BufferJSON = {
|
|
174
134
|
replacer: (k, value) => {
|
|
175
135
|
if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
|
|
@@ -195,7 +155,6 @@ export const BufferJSON = {
|
|
|
195
155
|
export const getKeyAuthor = (key, meId = 'me') =>
|
|
196
156
|
(key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || ''
|
|
197
157
|
|
|
198
|
-
// eslint-disable-next-line eqeqeq
|
|
199
158
|
export const isStringNullOrEmpty = value => value == null || value === ''
|
|
200
159
|
|
|
201
160
|
export const writeRandomPadMax16 = msg => {
|
|
@@ -212,7 +171,6 @@ export const unpadRandomMax16 = e => {
|
|
|
212
171
|
return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
|
|
213
172
|
}
|
|
214
173
|
|
|
215
|
-
// code is inspired by whatsmeow
|
|
216
174
|
export const generateParticipantHashV2 = participants => {
|
|
217
175
|
participants.sort()
|
|
218
176
|
const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64')
|
|
@@ -235,7 +193,6 @@ export const encodeBigEndian = (e, t = 4) => {
|
|
|
235
193
|
|
|
236
194
|
export const toNumber = t => (typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0)
|
|
237
195
|
|
|
238
|
-
/** unix timestamp of a date in seconds */
|
|
239
196
|
export const unixTimestampSeconds = (date = new Date()) => (date.getTime() / 1000) | 0
|
|
240
197
|
|
|
241
198
|
export const debouncedTimeout = (intervalMs = 1000, task) => {
|
|
@@ -284,7 +241,6 @@ export async function promiseTimeout(ms, promiseExecutor) {
|
|
|
284
241
|
return p
|
|
285
242
|
}
|
|
286
243
|
|
|
287
|
-
// inspired from whatsmeow's send.go
|
|
288
244
|
export const generateMessageIDV2 = userId => {
|
|
289
245
|
const data = Buffer.alloc(8 + 20 + 16)
|
|
290
246
|
data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
|
|
@@ -329,14 +285,13 @@ export const bindWaitForConnectionUpdate = ev => bindWaitForEvent(ev, 'connectio
|
|
|
329
285
|
|
|
330
286
|
const baileysVersion = [2, 3000, 1047970367]
|
|
331
287
|
|
|
332
|
-
/** utility that fetches latest baileys version from the master branch. */
|
|
333
288
|
export const fetchLatestBaileysVersion = async (options = {}) => {
|
|
334
289
|
const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts'
|
|
335
290
|
try {
|
|
336
291
|
const response = await fetch(URL, { dispatcher: options.dispatcher, method: 'GET', headers: options.headers })
|
|
337
292
|
if (!response.ok) throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status })
|
|
338
293
|
const text = await response.text()
|
|
339
|
-
|
|
294
|
+
|
|
340
295
|
const versionMatch = text.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/)
|
|
341
296
|
if (versionMatch) {
|
|
342
297
|
const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])]
|
|
@@ -348,7 +303,6 @@ export const fetchLatestBaileysVersion = async (options = {}) => {
|
|
|
348
303
|
}
|
|
349
304
|
}
|
|
350
305
|
|
|
351
|
-
/** fetches the latest web version of whatsapp. */
|
|
352
306
|
export const fetchLatestWaWebVersion = async (options = {}) => {
|
|
353
307
|
try {
|
|
354
308
|
const defaultHeaders = {
|
|
@@ -370,7 +324,6 @@ export const fetchLatestWaWebVersion = async (options = {}) => {
|
|
|
370
324
|
}
|
|
371
325
|
}
|
|
372
326
|
|
|
373
|
-
/** unique message tag prefix for MD clients */
|
|
374
327
|
export const generateMdTagPrefix = () => {
|
|
375
328
|
const bytes = randomBytes(4)
|
|
376
329
|
return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
|
|
@@ -383,21 +336,29 @@ const STATUS_MAP = {
|
|
|
383
336
|
'read-self': proto.WebMessageInfo.Status.READ
|
|
384
337
|
}
|
|
385
338
|
|
|
386
|
-
/** Given a type of receipt, returns what the new status of the message should be */
|
|
387
339
|
export const getStatusFromReceiptType = type => {
|
|
388
340
|
const status = STATUS_MAP[type]
|
|
389
341
|
if (typeof type === 'undefined') return proto.WebMessageInfo.Status.DELIVERY_ACK
|
|
390
342
|
return status
|
|
391
343
|
}
|
|
392
344
|
|
|
393
|
-
const CODE_MAP = { conflict:
|
|
345
|
+
const CODE_MAP = { conflict: DisconnectReason.connectionReplaced }
|
|
394
346
|
|
|
395
|
-
/** Stream errors generally provide a reason, map that to a baileys DisconnectReason */
|
|
396
347
|
export const getErrorCodeFromStreamError = node => {
|
|
397
348
|
const [reasonNode] = getAllBinaryNodeChildren(node)
|
|
398
349
|
let reason = reasonNode?.tag || 'unknown'
|
|
399
|
-
|
|
400
|
-
|
|
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'
|
|
401
362
|
return { reason, statusCode }
|
|
402
363
|
}
|
|
403
364
|
|
|
@@ -407,7 +368,7 @@ export const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
|
407
368
|
case 'offer_notice':
|
|
408
369
|
return 'offer'
|
|
409
370
|
case 'terminate':
|
|
410
|
-
return attrs.reason === 'timeout' ? 'timeout' : 'terminate'
|
|
371
|
+
return attrs.reason === 'timeout' ? 'timeout' : 'terminate'
|
|
411
372
|
case 'preaccept':
|
|
412
373
|
return 'preaccept'
|
|
413
374
|
case 'transport':
|
|
@@ -425,17 +386,19 @@ export const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
|
425
386
|
|
|
426
387
|
const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
|
|
427
388
|
export const getCodeFromWSError = error => {
|
|
428
|
-
|
|
389
|
+
|
|
390
|
+
const code = error?.code || error?.cause?.code
|
|
429
391
|
if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
|
|
430
|
-
const
|
|
431
|
-
if (!Number.isNaN(
|
|
432
|
-
}
|
|
433
|
-
|
|
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
|
|
434
397
|
}
|
|
435
|
-
|
|
398
|
+
|
|
399
|
+
return 408
|
|
436
400
|
}
|
|
437
401
|
|
|
438
|
-
/** Is the given platform WA business */
|
|
439
402
|
export const isWABusinessPlatform = platform => platform === 'smbi' || platform === 'smba'
|
|
440
403
|
|
|
441
404
|
export function trimUndefined(obj) {
|
|
@@ -466,10 +429,6 @@ export function encodeNewsletterMessage(message) {
|
|
|
466
429
|
return proto.Message.encode(message).finish()
|
|
467
430
|
}
|
|
468
431
|
|
|
469
|
-
/* ------------------------------------------------------------------ */
|
|
470
|
-
/* Browser / companion-registration helpers */
|
|
471
|
-
/* ------------------------------------------------------------------ */
|
|
472
|
-
|
|
473
432
|
const PLATFORM_MAP = {
|
|
474
433
|
aix: 'AIX',
|
|
475
434
|
darwin: 'Mac OS',
|
|
@@ -495,7 +454,7 @@ export const Browsers = {
|
|
|
495
454
|
|
|
496
455
|
export const getPlatformId = browser => {
|
|
497
456
|
const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()]
|
|
498
|
-
return platformType ? platformType.toString() : '1'
|
|
457
|
+
return platformType ? platformType.toString() : '1'
|
|
499
458
|
}
|
|
500
459
|
|
|
501
460
|
export const CompanionWebClientType = {
|
|
@@ -530,29 +489,17 @@ export const getCompanionPlatformId = browser => getCompanionWebClientType(brows
|
|
|
530
489
|
export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) =>
|
|
531
490
|
'https://wa.me/settings/linked_devices#' + [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(',')
|
|
532
491
|
|
|
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
492
|
export function buildAckStanza(node, errorCode, meId) {
|
|
542
493
|
const { tag, attrs } = node
|
|
543
494
|
const stanza = { tag: 'ack', attrs: { id: attrs.id, to: attrs.from, class: tag } }
|
|
544
495
|
if (errorCode) stanza.attrs.error = errorCode.toString()
|
|
545
496
|
if (attrs.participant) stanza.attrs.participant = attrs.participant
|
|
546
497
|
if (attrs.recipient) stanza.attrs.recipient = attrs.recipient
|
|
547
|
-
if (attrs.type) stanza.attrs.type = attrs.type
|
|
548
|
-
if (tag === 'message' && meId) stanza.attrs.from = meId
|
|
498
|
+
if (attrs.type) stanza.attrs.type = attrs.type
|
|
499
|
+
if (tag === 'message' && meId) stanza.attrs.from = meId
|
|
549
500
|
return stanza
|
|
550
501
|
}
|
|
551
502
|
|
|
552
|
-
/* ------------------------------------------------------------------ */
|
|
553
|
-
/* Signal / prekey helpers */
|
|
554
|
-
/* ------------------------------------------------------------------ */
|
|
555
|
-
|
|
556
503
|
function chunkArray(array, size) {
|
|
557
504
|
const chunks = []
|
|
558
505
|
for (let i = 0; i < array.length; i += size) chunks.push(array.slice(i, i + size))
|
|
@@ -645,7 +592,6 @@ export const parseAndInjectE2ESessions = async (node, repository) => {
|
|
|
645
592
|
const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user')
|
|
646
593
|
for (const n of nodes) assertNodeErrorFree(n)
|
|
647
594
|
|
|
648
|
-
// Chunked to yield to the event loop between batches (injectE2ESession is CPU-heavy, not IO).
|
|
649
595
|
const chunkSize = 100
|
|
650
596
|
const chunks = chunkArray(nodes, chunkSize)
|
|
651
597
|
for (const nodesChunk of chunks) {
|
|
@@ -692,7 +638,6 @@ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
|
|
|
692
638
|
return extracted
|
|
693
639
|
}
|
|
694
640
|
|
|
695
|
-
/** get the next N keys for upload or processing */
|
|
696
641
|
export const getNextPreKeys = async ({ creds, keys }, count) => {
|
|
697
642
|
const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count)
|
|
698
643
|
const update = {
|
|
@@ -721,10 +666,6 @@ export const getNextPreKeysNode = async (state, count) => {
|
|
|
721
666
|
return { update, node }
|
|
722
667
|
}
|
|
723
668
|
|
|
724
|
-
/* ------------------------------------------------------------------ */
|
|
725
|
-
/* Noise protocol handshake handler */
|
|
726
|
-
/* ------------------------------------------------------------------ */
|
|
727
|
-
|
|
728
669
|
const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0'
|
|
729
670
|
const WA_CERT_DETAILS = {
|
|
730
671
|
SERIAL: 0,
|
|
@@ -767,9 +708,7 @@ class TransportState {
|
|
|
767
708
|
}
|
|
768
709
|
|
|
769
710
|
export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
|
|
770
|
-
|
|
771
|
-
// it explicitly (e.g. a stale reference during reconnect) — don't crash,
|
|
772
|
-
// fall back to a fresh silent-by-default logger instead.
|
|
711
|
+
|
|
773
712
|
logger = (logger || createLogger()).child({ class: 'ns' })
|
|
774
713
|
const data = Buffer.from(NOISE_MODE)
|
|
775
714
|
let hash = data.byteLength === 32 ? data : sha256(data)
|
|
@@ -784,9 +723,8 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
|
|
|
784
723
|
let pendingOnFrame = null
|
|
785
724
|
let introHeader
|
|
786
725
|
let destroyed = false
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
// process. Cap it and drop the buffered bytes rather than let it balloon.
|
|
726
|
+
let decodeChain = Promise.resolve()
|
|
727
|
+
|
|
790
728
|
const MAX_IN_BYTES = 10 * 1024 * 1024
|
|
791
729
|
|
|
792
730
|
if (routingInfo) {
|
|
@@ -842,18 +780,29 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
|
|
|
842
780
|
}
|
|
843
781
|
const processData = async onFrame => {
|
|
844
782
|
let size
|
|
845
|
-
while (
|
|
783
|
+
while (!destroyed) {
|
|
846
784
|
if (inBytes.length < 3) return
|
|
847
785
|
size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2]
|
|
848
786
|
if (inBytes.length < size + 3) return
|
|
849
787
|
let frame = inBytes.subarray(3, size + 3)
|
|
850
788
|
inBytes = inBytes.subarray(size + 3)
|
|
851
789
|
if (transport) {
|
|
852
|
-
const result = transport.decrypt(frame)
|
|
853
|
-
|
|
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
|
|
854
798
|
}
|
|
855
799
|
if (logger.level === 'trace') logger.trace({ msg: frame?.attrs?.id }, 'recv frame')
|
|
856
|
-
|
|
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
|
+
}
|
|
857
806
|
}
|
|
858
807
|
}
|
|
859
808
|
|
|
@@ -907,27 +856,30 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
|
|
|
907
856
|
frame.set(data, introSize + 3)
|
|
908
857
|
return frame
|
|
909
858
|
},
|
|
910
|
-
decodeFrame:
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
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)
|
|
923
875
|
}
|
|
924
|
-
|
|
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
|
|
925
881
|
},
|
|
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
|
-
*/
|
|
882
|
+
|
|
931
883
|
destroy: () => {
|
|
932
884
|
destroyed = true
|
|
933
885
|
inBytes = Buffer.alloc(0)
|
|
@@ -937,10 +889,6 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
|
|
|
937
889
|
}
|
|
938
890
|
}
|
|
939
891
|
|
|
940
|
-
/* ------------------------------------------------------------------ */
|
|
941
|
-
/* Connection validation (login / registration / pairing) */
|
|
942
|
-
/* ------------------------------------------------------------------ */
|
|
943
|
-
|
|
944
892
|
const WA_ADV_ACCOUNT_SIG_PREFIX = Buffer.from([6, 0])
|
|
945
893
|
const WA_ADV_DEVICE_SIG_PREFIX = Buffer.from([6, 1])
|
|
946
894
|
const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5])
|
|
@@ -1100,10 +1048,6 @@ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
|
|
|
1100
1048
|
return proto.ADVSignedDeviceIdentity.encode(account).finish()
|
|
1101
1049
|
}
|
|
1102
1050
|
|
|
1103
|
-
/* ------------------------------------------------------------------ */
|
|
1104
|
-
/* Message reporting token */
|
|
1105
|
-
/* ------------------------------------------------------------------ */
|
|
1106
|
-
|
|
1107
1051
|
const reportingFields = [
|
|
1108
1052
|
{ f: 1 },
|
|
1109
1053
|
{ f: 3, s: [{ f: 2 }, { f: 3 }, { f: 8 }, { f: 11 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 25 }] },
|