@ryuhan/baileys 1.0.9 → 1.2.9
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 → README.md} +63 -7
- 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 +79 -65
- 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 -78
- 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 +475 -273
- 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 +1011 -468
- 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 +1149 -386
- 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 -233
- 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/apocalypse-api.js +196 -0
- package/lib/Utils/apocalypse.d.ts +116 -0
- package/lib/Utils/apocalypse.js +275 -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 +10 -13
- package/lib/Utils/identity-change-handler.js.map +1 -0
- package/lib/Utils/index.d.ts +23 -0
- package/lib/Utils/index.d.ts.map +1 -0
- package/lib/Utils/index.js +28 -36
- 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 +148 -58
- 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 +316 -202
- 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 +25 -27
- 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 +30 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +57 -83
- package/lib/index.js.map +1 -0
- package/package.json +52 -81
- package/lib/Defaults/wileys-version.json +0 -3
- package/lib/Signal/Group/queue-job.js +0 -57
- package/lib/Utils/wileys-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,60 +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
|
-
// gently back off when encountering rate limits (429)
|
|
93
|
-
if (message.includes('429') || message.includes('rate limit')) {
|
|
94
|
-
const wait = Math.min(30000, (config.backoffDelayMs || 5000));
|
|
95
|
-
logger.info({ wait }, 'backing off due to rate limit');
|
|
96
|
-
setTimeout(() => {
|
|
97
|
-
// intentionally empty; wait to delay further sends
|
|
98
|
-
}, wait);
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
/** await the next incoming message */
|
|
102
|
-
const awaitNextMessage = async (sendMsg) => {
|
|
103
|
-
if (!ws.isOpen) {
|
|
104
|
-
throw new boom_1.Boom('Connection Closed', {
|
|
105
|
-
statusCode: Types_1.DisconnectReason.connectionClosed
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
let onOpen;
|
|
109
|
-
let onClose;
|
|
110
|
-
const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
|
|
111
|
-
onOpen = resolve;
|
|
112
|
-
onClose = mapWebSocketError(reject);
|
|
113
|
-
ws.on('frame', onOpen);
|
|
114
|
-
ws.on('close', onClose);
|
|
115
|
-
ws.on('error', onClose);
|
|
116
|
-
})
|
|
117
|
-
.finally(() => {
|
|
118
|
-
ws.off('frame', onOpen);
|
|
119
|
-
ws.off('close', onClose);
|
|
120
|
-
ws.off('error', onClose);
|
|
121
|
-
});
|
|
122
|
-
if (sendMsg) {
|
|
123
|
-
sendRawMessage(sendMsg).catch(onClose);
|
|
124
|
-
}
|
|
125
|
-
return result;
|
|
126
|
-
};
|
|
127
77
|
/**
|
|
128
78
|
* Wait for a message with a certain tag to be received
|
|
129
79
|
* @param msgId the message tag to await
|
|
@@ -133,21 +83,38 @@ const makeSocket = (config) => {
|
|
|
133
83
|
let onRecv;
|
|
134
84
|
let onErr;
|
|
135
85
|
try {
|
|
136
|
-
const result = await
|
|
137
|
-
onRecv =
|
|
86
|
+
const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
87
|
+
onRecv = data => {
|
|
88
|
+
resolve(data);
|
|
89
|
+
};
|
|
138
90
|
onErr = err => {
|
|
139
|
-
reject(err ||
|
|
91
|
+
reject(err ||
|
|
92
|
+
new Boom('Connection Closed', {
|
|
93
|
+
statusCode: DisconnectReason.connectionClosed
|
|
94
|
+
}));
|
|
140
95
|
};
|
|
141
96
|
ws.on(`TAG:${msgId}`, onRecv);
|
|
142
|
-
ws.on('close', onErr);
|
|
143
|
-
ws.
|
|
97
|
+
ws.on('close', onErr);
|
|
98
|
+
ws.on('error', onErr);
|
|
99
|
+
return () => reject(new Boom('Query Cancelled'));
|
|
144
100
|
});
|
|
145
101
|
return result;
|
|
146
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
|
+
}
|
|
147
111
|
finally {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
112
|
+
if (onRecv)
|
|
113
|
+
ws.off(`TAG:${msgId}`, onRecv);
|
|
114
|
+
if (onErr) {
|
|
115
|
+
ws.off('close', onErr);
|
|
116
|
+
ws.off('error', onErr);
|
|
117
|
+
}
|
|
151
118
|
}
|
|
152
119
|
};
|
|
153
120
|
/** send a query, and wait for its response. auto-generates message ID if not provided */
|
|
@@ -156,12 +123,185 @@ const makeSocket = (config) => {
|
|
|
156
123
|
node.attrs.id = generateMessageTag();
|
|
157
124
|
}
|
|
158
125
|
const msgId = node.attrs.id;
|
|
159
|
-
const
|
|
160
|
-
waitForMessage(msgId, timeoutMs)
|
|
126
|
+
const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
|
|
127
|
+
const result = waitForMessage(msgId, timeoutMs).catch(reject);
|
|
161
128
|
sendNode(node)
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
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);
|
|
165
305
|
}
|
|
166
306
|
return result;
|
|
167
307
|
};
|
|
@@ -170,30 +310,30 @@ const makeSocket = (config) => {
|
|
|
170
310
|
let helloMsg = {
|
|
171
311
|
clientHello: { ephemeral: ephemeralKeyPair.public }
|
|
172
312
|
};
|
|
173
|
-
helloMsg =
|
|
313
|
+
helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
|
|
174
314
|
logger.info({ browser, helloMsg }, 'connected to WA');
|
|
175
|
-
const init =
|
|
315
|
+
const init = proto.HandshakeMessage.encode(helloMsg).finish();
|
|
176
316
|
const result = await awaitNextMessage(init);
|
|
177
|
-
const handshake =
|
|
317
|
+
const handshake = proto.HandshakeMessage.decode(result);
|
|
178
318
|
logger.trace({ handshake }, 'handshake recv from WA');
|
|
179
|
-
const keyEnc =
|
|
319
|
+
const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
|
|
180
320
|
let node;
|
|
181
321
|
if (!creds.me) {
|
|
182
|
-
node =
|
|
322
|
+
node = generateRegistrationNode(creds, config);
|
|
183
323
|
logger.info({ node }, 'not logged in, attempting registration...');
|
|
184
324
|
}
|
|
185
325
|
else {
|
|
186
|
-
node =
|
|
326
|
+
node = generateLoginNode(creds.me.id, config);
|
|
187
327
|
logger.info({ node }, 'logging in...');
|
|
188
328
|
}
|
|
189
|
-
const payloadEnc = noise.encrypt(
|
|
190
|
-
await sendRawMessage(
|
|
329
|
+
const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
|
|
330
|
+
await sendRawMessage(proto.HandshakeMessage.encode({
|
|
191
331
|
clientFinish: {
|
|
192
332
|
static: keyEnc,
|
|
193
|
-
payload: payloadEnc
|
|
194
|
-
}
|
|
333
|
+
payload: payloadEnc
|
|
334
|
+
}
|
|
195
335
|
}).finish());
|
|
196
|
-
noise.finishInit();
|
|
336
|
+
await noise.finishInit();
|
|
197
337
|
startKeepAliveRequest();
|
|
198
338
|
};
|
|
199
339
|
const getAvailablePreKeysOnServer = async () => {
|
|
@@ -203,35 +343,114 @@ const makeSocket = (config) => {
|
|
|
203
343
|
id: generateMessageTag(),
|
|
204
344
|
xmlns: 'encrypt',
|
|
205
345
|
type: 'get',
|
|
206
|
-
to:
|
|
346
|
+
to: S_WHATSAPP_NET
|
|
207
347
|
},
|
|
208
|
-
content: [
|
|
209
|
-
{ tag: 'count', attrs: {} }
|
|
210
|
-
]
|
|
348
|
+
content: [{ tag: 'count', attrs: {} }]
|
|
211
349
|
});
|
|
212
|
-
const countChild =
|
|
350
|
+
const countChild = getBinaryNodeChild(result, 'count');
|
|
213
351
|
return +countChild.attrs.value;
|
|
214
352
|
};
|
|
353
|
+
// Pre-key upload state management
|
|
354
|
+
let uploadPreKeysPromise = null;
|
|
355
|
+
let lastUploadTime = 0;
|
|
215
356
|
/** generates and uploads a set of pre-keys to the server */
|
|
216
|
-
const uploadPreKeys = async (count =
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
const
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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 };
|
|
224
419
|
};
|
|
225
420
|
const uploadPreKeysToServerIfRequired = async () => {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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
|
|
230
450
|
}
|
|
231
451
|
};
|
|
232
|
-
const onMessageReceived = (data) => {
|
|
233
|
-
noise.decodeFrame(data, frame => {
|
|
234
|
-
var _a;
|
|
452
|
+
const onMessageReceived = async (data) => {
|
|
453
|
+
await noise.decodeFrame(data, frame => {
|
|
235
454
|
// reset ping timeout
|
|
236
455
|
lastDateRecv = new Date();
|
|
237
456
|
let anyTriggered = false;
|
|
@@ -240,45 +459,44 @@ const makeSocket = (config) => {
|
|
|
240
459
|
if (!(frame instanceof Uint8Array)) {
|
|
241
460
|
const msgId = frame.attrs.id;
|
|
242
461
|
if (logger.level === 'trace') {
|
|
243
|
-
logger.trace({ xml:
|
|
462
|
+
logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
|
|
244
463
|
}
|
|
245
464
|
/* Check if this is a response to a message we sent */
|
|
246
|
-
anyTriggered = ws.emit(`${
|
|
465
|
+
anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
|
|
247
466
|
/* Check if this is a response to a message we are expecting */
|
|
248
467
|
const l0 = frame.tag;
|
|
249
468
|
const l1 = frame.attrs || {};
|
|
250
|
-
const l2 = Array.isArray(frame.content) ?
|
|
469
|
+
const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
|
|
251
470
|
for (const key of Object.keys(l1)) {
|
|
252
|
-
anyTriggered = ws.emit(`${
|
|
253
|
-
anyTriggered = ws.emit(`${
|
|
254
|
-
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;
|
|
255
474
|
}
|
|
256
|
-
anyTriggered = ws.emit(`${
|
|
257
|
-
anyTriggered = ws.emit(`${
|
|
475
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
|
|
476
|
+
anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
|
|
258
477
|
if (!anyTriggered && logger.level === 'debug') {
|
|
259
478
|
logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
|
|
260
479
|
}
|
|
261
480
|
}
|
|
262
481
|
});
|
|
263
482
|
};
|
|
264
|
-
const end = (error) => {
|
|
483
|
+
const end = async (error) => {
|
|
265
484
|
if (closed) {
|
|
266
|
-
logger.trace({ trace: error
|
|
485
|
+
logger.trace({ trace: error?.stack }, 'connection already closed');
|
|
267
486
|
return;
|
|
268
487
|
}
|
|
269
488
|
closed = true;
|
|
270
|
-
logger.info({ trace: error
|
|
489
|
+
logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
|
|
271
490
|
clearInterval(keepAliveReq);
|
|
272
491
|
clearTimeout(qrTimer);
|
|
273
492
|
ws.removeAllListeners('close');
|
|
274
|
-
ws.removeAllListeners('error');
|
|
275
493
|
ws.removeAllListeners('open');
|
|
276
494
|
ws.removeAllListeners('message');
|
|
277
495
|
if (!ws.isClosed && !ws.isClosing) {
|
|
278
496
|
try {
|
|
279
|
-
ws.close();
|
|
497
|
+
await ws.close();
|
|
280
498
|
}
|
|
281
|
-
catch
|
|
499
|
+
catch { }
|
|
282
500
|
}
|
|
283
501
|
ev.emit('connection.update', {
|
|
284
502
|
connection: 'close',
|
|
@@ -294,7 +512,7 @@ const makeSocket = (config) => {
|
|
|
294
512
|
return;
|
|
295
513
|
}
|
|
296
514
|
if (ws.isClosed || ws.isClosing) {
|
|
297
|
-
throw new
|
|
515
|
+
throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
|
|
298
516
|
}
|
|
299
517
|
let onOpen;
|
|
300
518
|
let onClose;
|
|
@@ -304,8 +522,7 @@ const makeSocket = (config) => {
|
|
|
304
522
|
ws.on('open', onOpen);
|
|
305
523
|
ws.on('close', onClose);
|
|
306
524
|
ws.on('error', onClose);
|
|
307
|
-
})
|
|
308
|
-
.finally(() => {
|
|
525
|
+
}).finally(() => {
|
|
309
526
|
ws.off('open', onOpen);
|
|
310
527
|
ws.off('close', onClose);
|
|
311
528
|
ws.off('error', onClose);
|
|
@@ -321,7 +538,7 @@ const makeSocket = (config) => {
|
|
|
321
538
|
it could be that the network is down
|
|
322
539
|
*/
|
|
323
540
|
if (diff > keepAliveIntervalMs + 5000) {
|
|
324
|
-
end(new
|
|
541
|
+
void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
|
|
325
542
|
}
|
|
326
543
|
else if (ws.isOpen) {
|
|
327
544
|
// if its all good, send a keep alive request
|
|
@@ -329,13 +546,12 @@ const makeSocket = (config) => {
|
|
|
329
546
|
tag: 'iq',
|
|
330
547
|
attrs: {
|
|
331
548
|
id: generateMessageTag(),
|
|
332
|
-
to:
|
|
549
|
+
to: S_WHATSAPP_NET,
|
|
333
550
|
type: 'get',
|
|
334
|
-
xmlns: 'w:p'
|
|
551
|
+
xmlns: 'w:p'
|
|
335
552
|
},
|
|
336
553
|
content: [{ tag: 'ping', attrs: {} }]
|
|
337
|
-
})
|
|
338
|
-
.catch(err => {
|
|
554
|
+
}).catch(err => {
|
|
339
555
|
logger.error({ trace: err.stack }, 'error in sending keep alive');
|
|
340
556
|
});
|
|
341
557
|
}
|
|
@@ -344,26 +560,23 @@ const makeSocket = (config) => {
|
|
|
344
560
|
}
|
|
345
561
|
}, keepAliveIntervalMs));
|
|
346
562
|
/** i have no idea why this exists. pls enlighten me */
|
|
347
|
-
const sendPassiveIq = (tag) =>
|
|
563
|
+
const sendPassiveIq = (tag) => query({
|
|
348
564
|
tag: 'iq',
|
|
349
565
|
attrs: {
|
|
350
|
-
to:
|
|
566
|
+
to: S_WHATSAPP_NET,
|
|
351
567
|
xmlns: 'passive',
|
|
352
|
-
type: 'set'
|
|
568
|
+
type: 'set'
|
|
353
569
|
},
|
|
354
|
-
content: [
|
|
355
|
-
|
|
356
|
-
]
|
|
357
|
-
}));
|
|
570
|
+
content: [{ tag, attrs: {} }]
|
|
571
|
+
});
|
|
358
572
|
/** logout & invalidate connection */
|
|
359
573
|
const logout = async (msg) => {
|
|
360
|
-
|
|
361
|
-
const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
|
|
574
|
+
const jid = authState.creds.me?.id;
|
|
362
575
|
if (jid) {
|
|
363
576
|
await sendNode({
|
|
364
577
|
tag: 'iq',
|
|
365
578
|
attrs: {
|
|
366
|
-
to:
|
|
579
|
+
to: S_WHATSAPP_NET,
|
|
367
580
|
type: 'set',
|
|
368
581
|
id: generateMessageTag(),
|
|
369
582
|
xmlns: 'md'
|
|
@@ -379,31 +592,25 @@ const makeSocket = (config) => {
|
|
|
379
592
|
]
|
|
380
593
|
});
|
|
381
594
|
}
|
|
382
|
-
end(new
|
|
595
|
+
void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
|
|
383
596
|
};
|
|
384
|
-
const requestPairingCode = async (phoneNumber,
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
}
|
|
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;
|
|
391
605
|
authState.creds.me = {
|
|
392
|
-
id:
|
|
606
|
+
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
|
393
607
|
name: '~'
|
|
394
608
|
};
|
|
395
609
|
ev.emit('creds.update', authState.creds);
|
|
396
|
-
|
|
397
|
-
// Wait for WebSocket to be open before sending pairing request
|
|
398
|
-
if (!ws.isOpen) {
|
|
399
|
-
logger.info('WebSocket not open, waiting for connection...');
|
|
400
|
-
await waitForSocketOpen();
|
|
401
|
-
}
|
|
402
|
-
|
|
403
610
|
await sendNode({
|
|
404
611
|
tag: 'iq',
|
|
405
612
|
attrs: {
|
|
406
|
-
to:
|
|
613
|
+
to: S_WHATSAPP_NET,
|
|
407
614
|
type: 'set',
|
|
408
615
|
id: generateMessageTag(),
|
|
409
616
|
xmlns: 'md'
|
|
@@ -430,7 +637,7 @@ const makeSocket = (config) => {
|
|
|
430
637
|
{
|
|
431
638
|
tag: 'companion_platform_id',
|
|
432
639
|
attrs: {},
|
|
433
|
-
content:
|
|
640
|
+
content: getPlatformId(browser[1])
|
|
434
641
|
},
|
|
435
642
|
{
|
|
436
643
|
tag: 'companion_platform_display',
|
|
@@ -449,24 +656,24 @@ const makeSocket = (config) => {
|
|
|
449
656
|
return authState.creds.pairingCode;
|
|
450
657
|
};
|
|
451
658
|
async function generatePairingKey() {
|
|
452
|
-
const salt =
|
|
453
|
-
const randomIv =
|
|
454
|
-
const key = await
|
|
455
|
-
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);
|
|
456
663
|
return Buffer.concat([salt, randomIv, ciphered]);
|
|
457
664
|
}
|
|
458
665
|
const sendWAMBuffer = (wamBuffer) => {
|
|
459
666
|
return query({
|
|
460
667
|
tag: 'iq',
|
|
461
668
|
attrs: {
|
|
462
|
-
to:
|
|
669
|
+
to: S_WHATSAPP_NET,
|
|
463
670
|
id: generateMessageTag(),
|
|
464
671
|
xmlns: 'w:stats'
|
|
465
672
|
},
|
|
466
673
|
content: [
|
|
467
674
|
{
|
|
468
675
|
tag: 'add',
|
|
469
|
-
attrs: {},
|
|
676
|
+
attrs: { t: Math.round(Date.now() / 1000) + '' },
|
|
470
677
|
content: wamBuffer
|
|
471
678
|
}
|
|
472
679
|
]
|
|
@@ -479,26 +686,26 @@ const makeSocket = (config) => {
|
|
|
479
686
|
}
|
|
480
687
|
catch (err) {
|
|
481
688
|
logger.error({ err }, 'error in validating connection');
|
|
482
|
-
end(err);
|
|
689
|
+
void end(err);
|
|
483
690
|
}
|
|
484
691
|
});
|
|
485
692
|
ws.on('error', mapWebSocketError(end));
|
|
486
|
-
ws.on('close', () => end(new
|
|
693
|
+
ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
|
|
487
694
|
// the server terminated the connection
|
|
488
|
-
ws.on('CB:xmlstreamend', () => end(new
|
|
695
|
+
ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
|
|
489
696
|
// QR gen
|
|
490
697
|
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
491
698
|
const iq = {
|
|
492
699
|
tag: 'iq',
|
|
493
700
|
attrs: {
|
|
494
|
-
to:
|
|
701
|
+
to: S_WHATSAPP_NET,
|
|
495
702
|
type: 'result',
|
|
496
|
-
id: stanza.attrs.id
|
|
703
|
+
id: stanza.attrs.id
|
|
497
704
|
}
|
|
498
705
|
};
|
|
499
706
|
await sendNode(iq);
|
|
500
|
-
const pairDeviceNode =
|
|
501
|
-
const refNodes =
|
|
707
|
+
const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
|
|
708
|
+
const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
|
|
502
709
|
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
|
|
503
710
|
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
|
|
504
711
|
const advB64 = creds.advSecretKey;
|
|
@@ -509,7 +716,7 @@ const makeSocket = (config) => {
|
|
|
509
716
|
}
|
|
510
717
|
const refNode = refNodes.shift();
|
|
511
718
|
if (!refNode) {
|
|
512
|
-
end(new
|
|
719
|
+
void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
|
|
513
720
|
return;
|
|
514
721
|
}
|
|
515
722
|
const ref = refNode.content.toString('utf-8');
|
|
@@ -525,65 +732,98 @@ const makeSocket = (config) => {
|
|
|
525
732
|
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
526
733
|
logger.debug('pair success recv');
|
|
527
734
|
try {
|
|
528
|
-
|
|
735
|
+
updateServerTimeOffset(stanza);
|
|
736
|
+
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
|
|
529
737
|
logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
|
|
530
738
|
ev.emit('creds.update', updatedCreds);
|
|
531
739
|
ev.emit('connection.update', { isNewLogin: true, qr: undefined });
|
|
532
740
|
await sendNode(reply);
|
|
741
|
+
void sendUnifiedSession();
|
|
533
742
|
}
|
|
534
743
|
catch (error) {
|
|
535
744
|
logger.info({ trace: error.stack }, 'error in pairing');
|
|
536
|
-
end(error);
|
|
745
|
+
void end(error);
|
|
537
746
|
}
|
|
538
747
|
});
|
|
539
748
|
// login complete
|
|
540
749
|
ws.on('CB:success', async (node) => {
|
|
541
750
|
try {
|
|
751
|
+
updateServerTimeOffset(node);
|
|
542
752
|
await uploadPreKeysToServerIfRequired();
|
|
543
753
|
await sendPassiveIq('active');
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
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
|
+
}
|
|
548
761
|
}
|
|
549
762
|
catch (err) {
|
|
550
|
-
logger.
|
|
551
|
-
|
|
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
|
+
});
|
|
552
792
|
}
|
|
553
793
|
});
|
|
554
794
|
ws.on('CB:stream:error', (node) => {
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
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 }));
|
|
558
799
|
});
|
|
559
800
|
// stream fail, possible logout
|
|
560
801
|
ws.on('CB:failure', (node) => {
|
|
561
802
|
const reason = +(node.attrs.reason || 500);
|
|
562
|
-
end(new
|
|
803
|
+
void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
|
|
563
804
|
});
|
|
564
805
|
ws.on('CB:ib,,downgrade_webclient', () => {
|
|
565
|
-
end(new
|
|
806
|
+
void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
|
|
566
807
|
});
|
|
567
|
-
ws.on('CB:ib,,offline_preview', (node) => {
|
|
808
|
+
ws.on('CB:ib,,offline_preview', async (node) => {
|
|
568
809
|
logger.info('offline preview received', JSON.stringify(node));
|
|
569
|
-
sendNode({
|
|
810
|
+
await sendNode({
|
|
570
811
|
tag: 'ib',
|
|
571
812
|
attrs: {},
|
|
572
813
|
content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
|
|
573
814
|
});
|
|
574
815
|
});
|
|
575
816
|
ws.on('CB:ib,,edge_routing', (node) => {
|
|
576
|
-
const edgeRoutingNode =
|
|
577
|
-
const routingInfo =
|
|
578
|
-
if (routingInfo
|
|
579
|
-
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);
|
|
580
821
|
ev.emit('creds.update', authState.creds);
|
|
581
822
|
}
|
|
582
823
|
});
|
|
583
824
|
let didStartBuffer = false;
|
|
584
825
|
process.nextTick(() => {
|
|
585
|
-
|
|
586
|
-
if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
|
|
826
|
+
if (creds.me?.id) {
|
|
587
827
|
// start buffering important events
|
|
588
828
|
// if we're logged in
|
|
589
829
|
ev.buffer();
|
|
@@ -593,8 +833,8 @@ const makeSocket = (config) => {
|
|
|
593
833
|
});
|
|
594
834
|
// called when all offline notifs are handled
|
|
595
835
|
ws.on('CB:ib,,offline', (node) => {
|
|
596
|
-
const child =
|
|
597
|
-
const offlineNotifs = +(
|
|
836
|
+
const child = getBinaryNodeChild(node, 'offline');
|
|
837
|
+
const offlineNotifs = +(child?.attrs.count || 0);
|
|
598
838
|
logger.info(`handled ${offlineNotifs} offline messages/notifications`);
|
|
599
839
|
if (didStartBuffer) {
|
|
600
840
|
ev.flush();
|
|
@@ -604,24 +844,61 @@ const makeSocket = (config) => {
|
|
|
604
844
|
});
|
|
605
845
|
// update credentials when required
|
|
606
846
|
ev.on('creds.update', update => {
|
|
607
|
-
|
|
608
|
-
const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
|
|
847
|
+
const name = update.me?.name;
|
|
609
848
|
// if name has just been received
|
|
610
|
-
if (
|
|
849
|
+
if (creds.me?.name !== name) {
|
|
611
850
|
logger.debug({ name }, 'updated pushName');
|
|
612
851
|
sendNode({
|
|
613
852
|
tag: 'presence',
|
|
614
853
|
attrs: { name: name }
|
|
615
|
-
})
|
|
616
|
-
.catch(err => {
|
|
854
|
+
}).catch(err => {
|
|
617
855
|
logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
|
|
618
856
|
});
|
|
619
857
|
}
|
|
620
858
|
Object.assign(creds, update);
|
|
621
859
|
});
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
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
|
+
};
|
|
625
902
|
return {
|
|
626
903
|
type: 'md',
|
|
627
904
|
ws,
|
|
@@ -642,19 +919,26 @@ const makeSocket = (config) => {
|
|
|
642
919
|
onUnexpectedError,
|
|
643
920
|
uploadPreKeys,
|
|
644
921
|
uploadPreKeysToServerIfRequired,
|
|
922
|
+
digestKeyBundle,
|
|
923
|
+
rotateSignedPreKey,
|
|
645
924
|
requestPairingCode,
|
|
925
|
+
updateServerTimeOffset,
|
|
926
|
+
sendUnifiedSession,
|
|
927
|
+
wamBuffer: publicWAMBuffer,
|
|
646
928
|
/** Waits for the connection to WA to reach a state */
|
|
647
|
-
waitForConnectionUpdate:
|
|
929
|
+
waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
|
|
648
930
|
sendWAMBuffer,
|
|
931
|
+
executeUSyncQuery,
|
|
932
|
+
onWhatsApp
|
|
649
933
|
};
|
|
650
934
|
};
|
|
651
|
-
exports.makeSocket = makeSocket;
|
|
652
935
|
/**
|
|
653
936
|
* map the websocket error to the right type
|
|
654
937
|
* so it can be retried by the caller
|
|
655
938
|
* */
|
|
656
939
|
function mapWebSocketError(handler) {
|
|
657
940
|
return (error) => {
|
|
658
|
-
handler(new
|
|
941
|
+
handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
|
|
659
942
|
};
|
|
660
943
|
}
|
|
944
|
+
//# sourceMappingURL=socket.js.map
|