@hiroosy/baileys-lite 0.0.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -10
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +716 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,11 +1,3 @@
1
- /**
2
- * Core WA socket. Connects to WA servers and performs:
3
- * - simple queries (no retry mechanism, wait for connection establishment)
4
- * - listens to messages and emits events
5
- * - query phone connection
6
- *
7
- * Combines what used to be Socket/socket.js and Socket/mex.js.
8
- */
9
1
  import { randomBytes } from 'node:crypto'
10
2
  import { URL } from 'node:url'
11
3
  import { promisify } from 'node:util'
@@ -35,14 +27,12 @@ import {
35
27
  } from '../utils/wa-protocol-core.js'
36
28
  import { addTransactionCapability } from '../utils/auth-state-core.js'
37
29
  import { makeEventBuffer } from '../utils/chat-sync.js'
38
- import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../binary/wa-binary.js'
30
+ import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../binary/wa-binary.js'
39
31
  import { BinaryInfo } from '../wam/wam.js'
40
32
  import { USyncQuery, USyncUser } from './usync.js'
33
+ import { normalizeUsername, isValidUsername, isValidUsernameKey } from '../utils/username.js'
41
34
  import { WebSocketClient } from '../socket-client/websocket-client.js'
42
-
43
- /* ------------------------------------------------------------------ */
44
- /* w:mex GraphQL-over-XMPP query helper */
45
- /* ------------------------------------------------------------------ */
35
+ import { generateQR } from '../foundation/qrcode-terminal.js'
46
36
 
47
37
  const wMexQuery = (variables, queryId, query, generateMessageTag) =>
48
38
  query({
@@ -69,9 +59,9 @@ export const executeWMexQuery = async (variables, queryId, dataPath, query, gene
69
59
  throw new Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result })
70
60
  }
71
61
 
72
- /* ------------------------------------------------------------------ */
73
- /* Core socket */
74
- /* ------------------------------------------------------------------ */
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
75
65
 
76
66
  export const makeSocket = config => {
77
67
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config
@@ -80,12 +70,6 @@ export const makeSocket = config => {
80
70
  const uqTagId = generateMdTagPrefix()
81
71
  const generateMessageTag = () => `${uqTagId}${epoch++}`
82
72
 
83
- if (printQRInTerminal) {
84
- logger.warn(
85
- {},
86
- '⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.'
87
- )
88
- }
89
73
  if (browser[1].toLocaleLowerCase().includes('android')) {
90
74
  logger.warn('⚠️ Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk.')
91
75
  }
@@ -95,20 +79,28 @@ export const makeSocket = config => {
95
79
  logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS')
96
80
  }
97
81
 
98
- const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl
82
+ const url = new URL(typeof waWebSocketUrl === 'string' ? waWebSocketUrl : waWebSocketUrl.href) // salinan: jangan mutasi URL milik pemanggil
99
83
  if (config.mobile || url.protocol === 'tcp:') throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut })
100
- if (url.protocol === 'wss' && authState?.creds?.routingInfo) url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
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
+ }
101
95
 
102
- /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
103
96
  const ephemeralKeyPair = Curve.generateKeyPair()
104
- /** WA noise protocol wrapper */
97
+
105
98
  const noise = makeNoiseHandler({ keyPair: ephemeralKeyPair, NOISE_HEADER: NOISE_WA_HEADER, logger, routingInfo: authState?.creds?.routingInfo })
106
99
 
107
- const ws = new WebSocketClient(url, config)
100
+ const ws = new WebSocketClient(url, wsConfig)
108
101
  ws.connect()
109
102
  const sendPromise = promisify(ws.send)
110
103
 
111
- /** send a raw buffer */
112
104
  const sendRawMessage = async data => {
113
105
  if (!ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
114
106
  const bytes = noise.encodeFrame(data)
@@ -122,14 +114,12 @@ export const makeSocket = config => {
122
114
  })
123
115
  }
124
116
 
125
- /** send a binary node */
126
117
  const sendNode = frame => {
127
118
  if (logger.level === 'trace') logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
128
119
  const buff = encodeBinaryNode(frame)
129
120
  return sendRawMessage(buff)
130
121
  }
131
122
 
132
- /** Wait for a message with a certain tag to be received */
133
123
  const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
134
124
  let onRecv
135
125
  let onErr
@@ -157,7 +147,6 @@ export const makeSocket = config => {
157
147
  }
158
148
  }
159
149
 
160
- /** send a query, and wait for its response. auto-generates message ID if not provided */
161
150
  const query = async (node, timeoutMs) => {
162
151
  if (!node.attrs.id) node.attrs.id = generateMessageTag()
163
152
  const msgId = node.attrs.id
@@ -171,7 +160,6 @@ export const makeSocket = config => {
171
160
  return result
172
161
  }
173
162
 
174
- // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
175
163
  const digestKeyBundle = async () => {
176
164
  const res = await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' }, content: [{ tag: 'digest', attrs: {} }] })
177
165
  const digestNode = getBinaryNodeChild(res, 'digest')
@@ -181,7 +169,6 @@ export const makeSocket = config => {
181
169
  }
182
170
  }
183
171
 
184
- // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
185
172
  const rotateSignedPreKey = async () => {
186
173
  const newId = (creds.signedPreKey.keyId || 0) + 1
187
174
  const skey = await signedKeyPair(creds.signedIdentityKey, newId)
@@ -191,7 +178,7 @@ export const makeSocket = config => {
191
178
 
192
179
  const executeUSyncQuery = async usyncQuery => {
193
180
  if (usyncQuery.protocols.length === 0) throw new Boom('USyncQuery must have at least one protocol')
194
- // todo: validate users, throw WARNING on no valid users -- variable below has only validated users
181
+
195
182
  const validUsers = usyncQuery.users
196
183
  const userNodes = validUsers.map(user => ({
197
184
  tag: 'user',
@@ -224,7 +211,7 @@ export const makeSocket = config => {
224
211
  const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`
225
212
  usyncQuery.withUser(new USyncUser().withPhone(phone))
226
213
  }
227
- if (usyncQuery.users.length === 0) return [] // return early without forcing an empty query
214
+ if (usyncQuery.users.length === 0) return []
228
215
  const results = await executeUSyncQuery(usyncQuery)
229
216
  if (results) return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }))
230
217
  }
@@ -243,9 +230,72 @@ export const makeSocket = config => {
243
230
  return results ? results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid })) : []
244
231
  }
245
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
+
246
287
  const ev = makeEventBuffer(logger)
247
288
  const { creds } = authState
248
- // add transaction capability
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
+
249
299
  const keys = addTransactionCapability(authState.keys, logger, transactionOpts)
250
300
  const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync)
251
301
  let lastDateRecv
@@ -255,12 +305,10 @@ export const makeSocket = config => {
255
305
  let closed = false
256
306
  const socketEndHandlers = []
257
307
 
258
- /** log & process any unexpected errors */
259
308
  const onUnexpectedError = (err, msg) => {
260
309
  logger.error({ err }, `unexpected error in '${msg}'`)
261
310
  }
262
311
 
263
- /** await the next incoming message */
264
312
  const awaitNextMessage = async sendMsg => {
265
313
  if (!ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
266
314
  let onOpen
@@ -280,7 +328,6 @@ export const makeSocket = config => {
280
328
  return result
281
329
  }
282
330
 
283
- /** connection handshake */
284
331
  const validateConnection = async () => {
285
332
  let helloMsg = { clientHello: { ephemeral: ephemeralKeyPair.public } }
286
333
  helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
@@ -310,9 +357,8 @@ export const makeSocket = config => {
310
357
  return +countChild.attrs.value
311
358
  }
312
359
 
313
- // WAWeb has no time throttle here; the server drives uploads via PreKeyLow notifications.
314
360
  let uploadPreKeysPromise = null
315
- /** generates and uploads a set of pre-keys to the server */
361
+
316
362
  const uploadPreKeys = async (count = MIN_PREKEY_COUNT) => {
317
363
  if (uploadPreKeysPromise) {
318
364
  logger.debug('Pre-key upload already in progress, waiting for completion')
@@ -321,11 +367,11 @@ export const makeSocket = config => {
321
367
  }
322
368
  const uploadLogic = async retryCount => {
323
369
  logger.info({ count, retryCount }, 'uploading pre-keys')
324
- // Generate and save pre-keys atomically (prevents ID collisions on retry)
370
+
325
371
  const node = await keys.transaction(async () => {
326
372
  logger.debug({ requestedCount: count }, 'generating pre-keys with requested count')
327
373
  const { update, node: node_ } = await getNextPreKeysNode({ creds, keys }, count)
328
- ev.emit('creds.update', update) // update credentials immediately to prevent duplicate IDs on retry
374
+ ev.emit('creds.update', update)
329
375
  return node_
330
376
  }, creds?.me?.id || 'upload-pre-keys')
331
377
  try {
@@ -382,19 +428,20 @@ export const makeSocket = config => {
382
428
  }
383
429
  } catch (error) {
384
430
  logger.error({ error }, 'Failed to check/upload pre-keys during initialization')
385
- // Don't throw - allow connection to continue even if pre-key check fails
431
+
386
432
  }
387
433
  }
388
434
 
389
435
  const onMessageReceived = async data => {
436
+ try {
390
437
  await noise.decodeFrame(data, frame => {
391
- lastDateRecv = new Date() // reset ping timeout
438
+ lastDateRecv = new Date()
392
439
  let anyTriggered = false
393
440
  anyTriggered = ws.emit('frame', frame)
394
441
  if (!(frame instanceof Uint8Array)) {
395
442
  const msgId = frame.attrs.id
396
443
  if (logger.level === 'trace') logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
397
- anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered // response to a message we sent
444
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
398
445
  const l0 = frame.tag
399
446
  const l1 = frame.attrs || {}
400
447
  const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
@@ -408,6 +455,13 @@ export const makeSocket = config => {
408
455
  if (!anyTriggered && logger.level === 'debug') logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
409
456
  }
410
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
+ }
411
465
  }
412
466
 
413
467
  const end = async error => {
@@ -419,25 +473,20 @@ export const makeSocket = config => {
419
473
  logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
420
474
  clearInterval(keepAliveReq)
421
475
  clearTimeout(qrTimer)
422
- // Reset keepalive failure state so a stale counter can't carry over if the
423
- // socket object is somehow reused.
476
+
424
477
  consecutivePingFailures = 0
425
- // Remove ALL listeners registered on the websocket, not just close/open/message.
426
- // The CB:/TAG: prefixed listeners registered by messages-recv.js & co. hold
427
- // closures over the entire socket scope; leaving them attached prevents GC of
428
- // the old connection's state and can let handlers fire on stale data if a
429
- // close/reconnect race occurs.
478
+
430
479
  ws.removeAllListeners()
431
- // Release noise handler internal state (encryption buffers, transport state,
432
- // pending frame callbacks) so it can be garbage collected.
480
+ ws.on('error', () => {}) // error telat dari socket yang sedang ditutup tidak boleh jadi uncaught exception
481
+
433
482
  noise.destroy?.()
434
483
  signalRepository.close?.()
435
484
  if (!ws.isClosed && !ws.isClosing) {
436
485
  try {
437
- // Guard against a stuck TCP socket hanging teardown forever.
486
+
438
487
  await Promise.race([ws.close(), new Promise(resolve => setTimeout(resolve, 5000))])
439
488
  } catch {
440
- // ignore
489
+
441
490
  }
442
491
  }
443
492
  for (const handler of socketEndHandlers) {
@@ -470,71 +519,76 @@ export const makeSocket = config => {
470
519
  })
471
520
  }
472
521
 
473
- // A keepalive ping that times out or errors is direct evidence the socket is dead (or the
474
- // network is down) -- the previous implementation only logged that failure and kept waiting
475
- // for `lastDateRecv` to go stale by ANOTHER full interval before declaring the connection
476
- // lost, so a single failed ping could take up to ~2x keepAliveIntervalMs to surface as a
477
- // disconnect. This mirrors the fix used by more actively-maintained Baileys forks: react to
478
- // ping failure immediately instead of waiting for a second, independent staleness check.
479
522
  let keepAliveInFlight = false
480
- // CONNECTION STABILITY: a single failed/timed-out ping can be a transient blip
481
- // (a slow server response, a brief network hiccup) rather than proof the socket
482
- // is dead. Requiring a few consecutive failures before tearing down the
483
- // connection avoids reconnect churn from those blips, while the hard staleness
484
- // check below (diff > 2x interval) still catches a truly dead connection quickly
485
- // even if pings themselves never fail outright (e.g. event loop stalls).
523
+
486
524
  let consecutivePingFailures = 0
487
525
  const MAX_PING_FAILURES = 3
488
- const startKeepAliveRequest = () =>
489
- (keepAliveReq = setInterval(() => {
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
490
577
  if (!lastDateRecv) lastDateRecv = new Date()
491
- const diff = Date.now() - lastDateRecv.getTime()
492
- // Hard timeout: if it's been over twice the keepalive interval since we last
493
- // heard from the server, the connection is almost certainly dead -- don't
494
- // wait on further ping failures to confirm it.
495
- if (diff > keepAliveIntervalMs * 2 + 5000) {
496
- logger.warn({ diff, keepAliveIntervalMs }, 'connection silent for too long')
497
- void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
498
- return
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')
499
584
  }
500
- if (!ws.isOpen) {
501
- logger.warn('keep alive called when WS not open')
502
- return
503
- }
504
- if (keepAliveInFlight) {
505
- logger.trace('keep alive skipped: ping already in flight')
506
- return
507
- }
508
- // skip this tick if the server already proved the connection is alive recently --
509
- // but only up to half the interval, so a socket that's merely "somewhat recent" still
510
- // gets pinged well before it could go stale enough to trip the check above.
511
- if (diff < keepAliveIntervalMs / 2) {
512
- logger.trace('keep alive skipped: recent inbound activity', { diff })
513
- return
514
- }
515
- keepAliveInFlight = true
516
- query({ tag: 'iq', attrs: { id: generateMessageTag(), to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:p' }, content: [{ tag: 'ping', attrs: {} }] }, keepAliveIntervalMs)
517
- .then(() => {
518
- // Ping succeeded -- reset the failure counter.
519
- consecutivePingFailures = 0
520
- })
521
- .catch(err => {
522
- consecutivePingFailures++
523
- logger.warn({ trace: err.stack, consecutivePingFailures, maxFailures: MAX_PING_FAILURES }, 'keep alive ping failed')
524
- if (consecutivePingFailures >= MAX_PING_FAILURES) {
525
- logger.warn('max ping failures reached, closing connection')
526
- void end(new Boom('Connection was lost (ping failures)', { statusCode: DisconnectReason.connectionLost, data: { cause: err } }))
527
- }
528
- })
529
- .finally(() => {
530
- keepAliveInFlight = false
531
- })
532
- }, keepAliveIntervalMs))
585
+ // Penilaian ditunda ke fase check supaya frame yang sudah menumpuk di socket terbaca (fase poll) lebih dulu.
586
+ setImmediate(runKeepAliveCheck)
587
+ }, keepAliveIntervalMs)
588
+ }
533
589
 
534
- /** i have no idea why this exists. pls enlighten me */
535
590
  const sendPassiveIq = tag => query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, xmlns: 'passive', type: 'set' }, content: [{ tag, attrs: {} }] })
536
591
 
537
- /** logout & invalidate connection */
538
592
  const logout = async msg => {
539
593
  const jid = authState.creds.me?.id
540
594
  if (jid) {
@@ -548,28 +602,46 @@ export const makeSocket = config => {
548
602
  }
549
603
 
550
604
  const requestPairingCode = async (phoneNumber, customPairingCode) => {
551
- const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5))
552
- if (customPairingCode && customPairingCode?.length !== 8) throw new Error('Custom pairing code must be exactly 8 chars')
605
+ const customCode = customPairingCode == null ? '' : String(customPairingCode)
606
+ if (customCode && customCode.length !== 8) throw new Error('Custom pairing code must be exactly 8 characters')
607
+ // "+62 812-3456-7890" / "0812..." dll: jid hanya boleh berisi digit nomor internasional
608
+ const phone = String(phoneNumber ?? '').replace(/\D/g, '')
609
+ if (phone.length < 7 || phone.length > 15) throw new Error('Invalid phone number: use the international format, digits only (e.g. 6281234567890)')
610
+ if (authState.creds.account) throw new Boom('Session is already paired, log out before requesting a new pairing code', { statusCode: 400 })
611
+ // Socket yang sudah mati (mis. user terlalu lama mengetik nomor sampai refs QR habis & koneksi ditutup) tidak boleh
612
+ // menyentuh creds: creds.me sementara yang ikut tersimpan membuat start berikutnya LOGIN dan ditolak 401.
613
+ if (closed || !ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
614
+
615
+ const previous = { me: authState.creds.me, pairingCode: authState.creds.pairingCode }
616
+ const pairingCode = customCode || bytesToCrockford(randomBytes(5))
553
617
  authState.creds.pairingCode = pairingCode
554
- authState.creds.me = { id: jidEncode(phoneNumber, 's.whatsapp.net'), name: '~' }
618
+ authState.creds.me = { id: jidEncode(phone, 's.whatsapp.net'), name: '~' }
555
619
  ev.emit('creds.update', authState.creds)
556
- await sendNode({
557
- tag: 'iq',
558
- attrs: { to: S_WHATSAPP_NET, type: 'set', id: generateMessageTag(), xmlns: 'md' },
559
- content: [
560
- {
561
- tag: 'link_code_companion_reg',
562
- attrs: { jid: authState.creds.me.id, stage: 'companion_hello', should_show_push_notification: 'true' },
563
- content: [
564
- { tag: 'link_code_pairing_wrapped_companion_ephemeral_pub', attrs: {}, content: await generatePairingKey() },
565
- { tag: 'companion_server_auth_key_pub', attrs: {}, content: authState.creds.noiseKey.public },
566
- { tag: 'companion_platform_id', attrs: {}, content: getCompanionPlatformId(browser) },
567
- { tag: 'companion_platform_display', attrs: {}, content: `${browser[1]} (${browser[0]})` },
568
- { tag: 'link_code_pairing_nonce', attrs: {}, content: '0' }
569
- ]
570
- }
571
- ]
572
- })
620
+ try {
621
+ await sendNode({
622
+ tag: 'iq',
623
+ attrs: { to: S_WHATSAPP_NET, type: 'set', id: generateMessageTag(), xmlns: 'md' },
624
+ content: [
625
+ {
626
+ tag: 'link_code_companion_reg',
627
+ attrs: { jid: authState.creds.me.id, stage: 'companion_hello', should_show_push_notification: 'true' },
628
+ content: [
629
+ { tag: 'link_code_pairing_wrapped_companion_ephemeral_pub', attrs: {}, content: await generatePairingKey() },
630
+ { tag: 'companion_server_auth_key_pub', attrs: {}, content: authState.creds.noiseKey.public },
631
+ { tag: 'companion_platform_id', attrs: {}, content: getCompanionPlatformId(browser) },
632
+ { tag: 'companion_platform_display', attrs: {}, content: `${browser[1]} (${browser[0]})` },
633
+ { tag: 'link_code_pairing_nonce', attrs: {}, content: '0' }
634
+ ]
635
+ }
636
+ ]
637
+ })
638
+ } catch (error) {
639
+ // permintaan tidak sampai ke server: kembalikan creds seperti sebelum dipanggil
640
+ authState.creds.me = previous.me
641
+ authState.creds.pairingCode = previous.pairingCode
642
+ ev.emit('creds.update', authState.creds)
643
+ throw error
644
+ }
573
645
  return authState.creds.pairingCode
574
646
  }
575
647
 
@@ -598,10 +670,14 @@ export const makeSocket = config => {
598
670
  }
599
671
  })
600
672
  ws.on('error', mapWebSocketError(end))
601
- ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
602
- // the server terminated the connection
673
+ ws.on('close', (code, reason) => {
674
+ const wsReason = reason ? String(reason) : ''
675
+ logger.info({ wsCode: code, wsReason }, 'websocket closed')
676
+ void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed, data: { wsCode: code, wsReason } }))
677
+ })
678
+
603
679
  ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
604
- // QR gen
680
+
605
681
  ws.on('CB:iq,type:set,pair-device', async stanza => {
606
682
  const iq = { tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'result', id: stanza.attrs.id } }
607
683
  await sendNode(iq)
@@ -610,7 +686,7 @@ export const makeSocket = config => {
610
686
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
611
687
  const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
612
688
  const advB64 = creds.advSecretKey
613
- let qrMs = qrTimeout || 60000 // time to let a QR live
689
+ let qrMs = qrTimeout || 60000
614
690
  const genPairQR = () => {
615
691
  if (!ws.isOpen) return
616
692
  const refNode = refNodes.shift()
@@ -621,12 +697,13 @@ export const makeSocket = config => {
621
697
  const ref = refNode.content.toString('utf-8')
622
698
  const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser)
623
699
  ev.emit('connection.update', { qr })
700
+ if (printQRInTerminal) generateQR(qr, { small: true }, output => console.log('\n' + output))
624
701
  qrTimer = setTimeout(genPairQR, qrMs)
625
- qrMs = qrTimeout || 20000 // shorter subsequent qrs
702
+ qrMs = qrTimeout || 20000
626
703
  }
627
704
  genPairQR()
628
705
  })
629
- // device paired for the first time; server asks to restart the connection
706
+
630
707
  ws.on('CB:iq,,pair-success', async stanza => {
631
708
  logger.debug('pair success recv')
632
709
  try {
@@ -642,14 +719,14 @@ export const makeSocket = config => {
642
719
  void end(error)
643
720
  }
644
721
  })
645
- // login complete
722
+
646
723
  ws.on('CB:success', async node => {
647
724
  try {
648
725
  updateServerTimeOffset(node)
649
726
  await uploadPreKeysToServerIfRequired()
650
727
  await sendPassiveIq('active')
651
728
  try {
652
- await digestKeyBundle() // validate our key-bundle against server
729
+ await digestKeyBundle()
653
730
  } catch (e) {
654
731
  logger.warn({ e }, 'failed to run digest after login')
655
732
  }
@@ -657,7 +734,7 @@ export const makeSocket = config => {
657
734
  logger.warn({ err }, 'failed to send initial passive iq')
658
735
  }
659
736
  logger.info('opened connection to WA')
660
- clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
737
+ clearTimeout(qrTimer)
661
738
  ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
662
739
  ev.emit('connection.update', { connection: 'open' })
663
740
  void sendUnifiedSession()
@@ -683,7 +760,7 @@ export const makeSocket = config => {
683
760
  const { reason, statusCode } = getErrorCodeFromStreamError(node)
684
761
  void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }))
685
762
  })
686
- // stream fail, possible logout
763
+
687
764
  ws.on('CB:failure', node => {
688
765
  const reason = +(node.attrs.reason || 500)
689
766
  void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
@@ -707,12 +784,12 @@ export const makeSocket = config => {
707
784
  let didStartBuffer = false
708
785
  process.nextTick(() => {
709
786
  if (creds.me?.id) {
710
- ev.buffer() // start buffering important events if we're logged in
787
+ ev.buffer()
711
788
  didStartBuffer = true
712
789
  }
713
790
  ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
714
791
  })
715
- // called when all offline notifs are handled
792
+
716
793
  ws.on('CB:ib,,offline', node => {
717
794
  const child = getBinaryNodeChild(node, 'offline')
718
795
  const offlineNotifs = +(child?.attrs.count || 0)
@@ -723,7 +800,7 @@ export const makeSocket = config => {
723
800
  }
724
801
  ev.emit('connection.update', { receivedPendingNotifications: true })
725
802
  })
726
- // update credentials when required
803
+
727
804
  ev.on('creds.update', update => {
728
805
  const name = update.me?.name
729
806
  if (creds.me?.name !== name) {
@@ -761,7 +838,6 @@ export const makeSocket = config => {
761
838
  socketEndHandlers.push(handler)
762
839
  }
763
840
 
764
- /** Fetches your account's standing when it comes to restrictions. */
765
841
  const fetchAccountReachoutTimelock = async () => {
766
842
  const queryResult = await executeWMexQuery({}, QueryIds.REACHOUT_TIMELOCK, XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag)
767
843
  const result = {
@@ -773,7 +849,6 @@ export const makeSocket = config => {
773
849
  return result
774
850
  }
775
851
 
776
- /** Fetches your account's new chat limits. Returns the quota and the usage. */
777
852
  const fetchNewChatMessageCap = async () => executeWMexQuery({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, QueryIds.MESSAGE_CAPPING_INFO, XWAPaths.xwa2_message_capping_info, query, generateMessageTag)
778
853
 
779
854
  return {
@@ -785,12 +860,7 @@ export const makeSocket = config => {
785
860
  get user() {
786
861
  return authState.creds.me
787
862
  },
788
- /**
789
- * Connection health metrics so consumers can implement their own health
790
- * checks or monitoring.
791
- * - lastMessageReceived: timestamp of last data received from the server
792
- * - consecutivePingFailures: how many keepalive pings have failed in a row
793
- */
863
+
794
864
  get connectionHealth() {
795
865
  return {
796
866
  lastMessageReceived: lastDateRecv,
@@ -815,17 +885,17 @@ export const makeSocket = config => {
815
885
  updateServerTimeOffset,
816
886
  sendUnifiedSession,
817
887
  wamBuffer: publicWAMBuffer,
818
- /** Waits for the connection to WA to reach a state */
888
+
819
889
  waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
820
890
  sendWAMBuffer,
821
891
  executeUSyncQuery,
822
892
  onWhatsApp,
893
+ resolveUsername,
823
894
  fetchAccountReachoutTimelock,
824
895
  fetchNewChatMessageCap
825
896
  }
826
897
  }
827
898
 
828
- /** map the websocket error to the right type so it can be retried by the caller */
829
899
  function mapWebSocketError(handler) {
830
900
  return error => {
831
901
  handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }))