gifted-baileys 1.5.6 → 1.5.7
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/README.md +9 -0
- package/WAProto/WAProto.proto +969 -88
- package/WAProto/index.d.ts +13199 -1260
- package/WAProto/index.js +124901 -74525
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.d.ts +284 -0
- package/{src → lib}/Defaults/index.js +7 -14
- package/lib/Signal/libsignal.d.ts +3 -0
- package/lib/Signal/libsignal.js +161 -0
- package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/{src → lib}/Socket/Client/index.js +2 -3
- 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 +17 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.d.ts +12 -0
- package/lib/Socket/Client/websocket.js +62 -0
- package/lib/Socket/business.d.ts +170 -0
- package/{src → lib}/Socket/business.js +28 -33
- package/lib/Socket/chats.d.ts +81 -0
- package/{src → lib}/Socket/chats.js +174 -176
- package/lib/Socket/groups.d.ts +115 -0
- package/{src → lib}/Socket/groups.js +80 -68
- package/lib/Socket/index.d.ts +172 -0
- package/{src → lib}/Socket/index.js +4 -1
- package/lib/Socket/messages-recv.d.ts +158 -0
- package/{src → lib}/Socket/messages-recv.js +378 -211
- package/lib/Socket/messages-send.d.ts +155 -0
- package/{src → lib}/Socket/messages-send.js +452 -177
- package/lib/Socket/newsletter.d.ts +132 -0
- package/{src → lib}/Socket/newsletter.js +107 -98
- package/lib/Socket/registration.d.ts +264 -0
- package/{src → lib}/Socket/registration.js +56 -48
- package/lib/Socket/socket.d.ts +44 -0
- package/{src → lib}/Socket/socket.js +77 -77
- package/lib/Socket/usync.d.ts +37 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.d.ts +3 -0
- package/lib/Store/make-cache-manager-store.d.ts +14 -0
- package/{src → lib}/Store/make-cache-manager-store.js +25 -34
- package/lib/Store/make-in-memory-store.d.ts +118 -0
- package/{src → lib}/Store/make-in-memory-store.js +36 -32
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/{src → lib}/Store/object-repository.js +1 -1
- package/lib/Types/Auth.d.ts +109 -0
- package/lib/Types/Call.d.ts +13 -0
- package/lib/Types/Chat.d.ts +107 -0
- package/{src/Types/Contact.ts → lib/Types/Contact.d.ts} +8 -9
- package/lib/Types/Events.d.ts +172 -0
- package/lib/Types/GroupMetadata.d.ts +56 -0
- package/lib/Types/Label.d.ts +46 -0
- package/{src/Types/LabelAssociation.ts → lib/Types/LabelAssociation.d.ts} +16 -22
- package/lib/Types/Message.d.ts +433 -0
- package/lib/Types/Newsletter.d.ts +92 -0
- package/lib/Types/Product.d.ts +78 -0
- package/lib/Types/Signal.d.ts +57 -0
- package/{src/Types/Socket.ts → lib/Types/Socket.d.ts} +61 -68
- package/lib/Types/State.d.ts +27 -0
- package/lib/Types/USync.d.ts +25 -0
- package/lib/Types/index.d.ts +66 -0
- package/lib/Utils/auth-utils.d.ts +18 -0
- package/{src → lib}/Utils/auth-utils.js +73 -90
- package/lib/Utils/baileys-event-stream.d.ts +16 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.d.ts +22 -0
- package/{src → lib}/Utils/business.js +15 -43
- package/lib/Utils/chat-utils.d.ts +70 -0
- package/{src → lib}/Utils/chat-utils.js +87 -94
- package/lib/Utils/crypto.d.ts +40 -0
- package/{src → lib}/Utils/crypto.js +4 -2
- package/lib/Utils/decode-wa-message.d.ts +36 -0
- package/lib/Utils/decode-wa-message.js +226 -0
- package/lib/Utils/event-buffer.d.ts +35 -0
- package/{src → lib}/Utils/event-buffer.js +4 -13
- package/lib/Utils/generics.d.ts +88 -0
- package/{src → lib}/Utils/generics.js +67 -86
- package/lib/Utils/history.d.ts +19 -0
- package/{src → lib}/Utils/history.js +13 -39
- package/lib/Utils/index.d.ts +17 -0
- package/lib/Utils/link-preview.d.ts +21 -0
- package/{src → lib}/Utils/link-preview.js +17 -54
- package/lib/Utils/logger.d.ts +2 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/{src → lib}/Utils/make-mutex.js +4 -13
- package/lib/Utils/messages-media.d.ts +113 -0
- package/{src → lib}/Utils/messages-media.js +193 -255
- package/lib/Utils/messages.d.ts +77 -0
- package/{src → lib}/Utils/messages.js +588 -118
- package/lib/Utils/noise-handler.d.ts +20 -0
- package/lib/Utils/process-message.d.ts +41 -0
- package/{src → lib}/Utils/process-message.js +27 -30
- package/lib/Utils/signal.d.ts +33 -0
- package/{src → lib}/Utils/signal.js +25 -42
- package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
- package/{src → lib}/Utils/use-multi-file-auth-state.js +27 -28
- package/lib/Utils/validate-connection.d.ts +11 -0
- package/{src → lib}/Utils/validate-connection.js +40 -9
- package/lib/WABinary/constants.d.ts +27 -0
- package/lib/WABinary/decode.d.ts +6 -0
- package/lib/WABinary/encode.d.ts +2 -0
- package/{src → lib}/WABinary/encode.js +16 -10
- package/lib/WABinary/generic-utils.d.ts +14 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/jid-utils.d.ts +31 -0
- package/lib/WABinary/types.d.ts +18 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +8 -0
- package/lib/WAM/constants.d.ts +38 -0
- package/lib/WAM/encode.d.ts +2 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/index.d.ts +4 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.d.ts +26 -0
- package/lib/WAUSync/USyncQuery.js +79 -0
- package/lib/WAUSync/USyncUser.d.ts +10 -0
- package/lib/WAUSync/USyncUser.js +22 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +19 -0
- package/{src → lib}/index.js +1 -0
- package/package.json +26 -8
- package/LICENSE +0 -21
- package/src/Defaults/baileys-version.json +0 -3
- package/src/Defaults/index.ts +0 -131
- package/src/README.md +0 -1
- package/src/Signal/libsignal.js +0 -180
- package/src/Signal/libsignal.ts +0 -141
- package/src/Socket/Client/abstract-socket-client.ts +0 -19
- package/src/Socket/Client/index.ts +0 -3
- package/src/Socket/Client/mobile-socket-client.js +0 -78
- package/src/Socket/Client/mobile-socket-client.ts +0 -66
- package/src/Socket/Client/web-socket-client.js +0 -75
- package/src/Socket/Client/web-socket-client.ts +0 -57
- package/src/Socket/business.ts +0 -281
- package/src/Socket/chats.ts +0 -1030
- package/src/Socket/groups.ts +0 -356
- package/src/Socket/index.ts +0 -13
- package/src/Socket/messages-recv.ts +0 -985
- package/src/Socket/messages-send.ts +0 -871
- package/src/Socket/newsletter.ts +0 -282
- package/src/Socket/registration.ts +0 -250
- package/src/Socket/socket.ts +0 -777
- package/src/Store/index.ts +0 -3
- package/src/Store/make-cache-manager-store.ts +0 -100
- package/src/Store/make-in-memory-store.ts +0 -475
- package/src/Store/make-ordered-dictionary.ts +0 -86
- package/src/Store/object-repository.ts +0 -32
- package/src/Tests/test.app-state-sync.js +0 -204
- package/src/Tests/test.app-state-sync.ts +0 -207
- package/src/Tests/test.event-buffer.js +0 -270
- package/src/Tests/test.event-buffer.ts +0 -319
- package/src/Tests/test.key-store.js +0 -76
- package/src/Tests/test.key-store.ts +0 -92
- package/src/Tests/test.libsignal.js +0 -141
- package/src/Tests/test.libsignal.ts +0 -186
- package/src/Tests/test.media-download.js +0 -93
- package/src/Tests/test.media-download.ts +0 -76
- package/src/Tests/test.messages.js +0 -33
- package/src/Tests/test.messages.ts +0 -37
- package/src/Tests/utils.js +0 -34
- package/src/Tests/utils.ts +0 -36
- package/src/Types/Auth.ts +0 -113
- package/src/Types/Call.ts +0 -15
- package/src/Types/Chat.ts +0 -106
- package/src/Types/Events.ts +0 -93
- package/src/Types/GroupMetadata.ts +0 -53
- package/src/Types/Label.ts +0 -36
- package/src/Types/Message.ts +0 -288
- package/src/Types/Newsletter.ts +0 -98
- package/src/Types/Product.ts +0 -85
- package/src/Types/Signal.ts +0 -68
- package/src/Types/State.ts +0 -29
- package/src/Types/index.ts +0 -59
- package/src/Utils/auth-utils.ts +0 -222
- package/src/Utils/baileys-event-stream.js +0 -92
- package/src/Utils/baileys-event-stream.ts +0 -66
- package/src/Utils/business.ts +0 -275
- package/src/Utils/chat-utils.ts +0 -860
- package/src/Utils/crypto.ts +0 -131
- package/src/Utils/decode-wa-message.js +0 -211
- package/src/Utils/decode-wa-message.ts +0 -228
- package/src/Utils/event-buffer.ts +0 -613
- package/src/Utils/generics.ts +0 -434
- package/src/Utils/history.ts +0 -112
- package/src/Utils/index.ts +0 -17
- package/src/Utils/link-preview.ts +0 -122
- package/src/Utils/logger.ts +0 -3
- package/src/Utils/lt-hash.ts +0 -61
- package/src/Utils/make-mutex.ts +0 -44
- package/src/Utils/messages-media.ts +0 -847
- package/src/Utils/messages.ts +0 -956
- package/src/Utils/noise-handler.ts +0 -197
- package/src/Utils/process-message.ts +0 -414
- package/src/Utils/signal.ts +0 -177
- package/src/Utils/use-multi-file-auth-state.ts +0 -90
- package/src/Utils/validate-connection.ts +0 -238
- package/src/WABinary/constants.ts +0 -42
- package/src/WABinary/decode.ts +0 -265
- package/src/WABinary/encode.ts +0 -236
- package/src/WABinary/generic-utils.ts +0 -121
- package/src/WABinary/index.ts +0 -5
- package/src/WABinary/jid-utils.ts +0 -68
- package/src/WABinary/types.ts +0 -17
- package/src/WAM/BinaryInfo.ts +0 -12
- package/src/WAM/constants.ts +0 -15382
- package/src/WAM/encode.ts +0 -174
- package/src/WAM/index.ts +0 -3
- package/src/gifted +0 -1
- package/src/index.ts +0 -13
- /package/{src → lib}/Defaults/phonenumber-mcc.json +0 -0
- /package/{src → lib}/Socket/Client/abstract-socket-client.js +0 -0
- /package/{src → lib}/Store/index.js +0 -0
- /package/{src → lib}/Store/make-ordered-dictionary.js +0 -0
- /package/{src → lib}/Types/Auth.js +0 -0
- /package/{src → lib}/Types/Call.js +0 -0
- /package/{src → lib}/Types/Chat.js +0 -0
- /package/{src → lib}/Types/Contact.js +0 -0
- /package/{src → lib}/Types/Events.js +0 -0
- /package/{src → lib}/Types/GroupMetadata.js +0 -0
- /package/{src → lib}/Types/Label.js +0 -0
- /package/{src → lib}/Types/LabelAssociation.js +0 -0
- /package/{src → lib}/Types/Message.js +0 -0
- /package/{src → lib}/Types/Newsletter.js +0 -0
- /package/{src → lib}/Types/Product.js +0 -0
- /package/{src → lib}/Types/Signal.js +0 -0
- /package/{src → lib}/Types/Socket.js +0 -0
- /package/{src → lib}/Types/State.js +0 -0
- /package/{src/WABinary/types.js → lib/Types/USync.js} +0 -0
- /package/{src → lib}/Types/index.js +0 -0
- /package/{src → lib}/Utils/index.js +0 -0
- /package/{src → lib}/Utils/logger.js +0 -0
- /package/{src → lib}/Utils/lt-hash.js +0 -0
- /package/{src → lib}/Utils/noise-handler.js +0 -0
- /package/{src → lib}/WABinary/constants.js +0 -0
- /package/{src → lib}/WABinary/decode.js +0 -0
- /package/{src → lib}/WABinary/generic-utils.js +0 -0
- /package/{src → lib}/WABinary/index.js +0 -0
- /package/{src → lib}/WABinary/jid-utils.js +0 -0
- /package/{src → lib}/WAM/BinaryInfo.js +0 -0
- /package/{src → lib}/WAM/constants.js +0 -0
- /package/{src → lib}/WAM/encode.js +0 -0
- /package/{src → lib}/WAM/index.js +0 -0
package/src/Socket/socket.ts
DELETED
|
@@ -1,777 +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'
|
|
6
|
-
import {
|
|
7
|
-
DEF_CALLBACK_PREFIX,
|
|
8
|
-
DEF_TAG_PREFIX,
|
|
9
|
-
INITIAL_PREKEY_COUNT,
|
|
10
|
-
MIN_PREKEY_COUNT,
|
|
11
|
-
MOBILE_ENDPOINT,
|
|
12
|
-
MOBILE_NOISE_HEADER,
|
|
13
|
-
MOBILE_PORT,
|
|
14
|
-
NOISE_WA_HEADER
|
|
15
|
-
} from '../Defaults'
|
|
16
|
-
import { DisconnectReason, SocketConfig } from '../Types'
|
|
17
|
-
import {
|
|
18
|
-
addTransactionCapability,
|
|
19
|
-
aesEncryptCTR,
|
|
20
|
-
bindWaitForConnectionUpdate,
|
|
21
|
-
bytesToCrockford,
|
|
22
|
-
configureSuccessfulPairing,
|
|
23
|
-
Curve,
|
|
24
|
-
derivePairingCodeKey,
|
|
25
|
-
generateLoginNode,
|
|
26
|
-
generateMdTagPrefix,
|
|
27
|
-
generateMobileNode,
|
|
28
|
-
generateRegistrationNode,
|
|
29
|
-
getCodeFromWSError,
|
|
30
|
-
getErrorCodeFromStreamError,
|
|
31
|
-
getNextPreKeysNode,
|
|
32
|
-
makeEventBuffer,
|
|
33
|
-
makeNoiseHandler,
|
|
34
|
-
printQRIfNecessaryListener,
|
|
35
|
-
promiseTimeout
|
|
36
|
-
} from '../Utils'
|
|
37
|
-
import {
|
|
38
|
-
assertNodeErrorFree,
|
|
39
|
-
BinaryNode,
|
|
40
|
-
binaryNodeToString,
|
|
41
|
-
encodeBinaryNode,
|
|
42
|
-
getBinaryNodeChild,
|
|
43
|
-
getBinaryNodeChildren,
|
|
44
|
-
jidEncode,
|
|
45
|
-
S_WHATSAPP_NET
|
|
46
|
-
} from '../WABinary'
|
|
47
|
-
import { MobileSocketClient, WebSocketClient } from './Client'
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Connects to WA servers and performs:
|
|
51
|
-
* - simple queries (no retry mechanism, wait for connection establishment)
|
|
52
|
-
* - listen to messages and emit events
|
|
53
|
-
* - query phone connection
|
|
54
|
-
*/
|
|
55
|
-
|
|
56
|
-
export const makeSocket = (config: SocketConfig) => {
|
|
57
|
-
const {
|
|
58
|
-
waWebSocketUrl,
|
|
59
|
-
connectTimeoutMs,
|
|
60
|
-
logger,
|
|
61
|
-
keepAliveIntervalMs,
|
|
62
|
-
browser,
|
|
63
|
-
auth: authState,
|
|
64
|
-
printQRInTerminal,
|
|
65
|
-
defaultQueryTimeoutMs,
|
|
66
|
-
transactionOpts,
|
|
67
|
-
qrTimeout,
|
|
68
|
-
makeSignalRepository,
|
|
69
|
-
} = config
|
|
70
|
-
|
|
71
|
-
let url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl
|
|
72
|
-
|
|
73
|
-
config.mobile = config.mobile || url.protocol === 'tcp:'
|
|
74
|
-
|
|
75
|
-
if(config.mobile && url.protocol !== 'tcp:') {
|
|
76
|
-
url = new URL(`tcp://${MOBILE_ENDPOINT}:${MOBILE_PORT}`)
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
if(!config.mobile && url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
|
80
|
-
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
const ws = config.socket ? config.socket : config.mobile ? new MobileSocketClient(url, config) : new WebSocketClient(url, config)
|
|
84
|
-
|
|
85
|
-
ws.connect()
|
|
86
|
-
|
|
87
|
-
const ev = makeEventBuffer(logger)
|
|
88
|
-
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
|
|
89
|
-
const ephemeralKeyPair = Curve.generateKeyPair()
|
|
90
|
-
/** WA noise protocol wrapper */
|
|
91
|
-
const noise = makeNoiseHandler({
|
|
92
|
-
keyPair: ephemeralKeyPair,
|
|
93
|
-
NOISE_HEADER: config.mobile ? MOBILE_NOISE_HEADER : NOISE_WA_HEADER,
|
|
94
|
-
mobile: config.mobile,
|
|
95
|
-
logger,
|
|
96
|
-
routingInfo: authState?.creds?.routingInfo
|
|
97
|
-
})
|
|
98
|
-
|
|
99
|
-
const { creds } = authState
|
|
100
|
-
// add transaction capability
|
|
101
|
-
const keys = addTransactionCapability(authState.keys, logger, transactionOpts)
|
|
102
|
-
const signalRepository = makeSignalRepository({ creds, keys })
|
|
103
|
-
|
|
104
|
-
let lastDateRecv: Date
|
|
105
|
-
let epoch = 1
|
|
106
|
-
let keepAliveReq: NodeJS.Timeout
|
|
107
|
-
let qrTimer: NodeJS.Timeout
|
|
108
|
-
let closed = false
|
|
109
|
-
|
|
110
|
-
const uqTagId = generateMdTagPrefix()
|
|
111
|
-
const generateMessageTag = () => `${uqTagId}${epoch++}`
|
|
112
|
-
|
|
113
|
-
const sendPromise = promisify(ws.send)
|
|
114
|
-
/** send a raw buffer */
|
|
115
|
-
const sendRawMessage = async(data: Uint8Array | Buffer) => {
|
|
116
|
-
if(!ws.isOpen) {
|
|
117
|
-
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
const bytes = noise.encodeFrame(data)
|
|
121
|
-
await promiseTimeout<void>(
|
|
122
|
-
connectTimeoutMs,
|
|
123
|
-
async(resolve, reject) => {
|
|
124
|
-
try {
|
|
125
|
-
await sendPromise.call(ws, bytes)
|
|
126
|
-
resolve()
|
|
127
|
-
} catch(error) {
|
|
128
|
-
reject(error)
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
)
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** send a binary node */
|
|
135
|
-
const sendNode = (frame: BinaryNode) => {
|
|
136
|
-
if(logger.level === 'trace') {
|
|
137
|
-
logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
const buff = encodeBinaryNode(frame)
|
|
141
|
-
return sendRawMessage(buff)
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** log & process any unexpected errors */
|
|
145
|
-
const onUnexpectedError = (err: Error | Boom, msg: string) => {
|
|
146
|
-
logger.error(
|
|
147
|
-
{ err },
|
|
148
|
-
`unexpected error in '${msg}'`
|
|
149
|
-
)
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** await the next incoming message */
|
|
153
|
-
const awaitNextMessage = async<T>(sendMsg?: Uint8Array) => {
|
|
154
|
-
if(!ws.isOpen) {
|
|
155
|
-
throw new Boom('Connection Closed', {
|
|
156
|
-
statusCode: DisconnectReason.connectionClosed
|
|
157
|
-
})
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
let onOpen: (data: T) => void
|
|
161
|
-
let onClose: (err: Error) => void
|
|
162
|
-
|
|
163
|
-
const result = promiseTimeout<T>(connectTimeoutMs, (resolve, reject) => {
|
|
164
|
-
onOpen = resolve
|
|
165
|
-
onClose = mapWebSocketError(reject)
|
|
166
|
-
ws.on('frame', onOpen)
|
|
167
|
-
ws.on('close', onClose)
|
|
168
|
-
ws.on('error', onClose)
|
|
169
|
-
})
|
|
170
|
-
.finally(() => {
|
|
171
|
-
ws.off('frame', onOpen)
|
|
172
|
-
ws.off('close', onClose)
|
|
173
|
-
ws.off('error', onClose)
|
|
174
|
-
})
|
|
175
|
-
|
|
176
|
-
if(sendMsg) {
|
|
177
|
-
sendRawMessage(sendMsg).catch(onClose!)
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
return result
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* Wait for a message with a certain tag to be received
|
|
185
|
-
* @param msgId the message tag to await
|
|
186
|
-
* @param timeoutMs timeout after which the promise will reject
|
|
187
|
-
*/
|
|
188
|
-
const waitForMessage = async<T>(msgId: string, timeoutMs = defaultQueryTimeoutMs) => {
|
|
189
|
-
let onRecv: (json) => void
|
|
190
|
-
let onErr: (err) => void
|
|
191
|
-
try {
|
|
192
|
-
return await promiseTimeout<T>(timeoutMs,
|
|
193
|
-
(resolve, reject) => {
|
|
194
|
-
onRecv = resolve
|
|
195
|
-
onErr = err => {
|
|
196
|
-
reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
ws.on(`TAG:${msgId}`, onRecv)
|
|
200
|
-
ws.on('close', onErr) // if the socket closes, you'll never receive the message
|
|
201
|
-
ws.off('error', onErr)
|
|
202
|
-
},
|
|
203
|
-
)
|
|
204
|
-
} finally {
|
|
205
|
-
ws.off(`TAG:${msgId}`, onRecv!)
|
|
206
|
-
ws.off('close', onErr!) // if the socket closes, you'll never receive the message
|
|
207
|
-
ws.off('error', onErr!)
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
|
212
|
-
const query = async(node: BinaryNode, timeoutMs?: number) => {
|
|
213
|
-
if(!node.attrs.id) {
|
|
214
|
-
node.attrs.id = generateMessageTag()
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
const msgId = node.attrs.id
|
|
218
|
-
const wait = waitForMessage(msgId, timeoutMs)
|
|
219
|
-
|
|
220
|
-
await sendNode(node)
|
|
221
|
-
|
|
222
|
-
const result = await (wait as Promise<BinaryNode>)
|
|
223
|
-
if('tag' in result) {
|
|
224
|
-
assertNodeErrorFree(result)
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
return result
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/** connection handshake */
|
|
231
|
-
const validateConnection = async() => {
|
|
232
|
-
let helloMsg: proto.IHandshakeMessage = {
|
|
233
|
-
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
234
|
-
}
|
|
235
|
-
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
|
|
236
|
-
|
|
237
|
-
logger.info({ browser, helloMsg }, 'connected to WA')
|
|
238
|
-
|
|
239
|
-
const init = proto.HandshakeMessage.encode(helloMsg).finish()
|
|
240
|
-
|
|
241
|
-
const result = await awaitNextMessage<Uint8Array>(init)
|
|
242
|
-
const handshake = proto.HandshakeMessage.decode(result)
|
|
243
|
-
|
|
244
|
-
logger.trace({ handshake }, 'handshake recv from WA')
|
|
245
|
-
|
|
246
|
-
const keyEnc = noise.processHandshake(handshake, creds.noiseKey)
|
|
247
|
-
|
|
248
|
-
let node: proto.IClientPayload
|
|
249
|
-
if(config.mobile) {
|
|
250
|
-
node = generateMobileNode(config)
|
|
251
|
-
} else if(!creds.me) {
|
|
252
|
-
node = generateRegistrationNode(creds, config)
|
|
253
|
-
logger.info({ node }, 'not logged in, attempting registration...')
|
|
254
|
-
} else {
|
|
255
|
-
node = generateLoginNode(creds.me.id, config)
|
|
256
|
-
logger.info({ node }, 'logging in...')
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
const payloadEnc = noise.encrypt(
|
|
260
|
-
proto.ClientPayload.encode(node).finish()
|
|
261
|
-
)
|
|
262
|
-
await sendRawMessage(
|
|
263
|
-
proto.HandshakeMessage.encode({
|
|
264
|
-
clientFinish: {
|
|
265
|
-
static: keyEnc,
|
|
266
|
-
payload: payloadEnc,
|
|
267
|
-
},
|
|
268
|
-
}).finish()
|
|
269
|
-
)
|
|
270
|
-
noise.finishInit()
|
|
271
|
-
startKeepAliveRequest()
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
const getAvailablePreKeysOnServer = async() => {
|
|
275
|
-
const result = await query({
|
|
276
|
-
tag: 'iq',
|
|
277
|
-
attrs: {
|
|
278
|
-
id: generateMessageTag(),
|
|
279
|
-
xmlns: 'encrypt',
|
|
280
|
-
type: 'get',
|
|
281
|
-
to: S_WHATSAPP_NET
|
|
282
|
-
},
|
|
283
|
-
content: [
|
|
284
|
-
{ tag: 'count', attrs: {} }
|
|
285
|
-
]
|
|
286
|
-
})
|
|
287
|
-
const countChild = getBinaryNodeChild(result, 'count')
|
|
288
|
-
return +countChild!.attrs.value
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/** generates and uploads a set of pre-keys to the server */
|
|
292
|
-
const uploadPreKeys = async(count = INITIAL_PREKEY_COUNT) => {
|
|
293
|
-
await keys.transaction(
|
|
294
|
-
async() => {
|
|
295
|
-
logger.info({ count }, 'uploading pre-keys')
|
|
296
|
-
const { update, node } = await getNextPreKeysNode({ creds, keys }, count)
|
|
297
|
-
|
|
298
|
-
await query(node)
|
|
299
|
-
ev.emit('creds.update', update)
|
|
300
|
-
|
|
301
|
-
logger.info({ count }, 'uploaded pre-keys')
|
|
302
|
-
}
|
|
303
|
-
)
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
const uploadPreKeysToServerIfRequired = async() => {
|
|
307
|
-
const preKeyCount = await getAvailablePreKeysOnServer()
|
|
308
|
-
logger.info(`${preKeyCount} pre-keys found on server`)
|
|
309
|
-
if(preKeyCount <= MIN_PREKEY_COUNT) {
|
|
310
|
-
await uploadPreKeys()
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
const onMessageReceived = (data: Buffer) => {
|
|
315
|
-
noise.decodeFrame(data, frame => {
|
|
316
|
-
// reset ping timeout
|
|
317
|
-
lastDateRecv = new Date()
|
|
318
|
-
|
|
319
|
-
let anyTriggered = false
|
|
320
|
-
|
|
321
|
-
anyTriggered = ws.emit('frame', frame)
|
|
322
|
-
// if it's a binary node
|
|
323
|
-
if(!(frame instanceof Uint8Array)) {
|
|
324
|
-
const msgId = frame.attrs.id
|
|
325
|
-
|
|
326
|
-
if(logger.level === 'trace') {
|
|
327
|
-
logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
/* Check if this is a response to a message we sent */
|
|
331
|
-
anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
|
|
332
|
-
/* Check if this is a response to a message we are expecting */
|
|
333
|
-
const l0 = frame.tag
|
|
334
|
-
const l1 = frame.attrs || {}
|
|
335
|
-
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
|
|
336
|
-
|
|
337
|
-
Object.keys(l1).forEach(key => {
|
|
338
|
-
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
|
|
339
|
-
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
|
|
340
|
-
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
|
|
341
|
-
})
|
|
342
|
-
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
|
|
343
|
-
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
|
|
344
|
-
|
|
345
|
-
if(!anyTriggered && logger.level === 'debug') {
|
|
346
|
-
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
})
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
const end = (error: Error | undefined) => {
|
|
353
|
-
if(closed) {
|
|
354
|
-
logger.trace({ trace: error?.stack }, 'connection already closed')
|
|
355
|
-
return
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
closed = true
|
|
359
|
-
logger.info(
|
|
360
|
-
{ trace: error?.stack },
|
|
361
|
-
error ? 'connection errored' : 'connection closed'
|
|
362
|
-
)
|
|
363
|
-
|
|
364
|
-
clearInterval(keepAliveReq)
|
|
365
|
-
clearTimeout(qrTimer)
|
|
366
|
-
|
|
367
|
-
ws.removeAllListeners('close')
|
|
368
|
-
ws.removeAllListeners('error')
|
|
369
|
-
ws.removeAllListeners('open')
|
|
370
|
-
ws.removeAllListeners('message')
|
|
371
|
-
|
|
372
|
-
if(!ws.isClosed && !ws.isClosing) {
|
|
373
|
-
try {
|
|
374
|
-
ws.close()
|
|
375
|
-
} catch{ }
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
ev.emit('connection.update', {
|
|
379
|
-
connection: 'close',
|
|
380
|
-
lastDisconnect: {
|
|
381
|
-
error,
|
|
382
|
-
date: new Date()
|
|
383
|
-
}
|
|
384
|
-
})
|
|
385
|
-
ev.removeAllListeners('connection.update')
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
const waitForSocketOpen = async() => {
|
|
389
|
-
if(ws.isOpen) {
|
|
390
|
-
return
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
if(ws.isClosed || ws.isClosing) {
|
|
394
|
-
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
let onOpen: () => void
|
|
398
|
-
let onClose: (err: Error) => void
|
|
399
|
-
await new Promise((resolve, reject) => {
|
|
400
|
-
onOpen = () => resolve(undefined)
|
|
401
|
-
onClose = mapWebSocketError(reject)
|
|
402
|
-
ws.on('open', onOpen)
|
|
403
|
-
ws.on('close', onClose)
|
|
404
|
-
ws.on('error', onClose)
|
|
405
|
-
})
|
|
406
|
-
.finally(() => {
|
|
407
|
-
ws.off('open', onOpen)
|
|
408
|
-
ws.off('close', onClose)
|
|
409
|
-
ws.off('error', onClose)
|
|
410
|
-
})
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
const startKeepAliveRequest = () => (
|
|
414
|
-
keepAliveReq = setInterval(() => {
|
|
415
|
-
if(!lastDateRecv) {
|
|
416
|
-
lastDateRecv = new Date()
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
const diff = Date.now() - lastDateRecv.getTime()
|
|
420
|
-
/*
|
|
421
|
-
check if it's been a suspicious amount of time since the server responded with our last seen
|
|
422
|
-
it could be that the network is down
|
|
423
|
-
*/
|
|
424
|
-
if(diff > keepAliveIntervalMs + 5000) {
|
|
425
|
-
end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
|
|
426
|
-
} else if(ws.isOpen) {
|
|
427
|
-
// if its all good, send a keep alive request
|
|
428
|
-
query(
|
|
429
|
-
{
|
|
430
|
-
tag: 'iq',
|
|
431
|
-
attrs: {
|
|
432
|
-
id: generateMessageTag(),
|
|
433
|
-
to: S_WHATSAPP_NET,
|
|
434
|
-
type: 'get',
|
|
435
|
-
xmlns: 'w:p',
|
|
436
|
-
},
|
|
437
|
-
content: [{ tag: 'ping', attrs: {} }]
|
|
438
|
-
}
|
|
439
|
-
)
|
|
440
|
-
.catch(err => {
|
|
441
|
-
logger.error({ trace: err.stack }, 'error in sending keep alive')
|
|
442
|
-
})
|
|
443
|
-
} else {
|
|
444
|
-
logger.warn('keep alive called when WS not open')
|
|
445
|
-
}
|
|
446
|
-
}, keepAliveIntervalMs)
|
|
447
|
-
)
|
|
448
|
-
/** i have no idea why this exists. pls enlighten me */
|
|
449
|
-
const sendPassiveIq = (tag: 'passive' | 'active') => (
|
|
450
|
-
query({
|
|
451
|
-
tag: 'iq',
|
|
452
|
-
attrs: {
|
|
453
|
-
to: S_WHATSAPP_NET,
|
|
454
|
-
xmlns: 'passive',
|
|
455
|
-
type: 'set',
|
|
456
|
-
},
|
|
457
|
-
content: [
|
|
458
|
-
{ tag, attrs: {} }
|
|
459
|
-
]
|
|
460
|
-
})
|
|
461
|
-
)
|
|
462
|
-
|
|
463
|
-
/** logout & invalidate connection */
|
|
464
|
-
const logout = async(msg?: string) => {
|
|
465
|
-
const jid = authState.creds.me?.id
|
|
466
|
-
if(jid) {
|
|
467
|
-
await sendNode({
|
|
468
|
-
tag: 'iq',
|
|
469
|
-
attrs: {
|
|
470
|
-
to: S_WHATSAPP_NET,
|
|
471
|
-
type: 'set',
|
|
472
|
-
id: generateMessageTag(),
|
|
473
|
-
xmlns: 'md'
|
|
474
|
-
},
|
|
475
|
-
content: [
|
|
476
|
-
{
|
|
477
|
-
tag: 'remove-companion-device',
|
|
478
|
-
attrs: {
|
|
479
|
-
jid,
|
|
480
|
-
reason: 'user_initiated'
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
]
|
|
484
|
-
})
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }))
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
const requestPairingCode = async(phoneNumber: string): Promise<string> => {
|
|
491
|
-
authState.creds.pairingCode = bytesToCrockford(randomBytes(5))
|
|
492
|
-
authState.creds.me = {
|
|
493
|
-
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
|
494
|
-
name: '~'
|
|
495
|
-
}
|
|
496
|
-
ev.emit('creds.update', authState.creds)
|
|
497
|
-
await sendNode({
|
|
498
|
-
tag: 'iq',
|
|
499
|
-
attrs: {
|
|
500
|
-
to: S_WHATSAPP_NET,
|
|
501
|
-
type: 'set',
|
|
502
|
-
id: generateMessageTag(),
|
|
503
|
-
xmlns: 'md'
|
|
504
|
-
},
|
|
505
|
-
content: [
|
|
506
|
-
{
|
|
507
|
-
tag: 'link_code_companion_reg',
|
|
508
|
-
attrs: {
|
|
509
|
-
jid: authState.creds.me.id,
|
|
510
|
-
stage: 'companion_hello',
|
|
511
|
-
// eslint-disable-next-line camelcase
|
|
512
|
-
should_show_push_notification: 'true'
|
|
513
|
-
},
|
|
514
|
-
content: [
|
|
515
|
-
{
|
|
516
|
-
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
517
|
-
attrs: {},
|
|
518
|
-
content: await generatePairingKey()
|
|
519
|
-
},
|
|
520
|
-
{
|
|
521
|
-
tag: 'companion_server_auth_key_pub',
|
|
522
|
-
attrs: {},
|
|
523
|
-
content: authState.creds.noiseKey.public
|
|
524
|
-
},
|
|
525
|
-
{
|
|
526
|
-
tag: 'companion_platform_id',
|
|
527
|
-
attrs: {},
|
|
528
|
-
content: '49' // Chrome
|
|
529
|
-
},
|
|
530
|
-
{
|
|
531
|
-
tag: 'companion_platform_display',
|
|
532
|
-
attrs: {},
|
|
533
|
-
content: `${browser[1]} (${browser[0]})`
|
|
534
|
-
},
|
|
535
|
-
{
|
|
536
|
-
tag: 'link_code_pairing_nonce',
|
|
537
|
-
attrs: {},
|
|
538
|
-
content: '0'
|
|
539
|
-
}
|
|
540
|
-
]
|
|
541
|
-
}
|
|
542
|
-
]
|
|
543
|
-
})
|
|
544
|
-
return authState.creds.pairingCode
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
async function generatePairingKey() {
|
|
548
|
-
const salt = randomBytes(32)
|
|
549
|
-
const randomIv = randomBytes(16)
|
|
550
|
-
const key = derivePairingCodeKey(authState.creds.pairingCode!, salt)
|
|
551
|
-
const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
|
|
552
|
-
return Buffer.concat([salt, randomIv, ciphered])
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
const sendWAMBuffer = (wamBuffer: Buffer) => {
|
|
556
|
-
return query({
|
|
557
|
-
tag: 'iq',
|
|
558
|
-
attrs: {
|
|
559
|
-
to: S_WHATSAPP_NET,
|
|
560
|
-
id: generateMessageTag(),
|
|
561
|
-
xmlns: 'w:stats'
|
|
562
|
-
},
|
|
563
|
-
content: [
|
|
564
|
-
{
|
|
565
|
-
tag: 'add',
|
|
566
|
-
attrs: {},
|
|
567
|
-
content: wamBuffer
|
|
568
|
-
}
|
|
569
|
-
]
|
|
570
|
-
})
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
ws.on('message', onMessageReceived)
|
|
574
|
-
|
|
575
|
-
ws.on('open', async() => {
|
|
576
|
-
try {
|
|
577
|
-
await validateConnection()
|
|
578
|
-
} catch(err) {
|
|
579
|
-
logger.error({ err }, 'error in validating connection')
|
|
580
|
-
end(err)
|
|
581
|
-
}
|
|
582
|
-
})
|
|
583
|
-
ws.on('error', mapWebSocketError(end))
|
|
584
|
-
ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
|
|
585
|
-
// the server terminated the connection
|
|
586
|
-
ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
|
|
587
|
-
// QR gen
|
|
588
|
-
ws.on('CB:iq,type:set,pair-device', async(stanza: BinaryNode) => {
|
|
589
|
-
const iq: BinaryNode = {
|
|
590
|
-
tag: 'iq',
|
|
591
|
-
attrs: {
|
|
592
|
-
to: S_WHATSAPP_NET,
|
|
593
|
-
type: 'result',
|
|
594
|
-
id: stanza.attrs.id,
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
await sendNode(iq)
|
|
598
|
-
|
|
599
|
-
const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device')
|
|
600
|
-
const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref')
|
|
601
|
-
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
|
|
602
|
-
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
|
|
603
|
-
const advB64 = creds.advSecretKey
|
|
604
|
-
|
|
605
|
-
let qrMs = qrTimeout || 60_000 // time to let a QR live
|
|
606
|
-
const genPairQR = () => {
|
|
607
|
-
if(!ws.isOpen) {
|
|
608
|
-
return
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
const refNode = refNodes.shift()
|
|
612
|
-
if(!refNode) {
|
|
613
|
-
end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
|
|
614
|
-
return
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
const ref = (refNode.content as Buffer).toString('utf-8')
|
|
618
|
-
const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',')
|
|
619
|
-
|
|
620
|
-
ev.emit('connection.update', { qr })
|
|
621
|
-
|
|
622
|
-
qrTimer = setTimeout(genPairQR, qrMs)
|
|
623
|
-
qrMs = qrTimeout || 20_000 // shorter subsequent qrs
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
genPairQR()
|
|
627
|
-
})
|
|
628
|
-
// device paired for the first time
|
|
629
|
-
// if device pairs successfully, the server asks to restart the connection
|
|
630
|
-
ws.on('CB:iq,,pair-success', async(stanza: BinaryNode) => {
|
|
631
|
-
logger.debug('pair success recv')
|
|
632
|
-
try {
|
|
633
|
-
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
|
|
634
|
-
|
|
635
|
-
logger.info(
|
|
636
|
-
{ me: updatedCreds.me, platform: updatedCreds.platform },
|
|
637
|
-
'pairing configured successfully, expect to restart the connection...'
|
|
638
|
-
)
|
|
639
|
-
|
|
640
|
-
ev.emit('creds.update', updatedCreds)
|
|
641
|
-
ev.emit('connection.update', { isNewLogin: true, qr: undefined })
|
|
642
|
-
|
|
643
|
-
await sendNode(reply)
|
|
644
|
-
} catch(error) {
|
|
645
|
-
logger.info({ trace: error.stack }, 'error in pairing')
|
|
646
|
-
end(error)
|
|
647
|
-
}
|
|
648
|
-
})
|
|
649
|
-
// login complete
|
|
650
|
-
ws.on('CB:success', async(node: BinaryNode) => {
|
|
651
|
-
await uploadPreKeysToServerIfRequired()
|
|
652
|
-
await sendPassiveIq('active')
|
|
653
|
-
|
|
654
|
-
logger.info('opened connection to WA')
|
|
655
|
-
clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
|
|
656
|
-
|
|
657
|
-
ev.emit('creds.update', { me: { ...authState.creds.me!, lid: node.attrs.lid } })
|
|
658
|
-
|
|
659
|
-
ev.emit('connection.update', { connection: 'open' })
|
|
660
|
-
})
|
|
661
|
-
|
|
662
|
-
ws.on('CB:stream:error', (node: BinaryNode) => {
|
|
663
|
-
logger.error({ node }, 'stream errored out')
|
|
664
|
-
|
|
665
|
-
const { reason, statusCode } = getErrorCodeFromStreamError(node)
|
|
666
|
-
|
|
667
|
-
end(new Boom(`Stream Errored (${reason})`, { statusCode, data: node }))
|
|
668
|
-
})
|
|
669
|
-
// stream fail, possible logout
|
|
670
|
-
ws.on('CB:failure', (node: BinaryNode) => {
|
|
671
|
-
const reason = +(node.attrs.reason || 500)
|
|
672
|
-
end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
|
|
673
|
-
})
|
|
674
|
-
|
|
675
|
-
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
676
|
-
end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }))
|
|
677
|
-
})
|
|
678
|
-
|
|
679
|
-
ws.on('CB:ib,,edge_routing', (node: BinaryNode) => {
|
|
680
|
-
const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
|
|
681
|
-
const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
|
|
682
|
-
if(routingInfo?.content) {
|
|
683
|
-
authState.creds.routingInfo = Buffer.from(routingInfo?.content as Uint8Array)
|
|
684
|
-
}
|
|
685
|
-
})
|
|
686
|
-
|
|
687
|
-
let didStartBuffer = false
|
|
688
|
-
process.nextTick(() => {
|
|
689
|
-
if(creds.me?.id) {
|
|
690
|
-
// start buffering important events
|
|
691
|
-
// if we're logged in
|
|
692
|
-
ev.buffer()
|
|
693
|
-
didStartBuffer = true
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
|
|
697
|
-
})
|
|
698
|
-
|
|
699
|
-
// called when all offline notifs are handled
|
|
700
|
-
ws.on('CB:ib,,offline', (node: BinaryNode) => {
|
|
701
|
-
const child = getBinaryNodeChild(node, 'offline')
|
|
702
|
-
const offlineNotifs = +(child?.attrs.count || 0)
|
|
703
|
-
|
|
704
|
-
logger.info(`handled ${offlineNotifs} offline messages/notifications`)
|
|
705
|
-
if(didStartBuffer) {
|
|
706
|
-
ev.flush()
|
|
707
|
-
logger.trace('flushed events for initial buffer')
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
ev.emit('connection.update', { receivedPendingNotifications: true })
|
|
711
|
-
})
|
|
712
|
-
|
|
713
|
-
// update credentials when required
|
|
714
|
-
ev.on('creds.update', update => {
|
|
715
|
-
const name = update.me?.name
|
|
716
|
-
// if name has just been received
|
|
717
|
-
if(creds.me?.name !== name) {
|
|
718
|
-
logger.debug({ name }, 'updated pushName')
|
|
719
|
-
sendNode({
|
|
720
|
-
tag: 'presence',
|
|
721
|
-
attrs: { name: name! }
|
|
722
|
-
})
|
|
723
|
-
.catch(err => {
|
|
724
|
-
logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
|
|
725
|
-
})
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
Object.assign(creds, update)
|
|
729
|
-
})
|
|
730
|
-
|
|
731
|
-
if(printQRInTerminal) {
|
|
732
|
-
printQRIfNecessaryListener(ev, logger)
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
return {
|
|
736
|
-
type: 'md' as 'md',
|
|
737
|
-
ws,
|
|
738
|
-
ev,
|
|
739
|
-
authState: { creds, keys },
|
|
740
|
-
signalRepository,
|
|
741
|
-
get user() {
|
|
742
|
-
return authState.creds.me
|
|
743
|
-
},
|
|
744
|
-
generateMessageTag,
|
|
745
|
-
query,
|
|
746
|
-
waitForMessage,
|
|
747
|
-
waitForSocketOpen,
|
|
748
|
-
sendRawMessage,
|
|
749
|
-
sendNode,
|
|
750
|
-
logout,
|
|
751
|
-
end,
|
|
752
|
-
onUnexpectedError,
|
|
753
|
-
uploadPreKeys,
|
|
754
|
-
uploadPreKeysToServerIfRequired,
|
|
755
|
-
requestPairingCode,
|
|
756
|
-
/** Waits for the connection to WA to reach a state */
|
|
757
|
-
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
|
758
|
-
sendWAMBuffer,
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
/**
|
|
763
|
-
* map the websocket error to the right type
|
|
764
|
-
* so it can be retried by the caller
|
|
765
|
-
* */
|
|
766
|
-
function mapWebSocketError(handler: (err: Error) => void) {
|
|
767
|
-
return (error: Error) => {
|
|
768
|
-
handler(
|
|
769
|
-
new Boom(
|
|
770
|
-
`WebSocket Error (${error?.message})`,
|
|
771
|
-
{ statusCode: getCodeFromWSError(error), data: error }
|
|
772
|
-
)
|
|
773
|
-
)
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
export type Socket = ReturnType<typeof makeSocket>
|