kage-baileys 3.0.6 → 3.2.3
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/Example/connection.cjs +4 -0
- package/README.MD +4726 -48
- package/WAProto/WAProto.proto +3395 -415
- package/WAProto/compat.cjs +12 -0
- package/WAProto/index.d.ts +47104 -19888
- package/WAProto/index.js +131979 -57361
- package/lib/Addon/http-error.js +43 -0
- package/lib/Addon/index.js +32 -0
- package/lib/Addon/keyed-db.js +250 -0
- package/lib/Addon/link-preview.js +82 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/connection.js +110 -0
- package/lib/Defaults/constants.js +156 -0
- package/lib/Defaults/history.js +46 -0
- package/lib/Defaults/index.js +230 -0
- package/lib/Defaults/media.js +104 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Defaults/prefix.js +44 -0
- package/lib/Extensions/business-advanced.js +382 -0
- package/lib/Extensions/business.js +159 -0
- package/lib/Extensions/chats-advanced.js +1106 -0
- package/lib/Extensions/chats.js +349 -0
- package/lib/Extensions/communities-advanced.js +430 -0
- package/lib/Extensions/community.js +94 -0
- package/lib/Extensions/groups-advanced.js +343 -0
- package/lib/Extensions/index.js +30 -0
- package/lib/Extensions/messages-recv-advanced.js +1690 -0
- package/lib/Extensions/messages-send-advanced.js +622 -0
- package/lib/Extensions/messages-send.js +1380 -0
- package/lib/Extensions/newsletter-advanced.js +228 -0
- package/lib/Extensions/newsletter.js +72 -0
- package/lib/Extensions/socket.js +389 -0
- package/lib/Modded/message_builder.js +2084 -4
- package/lib/Signal/Group/ciphertext-message.js +54 -0
- package/lib/Signal/Group/group-session-builder.js +124 -0
- package/lib/Signal/Group/group_cipher.js +216 -0
- package/lib/Signal/Group/index.js +124 -0
- package/lib/Signal/Group/keyhelper.js +108 -0
- package/lib/Signal/Group/sender-chain-key.js +83 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
- package/lib/Signal/Group/sender-key-message.js +166 -0
- package/lib/Signal/Group/sender-key-name.js +130 -0
- package/lib/Signal/Group/sender-key-record.js +113 -0
- package/lib/Signal/Group/sender-key-state.js +208 -0
- package/lib/Signal/Group/sender-message-key.js +82 -0
- package/lib/Signal/libsignal.js +935 -0
- package/lib/Signal/lid-mapping.js +545 -1
- package/lib/Socket/Client/index.js +60 -0
- package/lib/Socket/Client/types.js +51 -0
- package/lib/Socket/Client/websocket.js +152 -0
- package/lib/Socket/business.js +831 -0
- package/lib/Socket/chats.js +2535 -49
- package/lib/Socket/communities.js +450 -1
- package/lib/Socket/community.js +1022 -0
- package/lib/Socket/dugong.js +1 -1
- package/lib/Socket/groups.js +747 -0
- package/lib/Socket/index.js +60 -2
- package/lib/Socket/messages-recv.js +3450 -5
- package/lib/Socket/messages-send.js +3123 -0
- package/lib/Socket/mex.js +126 -1
- package/lib/Socket/newsletter.js +465 -0
- package/lib/Socket/socket.js +2217 -1
- package/lib/Store/index.js +79 -0
- package/lib/Store/make-cache-manager-store.js +186 -0
- package/lib/Store/make-in-memory-store.js +878 -0
- package/lib/Store/make-ordered-dictionary.js +187 -0
- package/lib/Store/object-repository.js +78 -0
- package/lib/Types/Auth.js +25 -0
- package/lib/Types/Bussines.js +25 -1
- package/lib/Types/Call.js +25 -0
- package/lib/Types/Chat.js +39 -0
- package/lib/Types/Contact.js +25 -0
- package/lib/Types/Events.js +25 -0
- package/lib/Types/GroupMetadata.js +25 -0
- package/lib/Types/Label.js +76 -0
- package/lib/Types/LabelAssociation.js +40 -0
- package/lib/Types/Message.js +57 -0
- package/lib/Types/Mex.js +56 -1
- package/lib/Types/MexUpdates.js +46 -0
- package/lib/Types/Newsletter.js +56 -0
- package/lib/Types/Product.js +25 -0
- package/lib/Types/RichType.js +23 -0
- package/lib/Types/Signal.js +25 -0
- package/lib/Types/Socket.js +25 -0
- package/lib/Types/State.js +92 -0
- package/lib/Types/USync.js +25 -0
- package/lib/Types/index.js +133 -0
- package/lib/Utils/auth-utils.js +703 -0
- package/lib/Utils/automation-tools.js +51 -16
- package/lib/Utils/baileys-event-stream.js +146 -0
- package/lib/Utils/browser-utils.js +95 -0
- package/lib/Utils/business.js +525 -0
- package/lib/Utils/chat-utils.js +1861 -0
- package/lib/Utils/companion-reg-client-utils.js +55 -1
- package/lib/Utils/crypto.js +355 -0
- package/lib/Utils/decode-wa-message.js +709 -0
- package/lib/Utils/event-buffer.js +1323 -8
- package/lib/Utils/generics.js +945 -1
- package/lib/Utils/history.js +266 -0
- package/lib/Utils/identity-change-handler.js +62 -1
- package/lib/Utils/index.js +114 -0
- package/lib/Utils/link-preview.js +179 -0
- package/lib/Utils/logger.js +42 -0
- package/lib/Utils/lt-hash.js +73 -0
- package/lib/Utils/make-mutex.js +104 -0
- package/lib/Utils/message-inspector.js +110 -0
- package/lib/Utils/message-retry-manager.js +507 -2
- package/lib/Utils/messages-media.js +1931 -1
- package/lib/Utils/messages.js +3748 -0
- package/lib/Utils/noise-handler.js +423 -0
- package/lib/Utils/offline-node-processor.js +53 -1
- package/lib/Utils/pre-key-manager.js +255 -1
- package/lib/Utils/process-message.js +1592 -0
- package/lib/Utils/reporting-utils.js +272 -1
- package/lib/Utils/rich-message-utils.js +377 -0
- package/lib/Utils/rich-messages.js +1 -1
- package/lib/Utils/signal.js +437 -0
- package/lib/Utils/stanza-ack.js +51 -1
- package/lib/Utils/status-refresh.js +37 -0
- package/lib/Utils/status-tools.js +4 -2
- package/lib/Utils/sync-action-utils.js +63 -1
- package/lib/Utils/tc-token-utils.js +185 -1
- package/lib/Utils/terminal-banner.js +31 -0
- package/lib/Utils/use-multi-file-auth-state.js +271 -0
- package/lib/Utils/use-single-file-auth-state.js +108 -0
- package/lib/Utils/use-sqlite-auth-state.js +142 -0
- package/lib/Utils/validate-connection.js +497 -1
- package/lib/Utils/view-once-compat.js +13 -5
- package/lib/VoIP/audio-feeder.js +150 -0
- package/lib/VoIP/index.js +289 -0
- package/lib/VoIP/relay-transport.js +608 -0
- package/lib/VoIP/signaling.js +583 -0
- package/lib/VoIP/types.js +30 -0
- package/lib/VoIP/wasm-engine.js +1261 -2
- package/lib/VoIP/worker-bootstrap.js +1090 -2
- package/lib/WABinary/constants.js +2805 -0
- package/lib/WABinary/decode.js +649 -2
- package/lib/WABinary/encode.js +564 -2
- package/lib/WABinary/generic-utils.js +401 -0
- package/lib/WABinary/index.js +82 -0
- package/lib/WABinary/jid-utils.js +290 -0
- package/lib/WABinary/types.js +25 -0
- package/lib/WAM/BinaryInfo.js +50 -0
- package/lib/WAM/constants.js +45747 -0
- package/lib/WAM/encode.js +393 -0
- package/lib/WAM/index.js +78 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
- package/lib/WAUSync/Protocols/index.js +83 -0
- package/lib/WAUSync/USyncQuery.js +241 -2
- package/lib/WAUSync/USyncUser.js +86 -0
- package/lib/WAUSync/index.js +78 -0
- package/lib/assets/wasm/loader.js +1875 -1
- package/lib/assets/wasm/worker-modules.js +11047 -1
- package/lib/index.d.ts +126 -0
- package/lib/index.js +53 -21
- package/lib/index.mjs +437 -0
- package/licenses/upstream-MIT.txt +22 -0
- package/maintenance/api-coverage.json +1642 -0
- package/maintenance/archivos-sha256.json +207 -0
- package/maintenance/consumer-validation.log +3 -0
- package/maintenance/dependency-audit.json +4 -4
- package/maintenance/extension-inventory.json +57 -0
- package/maintenance/protocol-update.json +1101 -0
- package/maintenance/protocol-wire-audit.json +4 -0
- package/maintenance/reference-socket-surface.json +209 -0
- package/maintenance/resumen-validacion.json +50 -0
- package/maintenance/validation.log +2725 -0
- package/maintenance/verification.json +566 -0
- package/package.json +107 -9
- package/scripts/check-imports.cjs +10 -0
- package/scripts/check-package.cjs +40 -0
- package/scripts/check-syntax.cjs +1 -1
- package/scripts/generate-protobuf.cjs +6 -1
- package/scripts/generate-public-types.cjs +9 -0
- package/scripts/kage-base64-fix.cjs +45 -0
- package/scripts/maintenance.cjs +10 -0
- package/test/advanced.test.cjs +24 -0
- package/test/base64-fix.test.cjs +49 -0
- package/test/maintenance.test.cjs +1 -1
- package/test/npm-publication.test.cjs +141 -0
- package/test/recepcion-reparada.test.cjs +98 -0
- package/test/resilience-binary.test.cjs +69 -0
- package/test/resilience-transport.test.cjs +34 -0
- package/test/types.test.ts +5 -0
- package/test/upgrade.test.cjs +104 -0
- package/tsconfig.json +20 -0
- package/WAProto/p.html +0 -1
- package/lib/KageExtra/Modded/message_builder.js +0 -2330
- package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
- package/lib/KageExtra/VoIP/index.js +0 -282
- package/lib/KageExtra/VoIP/relay-transport.js +0 -559
- package/lib/KageExtra/VoIP/signaling.js +0 -603
- package/lib/KageExtra/VoIP/types.js +0 -17
- package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
- package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
- package/lib/KageExtra/assets/wasm/loader.js +0 -5
- package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
- package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
- package/lib/KageExtra/index.js +0 -3
- package/lib/KageExtra/package.json +0 -1
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
- package/maintenance/revision-full-check.txt +0 -1097
- package/maintenance/revision-library-tests.tap +0 -1088
- package/maintenance/revision-protobuf.txt +0 -5
- package/maintenance/revision-syntax.txt +0 -5
- package/maintenance/schema-coverage.json +0 -23
- package/maintenance/schema-merge.json +0 -30
- package/maintenance/validation-node20.txt +0 -191
- package/maintenance/validation-node22.txt +0 -237
package/lib/Socket/socket.js
CHANGED
|
@@ -48,6 +48,20 @@ const makeSocket = (config) => {
|
|
|
48
48
|
let keepAliveReq;
|
|
49
49
|
let qrTimer;
|
|
50
50
|
let closed = false;
|
|
51
|
+
let serverTimeOffsetMs = 0;
|
|
52
|
+
const socketEndHandlers = new Set();
|
|
53
|
+
const runEndHandler = handler => {
|
|
54
|
+
try {
|
|
55
|
+
Promise.resolve(handler()).catch(error => logger.warn({ error }, 'socket cleanup failed'));
|
|
56
|
+
} catch (error) { logger.warn({ error }, 'socket cleanup failed'); }
|
|
57
|
+
};
|
|
58
|
+
const registerSocketEndHandler = handler => {
|
|
59
|
+
if (typeof handler !== 'function') throw new TypeError('Socket end handler must be a function');
|
|
60
|
+
if (closed) { runEndHandler(handler); return () => {}; }
|
|
61
|
+
socketEndHandlers.add(handler);
|
|
62
|
+
return () => socketEndHandlers.delete(handler);
|
|
63
|
+
};
|
|
64
|
+
registerSocketEndHandler(() => keys.disposeTransactionStorage?.());
|
|
51
65
|
const uqTagId = (0, Utils_1.generateMdTagPrefix)();
|
|
52
66
|
const generateMessageTag = () => `${uqTagId}${epoch++}`;
|
|
53
67
|
const sendPromise = (0, util_1.promisify)(ws.send);
|
|
@@ -132,7 +146,7 @@ const makeSocket = (config) => {
|
|
|
132
146
|
};
|
|
133
147
|
ws.on(`TAG:${msgId}`, onRecv);
|
|
134
148
|
ws.on('close', onErr); // if the socket closes, you'll never receive the message
|
|
135
|
-
ws.
|
|
149
|
+
ws.on('error', onErr);
|
|
136
150
|
});
|
|
137
151
|
return result;
|
|
138
152
|
}
|
|
@@ -251,6 +265,9 @@ const makeSocket = (config) => {
|
|
|
251
265
|
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
|
|
252
266
|
}
|
|
253
267
|
}
|
|
268
|
+
}).catch(error => {
|
|
269
|
+
logger.warn({ error: error?.message }, 'invalid incoming frame; reconnect required');
|
|
270
|
+
end(error);
|
|
254
271
|
});
|
|
255
272
|
};
|
|
256
273
|
const end = (error) => {
|
|
@@ -259,11 +276,15 @@ const makeSocket = (config) => {
|
|
|
259
276
|
return;
|
|
260
277
|
}
|
|
261
278
|
closed = true;
|
|
279
|
+
for (const handler of socketEndHandlers) runEndHandler(handler);
|
|
280
|
+
socketEndHandlers.clear();
|
|
262
281
|
logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
|
|
263
282
|
clearInterval(keepAliveReq);
|
|
264
283
|
clearTimeout(qrTimer);
|
|
265
284
|
ws.removeAllListeners('close');
|
|
266
285
|
ws.removeAllListeners('error');
|
|
286
|
+
// Closing an unfinished WebSocket handshake emits a late error.
|
|
287
|
+
ws.on('error', () => {});
|
|
267
288
|
ws.removeAllListeners('open');
|
|
268
289
|
ws.removeAllListeners('message');
|
|
269
290
|
if (!ws.isClosed && !ws.isClosing) {
|
|
@@ -568,6 +589,7 @@ const makeSocket = (config) => {
|
|
|
568
589
|
});
|
|
569
590
|
let didStartBuffer = false;
|
|
570
591
|
process.nextTick(() => {
|
|
592
|
+
if (closed) return;
|
|
571
593
|
var _a;
|
|
572
594
|
if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
|
|
573
595
|
// start buffering important events
|
|
@@ -608,7 +630,42 @@ const makeSocket = (config) => {
|
|
|
608
630
|
if (printQRInTerminal) {
|
|
609
631
|
(0, Utils_1.printQRIfNecessaryListener)(ev, logger);
|
|
610
632
|
}
|
|
633
|
+
// Account/session methods use this socket's transport and lifecycle.
|
|
634
|
+
const updateServerTimeOffset = ({ attrs } = {}) => {
|
|
635
|
+
const parsed = Number(attrs?.t);
|
|
636
|
+
if (!Number.isFinite(parsed) || parsed <= 0) return;
|
|
637
|
+
serverTimeOffsetMs = parsed * 1000 - Date.now();
|
|
638
|
+
logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
|
|
639
|
+
};
|
|
640
|
+
const sendUnifiedSession = async () => {
|
|
641
|
+
if (closed || !ws.isOpen) return;
|
|
642
|
+
const id = ((Date.now() + serverTimeOffsetMs + 3 * Defaults_1.TimeMs.Day) % Defaults_1.TimeMs.Week).toString();
|
|
643
|
+
try { await sendNode({ tag: 'ib', attrs: {}, content: [{ tag: 'unified_session', attrs: { id } }] }); }
|
|
644
|
+
catch (error) { logger.debug({ error }, 'failed to send unified_session telemetry'); }
|
|
645
|
+
};
|
|
646
|
+
const fetchAccountReachoutTimelock = async () => {
|
|
647
|
+
const result = await require('./mex').executeWMexQuery({}, Types_1.QueryIds.REACHOUT_TIMELOCK,
|
|
648
|
+
Types_1.XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag);
|
|
649
|
+
const parsed = {
|
|
650
|
+
isActive: !!result?.is_active,
|
|
651
|
+
timeEnforcementEnds: result?.time_enforcement_ends && result.time_enforcement_ends !== '0'
|
|
652
|
+
? new Date(parseInt(result.time_enforcement_ends, 10) * 1000) : undefined,
|
|
653
|
+
enforcementType: result?.enforcement_type ?? Types_1.ReachoutTimelockEnforcementType.DEFAULT
|
|
654
|
+
};
|
|
655
|
+
ev.emit('connection.update', { reachoutTimeLock: parsed });
|
|
656
|
+
return parsed;
|
|
657
|
+
};
|
|
658
|
+
const fetchNewChatMessageCap = async () => require('./mex').executeWMexQuery(
|
|
659
|
+
{ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, Types_1.QueryIds.MESSAGE_CAPPING_INFO,
|
|
660
|
+
Types_1.XWAPaths.xwa2_message_capping_info, query, generateMessageTag);
|
|
661
|
+
ws.on('CB:iq,,pair-success', updateServerTimeOffset);
|
|
662
|
+
ws.on('CB:success', node => { updateServerTimeOffset(node); void sendUnifiedSession(); });
|
|
611
663
|
return {
|
|
664
|
+
registerSocketEndHandler,
|
|
665
|
+
updateServerTimeOffset,
|
|
666
|
+
sendUnifiedSession,
|
|
667
|
+
fetchAccountReachoutTimelock,
|
|
668
|
+
fetchNewChatMessageCap,
|
|
612
669
|
type: 'md',
|
|
613
670
|
ws,
|
|
614
671
|
ev,
|
|
@@ -644,3 +701,2162 @@ function mapWebSocketError(handler) {
|
|
|
644
701
|
handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
|
|
645
702
|
};
|
|
646
703
|
}
|
|
704
|
+
|
|
705
|
+
// Kage: compatibilidad de API.
|
|
706
|
+
const __kageModule33 = (() => {
|
|
707
|
+
const module = { exports: {} }; const exports = module.exports;
|
|
708
|
+
"use strict"
|
|
709
|
+
|
|
710
|
+
Object.defineProperty(exports, "__esModule", { value: true })
|
|
711
|
+
|
|
712
|
+
const { Boom } = require("@hapi/boom")
|
|
713
|
+
const { randomBytes } = require("crypto")
|
|
714
|
+
const { URL } = require("url")
|
|
715
|
+
const { promisify } = require("util")
|
|
716
|
+
const { proto } = require("../../WAProto")
|
|
717
|
+
const {
|
|
718
|
+
DEF_TAG_PREFIX,
|
|
719
|
+
DEF_CALLBACK_PREFIX
|
|
720
|
+
} = require("../Defaults/prefix")
|
|
721
|
+
const {
|
|
722
|
+
NOISE_WA_HEADER,
|
|
723
|
+
INITIAL_PREKEY_COUNT,
|
|
724
|
+
MIN_UPLOAD_INTERVAL,
|
|
725
|
+
MIN_PREKEY_COUNT,
|
|
726
|
+
UPLOAD_TIMEOUT
|
|
727
|
+
} = require("../Defaults/constants")
|
|
728
|
+
const { DisconnectReason } = require("../Types")
|
|
729
|
+
const {
|
|
730
|
+
addTransactionCapability,
|
|
731
|
+
aesEncryptCTR,
|
|
732
|
+
printQRIfNecessaryListener,
|
|
733
|
+
bindWaitForConnectionUpdate,
|
|
734
|
+
bytesToCrockford,
|
|
735
|
+
configureSuccessfulPairing,
|
|
736
|
+
Curve,
|
|
737
|
+
derivePairingCodeKey,
|
|
738
|
+
generateLoginNode,
|
|
739
|
+
generateMdTagPrefix,
|
|
740
|
+
generateRegistrationNode,
|
|
741
|
+
getCodeFromWSError,
|
|
742
|
+
getErrorCodeFromStreamError,
|
|
743
|
+
getNextPreKeysNode,
|
|
744
|
+
getPlatformId,
|
|
745
|
+
makeEventBuffer,
|
|
746
|
+
makeNoiseHandler,
|
|
747
|
+
promiseTimeout,
|
|
748
|
+
asciiDecode
|
|
749
|
+
} = require("../Utils")
|
|
750
|
+
const {
|
|
751
|
+
assertNodeErrorFree,
|
|
752
|
+
binaryNodeToString,
|
|
753
|
+
encodeBinaryNode,
|
|
754
|
+
getBinaryNodeChild,
|
|
755
|
+
getBinaryNodeChildren,
|
|
756
|
+
getAllBinaryNodeChildren,
|
|
757
|
+
isLidUser,
|
|
758
|
+
jidDecode,
|
|
759
|
+
jidEncode,
|
|
760
|
+
S_WHATSAPP_NET
|
|
761
|
+
} = require("../WABinary")
|
|
762
|
+
const { BinaryInfo } = require("../WAM")
|
|
763
|
+
const {
|
|
764
|
+
USyncUser,
|
|
765
|
+
USyncQuery
|
|
766
|
+
} = require("../WAUSync")
|
|
767
|
+
const { WebSocketClient } = require("./Client")
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Connects to WA servers and performs:
|
|
771
|
+
* - simple queries (no retry mechanism, wait for connection establishment)
|
|
772
|
+
* - listen to messages and emit events
|
|
773
|
+
* - query phone connection
|
|
774
|
+
*/
|
|
775
|
+
const makeSocket = (config) => {
|
|
776
|
+
const {
|
|
777
|
+
waWebSocketUrl,
|
|
778
|
+
connectTimeoutMs,
|
|
779
|
+
logger,
|
|
780
|
+
keepAliveIntervalMs,
|
|
781
|
+
browser,
|
|
782
|
+
auth: authState,
|
|
783
|
+
printQRInTerminal,
|
|
784
|
+
defaultQueryTimeoutMs,
|
|
785
|
+
transactionOpts,
|
|
786
|
+
qrTimeout,
|
|
787
|
+
makeSignalRepository
|
|
788
|
+
} = config
|
|
789
|
+
|
|
790
|
+
const uqTagId = generateMdTagPrefix()
|
|
791
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`
|
|
792
|
+
const publicWAMBuffer = new BinaryInfo()
|
|
793
|
+
const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl
|
|
794
|
+
|
|
795
|
+
if (config.mobile || url.protocol === 'tcp:') {
|
|
796
|
+
throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut })
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
|
800
|
+
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
|
|
804
|
+
const ephemeralKeyPair = Curve.generateKeyPair()
|
|
805
|
+
|
|
806
|
+
/** WA noise protocol wrapper */
|
|
807
|
+
const noise = makeNoiseHandler({
|
|
808
|
+
keyPair: ephemeralKeyPair,
|
|
809
|
+
NOISE_HEADER: NOISE_WA_HEADER,
|
|
810
|
+
logger,
|
|
811
|
+
routingInfo: authState?.creds?.routingInfo
|
|
812
|
+
})
|
|
813
|
+
|
|
814
|
+
const ws = new WebSocketClient(url, config)
|
|
815
|
+
|
|
816
|
+
ws.connect()
|
|
817
|
+
|
|
818
|
+
const sendPromise = promisify(ws.send)
|
|
819
|
+
|
|
820
|
+
/** send a raw buffer */
|
|
821
|
+
const sendRawMessage = async (data) => {
|
|
822
|
+
if (!ws.isOpen) {
|
|
823
|
+
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const bytes = noise.encodeFrame(data)
|
|
827
|
+
|
|
828
|
+
await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
|
|
829
|
+
try {
|
|
830
|
+
await sendPromise.call(ws, bytes)
|
|
831
|
+
resolve()
|
|
832
|
+
}
|
|
833
|
+
catch (error) {
|
|
834
|
+
reject(error)
|
|
835
|
+
}
|
|
836
|
+
})
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** send a binary node */
|
|
840
|
+
const sendNode = (frame) => {
|
|
841
|
+
if (logger.level === 'trace') {
|
|
842
|
+
logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
const buff = encodeBinaryNode(frame)
|
|
846
|
+
|
|
847
|
+
return sendRawMessage(buff)
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Wait for a message with a certain tag to be received
|
|
852
|
+
* @param msgId the message tag to await
|
|
853
|
+
* @param timeoutMs timeout after which the promise will reject
|
|
854
|
+
*/
|
|
855
|
+
const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
|
|
856
|
+
let onRecv
|
|
857
|
+
let onErr
|
|
858
|
+
|
|
859
|
+
try {
|
|
860
|
+
const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
861
|
+
onRecv = data => {
|
|
862
|
+
resolve(data)
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
onErr = err => {
|
|
866
|
+
reject(err ||
|
|
867
|
+
new Boom('Connection Closed', {
|
|
868
|
+
statusCode: DisconnectReason.connectionClosed
|
|
869
|
+
}))
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
ws.on(`TAG:${msgId}`, onRecv)
|
|
873
|
+
ws.on('close', onErr)
|
|
874
|
+
ws.on('error', onErr)
|
|
875
|
+
|
|
876
|
+
return () => reject(new Boom('Query Cancelled'))
|
|
877
|
+
})
|
|
878
|
+
|
|
879
|
+
return result
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
catch (error) {
|
|
883
|
+
// Catch timeout and return undefined instead of throwing
|
|
884
|
+
if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
|
|
885
|
+
logger?.warn?.({ msgId }, 'timed out waiting for message')
|
|
886
|
+
return undefined
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
throw error
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
finally {
|
|
893
|
+
if (onRecv)
|
|
894
|
+
ws.off(`TAG:${msgId}`, onRecv)
|
|
895
|
+
if (onErr) {
|
|
896
|
+
ws.off('close', onErr)
|
|
897
|
+
ws.off('error', onErr)
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
|
903
|
+
const query = async (node, timeoutMs) => {
|
|
904
|
+
if (!node.attrs.id) {
|
|
905
|
+
node.attrs.id = generateMessageTag()
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const msgId = node.attrs.id
|
|
909
|
+
const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
|
|
910
|
+
const result = waitForMessage(msgId, timeoutMs).catch(reject)
|
|
911
|
+
sendNode(node)
|
|
912
|
+
.then(async () => resolve(await result))
|
|
913
|
+
.catch(reject)
|
|
914
|
+
})
|
|
915
|
+
|
|
916
|
+
if (result && 'tag' in result) {
|
|
917
|
+
assertNodeErrorFree(result)
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
return result
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
|
|
924
|
+
const digestKeyBundle = async () => {
|
|
925
|
+
const res = await query({
|
|
926
|
+
tag: 'iq',
|
|
927
|
+
attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
|
|
928
|
+
content: [{ tag: 'digest', attrs: {} }]
|
|
929
|
+
})
|
|
930
|
+
|
|
931
|
+
const digestNode = getBinaryNodeChild(res, 'digest')
|
|
932
|
+
|
|
933
|
+
if (!digestNode) {
|
|
934
|
+
await uploadPreKeys()
|
|
935
|
+
throw new Error('encrypt/get digest returned no digest node')
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
// Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
|
|
940
|
+
const rotateSignedPreKey = async () => {
|
|
941
|
+
const newId = (creds.signedPreKey.keyId || 0) + 1
|
|
942
|
+
const skey = await signedKeyPair(creds.signedIdentityKey, newId)
|
|
943
|
+
|
|
944
|
+
await query({
|
|
945
|
+
tag: 'iq',
|
|
946
|
+
attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
|
|
947
|
+
content: [
|
|
948
|
+
{
|
|
949
|
+
tag: 'rotate',
|
|
950
|
+
attrs: {},
|
|
951
|
+
content: [xmppSignedPreKey(skey)]
|
|
952
|
+
}
|
|
953
|
+
]
|
|
954
|
+
})
|
|
955
|
+
|
|
956
|
+
// Persist new signed pre-key in creds
|
|
957
|
+
ev.emit('creds.update', { signedPreKey: skey })
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
const executeUSyncQuery = async (usyncQuery) => {
|
|
961
|
+
if (usyncQuery.protocols.length === 0) {
|
|
962
|
+
throw new Boom('USyncQuery must have at least one protocol')
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
// todo: validate users, throw WARNING on no valid users
|
|
966
|
+
// variable below has only validated users
|
|
967
|
+
const validUsers = usyncQuery.users
|
|
968
|
+
const userNodes = validUsers.map(user => {
|
|
969
|
+
return {
|
|
970
|
+
tag: 'user',
|
|
971
|
+
attrs: {
|
|
972
|
+
jid: !user.phone ? user.id : undefined
|
|
973
|
+
},
|
|
974
|
+
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
|
975
|
+
}
|
|
976
|
+
})
|
|
977
|
+
|
|
978
|
+
const listNode = {
|
|
979
|
+
tag: 'list',
|
|
980
|
+
attrs: {},
|
|
981
|
+
content: userNodes
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
const queryNode = {
|
|
985
|
+
tag: 'query',
|
|
986
|
+
attrs: {},
|
|
987
|
+
content: usyncQuery.protocols.map(a => a.getQueryElement())
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
const iq = {
|
|
991
|
+
tag: 'iq',
|
|
992
|
+
attrs: {
|
|
993
|
+
to: S_WHATSAPP_NET,
|
|
994
|
+
type: 'get',
|
|
995
|
+
xmlns: 'usync'
|
|
996
|
+
},
|
|
997
|
+
content: [
|
|
998
|
+
{
|
|
999
|
+
tag: 'usync',
|
|
1000
|
+
attrs: {
|
|
1001
|
+
context: usyncQuery.context,
|
|
1002
|
+
mode: usyncQuery.mode,
|
|
1003
|
+
sid: generateMessageTag(),
|
|
1004
|
+
last: 'true',
|
|
1005
|
+
index: '0'
|
|
1006
|
+
},
|
|
1007
|
+
content: [queryNode, listNode]
|
|
1008
|
+
}
|
|
1009
|
+
]
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
const result = await query(iq)
|
|
1013
|
+
|
|
1014
|
+
return usyncQuery.parseUSyncQueryResult(result)
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
const onWhatsApp = async (...phoneNumber) => {
|
|
1018
|
+
let usyncQuery = new USyncQuery()
|
|
1019
|
+
let contactEnabled = false
|
|
1020
|
+
|
|
1021
|
+
for (const jid of phoneNumber) {
|
|
1022
|
+
if (isLidUser(jid)) {
|
|
1023
|
+
logger?.warn('LIDs are not supported with onWhatsApp')
|
|
1024
|
+
continue
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
else {
|
|
1028
|
+
if (!contactEnabled) {
|
|
1029
|
+
contactEnabled = true
|
|
1030
|
+
usyncQuery = usyncQuery.withContactProtocol()
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`
|
|
1034
|
+
usyncQuery.withUser(new USyncUser().withPhone(phone))
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
if (usyncQuery.users.length === 0) {
|
|
1039
|
+
return [] // return early without forcing an empty query
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
const results = await executeUSyncQuery(usyncQuery)
|
|
1043
|
+
|
|
1044
|
+
if (results) {
|
|
1045
|
+
return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }))
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const pnFromLIDUSync = async (jids) => {
|
|
1050
|
+
const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background')
|
|
1051
|
+
for (const jid of jids) {
|
|
1052
|
+
if (isLidUser(jid)) {
|
|
1053
|
+
logger?.warn('LID user found in LID fetch call')
|
|
1054
|
+
continue
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
else {
|
|
1058
|
+
usyncQuery.withUser(new USyncUser().withId(jid))
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
if (usyncQuery.users.length === 0) {
|
|
1063
|
+
return [] // return early without forcing an empty query
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
const results = await executeUSyncQuery(usyncQuery)
|
|
1067
|
+
|
|
1068
|
+
if (results) {
|
|
1069
|
+
return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }))
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
return []
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
const ev = makeEventBuffer(logger)
|
|
1076
|
+
const { creds } = authState
|
|
1077
|
+
|
|
1078
|
+
// add transaction capability
|
|
1079
|
+
const keys = addTransactionCapability(authState.keys, logger, transactionOpts)
|
|
1080
|
+
const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync)
|
|
1081
|
+
|
|
1082
|
+
let lastDateRecv
|
|
1083
|
+
let epoch = 1
|
|
1084
|
+
let keepAliveReq
|
|
1085
|
+
let qrTimer
|
|
1086
|
+
let closed = false
|
|
1087
|
+
|
|
1088
|
+
/** log & process any unexpected errors */
|
|
1089
|
+
const onUnexpectedError = (err, msg) => {
|
|
1090
|
+
logger.error({ err }, `unexpected error in '${msg}'`)
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/** await the next incoming message */
|
|
1094
|
+
const awaitNextMessage = async (sendMsg) => {
|
|
1095
|
+
if (!ws.isOpen) {
|
|
1096
|
+
throw new Boom('Connection Closed', {
|
|
1097
|
+
statusCode: DisconnectReason.connectionClosed
|
|
1098
|
+
})
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
let onOpen
|
|
1102
|
+
let onClose
|
|
1103
|
+
|
|
1104
|
+
const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
|
|
1105
|
+
onOpen = resolve
|
|
1106
|
+
onClose = mapWebSocketError(reject)
|
|
1107
|
+
|
|
1108
|
+
ws.on('frame', onOpen)
|
|
1109
|
+
ws.on('close', onClose)
|
|
1110
|
+
ws.on('error', onClose)
|
|
1111
|
+
}).finally(() => {
|
|
1112
|
+
ws.off('frame', onOpen)
|
|
1113
|
+
ws.off('close', onClose)
|
|
1114
|
+
ws.off('error', onClose)
|
|
1115
|
+
})
|
|
1116
|
+
|
|
1117
|
+
if (sendMsg) {
|
|
1118
|
+
sendRawMessage(sendMsg).catch(onClose)
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
return result
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/** connection handshake */
|
|
1125
|
+
const validateConnection = async () => {
|
|
1126
|
+
let helloMsg = {
|
|
1127
|
+
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
|
|
1131
|
+
|
|
1132
|
+
logger.info({ browser, helloMsg }, 'connected to WA')
|
|
1133
|
+
|
|
1134
|
+
const init = proto.HandshakeMessage.encode(helloMsg).finish()
|
|
1135
|
+
const result = await awaitNextMessage(init)
|
|
1136
|
+
const handshake = proto.HandshakeMessage.decode(result)
|
|
1137
|
+
|
|
1138
|
+
logger.trace({ handshake }, 'handshake recv from WA')
|
|
1139
|
+
|
|
1140
|
+
const keyEnc = await noise.processHandshake(handshake, creds.noiseKey)
|
|
1141
|
+
|
|
1142
|
+
let node
|
|
1143
|
+
|
|
1144
|
+
if (!creds.me) {
|
|
1145
|
+
node = generateRegistrationNode(creds, config)
|
|
1146
|
+
logger.info({ node }, 'not logged in, attempting registration...')
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
else {
|
|
1150
|
+
node = generateLoginNode(creds.me.id, config)
|
|
1151
|
+
logger.info({ node }, 'logging in...')
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish())
|
|
1155
|
+
|
|
1156
|
+
await sendRawMessage(proto.HandshakeMessage.encode({
|
|
1157
|
+
clientFinish: {
|
|
1158
|
+
static: keyEnc,
|
|
1159
|
+
payload: payloadEnc
|
|
1160
|
+
}
|
|
1161
|
+
}).finish())
|
|
1162
|
+
|
|
1163
|
+
await noise.finishInit()
|
|
1164
|
+
|
|
1165
|
+
startKeepAliveRequest()
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
const getAvailablePreKeysOnServer = async () => {
|
|
1169
|
+
const result = await query({
|
|
1170
|
+
tag: 'iq',
|
|
1171
|
+
attrs: {
|
|
1172
|
+
id: generateMessageTag(),
|
|
1173
|
+
xmlns: 'encrypt',
|
|
1174
|
+
type: 'get',
|
|
1175
|
+
to: S_WHATSAPP_NET
|
|
1176
|
+
},
|
|
1177
|
+
content: [
|
|
1178
|
+
{ tag: 'count', attrs: {} }
|
|
1179
|
+
]
|
|
1180
|
+
})
|
|
1181
|
+
|
|
1182
|
+
const countChild = getBinaryNodeChild(result, 'count')
|
|
1183
|
+
|
|
1184
|
+
return +countChild.attrs.value
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// Pre-key upload state management
|
|
1188
|
+
let uploadPreKeysPromise = null
|
|
1189
|
+
let lastUploadTime = 0
|
|
1190
|
+
|
|
1191
|
+
/** generates and uploads a set of pre-keys to the server */
|
|
1192
|
+
const uploadPreKeys = async (count = MIN_PREKEY_COUNT, retryCount = 0) => {
|
|
1193
|
+
// Check minimum interval (except for retries)
|
|
1194
|
+
if (retryCount === 0) {
|
|
1195
|
+
const timeSinceLastUpload = Date.now() - lastUploadTime
|
|
1196
|
+
|
|
1197
|
+
if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
|
|
1198
|
+
logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`)
|
|
1199
|
+
return
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// Prevent multiple concurrent uploads
|
|
1204
|
+
if (uploadPreKeysPromise) {
|
|
1205
|
+
logger.debug('Pre-key upload already in progress, waiting for completion')
|
|
1206
|
+
await uploadPreKeysPromise
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
const uploadLogic = async () => {
|
|
1210
|
+
logger.info({ count, retryCount }, 'uploading pre-keys')
|
|
1211
|
+
|
|
1212
|
+
// Generate and save pre-keys atomically (prevents ID collisions on retry)
|
|
1213
|
+
const node = await keys.transaction(async () => {
|
|
1214
|
+
logger.debug({ requestedCount: count }, 'generating pre-keys with requested count')
|
|
1215
|
+
|
|
1216
|
+
const { update, node } = await getNextPreKeysNode({ creds, keys }, count)
|
|
1217
|
+
|
|
1218
|
+
// Update credentials immediately to prevent duplicate IDs on retry
|
|
1219
|
+
ev.emit('creds.update', update)
|
|
1220
|
+
|
|
1221
|
+
return node // Only return node since update is already used
|
|
1222
|
+
}, creds?.me?.id || 'upload-pre-keys')
|
|
1223
|
+
|
|
1224
|
+
// Upload to server (outside transaction, can fail without affecting local keys)
|
|
1225
|
+
try {
|
|
1226
|
+
await query(node)
|
|
1227
|
+
logger.info({ count }, 'uploaded pre-keys successfully')
|
|
1228
|
+
lastUploadTime = Date.now()
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
catch (uploadError) {
|
|
1232
|
+
logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server')
|
|
1233
|
+
|
|
1234
|
+
// Exponential backoff retry (max 3 retries)
|
|
1235
|
+
if (retryCount < 3) {
|
|
1236
|
+
const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000)
|
|
1237
|
+
|
|
1238
|
+
logger.info(`Retrying pre-key upload in ${backoffDelay}ms`)
|
|
1239
|
+
|
|
1240
|
+
await new Promise(resolve => setTimeout(resolve, backoffDelay))
|
|
1241
|
+
|
|
1242
|
+
return uploadPreKeys(count, retryCount + 1)
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
throw uploadError
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// Add timeout protection
|
|
1250
|
+
uploadPreKeysPromise = Promise.race([
|
|
1251
|
+
uploadLogic(),
|
|
1252
|
+
new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
|
|
1253
|
+
])
|
|
1254
|
+
|
|
1255
|
+
try {
|
|
1256
|
+
await uploadPreKeysPromise
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
finally {
|
|
1260
|
+
uploadPreKeysPromise = null
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
const verifyCurrentPreKeyExists = async () => {
|
|
1265
|
+
const currentPreKeyId = creds.nextPreKeyId - 1
|
|
1266
|
+
|
|
1267
|
+
if (currentPreKeyId <= 0) {
|
|
1268
|
+
return { exists: false, currentPreKeyId: 0 }
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()])
|
|
1272
|
+
const exists = !!preKeys[currentPreKeyId.toString()]
|
|
1273
|
+
|
|
1274
|
+
return { exists, currentPreKeyId }
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
1278
|
+
try {
|
|
1279
|
+
let count = 0
|
|
1280
|
+
|
|
1281
|
+
const preKeyCount = await getAvailablePreKeysOnServer()
|
|
1282
|
+
|
|
1283
|
+
if (preKeyCount === 0)
|
|
1284
|
+
count = INITIAL_PREKEY_COUNT
|
|
1285
|
+
else
|
|
1286
|
+
count = MIN_PREKEY_COUNT
|
|
1287
|
+
|
|
1288
|
+
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists()
|
|
1289
|
+
|
|
1290
|
+
logger.info(`${preKeyCount} pre-keys found on server`)
|
|
1291
|
+
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`)
|
|
1292
|
+
|
|
1293
|
+
const lowServerCount = preKeyCount <= count
|
|
1294
|
+
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
|
|
1295
|
+
const shouldUpload = lowServerCount || missingCurrentPreKey
|
|
1296
|
+
|
|
1297
|
+
if (shouldUpload) {
|
|
1298
|
+
const reasons = []
|
|
1299
|
+
|
|
1300
|
+
if (lowServerCount)
|
|
1301
|
+
reasons.push(`server count low (${preKeyCount})`)
|
|
1302
|
+
|
|
1303
|
+
if (missingCurrentPreKey)
|
|
1304
|
+
reasons.push(`current prekey ${currentPreKeyId} missing from storage`)
|
|
1305
|
+
|
|
1306
|
+
logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`)
|
|
1307
|
+
|
|
1308
|
+
await uploadPreKeys(count)
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
else {
|
|
1312
|
+
logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`)
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
catch (error) {
|
|
1317
|
+
logger.error({ error }, 'Failed to check/upload pre-keys during initialization')
|
|
1318
|
+
// Don't throw - allow connection to continue even if pre-key check fails
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
const onMessageReceived = async (data) => {
|
|
1323
|
+
await noise.decodeFrame(data, frame => {
|
|
1324
|
+
// reset ping timeout
|
|
1325
|
+
lastDateRecv = new Date()
|
|
1326
|
+
|
|
1327
|
+
let anyTriggered = false
|
|
1328
|
+
|
|
1329
|
+
anyTriggered = ws.emit('frame', frame)
|
|
1330
|
+
|
|
1331
|
+
// if it's a binary node
|
|
1332
|
+
if (!(frame instanceof Uint8Array)) {
|
|
1333
|
+
const msgId = frame.attrs.id
|
|
1334
|
+
|
|
1335
|
+
if (logger.level === 'trace') {
|
|
1336
|
+
logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/* Check if this is a response to a message we sent */
|
|
1340
|
+
anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
|
|
1341
|
+
|
|
1342
|
+
/* Check if this is a response to a message we are expecting */
|
|
1343
|
+
const l0 = frame.tag
|
|
1344
|
+
const l1 = frame.attrs || {}
|
|
1345
|
+
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
|
|
1346
|
+
|
|
1347
|
+
for (const key of Object.keys(l1)) {
|
|
1348
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
|
|
1349
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
|
|
1350
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
|
|
1354
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
|
|
1355
|
+
|
|
1356
|
+
if (!anyTriggered && logger.level === 'debug') {
|
|
1357
|
+
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
})
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
const end = (error) => {
|
|
1364
|
+
if (closed) {
|
|
1365
|
+
logger.trace({ trace: error?.stack }, 'connection already closed')
|
|
1366
|
+
return
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
closed = true
|
|
1370
|
+
|
|
1371
|
+
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
|
|
1372
|
+
|
|
1373
|
+
clearInterval(keepAliveReq)
|
|
1374
|
+
clearTimeout(qrTimer)
|
|
1375
|
+
|
|
1376
|
+
ws.removeAllListeners('close')
|
|
1377
|
+
ws.removeAllListeners('open')
|
|
1378
|
+
ws.removeAllListeners('message')
|
|
1379
|
+
|
|
1380
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
1381
|
+
try {
|
|
1382
|
+
ws.close()
|
|
1383
|
+
}
|
|
1384
|
+
catch { }
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
ev.emit('connection.update', {
|
|
1388
|
+
connection: 'close',
|
|
1389
|
+
lastDisconnect: {
|
|
1390
|
+
error,
|
|
1391
|
+
date: new Date()
|
|
1392
|
+
}
|
|
1393
|
+
})
|
|
1394
|
+
|
|
1395
|
+
ev.removeAllListeners('connection.update')
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
const waitForSocketOpen = async () => {
|
|
1399
|
+
if (ws.isOpen) {
|
|
1400
|
+
return
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
if (ws.isClosed || ws.isClosing) {
|
|
1404
|
+
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
let onOpen
|
|
1408
|
+
let onClose
|
|
1409
|
+
|
|
1410
|
+
await new Promise((resolve, reject) => {
|
|
1411
|
+
onOpen = () => resolve(undefined)
|
|
1412
|
+
onClose = mapWebSocketError(reject)
|
|
1413
|
+
|
|
1414
|
+
ws.on('open', onOpen)
|
|
1415
|
+
ws.on('close', onClose)
|
|
1416
|
+
ws.on('error', onClose)
|
|
1417
|
+
}).finally(() => {
|
|
1418
|
+
ws.off('open', onOpen)
|
|
1419
|
+
ws.off('close', onClose)
|
|
1420
|
+
ws.off('error', onClose)
|
|
1421
|
+
})
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
|
|
1425
|
+
if (!lastDateRecv) {
|
|
1426
|
+
lastDateRecv = new Date()
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
const diff = Date.now() - lastDateRecv.getTime()
|
|
1430
|
+
|
|
1431
|
+
/*
|
|
1432
|
+
check if it's been a suspicious amount of time since the server responded with our last seen
|
|
1433
|
+
it could be that the network is down
|
|
1434
|
+
*/
|
|
1435
|
+
if (diff > keepAliveIntervalMs + 5000) {
|
|
1436
|
+
end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
else if (ws.isOpen) {
|
|
1440
|
+
// if its all good, send a keep alive request
|
|
1441
|
+
query({
|
|
1442
|
+
tag: 'iq',
|
|
1443
|
+
attrs: {
|
|
1444
|
+
id: generateMessageTag(),
|
|
1445
|
+
to: S_WHATSAPP_NET,
|
|
1446
|
+
type: 'get',
|
|
1447
|
+
xmlns: 'w:p',
|
|
1448
|
+
},
|
|
1449
|
+
content: [{ tag: 'ping', attrs: {} }]
|
|
1450
|
+
}).catch(err => {
|
|
1451
|
+
logger.error({ trace: err.stack }, 'error in sending keep alive')
|
|
1452
|
+
})
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
else {
|
|
1456
|
+
logger.warn('keep alive called when WS not open')
|
|
1457
|
+
}
|
|
1458
|
+
}, keepAliveIntervalMs))
|
|
1459
|
+
|
|
1460
|
+
/** i have no idea why this exists. pls enlighten me */
|
|
1461
|
+
const sendPassiveIq = (tag) => (query({
|
|
1462
|
+
tag: 'iq',
|
|
1463
|
+
attrs: {
|
|
1464
|
+
to: S_WHATSAPP_NET,
|
|
1465
|
+
xmlns: 'passive',
|
|
1466
|
+
type: 'set',
|
|
1467
|
+
},
|
|
1468
|
+
content: [
|
|
1469
|
+
{ tag, attrs: {} }
|
|
1470
|
+
]
|
|
1471
|
+
}))
|
|
1472
|
+
|
|
1473
|
+
/** logout & invalidate connection */
|
|
1474
|
+
const logout = async (msg) => {
|
|
1475
|
+
const jid = authState.creds.me?.id
|
|
1476
|
+
|
|
1477
|
+
if (jid) {
|
|
1478
|
+
await sendNode({
|
|
1479
|
+
tag: 'iq',
|
|
1480
|
+
attrs: {
|
|
1481
|
+
to: S_WHATSAPP_NET,
|
|
1482
|
+
type: 'set',
|
|
1483
|
+
id: generateMessageTag(),
|
|
1484
|
+
xmlns: 'md'
|
|
1485
|
+
},
|
|
1486
|
+
content: [
|
|
1487
|
+
{
|
|
1488
|
+
tag: 'remove-companion-device',
|
|
1489
|
+
attrs: {
|
|
1490
|
+
jid,
|
|
1491
|
+
reason: 'user_initiated'
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
]
|
|
1495
|
+
})
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }))
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
const requestPairingCode = async (phoneNumber, code) => {
|
|
1502
|
+
authState.creds.pairingCode = code?.toUpperCase() || asciiDecode([83, 85, 75, 49, 67, 72, 52, 78])
|
|
1503
|
+
|
|
1504
|
+
authState.creds.me = {
|
|
1505
|
+
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
|
1506
|
+
name: '~'
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
ev.emit('creds.update', authState.creds)
|
|
1510
|
+
|
|
1511
|
+
await sendNode({
|
|
1512
|
+
tag: 'iq',
|
|
1513
|
+
attrs: {
|
|
1514
|
+
to: S_WHATSAPP_NET,
|
|
1515
|
+
type: 'set',
|
|
1516
|
+
id: generateMessageTag(),
|
|
1517
|
+
xmlns: 'md'
|
|
1518
|
+
},
|
|
1519
|
+
content: [
|
|
1520
|
+
{
|
|
1521
|
+
tag: 'link_code_companion_reg',
|
|
1522
|
+
attrs: {
|
|
1523
|
+
jid: authState.creds.me.id,
|
|
1524
|
+
stage: 'companion_hello',
|
|
1525
|
+
should_show_push_notification: 'true'
|
|
1526
|
+
},
|
|
1527
|
+
content: [
|
|
1528
|
+
{
|
|
1529
|
+
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
1530
|
+
attrs: {},
|
|
1531
|
+
content: await generatePairingKey()
|
|
1532
|
+
},
|
|
1533
|
+
{
|
|
1534
|
+
tag: 'companion_server_auth_key_pub',
|
|
1535
|
+
attrs: {},
|
|
1536
|
+
content: authState.creds.noiseKey.public
|
|
1537
|
+
},
|
|
1538
|
+
{
|
|
1539
|
+
tag: 'companion_platform_id',
|
|
1540
|
+
attrs: {},
|
|
1541
|
+
content: getPlatformId(browser[1])
|
|
1542
|
+
},
|
|
1543
|
+
{
|
|
1544
|
+
tag: 'companion_platform_display',
|
|
1545
|
+
attrs: {},
|
|
1546
|
+
content: `${browser[1]} (${browser[0]})`
|
|
1547
|
+
},
|
|
1548
|
+
{
|
|
1549
|
+
tag: 'link_code_pairing_nonce',
|
|
1550
|
+
attrs: {},
|
|
1551
|
+
content: '0'
|
|
1552
|
+
}
|
|
1553
|
+
]
|
|
1554
|
+
}
|
|
1555
|
+
]
|
|
1556
|
+
})
|
|
1557
|
+
|
|
1558
|
+
return authState.creds.pairingCode
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
async function generatePairingKey() {
|
|
1562
|
+
const salt = randomBytes(32)
|
|
1563
|
+
const randomIv = randomBytes(16)
|
|
1564
|
+
const key = await derivePairingCodeKey(authState.creds.pairingCode, salt)
|
|
1565
|
+
const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
|
|
1566
|
+
|
|
1567
|
+
return Buffer.concat([salt, randomIv, ciphered])
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
const sendWAMBuffer = (wamBuffer) => {
|
|
1571
|
+
return query({
|
|
1572
|
+
tag: 'iq',
|
|
1573
|
+
attrs: {
|
|
1574
|
+
to: S_WHATSAPP_NET,
|
|
1575
|
+
id: generateMessageTag(),
|
|
1576
|
+
xmlns: 'w:stats'
|
|
1577
|
+
},
|
|
1578
|
+
content: [
|
|
1579
|
+
{
|
|
1580
|
+
tag: 'add',
|
|
1581
|
+
attrs: { t: Math.round(Date.now() / 1000) + '' },
|
|
1582
|
+
content: wamBuffer
|
|
1583
|
+
}
|
|
1584
|
+
]
|
|
1585
|
+
})
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
ws.on('message', onMessageReceived)
|
|
1589
|
+
|
|
1590
|
+
ws.on('open', async () => {
|
|
1591
|
+
try {
|
|
1592
|
+
await validateConnection()
|
|
1593
|
+
}
|
|
1594
|
+
catch (err) {
|
|
1595
|
+
logger.error({ err }, 'error in validating connection')
|
|
1596
|
+
end(err)
|
|
1597
|
+
}
|
|
1598
|
+
})
|
|
1599
|
+
|
|
1600
|
+
ws.on('error', mapWebSocketError(end))
|
|
1601
|
+
|
|
1602
|
+
ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
|
|
1603
|
+
|
|
1604
|
+
// the server terminated the connection
|
|
1605
|
+
ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
|
|
1606
|
+
|
|
1607
|
+
// QR gen
|
|
1608
|
+
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
1609
|
+
const iq = {
|
|
1610
|
+
tag: 'iq',
|
|
1611
|
+
attrs: {
|
|
1612
|
+
to: S_WHATSAPP_NET,
|
|
1613
|
+
type: 'result',
|
|
1614
|
+
id: stanza.attrs.id,
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
await sendNode(iq)
|
|
1619
|
+
|
|
1620
|
+
const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device')
|
|
1621
|
+
const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref')
|
|
1622
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
|
|
1623
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
|
|
1624
|
+
const advB64 = creds.advSecretKey
|
|
1625
|
+
|
|
1626
|
+
let qrMs = qrTimeout || 60000 // time to let a QR live
|
|
1627
|
+
|
|
1628
|
+
const genPairQR = () => {
|
|
1629
|
+
if (!ws.isOpen) {
|
|
1630
|
+
return
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
const refNode = refNodes.shift()
|
|
1634
|
+
|
|
1635
|
+
if (!refNode) {
|
|
1636
|
+
end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
|
|
1637
|
+
return
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
const ref = refNode.content.toString('utf-8')
|
|
1641
|
+
const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',')
|
|
1642
|
+
|
|
1643
|
+
ev.emit('connection.update', { qr })
|
|
1644
|
+
qrTimer = setTimeout(genPairQR, qrMs)
|
|
1645
|
+
qrMs = qrTimeout || 20000 // shorter subsequent qrs
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
genPairQR()
|
|
1649
|
+
})
|
|
1650
|
+
|
|
1651
|
+
// device paired for the first time
|
|
1652
|
+
// if device pairs successfully, the server asks to restart the connection
|
|
1653
|
+
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
1654
|
+
logger.debug('pair success recv')
|
|
1655
|
+
try {
|
|
1656
|
+
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
|
|
1657
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...')
|
|
1658
|
+
|
|
1659
|
+
ev.emit('creds.update', updatedCreds)
|
|
1660
|
+
ev.emit('connection.update', { isNewLogin: true, qr: undefined })
|
|
1661
|
+
|
|
1662
|
+
await sendNode(reply)
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
catch (error) {
|
|
1666
|
+
logger.info({ trace: error.stack }, 'error in pairing')
|
|
1667
|
+
end(error)
|
|
1668
|
+
}
|
|
1669
|
+
})
|
|
1670
|
+
|
|
1671
|
+
// login complete
|
|
1672
|
+
// login complete
|
|
1673
|
+
ws.on('CB:success', async (node) => {
|
|
1674
|
+
try {
|
|
1675
|
+
await uploadPreKeysToServerIfRequired()
|
|
1676
|
+
await sendPassiveIq('active')
|
|
1677
|
+
|
|
1678
|
+
// After successful login, validate our key-bundle against server
|
|
1679
|
+
try {
|
|
1680
|
+
await digestKeyBundle()
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
catch (e) {
|
|
1684
|
+
logger.warn({ e }, 'failed to run digest after login');
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
catch (err) {
|
|
1689
|
+
logger.warn({ err }, 'failed to send initial passive iq')
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
logger.info('opened connection to WA')
|
|
1693
|
+
|
|
1694
|
+
clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
|
|
1695
|
+
|
|
1696
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
|
|
1697
|
+
ev.emit('connection.update', { connection: 'open' })
|
|
1698
|
+
|
|
1699
|
+
if (node.attrs.lid && authState.creds.me?.id) {
|
|
1700
|
+
const myLID = node.attrs.lid
|
|
1701
|
+
|
|
1702
|
+
process.nextTick(async () => {
|
|
1703
|
+
try {
|
|
1704
|
+
const myPN = authState.creds.me.id
|
|
1705
|
+
|
|
1706
|
+
// Store our own LID-PN mapping
|
|
1707
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }])
|
|
1708
|
+
|
|
1709
|
+
// Create device list for our own user (needed for bulk migration)
|
|
1710
|
+
const { user, device } = jidDecode(myPN)
|
|
1711
|
+
|
|
1712
|
+
await authState.keys.set({
|
|
1713
|
+
'device-list': {
|
|
1714
|
+
[user]: [device?.toString() || '0']
|
|
1715
|
+
}
|
|
1716
|
+
})
|
|
1717
|
+
|
|
1718
|
+
// migrate our own session
|
|
1719
|
+
await signalRepository.migrateSession(myPN, myLID)
|
|
1720
|
+
|
|
1721
|
+
logger.info({ myPN, myLID }, 'Own LID session created successfully')
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
catch (error) {
|
|
1725
|
+
logger.error({ error, lid: myLID }, 'Failed to create own LID session')
|
|
1726
|
+
}
|
|
1727
|
+
})
|
|
1728
|
+
}
|
|
1729
|
+
})
|
|
1730
|
+
|
|
1731
|
+
ws.on('CB:stream:error', (node) => {
|
|
1732
|
+
const [reasonNode] = getAllBinaryNodeChildren(node)
|
|
1733
|
+
|
|
1734
|
+
logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out')
|
|
1735
|
+
|
|
1736
|
+
const { reason, statusCode } = getErrorCodeFromStreamError(node)
|
|
1737
|
+
|
|
1738
|
+
end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }))
|
|
1739
|
+
});
|
|
1740
|
+
|
|
1741
|
+
// stream fail, possible logout
|
|
1742
|
+
ws.on('CB:failure', (node) => {
|
|
1743
|
+
const reason = +(node.attrs.reason || 500)
|
|
1744
|
+
|
|
1745
|
+
end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
|
|
1746
|
+
})
|
|
1747
|
+
|
|
1748
|
+
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
1749
|
+
end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }))
|
|
1750
|
+
})
|
|
1751
|
+
|
|
1752
|
+
ws.on('CB:ib,,offline_preview', (node) => {
|
|
1753
|
+
logger.info('offline preview received', JSON.stringify(node))
|
|
1754
|
+
|
|
1755
|
+
sendNode({
|
|
1756
|
+
tag: 'ib',
|
|
1757
|
+
attrs: {},
|
|
1758
|
+
content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
|
|
1759
|
+
})
|
|
1760
|
+
})
|
|
1761
|
+
|
|
1762
|
+
ws.on('CB:ib,,edge_routing', (node) => {
|
|
1763
|
+
const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
|
|
1764
|
+
const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
|
|
1765
|
+
|
|
1766
|
+
if (routingInfo?.content) {
|
|
1767
|
+
authState.creds.routingInfo = Buffer.from(routingInfo?.content)
|
|
1768
|
+
ev.emit('creds.update', authState.creds)
|
|
1769
|
+
}
|
|
1770
|
+
})
|
|
1771
|
+
|
|
1772
|
+
let didStartBuffer = false
|
|
1773
|
+
|
|
1774
|
+
process.nextTick(() => {
|
|
1775
|
+
if (creds.me?.id) {
|
|
1776
|
+
// start buffering important events
|
|
1777
|
+
// if we're logged in
|
|
1778
|
+
ev.buffer()
|
|
1779
|
+
didStartBuffer = true
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
|
|
1783
|
+
})
|
|
1784
|
+
|
|
1785
|
+
// called when all offline notifs are handled
|
|
1786
|
+
ws.on('CB:ib,,offline', (node) => {
|
|
1787
|
+
const child = getBinaryNodeChild(node, 'offline')
|
|
1788
|
+
const offlineNotifs = +(child?.attrs.count || 0)
|
|
1789
|
+
|
|
1790
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`)
|
|
1791
|
+
|
|
1792
|
+
if (didStartBuffer) {
|
|
1793
|
+
ev.flush()
|
|
1794
|
+
logger.trace('flushed events for initial buffer')
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
ev.emit('connection.update', { receivedPendingNotifications: true })
|
|
1798
|
+
})
|
|
1799
|
+
|
|
1800
|
+
// update credentials when required
|
|
1801
|
+
ev.on('creds.update', update => {
|
|
1802
|
+
const name = update.me?.name
|
|
1803
|
+
|
|
1804
|
+
// if name has just been received
|
|
1805
|
+
if (creds.me?.name !== name) {
|
|
1806
|
+
logger.debug({ name }, 'updated pushName')
|
|
1807
|
+
|
|
1808
|
+
sendNode({
|
|
1809
|
+
tag: 'presence',
|
|
1810
|
+
attrs: { name }
|
|
1811
|
+
}).catch(err => {
|
|
1812
|
+
logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
|
|
1813
|
+
})
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
Object.assign(creds, update)
|
|
1817
|
+
})
|
|
1818
|
+
|
|
1819
|
+
if (printQRInTerminal) {
|
|
1820
|
+
printQRIfNecessaryListener(ev, logger)
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
return {
|
|
1824
|
+
type: 'md',
|
|
1825
|
+
ws,
|
|
1826
|
+
ev,
|
|
1827
|
+
authState: { creds, keys },
|
|
1828
|
+
signalRepository,
|
|
1829
|
+
get user() {
|
|
1830
|
+
return authState.creds.me;
|
|
1831
|
+
},
|
|
1832
|
+
generateMessageTag,
|
|
1833
|
+
query,
|
|
1834
|
+
waitForMessage,
|
|
1835
|
+
waitForSocketOpen,
|
|
1836
|
+
sendRawMessage,
|
|
1837
|
+
sendNode,
|
|
1838
|
+
logout,
|
|
1839
|
+
end,
|
|
1840
|
+
onUnexpectedError,
|
|
1841
|
+
uploadPreKeys,
|
|
1842
|
+
uploadPreKeysToServerIfRequired,
|
|
1843
|
+
digestKeyBundle,
|
|
1844
|
+
rotateSignedPreKey,
|
|
1845
|
+
requestPairingCode,
|
|
1846
|
+
wamBuffer: publicWAMBuffer,
|
|
1847
|
+
/** Waits for the connection to WA to reach a state */
|
|
1848
|
+
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
|
1849
|
+
sendWAMBuffer,
|
|
1850
|
+
executeUSyncQuery,
|
|
1851
|
+
onWhatsApp
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
/**
|
|
1856
|
+
* map the websocket error to the right type
|
|
1857
|
+
* so it can be retried by the caller
|
|
1858
|
+
* */
|
|
1859
|
+
function mapWebSocketError(handler) {
|
|
1860
|
+
return (error) => {
|
|
1861
|
+
handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }))
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
module.exports = {
|
|
1866
|
+
makeSocket
|
|
1867
|
+
}
|
|
1868
|
+
return module.exports;
|
|
1869
|
+
})();
|
|
1870
|
+
for (const key of Object.keys(__kageModule33)) {
|
|
1871
|
+
if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule33[key]});
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
// Kage: funciones avanzadas.
|
|
1875
|
+
const __kageModule139 = (() => {
|
|
1876
|
+
const module = { exports: {} }; const exports = module.exports;
|
|
1877
|
+
"use strict";
|
|
1878
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1879
|
+
exports.makeSocket = void 0;
|
|
1880
|
+
const node_crypto_1 = require("node:crypto");
|
|
1881
|
+
const node_url_1 = require("node:url");
|
|
1882
|
+
const node_util_1 = require("node:util");
|
|
1883
|
+
const index_js_1 = require("../../WAProto/index.js");
|
|
1884
|
+
const index_js_2 = require("../Addon/index.js");
|
|
1885
|
+
const index_js_3 = require("../Defaults/index.js");
|
|
1886
|
+
const index_js_4 = require("../Types/index.js");
|
|
1887
|
+
const index_js_5 = require("../Types/index.js");
|
|
1888
|
+
const index_js_6 = require("../Utils/index.js");
|
|
1889
|
+
const index_js_7 = require("../WABinary/index.js");
|
|
1890
|
+
const BinaryInfo_js_1 = require("../WAM/BinaryInfo.js");
|
|
1891
|
+
const index_js_8 = require("../WAUSync/index.js");
|
|
1892
|
+
const index_js_9 = require("./Client/index.js");
|
|
1893
|
+
const mex_js_1 = require("./mex.js");
|
|
1894
|
+
/**
|
|
1895
|
+
* Connects to WA servers and performs:
|
|
1896
|
+
* - simple queries (no retry mechanism, wait for connection establishment)
|
|
1897
|
+
* - listen to messages and emit events
|
|
1898
|
+
* - query phone connection
|
|
1899
|
+
*/
|
|
1900
|
+
const makeSocket = (config) => {
|
|
1901
|
+
const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
|
|
1902
|
+
const publicWAMBuffer = new BinaryInfo_js_1.BinaryInfo();
|
|
1903
|
+
let serverTimeOffsetMs = 0;
|
|
1904
|
+
const uqTagId = (0, index_js_6.generateMdTagPrefix)();
|
|
1905
|
+
const generateMessageTag = () => `${uqTagId}${epoch++}`;
|
|
1906
|
+
if (printQRInTerminal) {
|
|
1907
|
+
logger.warn({}, '⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
|
|
1908
|
+
}
|
|
1909
|
+
if (browser[1].toLocaleLowerCase().includes('android')) {
|
|
1910
|
+
logger.warn('⚠️ Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk.');
|
|
1911
|
+
}
|
|
1912
|
+
const syncDisabled = index_js_3.PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false)
|
|
1913
|
+
.length === index_js_3.PROCESSABLE_HISTORY_TYPES.length;
|
|
1914
|
+
if (syncDisabled) {
|
|
1915
|
+
logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
|
|
1916
|
+
}
|
|
1917
|
+
const url = typeof waWebSocketUrl === 'string' ? new node_url_1.URL(waWebSocketUrl) : waWebSocketUrl;
|
|
1918
|
+
if (config.mobile || url.protocol === 'tcp:') {
|
|
1919
|
+
throw new index_js_2.HttpError('Mobile API is not supported anymore', { statusCode: index_js_5.DisconnectReason.loggedOut });
|
|
1920
|
+
}
|
|
1921
|
+
if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
|
|
1922
|
+
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
|
|
1923
|
+
}
|
|
1924
|
+
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
|
|
1925
|
+
const ephemeralKeyPair = index_js_6.Curve.generateKeyPair();
|
|
1926
|
+
/** WA noise protocol wrapper */
|
|
1927
|
+
const noise = (0, index_js_6.makeNoiseHandler)({
|
|
1928
|
+
keyPair: ephemeralKeyPair,
|
|
1929
|
+
NOISE_HEADER: index_js_3.NOISE_WA_HEADER,
|
|
1930
|
+
logger,
|
|
1931
|
+
routingInfo: authState?.creds?.routingInfo
|
|
1932
|
+
});
|
|
1933
|
+
const ws = new index_js_9.WebSocketClient(url, config);
|
|
1934
|
+
ws.connect();
|
|
1935
|
+
const sendPromise = (0, node_util_1.promisify)(ws.send);
|
|
1936
|
+
/** send a raw buffer */
|
|
1937
|
+
const sendRawMessage = async (data) => {
|
|
1938
|
+
if (!ws.isOpen) {
|
|
1939
|
+
throw new index_js_2.HttpError('Connection Closed', { statusCode: index_js_5.DisconnectReason.connectionClosed });
|
|
1940
|
+
}
|
|
1941
|
+
const bytes = noise.encodeFrame(data);
|
|
1942
|
+
await (0, index_js_6.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
|
|
1943
|
+
try {
|
|
1944
|
+
await sendPromise.call(ws, bytes);
|
|
1945
|
+
resolve();
|
|
1946
|
+
}
|
|
1947
|
+
catch (error) {
|
|
1948
|
+
reject(error);
|
|
1949
|
+
}
|
|
1950
|
+
});
|
|
1951
|
+
};
|
|
1952
|
+
/** send a binary node */
|
|
1953
|
+
const sendNode = (frame) => {
|
|
1954
|
+
if (logger.level === 'trace') {
|
|
1955
|
+
logger.trace({ xml: (0, index_js_7.binaryNodeToString)(frame), msg: 'xml send' });
|
|
1956
|
+
}
|
|
1957
|
+
const buff = (0, index_js_7.encodeBinaryNode)(frame);
|
|
1958
|
+
return sendRawMessage(buff);
|
|
1959
|
+
};
|
|
1960
|
+
/**
|
|
1961
|
+
* Wait for a message with a certain tag to be received
|
|
1962
|
+
* @param msgId the message tag to await
|
|
1963
|
+
* @param timeoutMs timeout after which the promise will reject
|
|
1964
|
+
*/
|
|
1965
|
+
const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
|
|
1966
|
+
let onRecv;
|
|
1967
|
+
let onErr;
|
|
1968
|
+
try {
|
|
1969
|
+
const result = await (0, index_js_6.promiseTimeout)(timeoutMs, (resolve, reject) => {
|
|
1970
|
+
onRecv = data => {
|
|
1971
|
+
resolve(data);
|
|
1972
|
+
};
|
|
1973
|
+
onErr = err => {
|
|
1974
|
+
reject(err ||
|
|
1975
|
+
new index_js_2.HttpError('Connection Closed', {
|
|
1976
|
+
statusCode: index_js_5.DisconnectReason.connectionClosed
|
|
1977
|
+
}));
|
|
1978
|
+
};
|
|
1979
|
+
ws.on(`TAG:${msgId}`, onRecv);
|
|
1980
|
+
ws.on('close', onErr);
|
|
1981
|
+
ws.on('error', onErr);
|
|
1982
|
+
return () => reject(new index_js_2.HttpError('Query Cancelled'));
|
|
1983
|
+
});
|
|
1984
|
+
return result;
|
|
1985
|
+
}
|
|
1986
|
+
catch (error) {
|
|
1987
|
+
// Catch timeout and return undefined instead of throwing
|
|
1988
|
+
if (error instanceof index_js_2.HttpError && error.output?.statusCode === index_js_5.DisconnectReason.timedOut) {
|
|
1989
|
+
logger?.warn?.({ msgId }, 'timed out waiting for message');
|
|
1990
|
+
return undefined;
|
|
1991
|
+
}
|
|
1992
|
+
throw error;
|
|
1993
|
+
}
|
|
1994
|
+
finally {
|
|
1995
|
+
if (onRecv)
|
|
1996
|
+
ws.off(`TAG:${msgId}`, onRecv);
|
|
1997
|
+
if (onErr) {
|
|
1998
|
+
ws.off('close', onErr);
|
|
1999
|
+
ws.off('error', onErr);
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
};
|
|
2003
|
+
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
|
2004
|
+
const query = async (node, timeoutMs) => {
|
|
2005
|
+
if (!node.attrs.id) {
|
|
2006
|
+
node.attrs.id = generateMessageTag();
|
|
2007
|
+
}
|
|
2008
|
+
const msgId = node.attrs.id;
|
|
2009
|
+
const result = await (0, index_js_6.promiseTimeout)(timeoutMs, async (resolve, reject) => {
|
|
2010
|
+
const result = waitForMessage(msgId, timeoutMs).catch(reject);
|
|
2011
|
+
sendNode(node)
|
|
2012
|
+
.then(async () => resolve(await result))
|
|
2013
|
+
.catch(reject);
|
|
2014
|
+
});
|
|
2015
|
+
if (result && 'tag' in result) {
|
|
2016
|
+
(0, index_js_7.assertNodeErrorFree)(result);
|
|
2017
|
+
}
|
|
2018
|
+
return result;
|
|
2019
|
+
};
|
|
2020
|
+
// Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
|
|
2021
|
+
const digestKeyBundle = async () => {
|
|
2022
|
+
const res = await query({
|
|
2023
|
+
tag: 'iq',
|
|
2024
|
+
attrs: { to: index_js_7.S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
|
|
2025
|
+
content: [{ tag: 'digest', attrs: {} }]
|
|
2026
|
+
});
|
|
2027
|
+
const digestNode = (0, index_js_7.getBinaryNodeChild)(res, 'digest');
|
|
2028
|
+
if (!digestNode) {
|
|
2029
|
+
await uploadPreKeys();
|
|
2030
|
+
throw new Error('encrypt/get digest returned no digest node');
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
// Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
|
|
2034
|
+
const rotateSignedPreKey = async () => {
|
|
2035
|
+
const newId = (creds.signedPreKey.keyId || 0) + 1;
|
|
2036
|
+
const skey = await (0, index_js_6.signedKeyPair)(creds.signedIdentityKey, newId);
|
|
2037
|
+
await query({
|
|
2038
|
+
tag: 'iq',
|
|
2039
|
+
attrs: { to: index_js_7.S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
|
|
2040
|
+
content: [
|
|
2041
|
+
{
|
|
2042
|
+
tag: 'rotate',
|
|
2043
|
+
attrs: {},
|
|
2044
|
+
content: [(0, index_js_6.xmppSignedPreKey)(skey)]
|
|
2045
|
+
}
|
|
2046
|
+
]
|
|
2047
|
+
});
|
|
2048
|
+
// Persist new signed pre-key in creds
|
|
2049
|
+
ev.emit('creds.update', { signedPreKey: skey });
|
|
2050
|
+
};
|
|
2051
|
+
const executeUSyncQuery = async (usyncQuery) => {
|
|
2052
|
+
if (usyncQuery.protocols.length === 0) {
|
|
2053
|
+
throw new index_js_2.HttpError('USyncQuery must have at least one protocol');
|
|
2054
|
+
}
|
|
2055
|
+
// todo: validate users, throw WARNING on no valid users
|
|
2056
|
+
// variable below has only validated users
|
|
2057
|
+
const validUsers = usyncQuery.users;
|
|
2058
|
+
const userNodes = validUsers.map(user => {
|
|
2059
|
+
return {
|
|
2060
|
+
tag: 'user',
|
|
2061
|
+
attrs: {
|
|
2062
|
+
jid: !user.phone ? user.id : undefined
|
|
2063
|
+
},
|
|
2064
|
+
content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
|
|
2065
|
+
};
|
|
2066
|
+
});
|
|
2067
|
+
const listNode = {
|
|
2068
|
+
tag: 'list',
|
|
2069
|
+
attrs: {},
|
|
2070
|
+
content: userNodes
|
|
2071
|
+
};
|
|
2072
|
+
const queryNode = {
|
|
2073
|
+
tag: 'query',
|
|
2074
|
+
attrs: {},
|
|
2075
|
+
content: usyncQuery.protocols.map(a => a.getQueryElement())
|
|
2076
|
+
};
|
|
2077
|
+
const iq = {
|
|
2078
|
+
tag: 'iq',
|
|
2079
|
+
attrs: {
|
|
2080
|
+
to: index_js_7.S_WHATSAPP_NET,
|
|
2081
|
+
type: 'get',
|
|
2082
|
+
xmlns: 'usync'
|
|
2083
|
+
},
|
|
2084
|
+
content: [
|
|
2085
|
+
{
|
|
2086
|
+
tag: 'usync',
|
|
2087
|
+
attrs: {
|
|
2088
|
+
context: usyncQuery.context,
|
|
2089
|
+
mode: usyncQuery.mode,
|
|
2090
|
+
sid: generateMessageTag(),
|
|
2091
|
+
last: 'true',
|
|
2092
|
+
index: '0'
|
|
2093
|
+
},
|
|
2094
|
+
content: [queryNode, listNode]
|
|
2095
|
+
}
|
|
2096
|
+
]
|
|
2097
|
+
};
|
|
2098
|
+
const result = await query(iq);
|
|
2099
|
+
return usyncQuery.parseUSyncQueryResult(result);
|
|
2100
|
+
};
|
|
2101
|
+
const onWhatsApp = async (...phoneNumber) => {
|
|
2102
|
+
let usyncQuery = new index_js_8.USyncQuery();
|
|
2103
|
+
let contactEnabled = false;
|
|
2104
|
+
for (const jid of phoneNumber) {
|
|
2105
|
+
if ((0, index_js_7.isLidUser)(jid)) {
|
|
2106
|
+
logger?.warn('LIDs are not supported with onWhatsApp');
|
|
2107
|
+
continue;
|
|
2108
|
+
}
|
|
2109
|
+
else {
|
|
2110
|
+
if (!contactEnabled) {
|
|
2111
|
+
contactEnabled = true;
|
|
2112
|
+
usyncQuery = usyncQuery.withContactProtocol();
|
|
2113
|
+
}
|
|
2114
|
+
const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
|
|
2115
|
+
usyncQuery.withUser(new index_js_8.USyncUser().withPhone(phone));
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
if (usyncQuery.users.length === 0) {
|
|
2119
|
+
return []; // return early without forcing an empty query
|
|
2120
|
+
}
|
|
2121
|
+
const results = await executeUSyncQuery(usyncQuery);
|
|
2122
|
+
if (results) {
|
|
2123
|
+
return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
|
|
2124
|
+
}
|
|
2125
|
+
};
|
|
2126
|
+
const pnFromLIDUSync = async (jids) => {
|
|
2127
|
+
const usyncQuery = new index_js_8.USyncQuery().withLIDProtocol().withContext('background');
|
|
2128
|
+
for (const jid of jids) {
|
|
2129
|
+
if ((0, index_js_7.isLidUser)(jid)) {
|
|
2130
|
+
logger?.warn('LID user found in LID fetch call');
|
|
2131
|
+
continue;
|
|
2132
|
+
}
|
|
2133
|
+
else {
|
|
2134
|
+
usyncQuery.withUser(new index_js_8.USyncUser().withId(jid));
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
if (usyncQuery.users.length === 0) {
|
|
2138
|
+
return []; // return early without forcing an empty query
|
|
2139
|
+
}
|
|
2140
|
+
const results = await executeUSyncQuery(usyncQuery);
|
|
2141
|
+
if (results) {
|
|
2142
|
+
return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
|
|
2143
|
+
}
|
|
2144
|
+
return [];
|
|
2145
|
+
};
|
|
2146
|
+
const ev = (0, index_js_6.makeEventBuffer)(logger);
|
|
2147
|
+
const { creds } = authState;
|
|
2148
|
+
// add transaction capability
|
|
2149
|
+
const keys = (0, index_js_6.addTransactionCapability)(authState.keys, logger, transactionOpts);
|
|
2150
|
+
const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
|
|
2151
|
+
let lastDateRecv;
|
|
2152
|
+
let epoch = 1;
|
|
2153
|
+
let keepAliveReq;
|
|
2154
|
+
let qrTimer;
|
|
2155
|
+
let closed = false;
|
|
2156
|
+
const socketEndHandlers = [];
|
|
2157
|
+
/** log & process any unexpected errors */
|
|
2158
|
+
const onUnexpectedError = (err, msg) => {
|
|
2159
|
+
logger.error({ err }, `unexpected error in '${msg}'`);
|
|
2160
|
+
};
|
|
2161
|
+
/** await the next incoming message */
|
|
2162
|
+
const awaitNextMessage = async (sendMsg) => {
|
|
2163
|
+
if (!ws.isOpen) {
|
|
2164
|
+
throw new index_js_2.HttpError('Connection Closed', {
|
|
2165
|
+
statusCode: index_js_5.DisconnectReason.connectionClosed
|
|
2166
|
+
});
|
|
2167
|
+
}
|
|
2168
|
+
let onOpen;
|
|
2169
|
+
let onClose;
|
|
2170
|
+
const result = (0, index_js_6.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
|
|
2171
|
+
onOpen = resolve;
|
|
2172
|
+
onClose = mapWebSocketError(reject);
|
|
2173
|
+
ws.on('frame', onOpen);
|
|
2174
|
+
ws.on('close', onClose);
|
|
2175
|
+
ws.on('error', onClose);
|
|
2176
|
+
}).finally(() => {
|
|
2177
|
+
ws.off('frame', onOpen);
|
|
2178
|
+
ws.off('close', onClose);
|
|
2179
|
+
ws.off('error', onClose);
|
|
2180
|
+
});
|
|
2181
|
+
if (sendMsg) {
|
|
2182
|
+
sendRawMessage(sendMsg).catch(onClose);
|
|
2183
|
+
}
|
|
2184
|
+
return result;
|
|
2185
|
+
};
|
|
2186
|
+
/** connection handshake */
|
|
2187
|
+
const validateConnection = async () => {
|
|
2188
|
+
let helloMsg = {
|
|
2189
|
+
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
2190
|
+
};
|
|
2191
|
+
helloMsg = index_js_1.proto.HandshakeMessage.fromObject(helloMsg);
|
|
2192
|
+
logger.info({ browser, helloMsg }, 'connected to WA');
|
|
2193
|
+
const init = index_js_1.proto.HandshakeMessage.encode(helloMsg).finish();
|
|
2194
|
+
const result = await awaitNextMessage(init);
|
|
2195
|
+
const handshake = index_js_1.proto.HandshakeMessage.decode(result);
|
|
2196
|
+
logger.trace({ handshake }, 'handshake recv from WA');
|
|
2197
|
+
const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
|
|
2198
|
+
let node;
|
|
2199
|
+
if (!creds.me || (!!creds.pairingCode && !creds.registered)) {
|
|
2200
|
+
node = (0, index_js_6.generateRegistrationNode)(creds, config);
|
|
2201
|
+
logger.info({ node }, 'not logged in, attempting registration...');
|
|
2202
|
+
}
|
|
2203
|
+
else {
|
|
2204
|
+
node = (0, index_js_6.generateLoginNode)(creds.me.id, config);
|
|
2205
|
+
logger.info({ node }, 'logging in...');
|
|
2206
|
+
}
|
|
2207
|
+
const payloadEnc = noise.encrypt(index_js_1.proto.ClientPayload.encode(node).finish());
|
|
2208
|
+
await sendRawMessage(index_js_1.proto.HandshakeMessage.encode({
|
|
2209
|
+
clientFinish: {
|
|
2210
|
+
static: keyEnc,
|
|
2211
|
+
payload: payloadEnc
|
|
2212
|
+
}
|
|
2213
|
+
}).finish());
|
|
2214
|
+
await noise.finishInit();
|
|
2215
|
+
startKeepAliveRequest();
|
|
2216
|
+
};
|
|
2217
|
+
const getAvailablePreKeysOnServer = async () => {
|
|
2218
|
+
const result = await query({
|
|
2219
|
+
tag: 'iq',
|
|
2220
|
+
attrs: {
|
|
2221
|
+
id: generateMessageTag(),
|
|
2222
|
+
xmlns: 'encrypt',
|
|
2223
|
+
type: 'get',
|
|
2224
|
+
to: index_js_7.S_WHATSAPP_NET
|
|
2225
|
+
},
|
|
2226
|
+
content: [{ tag: 'count', attrs: {} }]
|
|
2227
|
+
});
|
|
2228
|
+
const countChild = (0, index_js_7.getBinaryNodeChild)(result, 'count');
|
|
2229
|
+
return +countChild.attrs.value;
|
|
2230
|
+
};
|
|
2231
|
+
// WAWeb has no time throttle here; the server drives uploads via PreKeyLow notifications.
|
|
2232
|
+
let uploadPreKeysPromise = null;
|
|
2233
|
+
/** generates and uploads a set of pre-keys to the server */
|
|
2234
|
+
const uploadPreKeys = async (count = index_js_3.MIN_PREKEY_COUNT) => {
|
|
2235
|
+
if (uploadPreKeysPromise) {
|
|
2236
|
+
logger.debug('Pre-key upload already in progress, waiting for completion');
|
|
2237
|
+
await uploadPreKeysPromise;
|
|
2238
|
+
return;
|
|
2239
|
+
}
|
|
2240
|
+
const uploadLogic = async (retryCount) => {
|
|
2241
|
+
logger.info({ count, retryCount }, 'uploading pre-keys');
|
|
2242
|
+
// Generate and save pre-keys atomically (prevents ID collisions on retry)
|
|
2243
|
+
const node = await keys.transaction(async () => {
|
|
2244
|
+
logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
|
|
2245
|
+
const { update, node } = await (0, index_js_6.getNextPreKeysNode)({ creds, keys }, count);
|
|
2246
|
+
// Update credentials immediately to prevent duplicate IDs on retry
|
|
2247
|
+
ev.emit('creds.update', update);
|
|
2248
|
+
return node;
|
|
2249
|
+
}, creds?.me?.id || 'upload-pre-keys');
|
|
2250
|
+
// Upload to server (outside transaction, can fail without affecting local keys)
|
|
2251
|
+
try {
|
|
2252
|
+
await query(node);
|
|
2253
|
+
logger.info({ count }, 'uploaded pre-keys successfully');
|
|
2254
|
+
}
|
|
2255
|
+
catch (uploadError) {
|
|
2256
|
+
logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
|
|
2257
|
+
// Recurse into uploadLogic; calling uploadPreKeys would await its own in-flight promise.
|
|
2258
|
+
if (retryCount < 3) {
|
|
2259
|
+
const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
|
|
2260
|
+
logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
|
|
2261
|
+
await new Promise(resolve => setTimeout(resolve, backoffDelay));
|
|
2262
|
+
return uploadLogic(retryCount + 1);
|
|
2263
|
+
}
|
|
2264
|
+
throw uploadError;
|
|
2265
|
+
}
|
|
2266
|
+
};
|
|
2267
|
+
// Add timeout protection
|
|
2268
|
+
uploadPreKeysPromise = Promise.race([
|
|
2269
|
+
uploadLogic(0),
|
|
2270
|
+
new Promise((_, reject) => setTimeout(() => reject(new index_js_2.HttpError('Pre-key upload timeout', { statusCode: 408 })), index_js_3.UPLOAD_TIMEOUT))
|
|
2271
|
+
]);
|
|
2272
|
+
try {
|
|
2273
|
+
await uploadPreKeysPromise;
|
|
2274
|
+
}
|
|
2275
|
+
finally {
|
|
2276
|
+
uploadPreKeysPromise = null;
|
|
2277
|
+
}
|
|
2278
|
+
};
|
|
2279
|
+
const verifyCurrentPreKeyExists = async () => {
|
|
2280
|
+
const currentPreKeyId = creds.nextPreKeyId - 1;
|
|
2281
|
+
if (currentPreKeyId <= 0) {
|
|
2282
|
+
return { exists: false, currentPreKeyId: 0 };
|
|
2283
|
+
}
|
|
2284
|
+
const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
|
|
2285
|
+
const exists = !!preKeys[currentPreKeyId.toString()];
|
|
2286
|
+
return { exists, currentPreKeyId };
|
|
2287
|
+
};
|
|
2288
|
+
const uploadPreKeysToServerIfRequired = async () => {
|
|
2289
|
+
try {
|
|
2290
|
+
let count = 0;
|
|
2291
|
+
const preKeyCount = await getAvailablePreKeysOnServer();
|
|
2292
|
+
if (preKeyCount === 0)
|
|
2293
|
+
count = index_js_3.INITIAL_PREKEY_COUNT;
|
|
2294
|
+
else
|
|
2295
|
+
count = index_js_3.MIN_PREKEY_COUNT;
|
|
2296
|
+
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
|
|
2297
|
+
logger.info(`${preKeyCount} pre-keys found on server`);
|
|
2298
|
+
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
|
|
2299
|
+
const lowServerCount = preKeyCount <= count;
|
|
2300
|
+
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
|
|
2301
|
+
const shouldUpload = lowServerCount || missingCurrentPreKey;
|
|
2302
|
+
if (shouldUpload) {
|
|
2303
|
+
const reasons = [];
|
|
2304
|
+
if (lowServerCount)
|
|
2305
|
+
reasons.push(`server count low (${preKeyCount})`);
|
|
2306
|
+
if (missingCurrentPreKey)
|
|
2307
|
+
reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
|
|
2308
|
+
logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
|
|
2309
|
+
await uploadPreKeys(count);
|
|
2310
|
+
}
|
|
2311
|
+
else {
|
|
2312
|
+
logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
catch (error) {
|
|
2316
|
+
logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
|
|
2317
|
+
// Don't throw - allow connection to continue even if pre-key check fails
|
|
2318
|
+
}
|
|
2319
|
+
};
|
|
2320
|
+
const onMessageReceived = async (data) => {
|
|
2321
|
+
await noise.decodeFrame(data, frame => {
|
|
2322
|
+
// reset ping timeout
|
|
2323
|
+
lastDateRecv = new Date();
|
|
2324
|
+
let anyTriggered = false;
|
|
2325
|
+
anyTriggered = ws.emit('frame', frame);
|
|
2326
|
+
// if it's a binary node
|
|
2327
|
+
if (!(frame instanceof Uint8Array)) {
|
|
2328
|
+
const msgId = frame.attrs.id;
|
|
2329
|
+
if (logger.level === 'trace') {
|
|
2330
|
+
logger.trace({ xml: (0, index_js_7.binaryNodeToString)(frame), msg: 'recv xml' });
|
|
2331
|
+
}
|
|
2332
|
+
/* Check if this is a response to a message we sent */
|
|
2333
|
+
anyTriggered = ws.emit(`${index_js_3.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
|
|
2334
|
+
/* Check if this is a response to a message we are expecting */
|
|
2335
|
+
const l0 = frame.tag;
|
|
2336
|
+
const l1 = frame.attrs || {};
|
|
2337
|
+
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
|
|
2338
|
+
for (const key of Object.keys(l1)) {
|
|
2339
|
+
anyTriggered = ws.emit(`${index_js_3.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
|
|
2340
|
+
anyTriggered = ws.emit(`${index_js_3.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
|
|
2341
|
+
anyTriggered = ws.emit(`${index_js_3.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
|
|
2342
|
+
}
|
|
2343
|
+
anyTriggered = ws.emit(`${index_js_3.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
|
|
2344
|
+
anyTriggered = ws.emit(`${index_js_3.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
|
|
2345
|
+
if (!anyTriggered && logger.level === 'debug') {
|
|
2346
|
+
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
});
|
|
2350
|
+
};
|
|
2351
|
+
const end = async (error) => {
|
|
2352
|
+
if (closed) {
|
|
2353
|
+
logger.trace({ trace: error?.stack }, 'connection already closed');
|
|
2354
|
+
return;
|
|
2355
|
+
}
|
|
2356
|
+
closed = true;
|
|
2357
|
+
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
|
|
2358
|
+
clearInterval(keepAliveReq);
|
|
2359
|
+
clearTimeout(qrTimer);
|
|
2360
|
+
ws.removeAllListeners('close');
|
|
2361
|
+
ws.removeAllListeners('open');
|
|
2362
|
+
ws.removeAllListeners('message');
|
|
2363
|
+
signalRepository.close?.();
|
|
2364
|
+
if (!ws.isClosed && !ws.isClosing) {
|
|
2365
|
+
try {
|
|
2366
|
+
await ws.close();
|
|
2367
|
+
}
|
|
2368
|
+
catch { }
|
|
2369
|
+
}
|
|
2370
|
+
for (const handler of socketEndHandlers) {
|
|
2371
|
+
try {
|
|
2372
|
+
await handler(error);
|
|
2373
|
+
}
|
|
2374
|
+
catch (err) {
|
|
2375
|
+
logger.error({ err }, 'error in socket end handler');
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
ev.emit('connection.update', {
|
|
2379
|
+
connection: 'close',
|
|
2380
|
+
lastDisconnect: {
|
|
2381
|
+
error,
|
|
2382
|
+
date: new Date()
|
|
2383
|
+
}
|
|
2384
|
+
});
|
|
2385
|
+
ev.removeAllListeners('connection.update');
|
|
2386
|
+
ev.destroy();
|
|
2387
|
+
};
|
|
2388
|
+
const waitForSocketOpen = async () => {
|
|
2389
|
+
if (ws.isOpen) {
|
|
2390
|
+
return;
|
|
2391
|
+
}
|
|
2392
|
+
if (ws.isClosed || ws.isClosing) {
|
|
2393
|
+
throw new index_js_2.HttpError('Connection Closed', { statusCode: index_js_5.DisconnectReason.connectionClosed });
|
|
2394
|
+
}
|
|
2395
|
+
let onOpen;
|
|
2396
|
+
let onClose;
|
|
2397
|
+
await new Promise((resolve, reject) => {
|
|
2398
|
+
onOpen = () => resolve(undefined);
|
|
2399
|
+
onClose = mapWebSocketError(reject);
|
|
2400
|
+
ws.on('open', onOpen);
|
|
2401
|
+
ws.on('close', onClose);
|
|
2402
|
+
ws.on('error', onClose);
|
|
2403
|
+
}).finally(() => {
|
|
2404
|
+
ws.off('open', onOpen);
|
|
2405
|
+
ws.off('close', onClose);
|
|
2406
|
+
ws.off('error', onClose);
|
|
2407
|
+
});
|
|
2408
|
+
};
|
|
2409
|
+
const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
|
|
2410
|
+
if (!lastDateRecv) {
|
|
2411
|
+
lastDateRecv = new Date();
|
|
2412
|
+
}
|
|
2413
|
+
const diff = Date.now() - lastDateRecv.getTime();
|
|
2414
|
+
/*
|
|
2415
|
+
check if it's been a suspicious amount of time since the server responded with our last seen
|
|
2416
|
+
it could be that the network is down
|
|
2417
|
+
*/
|
|
2418
|
+
if (diff > keepAliveIntervalMs + 5000) {
|
|
2419
|
+
void end(new index_js_2.HttpError('Connection was lost', { statusCode: index_js_5.DisconnectReason.connectionLost }));
|
|
2420
|
+
}
|
|
2421
|
+
else if (ws.isOpen) {
|
|
2422
|
+
// if its all good, send a keep alive request
|
|
2423
|
+
query({
|
|
2424
|
+
tag: 'iq',
|
|
2425
|
+
attrs: {
|
|
2426
|
+
id: generateMessageTag(),
|
|
2427
|
+
to: index_js_7.S_WHATSAPP_NET,
|
|
2428
|
+
type: 'get',
|
|
2429
|
+
xmlns: 'w:p'
|
|
2430
|
+
},
|
|
2431
|
+
content: [{ tag: 'ping', attrs: {} }]
|
|
2432
|
+
}).catch(err => {
|
|
2433
|
+
logger.error({ trace: err.stack }, 'error in sending keep alive');
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
else {
|
|
2437
|
+
logger.warn('keep alive called when WS not open');
|
|
2438
|
+
}
|
|
2439
|
+
}, keepAliveIntervalMs));
|
|
2440
|
+
/** i have no idea why this exists. pls enlighten me */
|
|
2441
|
+
const sendPassiveIq = (tag) => query({
|
|
2442
|
+
tag: 'iq',
|
|
2443
|
+
attrs: {
|
|
2444
|
+
to: index_js_7.S_WHATSAPP_NET,
|
|
2445
|
+
xmlns: 'passive',
|
|
2446
|
+
type: 'set'
|
|
2447
|
+
},
|
|
2448
|
+
content: [{ tag, attrs: {} }]
|
|
2449
|
+
});
|
|
2450
|
+
/** logout & invalidate connection */
|
|
2451
|
+
const logout = async (msg) => {
|
|
2452
|
+
const jid = authState.creds.me?.id;
|
|
2453
|
+
if (jid) {
|
|
2454
|
+
await sendNode({
|
|
2455
|
+
tag: 'iq',
|
|
2456
|
+
attrs: {
|
|
2457
|
+
to: index_js_7.S_WHATSAPP_NET,
|
|
2458
|
+
type: 'set',
|
|
2459
|
+
id: generateMessageTag(),
|
|
2460
|
+
xmlns: 'md'
|
|
2461
|
+
},
|
|
2462
|
+
content: [
|
|
2463
|
+
{
|
|
2464
|
+
tag: 'remove-companion-device',
|
|
2465
|
+
attrs: {
|
|
2466
|
+
jid,
|
|
2467
|
+
reason: 'user_initiated'
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
]
|
|
2471
|
+
});
|
|
2472
|
+
}
|
|
2473
|
+
void end(new index_js_2.HttpError(msg || 'Intentional Logout', { statusCode: index_js_5.DisconnectReason.loggedOut }));
|
|
2474
|
+
};
|
|
2475
|
+
const requestPairingCode = async (phoneNumber, customPairingCode) => {
|
|
2476
|
+
const pairingCode = customPairingCode ?? (0, index_js_6.bytesToCrockford)((0, node_crypto_1.randomBytes)(5));
|
|
2477
|
+
if (customPairingCode && customPairingCode?.length !== 8) {
|
|
2478
|
+
throw new Error('Custom pairing code must be exactly 8 chars');
|
|
2479
|
+
}
|
|
2480
|
+
authState.creds.pairingCode = pairingCode;
|
|
2481
|
+
authState.creds.me = {
|
|
2482
|
+
id: (0, index_js_7.jidEncode)(phoneNumber, 's.whatsapp.net'),
|
|
2483
|
+
name: '~'
|
|
2484
|
+
};
|
|
2485
|
+
ev.emit('creds.update', authState.creds);
|
|
2486
|
+
await sendNode({
|
|
2487
|
+
tag: 'iq',
|
|
2488
|
+
attrs: {
|
|
2489
|
+
to: index_js_7.S_WHATSAPP_NET,
|
|
2490
|
+
type: 'set',
|
|
2491
|
+
id: generateMessageTag(),
|
|
2492
|
+
xmlns: 'md'
|
|
2493
|
+
},
|
|
2494
|
+
content: [
|
|
2495
|
+
{
|
|
2496
|
+
tag: 'link_code_companion_reg',
|
|
2497
|
+
attrs: {
|
|
2498
|
+
jid: authState.creds.me.id,
|
|
2499
|
+
stage: 'companion_hello',
|
|
2500
|
+
should_show_push_notification: 'true'
|
|
2501
|
+
},
|
|
2502
|
+
content: [
|
|
2503
|
+
{
|
|
2504
|
+
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
2505
|
+
attrs: {},
|
|
2506
|
+
content: await generatePairingKey()
|
|
2507
|
+
},
|
|
2508
|
+
{
|
|
2509
|
+
tag: 'companion_server_auth_key_pub',
|
|
2510
|
+
attrs: {},
|
|
2511
|
+
content: authState.creds.noiseKey.public
|
|
2512
|
+
},
|
|
2513
|
+
{
|
|
2514
|
+
tag: 'companion_platform_id',
|
|
2515
|
+
attrs: {},
|
|
2516
|
+
content: (0, index_js_6.getCompanionPlatformId)(browser)
|
|
2517
|
+
},
|
|
2518
|
+
{
|
|
2519
|
+
tag: 'companion_platform_display',
|
|
2520
|
+
attrs: {},
|
|
2521
|
+
content: `${browser[1]} (${browser[0]})`
|
|
2522
|
+
},
|
|
2523
|
+
{
|
|
2524
|
+
tag: 'link_code_pairing_nonce',
|
|
2525
|
+
attrs: {},
|
|
2526
|
+
content: Buffer.alloc(1)
|
|
2527
|
+
}
|
|
2528
|
+
]
|
|
2529
|
+
}
|
|
2530
|
+
]
|
|
2531
|
+
});
|
|
2532
|
+
return authState.creds.pairingCode;
|
|
2533
|
+
};
|
|
2534
|
+
async function generatePairingKey() {
|
|
2535
|
+
const salt = (0, node_crypto_1.randomBytes)(32);
|
|
2536
|
+
const randomIv = (0, node_crypto_1.randomBytes)(16);
|
|
2537
|
+
const key = await (0, index_js_6.derivePairingCodeKey)(authState.creds.pairingCode, salt);
|
|
2538
|
+
const ciphered = (0, index_js_6.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
|
|
2539
|
+
return Buffer.concat([salt, randomIv, ciphered]);
|
|
2540
|
+
}
|
|
2541
|
+
const sendWAMBuffer = (wamBuffer) => {
|
|
2542
|
+
return query({
|
|
2543
|
+
tag: 'iq',
|
|
2544
|
+
attrs: {
|
|
2545
|
+
to: index_js_7.S_WHATSAPP_NET,
|
|
2546
|
+
id: generateMessageTag(),
|
|
2547
|
+
xmlns: 'w:stats'
|
|
2548
|
+
},
|
|
2549
|
+
content: [
|
|
2550
|
+
{
|
|
2551
|
+
tag: 'add',
|
|
2552
|
+
attrs: { t: Math.round(Date.now() / 1000) + '' },
|
|
2553
|
+
content: wamBuffer
|
|
2554
|
+
}
|
|
2555
|
+
]
|
|
2556
|
+
});
|
|
2557
|
+
};
|
|
2558
|
+
ws.on('message', onMessageReceived);
|
|
2559
|
+
ws.on('open', async () => {
|
|
2560
|
+
try {
|
|
2561
|
+
await validateConnection();
|
|
2562
|
+
}
|
|
2563
|
+
catch (err) {
|
|
2564
|
+
logger.error({ err }, 'error in validating connection');
|
|
2565
|
+
void end(err);
|
|
2566
|
+
}
|
|
2567
|
+
});
|
|
2568
|
+
ws.on('error', mapWebSocketError(end));
|
|
2569
|
+
ws.on('close', () => void end(new index_js_2.HttpError('Connection Terminated', { statusCode: index_js_5.DisconnectReason.connectionClosed })));
|
|
2570
|
+
// the server terminated the connection
|
|
2571
|
+
ws.on('CB:xmlstreamend', () => void end(new index_js_2.HttpError('Connection Terminated by Server', { statusCode: index_js_5.DisconnectReason.connectionClosed })));
|
|
2572
|
+
// QR gen
|
|
2573
|
+
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
2574
|
+
const iq = {
|
|
2575
|
+
tag: 'iq',
|
|
2576
|
+
attrs: {
|
|
2577
|
+
to: index_js_7.S_WHATSAPP_NET,
|
|
2578
|
+
type: 'result',
|
|
2579
|
+
id: stanza.attrs.id
|
|
2580
|
+
}
|
|
2581
|
+
};
|
|
2582
|
+
await sendNode(iq);
|
|
2583
|
+
const pairDeviceNode = (0, index_js_7.getBinaryNodeChild)(stanza, 'pair-device');
|
|
2584
|
+
const refNodes = (0, index_js_7.getBinaryNodeChildren)(pairDeviceNode, 'ref');
|
|
2585
|
+
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
|
|
2586
|
+
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
|
|
2587
|
+
const advB64 = creds.advSecretKey;
|
|
2588
|
+
let qrMs = qrTimeout || 60000; // time to let a QR live
|
|
2589
|
+
const genPairQR = () => {
|
|
2590
|
+
if (!ws.isOpen) {
|
|
2591
|
+
return;
|
|
2592
|
+
}
|
|
2593
|
+
const refNode = refNodes.shift();
|
|
2594
|
+
if (!refNode) {
|
|
2595
|
+
void end(new index_js_2.HttpError('QR refs attempts ended', { statusCode: index_js_5.DisconnectReason.timedOut }));
|
|
2596
|
+
return;
|
|
2597
|
+
}
|
|
2598
|
+
const ref = refNode.content.toString('utf-8');
|
|
2599
|
+
const qr = (0, index_js_6.buildPairingQRData)(ref, noiseKeyB64, identityKeyB64, advB64, browser);
|
|
2600
|
+
ev.emit('connection.update', { qr });
|
|
2601
|
+
qrTimer = setTimeout(genPairQR, qrMs);
|
|
2602
|
+
qrMs = qrTimeout || 20000; // shorter subsequent qrs
|
|
2603
|
+
};
|
|
2604
|
+
genPairQR();
|
|
2605
|
+
});
|
|
2606
|
+
// device paired for the first time
|
|
2607
|
+
// if device pairs successfully, the server asks to restart the connection
|
|
2608
|
+
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
2609
|
+
logger.debug('pair success recv');
|
|
2610
|
+
try {
|
|
2611
|
+
updateServerTimeOffset(stanza);
|
|
2612
|
+
const { reply, creds: updatedCreds } = (0, index_js_6.configureSuccessfulPairing)(stanza, creds);
|
|
2613
|
+
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
|
|
2614
|
+
ev.emit('creds.update', updatedCreds);
|
|
2615
|
+
ev.emit('connection.update', { isNewLogin: true, qr: undefined });
|
|
2616
|
+
await sendNode(reply);
|
|
2617
|
+
void sendUnifiedSession();
|
|
2618
|
+
}
|
|
2619
|
+
catch (error) {
|
|
2620
|
+
logger.info({ trace: error.stack }, 'error in pairing');
|
|
2621
|
+
void end(error);
|
|
2622
|
+
}
|
|
2623
|
+
});
|
|
2624
|
+
// login complete
|
|
2625
|
+
ws.on('CB:success', async (node) => {
|
|
2626
|
+
try {
|
|
2627
|
+
updateServerTimeOffset(node);
|
|
2628
|
+
await uploadPreKeysToServerIfRequired();
|
|
2629
|
+
await sendPassiveIq('active');
|
|
2630
|
+
// After successful login, validate our key-bundle against server
|
|
2631
|
+
try {
|
|
2632
|
+
await digestKeyBundle();
|
|
2633
|
+
}
|
|
2634
|
+
catch (e) {
|
|
2635
|
+
logger.warn({ e }, 'failed to run digest after login');
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
catch (err) {
|
|
2639
|
+
logger.warn({ err }, 'failed to send initial passive iq');
|
|
2640
|
+
}
|
|
2641
|
+
logger.info('opened connection to WA');
|
|
2642
|
+
clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
|
|
2643
|
+
ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
|
|
2644
|
+
ev.emit('connection.update', { connection: 'open' });
|
|
2645
|
+
void sendUnifiedSession();
|
|
2646
|
+
if (node.attrs.lid && authState.creds.me?.id) {
|
|
2647
|
+
const myLID = node.attrs.lid;
|
|
2648
|
+
process.nextTick(async () => {
|
|
2649
|
+
try {
|
|
2650
|
+
const myPN = authState.creds.me.id;
|
|
2651
|
+
// Store our own LID-PN mapping
|
|
2652
|
+
await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
|
|
2653
|
+
// Create device list for our own user (needed for bulk migration)
|
|
2654
|
+
const { user, device } = (0, index_js_7.jidDecode)(myPN);
|
|
2655
|
+
await authState.keys.set({
|
|
2656
|
+
'device-list': {
|
|
2657
|
+
[user]: [device?.toString() || '0']
|
|
2658
|
+
}
|
|
2659
|
+
});
|
|
2660
|
+
// migrate our own session
|
|
2661
|
+
await signalRepository.migrateSession(myPN, myLID);
|
|
2662
|
+
logger.info({ myPN, myLID }, 'Own LID session created successfully');
|
|
2663
|
+
}
|
|
2664
|
+
catch (error) {
|
|
2665
|
+
logger.error({ error, lid: myLID }, 'Failed to create own LID session');
|
|
2666
|
+
}
|
|
2667
|
+
});
|
|
2668
|
+
}
|
|
2669
|
+
});
|
|
2670
|
+
ws.on('CB:stream:error', (node) => {
|
|
2671
|
+
const [reasonNode] = (0, index_js_7.getAllBinaryNodeChildren)(node);
|
|
2672
|
+
logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
|
|
2673
|
+
const { reason, statusCode } = (0, index_js_6.getErrorCodeFromStreamError)(node);
|
|
2674
|
+
void end(new index_js_2.HttpError(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
|
|
2675
|
+
});
|
|
2676
|
+
// stream fail, possible logout
|
|
2677
|
+
ws.on('CB:failure', (node) => {
|
|
2678
|
+
const reason = +(node.attrs.reason || 500);
|
|
2679
|
+
void end(new index_js_2.HttpError('Connection Failure', { statusCode: reason, data: node.attrs }));
|
|
2680
|
+
});
|
|
2681
|
+
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
2682
|
+
void end(new index_js_2.HttpError('Multi-device beta not joined', { statusCode: index_js_5.DisconnectReason.multideviceMismatch }));
|
|
2683
|
+
});
|
|
2684
|
+
ws.on('CB:ib,,offline_preview', async (node) => {
|
|
2685
|
+
logger.info('offline preview received', JSON.stringify(node));
|
|
2686
|
+
await sendNode({
|
|
2687
|
+
tag: 'ib',
|
|
2688
|
+
attrs: {},
|
|
2689
|
+
content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
|
|
2690
|
+
});
|
|
2691
|
+
});
|
|
2692
|
+
ws.on('CB:ib,,edge_routing', (node) => {
|
|
2693
|
+
const edgeRoutingNode = (0, index_js_7.getBinaryNodeChild)(node, 'edge_routing');
|
|
2694
|
+
const routingInfo = (0, index_js_7.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
|
|
2695
|
+
if (routingInfo?.content) {
|
|
2696
|
+
authState.creds.routingInfo = Buffer.from(routingInfo?.content);
|
|
2697
|
+
ev.emit('creds.update', authState.creds);
|
|
2698
|
+
}
|
|
2699
|
+
});
|
|
2700
|
+
let didStartBuffer = false;
|
|
2701
|
+
process.nextTick(() => {
|
|
2702
|
+
if (creds.me?.id) {
|
|
2703
|
+
// start buffering important events
|
|
2704
|
+
// if we're logged in
|
|
2705
|
+
ev.buffer();
|
|
2706
|
+
didStartBuffer = true;
|
|
2707
|
+
}
|
|
2708
|
+
ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
|
|
2709
|
+
});
|
|
2710
|
+
// called when all offline notifs are handled
|
|
2711
|
+
ws.on('CB:ib,,offline', (node) => {
|
|
2712
|
+
const child = (0, index_js_7.getBinaryNodeChild)(node, 'offline');
|
|
2713
|
+
const offlineNotifs = +(child?.attrs.count || 0);
|
|
2714
|
+
logger.info(`handled ${offlineNotifs} offline messages/notifications`);
|
|
2715
|
+
if (didStartBuffer) {
|
|
2716
|
+
ev.flush();
|
|
2717
|
+
logger.trace('flushed events for initial buffer');
|
|
2718
|
+
}
|
|
2719
|
+
ev.emit('connection.update', { receivedPendingNotifications: true });
|
|
2720
|
+
});
|
|
2721
|
+
// update credentials when required
|
|
2722
|
+
ev.on('creds.update', update => {
|
|
2723
|
+
const name = update.me?.name;
|
|
2724
|
+
// if name has just been received
|
|
2725
|
+
if (creds.me?.name !== name) {
|
|
2726
|
+
logger.debug({ name }, 'updated pushName');
|
|
2727
|
+
sendNode({
|
|
2728
|
+
tag: 'presence',
|
|
2729
|
+
attrs: { name: name }
|
|
2730
|
+
}).catch(err => {
|
|
2731
|
+
logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
|
|
2732
|
+
});
|
|
2733
|
+
}
|
|
2734
|
+
Object.assign(creds, update);
|
|
2735
|
+
});
|
|
2736
|
+
const updateServerTimeOffset = ({ attrs }) => {
|
|
2737
|
+
const tValue = attrs?.t;
|
|
2738
|
+
if (!tValue) {
|
|
2739
|
+
return;
|
|
2740
|
+
}
|
|
2741
|
+
const parsed = Number(tValue);
|
|
2742
|
+
if (Number.isNaN(parsed) || parsed <= 0) {
|
|
2743
|
+
return;
|
|
2744
|
+
}
|
|
2745
|
+
const localMs = Date.now();
|
|
2746
|
+
serverTimeOffsetMs = parsed * 1000 - localMs;
|
|
2747
|
+
logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
|
|
2748
|
+
};
|
|
2749
|
+
const getUnifiedSessionId = () => {
|
|
2750
|
+
const offsetMs = 3 * index_js_3.TimeMs.Day;
|
|
2751
|
+
const now = Date.now() + serverTimeOffsetMs;
|
|
2752
|
+
const id = (now + offsetMs) % index_js_3.TimeMs.Week;
|
|
2753
|
+
return id.toString();
|
|
2754
|
+
};
|
|
2755
|
+
const sendUnifiedSession = async () => {
|
|
2756
|
+
if (!ws.isOpen) {
|
|
2757
|
+
return;
|
|
2758
|
+
}
|
|
2759
|
+
const node = {
|
|
2760
|
+
tag: 'ib',
|
|
2761
|
+
attrs: {},
|
|
2762
|
+
content: [
|
|
2763
|
+
{
|
|
2764
|
+
tag: 'unified_session',
|
|
2765
|
+
attrs: {
|
|
2766
|
+
id: getUnifiedSessionId()
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
]
|
|
2770
|
+
};
|
|
2771
|
+
try {
|
|
2772
|
+
await sendNode(node);
|
|
2773
|
+
}
|
|
2774
|
+
catch (error) {
|
|
2775
|
+
logger.debug({ error }, 'failed to send unified_session telemetry');
|
|
2776
|
+
}
|
|
2777
|
+
};
|
|
2778
|
+
const registerSocketEndHandler = (handler) => {
|
|
2779
|
+
socketEndHandlers.push(handler);
|
|
2780
|
+
};
|
|
2781
|
+
// free the per-socket AsyncLocalStorage created by addTransactionCapability -
|
|
2782
|
+
// end() runs every handler unconditionally and is reached from ws.on('close'),
|
|
2783
|
+
// so this also fires for abnormal closes (1006)
|
|
2784
|
+
registerSocketEndHandler(() => {
|
|
2785
|
+
keys.disposeTransactionStorage();
|
|
2786
|
+
});
|
|
2787
|
+
/**
|
|
2788
|
+
* Fetches your account's standing when it comes to restrictions.
|
|
2789
|
+
* @returns Returns the state of the restrictions.
|
|
2790
|
+
*/
|
|
2791
|
+
const fetchAccountReachoutTimelock = async () => {
|
|
2792
|
+
const queryResult = await (0, mex_js_1.executeWMexQuery)({}, index_js_4.QueryIds.REACHOUT_TIMELOCK, index_js_5.XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag);
|
|
2793
|
+
const result = {
|
|
2794
|
+
isActive: !!queryResult?.is_active,
|
|
2795
|
+
timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0'
|
|
2796
|
+
? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000)
|
|
2797
|
+
: undefined,
|
|
2798
|
+
enforcementType: queryResult?.enforcement_type ?? index_js_4.ReachoutTimelockEnforcementType.DEFAULT
|
|
2799
|
+
};
|
|
2800
|
+
ev.emit('connection.update', { reachoutTimeLock: result });
|
|
2801
|
+
return result;
|
|
2802
|
+
};
|
|
2803
|
+
/**
|
|
2804
|
+
* Fetches your account's new chat limits.
|
|
2805
|
+
* @returns Returns the quota and the usage.
|
|
2806
|
+
*/
|
|
2807
|
+
const fetchNewChatMessageCap = async () => {
|
|
2808
|
+
return (0, mex_js_1.executeWMexQuery)({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, index_js_4.QueryIds.MESSAGE_CAPPING_INFO, index_js_5.XWAPaths.xwa2_message_capping_info, query, generateMessageTag);
|
|
2809
|
+
};
|
|
2810
|
+
return {
|
|
2811
|
+
type: 'md',
|
|
2812
|
+
ws,
|
|
2813
|
+
ev,
|
|
2814
|
+
authState: { creds, keys },
|
|
2815
|
+
signalRepository,
|
|
2816
|
+
get user() {
|
|
2817
|
+
return authState.creds.me;
|
|
2818
|
+
},
|
|
2819
|
+
generateMessageTag,
|
|
2820
|
+
query,
|
|
2821
|
+
waitForMessage,
|
|
2822
|
+
waitForSocketOpen,
|
|
2823
|
+
sendRawMessage,
|
|
2824
|
+
sendNode,
|
|
2825
|
+
logout,
|
|
2826
|
+
end,
|
|
2827
|
+
registerSocketEndHandler,
|
|
2828
|
+
onUnexpectedError,
|
|
2829
|
+
uploadPreKeys,
|
|
2830
|
+
uploadPreKeysToServerIfRequired,
|
|
2831
|
+
digestKeyBundle,
|
|
2832
|
+
rotateSignedPreKey,
|
|
2833
|
+
requestPairingCode,
|
|
2834
|
+
updateServerTimeOffset,
|
|
2835
|
+
sendUnifiedSession,
|
|
2836
|
+
wamBuffer: publicWAMBuffer,
|
|
2837
|
+
/** Waits for the connection to WA to reach a state */
|
|
2838
|
+
waitForConnectionUpdate: (0, index_js_6.bindWaitForConnectionUpdate)(ev),
|
|
2839
|
+
sendWAMBuffer,
|
|
2840
|
+
executeUSyncQuery,
|
|
2841
|
+
onWhatsApp,
|
|
2842
|
+
fetchAccountReachoutTimelock,
|
|
2843
|
+
fetchNewChatMessageCap
|
|
2844
|
+
};
|
|
2845
|
+
};
|
|
2846
|
+
exports.makeSocket = makeSocket;
|
|
2847
|
+
/**
|
|
2848
|
+
* map the websocket error to the right type
|
|
2849
|
+
* so it can be retried by the caller
|
|
2850
|
+
* */
|
|
2851
|
+
function mapWebSocketError(handler) {
|
|
2852
|
+
return (error) => {
|
|
2853
|
+
handler(new index_js_2.HttpError(`WebSocket Error (${error?.message})`, { statusCode: (0, index_js_6.getCodeFromWSError)(error), data: error }));
|
|
2854
|
+
};
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
return module.exports;
|
|
2858
|
+
})();
|
|
2859
|
+
for (const key of Object.keys(__kageModule139)) {
|
|
2860
|
+
if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule139[key]});
|
|
2861
|
+
}
|
|
2862
|
+
Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule139, configurable:true});
|