@xbibzlibrary/whatsbibz 1.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.
Files changed (260) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +22 -0
  3. package/LICENSE.upstream +21 -0
  4. package/README.md +280 -0
  5. package/VERIFIKASI-IDENTITAS-2026-09-03.md +138 -0
  6. package/WAProto/GenerateStatics.sh +3 -0
  7. package/WAProto/WAProto.proto +6035 -0
  8. package/WAProto/fix-imports.js +81 -0
  9. package/WAProto/index.d.ts +15314 -0
  10. package/WAProto/index.js +132326 -0
  11. package/assets/logo/README.md +21 -0
  12. package/assets/logo/png/banner-1200x360.png +0 -0
  13. package/assets/logo/png/icon-1024.png +0 -0
  14. package/assets/logo/png/icon-128.png +0 -0
  15. package/assets/logo/png/icon-16.png +0 -0
  16. package/assets/logo/png/icon-24.png +0 -0
  17. package/assets/logo/png/icon-256.png +0 -0
  18. package/assets/logo/png/icon-32.png +0 -0
  19. package/assets/logo/png/icon-48.png +0 -0
  20. package/assets/logo/png/icon-512.png +0 -0
  21. package/assets/logo/png/icon-64.png +0 -0
  22. package/assets/logo/png/mark-512.png +0 -0
  23. package/assets/logo/preview.png +0 -0
  24. package/assets/logo/whatsbibz.ico +0 -0
  25. package/lib/BibzWhats/client.d.ts +95 -0
  26. package/lib/BibzWhats/client.js +501 -0
  27. package/lib/BibzWhats/device-identity.d.ts +60 -0
  28. package/lib/BibzWhats/device-identity.js +234 -0
  29. package/lib/BibzWhats/extract.d.ts +29 -0
  30. package/lib/BibzWhats/extract.js +115 -0
  31. package/lib/BibzWhats/index.d.ts +7 -0
  32. package/lib/BibzWhats/index.js +8 -0
  33. package/lib/BibzWhats/jid.d.ts +22 -0
  34. package/lib/BibzWhats/jid.js +98 -0
  35. package/lib/BibzWhats/pairing.d.ts +35 -0
  36. package/lib/BibzWhats/pairing.js +186 -0
  37. package/lib/BibzWhats/send.d.ts +9 -0
  38. package/lib/BibzWhats/send.js +107 -0
  39. package/lib/BibzWhats/version.d.ts +6 -0
  40. package/lib/BibzWhats/version.js +7 -0
  41. package/lib/Defaults/index.d.ts +73 -0
  42. package/lib/Defaults/index.js +141 -0
  43. package/lib/Modded/message_builder.d.ts +15 -0
  44. package/lib/Modded/message_builder.js +2330 -0
  45. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  46. package/lib/Signal/Group/ciphertext-message.js +11 -0
  47. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  48. package/lib/Signal/Group/group-session-builder.js +29 -0
  49. package/lib/Signal/Group/group_cipher.d.ts +16 -0
  50. package/lib/Signal/Group/group_cipher.js +81 -0
  51. package/lib/Signal/Group/index.d.ts +11 -0
  52. package/lib/Signal/Group/index.js +11 -0
  53. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  54. package/lib/Signal/Group/keyhelper.js +17 -0
  55. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  56. package/lib/Signal/Group/sender-chain-key.js +25 -0
  57. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  58. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  59. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  60. package/lib/Signal/Group/sender-key-message.js +65 -0
  61. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  62. package/lib/Signal/Group/sender-key-name.js +47 -0
  63. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  64. package/lib/Signal/Group/sender-key-record.js +40 -0
  65. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  66. package/lib/Signal/Group/sender-key-state.js +83 -0
  67. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  68. package/lib/Signal/Group/sender-message-key.js +25 -0
  69. package/lib/Signal/libsignal.d.ts +4 -0
  70. package/lib/Signal/libsignal.js +406 -0
  71. package/lib/Signal/lid-mapping.d.ts +18 -0
  72. package/lib/Signal/lid-mapping.js +276 -0
  73. package/lib/Socket/Client/index.d.ts +2 -0
  74. package/lib/Socket/Client/index.js +2 -0
  75. package/lib/Socket/Client/types.d.ts +15 -0
  76. package/lib/Socket/Client/types.js +10 -0
  77. package/lib/Socket/Client/websocket.d.ts +12 -0
  78. package/lib/Socket/Client/websocket.js +53 -0
  79. package/lib/Socket/business.d.ts +537 -0
  80. package/lib/Socket/business.js +421 -0
  81. package/lib/Socket/chats.d.ts +110 -0
  82. package/lib/Socket/chats.js +1006 -0
  83. package/lib/Socket/communities.d.ts +646 -0
  84. package/lib/Socket/communities.js +430 -0
  85. package/lib/Socket/engine.d.ts +129 -0
  86. package/lib/Socket/engine.js +767 -0
  87. package/lib/Socket/groups.d.ts +149 -0
  88. package/lib/Socket/groups.js +326 -0
  89. package/lib/Socket/index.d.ts +637 -0
  90. package/lib/Socket/index.js +14 -0
  91. package/lib/Socket/messages-recv.d.ts +239 -0
  92. package/lib/Socket/messages-recv.js +1307 -0
  93. package/lib/Socket/messages-send.d.ts +580 -0
  94. package/lib/Socket/messages-send.js +1639 -0
  95. package/lib/Socket/mex.d.ts +2 -0
  96. package/lib/Socket/mex.js +47 -0
  97. package/lib/Socket/newsletter.d.ts +176 -0
  98. package/lib/Socket/newsletter.js +456 -0
  99. package/lib/Socket/socket.d.ts +56 -0
  100. package/lib/Socket/socket.js +998 -0
  101. package/lib/Types/Auth.d.ts +115 -0
  102. package/lib/Types/Auth.js +1 -0
  103. package/lib/Types/Bussines.d.ts +36 -0
  104. package/lib/Types/Bussines.js +1 -0
  105. package/lib/Types/Call.d.ts +14 -0
  106. package/lib/Types/Call.js +1 -0
  107. package/lib/Types/Chat.d.ts +124 -0
  108. package/lib/Types/Chat.js +7 -0
  109. package/lib/Types/Contact.d.ts +23 -0
  110. package/lib/Types/Contact.js +1 -0
  111. package/lib/Types/Events.d.ts +241 -0
  112. package/lib/Types/Events.js +1 -0
  113. package/lib/Types/GroupMetadata.d.ts +67 -0
  114. package/lib/Types/GroupMetadata.js +1 -0
  115. package/lib/Types/Label.d.ts +46 -0
  116. package/lib/Types/Label.js +24 -0
  117. package/lib/Types/LabelAssociation.d.ts +29 -0
  118. package/lib/Types/LabelAssociation.js +6 -0
  119. package/lib/Types/Message.d.ts +427 -0
  120. package/lib/Types/Message.js +10 -0
  121. package/lib/Types/Newsletter.d.ts +134 -0
  122. package/lib/Types/Newsletter.js +30 -0
  123. package/lib/Types/Product.d.ts +78 -0
  124. package/lib/Types/Product.js +1 -0
  125. package/lib/Types/Signal.d.ts +77 -0
  126. package/lib/Types/Signal.js +1 -0
  127. package/lib/Types/Socket.d.ts +173 -0
  128. package/lib/Types/Socket.js +2 -0
  129. package/lib/Types/State.d.ts +38 -0
  130. package/lib/Types/State.js +12 -0
  131. package/lib/Types/USync.d.ts +25 -0
  132. package/lib/Types/USync.js +1 -0
  133. package/lib/Types/index.d.ts +75 -0
  134. package/lib/Types/index.js +32 -0
  135. package/lib/Utils/auth-utils.d.ts +18 -0
  136. package/lib/Utils/auth-utils.js +289 -0
  137. package/lib/Utils/browser-utils.d.ts +3 -0
  138. package/lib/Utils/browser-utils.js +47 -0
  139. package/lib/Utils/business.d.ts +22 -0
  140. package/lib/Utils/business.js +230 -0
  141. package/lib/Utils/chat-utils.d.ts +69 -0
  142. package/lib/Utils/chat-utils.js +811 -0
  143. package/lib/Utils/companion-reg-client-utils.d.ts +20 -0
  144. package/lib/Utils/companion-reg-client-utils.js +66 -0
  145. package/lib/Utils/crypto.d.ts +41 -0
  146. package/lib/Utils/crypto.js +117 -0
  147. package/lib/Utils/decode-wa-message.d.ts +47 -0
  148. package/lib/Utils/decode-wa-message.js +282 -0
  149. package/lib/Utils/event-buffer.d.ts +35 -0
  150. package/lib/Utils/event-buffer.js +590 -0
  151. package/lib/Utils/generics.d.ts +90 -0
  152. package/lib/Utils/generics.js +384 -0
  153. package/lib/Utils/history.d.ts +21 -0
  154. package/lib/Utils/history.js +130 -0
  155. package/lib/Utils/identity-change-handler.d.ts +36 -0
  156. package/lib/Utils/identity-change-handler.js +48 -0
  157. package/lib/Utils/index.d.ts +25 -0
  158. package/lib/Utils/index.js +24 -0
  159. package/lib/Utils/link-preview.d.ts +20 -0
  160. package/lib/Utils/link-preview.js +84 -0
  161. package/lib/Utils/logger.d.ts +12 -0
  162. package/lib/Utils/logger.js +2 -0
  163. package/lib/Utils/lt-hash.d.ts +10 -0
  164. package/lib/Utils/lt-hash.js +7 -0
  165. package/lib/Utils/make-mutex.d.ts +8 -0
  166. package/lib/Utils/make-mutex.js +32 -0
  167. package/lib/Utils/message-retry-manager.d.ts +109 -0
  168. package/lib/Utils/message-retry-manager.js +224 -0
  169. package/lib/Utils/messages-media.d.ts +129 -0
  170. package/lib/Utils/messages-media.js +784 -0
  171. package/lib/Utils/messages.d.ts +90 -0
  172. package/lib/Utils/messages.js +1240 -0
  173. package/lib/Utils/noise-handler.d.ts +19 -0
  174. package/lib/Utils/noise-handler.js +200 -0
  175. package/lib/Utils/offline-node-processor.d.ts +16 -0
  176. package/lib/Utils/offline-node-processor.js +39 -0
  177. package/lib/Utils/platform-identity.d.ts +14 -0
  178. package/lib/Utils/platform-identity.js +148 -0
  179. package/lib/Utils/pre-key-manager.d.ts +27 -0
  180. package/lib/Utils/pre-key-manager.js +105 -0
  181. package/lib/Utils/process-message.d.ts +59 -0
  182. package/lib/Utils/process-message.js +544 -0
  183. package/lib/Utils/reporting-utils.d.ts +10 -0
  184. package/lib/Utils/reporting-utils.js +257 -0
  185. package/lib/Utils/rich-messages.d.ts +276 -0
  186. package/lib/Utils/rich-messages.js +1143 -0
  187. package/lib/Utils/signal.d.ts +33 -0
  188. package/lib/Utils/signal.js +158 -0
  189. package/lib/Utils/stanza-ack.d.ts +10 -0
  190. package/lib/Utils/stanza-ack.js +37 -0
  191. package/lib/Utils/sticker-pack.d.ts +10 -0
  192. package/lib/Utils/sticker-pack.js +111 -0
  193. package/lib/Utils/sync-action-utils.d.ts +18 -0
  194. package/lib/Utils/sync-action-utils.js +47 -0
  195. package/lib/Utils/tc-token-utils.d.ts +8 -0
  196. package/lib/Utils/tc-token-utils.js +45 -0
  197. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  198. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  199. package/lib/Utils/validate-connection.d.ts +10 -0
  200. package/lib/Utils/validate-connection.js +222 -0
  201. package/lib/VoIP/audio-feeder.d.ts +15 -0
  202. package/lib/VoIP/audio-feeder.js +136 -0
  203. package/lib/VoIP/index.d.ts +12 -0
  204. package/lib/VoIP/index.js +282 -0
  205. package/lib/VoIP/relay-transport.d.ts +43 -0
  206. package/lib/VoIP/relay-transport.js +559 -0
  207. package/lib/VoIP/signaling.js +603 -0
  208. package/lib/VoIP/types.d.ts +69 -0
  209. package/lib/VoIP/types.js +17 -0
  210. package/lib/VoIP/wasm-engine.d.ts +103 -0
  211. package/lib/VoIP/wasm-engine.js +1214 -0
  212. package/lib/VoIP/worker-bootstrap.js +1042 -0
  213. package/lib/WABinary/constants.d.ts +27 -0
  214. package/lib/WABinary/constants.js +1300 -0
  215. package/lib/WABinary/decode.d.ts +6 -0
  216. package/lib/WABinary/decode.js +261 -0
  217. package/lib/WABinary/encode.d.ts +2 -0
  218. package/lib/WABinary/encode.js +219 -0
  219. package/lib/WABinary/generic-utils.d.ts +16 -0
  220. package/lib/WABinary/generic-utils.js +190 -0
  221. package/lib/WABinary/index.d.ts +5 -0
  222. package/lib/WABinary/index.js +5 -0
  223. package/lib/WABinary/jid-utils.d.ts +47 -0
  224. package/lib/WABinary/jid-utils.js +95 -0
  225. package/lib/WABinary/types.d.ts +18 -0
  226. package/lib/WABinary/types.js +1 -0
  227. package/lib/WAM/BinaryInfo.d.ts +8 -0
  228. package/lib/WAM/BinaryInfo.js +9 -0
  229. package/lib/WAM/constants.d.ts +39 -0
  230. package/lib/WAM/constants.js +22852 -0
  231. package/lib/WAM/encode.d.ts +2 -0
  232. package/lib/WAM/encode.js +149 -0
  233. package/lib/WAM/index.d.ts +3 -0
  234. package/lib/WAM/index.js +3 -0
  235. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  236. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  237. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  238. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  239. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  240. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  241. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  242. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  243. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  244. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  245. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +9 -0
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  247. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  248. package/lib/WAUSync/Protocols/index.js +4 -0
  249. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  250. package/lib/WAUSync/USyncQuery.js +93 -0
  251. package/lib/WAUSync/USyncUser.d.ts +12 -0
  252. package/lib/WAUSync/USyncUser.js +22 -0
  253. package/lib/WAUSync/index.d.ts +3 -0
  254. package/lib/WAUSync/index.js +3 -0
  255. package/lib/assets/wasm/loader.js +5 -0
  256. package/lib/assets/wasm/whatsapp.wasm +0 -0
  257. package/lib/assets/wasm/worker-modules.js +273 -0
  258. package/lib/index.d.ts +21 -0
  259. package/lib/index.js +22 -0
  260. package/package.json +111 -0
@@ -0,0 +1,998 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { randomBytes } from 'crypto';
3
+ import { URL } from 'url';
4
+ import { promisify } from 'util';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, MIN_UPLOAD_INTERVAL, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
7
+ import { DisconnectReason } from '../Types/index.js';
8
+ import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, handleCompanionRegRefresh, makeEventBuffer, makePairingQRRenderer, makeNoiseHandler, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
9
+ import { getPlatformId } from '../Utils/browser-utils.js';
10
+ import { derivePairingDisplay } from '../Utils/platform-identity.js';
11
+ import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { BinaryInfo } from '../WAM/BinaryInfo.js';
13
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
14
+ import { WebSocketClient } from './Client/index.js';
15
+ /**
16
+ * Connects to WA servers and performs:
17
+ * - simple queries (no retry mechanism, wait for connection establishment)
18
+ * - listen to messages and emit events
19
+ * - query phone connection
20
+ */
21
+ export const makeSocket = (config) => {
22
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
23
+ const publicWAMBuffer = new BinaryInfo();
24
+ let serverTimeOffsetMs = 0;
25
+ const uqTagId = generateMdTagPrefix();
26
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
27
+ if (printQRInTerminal) {
28
+ logger.warn({}, '⚠️ 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.');
29
+ }
30
+ const syncDisabled = PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false)
31
+ .length === PROCESSABLE_HISTORY_TYPES.length;
32
+ if (syncDisabled) {
33
+ logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BIBZWHATS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
34
+ }
35
+ const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
36
+ if (config.mobile || url.protocol === 'tcp:') {
37
+ throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
38
+ }
39
+ if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
40
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
41
+ }
42
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
43
+ const ephemeralKeyPair = Curve.generateKeyPair();
44
+ /** WA noise protocol wrapper */
45
+ const noise = makeNoiseHandler({
46
+ keyPair: ephemeralKeyPair,
47
+ NOISE_HEADER: NOISE_WA_HEADER,
48
+ logger,
49
+ routingInfo: authState?.creds?.routingInfo
50
+ });
51
+ const ws = new WebSocketClient(url, config);
52
+ ws.connect();
53
+ const sendPromise = promisify(ws.send);
54
+ /** send a raw buffer */
55
+ const sendRawMessage = async (data) => {
56
+ if (!ws.isOpen) {
57
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
58
+ }
59
+ const bytes = noise.encodeFrame(data);
60
+ await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
61
+ try {
62
+ await sendPromise.call(ws, bytes);
63
+ resolve();
64
+ }
65
+ catch (error) {
66
+ reject(error);
67
+ }
68
+ });
69
+ };
70
+ /** send a binary node */
71
+ const sendNode = (frame) => {
72
+ if (logger.level === 'trace') {
73
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
74
+ }
75
+ const buff = encodeBinaryNode(frame);
76
+ return sendRawMessage(buff);
77
+ };
78
+ /**
79
+ * Wait for a message with a certain tag to be received
80
+ * @param msgId the message tag to await
81
+ * @param timeoutMs timeout after which the promise will reject
82
+ */
83
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
84
+ let onRecv;
85
+ let onErr;
86
+ try {
87
+ const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
88
+ onRecv = data => {
89
+ resolve(data);
90
+ };
91
+ onErr = err => {
92
+ reject(err ||
93
+ new Boom('Connection Closed', {
94
+ statusCode: DisconnectReason.connectionClosed
95
+ }));
96
+ };
97
+ ws.on(`TAG:${msgId}`, onRecv);
98
+ ws.on('close', onErr);
99
+ ws.on('error', onErr);
100
+ return () => reject(new Boom('Query Cancelled'));
101
+ });
102
+ return result;
103
+ }
104
+ catch (error) {
105
+ // Catch timeout and return undefined instead of throwing
106
+ if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
107
+ logger?.warn?.({ msgId }, 'timed out waiting for message');
108
+ return undefined;
109
+ }
110
+ throw error;
111
+ }
112
+ finally {
113
+ if (onRecv)
114
+ ws.off(`TAG:${msgId}`, onRecv);
115
+ if (onErr) {
116
+ ws.off('close', onErr);
117
+ ws.off('error', onErr);
118
+ }
119
+ }
120
+ };
121
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
122
+ const query = async (node, timeoutMs) => {
123
+ if (!node.attrs.id) {
124
+ node.attrs.id = generateMessageTag();
125
+ }
126
+ const msgId = node.attrs.id;
127
+ const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
128
+ const result = waitForMessage(msgId, timeoutMs).catch(reject);
129
+ sendNode(node)
130
+ .then(async () => resolve(await result))
131
+ .catch(reject);
132
+ });
133
+ if (result && 'tag' in result) {
134
+ assertNodeErrorFree(result);
135
+ }
136
+ return result;
137
+ };
138
+ // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
139
+ const digestKeyBundle = async () => {
140
+ const res = await query({
141
+ tag: 'iq',
142
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
143
+ content: [{ tag: 'digest', attrs: {} }]
144
+ });
145
+ const digestNode = getBinaryNodeChild(res, 'digest');
146
+ if (!digestNode) {
147
+ await uploadPreKeys();
148
+ throw new Error('encrypt/get digest returned no digest node');
149
+ }
150
+ };
151
+ // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
152
+ const rotateSignedPreKey = async () => {
153
+ const newId = (creds.signedPreKey.keyId || 0) + 1;
154
+ const skey = await signedKeyPair(creds.signedIdentityKey, newId);
155
+ await query({
156
+ tag: 'iq',
157
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
158
+ content: [
159
+ {
160
+ tag: 'rotate',
161
+ attrs: {},
162
+ content: [xmppSignedPreKey(skey)]
163
+ }
164
+ ]
165
+ });
166
+ // Persist new signed pre-key in creds
167
+ ev.emit('creds.update', { signedPreKey: skey });
168
+ };
169
+ const executeUSyncQuery = async (usyncQuery) => {
170
+ if (usyncQuery.protocols.length === 0) {
171
+ throw new Boom('USyncQuery must have at least one protocol');
172
+ }
173
+ // todo: validate users, throw WARNING on no valid users
174
+ // variable below has only validated users
175
+ const validUsers = usyncQuery.users;
176
+ const userNodes = validUsers.map(user => {
177
+ return {
178
+ tag: 'user',
179
+ attrs: {
180
+ jid: !user.phone ? user.id : undefined
181
+ },
182
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
183
+ };
184
+ });
185
+ const listNode = {
186
+ tag: 'list',
187
+ attrs: {},
188
+ content: userNodes
189
+ };
190
+ const queryNode = {
191
+ tag: 'query',
192
+ attrs: {},
193
+ content: usyncQuery.protocols.map(a => a.getQueryElement())
194
+ };
195
+ const iq = {
196
+ tag: 'iq',
197
+ attrs: {
198
+ to: S_WHATSAPP_NET,
199
+ type: 'get',
200
+ xmlns: 'usync'
201
+ },
202
+ content: [
203
+ {
204
+ tag: 'usync',
205
+ attrs: {
206
+ context: usyncQuery.context,
207
+ mode: usyncQuery.mode,
208
+ sid: generateMessageTag(),
209
+ last: 'true',
210
+ index: '0'
211
+ },
212
+ content: [queryNode, listNode]
213
+ }
214
+ ]
215
+ };
216
+ const result = await query(iq);
217
+ return usyncQuery.parseUSyncQueryResult(result);
218
+ };
219
+ const onWhatsApp = async (...phoneNumber) => {
220
+ let usyncQuery = new USyncQuery();
221
+ let contactEnabled = false;
222
+ for (const jid of phoneNumber) {
223
+ if (isLidUser(jid)) {
224
+ logger?.warn('LIDs are not supported with onWhatsApp');
225
+ continue;
226
+ }
227
+ else {
228
+ if (!contactEnabled) {
229
+ contactEnabled = true;
230
+ usyncQuery = usyncQuery.withContactProtocol();
231
+ }
232
+ const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
233
+ usyncQuery.withUser(new USyncUser().withPhone(phone));
234
+ }
235
+ }
236
+ if (usyncQuery.users.length === 0) {
237
+ return []; // return early without forcing an empty query
238
+ }
239
+ const results = await executeUSyncQuery(usyncQuery);
240
+ if (results) {
241
+ return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
242
+ }
243
+ };
244
+ const pnFromLIDUSync = async (jids) => {
245
+ const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background');
246
+ for (const jid of jids) {
247
+ if (isLidUser(jid)) {
248
+ logger?.warn('LID user found in LID fetch call');
249
+ continue;
250
+ }
251
+ else {
252
+ usyncQuery.withUser(new USyncUser().withId(jid));
253
+ }
254
+ }
255
+ if (usyncQuery.users.length === 0) {
256
+ return []; // return early without forcing an empty query
257
+ }
258
+ const results = await executeUSyncQuery(usyncQuery);
259
+ if (results) {
260
+ return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
261
+ }
262
+ return [];
263
+ };
264
+ const ev = makeEventBuffer(logger);
265
+ const { creds } = authState;
266
+ // add transaction capability
267
+ const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
268
+ const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
269
+ let lastDateRecv;
270
+ let epoch = 1;
271
+ let keepAliveReq;
272
+ let qrTimer;
273
+ let closed = false;
274
+ /** log & process any unexpected errors */
275
+ const onUnexpectedError = (err, msg) => {
276
+ logger.error({ err }, `unexpected error in '${msg}'`);
277
+ };
278
+ /** await the next incoming message */
279
+ const awaitNextMessage = async (sendMsg) => {
280
+ if (!ws.isOpen) {
281
+ throw new Boom('Connection Closed', {
282
+ statusCode: DisconnectReason.connectionClosed
283
+ });
284
+ }
285
+ let onOpen;
286
+ let onClose;
287
+ const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
288
+ onOpen = resolve;
289
+ onClose = mapWebSocketError(reject);
290
+ ws.on('frame', onOpen);
291
+ ws.on('close', onClose);
292
+ ws.on('error', onClose);
293
+ }).finally(() => {
294
+ ws.off('frame', onOpen);
295
+ ws.off('close', onClose);
296
+ ws.off('error', onClose);
297
+ });
298
+ if (sendMsg) {
299
+ sendRawMessage(sendMsg).catch(onClose);
300
+ }
301
+ return result;
302
+ };
303
+ /** connection handshake */
304
+ const validateConnection = async () => {
305
+ let helloMsg = {
306
+ clientHello: { ephemeral: ephemeralKeyPair.public }
307
+ };
308
+ helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
309
+ logger.info({ browser, helloMsg }, 'connected to WA');
310
+ const init = proto.HandshakeMessage.encode(helloMsg).finish();
311
+ const result = await awaitNextMessage(init);
312
+ const handshake = proto.HandshakeMessage.decode(result);
313
+ logger.trace({ handshake }, 'handshake recv from WA');
314
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
315
+ let node;
316
+ if (!creds.me) {
317
+ node = generateRegistrationNode(creds, config);
318
+ logger.info({ node }, 'not logged in, attempting registration...');
319
+ }
320
+ else {
321
+ node = generateLoginNode(creds.me.id, config);
322
+ logger.info({ node }, 'logging in...');
323
+ }
324
+ const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
325
+ await sendRawMessage(proto.HandshakeMessage.encode({
326
+ clientFinish: {
327
+ static: keyEnc,
328
+ payload: payloadEnc
329
+ }
330
+ }).finish());
331
+ await noise.finishInit();
332
+ startKeepAliveRequest();
333
+ };
334
+ const getAvailablePreKeysOnServer = async () => {
335
+ const result = await query({
336
+ tag: 'iq',
337
+ attrs: {
338
+ id: generateMessageTag(),
339
+ xmlns: 'encrypt',
340
+ type: 'get',
341
+ to: S_WHATSAPP_NET
342
+ },
343
+ content: [{ tag: 'count', attrs: {} }]
344
+ });
345
+ const countChild = getBinaryNodeChild(result, 'count');
346
+ return +countChild.attrs.value;
347
+ };
348
+ // Pre-key upload state management
349
+ let uploadPreKeysPromise = null;
350
+ let lastUploadTime = 0;
351
+ /** generates and uploads a set of pre-keys to the server */
352
+ const uploadPreKeys = async (count = MIN_PREKEY_COUNT, retryCount = 0) => {
353
+ // Check minimum interval (except for retries)
354
+ if (retryCount === 0) {
355
+ const timeSinceLastUpload = Date.now() - lastUploadTime;
356
+ if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
357
+ logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
358
+ return;
359
+ }
360
+ }
361
+ // Prevent multiple concurrent uploads
362
+ if (uploadPreKeysPromise) {
363
+ logger.debug('Pre-key upload already in progress, waiting for completion');
364
+ await uploadPreKeysPromise;
365
+ }
366
+ const uploadLogic = async () => {
367
+ logger.info({ count, retryCount }, 'uploading pre-keys');
368
+ // Generate and save pre-keys atomically (prevents ID collisions on retry)
369
+ const node = await keys.transaction(async () => {
370
+ logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
371
+ const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
372
+ // Update credentials immediately to prevent duplicate IDs on retry
373
+ ev.emit('creds.update', update);
374
+ return node; // Only return node since update is already used
375
+ }, creds?.me?.id || 'upload-pre-keys');
376
+ // Upload to server (outside transaction, can fail without affecting local keys)
377
+ try {
378
+ await query(node);
379
+ logger.info({ count }, 'uploaded pre-keys successfully');
380
+ lastUploadTime = Date.now();
381
+ }
382
+ catch (uploadError) {
383
+ logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
384
+ // Exponential backoff retry (max 3 retries)
385
+ if (retryCount < 3) {
386
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
387
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
388
+ await new Promise(resolve => setTimeout(resolve, backoffDelay));
389
+ return uploadPreKeys(count, retryCount + 1);
390
+ }
391
+ throw uploadError;
392
+ }
393
+ };
394
+ // Add timeout protection
395
+ uploadPreKeysPromise = Promise.race([
396
+ uploadLogic(),
397
+ new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
398
+ ]);
399
+ try {
400
+ await uploadPreKeysPromise;
401
+ }
402
+ finally {
403
+ uploadPreKeysPromise = null;
404
+ }
405
+ };
406
+ const verifyCurrentPreKeyExists = async () => {
407
+ const currentPreKeyId = creds.nextPreKeyId - 1;
408
+ if (currentPreKeyId <= 0) {
409
+ return { exists: false, currentPreKeyId: 0 };
410
+ }
411
+ const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
412
+ const exists = !!preKeys[currentPreKeyId.toString()];
413
+ return { exists, currentPreKeyId };
414
+ };
415
+ const uploadPreKeysToServerIfRequired = async () => {
416
+ try {
417
+ let count = 0;
418
+ const preKeyCount = await getAvailablePreKeysOnServer();
419
+ if (preKeyCount === 0)
420
+ count = INITIAL_PREKEY_COUNT;
421
+ else
422
+ count = MIN_PREKEY_COUNT;
423
+ const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
424
+ logger.info(`${preKeyCount} pre-keys found on server`);
425
+ logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
426
+ const lowServerCount = preKeyCount <= count;
427
+ const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
428
+ const shouldUpload = lowServerCount || missingCurrentPreKey;
429
+ if (shouldUpload) {
430
+ const reasons = [];
431
+ if (lowServerCount)
432
+ reasons.push(`server count low (${preKeyCount})`);
433
+ if (missingCurrentPreKey)
434
+ reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
435
+ logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
436
+ await uploadPreKeys(count);
437
+ }
438
+ else {
439
+ logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
440
+ }
441
+ }
442
+ catch (error) {
443
+ logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
444
+ // Don't throw - allow connection to continue even if pre-key check fails
445
+ }
446
+ };
447
+ const onMessageReceived = async (data) => {
448
+ await noise.decodeFrame(data, frame => {
449
+ // reset ping timeout
450
+ lastDateRecv = new Date();
451
+ let anyTriggered = false;
452
+ anyTriggered = ws.emit('frame', frame);
453
+ // if it's a binary node
454
+ if (!(frame instanceof Uint8Array)) {
455
+ const msgId = frame.attrs.id;
456
+ if (logger.level === 'trace') {
457
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
458
+ }
459
+ /* Check if this is a response to a message we sent */
460
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
461
+ /* Check if this is a response to a message we are expecting */
462
+ const l0 = frame.tag;
463
+ const l1 = frame.attrs || {};
464
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
465
+ for (const key of Object.keys(l1)) {
466
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
467
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
468
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
469
+ }
470
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
471
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
472
+ if (!anyTriggered && logger.level === 'debug') {
473
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
474
+ }
475
+ }
476
+ });
477
+ };
478
+ const socketEndHandlers = [];
479
+ const end = async (error) => {
480
+ if (closed) {
481
+ logger.trace({ trace: error?.stack }, 'connection already closed');
482
+ return;
483
+ }
484
+ closed = true;
485
+ logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
486
+ clearInterval(keepAliveReq);
487
+ clearTimeout(qrTimer);
488
+ ws.removeAllListeners('close');
489
+ ws.removeAllListeners('open');
490
+ ws.removeAllListeners('message');
491
+ // BibzWhats (upstream #2191): lepaskan cache repositori signal agar socket
492
+ // lama tidak bocor memori setelah reconnect berulang.
493
+ try {
494
+ signalRepository.close?.();
495
+ }
496
+ catch { }
497
+ if (!ws.isClosed && !ws.isClosing) {
498
+ try {
499
+ await ws.close();
500
+ }
501
+ catch { }
502
+ }
503
+ for (const handler of socketEndHandlers) {
504
+ try {
505
+ await handler(error);
506
+ }
507
+ catch (err) {
508
+ logger.error({ err }, 'error in socket end handler');
509
+ }
510
+ }
511
+ ev.emit('connection.update', {
512
+ connection: 'close',
513
+ lastDisconnect: {
514
+ error,
515
+ date: new Date()
516
+ }
517
+ });
518
+ ev.removeAllListeners('connection.update');
519
+ ev.destroy?.();
520
+ };
521
+ /** daftarkan pembersih yang dijalankan saat socket ditutup (mis. clear cache/interval) */
522
+ const registerSocketEndHandler = (handler) => {
523
+ socketEndHandlers.push(handler);
524
+ };
525
+ const waitForSocketOpen = async () => {
526
+ if (ws.isOpen) {
527
+ return;
528
+ }
529
+ if (ws.isClosed || ws.isClosing) {
530
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
531
+ }
532
+ let onOpen;
533
+ let onClose;
534
+ await new Promise((resolve, reject) => {
535
+ onOpen = () => resolve(undefined);
536
+ onClose = mapWebSocketError(reject);
537
+ ws.on('open', onOpen);
538
+ ws.on('close', onClose);
539
+ ws.on('error', onClose);
540
+ }).finally(() => {
541
+ ws.off('open', onOpen);
542
+ ws.off('close', onClose);
543
+ ws.off('error', onClose);
544
+ });
545
+ };
546
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
547
+ if (!lastDateRecv) {
548
+ lastDateRecv = new Date();
549
+ }
550
+ const diff = Date.now() - lastDateRecv.getTime();
551
+ /*
552
+ check if it's been a suspicious amount of time since the server responded with our last seen
553
+ it could be that the network is down
554
+ */
555
+ if (diff > keepAliveIntervalMs + 5000) {
556
+ void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
557
+ }
558
+ else if (ws.isOpen) {
559
+ // if its all good, send a keep alive request
560
+ query({
561
+ tag: 'iq',
562
+ attrs: {
563
+ id: generateMessageTag(),
564
+ to: S_WHATSAPP_NET,
565
+ type: 'get',
566
+ xmlns: 'w:p'
567
+ },
568
+ content: [{ tag: 'ping', attrs: {} }]
569
+ }).catch(err => {
570
+ logger.error({ trace: err.stack }, 'error in sending keep alive');
571
+ });
572
+ }
573
+ else {
574
+ logger.warn('keep alive called when WS not open');
575
+ }
576
+ }, keepAliveIntervalMs));
577
+ /** i have no idea why this exists. pls enlighten me */
578
+ const sendPassiveIq = (tag) => query({
579
+ tag: 'iq',
580
+ attrs: {
581
+ to: S_WHATSAPP_NET,
582
+ xmlns: 'passive',
583
+ type: 'set'
584
+ },
585
+ content: [{ tag, attrs: {} }]
586
+ });
587
+ /** logout & invalidate connection */
588
+ const logout = async (msg) => {
589
+ const jid = authState.creds.me?.id;
590
+ if (jid) {
591
+ await sendNode({
592
+ tag: 'iq',
593
+ attrs: {
594
+ to: S_WHATSAPP_NET,
595
+ type: 'set',
596
+ id: generateMessageTag(),
597
+ xmlns: 'md'
598
+ },
599
+ content: [
600
+ {
601
+ tag: 'remove-companion-device',
602
+ attrs: {
603
+ jid,
604
+ reason: 'user_initiated'
605
+ }
606
+ }
607
+ ]
608
+ });
609
+ }
610
+ void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
611
+ };
612
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
613
+ const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
614
+ if (customPairingCode && customPairingCode?.length !== 8) {
615
+ throw new Error('Custom pairing code must be exactly 8 chars');
616
+ }
617
+ const me = { id: jidEncode(phoneNumber, 's.whatsapp.net'), name: '~' };
618
+ // BibzWhats (upstream PR #2769): pakai `query`, BUKAN `sendNode`.
619
+ // `sendNode` hanya menulis IQ lalu kembali, jadi penolakan server —
620
+ // `400 bad-request` bila companion_platform_display tidak dikenali,
621
+ // `429 rate-overlimit` bila terlalu sering — dulu lewat begitu saja:
622
+ // pemanggil tetap dapat kode (dibuat lokal) yang tidak pernah diakui
623
+ // server → notifikasi "tautkan perangkat" tidak pernah muncul di HP.
624
+ // Server menjawab <iq type='result'><link_code_companion_reg
625
+ // stage='companion_hello'>… bila sukses, jadi menunggunya aman.
626
+ const registration = await query({
627
+ tag: 'iq',
628
+ attrs: {
629
+ to: S_WHATSAPP_NET,
630
+ type: 'set',
631
+ id: generateMessageTag(),
632
+ xmlns: 'md'
633
+ },
634
+ content: [
635
+ {
636
+ tag: 'link_code_companion_reg',
637
+ attrs: {
638
+ jid: me.id,
639
+ stage: 'companion_hello',
640
+ should_show_push_notification: 'true'
641
+ },
642
+ content: [
643
+ {
644
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
645
+ attrs: {},
646
+ content: await generatePairingKey(pairingCode)
647
+ },
648
+ {
649
+ tag: 'companion_server_auth_key_pub',
650
+ attrs: {},
651
+ content: authState.creds.noiseKey.public
652
+ },
653
+ {
654
+ tag: 'companion_platform_id',
655
+ attrs: {},
656
+ content: String(config.companionPlatformId ?? getPlatformId(browser[1]))
657
+ },
658
+ {
659
+ tag: 'companion_platform_display',
660
+ attrs: {},
661
+ // WA MEMVALIDASI string ini dgn allow-list (400 bila
662
+ // tak dikenal: 'Arch Linux', 'Desktop', nama produk...).
663
+ // derivePairingDisplay memetakan ke padanan valid
664
+ // ('Chrome (Linux)', 'Chrome (Mac OS)'); override tetap
665
+ // dihormati apa adanya bila diberikan.
666
+ content: config.companionPlatformDisplay ?? derivePairingDisplay(browser)
667
+ },
668
+ {
669
+ tag: 'link_code_pairing_nonce',
670
+ attrs: {},
671
+ content: '0'
672
+ }
673
+ ]
674
+ }
675
+ ]
676
+ }, config.pairingRequestTimeoutMs ?? defaultQueryTimeoutMs);
677
+ // waitForMessage menelan timeout dan mengembalikan undefined → harus dicek,
678
+ // kalau tidak creds.me tersimpan untuk perangkat yang tak pernah diakui server
679
+ // dan setiap koneksi berikutnya mencoba LOGIN → 401 loggedOut beruntun.
680
+ if (!registration) {
681
+ throw new Boom('Companion registration timed out', { statusCode: DisconnectReason.timedOut });
682
+ }
683
+ // Baru sekarang: creds.me menentukan koneksi berikutnya LOGIN (bukan REGISTER).
684
+ authState.creds.pairingCode = pairingCode;
685
+ authState.creds.me = me;
686
+ ev.emit('creds.update', authState.creds);
687
+ return pairingCode;
688
+ };
689
+ // Terima kode sebagai argumen (bukan baca authState.creds) agar dua panggilan
690
+ // requestPairingCode yang tumpang tindih tidak saling menimpa.
691
+ async function generatePairingKey(pairingCode) {
692
+ const salt = randomBytes(32);
693
+ const randomIv = randomBytes(16);
694
+ const key = await derivePairingCodeKey(pairingCode, salt);
695
+ const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
696
+ return Buffer.concat([salt, randomIv, ciphered]);
697
+ }
698
+ const sendWAMBuffer = (wamBuffer) => {
699
+ return query({
700
+ tag: 'iq',
701
+ attrs: {
702
+ to: S_WHATSAPP_NET,
703
+ id: generateMessageTag(),
704
+ xmlns: 'w:stats'
705
+ },
706
+ content: [
707
+ {
708
+ tag: 'add',
709
+ attrs: { t: Math.round(Date.now() / 1000) + '' },
710
+ content: wamBuffer
711
+ }
712
+ ]
713
+ });
714
+ };
715
+ ws.on('message', onMessageReceived);
716
+ ws.on('open', async () => {
717
+ try {
718
+ await validateConnection();
719
+ }
720
+ catch (err) {
721
+ logger.error({ err }, 'error in validating connection');
722
+ void end(err);
723
+ }
724
+ });
725
+ ws.on('error', mapWebSocketError(end));
726
+ ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
727
+ // the server terminated the connection
728
+ ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
729
+ let refreshPairingQR;
730
+ // QR gen
731
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
732
+ const iq = {
733
+ tag: 'iq',
734
+ attrs: {
735
+ to: S_WHATSAPP_NET,
736
+ type: 'result',
737
+ id: stanza.attrs.id
738
+ }
739
+ };
740
+ await sendNode(iq);
741
+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
742
+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
743
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
744
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
745
+ // BibzWhats: QR dirender lewat renderer agar bisa di-refresh ulang
746
+ // (ref yang sama) saat server mengirim companion_reg_refresh.
747
+ const renderer = makePairingQRRenderer(
748
+ refNodes.map((refNode) => refNode.content.toString('utf-8')),
749
+ (ref) => ev.emit('connection.update', {
750
+ qr: [ref, noiseKeyB64, identityKeyB64, creds.advSecretKey].join(',')
751
+ })
752
+ );
753
+ refreshPairingQR = () => {
754
+ void renderer.refresh();
755
+ };
756
+ let qrMs = qrTimeout || 60000; // time to let a QR live
757
+ const genPairQR = () => {
758
+ if (!ws.isOpen) {
759
+ return;
760
+ }
761
+ if (!renderer.next()) {
762
+ void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
763
+ return;
764
+ }
765
+ qrTimer = setTimeout(genPairQR, qrMs);
766
+ qrMs = qrTimeout || 20000; // shorter subsequent qrs
767
+ };
768
+ genPairQR();
769
+ });
770
+ // BibzWhats: server menyita material registrasi companion yang belum
771
+ // paired (perubahan protokol WA 2026-07-28) → rotate adv secret & render
772
+ // ulang QR ref saat ini (jangan geser ref).
773
+ ws.on('CB:notification,type:companion_reg_refresh', (node) => {
774
+ handleCompanionRegRefresh(node, {
775
+ creds,
776
+ emitCredsUpdate: (update) => ev.emit('creds.update', update),
777
+ refreshQR: () => refreshPairingQR?.(),
778
+ logger
779
+ });
780
+ });
781
+ // device paired for the first time
782
+ // if device pairs successfully, the server asks to restart the connection
783
+ ws.on('CB:iq,,pair-success', async (stanza) => {
784
+ logger.debug('pair success recv');
785
+ try {
786
+ updateServerTimeOffset(stanza);
787
+ const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
788
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
789
+ ev.emit('creds.update', updatedCreds);
790
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined });
791
+ await sendNode(reply);
792
+ void sendUnifiedSession();
793
+ }
794
+ catch (error) {
795
+ logger.info({ trace: error.stack }, 'error in pairing');
796
+ void end(error);
797
+ }
798
+ });
799
+ // login complete
800
+ ws.on('CB:success', async (node) => {
801
+ try {
802
+ updateServerTimeOffset(node);
803
+ await uploadPreKeysToServerIfRequired();
804
+ await sendPassiveIq('active');
805
+ // After successful login, validate our key-bundle against server
806
+ try {
807
+ await digestKeyBundle();
808
+ }
809
+ catch (e) {
810
+ logger.warn({ e }, 'failed to run digest after login');
811
+ }
812
+ }
813
+ catch (err) {
814
+ logger.warn({ err }, 'failed to send initial passive iq');
815
+ }
816
+ logger.info('opened connection to WA');
817
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
818
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
819
+ ev.emit('connection.update', { connection: 'open' });
820
+ void sendUnifiedSession();
821
+ if (node.attrs.lid && authState.creds.me?.id) {
822
+ const myLID = node.attrs.lid;
823
+ process.nextTick(async () => {
824
+ try {
825
+ const myPN = authState.creds.me.id;
826
+ // Store our own LID-PN mapping
827
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
828
+ // Create device list for our own user (needed for bulk migration)
829
+ const { user, device } = jidDecode(myPN);
830
+ await authState.keys.set({
831
+ 'device-list': {
832
+ [user]: [device?.toString() || '0']
833
+ }
834
+ });
835
+ // migrate our own session
836
+ await signalRepository.migrateSession(myPN, myLID);
837
+ logger.info({ myPN, myLID }, 'Own LID session created successfully');
838
+ }
839
+ catch (error) {
840
+ logger.error({ error, lid: myLID }, 'Failed to create own LID session');
841
+ }
842
+ });
843
+ }
844
+ });
845
+ ws.on('CB:stream:error', (node) => {
846
+ const [reasonNode] = getAllBinaryNodeChildren(node);
847
+ logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
848
+ const { reason, statusCode } = getErrorCodeFromStreamError(node);
849
+ void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
850
+ });
851
+ // stream fail, possible logout
852
+ ws.on('CB:failure', (node) => {
853
+ const reason = +(node.attrs.reason || 500);
854
+ void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
855
+ });
856
+ ws.on('CB:ib,,downgrade_webclient', () => {
857
+ void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
858
+ });
859
+ ws.on('CB:ib,,offline_preview', async (node) => {
860
+ logger.info('offline preview received', JSON.stringify(node));
861
+ await sendNode({
862
+ tag: 'ib',
863
+ attrs: {},
864
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
865
+ });
866
+ });
867
+ ws.on('CB:ib,,edge_routing', (node) => {
868
+ const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
869
+ const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
870
+ if (routingInfo?.content) {
871
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content);
872
+ ev.emit('creds.update', authState.creds);
873
+ }
874
+ });
875
+ let didStartBuffer = false;
876
+ process.nextTick(() => {
877
+ if (creds.me?.id) {
878
+ // start buffering important events
879
+ // if we're logged in
880
+ ev.buffer();
881
+ didStartBuffer = true;
882
+ }
883
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
884
+ });
885
+ // called when all offline notifs are handled
886
+ ws.on('CB:ib,,offline', (node) => {
887
+ const child = getBinaryNodeChild(node, 'offline');
888
+ const offlineNotifs = +(child?.attrs.count || 0);
889
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
890
+ if (didStartBuffer) {
891
+ ev.flush();
892
+ logger.trace('flushed events for initial buffer');
893
+ }
894
+ ev.emit('connection.update', { receivedPendingNotifications: true });
895
+ });
896
+ // update credentials when required
897
+ ev.on('creds.update', update => {
898
+ const name = update.me?.name;
899
+ // BibzWhats (upstream PR #2789): creds.update parsial (tanpa `me`) dulu
900
+ // mengirim <presence/> TANPA nama → dibaca server sebagai "available" →
901
+ // akun tampak online terus & notifikasi push ke HP tersedot. Kirim hanya
902
+ // bila pushName benar-benar berubah.
903
+ if (typeof name === 'string' && name.length > 0 && creds.me?.name !== name) {
904
+ logger.debug({ name }, 'updated pushName');
905
+ sendNode({
906
+ tag: 'presence',
907
+ attrs: { name }
908
+ }).catch(err => {
909
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
910
+ });
911
+ }
912
+ Object.assign(creds, update);
913
+ });
914
+ const updateServerTimeOffset = ({ attrs }) => {
915
+ const tValue = attrs?.t;
916
+ if (!tValue) {
917
+ return;
918
+ }
919
+ const parsed = Number(tValue);
920
+ if (Number.isNaN(parsed) || parsed <= 0) {
921
+ return;
922
+ }
923
+ const localMs = Date.now();
924
+ serverTimeOffsetMs = parsed * 1000 - localMs;
925
+ logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
926
+ };
927
+ const getUnifiedSessionId = () => {
928
+ const offsetMs = 3 * TimeMs.Day;
929
+ const now = Date.now() + serverTimeOffsetMs;
930
+ const id = (now + offsetMs) % TimeMs.Week;
931
+ return id.toString();
932
+ };
933
+ const sendUnifiedSession = async () => {
934
+ if (!ws.isOpen) {
935
+ return;
936
+ }
937
+ const node = {
938
+ tag: 'ib',
939
+ attrs: {},
940
+ content: [
941
+ {
942
+ tag: 'unified_session',
943
+ attrs: {
944
+ id: getUnifiedSessionId()
945
+ }
946
+ }
947
+ ]
948
+ };
949
+ try {
950
+ await sendNode(node);
951
+ }
952
+ catch (error) {
953
+ logger.debug({ error }, 'failed to send unified_session telemetry');
954
+ }
955
+ };
956
+ return {
957
+ type: 'md',
958
+ ws,
959
+ ev,
960
+ authState: { creds, keys },
961
+ signalRepository,
962
+ get user() {
963
+ return authState.creds.me;
964
+ },
965
+ generateMessageTag,
966
+ query,
967
+ waitForMessage,
968
+ waitForSocketOpen,
969
+ sendRawMessage,
970
+ sendNode,
971
+ logout,
972
+ end,
973
+ onUnexpectedError,
974
+ uploadPreKeys,
975
+ uploadPreKeysToServerIfRequired,
976
+ digestKeyBundle,
977
+ rotateSignedPreKey,
978
+ requestPairingCode,
979
+ updateServerTimeOffset,
980
+ sendUnifiedSession,
981
+ wamBuffer: publicWAMBuffer,
982
+ /** Waits for the connection to WA to reach a state */
983
+ waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
984
+ sendWAMBuffer,
985
+ executeUSyncQuery,
986
+ onWhatsApp,
987
+ registerSocketEndHandler
988
+ };
989
+ };
990
+ /**
991
+ * map the websocket error to the right type
992
+ * so it can be retried by the caller
993
+ * */
994
+ function mapWebSocketError(handler) {
995
+ return (error) => {
996
+ handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
997
+ };
998
+ }