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