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