@badzz88/baileys 8.4.6 → 8.4.9

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