@neelegirly/baileys 2.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +108 -0
- package/WAProto/WAProto.proto +5007 -0
- package/WAProto/index.d.ts +57712 -0
- package/WAProto/index.js +178969 -0
- package/lib/Defaults/baileys-version.json +1 -0
- package/lib/Defaults/index.d.ts +68 -0
- package/lib/Defaults/index.js +155 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Signal/WASignalGroup/GroupProtocol.js +1909 -0
- package/lib/Signal/WASignalGroup/ciphertext_message.js +16 -0
- package/lib/Signal/WASignalGroup/generate-proto.sh +1 -0
- package/lib/Signal/WASignalGroup/group.proto +42 -0
- package/lib/Signal/WASignalGroup/group_cipher.js +120 -0
- package/lib/Signal/WASignalGroup/group_session_builder.js +46 -0
- package/lib/Signal/WASignalGroup/index.js +6 -0
- package/lib/Signal/WASignalGroup/keyhelper.js +22 -0
- package/lib/Signal/WASignalGroup/protobufs.js +3 -0
- package/lib/Signal/WASignalGroup/queue_job.js +69 -0
- package/lib/Signal/WASignalGroup/readme.md +6 -0
- package/lib/Signal/WASignalGroup/sender_chain_key.js +50 -0
- package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +78 -0
- package/lib/Signal/WASignalGroup/sender_key_message.js +92 -0
- package/lib/Signal/WASignalGroup/sender_key_name.js +70 -0
- package/lib/Signal/WASignalGroup/sender_key_record.js +56 -0
- package/lib/Signal/WASignalGroup/sender_key_state.js +129 -0
- package/lib/Signal/WASignalGroup/sender_message_key.js +39 -0
- package/lib/Signal/libsignal.d.ts +4 -0
- package/lib/Signal/libsignal.js +427 -0
- package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
- package/lib/Socket/Client/abstract-socket-client.js +13 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/lib/Socket/Client/index.js +22 -0
- package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
- package/lib/Socket/Client/mobile-socket-client.js +65 -0
- package/lib/Socket/Client/types.d.ts +16 -0
- package/lib/Socket/Client/types.js +18 -0
- package/lib/Socket/Client/websocket.d.ts +13 -0
- package/lib/Socket/Client/websocket.js +62 -0
- package/lib/Socket/business.d.ts +187 -0
- package/lib/Socket/business.js +268 -0
- package/lib/Socket/chats.d.ts +98 -0
- package/lib/Socket/chats.js +1133 -0
- package/lib/Socket/communities.d.ts +223 -0
- package/lib/Socket/communities.js +433 -0
- package/lib/Socket/groups.d.ts +131 -0
- package/lib/Socket/groups.js +352 -0
- package/lib/Socket/index.d.ts +191 -0
- package/lib/Socket/index.js +23 -0
- package/lib/Socket/messages-recv.d.ts +177 -0
- package/lib/Socket/messages-recv.js +1826 -0
- package/lib/Socket/messages-send.d.ts +168 -0
- package/lib/Socket/messages-send.js +1537 -0
- package/lib/Socket/mex.d.ts +2 -0
- package/lib/Socket/mex.js +47 -0
- package/lib/Socket/newsletter.d.ts +147 -0
- package/lib/Socket/newsletter.js +286 -0
- package/lib/Socket/registration.d.ts +266 -0
- package/lib/Socket/registration.js +166 -0
- package/lib/Socket/socket.d.ts +45 -0
- package/lib/Socket/socket.js +928 -0
- package/lib/Socket/usync.d.ts +37 -0
- package/lib/Socket/usync.js +83 -0
- package/lib/Store/index.d.ts +4 -0
- package/lib/Store/index.js +24 -0
- package/lib/Store/make-cache-manager-store.d.ts +14 -0
- package/lib/Store/make-cache-manager-store.js +90 -0
- package/lib/Store/make-in-memory-store.d.ts +123 -0
- package/lib/Store/make-in-memory-store.js +429 -0
- package/lib/Store/make-ordered-dictionary.d.ts +12 -0
- package/lib/Store/make-ordered-dictionary.js +86 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +31 -0
- package/lib/Types/Auth.d.ts +120 -0
- package/lib/Types/Auth.js +3 -0
- package/lib/Types/Bussines.d.ts +20 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.d.ts +14 -0
- package/lib/Types/Call.js +3 -0
- package/lib/Types/Chat.d.ts +141 -0
- package/lib/Types/Chat.js +9 -0
- package/lib/Types/Contact.d.ts +20 -0
- package/lib/Types/Contact.js +3 -0
- package/lib/Types/Events.d.ts +237 -0
- package/lib/Types/Events.js +3 -0
- package/lib/Types/GroupMetadata.d.ts +66 -0
- package/lib/Types/GroupMetadata.js +3 -0
- package/lib/Types/Label.d.ts +48 -0
- package/lib/Types/Label.js +31 -0
- package/lib/Types/LabelAssociation.d.ts +35 -0
- package/lib/Types/LabelAssociation.js +13 -0
- package/lib/Types/Message.d.ts +473 -0
- package/lib/Types/Message.js +13 -0
- package/lib/Types/MexUpdates.d.ts +9 -0
- package/lib/Types/MexUpdates.js +18 -0
- package/lib/Types/Newsletter.d.ts +109 -0
- package/lib/Types/Newsletter.js +40 -0
- package/lib/Types/Product.d.ts +92 -0
- package/lib/Types/Product.js +3 -0
- package/lib/Types/Signal.d.ts +68 -0
- package/lib/Types/Signal.js +3 -0
- package/lib/Types/Socket.d.ts +122 -0
- package/lib/Types/Socket.js +3 -0
- package/lib/Types/State.d.ts +41 -0
- package/lib/Types/State.js +14 -0
- package/lib/Types/USync.d.ts +26 -0
- package/lib/Types/USync.js +3 -0
- package/lib/Types/index.d.ts +80 -0
- package/lib/Types/index.js +48 -0
- package/lib/Utils/auth-utils.d.ts +21 -0
- package/lib/Utils/auth-utils.js +205 -0
- package/lib/Utils/baileys-event-stream.d.ts +18 -0
- package/lib/Utils/baileys-event-stream.js +70 -0
- package/lib/Utils/branding.d.ts +24 -0
- package/lib/Utils/branding.js +209 -0
- package/lib/Utils/business.d.ts +29 -0
- package/lib/Utils/business.js +255 -0
- package/lib/Utils/chat-utils.d.ts +82 -0
- package/lib/Utils/chat-utils.js +798 -0
- package/lib/Utils/check-npm-version.d.ts +18 -0
- package/lib/Utils/check-npm-version.js +130 -0
- package/lib/Utils/crypto.d.ts +56 -0
- package/lib/Utils/crypto.js +179 -0
- package/lib/Utils/decode-wa-message.d.ts +41 -0
- package/lib/Utils/decode-wa-message.js +288 -0
- package/lib/Utils/event-buffer.d.ts +39 -0
- package/lib/Utils/event-buffer.js +565 -0
- package/lib/Utils/generics.d.ts +129 -0
- package/lib/Utils/generics.js +630 -0
- package/lib/Utils/history.d.ts +23 -0
- package/lib/Utils/history.js +110 -0
- package/lib/Utils/index.d.ts +22 -0
- package/lib/Utils/index.js +42 -0
- package/lib/Utils/link-preview.d.ts +23 -0
- package/lib/Utils/link-preview.js +120 -0
- package/lib/Utils/logger.d.ts +13 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.d.ts +14 -0
- package/lib/Utils/lt-hash.js +58 -0
- package/lib/Utils/make-mutex.d.ts +9 -0
- package/lib/Utils/make-mutex.js +49 -0
- package/lib/Utils/message-retry-manager.d.ts +84 -0
- package/lib/Utils/message-retry-manager.js +179 -0
- package/lib/Utils/messages-media.d.ts +129 -0
- package/lib/Utils/messages-media.js +806 -0
- package/lib/Utils/messages.d.ts +103 -0
- package/lib/Utils/messages.js +1579 -0
- package/lib/Utils/noise-handler.d.ts +20 -0
- package/lib/Utils/noise-handler.js +155 -0
- package/lib/Utils/process-message.d.ts +49 -0
- package/lib/Utils/process-message.js +443 -0
- package/lib/Utils/signal.d.ts +42 -0
- package/lib/Utils/signal.js +168 -0
- package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
- package/lib/Utils/use-mongo-file-auth-state.js +84 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
- package/lib/Utils/use-multi-file-auth-state.js +249 -0
- package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
- package/lib/Utils/use-single-file-auth-state.js +80 -0
- package/lib/Utils/validate-connection.d.ts +13 -0
- package/lib/Utils/validate-connection.js +218 -0
- package/lib/WABinary/constants.d.ts +30 -0
- package/lib/WABinary/constants.js +1316 -0
- package/lib/WABinary/decode.d.ts +9 -0
- package/lib/WABinary/decode.js +288 -0
- package/lib/WABinary/encode.d.ts +3 -0
- package/lib/WABinary/encode.js +265 -0
- package/lib/WABinary/generic-utils.d.ts +28 -0
- package/lib/WABinary/generic-utils.js +142 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +25 -0
- package/lib/WABinary/jid-utils.d.ts +59 -0
- package/lib/WABinary/jid-utils.js +105 -0
- package/lib/WABinary/types.d.ts +22 -0
- package/lib/WABinary/types.js +3 -0
- package/lib/WAM/BinaryInfo.d.ts +16 -0
- package/lib/WAM/BinaryInfo.js +17 -0
- package/lib/WAM/constants.d.ts +47 -0
- package/lib/WAM/constants.js +15371 -0
- package/lib/WAM/encode.d.ts +3 -0
- package/lib/WAM/encode.js +165 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +23 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +36 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
- package/lib/WAUSync/Protocols/index.d.ts +6 -0
- package/lib/WAUSync/Protocols/index.js +26 -0
- package/lib/WAUSync/USyncQuery.d.ts +31 -0
- package/lib/WAUSync/USyncQuery.js +82 -0
- package/lib/WAUSync/USyncUser.d.ts +12 -0
- package/lib/WAUSync/USyncUser.js +30 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +23 -0
- package/lib/index.d.ts +13 -0
- package/lib/index.js +33 -0
- package/package.json +120 -0
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true })
|
|
4
|
+
|
|
5
|
+
const boom_1 = require("@hapi/boom")
|
|
6
|
+
const crypto_1 = require("crypto")
|
|
7
|
+
const url_1 = require("url")
|
|
8
|
+
const util_1 = require("util")
|
|
9
|
+
const WAProto_1 = require("../../WAProto")
|
|
10
|
+
const Defaults_1 = require("../Defaults")
|
|
11
|
+
const Types_1 = require("../Types")
|
|
12
|
+
const Utils_1 = require("../Utils")
|
|
13
|
+
const WABinary_1 = require("../WABinary")
|
|
14
|
+
const BinaryInfo_1 = require("../WAM/BinaryInfo")
|
|
15
|
+
const USyncQuery_1 = require("../WAUSync/USyncQuery")
|
|
16
|
+
const USyncUser_1 = require("../WAUSync/USyncUser")
|
|
17
|
+
const Client_1 = require("./Client")
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Connects to WA servers and performs:
|
|
21
|
+
* - simple queries (no retry mechanism, wait for connection establishment)
|
|
22
|
+
* - listen to messages and emit events
|
|
23
|
+
* - query phone connection
|
|
24
|
+
*/
|
|
25
|
+
const makeSocket = (config) => {
|
|
26
|
+
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config
|
|
27
|
+
|
|
28
|
+
const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl
|
|
29
|
+
|
|
30
|
+
if (config.mobile || url.protocol === 'tcp:') {
|
|
31
|
+
throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut })
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
|
35
|
+
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const ws = new Client_1.WebSocketClient(url, config)
|
|
39
|
+
|
|
40
|
+
ws.connect()
|
|
41
|
+
const ev = Utils_1.makeEventBuffer(logger)
|
|
42
|
+
const publicWAMBuffer = new BinaryInfo_1.BinaryInfo()
|
|
43
|
+
|
|
44
|
+
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
|
|
45
|
+
const ephemeralKeyPair = Utils_1.Curve.generateKeyPair()
|
|
46
|
+
|
|
47
|
+
/** WA noise protocol wrapper */
|
|
48
|
+
const noise = Utils_1.makeNoiseHandler({
|
|
49
|
+
keyPair: ephemeralKeyPair,
|
|
50
|
+
NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
|
|
51
|
+
logger,
|
|
52
|
+
routingInfo: authState?.creds?.routingInfo
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
const { creds } = authState
|
|
56
|
+
|
|
57
|
+
// add transaction capability
|
|
58
|
+
const keys = Utils_1.addTransactionCapability(authState.keys, logger, transactionOpts)
|
|
59
|
+
// pnFromLIDUSync wird später definiert, daher temporär undefined
|
|
60
|
+
let signalRepository
|
|
61
|
+
const initSignalRepository = () => {
|
|
62
|
+
signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let lastDateRecv
|
|
66
|
+
let epoch = 1
|
|
67
|
+
let keepAliveReq
|
|
68
|
+
let qrTimer
|
|
69
|
+
let closed = false
|
|
70
|
+
|
|
71
|
+
const uqTagId = Utils_1.generateMdTagPrefix()
|
|
72
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`
|
|
73
|
+
const sendPromise = util_1.promisify(ws.send)
|
|
74
|
+
|
|
75
|
+
/** send a raw buffer */
|
|
76
|
+
const sendRawMessage = async (data) => {
|
|
77
|
+
if (!ws.isOpen) {
|
|
78
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const bytes = noise.encodeFrame(data)
|
|
82
|
+
await Utils_1.promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
|
|
83
|
+
try {
|
|
84
|
+
await sendPromise.call(ws, bytes)
|
|
85
|
+
resolve()
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
reject(error)
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** send a binary node */
|
|
94
|
+
const sendNode = (frame) => {
|
|
95
|
+
if (logger.level === 'trace') {
|
|
96
|
+
logger.trace({ xml: WABinary_1.binaryNodeToString(frame), msg: 'xml send' })
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const buff = WABinary_1.encodeBinaryNode(frame)
|
|
100
|
+
|
|
101
|
+
return sendRawMessage(buff)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** log & process any unexpected errors */
|
|
105
|
+
const onUnexpectedError = (err, msg) => {
|
|
106
|
+
logger.error({ err }, `unexpected error in '${msg}'`)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** await the next incoming message */
|
|
110
|
+
const awaitNextMessage = async (sendMsg) => {
|
|
111
|
+
if (!ws.isOpen) {
|
|
112
|
+
throw new boom_1.Boom('Connection Closed', {
|
|
113
|
+
statusCode: Types_1.DisconnectReason.connectionClosed
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
let onOpen
|
|
118
|
+
let onClose
|
|
119
|
+
|
|
120
|
+
const result = Utils_1.promiseTimeout(connectTimeoutMs, (resolve, reject) => {
|
|
121
|
+
onOpen = resolve
|
|
122
|
+
onClose = mapWebSocketError(reject)
|
|
123
|
+
ws.on('frame', onOpen)
|
|
124
|
+
ws.on('close', onClose)
|
|
125
|
+
ws.on('error', onClose)
|
|
126
|
+
}).finally(() => {
|
|
127
|
+
ws.off('frame', onOpen)
|
|
128
|
+
ws.off('close', onClose)
|
|
129
|
+
ws.off('error', onClose)
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
if (sendMsg) {
|
|
133
|
+
sendRawMessage(sendMsg).catch(onClose)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return result
|
|
137
|
+
}
|
|
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 Utils_1.promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
149
|
+
onRecv = data => {
|
|
150
|
+
resolve(data)
|
|
151
|
+
}
|
|
152
|
+
onErr = err => {
|
|
153
|
+
reject(err ||
|
|
154
|
+
new boom_1.Boom('Connection Closed', {
|
|
155
|
+
statusCode: Types_1.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_1.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_1.Boom && error.output?.statusCode === Types_1.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
|
+
|
|
183
|
+
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
|
184
|
+
const query = async (node, timeoutMs) => {
|
|
185
|
+
if (!node.attrs.id) {
|
|
186
|
+
node.attrs.id = generateMessageTag()
|
|
187
|
+
}
|
|
188
|
+
const msgId = node.attrs.id
|
|
189
|
+
const result = await Utils_1.promiseTimeout(timeoutMs, async (resolve, reject) => {
|
|
190
|
+
const result = waitForMessage(msgId, timeoutMs).catch(reject)
|
|
191
|
+
sendNode(node)
|
|
192
|
+
.then(async () => resolve(await result))
|
|
193
|
+
.catch(reject)
|
|
194
|
+
})
|
|
195
|
+
if (result && 'tag' in result) {
|
|
196
|
+
WABinary_1.assertNodeErrorFree(result)
|
|
197
|
+
}
|
|
198
|
+
return result
|
|
199
|
+
}
|
|
200
|
+
// Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
|
|
201
|
+
const digestKeyBundle = async () => {
|
|
202
|
+
const res = await query({
|
|
203
|
+
tag: 'iq',
|
|
204
|
+
attrs: { to: WABinary_1.S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
|
|
205
|
+
content: [{ tag: 'digest', attrs: {} }]
|
|
206
|
+
})
|
|
207
|
+
const digestNode = WABinary_1.getBinaryNodeChild(res, 'digest')
|
|
208
|
+
if (!digestNode) {
|
|
209
|
+
await uploadPreKeys()
|
|
210
|
+
throw new Error('encrypt/get digest returned no digest node')
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
// Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
|
|
214
|
+
const rotateSignedPreKey = async () => {
|
|
215
|
+
const newId = (creds.signedPreKey.keyId || 0) + 1
|
|
216
|
+
const skey = await Utils_1.signedKeyPair(creds.signedIdentityKey, newId)
|
|
217
|
+
await query({
|
|
218
|
+
tag: 'iq',
|
|
219
|
+
attrs: { to: WABinary_1.S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
|
|
220
|
+
content: [
|
|
221
|
+
{
|
|
222
|
+
tag: 'rotate',
|
|
223
|
+
attrs: {},
|
|
224
|
+
content: [Utils_1.xmppSignedPreKey(skey)]
|
|
225
|
+
}
|
|
226
|
+
]
|
|
227
|
+
})
|
|
228
|
+
// Persist new signed pre-key in creds
|
|
229
|
+
ev.emit('creds.update', { signedPreKey: skey })
|
|
230
|
+
}
|
|
231
|
+
const executeUSyncQuery = async (usyncQuery) => {
|
|
232
|
+
if (usyncQuery.protocols.length === 0) {
|
|
233
|
+
throw new boom_1.Boom('USyncQuery must have at least one protocol')
|
|
234
|
+
}
|
|
235
|
+
// todo: validate users, throw WARNING on no valid users
|
|
236
|
+
// variable below has only validated users
|
|
237
|
+
const validUsers = usyncQuery.users
|
|
238
|
+
const userNodes = validUsers.map(user => {
|
|
239
|
+
return {
|
|
240
|
+
tag: 'user',
|
|
241
|
+
attrs: {
|
|
242
|
+
jid: !user.phone ? user.id : undefined
|
|
243
|
+
},
|
|
244
|
+
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
const listNode = {
|
|
248
|
+
tag: 'list',
|
|
249
|
+
attrs: {},
|
|
250
|
+
content: userNodes
|
|
251
|
+
}
|
|
252
|
+
const queryNode = {
|
|
253
|
+
tag: 'query',
|
|
254
|
+
attrs: {},
|
|
255
|
+
content: usyncQuery.protocols.map(a => a.getQueryElement())
|
|
256
|
+
}
|
|
257
|
+
const iq = {
|
|
258
|
+
tag: 'iq',
|
|
259
|
+
attrs: {
|
|
260
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
261
|
+
type: 'get',
|
|
262
|
+
xmlns: 'usync'
|
|
263
|
+
},
|
|
264
|
+
content: [
|
|
265
|
+
{
|
|
266
|
+
tag: 'usync',
|
|
267
|
+
attrs: {
|
|
268
|
+
context: usyncQuery.context,
|
|
269
|
+
mode: usyncQuery.mode,
|
|
270
|
+
sid: generateMessageTag(),
|
|
271
|
+
last: 'true',
|
|
272
|
+
index: '0'
|
|
273
|
+
},
|
|
274
|
+
content: [queryNode, listNode]
|
|
275
|
+
}
|
|
276
|
+
]
|
|
277
|
+
}
|
|
278
|
+
const result = await query(iq)
|
|
279
|
+
return usyncQuery.parseUSyncQueryResult(result)
|
|
280
|
+
}
|
|
281
|
+
const onWhatsApp = async (...phoneNumber) => {
|
|
282
|
+
let usyncQuery = new USyncQuery_1.USyncQuery()
|
|
283
|
+
let contactEnabled = false
|
|
284
|
+
for (const jid of phoneNumber) {
|
|
285
|
+
if (WABinary_1.isLidUser(jid)) {
|
|
286
|
+
logger?.warn('LIDs are not supported with onWhatsApp')
|
|
287
|
+
continue
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
if (!contactEnabled) {
|
|
291
|
+
contactEnabled = true
|
|
292
|
+
usyncQuery = usyncQuery.withContactProtocol()
|
|
293
|
+
}
|
|
294
|
+
const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`
|
|
295
|
+
usyncQuery.withUser(new USyncUser_1.USyncUser().withPhone(phone))
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (usyncQuery.users.length === 0) {
|
|
299
|
+
return [] // return early without forcing an empty query
|
|
300
|
+
}
|
|
301
|
+
const results = await executeUSyncQuery(usyncQuery)
|
|
302
|
+
if (results) {
|
|
303
|
+
return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }))
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const pnFromLIDUSync = async (jids) => {
|
|
307
|
+
const usyncQuery = new USyncQuery_1.USyncQuery().withLIDProtocol().withContext('background')
|
|
308
|
+
for (const jid of jids) {
|
|
309
|
+
if (WABinary_1.isLidUser(jid)) {
|
|
310
|
+
logger?.warn('LID user found in LID fetch call')
|
|
311
|
+
continue
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
usyncQuery.withUser(new USyncUser_1.USyncUser().withId(jid))
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (usyncQuery.users.length === 0) {
|
|
318
|
+
return [] // return early without forcing an empty query
|
|
319
|
+
}
|
|
320
|
+
const results = await executeUSyncQuery(usyncQuery)
|
|
321
|
+
if (results) {
|
|
322
|
+
return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }))
|
|
323
|
+
}
|
|
324
|
+
return []
|
|
325
|
+
}
|
|
326
|
+
// Initialize signalRepository after pnFromLIDUSync is defined
|
|
327
|
+
initSignalRepository()
|
|
328
|
+
/** connection handshake */
|
|
329
|
+
const validateConnection = async () => {
|
|
330
|
+
let helloMsg = {
|
|
331
|
+
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg)
|
|
335
|
+
logger.info({ browser, helloMsg }, 'connected to WA')
|
|
336
|
+
|
|
337
|
+
const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish()
|
|
338
|
+
const result = await awaitNextMessage(init)
|
|
339
|
+
const handshake = WAProto_1.proto.HandshakeMessage.decode(result)
|
|
340
|
+
|
|
341
|
+
logger.trace({ handshake }, 'handshake recv from WA')
|
|
342
|
+
|
|
343
|
+
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey)
|
|
344
|
+
let node
|
|
345
|
+
|
|
346
|
+
if (!creds.me) {
|
|
347
|
+
node = Utils_1.generateRegistrationNode(creds, config)
|
|
348
|
+
logger.info({ node }, 'not logged in, attempting registration...')
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
else {
|
|
352
|
+
node = Utils_1.generateLoginNode(creds.me.id, config)
|
|
353
|
+
logger.info({ node }, 'logging in...')
|
|
354
|
+
}
|
|
355
|
+
const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish())
|
|
356
|
+
|
|
357
|
+
await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
|
|
358
|
+
clientFinish: {
|
|
359
|
+
static: keyEnc,
|
|
360
|
+
payload: payloadEnc,
|
|
361
|
+
},
|
|
362
|
+
}).finish())
|
|
363
|
+
noise.finishInit()
|
|
364
|
+
startKeepAliveRequest()
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const getAvailablePreKeysOnServer = async () => {
|
|
368
|
+
const result = await query({
|
|
369
|
+
tag: 'iq',
|
|
370
|
+
attrs: {
|
|
371
|
+
id: generateMessageTag(),
|
|
372
|
+
xmlns: 'encrypt',
|
|
373
|
+
type: 'get',
|
|
374
|
+
to: WABinary_1.S_WHATSAPP_NET
|
|
375
|
+
},
|
|
376
|
+
content: [
|
|
377
|
+
{ tag: 'count', attrs: {} }
|
|
378
|
+
]
|
|
379
|
+
})
|
|
380
|
+
|
|
381
|
+
const countChild = WABinary_1.getBinaryNodeChild(result, 'count')
|
|
382
|
+
|
|
383
|
+
return +countChild.attrs.value
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** generates and uploads a set of pre-keys to the server */
|
|
387
|
+
const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
|
|
388
|
+
await keys.transaction(async () => {
|
|
389
|
+
logger.info({ count }, 'uploading pre-keys')
|
|
390
|
+
const { update, node } = await Utils_1.getNextPreKeysNode({ creds, keys }, count)
|
|
391
|
+
await query(node)
|
|
392
|
+
ev.emit('creds.update', update)
|
|
393
|
+
logger.info({ count }, 'uploaded pre-keys')
|
|
394
|
+
})
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
398
|
+
const preKeyCount = await getAvailablePreKeysOnServer()
|
|
399
|
+
logger.info(`${preKeyCount} pre-keys found on server`)
|
|
400
|
+
|
|
401
|
+
if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
|
|
402
|
+
await uploadPreKeys()
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const onMessageReceived = async (data) => {
|
|
407
|
+
await noise.decodeFrame(data, frame => {
|
|
408
|
+
// reset ping timeout
|
|
409
|
+
lastDateRecv = new Date()
|
|
410
|
+
let anyTriggered = false
|
|
411
|
+
anyTriggered = ws.emit('frame', frame)
|
|
412
|
+
|
|
413
|
+
// if it's a binary node
|
|
414
|
+
if (!(frame instanceof Uint8Array)) {
|
|
415
|
+
const msgId = frame.attrs.id
|
|
416
|
+
|
|
417
|
+
if (logger.level === 'trace') {
|
|
418
|
+
logger.trace({ xml: WABinary_1.binaryNodeToString(frame), msg: 'recv xml' })
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/* Check if this is a response to a message we sent */
|
|
422
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
|
|
423
|
+
|
|
424
|
+
/* Check if this is a response to a message we are expecting */
|
|
425
|
+
const l0 = frame.tag
|
|
426
|
+
const l1 = frame.attrs || {}
|
|
427
|
+
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
|
|
428
|
+
|
|
429
|
+
for (const key of Object.keys(l1)) {
|
|
430
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
|
|
431
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
|
|
432
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
|
|
436
|
+
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
|
|
437
|
+
|
|
438
|
+
if (!anyTriggered && logger.level === 'debug') {
|
|
439
|
+
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
})
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const end = (error) => {
|
|
446
|
+
if (closed) {
|
|
447
|
+
logger.trace({ trace: error?.stack }, 'connection already closed')
|
|
448
|
+
return
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
closed = true
|
|
452
|
+
|
|
453
|
+
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
|
|
454
|
+
clearInterval(keepAliveReq)
|
|
455
|
+
clearTimeout(qrTimer)
|
|
456
|
+
ws.removeAllListeners('close')
|
|
457
|
+
ws.removeAllListeners('open')
|
|
458
|
+
ws.removeAllListeners('message')
|
|
459
|
+
|
|
460
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
461
|
+
try {
|
|
462
|
+
ws.close()
|
|
463
|
+
}
|
|
464
|
+
catch (_a) { }
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
ev.emit('connection.update', {
|
|
468
|
+
connection: 'close',
|
|
469
|
+
lastDisconnect: {
|
|
470
|
+
error,
|
|
471
|
+
date: new Date()
|
|
472
|
+
}
|
|
473
|
+
})
|
|
474
|
+
|
|
475
|
+
ev.removeAllListeners('connection.update')
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const waitForSocketOpen = async () => {
|
|
479
|
+
if (ws.isOpen) {
|
|
480
|
+
return
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
if (ws.isClosed || ws.isClosing) {
|
|
484
|
+
throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed })
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
let onOpen
|
|
488
|
+
let onClose
|
|
489
|
+
|
|
490
|
+
await new Promise((resolve, reject) => {
|
|
491
|
+
onOpen = () => resolve(undefined)
|
|
492
|
+
onClose = mapWebSocketError(reject)
|
|
493
|
+
ws.on('open', onOpen)
|
|
494
|
+
ws.on('close', onClose)
|
|
495
|
+
ws.on('error', onClose)
|
|
496
|
+
}).finally(() => {
|
|
497
|
+
ws.off('open', onOpen)
|
|
498
|
+
ws.off('close', onClose)
|
|
499
|
+
ws.off('error', onClose)
|
|
500
|
+
})
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
|
|
504
|
+
if (!lastDateRecv) {
|
|
505
|
+
lastDateRecv = new Date()
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const diff = Date.now() - lastDateRecv.getTime()
|
|
509
|
+
|
|
510
|
+
/*
|
|
511
|
+
check if it's been a suspicious amount of time since the server responded with our last seen
|
|
512
|
+
it could be that the network is down
|
|
513
|
+
*/
|
|
514
|
+
if (diff > keepAliveIntervalMs + 5000) {
|
|
515
|
+
end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }))
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
else if (ws.isOpen) {
|
|
519
|
+
// if its all good, send a keep alive request
|
|
520
|
+
query({
|
|
521
|
+
tag: 'iq',
|
|
522
|
+
attrs: {
|
|
523
|
+
id: generateMessageTag(),
|
|
524
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
525
|
+
type: 'get',
|
|
526
|
+
xmlns: 'w:p',
|
|
527
|
+
},
|
|
528
|
+
content: [{ tag: 'ping', attrs: {} }]
|
|
529
|
+
}).catch(err => {
|
|
530
|
+
logger.error({ trace: err.stack }, 'error in sending keep alive')
|
|
531
|
+
})
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
else {
|
|
535
|
+
logger.warn('keep alive called when WS not open')
|
|
536
|
+
}
|
|
537
|
+
}, keepAliveIntervalMs))
|
|
538
|
+
|
|
539
|
+
/** i have no idea why this exists. pls enlighten me */
|
|
540
|
+
const sendPassiveIq = (tag) => (query({
|
|
541
|
+
tag: 'iq',
|
|
542
|
+
attrs: {
|
|
543
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
544
|
+
xmlns: 'passive',
|
|
545
|
+
type: 'set',
|
|
546
|
+
},
|
|
547
|
+
content: [
|
|
548
|
+
{ tag, attrs: {} }
|
|
549
|
+
]
|
|
550
|
+
}))
|
|
551
|
+
|
|
552
|
+
/** logout & invalidate connection */
|
|
553
|
+
const logout = async (msg) => {
|
|
554
|
+
const jid = authState.creds.me?.id
|
|
555
|
+
|
|
556
|
+
if (jid) {
|
|
557
|
+
await sendNode({
|
|
558
|
+
tag: 'iq',
|
|
559
|
+
attrs: {
|
|
560
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
561
|
+
type: 'set',
|
|
562
|
+
id: generateMessageTag(),
|
|
563
|
+
xmlns: 'md'
|
|
564
|
+
},
|
|
565
|
+
content: [
|
|
566
|
+
{
|
|
567
|
+
tag: 'remove-companion-device',
|
|
568
|
+
attrs: {
|
|
569
|
+
jid,
|
|
570
|
+
reason: 'user_initiated'
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
]
|
|
574
|
+
})
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }))
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const requestPairingCode = async (phoneNumber, pairKey = "ONIMAIII") => {
|
|
581
|
+
const forcedCode = (pairKey || 'ONIMAIII').toUpperCase()
|
|
582
|
+
if (forcedCode.length !== 8) {
|
|
583
|
+
throw new Error('Custom pairing code must be exactly 8 chars')
|
|
584
|
+
}
|
|
585
|
+
authState.creds.pairingCode = forcedCode
|
|
586
|
+
authState.creds.me = {
|
|
587
|
+
id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
|
|
588
|
+
name: '~'
|
|
589
|
+
};
|
|
590
|
+
ev.emit('creds.update', authState.creds);
|
|
591
|
+
await sendNode({
|
|
592
|
+
tag: 'iq',
|
|
593
|
+
attrs: {
|
|
594
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
595
|
+
type: 'set',
|
|
596
|
+
id: generateMessageTag(),
|
|
597
|
+
xmlns: 'md'
|
|
598
|
+
},
|
|
599
|
+
content: [
|
|
600
|
+
{
|
|
601
|
+
tag: 'link_code_companion_reg',
|
|
602
|
+
attrs: {
|
|
603
|
+
jid: authState.creds.me.id,
|
|
604
|
+
stage: 'companion_hello',
|
|
605
|
+
// eslint-disable-next-line camelcase
|
|
606
|
+
should_show_push_notification: 'true'
|
|
607
|
+
},
|
|
608
|
+
content: [
|
|
609
|
+
{
|
|
610
|
+
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
611
|
+
attrs: {},
|
|
612
|
+
content: await generatePairingKey()
|
|
613
|
+
},
|
|
614
|
+
{
|
|
615
|
+
tag: 'companion_server_auth_key_pub',
|
|
616
|
+
attrs: {},
|
|
617
|
+
content: authState.creds.noiseKey.public
|
|
618
|
+
},
|
|
619
|
+
{
|
|
620
|
+
tag: 'companion_platform_id',
|
|
621
|
+
attrs: {},
|
|
622
|
+
content: (0, Utils_1.getPlatformId)(browser[1])
|
|
623
|
+
},
|
|
624
|
+
{
|
|
625
|
+
tag: 'companion_platform_display',
|
|
626
|
+
attrs: {},
|
|
627
|
+
content: `${browser[1]} (${browser[0]})`
|
|
628
|
+
},
|
|
629
|
+
{
|
|
630
|
+
tag: 'link_code_pairing_nonce',
|
|
631
|
+
attrs: {},
|
|
632
|
+
content: '0'
|
|
633
|
+
}
|
|
634
|
+
]
|
|
635
|
+
}
|
|
636
|
+
]
|
|
637
|
+
});
|
|
638
|
+
return authState.creds.pairingCode;
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
async function generatePairingKey() {
|
|
642
|
+
const salt = crypto_1.randomBytes(32)
|
|
643
|
+
const randomIv = crypto_1.randomBytes(16)
|
|
644
|
+
const key = await Utils_1.derivePairingCodeKey(authState.creds.pairingCode, salt)
|
|
645
|
+
const ciphered = Utils_1.aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
|
|
646
|
+
|
|
647
|
+
return Buffer.concat([salt, randomIv, ciphered])
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const sendWAMBuffer = (wamBuffer) => {
|
|
651
|
+
return query({
|
|
652
|
+
tag: 'iq',
|
|
653
|
+
attrs: {
|
|
654
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
655
|
+
id: generateMessageTag(),
|
|
656
|
+
xmlns: 'w:stats'
|
|
657
|
+
},
|
|
658
|
+
content: [
|
|
659
|
+
{
|
|
660
|
+
tag: 'add',
|
|
661
|
+
attrs: { t: Math.round(Date.now() / 1000) + '' },
|
|
662
|
+
content: wamBuffer
|
|
663
|
+
}
|
|
664
|
+
]
|
|
665
|
+
})
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
ws.on('message', onMessageReceived)
|
|
669
|
+
|
|
670
|
+
ws.on('open', async () => {
|
|
671
|
+
try {
|
|
672
|
+
await validateConnection()
|
|
673
|
+
}
|
|
674
|
+
catch (err) {
|
|
675
|
+
logger.error({ err }, 'error in validating connection')
|
|
676
|
+
end(err)
|
|
677
|
+
}
|
|
678
|
+
})
|
|
679
|
+
|
|
680
|
+
ws.on('error', mapWebSocketError(end))
|
|
681
|
+
|
|
682
|
+
ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })))
|
|
683
|
+
|
|
684
|
+
// the server terminated the connection
|
|
685
|
+
ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })))
|
|
686
|
+
|
|
687
|
+
// QR gen
|
|
688
|
+
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
689
|
+
const iq = {
|
|
690
|
+
tag: 'iq',
|
|
691
|
+
attrs: {
|
|
692
|
+
to: WABinary_1.S_WHATSAPP_NET,
|
|
693
|
+
type: 'result',
|
|
694
|
+
id: stanza.attrs.id,
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
await sendNode(iq)
|
|
699
|
+
|
|
700
|
+
const pairDeviceNode = WABinary_1.getBinaryNodeChild(stanza, 'pair-device')
|
|
701
|
+
const refNodes = WABinary_1.getBinaryNodeChildren(pairDeviceNode, 'ref')
|
|
702
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
|
|
703
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
|
|
704
|
+
const advB64 = creds.advSecretKey
|
|
705
|
+
|
|
706
|
+
let qrMs = qrTimeout || 60000 // time to let a QR live
|
|
707
|
+
|
|
708
|
+
const genPairQR = () => {
|
|
709
|
+
if (!ws.isOpen) {
|
|
710
|
+
return
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const refNode = refNodes.shift()
|
|
714
|
+
|
|
715
|
+
if (!refNode) {
|
|
716
|
+
end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }))
|
|
717
|
+
return
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
const ref = refNode.content.toString('utf-8')
|
|
721
|
+
const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',')
|
|
722
|
+
|
|
723
|
+
ev.emit('connection.update', { qr })
|
|
724
|
+
qrTimer = setTimeout(genPairQR, qrMs)
|
|
725
|
+
qrMs = qrTimeout || 20000 // shorter subsequent qrs
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
genPairQR()
|
|
729
|
+
})
|
|
730
|
+
|
|
731
|
+
// device paired for the first time
|
|
732
|
+
// if device pairs successfully, the server asks to restart the connection
|
|
733
|
+
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
734
|
+
logger.debug('pair success recv')
|
|
735
|
+
try {
|
|
736
|
+
const { reply, creds: updatedCreds } = Utils_1.configureSuccessfulPairing(stanza, creds)
|
|
737
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...')
|
|
738
|
+
|
|
739
|
+
ev.emit('creds.update', updatedCreds)
|
|
740
|
+
ev.emit('connection.update', { isNewLogin: true, qr: undefined })
|
|
741
|
+
|
|
742
|
+
await sendNode(reply)
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
catch (error) {
|
|
746
|
+
logger.info({ trace: error.stack }, 'error in pairing')
|
|
747
|
+
end(error)
|
|
748
|
+
}
|
|
749
|
+
})
|
|
750
|
+
|
|
751
|
+
// login complete
|
|
752
|
+
ws.on('CB:success', async (node) => {
|
|
753
|
+
try {
|
|
754
|
+
await uploadPreKeysToServerIfRequired()
|
|
755
|
+
await sendPassiveIq('active')
|
|
756
|
+
// After successful login, validate our key-bundle against server
|
|
757
|
+
try {
|
|
758
|
+
await digestKeyBundle()
|
|
759
|
+
}
|
|
760
|
+
catch (e) {
|
|
761
|
+
logger.warn({ e }, 'failed to run digest after login')
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
catch (err) {
|
|
765
|
+
logger.warn({ err }, 'failed to send initial passive iq')
|
|
766
|
+
}
|
|
767
|
+
logger.info('opened connection to WA')
|
|
768
|
+
clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
|
|
769
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
|
|
770
|
+
ev.emit('connection.update', { connection: 'open' })
|
|
771
|
+
if (node.attrs.lid && authState.creds.me?.id) {
|
|
772
|
+
const myLID = node.attrs.lid
|
|
773
|
+
process.nextTick(async () => {
|
|
774
|
+
try {
|
|
775
|
+
const myPN = authState.creds.me.id
|
|
776
|
+
// Store our own LID-PN mapping
|
|
777
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }])
|
|
778
|
+
// Create device list for our own user (needed for bulk migration)
|
|
779
|
+
const { user, device } = WABinary_1.jidDecode(myPN)
|
|
780
|
+
await authState.keys.set({
|
|
781
|
+
'device-list': {
|
|
782
|
+
[user]: [device?.toString() || '0']
|
|
783
|
+
}
|
|
784
|
+
})
|
|
785
|
+
// migrate our own session
|
|
786
|
+
await signalRepository.migrateSession(myPN, myLID)
|
|
787
|
+
logger.info({ myPN, myLID }, 'Own LID session created successfully')
|
|
788
|
+
}
|
|
789
|
+
catch (error) {
|
|
790
|
+
logger.error({ error, lid: myLID }, 'Failed to create own LID session')
|
|
791
|
+
}
|
|
792
|
+
})
|
|
793
|
+
}
|
|
794
|
+
})
|
|
795
|
+
|
|
796
|
+
ws.on('CB:stream:error', (node) => {
|
|
797
|
+
const [reasonNode] = WABinary_1.getAllBinaryNodeChildren(node)
|
|
798
|
+
logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out')
|
|
799
|
+
const { reason, statusCode } = Utils_1.getErrorCodeFromStreamError(node)
|
|
800
|
+
end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }))
|
|
801
|
+
})
|
|
802
|
+
|
|
803
|
+
// stream fail, possible logout
|
|
804
|
+
ws.on('CB:failure', (node) => {
|
|
805
|
+
const reason = +(node.attrs.reason || 500)
|
|
806
|
+
|
|
807
|
+
end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
|
|
808
|
+
})
|
|
809
|
+
|
|
810
|
+
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
811
|
+
end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }))
|
|
812
|
+
})
|
|
813
|
+
|
|
814
|
+
ws.on('CB:ib,,offline_preview', async (node) => {
|
|
815
|
+
logger.info('offline preview received', JSON.stringify(node))
|
|
816
|
+
await sendNode({
|
|
817
|
+
tag: 'ib',
|
|
818
|
+
attrs: {},
|
|
819
|
+
content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
|
|
820
|
+
})
|
|
821
|
+
})
|
|
822
|
+
|
|
823
|
+
ws.on('CB:ib,,edge_routing', (node) => {
|
|
824
|
+
const edgeRoutingNode = WABinary_1.getBinaryNodeChild(node, 'edge_routing')
|
|
825
|
+
const routingInfo = WABinary_1.getBinaryNodeChild(edgeRoutingNode, 'routing_info')
|
|
826
|
+
|
|
827
|
+
if (routingInfo?.content) {
|
|
828
|
+
authState.creds.routingInfo = Buffer.from(routingInfo?.content)
|
|
829
|
+
ev.emit('creds.update', authState.creds)
|
|
830
|
+
}
|
|
831
|
+
})
|
|
832
|
+
|
|
833
|
+
let didStartBuffer = false
|
|
834
|
+
|
|
835
|
+
process.nextTick(() => {
|
|
836
|
+
if (creds.me?.id) {
|
|
837
|
+
// start buffering important events
|
|
838
|
+
// if we're logged in
|
|
839
|
+
ev.buffer()
|
|
840
|
+
didStartBuffer = true
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
|
|
844
|
+
})
|
|
845
|
+
|
|
846
|
+
// called when all offline notifs are handled
|
|
847
|
+
ws.on('CB:ib,,offline', (node) => {
|
|
848
|
+
const child = WABinary_1.getBinaryNodeChild(node, 'offline')
|
|
849
|
+
const offlineNotifs = +(child?.attrs.count || 0)
|
|
850
|
+
|
|
851
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`)
|
|
852
|
+
|
|
853
|
+
if (didStartBuffer) {
|
|
854
|
+
ev.flush()
|
|
855
|
+
logger.trace('flushed events for initial buffer')
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
ev.emit('connection.update', { receivedPendingNotifications: true })
|
|
859
|
+
})
|
|
860
|
+
|
|
861
|
+
// update credentials when required
|
|
862
|
+
ev.on('creds.update', update => {
|
|
863
|
+
const name = update.me?.name
|
|
864
|
+
|
|
865
|
+
// if name has just been received
|
|
866
|
+
if (creds.me?.name !== name) {
|
|
867
|
+
logger.debug({ name }, 'updated pushName')
|
|
868
|
+
|
|
869
|
+
sendNode({
|
|
870
|
+
tag: 'presence',
|
|
871
|
+
attrs: { name }
|
|
872
|
+
}).catch(err => {
|
|
873
|
+
logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
|
|
874
|
+
})
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
Object.assign(creds, update)
|
|
878
|
+
})
|
|
879
|
+
|
|
880
|
+
if (printQRInTerminal) {
|
|
881
|
+
Utils_1.printQRIfNecessaryListener(ev, logger)
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
return {
|
|
885
|
+
type: 'md',
|
|
886
|
+
ws,
|
|
887
|
+
ev,
|
|
888
|
+
authState: { creds, keys },
|
|
889
|
+
signalRepository,
|
|
890
|
+
get user() {
|
|
891
|
+
return authState.creds.me
|
|
892
|
+
},
|
|
893
|
+
generateMessageTag,
|
|
894
|
+
query,
|
|
895
|
+
waitForMessage,
|
|
896
|
+
waitForSocketOpen,
|
|
897
|
+
sendRawMessage,
|
|
898
|
+
sendNode,
|
|
899
|
+
logout,
|
|
900
|
+
end,
|
|
901
|
+
onUnexpectedError,
|
|
902
|
+
uploadPreKeys,
|
|
903
|
+
uploadPreKeysToServerIfRequired,
|
|
904
|
+
digestKeyBundle,
|
|
905
|
+
rotateSignedPreKey,
|
|
906
|
+
requestPairingCode,
|
|
907
|
+
wamBuffer: publicWAMBuffer,
|
|
908
|
+
/** Waits for the connection to WA to reach a state */
|
|
909
|
+
waitForConnectionUpdate: Utils_1.bindWaitForConnectionUpdate(ev),
|
|
910
|
+
sendWAMBuffer,
|
|
911
|
+
executeUSyncQuery,
|
|
912
|
+
onWhatsApp
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* map the websocket error to the right type
|
|
918
|
+
* so it can be retried by the caller
|
|
919
|
+
* */
|
|
920
|
+
function mapWebSocketError(handler) {
|
|
921
|
+
return (error) => {
|
|
922
|
+
handler(new boom_1.Boom(`WebSocket Error (${error?.message})`, { statusCode: Utils_1.getCodeFromWSError(error), data: error }))
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
module.exports = {
|
|
927
|
+
makeSocket
|
|
928
|
+
}
|