Compare commits
205 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4d00e8f9ce | |||
| 4687a2a86f | |||
| d5796b36b6 | |||
| f914ffe272 | |||
| 73d63b6304 | |||
| 0700c44d59 | |||
| b0030a0482 | |||
| d0bbf85e6a | |||
| 0f2402da58 | |||
| 5017393277 | |||
| c557714e72 | |||
| c8056a967c | |||
| 24329e9ba1 | |||
| b70d144699 | |||
| d9e0e0e0af | |||
| a6cf9b0b26 | |||
| b531b46999 | |||
| 3ece5f7446 | |||
| 314dd9469d | |||
| 8b0a20fed9 | |||
| df1acc8f0c | |||
| 1dffe3b311 | |||
| 4fe708445a | |||
| 336ed64a44 | |||
| 65cb09e4df | |||
| 9ff21db749 | |||
| 9525f42cb2 | |||
| e117456079 | |||
| c179c82cca | |||
| d08a09c35f | |||
| cffaad9e5a | |||
| 104d2c47f5 | |||
| 924c54f1f8 | |||
| e34ef5479d | |||
| 5e8d30d709 | |||
| ac93080595 | |||
| 37d1bdfb76 | |||
| 76b2007f27 | |||
| 676912c295 | |||
| 06d9f35ca9 | |||
| 4cadcd1c57 | |||
| 937b26edcd | |||
| acad0c06dc | |||
| 98995aae89 | |||
| 7a7d92e3f8 | |||
| 1fbaa284f9 | |||
| 9c7dd0460c | |||
| 579277cb29 | |||
| bb0cb90260 | |||
| 56955e12f5 | |||
| b7d9f2b866 | |||
| daaf0bc813 | |||
| bf95867089 | |||
| 9fac156474 | |||
| 230e08037b | |||
| 77ffe59911 | |||
| 313f304ddf | |||
| a74fbb08a6 | |||
| 0e6bad72bb | |||
| 08c19e2951 | |||
| 90061dd6a1 | |||
| d014a2496e | |||
| 47b0940428 | |||
| 90937af374 | |||
| 703b5da554 | |||
| 8c61ce5f8e | |||
| 000932accd | |||
| 8df39c320e | |||
| 22e758b1e6 | |||
| f473484852 | |||
| 4dde4c5500 | |||
| e3cf104b59 | |||
| aa0a3c2b71 | |||
| bdbad50074 | |||
| 45b322abac | |||
| 3c3cf32027 | |||
| 99d85498fb | |||
| d6414f203b | |||
| b98df92d8c | |||
| 00a8113d47 | |||
| 670ac582f9 | |||
| 08910c61e1 | |||
| cb5e42c46e | |||
| 30e986ee67 | |||
| 60302d73d5 | |||
| 3baa494fad | |||
| 59cad85544 | |||
| ad53bc0982 | |||
| fb8f51be52 | |||
| 9a7d43d4ba | |||
| 578efe945f | |||
| e999fc1aa1 | |||
| 9fd88b533d | |||
| 43f3525437 | |||
| fdcbd3fc1d | |||
| cdc89316f0 | |||
| 3050c329c5 | |||
| 3ef7474842 | |||
| 9dfd31d109 | |||
| e686c5a2e1 | |||
| 466c14ff82 | |||
| 03bc03b318 | |||
| d83971d15e | |||
| 14f0321d7c | |||
| b65a8a334b | |||
| 28e9e5b912 | |||
| 962e7de0bf | |||
| c6cb29fd80 | |||
| a283d858c6 | |||
| 9c626801b0 | |||
| 4ca1878705 | |||
| 452df5d409 | |||
| e633d62a3b | |||
| 2a321b881e | |||
| 802d5f6efa | |||
| e0038bde36 | |||
| 1cbf1b18b7 | |||
| c3a021fcde | |||
| e6ea7e4563 | |||
| 3ab578aadf | |||
| d2db4cec97 | |||
| be44c5fdb0 | |||
| f63f0a766f | |||
| fbefa6a0ad | |||
| 9c4cdc3e02 | |||
| ba1c1b0fdb | |||
| 876af2e96c | |||
| 5bb18da6bf | |||
| 52d8ddae32 | |||
| 8c8c5a312e | |||
| 52756fb50d | |||
| bd8465d9b8 | |||
| 6c52b01ea7 | |||
| 5926da9493 | |||
| a9e926b907 | |||
| 2b2c3f9155 | |||
| 71fe69fd21 | |||
| eecf6df2a2 | |||
| d04a3e1af8 | |||
| 21462c26d5 | |||
| fc2122b11a | |||
| 11eed3aedc | |||
| dbc6dd6aed | |||
| e152aee740 | |||
| ff9b84c561 | |||
| 50c13398c4 | |||
| d991d0212d | |||
| 7c095c84a5 | |||
| a25e6740fd | |||
| d077902695 | |||
| 986ac588a9 | |||
| 64c73faab2 | |||
| b5464bec73 | |||
| 9f8f74fc7a | |||
| c4e5d1262a | |||
| 6afde71691 | |||
| aaf3bd83eb | |||
| 8fe71b03d5 | |||
| c2c156d707 | |||
| e46b9750c2 | |||
| 542b7a278d | |||
| 6d7e0d7b35 | |||
| 9daee4d8fd | |||
| d7b2ceb161 | |||
| 2236ef83a9 | |||
| 07f775dd18 | |||
| ad81d1535d | |||
| 7ecfaefcfa | |||
| ad4f676e2b | |||
| 54d6a023a4 | |||
| 6060293793 | |||
| afce764ce9 | |||
| 935484c790 | |||
| f2c14f9ad6 | |||
| ac2acf3d87 | |||
| 0b527b0855 | |||
| 9f8b603e28 | |||
| 6c904484e4 | |||
| 5382d03f93 | |||
| 5e602ebbf8 | |||
| 12c400cf1e | |||
| 92085d283a | |||
| 38aa34ffb0 | |||
| 52aa6402c0 | |||
| 8ea7f5434e | |||
| cf72068b6c | |||
| 9165a4941e | |||
| a8d9e308bc | |||
| c29fe8e5ac | |||
| d2ceeaadc4 | |||
| 32a2a9b15c | |||
| 31ac5aeb11 | |||
| 45885c7a01 | |||
| f1b43e26a1 | |||
| a3dd21c9d7 | |||
| e1e3d88a1c | |||
| 758ab6d8af | |||
| 569e43f184 | |||
| 79ee40037b | |||
| f032c9b0ea | |||
| 3d79b8fc36 | |||
| f6e976f182 | |||
| 3d9d7bafe4 | |||
| ad5ea817f7 | |||
| 3841abca35 |
+235
-4
@@ -1,7 +1,7 @@
|
|||||||
syntax = "proto3";
|
syntax = "proto3";
|
||||||
package proto;
|
package proto;
|
||||||
|
|
||||||
/// WhatsApp Version: 2.3000.1034238531
|
/// WhatsApp Version: 2.3000.1038164556
|
||||||
|
|
||||||
message ADVDeviceIdentity {
|
message ADVDeviceIdentity {
|
||||||
optional uint32 rawId = 1;
|
optional uint32 rawId = 1;
|
||||||
@@ -74,6 +74,7 @@ message AIMediaCollectionMessage {
|
|||||||
|
|
||||||
message AIMediaCollectionMetadata {
|
message AIMediaCollectionMetadata {
|
||||||
optional string collectionId = 1;
|
optional string collectionId = 1;
|
||||||
|
optional uint32 uploadOrderIndex = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message AIQueryFanout {
|
message AIQueryFanout {
|
||||||
@@ -251,10 +252,12 @@ message AIThreadInfo {
|
|||||||
optional AIThreadClientInfo clientInfo = 2;
|
optional AIThreadClientInfo clientInfo = 2;
|
||||||
message AIThreadClientInfo {
|
message AIThreadClientInfo {
|
||||||
optional AIThreadType type = 1;
|
optional AIThreadType type = 1;
|
||||||
|
optional string sourceChatJid = 2;
|
||||||
enum AIThreadType {
|
enum AIThreadType {
|
||||||
UNKNOWN = 0;
|
UNKNOWN = 0;
|
||||||
DEFAULT = 1;
|
DEFAULT = 1;
|
||||||
INCOGNITO = 2;
|
INCOGNITO = 2;
|
||||||
|
SIDE_CHAT = 3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,6 +345,14 @@ message BotAgeCollectionMetadata {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message BotAgentDeepLinkMetadata {
|
||||||
|
optional string token = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
message BotAgentMetadata {
|
||||||
|
optional BotAgentDeepLinkMetadata deepLinkMetadata = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message BotCapabilityMetadata {
|
message BotCapabilityMetadata {
|
||||||
repeated BotCapabilityType capabilities = 1;
|
repeated BotCapabilityType capabilities = 1;
|
||||||
enum BotCapabilityType {
|
enum BotCapabilityType {
|
||||||
@@ -403,9 +414,19 @@ message BotCapabilityMetadata {
|
|||||||
RICH_RESPONSE_UR_BLOKS_ENABLED = 55;
|
RICH_RESPONSE_UR_BLOKS_ENABLED = 55;
|
||||||
RICH_RESPONSE_INLINE_LINKS_ENABLED = 56;
|
RICH_RESPONSE_INLINE_LINKS_ENABLED = 56;
|
||||||
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57;
|
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57;
|
||||||
|
JSON_PATCH_STREAMING = 58;
|
||||||
|
AI_TAB_FORCE_CLIPPY = 59;
|
||||||
|
UNIFIED_RESPONSE_EMBEDDED_SCREENS = 60;
|
||||||
|
AI_SUBSCRIPTION_ENABLED = 61;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message BotCommandMetadata {
|
||||||
|
optional string commandName = 1;
|
||||||
|
optional string commandDescription = 2;
|
||||||
|
optional string commandPrompt = 3;
|
||||||
|
}
|
||||||
|
|
||||||
message BotDocumentMessageMetadata {
|
message BotDocumentMessageMetadata {
|
||||||
optional DocumentPluginType pluginType = 1;
|
optional DocumentPluginType pluginType = 1;
|
||||||
enum DocumentPluginType {
|
enum DocumentPluginType {
|
||||||
@@ -637,6 +658,7 @@ message BotMetadata {
|
|||||||
optional BotRenderingConfigMetadata botRenderingConfigMetadata = 36;
|
optional BotRenderingConfigMetadata botRenderingConfigMetadata = 36;
|
||||||
optional BotInfrastructureDiagnostics botInfrastructureDiagnostics = 37;
|
optional BotInfrastructureDiagnostics botInfrastructureDiagnostics = 37;
|
||||||
optional AIMediaCollectionMetadata aiMediaCollectionMetadata = 38;
|
optional AIMediaCollectionMetadata aiMediaCollectionMetadata = 38;
|
||||||
|
optional BotCommandMetadata commandMetadata = 39;
|
||||||
optional bytes internalMetadata = 999;
|
optional bytes internalMetadata = 999;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -687,6 +709,8 @@ enum BotMetricsEntryPoint {
|
|||||||
WEB_INTRO_PANEL = 46;
|
WEB_INTRO_PANEL = 46;
|
||||||
WEB_NAVIGATION_BAR = 47;
|
WEB_NAVIGATION_BAR = 47;
|
||||||
GROUP_MEMBER = 54;
|
GROUP_MEMBER = 54;
|
||||||
|
CHATLIST_SEARCH = 55;
|
||||||
|
NEW_CHAT_LIST = 56;
|
||||||
}
|
}
|
||||||
message BotMetricsMetadata {
|
message BotMetricsMetadata {
|
||||||
optional string destinationId = 1;
|
optional string destinationId = 1;
|
||||||
@@ -1069,6 +1093,7 @@ message ClientPairingProps {
|
|||||||
optional bool isSyncdPureLidSession = 2;
|
optional bool isSyncdPureLidSession = 2;
|
||||||
optional bool isSyncdSnapshotRecoveryEnabled = 3;
|
optional bool isSyncdSnapshotRecoveryEnabled = 3;
|
||||||
optional bool isHsThumbnailSyncEnabled = 4;
|
optional bool isHsThumbnailSyncEnabled = 4;
|
||||||
|
optional bytes subscriptionSyncPayload = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
message ClientPayload {
|
message ClientPayload {
|
||||||
@@ -1106,6 +1131,7 @@ message ClientPayload {
|
|||||||
optional bool paaLink = 44;
|
optional bool paaLink = 44;
|
||||||
optional int32 preacksCount = 45;
|
optional int32 preacksCount = 45;
|
||||||
optional int32 processingQueueSize = 46;
|
optional int32 processingQueueSize = 46;
|
||||||
|
repeated string pairedPeripherals = 47;
|
||||||
enum AccountType {
|
enum AccountType {
|
||||||
DEFAULT = 0;
|
DEFAULT = 0;
|
||||||
GUEST = 1;
|
GUEST = 1;
|
||||||
@@ -1448,6 +1474,11 @@ message ContextInfo {
|
|||||||
optional AdType adType = 25;
|
optional AdType adType = 25;
|
||||||
optional string wtwaWebsiteUrl = 26;
|
optional string wtwaWebsiteUrl = 26;
|
||||||
optional string adPreviewUrl = 27;
|
optional string adPreviewUrl = 27;
|
||||||
|
optional bool containsCtwaFlowsAutoReply = 28;
|
||||||
|
optional int32 agmThumbnailStrategy = 29;
|
||||||
|
optional int32 agmTitleStrategy = 30;
|
||||||
|
optional int32 agmSubtitleStrategy = 31;
|
||||||
|
optional int32 agmHeaderInteractionStrategy = 32;
|
||||||
enum AdType {
|
enum AdType {
|
||||||
CTWA = 0;
|
CTWA = 0;
|
||||||
CAWC = 1;
|
CAWC = 1;
|
||||||
@@ -1602,6 +1633,8 @@ message Conversation {
|
|||||||
optional bool limitSharingInitiatedByMe = 53;
|
optional bool limitSharingInitiatedByMe = 53;
|
||||||
optional bool maibaAiThreadEnabled = 54;
|
optional bool maibaAiThreadEnabled = 54;
|
||||||
optional bool isMarketingMessageThread = 55;
|
optional bool isMarketingMessageThread = 55;
|
||||||
|
optional bool isSenderNewAccount = 56;
|
||||||
|
optional uint32 afterReadDuration = 57;
|
||||||
enum EndOfHistoryTransferType {
|
enum EndOfHistoryTransferType {
|
||||||
COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY = 0;
|
COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY = 0;
|
||||||
COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY = 1;
|
COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY = 1;
|
||||||
@@ -1628,6 +1661,10 @@ message DeviceCapabilities {
|
|||||||
|
|
||||||
message BusinessBroadcast {
|
message BusinessBroadcast {
|
||||||
optional bool importListEnabled = 1;
|
optional bool importListEnabled = 1;
|
||||||
|
optional bool companionSupportEnabled = 2;
|
||||||
|
optional bool campaignSyncEnabled = 3;
|
||||||
|
optional bool insightsSyncEnabled = 4;
|
||||||
|
optional int32 recipientLimit = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum ChatLockSupportLevel {
|
enum ChatLockSupportLevel {
|
||||||
@@ -1702,6 +1739,9 @@ message DeviceProps {
|
|||||||
optional uint32 thumbnailSyncDaysLimit = 19;
|
optional uint32 thumbnailSyncDaysLimit = 19;
|
||||||
optional uint32 initialSyncMaxMessagesPerChat = 20;
|
optional uint32 initialSyncMaxMessagesPerChat = 20;
|
||||||
optional bool supportManusHistory = 21;
|
optional bool supportManusHistory = 21;
|
||||||
|
optional bool supportHatchHistory = 22;
|
||||||
|
repeated string supportedBotChannelFbids = 23;
|
||||||
|
optional bool supportInlineContacts = 24;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum PlatformType {
|
enum PlatformType {
|
||||||
@@ -1888,6 +1928,16 @@ message GroupParticipant {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message GroupRootKeyShare {
|
||||||
|
repeated GroupRootKeyShareEntry keys = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
message GroupRootKeyShareEntry {
|
||||||
|
optional bytes groupRootKey = 1;
|
||||||
|
optional string keyId = 2;
|
||||||
|
optional int64 expiryTimestampMs = 3;
|
||||||
|
}
|
||||||
|
|
||||||
message HandshakeMessage {
|
message HandshakeMessage {
|
||||||
optional ClientHello clientHello = 2;
|
optional ClientHello clientHello = 2;
|
||||||
optional ServerHello serverHello = 3;
|
optional ServerHello serverHello = 3;
|
||||||
@@ -1896,6 +1946,8 @@ message HandshakeMessage {
|
|||||||
optional bytes static = 1;
|
optional bytes static = 1;
|
||||||
optional bytes payload = 2;
|
optional bytes payload = 2;
|
||||||
optional bytes extendedCiphertext = 3;
|
optional bytes extendedCiphertext = 3;
|
||||||
|
optional bytes paddedBytes = 4;
|
||||||
|
optional bool simulateXxkemFs = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
message ClientHello {
|
message ClientHello {
|
||||||
@@ -1904,13 +1956,31 @@ message HandshakeMessage {
|
|||||||
optional bytes payload = 3;
|
optional bytes payload = 3;
|
||||||
optional bool useExtended = 4;
|
optional bool useExtended = 4;
|
||||||
optional bytes extendedCiphertext = 5;
|
optional bytes extendedCiphertext = 5;
|
||||||
|
optional bytes paddedBytes = 6;
|
||||||
|
optional bool sendServerHelloPaddedBytes = 7;
|
||||||
|
optional bool simulateXxkemFs = 8;
|
||||||
|
optional HandshakeMessage.HandshakePqMode pqMode = 9;
|
||||||
|
optional bytes extendedEphemeral = 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum HandshakePqMode {
|
||||||
|
HANDSHAKE_PQ_MODE_UNKNOWN = 0;
|
||||||
|
XXKEM = 1;
|
||||||
|
XXKEM_FS = 2;
|
||||||
|
WA_CLASSICAL = 3;
|
||||||
|
WA_PQ = 4;
|
||||||
|
IKKEM = 5;
|
||||||
|
IKKEM_FS = 6;
|
||||||
|
XXKEM_2 = 7;
|
||||||
|
IKKEM_2 = 8;
|
||||||
|
}
|
||||||
message ServerHello {
|
message ServerHello {
|
||||||
optional bytes ephemeral = 1;
|
optional bytes ephemeral = 1;
|
||||||
optional bytes static = 2;
|
optional bytes static = 2;
|
||||||
optional bytes payload = 3;
|
optional bytes payload = 3;
|
||||||
optional bytes extendedStatic = 4;
|
optional bytes extendedStatic = 4;
|
||||||
|
optional bytes paddingBytes = 5;
|
||||||
|
optional bytes extendedCiphertext = 6;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1934,6 +2004,8 @@ message HistorySync {
|
|||||||
optional bytes shareableChatIdentifierEncryptionKey = 17;
|
optional bytes shareableChatIdentifierEncryptionKey = 17;
|
||||||
repeated Account accounts = 18;
|
repeated Account accounts = 18;
|
||||||
optional bytes nctSalt = 19;
|
optional bytes nctSalt = 19;
|
||||||
|
repeated InlineContact inlineContacts = 20;
|
||||||
|
optional bool inlineContactsProvided = 21;
|
||||||
enum BotAIWaitListState {
|
enum BotAIWaitListState {
|
||||||
IN_WAITLIST = 0;
|
IN_WAITLIST = 0;
|
||||||
AI_AVAILABLE = 1;
|
AI_AVAILABLE = 1;
|
||||||
@@ -2028,6 +2100,14 @@ message InThreadSurveyMetadata {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message InlineContact {
|
||||||
|
optional string pnJid = 1;
|
||||||
|
optional string lidJid = 2;
|
||||||
|
optional string fullName = 3;
|
||||||
|
optional string firstName = 4;
|
||||||
|
optional string username = 5;
|
||||||
|
}
|
||||||
|
|
||||||
message InteractiveAnnotation {
|
message InteractiveAnnotation {
|
||||||
repeated Point polygonVertices = 1;
|
repeated Point polygonVertices = 1;
|
||||||
optional bool shouldSkipConfirmation = 4;
|
optional bool shouldSkipConfirmation = 4;
|
||||||
@@ -2106,7 +2186,6 @@ message LimitSharing {
|
|||||||
CHAT_SETTING = 1;
|
CHAT_SETTING = 1;
|
||||||
BIZ_SUPPORTS_FB_HOSTING = 2;
|
BIZ_SUPPORTS_FB_HOSTING = 2;
|
||||||
UNKNOWN_GROUP = 3;
|
UNKNOWN_GROUP = 3;
|
||||||
DEPRECATION = 4;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2267,6 +2346,8 @@ message Message {
|
|||||||
optional PollCreationMessage pollCreationMessageV6 = 119;
|
optional PollCreationMessage pollCreationMessageV6 = 119;
|
||||||
optional ConditionalRevealMessage conditionalRevealMessage = 120;
|
optional ConditionalRevealMessage conditionalRevealMessage = 120;
|
||||||
optional PollAddOptionMessage pollAddOptionMessage = 121;
|
optional PollAddOptionMessage pollAddOptionMessage = 121;
|
||||||
|
optional EventInviteMessage eventInviteMessage = 122;
|
||||||
|
optional GroupRootKeyShare groupRootKeyShare = 123;
|
||||||
message AlbumMessage {
|
message AlbumMessage {
|
||||||
optional uint32 expectedImageCount = 2;
|
optional uint32 expectedImageCount = 2;
|
||||||
optional uint32 expectedVideoCount = 3;
|
optional uint32 expectedVideoCount = 3;
|
||||||
@@ -2458,6 +2539,7 @@ message Message {
|
|||||||
UNKNOWN = 0;
|
UNKNOWN = 0;
|
||||||
CONTROL_PASSED = 1;
|
CONTROL_PASSED = 1;
|
||||||
CONTROL_TAKEN = 2;
|
CONTROL_TAKEN = 2;
|
||||||
|
INFO = 3;
|
||||||
}
|
}
|
||||||
message CloudAPIThreadControlNotificationContent {
|
message CloudAPIThreadControlNotificationContent {
|
||||||
optional string handoffNotificationText = 1;
|
optional string handoffNotificationText = 1;
|
||||||
@@ -2547,6 +2629,16 @@ message Message {
|
|||||||
optional bytes encIv = 3;
|
optional bytes encIv = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message EventInviteMessage {
|
||||||
|
optional ContextInfo contextInfo = 1;
|
||||||
|
optional string eventId = 2;
|
||||||
|
optional string eventTitle = 3;
|
||||||
|
optional bytes jpegThumbnail = 4;
|
||||||
|
optional int64 startTime = 5;
|
||||||
|
optional string caption = 6;
|
||||||
|
optional bool isCanceled = 7;
|
||||||
|
}
|
||||||
|
|
||||||
message EventMessage {
|
message EventMessage {
|
||||||
optional ContextInfo contextInfo = 1;
|
optional ContextInfo contextInfo = 1;
|
||||||
optional bool isCanceled = 2;
|
optional bool isCanceled = 2;
|
||||||
@@ -2798,6 +2890,13 @@ message Message {
|
|||||||
optional bool securityNotificationEnabled = 1;
|
optional bool securityNotificationEnabled = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum InsightDeliveryState {
|
||||||
|
SENT = 0;
|
||||||
|
DELIVERED = 1;
|
||||||
|
READ = 2;
|
||||||
|
REPLIED = 3;
|
||||||
|
QUICK_REPLIED = 4;
|
||||||
|
}
|
||||||
message InteractiveMessage {
|
message InteractiveMessage {
|
||||||
optional Header header = 1;
|
optional Header header = 1;
|
||||||
optional Body body = 2;
|
optional Body body = 2;
|
||||||
@@ -3066,9 +3165,10 @@ message Message {
|
|||||||
|
|
||||||
message MessageHistoryMetadata {
|
message MessageHistoryMetadata {
|
||||||
repeated string historyReceivers = 1;
|
repeated string historyReceivers = 1;
|
||||||
optional int64 oldestMessageTimestamp = 2;
|
optional int64 oldestMessageTimestampInWindow = 2;
|
||||||
optional int64 messageCount = 3;
|
optional int64 messageCount = 3;
|
||||||
repeated string nonHistoryReceivers = 4;
|
repeated string nonHistoryReceivers = 4;
|
||||||
|
optional int64 oldestMessageTimestampInBundle = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
message MessageHistoryNotice {
|
message MessageHistoryNotice {
|
||||||
@@ -3129,6 +3229,11 @@ message Message {
|
|||||||
optional int64 expiryTimestamp = 2;
|
optional int64 expiryTimestamp = 2;
|
||||||
optional bool incentiveEligible = 3;
|
optional bool incentiveEligible = 3;
|
||||||
optional string referralId = 4;
|
optional string referralId = 4;
|
||||||
|
optional InviteType inviteType = 5;
|
||||||
|
enum InviteType {
|
||||||
|
DEFAULT = 0;
|
||||||
|
MAPPER = 1;
|
||||||
|
}
|
||||||
enum ServiceType {
|
enum ServiceType {
|
||||||
UNKNOWN = 0;
|
UNKNOWN = 0;
|
||||||
FBPAY = 1;
|
FBPAY = 1;
|
||||||
@@ -3170,6 +3275,16 @@ message Message {
|
|||||||
optional HistorySyncChunkRetryRequest historySyncChunkRetryRequest = 8;
|
optional HistorySyncChunkRetryRequest historySyncChunkRetryRequest = 8;
|
||||||
optional GalaxyFlowAction galaxyFlowAction = 9;
|
optional GalaxyFlowAction galaxyFlowAction = 9;
|
||||||
optional CompanionCanonicalUserNonceFetchRequest companionCanonicalUserNonceFetchRequest = 10;
|
optional CompanionCanonicalUserNonceFetchRequest companionCanonicalUserNonceFetchRequest = 10;
|
||||||
|
optional BizBroadcastInsightsContactListRequest bizBroadcastInsightsContactListRequest = 11;
|
||||||
|
optional BizBroadcastInsightsRefreshRequest bizBroadcastInsightsRefreshRequest = 12;
|
||||||
|
message BizBroadcastInsightsContactListRequest {
|
||||||
|
optional string campaignId = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
message BizBroadcastInsightsRefreshRequest {
|
||||||
|
optional string campaignId = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message CompanionCanonicalUserNonceFetchRequest {
|
message CompanionCanonicalUserNonceFetchRequest {
|
||||||
optional string registrationTraceId = 1;
|
optional string registrationTraceId = 1;
|
||||||
}
|
}
|
||||||
@@ -3206,6 +3321,7 @@ message Message {
|
|||||||
optional int32 onDemandMsgCount = 4;
|
optional int32 onDemandMsgCount = 4;
|
||||||
optional int64 oldestMsgTimestampMs = 5;
|
optional int64 oldestMsgTimestampMs = 5;
|
||||||
optional string accountLid = 6;
|
optional string accountLid = 6;
|
||||||
|
optional bool supportInlineResponse = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
message PlaceholderMessageResendRequest {
|
message PlaceholderMessageResendRequest {
|
||||||
@@ -3244,6 +3360,18 @@ message Message {
|
|||||||
optional CompanionCanonicalUserNonceFetchResponse companionCanonicalUserNonceFetchRequestResponse = 9;
|
optional CompanionCanonicalUserNonceFetchResponse companionCanonicalUserNonceFetchRequestResponse = 9;
|
||||||
optional HistorySyncChunkRetryResponse historySyncChunkRetryResponse = 10;
|
optional HistorySyncChunkRetryResponse historySyncChunkRetryResponse = 10;
|
||||||
optional FlowResponsesCsvBundle flowResponsesCsvBundle = 11;
|
optional FlowResponsesCsvBundle flowResponsesCsvBundle = 11;
|
||||||
|
optional BizBroadcastInsightsContactListResponse bizBroadcastInsightsContactListResponse = 12;
|
||||||
|
message BizBroadcastInsightsContactListResponse {
|
||||||
|
optional string campaignId = 1;
|
||||||
|
optional int64 timestampMs = 2;
|
||||||
|
repeated Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactState contacts = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message BizBroadcastInsightsContactState {
|
||||||
|
optional string contactJid = 1;
|
||||||
|
optional Message.InsightDeliveryState state = 2;
|
||||||
|
}
|
||||||
|
|
||||||
message CompanionCanonicalUserNonceFetchResponse {
|
message CompanionCanonicalUserNonceFetchResponse {
|
||||||
optional string nonce = 1;
|
optional string nonce = 1;
|
||||||
optional string waFbid = 2;
|
optional string waFbid = 2;
|
||||||
@@ -3280,6 +3408,7 @@ message Message {
|
|||||||
ERROR_REQUEST_ON_NON_SMB_PRIMARY = 4;
|
ERROR_REQUEST_ON_NON_SMB_PRIMARY = 4;
|
||||||
ERROR_HOSTED_DEVICE_NOT_CONNECTED = 5;
|
ERROR_HOSTED_DEVICE_NOT_CONNECTED = 5;
|
||||||
ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET = 6;
|
ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET = 6;
|
||||||
|
ERROR_MULTI_PROVIDER_NOT_CONFIGURED = 7;
|
||||||
}
|
}
|
||||||
message HistorySyncChunkRetryResponse {
|
message HistorySyncChunkRetryResponse {
|
||||||
optional Message.HistorySyncType syncType = 1;
|
optional Message.HistorySyncType syncType = 1;
|
||||||
@@ -3357,6 +3486,8 @@ message Message {
|
|||||||
COMPANION_CANONICAL_USER_NONCE_FETCH = 9;
|
COMPANION_CANONICAL_USER_NONCE_FETCH = 9;
|
||||||
HISTORY_SYNC_CHUNK_RETRY = 10;
|
HISTORY_SYNC_CHUNK_RETRY = 10;
|
||||||
GALAXY_FLOW_ACTION = 11;
|
GALAXY_FLOW_ACTION = 11;
|
||||||
|
BUSINESS_BROADCAST_INSIGHTS_DELIVERED_TO = 12;
|
||||||
|
BUSINESS_BROADCAST_INSIGHTS_REFRESH = 13;
|
||||||
}
|
}
|
||||||
message PinInChatMessage {
|
message PinInChatMessage {
|
||||||
optional MessageKey key = 1;
|
optional MessageKey key = 1;
|
||||||
@@ -3558,6 +3689,7 @@ message Message {
|
|||||||
message RequestWelcomeMessageMetadata {
|
message RequestWelcomeMessageMetadata {
|
||||||
optional LocalChatState localChatState = 1;
|
optional LocalChatState localChatState = 1;
|
||||||
optional WelcomeTrigger welcomeTrigger = 2;
|
optional WelcomeTrigger welcomeTrigger = 2;
|
||||||
|
optional BotAgentMetadata botAgentMetadata = 3;
|
||||||
enum LocalChatState {
|
enum LocalChatState {
|
||||||
EMPTY = 0;
|
EMPTY = 0;
|
||||||
NON_EMPTY = 1;
|
NON_EMPTY = 1;
|
||||||
@@ -3675,6 +3807,7 @@ message Message {
|
|||||||
optional bool isLottie = 21;
|
optional bool isLottie = 21;
|
||||||
optional string accessibilityLabel = 22;
|
optional string accessibilityLabel = 22;
|
||||||
optional int32 premium = 24;
|
optional int32 premium = 24;
|
||||||
|
optional string emojis = 25;
|
||||||
}
|
}
|
||||||
|
|
||||||
message StickerPackMessage {
|
message StickerPackMessage {
|
||||||
@@ -3895,6 +4028,7 @@ message MessageContextInfo {
|
|||||||
optional LimitSharing limitSharingV2 = 14;
|
optional LimitSharing limitSharingV2 = 14;
|
||||||
repeated ThreadID threadId = 15;
|
repeated ThreadID threadId = 15;
|
||||||
optional WebLinkRenderConfig weblinkRenderConfig = 16;
|
optional WebLinkRenderConfig weblinkRenderConfig = 16;
|
||||||
|
optional bytes teeBotMetadata = 17;
|
||||||
enum MessageAddonExpiryType {
|
enum MessageAddonExpiryType {
|
||||||
STATIC = 1;
|
STATIC = 1;
|
||||||
DEPENDENT_ON_PARENT = 2;
|
DEPENDENT_ON_PARENT = 2;
|
||||||
@@ -3967,6 +4101,7 @@ message MsgOpaqueData {
|
|||||||
optional string quarantineExtractedText = 48;
|
optional string quarantineExtractedText = 48;
|
||||||
optional int64 pollEndTime = 49;
|
optional int64 pollEndTime = 49;
|
||||||
optional bool pollHideVoterNames = 50;
|
optional bool pollHideVoterNames = 50;
|
||||||
|
optional bool pollAllowAddOption = 52;
|
||||||
message EventLocation {
|
message EventLocation {
|
||||||
optional double degreesLatitude = 1;
|
optional double degreesLatitude = 1;
|
||||||
optional double degreesLongitude = 2;
|
optional double degreesLongitude = 2;
|
||||||
@@ -4083,6 +4218,11 @@ enum MutationProps {
|
|||||||
NCT_SALT_SYNC_ACTION = 80;
|
NCT_SALT_SYNC_ACTION = 80;
|
||||||
BUSINESS_BROADCAST_CAMPAIGN_ACTION = 81;
|
BUSINESS_BROADCAST_CAMPAIGN_ACTION = 81;
|
||||||
BUSINESS_BROADCAST_INSIGHTS_ACTION = 82;
|
BUSINESS_BROADCAST_INSIGHTS_ACTION = 82;
|
||||||
|
CUSTOMER_DATA_ACTION = 83;
|
||||||
|
SUBSCRIPTIONS_SYNC_V2_ACTION = 84;
|
||||||
|
THREAD_PIN_ACTION = 85;
|
||||||
|
AUTO_ORGANIZE_BUSINESS_CHAT_SETTING = 86;
|
||||||
|
BIZ_AI_SETTINGS_NUDGE_ACTION = 87;
|
||||||
SHARE_OWN_PN = 10001;
|
SHARE_OWN_PN = 10001;
|
||||||
BUSINESS_BROADCAST_ACTION = 10002;
|
BUSINESS_BROADCAST_ACTION = 10002;
|
||||||
AI_THREAD_DELETE_ACTION = 10003;
|
AI_THREAD_DELETE_ACTION = 10003;
|
||||||
@@ -4396,6 +4536,12 @@ message ReportingTokenInfo {
|
|||||||
optional bytes reportingTag = 1;
|
optional bytes reportingTag = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message ScheduledMessageMetadata {
|
||||||
|
optional string revealKeyId = 1;
|
||||||
|
optional bytes revealKey = 2;
|
||||||
|
optional uint64 scheduledTime = 3;
|
||||||
|
}
|
||||||
|
|
||||||
message SenderKeyDistributionMessage {
|
message SenderKeyDistributionMessage {
|
||||||
optional uint32 id = 1;
|
optional uint32 id = 1;
|
||||||
optional uint32 iteration = 2;
|
optional uint32 iteration = 2;
|
||||||
@@ -4551,6 +4697,7 @@ message StatusAttribution {
|
|||||||
APPLE_MUSIC = 8;
|
APPLE_MUSIC = 8;
|
||||||
SHARECHAT = 9;
|
SHARECHAT = 9;
|
||||||
GOOGLE_PHOTOS = 10;
|
GOOGLE_PHOTOS = 10;
|
||||||
|
SOUNDCLOUD = 11;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4718,6 +4865,11 @@ message SyncActionValue {
|
|||||||
optional NctSaltSyncAction nctSaltSyncAction = 80;
|
optional NctSaltSyncAction nctSaltSyncAction = 80;
|
||||||
optional BusinessBroadcastCampaignAction businessBroadcastCampaignAction = 81;
|
optional BusinessBroadcastCampaignAction businessBroadcastCampaignAction = 81;
|
||||||
optional BusinessBroadcastInsightsAction businessBroadcastInsightsAction = 82;
|
optional BusinessBroadcastInsightsAction businessBroadcastInsightsAction = 82;
|
||||||
|
optional CustomerDataAction customerDataAction = 83;
|
||||||
|
optional SubscriptionsSyncV2Action subscriptionsSyncV2Action = 84;
|
||||||
|
optional ThreadPinAction threadPinAction = 85;
|
||||||
|
optional AutoOrganizeBusinessChatSetting autoOrganizeBusinessChatSetting = 86;
|
||||||
|
optional BizAISettingsNudgeAction bizAiSettingsNudgeAction = 87;
|
||||||
message AgentAction {
|
message AgentAction {
|
||||||
optional string name = 1;
|
optional string name = 1;
|
||||||
optional int32 deviceID = 2;
|
optional int32 deviceID = 2;
|
||||||
@@ -4737,6 +4889,10 @@ message SyncActionValue {
|
|||||||
optional SyncActionValue.SyncActionMessageRange messageRange = 2;
|
optional SyncActionValue.SyncActionMessageRange messageRange = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message AutoOrganizeBusinessChatSetting {
|
||||||
|
optional bool autoOrganize = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message AvatarUpdatedAction {
|
message AvatarUpdatedAction {
|
||||||
optional AvatarEventType eventType = 1;
|
optional AvatarEventType eventType = 1;
|
||||||
repeated SyncActionValue.StickerAction recentAvatarStickers = 2;
|
repeated SyncActionValue.StickerAction recentAvatarStickers = 2;
|
||||||
@@ -4747,6 +4903,20 @@ message SyncActionValue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message BizAISettingsNudgeAction {
|
||||||
|
optional BizAISettingsCategory category = 1;
|
||||||
|
optional int64 version = 2;
|
||||||
|
optional int64 updatedAtMs = 3;
|
||||||
|
enum BizAISettingsCategory {
|
||||||
|
UNKNOWN = 0;
|
||||||
|
INSTRUCTIONS = 1;
|
||||||
|
RESPONSE_SETTINGS = 2;
|
||||||
|
EXAMPLE_RESPONSES = 3;
|
||||||
|
KNOWLEDGE = 4;
|
||||||
|
LEAD_GEN = 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
message BotWelcomeRequestAction {
|
message BotWelcomeRequestAction {
|
||||||
optional bool isSent = 1;
|
optional bool isSent = 1;
|
||||||
}
|
}
|
||||||
@@ -4792,6 +4962,7 @@ message SyncActionValue {
|
|||||||
repeated SyncActionValue.BroadcastListParticipant participants = 2;
|
repeated SyncActionValue.BroadcastListParticipant participants = 2;
|
||||||
optional string listName = 3;
|
optional string listName = 3;
|
||||||
repeated string labelIds = 4;
|
repeated string labelIds = 4;
|
||||||
|
optional string audienceExpression = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
message CallLogAction {
|
message CallLogAction {
|
||||||
@@ -4839,6 +5010,20 @@ message SyncActionValue {
|
|||||||
repeated SyncActionValue.CustomPaymentMethod customPaymentMethods = 1;
|
repeated SyncActionValue.CustomPaymentMethod customPaymentMethods = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message CustomerDataAction {
|
||||||
|
optional string chatJid = 1;
|
||||||
|
optional int32 contactType = 2;
|
||||||
|
optional string email = 3;
|
||||||
|
optional string altPhoneNumbers = 4;
|
||||||
|
optional int64 birthday = 5;
|
||||||
|
optional string address = 6;
|
||||||
|
optional int32 acquisitionSource = 7;
|
||||||
|
optional int32 leadStage = 8;
|
||||||
|
optional int64 lastOrder = 9;
|
||||||
|
optional int64 createdAt = 10;
|
||||||
|
optional int64 modifiedAt = 11;
|
||||||
|
}
|
||||||
|
|
||||||
message DeleteChatAction {
|
message DeleteChatAction {
|
||||||
optional SyncActionValue.SyncActionMessageRange messageRange = 1;
|
optional SyncActionValue.SyncActionMessageRange messageRange = 1;
|
||||||
}
|
}
|
||||||
@@ -4907,6 +5092,7 @@ message SyncActionValue {
|
|||||||
DRAFTED = 8;
|
DRAFTED = 8;
|
||||||
AI_HANDOFF = 9;
|
AI_HANDOFF = 9;
|
||||||
CHANNELS = 10;
|
CHANNELS = 10;
|
||||||
|
AI_RESPONDING = 11;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5122,6 +5308,8 @@ message SyncActionValue {
|
|||||||
optional bool isStatusNotificationEnabled = 29;
|
optional bool isStatusNotificationEnabled = 29;
|
||||||
optional int32 statusNotificationToneId = 30;
|
optional int32 statusNotificationToneId = 30;
|
||||||
optional bool shouldPlaySoundForCallNotification = 31;
|
optional bool shouldPlaySoundForCallNotification = 31;
|
||||||
|
optional string chatThemeId = 32;
|
||||||
|
optional string colorSchemeId = 33;
|
||||||
enum DisplayMode {
|
enum DisplayMode {
|
||||||
DISPLAY_MODE_UNKNOWN = 0;
|
DISPLAY_MODE_UNKNOWN = 0;
|
||||||
ALWAYS = 1;
|
ALWAYS = 1;
|
||||||
@@ -5166,6 +5354,8 @@ message SyncActionValue {
|
|||||||
IS_STATUS_NOTIFICATION_ENABLED = 29;
|
IS_STATUS_NOTIFICATION_ENABLED = 29;
|
||||||
STATUS_NOTIFICATION_TONE_ID = 30;
|
STATUS_NOTIFICATION_TONE_ID = 30;
|
||||||
SHOULD_PLAY_SOUND_FOR_CALL_NOTIFICATION = 31;
|
SHOULD_PLAY_SOUND_FOR_CALL_NOTIFICATION = 31;
|
||||||
|
CHAT_THEME_ID = 32;
|
||||||
|
COLOR_SCHEME_ID = 33;
|
||||||
}
|
}
|
||||||
enum SettingPlatform {
|
enum SettingPlatform {
|
||||||
PLATFORM_UNKNOWN = 0;
|
PLATFORM_UNKNOWN = 0;
|
||||||
@@ -5189,11 +5379,22 @@ message SyncActionValue {
|
|||||||
repeated string userJid = 2;
|
repeated string userJid = 2;
|
||||||
optional bool shareToFB = 3;
|
optional bool shareToFB = 3;
|
||||||
optional bool shareToIG = 4;
|
optional bool shareToIG = 4;
|
||||||
|
repeated CustomList customLists = 5;
|
||||||
|
repeated StatusDistributionMode modes = 6;
|
||||||
|
message CustomList {
|
||||||
|
optional string listId = 1;
|
||||||
|
optional string name = 2;
|
||||||
|
optional string emoji = 3;
|
||||||
|
optional bool isSelected = 4;
|
||||||
|
repeated string userJid = 5;
|
||||||
|
}
|
||||||
|
|
||||||
enum StatusDistributionMode {
|
enum StatusDistributionMode {
|
||||||
ALLOW_LIST = 0;
|
ALLOW_LIST = 0;
|
||||||
DENY_LIST = 1;
|
DENY_LIST = 1;
|
||||||
CONTACTS = 2;
|
CONTACTS = 2;
|
||||||
CLOSE_FRIENDS = 3;
|
CLOSE_FRIENDS = 3;
|
||||||
|
CUSTOM_LIST = 4;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5219,6 +5420,29 @@ message SyncActionValue {
|
|||||||
optional int64 expirationDate = 3;
|
optional int64 expirationDate = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message SubscriptionsSyncV2Action {
|
||||||
|
repeated SubscriptionInfo subscriptions = 1;
|
||||||
|
repeated PaidFeature paidFeature = 2;
|
||||||
|
message PaidFeature {
|
||||||
|
optional string name = 1;
|
||||||
|
optional bool enabled = 2;
|
||||||
|
optional int32 limit = 3;
|
||||||
|
optional int64 expirationTime = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
message SubscriptionInfo {
|
||||||
|
optional string id = 1;
|
||||||
|
optional int32 tier = 2;
|
||||||
|
optional string status = 3;
|
||||||
|
optional int64 startTime = 4;
|
||||||
|
optional int64 endTime = 5;
|
||||||
|
optional bool isPlatformChanged = 6;
|
||||||
|
optional string source = 7;
|
||||||
|
optional int64 creationTime = 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
message SyncActionMessage {
|
message SyncActionMessage {
|
||||||
optional MessageKey key = 1;
|
optional MessageKey key = 1;
|
||||||
optional int64 timestamp = 2;
|
optional int64 timestamp = 2;
|
||||||
@@ -5230,6 +5454,10 @@ message SyncActionValue {
|
|||||||
repeated SyncActionValue.SyncActionMessage messages = 3;
|
repeated SyncActionValue.SyncActionMessage messages = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message ThreadPinAction {
|
||||||
|
optional bool pinned = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message TimeFormatAction {
|
message TimeFormatAction {
|
||||||
optional bool isTwentyFourHourFormatEnabled = 1;
|
optional bool isTwentyFourHourFormatEnabled = 1;
|
||||||
}
|
}
|
||||||
@@ -5351,7 +5579,6 @@ message TemplateButton {
|
|||||||
message ThreadID {
|
message ThreadID {
|
||||||
optional ThreadType threadType = 1;
|
optional ThreadType threadType = 1;
|
||||||
optional MessageKey threadKey = 2;
|
optional MessageKey threadKey = 2;
|
||||||
optional string sourceChatJid = 3;
|
|
||||||
enum ThreadType {
|
enum ThreadType {
|
||||||
UNKNOWN = 0;
|
UNKNOWN = 0;
|
||||||
VIEW_REPLIES = 1;
|
VIEW_REPLIES = 1;
|
||||||
@@ -5554,6 +5781,8 @@ message WebMessageInfo {
|
|||||||
optional QuarantinedMessage quarantinedMessage = 77;
|
optional QuarantinedMessage quarantinedMessage = 77;
|
||||||
optional uint32 nonJidMentions = 78;
|
optional uint32 nonJidMentions = 78;
|
||||||
optional string hsmTag = 79;
|
optional string hsmTag = 79;
|
||||||
|
optional uint64 ephemeralExpirationTimestamp = 80;
|
||||||
|
optional ScheduledMessageMetadata scheduledMessageMetadata = 81;
|
||||||
enum BizPrivacyStatus {
|
enum BizPrivacyStatus {
|
||||||
E2EE = 0;
|
E2EE = 0;
|
||||||
FB = 2;
|
FB = 2;
|
||||||
@@ -5793,6 +6022,8 @@ message WebMessageInfo {
|
|||||||
GROUP_MEMBER_SHARE_GROUP_HISTORY_MODE = 221;
|
GROUP_MEMBER_SHARE_GROUP_HISTORY_MODE = 221;
|
||||||
GROUP_OPEN_BOT_ADDED = 222;
|
GROUP_OPEN_BOT_ADDED = 222;
|
||||||
GROUP_TEE_BOT_ADDED = 223;
|
GROUP_TEE_BOT_ADDED = 223;
|
||||||
|
CONTACT_INFO = 224;
|
||||||
|
SCHEDULED_MESSAGE_CREATED = 225;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+26
-18
@@ -18,14 +18,21 @@ try {
|
|||||||
'\tif (typeof value === "number") {\n' +
|
'\tif (typeof value === "number") {\n' +
|
||||||
'\t\treturn String(value);\n' +
|
'\t\treturn String(value);\n' +
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\tif (!$util.Long) {\n' +
|
'\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
|
||||||
'\t\treturn String(value);\n' +
|
'\t// BigInt.toString() is a native C++ operation, much faster than Long\'s pure JS division loops\n' +
|
||||||
|
'\tif (value && typeof value.low === "number" && typeof value.high === "number") {\n' +
|
||||||
|
'\t\t// Normalize high to signed int32 so the sign-bit check works for inputs\n' +
|
||||||
|
'\t\t// where high is stored unsigned (e.g. raw {low, high} JSON).\n' +
|
||||||
|
'\t\tconst high = value.high | 0;\n' +
|
||||||
|
'\t\tconst lo = BigInt(value.low >>> 0);\n' +
|
||||||
|
'\t\tconst hi = BigInt(value.high >>> 0);\n' +
|
||||||
|
'\t\tconst combined = (hi << 32n) | lo;\n' +
|
||||||
|
'\t\tif (!unsigned && high < 0) {\n' +
|
||||||
|
'\t\t\treturn (combined - (1n << 64n)).toString();\n' +
|
||||||
|
'\t\t}\n' +
|
||||||
|
'\t\treturn combined.toString();\n' +
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\tconst normalized = $util.Long.fromValue(value);\n' +
|
'\treturn String(value);\n' +
|
||||||
'\tconst prepared = unsigned && normalized && typeof normalized.toUnsigned === "function"\n' +
|
|
||||||
'\t\t? normalized.toUnsigned()\n' +
|
|
||||||
'\t\t: normalized;\n' +
|
|
||||||
'\treturn prepared.toString();\n' +
|
|
||||||
'}\n\n'
|
'}\n\n'
|
||||||
const longToNumberHelper =
|
const longToNumberHelper =
|
||||||
'function longToNumber(value, unsigned) {\n' +
|
'function longToNumber(value, unsigned) {\n' +
|
||||||
@@ -33,19 +40,20 @@ try {
|
|||||||
'\t\treturn value;\n' +
|
'\t\treturn value;\n' +
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\tif (typeof value === "string") {\n' +
|
'\tif (typeof value === "string") {\n' +
|
||||||
'\t\tconst numeric = Number(value);\n' +
|
|
||||||
'\t\treturn numeric;\n' +
|
|
||||||
'\t}\n' +
|
|
||||||
'\tif (!$util.Long) {\n' +
|
|
||||||
'\t\treturn Number(value);\n' +
|
'\t\treturn Number(value);\n' +
|
||||||
'\t}\n' +
|
'\t}\n' +
|
||||||
'\tconst normalized = $util.Long.fromValue(value);\n' +
|
'\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
|
||||||
'\tconst prepared = unsigned && normalized && typeof normalized.toUnsigned === "function"\n' +
|
'\tif (value && typeof value.low === "number" && typeof value.high === "number") {\n' +
|
||||||
'\t\t? normalized.toUnsigned()\n' +
|
'\t\tconst high = value.high | 0;\n' +
|
||||||
'\t\t: typeof normalized.toSigned === "function"\n' +
|
'\t\tconst lo = BigInt(value.low >>> 0);\n' +
|
||||||
'\t\t\t? normalized.toSigned()\n' +
|
'\t\tconst hi = BigInt(value.high >>> 0);\n' +
|
||||||
'\t\t\t: normalized;\n' +
|
'\t\tconst combined = (hi << 32n) | lo;\n' +
|
||||||
'\treturn prepared.toNumber();\n' +
|
'\t\tif (!unsigned && high < 0) {\n' +
|
||||||
|
'\t\t\treturn Number(combined - (1n << 64n));\n' +
|
||||||
|
'\t\t}\n' +
|
||||||
|
'\t\treturn Number(combined);\n' +
|
||||||
|
'\t}\n' +
|
||||||
|
'\treturn Number(value);\n' +
|
||||||
'}\n\n'
|
'}\n\n'
|
||||||
|
|
||||||
if (!content.includes('function longToString(')) {
|
if (!content.includes('function longToString(')) {
|
||||||
|
|||||||
Vendored
+597
-17
File diff suppressed because it is too large
Load Diff
+4489
-67
File diff suppressed because it is too large
Load Diff
+725
-409
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,531 @@
|
|||||||
|
# Mensagens View-Once (Visualização Única) — Guia de Implementação
|
||||||
|
|
||||||
|
**Data:** 2026-03-23
|
||||||
|
**Versão:** 1.0
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. O que é View-Once
|
||||||
|
|
||||||
|
Mensagem de visualização única é um tipo especial de mídia (imagem, vídeo ou áudio) que o destinatário pode abrir apenas uma vez. Após abrir, o conteúdo some permanentemente.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> ## ⚠️ RESTRIÇÃO CRÍTICA — Contas Hosted (Meta Business Cloud API)
|
||||||
|
>
|
||||||
|
> **Contas registradas como "hosted" na Meta Business Cloud API têm view-once bloqueado pelo servidor do WhatsApp.**
|
||||||
|
>
|
||||||
|
> Essa restrição se aplica a **todos os clientes** (Android, iOS, WA Web) e **não há como contornar por código** — é uma política imposta diretamente pelo servidor WA para contas hosted.
|
||||||
|
>
|
||||||
|
> **Como identificar se sua conta é hosted:**
|
||||||
|
> - A conta foi criada via Meta Business Cloud API (WABA)
|
||||||
|
> - Aparece como "Meta" ou "Business Cloud" nas configurações do WhatsApp Business Manager
|
||||||
|
>
|
||||||
|
> **Contas não-hosted** (registradas diretamente via QR code ou pair code) **funcionam normalmente** com view-once.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Comportamento em cada dispositivo após envio via API (contas não-hosted):**
|
||||||
|
|
||||||
|
| Dispositivo | O que aparece |
|
||||||
|
|---|---|
|
||||||
|
| Destinatário (Android/iOS) | Recebe a mídia com ícone de olhinho — pode abrir uma vez |
|
||||||
|
| Android principal do remetente | Mostra na conversa que a mensagem foi enviada (ícone de olhinho) |
|
||||||
|
| WA Web do remetente | "Aguardando mensagem. Abra o WhatsApp no seu celular." |
|
||||||
|
|
||||||
|
> **Nota:** A mensagem "Aguardando mensagem..." no WA Web é o comportamento correto e esperado quando o envio vem de um companion (API). É uma limitação do protocolo WhatsApp — o servidor só permite que o celular principal notifique companions com o conteúdo da view-once.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Como Enviar via API
|
||||||
|
|
||||||
|
### 2.1 Imagem
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST https://sua-api.com/v1/messages/send_image \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "x-api-key: SEU_API_KEY" \
|
||||||
|
-d '{
|
||||||
|
"instance": "nome-da-instancia",
|
||||||
|
"to": "5511999999999",
|
||||||
|
"caption": "Olha só isso!",
|
||||||
|
"imageUrl": "https://exemplo.com/foto.jpg",
|
||||||
|
"viewOnce": true
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
**Resposta de sucesso:**
|
||||||
|
```json
|
||||||
|
{ "ok": true }
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Vídeo
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST https://sua-api.com/v1/messages/send_video \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "x-api-key: SEU_API_KEY" \
|
||||||
|
-d '{
|
||||||
|
"instance": "nome-da-instancia",
|
||||||
|
"to": "5511999999999",
|
||||||
|
"caption": "Assista uma vez",
|
||||||
|
"videoUrl": "https://exemplo.com/video.mp4",
|
||||||
|
"viewOnce": true
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 Áudio
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST https://sua-api.com/v1/messages/send_audio \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "x-api-key: SEU_API_KEY" \
|
||||||
|
-d '{
|
||||||
|
"instance": "nome-da-instancia",
|
||||||
|
"to": "5511999999999",
|
||||||
|
"audioUrl": "https://exemplo.com/audio.ogg",
|
||||||
|
"ptt": false,
|
||||||
|
"viewOnce": true
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 Usando Base64 (sem URL pública)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST https://sua-api.com/v1/messages/send_image \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "x-api-key: SEU_API_KEY" \
|
||||||
|
-d '{
|
||||||
|
"instance": "nome-da-instancia",
|
||||||
|
"to": "5511999999999",
|
||||||
|
"imageBase64": "data:image/jpeg;base64,/9j/4AAQSkZJRgAB...",
|
||||||
|
"viewOnce": true
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Como Receber via Webhook
|
||||||
|
|
||||||
|
Quando um contato envia uma mensagem de visualização única para o número conectado na API, o webhook recebe o evento com `key.isViewOnce = true`.
|
||||||
|
|
||||||
|
### 3.1 Estrutura do evento recebido
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"event": "messages.upsert",
|
||||||
|
"instance": "nome-da-instancia",
|
||||||
|
"data": {
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"key": {
|
||||||
|
"remoteJid": "5511999999999@s.whatsapp.net",
|
||||||
|
"fromMe": false,
|
||||||
|
"id": "3EB0ABCDEF123456",
|
||||||
|
"isViewOnce": true
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"viewOnceMessageV2": {
|
||||||
|
"message": {
|
||||||
|
"imageMessage": {
|
||||||
|
"url": "https://mmg.whatsapp.net/...",
|
||||||
|
"mimetype": "image/jpeg",
|
||||||
|
"mediaKey": "base64...",
|
||||||
|
"fileEncSha256": "base64...",
|
||||||
|
"directPath": "/v/...",
|
||||||
|
"viewOnce": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"messageTimestamp": 1742700000,
|
||||||
|
"pushName": "João Silva"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"type": "notify"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Como identificar que é view-once
|
||||||
|
|
||||||
|
O campo principal para identificar é `key.isViewOnce = true`. Existem dois caminhos para confirmar:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function isViewOnce(msg) {
|
||||||
|
// Caminho 1: flag direta (mais simples)
|
||||||
|
if (msg.key?.isViewOnce) return true
|
||||||
|
|
||||||
|
// Caminho 2: verificar o wrapper da mensagem
|
||||||
|
const inner =
|
||||||
|
msg.message?.viewOnceMessageV2?.message ||
|
||||||
|
msg.message?.viewOnceMessage?.message ||
|
||||||
|
msg.message?.viewOnceMessageV2Extension?.message
|
||||||
|
|
||||||
|
return !!(
|
||||||
|
inner?.imageMessage?.viewOnce ||
|
||||||
|
inner?.videoMessage?.viewOnce ||
|
||||||
|
inner?.audioMessage?.viewOnce
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Como acessar a mídia
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function getViewOnceMedia(msg) {
|
||||||
|
const inner =
|
||||||
|
msg.message?.viewOnceMessageV2?.message ||
|
||||||
|
msg.message?.viewOnceMessage?.message ||
|
||||||
|
msg.message?.viewOnceMessageV2Extension?.message
|
||||||
|
|
||||||
|
if (!inner) return null
|
||||||
|
|
||||||
|
if (inner.imageMessage) return { type: 'image', media: inner.imageMessage }
|
||||||
|
if (inner.videoMessage) return { type: 'video', media: inner.videoMessage }
|
||||||
|
if (inner.audioMessage) return { type: 'audio', media: inner.audioMessage }
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Uso:
|
||||||
|
const media = getViewOnceMedia(msg)
|
||||||
|
if (media) {
|
||||||
|
console.log(`View-once ${media.type}`)
|
||||||
|
console.log('URL:', media.media.url)
|
||||||
|
console.log('DirectPath:', media.media.directPath)
|
||||||
|
console.log('MediaKey:', media.media.mediaKey) // necessário para download
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Como Exibir numa Ferramenta (Frontend/CRM)
|
||||||
|
|
||||||
|
### 4.1 Lógica de detecção e exibição
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function renderMessage(msg) {
|
||||||
|
if (!isViewOnce(msg)) {
|
||||||
|
// Renderizar mensagem normal
|
||||||
|
return renderNormalMessage(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
const media = getViewOnceMedia(msg)
|
||||||
|
if (!media) return
|
||||||
|
|
||||||
|
// Verificar se já foi aberta (controle local da ferramenta)
|
||||||
|
const alreadyOpened = localStorage.getItem(`vo_${msg.key.id}`)
|
||||||
|
|
||||||
|
if (alreadyOpened) {
|
||||||
|
// Mostrar placeholder de "já visualizado"
|
||||||
|
return renderViewOncePlaceholder(media.type, msg.key.fromMe)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.key.fromMe) {
|
||||||
|
// Mensagem enviada por mim — nunca mostrar conteúdo
|
||||||
|
return renderSentViewOnce(media.type)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mensagem recebida — mostrar botão para "abrir uma vez"
|
||||||
|
return renderViewOnceButton(media.type, msg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Componente de exibição — mensagem recebida
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function renderViewOnceButton(type, msg) {
|
||||||
|
const icons = { image: '📷', video: '🎥', audio: '🎵' }
|
||||||
|
const labels = { image: 'Foto', video: 'Vídeo', áudio: 'Áudio' }
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="view-once-bubble received">
|
||||||
|
<span class="view-once-icon">${icons[type]}</span>
|
||||||
|
<span class="view-once-label">${labels[type]} de visualização única</span>
|
||||||
|
<button onclick="openViewOnce('${msg.key.id}', '${type}')">
|
||||||
|
Abrir
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openViewOnce(msgId, type) {
|
||||||
|
// 1. Marcar como aberta ANTES de mostrar (só uma chance)
|
||||||
|
localStorage.setItem(`vo_${msgId}`, '1')
|
||||||
|
|
||||||
|
// 2. Baixar e mostrar a mídia
|
||||||
|
const mediaUrl = await downloadViewOnceMedia(msgId)
|
||||||
|
showMedia(type, mediaUrl)
|
||||||
|
|
||||||
|
// 3. Após fechar/visualizar, substituir pelo placeholder
|
||||||
|
onMediaClosed(() => {
|
||||||
|
replaceWithPlaceholder(msgId, type)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Componente de exibição — mensagem enviada
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function renderSentViewOnce(type) {
|
||||||
|
const labels = { image: 'Foto', video: 'Vídeo', audio: 'Áudio' }
|
||||||
|
return `
|
||||||
|
<div class="view-once-bubble sent">
|
||||||
|
<span class="view-once-icon">👁️</span>
|
||||||
|
<span>${labels[type]} de visualização única</span>
|
||||||
|
<span class="view-once-status">Enviada</span>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 Placeholder após visualização
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function renderViewOncePlaceholder(type, fromMe) {
|
||||||
|
const labels = { image: 'foto', video: 'vídeo', audio: 'áudio' }
|
||||||
|
const text = fromMe
|
||||||
|
? `Você enviou uma ${labels[type]} de visualização única`
|
||||||
|
: `${labels[type]} de visualização única aberta`
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="view-once-bubble placeholder">
|
||||||
|
<span class="view-once-icon">🚫</span>
|
||||||
|
<span>${text}</span>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.5 CSS sugerido
|
||||||
|
|
||||||
|
```css
|
||||||
|
.view-once-bubble {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
max-width: 280px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.view-once-bubble.received {
|
||||||
|
background: #f0f0f0;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.view-once-bubble.sent {
|
||||||
|
background: #dcf8c6;
|
||||||
|
color: #333;
|
||||||
|
align-self: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.view-once-bubble.placeholder {
|
||||||
|
background: #e8e8e8;
|
||||||
|
color: #999;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.view-once-bubble button {
|
||||||
|
background: #25d366;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 6px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Código Implementado na API
|
||||||
|
|
||||||
|
### 5.1 Geração da mensagem — `src/Utils/messages.ts`
|
||||||
|
|
||||||
|
Quando `viewOnce: true` é passado, a mídia é encapsulada no wrapper moderno `viewOnceMessageV2` (campo 55 do proto) e o flag `viewOnce=true` é setado na mídia interna:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
|
||||||
|
// Seta viewOnce=true na mensagem de mídia interna
|
||||||
|
if (m.imageMessage) m.imageMessage.viewOnce = true
|
||||||
|
else if (m.videoMessage) m.videoMessage.viewOnce = true
|
||||||
|
else if (m.audioMessage) m.audioMessage.viewOnce = true
|
||||||
|
// Usa viewOnceMessageV2 (campo 55) — formato atual do WA
|
||||||
|
m = { viewOnceMessageV2: { message: m } }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 Envio — `src/Socket/messages-send.ts`
|
||||||
|
|
||||||
|
**Detecção de view-once real** (não confunde com botões/listas que também usam o wrapper `viewOnceMessage`):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Detecta view-once real pela flag viewOnce na mídia interna.
|
||||||
|
// viewOnceMessage* wrappers são também usados por botões/listas/carrosséis
|
||||||
|
// (que carregam interactiveMessage dentro) — esses NÃO têm viewOnce=true na mídia.
|
||||||
|
const viewOnceInner =
|
||||||
|
message.viewOnceMessageV2?.message ||
|
||||||
|
message.viewOnceMessage?.message ||
|
||||||
|
message.viewOnceMessageV2Extension?.message
|
||||||
|
const isViewOnceMsg = !!(
|
||||||
|
viewOnceInner?.imageMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.videoMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.audioMessage?.viewOnce
|
||||||
|
)
|
||||||
|
|
||||||
|
// Para view-once: DSM enviado apenas para o celular principal (device=0).
|
||||||
|
// Companions (device>0) são omitidos — o servidor WA gera
|
||||||
|
// <unavailable type="view_once"/> automaticamente para eles.
|
||||||
|
const viewOnceMeRecipients = isViewOnceMsg
|
||||||
|
? meRecipients.filter(jid => !jidDecode(jid)?.device)
|
||||||
|
: meRecipients
|
||||||
|
|
||||||
|
// assertSessions apenas para quem vai realmente receber
|
||||||
|
await assertSessions([...viewOnceMeRecipients, ...otherRecipients])
|
||||||
|
|
||||||
|
const [meNodes, otherNodes] = await Promise.all([
|
||||||
|
createParticipantNodes(viewOnceMeRecipients, meMsg || message, extraAttrs),
|
||||||
|
createParticipantNodes(otherRecipients, message, extraAttrs)
|
||||||
|
])
|
||||||
|
participants.push(...meNodes)
|
||||||
|
participants.push(...otherNodes)
|
||||||
|
|
||||||
|
// phash recalculado com os participantes reais
|
||||||
|
const phashRecipients = isViewOnceMsg
|
||||||
|
? [...viewOnceMeRecipients, ...otherRecipients]
|
||||||
|
: [...meRecipients, ...otherRecipients]
|
||||||
|
if (phashRecipients.length > 0) {
|
||||||
|
extraAttrs['phash'] = generateParticipantHashV2(phashRecipients)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**`getMediaType()` — garante que vídeo e áudio view-once sejam entregues:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const getMediaType = (message: proto.IMessage) => {
|
||||||
|
// Desencapsula wrapper view-once antes de verificar o tipo de mídia.
|
||||||
|
// Sem isso, message.videoMessage e message.audioMessage são undefined
|
||||||
|
// (estão dentro do wrapper) e o atributo mediatype ficaria ausente no
|
||||||
|
// enc node — o servidor WA descarta silenciosamente vídeo/áudio view-once.
|
||||||
|
const inner =
|
||||||
|
message.viewOnceMessage?.message ||
|
||||||
|
message.viewOnceMessageV2?.message ||
|
||||||
|
message.viewOnceMessageV2Extension?.message
|
||||||
|
if (inner) {
|
||||||
|
return getMediaType(inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.imageMessage) return 'image'
|
||||||
|
else if (message.videoMessage) return 'video'
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 Recepção — `src/Utils/decode-wa-message.ts`
|
||||||
|
|
||||||
|
Quando a API recebe uma view-once como companion (linked device), o servidor envia dois stanzas:
|
||||||
|
|
||||||
|
- **Stanza 1** (`enc`): conteúdo completo com metadados da mídia
|
||||||
|
- **Stanza 2** (`unavailable type="view_once"`): sinal de sync
|
||||||
|
|
||||||
|
O stanza 1 é detectado e marcado corretamente:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Detecta view-once na stanza 1 recebida por linked device.
|
||||||
|
// O wrapper viewOnceMessage também é usado por mensagens interativas
|
||||||
|
// (interactiveMessage, listMessage) — esses NÃO têm viewOnce=true na mídia.
|
||||||
|
const viewOnceInner =
|
||||||
|
msg.viewOnceMessage?.message ||
|
||||||
|
msg.viewOnceMessageV2?.message ||
|
||||||
|
msg.viewOnceMessageV2Extension?.message
|
||||||
|
if (
|
||||||
|
viewOnceInner?.imageMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.videoMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.audioMessage?.viewOnce
|
||||||
|
) {
|
||||||
|
fullMessage.key.isViewOnce = true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Fluxo Completo
|
||||||
|
|
||||||
|
```
|
||||||
|
API envia view-once para destinatário
|
||||||
|
│
|
||||||
|
├── Protobuf gerado:
|
||||||
|
│ viewOnceMessageV2 {
|
||||||
|
│ message {
|
||||||
|
│ imageMessage { viewOnce: true, url, mediaKey, ... }
|
||||||
|
│ }
|
||||||
|
│ }
|
||||||
|
│
|
||||||
|
├── Stanza enviado ao servidor WA:
|
||||||
|
│ <message to="destinatario@s.whatsapp.net" type="media">
|
||||||
|
│ <enc type="pkmsg">...viewOnceMessageV2 cifrado...</enc> ← para o destinatário
|
||||||
|
│ <participants>
|
||||||
|
│ <to jid="meu-numero:0@lid"> ← celular principal
|
||||||
|
│ <enc type="msg">...DSM{viewOnceMessageV2}...</enc>
|
||||||
|
│ </to>
|
||||||
|
│ <!-- device>0 omitidos — servidor gera unavailable -->
|
||||||
|
│ </participants>
|
||||||
|
│ </message>
|
||||||
|
│
|
||||||
|
└── Distribuição pelo servidor:
|
||||||
|
├── Destinatário → recebe enc → abre uma vez ✅
|
||||||
|
├── Celular principal → recebe DSM → mostra "você enviou" ✅
|
||||||
|
└── WA Web → recebe <unavailable> → "Aguardando..." ✅
|
||||||
|
|
||||||
|
|
||||||
|
Destinatário envia view-once de volta para a API
|
||||||
|
│
|
||||||
|
├── Stanza recebido pela API (stanza 1 — enc com conteúdo):
|
||||||
|
│ <message from="destinatario@s.whatsapp.net" type="media">
|
||||||
|
│ <enc type="msg">...viewOnceMessageV2 cifrado...</enc>
|
||||||
|
│ </message>
|
||||||
|
│
|
||||||
|
├── decode-wa-message.ts:
|
||||||
|
│ └── Descriptografa → detecta viewOnce=true → seta key.isViewOnce=true
|
||||||
|
│
|
||||||
|
├── Stanza recebido (stanza 2 — unavailable, ignorado):
|
||||||
|
│ <message from="...">
|
||||||
|
│ <unavailable type="view_once"/>
|
||||||
|
│ </message>
|
||||||
|
│
|
||||||
|
└── Webhook emitido:
|
||||||
|
messages.upsert → msg.key.isViewOnce = true ✅
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Limitações
|
||||||
|
|
||||||
|
| Situação | Comportamento | Motivo |
|
||||||
|
|---|---|---|
|
||||||
|
| **Conta hosted (Meta Business Cloud API)** | **View-once bloqueado para todos os clientes** | **Política do servidor WA para contas hosted — sem workaround** |
|
||||||
|
| WA Web do remetente | "Aguardando mensagem. Abra no celular." | Servidor WA só aceita `<unavailable>` vindo do celular principal, não de companions |
|
||||||
|
| View-once de documento/sticker | Não suportado | Limitação do protocolo WA — só imagem, vídeo e áudio |
|
||||||
|
| `error_479` nos logs | Normal, não é erro | TcToken é atualizado após o envio de view-once |
|
||||||
|
| Companion não consegue abrir | Por design | O conteúdo não é entregue para linked devices |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Checklist de Validação
|
||||||
|
|
||||||
|
**Envio:**
|
||||||
|
- [ ] Destinatário recebe com ícone de olhinho
|
||||||
|
- [ ] Destinatário consegue abrir a mídia
|
||||||
|
- [ ] Após abrir, a mídia some
|
||||||
|
- [ ] Celular principal do remetente mostra "você enviou" com ícone de olhinho
|
||||||
|
- [ ] WA Web do remetente mostra "Aguardando mensagem..."
|
||||||
|
- [ ] Funciona para imagem, vídeo e áudio
|
||||||
|
- [ ] Logs mostram `📤 Message sent` (error_479 é normal)
|
||||||
|
|
||||||
|
**Recepção:**
|
||||||
|
- [ ] Webhook recebe `key.isViewOnce = true`
|
||||||
|
- [ ] `viewOnceMessageV2.message.imageMessage` (ou video/audio) está presente
|
||||||
|
- [ ] API não crasha ao receber view-once de outro dispositivo
|
||||||
|
- [ ] Mensagem interativa (botão/lista) enviada após view-once não é afetada
|
||||||
+1
-1
@@ -47,7 +47,7 @@
|
|||||||
"fflate": "^0.8.2",
|
"fflate": "^0.8.2",
|
||||||
"libsignal": "github:whiskeysockets/libsignal-node",
|
"libsignal": "github:whiskeysockets/libsignal-node",
|
||||||
"lru-cache": "^11.2.6",
|
"lru-cache": "^11.2.6",
|
||||||
"music-metadata": "^11.12.0",
|
"music-metadata": "^11.12.3",
|
||||||
"p-queue": "^9.0.0",
|
"p-queue": "^9.0.0",
|
||||||
"pino": "^10.3.1",
|
"pino": "^10.3.1",
|
||||||
"prom-client": "^15.1.3",
|
"prom-client": "^15.1.3",
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
{"version":[2,3000,1034258243]}
|
{"version":[2,3000,1038167900]}
|
||||||
|
|||||||
+69
-12
@@ -31,9 +31,26 @@ export const STATUS_EXPIRY_SECONDS = 24 * 60 * 60
|
|||||||
export const PLACEHOLDER_MAX_AGE_SECONDS = 7 * 24 * 60 * 60
|
export const PLACEHOLDER_MAX_AGE_SECONDS = 7 * 24 * 60 * 60
|
||||||
|
|
||||||
export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0'
|
export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0'
|
||||||
export const DICT_VERSION = 3
|
|
||||||
|
/**
|
||||||
|
* Protocol mode: 'web' (default) or 'native' (experimental)
|
||||||
|
* - web: WA\x06\x03 — standard WhatsApp Web protocol
|
||||||
|
* - native: WAM\x05 — native Android protocol (may enable view-once media on companions)
|
||||||
|
*
|
||||||
|
* Set via BAILEYS_PROTOCOL env var:
|
||||||
|
* BAILEYS_PROTOCOL=native
|
||||||
|
*/
|
||||||
|
const PROTOCOL_MODE = process.env.BAILEYS_PROTOCOL?.trim().toLowerCase() === 'native' ? 'native' : 'web'
|
||||||
|
|
||||||
|
export const DICT_VERSION = PROTOCOL_MODE === 'native' ? 5 : 3
|
||||||
export const KEY_BUNDLE_TYPE = Buffer.from([5])
|
export const KEY_BUNDLE_TYPE = Buffer.from([5])
|
||||||
export const NOISE_WA_HEADER = Buffer.from([87, 65, 6, DICT_VERSION]) // last is "DICT_VERSION"
|
|
||||||
|
// WA\x06\x03 = web protocol, WAM\x05 = native Android protocol
|
||||||
|
export const NOISE_WA_HEADER = PROTOCOL_MODE === 'native'
|
||||||
|
? Buffer.from([87, 65, 77, DICT_VERSION]) // WAM\x05
|
||||||
|
: Buffer.from([87, 65, 6, DICT_VERSION]) // WA\x06\x03
|
||||||
|
|
||||||
|
export { PROTOCOL_MODE }
|
||||||
/** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
|
/** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
|
||||||
export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g
|
export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g
|
||||||
|
|
||||||
@@ -56,10 +73,33 @@ export const PROCESSABLE_HISTORY_TYPES = [
|
|||||||
// 6 hours in milliseconds
|
// 6 hours in milliseconds
|
||||||
const SIX_HOURS_MS = 6 * 60 * 60 * 1000
|
const SIX_HOURS_MS = 6 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the default browser tuple from the BAILEYS_BROWSER env var.
|
||||||
|
* Default: Android companion (SMB_ANDROID) — matches upstream PR #2201.
|
||||||
|
* Pair code auto-detects Android and falls back to Chrome in socket.ts.
|
||||||
|
*
|
||||||
|
* unset / 'android' → Browsers.android('14')
|
||||||
|
* 'android:15' → Browsers.android('15')
|
||||||
|
* 'chrome' / 'macos' → Browsers.macOS('Chrome')
|
||||||
|
*/
|
||||||
|
const resolveDefaultBrowser = (): [string, string, string] => {
|
||||||
|
const env = process.env.BAILEYS_BROWSER?.trim().toLowerCase()
|
||||||
|
if (env === 'chrome' || env === 'macos') {
|
||||||
|
return Browsers.macOS('Chrome')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (env?.startsWith('android:')) {
|
||||||
|
const apiLevel = env.split(':')[1] || '14'
|
||||||
|
return Browsers.android(apiLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Browsers.android('14')
|
||||||
|
}
|
||||||
|
|
||||||
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
||||||
version: version as WAVersion,
|
version: version as WAVersion,
|
||||||
versionCheckIntervalMs: SIX_HOURS_MS,
|
versionCheckIntervalMs: SIX_HOURS_MS,
|
||||||
browser: Browsers.macOS('Chrome'),
|
browser: resolveDefaultBrowser(),
|
||||||
waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
|
waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
|
||||||
connectTimeoutMs: 20_000,
|
connectTimeoutMs: 20_000,
|
||||||
keepAliveIntervalMs: 15_000,
|
keepAliveIntervalMs: 15_000,
|
||||||
@@ -67,7 +107,7 @@ export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
|||||||
emitOwnEvents: true,
|
emitOwnEvents: true,
|
||||||
defaultQueryTimeoutMs: 30_000,
|
defaultQueryTimeoutMs: 30_000,
|
||||||
customUploadHosts: [],
|
customUploadHosts: [],
|
||||||
retryRequestDelayMs: 250,
|
retryRequestDelayMs: 150,
|
||||||
maxMsgRetryCount: 5,
|
maxMsgRetryCount: 5,
|
||||||
fireInitQueries: true,
|
fireInitQueries: true,
|
||||||
auth: undefined as unknown as AuthenticationState,
|
auth: undefined as unknown as AuthenticationState,
|
||||||
@@ -78,7 +118,7 @@ export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
|||||||
shouldSyncHistoryMessage: () => true,
|
shouldSyncHistoryMessage: () => true,
|
||||||
shouldIgnoreJid: () => false,
|
shouldIgnoreJid: () => false,
|
||||||
linkPreviewImageThumbnailWidth: 192,
|
linkPreviewImageThumbnailWidth: 192,
|
||||||
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
|
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 1000 },
|
||||||
generateHighQualityLinkPreview: false,
|
generateHighQualityLinkPreview: false,
|
||||||
enableAutoSessionRecreation: true,
|
enableAutoSessionRecreation: true,
|
||||||
enableRecentMessageCache: true,
|
enableRecentMessageCache: true,
|
||||||
@@ -102,8 +142,6 @@ export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
|||||||
getMessage: async () => undefined,
|
getMessage: async () => undefined,
|
||||||
cachedGroupMetadata: async () => undefined,
|
cachedGroupMetadata: async () => undefined,
|
||||||
makeSignalRepository: makeLibSignalRepository,
|
makeSignalRepository: makeLibSignalRepository,
|
||||||
// Circuit breaker configuration
|
|
||||||
enableCircuitBreaker: true,
|
|
||||||
// Listener limits (memory leak prevention)
|
// Listener limits (memory leak prevention)
|
||||||
// WebSocket: 8 core events (open, close, error, message, ping, pong, upgrade, unexpected-response)
|
// WebSocket: 8 core events (open, close, error, message, ping, pong, upgrade, unexpected-response)
|
||||||
// + 10 dynamic listeners (reconnect handlers, custom events)
|
// + 10 dynamic listeners (reconnect handlers, custom events)
|
||||||
@@ -131,7 +169,20 @@ export const MEDIA_PATH_MAP: { [T in MediaType]?: string } = {
|
|||||||
'md-msg-hist': '/mms/md-app-state',
|
'md-msg-hist': '/mms/md-app-state',
|
||||||
'biz-cover-photo': '/pps/biz-cover-photo',
|
'biz-cover-photo': '/pps/biz-cover-photo',
|
||||||
'sticker-pack': '/mms/sticker-pack',
|
'sticker-pack': '/mms/sticker-pack',
|
||||||
'thumbnail-sticker-pack': '/mms/thumbnail-sticker-pack'
|
'thumbnail-sticker-pack': '/mms/thumbnail-sticker-pack',
|
||||||
|
// View-once types — same upload path as regular media (server CDN routing TBD)
|
||||||
|
'viewonce-image': '/mms/image',
|
||||||
|
'viewonce-video': '/mms/video',
|
||||||
|
'viewonce-audio': '/mms/audio'
|
||||||
|
}
|
||||||
|
|
||||||
|
export const NEWSLETTER_MEDIA_PATH_MAP: { [T in MediaType]?: string } = {
|
||||||
|
image: '/newsletter/newsletter-image',
|
||||||
|
video: '/newsletter/newsletter-video',
|
||||||
|
document: '/newsletter/newsletter-document',
|
||||||
|
audio: '/newsletter/newsletter-audio',
|
||||||
|
sticker: '/newsletter/newsletter-image',
|
||||||
|
'thumbnail-link': '/newsletter/newsletter-image'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MEDIA_HKDF_KEY_MAPPING = {
|
export const MEDIA_HKDF_KEY_MAPPING = {
|
||||||
@@ -155,7 +206,11 @@ export const MEDIA_HKDF_KEY_MAPPING = {
|
|||||||
ptv: 'Video',
|
ptv: 'Video',
|
||||||
'biz-cover-photo': 'Image',
|
'biz-cover-photo': 'Image',
|
||||||
'sticker-pack': 'Sticker Pack',
|
'sticker-pack': 'Sticker Pack',
|
||||||
'thumbnail-sticker-pack': 'Sticker Pack Thumbnail'
|
'thumbnail-sticker-pack': 'Sticker Pack Thumbnail',
|
||||||
|
// View-once types — same HKDF keys as regular types (recipients decrypt with normal keys)
|
||||||
|
'viewonce-image': 'Image',
|
||||||
|
'viewonce-video': 'Video',
|
||||||
|
'viewonce-audio': 'Audio'
|
||||||
}
|
}
|
||||||
|
|
||||||
export type MediaType = keyof typeof MEDIA_HKDF_KEY_MAPPING
|
export type MediaType = keyof typeof MEDIA_HKDF_KEY_MAPPING
|
||||||
@@ -165,10 +220,12 @@ export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP) as MediaType[]
|
|||||||
/** 120s timeout for history sync stall detection, same as WA Web's handleChunkProgress / restartPausedTimer (g = 120) */
|
/** 120s timeout for history sync stall detection, same as WA Web's handleChunkProgress / restartPausedTimer (g = 120) */
|
||||||
export const HISTORY_SYNC_PAUSED_TIMEOUT_MS = 120_000
|
export const HISTORY_SYNC_PAUSED_TIMEOUT_MS = 120_000
|
||||||
|
|
||||||
export const MIN_PREKEY_COUNT = 5
|
// Replenishment threshold: when server count drops below this, top-up back to INITIAL_PREKEY_COUNT
|
||||||
|
export const MIN_PREKEY_COUNT = 200
|
||||||
|
|
||||||
// Moderate prekey count (upstream uses 812, reduced to balance rate limiting and availability)
|
// Initial pool size matching WA Business (CDP IDB capture: prekey-store = 812 on registration)
|
||||||
export const INITIAL_PREKEY_COUNT = 200
|
// Rounded to 800 for cleanliness; replenishment always tops up to this value
|
||||||
|
export const INITIAL_PREKEY_COUNT = 800
|
||||||
|
|
||||||
export const UPLOAD_TIMEOUT = 30000 // 30 seconds
|
export const UPLOAD_TIMEOUT = 30000 // 30 seconds
|
||||||
// Moderate upload interval to balance rate limiting and responsiveness (was 5000)
|
// Moderate upload interval to balance rate limiting and responsiveness (was 5000)
|
||||||
|
|||||||
+84
-26
@@ -6,7 +6,6 @@ import type { LIDMapping, SignalAuthState, SignalKeyStoreWithTransaction } from
|
|||||||
import type { BaileysEventEmitter } from '../Types/Events'
|
import type { BaileysEventEmitter } from '../Types/Events'
|
||||||
import type { SignalRepositoryWithLIDStore } from '../Types/Signal'
|
import type { SignalRepositoryWithLIDStore } from '../Types/Signal'
|
||||||
import { generateSignalPubKey } from '../Utils'
|
import { generateSignalPubKey } from '../Utils'
|
||||||
import { CircuitBreaker } from '../Utils/circuit-breaker.js'
|
|
||||||
import type { ILogger } from '../Utils/logger'
|
import type { ILogger } from '../Utils/logger'
|
||||||
import { metrics } from '../Utils/prometheus-metrics.js'
|
import { metrics } from '../Utils/prometheus-metrics.js'
|
||||||
import { isAnyLidUser, isAnyPnUser, jidDecode, transferDevice, WAJIDDomains } from '../WABinary'
|
import { isAnyLidUser, isAnyPnUser, jidDecode, transferDevice, WAJIDDomains } from '../WABinary'
|
||||||
@@ -67,8 +66,6 @@ export interface IdentitySaveResult {
|
|||||||
export interface LibSignalRepositoryOptions {
|
export interface LibSignalRepositoryOptions {
|
||||||
/** Event emitter for broadcasting identity changes */
|
/** Event emitter for broadcasting identity changes */
|
||||||
ev?: BaileysEventEmitter
|
ev?: BaileysEventEmitter
|
||||||
/** Circuit breaker for prekey operations (optional) */
|
|
||||||
preKeyCircuitBreaker?: CircuitBreaker
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================
|
// ============================================
|
||||||
@@ -256,7 +253,7 @@ export function makeLibSignalRepository(
|
|||||||
pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>,
|
pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>,
|
||||||
options?: LibSignalRepositoryOptions
|
options?: LibSignalRepositoryOptions
|
||||||
): SignalRepositoryWithLIDStore {
|
): SignalRepositoryWithLIDStore {
|
||||||
const { ev, preKeyCircuitBreaker } = options || {}
|
const { ev } = options || {}
|
||||||
const lidMapping = new LIDMappingStore(auth.keys as SignalKeyStoreWithTransaction, logger, pnToLIDFunc)
|
const lidMapping = new LIDMappingStore(auth.keys as SignalKeyStoreWithTransaction, logger, pnToLIDFunc)
|
||||||
|
|
||||||
// Identity key cache to avoid repeated storage reads
|
// Identity key cache to avoid repeated storage reads
|
||||||
@@ -277,7 +274,7 @@ export function makeLibSignalRepository(
|
|||||||
cacheMetricsInterval.unref()
|
cacheMetricsInterval.unref()
|
||||||
}
|
}
|
||||||
|
|
||||||
const storage = signalStorage(auth, lidMapping, identityKeyCache, ev, preKeyCircuitBreaker, logger)
|
const storage = signalStorage(auth, lidMapping, identityKeyCache, ev, logger)
|
||||||
|
|
||||||
const parsedKeys = auth.keys as SignalKeyStoreWithTransaction
|
const parsedKeys = auth.keys as SignalKeyStoreWithTransaction
|
||||||
const migratedSessionCache = new LRUCache<string, true>({
|
const migratedSessionCache = new LRUCache<string, true>({
|
||||||
@@ -302,6 +299,25 @@ export function makeLibSignalRepository(
|
|||||||
// Promise instead of each spawning their own DB transactions.
|
// Promise instead of each spawning their own DB transactions.
|
||||||
const migrationInFlight = new Map<string, Promise<{ migrated: number; skipped: number; total: number }>>()
|
const migrationInFlight = new Map<string, Promise<{ migrated: number; skipped: number; total: number }>>()
|
||||||
|
|
||||||
|
// Resolve PN JID to its canonical LID JID for transaction locking.
|
||||||
|
// This prevents PN/LID race conditions where concurrent operations for the
|
||||||
|
// same logical contact acquire different mutex locks because one uses PN
|
||||||
|
// and the other uses LID. (Aligned with WABA behavior — all operations use LID internally.)
|
||||||
|
const resolveCanonicalJid = async(jid: string): Promise<string> => {
|
||||||
|
if (isAnyLidUser(jid)) {
|
||||||
|
return jid
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAnyPnUser(jid)) {
|
||||||
|
const lid = await lidMapping.getLIDForPN(jid)
|
||||||
|
if (lid) {
|
||||||
|
return lid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return jid
|
||||||
|
}
|
||||||
|
|
||||||
const repository: SignalRepositoryWithLIDStore = {
|
const repository: SignalRepositoryWithLIDStore = {
|
||||||
decryptGroupMessage({ group, authorJid, msg }) {
|
decryptGroupMessage({ group, authorJid, msg }) {
|
||||||
const senderName = jidToSignalSenderKeyName(group, authorJid)
|
const senderName = jidToSignalSenderKeyName(group, authorJid)
|
||||||
@@ -366,13 +382,9 @@ export function makeLibSignalRepository(
|
|||||||
'Identity key changed - contact may have reinstalled WhatsApp, session will be re-established'
|
'Identity key changed - contact may have reinstalled WhatsApp, session will be re-established'
|
||||||
)
|
)
|
||||||
|
|
||||||
// Reset prekey circuit breaker since we identified the cause
|
// (No circuit breaker to reset — bounded-retry is stateless,
|
||||||
// Reset regardless of state (could be open, half-open, or closed with accumulated failures)
|
// each retry is independent so identity-change recovery
|
||||||
// eslint-disable-next-line max-depth
|
// happens automatically on the next operation.)
|
||||||
if (preKeyCircuitBreaker) {
|
|
||||||
preKeyCircuitBreaker.reset()
|
|
||||||
logger.debug({ jid }, 'Reset prekey circuit breaker after identity key change detection')
|
|
||||||
}
|
|
||||||
} else if (saveResult.isNew) {
|
} else if (saveResult.isNew) {
|
||||||
logger.debug(
|
logger.debug(
|
||||||
{ jid, addr: addrStr, fingerprint: saveResult.currentFingerprint },
|
{ jid, addr: addrStr, fingerprint: saveResult.currentFingerprint },
|
||||||
@@ -396,23 +408,24 @@ export function makeLibSignalRepository(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// If it's not a sync message, we need to ensure atomicity
|
// Use canonical JID (PN→LID resolved) as transaction key to prevent
|
||||||
// For regular messages, we use a transaction to ensure atomicity
|
// PN/LID race conditions on the same logical session.
|
||||||
|
const canonicalJid = await resolveCanonicalJid(jid)
|
||||||
return parsedKeys.transaction(async () => {
|
return parsedKeys.transaction(async () => {
|
||||||
return await doDecrypt()
|
return await doDecrypt()
|
||||||
}, jid)
|
}, canonicalJid)
|
||||||
},
|
},
|
||||||
|
|
||||||
async encryptMessage({ jid, data }) {
|
async encryptMessage({ jid, data }) {
|
||||||
const addr = jidToSignalProtocolAddress(jid)
|
const addr = jidToSignalProtocolAddress(jid)
|
||||||
const cipher = new libsignal.SessionCipher(storage, addr)
|
const cipher = new libsignal.SessionCipher(storage, addr)
|
||||||
|
|
||||||
// Use transaction to ensure atomicity
|
const canonicalJid = await resolveCanonicalJid(jid)
|
||||||
return parsedKeys.transaction(async () => {
|
return parsedKeys.transaction(async () => {
|
||||||
const { type: sigType, body } = await cipher.encrypt(data)
|
const { type: sigType, body } = await cipher.encrypt(data)
|
||||||
const type = sigType === 3 ? 'pkmsg' : 'msg'
|
const type = sigType === 3 ? 'pkmsg' : 'msg'
|
||||||
return { type, ciphertext: Buffer.from(body, 'binary') }
|
return { type, ciphertext: Buffer.from(body, 'binary') }
|
||||||
}, jid)
|
}, canonicalJid)
|
||||||
},
|
},
|
||||||
|
|
||||||
async encryptGroupMessage({ group, meId, data }) {
|
async encryptGroupMessage({ group, meId, data }) {
|
||||||
@@ -654,9 +667,10 @@ export function makeLibSignalRepository(
|
|||||||
// Session exists (guaranteed from device discovery)
|
// Session exists (guaranteed from device discovery)
|
||||||
const fromSession = libsignal.SessionRecord.deserialize(pnSession)
|
const fromSession = libsignal.SessionRecord.deserialize(pnSession)
|
||||||
if (fromSession.haveOpenSession()) {
|
if (fromSession.haveOpenSession()) {
|
||||||
// Queue for bulk update: copy to LID, delete from PN
|
// Queue for bulk update: copy to LID, retain PN session.
|
||||||
|
// WABA retains both PN and LID sessions during migration to avoid
|
||||||
|
// No Session errors if messages arrive via PN before migration completes.
|
||||||
sessionUpdates[lidAddrStr] = fromSession.serialize()
|
sessionUpdates[lidAddrStr] = fromSession.serialize()
|
||||||
sessionUpdates[pnAddrStr] = null
|
|
||||||
|
|
||||||
migratedCount++
|
migratedCount++
|
||||||
}
|
}
|
||||||
@@ -748,7 +762,6 @@ function signalStorage(
|
|||||||
lidMapping: LIDMappingStore,
|
lidMapping: LIDMappingStore,
|
||||||
identityKeyCache: LRUCache<string, Uint8Array>,
|
identityKeyCache: LRUCache<string, Uint8Array>,
|
||||||
ev?: BaileysEventEmitter,
|
ev?: BaileysEventEmitter,
|
||||||
preKeyCircuitBreaker?: CircuitBreaker,
|
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
): ExtendedSignalStorage {
|
): ExtendedSignalStorage {
|
||||||
// Shared function to resolve PN signal address to LID if mapping exists
|
// Shared function to resolve PN signal address to LID if mapping exists
|
||||||
@@ -776,6 +789,13 @@ function signalStorage(
|
|||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delayed PreKey deletion: grace period to handle race conditions
|
||||||
|
// where two pkmsg with the same preKeyId arrive nearly simultaneously.
|
||||||
|
// WABA deletes immediately (33ms), but we add a 5-min grace period
|
||||||
|
// because we can't handle "Invalid PreKey ID" errors at the native level.
|
||||||
|
const PREKEY_GRACE_PERIOD_MS = 5 * 60 * 1000 // 5 minutes
|
||||||
|
const pendingPreKeyDeletions = new Map<string, ReturnType<typeof setTimeout>>()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
loadSession: async (id: string) => {
|
loadSession: async (id: string) => {
|
||||||
try {
|
try {
|
||||||
@@ -808,7 +828,26 @@ function signalStorage(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
removePreKey: (id: number) => keys.set({ 'pre-key': { [id]: null } }),
|
removePreKey: (id: number) => {
|
||||||
|
const keyId = id.toString()
|
||||||
|
// Clear any existing timer for this key
|
||||||
|
const existing = pendingPreKeyDeletions.get(keyId)
|
||||||
|
if (existing) {
|
||||||
|
clearTimeout(existing)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule deletion after grace period
|
||||||
|
const timer = setTimeout(async () => {
|
||||||
|
pendingPreKeyDeletions.delete(keyId)
|
||||||
|
try {
|
||||||
|
await keys.set({ 'pre-key': { [id]: null } })
|
||||||
|
} catch {
|
||||||
|
// Keystore may be destroyed if connection closed — safe to ignore
|
||||||
|
}
|
||||||
|
}, PREKEY_GRACE_PERIOD_MS)
|
||||||
|
|
||||||
|
pendingPreKeyDeletions.set(keyId, timer)
|
||||||
|
},
|
||||||
loadSignedPreKey: () => {
|
loadSignedPreKey: () => {
|
||||||
const key = creds.signedPreKey
|
const key = creds.signedPreKey
|
||||||
return {
|
return {
|
||||||
@@ -898,14 +937,24 @@ function signalStorage(
|
|||||||
// IDENTITY KEY CHANGED - contact reinstalled WhatsApp or switched devices
|
// IDENTITY KEY CHANGED - contact reinstalled WhatsApp or switched devices
|
||||||
const previousFingerprint = generateKeyFingerprint(existingKey)
|
const previousFingerprint = generateKeyFingerprint(existingKey)
|
||||||
|
|
||||||
// Delete old session and save new identity key atomically
|
// Delete old session and save new identity key atomically.
|
||||||
|
// Store identity in BOTH LID and PN addresses (WABA stores in both
|
||||||
|
// recipient_account_type=0 and type=1 with CONFLICT_REPLACE).
|
||||||
|
const identityUpdates: Record<string, Uint8Array> = { [wireJid]: identityKey }
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityUpdates[id] = identityKey
|
||||||
|
}
|
||||||
|
|
||||||
await keys.set({
|
await keys.set({
|
||||||
session: { [wireJid]: null },
|
session: { [wireJid]: null },
|
||||||
'identity-key': { [wireJid]: identityKey }
|
'identity-key': identityUpdates
|
||||||
})
|
})
|
||||||
|
|
||||||
// Update cache
|
// Update cache for both addresses
|
||||||
identityKeyCache.set(wireJid, identityKey)
|
identityKeyCache.set(wireJid, identityKey)
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityKeyCache.set(id, identityKey)
|
||||||
|
}
|
||||||
|
|
||||||
// Record metrics
|
// Record metrics
|
||||||
metrics.signalIdentityChanges?.inc({ type: 'changed' })
|
metrics.signalIdentityChanges?.inc({ type: 'changed' })
|
||||||
@@ -941,10 +990,19 @@ function signalStorage(
|
|||||||
|
|
||||||
if (!existingKey) {
|
if (!existingKey) {
|
||||||
// NEW CONTACT - Trust On First Use (TOFU)
|
// NEW CONTACT - Trust On First Use (TOFU)
|
||||||
await keys.set({ 'identity-key': { [wireJid]: identityKey } })
|
// Store in both LID and PN addresses (aligned with WABA dual identity storage)
|
||||||
|
const identityUpdates: Record<string, Uint8Array> = { [wireJid]: identityKey }
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityUpdates[id] = identityKey
|
||||||
|
}
|
||||||
|
|
||||||
// Update cache
|
await keys.set({ 'identity-key': identityUpdates })
|
||||||
|
|
||||||
|
// Update cache for both addresses
|
||||||
identityKeyCache.set(wireJid, identityKey)
|
identityKeyCache.set(wireJid, identityKey)
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityKeyCache.set(id, identityKey)
|
||||||
|
}
|
||||||
|
|
||||||
// Record metrics
|
// Record metrics
|
||||||
metrics.signalIdentityChanges?.inc({ type: 'new' })
|
metrics.signalIdentityChanges?.inc({ type: 'new' })
|
||||||
|
|||||||
+228
-36
@@ -50,10 +50,11 @@ import {
|
|||||||
isMissingKeyError,
|
isMissingKeyError,
|
||||||
MAX_SYNC_ATTEMPTS,
|
MAX_SYNC_ATTEMPTS,
|
||||||
newLTHashState,
|
newLTHashState,
|
||||||
processSyncAction
|
processSyncAction,
|
||||||
|
resolveLidToPn
|
||||||
} from '../Utils'
|
} from '../Utils'
|
||||||
import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex'
|
import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex'
|
||||||
import processMessage from '../Utils/process-message'
|
import processMessage, { getChatId } from '../Utils/process-message'
|
||||||
import { buildTcTokenFromJid } from '../Utils/tc-token-utils'
|
import { buildTcTokenFromJid } from '../Utils/tc-token-utils'
|
||||||
import {
|
import {
|
||||||
type BinaryNode,
|
type BinaryNode,
|
||||||
@@ -97,19 +98,49 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
let privacySettings: { [_: string]: string } | undefined
|
let privacySettings: { [_: string]: string } | undefined
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server-assigned AB props that gate tctoken-related protocol behavior.
|
||||||
|
* Defaults match WA Web (safe — avoids spurious error 463 if the prop never
|
||||||
|
* arrives). Populated from `fetchProps()` on connection.
|
||||||
|
*
|
||||||
|
* - `privacyTokenOn1to1` (AB prop 10518 / `privacy_token_sending_on_all_1_on_1_messages`):
|
||||||
|
* include tctoken in 1:1 messages.
|
||||||
|
* - `profilePicPrivacyToken` (AB prop 9666 / `profile_scraping_privacy_token_in_photo_iq`):
|
||||||
|
* include tctoken in profile picture IQs.
|
||||||
|
* - `lidTrustedTokenIssueToLid` (AB prop 14303 / `lid_trusted_token_issue_to_lid`):
|
||||||
|
* issue privacy tokens to the contact's LID instead of the PN.
|
||||||
|
*/
|
||||||
|
const serverProps = {
|
||||||
|
privacyTokenOn1to1: true,
|
||||||
|
profilePicPrivacyToken: true,
|
||||||
|
lidTrustedTokenIssueToLid: false
|
||||||
|
}
|
||||||
|
|
||||||
let syncState: SyncState = SyncState.Connecting
|
let syncState: SyncState = SyncState.Connecting
|
||||||
|
|
||||||
/** this mutex ensures that messages from the same chat are processed in order, while allowing parallel processing of messages from different chats */
|
/** this mutex ensures that messages from the same chat are processed in order, while allowing parallel processing of messages from different chats */
|
||||||
const messageMutex = makeKeyedMutex()
|
const messageMutex = makeKeyedMutex()
|
||||||
|
|
||||||
/** this mutex ensures that receipts are processed in order */
|
/** this mutex ensures that receipts from the same chat are processed in order, while allowing parallel processing across chats */
|
||||||
const receiptMutex = makeMutex()
|
const receiptMutex = makeKeyedMutex()
|
||||||
|
|
||||||
/** this mutex ensures that app state patches are processed in order */
|
/** this mutex ensures that app state patches are processed in order */
|
||||||
const appStatePatchMutex = makeMutex()
|
const appStatePatchMutex = makeMutex()
|
||||||
|
|
||||||
/** this mutex ensures that notifications are processed in order */
|
/** this mutex ensures that notifications from the same chat are processed in order, while allowing parallel processing across chats */
|
||||||
const notificationMutex = makeMutex()
|
const notificationMutex = makeKeyedMutex()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-chat mutex dedicated to post-upsert work (history app-state sync +
|
||||||
|
* processMessage side effects). Kept separate from `messageMutex` because
|
||||||
|
* the inbound caller already holds `messageMutex(chatId)` while running
|
||||||
|
* decrypt + upsertMessage; sharing the same mutex would let a concurrently-
|
||||||
|
* arrived message N+1 enqueue *between* msg N's outer callback and msg N's
|
||||||
|
* post-upsert task, so msg N+1's processMessage could run before msg N's
|
||||||
|
* (breaking per-chat ordering of side effects). With a separate mutex,
|
||||||
|
* post-upsert tasks enqueue strictly in upsertMessage call order.
|
||||||
|
*/
|
||||||
|
const postUpsertMutex = makeKeyedMutex()
|
||||||
|
|
||||||
// Timeout for AwaitingInitialSync state
|
// Timeout for AwaitingInitialSync state
|
||||||
let awaitingSyncTimeout: NodeJS.Timeout | undefined
|
let awaitingSyncTimeout: NodeJS.Timeout | undefined
|
||||||
@@ -757,9 +788,16 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}, authState?.creds?.me?.id || 'resync-app-state')
|
}, authState?.creds?.me?.id || 'resync-app-state')
|
||||||
|
|
||||||
const { onMutation } = newAppStateChunkHandler(isInitialSync)
|
const { onMutation } = newAppStateChunkHandler(isInitialSync)
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
for (const key in globalMutationMap) {
|
for (const key in globalMutationMap) {
|
||||||
const mutation = globalMutationMap[key]
|
const mutation = globalMutationMap[key]
|
||||||
if (!mutation) continue
|
if (!mutation) continue
|
||||||
|
// Normalize LID→PN in sync action index[1] (chat/contact ID)
|
||||||
|
if (mutation.index[1] && isAnyLidUser(mutation.index[1])) {
|
||||||
|
const resolved = await resolveLidToPn(mutation.index[1], lidMapping, logger)
|
||||||
|
if (resolved) mutation.index[1] = resolved
|
||||||
|
}
|
||||||
|
|
||||||
onMutation(mutation)
|
onMutation(mutation)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -783,7 +821,10 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)))
|
me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)))
|
||||||
let content: BinaryNode[] | undefined = baseContent
|
let content: BinaryNode[] | undefined = baseContent
|
||||||
|
|
||||||
if (isUserJid && !isSelf) {
|
// Gate inclusion on AB prop 9666 (profile_scraping_privacy_token_in_photo_iq).
|
||||||
|
// WA Web defaults to true; if the server flips it off, we mirror that to
|
||||||
|
// avoid divergence with the spec-compliant client.
|
||||||
|
if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
|
||||||
content = await buildTcTokenFromJid({
|
content = await buildTcTokenFromJid({
|
||||||
authState,
|
authState,
|
||||||
jid: normalizedJid,
|
jid: normalizedJid,
|
||||||
@@ -912,16 +953,16 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const handlePresenceUpdate = ({ tag, attrs, content }: BinaryNode) => {
|
const handlePresenceUpdate = async ({ tag, attrs, content }: BinaryNode) => {
|
||||||
let presence: PresenceData | undefined
|
let presence: PresenceData | undefined
|
||||||
const jid = attrs.from
|
const rawJid = attrs.from
|
||||||
const participant = attrs.participant || attrs.from
|
const rawParticipant = attrs.participant || attrs.from
|
||||||
if (!jid) {
|
if (!rawJid) {
|
||||||
logger.warn({ attrs }, 'handlePresenceUpdate: jid (attrs.from) is missing, skipping')
|
logger.warn({ attrs }, 'handlePresenceUpdate: jid (attrs.from) is missing, skipping')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
|
if (shouldIgnoreJid(rawJid) && rawJid !== S_WHATSAPP_NET) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -933,7 +974,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
} else if (Array.isArray(content)) {
|
} else if (Array.isArray(content)) {
|
||||||
const [firstChild] = content
|
const [firstChild] = content
|
||||||
if (!firstChild) {
|
if (!firstChild) {
|
||||||
logger.warn({ jid }, 'handlePresenceUpdate: firstChild content is empty, skipping')
|
logger.warn({ jid: rawJid }, 'handlePresenceUpdate: firstChild content is empty, skipping')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -952,12 +993,19 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (presence) {
|
if (presence) {
|
||||||
if (!participant) {
|
if (!rawParticipant) {
|
||||||
logger.warn({ jid }, 'handlePresenceUpdate: participant is missing, skipping')
|
logger.warn({ jid: rawJid }, 'handlePresenceUpdate: participant is missing, skipping')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
|
// Resolve LID→PN so consumers always see phone-number JIDs
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
|
const [jid, participant] = await Promise.all([
|
||||||
|
resolveLidToPn(rawJid, lidMapping, logger),
|
||||||
|
resolveLidToPn(rawParticipant, lidMapping, logger)
|
||||||
|
])
|
||||||
|
|
||||||
|
ev.emit('presence.update', { id: jid!, presences: { [participant!]: presence } })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1031,28 +1079,35 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
undefined,
|
undefined,
|
||||||
logger
|
logger
|
||||||
)
|
)
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
for (const key in mutationMap) {
|
for (const key in mutationMap) {
|
||||||
onMutation(mutationMap[key]!)
|
const mutation = mutationMap[key]!
|
||||||
|
// Normalize LID→PN in sync action index[1] (chat/contact ID)
|
||||||
|
if (mutation.index[1] && isAnyLidUser(mutation.index[1])) {
|
||||||
|
const resolved = await resolveLidToPn(mutation.index[1], lidMapping, logger)
|
||||||
|
if (resolved) mutation.index[1] = resolved
|
||||||
|
}
|
||||||
|
|
||||||
|
onMutation(mutation)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** sending non-abt props may fix QR scan fail if server expects */
|
/** fetch AB props */
|
||||||
const fetchProps = async () => {
|
const fetchProps = async () => {
|
||||||
//TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
|
|
||||||
const resultNode = await query({
|
const resultNode = await query({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
xmlns: 'w',
|
xmlns: 'abt',
|
||||||
type: 'get'
|
type: 'get'
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'props',
|
tag: 'props',
|
||||||
attrs: {
|
attrs: {
|
||||||
protocol: '2',
|
protocol: '1',
|
||||||
hash: authState?.creds?.lastPropHash || ''
|
...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -1071,7 +1126,25 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
props = reduceBinaryNodeToDictionary(propsNode, 'prop')
|
props = reduceBinaryNodeToDictionary(propsNode, 'prop')
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug('fetched props')
|
// Extract protocol-relevant AB props (defaults match WA Web; see serverProps doc).
|
||||||
|
// We accept both numeric IDs and human-readable names so the parser is resilient
|
||||||
|
// to upstream renaming and to future-versioned WA Web servers.
|
||||||
|
const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages']
|
||||||
|
if (privacyTokenProp !== undefined) {
|
||||||
|
serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1'
|
||||||
|
}
|
||||||
|
|
||||||
|
const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq']
|
||||||
|
if (profilePicProp !== undefined) {
|
||||||
|
serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1'
|
||||||
|
}
|
||||||
|
|
||||||
|
const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid']
|
||||||
|
if (lidIssueProp !== undefined) {
|
||||||
|
serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1'
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug({ serverProps }, 'fetched props')
|
||||||
|
|
||||||
return props
|
return props
|
||||||
}
|
}
|
||||||
@@ -1338,7 +1411,19 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
blockedCollections.clear()
|
blockedCollections.clear()
|
||||||
|
|
||||||
logger.info('Doing app state sync')
|
logger.info('Doing app state sync')
|
||||||
|
try {
|
||||||
await resyncAppState(ALL_WA_PATCH_NAMES, true)
|
await resyncAppState(ALL_WA_PATCH_NAMES, true)
|
||||||
|
} catch (err) {
|
||||||
|
// Failure recovery: without this, syncState would stay at Syncing
|
||||||
|
// and ev.flush() would never run, leaving the event buffer pinned
|
||||||
|
// until the buffer's own safety timeout expires. Force the state
|
||||||
|
// machine forward so live inbound events can flow even if the
|
||||||
|
// app-state resync failed (collections are already cleared, so
|
||||||
|
// blocked patches will be retried on the next creds.update tick).
|
||||||
|
syncState = SyncState.Online
|
||||||
|
ev.flush()
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
|
||||||
// Sync is complete, go online and flush everything
|
// Sync is complete, go online and flush everything
|
||||||
syncState = SyncState.Online
|
syncState = SyncState.Online
|
||||||
@@ -1350,12 +1435,25 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await Promise.all([
|
// Post-upsert work: history app-state sync + processMessage side effects.
|
||||||
(async () => {
|
// Awaiting here keeps `messages.upsert` pinned in the event buffer
|
||||||
if (shouldProcessHistoryMsg) {
|
// (createBufferedFunction only schedules flush after work() resolves), so
|
||||||
await doAppStateSync()
|
// the hot path detaches this work to release the emit on the next debounce
|
||||||
}
|
// tick.
|
||||||
})(),
|
//
|
||||||
|
// Use Promise.allSettled so the combined promise only settles after BOTH
|
||||||
|
// tasks finish. With a plain Promise.all, an early rejection from one task
|
||||||
|
// would release the keyed mutex while the other task is still mutating
|
||||||
|
// chat state — letting the next message of the same chat overtake it and
|
||||||
|
// break per-chat ordering.
|
||||||
|
//
|
||||||
|
// Returns the per-task settle status so the keyShare branch can know
|
||||||
|
// whether processMessage actually persisted the new app-state-sync key
|
||||||
|
// before triggering doAppStateSync (otherwise the sync would hit
|
||||||
|
// isMissingKeyError and park collections in blockedCollections).
|
||||||
|
const postUpsertTasks = async (): Promise<{ processMessageOk: boolean }> => {
|
||||||
|
const [historyResult, processResult] = await Promise.allSettled([
|
||||||
|
shouldProcessHistoryMsg ? doAppStateSync() : Promise.resolve(),
|
||||||
processMessage(msg, {
|
processMessage(msg, {
|
||||||
signalRepository,
|
signalRepository,
|
||||||
shouldProcessHistoryMsg,
|
shouldProcessHistoryMsg,
|
||||||
@@ -1369,15 +1467,108 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
])
|
])
|
||||||
|
|
||||||
// If the app state key arrives and we are waiting to sync, trigger the sync now.
|
if (historyResult.status === 'rejected') {
|
||||||
if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
|
logger?.warn(
|
||||||
logger.info('App state sync key arrived, triggering app state sync')
|
{ err: historyResult.reason, messageId: msg.key?.id, remoteJid: msg.key?.remoteJid },
|
||||||
|
'history doAppStateSync failed'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (processResult.status === 'rejected') {
|
||||||
|
logger?.warn(
|
||||||
|
{ err: processResult.reason, messageId: msg.key?.id, remoteJid: msg.key?.remoteJid },
|
||||||
|
'processMessage failed'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { processMessageOk: processResult.status === 'fulfilled' }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use getChatId + jidNormalizedUser so the mutex key matches the chat-id
|
||||||
|
// scheme processMessage uses for chat updates (broadcasts target the
|
||||||
|
// participant). When getChatId/jidNormalizedUser yields nothing usable
|
||||||
|
// (missing or malformed JID), prefer a message-derived fallback over a
|
||||||
|
// single global 'unknown' bucket — that bucket would head-of-line block
|
||||||
|
// every malformed message behind a shared queue. msg.key.id is unique
|
||||||
|
// per message so unrelated malformed inputs no longer serialize together;
|
||||||
|
// for valid messages we still hit the normalized chat-id path, so the
|
||||||
|
// per-chat ordering guarantee is unchanged where it matters.
|
||||||
|
const rawChatId = getChatId(msg.key)
|
||||||
|
const normalizedChatId = rawChatId ? jidNormalizedUser(rawChatId) : ''
|
||||||
|
const postUpsertChatId = normalizedChatId || msg.key?.id || 'unknown'
|
||||||
|
|
||||||
|
// Wrap in `postUpsertMutex(chatId)` (a SEPARATE keyed mutex from the outer
|
||||||
|
// `messageMutex` held by the inbound caller) so per-chat ordering of
|
||||||
|
// processMessage side effects (chat.unreadCount, LID/PN mapping,
|
||||||
|
// messages.update, history downloads) is preserved across messages of the
|
||||||
|
// same chat.
|
||||||
|
//
|
||||||
|
// Why a separate mutex: if we re-used messageMutex, a concurrently-arrived
|
||||||
|
// message N+1 could enqueue on the outer mutex BEFORE msg N's post-upsert
|
||||||
|
// task gets enqueued (because N's outer callback yields on `await decrypt()`
|
||||||
|
// before reaching the inner enqueue site). The queue would then be
|
||||||
|
// [OuterN+1, InnerN, ...], so InnerN+1 would beat InnerN to processMessage.
|
||||||
|
// With its own mutex, post-upsert tasks enqueue strictly in upsertMessage
|
||||||
|
// call order (which IS message arrival order because the outer
|
||||||
|
// messageMutex serializes the upserts per-chat).
|
||||||
|
const postUpsertWork = postUpsertMutex.mutex(postUpsertChatId, postUpsertTasks)
|
||||||
|
|
||||||
|
const isKeyShareDuringSync =
|
||||||
|
!!msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing
|
||||||
|
|
||||||
|
if (isKeyShareDuringSync) {
|
||||||
|
// appStateSyncKeyShare path: processMessage persists the new app-state-sync
|
||||||
|
// key in its APP_STATE_SYNC_KEY_SHARE handler (via keyStore.transaction).
|
||||||
|
// The follow-up doAppStateSync() needs that key to decrypt patches, so
|
||||||
|
// we MUST wait for processMessage to actually succeed before kicking off
|
||||||
|
// the sync — otherwise it would hit isMissingKeyError and park
|
||||||
|
// collections in blockedCollections, regressing the very issue this
|
||||||
|
// branch was added to fix.
|
||||||
|
//
|
||||||
|
// No deadlock with the inbound caller's messageMutex because
|
||||||
|
// postUpsertMutex is a different mutex instance.
|
||||||
|
logger.info('App state sync key arrived, awaiting persistence before triggering sync')
|
||||||
|
const { processMessageOk } = await postUpsertWork
|
||||||
|
|
||||||
|
if (!processMessageOk) {
|
||||||
|
logger?.warn(
|
||||||
|
{ messageId: msg.key?.id, remoteJid: msg.key?.remoteJid },
|
||||||
|
'processMessage failed during key-share — skipping doAppStateSync to avoid isMissingKeyError'
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
await doAppStateSync()
|
await doAppStateSync()
|
||||||
|
} catch (err) {
|
||||||
|
logger?.warn(
|
||||||
|
{ err, messageId: msg.key?.id, remoteJid: msg.key?.remoteJid },
|
||||||
|
'doAppStateSync failed after key-share persistence'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// `postUpsertWork` is not expected to reject — `Promise.allSettled`
|
||||||
|
// inside `postUpsertTasks` never rejects, and per-task failures are
|
||||||
|
// already logged inline. The defensive catch routes any truly
|
||||||
|
// unexpected rejection (e.g. `postUpsertMutex` internal corruption,
|
||||||
|
// future synchronous throws inside processMessage) through
|
||||||
|
// `onUnexpectedError` instead of letting it surface as an
|
||||||
|
// UnhandledPromiseRejection — which on Node ≥15 can terminate the
|
||||||
|
// long-running socket process.
|
||||||
|
postUpsertWork.catch(err =>
|
||||||
|
onUnexpectedError(
|
||||||
|
err,
|
||||||
|
`processing post-upsert work for message ${msg.key?.id || 'unknown'} on ${msg.key?.remoteJid || 'unknown chat'}`
|
||||||
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
ws.on('CB:presence', handlePresenceUpdate)
|
ws.on('CB:presence', (node: BinaryNode) => {
|
||||||
ws.on('CB:chatstate', handlePresenceUpdate)
|
handlePresenceUpdate(node).catch(err => onUnexpectedError(err, 'handling presence update'))
|
||||||
|
})
|
||||||
|
ws.on('CB:chatstate', (node: BinaryNode) => {
|
||||||
|
handlePresenceUpdate(node).catch(err => onUnexpectedError(err, 'handling chatstate update'))
|
||||||
|
})
|
||||||
|
|
||||||
ws.on('CB:ib,,dirty', async (node: BinaryNode) => {
|
ws.on('CB:ib,,dirty', async (node: BinaryNode) => {
|
||||||
const { attrs } = getBinaryNodeChild(node, 'dirty')!
|
const { attrs } = getBinaryNodeChild(node, 'dirty')!
|
||||||
@@ -1495,7 +1686,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
awaitingSyncTimeout = setTimeout(() => {
|
awaitingSyncTimeout = setTimeout(() => {
|
||||||
if (syncState === SyncState.AwaitingInitialSync) {
|
if (syncState === SyncState.AwaitingInitialSync) {
|
||||||
logger.warn('Timeout in AwaitingInitialSync (4s), forcing state to Online and flushing buffer')
|
logger.warn('Timeout in AwaitingInitialSync (2s), forcing state to Online and flushing buffer')
|
||||||
syncState = SyncState.Online
|
syncState = SyncState.Online
|
||||||
ev.flush()
|
ev.flush()
|
||||||
|
|
||||||
@@ -1505,7 +1696,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
|
const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
|
||||||
ev.emit('creds.update', { accountSyncCounter })
|
ev.emit('creds.update', { accountSyncCounter })
|
||||||
}
|
}
|
||||||
}, 4_000)
|
}, 2_000)
|
||||||
})
|
})
|
||||||
|
|
||||||
// When an app state sync key arrives (myAppStateKeyId is set) and there are
|
// When an app state sync key arrives (myAppStateKeyId is set) and there are
|
||||||
@@ -1585,6 +1776,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...sock,
|
...sock,
|
||||||
|
serverProps,
|
||||||
createCallLink,
|
createCallLink,
|
||||||
getBotListV2,
|
getBotListV2,
|
||||||
messageMutex,
|
messageMutex,
|
||||||
|
|||||||
+49
-7
@@ -1,7 +1,7 @@
|
|||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type { GroupMetadata, GroupParticipant, ParticipantAction, SocketConfig, WAMessageKey } from '../Types'
|
import type { GroupMetadata, GroupParticipant, ParticipantAction, SocketConfig, WAMessageKey } from '../Types'
|
||||||
import { WAMessageAddressingMode, WAMessageStubType } from '../Types'
|
import { WAMessageAddressingMode, WAMessageStubType } from '../Types'
|
||||||
import { generateMessageIDV2, unixTimestampSeconds } from '../Utils'
|
import { generateMessageIDV2, resolveLidToPn, unixTimestampSeconds } from '../Utils'
|
||||||
import {
|
import {
|
||||||
type BinaryNode,
|
type BinaryNode,
|
||||||
getBinaryNodeChild,
|
getBinaryNodeChild,
|
||||||
@@ -17,6 +17,43 @@ import { makeChatsSocket } from './chats'
|
|||||||
export const makeGroupsSocket = (config: SocketConfig) => {
|
export const makeGroupsSocket = (config: SocketConfig) => {
|
||||||
const sock = makeChatsSocket(config)
|
const sock = makeChatsSocket(config)
|
||||||
const { authState, ev, query, upsertMessage } = sock
|
const { authState, ev, query, upsertMessage } = sock
|
||||||
|
const { signalRepository } = sock
|
||||||
|
const { logger } = config
|
||||||
|
|
||||||
|
/** Normalize group metadata participant IDs from LID to PN */
|
||||||
|
const normalizeGroupMetadata = async (metadata: GroupMetadata): Promise<GroupMetadata> => {
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
|
|
||||||
|
// Resolve all participant LIDs in parallel for better performance on large groups
|
||||||
|
await Promise.all(metadata.participants.map(async (p) => {
|
||||||
|
if (isLidUser(p.id)) {
|
||||||
|
if (p.phoneNumber) {
|
||||||
|
p.lid = p.id
|
||||||
|
p.id = p.phoneNumber
|
||||||
|
} else {
|
||||||
|
const resolved = await resolveLidToPn(p.id, lidMapping, logger)
|
||||||
|
if (resolved && resolved !== p.id) {
|
||||||
|
p.lid = p.id
|
||||||
|
p.id = resolved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Normalize owner/subjectOwner if LID (parallel)
|
||||||
|
const [resolvedOwner, resolvedSubjectOwner] = await Promise.all([
|
||||||
|
metadata.owner && isLidUser(metadata.owner)
|
||||||
|
? (metadata.ownerPn || resolveLidToPn(metadata.owner, lidMapping, logger))
|
||||||
|
: null,
|
||||||
|
metadata.subjectOwner && isLidUser(metadata.subjectOwner)
|
||||||
|
? (metadata.subjectOwnerPn || resolveLidToPn(metadata.subjectOwner, lidMapping, logger))
|
||||||
|
: null
|
||||||
|
])
|
||||||
|
if (resolvedOwner) metadata.owner = resolvedOwner
|
||||||
|
if (resolvedSubjectOwner) metadata.subjectOwner = resolvedSubjectOwner
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
}
|
||||||
|
|
||||||
const groupQuery = async (jid: string, type: 'get' | 'set', content: BinaryNode[]) =>
|
const groupQuery = async (jid: string, type: 'get' | 'set', content: BinaryNode[]) =>
|
||||||
query({
|
query({
|
||||||
@@ -31,7 +68,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const groupMetadata = async (jid: string) => {
|
const groupMetadata = async (jid: string) => {
|
||||||
const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
|
const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
|
||||||
return extractGroupMetadata(result)
|
return normalizeGroupMetadata(extractGroupMetadata(result))
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupFetchAllParticipating = async () => {
|
const groupFetchAllParticipating = async () => {
|
||||||
@@ -58,16 +95,15 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
if (groupsChild) {
|
if (groupsChild) {
|
||||||
const groups = getBinaryNodeChildren(groupsChild, 'group')
|
const groups = getBinaryNodeChildren(groupsChild, 'group')
|
||||||
for (const groupNode of groups) {
|
for (const groupNode of groups) {
|
||||||
const meta = extractGroupMetadata({
|
const meta = await normalizeGroupMetadata(extractGroupMetadata({
|
||||||
tag: 'result',
|
tag: 'result',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: [groupNode]
|
content: [groupNode]
|
||||||
})
|
}))
|
||||||
data[meta.id] = meta
|
data[meta.id] = meta
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: properly parse LID / PN DATA
|
|
||||||
sock.ev.emit('groups.update', Object.values(data))
|
sock.ev.emit('groups.update', Object.values(data))
|
||||||
|
|
||||||
return data
|
return data
|
||||||
@@ -101,7 +137,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
])
|
])
|
||||||
return extractGroupMetadata(result)
|
return normalizeGroupMetadata(extractGroupMetadata(result))
|
||||||
},
|
},
|
||||||
groupLeave: async (id: string) => {
|
groupLeave: async (id: string) => {
|
||||||
await groupQuery('@g.us', 'set', [
|
await groupQuery('@g.us', 'set', [
|
||||||
@@ -277,7 +313,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
),
|
),
|
||||||
groupGetInviteInfo: async (code: string) => {
|
groupGetInviteInfo: async (code: string) => {
|
||||||
const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
|
const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
|
||||||
return extractGroupMetadata(results)
|
return normalizeGroupMetadata(extractGroupMetadata(results))
|
||||||
},
|
},
|
||||||
groupToggleEphemeral: async (jid: string, ephemeralExpiration: number) => {
|
groupToggleEphemeral: async (jid: string, ephemeralExpiration: number) => {
|
||||||
const content: BinaryNode = ephemeralExpiration
|
const content: BinaryNode = ephemeralExpiration
|
||||||
@@ -307,11 +343,13 @@ export const extractGroupMetadata = (result: BinaryNode) => {
|
|||||||
let descId: string | undefined
|
let descId: string | undefined
|
||||||
let descOwner: string | undefined
|
let descOwner: string | undefined
|
||||||
let descOwnerPn: string | undefined
|
let descOwnerPn: string | undefined
|
||||||
|
let descOwnerUsername: string | undefined
|
||||||
let descTime: number | undefined
|
let descTime: number | undefined
|
||||||
if (descChild) {
|
if (descChild) {
|
||||||
desc = getBinaryNodeChildString(descChild, 'body')
|
desc = getBinaryNodeChildString(descChild, 'body')
|
||||||
descOwner = descChild.attrs.participant ? jidNormalizedUser(descChild.attrs.participant) : undefined
|
descOwner = descChild.attrs.participant ? jidNormalizedUser(descChild.attrs.participant) : undefined
|
||||||
descOwnerPn = descChild.attrs.participant_pn ? jidNormalizedUser(descChild.attrs.participant_pn) : undefined
|
descOwnerPn = descChild.attrs.participant_pn ? jidNormalizedUser(descChild.attrs.participant_pn) : undefined
|
||||||
|
descOwnerUsername = descChild.attrs.participant_username || undefined
|
||||||
descTime = +descChild.attrs.t!
|
descTime = +descChild.attrs.t!
|
||||||
descId = descChild.attrs.id
|
descId = descChild.attrs.id
|
||||||
}
|
}
|
||||||
@@ -326,16 +364,19 @@ export const extractGroupMetadata = (result: BinaryNode) => {
|
|||||||
subject: group.attrs.subject!,
|
subject: group.attrs.subject!,
|
||||||
subjectOwner: group.attrs.s_o,
|
subjectOwner: group.attrs.s_o,
|
||||||
subjectOwnerPn: group.attrs.s_o_pn,
|
subjectOwnerPn: group.attrs.s_o_pn,
|
||||||
|
subjectOwnerUsername: group.attrs.s_o_username,
|
||||||
subjectTime: +(group.attrs.s_t ?? '0'),
|
subjectTime: +(group.attrs.s_t ?? '0'),
|
||||||
size: group.attrs.size ? +group.attrs.size : getBinaryNodeChildren(group, 'participant').length,
|
size: group.attrs.size ? +group.attrs.size : getBinaryNodeChildren(group, 'participant').length,
|
||||||
creation: +(group.attrs.creation ?? '0'),
|
creation: +(group.attrs.creation ?? '0'),
|
||||||
owner: group.attrs.creator ? jidNormalizedUser(group.attrs.creator) : undefined,
|
owner: group.attrs.creator ? jidNormalizedUser(group.attrs.creator) : undefined,
|
||||||
ownerPn: group.attrs.creator_pn ? jidNormalizedUser(group.attrs.creator_pn) : undefined,
|
ownerPn: group.attrs.creator_pn ? jidNormalizedUser(group.attrs.creator_pn) : undefined,
|
||||||
|
ownerUsername: group.attrs.creator_username || undefined,
|
||||||
owner_country_code: group.attrs.creator_country_code,
|
owner_country_code: group.attrs.creator_country_code,
|
||||||
desc,
|
desc,
|
||||||
descId,
|
descId,
|
||||||
descOwner,
|
descOwner,
|
||||||
descOwnerPn,
|
descOwnerPn,
|
||||||
|
descOwnerUsername,
|
||||||
descTime,
|
descTime,
|
||||||
linkedParent: getBinaryNodeChild(group, 'linked_parent')?.attrs.jid || undefined,
|
linkedParent: getBinaryNodeChild(group, 'linked_parent')?.attrs.jid || undefined,
|
||||||
restrict: !!getBinaryNodeChild(group, 'locked'),
|
restrict: !!getBinaryNodeChild(group, 'locked'),
|
||||||
@@ -350,6 +391,7 @@ export const extractGroupMetadata = (result: BinaryNode) => {
|
|||||||
id: attrs.jid!,
|
id: attrs.jid!,
|
||||||
phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
|
phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
|
||||||
lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
|
lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
|
||||||
|
username: attrs.participant_username || attrs.username || undefined,
|
||||||
admin: (attrs.type || null) as GroupParticipant['admin']
|
admin: (attrs.type || null) as GroupParticipant['admin']
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|||||||
+1327
-156
File diff suppressed because it is too large
Load Diff
+370
-85
@@ -1,3 +1,4 @@
|
|||||||
|
import { randomBytes } from 'crypto'
|
||||||
import NodeCache from '@cacheable/node-cache'
|
import NodeCache from '@cacheable/node-cache'
|
||||||
import { Boom } from '@hapi/boom'
|
import { Boom } from '@hapi/boom'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
@@ -8,6 +9,7 @@ import type {
|
|||||||
AlbumMessageOptions,
|
AlbumMessageOptions,
|
||||||
AlbumSendResult,
|
AlbumSendResult,
|
||||||
AnyMessageContent,
|
AnyMessageContent,
|
||||||
|
LIDMapping,
|
||||||
MediaConnInfo,
|
MediaConnInfo,
|
||||||
MessageReceiptType,
|
MessageReceiptType,
|
||||||
MessageRelayOptions,
|
MessageRelayOptions,
|
||||||
@@ -44,7 +46,10 @@ import { makeKeyedMutex } from '../Utils/make-mutex'
|
|||||||
import { metrics, recordMessageFailure, recordMessageSent } from '../Utils/prometheus-metrics'
|
import { metrics, recordMessageFailure, recordMessageSent } from '../Utils/prometheus-metrics'
|
||||||
import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils'
|
import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils'
|
||||||
import {
|
import {
|
||||||
|
buildMergedTcTokenIndexWrite,
|
||||||
|
isRegularUser,
|
||||||
isTcTokenExpired,
|
isTcTokenExpired,
|
||||||
|
resolveIssuanceJid,
|
||||||
resolveTcTokenJid,
|
resolveTcTokenJid,
|
||||||
shouldSendNewTcToken,
|
shouldSendNewTcToken,
|
||||||
storeTcTokensFromIqResult
|
storeTcTokensFromIqResult
|
||||||
@@ -123,6 +128,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
// Tracks JIDs with an in-flight getPrivacyTokens IQ to avoid duplicate concurrent fetches
|
// Tracks JIDs with an in-flight getPrivacyTokens IQ to avoid duplicate concurrent fetches
|
||||||
const tcTokenFetchingJids = new Set<string>()
|
const tcTokenFetchingJids = new Set<string>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
|
||||||
|
* Distinct from `tcTokenFetchingJids` (which dedupes inbound *fetches* of the peer's
|
||||||
|
* token). Prevents duplicate IQs when a caller fires several rapid back-to-back sends
|
||||||
|
* to the same contact before `senderTimestamp` persists. Entries are always removed
|
||||||
|
* in `.finally()`, so the set is bounded by current concurrency.
|
||||||
|
*/
|
||||||
|
const inFlightTcTokenIssuance = new Set<string>()
|
||||||
|
|
||||||
let mediaConn: Promise<MediaConnInfo>
|
let mediaConn: Promise<MediaConnInfo>
|
||||||
const refreshMediaConn = async (forceGet = false) => {
|
const refreshMediaConn = async (forceGet = false) => {
|
||||||
const media = await mediaConn
|
const media = await mediaConn
|
||||||
@@ -337,6 +351,33 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 4th LID→PN source: device-list entries sharing the same raw_id
|
||||||
|
// WA Business uses this for accounts where HistorySync sends zero phoneNumberToLidMappings
|
||||||
|
const allEntries = [...result.list, ...result.sideList]
|
||||||
|
const rawIdMap = new Map<number, { pn?: string; lid?: string }>()
|
||||||
|
for (const item of allEntries) {
|
||||||
|
if (typeof item.rawId !== 'number' || isNaN(item.rawId)) continue
|
||||||
|
const decoded = jidDecode(item.id)
|
||||||
|
if (!decoded) continue
|
||||||
|
const entry = rawIdMap.get(item.rawId) || {}
|
||||||
|
if (decoded.server === 'lid' || decoded.server === 'hosted.lid') {
|
||||||
|
entry.lid = item.id
|
||||||
|
} else if (decoded.server === 's.whatsapp.net' || decoded.server === 'c.us') {
|
||||||
|
entry.pn = item.id
|
||||||
|
}
|
||||||
|
rawIdMap.set(item.rawId, entry)
|
||||||
|
}
|
||||||
|
const rawIdMappings: LIDMapping[] = []
|
||||||
|
for (const { pn, lid } of rawIdMap.values()) {
|
||||||
|
if (pn && lid) {
|
||||||
|
rawIdMappings.push({ lid: jidNormalizedUser(lid), pn: jidNormalizedUser(pn) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rawIdMappings.length > 0) {
|
||||||
|
await signalRepository.lidMapping.storeLIDPNMappings(rawIdMappings)
|
||||||
|
logger.debug({ count: rawIdMappings.length }, 'stored LID-PN mappings from raw_id pairing')
|
||||||
|
}
|
||||||
|
|
||||||
const meId = authState.creds.me?.id
|
const meId = authState.creds.me?.id
|
||||||
if (!meId) throw new Boom('Not authenticated', { statusCode: 401 })
|
if (!meId) throw new Boom('Not authenticated', { statusCode: 401 })
|
||||||
const meLid = authState.creds.me?.lid || ''
|
const meLid = authState.creds.me?.lid || ''
|
||||||
@@ -507,6 +548,38 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
return didFetchNewSession
|
return didFetchNewSession
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const canonicalizeCarouselRecipients = async (recipientJids: string[]): Promise<string[]> => {
|
||||||
|
if (!recipientJids.length) {
|
||||||
|
return recipientJids
|
||||||
|
}
|
||||||
|
|
||||||
|
const pnRecipients = [...new Set(recipientJids.filter(jid => isAnyPnUser(jid)))]
|
||||||
|
if (!pnRecipients.length) {
|
||||||
|
return recipientJids
|
||||||
|
}
|
||||||
|
|
||||||
|
const mappings = (await signalRepository.lidMapping.getLIDsForPNs(pnRecipients)) || []
|
||||||
|
if (!mappings.length) {
|
||||||
|
logger.debug({ recipientCount: recipientJids.length }, '[CAROUSEL] No PN→LID recipient mappings found')
|
||||||
|
return recipientJids
|
||||||
|
}
|
||||||
|
|
||||||
|
const pnToLid = new Map(mappings.map(item => [item.pn, item.lid]))
|
||||||
|
const mapped = recipientJids.map(jid => pnToLid.get(jid) || jid)
|
||||||
|
const changed = mapped.filter((jid, index) => jid !== recipientJids[index]).length
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
{
|
||||||
|
recipientCount: recipientJids.length,
|
||||||
|
pnRecipients: pnRecipients.length,
|
||||||
|
mappedRecipients: changed
|
||||||
|
},
|
||||||
|
'[CAROUSEL] Canonicalized recipient addressing to LID before session assert/encrypt'
|
||||||
|
)
|
||||||
|
|
||||||
|
return mapped
|
||||||
|
}
|
||||||
|
|
||||||
const sendPeerDataOperationMessage = async (
|
const sendPeerDataOperationMessage = async (
|
||||||
pdoMessage: proto.Message.IPeerDataOperationRequestMessage
|
pdoMessage: proto.Message.IPeerDataOperationRequestMessage
|
||||||
): Promise<string> => {
|
): Promise<string> => {
|
||||||
@@ -541,6 +614,82 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
return msgId
|
return msgId
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const resolveDsmMessageForRecipient = (
|
||||||
|
jid: string,
|
||||||
|
patchedMessage: proto.IMessage,
|
||||||
|
dsmMessage: proto.IMessage | undefined,
|
||||||
|
meId: string,
|
||||||
|
meLid: string | undefined,
|
||||||
|
meLidUser: string | null | undefined
|
||||||
|
) => {
|
||||||
|
if (!dsmMessage) {
|
||||||
|
return patchedMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
const { user: targetUser } = jidDecode(jid)!
|
||||||
|
const { user: ownPnUser } = jidDecode(meId)!
|
||||||
|
const isOwnUser = targetUser === ownPnUser || (meLidUser && targetUser === meLidUser)
|
||||||
|
const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
|
||||||
|
|
||||||
|
if (isOwnUser && !isExactSenderDevice) {
|
||||||
|
logger.debug({ jid, targetUser }, 'Using DSM for own device')
|
||||||
|
return dsmMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
return patchedMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
const encryptPatchedMessageForRecipient = async ({
|
||||||
|
jid,
|
||||||
|
patchedMessage,
|
||||||
|
dsmMessage,
|
||||||
|
meId,
|
||||||
|
meLid,
|
||||||
|
meLidUser,
|
||||||
|
extraAttrs,
|
||||||
|
onPkmsg
|
||||||
|
}: {
|
||||||
|
jid: string
|
||||||
|
patchedMessage: proto.IMessage
|
||||||
|
dsmMessage: proto.IMessage | undefined
|
||||||
|
meId: string
|
||||||
|
meLid: string | undefined
|
||||||
|
meLidUser: string | null | undefined
|
||||||
|
extraAttrs: BinaryNode['attrs'] | undefined
|
||||||
|
onPkmsg: () => void
|
||||||
|
}) => {
|
||||||
|
if (!jid) return null
|
||||||
|
|
||||||
|
try {
|
||||||
|
const msgToEncrypt = resolveDsmMessageForRecipient(jid, patchedMessage, dsmMessage, meId, meLid, meLidUser)
|
||||||
|
const bytes = encodeWAMessage(msgToEncrypt)
|
||||||
|
const mutexKey = jid
|
||||||
|
|
||||||
|
return await encryptionMutex.mutex(mutexKey, async () => {
|
||||||
|
const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
|
||||||
|
|
||||||
|
if (type === 'pkmsg') {
|
||||||
|
onPkmsg()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
tag: 'to',
|
||||||
|
attrs: { jid },
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
tag: 'enc',
|
||||||
|
attrs: { v: '2', type, ...(extraAttrs || {}) },
|
||||||
|
content: ciphertext
|
||||||
|
}
|
||||||
|
]
|
||||||
|
} as BinaryNode
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
logger.error({ jid, err }, 'Failed to encrypt for recipient')
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const createParticipantNodes = async (
|
const createParticipantNodes = async (
|
||||||
recipientJids: string[],
|
recipientJids: string[],
|
||||||
message: proto.IMessage,
|
message: proto.IMessage,
|
||||||
@@ -560,58 +709,23 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
const meId = authState.creds.me?.id
|
const meId = authState.creds.me?.id
|
||||||
if (!meId) throw new Boom('Not authenticated', { statusCode: 401 })
|
if (!meId) throw new Boom('Not authenticated', { statusCode: 401 })
|
||||||
const meLid = authState.creds.me?.lid
|
const meLid = authState.creds.me?.lid
|
||||||
const meLidUser = meLid ? jidDecode(meLid)?.user : null
|
const meLidUser = meLid ? (jidDecode(meLid)?.user ?? null) : null
|
||||||
|
const onPkmsg = () => {
|
||||||
const encryptionPromises = (patchedMessages as { recipientJid: string; message: proto.IMessage }[]).map(
|
|
||||||
async ({ recipientJid: jid, message: patchedMessage }: { recipientJid: string; message: proto.IMessage }) => {
|
|
||||||
try {
|
|
||||||
if (!jid) return null
|
|
||||||
|
|
||||||
let msgToEncrypt = patchedMessage
|
|
||||||
|
|
||||||
if (dsmMessage) {
|
|
||||||
const { user: targetUser } = jidDecode(jid)!
|
|
||||||
const { user: ownPnUser } = jidDecode(meId)!
|
|
||||||
const ownLidUser = meLidUser
|
|
||||||
|
|
||||||
const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser)
|
|
||||||
const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
|
|
||||||
|
|
||||||
if (isOwnUser && !isExactSenderDevice) {
|
|
||||||
msgToEncrypt = dsmMessage
|
|
||||||
logger.debug({ jid, targetUser }, 'Using DSM for own device')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const bytes = encodeWAMessage(msgToEncrypt)
|
|
||||||
const mutexKey = jid
|
|
||||||
|
|
||||||
const node = await encryptionMutex.mutex(mutexKey, async () => {
|
|
||||||
const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
|
|
||||||
|
|
||||||
if (type === 'pkmsg') {
|
|
||||||
shouldIncludeDeviceIdentity = true
|
shouldIncludeDeviceIdentity = true
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
const encryptionPromises = (patchedMessages as { recipientJid: string; message: proto.IMessage }[]).map(
|
||||||
tag: 'to',
|
({ recipientJid: jid, message: patchedMessage }: { recipientJid: string; message: proto.IMessage }) =>
|
||||||
attrs: { jid },
|
encryptPatchedMessageForRecipient({
|
||||||
content: [
|
jid,
|
||||||
{
|
patchedMessage,
|
||||||
tag: 'enc',
|
dsmMessage,
|
||||||
attrs: { v: '2', type, ...(extraAttrs || {}) },
|
meId,
|
||||||
content: ciphertext
|
meLid,
|
||||||
}
|
meLidUser,
|
||||||
]
|
extraAttrs,
|
||||||
}
|
onPkmsg
|
||||||
})
|
})
|
||||||
|
|
||||||
return node
|
|
||||||
} catch (err) {
|
|
||||||
logger.error({ jid, err }, 'Failed to encrypt for recipient')
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null) as BinaryNode[]
|
const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null) as BinaryNode[]
|
||||||
@@ -939,7 +1053,8 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await authState.keys.transaction(async () => {
|
await authState.keys.transaction(async () => {
|
||||||
const mediaType = getMediaType(message)
|
// normalizeMessageContent unwraps viewOnceMessage/viewOnceMessageV2 so getMediaType works correctly
|
||||||
|
const mediaType = getMediaType(normalizeMessageContent(message) || message)
|
||||||
if (mediaType) {
|
if (mediaType) {
|
||||||
extraAttrs['mediatype'] = mediaType
|
extraAttrs['mediatype'] = mediaType
|
||||||
}
|
}
|
||||||
@@ -949,7 +1064,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
const bytes = encodeNewsletterMessage(patched as proto.IMessage)
|
const bytes = encodeNewsletterMessage(patched as proto.IMessage)
|
||||||
binaryNodeContent.push({
|
binaryNodeContent.push({
|
||||||
tag: 'plaintext',
|
tag: 'plaintext',
|
||||||
attrs: {},
|
attrs: mediaType ? { mediatype: mediaType } : {},
|
||||||
content: bytes
|
content: bytes
|
||||||
})
|
})
|
||||||
const stanza: BinaryNode = {
|
const stanza: BinaryNode = {
|
||||||
@@ -971,6 +1086,8 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
extraAttrs['decrypt-fail'] = 'hide' // todo: expand for reactions and other types
|
extraAttrs['decrypt-fail'] = 'hide' // todo: expand for reactions and other types
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// view_once_write disabled — causes server to drop message (validation fails for linked device sessions)
|
||||||
|
|
||||||
if (isGroupOrStatus && !isRetryResend) {
|
if (isGroupOrStatus && !isRetryResend) {
|
||||||
const [groupData, senderKeyMap] = await Promise.all([
|
const [groupData, senderKeyMap] = await Promise.all([
|
||||||
(async () => {
|
(async () => {
|
||||||
@@ -1166,21 +1283,57 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
allRecipients.push(jid)
|
allRecipients.push(jid)
|
||||||
}
|
}
|
||||||
|
|
||||||
await assertSessions(allRecipients)
|
const isCarouselFanout = isCarouselMessage(message)
|
||||||
|
const effectiveMeRecipients = isCarouselFanout
|
||||||
|
? await canonicalizeCarouselRecipients(meRecipients)
|
||||||
|
: meRecipients
|
||||||
|
const effectiveOtherRecipients = isCarouselFanout
|
||||||
|
? await canonicalizeCarouselRecipients(otherRecipients)
|
||||||
|
: otherRecipients
|
||||||
|
const effectiveAllRecipients = [...effectiveMeRecipients, ...effectiveOtherRecipients]
|
||||||
|
|
||||||
|
// P2: detect actual view-once media by checking inner message's viewOnce flag.
|
||||||
|
// viewOnceMessage wrapper is also used for interactive messages (buttons, lists, etc)
|
||||||
|
// which do NOT carry viewOnce=true on the media — those must NOT be filtered.
|
||||||
|
const viewOnceInner =
|
||||||
|
message.viewOnceMessageV2?.message ||
|
||||||
|
message.viewOnceMessage?.message ||
|
||||||
|
message.viewOnceMessageV2Extension?.message
|
||||||
|
const isViewOnceMsg = !!(
|
||||||
|
viewOnceInner?.imageMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.videoMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.audioMessage?.viewOnce
|
||||||
|
)
|
||||||
|
|
||||||
|
// For view-once: only send DSM to primary phone (device=0).
|
||||||
|
// Companion devices (device>0) are omitted — WA server generates
|
||||||
|
// <unavailable type="view_once"/> for them automatically.
|
||||||
|
// Sending explicit <unavailable> from a companion is rejected by the server.
|
||||||
|
const viewOnceMeRecipients = isViewOnceMsg
|
||||||
|
? effectiveMeRecipients.filter(jid => !jidDecode(jid)?.device)
|
||||||
|
: effectiveMeRecipients
|
||||||
|
|
||||||
|
// P3: assert sessions only for recipients we actually encrypt for.
|
||||||
|
// For view-once, companions are omitted — asserting their sessions is wasteful
|
||||||
|
// and could block the send if a companion session is corrupted.
|
||||||
|
await assertSessions([...viewOnceMeRecipients, ...effectiveOtherRecipients])
|
||||||
|
|
||||||
const [
|
const [
|
||||||
{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
|
{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
|
||||||
{ nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
|
{ nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
// For own devices: use DSM (deviceSentMessage) wrapper
|
createParticipantNodes(viewOnceMeRecipients, meMsg || message, extraAttrs),
|
||||||
createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
|
createParticipantNodes(effectiveOtherRecipients, message, extraAttrs)
|
||||||
createParticipantNodes(otherRecipients, message, extraAttrs)
|
|
||||||
])
|
])
|
||||||
participants.push(...meNodes)
|
participants.push(...meNodes)
|
||||||
participants.push(...otherNodes)
|
participants.push(...otherNodes)
|
||||||
|
|
||||||
if (meRecipients.length > 0 || otherRecipients.length > 0) {
|
// phash: para view-once inclui só celular principal + destinatários
|
||||||
extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients])
|
const phashRecipients = isViewOnceMsg
|
||||||
|
? [...viewOnceMeRecipients, ...effectiveOtherRecipients]
|
||||||
|
: effectiveAllRecipients
|
||||||
|
if (phashRecipients.length > 0) {
|
||||||
|
extraAttrs['phash'] = generateParticipantHashV2(phashRecipients)
|
||||||
}
|
}
|
||||||
|
|
||||||
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
|
shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
|
||||||
@@ -1253,13 +1406,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
const isCarousel = isCarouselMessage(message)
|
const isCarousel = isCarouselMessage(message)
|
||||||
|
|
||||||
// Collect biz/bot nodes to append AFTER device-identity and tctoken
|
// Collect biz/bot nodes to append AFTER device-identity and tctoken
|
||||||
// Stanza order: participants → device-identity → tctoken → biz
|
// Stanza order: participants → device-identity → tctoken → biz (when applicable)
|
||||||
// The biz node MUST be last for WhatsApp Web carousel rendering
|
// CDP capture confirms Pastorini INCLUDES biz node for carousel (native_flow v=9, name=mixed)
|
||||||
const deferredNodes: BinaryNode[] = []
|
const deferredNodes: BinaryNode[] = []
|
||||||
|
|
||||||
// Inject biz node for interactive messages (including carousel)
|
// Inject biz node for interactive messages (including carousel — CDP evidence from Pastorini)
|
||||||
if (buttonType && enableInteractiveMessages) {
|
if ((buttonType || isCarousel) && enableInteractiveMessages) {
|
||||||
const startTime = Date.now()
|
const startTime = Date.now()
|
||||||
|
// When entering via isCarousel, buttonType may be undefined — default to 'native_flow'
|
||||||
|
const effectiveButtonType = buttonType || 'native_flow'
|
||||||
|
|
||||||
// Debug: Log message structure to diagnose list detection
|
// Debug: Log message structure to diagnose list detection
|
||||||
const interactiveMsg =
|
const interactiveMsg =
|
||||||
@@ -1297,7 +1452,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Track that we're sending an interactive message
|
// Track that we're sending an interactive message
|
||||||
metrics.interactiveMessagesSent.inc({ type: buttonType })
|
metrics.interactiveMessagesSent.inc({ type: effectiveButtonType })
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Classify button types for native_flow name and bot node decisions
|
// Classify button types for native_flow name and bot node decisions
|
||||||
@@ -1340,10 +1495,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
const interactiveType = 'native_flow'
|
const interactiveType = 'native_flow'
|
||||||
deferredNodes.push({
|
const bizContent: BinaryNode[] = [
|
||||||
tag: 'biz',
|
|
||||||
attrs: {},
|
|
||||||
content: [
|
|
||||||
{
|
{
|
||||||
tag: 'interactive',
|
tag: 'interactive',
|
||||||
attrs: {
|
attrs: {
|
||||||
@@ -1361,6 +1513,31 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// CDP capture shows Pastorini includes quality_control inside biz for carousel
|
||||||
|
if (isCarousel) {
|
||||||
|
const decisionId = randomBytes(20).toString('hex')
|
||||||
|
bizContent.push({
|
||||||
|
tag: 'quality_control',
|
||||||
|
attrs: {
|
||||||
|
decision_id: decisionId
|
||||||
|
},
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
tag: 'decision_source',
|
||||||
|
attrs: {
|
||||||
|
value: 'df'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
logger.info({ msgId, decisionId }, '[BIZ NODE] Added quality_control for carousel')
|
||||||
|
}
|
||||||
|
|
||||||
|
deferredNodes.push({
|
||||||
|
tag: 'biz',
|
||||||
|
attrs: {},
|
||||||
|
content: bizContent
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1386,11 +1563,11 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Track success and latency after message is sent
|
// Track success and latency after message is sent
|
||||||
metrics.interactiveMessagesSuccess.inc({ type: buttonType })
|
metrics.interactiveMessagesSuccess.inc({ type: effectiveButtonType })
|
||||||
metrics.interactiveMessagesLatency.observe({ type: buttonType }, Date.now() - startTime)
|
metrics.interactiveMessagesLatency.observe({ type: effectiveButtonType }, Date.now() - startTime)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error({ error, msgId, buttonType }, '[BIZ NODE] Failed to inject biz node')
|
logger.error({ error, msgId, buttonType: effectiveButtonType }, '[BIZ NODE] Failed to inject biz node')
|
||||||
metrics.interactiveMessagesFailures.inc({ type: buttonType, reason: 'injection_failed' })
|
metrics.interactiveMessagesFailures.inc({ type: effectiveButtonType, reason: 'injection_failed' })
|
||||||
}
|
}
|
||||||
} else if (buttonType && !enableInteractiveMessages) {
|
} else if (buttonType && !enableInteractiveMessages) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
@@ -1417,7 +1594,8 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
stanza.attrs.to = destinationJid
|
stanza.attrs.to = destinationJid
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldIncludeDeviceIdentity) {
|
// Always include device-identity for carousel (Pastorini stanza always has it)
|
||||||
|
if (shouldIncludeDeviceIdentity || isCarousel) {
|
||||||
;(stanza.content as BinaryNode[]).push({
|
;(stanza.content as BinaryNode[]).push({
|
||||||
tag: 'device-identity',
|
tag: 'device-identity',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
@@ -1474,11 +1652,63 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If tctoken is missing for a 1:1 send, fire-and-forget fetch so the
|
// If tctoken is missing for a 1:1 send, fetch it
|
||||||
// retry path (error 463 → handleBadAck) can pick it up on resend
|
// CDP capture confirms Pastorini stanza includes tctoken for carousel
|
||||||
if (!tcTokenBuffer?.length && is1on1Send && !tcTokenFetchingJids.has(tcTokenJid)) {
|
if (!tcTokenBuffer?.length && is1on1Send && !tcTokenFetchingJids.has(tcTokenJid)) {
|
||||||
tcTokenFetchingJids.add(tcTokenJid)
|
tcTokenFetchingJids.add(tcTokenJid)
|
||||||
logTcToken('fetch', { jid: destinationJid })
|
logTcToken('fetch', { jid: destinationJid })
|
||||||
|
|
||||||
|
if (isCarousel) {
|
||||||
|
// BLOCKING fetch for carousel — tctoken is required (Pastorini stanza has it)
|
||||||
|
try {
|
||||||
|
const fetchResult = await getPrivacyTokens([destinationJid])
|
||||||
|
|
||||||
|
// Direct extraction from IQ result — bypass store/read key mismatch
|
||||||
|
const tokensNode = getBinaryNodeChild(fetchResult, 'tokens')
|
||||||
|
if (tokensNode) {
|
||||||
|
const tokenNodes = getBinaryNodeChildren(tokensNode, 'token')
|
||||||
|
for (const tokenNode of tokenNodes) {
|
||||||
|
if (tokenNode.attrs.type === 'trusted_contact' && tokenNode.content instanceof Uint8Array) {
|
||||||
|
tcTokenBuffer = Buffer.from(tokenNode.content)
|
||||||
|
logger.info(
|
||||||
|
{
|
||||||
|
jid: destinationJid,
|
||||||
|
tokenLen: tcTokenBuffer.length,
|
||||||
|
tokenJid: tokenNode.attrs.jid,
|
||||||
|
timestamp: tokenNode.attrs.t
|
||||||
|
},
|
||||||
|
'[CAROUSEL] tctoken extracted directly from IQ result'
|
||||||
|
)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tcTokenBuffer?.length) {
|
||||||
|
// Debug: dump the IQ result structure
|
||||||
|
const childTags = Array.isArray(fetchResult.content)
|
||||||
|
? (fetchResult.content as BinaryNode[]).map(n => `${n.tag}(${JSON.stringify(n.attrs)})`)
|
||||||
|
: []
|
||||||
|
logger.warn(
|
||||||
|
{ jid: destinationJid, resultTag: fetchResult.tag, resultAttrs: fetchResult.attrs, childTags },
|
||||||
|
'[CAROUSEL] tctoken fetch completed but NO valid token in IQ result'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also store for future use
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: fetchResult,
|
||||||
|
fallbackJid: destinationJid,
|
||||||
|
keys: authState.keys,
|
||||||
|
getLIDForPN
|
||||||
|
}).catch(() => {})
|
||||||
|
} catch (err: any) {
|
||||||
|
logger.warn({ jid: destinationJid, err: err?.message }, '[CAROUSEL] Blocking tctoken fetch failed')
|
||||||
|
} finally {
|
||||||
|
tcTokenFetchingJids.delete(tcTokenJid)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fire-and-forget for non-carousel
|
||||||
getPrivacyTokens([destinationJid])
|
getPrivacyTokens([destinationJid])
|
||||||
.then(async fetchResult => {
|
.then(async fetchResult => {
|
||||||
await storeTcTokensFromIqResult({
|
await storeTcTokensFromIqResult({
|
||||||
@@ -1486,7 +1716,6 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
fallbackJid: destinationJid,
|
fallbackJid: destinationJid,
|
||||||
keys: authState.keys,
|
keys: authState.keys,
|
||||||
getLIDForPN
|
getLIDForPN
|
||||||
// onNewJidStored not passed — the pruning index lives in messages-recv (higher layer)
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.catch(err => {
|
.catch(err => {
|
||||||
@@ -1496,8 +1725,18 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
tcTokenFetchingJids.delete(tcTokenJid)
|
tcTokenFetchingJids.delete(tcTokenJid)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (tcTokenBuffer?.length) {
|
// Gate inclusion on AB prop 10518 (privacy_token_sending_on_all_1_on_1_messages).
|
||||||
|
// WA Web defaults to true; if the server flips it off we mirror that to avoid
|
||||||
|
// divergence with the spec-compliant client.
|
||||||
|
//
|
||||||
|
// CARROUSEL EXCEPTION: Pastorini-validated carousel stanzas REQUIRE tctoken
|
||||||
|
// (CDP capture confirms it). If the AB prop ever flips off, dropping the
|
||||||
|
// tctoken from carousel would break rendering on Android. Carousel always
|
||||||
|
// includes the tctoken when one is available, regardless of the prop —
|
||||||
|
// matching the fork's existing behaviour pre-PR #2339.
|
||||||
|
if (tcTokenBuffer?.length && (sock.serverProps.privacyTokenOn1to1 || isCarousel)) {
|
||||||
;(stanza.content as BinaryNode[]).push({
|
;(stanza.content as BinaryNode[]).push({
|
||||||
tag: 'tctoken',
|
tag: 'tctoken',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
@@ -1525,8 +1764,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
logger.debug({ msgId }, `sending message to ${participants.length} devices`)
|
logger.debug({ msgId }, `sending message to ${participants.length} devices`)
|
||||||
|
|
||||||
// ======= PROTOBUF ROUNDTRIP TEST: Verify encoding preserves carousel =======
|
// ======= PROTOBUF ROUNDTRIP TEST: Verify encoding preserves carousel =======
|
||||||
// Only runs at debug level to avoid performance overhead in production
|
if (isCarousel) {
|
||||||
if (isCarousel && logger.level === 'debug') {
|
|
||||||
try {
|
try {
|
||||||
const encoded = proto.Message.encode(message).finish()
|
const encoded = proto.Message.encode(message).finish()
|
||||||
const decoded = proto.Message.decode(encoded)
|
const decoded = proto.Message.decode(encoded)
|
||||||
@@ -1535,15 +1773,19 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
const card0 = decodedInteractive?.carouselMessage?.cards?.[0]
|
const card0 = decodedInteractive?.carouselMessage?.cards?.[0]
|
||||||
const card0Header = card0?.header
|
const card0Header = card0?.header
|
||||||
|
|
||||||
logger.debug(
|
logger.info(
|
||||||
{
|
{
|
||||||
msgId,
|
msgId,
|
||||||
encodedSize: encoded.length,
|
encodedSize: encoded.length,
|
||||||
|
messageKeys: Object.keys(message),
|
||||||
|
hasInteractive: !!message.interactiveMessage,
|
||||||
|
hasViewOnce: !!message.viewOnceMessage,
|
||||||
hasCarouselAfterDecode: !!decodedInteractive?.carouselMessage,
|
hasCarouselAfterDecode: !!decodedInteractive?.carouselMessage,
|
||||||
cardsCount,
|
cardsCount,
|
||||||
card0Title: card0Header?.title,
|
card0Title: card0Header?.title,
|
||||||
card0HasImage: !!card0Header?.imageMessage,
|
card0HasImage: !!card0Header?.imageMessage,
|
||||||
card0Buttons: card0?.nativeFlowMessage?.buttons?.length || 0
|
card0Buttons: card0?.nativeFlowMessage?.buttons?.length || 0,
|
||||||
|
messageVersion: decodedInteractive?.carouselMessage?.messageVersion
|
||||||
},
|
},
|
||||||
'[ROUNDTRIP] Protobuf encode→decode verification'
|
'[ROUNDTRIP] Protobuf encode→decode verification'
|
||||||
)
|
)
|
||||||
@@ -1553,8 +1795,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ======= PROTOCOL INTERCEPTOR: Dump complete stanza for debugging =======
|
// ======= PROTOCOL INTERCEPTOR: Dump complete stanza for debugging =======
|
||||||
// Only runs at debug level to avoid logging sensitive content in production
|
if (buttonType || isCarousel) {
|
||||||
if ((buttonType || isCarousel) && logger.level === 'debug') {
|
|
||||||
const dumpBinaryNode = (node: BinaryNode, indent = 0): string => {
|
const dumpBinaryNode = (node: BinaryNode, indent = 0): string => {
|
||||||
if (!node) return ''
|
if (!node) return ''
|
||||||
const pad = ' '.repeat(indent)
|
const pad = ' '.repeat(indent)
|
||||||
@@ -1595,13 +1836,39 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
// Gated only by shouldSendNewTcToken — removed tcTokenBuffer?.length guard so
|
// Gated only by shouldSendNewTcToken — removed tcTokenBuffer?.length guard so
|
||||||
// issuance fires even when we don't yet hold a token (bucket boundary crossed).
|
// issuance fires even when we don't yet hold a token (bucket boundary crossed).
|
||||||
// IMPORTANT: must run AFTER sendNode — issuing before the message causes error 463.
|
// IMPORTANT: must run AFTER sendNode — issuing before the message causes error 463.
|
||||||
if (is1on1Send && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp)) {
|
//
|
||||||
|
// WA Web also skips issuance for:
|
||||||
|
// - protocol messages (revoke, ephemeral settings, etc — see TcTokenChatAction)
|
||||||
|
// - PSA, bots, MetaAI (isRegularUser filter)
|
||||||
|
// and dedupes back-to-back issuances with `inFlightTcTokenIssuance` so a burst of
|
||||||
|
// rapid sends to the same contact only triggers a single IQ before senderTimestamp
|
||||||
|
// is persisted.
|
||||||
|
const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage
|
||||||
|
// Use isRegularUser (the same Wid.isRegularUser() port that gates the store
|
||||||
|
// path) so we filter PSA/bot/MetaAI consistently regardless of JID server
|
||||||
|
// (@c.us vs @s.whatsapp.net) and device suffix. The previous PSA_WID/isJidBot
|
||||||
|
// checks only matched @c.us forms — destinationJid arrives normalized.
|
||||||
|
const isBotOrPSA = !isRegularUser(destinationJid)
|
||||||
|
if (
|
||||||
|
is1on1Send &&
|
||||||
|
!isProtocolMsg &&
|
||||||
|
!isBotOrPSA &&
|
||||||
|
shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
|
||||||
|
!inFlightTcTokenIssuance.has(tcTokenJid)
|
||||||
|
) {
|
||||||
|
inFlightTcTokenIssuance.add(tcTokenJid)
|
||||||
const issueTimestamp = unixTimestampSeconds()
|
const issueTimestamp = unixTimestampSeconds()
|
||||||
logTcToken('reissue', { jid: destinationJid })
|
logTcToken('reissue', { jid: destinationJid })
|
||||||
getPrivacyTokens([destinationJid], issueTimestamp)
|
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
|
||||||
|
resolveIssuanceJid(
|
||||||
|
destinationJid,
|
||||||
|
sock.serverProps.lidTrustedTokenIssueToLid,
|
||||||
|
getLIDForPN,
|
||||||
|
getPNForLID
|
||||||
|
)
|
||||||
|
.then(issueJid => getPrivacyTokens([issueJid], issueTimestamp))
|
||||||
.then(async result => {
|
.then(async result => {
|
||||||
// Store any tokens received in the IQ response.
|
// Store any tokens received in the IQ response.
|
||||||
// onNewJidStored not passed — pruning index lives in messages-recv (higher layer).
|
|
||||||
await storeTcTokensFromIqResult({
|
await storeTcTokensFromIqResult({
|
||||||
result,
|
result,
|
||||||
fallbackJid: tcTokenJid,
|
fallbackJid: tcTokenJid,
|
||||||
@@ -1611,15 +1878,21 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
// Persist senderTimestamp unconditionally — WA Web stores it in the chat table
|
// Persist senderTimestamp unconditionally — WA Web stores it in the chat table
|
||||||
// regardless of whether a token exists. Spread preserves token+timestamp if present.
|
// regardless of whether a token exists. Spread preserves token+timestamp if present.
|
||||||
|
// WABA Android: INSERT INTO wa_trusted_contacts_send (jid, sent_tc_token_timestamp, real_issue_timestamp)
|
||||||
|
// VALUES (?, ?, 0) — realIssueTimestamp=0 means issued but not yet confirmed by server.
|
||||||
|
// Also bump the cross-session prune index so this JID is tracked persistently.
|
||||||
const currentData = await authState.keys.get('tctoken', [tcTokenJid])
|
const currentData = await authState.keys.get('tctoken', [tcTokenJid])
|
||||||
const currentEntry = currentData[tcTokenJid]
|
const currentEntry = currentData[tcTokenJid]
|
||||||
|
const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
|
||||||
await authState.keys.set({
|
await authState.keys.set({
|
||||||
tctoken: {
|
tctoken: {
|
||||||
[tcTokenJid]: {
|
[tcTokenJid]: {
|
||||||
...currentEntry,
|
...currentEntry,
|
||||||
token: currentEntry?.token ?? Buffer.alloc(0),
|
token: currentEntry?.token ?? Buffer.alloc(0),
|
||||||
senderTimestamp: issueTimestamp
|
senderTimestamp: issueTimestamp,
|
||||||
}
|
realIssueTimestamp: 0
|
||||||
|
},
|
||||||
|
...indexWrite
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -1628,6 +1901,9 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
.catch(err => {
|
.catch(err => {
|
||||||
logTcToken('reissue_fail', { jid: destinationJid, error: err?.message })
|
logTcToken('reissue_fail', { jid: destinationJid, error: err?.message })
|
||||||
})
|
})
|
||||||
|
.finally(() => {
|
||||||
|
inFlightTcTokenIssuance.delete(tcTokenJid)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log with [BAILEYS] prefix
|
// Log with [BAILEYS] prefix
|
||||||
@@ -1704,6 +1980,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getMediaType = (message: proto.IMessage) => {
|
const getMediaType = (message: proto.IMessage) => {
|
||||||
|
// For view-once media, unwrap the viewOnceMessage wrapper before checking media type
|
||||||
|
const inner =
|
||||||
|
message.viewOnceMessage?.message ||
|
||||||
|
message.viewOnceMessageV2?.message ||
|
||||||
|
message.viewOnceMessageV2Extension?.message
|
||||||
|
if (inner) {
|
||||||
|
return getMediaType(inner)
|
||||||
|
}
|
||||||
|
|
||||||
if (message.imageMessage) {
|
if (message.imageMessage) {
|
||||||
return 'image'
|
return 'image'
|
||||||
} else if (message.videoMessage) {
|
} else if (message.videoMessage) {
|
||||||
|
|||||||
@@ -123,11 +123,11 @@ export const makeNewsletterSocket = (config: SocketConfig) => {
|
|||||||
},
|
},
|
||||||
|
|
||||||
newsletterMute: (jid: string) => {
|
newsletterMute: (jid: string) => {
|
||||||
return executeWMexQuery({ newsletter_id: jid }, QueryIds.MUTE, XWAPaths.xwa2_newsletter_mute_v2)
|
return executeWMexQuery({ input: { newsletter_id: jid, type: 'MUTE_ADMIN_ACTIVITY', value: 'OFF' } }, QueryIds.MUTE, XWAPaths.xwa2_newsletter_mute_v2)
|
||||||
},
|
},
|
||||||
|
|
||||||
newsletterUnmute: (jid: string) => {
|
newsletterUnmute: (jid: string) => {
|
||||||
return executeWMexQuery({ newsletter_id: jid }, QueryIds.UNMUTE, XWAPaths.xwa2_newsletter_unmute_v2)
|
return executeWMexQuery({ input: { newsletter_id: jid, type: 'MUTE_ADMIN_ACTIVITY', value: 'ON' } }, QueryIds.UNMUTE, XWAPaths.xwa2_newsletter_unmute_v2)
|
||||||
},
|
},
|
||||||
|
|
||||||
newsletterUpdateName: async (jid: string, name: string) => {
|
newsletterUpdateName: async (jid: string, name: string) => {
|
||||||
|
|||||||
+146
-179
@@ -38,13 +38,8 @@ import {
|
|||||||
signedKeyPair,
|
signedKeyPair,
|
||||||
xmppSignedPreKey
|
xmppSignedPreKey
|
||||||
} from '../Utils'
|
} from '../Utils'
|
||||||
import { getPlatformId } from '../Utils/browser-utils'
|
import { getPlatformId, isAndroidBrowser } from '../Utils/browser-utils'
|
||||||
import {
|
import { withBoundedRetry } from '../Utils/bounded-retry'
|
||||||
CircuitBreaker,
|
|
||||||
CircuitOpenError,
|
|
||||||
createConnectionCircuitBreaker,
|
|
||||||
createPreKeyCircuitBreaker
|
|
||||||
} from '../Utils/circuit-breaker'
|
|
||||||
import {
|
import {
|
||||||
decrementActiveConnections,
|
decrementActiveConnections,
|
||||||
incrementActiveConnections,
|
incrementActiveConnections,
|
||||||
@@ -94,10 +89,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
transactionOpts,
|
transactionOpts,
|
||||||
qrTimeout,
|
qrTimeout,
|
||||||
makeSignalRepository,
|
makeSignalRepository,
|
||||||
enableCircuitBreaker = true,
|
|
||||||
queryCircuitBreaker: queryCircuitBreakerConfig,
|
|
||||||
connectionCircuitBreaker: connectionCircuitBreakerConfig,
|
|
||||||
preKeyCircuitBreaker: preKeyCircuitBreakerConfig,
|
|
||||||
// If enableUnifiedSession is explicitly set (true/false), use it
|
// If enableUnifiedSession is explicitly set (true/false), use it
|
||||||
// Otherwise (undefined), check env var, then default to true
|
// Otherwise (undefined), check env var, then default to true
|
||||||
enableUnifiedSession: enableUnifiedSessionConfig
|
enableUnifiedSession: enableUnifiedSessionConfig
|
||||||
@@ -107,57 +98,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
const enableUnifiedSession =
|
const enableUnifiedSession =
|
||||||
enableUnifiedSessionConfig !== undefined ? enableUnifiedSessionConfig : shouldEnableUnifiedSession()
|
enableUnifiedSessionConfig !== undefined ? enableUnifiedSessionConfig : shouldEnableUnifiedSession()
|
||||||
|
|
||||||
// Initialize circuit breakers if enabled
|
|
||||||
let queryCircuitBreaker: CircuitBreaker | undefined
|
|
||||||
let connectionCircuitBreaker: CircuitBreaker | undefined
|
|
||||||
let preKeyCircuitBreaker: CircuitBreaker | undefined
|
|
||||||
|
|
||||||
if (enableCircuitBreaker) {
|
|
||||||
// Circuit breaker for query operations (most critical)
|
|
||||||
queryCircuitBreaker = createConnectionCircuitBreaker({
|
|
||||||
name: 'socket-query',
|
|
||||||
failureThreshold: 5,
|
|
||||||
failureWindow: 60000,
|
|
||||||
resetTimeout: 30000,
|
|
||||||
successThreshold: 2,
|
|
||||||
timeout: defaultQueryTimeoutMs || 60000,
|
|
||||||
onStateChange: (from, to) => {
|
|
||||||
logger.info({ from, to }, 'Query circuit breaker state changed')
|
|
||||||
},
|
|
||||||
onOpen: () => {
|
|
||||||
logger.warn('Query circuit breaker OPENED - blocking requests')
|
|
||||||
},
|
|
||||||
onClose: () => {
|
|
||||||
logger.info('Query circuit breaker CLOSED - resuming normal operation')
|
|
||||||
},
|
|
||||||
...queryCircuitBreakerConfig
|
|
||||||
})
|
|
||||||
|
|
||||||
// Circuit breaker for connection operations
|
|
||||||
connectionCircuitBreaker = createConnectionCircuitBreaker({
|
|
||||||
name: 'socket-connection',
|
|
||||||
failureThreshold: 3,
|
|
||||||
failureWindow: 30000,
|
|
||||||
resetTimeout: 60000,
|
|
||||||
successThreshold: 1,
|
|
||||||
onStateChange: (from, to) => {
|
|
||||||
logger.info({ from, to }, 'Connection circuit breaker state changed')
|
|
||||||
},
|
|
||||||
...connectionCircuitBreakerConfig
|
|
||||||
})
|
|
||||||
|
|
||||||
// Circuit breaker for pre-key operations
|
|
||||||
preKeyCircuitBreaker = createPreKeyCircuitBreaker({
|
|
||||||
name: 'socket-prekey',
|
|
||||||
onStateChange: (from, to) => {
|
|
||||||
logger.info({ from, to }, 'PreKey circuit breaker state changed')
|
|
||||||
},
|
|
||||||
...preKeyCircuitBreakerConfig
|
|
||||||
})
|
|
||||||
|
|
||||||
logger.info('Circuit breakers initialized for socket operations')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unified Session Manager will be initialized after sendNode is defined
|
// Unified Session Manager will be initialized after sendNode is defined
|
||||||
let unifiedSessionManager: UnifiedSessionManager | undefined
|
let unifiedSessionManager: UnifiedSessionManager | undefined
|
||||||
|
|
||||||
@@ -238,20 +178,17 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** send a raw buffer with circuit breaker protection */
|
/**
|
||||||
|
* Send a raw buffer over the WebSocket.
|
||||||
|
*
|
||||||
|
* Replaces the previous connectionCircuitBreaker wrapping. WebSocket
|
||||||
|
* lifecycle errors (Connection Closed / Lost / Replaced) were already
|
||||||
|
* filtered out of the circuit's failure count, so the only failures it
|
||||||
|
* tripped on were rare native send() errors — for which a state-machine
|
||||||
|
* gate adds no value over a fast propagated error. Reconnection logic
|
||||||
|
* in makeSocket already handles WS recovery independently.
|
||||||
|
*/
|
||||||
const sendRawMessage = async (data: Uint8Array | Buffer) => {
|
const sendRawMessage = async (data: Uint8Array | Buffer) => {
|
||||||
if (connectionCircuitBreaker) {
|
|
||||||
try {
|
|
||||||
return await connectionCircuitBreaker.execute(() => sendRawMessageInternal(data))
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof CircuitOpenError) {
|
|
||||||
logger.warn({ circuitName: error.circuitName }, 'Send blocked by connection circuit breaker')
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return sendRawMessageInternal(data)
|
return sendRawMessageInternal(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -266,7 +203,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Initialize Unified Session Manager now that sendNode is defined
|
// Initialize Unified Session Manager now that sendNode is defined
|
||||||
// (single initialization to avoid duplicating circuit breakers and state)
|
// (single initialization to avoid duplicating manager state)
|
||||||
if (enableUnifiedSession) {
|
if (enableUnifiedSession) {
|
||||||
const sendNodeForSession = async (node: BinaryNode): Promise<void> => {
|
const sendNodeForSession = async (node: BinaryNode): Promise<void> => {
|
||||||
await sendNode(node)
|
await sendNode(node)
|
||||||
@@ -275,7 +212,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
unifiedSessionManager = createUnifiedSessionManager({
|
unifiedSessionManager = createUnifiedSessionManager({
|
||||||
enabled: true,
|
enabled: true,
|
||||||
logger,
|
logger,
|
||||||
enableCircuitBreaker,
|
|
||||||
sendNode: sendNodeForSession
|
sendNode: sendNodeForSession
|
||||||
})
|
})
|
||||||
logger.info('Unified session manager initialized')
|
logger.info('Unified session manager initialized')
|
||||||
@@ -346,11 +282,8 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
// Register the response listener BEFORE sending — avoids a race where the server
|
// Register the response listener BEFORE sending — avoids a race where the server
|
||||||
// responds before we start listening. waitForMessage already handles its own
|
// responds before we start listening. waitForMessage already handles its own
|
||||||
// timeout (returns undefined) and connection-close errors (throws), so we do NOT
|
// timeout (returns undefined) and connection-close errors (throws), so we do NOT
|
||||||
// wrap it in a second promiseTimeout. The outer wrapper caused a race condition
|
// wrap it in a second promiseTimeout. The outer wrapper would race the inner
|
||||||
// where both timers fired at ~the same deadline: the outer one threw
|
// timeout near the deadline and throw a spurious Boom('Timed Out').
|
||||||
// Boom('Timed Out') while sendNode was still pending, producing a spurious error
|
|
||||||
// whose message contained "socket-query" → matched the circuit-breaker's
|
|
||||||
// "socket" pattern → incorrectly tripped the breaker after 5 timeouts.
|
|
||||||
const responsePromise = waitForMessage<any>(msgId, timeoutMs)
|
const responsePromise = waitForMessage<any>(msgId, timeoutMs)
|
||||||
// Prevent unhandled-rejection if sendNode throws before we reach
|
// Prevent unhandled-rejection if sendNode throws before we reach
|
||||||
// `await responsePromise` below. The error from sendNode still propagates
|
// `await responsePromise` below. The error from sendNode still propagates
|
||||||
@@ -372,23 +305,17 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/** send a query with circuit breaker protection */
|
/**
|
||||||
|
* Send a query (iq stanza) and wait for its response.
|
||||||
|
*
|
||||||
|
* Replaces the previous queryCircuitBreaker wrapping (state-machine that
|
||||||
|
* blocked ALL queries for 30s after 5 failures). The cascade behavior
|
||||||
|
* was incompatible with WhatsApp Android's empirical retry pattern:
|
||||||
|
* each operation retries independently with exponential backoff, no
|
||||||
|
* global state. Callers that need retry semantics wrap query() with
|
||||||
|
* withBoundedRetry() at their level (assertSessions, etc.).
|
||||||
|
*/
|
||||||
const query = async (node: BinaryNode, timeoutMs?: number) => {
|
const query = async (node: BinaryNode, timeoutMs?: number) => {
|
||||||
// If circuit breaker is enabled, wrap the query
|
|
||||||
if (queryCircuitBreaker) {
|
|
||||||
try {
|
|
||||||
return await queryCircuitBreaker.execute(() => queryInternal(node, timeoutMs))
|
|
||||||
} catch (error) {
|
|
||||||
// If circuit is open, log and rethrow with context
|
|
||||||
if (error instanceof CircuitOpenError) {
|
|
||||||
logger.warn({ circuitName: error.circuitName, state: error.state }, 'Query blocked by circuit breaker')
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback to direct query if circuit breaker is disabled
|
|
||||||
return queryInternal(node, timeoutMs)
|
return queryInternal(node, timeoutMs)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -634,8 +561,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
|
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
|
||||||
|
|
||||||
logger.info({ browser, helloMsg }, 'connected to WA')
|
|
||||||
|
|
||||||
const init = proto.HandshakeMessage.encode(helloMsg).finish()
|
const init = proto.HandshakeMessage.encode(helloMsg).finish()
|
||||||
|
|
||||||
const result = await awaitNextMessage<Uint8Array>(init)
|
const result = await awaitNextMessage<Uint8Array>(init)
|
||||||
@@ -687,30 +612,33 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
let lastUploadTime = 0
|
let lastUploadTime = 0
|
||||||
|
|
||||||
/** generates and uploads a set of pre-keys to the server */
|
/** generates and uploads a set of pre-keys to the server */
|
||||||
const uploadPreKeys = async (count = MIN_PREKEY_COUNT, retryCount = 0) => {
|
const uploadPreKeys = async (count = MIN_PREKEY_COUNT) => {
|
||||||
// Check if pre-key circuit breaker is open
|
// Check minimum interval. (Previously this was guarded by `retryCount === 0`
|
||||||
if (preKeyCircuitBreaker?.isOpen()) {
|
// because the function recursed on retry; with bounded-retry handling
|
||||||
logger.warn('PreKey circuit breaker is open, skipping upload')
|
// retries internally there is no recursion and the guard is implicit.)
|
||||||
throw new CircuitOpenError('socket-prekey', 'open')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check minimum interval (except for retries)
|
|
||||||
if (retryCount === 0) {
|
|
||||||
const timeSinceLastUpload = Date.now() - lastUploadTime
|
const timeSinceLastUpload = Date.now() - lastUploadTime
|
||||||
if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
|
if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
|
||||||
logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`)
|
logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Prevent multiple concurrent uploads
|
// Prevent multiple concurrent uploads — if one is already running, wait for it and return:
|
||||||
|
// the concurrent upload already replenished the pool, so there is nothing left to do.
|
||||||
if (uploadPreKeysPromise) {
|
if (uploadPreKeysPromise) {
|
||||||
logger.debug('Pre-key upload already in progress, waiting for completion')
|
logger.debug('Pre-key upload already in progress, waiting for completion')
|
||||||
await uploadPreKeysPromise
|
await uploadPreKeysPromise
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Shared abort controller so the outer Promise.race can cancel the
|
||||||
|
// in-flight bounded-retry loop if its own timeout fires first.
|
||||||
|
// Without this, the outer race rejects but the bounded-retry loop
|
||||||
|
// keeps running in the background, mutating lastUploadTime / logs
|
||||||
|
// after the caller has given up (CodeRabbit + Copilot reviews).
|
||||||
|
const uploadAbort = new AbortController()
|
||||||
|
|
||||||
const uploadLogic = async () => {
|
const uploadLogic = async () => {
|
||||||
logger.info({ count, retryCount }, 'uploading pre-keys')
|
logger.info({ count }, 'uploading pre-keys')
|
||||||
|
|
||||||
// Generate and save pre-keys atomically (prevents ID collisions on retry)
|
// Generate and save pre-keys atomically (prevents ID collisions on retry)
|
||||||
const node = await keys.transaction(async () => {
|
const node = await keys.transaction(async () => {
|
||||||
@@ -721,45 +649,69 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
return node // Only return node since update is already used
|
return node // Only return node since update is already used
|
||||||
}, creds?.me?.id || 'upload-pre-keys')
|
}, creds?.me?.id || 'upload-pre-keys')
|
||||||
|
|
||||||
// Upload to server with circuit breaker protection
|
// Upload to server. Bounded-retry handles backoff (replaces both
|
||||||
const uploadToServer = async () => {
|
// the previous circuit breaker AND the manual exponential backoff
|
||||||
await query(node)
|
// retry loop with maxRetries=3).
|
||||||
|
//
|
||||||
|
// CRITICAL: query() returns `undefined` on timeout (it does NOT
|
||||||
|
// throw — see waitForMessage). If we just `await query(node)`,
|
||||||
|
// a timed-out upload would resolve with undefined and bounded-retry
|
||||||
|
// would treat it as success. Validate the response shape so a
|
||||||
|
// timeout actually triggers a retry (CodeRabbit review on PR #393).
|
||||||
|
//
|
||||||
|
// bounded-retry's ttlMs MUST be < UPLOAD_TIMEOUT (the outer
|
||||||
|
// Promise.race below). With margin (28s vs 30s) bounded-retry
|
||||||
|
// always reaches its natural give-up first. We additionally pass
|
||||||
|
// an AbortController signal so that if the outer race ever fires
|
||||||
|
// first, the bounded-retry loop is aborted and does not keep
|
||||||
|
// running in the background (CodeRabbit + Copilot reviews).
|
||||||
|
const PER_ATTEMPT_TIMEOUT_MS = 8_000
|
||||||
|
const RETRY_TTL_MS = UPLOAD_TIMEOUT - 2_000
|
||||||
|
|
||||||
|
const uploadToServer = async (signal?: AbortSignal) => {
|
||||||
|
const result = await query(node, PER_ATTEMPT_TIMEOUT_MS)
|
||||||
|
if (signal?.aborted) {
|
||||||
|
throw new Error('aborted')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
// query() returned undefined → underlying iq response
|
||||||
|
// timed out. Throw so bounded-retry retries.
|
||||||
|
throw new Boom('Pre-key upload query timed out (no response)', { statusCode: 408 })
|
||||||
|
}
|
||||||
|
|
||||||
logger.info({ count }, 'uploaded pre-keys successfully')
|
logger.info({ count }, 'uploaded pre-keys successfully')
|
||||||
lastUploadTime = Date.now()
|
lastUploadTime = Date.now()
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Use circuit breaker if available
|
await withBoundedRetry(uploadToServer, {
|
||||||
if (preKeyCircuitBreaker) {
|
name: 'uploadPreKeys',
|
||||||
await preKeyCircuitBreaker.execute(uploadToServer)
|
// 1s -> 2s -> 4s -> 8s (cap). Max 4 attempts fit comfortably
|
||||||
} else {
|
// within RETRY_TTL_MS (28s) given perAttemptTimeoutMs=8s.
|
||||||
await uploadToServer()
|
delays: [1000, 2000, 4000, 8000],
|
||||||
}
|
ttlMs: RETRY_TTL_MS,
|
||||||
|
perAttemptTimeoutMs: PER_ATTEMPT_TIMEOUT_MS,
|
||||||
|
signal: uploadAbort.signal,
|
||||||
|
logger
|
||||||
|
})
|
||||||
} catch (uploadError) {
|
} catch (uploadError) {
|
||||||
logger.error({ uploadError: (uploadError as Error).toString(), count }, 'Failed to upload pre-keys to server')
|
logger.error({ uploadError: (uploadError as Error).toString(), count }, 'Failed to upload pre-keys to server')
|
||||||
|
|
||||||
// Don't retry if circuit breaker is open
|
|
||||||
if (uploadError instanceof CircuitOpenError) {
|
|
||||||
throw uploadError
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exponential backoff retry (max 3 retries)
|
|
||||||
if (retryCount < 3) {
|
|
||||||
const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000)
|
|
||||||
logger.info(`Retrying pre-key upload in ${backoffDelay}ms`)
|
|
||||||
await new Promise(resolve => setTimeout(resolve, backoffDelay))
|
|
||||||
return uploadPreKeys(count, retryCount + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
throw uploadError
|
throw uploadError
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add timeout protection
|
// Outer timeout protection. With ttlMs=28s vs UPLOAD_TIMEOUT=30s,
|
||||||
|
// bounded-retry should always win — but if anything ever blocks
|
||||||
|
// uploadLogic outside bounded-retry's reach, this race aborts the
|
||||||
|
// whole thing cleanly via uploadAbort.
|
||||||
uploadPreKeysPromise = Promise.race([
|
uploadPreKeysPromise = Promise.race([
|
||||||
uploadLogic(),
|
uploadLogic(),
|
||||||
new Promise<void>((_, reject) =>
|
new Promise<void>((_, reject) =>
|
||||||
setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT)
|
setTimeout(() => {
|
||||||
|
uploadAbort.abort()
|
||||||
|
reject(new Boom('Pre-key upload timeout', { statusCode: 408 }))
|
||||||
|
}, UPLOAD_TIMEOUT)
|
||||||
)
|
)
|
||||||
])
|
])
|
||||||
|
|
||||||
@@ -786,14 +738,15 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
try {
|
try {
|
||||||
let count = 0
|
let count = 0
|
||||||
const preKeyCount = await getAvailablePreKeysOnServer()
|
const preKeyCount = await getAvailablePreKeysOnServer()
|
||||||
if (preKeyCount === 0) count = INITIAL_PREKEY_COUNT
|
// How many to upload: top-up to INITIAL_PREKEY_COUNT from whatever remains on server
|
||||||
else count = MIN_PREKEY_COUNT
|
count = Math.max(0, INITIAL_PREKEY_COUNT - preKeyCount)
|
||||||
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists()
|
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists()
|
||||||
|
|
||||||
logger.info(`${preKeyCount} pre-keys found on server`)
|
logger.info(`${preKeyCount} pre-keys found on server`)
|
||||||
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`)
|
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`)
|
||||||
|
|
||||||
const lowServerCount = preKeyCount <= count
|
// Trigger upload when below the replenishment threshold, not when count < topUp amount
|
||||||
|
const lowServerCount = preKeyCount < MIN_PREKEY_COUNT
|
||||||
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
|
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
|
||||||
|
|
||||||
const shouldUpload = lowServerCount || missingCurrentPreKey
|
const shouldUpload = lowServerCount || missingCurrentPreKey
|
||||||
@@ -1153,7 +1106,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
// Decrement active connections
|
// Decrement active connections
|
||||||
decrementActiveConnections()
|
decrementActiveConnections()
|
||||||
|
|
||||||
clearInterval(keepAliveReq)
|
clearTimeout(keepAliveReq)
|
||||||
clearTimeout(qrTimer)
|
clearTimeout(qrTimer)
|
||||||
|
|
||||||
// Clear offline-buffer safety timer so its callback cannot call ev.flush()
|
// Clear offline-buffer safety timer so its callback cannot call ev.flush()
|
||||||
@@ -1230,12 +1183,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
cleanupPreKeyAutoSync()
|
cleanupPreKeyAutoSync()
|
||||||
cleanupSessionTTL()
|
cleanupSessionTTL()
|
||||||
|
|
||||||
// CRITICAL: Destroy circuit breakers AFTER cleanup functions complete
|
|
||||||
// This ensures cleanup functions can still use circuit breakers if needed
|
|
||||||
queryCircuitBreaker?.destroy()
|
|
||||||
connectionCircuitBreaker?.destroy()
|
|
||||||
preKeyCircuitBreaker?.destroy()
|
|
||||||
|
|
||||||
// IMPORTANT: Do NOT use removeAllListeners('connection.update')
|
// IMPORTANT: Do NOT use removeAllListeners('connection.update')
|
||||||
// It would remove consumer listeners, breaking their reconnection logic
|
// It would remove consumer listeners, breaking their reconnection logic
|
||||||
}
|
}
|
||||||
@@ -1264,8 +1211,16 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const startKeepAliveRequest = () =>
|
const startKeepAliveRequest = () => {
|
||||||
(keepAliveReq = setInterval(() => {
|
// Use recursive setTimeout with ±15% jitter to match WA Desktop behaviour
|
||||||
|
// (WA Business Desktop: ~25-30s intervals with natural variance)
|
||||||
|
const scheduleNextKeepAlive = () => {
|
||||||
|
const jitter = keepAliveIntervalMs * 0.15
|
||||||
|
const delay = keepAliveIntervalMs + Math.floor((Math.random() * 2 - 1) * jitter)
|
||||||
|
keepAliveReq = setTimeout(onKeepAliveTick, delay)
|
||||||
|
}
|
||||||
|
|
||||||
|
const onKeepAliveTick = () => {
|
||||||
if (!lastDateRecv) {
|
if (!lastDateRecv) {
|
||||||
lastDateRecv = new Date()
|
lastDateRecv = new Date()
|
||||||
}
|
}
|
||||||
@@ -1277,13 +1232,15 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
*/
|
*/
|
||||||
if (diff > keepAliveIntervalMs + 5000) {
|
if (diff > keepAliveIntervalMs + 5000) {
|
||||||
void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
|
void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
|
||||||
|
return // connection closing — do not reschedule
|
||||||
} else if (ws.isOpen) {
|
} else if (ws.isOpen) {
|
||||||
// Send keep-alive ping via sendNode() (fire-and-forget) instead of query().
|
// Send keep-alive ping via sendNode() (fire-and-forget) instead of query().
|
||||||
// query() wraps the ping in the query circuit breaker — when that breaker is
|
// We don't need the response correlator overhead — WA's pong arrives as an
|
||||||
// open or timing out, the ping is never sent, WA never responds, lastDateRecv
|
// incoming frame and updates lastDateRecv via the standard receive path.
|
||||||
// goes stale, and the diff check above wrongly fires "Connection was lost".
|
// (Historical context: this used to bypass the query circuit breaker,
|
||||||
// sendNode() bypasses the query circuit breaker entirely; WA's ping response
|
// which would block pings during cascade failures. Circuit breaker has
|
||||||
// still arrives as an incoming frame and updates lastDateRecv normally.
|
// since been replaced by per-operation bounded-retry — but the
|
||||||
|
// fire-and-forget pattern stays correct on its own merits.)
|
||||||
sendNode({
|
sendNode({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
attrs: {
|
attrs: {
|
||||||
@@ -1299,7 +1256,15 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
} else {
|
} else {
|
||||||
logger.warn('keep alive called when WS not open')
|
logger.warn('keep alive called when WS not open')
|
||||||
}
|
}
|
||||||
}, keepAliveIntervalMs))
|
|
||||||
|
// Do not reschedule once shutdown has started (closed set by end() on any concurrent path)
|
||||||
|
if (!closed) {
|
||||||
|
scheduleNextKeepAlive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleNextKeepAlive()
|
||||||
|
}
|
||||||
/** i have no idea why this exists. pls enlighten me */
|
/** i have no idea why this exists. pls enlighten me */
|
||||||
const sendPassiveIq = (tag: 'passive' | 'active') =>
|
const sendPassiveIq = (tag: 'passive' | 'active') =>
|
||||||
query({
|
query({
|
||||||
@@ -1352,6 +1317,25 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
||||||
name: '~'
|
name: '~'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pair code companion_platform_id must be Chrome (1) when using Android
|
||||||
|
// browser preset. ANDROID_PHONE (16) causes silent timeout (server ignores),
|
||||||
|
// UWP (21) causes "cannot connect device" rejection. Only Chrome (1) works
|
||||||
|
// for pair code via web protocol (WA\x06\x03). The device still appears as
|
||||||
|
// "Android" in linked devices because DeviceProps.platformType=ANDROID_PHONE
|
||||||
|
// is set separately in the registration node.
|
||||||
|
const isAndroid = isAndroidBrowser(browser)
|
||||||
|
const pairPlatformId = isAndroid ? getPlatformId('Chrome') : getPlatformId(browser[1])
|
||||||
|
const pairPlatformDisplay = isAndroid ? 'Chrome (Mac OS)' : `${browser[1]} (${browser[0]})`
|
||||||
|
|
||||||
|
logger.info({
|
||||||
|
pairCode: pairingCode,
|
||||||
|
jid: authState.creds.me.id,
|
||||||
|
companionPlatformId: pairPlatformId,
|
||||||
|
companionPlatformDisplay: pairPlatformDisplay,
|
||||||
|
isAndroid,
|
||||||
|
}, `pair code requested | companion: ${pairPlatformDisplay} | ${isAndroid ? 'android override -> Chrome' : 'native platform'}`)
|
||||||
|
|
||||||
ev.emit('creds.update', authState.creds)
|
ev.emit('creds.update', authState.creds)
|
||||||
await sendNode({
|
await sendNode({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
@@ -1384,12 +1368,12 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
{
|
{
|
||||||
tag: 'companion_platform_id',
|
tag: 'companion_platform_id',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: getPlatformId(browser[1])
|
content: pairPlatformId
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'companion_platform_display',
|
tag: 'companion_platform_display',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: `${browser[1]} (${browser[0]})`
|
content: pairPlatformDisplay
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'link_code_pairing_nonce',
|
tag: 'link_code_pairing_nonce',
|
||||||
@@ -1519,7 +1503,9 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
// login complete
|
// login complete
|
||||||
ws.on('CB:success', async (node: BinaryNode) => {
|
ws.on('CB:success', async (node: BinaryNode) => {
|
||||||
logger.info('opened connection to WA')
|
const isAndroid = isAndroidBrowser(browser)
|
||||||
|
const phoneId = authState.creds.me?.id?.split(':')[0]?.split('@')[0] || 'new session'
|
||||||
|
logger.info(`${isAndroid ? '\uD83D\uDCF1' : '\uD83D\uDDA5\uFE0F'} Connected to WA | ${phoneId} | platform: ${isAndroid ? 'SMB_ANDROID' : 'MACOS'} | device: ${isAndroid ? 'Android' : 'Desktop'} | platformType: ${isAndroid ? 'ANDROID_PHONE' : 'CHROME'}`)
|
||||||
clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
|
clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
|
||||||
|
|
||||||
ev.emit('creds.update', { me: { ...authState.creds.me!, lid: node.attrs.lid } })
|
ev.emit('creds.update', { me: { ...authState.creds.me!, lid: node.attrs.lid } })
|
||||||
@@ -1667,8 +1653,8 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
// already-authenticated session (no QR re-scan needed). In this case we skip
|
// already-authenticated session (no QR re-scan needed). In this case we skip
|
||||||
// the offline buffer entirely so live messages are not held hostage waiting for the
|
// the offline buffer entirely so live messages are not held hostage waiting for the
|
||||||
// server to finish flushing the pending-message backlog (CB:ib,,offline).
|
// server to finish flushing the pending-message backlog (CB:ib,,offline).
|
||||||
// For normal restarts (no stale routingInfo) the standard 5 s safety cap applies.
|
// For normal restarts (no stale routingInfo) the standard 2 s safety cap applies.
|
||||||
const OFFLINE_BUFFER_TIMEOUT_MS = 5_000
|
const OFFLINE_BUFFER_TIMEOUT_MS = 2_000
|
||||||
let offlineBufferTimeout: NodeJS.Timeout | undefined
|
let offlineBufferTimeout: NodeJS.Timeout | undefined
|
||||||
|
|
||||||
process.nextTick(() => {
|
process.nextTick(() => {
|
||||||
@@ -1770,25 +1756,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
sendWAMBuffer,
|
sendWAMBuffer,
|
||||||
executeUSyncQuery,
|
executeUSyncQuery,
|
||||||
onWhatsApp,
|
onWhatsApp,
|
||||||
// Circuit breaker utilities
|
|
||||||
circuitBreakers: {
|
|
||||||
query: queryCircuitBreaker,
|
|
||||||
connection: connectionCircuitBreaker,
|
|
||||||
preKey: preKeyCircuitBreaker
|
|
||||||
},
|
|
||||||
/** Get circuit breaker statistics */
|
|
||||||
getCircuitBreakerStats: () => ({
|
|
||||||
query: queryCircuitBreaker?.getStats(),
|
|
||||||
connection: connectionCircuitBreaker?.getStats(),
|
|
||||||
preKey: preKeyCircuitBreaker?.getStats()
|
|
||||||
}),
|
|
||||||
/** Reset all circuit breakers to closed state */
|
|
||||||
resetCircuitBreakers: () => {
|
|
||||||
queryCircuitBreaker?.reset()
|
|
||||||
connectionCircuitBreaker?.reset()
|
|
||||||
preKeyCircuitBreaker?.reset()
|
|
||||||
logger.info('All circuit breakers reset to closed state')
|
|
||||||
},
|
|
||||||
// Unified Session Telemetry
|
// Unified Session Telemetry
|
||||||
/** Send unified_session telemetry manually */
|
/** Send unified_session telemetry manually */
|
||||||
sendUnifiedSession,
|
sendUnifiedSession,
|
||||||
|
|||||||
+1
-1
@@ -80,7 +80,7 @@ export type SignalDataTypeMap = {
|
|||||||
'app-state-sync-version': LTHashState
|
'app-state-sync-version': LTHashState
|
||||||
'lid-mapping': string
|
'lid-mapping': string
|
||||||
'device-list': string[]
|
'device-list': string[]
|
||||||
tctoken: { token: Buffer; timestamp?: string; senderTimestamp?: number }
|
tctoken: { token: Buffer; timestamp?: string; senderTimestamp?: number; realIssueTimestamp?: number | null }
|
||||||
/** Identity key for Signal Protocol - used for detecting contact reinstalls */
|
/** Identity key for Signal Protocol - used for detecting contact reinstalls */
|
||||||
'identity-key': Uint8Array
|
'identity-key': Uint8Array
|
||||||
}
|
}
|
||||||
|
|||||||
+43
-1
@@ -1,4 +1,30 @@
|
|||||||
export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate'
|
export type WACallUpdateType =
|
||||||
|
| 'offer'
|
||||||
|
| 'ringing'
|
||||||
|
| 'timeout'
|
||||||
|
| 'reject'
|
||||||
|
| 'accept'
|
||||||
|
| 'terminate'
|
||||||
|
| 'preaccept'
|
||||||
|
| 'transport'
|
||||||
|
| 'relaylatency'
|
||||||
|
| 'group_update'
|
||||||
|
| 'reminder'
|
||||||
|
| 'heartbeat'
|
||||||
|
| 'mute_v2'
|
||||||
|
| 'enc_rekey'
|
||||||
|
| 'video'
|
||||||
|
| 'relay'
|
||||||
|
|
||||||
|
export type WACallParticipant = {
|
||||||
|
jid?: string
|
||||||
|
/** 'connected' | 'invited' | 'left' etc. */
|
||||||
|
state?: string
|
||||||
|
/** Phone number in s.whatsapp.net format */
|
||||||
|
userPn?: string
|
||||||
|
/** 'admin' for group call link creator */
|
||||||
|
type?: string
|
||||||
|
}
|
||||||
|
|
||||||
export type WACallEvent = {
|
export type WACallEvent = {
|
||||||
chatId: string
|
chatId: string
|
||||||
@@ -13,4 +39,20 @@ export type WACallEvent = {
|
|||||||
latencyMs?: number
|
latencyMs?: number
|
||||||
/** Phone number of the caller (sanitized to fix Brazilian landline bug) */
|
/** Phone number of the caller (sanitized to fix Brazilian landline bug) */
|
||||||
callerPn?: string
|
callerPn?: string
|
||||||
|
/** Call link token (forms URL: https://call.whatsapp.com/video/<token>) */
|
||||||
|
linkToken?: string
|
||||||
|
/** JID of who created the call link */
|
||||||
|
linkCreator?: string
|
||||||
|
/** Phone number of link creator */
|
||||||
|
linkCreatorPn?: string
|
||||||
|
/** Media type: 'video' or 'audio' */
|
||||||
|
media?: string
|
||||||
|
/** Max participants for group/link calls */
|
||||||
|
connectedLimit?: number
|
||||||
|
/** Participants in a group/link call */
|
||||||
|
participants?: WACallParticipant[]
|
||||||
|
/** Call duration in ms (from terminate/call_summary) */
|
||||||
|
duration?: number
|
||||||
|
/** Terminate reason (e.g. 'group_call_ended', 'accepted_elsewhere', 'timeout') */
|
||||||
|
terminateReason?: string
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ export interface Contact {
|
|||||||
name?: string
|
name?: string
|
||||||
/** name of the contact, the contact has set on their own on WA */
|
/** name of the contact, the contact has set on their own on WA */
|
||||||
notify?: string
|
notify?: string
|
||||||
|
/** username associated with this contact, when provided by WA */
|
||||||
|
username?: string
|
||||||
/** I have no idea */
|
/** I have no idea */
|
||||||
verifiedName?: string
|
verifiedName?: string
|
||||||
// Baileys Added
|
// Baileys Added
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ export type BaileysEventMap = {
|
|||||||
chats: Chat[]
|
chats: Chat[]
|
||||||
contacts: Contact[]
|
contacts: Contact[]
|
||||||
messages: WAMessage[]
|
messages: WAMessage[]
|
||||||
|
/** Past participants for group chats (people who left/were removed). userJid is always a phone number (PN), never a LID. */
|
||||||
|
pastParticipants?: proto.IPastParticipants[] | null
|
||||||
isLatest?: boolean
|
isLatest?: boolean
|
||||||
progress?: number | null
|
progress?: number | null
|
||||||
syncType?: proto.HistorySync.HistorySyncType | null
|
syncType?: proto.HistorySync.HistorySyncType | null
|
||||||
@@ -79,6 +81,7 @@ export type BaileysEventMap = {
|
|||||||
id: string
|
id: string
|
||||||
author: string
|
author: string
|
||||||
authorPn?: string
|
authorPn?: string
|
||||||
|
authorUsername?: string
|
||||||
participants: GroupParticipant[]
|
participants: GroupParticipant[]
|
||||||
action: ParticipantAction
|
action: ParticipantAction
|
||||||
}
|
}
|
||||||
@@ -86,6 +89,7 @@ export type BaileysEventMap = {
|
|||||||
id: string
|
id: string
|
||||||
author: string
|
author: string
|
||||||
authorPn?: string
|
authorPn?: string
|
||||||
|
authorUsername?: string
|
||||||
participant: string
|
participant: string
|
||||||
participantPn?: string
|
participantPn?: string
|
||||||
action: RequestJoinAction
|
action: RequestJoinAction
|
||||||
@@ -185,6 +189,8 @@ export type BufferedEventData = {
|
|||||||
chats: { [jid: string]: Chat }
|
chats: { [jid: string]: Chat }
|
||||||
contacts: { [jid: string]: Contact }
|
contacts: { [jid: string]: Contact }
|
||||||
messages: { [uqId: string]: WAMessage }
|
messages: { [uqId: string]: WAMessage }
|
||||||
|
/** Keyed by groupJid for O(1) deduplication across chunks */
|
||||||
|
pastParticipants: { [groupJid: string]: proto.IPastParticipant[] }
|
||||||
empty: boolean
|
empty: boolean
|
||||||
isLatest: boolean
|
isLatest: boolean
|
||||||
progress?: number | null
|
progress?: number | null
|
||||||
|
|||||||
@@ -20,17 +20,20 @@ export interface GroupMetadata {
|
|||||||
addressingMode?: WAMessageAddressingMode
|
addressingMode?: WAMessageAddressingMode
|
||||||
owner: string | undefined
|
owner: string | undefined
|
||||||
ownerPn?: string | undefined
|
ownerPn?: string | undefined
|
||||||
|
ownerUsername?: string | undefined
|
||||||
owner_country_code?: string | undefined
|
owner_country_code?: string | undefined
|
||||||
subject: string
|
subject: string
|
||||||
/** group subject owner */
|
/** group subject owner */
|
||||||
subjectOwner?: string
|
subjectOwner?: string
|
||||||
subjectOwnerPn?: string
|
subjectOwnerPn?: string
|
||||||
|
subjectOwnerUsername?: string
|
||||||
/** group subject modification date */
|
/** group subject modification date */
|
||||||
subjectTime?: number
|
subjectTime?: number
|
||||||
creation?: number
|
creation?: number
|
||||||
desc?: string
|
desc?: string
|
||||||
descOwner?: string
|
descOwner?: string
|
||||||
descOwnerPn?: string
|
descOwnerPn?: string
|
||||||
|
descOwnerUsername?: string
|
||||||
descId?: string
|
descId?: string
|
||||||
descTime?: number
|
descTime?: number
|
||||||
/** if this group is part of a community, it returns the jid of the community to which it belongs */
|
/** if this group is part of a community, it returns the jid of the community to which it belongs */
|
||||||
@@ -56,6 +59,7 @@ export interface GroupMetadata {
|
|||||||
/** the person who added you to group or changed some setting in group */
|
/** the person who added you to group or changed some setting in group */
|
||||||
author?: string
|
author?: string
|
||||||
authorPn?: string
|
authorPn?: string
|
||||||
|
authorUsername?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WAGroupCreateResponse {
|
export interface WAGroupCreateResponse {
|
||||||
|
|||||||
+18
-3
@@ -19,7 +19,9 @@ export type WAContactMessage = proto.Message.IContactMessage
|
|||||||
export type WAContactsArrayMessage = proto.Message.IContactsArrayMessage
|
export type WAContactsArrayMessage = proto.Message.IContactsArrayMessage
|
||||||
export type WAMessageKey = proto.IMessageKey & {
|
export type WAMessageKey = proto.IMessageKey & {
|
||||||
remoteJidAlt?: string
|
remoteJidAlt?: string
|
||||||
|
remoteJidUsername?: string
|
||||||
participantAlt?: string
|
participantAlt?: string
|
||||||
|
participantUsername?: string
|
||||||
server_id?: string
|
server_id?: string
|
||||||
addressingMode?: string
|
addressingMode?: string
|
||||||
isViewOnce?: boolean // TODO: remove out of the message key, place in WebMessageInfo
|
isViewOnce?: boolean // TODO: remove out of the message key, place in WebMessageInfo
|
||||||
@@ -54,12 +56,14 @@ export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL
|
|||||||
* Individual sticker in a sticker pack
|
* Individual sticker in a sticker pack
|
||||||
*/
|
*/
|
||||||
export type Sticker = {
|
export type Sticker = {
|
||||||
/** Buffer, Stream or URL of the sticker image (will be converted to WebP if needed) */
|
/** Buffer, Stream or URL of the sticker image (WebP or Lottie/WAS format) */
|
||||||
data: WAMediaUpload
|
data: WAMediaUpload
|
||||||
/** Array of emojis associated with this sticker (max 3 recommended per WhatsApp standards) */
|
/** Array of emojis associated with this sticker (max 3 recommended per WhatsApp standards) */
|
||||||
emojis?: string[]
|
emojis?: string[]
|
||||||
/** Accessibility label for screen readers (max 125 chars for static, 255 for animated) */
|
/** Accessibility label for screen readers (max 125 chars for static, 255 for animated) */
|
||||||
accessibilityLabel?: string
|
accessibilityLabel?: string
|
||||||
|
/** Force Lottie format detection (auto-detected if omitted) */
|
||||||
|
isLottie?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -153,6 +157,7 @@ export type MessageReceiptType =
|
|||||||
| 'sender'
|
| 'sender'
|
||||||
| 'inactive'
|
| 'inactive'
|
||||||
| 'played'
|
| 'played'
|
||||||
|
| 'view_once_read'
|
||||||
| undefined
|
| undefined
|
||||||
|
|
||||||
export type MediaConnInfo = {
|
export type MediaConnInfo = {
|
||||||
@@ -176,6 +181,8 @@ export interface WAUrlInfo {
|
|||||||
type Mentionable = {
|
type Mentionable = {
|
||||||
/** list of jids that are mentioned in the accompanying text */
|
/** list of jids that are mentioned in the accompanying text */
|
||||||
mentions?: string[]
|
mentions?: string[]
|
||||||
|
/** mention all participants in the group */
|
||||||
|
mentionAll?: boolean
|
||||||
}
|
}
|
||||||
type Contextable = {
|
type Contextable = {
|
||||||
/** add contextInfo to the message */
|
/** add contextInfo to the message */
|
||||||
@@ -988,8 +995,16 @@ export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions &
|
|||||||
|
|
||||||
export type WAMediaUploadFunction = (
|
export type WAMediaUploadFunction = (
|
||||||
encFilePath: string,
|
encFilePath: string,
|
||||||
opts: { fileEncSha256B64: string; mediaType: MediaType; timeoutMs?: number }
|
opts: { fileEncSha256B64: string; mediaType: MediaType; timeoutMs?: number; newsletter?: boolean }
|
||||||
) => Promise<{ mediaUrl: string; directPath: string; meta_hmac?: string; ts?: number; fbid?: number }>
|
) => Promise<{
|
||||||
|
mediaUrl: string | undefined
|
||||||
|
directPath: string
|
||||||
|
meta_hmac?: string
|
||||||
|
ts?: number
|
||||||
|
fbid?: number
|
||||||
|
thumbnailDirectPath?: string
|
||||||
|
thumbnailSha256?: string
|
||||||
|
}>
|
||||||
|
|
||||||
export type MediaGenerationOptions = {
|
export type MediaGenerationOptions = {
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ export enum XWAPaths {
|
|||||||
xwa2_newsletter_view = 'xwa2_newsletter_view',
|
xwa2_newsletter_view = 'xwa2_newsletter_view',
|
||||||
xwa2_newsletter_metadata = 'xwa2_newsletter',
|
xwa2_newsletter_metadata = 'xwa2_newsletter',
|
||||||
xwa2_newsletter_admin_count = 'xwa2_newsletter_admin',
|
xwa2_newsletter_admin_count = 'xwa2_newsletter_admin',
|
||||||
xwa2_newsletter_mute_v2 = 'xwa2_newsletter_mute_v2',
|
xwa2_newsletter_mute_v2 = 'xwa2_newsletter_update_user_setting',
|
||||||
xwa2_newsletter_unmute_v2 = 'xwa2_newsletter_unmute_v2',
|
xwa2_newsletter_unmute_v2 = 'xwa2_newsletter_update_user_setting',
|
||||||
xwa2_newsletter_follow = 'xwa2_newsletter_follow',
|
xwa2_newsletter_follow = 'xwa2_newsletter_join_v2',
|
||||||
xwa2_newsletter_unfollow = 'xwa2_newsletter_unfollow',
|
xwa2_newsletter_unfollow = 'xwa2_newsletter_leave_v2',
|
||||||
xwa2_newsletter_change_owner = 'xwa2_newsletter_change_owner',
|
xwa2_newsletter_change_owner = 'xwa2_newsletter_change_owner',
|
||||||
xwa2_newsletter_demote = 'xwa2_newsletter_demote',
|
xwa2_newsletter_demote = 'xwa2_newsletter_demote',
|
||||||
xwa2_newsletter_delete_v2 = 'xwa2_newsletter_delete_v2'
|
xwa2_newsletter_delete_v2 = 'xwa2_newsletter_delete_v2'
|
||||||
@@ -17,10 +17,10 @@ export enum QueryIds {
|
|||||||
UPDATE_METADATA = '24250201037901610',
|
UPDATE_METADATA = '24250201037901610',
|
||||||
METADATA = '6563316087068696',
|
METADATA = '6563316087068696',
|
||||||
SUBSCRIBERS = '9783111038412085',
|
SUBSCRIBERS = '9783111038412085',
|
||||||
FOLLOW = '7871414976211147',
|
FOLLOW = '24404358912487870',
|
||||||
UNFOLLOW = '7238632346214362',
|
UNFOLLOW = '9767147403369991',
|
||||||
MUTE = '29766401636284406',
|
MUTE = '31938993655691868',
|
||||||
UNMUTE = '9864994326891137',
|
UNMUTE = '31938993655691868',
|
||||||
ADMIN_COUNT = '7130823597031706',
|
ADMIN_COUNT = '7130823597031706',
|
||||||
CHANGE_OWNER = '7341777602580933',
|
CHANGE_OWNER = '7341777602580933',
|
||||||
DEMOTE = '6551828931592903',
|
DEMOTE = '6551828931592903',
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import type { Agent } from 'https'
|
import type { Agent } from 'https'
|
||||||
import type { URL } from 'url'
|
import type { URL } from 'url'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type { CircuitBreakerOptions } from '../Utils/circuit-breaker'
|
|
||||||
import type { ILogger } from '../Utils/logger'
|
import type { ILogger } from '../Utils/logger'
|
||||||
import type { AuthenticationState, LIDMapping, SignalAuthState, TransactionCapabilityOptions } from './Auth'
|
import type { AuthenticationState, LIDMapping, SignalAuthState, TransactionCapabilityOptions } from './Auth'
|
||||||
import type { GroupMetadata } from './GroupMetadata'
|
import type { GroupMetadata } from './GroupMetadata'
|
||||||
@@ -203,23 +202,6 @@ export type SocketConfig = {
|
|||||||
pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>
|
pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>
|
||||||
) => SignalRepositoryWithLIDStore
|
) => SignalRepositoryWithLIDStore
|
||||||
|
|
||||||
// === Circuit Breaker Configuration ===
|
|
||||||
|
|
||||||
/** Enable circuit breaker protection for socket operations (default: true) */
|
|
||||||
enableCircuitBreaker?: boolean
|
|
||||||
|
|
||||||
/** Circuit breaker configuration for query operations */
|
|
||||||
queryCircuitBreaker?: Partial<CircuitBreakerOptions>
|
|
||||||
|
|
||||||
/** Circuit breaker configuration for connection operations */
|
|
||||||
connectionCircuitBreaker?: Partial<CircuitBreakerOptions>
|
|
||||||
|
|
||||||
/** Circuit breaker configuration for pre-key operations */
|
|
||||||
preKeyCircuitBreaker?: Partial<CircuitBreakerOptions>
|
|
||||||
|
|
||||||
/** Circuit breaker configuration for message operations */
|
|
||||||
messageCircuitBreaker?: Partial<CircuitBreakerOptions>
|
|
||||||
|
|
||||||
// === Listener Limits (Memory Leak Prevention) ===
|
// === Listener Limits (Memory Leak Prevention) ===
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export type BrowsersMap = {
|
|||||||
baileys(browser: string): [string, string, string]
|
baileys(browser: string): [string, string, string]
|
||||||
windows(browser: string): [string, string, string]
|
windows(browser: string): [string, string, string]
|
||||||
appropriate(browser: string): [string, string, string]
|
appropriate(browser: string): [string, string, string]
|
||||||
|
android(apiLevel: string): [string, string, string]
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum DisconnectReason {
|
export enum DisconnectReason {
|
||||||
|
|||||||
@@ -341,7 +341,18 @@ export const addTransactionCapability = (
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
// SessionError is part of the normal Bad MAC recovery flow
|
||||||
|
// (retry receipt → sender resends as pkmsg → new session within ~1.3s).
|
||||||
|
// Logging it as ERROR creates 2 noise lines per recoverable Bad MAC cycle.
|
||||||
|
// Downgrade to debug for SessionError; keep ERROR for everything else.
|
||||||
|
// The error is still re-thrown — recovery behavior is unchanged.
|
||||||
|
const errName = (error as { name?: string })?.name
|
||||||
|
if (errName === 'SessionError') {
|
||||||
|
logger.debug({ error }, 'transaction failed (SessionError — recoverable via retry receipt)')
|
||||||
|
} else {
|
||||||
logger.error({ error }, 'transaction failed, rolling back')
|
logger.error({ error }, 'transaction failed, rolling back')
|
||||||
|
}
|
||||||
|
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,393 @@
|
|||||||
|
/**
|
||||||
|
* Bounded retry — WhatsApp-aligned per-operation retry without global state.
|
||||||
|
*
|
||||||
|
* # Why this exists
|
||||||
|
*
|
||||||
|
* Replaces the circuit breaker pattern that was causing cascading failures
|
||||||
|
* in production: 5 timeouts in 60s would trip the global breaker, blocking
|
||||||
|
* EVERY socket query (typing indicators, profile pic fetches, contact
|
||||||
|
* validation, presence updates) for 30s — even queries to peers that were
|
||||||
|
* perfectly healthy.
|
||||||
|
*
|
||||||
|
* # Empirical justification
|
||||||
|
*
|
||||||
|
* Captured WhatsApp Android's actual retry behavior via Frida hooks
|
||||||
|
* (`hook-circuit-breaker-re-v2.js`, `hook-retry-bounds.js`) on a real
|
||||||
|
* device under controlled WiFi off/on cycles. Findings:
|
||||||
|
*
|
||||||
|
* 1. Delay sequence (per-operation): 3s -> 10s -> 60s -> ~64s -> 120s
|
||||||
|
* (cap at 2 min). Last value reused for further attempts.
|
||||||
|
* 2. Memory profile during 5-min network outage: PSS dropped 53MB and
|
||||||
|
* stabilised. FDs closed (305 -> 295). NO unbounded accumulation.
|
||||||
|
* 3. Recovery on reconnect: ~10s. No retry storm.
|
||||||
|
* 4. NO global state machine observed. Each operation has its own timer.
|
||||||
|
* Failures of operation A do NOT block operation B.
|
||||||
|
*
|
||||||
|
* The default delays in WHATSAPP_BACKOFF_DELAYS below match the captured
|
||||||
|
* sequence directly. The default 10-min TTL is empirical 3-5 min stability
|
||||||
|
* + safety buffer.
|
||||||
|
*
|
||||||
|
* # Design properties
|
||||||
|
*
|
||||||
|
* - Per-operation isolation: each call to `withBoundedRetry` has its own
|
||||||
|
* timer. No shared state. Operation A failing has zero effect on B.
|
||||||
|
* - Bounded by `ttlMs` (wall-clock budget). The TTL is enforced strictly
|
||||||
|
* at three points: (a) before each attempt, (b) cap on per-attempt
|
||||||
|
* timeout, (c) cap on retry delay.
|
||||||
|
* - Per-attempt timeout: each attempt has its own deadline (default 30s),
|
||||||
|
* automatically capped to remaining TTL budget so total runtime never
|
||||||
|
* exceeds ttlMs.
|
||||||
|
* - AbortSignal cancellation: external cancellation supported, both for
|
||||||
|
* the sleep between retries AND (optionally) the in-flight operation
|
||||||
|
* when the operation accepts a signal parameter.
|
||||||
|
* - Memory bound: at most one outstanding retry timer per call. Listeners
|
||||||
|
* are explicitly removed when timers settle. Once the call resolves /
|
||||||
|
* rejects / aborts, all state is freed.
|
||||||
|
*
|
||||||
|
* # Logging
|
||||||
|
*
|
||||||
|
* Pass `logger` in options to get structured logs at each retry attempt,
|
||||||
|
* give-up, and post-failure recovery. The module emits Prometheus metrics
|
||||||
|
* regardless of whether a logger is provided.
|
||||||
|
*
|
||||||
|
* # When to use this vs. plain query()
|
||||||
|
*
|
||||||
|
* - Use plain `query()` when you want fast-fail semantics (caller decides
|
||||||
|
* what to do on failure). Most call sites in InfiniteAPI use this.
|
||||||
|
* - Use `withBoundedRetry(() => query(...), { name: 'X' })` when the
|
||||||
|
* operation is "must-eventually-succeed" with no upstream retry — e.g.
|
||||||
|
* `uploadPreKeys` or other write paths where the alternative is data loss.
|
||||||
|
*
|
||||||
|
* # Examples
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* // Single attempt with 5-min TTL, give up after that:
|
||||||
|
* await withBoundedRetry(
|
||||||
|
* () => assertSessions([jid], true),
|
||||||
|
* { name: 'assertSessions', ttlMs: 5 * 60_000, logger }
|
||||||
|
* )
|
||||||
|
*
|
||||||
|
* // Tight deadline, fast give-up:
|
||||||
|
* await withBoundedRetry(
|
||||||
|
* () => sendNode(node),
|
||||||
|
* { name: 'send', ttlMs: 30_000, perAttemptTimeoutMs: 5_000 }
|
||||||
|
* )
|
||||||
|
*
|
||||||
|
* // Operation that respects abort signal (best practice):
|
||||||
|
* await withBoundedRetry(
|
||||||
|
* (signal) => fetchSomething({ signal }),
|
||||||
|
* { name: 'fetch', logger }
|
||||||
|
* )
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @module Utils/bounded-retry
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { ILogger } from './logger'
|
||||||
|
import { metrics } from './prometheus-metrics.js'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default delay sequence (milliseconds) — matches WhatsApp Android empirical
|
||||||
|
* behavior. After exhausting the sequence, the last value is used (cap).
|
||||||
|
*/
|
||||||
|
export const WHATSAPP_BACKOFF_DELAYS = [3000, 10000, 60000, 60000, 120000] as const
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default jitter (+/- 15%) to prevent thundering-herd retries.
|
||||||
|
*/
|
||||||
|
export const DEFAULT_JITTER_FACTOR = 0.15 as const
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default time-to-live for retries: 10 minutes.
|
||||||
|
*
|
||||||
|
* Empirical justification: WhatsApp Android stabilises memory in ~3-5 min
|
||||||
|
* during a network outage; 10 min gives a generous safety buffer while
|
||||||
|
* preventing unbounded retry accumulation.
|
||||||
|
*/
|
||||||
|
export const DEFAULT_TTL_MS = 10 * 60 * 1000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default per-attempt timeout: 30 seconds.
|
||||||
|
*
|
||||||
|
* Most WhatsApp queries respond within seconds. A 30s timeout is generous
|
||||||
|
* enough for slow networks but prevents a single hang from blocking retries.
|
||||||
|
*/
|
||||||
|
export const DEFAULT_PER_ATTEMPT_TIMEOUT_MS = 30000
|
||||||
|
|
||||||
|
export interface BoundedRetryOptions {
|
||||||
|
/** Operation name for logging/metrics */
|
||||||
|
name?: string
|
||||||
|
/** Sequence of delays (ms). Last value is used as cap. */
|
||||||
|
delays?: readonly number[]
|
||||||
|
/** Jitter factor 0..1 (default 0.15) */
|
||||||
|
jitter?: number
|
||||||
|
/** Total wall-clock budget — gives up after this. Default 10 min. */
|
||||||
|
ttlMs?: number
|
||||||
|
/** Per-attempt timeout (ms). Default 30s. Capped by remaining TTL. */
|
||||||
|
perAttemptTimeoutMs?: number
|
||||||
|
/** Predicate: should we retry on this error? Default: always */
|
||||||
|
shouldRetry?: (err: Error, attempt: number) => boolean
|
||||||
|
/** Hook fired before each retry */
|
||||||
|
onRetry?: (err: Error, attempt: number, delayMs: number) => void
|
||||||
|
/**
|
||||||
|
* AbortSignal — when fired, the loop stops at the next observation point:
|
||||||
|
* - If the loop is sleeping between retries, the sleep rejects immediately.
|
||||||
|
* - If an attempt is in flight, the abort is forwarded to the operation
|
||||||
|
* via the per-attempt signal. The operation must ITSELF observe the
|
||||||
|
* signal (e.g. `(signal) => fetch({ signal })`) for cancellation to
|
||||||
|
* be truly immediate; otherwise it cancels at the next per-attempt
|
||||||
|
* timeout boundary.
|
||||||
|
* - Either way, on the next loop iteration BoundedRetryAbortedError is
|
||||||
|
* thrown, so the caller never sees more than one trailing attempt
|
||||||
|
* after the abort.
|
||||||
|
*/
|
||||||
|
signal?: AbortSignal
|
||||||
|
/** Optional logger for structured retry/give-up/recovery logs */
|
||||||
|
logger?: ILogger
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BoundedRetryGiveUpError extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly opName: string,
|
||||||
|
public readonly attempts: number,
|
||||||
|
public readonly elapsedMs: number,
|
||||||
|
public readonly lastError: Error
|
||||||
|
) {
|
||||||
|
super(
|
||||||
|
`bounded-retry "${opName}" gave up after ${attempts} attempts ` +
|
||||||
|
`(${elapsedMs}ms elapsed). Last error: ${lastError.message}`
|
||||||
|
)
|
||||||
|
this.name = 'BoundedRetryGiveUpError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BoundedRetryAbortedError extends Error {
|
||||||
|
constructor(public readonly opName: string) {
|
||||||
|
super(`bounded-retry "${opName}" aborted via signal`)
|
||||||
|
this.name = 'BoundedRetryAbortedError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply jitter to a delay: returns delay * (1 +/- jitter)
|
||||||
|
*/
|
||||||
|
function withJitter(delayMs: number, jitter: number): number {
|
||||||
|
if (jitter <= 0) return delayMs
|
||||||
|
const factor = 1 + (Math.random() * 2 - 1) * jitter
|
||||||
|
return Math.max(0, Math.round(delayMs * factor))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pick the delay for a given attempt index. Falls back to the last value
|
||||||
|
* (cap) once the sequence is exhausted.
|
||||||
|
*/
|
||||||
|
function pickDelay(attempt: number, delays: readonly number[]): number {
|
||||||
|
if (delays.length === 0) return 0
|
||||||
|
if (attempt < delays.length) return delays[attempt]!
|
||||||
|
return delays[delays.length - 1]!
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap a promise with a per-attempt timeout. Aborts the supplied controller
|
||||||
|
* when the timeout fires so the caller can cancel any in-flight work
|
||||||
|
* (operations that accept the signal). Always clears the timer on settlement.
|
||||||
|
*/
|
||||||
|
function withTimeout<T>(
|
||||||
|
promise: Promise<T>,
|
||||||
|
timeoutMs: number,
|
||||||
|
name: string,
|
||||||
|
abortOnTimeout: AbortController
|
||||||
|
): Promise<T> {
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
abortOnTimeout.abort()
|
||||||
|
reject(new Error(`bounded-retry "${name}" attempt timed out after ${timeoutMs}ms`))
|
||||||
|
}, timeoutMs)
|
||||||
|
promise
|
||||||
|
.then(value => {
|
||||||
|
clearTimeout(timer)
|
||||||
|
resolve(value)
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
clearTimeout(timer)
|
||||||
|
reject(err as Error)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sleep with abort support. Always removes the abort listener on settlement
|
||||||
|
* so listeners do not accumulate on long-lived signals.
|
||||||
|
*/
|
||||||
|
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (signal?.aborted) {
|
||||||
|
reject(new Error('aborted'))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let onAbort: (() => void) | undefined
|
||||||
|
const cleanup = () => {
|
||||||
|
if (onAbort && signal) {
|
||||||
|
signal.removeEventListener('abort', onAbort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
cleanup()
|
||||||
|
resolve()
|
||||||
|
}, ms)
|
||||||
|
|
||||||
|
if (signal) {
|
||||||
|
onAbort = () => {
|
||||||
|
clearTimeout(timer)
|
||||||
|
cleanup()
|
||||||
|
reject(new Error('aborted'))
|
||||||
|
}
|
||||||
|
|
||||||
|
signal.addEventListener('abort', onAbort, { once: true })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run an async operation with bounded exponential-backoff retry.
|
||||||
|
*
|
||||||
|
* Independent per-call: no global state, no cross-operation interaction.
|
||||||
|
* Memory bound: at most one outstanding retry timer per call.
|
||||||
|
*
|
||||||
|
* The operation may optionally accept an `AbortSignal` parameter — when the
|
||||||
|
* per-attempt timeout fires (or the outer signal is aborted), the inner
|
||||||
|
* signal is aborted so the operation can stop in-flight work cleanly.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* const result = await withBoundedRetry(
|
||||||
|
* (signal) => assertSessions([jid], true, { signal }),
|
||||||
|
* { name: 'assertSessions', ttlMs: 5 * 60_000, logger }
|
||||||
|
* )
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export async function withBoundedRetry<T>(
|
||||||
|
operation: (signal?: AbortSignal) => Promise<T>,
|
||||||
|
options: BoundedRetryOptions = {}
|
||||||
|
): Promise<T> {
|
||||||
|
const name = options.name ?? 'bounded-retry'
|
||||||
|
const delays = options.delays ?? WHATSAPP_BACKOFF_DELAYS
|
||||||
|
const jitter = options.jitter ?? DEFAULT_JITTER_FACTOR
|
||||||
|
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
|
||||||
|
const perAttemptTimeoutMs = options.perAttemptTimeoutMs ?? DEFAULT_PER_ATTEMPT_TIMEOUT_MS
|
||||||
|
const shouldRetry = options.shouldRetry ?? (() => true)
|
||||||
|
const logger = options.logger
|
||||||
|
|
||||||
|
const start = Date.now()
|
||||||
|
let lastError: Error = new Error('unknown')
|
||||||
|
let attempt = 0
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
// Check abort + TTL BEFORE starting an attempt — strict wall-clock
|
||||||
|
// budget. Without this check the loop could begin a new attempt with
|
||||||
|
// 0ms remaining and then run for up to `perAttemptTimeoutMs`.
|
||||||
|
if (options.signal?.aborted) {
|
||||||
|
throw new BoundedRetryAbortedError(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
const elapsedBeforeAttempt = Date.now() - start
|
||||||
|
const remainingBudget = ttlMs - elapsedBeforeAttempt
|
||||||
|
if (remainingBudget <= 0) {
|
||||||
|
metrics.errors?.inc({ category: 'bounded_retry', code: 'ttl_exceeded' })
|
||||||
|
logger?.warn?.(
|
||||||
|
{ op: name, attempts: attempt, elapsedMs: elapsedBeforeAttempt, ttlMs, lastError: lastError.message },
|
||||||
|
'bounded-retry: TTL exceeded before next attempt — giving up'
|
||||||
|
)
|
||||||
|
throw new BoundedRetryGiveUpError(name, attempt, elapsedBeforeAttempt, lastError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cap the per-attempt timeout to the remaining TTL budget so a single
|
||||||
|
// attempt cannot run past the wall-clock deadline.
|
||||||
|
const attemptTimeoutMs = Math.min(perAttemptTimeoutMs, remainingBudget)
|
||||||
|
const attemptAbort = new AbortController()
|
||||||
|
|
||||||
|
// Forward outer abort to the per-attempt controller so the in-flight
|
||||||
|
// operation is cancelled when the user aborts. Cleaned up below.
|
||||||
|
let onOuterAbort: (() => void) | undefined
|
||||||
|
if (options.signal) {
|
||||||
|
onOuterAbort = () => attemptAbort.abort()
|
||||||
|
if (options.signal.aborted) {
|
||||||
|
attemptAbort.abort()
|
||||||
|
} else {
|
||||||
|
options.signal.addEventListener('abort', onOuterAbort, { once: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await withTimeout(operation(attemptAbort.signal), attemptTimeoutMs, name, attemptAbort)
|
||||||
|
|
||||||
|
if (attempt > 0) {
|
||||||
|
metrics.socketEvents?.inc({ event: 'bounded_retry_recovered' })
|
||||||
|
logger?.info?.(
|
||||||
|
{ op: name, attempts: attempt + 1, elapsedMs: Date.now() - start },
|
||||||
|
'bounded-retry: operation succeeded after retries'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
} catch (err) {
|
||||||
|
lastError = err as Error
|
||||||
|
attempt++
|
||||||
|
|
||||||
|
// (outer-abort listener detachment happens in the finally below —
|
||||||
|
// avoiding a double-remove that breaks listener-count assertions.)
|
||||||
|
|
||||||
|
// If the outer signal aborted us mid-attempt, surface that explicitly
|
||||||
|
// rather than as a generic operation failure.
|
||||||
|
if (options.signal?.aborted) {
|
||||||
|
throw new BoundedRetryAbortedError(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
const elapsed = Date.now() - start
|
||||||
|
|
||||||
|
if (!shouldRetry(lastError, attempt)) {
|
||||||
|
metrics.errors?.inc({ category: 'bounded_retry', code: 'predicate_no_retry' })
|
||||||
|
logger?.warn?.(
|
||||||
|
{ op: name, attempts: attempt, elapsedMs: elapsed, error: lastError.message },
|
||||||
|
'bounded-retry: shouldRetry returned false — giving up'
|
||||||
|
)
|
||||||
|
throw lastError
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-check budget after the failure so we do not sleep past TTL.
|
||||||
|
const remainingAfterFailure = ttlMs - elapsed
|
||||||
|
if (remainingAfterFailure <= 0) {
|
||||||
|
metrics.errors?.inc({ category: 'bounded_retry', code: 'ttl_exceeded' })
|
||||||
|
logger?.warn?.(
|
||||||
|
{ op: name, attempts: attempt, elapsedMs: elapsed, ttlMs, lastError: lastError.message },
|
||||||
|
'bounded-retry: TTL exceeded after attempt — giving up'
|
||||||
|
)
|
||||||
|
throw new BoundedRetryGiveUpError(name, attempt, elapsed, lastError)
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseDelay = pickDelay(attempt - 1, delays)
|
||||||
|
const delayMs = Math.min(withJitter(baseDelay, jitter), remainingAfterFailure)
|
||||||
|
|
||||||
|
options.onRetry?.(lastError, attempt, delayMs)
|
||||||
|
metrics.socketEvents?.inc({ event: 'bounded_retry_attempt' })
|
||||||
|
logger?.debug?.(
|
||||||
|
{ op: name, attempt, delayMs, elapsedMs: elapsed, error: lastError.message },
|
||||||
|
'bounded-retry: scheduling next attempt'
|
||||||
|
)
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(delayMs, options.signal)
|
||||||
|
} catch {
|
||||||
|
throw new BoundedRetryAbortedError(name)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
// Belt-and-suspenders: ensure the outer-abort listener is always
|
||||||
|
// removed even on early throws.
|
||||||
|
if (options.signal && onOuterAbort) {
|
||||||
|
options.signal.removeEventListener('abort', onOuterAbort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -94,7 +94,13 @@ const BROWSER_TO_PLATFORM_ID: ReadonlyMap<string, string> = (() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Map(entries)
|
const map = new Map(entries)
|
||||||
|
// ANDROID → ANDROID_PHONE alias (DeviceProps.PlatformType has ANDROID_PHONE but not ANDROID)
|
||||||
|
if (!map.has('ANDROID') && map.has('ANDROID_PHONE')) {
|
||||||
|
map.set('ANDROID', map.get('ANDROID_PHONE')!)
|
||||||
|
}
|
||||||
|
|
||||||
|
return map
|
||||||
})()
|
})()
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -331,7 +337,8 @@ export const Browsers: BrowsersMap = {
|
|||||||
macOS: (browser: string): [string, string, string] => ['Mac OS', browser, OS_VERSIONS.macOS],
|
macOS: (browser: string): [string, string, string] => ['Mac OS', browser, OS_VERSIONS.macOS],
|
||||||
windows: (browser: string): [string, string, string] => ['Windows', browser, OS_VERSIONS.windows],
|
windows: (browser: string): [string, string, string] => ['Windows', browser, OS_VERSIONS.windows],
|
||||||
baileys: (browser: string): [string, string, string] => ['Baileys', browser, OS_VERSIONS.baileys],
|
baileys: (browser: string): [string, string, string] => ['Baileys', browser, OS_VERSIONS.baileys],
|
||||||
appropriate: (browser: string): [string, string, string] => [getPlatformName(), browser, getAppropriateVersion()]
|
appropriate: (browser: string): [string, string, string] => [getPlatformName(), browser, getAppropriateVersion()],
|
||||||
|
android: (apiLevel: string): [string, string, string] => [apiLevel, 'Android', '']
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -378,7 +385,7 @@ export const getPlatformId = (browser: unknown): string => {
|
|||||||
* properties like 'toString' or 'constructor'.
|
* properties like 'toString' or 'constructor'.
|
||||||
*
|
*
|
||||||
* @param value - Value to check
|
* @param value - Value to check
|
||||||
* @returns True if value is a valid browser preset key ('ubuntu', 'macOS', 'windows', 'baileys', 'appropriate')
|
* @returns True if value is a valid browser preset key ('ubuntu', 'macOS', 'windows', 'baileys', 'appropriate', 'android')
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* isValidBrowserPreset('ubuntu') // true
|
* isValidBrowserPreset('ubuntu') // true
|
||||||
@@ -391,6 +398,16 @@ export const getPlatformId = (browser: unknown): string => {
|
|||||||
* const config = Browsers[userInput]('MyApp')
|
* const config = Browsers[userInput]('MyApp')
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Checks if the browser tuple represents an Android companion device.
|
||||||
|
*
|
||||||
|
* @param browser - Browser tuple [os, platform, version]
|
||||||
|
* @returns True if platform is 'Android' (case-insensitive)
|
||||||
|
*/
|
||||||
|
export const isAndroidBrowser = (browser: [string, string, string]): boolean => {
|
||||||
|
return browser[1]?.toUpperCase() === 'ANDROID'
|
||||||
|
}
|
||||||
|
|
||||||
export const isValidBrowserPreset = (value: unknown): value is keyof BrowsersMap => {
|
export const isValidBrowserPreset = (value: unknown): value is keyof BrowsersMap => {
|
||||||
return typeof value === 'string' && Object.prototype.hasOwnProperty.call(Browsers, value)
|
return typeof value === 'string' && Object.prototype.hasOwnProperty.call(Browsers, value)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1083,6 +1083,7 @@ export const processSyncAction = (
|
|||||||
action.lidContactAction.firstName ||
|
action.lidContactAction.firstName ||
|
||||||
action.lidContactAction.username ||
|
action.lidContactAction.username ||
|
||||||
undefined,
|
undefined,
|
||||||
|
username: action.lidContactAction.username || undefined,
|
||||||
lid: id!,
|
lid: id!,
|
||||||
phoneNumber: undefined
|
phoneNumber: undefined
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,766 +0,0 @@
|
|||||||
/**
|
|
||||||
* Circuit Breaker Pattern Implementation
|
|
||||||
*
|
|
||||||
* Provides protection against cascading failures by monitoring operation outcomes
|
|
||||||
* and temporarily blocking requests when failure thresholds are exceeded.
|
|
||||||
*
|
|
||||||
* States:
|
|
||||||
* - CLOSED: Normal operation, requests pass through
|
|
||||||
* - OPEN: Failures exceeded threshold, requests are blocked
|
|
||||||
* - HALF_OPEN: Testing recovery, limited requests allowed
|
|
||||||
*
|
|
||||||
* @module Utils/circuit-breaker
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { EventEmitter } from 'events'
|
|
||||||
import { metrics } from './prometheus-metrics.js'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Circuit breaker operational states
|
|
||||||
*/
|
|
||||||
export type CircuitState = 'closed' | 'open' | 'half-open'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Failure record with timestamp for sliding window tracking
|
|
||||||
*/
|
|
||||||
export interface FailureRecord {
|
|
||||||
timestamp: number
|
|
||||||
error: Error
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Circuit breaker configuration options
|
|
||||||
*/
|
|
||||||
export interface CircuitBreakerOptions {
|
|
||||||
/** Unique identifier for this circuit breaker (used in metrics/logging) */
|
|
||||||
name: string
|
|
||||||
/** Number of failures within the window to trigger OPEN state (default: 5) */
|
|
||||||
failureThreshold?: number
|
|
||||||
/** Time window in ms for counting failures (default: 60000) */
|
|
||||||
failureWindow?: number
|
|
||||||
/** Number of successes required in HALF_OPEN to return to CLOSED (default: 2) */
|
|
||||||
successThreshold?: number
|
|
||||||
/** Time in ms to wait before transitioning from OPEN to HALF_OPEN (default: 30000) */
|
|
||||||
resetTimeout?: number
|
|
||||||
/** Timeout for individual operations in ms (default: 10000) */
|
|
||||||
timeout?: number
|
|
||||||
/** Minimum number of requests before circuit can trip (default: 5) */
|
|
||||||
volumeThreshold?: number
|
|
||||||
/** Predicate to determine if an error should count as a failure */
|
|
||||||
shouldCountError?: (error: Error) => boolean
|
|
||||||
/** Whether to collect Prometheus metrics (default: true) */
|
|
||||||
collectMetrics?: boolean
|
|
||||||
/** Fallback function when circuit is OPEN */
|
|
||||||
fallback?: <T>() => T | Promise<T>
|
|
||||||
/** Callback when state changes */
|
|
||||||
onStateChange?: (from: CircuitState, to: CircuitState) => void
|
|
||||||
/** Callback on failure */
|
|
||||||
onFailure?: (error: Error) => void
|
|
||||||
/** Callback on success */
|
|
||||||
onSuccess?: () => void
|
|
||||||
/** Callback when circuit opens */
|
|
||||||
onOpen?: () => void
|
|
||||||
/** Callback when circuit closes */
|
|
||||||
onClose?: () => void
|
|
||||||
/** Callback when circuit enters half-open */
|
|
||||||
onHalfOpen?: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Circuit breaker statistics
|
|
||||||
*/
|
|
||||||
export interface CircuitBreakerStats {
|
|
||||||
state: CircuitState
|
|
||||||
failures: number
|
|
||||||
successes: number
|
|
||||||
consecutiveFailures: number
|
|
||||||
consecutiveSuccesses: number
|
|
||||||
totalCalls: number
|
|
||||||
totalFailures: number
|
|
||||||
totalSuccesses: number
|
|
||||||
totalRejected: number
|
|
||||||
failureRate: number
|
|
||||||
lastFailureTime?: number
|
|
||||||
lastSuccessTime?: number
|
|
||||||
lastStateChange?: number
|
|
||||||
isOpen: boolean
|
|
||||||
isClosed: boolean
|
|
||||||
isHalfOpen: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Error thrown when circuit is OPEN and request is rejected
|
|
||||||
*/
|
|
||||||
export class CircuitOpenError extends Error {
|
|
||||||
constructor(
|
|
||||||
public readonly circuitName: string,
|
|
||||||
public readonly state: CircuitState
|
|
||||||
) {
|
|
||||||
super(`Circuit breaker "${circuitName}" is ${state}`)
|
|
||||||
this.name = 'CircuitOpenError'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Error thrown when operation exceeds timeout
|
|
||||||
*/
|
|
||||||
export class CircuitTimeoutError extends Error {
|
|
||||||
constructor(
|
|
||||||
public readonly circuitName: string,
|
|
||||||
public readonly timeoutMs: number
|
|
||||||
) {
|
|
||||||
super(`Circuit breaker "${circuitName}" operation timed out after ${timeoutMs}ms`)
|
|
||||||
this.name = 'CircuitTimeoutError'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Circuit Breaker implementation with sliding window failure tracking
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const breaker = new CircuitBreaker({
|
|
||||||
* name: 'whatsapp-api',
|
|
||||||
* failureThreshold: 5,
|
|
||||||
* resetTimeout: 30000
|
|
||||||
* })
|
|
||||||
*
|
|
||||||
* try {
|
|
||||||
* const result = await breaker.execute(() => sendMessage(msg))
|
|
||||||
* } catch (error) {
|
|
||||||
* if (error instanceof CircuitOpenError) {
|
|
||||||
* // Circuit is open, use fallback
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export class CircuitBreaker extends EventEmitter {
|
|
||||||
private state: CircuitState = 'closed'
|
|
||||||
private failureRecords: FailureRecord[] = []
|
|
||||||
private consecutiveFailures = 0
|
|
||||||
private consecutiveSuccesses = 0
|
|
||||||
private totalCalls = 0
|
|
||||||
private totalFailures = 0
|
|
||||||
private totalSuccesses = 0
|
|
||||||
private totalRejected = 0
|
|
||||||
private lastFailureTime?: number
|
|
||||||
private lastSuccessTime?: number
|
|
||||||
private lastStateChange: number
|
|
||||||
private resetTimer?: ReturnType<typeof setTimeout>
|
|
||||||
private readonly options: Required<CircuitBreakerOptions>
|
|
||||||
|
|
||||||
constructor(options: CircuitBreakerOptions) {
|
|
||||||
super()
|
|
||||||
|
|
||||||
this.options = {
|
|
||||||
name: options.name,
|
|
||||||
failureThreshold: options.failureThreshold ?? 5,
|
|
||||||
failureWindow: options.failureWindow ?? 60000,
|
|
||||||
successThreshold: options.successThreshold ?? 2,
|
|
||||||
resetTimeout: options.resetTimeout ?? 30000,
|
|
||||||
timeout: options.timeout ?? 10000,
|
|
||||||
volumeThreshold: options.volumeThreshold ?? 5,
|
|
||||||
shouldCountError: options.shouldCountError ?? (() => true),
|
|
||||||
collectMetrics: options.collectMetrics ?? true,
|
|
||||||
fallback:
|
|
||||||
options.fallback ??
|
|
||||||
(() => {
|
|
||||||
throw new CircuitOpenError(this.options.name, this.state)
|
|
||||||
}),
|
|
||||||
onStateChange: options.onStateChange ?? (() => {}),
|
|
||||||
onFailure: options.onFailure ?? (() => {}),
|
|
||||||
onSuccess: options.onSuccess ?? (() => {}),
|
|
||||||
onOpen: options.onOpen ?? (() => {}),
|
|
||||||
onClose: options.onClose ?? (() => {}),
|
|
||||||
onHalfOpen: options.onHalfOpen ?? (() => {})
|
|
||||||
}
|
|
||||||
|
|
||||||
this.lastStateChange = Date.now()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the circuit allows execution
|
|
||||||
*/
|
|
||||||
canExecute(): boolean {
|
|
||||||
if (this.state === 'closed') {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.state === 'open') {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// HALF_OPEN: allow limited requests for testing
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute an async operation with circuit breaker protection
|
|
||||||
*/
|
|
||||||
async execute<T>(operation: () => T | Promise<T>): Promise<T> {
|
|
||||||
this.totalCalls++
|
|
||||||
|
|
||||||
// Check if circuit allows execution
|
|
||||||
if (this.state === 'open') {
|
|
||||||
this.totalRejected++
|
|
||||||
|
|
||||||
if (this.options.collectMetrics) {
|
|
||||||
metrics.errors.inc({ category: 'circuit_breaker', code: 'rejected' })
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.options.fallback() as T
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute with timeout protection
|
|
||||||
try {
|
|
||||||
const result = await this.executeWithTimeout(operation)
|
|
||||||
this.recordSuccess()
|
|
||||||
return result
|
|
||||||
} catch (error) {
|
|
||||||
this.recordFailure(error as Error)
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute a synchronous operation with circuit breaker protection
|
|
||||||
*/
|
|
||||||
executeSync<T>(operation: () => T): T {
|
|
||||||
this.totalCalls++
|
|
||||||
|
|
||||||
if (this.state === 'open') {
|
|
||||||
this.totalRejected++
|
|
||||||
|
|
||||||
if (this.options.collectMetrics) {
|
|
||||||
metrics.errors.inc({ category: 'circuit_breaker', code: 'rejected' })
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.options.fallback() as T
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = operation()
|
|
||||||
this.recordSuccess()
|
|
||||||
return result
|
|
||||||
} catch (error) {
|
|
||||||
this.recordFailure(error as Error)
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute operation with timeout wrapper
|
|
||||||
*/
|
|
||||||
private async executeWithTimeout<T>(operation: () => T | Promise<T>): Promise<T> {
|
|
||||||
return new Promise<T>((resolve, reject) => {
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
reject(new CircuitTimeoutError(this.options.name, this.options.timeout))
|
|
||||||
}, this.options.timeout)
|
|
||||||
|
|
||||||
Promise.resolve(operation())
|
|
||||||
.then(result => {
|
|
||||||
clearTimeout(timer)
|
|
||||||
resolve(result)
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
clearTimeout(timer)
|
|
||||||
reject(error)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Record a successful operation
|
|
||||||
*/
|
|
||||||
private recordSuccess(): void {
|
|
||||||
this.totalSuccesses++
|
|
||||||
this.lastSuccessTime = Date.now()
|
|
||||||
this.consecutiveSuccesses++
|
|
||||||
this.consecutiveFailures = 0
|
|
||||||
|
|
||||||
if (this.options.collectMetrics) {
|
|
||||||
metrics.socketEvents.inc({ event: 'circuit_success' })
|
|
||||||
}
|
|
||||||
|
|
||||||
this.options.onSuccess()
|
|
||||||
this.emit('success')
|
|
||||||
|
|
||||||
// In HALF_OPEN state, check if we can close the circuit
|
|
||||||
if (this.state === 'half-open') {
|
|
||||||
if (this.consecutiveSuccesses >= this.options.successThreshold) {
|
|
||||||
this.transitionTo('closed')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Record a failed operation
|
|
||||||
*/
|
|
||||||
private recordFailure(error: Error): void {
|
|
||||||
// Check if this error should count as a failure
|
|
||||||
if (!this.options.shouldCountError(error)) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = Date.now()
|
|
||||||
this.totalFailures++
|
|
||||||
this.lastFailureTime = now
|
|
||||||
this.consecutiveFailures++
|
|
||||||
this.consecutiveSuccesses = 0
|
|
||||||
|
|
||||||
// Add to failure records for sliding window
|
|
||||||
this.failureRecords.push({ timestamp: now, error })
|
|
||||||
|
|
||||||
// Clean old failures outside the window
|
|
||||||
this.cleanOldFailures()
|
|
||||||
|
|
||||||
if (this.options.collectMetrics) {
|
|
||||||
metrics.errors.inc({ category: 'circuit_breaker', code: 'failure' })
|
|
||||||
}
|
|
||||||
|
|
||||||
this.options.onFailure(error)
|
|
||||||
this.emit('failure', error)
|
|
||||||
|
|
||||||
// State transition logic
|
|
||||||
if (this.state === 'half-open') {
|
|
||||||
// Any failure in HALF_OPEN immediately reopens the circuit
|
|
||||||
this.transitionTo('open')
|
|
||||||
} else if (this.state === 'closed') {
|
|
||||||
// Check if we should trip the circuit
|
|
||||||
const recentFailures = this.failureRecords.length
|
|
||||||
|
|
||||||
if (this.totalCalls >= this.options.volumeThreshold && recentFailures >= this.options.failureThreshold) {
|
|
||||||
this.transitionTo('open')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove failure records outside the sliding window
|
|
||||||
*/
|
|
||||||
private cleanOldFailures(): void {
|
|
||||||
const cutoff = Date.now() - this.options.failureWindow
|
|
||||||
this.failureRecords = this.failureRecords.filter(record => record.timestamp > cutoff)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Transition to a new state
|
|
||||||
*/
|
|
||||||
private transitionTo(newState: CircuitState): void {
|
|
||||||
const oldState = this.state
|
|
||||||
|
|
||||||
if (oldState === newState) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
this.state = newState
|
|
||||||
this.lastStateChange = Date.now()
|
|
||||||
|
|
||||||
// Clear existing reset timer
|
|
||||||
if (this.resetTimer) {
|
|
||||||
clearTimeout(this.resetTimer)
|
|
||||||
this.resetTimer = undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
// State-specific actions
|
|
||||||
switch (newState) {
|
|
||||||
case 'closed':
|
|
||||||
this.consecutiveFailures = 0
|
|
||||||
this.consecutiveSuccesses = 0
|
|
||||||
this.failureRecords = []
|
|
||||||
this.options.onClose()
|
|
||||||
this.emit('close')
|
|
||||||
break
|
|
||||||
|
|
||||||
case 'open':
|
|
||||||
this.consecutiveSuccesses = 0
|
|
||||||
this.options.onOpen()
|
|
||||||
this.emit('open')
|
|
||||||
|
|
||||||
// Record circuit breaker trip metric
|
|
||||||
if (this.options.collectMetrics) {
|
|
||||||
metrics.circuitBreakerTrips?.inc({ name: this.options.name })
|
|
||||||
}
|
|
||||||
|
|
||||||
// Schedule transition to HALF_OPEN
|
|
||||||
this.resetTimer = setTimeout(() => {
|
|
||||||
this.transitionTo('half-open')
|
|
||||||
}, this.options.resetTimeout)
|
|
||||||
break
|
|
||||||
|
|
||||||
case 'half-open':
|
|
||||||
this.consecutiveSuccesses = 0
|
|
||||||
this.consecutiveFailures = 0
|
|
||||||
this.options.onHalfOpen()
|
|
||||||
this.emit('half-open')
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
this.options.onStateChange(oldState, newState)
|
|
||||||
this.emit('state-change', { from: oldState, to: newState })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Manually trip the circuit to OPEN state
|
|
||||||
*/
|
|
||||||
trip(): void {
|
|
||||||
this.transitionTo('open')
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Manually reset the circuit to CLOSED state
|
|
||||||
*/
|
|
||||||
reset(): void {
|
|
||||||
this.transitionTo('closed')
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get current circuit state
|
|
||||||
*/
|
|
||||||
getState(): CircuitState {
|
|
||||||
return this.state
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if circuit is OPEN
|
|
||||||
*/
|
|
||||||
isOpen(): boolean {
|
|
||||||
return this.state === 'open'
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if circuit is CLOSED
|
|
||||||
*/
|
|
||||||
isClosed(): boolean {
|
|
||||||
return this.state === 'closed'
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if circuit is HALF_OPEN
|
|
||||||
*/
|
|
||||||
isHalfOpen(): boolean {
|
|
||||||
return this.state === 'half-open'
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get circuit breaker statistics
|
|
||||||
*/
|
|
||||||
getStats(): CircuitBreakerStats {
|
|
||||||
this.cleanOldFailures()
|
|
||||||
|
|
||||||
const failureRate = this.totalCalls > 0 ? (this.totalFailures / this.totalCalls) * 100 : 0
|
|
||||||
|
|
||||||
return {
|
|
||||||
state: this.state,
|
|
||||||
failures: this.failureRecords.length,
|
|
||||||
successes: this.consecutiveSuccesses,
|
|
||||||
consecutiveFailures: this.consecutiveFailures,
|
|
||||||
consecutiveSuccesses: this.consecutiveSuccesses,
|
|
||||||
totalCalls: this.totalCalls,
|
|
||||||
totalFailures: this.totalFailures,
|
|
||||||
totalSuccesses: this.totalSuccesses,
|
|
||||||
totalRejected: this.totalRejected,
|
|
||||||
failureRate,
|
|
||||||
lastFailureTime: this.lastFailureTime,
|
|
||||||
lastSuccessTime: this.lastSuccessTime,
|
|
||||||
lastStateChange: this.lastStateChange,
|
|
||||||
isOpen: this.isOpen(),
|
|
||||||
isClosed: this.isClosed(),
|
|
||||||
isHalfOpen: this.isHalfOpen()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get circuit breaker name
|
|
||||||
*/
|
|
||||||
getName(): string {
|
|
||||||
return this.options.name
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Destroy circuit breaker and clean up resources
|
|
||||||
*/
|
|
||||||
destroy(): void {
|
|
||||||
if (this.resetTimer) {
|
|
||||||
clearTimeout(this.resetTimer)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.failureRecords = []
|
|
||||||
this.removeAllListeners()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Factory function to create a circuit breaker
|
|
||||||
*/
|
|
||||||
export function createCircuitBreaker(options: CircuitBreakerOptions): CircuitBreaker {
|
|
||||||
return new CircuitBreaker(options)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Registry for managing multiple circuit breakers
|
|
||||||
*/
|
|
||||||
export class CircuitBreakerRegistry {
|
|
||||||
private breakers: Map<string, CircuitBreaker> = new Map()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get or create a circuit breaker by name
|
|
||||||
*/
|
|
||||||
get(name: string, options?: Omit<CircuitBreakerOptions, 'name'>): CircuitBreaker {
|
|
||||||
if (!this.breakers.has(name)) {
|
|
||||||
const breaker = new CircuitBreaker({ ...options, name })
|
|
||||||
this.breakers.set(name, breaker)
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.breakers.get(name)!
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a circuit breaker exists
|
|
||||||
*/
|
|
||||||
has(name: string): boolean {
|
|
||||||
return this.breakers.has(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove a circuit breaker
|
|
||||||
*/
|
|
||||||
remove(name: string): boolean {
|
|
||||||
const breaker = this.breakers.get(name)
|
|
||||||
if (breaker) {
|
|
||||||
breaker.destroy()
|
|
||||||
return this.breakers.delete(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all circuit breakers
|
|
||||||
*/
|
|
||||||
getAll(): Map<string, CircuitBreaker> {
|
|
||||||
return new Map(this.breakers)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get statistics for all circuit breakers
|
|
||||||
*/
|
|
||||||
getAllStats(): Record<string, CircuitBreakerStats> {
|
|
||||||
const stats: Record<string, CircuitBreakerStats> = {}
|
|
||||||
for (const [name, breaker] of this.breakers) {
|
|
||||||
stats[name] = breaker.getStats()
|
|
||||||
}
|
|
||||||
|
|
||||||
return stats
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reset all circuit breakers to CLOSED state
|
|
||||||
*/
|
|
||||||
resetAll(): void {
|
|
||||||
for (const breaker of this.breakers.values()) {
|
|
||||||
breaker.reset()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Destroy all circuit breakers
|
|
||||||
*/
|
|
||||||
destroyAll(): void {
|
|
||||||
for (const breaker of this.breakers.values()) {
|
|
||||||
breaker.destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
this.breakers.clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Global circuit breaker registry instance
|
|
||||||
*/
|
|
||||||
export const globalCircuitRegistry = new CircuitBreakerRegistry()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decorator to protect a method with circuit breaker
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* class MyService {
|
|
||||||
* @circuitBreaker({ failureThreshold: 3 })
|
|
||||||
* async fetchData() {
|
|
||||||
* return await api.getData()
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function circuitBreaker(options: Omit<CircuitBreakerOptions, 'name'> & { name?: string } = {}) {
|
|
||||||
return function (
|
|
||||||
_target: unknown,
|
|
||||||
propertyKey: string,
|
|
||||||
descriptor: TypedPropertyDescriptor<(...args: unknown[]) => unknown>
|
|
||||||
) {
|
|
||||||
const originalMethod = descriptor.value
|
|
||||||
if (!originalMethod) return descriptor
|
|
||||||
|
|
||||||
const name = options.name || propertyKey
|
|
||||||
const breaker = globalCircuitRegistry.get(name, options)
|
|
||||||
|
|
||||||
descriptor.value = async function (...args: unknown[]): Promise<unknown> {
|
|
||||||
return breaker.execute(() => originalMethod.apply(this, args))
|
|
||||||
}
|
|
||||||
|
|
||||||
return descriptor
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wrap a function with circuit breaker protection
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const protectedFetch = withCircuitBreaker(
|
|
||||||
* fetchData,
|
|
||||||
* { name: 'api-fetch', failureThreshold: 5 }
|
|
||||||
* )
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
// eslint-disable-next-line space-before-function-paren
|
|
||||||
export function withCircuitBreaker<T extends (...args: unknown[]) => unknown>(
|
|
||||||
fn: T,
|
|
||||||
options: CircuitBreakerOptions
|
|
||||||
): T {
|
|
||||||
const breaker = new CircuitBreaker(options)
|
|
||||||
|
|
||||||
return (async (...args: Parameters<T>): Promise<ReturnType<T>> => {
|
|
||||||
return breaker.execute(() => fn(...args)) as Promise<ReturnType<T>>
|
|
||||||
}) as unknown as T
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get health status of all circuit breakers
|
|
||||||
*/
|
|
||||||
export function getCircuitHealth(): {
|
|
||||||
healthy: boolean
|
|
||||||
openCircuits: string[]
|
|
||||||
stats: Record<string, CircuitBreakerStats>
|
|
||||||
} {
|
|
||||||
const stats = globalCircuitRegistry.getAllStats()
|
|
||||||
const openCircuits: string[] = []
|
|
||||||
|
|
||||||
for (const [name, stat] of Object.entries(stats)) {
|
|
||||||
if (stat.isOpen) {
|
|
||||||
openCircuits.push(name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
healthy: openCircuits.length === 0,
|
|
||||||
openCircuits,
|
|
||||||
stats
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a pre-configured circuit breaker for WhatsApp PreKey operations
|
|
||||||
*
|
|
||||||
* This circuit breaker is optimized for handling encryption/session errors
|
|
||||||
* that commonly occur with WhatsApp's Signal protocol implementation.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const preKeyBreaker = createPreKeyCircuitBreaker()
|
|
||||||
*
|
|
||||||
* async function sendEncryptedMessage(msg) {
|
|
||||||
* return preKeyBreaker.execute(async () => {
|
|
||||||
* return await encryptAndSend(msg)
|
|
||||||
* })
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function createPreKeyCircuitBreaker(customOptions?: Partial<CircuitBreakerOptions>): CircuitBreaker {
|
|
||||||
const preKeyErrorPatterns = ['prekey', 'pre-key', 'session', 'signal', 'encrypt', 'decrypt', 'cipher', 'key']
|
|
||||||
|
|
||||||
return new CircuitBreaker({
|
|
||||||
name: 'prekey-operations',
|
|
||||||
failureThreshold: 5,
|
|
||||||
failureWindow: 60000,
|
|
||||||
resetTimeout: 30000,
|
|
||||||
successThreshold: 2,
|
|
||||||
shouldCountError: (error: Error) => {
|
|
||||||
const message = error.message.toLowerCase()
|
|
||||||
return preKeyErrorPatterns.some(pattern => message.includes(pattern))
|
|
||||||
},
|
|
||||||
...customOptions
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a circuit breaker for WebSocket connection operations
|
|
||||||
*/
|
|
||||||
export function createConnectionCircuitBreaker(customOptions?: Partial<CircuitBreakerOptions>): CircuitBreaker {
|
|
||||||
const connectionErrorPatterns = [
|
|
||||||
'econnrefused',
|
|
||||||
'econnreset',
|
|
||||||
'etimedout',
|
|
||||||
'enotfound',
|
|
||||||
'socket',
|
|
||||||
'websocket',
|
|
||||||
'connection',
|
|
||||||
'network'
|
|
||||||
]
|
|
||||||
|
|
||||||
// Normal WS lifecycle status codes that must NEVER trip the query circuit breaker.
|
|
||||||
// These are transient events that happen on every reconnect and carry no information
|
|
||||||
// about persistent server-side failures. The reconnection logic in makeSocket handles
|
|
||||||
// them independently.
|
|
||||||
const WS_LIFECYCLE_STATUS_CODES = new Set([
|
|
||||||
428, // connectionClosed
|
|
||||||
408, // connectionLost / timedOut
|
|
||||||
440, // connectionReplaced
|
|
||||||
])
|
|
||||||
|
|
||||||
return new CircuitBreaker({
|
|
||||||
name: 'connection-operations',
|
|
||||||
failureThreshold: 3,
|
|
||||||
failureWindow: 30000,
|
|
||||||
resetTimeout: 60000,
|
|
||||||
successThreshold: 1,
|
|
||||||
shouldCountError: (error: Error) => {
|
|
||||||
// CircuitTimeoutError messages embed the circuit name (e.g. "socket-query"), which
|
|
||||||
// accidentally matches the "socket" pattern below and causes a self-reinforcing loop
|
|
||||||
// where the breaker's own timeouts keep tripping the breaker. Exclude them explicitly.
|
|
||||||
if (error instanceof CircuitTimeoutError) return false
|
|
||||||
|
|
||||||
// Exclude normal WS reconnect events (Connection Closed, Connection Lost, Timed Out, etc.).
|
|
||||||
// These are not server-side failures — they happen on every restart/redeploy and should
|
|
||||||
// never cause the circuit to open. If we counted them, the 3 concurrent parallel
|
|
||||||
// post-login queries (sendPassiveIq, uploadPreKeysToServerIfRequired, digestKeyBundle) could all
|
|
||||||
// fail simultaneously when the WS drops, instantly opening the circuit and blocking
|
|
||||||
// profile-picture fetches and message delivery for the next 30 s.
|
|
||||||
const statusCode = (error as { output?: { statusCode?: number } })?.output?.statusCode
|
|
||||||
if (statusCode !== undefined && WS_LIFECYCLE_STATUS_CODES.has(statusCode)) return false
|
|
||||||
|
|
||||||
const message = error.message.toLowerCase()
|
|
||||||
const code = (error as NodeJS.ErrnoException).code?.toLowerCase() || ''
|
|
||||||
return connectionErrorPatterns.some(pattern => message.includes(pattern) || code.includes(pattern))
|
|
||||||
},
|
|
||||||
...customOptions
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a circuit breaker for message sending operations
|
|
||||||
*/
|
|
||||||
export function createMessageCircuitBreaker(customOptions?: Partial<CircuitBreakerOptions>): CircuitBreaker {
|
|
||||||
return new CircuitBreaker({
|
|
||||||
name: 'message-operations',
|
|
||||||
failureThreshold: 5,
|
|
||||||
failureWindow: 60000,
|
|
||||||
resetTimeout: 15000,
|
|
||||||
successThreshold: 2,
|
|
||||||
timeout: 30000,
|
|
||||||
...customOptions
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export default CircuitBreaker
|
|
||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
isJidStatusBroadcast,
|
isJidStatusBroadcast,
|
||||||
isLidUser,
|
isLidUser,
|
||||||
isPnUser,
|
isPnUser,
|
||||||
jidDecode
|
|
||||||
// transferDevice
|
// transferDevice
|
||||||
} from '../WABinary'
|
} from '../WABinary'
|
||||||
import { unpadRandomMax16 } from './generics'
|
import { unpadRandomMax16 } from './generics'
|
||||||
@@ -59,7 +58,11 @@ export const BAD_MAC_ERROR_TEXT = 'Bad MAC'
|
|||||||
export const DECRYPTION_RETRY_CONFIG = {
|
export const DECRYPTION_RETRY_CONFIG = {
|
||||||
maxRetries: 3,
|
maxRetries: 3,
|
||||||
baseDelayMs: 100,
|
baseDelayMs: 100,
|
||||||
sessionRecordErrors: ['No session record', 'SessionError: No session record'],
|
// 'No matching sessions found' is the libsignal error when decryptWithSessions exhausts
|
||||||
|
// all stored sessions for a JID. Same recovery flow (retry receipt → pkmsg → new session)
|
||||||
|
// — categorise it as session-record so the caller logs DEBUG on retry, ERROR only when
|
||||||
|
// retries are exhausted (instead of dumping the full stack as an unknown error).
|
||||||
|
sessionRecordErrors: ['No session record', 'SessionError: No session record', 'No matching sessions found'],
|
||||||
corruptedSessionErrors: ['Bad MAC', 'MessageCounterError', MISSING_KEYS_ERROR_TEXT]
|
corruptedSessionErrors: ['Bad MAC', 'MessageCounterError', MISSING_KEYS_ERROR_TEXT]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,10 +246,14 @@ export function decodeMessageNode(stanza: BinaryNode, meId: string, meLid: strin
|
|||||||
const key: WAMessageKey = {
|
const key: WAMessageKey = {
|
||||||
remoteJid: chatId,
|
remoteJid: chatId,
|
||||||
remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
||||||
|
remoteJidUsername: !isJidGroup(chatId)
|
||||||
|
? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
|
||||||
|
: undefined,
|
||||||
fromMe,
|
fromMe,
|
||||||
id: msgId,
|
id: msgId,
|
||||||
participant,
|
participant,
|
||||||
participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
||||||
|
participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
|
||||||
addressingMode: addressingContext.addressingMode,
|
addressingMode: addressingContext.addressingMode,
|
||||||
...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
|
...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
|
||||||
}
|
}
|
||||||
@@ -276,7 +283,6 @@ export const decryptMessageNode = (
|
|||||||
meLid: string,
|
meLid: string,
|
||||||
repository: SignalRepositoryWithLIDStore,
|
repository: SignalRepositoryWithLIDStore,
|
||||||
logger: ILogger,
|
logger: ILogger,
|
||||||
autoCleanCorrupted = true
|
|
||||||
) => {
|
) => {
|
||||||
const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
|
const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
|
||||||
return {
|
return {
|
||||||
@@ -394,6 +400,23 @@ export const decryptMessageNode = (
|
|||||||
} else {
|
} else {
|
||||||
fullMessage.message = msg
|
fullMessage.message = msg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Detect view-once media on stanza 1 received by linked device.
|
||||||
|
// viewOnceMessage wrapper is also used for interactive messages
|
||||||
|
// (interactiveMessage, listMessage, nativeFlowMessage) -- those do NOT have
|
||||||
|
// imageMessage.viewOnce / videoMessage.viewOnce / audioMessage.viewOnce = true.
|
||||||
|
// Only real view-once media carries viewOnce: true on the inner media message.
|
||||||
|
const viewOnceInner =
|
||||||
|
msg.viewOnceMessage?.message ||
|
||||||
|
msg.viewOnceMessageV2?.message ||
|
||||||
|
msg.viewOnceMessageV2Extension?.message
|
||||||
|
if (
|
||||||
|
viewOnceInner?.imageMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.videoMessage?.viewOnce ||
|
||||||
|
viewOnceInner?.audioMessage?.viewOnce
|
||||||
|
) {
|
||||||
|
fullMessage.key.isViewOnce = true
|
||||||
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
// Check if this is a final failure after all retries exhausted
|
// Check if this is a final failure after all retries exhausted
|
||||||
const isRetryExhausted = err instanceof RetryExhaustedError
|
const isRetryExhausted = err instanceof RetryExhaustedError
|
||||||
@@ -402,9 +425,26 @@ export const decryptMessageNode = (
|
|||||||
const isCorrupted = isCorruptedSessionError(originalError)
|
const isCorrupted = isCorruptedSessionError(originalError)
|
||||||
const isSessionRecord = isSessionRecordError(originalError)
|
const isSessionRecord = isSessionRecordError(originalError)
|
||||||
|
|
||||||
|
// Slim error projection — keep name/message/type for diagnosis,
|
||||||
|
// drop `stack` which adds 4-5 lines of node_modules paths per log
|
||||||
|
// for known-recoverable libsignal errors.
|
||||||
|
//
|
||||||
|
// CRITICAL: only slim for KNOWN-RECOVERABLE categories (corrupted /
|
||||||
|
// session-record). The unknown-error branch keeps the full Error so
|
||||||
|
// protobuf/parsing/runtime bugs still emit a stack trace where it
|
||||||
|
// matters most. Catches Copilot/Codex P2 review on PR #391.
|
||||||
|
const slimErr = originalError
|
||||||
|
? {
|
||||||
|
name: (originalError as { name?: string }).name,
|
||||||
|
message: (originalError as { message?: string }).message,
|
||||||
|
type: (originalError as { type?: string }).type
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
const isRecoverableCategory = isCorrupted || isSessionRecord
|
||||||
|
|
||||||
const errorContext = {
|
const errorContext = {
|
||||||
key: fullMessage.key,
|
key: fullMessage.key,
|
||||||
err: originalError,
|
err: isRecoverableCategory ? slimErr : originalError,
|
||||||
messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
|
messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
|
||||||
sender,
|
sender,
|
||||||
author,
|
author,
|
||||||
@@ -422,34 +462,19 @@ export const decryptMessageNode = (
|
|||||||
if (isRetryExhausted) {
|
if (isRetryExhausted) {
|
||||||
logger.error(
|
logger.error(
|
||||||
errorContext,
|
errorContext,
|
||||||
`⚠️ Session corrupted and recovery failed after ${err.attempts} attempts. Auto-cleanup will attempt to recover.`
|
`⚠️ Session corrupted after ${err.attempts} attempts. Retry+pkmsg flow will recover.`
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// First occurrence - log as warning since auto-recovery will attempt
|
// First occurrence - log as warning since auto-recovery will attempt
|
||||||
logger.warn(errorContext, '⚠️ Corrupted session detected - attempting auto-recovery')
|
logger.warn(errorContext, '⚠️ Corrupted session detected - attempting auto-recovery')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Automatic cleanup of corrupted session (if enabled)
|
// Session cleanup is deferred to retry exhaustion (safety net).
|
||||||
// eslint-disable-next-line max-depth
|
// The Signal Protocol handles recovery naturally via retry+pkmsg:
|
||||||
if (autoCleanCorrupted) {
|
// Bad MAC -> retry receipt -> sender re-sends as pkmsg -> new session.
|
||||||
// eslint-disable-next-line max-depth
|
// Deleting sessions here (hot path) causes cascading failures when
|
||||||
try {
|
// multiple messages from the same contact arrive simultaneously.
|
||||||
const deletedCount = await cleanupCorruptedSession(decryptionJid, repository, logger)
|
// See: messages-recv.ts sendRetryRequest() for deferred cleanup.
|
||||||
|
|
||||||
// Mask only user portion of JID for privacy (preserve domain info)
|
|
||||||
const { user, server } = jidDecode(decryptionJid) || {}
|
|
||||||
const maskedUser =
|
|
||||||
user && user.length > 8 ? `${user.substring(0, 4)}****${user.substring(user.length - 4)}` : user
|
|
||||||
const maskedJid = maskedUser && server ? `${maskedUser}@${server}` : decryptionJid
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
{ jid: decryptionJid, maskedJid, targetedDevices: deletedCount },
|
|
||||||
`🔄 Session Reset | JID: ${maskedJid} | Targeted: ${deletedCount} devices | Will recreate on next message`
|
|
||||||
)
|
|
||||||
} catch (cleanupErr) {
|
|
||||||
logger.error({ decryptionJid, err: cleanupErr }, '❌ Failed to cleanup corrupted session')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (isSessionRecord) {
|
} else if (isSessionRecord) {
|
||||||
// Session record errors are transient - retry should handle them
|
// Session record errors are transient - retry should handle them
|
||||||
// eslint-disable-next-line max-depth
|
// eslint-disable-next-line max-depth
|
||||||
@@ -504,53 +529,20 @@ export function isCorruptedSessionError(error: any): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clean up corrupted session by deleting all device sessions for a JID
|
* Clean up corrupted session for a specific device JID.
|
||||||
* Signal Protocol will automatically recreate the session on next message
|
* WABA behavior: DELETE sessions WHERE recipient_id=? AND device_id=?
|
||||||
|
* Only deletes the exact device that was corrupted, not all devices.
|
||||||
|
*
|
||||||
|
* NOTE: This should NOT be called on every Bad MAC error (hot path).
|
||||||
|
* Instead, let the retry+pkmsg flow handle recovery naturally (like WhatsApp does).
|
||||||
|
* Only call this as a safety net when retries are exhausted.
|
||||||
*/
|
*/
|
||||||
async function cleanupCorruptedSession(
|
export async function cleanupCorruptedSession(
|
||||||
jid: string,
|
jid: string,
|
||||||
repository: SignalRepositoryWithLIDStore,
|
repository: SignalRepositoryWithLIDStore,
|
||||||
logger: ILogger
|
logger: ILogger
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
const { user, device } = jidDecode(jid) || {}
|
await repository.deleteSession([jid])
|
||||||
if (!user) {
|
logger.info({ jid }, 'Cleaned up corrupted session for specific device')
|
||||||
logger.warn({ jid }, 'Cannot cleanup session - invalid JID')
|
return 1
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build list of JIDs to delete (primary + secondary devices)
|
|
||||||
const jidsToDelete: string[] = []
|
|
||||||
|
|
||||||
// Determine domain type correctly (handle hosted JIDs)
|
|
||||||
// JID formats:
|
|
||||||
// - PN: user@s.whatsapp.net
|
|
||||||
// - LID: user@lid
|
|
||||||
// - Hosted PN: user@hosted
|
|
||||||
// - Hosted LID: user@hosted.lid
|
|
||||||
const isLID = jid.endsWith('@lid') || jid.endsWith('@hosted.lid')
|
|
||||||
const isHosted = jid.includes('@hosted')
|
|
||||||
|
|
||||||
let domain: string
|
|
||||||
if (isLID) {
|
|
||||||
domain = isHosted ? 'hosted.lid' : 'lid'
|
|
||||||
} else {
|
|
||||||
domain = isHosted ? 'hosted' : 's.whatsapp.net'
|
|
||||||
}
|
|
||||||
|
|
||||||
// Primary device (0)
|
|
||||||
jidsToDelete.push(`${user}@${domain}`)
|
|
||||||
|
|
||||||
// Secondary devices (1-5 common range for Web/Desktop/etc)
|
|
||||||
for (let i = 1; i <= 5; i++) {
|
|
||||||
jidsToDelete.push(`${user}:${i}@${domain}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// If specific device was identified and > 5, ensure it's included
|
|
||||||
if (device !== undefined && device > 5) {
|
|
||||||
jidsToDelete.push(`${user}:${device}@${domain}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
await repository.deleteSession(jidsToDelete)
|
|
||||||
|
|
||||||
return jidsToDelete.length
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import EventEmitter from 'events'
|
import EventEmitter from 'events'
|
||||||
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type {
|
import type {
|
||||||
BaileysEvent,
|
BaileysEvent,
|
||||||
BaileysEventEmitter,
|
BaileysEventEmitter,
|
||||||
@@ -54,15 +55,15 @@ export interface BufferConfig {
|
|||||||
*/
|
*/
|
||||||
export function loadBufferConfig(): BufferConfig {
|
export function loadBufferConfig(): BufferConfig {
|
||||||
return {
|
return {
|
||||||
// perf(inbound-latency): reduced from 15s → 5s so the safety auto-flush fires sooner.
|
// perf(inbound-latency): reduced from 15s → 3s so the safety auto-flush fires sooner.
|
||||||
// processNodeWithBuffer always calls ev.flush() explicitly (no-op for this timer),
|
// processNodeWithBuffer always calls ev.flush() explicitly (no-op for this timer),
|
||||||
// but socket.ts's offline-phase buffer and any stalled buffer benefit from the lower cap.
|
// but socket.ts's offline-phase buffer and any stalled buffer benefit from the lower cap.
|
||||||
bufferTimeoutMs: parseInt(process.env.BAILEYS_BUFFER_TIMEOUT_MS || '5000', 10),
|
bufferTimeoutMs: parseInt(process.env.BAILEYS_BUFFER_TIMEOUT_MS || '3000', 10),
|
||||||
minBufferTimeoutMs: parseInt(process.env.BAILEYS_BUFFER_MIN_TIMEOUT_MS || '1000', 10),
|
minBufferTimeoutMs: parseInt(process.env.BAILEYS_BUFFER_MIN_TIMEOUT_MS || '1000', 10),
|
||||||
maxBufferTimeoutMs: parseInt(process.env.BAILEYS_BUFFER_MAX_TIMEOUT_MS || '8000', 10),
|
maxBufferTimeoutMs: parseInt(process.env.BAILEYS_BUFFER_MAX_TIMEOUT_MS || '3000', 10),
|
||||||
maxHistoryCacheSize: parseInt(process.env.BAILEYS_BUFFER_MAX_HISTORY_CACHE || '10000', 10),
|
maxHistoryCacheSize: parseInt(process.env.BAILEYS_BUFFER_MAX_HISTORY_CACHE || '10000', 10),
|
||||||
maxBufferSize: parseInt(process.env.BAILEYS_BUFFER_MAX_SIZE || '5000', 10),
|
maxBufferSize: parseInt(process.env.BAILEYS_BUFFER_MAX_SIZE || '5000', 10),
|
||||||
flushDebounceMs: parseInt(process.env.BAILEYS_BUFFER_FLUSH_DEBOUNCE_MS || '100', 10),
|
flushDebounceMs: parseInt(process.env.BAILEYS_BUFFER_FLUSH_DEBOUNCE_MS || '10', 10),
|
||||||
enableAdaptiveTimeout: process.env.BAILEYS_BUFFER_ADAPTIVE_TIMEOUT !== 'false',
|
enableAdaptiveTimeout: process.env.BAILEYS_BUFFER_ADAPTIVE_TIMEOUT !== 'false',
|
||||||
enableMetrics: process.env.BAILEYS_BUFFER_METRICS === 'true' || process.env.BAILEYS_PROMETHEUS_ENABLED === 'true',
|
enableMetrics: process.env.BAILEYS_BUFFER_METRICS === 'true' || process.env.BAILEYS_PROMETHEUS_ENABLED === 'true',
|
||||||
lruCleanupRatio: parseFloat(process.env.BAILEYS_BUFFER_LRU_CLEANUP_RATIO || '0.2'),
|
lruCleanupRatio: parseFloat(process.env.BAILEYS_BUFFER_LRU_CLEANUP_RATIO || '0.2'),
|
||||||
@@ -890,6 +891,7 @@ const makeBufferData = (): BufferedEventData => {
|
|||||||
chats: {},
|
chats: {},
|
||||||
messages: {},
|
messages: {},
|
||||||
contacts: {},
|
contacts: {},
|
||||||
|
pastParticipants: {},
|
||||||
isLatest: false,
|
isLatest: false,
|
||||||
empty: true
|
empty: true
|
||||||
},
|
},
|
||||||
@@ -967,6 +969,28 @@ function append<E extends BufferableEvent>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Merge pastParticipants with deduplication by groupJid and by userJid within each group.
|
||||||
|
// Multiple HistorySync chunks can carry the same group -- we merge rather than concatenate
|
||||||
|
// to avoid duplicate entries in the final event delivered to the consumer.
|
||||||
|
for (const group of (eventData.pastParticipants ?? []) as proto.IPastParticipants[]) {
|
||||||
|
const groupJid = group.groupJid
|
||||||
|
if (!groupJid) continue
|
||||||
|
|
||||||
|
if (!data.historySets.pastParticipants[groupJid]) {
|
||||||
|
data.historySets.pastParticipants[groupJid] = []
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = data.historySets.pastParticipants[groupJid]
|
||||||
|
const seenJids = new Set(existing.map(p => p.userJid).filter(Boolean))
|
||||||
|
|
||||||
|
for (const participant of (group.pastParticipants ?? []) as proto.IPastParticipant[]) {
|
||||||
|
if (participant.userJid && !seenJids.has(participant.userJid)) {
|
||||||
|
existing.push(participant)
|
||||||
|
seenJids.add(participant.userJid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
data.historySets.empty = false
|
data.historySets.empty = false
|
||||||
data.historySets.syncType = eventData.syncType
|
data.historySets.syncType = eventData.syncType
|
||||||
data.historySets.progress = eventData.progress
|
data.historySets.progress = eventData.progress
|
||||||
@@ -1292,6 +1316,10 @@ function consolidateEvents(data: BufferedEventData) {
|
|||||||
chats: Object.values(data.historySets.chats),
|
chats: Object.values(data.historySets.chats),
|
||||||
messages: Object.values(data.historySets.messages),
|
messages: Object.values(data.historySets.messages),
|
||||||
contacts: Object.values(data.historySets.contacts),
|
contacts: Object.values(data.historySets.contacts),
|
||||||
|
// Convert dedup map back to array. Each entry has groupJid + participants (all unique userJids).
|
||||||
|
pastParticipants: Object.entries(data.historySets.pastParticipants).map(
|
||||||
|
([groupJid, participants]) => ({ groupJid, pastParticipants: participants })
|
||||||
|
),
|
||||||
syncType: data.historySets.syncType,
|
syncType: data.historySets.syncType,
|
||||||
progress: data.historySets.progress,
|
progress: data.historySets.progress,
|
||||||
isLatest: data.historySets.isLatest,
|
isLatest: data.historySets.isLatest,
|
||||||
|
|||||||
@@ -429,6 +429,36 @@ export const getCallStatusFromNode = ({ tag, attrs }: BinaryNode) => {
|
|||||||
case 'accept':
|
case 'accept':
|
||||||
status = 'accept'
|
status = 'accept'
|
||||||
break
|
break
|
||||||
|
case 'preaccept':
|
||||||
|
status = 'preaccept'
|
||||||
|
break
|
||||||
|
case 'transport':
|
||||||
|
status = 'transport'
|
||||||
|
break
|
||||||
|
case 'relaylatency':
|
||||||
|
status = 'relaylatency'
|
||||||
|
break
|
||||||
|
case 'group_update':
|
||||||
|
status = 'group_update'
|
||||||
|
break
|
||||||
|
case 'reminder':
|
||||||
|
status = 'reminder'
|
||||||
|
break
|
||||||
|
case 'heartbeat':
|
||||||
|
status = 'heartbeat'
|
||||||
|
break
|
||||||
|
case 'mute_v2':
|
||||||
|
status = 'mute_v2'
|
||||||
|
break
|
||||||
|
case 'enc_rekey':
|
||||||
|
status = 'enc_rekey'
|
||||||
|
break
|
||||||
|
case 'video':
|
||||||
|
status = 'video'
|
||||||
|
break
|
||||||
|
case 'relay':
|
||||||
|
status = 'relay'
|
||||||
|
break
|
||||||
default:
|
default:
|
||||||
status = 'ringing'
|
status = 'ringing'
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -6,11 +6,12 @@
|
|||||||
* @module Utils/health-status
|
* @module Utils/health-status
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { globalCircuitRegistry } from './circuit-breaker.js'
|
|
||||||
import { getVersionCacheStatus } from './version-cache.js'
|
import { getVersionCacheStatus } from './version-cache.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Circuit breaker health information
|
* Circuit breaker health information (kept for k8s probe schema stability —
|
||||||
|
* always reports an empty list now that circuit breakers were removed in
|
||||||
|
* favour of bounded-retry).
|
||||||
*/
|
*/
|
||||||
export interface CircuitBreakerHealth {
|
export interface CircuitBreakerHealth {
|
||||||
name: string
|
name: string
|
||||||
@@ -105,44 +106,10 @@ export function getHealthStatus(): HealthStatus {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Check circuit breakers
|
// 2. Circuit breakers were removed in favour of bounded-retry.
|
||||||
|
// Keep the field for backward-compat with k8s probe schema, always empty.
|
||||||
const circuitBreakers: CircuitBreakerHealth[] = []
|
const circuitBreakers: CircuitBreakerHealth[] = []
|
||||||
let openCircuits = 0
|
checks.push({ name: 'circuit_breakers', status: 'pass' })
|
||||||
|
|
||||||
for (const [name, breaker] of globalCircuitRegistry.getAll()) {
|
|
||||||
const stats = breaker.getStats()
|
|
||||||
const state = breaker.getState()
|
|
||||||
|
|
||||||
circuitBreakers.push({
|
|
||||||
name,
|
|
||||||
state,
|
|
||||||
failures: stats.totalFailures,
|
|
||||||
successes: stats.totalSuccesses,
|
|
||||||
totalCalls: stats.totalCalls
|
|
||||||
})
|
|
||||||
|
|
||||||
if (state === 'open') {
|
|
||||||
openCircuits++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (openCircuits > 0) {
|
|
||||||
checks.push({
|
|
||||||
name: 'circuit_breakers',
|
|
||||||
status: openCircuits > 2 ? 'fail' : 'warn',
|
|
||||||
message: `${openCircuits} circuit breaker(s) are open`
|
|
||||||
})
|
|
||||||
if (openCircuits > 2) {
|
|
||||||
overallStatus = 'unhealthy'
|
|
||||||
} else if (overallStatus === 'healthy') {
|
|
||||||
overallStatus = 'degraded'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
checks.push({
|
|
||||||
name: 'circuit_breakers',
|
|
||||||
status: 'pass'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Check memory usage (warn if > 90%)
|
// 3. Check memory usage (warn if > 90%)
|
||||||
const memUsage = process.memoryUsage()
|
const memUsage = process.memoryUsage()
|
||||||
|
|||||||
+46
-13
@@ -1,5 +1,6 @@
|
|||||||
|
import { pipeline } from 'stream/promises'
|
||||||
import { promisify } from 'util'
|
import { promisify } from 'util'
|
||||||
import { inflate } from 'zlib'
|
import { createInflate, inflate } from 'zlib'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type { Chat, Contact, LIDMapping, WAMessage } from '../Types'
|
import type { Chat, Contact, LIDMapping, WAMessage } from '../Types'
|
||||||
import { WAMessageStubType } from '../Types'
|
import { WAMessageStubType } from '../Types'
|
||||||
@@ -15,7 +16,8 @@ import {
|
|||||||
import { toNumber } from './generics'
|
import { toNumber } from './generics'
|
||||||
import type { ILogger } from './logger.js'
|
import type { ILogger } from './logger.js'
|
||||||
import { normalizeMessageContent } from './messages'
|
import { normalizeMessageContent } from './messages'
|
||||||
import { downloadContentFromMessage } from './messages-media'
|
import { DEFAULT_ORIGIN } from '../Defaults'
|
||||||
|
import { downloadContentFromMessage, getUrlFromDirectPath } from './messages-media'
|
||||||
|
|
||||||
const inflatePromise = promisify(inflate)
|
const inflatePromise = promisify(inflate)
|
||||||
|
|
||||||
@@ -28,16 +30,15 @@ const inflatePromise = promisify(inflate)
|
|||||||
*/
|
*/
|
||||||
export const downloadHistory = async (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => {
|
export const downloadHistory = async (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => {
|
||||||
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
||||||
const bufferArray: Buffer[] = []
|
// Pipe decrypted stream directly through zlib inflate.
|
||||||
for await (const chunk of stream) {
|
// Avoids allocating an intermediate buffer for the compressed payload —
|
||||||
bufferArray.push(chunk)
|
// memory peaks during 50MB history syncs drop ~50% (PR upstream #2333).
|
||||||
}
|
const inflater = createInflate()
|
||||||
|
const chunks: Buffer[] = []
|
||||||
let buffer: Buffer = Buffer.concat(bufferArray)
|
inflater.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||||
|
await pipeline(stream, inflater)
|
||||||
// decompress buffer
|
|
||||||
buffer = await inflatePromise(buffer)
|
|
||||||
|
|
||||||
|
const buffer = Buffer.concat(chunks)
|
||||||
const syncData = proto.HistorySync.decode(buffer)
|
const syncData = proto.HistorySync.decode(buffer)
|
||||||
return syncData
|
return syncData
|
||||||
}
|
}
|
||||||
@@ -314,6 +315,7 @@ export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger
|
|||||||
contacts.push({
|
contacts.push({
|
||||||
id: chatId,
|
id: chatId,
|
||||||
name: chat.displayName || chat.name || chat.username || undefined,
|
name: chat.displayName || chat.name || chat.username || undefined,
|
||||||
|
username: chat.username || undefined,
|
||||||
lid: chat.lidJid || chat.accountLid || undefined,
|
lid: chat.lidJid || chat.accountLid || undefined,
|
||||||
phoneNumber: chat.pnJid || undefined
|
phoneNumber: chat.pnJid || undefined
|
||||||
})
|
})
|
||||||
@@ -359,7 +361,7 @@ export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
chats.push({ ...chat })
|
chats.push(chat)
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break
|
||||||
@@ -374,10 +376,25 @@ export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger
|
|||||||
// Convert Map back to array for return
|
// Convert Map back to array for return
|
||||||
const lidPnMappings = Array.from(lidPnMap.values())
|
const lidPnMappings = Array.from(lidPnMap.values())
|
||||||
|
|
||||||
|
// Normalize pastParticipants: resolve LID userJids → PN so the consumer always
|
||||||
|
// receives a phone number, never an opaque LID identifier.
|
||||||
|
// Uses the lidPnMap built above (populated from phoneNumberToLidMappings + conversations).
|
||||||
|
// If a LID cannot be resolved, the original value is kept rather than dropping the participant.
|
||||||
|
const pastParticipants: proto.IPastParticipants[] = (item.pastParticipants ?? []).map(group => ({
|
||||||
|
groupJid: group.groupJid,
|
||||||
|
pastParticipants: (group.pastParticipants ?? []).map(participant => {
|
||||||
|
const userJid = participant.userJid
|
||||||
|
if (!userJid || !isAnyLidUser(userJid)) return participant
|
||||||
|
const mapping = lidPnMap.get(jidNormalizedUser(userJid))
|
||||||
|
return mapping?.pn ? { ...participant, userJid: mapping.pn } : participant
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
chats,
|
chats,
|
||||||
contacts,
|
contacts,
|
||||||
messages,
|
messages,
|
||||||
|
pastParticipants,
|
||||||
lidPnMappings,
|
lidPnMappings,
|
||||||
syncType: item.syncType,
|
syncType: item.syncType,
|
||||||
progress: item.progress
|
progress: item.progress
|
||||||
@@ -408,7 +425,23 @@ export const downloadAndProcessHistorySyncNotification = async (
|
|||||||
historyMsg = await downloadHistory(msg, options)
|
historyMsg = await downloadHistory(msg, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
return processHistoryMessage(historyMsg, logger)
|
const result = processHistoryMessage(historyMsg, logger)
|
||||||
|
|
||||||
|
// Mirror WA Desktop behaviour: DELETE the CDN blob only after processing succeeds.
|
||||||
|
// Doing this earlier (e.g. inside downloadHistory) risks permanent history loss if
|
||||||
|
// processing throws — the server copy would be gone and retry after reconnect would fail.
|
||||||
|
if (msg.directPath) {
|
||||||
|
const cdnUrl = getUrlFromDirectPath(msg.directPath)
|
||||||
|
fetch(cdnUrl, {
|
||||||
|
...options,
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: { ...((options as RequestInit).headers ?? {}), Origin: DEFAULT_ORIGIN }
|
||||||
|
}).catch(() => {
|
||||||
|
// non-fatal — server will expire it anyway
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -57,6 +57,16 @@ export type IdentityChangeContext = {
|
|||||||
debounceCache: NodeCache<boolean>
|
debounceCache: NodeCache<boolean>
|
||||||
/** Logger instance for debugging and monitoring */
|
/** Logger instance for debugging and monitoring */
|
||||||
logger: ILogger
|
logger: ILogger
|
||||||
|
/**
|
||||||
|
* Invoked right before `assertSessions` is called for an existing-session identity
|
||||||
|
* change. Used to kick off fire-and-forget side effects (e.g. tctoken re-issuance)
|
||||||
|
* in the same order WA Web does — i.e. before the E2E session is re-established.
|
||||||
|
* Must not throw; implementations are responsible for their own error handling.
|
||||||
|
*
|
||||||
|
* Skipped when the refresh itself is skipped (no_identity_node, invalid_notification,
|
||||||
|
* skipped_companion_device, skipped_self_primary, debounced, skipped_offline).
|
||||||
|
*/
|
||||||
|
onBeforeSessionRefresh?: (jid: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -170,6 +180,19 @@ export async function handleIdentityChange(
|
|||||||
// This ensures we don't incorrectly debounce when we exit early (offline, etc.)
|
// This ensures we don't incorrectly debounce when we exit early (offline, etc.)
|
||||||
ctx.debounceCache.set(from, true)
|
ctx.debounceCache.set(from, true)
|
||||||
|
|
||||||
|
// Fire-and-forget side effects (e.g. tctoken re-issuance) BEFORE the session is
|
||||||
|
// re-established. WA Web runs these in parallel with the session refresh —
|
||||||
|
// running afterwards would race with the next outbound send and risk error 463.
|
||||||
|
//
|
||||||
|
// Wrapped in try/catch so a misbehaving consumer callback cannot abort identity
|
||||||
|
// change recovery. We log and continue — assertSessions still runs so the E2E
|
||||||
|
// session always gets refreshed.
|
||||||
|
try {
|
||||||
|
ctx.onBeforeSessionRefresh?.(from)
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.warn({ error, jid: from }, 'onBeforeSessionRefresh callback threw — continuing with session refresh')
|
||||||
|
}
|
||||||
|
|
||||||
// Attempt session refresh/creation
|
// Attempt session refresh/creation
|
||||||
try {
|
try {
|
||||||
await ctx.assertSessions([from], true)
|
await ctx.assertSessions([from], true)
|
||||||
|
|||||||
+1
-1
@@ -33,8 +33,8 @@ export * from './trace-context'
|
|||||||
export * from './prometheus-metrics'
|
export * from './prometheus-metrics'
|
||||||
|
|
||||||
// Resilience and performance
|
// Resilience and performance
|
||||||
|
export * from './bounded-retry'
|
||||||
export * from './cache-utils'
|
export * from './cache-utils'
|
||||||
export * from './circuit-breaker'
|
|
||||||
export * from './retry-utils'
|
export * from './retry-utils'
|
||||||
|
|
||||||
// Telemetry and detection mitigation
|
// Telemetry and detection mitigation
|
||||||
|
|||||||
@@ -211,15 +211,33 @@ export class MessageRetryManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MAC errors require IMMEDIATE session recreation regardless of history
|
// MAC errors require session recreation, but rate-limited to prevent loops.
|
||||||
// This handles the case where contact reinstalled WhatsApp (identity key changed)
|
// When multiple messages fail with Bad MAC simultaneously, only the first
|
||||||
|
// should trigger recreation; subsequent ones within the cooldown window
|
||||||
|
// piggyback on the same new session established by the retry+pkmsg flow.
|
||||||
if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
|
if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
|
||||||
this.sessionRecreateHistory.set(jid, Date.now())
|
const now = Date.now()
|
||||||
|
const prevTime = this.sessionRecreateHistory.get(jid)
|
||||||
|
const MAC_ERROR_COOLDOWN_MS = 1_000 // 1 second — WABA recovers faster
|
||||||
|
|
||||||
|
if (prevTime && now - prevTime < MAC_ERROR_COOLDOWN_MS) {
|
||||||
|
const reasonName = RetryReason[errorCode] || `code_${errorCode}`
|
||||||
|
this.logger.debug(
|
||||||
|
{ jid, errorCode: reasonName, msSinceLast: now - prevTime },
|
||||||
|
'MAC error session recreation skipped — cooldown active'
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
reason: '',
|
||||||
|
recreate: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sessionRecreateHistory.set(jid, now)
|
||||||
this.statistics.sessionRecreations++
|
this.statistics.sessionRecreations++
|
||||||
const reasonName = RetryReason[errorCode] || `code_${errorCode}`
|
const reasonName = RetryReason[errorCode] || `code_${errorCode}`
|
||||||
metrics.signalMacErrors?.inc({ action: 'session_recreation' })
|
metrics.signalMacErrors?.inc({ action: 'session_recreation' })
|
||||||
metrics.signalSessionRecreations?.inc({ reason: 'mac_error' })
|
metrics.signalSessionRecreations?.inc({ reason: 'mac_error' })
|
||||||
this.logger.warn({ jid, errorCode: reasonName }, 'MAC error detected, forcing immediate session recreation')
|
this.logger.warn({ jid, errorCode: reasonName }, 'MAC error detected, recreating session')
|
||||||
return {
|
return {
|
||||||
reason: `MAC error (${reasonName}) - contact may have reinstalled WhatsApp`,
|
reason: `MAC error (${reasonName}) - contact may have reinstalled WhatsApp`,
|
||||||
recreate: true
|
recreate: true
|
||||||
|
|||||||
@@ -10,7 +10,13 @@ import { join } from 'path'
|
|||||||
import { Readable, Transform } from 'stream'
|
import { Readable, Transform } from 'stream'
|
||||||
import { URL } from 'url'
|
import { URL } from 'url'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP, type MediaType } from '../Defaults'
|
import {
|
||||||
|
DEFAULT_ORIGIN,
|
||||||
|
MEDIA_HKDF_KEY_MAPPING,
|
||||||
|
MEDIA_PATH_MAP,
|
||||||
|
type MediaType,
|
||||||
|
NEWSLETTER_MEDIA_PATH_MAP
|
||||||
|
} from '../Defaults'
|
||||||
import type {
|
import type {
|
||||||
BaileysEventMap,
|
BaileysEventMap,
|
||||||
DownloadableMessage,
|
DownloadableMessage,
|
||||||
@@ -160,7 +166,7 @@ export const extractImageThumb = async (bufferOrFilePath: Readable | Buffer | st
|
|||||||
height: dimensions.height
|
height: dimensions.height
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
|
} else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
|
||||||
const jimp = await (lib.jimp.Jimp as any).read(bufferOrFilePath)
|
const jimp = await (lib.jimp.Jimp as any).read(bufferOrFilePath)
|
||||||
const dimensions = {
|
const dimensions = {
|
||||||
width: jimp.width,
|
width: jimp.width,
|
||||||
@@ -612,7 +618,7 @@ export const downloadEncryptedContent = async (
|
|||||||
|
|
||||||
const output = new Transform({
|
const output = new Transform({
|
||||||
transform(chunk, _, callback) {
|
transform(chunk, _, callback) {
|
||||||
let data = Buffer.concat([remainingBytes, chunk])
|
let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk
|
||||||
|
|
||||||
const decryptLength = toSmallestChunkSize(data.length)
|
const decryptLength = toSmallestChunkSize(data.length)
|
||||||
remainingBytes = data.slice(decryptLength)
|
remainingBytes = data.slice(decryptLength)
|
||||||
@@ -681,6 +687,10 @@ type MediaUploadResult = {
|
|||||||
meta_hmac?: string
|
meta_hmac?: string
|
||||||
ts?: number
|
ts?: number
|
||||||
fbid?: number
|
fbid?: number
|
||||||
|
thumbnail_info?: {
|
||||||
|
thumbnail_sha256?: string
|
||||||
|
thumbnail_direct_path?: string
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type UploadParams = {
|
export type UploadParams = {
|
||||||
@@ -825,11 +835,21 @@ export const getWAUploadToServer = (
|
|||||||
{ customUploadHosts, fetchAgent, logger, options }: SocketConfig,
|
{ customUploadHosts, fetchAgent, logger, options }: SocketConfig,
|
||||||
refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>
|
refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>
|
||||||
): WAMediaUploadFunction => {
|
): WAMediaUploadFunction => {
|
||||||
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
|
||||||
// send a query JSON to obtain the url & auth token to upload our media
|
// send a query JSON to obtain the url & auth token to upload our media
|
||||||
let uploadInfo = await refreshMediaConn(false)
|
let uploadInfo = await refreshMediaConn(false)
|
||||||
|
|
||||||
let urls: { mediaUrl: string; directPath: string; meta_hmac?: string; ts?: number; fbid?: number } | undefined
|
let urls:
|
||||||
|
| {
|
||||||
|
mediaUrl: string
|
||||||
|
directPath: string
|
||||||
|
meta_hmac?: string
|
||||||
|
ts?: number
|
||||||
|
fbid?: number
|
||||||
|
thumbnailDirectPath?: string
|
||||||
|
thumbnailSha256?: string
|
||||||
|
}
|
||||||
|
| undefined
|
||||||
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
const hosts = [...customUploadHosts, ...uploadInfo.hosts]
|
||||||
|
|
||||||
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64)
|
||||||
@@ -851,7 +871,11 @@ export const getWAUploadToServer = (
|
|||||||
logger.debug(`uploading to "${hostname}"`)
|
logger.debug(`uploading to "${hostname}"`)
|
||||||
|
|
||||||
const auth = encodeURIComponent(uploadInfo.auth)
|
const auth = encodeURIComponent(uploadInfo.auth)
|
||||||
const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
|
const mediaPath = (newsletter ? NEWSLETTER_MEDIA_PATH_MAP[mediaType] : undefined) || MEDIA_PATH_MAP[mediaType]
|
||||||
|
let url = `https://${hostname}${mediaPath}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
|
||||||
|
if (newsletter) {
|
||||||
|
url += '&server_thumb_gen=1'
|
||||||
|
}
|
||||||
|
|
||||||
let result: MediaUploadResult | undefined
|
let result: MediaUploadResult | undefined
|
||||||
try {
|
try {
|
||||||
@@ -868,11 +892,13 @@ export const getWAUploadToServer = (
|
|||||||
|
|
||||||
if (result?.url || result?.direct_path) {
|
if (result?.url || result?.direct_path) {
|
||||||
urls = {
|
urls = {
|
||||||
mediaUrl: result.url!,
|
mediaUrl: result.url || result.direct_path!,
|
||||||
directPath: result.direct_path!,
|
directPath: result.direct_path!,
|
||||||
meta_hmac: result.meta_hmac,
|
meta_hmac: result.meta_hmac,
|
||||||
fbid: result.fbid,
|
fbid: result.fbid,
|
||||||
ts: result.ts
|
ts: result.ts,
|
||||||
|
thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
|
||||||
|
thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+107
-14
@@ -41,9 +41,11 @@ import type { ILogger } from './logger'
|
|||||||
import {
|
import {
|
||||||
downloadContentFromMessage,
|
downloadContentFromMessage,
|
||||||
encryptedStream,
|
encryptedStream,
|
||||||
|
extractImageThumb,
|
||||||
generateThumbnail,
|
generateThumbnail,
|
||||||
getAudioDuration,
|
getAudioDuration,
|
||||||
getAudioWaveform,
|
getAudioWaveform,
|
||||||
|
getStream,
|
||||||
getRawMediaUploadData,
|
getRawMediaUploadData,
|
||||||
type MediaDownloadOptions
|
type MediaDownloadOptions
|
||||||
} from './messages-media'
|
} from './messages-media'
|
||||||
@@ -194,10 +196,11 @@ export const prepareWAMessageMedia = async (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const fileSha256B64 = fileSha256.toString('base64')
|
const fileSha256B64 = fileSha256.toString('base64')
|
||||||
const { mediaUrl, directPath } = await options.upload(filePath, {
|
const { directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
|
||||||
fileEncSha256B64: fileSha256B64,
|
fileEncSha256B64: fileSha256B64,
|
||||||
mediaType: mediaType,
|
mediaType: mediaType,
|
||||||
timeoutMs: options.mediaUploadTimeoutMs
|
timeoutMs: options.mediaUploadTimeoutMs,
|
||||||
|
newsletter: true
|
||||||
})
|
})
|
||||||
|
|
||||||
await fs.unlink(filePath)
|
await fs.unlink(filePath)
|
||||||
@@ -205,10 +208,12 @@ export const prepareWAMessageMedia = async (
|
|||||||
const obj = WAProto.Message.fromObject({
|
const obj = WAProto.Message.fromObject({
|
||||||
// todo: add more support here
|
// todo: add more support here
|
||||||
[`${mediaType}Message`]: (MessageTypeProto as any)[mediaType].fromObject({
|
[`${mediaType}Message`]: (MessageTypeProto as any)[mediaType].fromObject({
|
||||||
url: mediaUrl,
|
// url intentionally omitted — newsletters use directPath only
|
||||||
directPath,
|
directPath,
|
||||||
fileSha256,
|
fileSha256,
|
||||||
fileLength,
|
fileLength,
|
||||||
|
thumbnailDirectPath,
|
||||||
|
thumbnailSha256: thumbnailSha256 ? Buffer.from(thumbnailSha256, 'base64') : undefined,
|
||||||
...uploadData,
|
...uploadData,
|
||||||
media: undefined
|
media: undefined
|
||||||
})
|
})
|
||||||
@@ -234,7 +239,7 @@ export const prepareWAMessageMedia = async (
|
|||||||
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
|
const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
|
||||||
const requiresThumbnailComputation =
|
const requiresThumbnailComputation =
|
||||||
(mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined'
|
(mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined'
|
||||||
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true
|
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined'
|
||||||
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true
|
const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true
|
||||||
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation
|
const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation
|
||||||
const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(
|
const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(
|
||||||
@@ -252,7 +257,9 @@ export const prepareWAMessageMedia = async (
|
|||||||
(async () => {
|
(async () => {
|
||||||
const result = await options.upload(encFilePath, {
|
const result = await options.upload(encFilePath, {
|
||||||
fileEncSha256B64,
|
fileEncSha256B64,
|
||||||
mediaType,
|
// Use mediaTypeOverride for upload path (e.g. 'viewonce-image' → /o1/mms/image)
|
||||||
|
// Encryption already used the override via encryptedStream above
|
||||||
|
mediaType: options.mediaTypeOverride || mediaType,
|
||||||
timeoutMs: options.mediaUploadTimeoutMs
|
timeoutMs: options.mediaUploadTimeoutMs
|
||||||
})
|
})
|
||||||
logger?.debug({ mediaType, cacheableKey }, 'uploaded media')
|
logger?.debug({ mediaType, cacheableKey }, 'uploaded media')
|
||||||
@@ -290,7 +297,7 @@ export const prepareWAMessageMedia = async (
|
|||||||
logger?.debug('computed audio duration')
|
logger?.debug('computed audio duration')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (requiresWaveformProcessing) {
|
if (requiresWaveformProcessing && !uploadData.waveform) {
|
||||||
uploadData.waveform = await getAudioWaveform(filePath, logger)
|
uploadData.waveform = await getAudioWaveform(filePath, logger)
|
||||||
logger?.debug('processed waveform')
|
logger?.debug('processed waveform')
|
||||||
}
|
}
|
||||||
@@ -633,6 +640,59 @@ export const generateCarouselMessage = async (
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const recoverCarouselImageMetadata = async (
|
||||||
|
imageMessage: proto.Message.IImageMessage | null | undefined,
|
||||||
|
cardImage: WAMediaUpload,
|
||||||
|
cardTitle: string | undefined,
|
||||||
|
uploadOptions: MessageContentGenerationOptions
|
||||||
|
) => {
|
||||||
|
if (!imageMessage) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const missingThumbnail = !imageMessage.jpegThumbnail
|
||||||
|
const missingWidth = !imageMessage.width
|
||||||
|
const missingHeight = !imageMessage.height
|
||||||
|
if (!missingThumbnail && !missingWidth && !missingHeight) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { stream } = await getStream(cardImage, uploadOptions.options)
|
||||||
|
const { buffer, original } = await extractImageThumb(stream)
|
||||||
|
|
||||||
|
if (missingThumbnail) {
|
||||||
|
imageMessage.jpegThumbnail = buffer.toString('base64')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missingWidth && original.width) {
|
||||||
|
imageMessage.width = original.width
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missingHeight && original.height) {
|
||||||
|
imageMessage.height = original.height
|
||||||
|
}
|
||||||
|
|
||||||
|
uploadOptions.logger?.info(
|
||||||
|
{
|
||||||
|
cardTitle,
|
||||||
|
recoveredThumbnail: !!imageMessage.jpegThumbnail,
|
||||||
|
width: imageMessage.width,
|
||||||
|
height: imageMessage.height
|
||||||
|
},
|
||||||
|
'[CAROUSEL] Recovered image metadata from source media'
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
uploadOptions.logger?.warn(
|
||||||
|
{
|
||||||
|
cardTitle,
|
||||||
|
trace: error instanceof Error ? error.stack : String(error)
|
||||||
|
},
|
||||||
|
'[CAROUSEL] Failed source-media thumbnail fallback'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Map cards to the carousel format (processing media)
|
// Map cards to the carousel format (processing media)
|
||||||
const carouselCards = await Promise.all(
|
const carouselCards = await Promise.all(
|
||||||
cards.map(async card => {
|
cards.map(async card => {
|
||||||
@@ -648,6 +708,11 @@ export const generateCarouselMessage = async (
|
|||||||
if (hasMedia && mediaOptions) {
|
if (hasMedia && mediaOptions) {
|
||||||
if (card.image) {
|
if (card.image) {
|
||||||
const { imageMessage } = await prepareWAMessageMedia({ image: card.image }, mediaOptions)
|
const { imageMessage } = await prepareWAMessageMedia({ image: card.image }, mediaOptions)
|
||||||
|
|
||||||
|
// Mirror the working Pastorini-style result: every carousel image card should
|
||||||
|
// carry a jpegThumbnail and dimensions before it reaches the Web live renderer.
|
||||||
|
await recoverCarouselImageMetadata(imageMessage, card.image, card.title, mediaOptions)
|
||||||
|
|
||||||
// Validate image fields needed for WhatsApp rendering
|
// Validate image fields needed for WhatsApp rendering
|
||||||
if (imageMessage && !imageMessage.jpegThumbnail) {
|
if (imageMessage && !imageMessage.jpegThumbnail) {
|
||||||
mediaOptions.logger?.warn(
|
mediaOptions.logger?.warn(
|
||||||
@@ -1239,7 +1304,8 @@ export const generateWAMessageContent = async (
|
|||||||
}
|
}
|
||||||
// Pass options for media processing if cards have images/videos
|
// Pass options for media processing if cards have images/videos
|
||||||
const generated = await generateCarouselMessage(carouselOptions, options)
|
const generated = await generateCarouselMessage(carouselOptions, options)
|
||||||
// Direct interactiveMessage — no viewOnceMessage wrapper, no root header/body/footer
|
// Frida capture shows interactiveMessage DIRECT (field 45) in DSM — no viewOnceMessage wrapper
|
||||||
|
// Testing without wrapper: biz node + quality_control already match Pastorini CDP stanza
|
||||||
m.interactiveMessage = generated.interactiveMessage
|
m.interactiveMessage = generated.interactiveMessage
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
@@ -1686,22 +1752,49 @@ export const generateWAMessageContent = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
m = await prepareWAMessageMedia(message, options)
|
// For view-once media, upload to the one-time CDN (/o1/mms/*) instead of regular CDN
|
||||||
|
// WA Web view-once messages always have directPath: /o1/v/t24/... (not /v/t62.7118-24/...)
|
||||||
|
// Using the wrong CDN causes WA server to flag the account and breaks view-once capability
|
||||||
|
const isViewOnce = hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce
|
||||||
|
const viewOnceTypeMap: Record<string, string> = {
|
||||||
|
image: 'viewonce-image',
|
||||||
|
video: 'viewonce-video',
|
||||||
|
audio: 'viewonce-audio'
|
||||||
|
}
|
||||||
|
const viewOnceOverride = isViewOnce
|
||||||
|
? viewOnceTypeMap[Object.keys(message).find(k => k in viewOnceTypeMap) || '']
|
||||||
|
: undefined
|
||||||
|
m = await prepareWAMessageMedia(message, {
|
||||||
|
...options,
|
||||||
|
mediaTypeOverride: (viewOnceOverride as any) || options.mediaTypeOverride
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
|
if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
|
||||||
m = { viewOnceMessage: { message: m } }
|
// Also set viewOnce=true on the inner media message (required by WA app to render as view-once)
|
||||||
|
if (m.imageMessage) m.imageMessage.viewOnce = true
|
||||||
|
else if (m.videoMessage) m.videoMessage.viewOnce = true
|
||||||
|
else if (m.audioMessage) m.audioMessage.viewOnce = true
|
||||||
|
// Use viewOnceMessageV2 (field 55) — modern WA clients use this wrapper
|
||||||
|
// viewOnceMessage (field 37) is the old format which WA server no longer accepts with view_once_write
|
||||||
|
m = { viewOnceMessageV2: { message: m } }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasOptionalProperty(message, 'mentions') && message.mentions?.length) {
|
if (
|
||||||
|
(hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
|
||||||
|
(hasOptionalProperty(message, 'mentionAll') && message.mentionAll)
|
||||||
|
) {
|
||||||
const messageType = Object.keys(m)[0] as Extract<keyof proto.IMessage, MessageWithContextInfo>
|
const messageType = Object.keys(m)[0] as Extract<keyof proto.IMessage, MessageWithContextInfo>
|
||||||
if (messageType) {
|
if (messageType) {
|
||||||
const key = m[messageType]
|
const key = m[messageType]
|
||||||
if (key && 'contextInfo' in key && !!key.contextInfo) {
|
if (key && 'contextInfo' in key) {
|
||||||
|
key.contextInfo = key.contextInfo || {}
|
||||||
|
if (message.mentions?.length) {
|
||||||
key.contextInfo.mentionedJid = message.mentions
|
key.contextInfo.mentionedJid = message.mentions
|
||||||
} else if (key) {
|
}
|
||||||
key.contextInfo = {
|
|
||||||
mentionedJid: message.mentions
|
if (message.mentionAll) {
|
||||||
|
key.contextInfo.nonJidMentions = 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+287
-19
@@ -19,10 +19,13 @@ import type {
|
|||||||
WAMessage,
|
WAMessage,
|
||||||
WAMessageKey
|
WAMessageKey
|
||||||
} from '../Types'
|
} from '../Types'
|
||||||
|
import type { LIDMappingStore } from '../Signal/lid-mapping'
|
||||||
import { WAMessageStubType } from '../Types'
|
import { WAMessageStubType } from '../Types'
|
||||||
import { getContentType, normalizeMessageContent } from '../Utils/messages'
|
import { getContentType, normalizeMessageContent } from '../Utils/messages'
|
||||||
import {
|
import {
|
||||||
areJidsSameUser,
|
areJidsSameUser,
|
||||||
|
isAnyLidUser,
|
||||||
|
isAnyPnUser,
|
||||||
isHostedLidUser,
|
isHostedLidUser,
|
||||||
isHostedPnUser,
|
isHostedPnUser,
|
||||||
isJidBroadcast,
|
isJidBroadcast,
|
||||||
@@ -37,6 +40,7 @@ import { getKeyAuthor, toNumber } from './generics'
|
|||||||
import { downloadAndProcessHistorySyncNotification } from './history'
|
import { downloadAndProcessHistorySyncNotification } from './history'
|
||||||
import type { ILogger } from './logger'
|
import type { ILogger } from './logger'
|
||||||
import { metrics, recordHistorySyncMessages } from './prometheus-metrics.js'
|
import { metrics, recordHistorySyncMessages } from './prometheus-metrics.js'
|
||||||
|
import { buildMergedTcTokenIndexWrite } from './tc-token-utils'
|
||||||
|
|
||||||
type ProcessMessageContext = {
|
type ProcessMessageContext = {
|
||||||
shouldProcessHistoryMsg: boolean
|
shouldProcessHistoryMsg: boolean
|
||||||
@@ -59,6 +63,163 @@ const REAL_MSG_STUB_TYPES = new Set([
|
|||||||
|
|
||||||
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
|
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract tctoken / tcTokenTimestamp / tcTokenSenderTimestamp from history-sync chats
|
||||||
|
* and persist them to the `tctoken` store. Mirrors WA Web's `bulkCreateOrMerge` pass
|
||||||
|
* over the chat table during history sync.
|
||||||
|
*
|
||||||
|
* Why this matters: when a user logs in on a new device, the multi-device history sync
|
||||||
|
* is the only way that device learns about tctokens issued/received on the original
|
||||||
|
* device. Without this pass, the new device sends 1:1 messages with no tctoken until
|
||||||
|
* the contact triggers a fresh notification — which surfaces as error 463 in production.
|
||||||
|
*
|
||||||
|
* Monotonicity: we only overwrite an existing entry if the incoming timestamp is
|
||||||
|
* STRICTLY newer (`incoming > existing`). Equal timestamps are skipped to avoid
|
||||||
|
* reverting senderTimestamp / realIssueTimestamp set by other layers (e.g. a
|
||||||
|
* reissue that fired between history-sync chunks).
|
||||||
|
*
|
||||||
|
* Index hygiene: every JID we write here is added to the persistent prune index
|
||||||
|
* (TC_TOKEN_INDEX_KEY) via buildMergedTcTokenIndexWrite, so the 24h prune sweep in
|
||||||
|
* messages-recv picks them up across sessions.
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* Single-concurrency queue for `storeTcTokensFromHistorySync` calls.
|
||||||
|
*
|
||||||
|
* Why: the function does read-then-write merges (`keyStore.get('tctoken', ...)` →
|
||||||
|
* compute → `keyStore.set(...)`) which are NOT atomic at the store level. If two
|
||||||
|
* history-sync chunks invoke this concurrently (common during reconnect / QR
|
||||||
|
* scan), an older chunk that started first can `keyStore.set` AFTER a newer
|
||||||
|
* chunk, overwriting the newer entry — and worse, the merged `__index` write
|
||||||
|
* can drop JIDs the other chunk just added. Result: stale tcTokens / repeat 463
|
||||||
|
* sends until the next opportunistic refetch.
|
||||||
|
*
|
||||||
|
* Serialising via a chained Promise keeps the runs ordered while still freeing
|
||||||
|
* the calling `processMessage` to emit `messaging-history.set` immediately
|
||||||
|
* (the chain is fire-and-forget at the call site). Errors don't break the chain
|
||||||
|
* — each `catch` resets it to `Promise.resolve()` so a single failure can't
|
||||||
|
* stall future runs.
|
||||||
|
*
|
||||||
|
* The chain is module-scoped (one per Node process). Multiple Baileys instances
|
||||||
|
* sharing this module will serialise across instances too, but their writes
|
||||||
|
* target different keyStores so there's no correctness gain — only a tiny loss
|
||||||
|
* of inter-instance parallelism for tcToken syncs, which is acceptable given
|
||||||
|
* how rarely this runs vs. how rare cross-instance contention is.
|
||||||
|
*/
|
||||||
|
let historyTcTokenChain: Promise<void> = Promise.resolve()
|
||||||
|
|
||||||
|
function scheduleHistoryTcTokenSync(
|
||||||
|
chats: Chat[],
|
||||||
|
signalRepository: SignalRepositoryWithLIDStore,
|
||||||
|
keyStore: SignalKeyStoreWithTransaction,
|
||||||
|
logger?: ILogger
|
||||||
|
): void {
|
||||||
|
historyTcTokenChain = historyTcTokenChain
|
||||||
|
.catch(() => {
|
||||||
|
/* swallow prior error so chain stays alive */
|
||||||
|
})
|
||||||
|
.then(() => storeTcTokensFromHistorySync(chats, signalRepository, keyStore, logger))
|
||||||
|
.catch(err => {
|
||||||
|
logger?.warn({ err }, 'background tctoken history-sync persistence failed')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function storeTcTokensFromHistorySync(
|
||||||
|
chats: Chat[],
|
||||||
|
signalRepository: SignalRepositoryWithLIDStore,
|
||||||
|
keyStore: SignalKeyStoreWithTransaction,
|
||||||
|
logger?: ILogger
|
||||||
|
) {
|
||||||
|
// Cheap filter first — most chats in a sync chunk don't carry tcToken at all,
|
||||||
|
// and we want to avoid spinning up promises for them.
|
||||||
|
const tokenChats = chats.filter(chat => {
|
||||||
|
const ts = chat.tcTokenTimestamp ? toNumber(chat.tcTokenTimestamp) : 0
|
||||||
|
return !!chat.tcToken?.length && ts > 0
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!tokenChats.length) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-normalize so the rest of the pipeline is a synchronous join.
|
||||||
|
const normalized = tokenChats.map(chat => ({
|
||||||
|
chat,
|
||||||
|
ts: toNumber(chat.tcTokenTimestamp!),
|
||||||
|
jid: jidNormalizedUser(chat.id!)
|
||||||
|
}))
|
||||||
|
|
||||||
|
// BATCHED LID resolution. The previous shape called getLIDForPN once per
|
||||||
|
// chat (sequential await inside a for-of), which became the bottleneck
|
||||||
|
// during heavy history sync — every cold-cache hit was a DB round-trip,
|
||||||
|
// stalling messaging-history.set and spilling into the event-buffer.
|
||||||
|
// `getLIDsForPNs` resolves a deduped list in ONE batched query (and shares
|
||||||
|
// USync retry across PNs that miss cache), turning O(N) round-trips into 1.
|
||||||
|
//
|
||||||
|
// LID inputs (and `@hosted.lid`) skip the lookup entirely — they're already
|
||||||
|
// the storage form. Failures degrade gracefully: a missing mapping just
|
||||||
|
// stores under the original jid, matching `resolveTcTokenJid`'s null branch.
|
||||||
|
const pnsToResolve = [...new Set(normalized.filter(({ jid }) => !isLidUser(jid)).map(({ jid }) => jid))]
|
||||||
|
const pnToLid = new Map<string, string>()
|
||||||
|
|
||||||
|
if (pnsToResolve.length) {
|
||||||
|
try {
|
||||||
|
const mappings = await signalRepository.lidMapping.getLIDsForPNs(pnsToResolve)
|
||||||
|
// Flat loop (continue-on-skip) keeps max nesting depth at 4 for lint.
|
||||||
|
for (const { pn, lid } of mappings ?? []) {
|
||||||
|
if (!pn || !lid) continue
|
||||||
|
pnToLid.set(jidNormalizedUser(pn), lid)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Per-chat fallback below (storageJid := jid). Don't abort the chunk —
|
||||||
|
// CodeRabbit noted that all-or-nothing rejection here would drop every
|
||||||
|
// tctoken in the batch AND prevent messaging-history.set from firing.
|
||||||
|
logger?.warn({ err }, 'storeTcTokensFromHistorySync: getLIDsForPNs batch failed; falling back to per-chat jid')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidates = normalized.map(({ chat, ts, jid }) => ({
|
||||||
|
storageJid: pnToLid.get(jid) ?? jid,
|
||||||
|
token: Buffer.from(chat.tcToken!),
|
||||||
|
ts,
|
||||||
|
senderTs: chat.tcTokenSenderTimestamp ? toNumber(chat.tcTokenSenderTimestamp) : undefined
|
||||||
|
}))
|
||||||
|
|
||||||
|
const jids = candidates.map(c => c.storageJid)
|
||||||
|
const existing = await keyStore.get('tctoken', jids)
|
||||||
|
const entries: Record<string, { token: Buffer; timestamp?: string; senderTimestamp?: number }> = {}
|
||||||
|
|
||||||
|
for (const c of candidates) {
|
||||||
|
// Same-batch dedup: when two chats resolve to the same storageJid (e.g. PN+LID
|
||||||
|
// aliases collapsing through resolveTcTokenJid, or duplicate chunks across
|
||||||
|
// retries), prefer the value already written by an earlier iteration so a
|
||||||
|
// lower-ts entry can't overwrite a higher-ts one captured from `existing`.
|
||||||
|
const existingEntry = entries[c.storageJid] ?? existing[c.storageJid]
|
||||||
|
const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
|
||||||
|
// Strict > guard: equal timestamps are skipped so we never clobber
|
||||||
|
// senderTimestamp written by other layers (issuance after send, etc).
|
||||||
|
if (existingTs > 0 && existingTs >= c.ts) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
entries[c.storageJid] = {
|
||||||
|
...existingEntry,
|
||||||
|
token: c.token,
|
||||||
|
timestamp: String(c.ts),
|
||||||
|
...(c.senderTs !== undefined ? { senderTimestamp: c.senderTs } : {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(entries).length) {
|
||||||
|
logger?.debug({ count: Object.keys(entries).length }, 'storing tctokens from history sync')
|
||||||
|
try {
|
||||||
|
// Include updated __index so cross-session pruning picks these JIDs up.
|
||||||
|
const indexWrite = await buildMergedTcTokenIndexWrite(keyStore, Object.keys(entries))
|
||||||
|
await keyStore.set({ tctoken: { ...entries, ...indexWrite } })
|
||||||
|
} catch (err) {
|
||||||
|
logger?.warn({ err }, 'failed to store tctokens from history sync')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Cleans a received message to further processing */
|
/** Cleans a received message to further processing */
|
||||||
export const cleanMessage = (message: WAMessage, meId: string, meLid: string) => {
|
export const cleanMessage = (message: WAMessage, meId: string, meLid: string) => {
|
||||||
// ensure remoteJid and participant doesn't have device or agent in it
|
// ensure remoteJid and participant doesn't have device or agent in it
|
||||||
@@ -113,26 +274,36 @@ export const cleanMessage = (message: WAMessage, meId: string, meLid: string) =>
|
|||||||
msgKey.remoteJid = message.key.remoteJid
|
msgKey.remoteJid = message.key.remoteJid
|
||||||
// set participant of the message
|
// set participant of the message
|
||||||
msgKey.participant = msgKey.participant || message.key.participant
|
msgKey.participant = msgKey.participant || message.key.participant
|
||||||
|
} else {
|
||||||
|
// fromMe reactions/polls: normalise remoteJid to match the chat JID
|
||||||
|
// ensures DM reaction keys are consistent with group behavior
|
||||||
|
msgKey.remoteJid = message.key.remoteJid
|
||||||
|
// in groups, normalise participant for own messages too
|
||||||
|
if (message.key.participant) {
|
||||||
|
msgKey.participant = msgKey.participant || message.key.participant
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const normalizeMessageJids = async (
|
/**
|
||||||
message: WAMessage,
|
* Resolves a LID JID to its PN equivalent using the LID mapping store.
|
||||||
signalRepository: SignalRepositoryWithLIDStore,
|
* Returns the original JID if it's not a LID or if no mapping is found.
|
||||||
|
* Safe to call with any JID type (group, newsletter, PN, etc.).
|
||||||
|
*/
|
||||||
|
export const resolveLidToPn = async (
|
||||||
|
jid: string | undefined | null,
|
||||||
|
lidMapping: LIDMappingStore,
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
): Promise<void> => {
|
): Promise<string | undefined> => {
|
||||||
const resolveLidToPn = async (jid: string | undefined | null): Promise<string | undefined> => {
|
|
||||||
if (!jid) {
|
if (!jid) {
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
if (isAnyLidUser(jid)) {
|
||||||
const pn = await signalRepository.lidMapping.getPNForLID(jid)
|
const pn = await lidMapping.getPNForLID(jid)
|
||||||
if (pn) {
|
if (pn) {
|
||||||
logger?.debug({ lid: jid, pn }, 'Resolved LID to PN for inbound message')
|
logger?.debug({ lid: jid, pn }, 'Resolved LID to PN')
|
||||||
} else {
|
|
||||||
logger?.debug({ lid: jid }, 'PN not found for inbound LID, keeping LID')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return pn || jid
|
return pn || jid
|
||||||
@@ -141,18 +312,68 @@ export const normalizeMessageJids = async (
|
|||||||
return jid
|
return jid
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute both lookups in parallel instead of sequentially to reduce latency
|
/**
|
||||||
|
* Normalizes a WAMessageKey by resolving LID→PN for remoteJid and participant.
|
||||||
|
*/
|
||||||
|
export const normalizeKeyLidToPn = async (
|
||||||
|
key: WAMessageKey,
|
||||||
|
lidMapping: LIDMappingStore,
|
||||||
|
logger?: ILogger
|
||||||
|
): Promise<void> => {
|
||||||
const [resolvedRemoteJid, resolvedParticipant] = await Promise.all([
|
const [resolvedRemoteJid, resolvedParticipant] = await Promise.all([
|
||||||
resolveLidToPn(message.key.remoteJid),
|
resolveLidToPn(key.remoteJid, lidMapping, logger),
|
||||||
resolveLidToPn(message.key.participant)
|
resolveLidToPn(key.participant, lidMapping, logger)
|
||||||
])
|
])
|
||||||
|
|
||||||
if (resolvedRemoteJid) {
|
if (resolvedRemoteJid) {
|
||||||
message.key.remoteJid = resolvedRemoteJid
|
key.remoteJid = resolvedRemoteJid
|
||||||
}
|
}
|
||||||
|
|
||||||
if (resolvedParticipant) {
|
if (resolvedParticipant) {
|
||||||
message.key.participant = resolvedParticipant
|
key.participant = resolvedParticipant
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const normalizeMessageJids = async (
|
||||||
|
message: WAMessage,
|
||||||
|
signalRepository: SignalRepositoryWithLIDStore,
|
||||||
|
logger?: ILogger
|
||||||
|
): Promise<void> => {
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
|
const key = message.key
|
||||||
|
|
||||||
|
// FAST PATH: Use alt JIDs directly when available (avoids LIDMappingStore race condition).
|
||||||
|
// The stanza always carries both formats (LID + PN) in the attributes.
|
||||||
|
// When addressing_mode=lid, remoteJid is LID and remoteJidAlt is PN.
|
||||||
|
// When addressing_mode=pn, remoteJid is already PN (no conversion needed).
|
||||||
|
if (key.remoteJid && isAnyLidUser(key.remoteJid) && key.remoteJidAlt && isAnyPnUser(key.remoteJidAlt)) {
|
||||||
|
logger?.debug({ lid: key.remoteJid, pn: key.remoteJidAlt }, 'Resolved remoteJid LID→PN via alt (fast path)')
|
||||||
|
key.remoteJid = key.remoteJidAlt
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key.participant && isAnyLidUser(key.participant) && key.participantAlt && isAnyPnUser(key.participantAlt)) {
|
||||||
|
logger?.debug({ lid: key.participant, pn: key.participantAlt }, 'Resolved participant LID→PN via alt (fast path)')
|
||||||
|
key.participant = key.participantAlt
|
||||||
|
}
|
||||||
|
|
||||||
|
// SLOW PATH: Resolve any remaining LIDs via LIDMappingStore lookup
|
||||||
|
await normalizeKeyLidToPn(key, lidMapping, logger)
|
||||||
|
|
||||||
|
// Also normalize participantAlt (the alternative JID format — can be LID when addressing_mode=pn)
|
||||||
|
if (key.participantAlt && isAnyLidUser(key.participantAlt)) {
|
||||||
|
const resolved = await resolveLidToPn(key.participantAlt, lidMapping, logger)
|
||||||
|
if (resolved) {
|
||||||
|
key.participantAlt = resolved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize nested message keys (reaction, poll) that may contain LID JIDs
|
||||||
|
const content = normalizeMessageContent(message.message)
|
||||||
|
if (content?.reactionMessage?.key) {
|
||||||
|
await normalizeKeyLidToPn(content.reactionMessage.key, lidMapping, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (content?.pollUpdateMessage?.pollCreationMessageKey) {
|
||||||
|
await normalizeKeyLidToPn(content.pollUpdateMessage.pollCreationMessageKey, lidMapping, logger)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -355,6 +576,12 @@ const processMessage = async (
|
|||||||
|
|
||||||
// Emit LID-PN mappings from history sync
|
// Emit LID-PN mappings from history sync
|
||||||
// This is how WhatsApp Web learns mappings for chats with non-contacts
|
// This is how WhatsApp Web learns mappings for chats with non-contacts
|
||||||
|
//
|
||||||
|
// MUST run BEFORE storeTcTokensFromHistorySync — otherwise resolveTcTokenJid()
|
||||||
|
// can't resolve PN→LID for fresh-device chats (mapping cache is empty), tokens
|
||||||
|
// get persisted under PN keys, and the send path (which resolves to LID first)
|
||||||
|
// misses them — exactly the error 463 scenario this whole change is meant to
|
||||||
|
// prevent. Catches Codex P1 review on PR #386.
|
||||||
if (data.lidPnMappings?.length) {
|
if (data.lidPnMappings?.length) {
|
||||||
logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync')
|
logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync')
|
||||||
// eslint-disable-next-line max-depth
|
// eslint-disable-next-line max-depth
|
||||||
@@ -379,6 +606,29 @@ const processMessage = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Persist tctokens carried by history-sync chats in BACKGROUND, serialised.
|
||||||
|
//
|
||||||
|
// Originally awaited (PR #386) to avoid 463 on first multi-device send, but in
|
||||||
|
// production this drained the event buffer per-chunk and added visible delivery
|
||||||
|
// latency (especially after restart / QR scan when many chunks arrived at once).
|
||||||
|
//
|
||||||
|
// `scheduleHistoryTcTokenSync` enqueues onto a single-concurrency promise chain
|
||||||
|
// (see definition above) — chunks persist sequentially in the order they were
|
||||||
|
// emitted, preserving timestamp monotonicity AND keeping the `__index` write
|
||||||
|
// safe from concurrent merge clobbers. The call returns immediately so the
|
||||||
|
// `messaging-history.set` emit is not blocked.
|
||||||
|
//
|
||||||
|
// TRADE-OFF: a listener that fires an outbound send IMMEDIATELY after the emit
|
||||||
|
// may race the still-pending persistence and get a 463 on that specific send.
|
||||||
|
// The existing 463 handler in messages-recv.ts triggers a getPrivacyTokens()
|
||||||
|
// refetch that auto-recovers within seconds. Net result is much better UX than
|
||||||
|
// per-chunk stalls.
|
||||||
|
//
|
||||||
|
// DO NOT add `await` back here without re-evaluating production latency, AND
|
||||||
|
// DO NOT call storeTcTokensFromHistorySync directly — it must go through the
|
||||||
|
// chain to preserve write ordering across overlapping chunks.
|
||||||
|
scheduleHistoryTcTokenSync(data.chats, signalRepository, keyStore, logger)
|
||||||
|
|
||||||
ev.emit('messaging-history.set', {
|
ev.emit('messaging-history.set', {
|
||||||
...data,
|
...data,
|
||||||
isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
|
isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
|
||||||
@@ -526,6 +776,12 @@ const processMessage = async (
|
|||||||
'CTWA: Successfully recovered message via placeholder resend'
|
'CTWA: Successfully recovered message via placeholder resend'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Normalize LID→PN in PDO-recovered message key before emitting
|
||||||
|
// eslint-disable-next-line max-depth
|
||||||
|
if (webMessageInfo.key && signalRepository) {
|
||||||
|
await normalizeKeyLidToPn(webMessageInfo.key as WAMessageKey, signalRepository.lidMapping, logger)
|
||||||
|
}
|
||||||
|
|
||||||
// wait till another upsert event is available, don't want it to be part of the PDO response message
|
// wait till another upsert event is available, don't want it to be part of the PDO response message
|
||||||
// TODO: parse through proper message handling utilities (to add relevant key fields)
|
// TODO: parse through proper message handling utilities (to add relevant key fields)
|
||||||
ev.emit('messages.upsert', {
|
ev.emit('messages.upsert', {
|
||||||
@@ -666,9 +922,13 @@ const processMessage = async (
|
|||||||
response: responseMsg
|
response: responseMsg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Normalize creationMsgKey JIDs for the emitted event
|
||||||
|
const normalizedCreationKey = { ...creationMsgKey }
|
||||||
|
await normalizeKeyLidToPn(normalizedCreationKey, signalRepository.lidMapping, logger)
|
||||||
|
|
||||||
ev.emit('messages.update', [
|
ev.emit('messages.update', [
|
||||||
{
|
{
|
||||||
key: creationMsgKey,
|
key: normalizedCreationKey,
|
||||||
update: {
|
update: {
|
||||||
eventResponses: [eventResponse]
|
eventResponses: [eventResponse]
|
||||||
}
|
}
|
||||||
@@ -690,12 +950,19 @@ const processMessage = async (
|
|||||||
id: jid,
|
id: jid,
|
||||||
author: message.key.participant!,
|
author: message.key.participant!,
|
||||||
authorPn: message.key.participantAlt!,
|
authorPn: message.key.participantAlt!,
|
||||||
|
authorUsername: message.key.participantUsername!,
|
||||||
participants,
|
participants,
|
||||||
action
|
action
|
||||||
})
|
})
|
||||||
const emitGroupUpdate = (update: Partial<GroupMetadata>) => {
|
const emitGroupUpdate = (update: Partial<GroupMetadata>) => {
|
||||||
ev.emit('groups.update', [
|
ev.emit('groups.update', [
|
||||||
{ id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt }
|
{
|
||||||
|
id: jid,
|
||||||
|
...update,
|
||||||
|
author: message.key.participant ?? undefined,
|
||||||
|
authorPn: message.key.participantAlt,
|
||||||
|
authorUsername: message.key.participantUsername
|
||||||
|
}
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -704,6 +971,7 @@ const processMessage = async (
|
|||||||
id: jid,
|
id: jid,
|
||||||
author: message.key.participant!,
|
author: message.key.participant!,
|
||||||
authorPn: message.key.participantAlt!,
|
authorPn: message.key.participantAlt!,
|
||||||
|
authorUsername: message.key.participantUsername!,
|
||||||
participant: participant.lid,
|
participant: participant.lid,
|
||||||
participantPn: participant.pn,
|
participantPn: participant.pn,
|
||||||
action,
|
action,
|
||||||
@@ -711,7 +979,7 @@ const processMessage = async (
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)) // ADD SUPPORT FOR LID
|
const participantsIncludesMe = () => participants.find(p => areJidsSameUser(meId, p.id) || areJidsSameUser(meId, p.phoneNumber))
|
||||||
|
|
||||||
switch (message.messageStubType) {
|
switch (message.messageStubType) {
|
||||||
case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
|
case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
|
||||||
|
|||||||
@@ -1570,26 +1570,6 @@ export const metrics = {
|
|||||||
new Counter('socket_reconnects_total', 'Total socket reconnection attempts', ['reason'])
|
new Counter('socket_reconnects_total', 'Total socket reconnection attempts', ['reason'])
|
||||||
),
|
),
|
||||||
|
|
||||||
// ========== Circuit Breaker Metrics ==========
|
|
||||||
circuitBreakerState: baileysMetrics.register(
|
|
||||||
new Gauge('circuit_breaker_state', 'Circuit breaker state (0=closed, 1=open, 2=half-open)', ['name'])
|
|
||||||
),
|
|
||||||
circuitBreakerTrips: baileysMetrics.register(
|
|
||||||
new Counter('circuit_breaker_trips_total', 'Total circuit breaker trips', ['name'])
|
|
||||||
),
|
|
||||||
circuitBreakerRecoveries: baileysMetrics.register(
|
|
||||||
new Counter('circuit_breaker_recoveries_total', 'Total circuit breaker recoveries', ['name'])
|
|
||||||
),
|
|
||||||
circuitBreakerRejections: baileysMetrics.register(
|
|
||||||
new Counter('circuit_breaker_rejections_total', 'Total requests rejected by circuit breaker', ['name'])
|
|
||||||
),
|
|
||||||
circuitBreakerSuccesses: baileysMetrics.register(
|
|
||||||
new Counter('circuit_breaker_successes_total', 'Total successful requests through circuit breaker', ['name'])
|
|
||||||
),
|
|
||||||
circuitBreakerFailures: baileysMetrics.register(
|
|
||||||
new Counter('circuit_breaker_failures_total', 'Total failed requests through circuit breaker', ['name'])
|
|
||||||
),
|
|
||||||
|
|
||||||
// ========== Encryption Metrics ==========
|
// ========== Encryption Metrics ==========
|
||||||
encryptionOperations: baileysMetrics.register(
|
encryptionOperations: baileysMetrics.register(
|
||||||
new Counter('encryption_operations_total', 'Total encryption operations', ['operation'])
|
new Counter('encryption_operations_total', 'Total encryption operations', ['operation'])
|
||||||
@@ -2167,9 +2147,6 @@ function initializeMetricsWithLabels(): void {
|
|||||||
metrics.messageFailures?.inc({ type: 'text', reason: 'max_retries' }, 0)
|
metrics.messageFailures?.inc({ type: 'text', reason: 'max_retries' }, 0)
|
||||||
metrics.messageFailures?.inc({ type: 'other', reason: 'max_retries' }, 0)
|
metrics.messageFailures?.inc({ type: 'other', reason: 'max_retries' }, 0)
|
||||||
|
|
||||||
// Circuit breaker metric
|
|
||||||
metrics.circuitBreakerTrips?.inc({ name: 'main' }, 0)
|
|
||||||
|
|
||||||
console.log('[Prometheus] Initialized metrics with labels')
|
console.log('[Prometheus] Initialized metrics with labels')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[Prometheus] Error initializing metrics with labels:', error)
|
console.error('[Prometheus] Error initializing metrics with labels:', error)
|
||||||
|
|||||||
+13
-148
@@ -6,15 +6,21 @@
|
|||||||
* - Jitter to avoid thundering herd
|
* - Jitter to avoid thundering herd
|
||||||
* - Configurable max attempts
|
* - Configurable max attempts
|
||||||
* - Customizable retry predicates
|
* - Customizable retry predicates
|
||||||
* - Circuit breaker integration
|
* - Cancellation support (AbortSignal)
|
||||||
* - Event hooks
|
*
|
||||||
* - Cancellation support
|
* Used by `decode-wa-message.ts` for Bad MAC retry recovery on the decrypt
|
||||||
|
* path. For socket-operation retries (uploadPreKeys etc.) prefer
|
||||||
|
* `withBoundedRetry` from `./bounded-retry.ts`, which is empirically
|
||||||
|
* aligned with WhatsApp Android's per-operation backoff.
|
||||||
|
*
|
||||||
|
* NOTE: the previous `circuitBreaker` integration option, the `withRetry`
|
||||||
|
* decorator, the `retryable` wrapper and the `RetryManager` class were
|
||||||
|
* removed when the socket-level circuit breaker was retired — see PR #393
|
||||||
|
* for the rationale.
|
||||||
*
|
*
|
||||||
* @module Utils/retry-utils
|
* @module Utils/retry-utils
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { EventEmitter } from 'events'
|
|
||||||
import type { CircuitBreaker } from './circuit-breaker.js'
|
|
||||||
import { metrics } from './prometheus-metrics.js'
|
import { metrics } from './prometheus-metrics.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,8 +65,6 @@ export interface RetryOptions {
|
|||||||
operationName?: string
|
operationName?: string
|
||||||
/** Collect metrics */
|
/** Collect metrics */
|
||||||
collectMetrics?: boolean
|
collectMetrics?: boolean
|
||||||
/** Circuit breaker for integration */
|
|
||||||
circuitBreaker?: CircuitBreaker
|
|
||||||
/** Callback before each retry */
|
/** Callback before each retry */
|
||||||
onRetry?: (error: Error, attempt: number, delay: number) => void | Promise<void>
|
onRetry?: (error: Error, attempt: number, delay: number) => void | Promise<void>
|
||||||
/** Callback on success */
|
/** Callback on success */
|
||||||
@@ -283,7 +287,6 @@ export async function retry<T>(
|
|||||||
timeout: options.timeout,
|
timeout: options.timeout,
|
||||||
operationName: options.operationName ?? 'operation',
|
operationName: options.operationName ?? 'operation',
|
||||||
collectMetrics: options.collectMetrics ?? true,
|
collectMetrics: options.collectMetrics ?? true,
|
||||||
circuitBreaker: options.circuitBreaker,
|
|
||||||
onRetry: options.onRetry ?? (() => {}),
|
onRetry: options.onRetry ?? (() => {}),
|
||||||
onSuccess: options.onSuccess ?? (() => {}),
|
onSuccess: options.onSuccess ?? (() => {}),
|
||||||
onFailure: options.onFailure ?? (() => {}),
|
onFailure: options.onFailure ?? (() => {}),
|
||||||
@@ -313,11 +316,6 @@ export async function retry<T>(
|
|||||||
throw new RetryAbortedError(attempt)
|
throw new RetryAbortedError(attempt)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check circuit breaker
|
|
||||||
if (config.circuitBreaker?.isOpen()) {
|
|
||||||
throw new Error(`Circuit breaker "${config.circuitBreaker.getName()}" is open`)
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Execute operation
|
// Execute operation
|
||||||
let result: T
|
let result: T
|
||||||
@@ -425,138 +423,6 @@ export function createRetrier(defaultOptions: RetryOptions = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Decorator to add retry to method
|
|
||||||
*/
|
|
||||||
export function withRetry(options: RetryOptions = {}) {
|
|
||||||
return function (
|
|
||||||
_target: unknown,
|
|
||||||
propertyKey: string,
|
|
||||||
descriptor: TypedPropertyDescriptor<(...args: unknown[]) => unknown>
|
|
||||||
) {
|
|
||||||
const originalMethod = descriptor.value
|
|
||||||
if (!originalMethod) return descriptor
|
|
||||||
|
|
||||||
descriptor.value = async function (...args: unknown[]): Promise<unknown> {
|
|
||||||
return retry(() => originalMethod.apply(this, args), {
|
|
||||||
...options,
|
|
||||||
operationName: options.operationName || propertyKey
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return descriptor
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wrapper for function with retry
|
|
||||||
*/
|
|
||||||
// eslint-disable-next-line space-before-function-paren
|
|
||||||
export function retryable<T extends (...args: unknown[]) => unknown>(
|
|
||||||
fn: T,
|
|
||||||
options: RetryOptions = {}
|
|
||||||
): (...args: Parameters<T>) => Promise<ReturnType<T>> {
|
|
||||||
return async (...args: Parameters<T>): Promise<ReturnType<T>> => {
|
|
||||||
return retry(() => fn(...args), options) as Promise<ReturnType<T>>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class to manage retries with state
|
|
||||||
*/
|
|
||||||
export class RetryManager extends EventEmitter {
|
|
||||||
private activeRetries: Map<string, { cancel: () => void; context: RetryContext }> = new Map()
|
|
||||||
private defaultOptions: RetryOptions
|
|
||||||
|
|
||||||
constructor(defaultOptions: RetryOptions = {}) {
|
|
||||||
super()
|
|
||||||
this.defaultOptions = defaultOptions
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute operation with retry
|
|
||||||
*/
|
|
||||||
async execute<T>(
|
|
||||||
id: string,
|
|
||||||
operation: (context: RetryContext) => T | Promise<T>,
|
|
||||||
options?: RetryOptions
|
|
||||||
): Promise<T> {
|
|
||||||
// Cancel previous retry with same ID
|
|
||||||
this.cancel(id)
|
|
||||||
|
|
||||||
const abortController = new AbortController()
|
|
||||||
const mergedOptions = { ...this.defaultOptions, ...options, abortSignal: abortController.signal }
|
|
||||||
|
|
||||||
const retryPromise = retry(context => {
|
|
||||||
this.activeRetries.set(id, {
|
|
||||||
cancel: () => abortController.abort(),
|
|
||||||
context
|
|
||||||
})
|
|
||||||
this.emit('attempt', { id, attempt: context.attempt })
|
|
||||||
return operation(context)
|
|
||||||
}, mergedOptions)
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await retryPromise
|
|
||||||
this.emit('success', { id })
|
|
||||||
return result
|
|
||||||
} catch (error) {
|
|
||||||
this.emit('failure', { id, error })
|
|
||||||
throw error
|
|
||||||
} finally {
|
|
||||||
this.activeRetries.delete(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cancel in-progress retry
|
|
||||||
*/
|
|
||||||
cancel(id: string): boolean {
|
|
||||||
const active = this.activeRetries.get(id)
|
|
||||||
if (active) {
|
|
||||||
active.cancel()
|
|
||||||
this.activeRetries.delete(id)
|
|
||||||
this.emit('cancelled', { id })
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cancel all retries
|
|
||||||
*/
|
|
||||||
cancelAll(): void {
|
|
||||||
for (const [id, active] of this.activeRetries) {
|
|
||||||
active.cancel()
|
|
||||||
this.emit('cancelled', { id })
|
|
||||||
}
|
|
||||||
|
|
||||||
this.activeRetries.clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if there is an active retry
|
|
||||||
*/
|
|
||||||
isActive(id: string): boolean {
|
|
||||||
return this.activeRetries.has(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return active retry context
|
|
||||||
*/
|
|
||||||
getContext(id: string): RetryContext | undefined {
|
|
||||||
return this.activeRetries.get(id)?.context
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return active retry IDs
|
|
||||||
*/
|
|
||||||
getActiveIds(): string[] {
|
|
||||||
return Array.from(this.activeRetries.keys())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Common predicates for shouldRetry
|
* Common predicates for shouldRetry
|
||||||
*/
|
*/
|
||||||
@@ -660,9 +526,8 @@ export const retryConfigs = {
|
|||||||
* Uses fixed delay array: 1s, 2s, 5s, 10s, 20s (with ±15% jitter)
|
* Uses fixed delay array: 1s, 2s, 5s, 10s, 20s (with ±15% jitter)
|
||||||
*
|
*
|
||||||
* NOTE: Values are hardcoded instead of referencing RETRY_BACKOFF_DELAYS/RETRY_JITTER_FACTOR
|
* NOTE: Values are hardcoded instead of referencing RETRY_BACKOFF_DELAYS/RETRY_JITTER_FACTOR
|
||||||
* to prevent "Cannot access before initialization" errors in ESM environments.
|
* to prevent "Cannot access before initialization" errors in ESM environments
|
||||||
* This occurs when modules are loaded in specific orders due to indirect circular imports
|
* caused by indirect circular imports through prometheus-metrics.ts.
|
||||||
* (e.g., via prometheus-metrics.ts -> circuit-breaker.ts chain).
|
|
||||||
* Keep these values in sync with the constants above (lines 25, 31).
|
* Keep these values in sync with the constants above (lines 25, 31).
|
||||||
*/
|
*/
|
||||||
rsocket: {
|
rsocket: {
|
||||||
|
|||||||
+120
-19
@@ -2,6 +2,7 @@ import { Boom } from '@hapi/boom'
|
|||||||
import { createHash } from 'crypto'
|
import { createHash } from 'crypto'
|
||||||
import { zipSync } from 'fflate'
|
import { zipSync } from 'fflate'
|
||||||
import { promises as fs } from 'fs'
|
import { promises as fs } from 'fs'
|
||||||
|
import { gzipSync, gunzipSync } from 'zlib'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type { MediaType } from '../Defaults/index.js'
|
import type { MediaType } from '../Defaults/index.js'
|
||||||
import type { StickerPack, WAMediaUpload, WAMediaUploadFunction } from '../Types/Message.js'
|
import type { StickerPack, WAMediaUpload, WAMediaUploadFunction } from '../Types/Message.js'
|
||||||
@@ -101,6 +102,49 @@ export const isAnimatedWebP = (buffer: Buffer): boolean => {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detecta se um buffer é Lottie JSON (raw ou gzip-compressed/WAS)
|
||||||
|
*
|
||||||
|
* WABA usa mimetype `application/was` para stickers Lottie.
|
||||||
|
* WAS (WhatsApp Animated Sticker) = gzip-compressed Lottie JSON.
|
||||||
|
*
|
||||||
|
* Detecção:
|
||||||
|
* - Gzip (0x1f 0x8b): descomprime e verifica se é Lottie JSON
|
||||||
|
* - JSON bruto: verifica campos Lottie obrigatórios (v, ip, op, layers)
|
||||||
|
*
|
||||||
|
* @param buffer - Buffer to check
|
||||||
|
* @returns true if buffer is Lottie/WAS format
|
||||||
|
*/
|
||||||
|
export const isLottieBuffer = (buffer: Buffer): boolean => {
|
||||||
|
if (buffer.length < 2) return false
|
||||||
|
|
||||||
|
let jsonBuffer: Buffer
|
||||||
|
|
||||||
|
// Check if gzip-compressed (WAS format)
|
||||||
|
if (buffer[0] === 0x1f && buffer[1] === 0x8b) {
|
||||||
|
try {
|
||||||
|
// SECURITY: Limit decompressed output to 50MB to prevent decompression bombs
|
||||||
|
jsonBuffer = gunzipSync(buffer, { maxOutputLength: 50 * 1024 * 1024 }) as Buffer
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
} else if (buffer[0] === 0x7b) {
|
||||||
|
// Starts with '{' - could be raw Lottie JSON
|
||||||
|
jsonBuffer = buffer
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate Lottie JSON structure: must have v, ip, op, AND layers
|
||||||
|
try {
|
||||||
|
const str = jsonBuffer.toString('utf8', 0, Math.min(jsonBuffer.length, 4096))
|
||||||
|
// Quick check for ALL required Lottie fields
|
||||||
|
return str.includes('"v"') && str.includes('"layers"') && str.includes('"ip"') && str.includes('"op"')
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Converte uma imagem para WebP usando Sharp
|
* Converte uma imagem para WebP usando Sharp
|
||||||
* Preserva o buffer original se já for WebP para manter EXIF e animações
|
* Preserva o buffer original se já for WebP para manter EXIF e animações
|
||||||
@@ -114,12 +158,25 @@ export const isAnimatedWebP = (buffer: Buffer): boolean => {
|
|||||||
const convertToWebP = async (
|
const convertToWebP = async (
|
||||||
buffer: Buffer,
|
buffer: Buffer,
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
): Promise<{ webpBuffer: Buffer; isAnimated: boolean }> => {
|
): Promise<{ webpBuffer: Buffer; isAnimated: boolean; isLottie: boolean }> => {
|
||||||
|
// Lottie/WAS: ensure gzip-compressed format (WAS = gzip Lottie JSON)
|
||||||
|
if (isLottieBuffer(buffer)) {
|
||||||
|
let wasBuffer = buffer
|
||||||
|
// Raw Lottie JSON (starts with '{') must be gzipped to produce valid WAS
|
||||||
|
if (buffer[0] === 0x7b) {
|
||||||
|
logger?.trace('Raw Lottie JSON detected, gzip-compressing to WAS format')
|
||||||
|
wasBuffer = gzipSync(buffer) as Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
logger?.trace('Input is Lottie/WAS format')
|
||||||
|
return { webpBuffer: wasBuffer, isAnimated: true, isLottie: true }
|
||||||
|
}
|
||||||
|
|
||||||
// Se já é WebP, preserva o buffer original (mantém EXIF e animações)
|
// Se já é WebP, preserva o buffer original (mantém EXIF e animações)
|
||||||
if (isWebPBuffer(buffer)) {
|
if (isWebPBuffer(buffer)) {
|
||||||
const isAnimated = isAnimatedWebP(buffer)
|
const isAnimated = isAnimatedWebP(buffer)
|
||||||
logger?.trace({ isAnimated }, 'Input is already WebP, preserving original buffer')
|
logger?.trace({ isAnimated }, 'Input is already WebP, preserving original buffer')
|
||||||
return { webpBuffer: buffer, isAnimated }
|
return { webpBuffer: buffer, isAnimated, isLottie: false }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tenta usar Sharp para converter
|
// Tenta usar Sharp para converter
|
||||||
@@ -135,7 +192,7 @@ const convertToWebP = async (
|
|||||||
logger?.trace('Converting image to WebP using Sharp')
|
logger?.trace('Converting image to WebP using Sharp')
|
||||||
const webpBuffer = await lib.sharp.default(buffer).webp().toBuffer()
|
const webpBuffer = await lib.sharp.default(buffer).webp().toBuffer()
|
||||||
|
|
||||||
return { webpBuffer, isAnimated: false }
|
return { webpBuffer, isAnimated: false, isLottie: false }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -338,9 +395,11 @@ export type PrepareStickerPackMessageOptions = {
|
|||||||
*
|
*
|
||||||
* **Especificações WhatsApp:**
|
* **Especificações WhatsApp:**
|
||||||
* - 3-30 stickers por pack (oficial)
|
* - 3-30 stickers por pack (oficial)
|
||||||
* - WebP obrigatório
|
* - WebP ou Lottie/WAS (application/was)
|
||||||
|
* - Stickers: 512x512 pixels (auto-resize)
|
||||||
* - Recomendado: 100KB por sticker estático, 500KB animado
|
* - Recomendado: 100KB por sticker estático, 500KB animado
|
||||||
* - Tray icon: 252x252 pixels
|
* - Tray icon: 96x96 pixels (PNG no ZIP)
|
||||||
|
* - Thumbnail: 252x252 pixels (JPEG, upload separado)
|
||||||
*
|
*
|
||||||
* @param stickerPack - Sticker pack data with stickers, cover, name, publisher
|
* @param stickerPack - Sticker pack data with stickers, cover, name, publisher
|
||||||
* @param options - Upload function and optional logger
|
* @param options - Upload function and optional logger
|
||||||
@@ -464,9 +523,36 @@ export const prepareStickerPackMessage = async (
|
|||||||
// Obtém buffer do sticker
|
// Obtém buffer do sticker
|
||||||
const buffer = await mediaToBuffer(sticker.data, `sticker ${i + 1}`)
|
const buffer = await mediaToBuffer(sticker.data, `sticker ${i + 1}`)
|
||||||
|
|
||||||
// Converte para WebP
|
// Detecta formato e converte se necessário
|
||||||
// eslint-disable-next-line prefer-const
|
// eslint-disable-next-line prefer-const
|
||||||
let { webpBuffer, isAnimated } = await convertToWebP(buffer, logger)
|
let { webpBuffer, isAnimated, isLottie } = await convertToWebP(buffer, logger)
|
||||||
|
|
||||||
|
// Validate explicit isLottie flag — must match detected format
|
||||||
|
if (sticker.isLottie !== undefined && sticker.isLottie !== isLottie) {
|
||||||
|
throw new Boom(
|
||||||
|
`Sticker ${i + 1}: explicit isLottie=${sticker.isLottie} does not match detected format (detected=${isLottie})`,
|
||||||
|
{ statusCode: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WABA: Enforce 512x512 dimensions for WebP stickers (Lottie is vector, skip)
|
||||||
|
if (!isLottie && isWebPBuffer(webpBuffer)) {
|
||||||
|
const lib = await getImageProcessingLibrary()
|
||||||
|
if (lib?.sharp) {
|
||||||
|
const metadata = await lib.sharp.default(webpBuffer).metadata()
|
||||||
|
if (metadata.width !== 512 || metadata.height !== 512) {
|
||||||
|
logger?.trace(
|
||||||
|
{ index: i, width: metadata.width, height: metadata.height },
|
||||||
|
'Resizing sticker to 512x512 (WABA standard)'
|
||||||
|
)
|
||||||
|
webpBuffer = await lib.sharp
|
||||||
|
.default(webpBuffer)
|
||||||
|
.resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
|
||||||
|
.webp()
|
||||||
|
.toBuffer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ENHANCEMENT: Auto-compression if exceeds 1MB (try quality 70, then 50)
|
// ENHANCEMENT: Auto-compression if exceeds 1MB (try quality 70, then 50)
|
||||||
const MAX_STICKER_SIZE = 1024 * 1024 // 1MB
|
const MAX_STICKER_SIZE = 1024 * 1024 // 1MB
|
||||||
@@ -483,7 +569,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
if (lib?.sharp) {
|
if (lib?.sharp) {
|
||||||
// Try quality 70
|
// Try quality 70
|
||||||
try {
|
try {
|
||||||
const compressed70 = await lib.sharp.default(buffer).webp({ quality: 70 }).toBuffer()
|
const compressed70 = await lib.sharp.default(webpBuffer).webp({ quality: 70 }).toBuffer()
|
||||||
|
|
||||||
// eslint-disable-next-line max-depth
|
// eslint-disable-next-line max-depth
|
||||||
if (compressed70.length <= MAX_STICKER_SIZE) {
|
if (compressed70.length <= MAX_STICKER_SIZE) {
|
||||||
@@ -498,7 +584,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// Try quality 50
|
// Try quality 50
|
||||||
const compressed50 = await lib.sharp.default(buffer).webp({ quality: 50 }).toBuffer()
|
const compressed50 = await lib.sharp.default(webpBuffer).webp({ quality: 50 }).toBuffer()
|
||||||
|
|
||||||
// eslint-disable-next-line max-depth
|
// eslint-disable-next-line max-depth
|
||||||
if (compressed50.length <= MAX_STICKER_SIZE) {
|
if (compressed50.length <= MAX_STICKER_SIZE) {
|
||||||
@@ -547,12 +633,13 @@ export const prepareStickerPackMessage = async (
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gera nome do arquivo: hash.webp (deduplicação automática)
|
// Gera nome do arquivo: hash.webp ou hash.was (WABA: plain_file_hash.ext)
|
||||||
const sha256Hash = generateSha256Hash(webpBuffer)
|
const sha256Hash = generateSha256Hash(webpBuffer)
|
||||||
const fileName = `${sha256Hash}.webp`
|
const extension = isLottie ? 'was' : 'webp'
|
||||||
|
const fileName = `${sha256Hash}.${extension}`
|
||||||
|
|
||||||
logger?.trace(
|
logger?.trace(
|
||||||
{ index: i, fileName, sizeKB: finalSizeKB.toFixed(2), isAnimated },
|
{ index: i, fileName, sizeKB: finalSizeKB.toFixed(2), isAnimated, isLottie },
|
||||||
'Sticker processed successfully'
|
'Sticker processed successfully'
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -560,6 +647,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
fileName,
|
fileName,
|
||||||
webpBuffer,
|
webpBuffer,
|
||||||
isAnimated,
|
isAnimated,
|
||||||
|
isLottie,
|
||||||
emojis: sticker.emojis || [],
|
emojis: sticker.emojis || [],
|
||||||
accessibilityLabel: sticker.accessibilityLabel
|
accessibilityLabel: sticker.accessibilityLabel
|
||||||
}
|
}
|
||||||
@@ -578,7 +666,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
for (const result of processedStickers) {
|
for (const result of processedStickers) {
|
||||||
if (!result) continue
|
if (!result) continue
|
||||||
|
|
||||||
const { fileName, webpBuffer, isAnimated, emojis, accessibilityLabel } = result
|
const { fileName, webpBuffer, isAnimated, isLottie, emojis, accessibilityLabel } = result
|
||||||
|
|
||||||
// SECURITY FIX #7: Check if this hash already exists (duplicate sticker)
|
// SECURITY FIX #7: Check if this hash already exists (duplicate sticker)
|
||||||
const existingMetadata = metadataByHash.get(fileName)
|
const existingMetadata = metadataByHash.get(fileName)
|
||||||
@@ -605,13 +693,14 @@ export const prepareStickerPackMessage = async (
|
|||||||
// New sticker - add to ZIP and create metadata
|
// New sticker - add to ZIP and create metadata
|
||||||
stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 as 0 }]
|
stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 as 0 }]
|
||||||
|
|
||||||
|
// WABA: mimetype é 'application/was' para Lottie, 'image/webp' para WebP
|
||||||
const metadata: proto.Message.StickerPackMessage.ISticker = {
|
const metadata: proto.Message.StickerPackMessage.ISticker = {
|
||||||
fileName,
|
fileName,
|
||||||
isAnimated,
|
isAnimated,
|
||||||
emojis,
|
emojis,
|
||||||
accessibilityLabel,
|
accessibilityLabel,
|
||||||
isLottie: false,
|
isLottie,
|
||||||
mimetype: 'image/webp'
|
mimetype: isLottie ? 'application/was' : 'image/webp'
|
||||||
}
|
}
|
||||||
|
|
||||||
metadataByHash.set(fileName, metadata)
|
metadataByHash.set(fileName, metadata)
|
||||||
@@ -636,10 +725,22 @@ export const prepareStickerPackMessage = async (
|
|||||||
logger?.trace('Processing cover image')
|
logger?.trace('Processing cover image')
|
||||||
coverBuffer = await mediaToBuffer(cover, 'cover image')
|
coverBuffer = await mediaToBuffer(cover, 'cover image')
|
||||||
|
|
||||||
// Converte cover para WebP e adiciona ao ZIP
|
// Tray icon uses PNG format, 96x96 pixels (official client standard)
|
||||||
const result = await convertToWebP(coverBuffer, logger)
|
const lib = await getImageProcessingLibrary()
|
||||||
coverWebP = result.webpBuffer
|
if (!lib?.sharp) {
|
||||||
coverFileName = `${stickerPackId}.webp`
|
throw new Boom(
|
||||||
|
'Sharp library is required for cover/tray icon processing. Install with: yarn add sharp',
|
||||||
|
{ statusCode: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
coverWebP = await lib.sharp
|
||||||
|
.default(coverBuffer)
|
||||||
|
.resize(96, 96, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
|
||||||
|
.png()
|
||||||
|
.toBuffer()
|
||||||
|
|
||||||
|
coverFileName = `${stickerPackId}.png`
|
||||||
stickerData[coverFileName] = [new Uint8Array(coverWebP), { level: 0 as 0 }]
|
stickerData[coverFileName] = [new Uint8Array(coverWebP), { level: 0 as 0 }]
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Boom(`Failed to process cover image: ${(error as Error).message}`, {
|
throw new Boom(`Failed to process cover image: ${(error as Error).message}`, {
|
||||||
|
|||||||
@@ -6,7 +6,9 @@
|
|||||||
* - Configurable log levels (trace, debug, info, warn, error, fatal)
|
* - Configurable log levels (trace, debug, info, warn, error, fatal)
|
||||||
* - JSON formatting for log analysis
|
* - JSON formatting for log analysis
|
||||||
* - Hierarchical context with child loggers
|
* - Hierarchical context with child loggers
|
||||||
* - External system integration via hooks with circuit breaker
|
* - External system integration via fire-and-forget hooks (failures
|
||||||
|
* counted in hookFailures metric; no per-hook circuit breaker — chronic
|
||||||
|
* breakage is visible to operators via the metric)
|
||||||
* - Logging metrics with Prometheus integration
|
* - Logging metrics with Prometheus integration
|
||||||
* - Sensitive data sanitization
|
* - Sensitive data sanitization
|
||||||
* - Log buffering for batch writes
|
* - Log buffering for batch writes
|
||||||
@@ -73,10 +75,6 @@ export interface StructuredLoggerConfig {
|
|||||||
maxLogsPerSecond?: number
|
maxLogsPerSecond?: number
|
||||||
/** Enable async logging queue (default: false) */
|
/** Enable async logging queue (default: false) */
|
||||||
enableAsyncQueue?: boolean
|
enableAsyncQueue?: boolean
|
||||||
/** Circuit breaker failure threshold for external hooks (default: 5) */
|
|
||||||
circuitBreakerThreshold?: number
|
|
||||||
/** Circuit breaker reset timeout in ms (default: 30000) */
|
|
||||||
circuitBreakerResetMs?: number
|
|
||||||
/** Enable Prometheus metrics integration (default: false) */
|
/** Enable Prometheus metrics integration (default: false) */
|
||||||
enableMetrics?: boolean
|
enableMetrics?: boolean
|
||||||
}
|
}
|
||||||
@@ -155,8 +153,6 @@ export interface LoggerMetrics {
|
|||||||
bufferFlushes: number
|
bufferFlushes: number
|
||||||
/** External hook failures */
|
/** External hook failures */
|
||||||
hookFailures: number
|
hookFailures: number
|
||||||
/** Circuit breaker trips */
|
|
||||||
circuitBreakerTrips: number
|
|
||||||
/** Average log processing time in ms */
|
/** Average log processing time in ms */
|
||||||
avgProcessingTimeMs: number
|
avgProcessingTimeMs: number
|
||||||
}
|
}
|
||||||
@@ -169,8 +165,6 @@ export interface LoggerStatistics extends LoggerMetrics {
|
|||||||
bufferSize: number
|
bufferSize: number
|
||||||
/** Rate limiter tokens available */
|
/** Rate limiter tokens available */
|
||||||
rateLimiterTokens: number
|
rateLimiterTokens: number
|
||||||
/** Circuit breaker state */
|
|
||||||
circuitBreakerState: 'closed' | 'open' | 'half-open'
|
|
||||||
/** Queue size (if async enabled) */
|
/** Queue size (if async enabled) */
|
||||||
queueSize: number
|
queueSize: number
|
||||||
/** Created timestamp */
|
/** Created timestamp */
|
||||||
@@ -242,69 +236,6 @@ class RateLimiter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// CIRCUIT BREAKER
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Circuit breaker for external hook protection
|
|
||||||
*/
|
|
||||||
class CircuitBreaker {
|
|
||||||
private failures = 0
|
|
||||||
private lastFailure = 0
|
|
||||||
private state: 'closed' | 'open' | 'half-open' = 'closed'
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly threshold: number,
|
|
||||||
private readonly resetTimeoutMs: number
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async execute<T>(operation: () => Promise<T>): Promise<T | null> {
|
|
||||||
if (this.state === 'open') {
|
|
||||||
if (Date.now() - this.lastFailure > this.resetTimeoutMs) {
|
|
||||||
this.state = 'half-open'
|
|
||||||
} else {
|
|
||||||
return null // Circuit is open, skip
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await operation()
|
|
||||||
this.onSuccess()
|
|
||||||
return result
|
|
||||||
} catch (error) {
|
|
||||||
this.onFailure()
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private onSuccess(): void {
|
|
||||||
this.failures = 0
|
|
||||||
this.state = 'closed'
|
|
||||||
}
|
|
||||||
|
|
||||||
private onFailure(): void {
|
|
||||||
this.failures++
|
|
||||||
this.lastFailure = Date.now()
|
|
||||||
if (this.failures >= this.threshold) {
|
|
||||||
this.state = 'open'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getState(): 'closed' | 'open' | 'half-open' {
|
|
||||||
// Check if should transition from open to half-open
|
|
||||||
if (this.state === 'open' && Date.now() - this.lastFailure > this.resetTimeoutMs) {
|
|
||||||
this.state = 'half-open'
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.state
|
|
||||||
}
|
|
||||||
|
|
||||||
getFailures(): number {
|
|
||||||
return this.failures
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// ASYNC LOG QUEUE
|
// ASYNC LOG QUEUE
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -403,8 +334,6 @@ export class StructuredLogger implements ILogger {
|
|||||||
private rateLimiter: RateLimiter | null = null
|
private rateLimiter: RateLimiter | null = null
|
||||||
|
|
||||||
// Circuit breaker for external hook
|
// Circuit breaker for external hook
|
||||||
private circuitBreaker: CircuitBreaker | null = null
|
|
||||||
|
|
||||||
// Async queue
|
// Async queue
|
||||||
private asyncQueue: AsyncLogQueue | null = null
|
private asyncQueue: AsyncLogQueue | null = null
|
||||||
|
|
||||||
@@ -435,8 +364,6 @@ export class StructuredLogger implements ILogger {
|
|||||||
enableRateLimiting: config.enableRateLimiting ?? envConfig.enableRateLimiting ?? false,
|
enableRateLimiting: config.enableRateLimiting ?? envConfig.enableRateLimiting ?? false,
|
||||||
maxLogsPerSecond: config.maxLogsPerSecond ?? envConfig.maxLogsPerSecond ?? 1000,
|
maxLogsPerSecond: config.maxLogsPerSecond ?? envConfig.maxLogsPerSecond ?? 1000,
|
||||||
enableAsyncQueue: config.enableAsyncQueue ?? envConfig.enableAsyncQueue ?? false,
|
enableAsyncQueue: config.enableAsyncQueue ?? envConfig.enableAsyncQueue ?? false,
|
||||||
circuitBreakerThreshold: config.circuitBreakerThreshold ?? 5,
|
|
||||||
circuitBreakerResetMs: config.circuitBreakerResetMs ?? 30000,
|
|
||||||
enableMetrics: config.enableMetrics ?? envConfig.enableMetrics ?? false
|
enableMetrics: config.enableMetrics ?? envConfig.enableMetrics ?? false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -455,7 +382,6 @@ export class StructuredLogger implements ILogger {
|
|||||||
droppedLogs: 0,
|
droppedLogs: 0,
|
||||||
bufferFlushes: 0,
|
bufferFlushes: 0,
|
||||||
hookFailures: 0,
|
hookFailures: 0,
|
||||||
circuitBreakerTrips: 0,
|
|
||||||
avgProcessingTimeMs: 0
|
avgProcessingTimeMs: 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -464,11 +390,6 @@ export class StructuredLogger implements ILogger {
|
|||||||
this.rateLimiter = new RateLimiter(this.config.maxLogsPerSecond)
|
this.rateLimiter = new RateLimiter(this.config.maxLogsPerSecond)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize circuit breaker for external hook
|
|
||||||
if (this.config.externalHook) {
|
|
||||||
this.circuitBreaker = new CircuitBreaker(this.config.circuitBreakerThreshold, this.config.circuitBreakerResetMs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize async queue
|
// Initialize async queue
|
||||||
if (this.config.enableAsyncQueue) {
|
if (this.config.enableAsyncQueue) {
|
||||||
this.asyncQueue = new AsyncLogQueue()
|
this.asyncQueue = new AsyncLogQueue()
|
||||||
@@ -569,20 +490,28 @@ export class StructuredLogger implements ILogger {
|
|||||||
this.output(entry)
|
this.output(entry)
|
||||||
}
|
}
|
||||||
|
|
||||||
// External hook with circuit breaker
|
// External hook — fire-and-forget. Failures are counted in
|
||||||
|
// hookFailures metric so chronic breakage is visible to operators
|
||||||
|
// who can fix their hook. We do not gate further calls — that is
|
||||||
|
// the consumer's responsibility (consistent with the rest of the
|
||||||
|
// codebase after the circuit-breaker removal).
|
||||||
const externalHook = this.config.externalHook
|
const externalHook = this.config.externalHook
|
||||||
if (externalHook && this.circuitBreaker) {
|
if (externalHook) {
|
||||||
this.circuitBreaker
|
try {
|
||||||
.execute(async () => {
|
const hookResult = externalHook(entry) as unknown
|
||||||
await Promise.resolve(externalHook(entry))
|
// Use Promise.resolve().catch() so any thenable (including
|
||||||
})
|
// Promise-likes that only implement .then) is handled
|
||||||
.catch(() => {
|
// safely — calling .catch directly would throw on such
|
||||||
|
// objects (Copilot review on PR #393).
|
||||||
|
if (hookResult && typeof (hookResult as PromiseLike<unknown>).then === 'function') {
|
||||||
|
void Promise.resolve(hookResult as PromiseLike<unknown>).catch(() => {
|
||||||
this.metrics.hookFailures++
|
this.metrics.hookFailures++
|
||||||
if (this.circuitBreaker?.getState() === 'open') {
|
|
||||||
this.metrics.circuitBreakerTrips++
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
this.metrics.hookFailures++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Track processing time
|
// Track processing time
|
||||||
this.totalProcessingTime += Date.now() - startTime
|
this.totalProcessingTime += Date.now() - startTime
|
||||||
@@ -834,7 +763,6 @@ export class StructuredLogger implements ILogger {
|
|||||||
...this.metrics,
|
...this.metrics,
|
||||||
bufferSize: this.buffer.length,
|
bufferSize: this.buffer.length,
|
||||||
rateLimiterTokens: this.rateLimiter?.getTokens() ?? 0,
|
rateLimiterTokens: this.rateLimiter?.getTokens() ?? 0,
|
||||||
circuitBreakerState: this.circuitBreaker?.getState() ?? 'closed',
|
|
||||||
queueSize: this.asyncQueue?.getSize() ?? 0,
|
queueSize: this.asyncQueue?.getSize() ?? 0,
|
||||||
createdAt: this.createdAt,
|
createdAt: this.createdAt,
|
||||||
uptimeMs: Date.now() - this.createdAt
|
uptimeMs: Date.now() - this.createdAt
|
||||||
@@ -860,7 +788,6 @@ export class StructuredLogger implements ILogger {
|
|||||||
droppedLogs: 0,
|
droppedLogs: 0,
|
||||||
bufferFlushes: 0,
|
bufferFlushes: 0,
|
||||||
hookFailures: 0,
|
hookFailures: 0,
|
||||||
circuitBreakerTrips: 0,
|
|
||||||
avgProcessingTimeMs: 0
|
avgProcessingTimeMs: 0
|
||||||
}
|
}
|
||||||
this.totalProcessingTime = 0
|
this.totalProcessingTime = 0
|
||||||
@@ -893,7 +820,6 @@ export class StructuredLogger implements ILogger {
|
|||||||
|
|
||||||
// Clear references
|
// Clear references
|
||||||
this.rateLimiter = null
|
this.rateLimiter = null
|
||||||
this.circuitBreaker = null
|
|
||||||
this.metricsModule = null
|
this.metricsModule = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ export const processContactAction = (
|
|||||||
{
|
{
|
||||||
id,
|
id,
|
||||||
name: action.fullName || action.firstName || action.username || undefined,
|
name: action.fullName || action.firstName || action.username || undefined,
|
||||||
|
username: action.username || undefined,
|
||||||
lid: lidJid || undefined,
|
lid: lidJid || undefined,
|
||||||
phoneNumber
|
phoneNumber
|
||||||
}
|
}
|
||||||
|
|||||||
+135
-7
@@ -1,12 +1,86 @@
|
|||||||
import type { SignalKeyStoreWithTransaction } from '../Types'
|
import type { SignalKeyStoreWithTransaction } from '../Types'
|
||||||
import type { BinaryNode } from '../WABinary'
|
import type { BinaryNode } from '../WABinary'
|
||||||
import { getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidNormalizedUser } from '../WABinary'
|
import {
|
||||||
|
getBinaryNodeChild,
|
||||||
|
getBinaryNodeChildren,
|
||||||
|
isAnyLidUser,
|
||||||
|
isAnyPnUser,
|
||||||
|
isHostedLidUser,
|
||||||
|
isHostedPnUser,
|
||||||
|
isJidMetaAI,
|
||||||
|
isLidUser,
|
||||||
|
isPnUser,
|
||||||
|
jidNormalizedUser
|
||||||
|
} from '../WABinary'
|
||||||
|
|
||||||
/** 7 days in seconds — matches WA Web AB prop tctoken_duration */
|
/** 7 days in seconds — matches WA Web AB prop tctoken_duration */
|
||||||
const TC_TOKEN_BUCKET_DURATION = 604800
|
const TC_TOKEN_BUCKET_DURATION = 604800
|
||||||
/** 4 buckets → ~28-day rolling window — matches WA Web AB prop tctoken_num_buckets */
|
/** 4 buckets → ~28-day rolling window — matches WA Web AB prop tctoken_num_buckets */
|
||||||
const TC_TOKEN_NUM_BUCKETS = 4
|
const TC_TOKEN_NUM_BUCKETS = 4
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sentinel key under the `tctoken` store holding a JSON array of tracked storage JIDs
|
||||||
|
* for cross-session pruning. Mirrors WA Web's CLEAN_TC_TOKENS index lookup.
|
||||||
|
*
|
||||||
|
* Exported so other modules (messages-recv, messages-send, process-message) reference
|
||||||
|
* the same constant. The fork previously inlined this string in messages-recv.ts;
|
||||||
|
* keep the value identical (`'__index'`) for backward compatibility with persisted state.
|
||||||
|
*/
|
||||||
|
export const TC_TOKEN_INDEX_KEY = '__index'
|
||||||
|
|
||||||
|
// Phone-number pattern matching WABinary's isJidBot, applied against the user part so
|
||||||
|
// the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
|
||||||
|
const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
|
||||||
|
* storage against malformed notifications — WA Web filters server-side but we
|
||||||
|
* defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
|
||||||
|
* Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
|
||||||
|
*/
|
||||||
|
export function isRegularUser(jid: string | undefined): boolean {
|
||||||
|
if (!jid) return false
|
||||||
|
const user = jid.split('@')[0] ?? ''
|
||||||
|
if (user === '0') return false // PSA
|
||||||
|
if (BOT_PHONE_REGEX.test(user)) return false // Bot by phone pattern
|
||||||
|
if (isJidMetaAI(jid)) return false // MetaAI (@bot server)
|
||||||
|
return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
|
||||||
|
export async function readTcTokenIndex(keys: SignalKeyStoreWithTransaction): Promise<string[]> {
|
||||||
|
const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY])
|
||||||
|
const entry = data[TC_TOKEN_INDEX_KEY]
|
||||||
|
if (!entry?.token?.length) return []
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(Buffer.from(entry.token).toString())
|
||||||
|
if (!Array.isArray(parsed)) return []
|
||||||
|
return parsed.filter((j): j is string => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY)
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a SignalDataSet fragment that writes the merged index (persisted ∪ added)
|
||||||
|
* under the sentinel key. Lets callers update the index without clobbering writes
|
||||||
|
* made by other layers (history sync, concurrent sessions on the same store).
|
||||||
|
*/
|
||||||
|
export async function buildMergedTcTokenIndexWrite(
|
||||||
|
keys: SignalKeyStoreWithTransaction,
|
||||||
|
addedJids: Iterable<string>
|
||||||
|
): Promise<{ [TC_TOKEN_INDEX_KEY]: { token: Buffer } }> {
|
||||||
|
const persisted = await readTcTokenIndex(keys)
|
||||||
|
const merged = new Set(persisted)
|
||||||
|
for (const jid of addedJids) {
|
||||||
|
if (jid && jid !== TC_TOKEN_INDEX_KEY) merged.add(jid)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
[TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if a received token is expired using WA Web's rolling bucket algorithm.
|
* Check if a received token is expired using WA Web's rolling bucket algorithm.
|
||||||
* Reference: WAWebTrustedContactsUtils.isTokenExpired
|
* Reference: WAWebTrustedContactsUtils.isTokenExpired
|
||||||
@@ -63,6 +137,43 @@ export async function resolveTcTokenJid(
|
|||||||
return lid ?? normalized
|
return lid ?? normalized
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve target JID for issuing privacy token based on AB prop 14303
|
||||||
|
* (`lid_trusted_token_issue_to_lid`). When the prop is on, issuance goes to
|
||||||
|
* the LID; when off, it goes to the PN. Returns the original JID if no
|
||||||
|
* mapping is found in either direction.
|
||||||
|
*
|
||||||
|
* Normalizes the JID upfront and uses the `isAny*` helpers so callers can pass
|
||||||
|
* `@c.us`, `@s.whatsapp.net`, `@hosted`, `@hosted.lid`, `@lid` or device-specific
|
||||||
|
* forms — `LIDMappingStore.getLIDForPN` early-returns unless `isAnyPnUser`,
|
||||||
|
* so unnormalized inputs would silently bypass routing.
|
||||||
|
*
|
||||||
|
* Reference: WAWebTrustedContactsManager.issuePrivacyTokens
|
||||||
|
*/
|
||||||
|
export async function resolveIssuanceJid(
|
||||||
|
jid: string,
|
||||||
|
issueToLid: boolean,
|
||||||
|
getLIDForPN: (pn: string) => Promise<string | null>,
|
||||||
|
getPNForLID?: (lid: string) => Promise<string | null>
|
||||||
|
): Promise<string> {
|
||||||
|
const normalized = jidNormalizedUser(jid)
|
||||||
|
|
||||||
|
if (issueToLid) {
|
||||||
|
if (isAnyLidUser(normalized)) return normalized
|
||||||
|
if (!isAnyPnUser(normalized)) return normalized
|
||||||
|
const lid = await getLIDForPN(normalized)
|
||||||
|
return lid ?? normalized
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAnyLidUser(normalized)) return normalized
|
||||||
|
if (getPNForLID) {
|
||||||
|
const pn = await getPNForLID(normalized)
|
||||||
|
return pn ?? normalized
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalized
|
||||||
|
}
|
||||||
|
|
||||||
type TcTokenParams = {
|
type TcTokenParams = {
|
||||||
jid: string
|
jid: string
|
||||||
baseContent?: BinaryNode[]
|
baseContent?: BinaryNode[]
|
||||||
@@ -135,7 +246,13 @@ export async function storeTcTokensFromIqResult({
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawJid = jidNormalizedUser(tokenNode.attrs.jid || fallbackJid)
|
// In notifications, tokenNode.attrs.jid is OUR own device JID, not the sender's.
|
||||||
|
// Prefer fallbackJid (resolved from notification's `from` / `sender_lid`) so the
|
||||||
|
// token is stored under the peer's JID, never under self.
|
||||||
|
const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid)
|
||||||
|
// Defense against malformed notifications (PSA WID '0', bots, MetaAI). WA Web
|
||||||
|
// filters these server-side; we mirror Wid.isRegularUser() locally.
|
||||||
|
if (!isRegularUser(rawJid)) continue
|
||||||
const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
|
const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
|
||||||
const existingTcData = await keys.get('tctoken', [storageJid])
|
const existingTcData = await keys.get('tctoken', [storageJid])
|
||||||
const existingEntry = existingTcData[storageJid]
|
const existingEntry = existingTcData[storageJid]
|
||||||
@@ -154,15 +271,26 @@ export async function storeTcTokensFromIqResult({
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
await keys.set({
|
const tokenEntry = {
|
||||||
tctoken: {
|
|
||||||
[storageJid]: {
|
|
||||||
...existingEntry,
|
...existingEntry,
|
||||||
token: Buffer.from(tokenNode.content),
|
token: Buffer.from(tokenNode.content),
|
||||||
timestamp: tokenNode.attrs.t
|
timestamp: tokenNode.attrs.t,
|
||||||
|
// WABA Android: resets real_issue_timestamp to null when storing a new token
|
||||||
|
// (UPDATE wa_trusted_contacts_send SET real_issue_timestamp=null)
|
||||||
|
realIssueTimestamp: null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Store under resolved storageJid AND under fallbackJid (PN) for reliable lookup
|
||||||
|
// The read path may resolve to a different LID than the store path
|
||||||
|
const normalizedFallback = jidNormalizedUser(fallbackJid)
|
||||||
|
const keysToStore: Record<string, typeof tokenEntry | null> = {
|
||||||
|
[storageJid]: tokenEntry
|
||||||
}
|
}
|
||||||
})
|
if (normalizedFallback !== storageJid) {
|
||||||
|
keysToStore[normalizedFallback] = tokenEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
await keys.set({ tctoken: keysToStore })
|
||||||
onNewJidStored?.(storageJid)
|
onNewJidStored?.(storageJid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,6 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import type { BinaryNode } from '../WABinary/types.js'
|
import type { BinaryNode } from '../WABinary/types.js'
|
||||||
import { CircuitBreaker, CircuitOpenError, createConnectionCircuitBreaker } from './circuit-breaker.js'
|
|
||||||
import type { ILogger } from './logger.js'
|
import type { ILogger } from './logger.js'
|
||||||
import { metrics } from './prometheus-metrics.js'
|
import { metrics } from './prometheus-metrics.js'
|
||||||
|
|
||||||
@@ -58,8 +57,6 @@ export interface UnifiedSessionOptions {
|
|||||||
enabled?: boolean
|
enabled?: boolean
|
||||||
/** Logger instance for debugging */
|
/** Logger instance for debugging */
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
/** Enable circuit breaker protection for send operations */
|
|
||||||
enableCircuitBreaker?: boolean
|
|
||||||
/** Function to send binary nodes to WhatsApp */
|
/** Function to send binary nodes to WhatsApp */
|
||||||
sendNode?: (node: BinaryNode) => Promise<void>
|
sendNode?: (node: BinaryNode) => Promise<void>
|
||||||
}
|
}
|
||||||
@@ -93,7 +90,9 @@ export type UnifiedSessionTrigger = 'login' | 'pairing' | 'presence' | 'manual'
|
|||||||
* Manages the unified_session telemetry feature with:
|
* Manages the unified_session telemetry feature with:
|
||||||
* - Server time synchronization
|
* - Server time synchronization
|
||||||
* - Rate limiting (prevents spam)
|
* - Rate limiting (prevents spam)
|
||||||
* - Circuit breaker protection
|
* - Best-effort send semantics (failures are swallowed and counted —
|
||||||
|
* telemetry is non-critical so a single attempt with the underlying
|
||||||
|
* sendNode timeout is enough; no retry, no circuit breaker)
|
||||||
* - Prometheus metrics integration
|
* - Prometheus metrics integration
|
||||||
* - Structured logging
|
* - Structured logging
|
||||||
*
|
*
|
||||||
@@ -121,7 +120,6 @@ export class UnifiedSessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private readonly options: Required<UnifiedSessionOptions>
|
private readonly options: Required<UnifiedSessionOptions>
|
||||||
private circuitBreaker: CircuitBreaker | null = null
|
|
||||||
|
|
||||||
/** Minimum interval between unified_session sends (1 minute) */
|
/** Minimum interval between unified_session sends (1 minute) */
|
||||||
private static readonly MIN_SEND_INTERVAL_MS = TimeMs.Minute
|
private static readonly MIN_SEND_INTERVAL_MS = TimeMs.Minute
|
||||||
@@ -130,7 +128,6 @@ export class UnifiedSessionManager {
|
|||||||
this.options = {
|
this.options = {
|
||||||
enabled: options.enabled ?? true,
|
enabled: options.enabled ?? true,
|
||||||
logger: options.logger ?? (console as unknown as ILogger),
|
logger: options.logger ?? (console as unknown as ILogger),
|
||||||
enableCircuitBreaker: options.enableCircuitBreaker ?? true,
|
|
||||||
sendNode:
|
sendNode:
|
||||||
options.sendNode ??
|
options.sendNode ??
|
||||||
(async () => {
|
(async () => {
|
||||||
@@ -138,25 +135,6 @@ export class UnifiedSessionManager {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize circuit breaker if enabled
|
|
||||||
if (this.options.enableCircuitBreaker) {
|
|
||||||
this.circuitBreaker = createConnectionCircuitBreaker({
|
|
||||||
name: 'unified-session',
|
|
||||||
failureThreshold: 3,
|
|
||||||
failureWindow: 60000,
|
|
||||||
resetTimeout: 30000,
|
|
||||||
successThreshold: 1,
|
|
||||||
timeout: 10000,
|
|
||||||
onStateChange: (from, to) => {
|
|
||||||
this.options.logger.debug?.({ from, to }, 'Unified session circuit breaker state changed')
|
|
||||||
},
|
|
||||||
onOpen: () => {
|
|
||||||
this.options.logger.warn?.('Unified session circuit breaker OPENED')
|
|
||||||
metrics.circuitBreakerTrips?.inc({ name: 'unified-session' })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
this.state.isInitialized = true
|
this.state.isInitialized = true
|
||||||
this.options.logger.debug?.('UnifiedSessionManager initialized')
|
this.options.logger.debug?.('UnifiedSessionManager initialized')
|
||||||
}
|
}
|
||||||
@@ -292,20 +270,12 @@ export class UnifiedSessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Execute with circuit breaker if available
|
// Telemetry is non-critical: a single send attempt with the
|
||||||
if (this.circuitBreaker) {
|
// underlying sendNode timeout is enough. No retry/circuit needed.
|
||||||
await this.circuitBreaker.execute(sendOperation)
|
|
||||||
} else {
|
|
||||||
await sendOperation()
|
await sendOperation()
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||||
|
|
||||||
if (error instanceof CircuitOpenError) {
|
|
||||||
this.options.logger.warn?.({ trigger, circuitState: error.state }, 'Unified session blocked by circuit breaker')
|
|
||||||
} else {
|
|
||||||
this.options.logger.warn?.({ trigger, error: errorMessage }, 'Failed to send unified session telemetry')
|
this.options.logger.warn?.({ trigger, error: errorMessage }, 'Failed to send unified session telemetry')
|
||||||
}
|
|
||||||
|
|
||||||
// Record failure metric
|
// Record failure metric
|
||||||
metrics.errors?.inc({ category: 'unified_session', code: 'send_failed' })
|
metrics.errors?.inc({ category: 'unified_session', code: 'send_failed' })
|
||||||
@@ -331,7 +301,6 @@ export class UnifiedSessionManager {
|
|||||||
sendCount: 0,
|
sendCount: 0,
|
||||||
isInitialized: true
|
isInitialized: true
|
||||||
}
|
}
|
||||||
this.circuitBreaker?.reset()
|
|
||||||
this.options.logger.debug?.('UnifiedSessionManager reset')
|
this.options.logger.debug?.('UnifiedSessionManager reset')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,7 +308,6 @@ export class UnifiedSessionManager {
|
|||||||
* Destroy the manager and clean up resources.
|
* Destroy the manager and clean up resources.
|
||||||
*/
|
*/
|
||||||
destroy(): void {
|
destroy(): void {
|
||||||
this.circuitBreaker?.destroy()
|
|
||||||
this.state.isInitialized = false
|
this.state.isInitialized = false
|
||||||
this.options.logger.debug?.('UnifiedSessionManager destroyed')
|
this.options.logger.debug?.('UnifiedSessionManager destroyed')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { createHash } from 'crypto'
|
|||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import {
|
import {
|
||||||
KEY_BUNDLE_TYPE,
|
KEY_BUNDLE_TYPE,
|
||||||
|
PROTOCOL_MODE,
|
||||||
WA_ADV_ACCOUNT_SIG_PREFIX,
|
WA_ADV_ACCOUNT_SIG_PREFIX,
|
||||||
WA_ADV_DEVICE_SIG_PREFIX,
|
WA_ADV_DEVICE_SIG_PREFIX,
|
||||||
WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
||||||
@@ -58,18 +59,16 @@ const getClientPayload = (config: SocketConfig) => {
|
|||||||
userAgent: getUserAgent(config)
|
userAgent: getUserAgent(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Native protocol (WAM\x05) does not use WebInfo — only web protocol does
|
||||||
|
if (PROTOCOL_MODE !== 'native') {
|
||||||
payload.webInfo = getWebInfo(config)
|
payload.webInfo = getWebInfo(config)
|
||||||
|
}
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
|
||||||
export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
|
export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
|
||||||
const decoded = jidDecode(userJid)
|
const { user, device } = jidDecode(userJid)!
|
||||||
if (!decoded) {
|
|
||||||
throw new Boom('Invalid user JID', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { user, device } = decoded
|
|
||||||
const payload: proto.IClientPayload = {
|
const payload: proto.IClientPayload = {
|
||||||
...getClientPayload(config),
|
...getClientPayload(config),
|
||||||
passive: true,
|
passive: true,
|
||||||
@@ -158,9 +157,6 @@ export const configureSuccessfulPairing = (
|
|||||||
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
||||||
) => {
|
) => {
|
||||||
const msgId = stanza.attrs.id
|
const msgId = stanza.attrs.id
|
||||||
if (!msgId) {
|
|
||||||
throw new Boom('Missing message ID', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
|
const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
|
||||||
|
|
||||||
@@ -176,51 +172,42 @@ export const configureSuccessfulPairing = (
|
|||||||
const bizName = businessNode?.attrs.name
|
const bizName = businessNode?.attrs.name
|
||||||
const jid = deviceNode.attrs.jid
|
const jid = deviceNode.attrs.jid
|
||||||
const lid = deviceNode.attrs.lid
|
const lid = deviceNode.attrs.lid
|
||||||
if (!jid || !lid) {
|
|
||||||
throw new Boom('Missing JID or LID in device node', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
|
const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
|
||||||
if (!details || !hmac) {
|
|
||||||
throw new Boom('Missing ADV signature fields', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
let hmacPrefix = Buffer.from([])
|
let hmacPrefix = Buffer.from([])
|
||||||
if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
|
if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
|
||||||
hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
||||||
}
|
}
|
||||||
|
|
||||||
const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'))
|
const advSign = hmacSign(Buffer.concat([hmacPrefix, details!]), Buffer.from(advSecretKey, 'base64'))
|
||||||
if (Buffer.compare(hmac, advSign) !== 0) {
|
if (Buffer.compare(hmac!, advSign) !== 0) {
|
||||||
throw new Boom('Invalid account signature')
|
throw new Boom('Invalid account signature')
|
||||||
}
|
}
|
||||||
|
|
||||||
const account = proto.ADVSignedDeviceIdentity.decode(details)
|
const account = proto.ADVSignedDeviceIdentity.decode(details!)
|
||||||
const { accountSignatureKey, accountSignature, details: deviceDetails } = account
|
const { accountSignatureKey, accountSignature, details: deviceDetails } = account
|
||||||
if (!accountSignatureKey || !accountSignature || !deviceDetails) {
|
|
||||||
throw new Boom('Missing ADV account fields', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails)
|
const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails!)
|
||||||
|
|
||||||
const accountSignaturePrefix =
|
const accountSignaturePrefix =
|
||||||
deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
|
deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
|
||||||
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
||||||
: WA_ADV_ACCOUNT_SIG_PREFIX
|
: WA_ADV_ACCOUNT_SIG_PREFIX
|
||||||
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public])
|
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails!, signedIdentityKey.public])
|
||||||
if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
|
if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
|
||||||
throw new Boom('Failed to verify account signature')
|
throw new Boom('Failed to verify account signature')
|
||||||
}
|
}
|
||||||
|
|
||||||
const deviceMsg = Buffer.concat([
|
const deviceMsg = Buffer.concat([
|
||||||
WA_ADV_DEVICE_SIG_PREFIX,
|
WA_ADV_DEVICE_SIG_PREFIX,
|
||||||
deviceDetails,
|
deviceDetails!,
|
||||||
signedIdentityKey.public,
|
signedIdentityKey.public,
|
||||||
accountSignatureKey
|
accountSignatureKey!
|
||||||
])
|
])
|
||||||
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
|
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
|
||||||
|
|
||||||
const identity = createSignalIdentity(lid, accountSignatureKey)
|
const identity = createSignalIdentity(lid!, accountSignatureKey!)
|
||||||
const accountEnc = encodeSignedDeviceIdentity(account, false)
|
const accountEnc = encodeSignedDeviceIdentity(account, false)
|
||||||
|
|
||||||
const reply: BinaryNode = {
|
const reply: BinaryNode = {
|
||||||
@@ -228,7 +215,7 @@ export const configureSuccessfulPairing = (
|
|||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'result',
|
type: 'result',
|
||||||
id: msgId
|
id: msgId!
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
@@ -247,7 +234,7 @@ export const configureSuccessfulPairing = (
|
|||||||
|
|
||||||
const authUpdate: Partial<AuthenticationCreds> = {
|
const authUpdate: Partial<AuthenticationCreds> = {
|
||||||
account,
|
account,
|
||||||
me: { id: jid, name: bizName, lid },
|
me: { id: jid!, name: bizName, lid },
|
||||||
signalIdentities: [...(signalIdentities || []), identity],
|
signalIdentities: [...(signalIdentities || []), identity],
|
||||||
platform: platformNode?.attrs.name
|
platform: platformNode?.attrs.name
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export class USyncContactProtocol implements USyncQueryProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getUserElement(user: USyncUser): BinaryNode {
|
getUserElement(user: USyncUser): BinaryNode {
|
||||||
//TODO: Implement type / username fields (not yet supported)
|
if (user.phone) {
|
||||||
return {
|
return {
|
||||||
tag: 'contact',
|
tag: 'contact',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
@@ -21,6 +21,32 @@ export class USyncContactProtocol implements USyncQueryProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (user.username) {
|
||||||
|
return {
|
||||||
|
tag: 'contact',
|
||||||
|
attrs: {
|
||||||
|
username: user.username,
|
||||||
|
...(user.usernameKey ? { pin: user.usernameKey } : {}),
|
||||||
|
...(user.lid ? { lid: user.lid } : {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.type) {
|
||||||
|
return {
|
||||||
|
tag: 'contact',
|
||||||
|
attrs: {
|
||||||
|
type: user.type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
tag: 'contact',
|
||||||
|
attrs: {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
parser(node: BinaryNode): boolean {
|
parser(node: BinaryNode): boolean {
|
||||||
if (node.tag === 'contact') {
|
if (node.tag === 'contact') {
|
||||||
assertNodeErrorFree(node)
|
assertNodeErrorFree(node)
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import type { USyncQueryProtocol } from '../../Types/USync'
|
||||||
|
import { assertNodeErrorFree, type BinaryNode } from '../../WABinary'
|
||||||
|
import { USyncUser } from '../USyncUser'
|
||||||
|
|
||||||
|
export class USyncUsernameProtocol implements USyncQueryProtocol {
|
||||||
|
name = 'username'
|
||||||
|
|
||||||
|
getQueryElement(): BinaryNode {
|
||||||
|
return {
|
||||||
|
tag: 'username',
|
||||||
|
attrs: {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getUserElement(user: USyncUser): BinaryNode | null {
|
||||||
|
void user
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
parser(node: BinaryNode): string | null {
|
||||||
|
if (node.tag === 'username') {
|
||||||
|
assertNodeErrorFree(node)
|
||||||
|
return typeof node.content === 'string' ? node.content : null
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,3 +2,4 @@ export * from './USyncDeviceProtocol'
|
|||||||
export * from './USyncContactProtocol'
|
export * from './USyncContactProtocol'
|
||||||
export * from './USyncStatusProtocol'
|
export * from './USyncStatusProtocol'
|
||||||
export * from './USyncDisappearingModeProtocol'
|
export * from './USyncDisappearingModeProtocol'
|
||||||
|
export * from './USyncUsernameProtocol'
|
||||||
|
|||||||
@@ -6,11 +6,12 @@ import {
|
|||||||
USyncContactProtocol,
|
USyncContactProtocol,
|
||||||
USyncDeviceProtocol,
|
USyncDeviceProtocol,
|
||||||
USyncDisappearingModeProtocol,
|
USyncDisappearingModeProtocol,
|
||||||
USyncStatusProtocol
|
USyncStatusProtocol,
|
||||||
|
USyncUsernameProtocol
|
||||||
} from './Protocols'
|
} from './Protocols'
|
||||||
import { USyncUser } from './USyncUser'
|
import { USyncUser } from './USyncUser'
|
||||||
|
|
||||||
export type USyncQueryResultList = { [protocol: string]: unknown; id: string }
|
export type USyncQueryResultList = { [protocol: string]: unknown; id: string; rawId?: number }
|
||||||
|
|
||||||
export type USyncQueryResult = {
|
export type USyncQueryResult = {
|
||||||
list: USyncQueryResultList[]
|
list: USyncQueryResultList[]
|
||||||
@@ -68,10 +69,8 @@ export class USyncQuery {
|
|||||||
//TODO: see if there are any errors in the result node
|
//TODO: see if there are any errors in the result node
|
||||||
//const resultNode = getBinaryNodeChild(usyncNode, 'result')
|
//const resultNode = getBinaryNodeChild(usyncNode, 'result')
|
||||||
|
|
||||||
const listNode = usyncNode ? getBinaryNodeChild(usyncNode, 'list') : undefined
|
const parseNodeList = (content: BinaryNode[]): USyncQueryResultList[] =>
|
||||||
|
content.reduce((acc: USyncQueryResultList[], node) => {
|
||||||
if (listNode?.content && Array.isArray(listNode.content)) {
|
|
||||||
queryResult.list = listNode.content.reduce((acc: USyncQueryResultList[], node) => {
|
|
||||||
const id = node?.attrs.jid
|
const id = node?.attrs.jid
|
||||||
if (id) {
|
if (id) {
|
||||||
const data = Array.isArray(node?.content)
|
const data = Array.isArray(node?.content)
|
||||||
@@ -89,15 +88,24 @@ export class USyncQuery {
|
|||||||
.filter(([, b]) => b !== null) as [string, unknown][]
|
.filter(([, b]) => b !== null) as [string, unknown][]
|
||||||
)
|
)
|
||||||
: {}
|
: {}
|
||||||
acc.push({ ...data, id })
|
const rawIdAttr = node?.attrs?.['raw_id']
|
||||||
|
const rawId = rawIdAttr !== undefined ? Number(rawIdAttr) : undefined
|
||||||
|
acc.push({ ...data, id, ...(rawId !== undefined && !isNaN(rawId) ? { rawId } : {}) })
|
||||||
}
|
}
|
||||||
|
|
||||||
return acc
|
return acc
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
const listNode = usyncNode ? getBinaryNodeChild(usyncNode, 'list') : undefined
|
||||||
|
if (listNode?.content && Array.isArray(listNode.content)) {
|
||||||
|
queryResult.list = parseNodeList(listNode.content)
|
||||||
|
}
|
||||||
|
|
||||||
|
const sideListNode = usyncNode ? getBinaryNodeChild(usyncNode, 'side_list') : undefined
|
||||||
|
if (sideListNode?.content && Array.isArray(sideListNode.content)) {
|
||||||
|
queryResult.sideList = parseNodeList(sideListNode.content)
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: implement side list
|
|
||||||
//const sideListNode = getBinaryNodeChild(usyncNode, 'side_list')
|
|
||||||
return queryResult
|
return queryResult
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,4 +138,9 @@ export class USyncQuery {
|
|||||||
this.protocols.push(new USyncLIDProtocol())
|
this.protocols.push(new USyncLIDProtocol())
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
|
withUsernameProtocol() {
|
||||||
|
this.protocols.push(new USyncUsernameProtocol())
|
||||||
|
return this
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ export class USyncUser {
|
|||||||
id?: string
|
id?: string
|
||||||
lid?: string
|
lid?: string
|
||||||
phone?: string
|
phone?: string
|
||||||
|
username?: string
|
||||||
|
usernameKey?: string
|
||||||
type?: string
|
type?: string
|
||||||
personaId?: string
|
personaId?: string
|
||||||
|
|
||||||
@@ -20,6 +22,16 @@ export class USyncUser {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
|
withUsername(username: string) {
|
||||||
|
this.username = username
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
withUsernameKey(usernameKey: string) {
|
||||||
|
this.usernameKey = usernameKey
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
withType(type: string) {
|
withType(type: string) {
|
||||||
this.type = type
|
this.type = type
|
||||||
return this
|
return this
|
||||||
|
|||||||
@@ -297,4 +297,52 @@ describe('Identity Change Handling', () => {
|
|||||||
expect(result.device).toBe(5)
|
expect(result.device).toBe(5)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('onBeforeSessionRefresh callback', () => {
|
||||||
|
it('fires before assertSessions when a session refresh is about to run', async () => {
|
||||||
|
mockValidateSession.mockResolvedValue({ exists: true })
|
||||||
|
const callOrder: string[] = []
|
||||||
|
mockAssertSessions.mockImplementation(async () => {
|
||||||
|
callOrder.push('assertSessions')
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
const onBeforeSessionRefresh = jest.fn((jid: string) => {
|
||||||
|
callOrder.push(`before:${jid}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
const node = createIdentityChangeNode('user@s.whatsapp.net')
|
||||||
|
const ctx = { ...createContext(), onBeforeSessionRefresh }
|
||||||
|
const result = await handleIdentityChange(node, ctx)
|
||||||
|
|
||||||
|
expect(result.action).toBe('session_refreshed')
|
||||||
|
expect(callOrder).toEqual(['before:user@s.whatsapp.net', 'assertSessions'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not fire when the refresh is skipped (no_identity / offline / self)', async () => {
|
||||||
|
const onBeforeSessionRefresh = jest.fn()
|
||||||
|
|
||||||
|
// no identity node
|
||||||
|
const noIdentityNode: BinaryNode = {
|
||||||
|
tag: 'notification',
|
||||||
|
attrs: { from: 'a@s.whatsapp.net', type: 'encrypt' },
|
||||||
|
content: []
|
||||||
|
}
|
||||||
|
await handleIdentityChange(noIdentityNode, { ...createContext(), onBeforeSessionRefresh })
|
||||||
|
|
||||||
|
// offline notification
|
||||||
|
mockValidateSession.mockResolvedValue({ exists: true })
|
||||||
|
await handleIdentityChange(createIdentityChangeNode('b@s.whatsapp.net', '0'), {
|
||||||
|
...createContext(),
|
||||||
|
onBeforeSessionRefresh
|
||||||
|
})
|
||||||
|
|
||||||
|
// self primary
|
||||||
|
await handleIdentityChange(createIdentityChangeNode(mockMeId!), {
|
||||||
|
...createContext(),
|
||||||
|
onBeforeSessionRefresh
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(onBeforeSessionRefresh).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import { jest } from '@jest/globals'
|
|||||||
* bad-ack-handling.test.ts.
|
* bad-ack-handling.test.ts.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const OFFLINE_BUFFER_TIMEOUT_MS = 5_000
|
const OFFLINE_BUFFER_TIMEOUT_MS = 2_000
|
||||||
|
|
||||||
/** Mirrors the state variables declared at the top of makeSocket */
|
/** Mirrors the state variables declared at the top of makeSocket */
|
||||||
interface OfflineBufferState {
|
interface OfflineBufferState {
|
||||||
@@ -101,10 +101,10 @@ describe('offline-buffer safety timer (socket.ts)', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
// 1. Timeout path — CB:ib,,offline never arrives within 5 s
|
// 1. Timeout path — CB:ib,,offline never arrives within 2 s
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
it('fires after 5 s and flushes when CB:ib,,offline is delayed', () => {
|
it('fires after 2 s and flushes when CB:ib,,offline is delayed', () => {
|
||||||
startBuffer(state, mockFlush, mockWarn)
|
startBuffer(state, mockFlush, mockWarn)
|
||||||
|
|
||||||
expect(mockFlush).not.toHaveBeenCalled()
|
expect(mockFlush).not.toHaveBeenCalled()
|
||||||
@@ -144,17 +144,17 @@ describe('offline-buffer safety timer (socket.ts)', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
// 2. Happy path — CB:ib,,offline arrives before the 5 s timer fires
|
// 2. Happy path — CB:ib,,offline arrives before the 2 s timer fires
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
it('CB:ib,,offline cancels the timer and flushes exactly once', () => {
|
it('CB:ib,,offline cancels the timer and flushes exactly once', () => {
|
||||||
startBuffer(state, mockFlush, mockWarn)
|
startBuffer(state, mockFlush, mockWarn)
|
||||||
|
|
||||||
// Server responds before the 5 s timeout
|
// Server responds before the 2 s timeout
|
||||||
jest.advanceTimersByTime(1_000)
|
jest.advanceTimersByTime(1_000)
|
||||||
onOffline(state, mockFlush)
|
onOffline(state, mockFlush)
|
||||||
|
|
||||||
// Timer should be cancelled — advancing past 5 s must not cause a second flush
|
// Timer should be cancelled — advancing past 2 s must not cause a second flush
|
||||||
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS)
|
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS)
|
||||||
|
|
||||||
expect(mockFlush).toHaveBeenCalledTimes(1)
|
expect(mockFlush).toHaveBeenCalledTimes(1)
|
||||||
@@ -192,7 +192,7 @@ describe('offline-buffer safety timer (socket.ts)', () => {
|
|||||||
|
|
||||||
onClose(state)
|
onClose(state)
|
||||||
|
|
||||||
// Timer must be gone — advancing past 5 s must not trigger any flush
|
// Timer must be gone — advancing past 2 s must not trigger any flush
|
||||||
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS)
|
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS)
|
||||||
|
|
||||||
expect(mockFlush).not.toHaveBeenCalled()
|
expect(mockFlush).not.toHaveBeenCalled()
|
||||||
@@ -236,7 +236,7 @@ describe('offline-buffer safety timer (socket.ts)', () => {
|
|||||||
// 4. Boundary / timing edge cases
|
// 4. Boundary / timing edge cases
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
it('does not flush before exactly 5 s have elapsed', () => {
|
it('does not flush before exactly 2 s have elapsed', () => {
|
||||||
startBuffer(state, mockFlush, mockWarn)
|
startBuffer(state, mockFlush, mockWarn)
|
||||||
|
|
||||||
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS - 1)
|
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS - 1)
|
||||||
@@ -244,7 +244,7 @@ describe('offline-buffer safety timer (socket.ts)', () => {
|
|||||||
expect(mockFlush).not.toHaveBeenCalled()
|
expect(mockFlush).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('flushes at exactly the 5 s boundary', () => {
|
it('flushes at exactly the 2 s boundary', () => {
|
||||||
startBuffer(state, mockFlush, mockWarn)
|
startBuffer(state, mockFlush, mockWarn)
|
||||||
|
|
||||||
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS)
|
jest.advanceTimersByTime(OFFLINE_BUFFER_TIMEOUT_MS)
|
||||||
|
|||||||
@@ -0,0 +1,391 @@
|
|||||||
|
import { jest } from '@jest/globals'
|
||||||
|
import {
|
||||||
|
withBoundedRetry,
|
||||||
|
BoundedRetryGiveUpError,
|
||||||
|
BoundedRetryAbortedError,
|
||||||
|
WHATSAPP_BACKOFF_DELAYS,
|
||||||
|
DEFAULT_TTL_MS
|
||||||
|
} from '../../Utils/bounded-retry'
|
||||||
|
|
||||||
|
// All tests use very short real delays (1-50ms) so they run fast.
|
||||||
|
// This sidesteps the fragility of jest fake timers + async chains.
|
||||||
|
|
||||||
|
describe('bounded-retry — WhatsApp-aligned per-operation retry', () => {
|
||||||
|
test('default delay sequence matches WhatsApp Android empirical capture', () => {
|
||||||
|
// Frida trace: 3000 -> 10000 -> 60000 -> ~64000 -> 120000 ms
|
||||||
|
expect(WHATSAPP_BACKOFF_DELAYS).toEqual([3000, 10000, 60000, 60000, 120000])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('default TTL is 10 minutes (matches empirical stabilisation + safety buffer)', () => {
|
||||||
|
expect(DEFAULT_TTL_MS).toBe(600_000)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('first-attempt success returns immediately, no retries', async () => {
|
||||||
|
const op = jest.fn<() => Promise<string>>().mockResolvedValue('ok')
|
||||||
|
const result = await withBoundedRetry(op, { name: 'fast-success' })
|
||||||
|
expect(result).toBe('ok')
|
||||||
|
expect(op).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('retries with the configured delay sequence after failures', async () => {
|
||||||
|
const op = jest
|
||||||
|
.fn<() => Promise<number>>()
|
||||||
|
.mockRejectedValueOnce(new Error('try1'))
|
||||||
|
.mockRejectedValueOnce(new Error('try2'))
|
||||||
|
.mockResolvedValueOnce(42)
|
||||||
|
|
||||||
|
const onRetry = jest.fn<(err: Error, attempt: number, delayMs: number) => void>()
|
||||||
|
const result = await withBoundedRetry(op, {
|
||||||
|
name: 'three-tries',
|
||||||
|
delays: [10, 20, 40],
|
||||||
|
jitter: 0,
|
||||||
|
onRetry
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toBe(42)
|
||||||
|
expect(op).toHaveBeenCalledTimes(3)
|
||||||
|
expect(onRetry).toHaveBeenCalledTimes(2)
|
||||||
|
expect(onRetry.mock.calls[0]![2]).toBe(10)
|
||||||
|
expect(onRetry.mock.calls[1]![2]).toBe(20)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('TTL exhaustion throws BoundedRetryGiveUpError (no infinite retries)', async () => {
|
||||||
|
const op = jest.fn<() => Promise<string>>().mockRejectedValue(new Error('always-fails'))
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
withBoundedRetry(op, {
|
||||||
|
name: 'ttl-test',
|
||||||
|
delays: [10],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 50
|
||||||
|
})
|
||||||
|
).rejects.toBeInstanceOf(BoundedRetryGiveUpError)
|
||||||
|
|
||||||
|
// Should have tried multiple times before giving up
|
||||||
|
expect(op.mock.calls.length).toBeGreaterThanOrEqual(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('per-attempt timeout fires for slow operations', async () => {
|
||||||
|
const slowOp = jest.fn<() => Promise<string>>(() => new Promise(() => {})) // hangs
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
withBoundedRetry(slowOp, {
|
||||||
|
name: 'slow',
|
||||||
|
delays: [5],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 200,
|
||||||
|
perAttemptTimeoutMs: 30
|
||||||
|
})
|
||||||
|
).rejects.toBeInstanceOf(BoundedRetryGiveUpError)
|
||||||
|
|
||||||
|
// Multiple attempts should have been tried (each timed out at 30ms)
|
||||||
|
expect(slowOp.mock.calls.length).toBeGreaterThan(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('shouldRetry predicate can short-circuit retries', async () => {
|
||||||
|
const op = jest
|
||||||
|
.fn<() => Promise<string>>()
|
||||||
|
.mockRejectedValueOnce(new Error('transient'))
|
||||||
|
.mockRejectedValueOnce(new Error('FATAL: do not retry'))
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
withBoundedRetry(op, {
|
||||||
|
name: 'predicate-test',
|
||||||
|
delays: [1],
|
||||||
|
jitter: 0,
|
||||||
|
shouldRetry: err => !err.message.startsWith('FATAL')
|
||||||
|
})
|
||||||
|
).rejects.toThrow('FATAL: do not retry')
|
||||||
|
|
||||||
|
expect(op).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('AbortSignal cancels in-flight retry sleep', async () => {
|
||||||
|
const op = jest.fn<() => Promise<string>>().mockRejectedValue(new Error('fail'))
|
||||||
|
const ctrl = new AbortController()
|
||||||
|
|
||||||
|
const promise = withBoundedRetry(op, {
|
||||||
|
name: 'abort-test',
|
||||||
|
delays: [10_000], // long sleep so abort can happen during it
|
||||||
|
jitter: 0,
|
||||||
|
signal: ctrl.signal
|
||||||
|
})
|
||||||
|
|
||||||
|
// First attempt fires immediately; sleep starts
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 10))
|
||||||
|
ctrl.abort()
|
||||||
|
|
||||||
|
await expect(promise).rejects.toBeInstanceOf(BoundedRetryAbortedError)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('two concurrent retry chains do NOT interfere with each other (per-op isolation)', async () => {
|
||||||
|
// Key advantage over circuit breaker: failures in one chain do not
|
||||||
|
// block another chain. With circuit breaker, 5 failures from chain A
|
||||||
|
// would block chain B too. With bounded-retry, B is independent.
|
||||||
|
|
||||||
|
const flakyOp = jest
|
||||||
|
.fn<() => Promise<string>>()
|
||||||
|
.mockRejectedValueOnce(new Error('a1'))
|
||||||
|
.mockResolvedValueOnce('a-ok')
|
||||||
|
|
||||||
|
const fastOp = jest.fn<() => Promise<string>>().mockResolvedValue('b-ok')
|
||||||
|
|
||||||
|
// Start a (will retry once after 30ms) and b (immediate)
|
||||||
|
const aPromise = withBoundedRetry(flakyOp, { name: 'a', delays: [30], jitter: 0 })
|
||||||
|
const bPromise = withBoundedRetry(fastOp, { name: 'b', delays: [30], jitter: 0 })
|
||||||
|
|
||||||
|
// b should resolve right away
|
||||||
|
const bResult = await bPromise
|
||||||
|
expect(bResult).toBe('b-ok')
|
||||||
|
expect(fastOp).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
// a still running — wait for it
|
||||||
|
const aResult = await aPromise
|
||||||
|
expect(aResult).toBe('a-ok')
|
||||||
|
expect(flakyOp).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('delay sequence caps at last value (no unbounded growth)', async () => {
|
||||||
|
const op = jest.fn<() => Promise<string>>().mockRejectedValue(new Error('fail'))
|
||||||
|
const onRetry = jest.fn<(err: Error, attempt: number, delayMs: number) => void>()
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
withBoundedRetry(op, {
|
||||||
|
name: 'cap-test',
|
||||||
|
delays: [5, 10, 15], // 3 distinct steps; 4th+ retry should reuse 15
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 300,
|
||||||
|
onRetry
|
||||||
|
})
|
||||||
|
).rejects.toBeInstanceOf(BoundedRetryGiveUpError)
|
||||||
|
|
||||||
|
// Find delays >= 4th retry — all should be capped at 15
|
||||||
|
const lateRetries = onRetry.mock.calls.filter(c => c[1] >= 4)
|
||||||
|
expect(lateRetries.length).toBeGreaterThan(0)
|
||||||
|
for (const call of lateRetries) {
|
||||||
|
expect(call[2]).toBeLessThanOrEqual(15)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('jitter randomises delay within +/- factor', async () => {
|
||||||
|
const op = jest.fn<() => Promise<string>>().mockRejectedValue(new Error('fail'))
|
||||||
|
const observed: number[] = []
|
||||||
|
|
||||||
|
// Single run, capture multiple onRetry calls (each with different jitter)
|
||||||
|
await withBoundedRetry(op, {
|
||||||
|
name: 'jitter-test',
|
||||||
|
delays: [50], // base delay
|
||||||
|
jitter: 0.3, // +/- 30% -> [35, 65]
|
||||||
|
ttlMs: 1000, // ttl high enough for ~10 retries
|
||||||
|
perAttemptTimeoutMs: 5,
|
||||||
|
onRetry: (_, __, d) => observed.push(d)
|
||||||
|
}).catch(() => {})
|
||||||
|
|
||||||
|
expect(observed.length).toBeGreaterThanOrEqual(3)
|
||||||
|
const unique = new Set(observed)
|
||||||
|
expect(unique.size).toBeGreaterThan(1)
|
||||||
|
// Every observed delay must be within jitter window — but the LAST one
|
||||||
|
// may be capped by remaining ttl budget, so check all but the last
|
||||||
|
const inWindow = observed.slice(0, -1)
|
||||||
|
for (const d of inWindow) {
|
||||||
|
expect(d).toBeGreaterThanOrEqual(35)
|
||||||
|
expect(d).toBeLessThanOrEqual(65)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('delay does not exceed remaining TTL budget', async () => {
|
||||||
|
const op = jest.fn<() => Promise<string>>().mockRejectedValue(new Error('fail'))
|
||||||
|
const onRetry = jest.fn<(err: Error, attempt: number, delayMs: number) => void>()
|
||||||
|
|
||||||
|
await withBoundedRetry(op, {
|
||||||
|
name: 'budget-cap',
|
||||||
|
delays: [200], // would exceed ttl
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 50, // very short
|
||||||
|
onRetry
|
||||||
|
}).catch(() => {})
|
||||||
|
|
||||||
|
// All scheduled delays should be capped to remaining budget
|
||||||
|
for (const call of onRetry.mock.calls) {
|
||||||
|
expect(call[2]).toBeLessThanOrEqual(50)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Tests for fixes from PR #393 review ──────────────────────────────
|
||||||
|
|
||||||
|
test('TTL is enforced BEFORE the next attempt (not just after)', async () => {
|
||||||
|
// Regression: previously TTL was only checked after a failure, so a
|
||||||
|
// new attempt could start with 0ms remaining and run for the full
|
||||||
|
// per-attempt timeout, overshooting wall-clock budget by that much.
|
||||||
|
const slowOp = jest.fn<() => Promise<string>>(() => new Promise(resolve => setTimeout(() => resolve('late'), 200)))
|
||||||
|
|
||||||
|
const start = Date.now()
|
||||||
|
await expect(
|
||||||
|
withBoundedRetry(slowOp, {
|
||||||
|
name: 'ttl-strict',
|
||||||
|
delays: [10],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 50,
|
||||||
|
perAttemptTimeoutMs: 1000 // huge, must be capped by TTL
|
||||||
|
})
|
||||||
|
).rejects.toBeInstanceOf(BoundedRetryGiveUpError)
|
||||||
|
|
||||||
|
const elapsed = Date.now() - start
|
||||||
|
// With strict TTL enforcement, total runtime should be very close to ttlMs.
|
||||||
|
// Allow up to 100ms slack for Node timer + microtask scheduling.
|
||||||
|
expect(elapsed).toBeLessThan(150)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('per-attempt timeout is capped by remaining TTL budget', async () => {
|
||||||
|
// If user passes perAttemptTimeoutMs > ttlMs, the cap should apply.
|
||||||
|
const slowOp = jest.fn<() => Promise<string>>(() => new Promise(() => {})) // hangs forever
|
||||||
|
|
||||||
|
const start = Date.now()
|
||||||
|
await expect(
|
||||||
|
withBoundedRetry(slowOp, {
|
||||||
|
name: 'attempt-cap',
|
||||||
|
delays: [1],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 30,
|
||||||
|
perAttemptTimeoutMs: 5000 // way bigger than ttl
|
||||||
|
})
|
||||||
|
).rejects.toBeInstanceOf(BoundedRetryGiveUpError)
|
||||||
|
|
||||||
|
const elapsed = Date.now() - start
|
||||||
|
expect(elapsed).toBeLessThan(150) // not 5000ms!
|
||||||
|
})
|
||||||
|
|
||||||
|
test('operation receives an AbortSignal that is aborted on per-attempt timeout', async () => {
|
||||||
|
// New API: operation can opt into cancellation via the signal arg.
|
||||||
|
const aborts: boolean[] = []
|
||||||
|
const opThatRespectsSignal = jest.fn(
|
||||||
|
(signal?: AbortSignal) =>
|
||||||
|
new Promise<string>((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => resolve('late'), 100)
|
||||||
|
signal?.addEventListener('abort', () => {
|
||||||
|
clearTimeout(timer)
|
||||||
|
aborts.push(true)
|
||||||
|
reject(new Error('aborted by signal'))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
await withBoundedRetry(opThatRespectsSignal, {
|
||||||
|
name: 'signal-aware',
|
||||||
|
delays: [1],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 80,
|
||||||
|
perAttemptTimeoutMs: 20 // smaller than 100ms op duration
|
||||||
|
}).catch(() => {})
|
||||||
|
|
||||||
|
expect(aborts.length).toBeGreaterThan(0) // at least one attempt was aborted
|
||||||
|
})
|
||||||
|
|
||||||
|
test('sleep listener is removed when timeout completes normally (no leak)', async () => {
|
||||||
|
// Regression: sleep used signal.addEventListener with { once: true } but
|
||||||
|
// never removed the listener on timer-resolve. With many retries on a
|
||||||
|
// shared signal, listeners would accumulate.
|
||||||
|
//
|
||||||
|
// Make the failure mode observable by spying on add/removeEventListener
|
||||||
|
// directly so the assertion fails if cleanup is removed.
|
||||||
|
const ctrl = new AbortController()
|
||||||
|
const realAdd = ctrl.signal.addEventListener.bind(ctrl.signal)
|
||||||
|
const realRemove = ctrl.signal.removeEventListener.bind(ctrl.signal)
|
||||||
|
let addCount = 0
|
||||||
|
let removeCount = 0
|
||||||
|
ctrl.signal.addEventListener = ((type: string, listener: never, opts?: never) => {
|
||||||
|
if (type === 'abort') addCount++
|
||||||
|
return realAdd(type, listener, opts)
|
||||||
|
}) as typeof ctrl.signal.addEventListener
|
||||||
|
ctrl.signal.removeEventListener = ((type: string, listener: never, opts?: never) => {
|
||||||
|
if (type === 'abort') removeCount++
|
||||||
|
return realRemove(type, listener, opts)
|
||||||
|
}) as typeof ctrl.signal.removeEventListener
|
||||||
|
|
||||||
|
const op = jest
|
||||||
|
.fn<() => Promise<string>>()
|
||||||
|
.mockRejectedValueOnce(new Error('1'))
|
||||||
|
.mockRejectedValueOnce(new Error('2'))
|
||||||
|
.mockRejectedValueOnce(new Error('3'))
|
||||||
|
.mockResolvedValueOnce('ok')
|
||||||
|
|
||||||
|
const result = await withBoundedRetry(op, {
|
||||||
|
name: 'no-leak',
|
||||||
|
delays: [5],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 500,
|
||||||
|
signal: ctrl.signal
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toBe('ok')
|
||||||
|
expect(op).toHaveBeenCalledTimes(4)
|
||||||
|
// If sleep() leaks listeners, addCount > removeCount. Each retry adds
|
||||||
|
// listeners (1 sleep + 1 outer-abort forwarding) and must remove the
|
||||||
|
// same number on settlement.
|
||||||
|
expect(addCount).toBeGreaterThan(0)
|
||||||
|
expect(addCount).toBe(removeCount)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('logger receives structured logs for retry, give-up, and recovery', async () => {
|
||||||
|
const debugCalls: unknown[][] = []
|
||||||
|
const infoCalls: unknown[][] = []
|
||||||
|
const warnCalls: unknown[][] = []
|
||||||
|
const fakeLogger = {
|
||||||
|
debug: (...args: unknown[]) => debugCalls.push(args),
|
||||||
|
info: (...args: unknown[]) => infoCalls.push(args),
|
||||||
|
warn: (...args: unknown[]) => warnCalls.push(args),
|
||||||
|
error: () => {},
|
||||||
|
fatal: () => {},
|
||||||
|
trace: () => {},
|
||||||
|
child: () => fakeLogger,
|
||||||
|
level: 'debug'
|
||||||
|
}
|
||||||
|
|
||||||
|
const op = jest
|
||||||
|
.fn<() => Promise<string>>()
|
||||||
|
.mockRejectedValueOnce(new Error('boom'))
|
||||||
|
.mockResolvedValueOnce('ok')
|
||||||
|
|
||||||
|
const result = await withBoundedRetry(op, {
|
||||||
|
name: 'logged-op',
|
||||||
|
delays: [5],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 200,
|
||||||
|
logger: fakeLogger as never
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toBe('ok')
|
||||||
|
// Should have logged the scheduling at debug level
|
||||||
|
expect(debugCalls.length).toBeGreaterThanOrEqual(1)
|
||||||
|
// Should have logged the recovery at info level
|
||||||
|
expect(infoCalls.length).toBeGreaterThanOrEqual(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('logger reports give-up via warn when TTL exceeded', async () => {
|
||||||
|
const warnCalls: unknown[][] = []
|
||||||
|
const fakeLogger = {
|
||||||
|
debug: () => {},
|
||||||
|
info: () => {},
|
||||||
|
warn: (...args: unknown[]) => warnCalls.push(args),
|
||||||
|
error: () => {},
|
||||||
|
fatal: () => {},
|
||||||
|
trace: () => {},
|
||||||
|
child: () => fakeLogger,
|
||||||
|
level: 'debug'
|
||||||
|
}
|
||||||
|
|
||||||
|
const op = jest.fn<() => Promise<string>>().mockRejectedValue(new Error('always-fails'))
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
withBoundedRetry(op, {
|
||||||
|
name: 'logged-fail',
|
||||||
|
delays: [5],
|
||||||
|
jitter: 0,
|
||||||
|
ttlMs: 30,
|
||||||
|
logger: fakeLogger as never
|
||||||
|
})
|
||||||
|
).rejects.toBeInstanceOf(BoundedRetryGiveUpError)
|
||||||
|
|
||||||
|
expect(warnCalls.length).toBeGreaterThanOrEqual(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,371 +0,0 @@
|
|||||||
/**
|
|
||||||
* Testes unitários para circuit-breaker.ts
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { afterEach, beforeEach, describe, expect, it } from '@jest/globals'
|
|
||||||
import {
|
|
||||||
CircuitBreaker,
|
|
||||||
CircuitBreakerRegistry,
|
|
||||||
CircuitOpenError,
|
|
||||||
type CircuitState,
|
|
||||||
CircuitTimeoutError,
|
|
||||||
createCircuitBreaker,
|
|
||||||
getCircuitHealth,
|
|
||||||
globalCircuitRegistry,
|
|
||||||
withCircuitBreaker
|
|
||||||
} from '../../Utils/circuit-breaker.js'
|
|
||||||
|
|
||||||
describe('CircuitBreaker', () => {
|
|
||||||
let breaker: CircuitBreaker
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
breaker = createCircuitBreaker({
|
|
||||||
name: 'test',
|
|
||||||
failureThreshold: 3,
|
|
||||||
successThreshold: 2,
|
|
||||||
resetTimeout: 100,
|
|
||||||
timeout: 1000,
|
|
||||||
volumeThreshold: 3,
|
|
||||||
collectMetrics: false
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
breaker.destroy()
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('initial state', () => {
|
|
||||||
it('should start in closed state', () => {
|
|
||||||
expect(breaker.getState()).toBe('closed')
|
|
||||||
expect(breaker.isClosed()).toBe(true)
|
|
||||||
expect(breaker.isOpen()).toBe(false)
|
|
||||||
expect(breaker.isHalfOpen()).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('successful operations', () => {
|
|
||||||
it('should execute successful operations', async () => {
|
|
||||||
const result = await breaker.execute(() => 'success')
|
|
||||||
expect(result).toBe('success')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should execute async operations', async () => {
|
|
||||||
const result = await breaker.execute(async () => {
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 10))
|
|
||||||
return 'async success'
|
|
||||||
})
|
|
||||||
expect(result).toBe('async success')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should track successful calls in stats', async () => {
|
|
||||||
await breaker.execute(() => 'success')
|
|
||||||
await breaker.execute(() => 'success')
|
|
||||||
|
|
||||||
const stats = breaker.getStats()
|
|
||||||
expect(stats.totalCalls).toBe(2)
|
|
||||||
expect(stats.totalSuccesses).toBe(2)
|
|
||||||
expect(stats.totalFailures).toBe(0)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('failure handling', () => {
|
|
||||||
it('should open after reaching failure threshold', async () => {
|
|
||||||
const failingOp = () => {
|
|
||||||
throw new Error('Failure')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reach failure threshold
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
await expect(breaker.execute(failingOp)).rejects.toThrow('Failure')
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(breaker.isOpen()).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not open before reaching threshold', async () => {
|
|
||||||
const failingOp = () => {
|
|
||||||
throw new Error('Failure')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Below threshold
|
|
||||||
for (let i = 0; i < 2; i++) {
|
|
||||||
await expect(breaker.execute(failingOp)).rejects.toThrow('Failure')
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(breaker.isClosed()).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should reset failure count on success', async () => {
|
|
||||||
const failingOp = () => {
|
|
||||||
throw new Error('Failure')
|
|
||||||
}
|
|
||||||
|
|
||||||
await expect(breaker.execute(failingOp)).rejects.toThrow()
|
|
||||||
await expect(breaker.execute(failingOp)).rejects.toThrow()
|
|
||||||
|
|
||||||
// Success resets failures
|
|
||||||
await breaker.execute(() => 'success')
|
|
||||||
|
|
||||||
// Only 1 more failure needed (already have 2 in window, need 3 total)
|
|
||||||
await expect(breaker.execute(failingOp)).rejects.toThrow()
|
|
||||||
|
|
||||||
// Should open now (3 failures in window)
|
|
||||||
expect(breaker.isOpen()).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('open state', () => {
|
|
||||||
beforeEach(async () => {
|
|
||||||
// Force open
|
|
||||||
breaker.trip()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should reject operations when open', async () => {
|
|
||||||
await expect(breaker.execute(() => 'success')).rejects.toThrow(CircuitOpenError)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should transition to half-open after reset timeout', async () => {
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 150))
|
|
||||||
expect(breaker.isHalfOpen()).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('half-open state', () => {
|
|
||||||
beforeEach(async () => {
|
|
||||||
breaker.trip()
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 150))
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should close after success threshold', async () => {
|
|
||||||
expect(breaker.isHalfOpen()).toBe(true)
|
|
||||||
|
|
||||||
// Success threshold is 2
|
|
||||||
await breaker.execute(() => 'success')
|
|
||||||
await breaker.execute(() => 'success')
|
|
||||||
|
|
||||||
expect(breaker.isClosed()).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should reopen on failure', async () => {
|
|
||||||
expect(breaker.isHalfOpen()).toBe(true)
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
breaker.execute(() => {
|
|
||||||
throw new Error('Failure')
|
|
||||||
})
|
|
||||||
).rejects.toThrow()
|
|
||||||
|
|
||||||
expect(breaker.isOpen()).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('manual controls', () => {
|
|
||||||
it('should force open with trip()', () => {
|
|
||||||
breaker.trip()
|
|
||||||
expect(breaker.isOpen()).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should force close with reset()', async () => {
|
|
||||||
breaker.trip()
|
|
||||||
breaker.reset()
|
|
||||||
expect(breaker.isClosed()).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('timeout', () => {
|
|
||||||
it('should timeout slow operations', async () => {
|
|
||||||
const slowBreaker = createCircuitBreaker({
|
|
||||||
name: 'slow',
|
|
||||||
timeout: 50,
|
|
||||||
collectMetrics: false
|
|
||||||
})
|
|
||||||
|
|
||||||
await expect(slowBreaker.execute(() => new Promise(resolve => setTimeout(resolve, 200)))).rejects.toThrow(
|
|
||||||
CircuitTimeoutError
|
|
||||||
)
|
|
||||||
|
|
||||||
slowBreaker.destroy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('events', () => {
|
|
||||||
it('should emit state-change event', async () => {
|
|
||||||
const stateChanges: Array<{ from: CircuitState; to: CircuitState }> = []
|
|
||||||
|
|
||||||
breaker.on('state-change', change => {
|
|
||||||
stateChanges.push(change)
|
|
||||||
})
|
|
||||||
|
|
||||||
breaker.trip()
|
|
||||||
breaker.reset()
|
|
||||||
|
|
||||||
expect(stateChanges).toHaveLength(2)
|
|
||||||
expect(stateChanges[0]).toEqual({ from: 'closed', to: 'open' })
|
|
||||||
expect(stateChanges[1]).toEqual({ from: 'open', to: 'closed' })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should emit success and failure events', async () => {
|
|
||||||
let successCount = 0
|
|
||||||
let failureCount = 0
|
|
||||||
|
|
||||||
breaker.on('success', () => successCount++)
|
|
||||||
breaker.on('failure', () => failureCount++)
|
|
||||||
|
|
||||||
await breaker.execute(() => 'success')
|
|
||||||
await expect(
|
|
||||||
breaker.execute(() => {
|
|
||||||
throw new Error()
|
|
||||||
})
|
|
||||||
).rejects.toThrow()
|
|
||||||
|
|
||||||
expect(successCount).toBe(1)
|
|
||||||
expect(failureCount).toBe(1)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('isFailure predicate', () => {
|
|
||||||
it('should use custom isFailure predicate', async () => {
|
|
||||||
const customBreaker = createCircuitBreaker({
|
|
||||||
name: 'custom',
|
|
||||||
failureThreshold: 1,
|
|
||||||
volumeThreshold: 1,
|
|
||||||
shouldCountError: (error: any) => error.message !== 'Ignored',
|
|
||||||
collectMetrics: false
|
|
||||||
})
|
|
||||||
|
|
||||||
// This error should be ignored
|
|
||||||
await expect(
|
|
||||||
customBreaker.execute(() => {
|
|
||||||
throw new Error('Ignored')
|
|
||||||
})
|
|
||||||
).rejects.toThrow()
|
|
||||||
|
|
||||||
expect(customBreaker.isClosed()).toBe(true)
|
|
||||||
|
|
||||||
// This should trip the breaker
|
|
||||||
await expect(
|
|
||||||
customBreaker.execute(() => {
|
|
||||||
throw new Error('Real failure')
|
|
||||||
})
|
|
||||||
).rejects.toThrow()
|
|
||||||
|
|
||||||
expect(customBreaker.isOpen()).toBe(true)
|
|
||||||
|
|
||||||
customBreaker.destroy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('sync operations', () => {
|
|
||||||
it('should execute sync operations', () => {
|
|
||||||
const result = breaker.executeSync(() => 'sync result')
|
|
||||||
expect(result).toBe('sync result')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should handle sync failures', () => {
|
|
||||||
expect(() =>
|
|
||||||
breaker.executeSync(() => {
|
|
||||||
throw new Error('Sync failure')
|
|
||||||
})
|
|
||||||
).toThrow('Sync failure')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('CircuitBreakerRegistry', () => {
|
|
||||||
let registry: CircuitBreakerRegistry
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
registry = new CircuitBreakerRegistry()
|
|
||||||
})
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
registry.destroyAll()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should create and retrieve circuit breakers', () => {
|
|
||||||
const breaker1 = registry.get('test1')
|
|
||||||
const breaker2 = registry.get('test1')
|
|
||||||
|
|
||||||
expect(breaker1).toBe(breaker2)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should check if breaker exists', () => {
|
|
||||||
registry.get('exists')
|
|
||||||
|
|
||||||
expect(registry.has('exists')).toBe(true)
|
|
||||||
expect(registry.has('notexists')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should remove breaker', () => {
|
|
||||||
registry.get('toRemove')
|
|
||||||
expect(registry.remove('toRemove')).toBe(true)
|
|
||||||
expect(registry.has('toRemove')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should get all stats', () => {
|
|
||||||
registry.get('breaker1')
|
|
||||||
registry.get('breaker2')
|
|
||||||
|
|
||||||
const stats = registry.getAllStats()
|
|
||||||
|
|
||||||
expect(stats).toHaveProperty('breaker1')
|
|
||||||
expect(stats).toHaveProperty('breaker2')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should reset all breakers', async () => {
|
|
||||||
const breaker = registry.get('test')
|
|
||||||
breaker.trip()
|
|
||||||
|
|
||||||
registry.resetAll()
|
|
||||||
|
|
||||||
expect(breaker.isClosed()).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('withCircuitBreaker', () => {
|
|
||||||
it('should wrap function with circuit breaker', async () => {
|
|
||||||
let callCount = 0
|
|
||||||
|
|
||||||
const protectedFn = withCircuitBreaker(
|
|
||||||
async () => {
|
|
||||||
callCount++
|
|
||||||
return 'result'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'wrapped-fn',
|
|
||||||
collectMetrics: false
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const result = await protectedFn()
|
|
||||||
|
|
||||||
expect(result).toBe('result')
|
|
||||||
expect(callCount).toBe(1)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('getCircuitHealth', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
globalCircuitRegistry.destroyAll()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report healthy when all circuits closed', () => {
|
|
||||||
globalCircuitRegistry.get('healthy1')
|
|
||||||
globalCircuitRegistry.get('healthy2')
|
|
||||||
|
|
||||||
const health = getCircuitHealth()
|
|
||||||
|
|
||||||
expect(health.healthy).toBe(true)
|
|
||||||
expect(health.openCircuits).toHaveLength(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report unhealthy when circuit is open', () => {
|
|
||||||
const breaker = globalCircuitRegistry.get('unhealthy')
|
|
||||||
breaker.trip()
|
|
||||||
|
|
||||||
const health = getCircuitHealth()
|
|
||||||
|
|
||||||
expect(health.healthy).toBe(false)
|
|
||||||
expect(health.openCircuits).toContain('unhealthy')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
* Testes unitários para retry-utils.ts
|
* Testes unitários para retry-utils.ts
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { beforeEach, describe, expect, it, jest } from '@jest/globals'
|
import { describe, expect, it, jest } from '@jest/globals'
|
||||||
import {
|
import {
|
||||||
calculateDelay,
|
calculateDelay,
|
||||||
createRetrier,
|
createRetrier,
|
||||||
@@ -11,12 +11,10 @@ import {
|
|||||||
retry,
|
retry,
|
||||||
RETRY_BACKOFF_DELAYS,
|
RETRY_BACKOFF_DELAYS,
|
||||||
RETRY_JITTER_FACTOR,
|
RETRY_JITTER_FACTOR,
|
||||||
retryable,
|
|
||||||
RetryAbortedError,
|
RetryAbortedError,
|
||||||
retryConfigs,
|
retryConfigs,
|
||||||
type RetryContext,
|
type RetryContext,
|
||||||
RetryExhaustedError,
|
RetryExhaustedError,
|
||||||
RetryManager,
|
|
||||||
retryPredicates,
|
retryPredicates,
|
||||||
retryWithResult
|
retryWithResult
|
||||||
} from '../../Utils/retry-utils.js'
|
} from '../../Utils/retry-utils.js'
|
||||||
@@ -315,103 +313,6 @@ describe('createRetrier', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('retryable', () => {
|
|
||||||
it('should wrap function with retry', async () => {
|
|
||||||
let attempts = 0
|
|
||||||
|
|
||||||
const fn = retryable(
|
|
||||||
() => {
|
|
||||||
attempts++
|
|
||||||
if (attempts < 2) throw new Error('Failing')
|
|
||||||
return 'wrapped result'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
maxAttempts: 5,
|
|
||||||
baseDelay: 10,
|
|
||||||
collectMetrics: false
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const result = await fn()
|
|
||||||
|
|
||||||
expect(result).toBe('wrapped result')
|
|
||||||
expect(attempts).toBe(2)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('RetryManager', () => {
|
|
||||||
let manager: RetryManager
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
manager = new RetryManager({ baseDelay: 200, collectMetrics: false })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should execute operation with id', async () => {
|
|
||||||
const result = await manager.execute('op1', () => 'result')
|
|
||||||
expect(result).toBe('result')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should cancel active retry', async () => {
|
|
||||||
let attempt = 0
|
|
||||||
|
|
||||||
const promise = manager.execute('cancelable', async () => {
|
|
||||||
attempt++
|
|
||||||
if (attempt === 1) {
|
|
||||||
throw new Error('Temporary failure')
|
|
||||||
}
|
|
||||||
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
|
||||||
return 'result'
|
|
||||||
})
|
|
||||||
|
|
||||||
// Cancel during retry delay
|
|
||||||
setTimeout(() => manager.cancel('cancelable'), 100)
|
|
||||||
|
|
||||||
await expect(promise).rejects.toThrow()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should check if operation is active', async () => {
|
|
||||||
let resolve: () => void
|
|
||||||
const promise = manager.execute(
|
|
||||||
'active',
|
|
||||||
() =>
|
|
||||||
new Promise<string>(r => {
|
|
||||||
resolve = () => r('done')
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(manager.isActive('active')).toBe(true)
|
|
||||||
|
|
||||||
resolve!()
|
|
||||||
await promise
|
|
||||||
|
|
||||||
expect(manager.isActive('active')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should cancel all operations', async () => {
|
|
||||||
const promises = [
|
|
||||||
manager.execute('op1', () => new Promise((_, reject) => setTimeout(() => reject(new Error()), 1000))),
|
|
||||||
manager.execute('op2', () => new Promise((_, reject) => setTimeout(() => reject(new Error()), 1000)))
|
|
||||||
]
|
|
||||||
|
|
||||||
setTimeout(() => manager.cancelAll(), 20)
|
|
||||||
|
|
||||||
await expect(Promise.all(promises)).rejects.toThrow()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should emit events', async () => {
|
|
||||||
const events: string[] = []
|
|
||||||
|
|
||||||
manager.on('attempt', () => events.push('attempt'))
|
|
||||||
manager.on('success', () => events.push('success'))
|
|
||||||
|
|
||||||
await manager.execute('test', () => 'result')
|
|
||||||
|
|
||||||
expect(events).toContain('attempt')
|
|
||||||
expect(events).toContain('success')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('retryPredicates', () => {
|
describe('retryPredicates', () => {
|
||||||
describe('always', () => {
|
describe('always', () => {
|
||||||
it('should always return true', () => {
|
it('should always return true', () => {
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
import { jest } from '@jest/globals'
|
import { jest } from '@jest/globals'
|
||||||
import { DisconnectReason, type SignalKeyStoreWithTransaction } from '../../Types'
|
import { DisconnectReason, type SignalKeyStoreWithTransaction } from '../../Types'
|
||||||
import { getErrorCodeFromStreamError, SERVER_ERROR_CODES } from '../../Utils'
|
import { getErrorCodeFromStreamError, SERVER_ERROR_CODES } from '../../Utils'
|
||||||
import { buildTcTokenFromJid, isTcTokenExpired, shouldSendNewTcToken } from '../../Utils/tc-token-utils'
|
import {
|
||||||
|
buildMergedTcTokenIndexWrite,
|
||||||
|
buildTcTokenFromJid,
|
||||||
|
isRegularUser,
|
||||||
|
isTcTokenExpired,
|
||||||
|
readTcTokenIndex,
|
||||||
|
resolveIssuanceJid,
|
||||||
|
shouldSendNewTcToken,
|
||||||
|
storeTcTokensFromIqResult,
|
||||||
|
TC_TOKEN_INDEX_KEY
|
||||||
|
} from '../../Utils/tc-token-utils'
|
||||||
import type { BinaryNode } from '../../WABinary'
|
import type { BinaryNode } from '../../WABinary'
|
||||||
|
|
||||||
/** 7 days in seconds — matches WA Web tctoken_duration */
|
/** 7 days in seconds — matches WA Web tctoken_duration */
|
||||||
@@ -848,3 +858,340 @@ describe('tctoken integration scenarios', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ─── isRegularUser (PSA / bot / MetaAI gating) ─────────────────────────
|
||||||
|
|
||||||
|
describe('isRegularUser', () => {
|
||||||
|
it('rejects undefined / empty', () => {
|
||||||
|
expect(isRegularUser(undefined)).toBe(false)
|
||||||
|
expect(isRegularUser('')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects PSA WID (user "0")', () => {
|
||||||
|
expect(isRegularUser('0@s.whatsapp.net')).toBe(false)
|
||||||
|
expect(isRegularUser('0@c.us')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects bot phone numbers (1313555XXXX, 131655500XX)', () => {
|
||||||
|
expect(isRegularUser('13135550000@s.whatsapp.net')).toBe(false)
|
||||||
|
expect(isRegularUser('13135559999@s.whatsapp.net')).toBe(false)
|
||||||
|
// /^131655500\d{2}$/ — 11 digits: 131655500 + 2 trailing
|
||||||
|
expect(isRegularUser('13165550000@s.whatsapp.net')).toBe(false)
|
||||||
|
expect(isRegularUser('13165550099@s.whatsapp.net')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects MetaAI (@bot server)', () => {
|
||||||
|
expect(isRegularUser('foo@bot')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts regular PN users (@s.whatsapp.net, @c.us)', () => {
|
||||||
|
expect(isRegularUser('5511999999999@s.whatsapp.net')).toBe(true)
|
||||||
|
expect(isRegularUser('5511999999999@c.us')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts LID users', () => {
|
||||||
|
expect(isRegularUser('123456@lid')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts hosted PN/LID users', () => {
|
||||||
|
expect(isRegularUser('5511999999999@hosted')).toBe(true)
|
||||||
|
expect(isRegularUser('123456@hosted.lid')).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── resolveIssuanceJid (AB prop 14303 routing) ────────────────────────
|
||||||
|
|
||||||
|
describe('resolveIssuanceJid', () => {
|
||||||
|
const PN = '5511999999999@s.whatsapp.net'
|
||||||
|
const LID = '123456@lid'
|
||||||
|
const PN_NO_LID = '5511888888888@s.whatsapp.net'
|
||||||
|
const LID_NO_PN = '999999@lid'
|
||||||
|
|
||||||
|
const getLIDForPN = jest.fn<(pn: string) => Promise<string | null>>(async (pn: string) => {
|
||||||
|
if (pn === PN) return LID
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
const getPNForLID = jest.fn<(lid: string) => Promise<string | null>>(async (lid: string) => {
|
||||||
|
if (lid === LID) return PN
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
getLIDForPN.mockClear()
|
||||||
|
getPNForLID.mockClear()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('AB prop 14303 ON (issueToLid=true)', () => {
|
||||||
|
it('returns LID unchanged when input is LID', async () => {
|
||||||
|
expect(await resolveIssuanceJid(LID, true, getLIDForPN, getPNForLID)).toBe(LID)
|
||||||
|
expect(getLIDForPN).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resolves PN to LID via lidMapping', async () => {
|
||||||
|
expect(await resolveIssuanceJid(PN, true, getLIDForPN, getPNForLID)).toBe(LID)
|
||||||
|
expect(getLIDForPN).toHaveBeenCalledWith(PN)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to original PN when no LID mapping exists', async () => {
|
||||||
|
expect(await resolveIssuanceJid(PN_NO_LID, true, getLIDForPN, getPNForLID)).toBe(PN_NO_LID)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('AB prop 14303 OFF (issueToLid=false)', () => {
|
||||||
|
it('returns PN unchanged when input is PN', async () => {
|
||||||
|
expect(await resolveIssuanceJid(PN, false, getLIDForPN, getPNForLID)).toBe(PN)
|
||||||
|
expect(getPNForLID).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resolves LID to PN via lidMapping', async () => {
|
||||||
|
expect(await resolveIssuanceJid(LID, false, getLIDForPN, getPNForLID)).toBe(PN)
|
||||||
|
expect(getPNForLID).toHaveBeenCalledWith(LID)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to original LID when no PN mapping exists', async () => {
|
||||||
|
expect(await resolveIssuanceJid(LID_NO_PN, false, getLIDForPN, getPNForLID)).toBe(LID_NO_PN)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns LID unchanged when getPNForLID is omitted', async () => {
|
||||||
|
expect(await resolveIssuanceJid(LID, false, getLIDForPN)).toBe(LID)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('JID normalization (handles @c.us and hosted forms)', () => {
|
||||||
|
const PN_CUS = '5511999999999@c.us'
|
||||||
|
const PN_NORMALIZED = '5511999999999@s.whatsapp.net'
|
||||||
|
const HOSTED_LID = '999999@hosted.lid'
|
||||||
|
|
||||||
|
it('normalizes @c.us before resolving (issueToLid=true)', async () => {
|
||||||
|
const fn = jest.fn<(pn: string) => Promise<string | null>>(async (pn: string) => {
|
||||||
|
if (pn === PN_NORMALIZED) return LID
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
const result = await resolveIssuanceJid(PN_CUS, true, fn, getPNForLID)
|
||||||
|
expect(result).toBe(LID)
|
||||||
|
// Mapping store called with NORMALIZED form
|
||||||
|
expect(fn).toHaveBeenCalledWith(PN_NORMALIZED)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats hosted LID as LID input (issueToLid=true returns it unchanged)', async () => {
|
||||||
|
expect(await resolveIssuanceJid(HOSTED_LID, true, getLIDForPN, getPNForLID)).toBe(HOSTED_LID)
|
||||||
|
expect(getLIDForPN).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats hosted LID as LID input (issueToLid=false converts via getPNForLID)', async () => {
|
||||||
|
const fn = jest.fn<(lid: string) => Promise<string | null>>(async () => null)
|
||||||
|
await resolveIssuanceJid(HOSTED_LID, false, getLIDForPN, fn)
|
||||||
|
expect(fn).toHaveBeenCalledWith(HOSTED_LID)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── readTcTokenIndex / buildMergedTcTokenIndexWrite ───────────────────
|
||||||
|
|
||||||
|
describe('tctoken cross-session prune index', () => {
|
||||||
|
it('exports the sentinel key as "__index"', () => {
|
||||||
|
// Persisted state compatibility — tests freeze the value to catch unintended renames.
|
||||||
|
expect(TC_TOKEN_INDEX_KEY).toBe('__index')
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('readTcTokenIndex', () => {
|
||||||
|
it('returns [] when the index entry is absent', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
expect(await readTcTokenIndex(keys)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns [] when the index token buffer is empty', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({ [TC_TOKEN_INDEX_KEY]: { token: Buffer.alloc(0) } })
|
||||||
|
expect(await readTcTokenIndex(keys)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns [] when the JSON payload is corrupted', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({ [TC_TOKEN_INDEX_KEY]: { token: Buffer.from('not-json') } })
|
||||||
|
expect(await readTcTokenIndex(keys)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns [] when the JSON payload is not an array', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({ [TC_TOKEN_INDEX_KEY]: { token: Buffer.from('{"a":1}') } })
|
||||||
|
expect(await readTcTokenIndex(keys)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns the persisted JIDs', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
const stored = ['a@lid', 'b@lid', 'c@s.whatsapp.net']
|
||||||
|
;(keys.get as any).mockResolvedValue({
|
||||||
|
[TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify(stored)) }
|
||||||
|
})
|
||||||
|
expect(await readTcTokenIndex(keys)).toEqual(stored)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('filters out the sentinel key itself, empty strings, and non-strings', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
const stored = ['a@lid', '', TC_TOKEN_INDEX_KEY, 42, null, 'b@lid']
|
||||||
|
;(keys.get as any).mockResolvedValue({
|
||||||
|
[TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify(stored)) }
|
||||||
|
})
|
||||||
|
expect(await readTcTokenIndex(keys)).toEqual(['a@lid', 'b@lid'])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('buildMergedTcTokenIndexWrite', () => {
|
||||||
|
it('merges added JIDs with the persisted set (de-duplicated)', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({
|
||||||
|
[TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify(['a@lid', 'b@lid'])) }
|
||||||
|
})
|
||||||
|
const write = await buildMergedTcTokenIndexWrite(keys, ['b@lid', 'c@lid'])
|
||||||
|
const decoded = JSON.parse(write[TC_TOKEN_INDEX_KEY].token.toString()) as string[]
|
||||||
|
expect(decoded.sort()).toEqual(['a@lid', 'b@lid', 'c@lid'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops the sentinel key from the added set', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
const write = await buildMergedTcTokenIndexWrite(keys, [TC_TOKEN_INDEX_KEY, 'a@lid'])
|
||||||
|
const decoded = JSON.parse(write[TC_TOKEN_INDEX_KEY].token.toString()) as string[]
|
||||||
|
expect(decoded).toEqual(['a@lid'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handles empty inputs', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
const write = await buildMergedTcTokenIndexWrite(keys, [])
|
||||||
|
const decoded = JSON.parse(write[TC_TOKEN_INDEX_KEY].token.toString()) as string[]
|
||||||
|
expect(decoded).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── storeTcTokensFromIqResult — isRegularUser gating + monotonicity ───
|
||||||
|
|
||||||
|
describe('storeTcTokensFromIqResult — gating and monotonicity', () => {
|
||||||
|
const PEER_PN = '5511999999999@s.whatsapp.net'
|
||||||
|
const PEER_LID = '123456@lid'
|
||||||
|
|
||||||
|
const getLIDForPN = jest.fn<(pn: string) => Promise<string | null>>(async (pn: string) => {
|
||||||
|
if (pn === PEER_PN) return PEER_LID
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
getLIDForPN.mockClear()
|
||||||
|
})
|
||||||
|
|
||||||
|
const buildIqResult = (jid: string, tokenBytes: Uint8Array, t: string): BinaryNode => ({
|
||||||
|
tag: 'iq',
|
||||||
|
attrs: {},
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
tag: 'tokens',
|
||||||
|
attrs: {},
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
tag: 'token',
|
||||||
|
attrs: { jid, type: 'trusted_contact', t },
|
||||||
|
content: tokenBytes
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips PSA WID (jid="0") even if returned in tokens block', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: buildIqResult('myDeviceJid@s.whatsapp.net', Buffer.from([0x01, 0x02]), '1700000000'),
|
||||||
|
fallbackJid: '0@s.whatsapp.net',
|
||||||
|
keys,
|
||||||
|
getLIDForPN
|
||||||
|
})
|
||||||
|
expect(keys.set).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips bot phone numbers', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: buildIqResult('myDeviceJid@s.whatsapp.net', Buffer.from([0x01, 0x02]), '1700000000'),
|
||||||
|
fallbackJid: '13135550000@s.whatsapp.net',
|
||||||
|
keys,
|
||||||
|
getLIDForPN
|
||||||
|
})
|
||||||
|
expect(keys.set).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips MetaAI (@bot server)', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: buildIqResult('myDeviceJid@s.whatsapp.net', Buffer.from([0x01, 0x02]), '1700000000'),
|
||||||
|
fallbackJid: 'meta-ai@bot',
|
||||||
|
keys,
|
||||||
|
getLIDForPN
|
||||||
|
})
|
||||||
|
expect(keys.set).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses fallbackJid (NOT the token node jid which is own device) as storage source', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
const onNewJidStored = jest.fn()
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: buildIqResult('myDeviceJid:1@s.whatsapp.net', Buffer.from([0xaa, 0xbb]), '1700000000'),
|
||||||
|
fallbackJid: PEER_PN,
|
||||||
|
keys,
|
||||||
|
getLIDForPN,
|
||||||
|
onNewJidStored
|
||||||
|
})
|
||||||
|
expect(keys.set).toHaveBeenCalled()
|
||||||
|
const setArgs = (keys.set.mock.calls[0]?.[0] as { tctoken: Record<string, unknown> }).tctoken
|
||||||
|
expect(Object.keys(setArgs)).toContain(PEER_LID)
|
||||||
|
expect(onNewJidStored).toHaveBeenCalledWith(PEER_LID)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips when incoming timestamp is older than existing (monotonicity)', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({
|
||||||
|
[PEER_LID]: { token: Buffer.from([0x99]), timestamp: '1800000000' }
|
||||||
|
})
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: buildIqResult('myDeviceJid@s.whatsapp.net', Buffer.from([0xaa]), '1700000000'),
|
||||||
|
fallbackJid: PEER_PN,
|
||||||
|
keys,
|
||||||
|
getLIDForPN
|
||||||
|
})
|
||||||
|
expect(keys.set).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips timestamp-less tokens (would be immediately expired)', async () => {
|
||||||
|
const keys = createMockKeys()
|
||||||
|
;(keys.get as any).mockResolvedValue({})
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: {
|
||||||
|
tag: 'iq',
|
||||||
|
attrs: {},
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
tag: 'tokens',
|
||||||
|
attrs: {},
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
tag: 'token',
|
||||||
|
attrs: { jid: 'd@s.whatsapp.net', type: 'trusted_contact' },
|
||||||
|
content: Buffer.from([0x01])
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
fallbackJid: PEER_PN,
|
||||||
|
keys,
|
||||||
|
getLIDForPN
|
||||||
|
})
|
||||||
|
expect(keys.set).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -29,8 +29,7 @@ const TimeMs = {
|
|||||||
jest.mock('../../Utils/prometheus-metrics.js', () => ({
|
jest.mock('../../Utils/prometheus-metrics.js', () => ({
|
||||||
metrics: {
|
metrics: {
|
||||||
socketEvents: { inc: jest.fn() },
|
socketEvents: { inc: jest.fn() },
|
||||||
errors: { inc: jest.fn() },
|
errors: { inc: jest.fn() }
|
||||||
circuitBreakerTrips: { inc: jest.fn() }
|
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
|
||||||
@@ -59,7 +58,6 @@ describe('UnifiedSessionManager', () => {
|
|||||||
manager = createUnifiedSessionManager({
|
manager = createUnifiedSessionManager({
|
||||||
enabled: true,
|
enabled: true,
|
||||||
logger: mockLogger as any,
|
logger: mockLogger as any,
|
||||||
enableCircuitBreaker: false, // Disable for simpler testing
|
|
||||||
sendNode: mockSendNode
|
sendNode: mockSendNode
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -356,7 +354,11 @@ describe('shouldEnableUnifiedSession', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('UnifiedSessionManager with CircuitBreaker', () => {
|
describe('UnifiedSessionManager — non-critical send semantics', () => {
|
||||||
|
// The previous "with CircuitBreaker" suite is gone — telemetry no longer
|
||||||
|
// uses a circuit breaker. Verify equivalent behavior still holds:
|
||||||
|
// failures are swallowed (telemetry is non-critical) and don't propagate.
|
||||||
|
|
||||||
let manager: UnifiedSessionManager
|
let manager: UnifiedSessionManager
|
||||||
let mockSendNode: MockSendNode
|
let mockSendNode: MockSendNode
|
||||||
|
|
||||||
@@ -366,7 +368,6 @@ describe('UnifiedSessionManager with CircuitBreaker', () => {
|
|||||||
manager = createUnifiedSessionManager({
|
manager = createUnifiedSessionManager({
|
||||||
enabled: true,
|
enabled: true,
|
||||||
logger: createMockLogger() as any,
|
logger: createMockLogger() as any,
|
||||||
enableCircuitBreaker: true,
|
|
||||||
sendNode: mockSendNode
|
sendNode: mockSendNode
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -375,24 +376,13 @@ describe('UnifiedSessionManager with CircuitBreaker', () => {
|
|||||||
manager.destroy()
|
manager.destroy()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should work with circuit breaker enabled', async () => {
|
it('should send telemetry once per call', async () => {
|
||||||
await manager.send('login')
|
await manager.send('login')
|
||||||
expect(mockSendNode).toHaveBeenCalledTimes(1)
|
expect(mockSendNode).toHaveBeenCalledTimes(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should handle circuit breaker failures gracefully', async () => {
|
it('should swallow send failures gracefully (telemetry is non-critical)', async () => {
|
||||||
// Make send fail multiple times to trigger circuit breaker
|
mockSendNode.mockRejectedValueOnce(new Error('boom'))
|
||||||
let callCount = 0
|
|
||||||
mockSendNode.mockImplementation(async () => {
|
|
||||||
callCount++
|
|
||||||
if (callCount <= 3) {
|
|
||||||
throw new Error(`Fail ${callCount}`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// These should not throw even with failures
|
|
||||||
await expect(manager.send('login')).resolves.toBeUndefined()
|
|
||||||
await expect(manager.send('login')).resolves.toBeUndefined()
|
|
||||||
await expect(manager.send('login')).resolves.toBeUndefined()
|
await expect(manager.send('login')).resolves.toBeUndefined()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,209 @@
|
|||||||
|
import Long from 'long'
|
||||||
|
import $protobuf from 'protobufjs/minimal.js'
|
||||||
|
|
||||||
|
const $util = $protobuf.util
|
||||||
|
|
||||||
|
// proto implementation
|
||||||
|
function longToStringOld(value: any, unsigned?: boolean): string {
|
||||||
|
if (typeof value === 'string') return value
|
||||||
|
if (typeof value === 'number') return String(value)
|
||||||
|
if (!$util.Long) return String(value)
|
||||||
|
const normalized = ($util.Long as any).fromValue(value)
|
||||||
|
const prepared =
|
||||||
|
unsigned && normalized && typeof normalized.toUnsigned === 'function' ? normalized.toUnsigned() : normalized
|
||||||
|
return prepared.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
// bigint implementation
|
||||||
|
function longToStringNew(value: any, unsigned?: boolean): string {
|
||||||
|
if (typeof value === 'string') return value
|
||||||
|
if (typeof value === 'number') return String(value)
|
||||||
|
if (value && typeof value.low === 'number' && typeof value.high === 'number') {
|
||||||
|
const high = value.high | 0
|
||||||
|
const lo = BigInt(value.low >>> 0)
|
||||||
|
const hi = BigInt(value.high >>> 0)
|
||||||
|
const combined = (hi << 32n) | lo
|
||||||
|
if (!unsigned && high < 0) {
|
||||||
|
return (combined - (1n << 64n)).toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
return combined.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
return String(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function longToNumberOld(value: any, unsigned?: boolean): number {
|
||||||
|
if (typeof value === 'number') return value
|
||||||
|
if (typeof value === 'string') return Number(value)
|
||||||
|
if (!$util.Long) return Number(value)
|
||||||
|
const normalized = ($util.Long as any).fromValue(value)
|
||||||
|
const prepared =
|
||||||
|
unsigned && normalized && typeof normalized.toUnsigned === 'function'
|
||||||
|
? normalized.toUnsigned()
|
||||||
|
: typeof normalized.toSigned === 'function'
|
||||||
|
? normalized.toSigned()
|
||||||
|
: normalized
|
||||||
|
return prepared.toNumber()
|
||||||
|
}
|
||||||
|
|
||||||
|
function longToNumberNew(value: any, unsigned?: boolean): number {
|
||||||
|
if (typeof value === 'number') return value
|
||||||
|
if (typeof value === 'string') return Number(value)
|
||||||
|
if (value && typeof value.low === 'number' && typeof value.high === 'number') {
|
||||||
|
const high = value.high | 0
|
||||||
|
const lo = BigInt(value.low >>> 0)
|
||||||
|
const hi = BigInt(value.high >>> 0)
|
||||||
|
const combined = (hi << 32n) | lo
|
||||||
|
if (!unsigned && high < 0) {
|
||||||
|
return Number(combined - (1n << 64n))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Number(combined)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Number(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('BigInt vs Long equivalence validation', () => {
|
||||||
|
// Test cases: [description, Long value, unsigned flag]
|
||||||
|
const testCases: [string, Long, boolean][] = [
|
||||||
|
// Basic values
|
||||||
|
['zero unsigned', Long.fromNumber(0, true), true],
|
||||||
|
['zero signed', Long.fromNumber(0, false), false],
|
||||||
|
['one unsigned', Long.fromNumber(1, true), true],
|
||||||
|
['one signed', Long.fromNumber(1, false), false],
|
||||||
|
|
||||||
|
// Typical WhatsApp timestamps (seconds since epoch)
|
||||||
|
['timestamp 2023', Long.fromNumber(1700000000, true), true],
|
||||||
|
['timestamp 2025', Long.fromNumber(1750000000, true), true],
|
||||||
|
['timestamp as signed', Long.fromNumber(1700000000, false), false],
|
||||||
|
|
||||||
|
// File sizes
|
||||||
|
['small file', Long.fromNumber(1024, true), true],
|
||||||
|
['medium file 10MB', Long.fromNumber(10485760, true), true],
|
||||||
|
['large file 2GB', Long.fromNumber(2147483648, true), true],
|
||||||
|
|
||||||
|
// Boundary values - 32-bit
|
||||||
|
['max int32', Long.fromNumber(2147483647, false), false],
|
||||||
|
['min int32', Long.fromNumber(-2147483648, false), false],
|
||||||
|
['max uint32', Long.fromNumber(4294967295, true), true],
|
||||||
|
|
||||||
|
// Around MAX_SAFE_INTEGER
|
||||||
|
['MAX_SAFE_INTEGER', Long.fromString('9007199254740991', false), false],
|
||||||
|
['MAX_SAFE_INTEGER + 1', Long.fromString('9007199254740992', false), false],
|
||||||
|
['MAX_SAFE_INTEGER unsigned', Long.fromString('9007199254740991', true), true],
|
||||||
|
|
||||||
|
// Large unsigned values
|
||||||
|
['large unsigned', Long.fromString('9999999999999999999', true), true],
|
||||||
|
['max uint64', Long.fromString('18446744073709551615', true), true],
|
||||||
|
['max uint64 - 1', Long.fromString('18446744073709551614', true), true],
|
||||||
|
|
||||||
|
// Signed negative values
|
||||||
|
['negative one', Long.fromNumber(-1, false), false],
|
||||||
|
['negative small', Long.fromNumber(-100, false), false],
|
||||||
|
['negative large', Long.fromNumber(-2147483648, false), false],
|
||||||
|
['min int64', Long.fromString('-9223372036854775808', false), false],
|
||||||
|
['max int64', Long.fromString('9223372036854775807', false), false],
|
||||||
|
['-1 as signed Long', Long.fromBits(-1, -1, false), false],
|
||||||
|
|
||||||
|
// Tricky bit patterns
|
||||||
|
['high=1, low=0', Long.fromBits(0, 1, true), true],
|
||||||
|
['high=0, low=-1 (0xFFFFFFFF)', Long.fromBits(-1, 0, true), true],
|
||||||
|
['high=-1, low=-1 unsigned (max uint64)', Long.fromBits(-1, -1, true), true],
|
||||||
|
['high=0x7FFFFFFF, low=0xFFFFFFFF (max int64)', Long.fromBits(-1, 0x7fffffff, false), false],
|
||||||
|
['high=0x80000000, low=0 (min int64)', Long.fromBits(0, -2147483648, false), false],
|
||||||
|
|
||||||
|
// Powers of 2
|
||||||
|
['2^32', Long.fromString('4294967296', true), true],
|
||||||
|
['2^32 signed', Long.fromString('4294967296', false), false],
|
||||||
|
['2^48', Long.fromString('281474976710656', true), true],
|
||||||
|
['2^63', Long.fromString('9223372036854775808', true), true]
|
||||||
|
]
|
||||||
|
|
||||||
|
describe('longToString equivalence', () => {
|
||||||
|
for (const [desc, longVal, unsigned] of testCases) {
|
||||||
|
it(`${desc}: Long(${longVal.low}, ${longVal.high}, ${unsigned})`, () => {
|
||||||
|
const oldResult = longToStringOld(longVal, unsigned)
|
||||||
|
const newResult = longToStringNew(longVal, unsigned)
|
||||||
|
expect(newResult).toBe(oldResult)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('longToNumber equivalence', () => {
|
||||||
|
for (const [desc, longVal, unsigned] of testCases) {
|
||||||
|
it(`${desc}: Long(${longVal.low}, ${longVal.high}, ${unsigned})`, () => {
|
||||||
|
const oldResult = longToNumberOld(longVal, unsigned)
|
||||||
|
const newResult = longToNumberNew(longVal, unsigned)
|
||||||
|
// For large values, both may lose precision equally (Number limitation)
|
||||||
|
// So we compare string representations
|
||||||
|
expect(newResult.toString()).toBe(oldResult.toString())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('non-Long inputs (fallback paths)', () => {
|
||||||
|
it('string passthrough', () => {
|
||||||
|
expect(longToStringNew('12345')).toBe('12345')
|
||||||
|
expect(longToStringNew('0')).toBe('0')
|
||||||
|
})
|
||||||
|
it('number passthrough', () => {
|
||||||
|
expect(longToStringNew(42)).toBe('42')
|
||||||
|
expect(longToStringNew(0)).toBe('0')
|
||||||
|
expect(longToStringNew(-1)).toBe('-1')
|
||||||
|
})
|
||||||
|
it('null/undefined fallback', () => {
|
||||||
|
expect(longToStringNew(null)).toBe('null')
|
||||||
|
expect(longToStringNew(undefined)).toBe('undefined')
|
||||||
|
})
|
||||||
|
it('object without low/high', () => {
|
||||||
|
expect(longToStringNew({ foo: 'bar' })).toBe('[object Object]')
|
||||||
|
})
|
||||||
|
|
||||||
|
// Defensive: a raw {low, high} JSON object can carry `high` as an
|
||||||
|
// unsigned 32-bit value (Long.fromBits would normalize via `| 0`,
|
||||||
|
// but plain JSON deserialization does not). Without `value.high | 0`
|
||||||
|
// the sign-bit check fails and the result is interpreted as unsigned.
|
||||||
|
// Upstream Baileys PR #2333 has this latent bug; InfiniteAPI fixes it.
|
||||||
|
it('signed sign-bit detection on raw unsigned high (-1 as {low: -1, high: 4294967295})', () => {
|
||||||
|
const raw = { low: -1, high: 0xffffffff }
|
||||||
|
// signed: -1
|
||||||
|
expect(longToStringNew(raw, false)).toBe('-1')
|
||||||
|
// unsigned: max uint64
|
||||||
|
expect(longToStringNew(raw, true)).toBe('18446744073709551615')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('signed sign-bit detection on raw unsigned high (-4294967296 as {low: 0, high: 4294967295})', () => {
|
||||||
|
const raw = { low: 0, high: 0xffffffff }
|
||||||
|
// signed: -4294967296 (high word = -1 after normalization)
|
||||||
|
expect(longToStringNew(raw, false)).toBe('-4294967296')
|
||||||
|
// unsigned: 0xFFFFFFFF00000000 = 18446744069414584320
|
||||||
|
expect(longToStringNew(raw, true)).toBe('18446744069414584320')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('fuzz: random Long values', () => {
|
||||||
|
it('100 random unsigned values match', () => {
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const low = (Math.random() * 0xffffffff) | 0
|
||||||
|
const high = (Math.random() * 0xffffffff) | 0
|
||||||
|
const longVal = Long.fromBits(low, high, true)
|
||||||
|
const oldResult = longToStringOld(longVal, true)
|
||||||
|
const newResult = longToStringNew(longVal, true)
|
||||||
|
expect(newResult).toBe(oldResult)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('100 random signed values match', () => {
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const low = (Math.random() * 0xffffffff) | 0
|
||||||
|
const high = (Math.random() * 0xffffffff) | 0
|
||||||
|
const longVal = Long.fromBits(low, high, false)
|
||||||
|
const oldResult = longToStringOld(longVal, false)
|
||||||
|
const newResult = longToStringNew(longVal, false)
|
||||||
|
expect(newResult).toBe(oldResult)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import { jest } from '@jest/globals'
|
||||||
|
import { proto, type WAMessage } from '../..'
|
||||||
|
import { DEFAULT_CONNECTION_CONFIG } from '../../Defaults'
|
||||||
|
import makeWASocket from '../../Socket'
|
||||||
|
import { makeSession, mockWebSocket } from '../TestUtils/session'
|
||||||
|
|
||||||
|
mockWebSocket()
|
||||||
|
|
||||||
|
// chats.ts treats a connection as a reconnection when EITHER signal is true:
|
||||||
|
// 1. authState.creds.accountSyncCounter > 0
|
||||||
|
// (at least one full history sync completed in a previous session)
|
||||||
|
// 2. socketSkippedOfflineBuffer (forwarded from socket.ts as `skipOfflineBuffer`)
|
||||||
|
// (socket.ts already decided to skip the offline buffer, e.g. because
|
||||||
|
// routingInfo was stale and was discarded on startup)
|
||||||
|
// On reconnection, AwaitingInitialSync is skipped and the buffer is flushed
|
||||||
|
// immediately so live messages are not held in the initial-sync window.
|
||||||
|
describe('Reconnection Sync Skip', () => {
|
||||||
|
it('should skip the history sync wait on reconnection (accountSyncCounter > 0)', async () => {
|
||||||
|
const { state, clear } = await makeSession()
|
||||||
|
|
||||||
|
state.creds.me = { id: '1234567890:1@s.whatsapp.net', name: 'Test User' }
|
||||||
|
// Simulate a session that has already synced before
|
||||||
|
state.creds.accountSyncCounter = 1
|
||||||
|
|
||||||
|
const sock = makeWASocket({
|
||||||
|
...DEFAULT_CONNECTION_CONFIG,
|
||||||
|
auth: state
|
||||||
|
})
|
||||||
|
|
||||||
|
const messageListener = jest.fn()
|
||||||
|
sock.ev.on('messages.upsert', messageListener)
|
||||||
|
|
||||||
|
// Simulate receiving pending notifications (triggers AwaitingInitialSync)
|
||||||
|
sock.ev.emit('connection.update', { receivedPendingNotifications: true })
|
||||||
|
|
||||||
|
// Emit a message immediately after — if the wait is skipped,
|
||||||
|
// the buffer should already be flushed and this message should be delivered.
|
||||||
|
const msg = proto.WebMessageInfo.fromObject({
|
||||||
|
key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'MSG_AFTER_RECONNECT' },
|
||||||
|
messageTimestamp: Date.now() / 1000,
|
||||||
|
message: { conversation: 'Hello after reconnect' }
|
||||||
|
}) as WAMessage
|
||||||
|
sock.ev.emit('messages.upsert', { messages: [msg], type: 'notify' })
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50))
|
||||||
|
|
||||||
|
// Message should be delivered immediately, NOT buffered
|
||||||
|
expect(messageListener).toHaveBeenCalledTimes(1)
|
||||||
|
expect(messageListener).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
messages: expect.arrayContaining([expect.objectContaining({ key: msg.key })]),
|
||||||
|
type: 'notify'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
await sock.end(new Error('Test completed'))
|
||||||
|
await clear()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should skip the history sync wait when socketSkippedOfflineBuffer is true (stale routingInfo, accountSyncCounter === 0)', async () => {
|
||||||
|
const { state, clear } = await makeSession()
|
||||||
|
|
||||||
|
state.creds.me = { id: '1234567890:1@s.whatsapp.net', name: 'Test User' }
|
||||||
|
// Fresh-looking session from the counter perspective
|
||||||
|
state.creds.accountSyncCounter = 0
|
||||||
|
// But routingInfo is present and we ask the socket to discard it on start.
|
||||||
|
// socket.ts will set hadStaleRoutingInfo=true → skipOfflineBuffer=true,
|
||||||
|
// which chats.ts forwards as socketSkippedOfflineBuffer. Without this
|
||||||
|
// branch, the buffers would be misaligned (offline buffer skipped while
|
||||||
|
// AwaitingInitialSync still waits) and live messages would stall.
|
||||||
|
state.creds.routingInfo = Buffer.from([1, 2, 3, 4])
|
||||||
|
|
||||||
|
const sock = makeWASocket({
|
||||||
|
...DEFAULT_CONNECTION_CONFIG,
|
||||||
|
auth: state,
|
||||||
|
clearRoutingInfoOnStart: true
|
||||||
|
})
|
||||||
|
|
||||||
|
const messageListener = jest.fn()
|
||||||
|
sock.ev.on('messages.upsert', messageListener)
|
||||||
|
|
||||||
|
sock.ev.emit('connection.update', { receivedPendingNotifications: true })
|
||||||
|
|
||||||
|
const msg = proto.WebMessageInfo.fromObject({
|
||||||
|
key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'MSG_AFTER_STALE_ROUTING' },
|
||||||
|
messageTimestamp: Date.now() / 1000,
|
||||||
|
message: { conversation: 'Hello after stale routing reconnect' }
|
||||||
|
}) as WAMessage
|
||||||
|
sock.ev.emit('messages.upsert', { messages: [msg], type: 'notify' })
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50))
|
||||||
|
|
||||||
|
expect(messageListener).toHaveBeenCalledTimes(1)
|
||||||
|
expect(messageListener).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
messages: expect.arrayContaining([expect.objectContaining({ key: msg.key })]),
|
||||||
|
type: 'notify'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
await sock.end(new Error('Test completed'))
|
||||||
|
await clear()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should still wait for history sync on fresh pairing (both signals false)', async () => {
|
||||||
|
const { state, clear } = await makeSession()
|
||||||
|
|
||||||
|
state.creds.me = { id: '1234567890:1@s.whatsapp.net', name: 'Test User' }
|
||||||
|
// Fresh pairing — both reconnect signals are false:
|
||||||
|
// accountSyncCounter is 0 (default) and no stale routingInfo to clear.
|
||||||
|
state.creds.accountSyncCounter = 0
|
||||||
|
|
||||||
|
const sock = makeWASocket({
|
||||||
|
...DEFAULT_CONNECTION_CONFIG,
|
||||||
|
auth: state
|
||||||
|
})
|
||||||
|
|
||||||
|
const messageListener = jest.fn()
|
||||||
|
sock.ev.on('messages.upsert', messageListener)
|
||||||
|
|
||||||
|
sock.ev.emit('connection.update', { receivedPendingNotifications: true })
|
||||||
|
|
||||||
|
const msg = proto.WebMessageInfo.fromObject({
|
||||||
|
key: { remoteJid: '1234567890@s.whatsapp.net', fromMe: false, id: 'MSG_DURING_INITIAL_SYNC' },
|
||||||
|
messageTimestamp: Date.now() / 1000,
|
||||||
|
message: { conversation: 'Hello during initial sync' }
|
||||||
|
}) as WAMessage
|
||||||
|
sock.ev.emit('messages.upsert', { messages: [msg], type: 'notify' })
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50))
|
||||||
|
|
||||||
|
// Message should be BUFFERED (not delivered) because we're waiting for history sync
|
||||||
|
expect(messageListener).toHaveBeenCalledTimes(0)
|
||||||
|
|
||||||
|
// Drain the 2s AwaitingInitialSync timeout (chats.ts:1522) so its callback
|
||||||
|
// doesn't fire after Jest considers the test done — otherwise we get a
|
||||||
|
// "Cannot log after tests are done" warning from the post-teardown flush
|
||||||
|
// and the suite is flagged with --detectOpenHandles. After the timer
|
||||||
|
// fires, syncState becomes Online and the buffer flushes; that delivery
|
||||||
|
// is post-assertion and irrelevant to the test goal.
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 2_100))
|
||||||
|
|
||||||
|
await sock.end(new Error('Test completed'))
|
||||||
|
await clear()
|
||||||
|
}, 10_000)
|
||||||
|
})
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import Long from 'long'
|
||||||
import '../index.js'
|
import '../index.js'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
|
|
||||||
@@ -28,4 +29,91 @@ describe('proto serialization', () => {
|
|||||||
const json = message.toJSON()
|
const json = message.toJSON()
|
||||||
expect(json.message?.imageMessage?.fileLength).toBe('1234567890123456789')
|
expect(json.message?.imageMessage?.fileLength).toBe('1234567890123456789')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('converts Long objects to strings correctly via BigInt fast path', () => {
|
||||||
|
const message = proto.WebMessageInfo.fromObject({
|
||||||
|
key: {
|
||||||
|
remoteJid: '123@s.whatsapp.net',
|
||||||
|
id: 'ABC123',
|
||||||
|
fromMe: false
|
||||||
|
},
|
||||||
|
messageTimestamp: Long.fromNumber(1700000000, true),
|
||||||
|
message: {
|
||||||
|
imageMessage: {
|
||||||
|
fileLength: Long.fromString('9876543210', true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const json = message.toJSON()
|
||||||
|
expect(json.messageTimestamp).toBe('1700000000')
|
||||||
|
expect(json.message?.imageMessage?.fileLength).toBe('9876543210')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handles large unsigned Long values (> MAX_SAFE_INTEGER)', () => {
|
||||||
|
const message = proto.WebMessageInfo.fromObject({
|
||||||
|
key: {
|
||||||
|
remoteJid: '123@s.whatsapp.net',
|
||||||
|
id: 'ABC123',
|
||||||
|
fromMe: false
|
||||||
|
},
|
||||||
|
messageTimestamp: Long.fromString('18446744073709551615', true), // max uint64
|
||||||
|
message: {
|
||||||
|
imageMessage: {
|
||||||
|
fileLength: Long.fromString('9999999999999999999', true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const json = message.toJSON()
|
||||||
|
expect(json.messageTimestamp).toBe('18446744073709551615')
|
||||||
|
expect(json.message?.imageMessage?.fileLength).toBe('9999999999999999999')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handles zero and small Long values', () => {
|
||||||
|
const message = proto.WebMessageInfo.fromObject({
|
||||||
|
key: {
|
||||||
|
remoteJid: '123@s.whatsapp.net',
|
||||||
|
id: 'ABC123',
|
||||||
|
fromMe: false
|
||||||
|
},
|
||||||
|
messageTimestamp: Long.fromNumber(0, true),
|
||||||
|
message: {
|
||||||
|
imageMessage: {
|
||||||
|
fileLength: Long.fromNumber(1, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const json = message.toJSON()
|
||||||
|
expect(json.messageTimestamp).toBe('0')
|
||||||
|
expect(json.message?.imageMessage?.fileLength).toBe('1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('roundtrips encode/decode with Long fields preserving values (> MAX_SAFE_INTEGER)', () => {
|
||||||
|
// Use uint64 values above Number.MAX_SAFE_INTEGER (2^53 - 1) so the
|
||||||
|
// roundtrip actually exercises the BigInt fast path on decode->toJSON.
|
||||||
|
// Safe integers would silently work even if longToString fell back to
|
||||||
|
// Number(value).
|
||||||
|
const original = proto.WebMessageInfo.fromObject({
|
||||||
|
key: {
|
||||||
|
remoteJid: '123@s.whatsapp.net',
|
||||||
|
id: 'ABC123',
|
||||||
|
fromMe: false
|
||||||
|
},
|
||||||
|
messageTimestamp: Long.fromString('18446744073709551615', true),
|
||||||
|
message: {
|
||||||
|
imageMessage: {
|
||||||
|
fileLength: Long.fromString('9999999999999999999', true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const encoded = proto.WebMessageInfo.encode(original).finish()
|
||||||
|
const decoded = proto.WebMessageInfo.decode(encoded)
|
||||||
|
const json = decoded.toJSON()
|
||||||
|
|
||||||
|
expect(json.messageTimestamp).toBe('18446744073709551615')
|
||||||
|
expect(json.message?.imageMessage?.fileLength).toBe('9999999999999999999')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+11
-2
@@ -28,7 +28,16 @@ console.info = function (...args: unknown[]) {
|
|||||||
|
|
||||||
// Track errors by type + JID to avoid duplicates (using Map for better performance)
|
// Track errors by type + JID to avoid duplicates (using Map for better performance)
|
||||||
const _errorTimestamps = new Map<string, number>()
|
const _errorTimestamps = new Map<string, number>()
|
||||||
const DEDUP_WINDOW_MS = 150
|
// Dedup window for repeated decrypt-error console lines (Bad MAC / Counter / etc).
|
||||||
|
// Was 150ms, but retry attempts of the SAME message are typically ~300-1000ms apart,
|
||||||
|
// so the second attempt fell outside the window and double-printed.
|
||||||
|
//
|
||||||
|
// TRADE-OFF: dedup key is `errorType + JID` (no message-id). With 5s, a burst of
|
||||||
|
// errors for the SAME JID — even of slightly different categories or different
|
||||||
|
// messages — collapses to one log line every 5s. This is intentional for a noisy
|
||||||
|
// production stream; if you need per-message visibility, set BAILEYS_LOG_LEVEL=debug
|
||||||
|
// to bypass this console-side dedup and see the structured pino logs in full.
|
||||||
|
const DEDUP_WINDOW_MS = 5000
|
||||||
|
|
||||||
console.error = function (...args: unknown[]) {
|
console.error = function (...args: unknown[]) {
|
||||||
if (args.length > 0 && typeof args[0] === 'string') {
|
if (args.length > 0 && typeof args[0] === 'string') {
|
||||||
@@ -70,7 +79,7 @@ console.error = function (...args: unknown[]) {
|
|||||||
const lastTime = _errorTimestamps.get(dedupeKey)
|
const lastTime = _errorTimestamps.get(dedupeKey)
|
||||||
|
|
||||||
if (lastTime && now - lastTime < DEDUP_WINDOW_MS) {
|
if (lastTime && now - lastTime < DEDUP_WINDOW_MS) {
|
||||||
return // Skip duplicate within 150ms window
|
return // Skip duplicate within DEDUP_WINDOW_MS window
|
||||||
}
|
}
|
||||||
|
|
||||||
_errorTimestamps.set(dedupeKey, now)
|
_errorTimestamps.set(dedupeKey, now)
|
||||||
|
|||||||
@@ -388,6 +388,13 @@ __metadata:
|
|||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
|
"@borewit/text-codec@npm:^0.2.2":
|
||||||
|
version: 0.2.2
|
||||||
|
resolution: "@borewit/text-codec@npm:0.2.2"
|
||||||
|
checksum: 10c0/2d3fb132bc6a132914a8fbf8e9ff2fa1ead210ecc395b28bb7355bd7719548a5e351ffe39f21c3bee8048f6cabd99eabd404bb5cc809cad9cba25abed19d271f
|
||||||
|
languageName: node
|
||||||
|
linkType: hard
|
||||||
|
|
||||||
"@cacheable/node-cache@npm:^2.0.1":
|
"@cacheable/node-cache@npm:^2.0.1":
|
||||||
version: 2.0.1
|
version: 2.0.1
|
||||||
resolution: "@cacheable/node-cache@npm:2.0.1"
|
resolution: "@cacheable/node-cache@npm:2.0.1"
|
||||||
@@ -3105,7 +3112,7 @@ __metadata:
|
|||||||
libsignal: "github:whiskeysockets/libsignal-node"
|
libsignal: "github:whiskeysockets/libsignal-node"
|
||||||
link-preview-js: "npm:^4.0.0"
|
link-preview-js: "npm:^4.0.0"
|
||||||
lru-cache: "npm:^11.2.6"
|
lru-cache: "npm:^11.2.6"
|
||||||
music-metadata: "npm:^11.12.0"
|
music-metadata: "npm:^11.12.3"
|
||||||
open: "npm:^11.0.0"
|
open: "npm:^11.0.0"
|
||||||
p-queue: "npm:^9.0.0"
|
p-queue: "npm:^9.0.0"
|
||||||
pino: "npm:^10.3.1"
|
pino: "npm:^10.3.1"
|
||||||
@@ -4556,15 +4563,15 @@ __metadata:
|
|||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
"file-type@npm:^21.3.0":
|
"file-type@npm:^21.3.1":
|
||||||
version: 21.3.0
|
version: 21.3.1
|
||||||
resolution: "file-type@npm:21.3.0"
|
resolution: "file-type@npm:21.3.1"
|
||||||
dependencies:
|
dependencies:
|
||||||
"@tokenizer/inflate": "npm:^0.4.1"
|
"@tokenizer/inflate": "npm:^0.4.1"
|
||||||
strtok3: "npm:^10.3.4"
|
strtok3: "npm:^10.3.4"
|
||||||
token-types: "npm:^6.1.1"
|
token-types: "npm:^6.1.1"
|
||||||
uint8array-extras: "npm:^1.4.0"
|
uint8array-extras: "npm:^1.4.0"
|
||||||
checksum: 10c0/1b1fa909e6063044a6da1d2ea348ee4d747ed9286382d3f0d4d6532c11fb2ea9f2e7e67b2bc7d745d1bc937e05dee1aa8cb912c64250933bcb393a3744f4e284
|
checksum: 10c0/66a8eda781c803c6fc372464abba88cee564cfe30f029716f06909da1564bc51d0a4e8d34654b881dc751cdb0513338b3c0747e06a608cee0dd5c5499b018d47
|
||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
@@ -6504,21 +6511,21 @@ __metadata:
|
|||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
"music-metadata@npm:^11.12.0":
|
"music-metadata@npm:^11.12.3":
|
||||||
version: 11.12.0
|
version: 11.12.3
|
||||||
resolution: "music-metadata@npm:11.12.0"
|
resolution: "music-metadata@npm:11.12.3"
|
||||||
dependencies:
|
dependencies:
|
||||||
"@borewit/text-codec": "npm:^0.2.1"
|
"@borewit/text-codec": "npm:^0.2.2"
|
||||||
"@tokenizer/token": "npm:^0.3.0"
|
"@tokenizer/token": "npm:^0.3.0"
|
||||||
content-type: "npm:^1.0.5"
|
content-type: "npm:^1.0.5"
|
||||||
debug: "npm:^4.4.3"
|
debug: "npm:^4.4.3"
|
||||||
file-type: "npm:^21.3.0"
|
file-type: "npm:^21.3.1"
|
||||||
media-typer: "npm:^1.1.0"
|
media-typer: "npm:^1.1.0"
|
||||||
strtok3: "npm:^10.3.4"
|
strtok3: "npm:^10.3.4"
|
||||||
token-types: "npm:^6.1.2"
|
token-types: "npm:^6.1.2"
|
||||||
uint8array-extras: "npm:^1.5.0"
|
uint8array-extras: "npm:^1.5.0"
|
||||||
win-guid: "npm:^0.2.1"
|
win-guid: "npm:^0.2.1"
|
||||||
checksum: 10c0/014a120b8941ab80452171def0ec3cba013041ba4b94f8061ad493a037d3423e6d316131a13fb0433404685ebd3c8e3ae2255c1bafaeb20673fcd73af2df0148
|
checksum: 10c0/57df905f51ec792e5b4c994645eab64d47d5608b9de11151f54b26fbd5f563598ec04d8aed7f244ef1479030d78ddab8af1ee84dfcee40a93b3241941b50999d
|
||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user