@itznomo/baileys 0.0.0-stage → 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.
- package/BUTTONS.md +153 -0
- package/Example/call-bot.mjs +38 -0
- package/Example/example.mjs +36 -0
- package/Example/full-bot-commands.mjs +319 -0
- package/Example/full-bot.mjs +77 -0
- package/LICENSE +21 -0
- package/README.md +543 -2
- package/WAProto/@dnuzi +1 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +113300 -0
- package/assets/banner.svg +17 -0
- package/assets/devider.svg +1 -0
- package/assets/features.svg +21 -0
- package/docs/CALLS.md +106 -0
- package/docs/FEATURES.md +1152 -0
- package/engine-requirements.js +19 -0
- package/index.d.ts +815 -0
- package/package.json +51 -4
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +627 -0
- package/src/constants.js +147 -0
- package/src/defaults.js +106 -0
- package/src/foundation/ai-rich.js +654 -0
- package/src/foundation/audio-duration.js +470 -0
- package/src/foundation/audio-samples.js +250 -0
- package/src/foundation/boom.js +39 -0
- package/src/foundation/builders.js +851 -0
- package/src/foundation/cache.js +134 -0
- package/src/foundation/concurrency.js +69 -0
- package/src/foundation/curve25519.js +189 -0
- package/src/foundation/image-thumb.js +65 -0
- package/src/foundation/link-preview.js +278 -0
- package/src/foundation/logger.js +78 -0
- package/src/foundation/long.js +130 -0
- package/src/foundation/performance.js +385 -0
- package/src/foundation/protobuf-minimal.js +587 -0
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +47 -0
- package/src/foundation/zip.js +108 -0
- package/src/index.js +67 -0
- package/src/signal/libsignal.js +996 -0
- package/src/signal/signal-group.js +455 -0
- package/src/signal/signal-repository.js +635 -0
- package/src/socket/business-communities.js +811 -0
- package/src/socket/chats.js +702 -0
- package/src/socket/groups-newsletter.js +524 -0
- package/src/socket/messages-recv.js +1815 -0
- package/src/socket/messages-send.js +1526 -0
- package/src/socket/socket-builder.js +131 -0
- package/src/socket/socket-core.js +913 -0
- package/src/socket/usync.js +287 -0
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +170 -0
- package/src/utils/auth-state-core.js +731 -0
- package/src/utils/auth-state-storage.js +594 -0
- package/src/utils/chat-sync.js +1046 -0
- package/src/utils/check-status.js +159 -0
- package/src/utils/cstoken.js +17 -0
- package/src/utils/media.js +807 -0
- package/src/utils/message-compose.js +1747 -0
- package/src/utils/message-processing.js +912 -0
- package/src/utils/modern-messages.js +435 -0
- package/src/utils/nomo-buttons.js +138 -0
- package/src/utils/nomo-commands.js +168 -0
- package/src/utils/spam-report-utils.js +136 -0
- package/src/utils/use-keyv-auth-state.js +307 -0
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +1227 -0
- 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/auto.js +139 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1727 -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 +730 -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 +22852 -0
- package/src/wam/wam.js +146 -0
- package/voip.d.ts +144 -0
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { URL } from 'node:url'
|
|
3
|
+
import { promisify } from 'node:util'
|
|
4
|
+
import { proto } from '../../WAProto/index.js'
|
|
5
|
+
import { Boom } from '../foundation/boom.js'
|
|
6
|
+
import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../defaults.js'
|
|
7
|
+
import { QueryIds, ReachoutTimelockEnforcementType, DisconnectReason, XWAPaths } from '../constants.js'
|
|
8
|
+
import {
|
|
9
|
+
aesEncryptCTR,
|
|
10
|
+
bindWaitForConnectionUpdate,
|
|
11
|
+
buildPairingQRData,
|
|
12
|
+
bytesToCrockford,
|
|
13
|
+
configureSuccessfulPairing,
|
|
14
|
+
Curve,
|
|
15
|
+
derivePairingCodeKey,
|
|
16
|
+
generateLoginNode,
|
|
17
|
+
generateMdTagPrefix,
|
|
18
|
+
generateRegistrationNode,
|
|
19
|
+
getCodeFromWSError,
|
|
20
|
+
getCompanionPlatformId,
|
|
21
|
+
getErrorCodeFromStreamError,
|
|
22
|
+
getNextPreKeysNode,
|
|
23
|
+
makeNoiseHandler,
|
|
24
|
+
promiseTimeout,
|
|
25
|
+
signedKeyPair,
|
|
26
|
+
xmppSignedPreKey
|
|
27
|
+
} from '../utils/wa-protocol-core.js'
|
|
28
|
+
import { addTransactionCapability } from '../utils/auth-state-core.js'
|
|
29
|
+
import { makeEventBuffer } from '../utils/chat-sync.js'
|
|
30
|
+
import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../binary/wa-binary.js'
|
|
31
|
+
import { BinaryInfo } from '../wam/wam.js'
|
|
32
|
+
import { USyncQuery, USyncUser } from './usync.js'
|
|
33
|
+
import { normalizeUsername, isValidUsername, isValidUsernameKey } from '../utils/username.js'
|
|
34
|
+
import { WebSocketClient } from '../socket-client/websocket-client.js'
|
|
35
|
+
import { generateQR } from '../foundation/qrcode-terminal.js'
|
|
36
|
+
|
|
37
|
+
const wMexQuery = (variables, queryId, query, generateMessageTag) =>
|
|
38
|
+
query({
|
|
39
|
+
tag: 'iq',
|
|
40
|
+
attrs: { id: generateMessageTag(), type: 'get', to: S_WHATSAPP_NET, xmlns: 'w:mex' },
|
|
41
|
+
content: [{ tag: 'query', attrs: { query_id: queryId }, content: Buffer.from(JSON.stringify({ variables }), 'utf-8') }]
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
|
|
45
|
+
const result = await wMexQuery(variables, queryId, query, generateMessageTag)
|
|
46
|
+
const child = getBinaryNodeChild(result, 'result')
|
|
47
|
+
if (child?.content) {
|
|
48
|
+
const data = JSON.parse(child.content.toString())
|
|
49
|
+
if (data.errors && data.errors.length > 0) {
|
|
50
|
+
const errorMessages = data.errors.map(err => err.message || 'Unknown error').join(', ')
|
|
51
|
+
const firstError = data.errors[0]
|
|
52
|
+
const errorCode = firstError.extensions?.error_code || 400
|
|
53
|
+
throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError })
|
|
54
|
+
}
|
|
55
|
+
const response = dataPath ? data?.data?.[dataPath] : data?.data
|
|
56
|
+
if (typeof response !== 'undefined') return response
|
|
57
|
+
}
|
|
58
|
+
const action = (dataPath || '').startsWith('xwa2_') ? dataPath.substring(5).replace(/_/g, ' ') : dataPath?.replace(/_/g, ' ')
|
|
59
|
+
throw new Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result })
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// requestPairingCode() menaruh me = { id, name: '~' } sebagai penanda sementara; pair-success menggantinya dengan identitas asli
|
|
63
|
+
// sekaligus mengisi creds.account. Selama account belum ada, me itu hanyalah sisa pairing yang belum selesai.
|
|
64
|
+
const isUnfinishedPairing = creds => creds?.me?.name === '~' && !creds.account
|
|
65
|
+
|
|
66
|
+
export const makeSocket = config => {
|
|
67
|
+
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config
|
|
68
|
+
const publicWAMBuffer = new BinaryInfo()
|
|
69
|
+
let serverTimeOffsetMs = 0
|
|
70
|
+
const uqTagId = generateMdTagPrefix()
|
|
71
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`
|
|
72
|
+
|
|
73
|
+
if (browser[1].toLocaleLowerCase().includes('android')) {
|
|
74
|
+
logger.warn('⚠️ Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk.')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const syncDisabled = PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false).length === PROCESSABLE_HISTORY_TYPES.length
|
|
78
|
+
if (syncDisabled) {
|
|
79
|
+
logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const url = new URL(typeof waWebSocketUrl === 'string' ? waWebSocketUrl : waWebSocketUrl.href) // salinan: jangan mutasi URL milik pemanggil
|
|
83
|
+
if (config.mobile || url.protocol === 'tcp:') throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut })
|
|
84
|
+
const routingInfo = authState?.creds?.routingInfo
|
|
85
|
+
let wsConfig = config
|
|
86
|
+
if (routingInfo?.length && !config.disableStickyRouting && (url.protocol === 'wss:' || url.protocol === 'ws:')) {
|
|
87
|
+
if (!url.searchParams.has('ED')) url.searchParams.set('ED', Buffer.from(routingInfo).toString('base64url'))
|
|
88
|
+
const headers = { ...(config.options?.headers || {}) }
|
|
89
|
+
const cookieKey = Object.keys(headers).find(k => k.toLowerCase() === 'cookie')
|
|
90
|
+
const cookie = cookieKey ? headers[cookieKey] : ''
|
|
91
|
+
if (cookieKey) delete headers[cookieKey]
|
|
92
|
+
headers.Cookie = cookie.includes('sticky_routing=') ? cookie : cookie ? `${cookie}; sticky_routing=` : 'sticky_routing='
|
|
93
|
+
wsConfig = { ...config, options: { ...(config.options || {}), headers } }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const ephemeralKeyPair = Curve.generateKeyPair()
|
|
97
|
+
|
|
98
|
+
const noise = makeNoiseHandler({ keyPair: ephemeralKeyPair, NOISE_HEADER: NOISE_WA_HEADER, logger, routingInfo: authState?.creds?.routingInfo })
|
|
99
|
+
|
|
100
|
+
const ws = new WebSocketClient(url, wsConfig)
|
|
101
|
+
ws.connect()
|
|
102
|
+
const sendPromise = promisify(ws.send)
|
|
103
|
+
|
|
104
|
+
const sendRawMessage = async data => {
|
|
105
|
+
if (!ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
106
|
+
const bytes = noise.encodeFrame(data)
|
|
107
|
+
await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
|
|
108
|
+
try {
|
|
109
|
+
await sendPromise.call(ws, bytes)
|
|
110
|
+
resolve()
|
|
111
|
+
} catch (error) {
|
|
112
|
+
reject(error)
|
|
113
|
+
}
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const sendNode = frame => {
|
|
118
|
+
if (logger.level === 'trace') logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
|
|
119
|
+
const buff = encodeBinaryNode(frame)
|
|
120
|
+
return sendRawMessage(buff)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
|
|
124
|
+
let onRecv
|
|
125
|
+
let onErr
|
|
126
|
+
try {
|
|
127
|
+
return await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
128
|
+
onRecv = data => resolve(data)
|
|
129
|
+
onErr = err => reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
|
|
130
|
+
ws.on(`TAG:${msgId}`, onRecv)
|
|
131
|
+
ws.on('close', onErr)
|
|
132
|
+
ws.on('error', onErr)
|
|
133
|
+
return () => reject(new Boom('Query Cancelled'))
|
|
134
|
+
})
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
|
|
137
|
+
logger?.warn?.({ msgId }, 'timed out waiting for message')
|
|
138
|
+
return undefined
|
|
139
|
+
}
|
|
140
|
+
throw error
|
|
141
|
+
} finally {
|
|
142
|
+
if (onRecv) ws.off(`TAG:${msgId}`, onRecv)
|
|
143
|
+
if (onErr) {
|
|
144
|
+
ws.off('close', onErr)
|
|
145
|
+
ws.off('error', onErr)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const query = async (node, timeoutMs) => {
|
|
151
|
+
if (!node.attrs.id) node.attrs.id = generateMessageTag()
|
|
152
|
+
const msgId = node.attrs.id
|
|
153
|
+
const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
|
|
154
|
+
const result_ = waitForMessage(msgId, timeoutMs).catch(reject)
|
|
155
|
+
sendNode(node)
|
|
156
|
+
.then(async () => resolve(await result_))
|
|
157
|
+
.catch(reject)
|
|
158
|
+
})
|
|
159
|
+
if (result && 'tag' in result) assertNodeErrorFree(result)
|
|
160
|
+
return result
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const digestKeyBundle = async () => {
|
|
164
|
+
const res = await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' }, content: [{ tag: 'digest', attrs: {} }] })
|
|
165
|
+
const digestNode = getBinaryNodeChild(res, 'digest')
|
|
166
|
+
if (!digestNode) {
|
|
167
|
+
await uploadPreKeys()
|
|
168
|
+
throw new Error('encrypt/get digest returned no digest node')
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const rotateSignedPreKey = async () => {
|
|
173
|
+
const newId = (creds.signedPreKey.keyId || 0) + 1
|
|
174
|
+
const skey = await signedKeyPair(creds.signedIdentityKey, newId)
|
|
175
|
+
await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' }, content: [{ tag: 'rotate', attrs: {}, content: [xmppSignedPreKey(skey)] }] })
|
|
176
|
+
ev.emit('creds.update', { signedPreKey: skey })
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const executeUSyncQuery = async usyncQuery => {
|
|
180
|
+
if (usyncQuery.protocols.length === 0) throw new Boom('USyncQuery must have at least one protocol')
|
|
181
|
+
|
|
182
|
+
const validUsers = usyncQuery.users
|
|
183
|
+
const userNodes = validUsers.map(user => ({
|
|
184
|
+
tag: 'user',
|
|
185
|
+
attrs: { jid: !user.phone ? user.id : undefined },
|
|
186
|
+
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
|
187
|
+
}))
|
|
188
|
+
const listNode = { tag: 'list', attrs: {}, content: userNodes }
|
|
189
|
+
const queryNode = { tag: 'query', attrs: {}, content: usyncQuery.protocols.map(a => a.getQueryElement()) }
|
|
190
|
+
const iq = {
|
|
191
|
+
tag: 'iq',
|
|
192
|
+
attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'usync' },
|
|
193
|
+
content: [{ tag: 'usync', attrs: { context: usyncQuery.context, mode: usyncQuery.mode, sid: generateMessageTag(), last: 'true', index: '0' }, content: [queryNode, listNode] }]
|
|
194
|
+
}
|
|
195
|
+
const result = await query(iq)
|
|
196
|
+
return usyncQuery.parseUSyncQueryResult(result)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const onWhatsApp = async (...phoneNumber) => {
|
|
200
|
+
let usyncQuery = new USyncQuery()
|
|
201
|
+
let contactEnabled = false
|
|
202
|
+
for (const jid of phoneNumber) {
|
|
203
|
+
if (isLidUser(jid)) {
|
|
204
|
+
logger?.warn('LIDs are not supported with onWhatsApp')
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
207
|
+
if (!contactEnabled) {
|
|
208
|
+
contactEnabled = true
|
|
209
|
+
usyncQuery = usyncQuery.withContactProtocol()
|
|
210
|
+
}
|
|
211
|
+
const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`
|
|
212
|
+
usyncQuery.withUser(new USyncUser().withPhone(phone))
|
|
213
|
+
}
|
|
214
|
+
if (usyncQuery.users.length === 0) return []
|
|
215
|
+
const results = await executeUSyncQuery(usyncQuery)
|
|
216
|
+
if (results) return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }))
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const pnFromLIDUSync = async jids => {
|
|
220
|
+
const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background')
|
|
221
|
+
for (const jid of jids) {
|
|
222
|
+
if (isLidUser(jid)) {
|
|
223
|
+
logger?.warn('LID user found in LID fetch call')
|
|
224
|
+
continue
|
|
225
|
+
}
|
|
226
|
+
usyncQuery.withUser(new USyncUser().withId(jid))
|
|
227
|
+
}
|
|
228
|
+
if (usyncQuery.users.length === 0) return []
|
|
229
|
+
const results = await executeUSyncQuery(usyncQuery)
|
|
230
|
+
return results ? results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid })) : []
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const resolveUsername = async (handle, usernameKey) => {
|
|
234
|
+
const username = normalizeUsername(handle)
|
|
235
|
+
if (!isValidUsername(username)) throw new Boom('Invalid username', { statusCode: 400 })
|
|
236
|
+
if (usernameKey !== undefined && !isValidUsernameKey(usernameKey)) {
|
|
237
|
+
throw new Boom('Invalid username key: expected a 4-digit string', { statusCode: 400 })
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const usyncUser = new USyncUser().withUsername(username)
|
|
241
|
+
if (usernameKey) usyncUser.withUsernameKey(usernameKey)
|
|
242
|
+
|
|
243
|
+
const usyncQuery = new USyncQuery().withContactProtocol().withUser(usyncUser)
|
|
244
|
+
const userNode = {
|
|
245
|
+
tag: 'user',
|
|
246
|
+
attrs: {},
|
|
247
|
+
content: [usyncQuery.protocols[0].getUserElement(usyncUser)].filter(a => a !== null)
|
|
248
|
+
}
|
|
249
|
+
const iq = {
|
|
250
|
+
tag: 'iq',
|
|
251
|
+
attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'usync' },
|
|
252
|
+
content: [
|
|
253
|
+
{
|
|
254
|
+
tag: 'usync',
|
|
255
|
+
attrs: { context: usyncQuery.context, mode: usyncQuery.mode, sid: generateMessageTag(), last: 'true', index: '0' },
|
|
256
|
+
content: [
|
|
257
|
+
{ tag: 'query', attrs: {}, content: [{ tag: 'contact', attrs: {} }] },
|
|
258
|
+
{ tag: 'list', attrs: {}, content: [userNode] }
|
|
259
|
+
]
|
|
260
|
+
}
|
|
261
|
+
]
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const result = await query(iq)
|
|
265
|
+
const usyncNode = getBinaryNodeChild(result, 'usync')
|
|
266
|
+
const listNode = usyncNode ? getBinaryNodeChild(usyncNode, 'list') : undefined
|
|
267
|
+
const resultUserNode = listNode ? getBinaryNodeChild(listNode, 'user') : undefined
|
|
268
|
+
if (!resultUserNode) return { status: 'not-found' }
|
|
269
|
+
|
|
270
|
+
const contactNode = getBinaryNodeChild(resultUserNode, 'contact')
|
|
271
|
+
if (!contactNode) return { status: 'not-found' }
|
|
272
|
+
|
|
273
|
+
const errorNode = getBinaryNodeChild(contactNode, 'error')
|
|
274
|
+
if (errorNode) {
|
|
275
|
+
|
|
276
|
+
return { status: 'key-required' }
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (contactNode.attrs?.type !== 'in') return { status: 'not-found' }
|
|
280
|
+
|
|
281
|
+
const jid = resultUserNode.attrs?.jid
|
|
282
|
+
if (!jid) return { status: 'key-required' }
|
|
283
|
+
|
|
284
|
+
return { status: 'ok', jid: jidNormalizedUser(jid) }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const ev = makeEventBuffer(logger)
|
|
288
|
+
const { creds } = authState
|
|
289
|
+
|
|
290
|
+
// Sisa pairing yang tidak pernah selesai bukan sesi login: requestPairingCode() mengisi creds.me sementara (name '~')
|
|
291
|
+
// dan itu ikut tersimpan. Kalau dibiarkan, validateConnection() mengirim LOGIN untuk nomor yang belum terdaftar,
|
|
292
|
+
// server membalas 401 (loggedOut) dan sesi macet selamanya tanpa pernah meminta pairing lagi.
|
|
293
|
+
if (isUnfinishedPairing(creds)) {
|
|
294
|
+
logger.info({ me: creds.me?.id }, 'discarding unfinished pairing state from a previous attempt')
|
|
295
|
+
creds.me = undefined
|
|
296
|
+
creds.registered = false
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const keys = addTransactionCapability(authState.keys, logger, transactionOpts)
|
|
300
|
+
const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync)
|
|
301
|
+
let lastDateRecv
|
|
302
|
+
let epoch = 1
|
|
303
|
+
let keepAliveReq
|
|
304
|
+
let qrTimer
|
|
305
|
+
let closed = false
|
|
306
|
+
const socketEndHandlers = []
|
|
307
|
+
|
|
308
|
+
const onUnexpectedError = (err, msg) => {
|
|
309
|
+
logger.error({ err }, `unexpected error in '${msg}'`)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const awaitNextMessage = async sendMsg => {
|
|
313
|
+
if (!ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
314
|
+
let onOpen
|
|
315
|
+
let onClose
|
|
316
|
+
const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
|
|
317
|
+
onOpen = resolve
|
|
318
|
+
onClose = mapWebSocketError(reject)
|
|
319
|
+
ws.on('frame', onOpen)
|
|
320
|
+
ws.on('close', onClose)
|
|
321
|
+
ws.on('error', onClose)
|
|
322
|
+
}).finally(() => {
|
|
323
|
+
ws.off('frame', onOpen)
|
|
324
|
+
ws.off('close', onClose)
|
|
325
|
+
ws.off('error', onClose)
|
|
326
|
+
})
|
|
327
|
+
if (sendMsg) sendRawMessage(sendMsg).catch(onClose)
|
|
328
|
+
return result
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const validateConnection = async () => {
|
|
332
|
+
let helloMsg = { clientHello: { ephemeral: ephemeralKeyPair.public } }
|
|
333
|
+
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
|
|
334
|
+
logger.info({ browser, helloMsg }, 'connected to WA')
|
|
335
|
+
const init = proto.HandshakeMessage.encode(helloMsg).finish()
|
|
336
|
+
const result = await awaitNextMessage(init)
|
|
337
|
+
const handshake = proto.HandshakeMessage.decode(result)
|
|
338
|
+
logger.trace({ handshake }, 'handshake recv from WA')
|
|
339
|
+
const keyEnc = noise.processHandshake(handshake, creds.noiseKey)
|
|
340
|
+
let node
|
|
341
|
+
if (!creds.me) {
|
|
342
|
+
node = generateRegistrationNode(creds, config)
|
|
343
|
+
logger.info({ node }, 'not logged in, attempting registration...')
|
|
344
|
+
} else {
|
|
345
|
+
node = generateLoginNode(creds.me.id, config)
|
|
346
|
+
logger.info({ node }, 'logging in...')
|
|
347
|
+
}
|
|
348
|
+
const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish())
|
|
349
|
+
await sendRawMessage(proto.HandshakeMessage.encode({ clientFinish: { static: keyEnc, payload: payloadEnc } }).finish())
|
|
350
|
+
await noise.finishInit()
|
|
351
|
+
startKeepAliveRequest()
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const getAvailablePreKeysOnServer = async () => {
|
|
355
|
+
const result = await query({ tag: 'iq', attrs: { id: generateMessageTag(), xmlns: 'encrypt', type: 'get', to: S_WHATSAPP_NET }, content: [{ tag: 'count', attrs: {} }] })
|
|
356
|
+
const countChild = getBinaryNodeChild(result, 'count')
|
|
357
|
+
return +countChild.attrs.value
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
let uploadPreKeysPromise = null
|
|
361
|
+
|
|
362
|
+
const uploadPreKeys = async (count = MIN_PREKEY_COUNT) => {
|
|
363
|
+
if (uploadPreKeysPromise) {
|
|
364
|
+
logger.debug('Pre-key upload already in progress, waiting for completion')
|
|
365
|
+
await uploadPreKeysPromise
|
|
366
|
+
return
|
|
367
|
+
}
|
|
368
|
+
const uploadLogic = async retryCount => {
|
|
369
|
+
logger.info({ count, retryCount }, 'uploading pre-keys')
|
|
370
|
+
|
|
371
|
+
const node = await keys.transaction(async () => {
|
|
372
|
+
logger.debug({ requestedCount: count }, 'generating pre-keys with requested count')
|
|
373
|
+
const { update, node: node_ } = await getNextPreKeysNode({ creds, keys }, count)
|
|
374
|
+
ev.emit('creds.update', update)
|
|
375
|
+
return node_
|
|
376
|
+
}, creds?.me?.id || 'upload-pre-keys')
|
|
377
|
+
try {
|
|
378
|
+
await query(node)
|
|
379
|
+
logger.info({ count }, 'uploaded pre-keys successfully')
|
|
380
|
+
} catch (uploadError) {
|
|
381
|
+
logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server')
|
|
382
|
+
if (retryCount < 3) {
|
|
383
|
+
const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000)
|
|
384
|
+
logger.info(`Retrying pre-key upload in ${backoffDelay}ms`)
|
|
385
|
+
await new Promise(resolve => setTimeout(resolve, backoffDelay))
|
|
386
|
+
return uploadLogic(retryCount + 1)
|
|
387
|
+
}
|
|
388
|
+
throw uploadError
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
uploadPreKeysPromise = Promise.race([
|
|
392
|
+
uploadLogic(0),
|
|
393
|
+
new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
|
|
394
|
+
])
|
|
395
|
+
try {
|
|
396
|
+
await uploadPreKeysPromise
|
|
397
|
+
} finally {
|
|
398
|
+
uploadPreKeysPromise = null
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const verifyCurrentPreKeyExists = async () => {
|
|
403
|
+
const currentPreKeyId = creds.nextPreKeyId - 1
|
|
404
|
+
if (currentPreKeyId <= 0) return { exists: false, currentPreKeyId: 0 }
|
|
405
|
+
const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()])
|
|
406
|
+
return { exists: !!preKeys[currentPreKeyId.toString()], currentPreKeyId }
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
410
|
+
try {
|
|
411
|
+
let count = 0
|
|
412
|
+
const preKeyCount = await getAvailablePreKeysOnServer()
|
|
413
|
+
count = preKeyCount === 0 ? INITIAL_PREKEY_COUNT : MIN_PREKEY_COUNT
|
|
414
|
+
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists()
|
|
415
|
+
logger.info(`${preKeyCount} pre-keys found on server`)
|
|
416
|
+
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`)
|
|
417
|
+
const lowServerCount = preKeyCount <= count
|
|
418
|
+
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
|
|
419
|
+
const shouldUpload = lowServerCount || missingCurrentPreKey
|
|
420
|
+
if (shouldUpload) {
|
|
421
|
+
const reasons = []
|
|
422
|
+
if (lowServerCount) reasons.push(`server count low (${preKeyCount})`)
|
|
423
|
+
if (missingCurrentPreKey) reasons.push(`current prekey ${currentPreKeyId} missing from storage`)
|
|
424
|
+
logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`)
|
|
425
|
+
await uploadPreKeys(count)
|
|
426
|
+
} else {
|
|
427
|
+
logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`)
|
|
428
|
+
}
|
|
429
|
+
} catch (error) {
|
|
430
|
+
logger.error({ error }, 'Failed to check/upload pre-keys during initialization')
|
|
431
|
+
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const onMessageReceived = async data => {
|
|
436
|
+
try {
|
|
437
|
+
await noise.decodeFrame(data, frame => {
|
|
438
|
+
lastDateRecv = new Date()
|
|
439
|
+
let anyTriggered = false
|
|
440
|
+
anyTriggered = ws.emit('frame', frame)
|
|
441
|
+
if (!(frame instanceof Uint8Array)) {
|
|
442
|
+
const msgId = frame.attrs.id
|
|
443
|
+
if (logger.level === 'trace') logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
|
|
444
|
+
anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
|
|
445
|
+
const l0 = frame.tag
|
|
446
|
+
const l1 = frame.attrs || {}
|
|
447
|
+
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
|
|
448
|
+
for (const key of Object.keys(l1)) {
|
|
449
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
|
|
450
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
|
|
451
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
|
|
452
|
+
}
|
|
453
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
|
|
454
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
|
|
455
|
+
if (!anyTriggered && logger.level === 'debug') logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
|
456
|
+
}
|
|
457
|
+
})
|
|
458
|
+
} catch (err) {
|
|
459
|
+
// satu-satunya error yang sampai sini: gagal decrypt frame (counter noise tidak sinkron) -> koneksi tidak bisa dipakai lagi.
|
|
460
|
+
// ditangani agar tidak jadi unhandled rejection yang mematikan proses.
|
|
461
|
+
if (closed) return
|
|
462
|
+
logger.error({ err }, 'failed to process inbound frame, closing connection')
|
|
463
|
+
void end(new Boom('Connection Terminated (inbound frame failed)', { statusCode: DisconnectReason.connectionLost, data: { cause: err } }))
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const end = async error => {
|
|
468
|
+
if (closed) {
|
|
469
|
+
logger.trace({ trace: error?.stack }, 'connection already closed')
|
|
470
|
+
return
|
|
471
|
+
}
|
|
472
|
+
closed = true
|
|
473
|
+
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
|
|
474
|
+
clearInterval(keepAliveReq)
|
|
475
|
+
clearTimeout(qrTimer)
|
|
476
|
+
|
|
477
|
+
consecutivePingFailures = 0
|
|
478
|
+
|
|
479
|
+
ws.removeAllListeners()
|
|
480
|
+
ws.on('error', () => {}) // error telat dari socket yang sedang ditutup tidak boleh jadi uncaught exception
|
|
481
|
+
|
|
482
|
+
noise.destroy?.()
|
|
483
|
+
signalRepository.close?.()
|
|
484
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
485
|
+
try {
|
|
486
|
+
|
|
487
|
+
await Promise.race([ws.close(), new Promise(resolve => setTimeout(resolve, 5000))])
|
|
488
|
+
} catch {
|
|
489
|
+
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
for (const handler of socketEndHandlers) {
|
|
493
|
+
try {
|
|
494
|
+
await handler(error)
|
|
495
|
+
} catch (err) {
|
|
496
|
+
logger.error({ err }, 'error in socket end handler')
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
ev.emit('connection.update', { connection: 'close', lastDisconnect: { error, date: new Date() } })
|
|
500
|
+
ev.removeAllListeners('connection.update')
|
|
501
|
+
ev.destroy()
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const waitForSocketOpen = async () => {
|
|
505
|
+
if (ws.isOpen) return
|
|
506
|
+
if (ws.isClosed || ws.isClosing) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
507
|
+
let onOpen
|
|
508
|
+
let onClose
|
|
509
|
+
await new Promise((resolve, reject) => {
|
|
510
|
+
onOpen = () => resolve(undefined)
|
|
511
|
+
onClose = mapWebSocketError(reject)
|
|
512
|
+
ws.on('open', onOpen)
|
|
513
|
+
ws.on('close', onClose)
|
|
514
|
+
ws.on('error', onClose)
|
|
515
|
+
}).finally(() => {
|
|
516
|
+
ws.off('open', onOpen)
|
|
517
|
+
ws.off('close', onClose)
|
|
518
|
+
ws.off('error', onClose)
|
|
519
|
+
})
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
let keepAliveInFlight = false
|
|
523
|
+
|
|
524
|
+
let consecutivePingFailures = 0
|
|
525
|
+
const MAX_PING_FAILURES = 3
|
|
526
|
+
const runKeepAliveCheck = () => {
|
|
527
|
+
if (closed) return
|
|
528
|
+
if (!lastDateRecv) lastDateRecv = new Date()
|
|
529
|
+
const diff = Date.now() - lastDateRecv.getTime()
|
|
530
|
+
|
|
531
|
+
if (diff > keepAliveIntervalMs * 2 + 5000) {
|
|
532
|
+
logger.warn({ diff, keepAliveIntervalMs }, 'connection silent for too long')
|
|
533
|
+
void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
|
|
534
|
+
return
|
|
535
|
+
}
|
|
536
|
+
if (!ws.isOpen) {
|
|
537
|
+
logger.warn('keep alive called when WS not open')
|
|
538
|
+
return
|
|
539
|
+
}
|
|
540
|
+
if (keepAliveInFlight) {
|
|
541
|
+
logger.trace('keep alive skipped: ping already in flight')
|
|
542
|
+
return
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if (diff < keepAliveIntervalMs / 2) {
|
|
546
|
+
logger.trace('keep alive skipped: recent inbound activity', { diff })
|
|
547
|
+
return
|
|
548
|
+
}
|
|
549
|
+
keepAliveInFlight = true
|
|
550
|
+
query({ tag: 'iq', attrs: { id: generateMessageTag(), to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:p' }, content: [{ tag: 'ping', attrs: {} }] }, keepAliveIntervalMs)
|
|
551
|
+
.then(() => {
|
|
552
|
+
|
|
553
|
+
consecutivePingFailures = 0
|
|
554
|
+
})
|
|
555
|
+
.catch(err => {
|
|
556
|
+
consecutivePingFailures++
|
|
557
|
+
logger.warn({ trace: err.stack, consecutivePingFailures, maxFailures: MAX_PING_FAILURES }, 'keep alive ping failed')
|
|
558
|
+
if (consecutivePingFailures >= MAX_PING_FAILURES) {
|
|
559
|
+
logger.warn('max ping failures reached, closing connection')
|
|
560
|
+
void end(new Boom('Connection was lost (ping failures)', { statusCode: DisconnectReason.connectionLost, data: { cause: err } }))
|
|
561
|
+
}
|
|
562
|
+
})
|
|
563
|
+
.finally(() => {
|
|
564
|
+
keepAliveInFlight = false
|
|
565
|
+
})
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// Timer yang telat lebih dari ini berarti event loop sempat macet, bukan jaringan yang diam.
|
|
569
|
+
const KEEPALIVE_STALL_TOLERANCE_MS = 1000
|
|
570
|
+
let lastKeepAliveTick = 0
|
|
571
|
+
const startKeepAliveRequest = () => {
|
|
572
|
+
lastKeepAliveTick = Date.now()
|
|
573
|
+
keepAliveReq = setInterval(() => {
|
|
574
|
+
const now = Date.now()
|
|
575
|
+
const stalledMs = Math.max(0, now - lastKeepAliveTick - keepAliveIntervalMs)
|
|
576
|
+
lastKeepAliveTick = now
|
|
577
|
+
if (!lastDateRecv) lastDateRecv = new Date()
|
|
578
|
+
if (stalledMs > KEEPALIVE_STALL_TOLERANCE_MS) {
|
|
579
|
+
// Event loop sempat macet (mis. penulisan DB sinkron saat login pertama: ratusan pre-key + sync awal).
|
|
580
|
+
// Selama macet frame dari server tidak bisa dibaca, jadi lamanya macet tidak boleh dihitung sebagai "server diam";
|
|
581
|
+
// kalau dihitung, koneksi yang sehat diputus dengan "Connection was lost" (408) begitu loop bebas lagi.
|
|
582
|
+
lastDateRecv = new Date(Math.min(now, lastDateRecv.getTime() + stalledMs))
|
|
583
|
+
logger.warn({ stalledMs, keepAliveIntervalMs }, 'event loop was blocked, keep-alive silence window shifted')
|
|
584
|
+
}
|
|
585
|
+
// Penilaian ditunda ke fase check supaya frame yang sudah menumpuk di socket terbaca (fase poll) lebih dulu.
|
|
586
|
+
setImmediate(runKeepAliveCheck)
|
|
587
|
+
}, keepAliveIntervalMs)
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const sendPassiveIq = tag => query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, xmlns: 'passive', type: 'set' }, content: [{ tag, attrs: {} }] })
|
|
591
|
+
|
|
592
|
+
const logout = async msg => {
|
|
593
|
+
const jid = authState.creds.me?.id
|
|
594
|
+
if (jid) {
|
|
595
|
+
await sendNode({
|
|
596
|
+
tag: 'iq',
|
|
597
|
+
attrs: { to: S_WHATSAPP_NET, type: 'set', id: generateMessageTag(), xmlns: 'md' },
|
|
598
|
+
content: [{ tag: 'remove-companion-device', attrs: { jid, reason: 'user_initiated' } }]
|
|
599
|
+
})
|
|
600
|
+
}
|
|
601
|
+
void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }))
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** This method was created by DanuZz, and implemented by DanuZz */
|
|
605
|
+
/** hey bro, if you delete this text */
|
|
606
|
+
/** you are the most cursed human being who likes to claim other people's property 😹🙌🏻 */
|
|
607
|
+
const requestPairingCode = async (phoneNumber, customPairingCode) => {
|
|
608
|
+
const customCode = customPairingCode == null ? '' : String(customPairingCode)
|
|
609
|
+
if (customCode && customCode.length !== 8) throw new Error('Custom pairing code must be exactly 8 chars')
|
|
610
|
+
// "+62 812-3456-7890" / "0812..." etc: jid may only contain the digits of the international number
|
|
611
|
+
const phone = String(phoneNumber ?? '').replace(/\D/g, '')
|
|
612
|
+
if (phone.length < 7 || phone.length > 15) throw new Error('Invalid phone number: use the international format, digits only (e.g. 6281234567890)')
|
|
613
|
+
if (authState.creds.account) throw new Boom('Session is already paired, log out before requesting a new pairing code', { statusCode: 400 })
|
|
614
|
+
if (closed || !ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
615
|
+
|
|
616
|
+
const previous = { me: authState.creds.me, pairingCode: authState.creds.pairingCode }
|
|
617
|
+
|
|
618
|
+
let pairingCode
|
|
619
|
+
if (customCode) {
|
|
620
|
+
pairingCode = customCode.toUpperCase() // custom code: no prefix
|
|
621
|
+
} else {
|
|
622
|
+
const prefix = 'DNUZ'
|
|
623
|
+
const randomPart = bytesToCrockford(randomBytes(5)).substring(0, 4).toUpperCase()
|
|
624
|
+
pairingCode = prefix + randomPart // prefix only for auto-generated codes
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
authState.creds.pairingCode = pairingCode
|
|
628
|
+
authState.creds.me = { id: jidEncode(phone, 's.whatsapp.net'), name: '~' }
|
|
629
|
+
ev.emit('creds.update', authState.creds)
|
|
630
|
+
try {
|
|
631
|
+
await sendNode({
|
|
632
|
+
tag: 'iq',
|
|
633
|
+
attrs: { to: S_WHATSAPP_NET, type: 'set', id: generateMessageTag(), xmlns: 'md' },
|
|
634
|
+
content: [
|
|
635
|
+
{
|
|
636
|
+
tag: 'link_code_companion_reg',
|
|
637
|
+
attrs: { jid: authState.creds.me.id, stage: 'companion_hello', should_show_push_notification: 'true' },
|
|
638
|
+
content: [
|
|
639
|
+
{ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub', attrs: {}, content: await generatePairingKey() },
|
|
640
|
+
{ tag: 'companion_server_auth_key_pub', attrs: {}, content: authState.creds.noiseKey.public },
|
|
641
|
+
{ tag: 'companion_platform_id', attrs: {}, content: getCompanionPlatformId(browser) },
|
|
642
|
+
{ tag: 'companion_platform_display', attrs: {}, content: `${browser[1]} (${browser[0]})` },
|
|
643
|
+
{ tag: 'link_code_pairing_nonce', attrs: {}, content: '0' }
|
|
644
|
+
]
|
|
645
|
+
}
|
|
646
|
+
]
|
|
647
|
+
})
|
|
648
|
+
} catch (error) {
|
|
649
|
+
// the request never reached the server: restore creds to how they were before the call
|
|
650
|
+
authState.creds.me = previous.me
|
|
651
|
+
authState.creds.pairingCode = previous.pairingCode
|
|
652
|
+
ev.emit('creds.update', authState.creds)
|
|
653
|
+
throw error
|
|
654
|
+
}
|
|
655
|
+
return authState.creds.pairingCode
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
async function generatePairingKey() {
|
|
659
|
+
const salt = randomBytes(32)
|
|
660
|
+
const randomIv = randomBytes(16)
|
|
661
|
+
const key = await derivePairingCodeKey(authState.creds.pairingCode, salt)
|
|
662
|
+
const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
|
|
663
|
+
return Buffer.concat([salt, randomIv, ciphered])
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const sendWAMBuffer = wamBuffer =>
|
|
667
|
+
query({
|
|
668
|
+
tag: 'iq',
|
|
669
|
+
attrs: { to: S_WHATSAPP_NET, id: generateMessageTag(), xmlns: 'w:stats' },
|
|
670
|
+
content: [{ tag: 'add', attrs: { t: Math.round(Date.now() / 1000) + '' }, content: wamBuffer }]
|
|
671
|
+
})
|
|
672
|
+
|
|
673
|
+
ws.on('message', onMessageReceived)
|
|
674
|
+
ws.on('open', async () => {
|
|
675
|
+
try {
|
|
676
|
+
await validateConnection()
|
|
677
|
+
} catch (err) {
|
|
678
|
+
logger.error({ err }, 'error in validating connection')
|
|
679
|
+
void end(err)
|
|
680
|
+
}
|
|
681
|
+
})
|
|
682
|
+
ws.on('error', mapWebSocketError(end))
|
|
683
|
+
ws.on('close', (code, reason) => {
|
|
684
|
+
const wsReason = reason ? String(reason) : ''
|
|
685
|
+
logger.info({ wsCode: code, wsReason }, 'websocket closed')
|
|
686
|
+
void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed, data: { wsCode: code, wsReason } }))
|
|
687
|
+
})
|
|
688
|
+
|
|
689
|
+
ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
|
|
690
|
+
|
|
691
|
+
ws.on('CB:iq,type:set,pair-device', async stanza => {
|
|
692
|
+
const iq = { tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'result', id: stanza.attrs.id } }
|
|
693
|
+
await sendNode(iq)
|
|
694
|
+
const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device')
|
|
695
|
+
const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref')
|
|
696
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
|
|
697
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
|
|
698
|
+
const advB64 = creds.advSecretKey
|
|
699
|
+
let qrMs = qrTimeout || 60000
|
|
700
|
+
const genPairQR = () => {
|
|
701
|
+
if (!ws.isOpen) return
|
|
702
|
+
const refNode = refNodes.shift()
|
|
703
|
+
if (!refNode) {
|
|
704
|
+
void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
|
|
705
|
+
return
|
|
706
|
+
}
|
|
707
|
+
const ref = refNode.content.toString('utf-8')
|
|
708
|
+
const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser)
|
|
709
|
+
ev.emit('connection.update', { qr })
|
|
710
|
+
if (printQRInTerminal) generateQR(qr, { small: true }, output => console.log('\n' + output))
|
|
711
|
+
qrTimer = setTimeout(genPairQR, qrMs)
|
|
712
|
+
qrMs = qrTimeout || 20000
|
|
713
|
+
}
|
|
714
|
+
genPairQR()
|
|
715
|
+
})
|
|
716
|
+
|
|
717
|
+
ws.on('CB:iq,,pair-success', async stanza => {
|
|
718
|
+
logger.debug('pair success recv')
|
|
719
|
+
try {
|
|
720
|
+
updateServerTimeOffset(stanza)
|
|
721
|
+
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
|
|
722
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...')
|
|
723
|
+
ev.emit('creds.update', updatedCreds)
|
|
724
|
+
ev.emit('connection.update', { isNewLogin: true, qr: undefined })
|
|
725
|
+
await sendNode(reply)
|
|
726
|
+
void sendUnifiedSession()
|
|
727
|
+
} catch (error) {
|
|
728
|
+
logger.info({ trace: error.stack }, 'error in pairing')
|
|
729
|
+
void end(error)
|
|
730
|
+
}
|
|
731
|
+
})
|
|
732
|
+
|
|
733
|
+
ws.on('CB:success', async node => {
|
|
734
|
+
try {
|
|
735
|
+
updateServerTimeOffset(node)
|
|
736
|
+
await uploadPreKeysToServerIfRequired()
|
|
737
|
+
await sendPassiveIq('active')
|
|
738
|
+
try {
|
|
739
|
+
await digestKeyBundle()
|
|
740
|
+
} catch (e) {
|
|
741
|
+
logger.warn({ e }, 'failed to run digest after login')
|
|
742
|
+
}
|
|
743
|
+
} catch (err) {
|
|
744
|
+
logger.warn({ err }, 'failed to send initial passive iq')
|
|
745
|
+
}
|
|
746
|
+
logger.info('opened connection to WA')
|
|
747
|
+
clearTimeout(qrTimer)
|
|
748
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
|
|
749
|
+
ev.emit('connection.update', { connection: 'open' })
|
|
750
|
+
void sendUnifiedSession()
|
|
751
|
+
if (node.attrs.lid && authState.creds.me?.id) {
|
|
752
|
+
const myLID = node.attrs.lid
|
|
753
|
+
process.nextTick(async () => {
|
|
754
|
+
try {
|
|
755
|
+
const myPN = authState.creds.me.id
|
|
756
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }])
|
|
757
|
+
const { user, device } = jidDecode(myPN)
|
|
758
|
+
await authState.keys.set({ 'device-list': { [user]: [device?.toString() || '0'] } })
|
|
759
|
+
await signalRepository.migrateSession(myPN, myLID)
|
|
760
|
+
logger.info({ myPN, myLID }, 'Own LID session created successfully')
|
|
761
|
+
} catch (error) {
|
|
762
|
+
logger.error({ error, lid: myLID }, 'Failed to create own LID session')
|
|
763
|
+
}
|
|
764
|
+
})
|
|
765
|
+
}
|
|
766
|
+
})
|
|
767
|
+
ws.on('CB:stream:error', node => {
|
|
768
|
+
const [reasonNode] = getAllBinaryNodeChildren(node)
|
|
769
|
+
logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out')
|
|
770
|
+
const { reason, statusCode } = getErrorCodeFromStreamError(node)
|
|
771
|
+
void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }))
|
|
772
|
+
})
|
|
773
|
+
|
|
774
|
+
ws.on('CB:failure', node => {
|
|
775
|
+
const reason = +(node.attrs.reason || 500)
|
|
776
|
+
void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
|
|
777
|
+
})
|
|
778
|
+
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
779
|
+
void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }))
|
|
780
|
+
})
|
|
781
|
+
ws.on('CB:ib,,offline_preview', async node => {
|
|
782
|
+
logger.info('offline preview received', JSON.stringify(node))
|
|
783
|
+
await sendNode({ tag: 'ib', attrs: {}, content: [{ tag: 'offline_batch', attrs: { count: '100' } }] })
|
|
784
|
+
})
|
|
785
|
+
ws.on('CB:ib,,edge_routing', node => {
|
|
786
|
+
const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
|
|
787
|
+
const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
|
|
788
|
+
if (routingInfo?.content) {
|
|
789
|
+
authState.creds.routingInfo = Buffer.from(routingInfo?.content)
|
|
790
|
+
ev.emit('creds.update', authState.creds)
|
|
791
|
+
}
|
|
792
|
+
})
|
|
793
|
+
|
|
794
|
+
let didStartBuffer = false
|
|
795
|
+
process.nextTick(() => {
|
|
796
|
+
if (creds.me?.id) {
|
|
797
|
+
ev.buffer()
|
|
798
|
+
didStartBuffer = true
|
|
799
|
+
}
|
|
800
|
+
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
|
|
801
|
+
})
|
|
802
|
+
|
|
803
|
+
ws.on('CB:ib,,offline', node => {
|
|
804
|
+
const child = getBinaryNodeChild(node, 'offline')
|
|
805
|
+
const offlineNotifs = +(child?.attrs.count || 0)
|
|
806
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`)
|
|
807
|
+
if (didStartBuffer) {
|
|
808
|
+
ev.flush()
|
|
809
|
+
logger.trace('flushed events for initial buffer')
|
|
810
|
+
}
|
|
811
|
+
ev.emit('connection.update', { receivedPendingNotifications: true })
|
|
812
|
+
})
|
|
813
|
+
|
|
814
|
+
ev.on('creds.update', update => {
|
|
815
|
+
const name = update.me?.name
|
|
816
|
+
if (creds.me?.name !== name) {
|
|
817
|
+
logger.debug({ name }, 'updated pushName')
|
|
818
|
+
sendNode({ tag: 'presence', attrs: { name } }).catch(err => logger.warn({ trace: err.stack }, 'error in sending presence update on name change'))
|
|
819
|
+
}
|
|
820
|
+
Object.assign(creds, update)
|
|
821
|
+
})
|
|
822
|
+
|
|
823
|
+
const updateServerTimeOffset = ({ attrs }) => {
|
|
824
|
+
const tValue = attrs?.t
|
|
825
|
+
if (!tValue) return
|
|
826
|
+
const parsed = Number(tValue)
|
|
827
|
+
if (Number.isNaN(parsed) || parsed <= 0) return
|
|
828
|
+
const localMs = Date.now()
|
|
829
|
+
serverTimeOffsetMs = parsed * 1000 - localMs
|
|
830
|
+
logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset')
|
|
831
|
+
}
|
|
832
|
+
const getUnifiedSessionId = () => {
|
|
833
|
+
const offsetMs = 3 * TimeMs.Day
|
|
834
|
+
const now = Date.now() + serverTimeOffsetMs
|
|
835
|
+
return ((now + offsetMs) % TimeMs.Week).toString()
|
|
836
|
+
}
|
|
837
|
+
const sendUnifiedSession = async () => {
|
|
838
|
+
if (!ws.isOpen) return
|
|
839
|
+
const node = { tag: 'ib', attrs: {}, content: [{ tag: 'unified_session', attrs: { id: getUnifiedSessionId() } }] }
|
|
840
|
+
try {
|
|
841
|
+
await sendNode(node)
|
|
842
|
+
} catch (error) {
|
|
843
|
+
logger.debug({ error }, 'failed to send unified_session telemetry')
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
const registerSocketEndHandler = handler => {
|
|
848
|
+
socketEndHandlers.push(handler)
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
const fetchAccountReachoutTimelock = async () => {
|
|
852
|
+
const queryResult = await executeWMexQuery({}, QueryIds.REACHOUT_TIMELOCK, XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag)
|
|
853
|
+
const result = {
|
|
854
|
+
isActive: !!queryResult?.is_active,
|
|
855
|
+
timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0' ? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000) : undefined,
|
|
856
|
+
enforcementType: queryResult?.enforcement_type ?? ReachoutTimelockEnforcementType.DEFAULT
|
|
857
|
+
}
|
|
858
|
+
ev.emit('connection.update', { reachoutTimeLock: result })
|
|
859
|
+
return result
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
const fetchNewChatMessageCap = async () => executeWMexQuery({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, QueryIds.MESSAGE_CAPPING_INFO, XWAPaths.xwa2_message_capping_info, query, generateMessageTag)
|
|
863
|
+
|
|
864
|
+
return {
|
|
865
|
+
type: 'md',
|
|
866
|
+
ws,
|
|
867
|
+
ev,
|
|
868
|
+
authState: { creds, keys },
|
|
869
|
+
signalRepository,
|
|
870
|
+
get user() {
|
|
871
|
+
return authState.creds.me
|
|
872
|
+
},
|
|
873
|
+
|
|
874
|
+
get connectionHealth() {
|
|
875
|
+
return {
|
|
876
|
+
lastMessageReceived: lastDateRecv,
|
|
877
|
+
consecutivePingFailures
|
|
878
|
+
}
|
|
879
|
+
},
|
|
880
|
+
generateMessageTag,
|
|
881
|
+
query,
|
|
882
|
+
waitForMessage,
|
|
883
|
+
waitForSocketOpen,
|
|
884
|
+
sendRawMessage,
|
|
885
|
+
sendNode,
|
|
886
|
+
logout,
|
|
887
|
+
end,
|
|
888
|
+
registerSocketEndHandler,
|
|
889
|
+
onUnexpectedError,
|
|
890
|
+
uploadPreKeys,
|
|
891
|
+
uploadPreKeysToServerIfRequired,
|
|
892
|
+
digestKeyBundle,
|
|
893
|
+
rotateSignedPreKey,
|
|
894
|
+
requestPairingCode,
|
|
895
|
+
updateServerTimeOffset,
|
|
896
|
+
sendUnifiedSession,
|
|
897
|
+
wamBuffer: publicWAMBuffer,
|
|
898
|
+
|
|
899
|
+
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
|
900
|
+
sendWAMBuffer,
|
|
901
|
+
executeUSyncQuery,
|
|
902
|
+
onWhatsApp,
|
|
903
|
+
resolveUsername,
|
|
904
|
+
fetchAccountReachoutTimelock,
|
|
905
|
+
fetchNewChatMessageCap
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function mapWebSocketError(handler) {
|
|
910
|
+
return error => {
|
|
911
|
+
handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }))
|
|
912
|
+
}
|
|
913
|
+
}
|