@violetix/baileys 0.0.0-stage → 0.3.18
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/LICENSE +22 -0
- package/README.md +2843 -2
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +115856 -0
- package/engine-requirements.js +13 -0
- package/lib/Defaults/index.d.ts +145 -0
- package/lib/Defaults/index.d.ts.map +1 -0
- package/lib/Defaults/index.js +157 -0
- package/lib/Defaults/index.js.map +1 -0
- package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
- package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
- package/lib/Signal/Group/ciphertext-message.js +12 -0
- package/lib/Signal/Group/ciphertext-message.js.map +1 -0
- package/lib/Signal/Group/group-session-builder.d.ts +8 -0
- package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
- package/lib/Signal/Group/group-session-builder.js +30 -0
- package/lib/Signal/Group/group-session-builder.js.map +1 -0
- package/lib/Signal/Group/group_cipher.d.ts +11 -0
- package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
- package/lib/Signal/Group/group_cipher.js +82 -0
- 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 -0
- package/lib/Signal/Group/index.js.map +1 -0
- package/lib/Signal/Group/keyhelper.d.ts +7 -0
- package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
- package/lib/Signal/Group/keyhelper.js +18 -0
- 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 +26 -0
- 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 +63 -0
- 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 +66 -0
- package/lib/Signal/Group/sender-key-message.js.map +1 -0
- package/lib/Signal/Group/sender-key-name.d.ts +12 -0
- package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
- package/lib/Signal/Group/sender-key-name.js +48 -0
- package/lib/Signal/Group/sender-key-name.js.map +1 -0
- package/lib/Signal/Group/sender-key-record.d.ts +13 -0
- package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
- package/lib/Signal/Group/sender-key-record.js +41 -0
- package/lib/Signal/Group/sender-key-record.js.map +1 -0
- package/lib/Signal/Group/sender-key-state.d.ts +17 -0
- package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
- package/lib/Signal/Group/sender-key-state.js +84 -0
- 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 +26 -0
- package/lib/Signal/Group/sender-message-key.js.map +1 -0
- package/lib/Signal/libsignal.d.ts +55 -0
- package/lib/Signal/libsignal.d.ts.map +1 -0
- package/lib/Signal/libsignal.js +403 -0
- package/lib/Signal/libsignal.js.map +1 -0
- package/lib/Signal/lid-mapping.d.ts +21 -0
- package/lib/Signal/lid-mapping.d.ts.map +1 -0
- package/lib/Signal/lid-mapping.js +277 -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 -0
- package/lib/Socket/Client/index.js.map +1 -0
- package/lib/Socket/Client/types.d.ts +6 -0
- package/lib/Socket/Client/types.d.ts.map +1 -0
- package/lib/Socket/Client/types.js +93 -0
- 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 +57 -0
- package/lib/Socket/Client/websocket.js.map +1 -0
- package/lib/Socket/business.d.ts +428 -0
- package/lib/Socket/business.d.ts.map +1 -0
- package/lib/Socket/business.js +380 -0
- package/lib/Socket/business.js.map +1 -0
- package/lib/Socket/chats.d.ts +176 -0
- package/lib/Socket/chats.d.ts.map +1 -0
- package/lib/Socket/chats.js +1238 -0
- package/lib/Socket/chats.js.map +1 -0
- package/lib/Socket/communities.d.ts +595 -0
- package/lib/Socket/communities.d.ts.map +1 -0
- package/lib/Socket/communities.js +432 -0
- package/lib/Socket/communities.js.map +1 -0
- package/lib/Socket/graphql.js +908 -0
- package/lib/Socket/groups.d.ts +318 -0
- package/lib/Socket/groups.d.ts.map +1 -0
- package/lib/Socket/groups.js +364 -0
- package/lib/Socket/groups.js.map +1 -0
- package/lib/Socket/index.d.ts +940 -0
- package/lib/Socket/index.d.ts.map +1 -0
- package/lib/Socket/index.js +19 -0
- package/lib/Socket/index.js.map +1 -0
- package/lib/Socket/interop.js +562 -0
- package/lib/Socket/managed-account.js +210 -0
- package/lib/Socket/messages-recv.d.ts +367 -0
- package/lib/Socket/messages-recv.d.ts.map +1 -0
- package/lib/Socket/messages-recv.js +2199 -0
- package/lib/Socket/messages-recv.js.map +1 -0
- package/lib/Socket/messages-send.d.ts +364 -0
- package/lib/Socket/messages-send.d.ts.map +1 -0
- package/lib/Socket/messages-send.js +1501 -0
- package/lib/Socket/messages-send.js.map +1 -0
- package/lib/Socket/mex.d.ts +2 -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 +315 -0
- package/lib/Socket/newsletter.d.ts.map +1 -0
- package/lib/Socket/newsletter.js +235 -0
- package/lib/Socket/newsletter.js.map +1 -0
- package/lib/Socket/privacy.js +448 -0
- package/lib/Socket/registration.js +430 -0
- package/lib/Socket/socket.d.ts +93 -0
- package/lib/Socket/socket.d.ts.map +1 -0
- package/lib/Socket/socket.js +1272 -0
- package/lib/Socket/socket.js.map +1 -0
- package/lib/Store/index.d.ts +4 -0
- package/lib/Store/index.d.ts.map +1 -0
- package/lib/Store/index.js +4 -0
- package/lib/Store/index.js.map +1 -0
- package/lib/Store/make-in-memory-store.d.ts +63 -0
- package/lib/Store/make-in-memory-store.d.ts.map +1 -0
- package/lib/Store/make-in-memory-store.js +462 -0
- package/lib/Store/make-in-memory-store.js.map +1 -0
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/make-ordered-dictionary.d.ts.map +1 -0
- package/lib/Store/make-ordered-dictionary.js +79 -0
- package/lib/Store/make-ordered-dictionary.js.map +1 -0
- package/lib/Store/object-repository.d.ts +11 -0
- package/lib/Store/object-repository.d.ts.map +1 -0
- package/lib/Store/object-repository.js +24 -0
- package/lib/Store/object-repository.js.map +1 -0
- package/lib/Types/Auth.d.ts +60 -0
- package/lib/Types/Auth.d.ts.map +1 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Auth.js.map +1 -0
- package/lib/Types/Bussines.d.ts +9 -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 +22 -0
- package/lib/Types/Call.d.ts.map +1 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Call.js.map +1 -0
- package/lib/Types/Chat.d.ts +3 -0
- package/lib/Types/Chat.d.ts.map +1 -0
- package/lib/Types/Chat.js +8 -0
- package/lib/Types/Chat.js.map +1 -0
- package/lib/Types/Contact.d.ts +11 -0
- package/lib/Types/Contact.d.ts.map +1 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Contact.js.map +1 -0
- package/lib/Types/Events.d.ts +41 -0
- package/lib/Types/Events.d.ts.map +1 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/Events.js.map +1 -0
- package/lib/Types/GroupMetadata.d.ts +36 -0
- package/lib/Types/GroupMetadata.d.ts.map +1 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/GroupMetadata.js.map +1 -0
- package/lib/Types/Label.d.ts +3 -0
- package/lib/Types/Label.d.ts.map +1 -0
- package/lib/Types/Label.js +25 -0
- package/lib/Types/Label.js.map +1 -0
- package/lib/Types/LabelAssociation.d.ts +3 -0
- package/lib/Types/LabelAssociation.d.ts.map +1 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/LabelAssociation.js.map +1 -0
- package/lib/Types/Message.d.ts +22 -0
- package/lib/Types/Message.d.ts.map +1 -0
- package/lib/Types/Message.js +18 -0
- package/lib/Types/Message.js.map +1 -0
- package/lib/Types/Mex.d.ts +3 -0
- package/lib/Types/Mex.d.ts.map +1 -0
- package/lib/Types/Mex.js +49 -0
- package/lib/Types/Mex.js.map +1 -0
- package/lib/Types/Product.d.ts +5 -0
- package/lib/Types/Product.d.ts.map +1 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Product.js.map +1 -0
- package/lib/Types/RichType.d.ts +3 -0
- package/lib/Types/RichType.d.ts.map +1 -0
- package/lib/Types/RichType.js +23 -0
- package/lib/Types/RichType.js.map +1 -0
- package/lib/Types/Signal.d.ts +10 -0
- package/lib/Types/Signal.d.ts.map +1 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Signal.js.map +1 -0
- package/lib/Types/Socket.d.ts +33 -0
- package/lib/Types/Socket.d.ts.map +1 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/Socket.js.map +1 -0
- package/lib/Types/State.d.ts +6 -0
- package/lib/Types/State.d.ts.map +1 -0
- package/lib/Types/State.js +56 -0
- package/lib/Types/State.js.map +1 -0
- package/lib/Types/USync.d.ts +9 -0
- package/lib/Types/USync.d.ts.map +1 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/USync.js.map +1 -0
- package/lib/Types/index.d.ts +16 -0
- package/lib/Types/index.d.ts.map +1 -0
- package/lib/Types/index.js +26 -0
- package/lib/Types/index.js.map +1 -0
- package/lib/Utils/async-utils.js +7 -0
- package/lib/Utils/auth-utils.d.ts +59 -0
- package/lib/Utils/auth-utils.d.ts.map +1 -0
- package/lib/Utils/auth-utils.js +306 -0
- package/lib/Utils/auth-utils.js.map +1 -0
- package/lib/Utils/browser-utils.d.ts +10 -0
- package/lib/Utils/browser-utils.d.ts.map +1 -0
- package/lib/Utils/browser-utils.js +29 -0
- package/lib/Utils/browser-utils.js.map +1 -0
- package/lib/Utils/business.d.ts +50 -0
- package/lib/Utils/business.d.ts.map +1 -0
- package/lib/Utils/business.js +231 -0
- package/lib/Utils/business.js.map +1 -0
- package/lib/Utils/chat-utils.d.ts +409 -0
- package/lib/Utils/chat-utils.d.ts.map +1 -0
- package/lib/Utils/chat-utils.js +872 -0
- package/lib/Utils/chat-utils.js.map +1 -0
- package/lib/Utils/companion-reg-client-utils.d.ts +10 -0
- package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
- package/lib/Utils/companion-reg-client-utils.js +69 -0
- package/lib/Utils/companion-reg-client-utils.js.map +1 -0
- package/lib/Utils/crypto-worker.js +20 -0
- package/lib/Utils/crypto.d.ts +40 -0
- package/lib/Utils/crypto.d.ts.map +1 -0
- package/lib/Utils/crypto.js +118 -0
- package/lib/Utils/crypto.js.map +1 -0
- package/lib/Utils/decode-wa-message.d.ts +85 -0
- package/lib/Utils/decode-wa-message.d.ts.map +1 -0
- package/lib/Utils/decode-wa-message.js +467 -0
- package/lib/Utils/decode-wa-message.js.map +1 -0
- package/lib/Utils/event-buffer.d.ts +13 -0
- package/lib/Utils/event-buffer.d.ts.map +1 -0
- package/lib/Utils/event-buffer.js +651 -0
- package/lib/Utils/event-buffer.js.map +1 -0
- package/lib/Utils/generics.d.ts +64 -0
- package/lib/Utils/generics.d.ts.map +1 -0
- package/lib/Utils/generics.js +442 -0
- package/lib/Utils/generics.js.map +1 -0
- package/lib/Utils/history.d.ts +77 -0
- package/lib/Utils/history.d.ts.map +1 -0
- package/lib/Utils/history.js +188 -0
- package/lib/Utils/history.js.map +1 -0
- package/lib/Utils/identity-change-handler.d.ts +14 -0
- package/lib/Utils/identity-change-handler.d.ts.map +1 -0
- package/lib/Utils/identity-change-handler.js +50 -0
- package/lib/Utils/identity-change-handler.js.map +1 -0
- package/lib/Utils/index.d.ts +26 -0
- package/lib/Utils/index.d.ts.map +1 -0
- package/lib/Utils/index.js +26 -0
- package/lib/Utils/index.js.map +1 -0
- package/lib/Utils/link-preview.d.ts +13 -0
- package/lib/Utils/link-preview.d.ts.map +1 -0
- package/lib/Utils/link-preview.js +85 -0
- package/lib/Utils/link-preview.js.map +1 -0
- package/lib/Utils/listener-guard.js +48 -0
- package/lib/Utils/logger.d.ts +3 -0
- package/lib/Utils/logger.d.ts.map +1 -0
- package/lib/Utils/logger.js +3 -0
- package/lib/Utils/logger.js.map +1 -0
- package/lib/Utils/lt-hash.d.ts +7 -0
- package/lib/Utils/lt-hash.d.ts.map +1 -0
- package/lib/Utils/lt-hash.js +8 -0
- package/lib/Utils/lt-hash.js.map +1 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.d.ts.map +1 -0
- package/lib/Utils/make-mutex.js +33 -0
- package/lib/Utils/make-mutex.js.map +1 -0
- package/lib/Utils/message-retry-manager.d.ts +80 -0
- package/lib/Utils/message-retry-manager.d.ts.map +1 -0
- package/lib/Utils/message-retry-manager.js +285 -0
- package/lib/Utils/message-retry-manager.js.map +1 -0
- package/lib/Utils/messages-media.d.ts +166 -0
- package/lib/Utils/messages-media.d.ts.map +1 -0
- package/lib/Utils/messages-media.js +957 -0
- package/lib/Utils/messages-media.js.map +1 -0
- package/lib/Utils/messages.d.ts +46 -0
- package/lib/Utils/messages.d.ts.map +1 -0
- package/lib/Utils/messages.js +1887 -0
- package/lib/Utils/messages.js.map +1 -0
- package/lib/Utils/meta-ai-msmsg.d.ts +12 -0
- package/lib/Utils/meta-ai-msmsg.js +124 -0
- package/lib/Utils/noise-handler.d.ts +21 -0
- package/lib/Utils/noise-handler.d.ts.map +1 -0
- package/lib/Utils/noise-handler.js +206 -0
- package/lib/Utils/noise-handler.js.map +1 -0
- package/lib/Utils/offline-node-processor.d.ts +10 -0
- package/lib/Utils/offline-node-processor.d.ts.map +1 -0
- package/lib/Utils/offline-node-processor.js +40 -0
- package/lib/Utils/offline-node-processor.js.map +1 -0
- package/lib/Utils/pre-key-manager.d.ts +26 -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 +102 -0
- package/lib/Utils/process-message.d.ts.map +1 -0
- package/lib/Utils/process-message.js +798 -0
- package/lib/Utils/process-message.js.map +1 -0
- package/lib/Utils/reporting-utils.d.ts +13 -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/rich-message-utils.d.ts +49 -0
- package/lib/Utils/rich-message-utils.d.ts.map +1 -0
- package/lib/Utils/rich-message-utils.js +369 -0
- package/lib/Utils/rich-message-utils.js.map +1 -0
- package/lib/Utils/session-queue.js +33 -0
- package/lib/Utils/signal.d.ts +83 -0
- package/lib/Utils/signal.d.ts.map +1 -0
- package/lib/Utils/signal.js +201 -0
- package/lib/Utils/signal.js.map +1 -0
- package/lib/Utils/stanza-ack.d.ts +22 -0
- package/lib/Utils/stanza-ack.d.ts.map +1 -0
- package/lib/Utils/stanza-ack.js +72 -0
- package/lib/Utils/stanza-ack.js.map +1 -0
- package/lib/Utils/sync-action-utils.d.ts +3 -0
- package/lib/Utils/sync-action-utils.d.ts.map +1 -0
- package/lib/Utils/sync-action-utils.js +49 -0
- package/lib/Utils/sync-action-utils.js.map +1 -0
- package/lib/Utils/tc-token-utils.d.ts +30 -0
- package/lib/Utils/tc-token-utils.d.ts.map +1 -0
- package/lib/Utils/tc-token-utils.js +164 -0
- package/lib/Utils/tc-token-utils.js.map +1 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
- package/lib/Utils/use-multi-file-auth-state.js +175 -0
- package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
- package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
- package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
- package/lib/Utils/use-single-file-auth-state.js +109 -0
- package/lib/Utils/use-single-file-auth-state.js.map +1 -0
- package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
- package/lib/Utils/use-sqlite-auth-state.d.ts.map +1 -0
- package/lib/Utils/use-sqlite-auth-state.js +109 -0
- package/lib/Utils/use-sqlite-auth-state.js.map +1 -0
- package/lib/Utils/validate-connection.d.ts +44 -0
- package/lib/Utils/validate-connection.d.ts.map +1 -0
- package/lib/Utils/validate-connection.js +210 -0
- package/lib/Utils/validate-connection.js.map +1 -0
- package/lib/Utils/worker-pool.js +73 -0
- package/lib/WABinary/constants.d.ts +62 -0
- package/lib/WABinary/constants.d.ts.map +1 -0
- package/lib/WABinary/constants.js +1467 -0
- package/lib/WABinary/constants.js.map +1 -0
- package/lib/WABinary/decode.d.ts +10 -0
- package/lib/WABinary/decode.d.ts.map +1 -0
- package/lib/WABinary/decode.js +262 -0
- 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 +220 -0
- package/lib/WABinary/encode.js.map +1 -0
- package/lib/WABinary/generic-utils.d.ts +77 -0
- package/lib/WABinary/generic-utils.d.ts.map +1 -0
- package/lib/WABinary/generic-utils.js +226 -0
- package/lib/WABinary/generic-utils.js.map +1 -0
- package/lib/WABinary/index.d.ts +6 -0
- package/lib/WABinary/index.d.ts.map +1 -0
- package/lib/WABinary/index.js +6 -0
- package/lib/WABinary/index.js.map +1 -0
- package/lib/WABinary/jid-utils.d.ts +29 -0
- package/lib/WABinary/jid-utils.d.ts.map +1 -0
- package/lib/WABinary/jid-utils.js +96 -0
- package/lib/WABinary/jid-utils.js.map +1 -0
- package/lib/WABinary/types.d.ts +6 -0
- package/lib/WABinary/types.d.ts.map +1 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WABinary/types.js.map +1 -0
- package/lib/WAM/BinaryInfo.d.ts +8 -0
- package/lib/WAM/BinaryInfo.d.ts.map +1 -0
- package/lib/WAM/BinaryInfo.js +10 -0
- package/lib/WAM/BinaryInfo.js.map +1 -0
- package/lib/WAM/constants.d.ts +34927 -0
- package/lib/WAM/constants.d.ts.map +1 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/constants.js.map +1 -0
- package/lib/WAM/encode.d.ts +2 -0
- package/lib/WAM/encode.d.ts.map +1 -0
- package/lib/WAM/encode.js +150 -0
- 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 -0
- package/lib/WAM/index.js.map +1 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.d.ts +8 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +99 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -0
- 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 +54 -0
- 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 +27 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -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 +38 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.d.ts +11 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +31 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/index.d.ts +11 -0
- package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/index.js +11 -0
- package/lib/WAUSync/Protocols/index.js.map +1 -0
- package/lib/WAUSync/USyncQuery.d.ts +32 -0
- package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
- package/lib/WAUSync/USyncQuery.js +185 -0
- package/lib/WAUSync/USyncQuery.js.map +1 -0
- package/lib/WAUSync/USyncUser.d.ts +25 -0
- package/lib/WAUSync/USyncUser.d.ts.map +1 -0
- package/lib/WAUSync/USyncUser.js +48 -0
- 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 -0
- 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 +12 -0
- package/lib/index.js.map +1 -0
- package/package.json +122 -5
|
@@ -0,0 +1,957 @@
|
|
|
1
|
+
import { Boom } from '@hapi/boom';
|
|
2
|
+
import { spawn } from 'child_process';
|
|
3
|
+
import * as Crypto from 'crypto';
|
|
4
|
+
import { once } from 'events';
|
|
5
|
+
import { createReadStream, createWriteStream, promises as fs, WriteStream } from 'fs';
|
|
6
|
+
import { tmpdir } from 'os';
|
|
7
|
+
import { join } from 'path';
|
|
8
|
+
import { Readable, Transform } from 'stream';
|
|
9
|
+
import { pipeline } from 'stream/promises';
|
|
10
|
+
import { URL } from 'url';
|
|
11
|
+
import { proto } from '../../WAProto/index.js';
|
|
12
|
+
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP, NEWSLETTER_MEDIA_PATH_MAP } from '../Defaults/index.js';
|
|
13
|
+
import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
|
|
14
|
+
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
|
|
15
|
+
import { generateMessageIDV2 } from './generics.js';
|
|
16
|
+
const getTmpFilesDirectory = () => tmpdir();
|
|
17
|
+
let imageProcessingLibrary;
|
|
18
|
+
export const getImageProcessingLibrary = async () => {
|
|
19
|
+
if (imageProcessingLibrary) {
|
|
20
|
+
return imageProcessingLibrary;
|
|
21
|
+
}
|
|
22
|
+
//@ts-ignore
|
|
23
|
+
const [sharp, image, jimp] = await Promise.all([
|
|
24
|
+
import('sharp').catch(() => { }),
|
|
25
|
+
import('@napi-rs/image').catch(() => { }),
|
|
26
|
+
import('jimp').catch(() => { })
|
|
27
|
+
]);
|
|
28
|
+
if (sharp) {
|
|
29
|
+
imageProcessingLibrary = { sharp };
|
|
30
|
+
}
|
|
31
|
+
else if (image) {
|
|
32
|
+
imageProcessingLibrary = { image };
|
|
33
|
+
}
|
|
34
|
+
else if (jimp) {
|
|
35
|
+
imageProcessingLibrary = { jimp };
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
throw new Boom('No image processing library available');
|
|
39
|
+
}
|
|
40
|
+
return imageProcessingLibrary;
|
|
41
|
+
};
|
|
42
|
+
export const hkdfInfoKey = (type) => {
|
|
43
|
+
const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
|
|
44
|
+
return `WhatsApp ${hkdfInfo} Keys`;
|
|
45
|
+
};
|
|
46
|
+
export const getRawMediaUploadData = async (media, mediaType, logger) => {
|
|
47
|
+
const { stream } = await getStream(media);
|
|
48
|
+
logger?.debug('got stream for raw upload');
|
|
49
|
+
const hasher = Crypto.createHash('sha256');
|
|
50
|
+
const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
|
|
51
|
+
const fileWriteStream = createWriteStream(filePath);
|
|
52
|
+
let fileLength = 0;
|
|
53
|
+
try {
|
|
54
|
+
for await (const data of stream) {
|
|
55
|
+
fileLength += data.length;
|
|
56
|
+
hasher.update(data);
|
|
57
|
+
if (!fileWriteStream.write(data)) {
|
|
58
|
+
await once(fileWriteStream, 'drain');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
fileWriteStream.end();
|
|
62
|
+
await once(fileWriteStream, 'finish');
|
|
63
|
+
stream.destroy();
|
|
64
|
+
const fileSha256 = hasher.digest();
|
|
65
|
+
logger?.debug('hashed data for raw upload');
|
|
66
|
+
return {
|
|
67
|
+
filePath: filePath,
|
|
68
|
+
fileSha256,
|
|
69
|
+
fileLength
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
fileWriteStream.destroy();
|
|
74
|
+
stream.destroy();
|
|
75
|
+
try {
|
|
76
|
+
await fs.unlink(filePath);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
//
|
|
80
|
+
}
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
/** generates all the keys required to encrypt/decrypt & sign a media message */
|
|
85
|
+
export async function getMediaKeys(buffer, mediaType) {
|
|
86
|
+
if (!buffer) {
|
|
87
|
+
throw new Boom('Cannot derive from empty media key');
|
|
88
|
+
}
|
|
89
|
+
if (typeof buffer === 'string') {
|
|
90
|
+
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
|
|
91
|
+
}
|
|
92
|
+
// expand using HKDF to 112 bytes, also pass in the relevant app info
|
|
93
|
+
const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
|
|
94
|
+
return {
|
|
95
|
+
iv: expandedMediaKey.slice(0, 16),
|
|
96
|
+
cipherKey: expandedMediaKey.slice(16, 48),
|
|
97
|
+
macKey: expandedMediaKey.slice(48, 80)
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** Extracts video thumb using FFMPEG */
|
|
101
|
+
export const extractVideoThumb = async (path, time, size) => {
|
|
102
|
+
const ffmpeg = spawn('ffmpeg', [
|
|
103
|
+
'-loglevel', 'error',
|
|
104
|
+
'-ss', String(time),
|
|
105
|
+
'-i', path,
|
|
106
|
+
'-an', '-sn', '-dn',
|
|
107
|
+
'-map_metadata', '-1',
|
|
108
|
+
'-vf', `scale=${size.width}:-1`,
|
|
109
|
+
'-frames:v', '1',
|
|
110
|
+
'-c:v', 'mjpeg',
|
|
111
|
+
'-f', 'image2pipe',
|
|
112
|
+
'pipe:1'
|
|
113
|
+
], {
|
|
114
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
115
|
+
});
|
|
116
|
+
let buffer = Buffer.alloc(0);
|
|
117
|
+
const stderrChunks = [];
|
|
118
|
+
ffmpeg.stdout.on('data', (chunk) => {
|
|
119
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
120
|
+
});
|
|
121
|
+
ffmpeg.stderr.on('data', (chunk) => stderrChunks.push(chunk));
|
|
122
|
+
const [code] = await once(ffmpeg, 'close');
|
|
123
|
+
if (code !== 0) {
|
|
124
|
+
throw new Boom(`FFmpeg failed (code ${code}):\n` +
|
|
125
|
+
Buffer.concat(stderrChunks).toString('utf8'));
|
|
126
|
+
}
|
|
127
|
+
return buffer;
|
|
128
|
+
};
|
|
129
|
+
export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
|
|
130
|
+
// TODO: Move entirely to sharp, removing jimp as it supports readable streams
|
|
131
|
+
// This will have positive speed and performance impacts as well as minimizing RAM usage.
|
|
132
|
+
if (bufferOrFilePath instanceof Readable) {
|
|
133
|
+
bufferOrFilePath = await toBuffer(bufferOrFilePath);
|
|
134
|
+
}
|
|
135
|
+
const lib = await getImageProcessingLibrary();
|
|
136
|
+
if ('sharp' in lib && lib.sharp?.default) {
|
|
137
|
+
const img = lib.sharp.default(bufferOrFilePath);
|
|
138
|
+
const dimensions = await img.metadata();
|
|
139
|
+
const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
|
|
140
|
+
return {
|
|
141
|
+
buffer,
|
|
142
|
+
original: {
|
|
143
|
+
width: dimensions.width,
|
|
144
|
+
height: dimensions.height
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
else if ('image' in lib && lib.image?.Transformer) {
|
|
149
|
+
if (!Buffer.isBuffer(bufferOrFilePath)) {
|
|
150
|
+
bufferOrFilePath = await fs.readFile(bufferOrFilePath);
|
|
151
|
+
}
|
|
152
|
+
const img = new lib.image.Transformer(bufferOrFilePath);
|
|
153
|
+
const dimensions = await img.metadata();
|
|
154
|
+
const buffer = await img.resize(width, undefined, 0).jpeg(50);
|
|
155
|
+
return {
|
|
156
|
+
buffer,
|
|
157
|
+
original: {
|
|
158
|
+
width: dimensions.width,
|
|
159
|
+
height: dimensions.height
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
else if ('jimp' in lib && lib.jimp?.Jimp) {
|
|
164
|
+
const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
|
|
165
|
+
const dimensions = {
|
|
166
|
+
width: jimp.width,
|
|
167
|
+
height: jimp.height
|
|
168
|
+
};
|
|
169
|
+
const buffer = await jimp
|
|
170
|
+
.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
|
|
171
|
+
.getBuffer('image/jpeg', { quality: 50 });
|
|
172
|
+
return {
|
|
173
|
+
buffer,
|
|
174
|
+
original: dimensions
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
throw new Boom('No image processing library available');
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
|
|
182
|
+
export const generateProfilePicture = async (mediaUpload, dimensions) => {
|
|
183
|
+
let buffer;
|
|
184
|
+
const { width: w = 720, height: h = 720 } = dimensions || {};
|
|
185
|
+
if (Buffer.isBuffer(mediaUpload)) {
|
|
186
|
+
buffer = mediaUpload;
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
// Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
|
|
190
|
+
const { stream } = await getStream(mediaUpload);
|
|
191
|
+
// Convert the resulting stream to a buffer
|
|
192
|
+
buffer = await toBuffer(stream);
|
|
193
|
+
}
|
|
194
|
+
const lib = await getImageProcessingLibrary();
|
|
195
|
+
let img;
|
|
196
|
+
if ('sharp' in lib && lib.sharp?.default) {
|
|
197
|
+
img = lib.sharp
|
|
198
|
+
.default(buffer)
|
|
199
|
+
.resize(w, h)
|
|
200
|
+
.jpeg({
|
|
201
|
+
quality: 80
|
|
202
|
+
})
|
|
203
|
+
.toBuffer();
|
|
204
|
+
}
|
|
205
|
+
else if ('image' in lib && lib.image?.Transformer) {
|
|
206
|
+
img = new lib.image
|
|
207
|
+
.Transformer(buffer)
|
|
208
|
+
.resize(w, h, 0)
|
|
209
|
+
.jpeg(80);
|
|
210
|
+
}
|
|
211
|
+
else if ('jimp' in lib && lib.jimp?.Jimp) {
|
|
212
|
+
const jimp = await lib.jimp.Jimp.read(buffer);
|
|
213
|
+
const min = Math.min(jimp.width, jimp.height);
|
|
214
|
+
const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
|
|
215
|
+
img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 80 });
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
throw new Boom('No image processing library available');
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
img: await img
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
/** gets the SHA256 of the given media message */
|
|
225
|
+
export const mediaMessageSHA256B64 = (message) => {
|
|
226
|
+
const media = Object.values(message)[0];
|
|
227
|
+
return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
|
|
228
|
+
};
|
|
229
|
+
export async function getAudioDuration(buffer) {
|
|
230
|
+
const musicMetadata = await import('music-metadata');
|
|
231
|
+
let metadata;
|
|
232
|
+
const options = {
|
|
233
|
+
duration: true
|
|
234
|
+
};
|
|
235
|
+
if (Buffer.isBuffer(buffer)) {
|
|
236
|
+
metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
|
|
237
|
+
}
|
|
238
|
+
else if (typeof buffer === 'string') {
|
|
239
|
+
metadata = await musicMetadata.parseFile(buffer, options);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
metadata = await musicMetadata.parseStream(buffer, undefined, options);
|
|
243
|
+
}
|
|
244
|
+
return metadata.format.duration;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
|
|
248
|
+
*/
|
|
249
|
+
export async function getAudioWaveform(buffer, logger) {
|
|
250
|
+
try {
|
|
251
|
+
// @ts-ignore
|
|
252
|
+
const { default: decoder } = await import('audio-decode');
|
|
253
|
+
let audioData;
|
|
254
|
+
if (Buffer.isBuffer(buffer)) {
|
|
255
|
+
audioData = buffer;
|
|
256
|
+
}
|
|
257
|
+
else if (typeof buffer === 'string') {
|
|
258
|
+
const rStream = createReadStream(buffer);
|
|
259
|
+
audioData = await toBuffer(rStream);
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
audioData = await toBuffer(buffer);
|
|
263
|
+
}
|
|
264
|
+
const audioBuffer = await decoder(audioData);
|
|
265
|
+
const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
|
|
266
|
+
const samples = 64; // Number of samples we want to have in our final data set
|
|
267
|
+
const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
|
|
268
|
+
const filteredData = [];
|
|
269
|
+
for (let i = 0; i < samples; i++) {
|
|
270
|
+
const blockStart = blockSize * i; // the location of the first sample in the block
|
|
271
|
+
let sum = 0;
|
|
272
|
+
for (let j = 0; j < blockSize; j++) {
|
|
273
|
+
sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
|
|
274
|
+
}
|
|
275
|
+
filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
|
|
276
|
+
}
|
|
277
|
+
// This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
|
|
278
|
+
const multiplier = Math.pow(Math.max(...filteredData), -1);
|
|
279
|
+
const normalizedData = filteredData.map(n => n * multiplier);
|
|
280
|
+
// Generate waveform like WhatsApp
|
|
281
|
+
const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
|
|
282
|
+
return waveform;
|
|
283
|
+
}
|
|
284
|
+
catch (e) {
|
|
285
|
+
logger?.debug('Failed to generate waveform: ' + e);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
export const toReadable = (buffer) => {
|
|
289
|
+
const readable = new Readable({ read: () => { } });
|
|
290
|
+
readable.push(buffer);
|
|
291
|
+
readable.push(null);
|
|
292
|
+
return readable;
|
|
293
|
+
};
|
|
294
|
+
export const toBuffer = async (stream) => {
|
|
295
|
+
const chunks = [];
|
|
296
|
+
for await (const chunk of stream) {
|
|
297
|
+
chunks.push(chunk);
|
|
298
|
+
}
|
|
299
|
+
stream.destroy();
|
|
300
|
+
return Buffer.concat(chunks);
|
|
301
|
+
};
|
|
302
|
+
export const getStream = async (item, opts) => {
|
|
303
|
+
if (Buffer.isBuffer(item)) {
|
|
304
|
+
return { stream: toReadable(item), type: 'buffer' };
|
|
305
|
+
}
|
|
306
|
+
if ('stream' in item) {
|
|
307
|
+
return { stream: item.stream, type: 'readable' };
|
|
308
|
+
}
|
|
309
|
+
const urlStr = item.url.toString();
|
|
310
|
+
if (urlStr.startsWith('data:')) {
|
|
311
|
+
const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
|
|
312
|
+
return { stream: toReadable(buffer), type: 'buffer' };
|
|
313
|
+
}
|
|
314
|
+
if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
|
|
315
|
+
return { stream: await getHttpStream(item.url, opts), type: 'remote' };
|
|
316
|
+
}
|
|
317
|
+
return { stream: createReadStream(item.url), type: 'file' };
|
|
318
|
+
};
|
|
319
|
+
/** generates a thumbnail for a given media, if required */
|
|
320
|
+
export async function generateThumbnail(file, mediaType, options) {
|
|
321
|
+
let thumbnail;
|
|
322
|
+
let originalImageDimensions;
|
|
323
|
+
if (mediaType === 'image') {
|
|
324
|
+
const { buffer, original } = await extractImageThumb(file);
|
|
325
|
+
thumbnail = buffer.toString('base64');
|
|
326
|
+
if (original.width && original.height) {
|
|
327
|
+
originalImageDimensions = {
|
|
328
|
+
width: original.width,
|
|
329
|
+
height: original.height
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
else if (mediaType === 'video') {
|
|
334
|
+
try {
|
|
335
|
+
const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 });
|
|
336
|
+
thumbnail = buff.toString('base64');
|
|
337
|
+
}
|
|
338
|
+
catch (err) {
|
|
339
|
+
options.logger?.debug('could not generate video thumb: ' + err);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return {
|
|
343
|
+
thumbnail,
|
|
344
|
+
originalImageDimensions
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
export const getHttpStream = async (url, options = {}) => {
|
|
348
|
+
const response = await fetch(url.toString(), {
|
|
349
|
+
dispatcher: options.dispatcher,
|
|
350
|
+
method: 'GET',
|
|
351
|
+
headers: options.headers,
|
|
352
|
+
signal: options.signal
|
|
353
|
+
});
|
|
354
|
+
if (!response.ok) {
|
|
355
|
+
if (response.body instanceof Readable) {
|
|
356
|
+
response.body.destroy();
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
await response.body?.cancel().catch(() => { });
|
|
360
|
+
}
|
|
361
|
+
throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
|
|
362
|
+
}
|
|
363
|
+
// @ts-ignore Node18+ Readable.fromWeb exists
|
|
364
|
+
return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
|
|
365
|
+
};
|
|
366
|
+
const SIDECAR_CHUNK_SIZE = 65536;
|
|
367
|
+
const SIDECAR_HMAC_SIZE = 10;
|
|
368
|
+
const SIDECAR_IV_SIZE = 16;
|
|
369
|
+
const CONTAINER_SCAN_MAX_BYTES = 1024;
|
|
370
|
+
const SIDECAR_MEDIA_TYPES = new Set(['video', 'audio', 'ptt', 'gif']);
|
|
371
|
+
const readU32 = (bytes, offset) => ((bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]) >>> 0;
|
|
372
|
+
/**
|
|
373
|
+
* Walks the top-level ISO-BMFF boxes (mp4/mov/3gp/m4a) in the leading bytes. A file is
|
|
374
|
+
* streamable only when `moov` precedes `mdat`; advertising a non-faststart mp4 as seekable
|
|
375
|
+
* (by attaching a sidecar) makes the recipient's player fail instead of falling back to a
|
|
376
|
+
* plain download. Non-ISO-BMFF payloads (ogg/opus voice notes) are streamable.
|
|
377
|
+
* Returns true / false, or null while `head` is too short to decide.
|
|
378
|
+
*/
|
|
379
|
+
export const scanStreamable = (head) => {
|
|
380
|
+
if (head.length < 8) {
|
|
381
|
+
return null;
|
|
382
|
+
}
|
|
383
|
+
if (readU32(head, 4) !== 0x66747970 /* ftyp */) {
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
let offset = 0;
|
|
387
|
+
while (offset + 8 <= head.length) {
|
|
388
|
+
const type = readU32(head, offset + 4);
|
|
389
|
+
if (type === 0x6d6f6f76 /* moov */) {
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
if (type === 0x6d646174 /* mdat */) {
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
let size = readU32(head, offset);
|
|
396
|
+
let headerSize = 8;
|
|
397
|
+
if (size === 1) {
|
|
398
|
+
if (offset + 16 > head.length) {
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
if (readU32(head, offset + 8) !== 0) {
|
|
402
|
+
return true;
|
|
403
|
+
}
|
|
404
|
+
size = readU32(head, offset + 12);
|
|
405
|
+
headerSize = 16;
|
|
406
|
+
}
|
|
407
|
+
else if (size === 0) {
|
|
408
|
+
return true;
|
|
409
|
+
}
|
|
410
|
+
if (size < headerSize) {
|
|
411
|
+
return true;
|
|
412
|
+
}
|
|
413
|
+
offset += size;
|
|
414
|
+
if (offset > CONTAINER_SCAN_MAX_BYTES) {
|
|
415
|
+
return true;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return offset > CONTAINER_SCAN_MAX_BYTES ? true : null;
|
|
419
|
+
};
|
|
420
|
+
/**
|
|
421
|
+
* Streaming sidecar as WhatsApp Web builds it: HMAC-SHA256(macKey) truncated to 10 bytes over
|
|
422
|
+
* each 64 KiB window of iv+ciphertext+mac, with the last 16 bytes of the previous window
|
|
423
|
+
* prepended, so the recipient can verify and play a range without the whole file.
|
|
424
|
+
*/
|
|
425
|
+
class SidecarAccumulator {
|
|
426
|
+
constructor(macKey) {
|
|
427
|
+
this.macKey = macKey;
|
|
428
|
+
this.window = Buffer.alloc(SIDECAR_IV_SIZE + SIDECAR_CHUNK_SIZE);
|
|
429
|
+
this.windowOffset = 0;
|
|
430
|
+
this.totalPushed = 0;
|
|
431
|
+
this.nextChunkStart = 0;
|
|
432
|
+
this.digests = [];
|
|
433
|
+
}
|
|
434
|
+
push(data) {
|
|
435
|
+
let srcOffset = 0;
|
|
436
|
+
while (srcOffset < data.length) {
|
|
437
|
+
const windowEnd = this.nextChunkStart + SIDECAR_IV_SIZE + SIDECAR_CHUNK_SIZE;
|
|
438
|
+
const toCopy = Math.min(windowEnd - this.totalPushed, data.length - srcOffset);
|
|
439
|
+
this.window.set(data.subarray(srcOffset, srcOffset + toCopy), this.windowOffset);
|
|
440
|
+
this.windowOffset += toCopy;
|
|
441
|
+
this.totalPushed += toCopy;
|
|
442
|
+
srcOffset += toCopy;
|
|
443
|
+
if (this.totalPushed === windowEnd) {
|
|
444
|
+
this.flushChunk();
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
finish() {
|
|
449
|
+
if (this.windowOffset > 0) {
|
|
450
|
+
this.flushChunk();
|
|
451
|
+
}
|
|
452
|
+
return Buffer.concat(this.digests);
|
|
453
|
+
}
|
|
454
|
+
flushChunk() {
|
|
455
|
+
const digest = Crypto.createHmac('sha256', this.macKey).update(this.window.subarray(0, this.windowOffset)).digest();
|
|
456
|
+
this.digests.push(digest.subarray(0, SIDECAR_HMAC_SIZE));
|
|
457
|
+
this.nextChunkStart += SIDECAR_CHUNK_SIZE;
|
|
458
|
+
this.window.copyWithin(0, this.windowOffset - SIDECAR_IV_SIZE, this.windowOffset);
|
|
459
|
+
this.windowOffset = SIDECAR_IV_SIZE;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
|
|
463
|
+
const { stream, type } = await getStream(media, opts);
|
|
464
|
+
logger?.debug('fetched media stream');
|
|
465
|
+
const mediaKey = Crypto.randomBytes(32);
|
|
466
|
+
const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
|
|
467
|
+
const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
|
|
468
|
+
const encFileWriteStream = createWriteStream(encFilePath);
|
|
469
|
+
let originalFileStream;
|
|
470
|
+
let originalFilePath;
|
|
471
|
+
if (saveOriginalFileIfRequired) {
|
|
472
|
+
originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
|
|
473
|
+
originalFileStream = createWriteStream(originalFilePath);
|
|
474
|
+
}
|
|
475
|
+
let fileLength = 0;
|
|
476
|
+
const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
|
|
477
|
+
const hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
|
478
|
+
const sha256Plain = Crypto.createHash('sha256');
|
|
479
|
+
const sha256Enc = Crypto.createHash('sha256');
|
|
480
|
+
const sidecar = SIDECAR_MEDIA_TYPES.has(mediaType) ? new SidecarAccumulator(macKey) : undefined;
|
|
481
|
+
sidecar?.push(iv);
|
|
482
|
+
let streamableVerdict = sidecar ? null : false;
|
|
483
|
+
let head = Buffer.alloc(0);
|
|
484
|
+
const onChunk = async (buff) => {
|
|
485
|
+
sha256Enc.update(buff);
|
|
486
|
+
hmac.update(buff);
|
|
487
|
+
sidecar?.push(buff);
|
|
488
|
+
// Handle backpressure: if write returns false, wait for drain
|
|
489
|
+
if (!encFileWriteStream.write(buff)) {
|
|
490
|
+
await once(encFileWriteStream, 'drain');
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
try {
|
|
494
|
+
for await (const data of stream) {
|
|
495
|
+
fileLength += data.length;
|
|
496
|
+
if (type === 'remote' &&
|
|
497
|
+
opts?.maxContentLength &&
|
|
498
|
+
fileLength > opts.maxContentLength) {
|
|
499
|
+
throw new Boom(`content length exceeded when encrypting "${type}"`, {
|
|
500
|
+
data: { media, type }
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
if (originalFileStream) {
|
|
504
|
+
if (!originalFileStream.write(data)) {
|
|
505
|
+
await once(originalFileStream, 'drain');
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
sha256Plain.update(data);
|
|
509
|
+
if (streamableVerdict === null) {
|
|
510
|
+
head = Buffer.concat([head, data]);
|
|
511
|
+
streamableVerdict = scanStreamable(head);
|
|
512
|
+
if (streamableVerdict === null && head.length > CONTAINER_SCAN_MAX_BYTES) {
|
|
513
|
+
streamableVerdict = true;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
await onChunk(aes.update(data));
|
|
517
|
+
}
|
|
518
|
+
await onChunk(aes.final());
|
|
519
|
+
const mac = hmac.digest().slice(0, 10);
|
|
520
|
+
sha256Enc.update(mac);
|
|
521
|
+
sidecar?.push(mac);
|
|
522
|
+
// a non-faststart mp4 (mdat before moov) must not advertise seekability
|
|
523
|
+
const streamingSidecar = sidecar && streamableVerdict !== false ? sidecar.finish() : undefined;
|
|
524
|
+
const fileSha256 = sha256Plain.digest();
|
|
525
|
+
const fileEncSha256 = sha256Enc.digest();
|
|
526
|
+
encFileWriteStream.write(mac);
|
|
527
|
+
const encFinishPromise = once(encFileWriteStream, 'finish');
|
|
528
|
+
const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
|
|
529
|
+
encFileWriteStream.end();
|
|
530
|
+
originalFileStream?.end?.();
|
|
531
|
+
stream.destroy();
|
|
532
|
+
// Wait for write streams to fully flush to disk
|
|
533
|
+
// This helps reduce memory pressure by allowing OS to release buffers
|
|
534
|
+
await encFinishPromise;
|
|
535
|
+
await originalFinishPromise;
|
|
536
|
+
logger?.debug('encrypted data successfully');
|
|
537
|
+
return {
|
|
538
|
+
mediaKey,
|
|
539
|
+
originalFilePath,
|
|
540
|
+
encFilePath,
|
|
541
|
+
mac,
|
|
542
|
+
fileEncSha256,
|
|
543
|
+
fileSha256,
|
|
544
|
+
fileLength,
|
|
545
|
+
streamingSidecar
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
catch (error) {
|
|
549
|
+
// destroy all streams with error
|
|
550
|
+
encFileWriteStream.destroy();
|
|
551
|
+
originalFileStream?.destroy?.();
|
|
552
|
+
aes.destroy();
|
|
553
|
+
hmac.destroy();
|
|
554
|
+
sha256Plain.destroy();
|
|
555
|
+
sha256Enc.destroy();
|
|
556
|
+
stream.destroy();
|
|
557
|
+
try {
|
|
558
|
+
await fs.unlink(encFilePath);
|
|
559
|
+
if (originalFilePath) {
|
|
560
|
+
await fs.unlink(originalFilePath);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
catch (err) {
|
|
564
|
+
logger?.error({ err }, 'failed deleting tmp files');
|
|
565
|
+
}
|
|
566
|
+
throw error;
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
|
|
570
|
+
const AES_CHUNK_SIZE = 16;
|
|
571
|
+
export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
|
|
572
|
+
const extractHost = (url) => {
|
|
573
|
+
if (!url)
|
|
574
|
+
return undefined;
|
|
575
|
+
try {
|
|
576
|
+
return new URL(url).host;
|
|
577
|
+
}
|
|
578
|
+
catch {
|
|
579
|
+
return undefined;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
583
|
+
// Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
|
|
584
|
+
// Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
|
|
585
|
+
const fallbackHost = opts.host ?? extractHost(url);
|
|
586
|
+
const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
|
|
587
|
+
if (!downloadUrl) {
|
|
588
|
+
throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
|
|
589
|
+
}
|
|
590
|
+
const keys = await getMediaKeys(mediaKey, type);
|
|
591
|
+
return downloadEncryptedContent(downloadUrl, keys, opts);
|
|
592
|
+
};
|
|
593
|
+
/**
|
|
594
|
+
* Authenticates the complete iv+ciphertext against its trailing 10-byte HMAC before
|
|
595
|
+
* returning plaintext. Downloads are spooled to a private temporary file, keeping
|
|
596
|
+
* memory bounded. Ranges use an inclusive startByte and exclusive endByte and are
|
|
597
|
+
* sliced after full authentication; they still download the complete media.
|
|
598
|
+
* Consume or destroy the returned stream to remove its temporary file.
|
|
599
|
+
* */
|
|
600
|
+
export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv, macKey }, { startByte = 0, endByte, options } = {}) => {
|
|
601
|
+
if (!macKey) {
|
|
602
|
+
throw new Boom('Media MAC key is required', { statusCode: 400 });
|
|
603
|
+
}
|
|
604
|
+
if (!Number.isSafeInteger(startByte) || startByte < 0 ||
|
|
605
|
+
(endByte !== undefined && (!Number.isSafeInteger(endByte) || endByte < startByte))) {
|
|
606
|
+
throw new Boom('Invalid media byte range', { statusCode: 400 });
|
|
607
|
+
}
|
|
608
|
+
const headers = new Headers(options?.headers);
|
|
609
|
+
headers.set('Origin', DEFAULT_ORIGIN);
|
|
610
|
+
// A caller-supplied Range would prevent verification of the full-file MAC.
|
|
611
|
+
headers.delete('Range');
|
|
612
|
+
let fetched;
|
|
613
|
+
let tempDirectory;
|
|
614
|
+
let filePath;
|
|
615
|
+
const cleanup = async () => {
|
|
616
|
+
if (filePath) {
|
|
617
|
+
await fs.rm(filePath, { force: true });
|
|
618
|
+
}
|
|
619
|
+
if (tempDirectory) {
|
|
620
|
+
await fs.rmdir(tempDirectory);
|
|
621
|
+
}
|
|
622
|
+
};
|
|
623
|
+
try {
|
|
624
|
+
tempDirectory = await fs.mkdtemp(join(getTmpFilesDirectory(), 'baileys-media-'));
|
|
625
|
+
filePath = join(tempDirectory, 'media');
|
|
626
|
+
fetched = await getHttpStream(downloadUrl, { ...options, headers });
|
|
627
|
+
const hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
|
628
|
+
let trailingMac = Buffer.alloc(0);
|
|
629
|
+
let ciphertextLength = 0;
|
|
630
|
+
const authenticate = new Transform({
|
|
631
|
+
transform(chunk, _, callback) {
|
|
632
|
+
const data = Buffer.concat([trailingMac, chunk]);
|
|
633
|
+
const length = Math.max(data.length - 10, 0);
|
|
634
|
+
trailingMac = data.subarray(length);
|
|
635
|
+
const ciphertext = data.subarray(0, length);
|
|
636
|
+
ciphertextLength += length;
|
|
637
|
+
hmac.update(ciphertext);
|
|
638
|
+
callback(null, ciphertext);
|
|
639
|
+
},
|
|
640
|
+
flush(callback) {
|
|
641
|
+
if (trailingMac.length !== 10 || ciphertextLength === 0 || ciphertextLength % AES_CHUNK_SIZE !== 0) {
|
|
642
|
+
callback(new Boom('Invalid or truncated media payload', { statusCode: 400 }));
|
|
643
|
+
}
|
|
644
|
+
else if (!Crypto.timingSafeEqual(hmac.digest().subarray(0, 10), trailingMac)) {
|
|
645
|
+
callback(new Boom('Media MAC verification failed', { statusCode: 400 }));
|
|
646
|
+
}
|
|
647
|
+
else {
|
|
648
|
+
callback();
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
await pipeline(fetched, authenticate, Crypto.createDecipheriv('aes-256-cbc', cipherKey, iv),
|
|
653
|
+
createWriteStream(filePath, { flags: 'wx', mode: 0o600 }), { signal: options?.signal });
|
|
654
|
+
const { size } = await fs.stat(filePath);
|
|
655
|
+
const end = Math.min(endByte ?? size, size);
|
|
656
|
+
if (startByte >= end) {
|
|
657
|
+
await cleanup();
|
|
658
|
+
return Readable.from([]);
|
|
659
|
+
}
|
|
660
|
+
const output = createReadStream(filePath, { start: startByte, end: end - 1, signal: options?.signal });
|
|
661
|
+
output.once('close', () => {
|
|
662
|
+
void cleanup().catch(() => { });
|
|
663
|
+
});
|
|
664
|
+
return output;
|
|
665
|
+
}
|
|
666
|
+
catch (error) {
|
|
667
|
+
fetched?.destroy();
|
|
668
|
+
await cleanup().catch(() => { });
|
|
669
|
+
throw error;
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
export function extensionForMediaMessage(message) {
|
|
673
|
+
const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
|
|
674
|
+
const type = Object.keys(message)[0];
|
|
675
|
+
let extension;
|
|
676
|
+
if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
|
|
677
|
+
extension = '.jpeg';
|
|
678
|
+
}
|
|
679
|
+
else {
|
|
680
|
+
const messageContent = message[type];
|
|
681
|
+
extension = getExtension(messageContent.mimetype);
|
|
682
|
+
}
|
|
683
|
+
return extension;
|
|
684
|
+
}
|
|
685
|
+
const isNodeRuntime = () => {
|
|
686
|
+
return (typeof process !== 'undefined' &&
|
|
687
|
+
process.versions?.node !== null &&
|
|
688
|
+
typeof process.versions.bun === 'undefined' &&
|
|
689
|
+
typeof globalThis.Deno === 'undefined');
|
|
690
|
+
};
|
|
691
|
+
export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
|
|
692
|
+
if (redirectCount > 5) {
|
|
693
|
+
throw new Error('Too many redirects');
|
|
694
|
+
}
|
|
695
|
+
const parsedUrl = new URL(url);
|
|
696
|
+
const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
|
|
697
|
+
// Get file size for Content-Length header (required for Node.js streaming)
|
|
698
|
+
const fileStats = await fs.stat(filePath);
|
|
699
|
+
const fileSize = fileStats.size;
|
|
700
|
+
return new Promise((resolve, reject) => {
|
|
701
|
+
const req = httpModule.request({
|
|
702
|
+
hostname: parsedUrl.hostname,
|
|
703
|
+
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
|
704
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
705
|
+
method: 'POST',
|
|
706
|
+
headers: {
|
|
707
|
+
...headers,
|
|
708
|
+
'Content-Length': fileSize
|
|
709
|
+
},
|
|
710
|
+
agent,
|
|
711
|
+
timeout: timeoutMs
|
|
712
|
+
}, res => {
|
|
713
|
+
// Handle redirects (3xx)
|
|
714
|
+
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
715
|
+
res.resume(); // Consume response to free resources
|
|
716
|
+
const newUrl = new URL(res.headers.location, url).toString();
|
|
717
|
+
resolve(uploadWithNodeHttp({
|
|
718
|
+
url: newUrl,
|
|
719
|
+
filePath,
|
|
720
|
+
headers,
|
|
721
|
+
timeoutMs,
|
|
722
|
+
agent
|
|
723
|
+
}, redirectCount + 1));
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
let body = '';
|
|
727
|
+
res.on('data', chunk => (body += chunk));
|
|
728
|
+
res.on('end', () => {
|
|
729
|
+
try {
|
|
730
|
+
resolve(JSON.parse(body));
|
|
731
|
+
}
|
|
732
|
+
catch {
|
|
733
|
+
resolve(undefined);
|
|
734
|
+
}
|
|
735
|
+
});
|
|
736
|
+
});
|
|
737
|
+
req.on('error', reject);
|
|
738
|
+
req.on('timeout', () => {
|
|
739
|
+
req.destroy();
|
|
740
|
+
reject(new Error('Upload timeout'));
|
|
741
|
+
});
|
|
742
|
+
const stream = createReadStream(filePath);
|
|
743
|
+
stream.pipe(req);
|
|
744
|
+
stream.on('error', err => {
|
|
745
|
+
req.destroy();
|
|
746
|
+
reject(err);
|
|
747
|
+
});
|
|
748
|
+
});
|
|
749
|
+
};
|
|
750
|
+
const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
|
|
751
|
+
// Convert Node.js Readable to Web ReadableStream
|
|
752
|
+
const nodeStream = createReadStream(filePath);
|
|
753
|
+
const webStream = Readable.toWeb(nodeStream);
|
|
754
|
+
// Native fetch only accepts Undici-style dispatchers, not generic https Agents.
|
|
755
|
+
const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
|
|
756
|
+
const response = await fetch(url, {
|
|
757
|
+
...(dispatcher ? { dispatcher } : {}),
|
|
758
|
+
method: 'POST',
|
|
759
|
+
body: webStream,
|
|
760
|
+
headers,
|
|
761
|
+
duplex: 'half',
|
|
762
|
+
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
763
|
+
});
|
|
764
|
+
try {
|
|
765
|
+
return (await response.json());
|
|
766
|
+
}
|
|
767
|
+
catch {
|
|
768
|
+
return undefined;
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
/**
|
|
772
|
+
* Uploads media to WhatsApp servers.
|
|
773
|
+
*
|
|
774
|
+
* ## Why we have two upload implementations:
|
|
775
|
+
*
|
|
776
|
+
* Node.js's native `fetch` (powered by undici) has a known bug where it buffers
|
|
777
|
+
* the entire request body in memory before sending, even when using streams.
|
|
778
|
+
* This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
|
|
779
|
+
* See: https://github.com/nodejs/undici/issues/4058
|
|
780
|
+
*
|
|
781
|
+
* Other runtimes (Bun, Deno, browsers) correctly stream the request body without
|
|
782
|
+
* buffering, so we can use the web-standard Fetch API there.
|
|
783
|
+
*
|
|
784
|
+
* ## Future considerations:
|
|
785
|
+
* Once the undici bug is fixed, we can simplify this to use only the Fetch API
|
|
786
|
+
* across all runtimes. Monitor the GitHub issue for updates.
|
|
787
|
+
*/
|
|
788
|
+
const uploadMedia = async (params, logger) => {
|
|
789
|
+
if (isNodeRuntime()) {
|
|
790
|
+
logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
|
|
791
|
+
return uploadWithNodeHttp(params);
|
|
792
|
+
}
|
|
793
|
+
else {
|
|
794
|
+
logger?.debug('Using web-standard Fetch API for upload');
|
|
795
|
+
return uploadWithFetch(params);
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
799
|
+
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
|
|
800
|
+
// send a query JSON to obtain the url & auth token to upload our media
|
|
801
|
+
const MAX_UPLOAD_RETRIES = 3;
|
|
802
|
+
for (let attempt = 1; attempt <= MAX_UPLOAD_RETRIES; attempt++) {
|
|
803
|
+
let uploadInfo = await refreshMediaConn(false);
|
|
804
|
+
let urls;
|
|
805
|
+
const hosts = [...customUploadHosts, ...uploadInfo.hosts];
|
|
806
|
+
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
|
|
807
|
+
const customHeaders = (() => {
|
|
808
|
+
const hdrs = options?.headers;
|
|
809
|
+
if (!hdrs)
|
|
810
|
+
return {};
|
|
811
|
+
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
|
|
812
|
+
})();
|
|
813
|
+
const headers = {
|
|
814
|
+
...customHeaders,
|
|
815
|
+
'Content-Type': 'application/octet-stream',
|
|
816
|
+
Origin: DEFAULT_ORIGIN
|
|
817
|
+
};
|
|
818
|
+
for (const { hostname } of hosts) {
|
|
819
|
+
logger.debug(`uploading to "${hostname}"`);
|
|
820
|
+
const auth = encodeURIComponent(uploadInfo.auth);
|
|
821
|
+
const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP;
|
|
822
|
+
const serverThumb = newsletter ? '&server_thumb_gen=1' : '';
|
|
823
|
+
const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`;
|
|
824
|
+
let result;
|
|
825
|
+
try {
|
|
826
|
+
result = await uploadMedia({
|
|
827
|
+
url,
|
|
828
|
+
filePath,
|
|
829
|
+
headers,
|
|
830
|
+
timeoutMs,
|
|
831
|
+
agent: fetchAgent
|
|
832
|
+
}, logger);
|
|
833
|
+
if (result?.url || result?.direct_path) {
|
|
834
|
+
urls = {
|
|
835
|
+
mediaUrl: result.url,
|
|
836
|
+
directPath: result.direct_path,
|
|
837
|
+
meta_hmac: result.meta_hmac,
|
|
838
|
+
fbid: result.fbid,
|
|
839
|
+
ts: result.ts,
|
|
840
|
+
thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
|
|
841
|
+
thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
|
|
842
|
+
};
|
|
843
|
+
break;
|
|
844
|
+
}
|
|
845
|
+
else {
|
|
846
|
+
uploadInfo = await refreshMediaConn(true);
|
|
847
|
+
throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
catch (error) {
|
|
851
|
+
// hosts is customUploadHosts + uploadInfo.hosts, so indexing it by the length
|
|
852
|
+
// of uploadInfo.hosts alone named the wrong host as last.
|
|
853
|
+
const isLast = hostname === hosts[hosts.length - 1]?.hostname;
|
|
854
|
+
logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
if (!urls) {
|
|
858
|
+
if (attempt < MAX_UPLOAD_RETRIES) {
|
|
859
|
+
logger.warn(`Media upload failed on all hosts, retrying (${attempt}/${MAX_UPLOAD_RETRIES})...`);
|
|
860
|
+
await new Promise(r => setTimeout(r, 2000));
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
logger.error(`Media upload failed on all hosts after ${MAX_UPLOAD_RETRIES} attempts`);
|
|
864
|
+
return null;
|
|
865
|
+
}
|
|
866
|
+
return urls;
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
};
|
|
870
|
+
const getMediaRetryKey = (mediaKey) => {
|
|
871
|
+
return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
|
|
872
|
+
};
|
|
873
|
+
/**
|
|
874
|
+
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
|
875
|
+
*/
|
|
876
|
+
export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
877
|
+
const recp = { stanzaId: key.id };
|
|
878
|
+
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
|
|
879
|
+
const iv = Crypto.randomBytes(12);
|
|
880
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
881
|
+
const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
|
|
882
|
+
const req = {
|
|
883
|
+
tag: 'receipt',
|
|
884
|
+
attrs: {
|
|
885
|
+
id: key.id,
|
|
886
|
+
to: jidNormalizedUser(meId),
|
|
887
|
+
type: 'server-error'
|
|
888
|
+
},
|
|
889
|
+
content: [
|
|
890
|
+
// this encrypt node is actually pretty useless
|
|
891
|
+
// the media is returned even without this node
|
|
892
|
+
// keeping it here to maintain parity with WA Web
|
|
893
|
+
{
|
|
894
|
+
tag: 'encrypt',
|
|
895
|
+
attrs: {},
|
|
896
|
+
content: [
|
|
897
|
+
{ tag: 'enc_p', attrs: {}, content: ciphertext },
|
|
898
|
+
{ tag: 'enc_iv', attrs: {}, content: iv }
|
|
899
|
+
]
|
|
900
|
+
},
|
|
901
|
+
{
|
|
902
|
+
tag: 'rmr',
|
|
903
|
+
attrs: {
|
|
904
|
+
jid: key.remoteJid,
|
|
905
|
+
from_me: (!!key.fromMe).toString(),
|
|
906
|
+
// @ts-ignore
|
|
907
|
+
participant: key.participant || undefined
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
]
|
|
911
|
+
};
|
|
912
|
+
return req;
|
|
913
|
+
};
|
|
914
|
+
export const decodeMediaRetryNode = (node) => {
|
|
915
|
+
const rmrNode = getBinaryNodeChild(node, 'rmr');
|
|
916
|
+
const event = {
|
|
917
|
+
key: {
|
|
918
|
+
id: node.attrs.id,
|
|
919
|
+
remoteJid: rmrNode.attrs.jid,
|
|
920
|
+
fromMe: rmrNode.attrs.from_me === 'true',
|
|
921
|
+
participant: rmrNode.attrs.participant
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
const errorNode = getBinaryNodeChild(node, 'error');
|
|
925
|
+
if (errorNode) {
|
|
926
|
+
const errorCode = +errorNode.attrs.code;
|
|
927
|
+
event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
|
|
928
|
+
data: errorNode.attrs,
|
|
929
|
+
statusCode: getStatusCodeForMediaRetry(errorCode)
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
else {
|
|
933
|
+
const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
|
|
934
|
+
const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
|
|
935
|
+
const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
|
|
936
|
+
if (ciphertext && iv) {
|
|
937
|
+
event.media = { ciphertext, iv };
|
|
938
|
+
}
|
|
939
|
+
else {
|
|
940
|
+
event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
return event;
|
|
944
|
+
};
|
|
945
|
+
export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
946
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
947
|
+
const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
|
|
948
|
+
return proto.MediaRetryNotification.decode(plaintext);
|
|
949
|
+
};
|
|
950
|
+
export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
|
|
951
|
+
const MEDIA_RETRY_STATUS_MAP = {
|
|
952
|
+
[proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
|
|
953
|
+
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
954
|
+
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
955
|
+
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
956
|
+
};
|
|
957
|
+
//# sourceMappingURL=messages-media.js.map
|