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