queenruva-sockets 5.6.23

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