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