Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 45cbdc4233 |
+3
-106
@@ -1,7 +1,7 @@
|
|||||||
syntax = "proto3";
|
syntax = "proto3";
|
||||||
package proto;
|
package proto;
|
||||||
|
|
||||||
/// WhatsApp Version: 2.3000.1038164556
|
/// WhatsApp Version: 2.3000.1035216863
|
||||||
|
|
||||||
message ADVDeviceIdentity {
|
message ADVDeviceIdentity {
|
||||||
optional uint32 rawId = 1;
|
optional uint32 rawId = 1;
|
||||||
@@ -417,16 +417,9 @@ message BotCapabilityMetadata {
|
|||||||
JSON_PATCH_STREAMING = 58;
|
JSON_PATCH_STREAMING = 58;
|
||||||
AI_TAB_FORCE_CLIPPY = 59;
|
AI_TAB_FORCE_CLIPPY = 59;
|
||||||
UNIFIED_RESPONSE_EMBEDDED_SCREENS = 60;
|
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 {
|
||||||
@@ -658,7 +651,6 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -710,7 +702,6 @@ enum BotMetricsEntryPoint {
|
|||||||
WEB_NAVIGATION_BAR = 47;
|
WEB_NAVIGATION_BAR = 47;
|
||||||
GROUP_MEMBER = 54;
|
GROUP_MEMBER = 54;
|
||||||
CHATLIST_SEARCH = 55;
|
CHATLIST_SEARCH = 55;
|
||||||
NEW_CHAT_LIST = 56;
|
|
||||||
}
|
}
|
||||||
message BotMetricsMetadata {
|
message BotMetricsMetadata {
|
||||||
optional string destinationId = 1;
|
optional string destinationId = 1;
|
||||||
@@ -1475,10 +1466,6 @@ message ContextInfo {
|
|||||||
optional string wtwaWebsiteUrl = 26;
|
optional string wtwaWebsiteUrl = 26;
|
||||||
optional string adPreviewUrl = 27;
|
optional string adPreviewUrl = 27;
|
||||||
optional bool containsCtwaFlowsAutoReply = 28;
|
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;
|
||||||
@@ -1664,7 +1651,6 @@ message DeviceCapabilities {
|
|||||||
optional bool companionSupportEnabled = 2;
|
optional bool companionSupportEnabled = 2;
|
||||||
optional bool campaignSyncEnabled = 3;
|
optional bool campaignSyncEnabled = 3;
|
||||||
optional bool insightsSyncEnabled = 4;
|
optional bool insightsSyncEnabled = 4;
|
||||||
optional int32 recipientLimit = 5;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum ChatLockSupportLevel {
|
enum ChatLockSupportLevel {
|
||||||
@@ -1740,8 +1726,6 @@ message DeviceProps {
|
|||||||
optional uint32 initialSyncMaxMessagesPerChat = 20;
|
optional uint32 initialSyncMaxMessagesPerChat = 20;
|
||||||
optional bool supportManusHistory = 21;
|
optional bool supportManusHistory = 21;
|
||||||
optional bool supportHatchHistory = 22;
|
optional bool supportHatchHistory = 22;
|
||||||
repeated string supportedBotChannelFbids = 23;
|
|
||||||
optional bool supportInlineContacts = 24;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum PlatformType {
|
enum PlatformType {
|
||||||
@@ -1928,16 +1912,6 @@ 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;
|
||||||
@@ -1959,28 +1933,14 @@ message HandshakeMessage {
|
|||||||
optional bytes paddedBytes = 6;
|
optional bytes paddedBytes = 6;
|
||||||
optional bool sendServerHelloPaddedBytes = 7;
|
optional bool sendServerHelloPaddedBytes = 7;
|
||||||
optional bool simulateXxkemFs = 8;
|
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 paddingBytes = 5;
|
||||||
optional bytes extendedCiphertext = 6;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -2004,8 +1964,6 @@ 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;
|
||||||
@@ -2100,14 +2058,6 @@ 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;
|
||||||
@@ -2186,6 +2136,7 @@ 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2347,7 +2298,6 @@ message Message {
|
|||||||
optional ConditionalRevealMessage conditionalRevealMessage = 120;
|
optional ConditionalRevealMessage conditionalRevealMessage = 120;
|
||||||
optional PollAddOptionMessage pollAddOptionMessage = 121;
|
optional PollAddOptionMessage pollAddOptionMessage = 121;
|
||||||
optional EventInviteMessage eventInviteMessage = 122;
|
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;
|
||||||
@@ -2539,7 +2489,6 @@ 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;
|
||||||
@@ -3321,7 +3270,6 @@ 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 {
|
||||||
@@ -3408,7 +3356,6 @@ 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;
|
||||||
@@ -3657,6 +3604,7 @@ message Message {
|
|||||||
GROUP_MEMBER_LABEL_CHANGE = 30;
|
GROUP_MEMBER_LABEL_CHANGE = 30;
|
||||||
AI_MEDIA_COLLECTION_MESSAGE = 31;
|
AI_MEDIA_COLLECTION_MESSAGE = 31;
|
||||||
MESSAGE_UNSCHEDULE = 32;
|
MESSAGE_UNSCHEDULE = 32;
|
||||||
|
BOT_UNLINK_MESSAGE = 33;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3807,7 +3755,6 @@ 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 {
|
||||||
@@ -4028,7 +3975,6 @@ 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;
|
||||||
@@ -4221,8 +4167,6 @@ enum MutationProps {
|
|||||||
CUSTOMER_DATA_ACTION = 83;
|
CUSTOMER_DATA_ACTION = 83;
|
||||||
SUBSCRIPTIONS_SYNC_V2_ACTION = 84;
|
SUBSCRIPTIONS_SYNC_V2_ACTION = 84;
|
||||||
THREAD_PIN_ACTION = 85;
|
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;
|
||||||
@@ -4536,12 +4480,6 @@ 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;
|
||||||
@@ -4868,8 +4806,6 @@ message SyncActionValue {
|
|||||||
optional CustomerDataAction customerDataAction = 83;
|
optional CustomerDataAction customerDataAction = 83;
|
||||||
optional SubscriptionsSyncV2Action subscriptionsSyncV2Action = 84;
|
optional SubscriptionsSyncV2Action subscriptionsSyncV2Action = 84;
|
||||||
optional ThreadPinAction threadPinAction = 85;
|
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;
|
||||||
@@ -4889,10 +4825,6 @@ 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;
|
||||||
@@ -4903,20 +4835,6 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -4962,7 +4880,6 @@ 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 {
|
||||||
@@ -5092,7 +5009,6 @@ message SyncActionValue {
|
|||||||
DRAFTED = 8;
|
DRAFTED = 8;
|
||||||
AI_HANDOFF = 9;
|
AI_HANDOFF = 9;
|
||||||
CHANNELS = 10;
|
CHANNELS = 10;
|
||||||
AI_RESPONDING = 11;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5308,8 +5224,6 @@ 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;
|
||||||
@@ -5354,8 +5268,6 @@ 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;
|
||||||
@@ -5379,22 +5291,11 @@ 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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5781,8 +5682,6 @@ 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;
|
||||||
@@ -6022,8 +5921,6 @@ 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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+18
-26
@@ -18,21 +18,14 @@ 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' +
|
||||||
'\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
|
'\tif (!$util.Long) {\n' +
|
||||||
'\t// BigInt.toString() is a native C++ operation, much faster than Long\'s pure JS division loops\n' +
|
'\t\treturn String(value);\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' +
|
||||||
'\treturn String(value);\n' +
|
'\tconst normalized = $util.Long.fromValue(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' +
|
||||||
@@ -40,20 +33,19 @@ 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' +
|
||||||
'\t// Fast path: convert Long {low, high} directly via native BigInt\n' +
|
'\tconst normalized = $util.Long.fromValue(value);\n' +
|
||||||
'\tif (value && typeof value.low === "number" && typeof value.high === "number") {\n' +
|
'\tconst prepared = unsigned && normalized && typeof normalized.toUnsigned === "function"\n' +
|
||||||
'\t\tconst high = value.high | 0;\n' +
|
'\t\t? normalized.toUnsigned()\n' +
|
||||||
'\t\tconst lo = BigInt(value.low >>> 0);\n' +
|
'\t\t: typeof normalized.toSigned === "function"\n' +
|
||||||
'\t\tconst hi = BigInt(value.high >>> 0);\n' +
|
'\t\t\t? normalized.toSigned()\n' +
|
||||||
'\t\tconst combined = (hi << 32n) | lo;\n' +
|
'\t\t\t: normalized;\n' +
|
||||||
'\t\tif (!unsigned && high < 0) {\n' +
|
'\treturn prepared.toNumber();\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
+12
-258
@@ -1092,31 +1092,10 @@ export namespace proto {
|
|||||||
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57,
|
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57,
|
||||||
JSON_PATCH_STREAMING = 58,
|
JSON_PATCH_STREAMING = 58,
|
||||||
AI_TAB_FORCE_CLIPPY = 59,
|
AI_TAB_FORCE_CLIPPY = 59,
|
||||||
UNIFIED_RESPONSE_EMBEDDED_SCREENS = 60,
|
UNIFIED_RESPONSE_EMBEDDED_SCREENS = 60
|
||||||
AI_SUBSCRIPTION_ENABLED = 61
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IBotCommandMetadata {
|
|
||||||
commandName?: (string|null);
|
|
||||||
commandDescription?: (string|null);
|
|
||||||
commandPrompt?: (string|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class BotCommandMetadata implements IBotCommandMetadata {
|
|
||||||
constructor(p?: proto.IBotCommandMetadata);
|
|
||||||
public commandName?: (string|null);
|
|
||||||
public commandDescription?: (string|null);
|
|
||||||
public commandPrompt?: (string|null);
|
|
||||||
public static create(properties?: proto.IBotCommandMetadata): proto.BotCommandMetadata;
|
|
||||||
public static encode(m: proto.IBotCommandMetadata, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.BotCommandMetadata;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.BotCommandMetadata;
|
|
||||||
public static toObject(m: proto.BotCommandMetadata, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IBotDocumentMessageMetadata {
|
interface IBotDocumentMessageMetadata {
|
||||||
pluginType?: (proto.BotDocumentMessageMetadata.DocumentPluginType|null);
|
pluginType?: (proto.BotDocumentMessageMetadata.DocumentPluginType|null);
|
||||||
}
|
}
|
||||||
@@ -1701,7 +1680,6 @@ export namespace proto {
|
|||||||
botRenderingConfigMetadata?: (proto.IBotRenderingConfigMetadata|null);
|
botRenderingConfigMetadata?: (proto.IBotRenderingConfigMetadata|null);
|
||||||
botInfrastructureDiagnostics?: (proto.IBotInfrastructureDiagnostics|null);
|
botInfrastructureDiagnostics?: (proto.IBotInfrastructureDiagnostics|null);
|
||||||
aiMediaCollectionMetadata?: (proto.IAIMediaCollectionMetadata|null);
|
aiMediaCollectionMetadata?: (proto.IAIMediaCollectionMetadata|null);
|
||||||
commandMetadata?: (proto.IBotCommandMetadata|null);
|
|
||||||
internalMetadata?: (Uint8Array|null);
|
internalMetadata?: (Uint8Array|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1744,7 +1722,6 @@ export namespace proto {
|
|||||||
public botRenderingConfigMetadata?: (proto.IBotRenderingConfigMetadata|null);
|
public botRenderingConfigMetadata?: (proto.IBotRenderingConfigMetadata|null);
|
||||||
public botInfrastructureDiagnostics?: (proto.IBotInfrastructureDiagnostics|null);
|
public botInfrastructureDiagnostics?: (proto.IBotInfrastructureDiagnostics|null);
|
||||||
public aiMediaCollectionMetadata?: (proto.IAIMediaCollectionMetadata|null);
|
public aiMediaCollectionMetadata?: (proto.IAIMediaCollectionMetadata|null);
|
||||||
public commandMetadata?: (proto.IBotCommandMetadata|null);
|
|
||||||
public internalMetadata?: (Uint8Array|null);
|
public internalMetadata?: (Uint8Array|null);
|
||||||
public static create(properties?: proto.IBotMetadata): proto.BotMetadata;
|
public static create(properties?: proto.IBotMetadata): proto.BotMetadata;
|
||||||
public static encode(m: proto.IBotMetadata, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IBotMetadata, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
@@ -1802,8 +1779,7 @@ export namespace proto {
|
|||||||
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,
|
CHATLIST_SEARCH = 55
|
||||||
NEW_CHAT_LIST = 56
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IBotMetricsMetadata {
|
interface IBotMetricsMetadata {
|
||||||
@@ -3615,10 +3591,6 @@ export namespace proto {
|
|||||||
wtwaWebsiteUrl?: (string|null);
|
wtwaWebsiteUrl?: (string|null);
|
||||||
adPreviewUrl?: (string|null);
|
adPreviewUrl?: (string|null);
|
||||||
containsCtwaFlowsAutoReply?: (boolean|null);
|
containsCtwaFlowsAutoReply?: (boolean|null);
|
||||||
agmThumbnailStrategy?: (number|null);
|
|
||||||
agmTitleStrategy?: (number|null);
|
|
||||||
agmSubtitleStrategy?: (number|null);
|
|
||||||
agmHeaderInteractionStrategy?: (number|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ExternalAdReplyInfo implements IExternalAdReplyInfo {
|
class ExternalAdReplyInfo implements IExternalAdReplyInfo {
|
||||||
@@ -3651,10 +3623,6 @@ export namespace proto {
|
|||||||
public wtwaWebsiteUrl?: (string|null);
|
public wtwaWebsiteUrl?: (string|null);
|
||||||
public adPreviewUrl?: (string|null);
|
public adPreviewUrl?: (string|null);
|
||||||
public containsCtwaFlowsAutoReply?: (boolean|null);
|
public containsCtwaFlowsAutoReply?: (boolean|null);
|
||||||
public agmThumbnailStrategy?: (number|null);
|
|
||||||
public agmTitleStrategy?: (number|null);
|
|
||||||
public agmSubtitleStrategy?: (number|null);
|
|
||||||
public agmHeaderInteractionStrategy?: (number|null);
|
|
||||||
public static create(properties?: proto.ContextInfo.IExternalAdReplyInfo): proto.ContextInfo.ExternalAdReplyInfo;
|
public static create(properties?: proto.ContextInfo.IExternalAdReplyInfo): proto.ContextInfo.ExternalAdReplyInfo;
|
||||||
public static encode(m: proto.ContextInfo.IExternalAdReplyInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.ContextInfo.IExternalAdReplyInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.ContextInfo.ExternalAdReplyInfo;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.ContextInfo.ExternalAdReplyInfo;
|
||||||
@@ -4059,7 +4027,6 @@ export namespace proto {
|
|||||||
companionSupportEnabled?: (boolean|null);
|
companionSupportEnabled?: (boolean|null);
|
||||||
campaignSyncEnabled?: (boolean|null);
|
campaignSyncEnabled?: (boolean|null);
|
||||||
insightsSyncEnabled?: (boolean|null);
|
insightsSyncEnabled?: (boolean|null);
|
||||||
recipientLimit?: (number|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class BusinessBroadcast implements IBusinessBroadcast {
|
class BusinessBroadcast implements IBusinessBroadcast {
|
||||||
@@ -4068,7 +4035,6 @@ export namespace proto {
|
|||||||
public companionSupportEnabled?: (boolean|null);
|
public companionSupportEnabled?: (boolean|null);
|
||||||
public campaignSyncEnabled?: (boolean|null);
|
public campaignSyncEnabled?: (boolean|null);
|
||||||
public insightsSyncEnabled?: (boolean|null);
|
public insightsSyncEnabled?: (boolean|null);
|
||||||
public recipientLimit?: (number|null);
|
|
||||||
public static create(properties?: proto.DeviceCapabilities.IBusinessBroadcast): proto.DeviceCapabilities.BusinessBroadcast;
|
public static create(properties?: proto.DeviceCapabilities.IBusinessBroadcast): proto.DeviceCapabilities.BusinessBroadcast;
|
||||||
public static encode(m: proto.DeviceCapabilities.IBusinessBroadcast, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.DeviceCapabilities.IBusinessBroadcast, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.DeviceCapabilities.BusinessBroadcast;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.DeviceCapabilities.BusinessBroadcast;
|
||||||
@@ -4244,8 +4210,6 @@ export namespace proto {
|
|||||||
initialSyncMaxMessagesPerChat?: (number|null);
|
initialSyncMaxMessagesPerChat?: (number|null);
|
||||||
supportManusHistory?: (boolean|null);
|
supportManusHistory?: (boolean|null);
|
||||||
supportHatchHistory?: (boolean|null);
|
supportHatchHistory?: (boolean|null);
|
||||||
supportedBotChannelFbids?: (string[]|null);
|
|
||||||
supportInlineContacts?: (boolean|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class HistorySyncConfig implements IHistorySyncConfig {
|
class HistorySyncConfig implements IHistorySyncConfig {
|
||||||
@@ -4272,8 +4236,6 @@ export namespace proto {
|
|||||||
public initialSyncMaxMessagesPerChat?: (number|null);
|
public initialSyncMaxMessagesPerChat?: (number|null);
|
||||||
public supportManusHistory?: (boolean|null);
|
public supportManusHistory?: (boolean|null);
|
||||||
public supportHatchHistory?: (boolean|null);
|
public supportHatchHistory?: (boolean|null);
|
||||||
public supportedBotChannelFbids: string[];
|
|
||||||
public supportInlineContacts?: (boolean|null);
|
|
||||||
public static create(properties?: proto.DeviceProps.IHistorySyncConfig): proto.DeviceProps.HistorySyncConfig;
|
public static create(properties?: proto.DeviceProps.IHistorySyncConfig): proto.DeviceProps.HistorySyncConfig;
|
||||||
public static encode(m: proto.DeviceProps.IHistorySyncConfig, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.DeviceProps.IHistorySyncConfig, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.DeviceProps.HistorySyncConfig;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.DeviceProps.HistorySyncConfig;
|
||||||
@@ -4742,42 +4704,6 @@ export namespace proto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IGroupRootKeyShare {
|
|
||||||
keys?: (proto.IGroupRootKeyShareEntry[]|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class GroupRootKeyShare implements IGroupRootKeyShare {
|
|
||||||
constructor(p?: proto.IGroupRootKeyShare);
|
|
||||||
public keys: proto.IGroupRootKeyShareEntry[];
|
|
||||||
public static create(properties?: proto.IGroupRootKeyShare): proto.GroupRootKeyShare;
|
|
||||||
public static encode(m: proto.IGroupRootKeyShare, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.GroupRootKeyShare;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.GroupRootKeyShare;
|
|
||||||
public static toObject(m: proto.GroupRootKeyShare, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IGroupRootKeyShareEntry {
|
|
||||||
groupRootKey?: (Uint8Array|null);
|
|
||||||
keyId?: (string|null);
|
|
||||||
expiryTimestampMs?: (number|Long|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class GroupRootKeyShareEntry implements IGroupRootKeyShareEntry {
|
|
||||||
constructor(p?: proto.IGroupRootKeyShareEntry);
|
|
||||||
public groupRootKey?: (Uint8Array|null);
|
|
||||||
public keyId?: (string|null);
|
|
||||||
public expiryTimestampMs?: (number|Long|null);
|
|
||||||
public static create(properties?: proto.IGroupRootKeyShareEntry): proto.GroupRootKeyShareEntry;
|
|
||||||
public static encode(m: proto.IGroupRootKeyShareEntry, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.GroupRootKeyShareEntry;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.GroupRootKeyShareEntry;
|
|
||||||
public static toObject(m: proto.GroupRootKeyShareEntry, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IHandshakeMessage {
|
interface IHandshakeMessage {
|
||||||
clientHello?: (proto.HandshakeMessage.IClientHello|null);
|
clientHello?: (proto.HandshakeMessage.IClientHello|null);
|
||||||
serverHello?: (proto.HandshakeMessage.IServerHello|null);
|
serverHello?: (proto.HandshakeMessage.IServerHello|null);
|
||||||
@@ -4833,8 +4759,6 @@ export namespace proto {
|
|||||||
paddedBytes?: (Uint8Array|null);
|
paddedBytes?: (Uint8Array|null);
|
||||||
sendServerHelloPaddedBytes?: (boolean|null);
|
sendServerHelloPaddedBytes?: (boolean|null);
|
||||||
simulateXxkemFs?: (boolean|null);
|
simulateXxkemFs?: (boolean|null);
|
||||||
pqMode?: (proto.HandshakeMessage.HandshakePqMode|null);
|
|
||||||
extendedEphemeral?: (Uint8Array|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ClientHello implements IClientHello {
|
class ClientHello implements IClientHello {
|
||||||
@@ -4847,8 +4771,6 @@ export namespace proto {
|
|||||||
public paddedBytes?: (Uint8Array|null);
|
public paddedBytes?: (Uint8Array|null);
|
||||||
public sendServerHelloPaddedBytes?: (boolean|null);
|
public sendServerHelloPaddedBytes?: (boolean|null);
|
||||||
public simulateXxkemFs?: (boolean|null);
|
public simulateXxkemFs?: (boolean|null);
|
||||||
public pqMode?: (proto.HandshakeMessage.HandshakePqMode|null);
|
|
||||||
public extendedEphemeral?: (Uint8Array|null);
|
|
||||||
public static create(properties?: proto.HandshakeMessage.IClientHello): proto.HandshakeMessage.ClientHello;
|
public static create(properties?: proto.HandshakeMessage.IClientHello): proto.HandshakeMessage.ClientHello;
|
||||||
public static encode(m: proto.HandshakeMessage.IClientHello, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.HandshakeMessage.IClientHello, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.HandshakeMessage.ClientHello;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.HandshakeMessage.ClientHello;
|
||||||
@@ -4858,25 +4780,12 @@ export namespace proto {
|
|||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IServerHello {
|
interface IServerHello {
|
||||||
ephemeral?: (Uint8Array|null);
|
ephemeral?: (Uint8Array|null);
|
||||||
"static"?: (Uint8Array|null);
|
"static"?: (Uint8Array|null);
|
||||||
payload?: (Uint8Array|null);
|
payload?: (Uint8Array|null);
|
||||||
extendedStatic?: (Uint8Array|null);
|
extendedStatic?: (Uint8Array|null);
|
||||||
paddingBytes?: (Uint8Array|null);
|
paddingBytes?: (Uint8Array|null);
|
||||||
extendedCiphertext?: (Uint8Array|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ServerHello implements IServerHello {
|
class ServerHello implements IServerHello {
|
||||||
@@ -4886,7 +4795,6 @@ export namespace proto {
|
|||||||
public payload?: (Uint8Array|null);
|
public payload?: (Uint8Array|null);
|
||||||
public extendedStatic?: (Uint8Array|null);
|
public extendedStatic?: (Uint8Array|null);
|
||||||
public paddingBytes?: (Uint8Array|null);
|
public paddingBytes?: (Uint8Array|null);
|
||||||
public extendedCiphertext?: (Uint8Array|null);
|
|
||||||
public static create(properties?: proto.HandshakeMessage.IServerHello): proto.HandshakeMessage.ServerHello;
|
public static create(properties?: proto.HandshakeMessage.IServerHello): proto.HandshakeMessage.ServerHello;
|
||||||
public static encode(m: proto.HandshakeMessage.IServerHello, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.HandshakeMessage.IServerHello, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.HandshakeMessage.ServerHello;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.HandshakeMessage.ServerHello;
|
||||||
@@ -4916,8 +4824,6 @@ export namespace proto {
|
|||||||
shareableChatIdentifierEncryptionKey?: (Uint8Array|null);
|
shareableChatIdentifierEncryptionKey?: (Uint8Array|null);
|
||||||
accounts?: (proto.IAccount[]|null);
|
accounts?: (proto.IAccount[]|null);
|
||||||
nctSalt?: (Uint8Array|null);
|
nctSalt?: (Uint8Array|null);
|
||||||
inlineContacts?: (proto.IInlineContact[]|null);
|
|
||||||
inlineContactsProvided?: (boolean|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class HistorySync implements IHistorySync {
|
class HistorySync implements IHistorySync {
|
||||||
@@ -4940,8 +4846,6 @@ export namespace proto {
|
|||||||
public shareableChatIdentifierEncryptionKey?: (Uint8Array|null);
|
public shareableChatIdentifierEncryptionKey?: (Uint8Array|null);
|
||||||
public accounts: proto.IAccount[];
|
public accounts: proto.IAccount[];
|
||||||
public nctSalt?: (Uint8Array|null);
|
public nctSalt?: (Uint8Array|null);
|
||||||
public inlineContacts: proto.IInlineContact[];
|
|
||||||
public inlineContactsProvided?: (boolean|null);
|
|
||||||
public static create(properties?: proto.IHistorySync): proto.HistorySync;
|
public static create(properties?: proto.IHistorySync): proto.HistorySync;
|
||||||
public static encode(m: proto.IHistorySync, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IHistorySync, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.HistorySync;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.HistorySync;
|
||||||
@@ -5209,30 +5113,6 @@ export namespace proto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IInlineContact {
|
|
||||||
pnJid?: (string|null);
|
|
||||||
lidJid?: (string|null);
|
|
||||||
fullName?: (string|null);
|
|
||||||
firstName?: (string|null);
|
|
||||||
username?: (string|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class InlineContact implements IInlineContact {
|
|
||||||
constructor(p?: proto.IInlineContact);
|
|
||||||
public pnJid?: (string|null);
|
|
||||||
public lidJid?: (string|null);
|
|
||||||
public fullName?: (string|null);
|
|
||||||
public firstName?: (string|null);
|
|
||||||
public username?: (string|null);
|
|
||||||
public static create(properties?: proto.IInlineContact): proto.InlineContact;
|
|
||||||
public static encode(m: proto.IInlineContact, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.InlineContact;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.InlineContact;
|
|
||||||
public static toObject(m: proto.InlineContact, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IInteractiveAnnotation {
|
interface IInteractiveAnnotation {
|
||||||
polygonVertices?: (proto.IPoint[]|null);
|
polygonVertices?: (proto.IPoint[]|null);
|
||||||
shouldSkipConfirmation?: (boolean|null);
|
shouldSkipConfirmation?: (boolean|null);
|
||||||
@@ -5461,7 +5341,8 @@ export namespace proto {
|
|||||||
UNKNOWN = 0,
|
UNKNOWN = 0,
|
||||||
CHAT_SETTING = 1,
|
CHAT_SETTING = 1,
|
||||||
BIZ_SUPPORTS_FB_HOSTING = 2,
|
BIZ_SUPPORTS_FB_HOSTING = 2,
|
||||||
UNKNOWN_GROUP = 3
|
UNKNOWN_GROUP = 3,
|
||||||
|
DEPRECATION = 4
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5724,7 +5605,6 @@ export namespace proto {
|
|||||||
conditionalRevealMessage?: (proto.Message.IConditionalRevealMessage|null);
|
conditionalRevealMessage?: (proto.Message.IConditionalRevealMessage|null);
|
||||||
pollAddOptionMessage?: (proto.Message.IPollAddOptionMessage|null);
|
pollAddOptionMessage?: (proto.Message.IPollAddOptionMessage|null);
|
||||||
eventInviteMessage?: (proto.Message.IEventInviteMessage|null);
|
eventInviteMessage?: (proto.Message.IEventInviteMessage|null);
|
||||||
groupRootKeyShare?: (proto.IGroupRootKeyShare|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class Message implements IMessage {
|
class Message implements IMessage {
|
||||||
@@ -5831,7 +5711,6 @@ export namespace proto {
|
|||||||
public conditionalRevealMessage?: (proto.Message.IConditionalRevealMessage|null);
|
public conditionalRevealMessage?: (proto.Message.IConditionalRevealMessage|null);
|
||||||
public pollAddOptionMessage?: (proto.Message.IPollAddOptionMessage|null);
|
public pollAddOptionMessage?: (proto.Message.IPollAddOptionMessage|null);
|
||||||
public eventInviteMessage?: (proto.Message.IEventInviteMessage|null);
|
public eventInviteMessage?: (proto.Message.IEventInviteMessage|null);
|
||||||
public groupRootKeyShare?: (proto.IGroupRootKeyShare|null);
|
|
||||||
public static create(properties?: proto.IMessage): proto.Message;
|
public static create(properties?: proto.IMessage): proto.Message;
|
||||||
public static encode(m: proto.IMessage, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IMessage, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message;
|
||||||
@@ -6371,8 +6250,7 @@ export namespace proto {
|
|||||||
enum CloudAPIThreadControl {
|
enum CloudAPIThreadControl {
|
||||||
UNKNOWN = 0,
|
UNKNOWN = 0,
|
||||||
CONTROL_PASSED = 1,
|
CONTROL_PASSED = 1,
|
||||||
CONTROL_TAKEN = 2,
|
CONTROL_TAKEN = 2
|
||||||
INFO = 3
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ICloudAPIThreadControlNotificationContent {
|
interface ICloudAPIThreadControlNotificationContent {
|
||||||
@@ -8480,7 +8358,6 @@ export namespace proto {
|
|||||||
onDemandMsgCount?: (number|null);
|
onDemandMsgCount?: (number|null);
|
||||||
oldestMsgTimestampMs?: (number|Long|null);
|
oldestMsgTimestampMs?: (number|Long|null);
|
||||||
accountLid?: (string|null);
|
accountLid?: (string|null);
|
||||||
supportInlineResponse?: (boolean|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class HistorySyncOnDemandRequest implements IHistorySyncOnDemandRequest {
|
class HistorySyncOnDemandRequest implements IHistorySyncOnDemandRequest {
|
||||||
@@ -8491,7 +8368,6 @@ export namespace proto {
|
|||||||
public onDemandMsgCount?: (number|null);
|
public onDemandMsgCount?: (number|null);
|
||||||
public oldestMsgTimestampMs?: (number|Long|null);
|
public oldestMsgTimestampMs?: (number|Long|null);
|
||||||
public accountLid?: (string|null);
|
public accountLid?: (string|null);
|
||||||
public supportInlineResponse?: (boolean|null);
|
|
||||||
public static create(properties?: proto.Message.PeerDataOperationRequestMessage.IHistorySyncOnDemandRequest): proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest;
|
public static create(properties?: proto.Message.PeerDataOperationRequestMessage.IHistorySyncOnDemandRequest): proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest;
|
||||||
public static encode(m: proto.Message.PeerDataOperationRequestMessage.IHistorySyncOnDemandRequest, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.Message.PeerDataOperationRequestMessage.IHistorySyncOnDemandRequest, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestMessage.HistorySyncOnDemandRequest;
|
||||||
@@ -8765,8 +8641,7 @@ export namespace proto {
|
|||||||
GENERIC_ERROR = 3,
|
GENERIC_ERROR = 3,
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IHistorySyncChunkRetryResponse {
|
interface IHistorySyncChunkRetryResponse {
|
||||||
@@ -9392,7 +9267,8 @@ export namespace proto {
|
|||||||
AI_QUERY_FANOUT = 29,
|
AI_QUERY_FANOUT = 29,
|
||||||
GROUP_MEMBER_LABEL_CHANGE = 30,
|
GROUP_MEMBER_LABEL_CHANGE = 30,
|
||||||
AI_MEDIA_COLLECTION_MESSAGE = 31,
|
AI_MEDIA_COLLECTION_MESSAGE = 31,
|
||||||
MESSAGE_UNSCHEDULE = 32
|
MESSAGE_UNSCHEDULE = 32,
|
||||||
|
BOT_UNLINK_MESSAGE = 33
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -9771,7 +9647,6 @@ export namespace proto {
|
|||||||
isLottie?: (boolean|null);
|
isLottie?: (boolean|null);
|
||||||
accessibilityLabel?: (string|null);
|
accessibilityLabel?: (string|null);
|
||||||
premium?: (number|null);
|
premium?: (number|null);
|
||||||
emojis?: (string|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class StickerMessage implements IStickerMessage {
|
class StickerMessage implements IStickerMessage {
|
||||||
@@ -9797,7 +9672,6 @@ export namespace proto {
|
|||||||
public isLottie?: (boolean|null);
|
public isLottie?: (boolean|null);
|
||||||
public accessibilityLabel?: (string|null);
|
public accessibilityLabel?: (string|null);
|
||||||
public premium?: (number|null);
|
public premium?: (number|null);
|
||||||
public emojis?: (string|null);
|
|
||||||
public static create(properties?: proto.Message.IStickerMessage): proto.Message.StickerMessage;
|
public static create(properties?: proto.Message.IStickerMessage): proto.Message.StickerMessage;
|
||||||
public static encode(m: proto.Message.IStickerMessage, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.Message.IStickerMessage, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.StickerMessage;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.StickerMessage;
|
||||||
@@ -10293,7 +10167,6 @@ export namespace proto {
|
|||||||
limitSharingV2?: (proto.ILimitSharing|null);
|
limitSharingV2?: (proto.ILimitSharing|null);
|
||||||
threadId?: (proto.IThreadID[]|null);
|
threadId?: (proto.IThreadID[]|null);
|
||||||
weblinkRenderConfig?: (proto.WebLinkRenderConfig|null);
|
weblinkRenderConfig?: (proto.WebLinkRenderConfig|null);
|
||||||
teeBotMetadata?: (Uint8Array|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class MessageContextInfo implements IMessageContextInfo {
|
class MessageContextInfo implements IMessageContextInfo {
|
||||||
@@ -10314,7 +10187,6 @@ export namespace proto {
|
|||||||
public limitSharingV2?: (proto.ILimitSharing|null);
|
public limitSharingV2?: (proto.ILimitSharing|null);
|
||||||
public threadId: proto.IThreadID[];
|
public threadId: proto.IThreadID[];
|
||||||
public weblinkRenderConfig?: (proto.WebLinkRenderConfig|null);
|
public weblinkRenderConfig?: (proto.WebLinkRenderConfig|null);
|
||||||
public teeBotMetadata?: (Uint8Array|null);
|
|
||||||
public static create(properties?: proto.IMessageContextInfo): proto.MessageContextInfo;
|
public static create(properties?: proto.IMessageContextInfo): proto.MessageContextInfo;
|
||||||
public static encode(m: proto.IMessageContextInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IMessageContextInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.MessageContextInfo;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.MessageContextInfo;
|
||||||
@@ -10692,8 +10564,6 @@ export namespace proto {
|
|||||||
CUSTOMER_DATA_ACTION = 83,
|
CUSTOMER_DATA_ACTION = 83,
|
||||||
SUBSCRIPTIONS_SYNC_V2_ACTION = 84,
|
SUBSCRIPTIONS_SYNC_V2_ACTION = 84,
|
||||||
THREAD_PIN_ACTION = 85,
|
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
|
||||||
@@ -11505,26 +11375,6 @@ export namespace proto {
|
|||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IScheduledMessageMetadata {
|
|
||||||
revealKeyId?: (string|null);
|
|
||||||
revealKey?: (Uint8Array|null);
|
|
||||||
scheduledTime?: (number|Long|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class ScheduledMessageMetadata implements IScheduledMessageMetadata {
|
|
||||||
constructor(p?: proto.IScheduledMessageMetadata);
|
|
||||||
public revealKeyId?: (string|null);
|
|
||||||
public revealKey?: (Uint8Array|null);
|
|
||||||
public scheduledTime?: (number|Long|null);
|
|
||||||
public static create(properties?: proto.IScheduledMessageMetadata): proto.ScheduledMessageMetadata;
|
|
||||||
public static encode(m: proto.IScheduledMessageMetadata, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.ScheduledMessageMetadata;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.ScheduledMessageMetadata;
|
|
||||||
public static toObject(m: proto.ScheduledMessageMetadata, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ISenderKeyDistributionMessage {
|
interface ISenderKeyDistributionMessage {
|
||||||
id?: (number|null);
|
id?: (number|null);
|
||||||
iteration?: (number|null);
|
iteration?: (number|null);
|
||||||
@@ -12311,8 +12161,6 @@ export namespace proto {
|
|||||||
customerDataAction?: (proto.SyncActionValue.ICustomerDataAction|null);
|
customerDataAction?: (proto.SyncActionValue.ICustomerDataAction|null);
|
||||||
subscriptionsSyncV2Action?: (proto.SyncActionValue.ISubscriptionsSyncV2Action|null);
|
subscriptionsSyncV2Action?: (proto.SyncActionValue.ISubscriptionsSyncV2Action|null);
|
||||||
threadPinAction?: (proto.SyncActionValue.IThreadPinAction|null);
|
threadPinAction?: (proto.SyncActionValue.IThreadPinAction|null);
|
||||||
autoOrganizeBusinessChatSetting?: (proto.SyncActionValue.IAutoOrganizeBusinessChatSetting|null);
|
|
||||||
bizAiSettingsNudgeAction?: (proto.SyncActionValue.IBizAISettingsNudgeAction|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class SyncActionValue implements ISyncActionValue {
|
class SyncActionValue implements ISyncActionValue {
|
||||||
@@ -12393,8 +12241,6 @@ export namespace proto {
|
|||||||
public customerDataAction?: (proto.SyncActionValue.ICustomerDataAction|null);
|
public customerDataAction?: (proto.SyncActionValue.ICustomerDataAction|null);
|
||||||
public subscriptionsSyncV2Action?: (proto.SyncActionValue.ISubscriptionsSyncV2Action|null);
|
public subscriptionsSyncV2Action?: (proto.SyncActionValue.ISubscriptionsSyncV2Action|null);
|
||||||
public threadPinAction?: (proto.SyncActionValue.IThreadPinAction|null);
|
public threadPinAction?: (proto.SyncActionValue.IThreadPinAction|null);
|
||||||
public autoOrganizeBusinessChatSetting?: (proto.SyncActionValue.IAutoOrganizeBusinessChatSetting|null);
|
|
||||||
public bizAiSettingsNudgeAction?: (proto.SyncActionValue.IBizAISettingsNudgeAction|null);
|
|
||||||
public static create(properties?: proto.ISyncActionValue): proto.SyncActionValue;
|
public static create(properties?: proto.ISyncActionValue): proto.SyncActionValue;
|
||||||
public static encode(m: proto.ISyncActionValue, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.ISyncActionValue, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue;
|
||||||
@@ -12476,22 +12322,6 @@ export namespace proto {
|
|||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IAutoOrganizeBusinessChatSetting {
|
|
||||||
autoOrganize?: (boolean|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class AutoOrganizeBusinessChatSetting implements IAutoOrganizeBusinessChatSetting {
|
|
||||||
constructor(p?: proto.SyncActionValue.IAutoOrganizeBusinessChatSetting);
|
|
||||||
public autoOrganize?: (boolean|null);
|
|
||||||
public static create(properties?: proto.SyncActionValue.IAutoOrganizeBusinessChatSetting): proto.SyncActionValue.AutoOrganizeBusinessChatSetting;
|
|
||||||
public static encode(m: proto.SyncActionValue.IAutoOrganizeBusinessChatSetting, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.AutoOrganizeBusinessChatSetting;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.SyncActionValue.AutoOrganizeBusinessChatSetting;
|
|
||||||
public static toObject(m: proto.SyncActionValue.AutoOrganizeBusinessChatSetting, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IAvatarUpdatedAction {
|
interface IAvatarUpdatedAction {
|
||||||
eventType?: (proto.SyncActionValue.AvatarUpdatedAction.AvatarEventType|null);
|
eventType?: (proto.SyncActionValue.AvatarUpdatedAction.AvatarEventType|null);
|
||||||
recentAvatarStickers?: (proto.SyncActionValue.IStickerAction[]|null);
|
recentAvatarStickers?: (proto.SyncActionValue.IStickerAction[]|null);
|
||||||
@@ -12519,38 +12349,6 @@ export namespace proto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IBizAISettingsNudgeAction {
|
|
||||||
category?: (proto.SyncActionValue.BizAISettingsNudgeAction.BizAISettingsCategory|null);
|
|
||||||
version?: (number|Long|null);
|
|
||||||
updatedAtMs?: (number|Long|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class BizAISettingsNudgeAction implements IBizAISettingsNudgeAction {
|
|
||||||
constructor(p?: proto.SyncActionValue.IBizAISettingsNudgeAction);
|
|
||||||
public category?: (proto.SyncActionValue.BizAISettingsNudgeAction.BizAISettingsCategory|null);
|
|
||||||
public version?: (number|Long|null);
|
|
||||||
public updatedAtMs?: (number|Long|null);
|
|
||||||
public static create(properties?: proto.SyncActionValue.IBizAISettingsNudgeAction): proto.SyncActionValue.BizAISettingsNudgeAction;
|
|
||||||
public static encode(m: proto.SyncActionValue.IBizAISettingsNudgeAction, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.BizAISettingsNudgeAction;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.SyncActionValue.BizAISettingsNudgeAction;
|
|
||||||
public static toObject(m: proto.SyncActionValue.BizAISettingsNudgeAction, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace BizAISettingsNudgeAction {
|
|
||||||
|
|
||||||
enum BizAISettingsCategory {
|
|
||||||
UNKNOWN = 0,
|
|
||||||
INSTRUCTIONS = 1,
|
|
||||||
RESPONSE_SETTINGS = 2,
|
|
||||||
EXAMPLE_RESPONSES = 3,
|
|
||||||
KNOWLEDGE = 4,
|
|
||||||
LEAD_GEN = 5
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IBotWelcomeRequestAction {
|
interface IBotWelcomeRequestAction {
|
||||||
isSent?: (boolean|null);
|
isSent?: (boolean|null);
|
||||||
}
|
}
|
||||||
@@ -12670,7 +12468,6 @@ export namespace proto {
|
|||||||
participants?: (proto.SyncActionValue.IBroadcastListParticipant[]|null);
|
participants?: (proto.SyncActionValue.IBroadcastListParticipant[]|null);
|
||||||
listName?: (string|null);
|
listName?: (string|null);
|
||||||
labelIds?: (string[]|null);
|
labelIds?: (string[]|null);
|
||||||
audienceExpression?: (string|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class BusinessBroadcastListAction implements IBusinessBroadcastListAction {
|
class BusinessBroadcastListAction implements IBusinessBroadcastListAction {
|
||||||
@@ -12679,7 +12476,6 @@ export namespace proto {
|
|||||||
public participants: proto.SyncActionValue.IBroadcastListParticipant[];
|
public participants: proto.SyncActionValue.IBroadcastListParticipant[];
|
||||||
public listName?: (string|null);
|
public listName?: (string|null);
|
||||||
public labelIds: string[];
|
public labelIds: string[];
|
||||||
public audienceExpression?: (string|null);
|
|
||||||
public static create(properties?: proto.SyncActionValue.IBusinessBroadcastListAction): proto.SyncActionValue.BusinessBroadcastListAction;
|
public static create(properties?: proto.SyncActionValue.IBusinessBroadcastListAction): proto.SyncActionValue.BusinessBroadcastListAction;
|
||||||
public static encode(m: proto.SyncActionValue.IBusinessBroadcastListAction, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.SyncActionValue.IBusinessBroadcastListAction, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.BusinessBroadcastListAction;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.BusinessBroadcastListAction;
|
||||||
@@ -13108,8 +12904,7 @@ export namespace proto {
|
|||||||
SERVER_ASSIGNED = 7,
|
SERVER_ASSIGNED = 7,
|
||||||
DRAFTED = 8,
|
DRAFTED = 8,
|
||||||
AI_HANDOFF = 9,
|
AI_HANDOFF = 9,
|
||||||
CHANNELS = 10,
|
CHANNELS = 10
|
||||||
AI_RESPONDING = 11
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13751,8 +13546,6 @@ export namespace proto {
|
|||||||
isStatusNotificationEnabled?: (boolean|null);
|
isStatusNotificationEnabled?: (boolean|null);
|
||||||
statusNotificationToneId?: (number|null);
|
statusNotificationToneId?: (number|null);
|
||||||
shouldPlaySoundForCallNotification?: (boolean|null);
|
shouldPlaySoundForCallNotification?: (boolean|null);
|
||||||
chatThemeId?: (string|null);
|
|
||||||
colorSchemeId?: (string|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class SettingsSyncAction implements ISettingsSyncAction {
|
class SettingsSyncAction implements ISettingsSyncAction {
|
||||||
@@ -13788,8 +13581,6 @@ export namespace proto {
|
|||||||
public isStatusNotificationEnabled?: (boolean|null);
|
public isStatusNotificationEnabled?: (boolean|null);
|
||||||
public statusNotificationToneId?: (number|null);
|
public statusNotificationToneId?: (number|null);
|
||||||
public shouldPlaySoundForCallNotification?: (boolean|null);
|
public shouldPlaySoundForCallNotification?: (boolean|null);
|
||||||
public chatThemeId?: (string|null);
|
|
||||||
public colorSchemeId?: (string|null);
|
|
||||||
public static create(properties?: proto.SyncActionValue.ISettingsSyncAction): proto.SyncActionValue.SettingsSyncAction;
|
public static create(properties?: proto.SyncActionValue.ISettingsSyncAction): proto.SyncActionValue.SettingsSyncAction;
|
||||||
public static encode(m: proto.SyncActionValue.ISettingsSyncAction, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.SyncActionValue.ISettingsSyncAction, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.SettingsSyncAction;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.SettingsSyncAction;
|
||||||
@@ -13846,9 +13637,7 @@ export namespace proto {
|
|||||||
IS_GROUP_REACTIONS_NOTIFICATION_ENABLED = 28,
|
IS_GROUP_REACTIONS_NOTIFICATION_ENABLED = 28,
|
||||||
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 {
|
||||||
@@ -13897,8 +13686,6 @@ export namespace proto {
|
|||||||
userJid?: (string[]|null);
|
userJid?: (string[]|null);
|
||||||
shareToFB?: (boolean|null);
|
shareToFB?: (boolean|null);
|
||||||
shareToIG?: (boolean|null);
|
shareToIG?: (boolean|null);
|
||||||
customLists?: (proto.SyncActionValue.StatusPrivacyAction.ICustomList[]|null);
|
|
||||||
modes?: (proto.SyncActionValue.StatusPrivacyAction.StatusDistributionMode[]|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class StatusPrivacyAction implements IStatusPrivacyAction {
|
class StatusPrivacyAction implements IStatusPrivacyAction {
|
||||||
@@ -13907,8 +13694,6 @@ export namespace proto {
|
|||||||
public userJid: string[];
|
public userJid: string[];
|
||||||
public shareToFB?: (boolean|null);
|
public shareToFB?: (boolean|null);
|
||||||
public shareToIG?: (boolean|null);
|
public shareToIG?: (boolean|null);
|
||||||
public customLists: proto.SyncActionValue.StatusPrivacyAction.ICustomList[];
|
|
||||||
public modes: proto.SyncActionValue.StatusPrivacyAction.StatusDistributionMode[];
|
|
||||||
public static create(properties?: proto.SyncActionValue.IStatusPrivacyAction): proto.SyncActionValue.StatusPrivacyAction;
|
public static create(properties?: proto.SyncActionValue.IStatusPrivacyAction): proto.SyncActionValue.StatusPrivacyAction;
|
||||||
public static encode(m: proto.SyncActionValue.IStatusPrivacyAction, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.SyncActionValue.IStatusPrivacyAction, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.StatusPrivacyAction;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.StatusPrivacyAction;
|
||||||
@@ -13920,36 +13705,11 @@ export namespace proto {
|
|||||||
|
|
||||||
namespace StatusPrivacyAction {
|
namespace StatusPrivacyAction {
|
||||||
|
|
||||||
interface ICustomList {
|
|
||||||
listId?: (string|null);
|
|
||||||
name?: (string|null);
|
|
||||||
emoji?: (string|null);
|
|
||||||
isSelected?: (boolean|null);
|
|
||||||
userJid?: (string[]|null);
|
|
||||||
}
|
|
||||||
|
|
||||||
class CustomList implements ICustomList {
|
|
||||||
constructor(p?: proto.SyncActionValue.StatusPrivacyAction.ICustomList);
|
|
||||||
public listId?: (string|null);
|
|
||||||
public name?: (string|null);
|
|
||||||
public emoji?: (string|null);
|
|
||||||
public isSelected?: (boolean|null);
|
|
||||||
public userJid: string[];
|
|
||||||
public static create(properties?: proto.SyncActionValue.StatusPrivacyAction.ICustomList): proto.SyncActionValue.StatusPrivacyAction.CustomList;
|
|
||||||
public static encode(m: proto.SyncActionValue.StatusPrivacyAction.ICustomList, w?: $protobuf.Writer): $protobuf.Writer;
|
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.StatusPrivacyAction.CustomList;
|
|
||||||
public static fromObject(d: { [k: string]: any }): proto.SyncActionValue.StatusPrivacyAction.CustomList;
|
|
||||||
public static toObject(m: proto.SyncActionValue.StatusPrivacyAction.CustomList, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
|
||||||
public toJSON(): { [k: string]: any };
|
|
||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14957,8 +14717,6 @@ export namespace proto {
|
|||||||
quarantinedMessage?: (proto.IQuarantinedMessage|null);
|
quarantinedMessage?: (proto.IQuarantinedMessage|null);
|
||||||
nonJidMentions?: (number|null);
|
nonJidMentions?: (number|null);
|
||||||
hsmTag?: (string|null);
|
hsmTag?: (string|null);
|
||||||
ephemeralExpirationTimestamp?: (number|Long|null);
|
|
||||||
scheduledMessageMetadata?: (proto.IScheduledMessageMetadata|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class WebMessageInfo implements IWebMessageInfo {
|
class WebMessageInfo implements IWebMessageInfo {
|
||||||
@@ -15031,8 +14789,6 @@ export namespace proto {
|
|||||||
public quarantinedMessage?: (proto.IQuarantinedMessage|null);
|
public quarantinedMessage?: (proto.IQuarantinedMessage|null);
|
||||||
public nonJidMentions?: (number|null);
|
public nonJidMentions?: (number|null);
|
||||||
public hsmTag?: (string|null);
|
public hsmTag?: (string|null);
|
||||||
public ephemeralExpirationTimestamp?: (number|Long|null);
|
|
||||||
public scheduledMessageMetadata?: (proto.IScheduledMessageMetadata|null);
|
|
||||||
public static create(properties?: proto.IWebMessageInfo): proto.WebMessageInfo;
|
public static create(properties?: proto.IWebMessageInfo): proto.WebMessageInfo;
|
||||||
public static encode(m: proto.IWebMessageInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IWebMessageInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.WebMessageInfo;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.WebMessageInfo;
|
||||||
@@ -15284,9 +15040,7 @@ export namespace proto {
|
|||||||
QUARANTINED_MESSAGE = 220,
|
QUARANTINED_MESSAGE = 220,
|
||||||
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+32
-1909
File diff suppressed because it is too large
Load Diff
+432
-748
File diff suppressed because it is too large
Load Diff
@@ -1,531 +0,0 @@
|
|||||||
# 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 @@
|
|||||||
{"version":[2,3000,1038167900]}
|
{"version":[2,3000,1035223526]}
|
||||||
|
|||||||
+7
-43
@@ -31,26 +31,9 @@ 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
|
||||||
|
|
||||||
@@ -171,20 +154,7 @@ 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 = {
|
||||||
@@ -208,11 +178,7 @@ 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
|
||||||
@@ -222,12 +188,10 @@ 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
|
||||||
|
|
||||||
// Replenishment threshold: when server count drops below this, top-up back to INITIAL_PREKEY_COUNT
|
export const MIN_PREKEY_COUNT = 5
|
||||||
export const MIN_PREKEY_COUNT = 200
|
|
||||||
|
|
||||||
// Initial pool size matching WA Business (CDP IDB capture: prekey-store = 812 on registration)
|
// Moderate prekey count (upstream uses 812, reduced to balance rate limiting and availability)
|
||||||
// Rounded to 800 for cleanliness; replenishment always tops up to this value
|
export const INITIAL_PREKEY_COUNT = 200
|
||||||
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)
|
||||||
|
|||||||
+7
-46
@@ -98,24 +98,6 @@ 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 */
|
||||||
@@ -809,10 +791,7 @@ 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
|
||||||
|
|
||||||
// Gate inclusion on AB prop 9666 (profile_scraping_privacy_token_in_photo_iq).
|
if (isUserJid && !isSelf) {
|
||||||
// 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,
|
||||||
@@ -1081,21 +1060,22 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** fetch AB props */
|
/** sending non-abt props may fix QR scan fail if server expects */
|
||||||
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: 'abt',
|
xmlns: 'w',
|
||||||
type: 'get'
|
type: 'get'
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
tag: 'props',
|
tag: 'props',
|
||||||
attrs: {
|
attrs: {
|
||||||
protocol: '1',
|
protocol: '2',
|
||||||
...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
|
hash: authState?.creds?.lastPropHash || ''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -1114,25 +1094,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
props = reduceBinaryNodeToDictionary(propsNode, 'prop')
|
props = reduceBinaryNodeToDictionary(propsNode, 'prop')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract protocol-relevant AB props (defaults match WA Web; see serverProps doc).
|
logger.debug('fetched props')
|
||||||
// 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
|
||||||
}
|
}
|
||||||
@@ -1650,7 +1612,6 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...sock,
|
...sock,
|
||||||
serverProps,
|
|
||||||
createCallLink,
|
createCallLink,
|
||||||
getBotListV2,
|
getBotListV2,
|
||||||
messageMutex,
|
messageMutex,
|
||||||
|
|||||||
@@ -343,13 +343,11 @@ 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
|
||||||
}
|
}
|
||||||
@@ -364,19 +362,16 @@ 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'),
|
||||||
@@ -391,7 +386,6 @@ 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']
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|||||||
+153
-286
@@ -7,7 +7,6 @@ import { proto } from '../../WAProto/index.js'
|
|||||||
import {
|
import {
|
||||||
DEFAULT_CACHE_TTLS,
|
DEFAULT_CACHE_TTLS,
|
||||||
DEFAULT_SESSION_CLEANUP_CONFIG,
|
DEFAULT_SESSION_CLEANUP_CONFIG,
|
||||||
INITIAL_PREKEY_COUNT,
|
|
||||||
KEY_BUNDLE_TYPE,
|
KEY_BUNDLE_TYPE,
|
||||||
MIN_PREKEY_COUNT,
|
MIN_PREKEY_COUNT,
|
||||||
PLACEHOLDER_MAX_AGE_SECONDS,
|
PLACEHOLDER_MAX_AGE_SECONDS,
|
||||||
@@ -49,12 +48,9 @@ import {
|
|||||||
getStatusFromReceiptType,
|
getStatusFromReceiptType,
|
||||||
handleIdentityChange,
|
handleIdentityChange,
|
||||||
hkdf,
|
hkdf,
|
||||||
BAD_MAC_ERROR_TEXT,
|
|
||||||
DECRYPTION_RETRY_CONFIG,
|
|
||||||
MISSING_KEYS_ERROR_TEXT,
|
MISSING_KEYS_ERROR_TEXT,
|
||||||
NACK_REASONS,
|
NACK_REASONS,
|
||||||
NO_MESSAGE_FOUND_ERROR_TEXT,
|
NO_MESSAGE_FOUND_ERROR_TEXT,
|
||||||
RetryReason,
|
|
||||||
normalizeKeyLidToPn,
|
normalizeKeyLidToPn,
|
||||||
normalizeMessageJids,
|
normalizeMessageJids,
|
||||||
resolveLidToPn,
|
resolveLidToPn,
|
||||||
@@ -73,14 +69,7 @@ import {
|
|||||||
recordMessageReceived,
|
recordMessageReceived,
|
||||||
recordMessageRetry
|
recordMessageRetry
|
||||||
} from '../Utils/prometheus-metrics.js'
|
} from '../Utils/prometheus-metrics.js'
|
||||||
import {
|
import { isTcTokenExpired, resolveTcTokenJid, storeTcTokensFromIqResult } from '../Utils/tc-token-utils'
|
||||||
buildMergedTcTokenIndexWrite,
|
|
||||||
isTcTokenExpired,
|
|
||||||
resolveIssuanceJid,
|
|
||||||
resolveTcTokenJid,
|
|
||||||
storeTcTokensFromIqResult,
|
|
||||||
TC_TOKEN_INDEX_KEY
|
|
||||||
} from '../Utils/tc-token-utils'
|
|
||||||
import {
|
import {
|
||||||
areJidsSameUser,
|
areJidsSameUser,
|
||||||
type BinaryNode,
|
type BinaryNode,
|
||||||
@@ -171,12 +160,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
let sendActiveReceipts = false
|
let sendActiveReceipts = false
|
||||||
|
|
||||||
// ======= tctoken index tracking for cross-session pruning =======
|
// ======= tctoken index tracking for cross-session pruning =======
|
||||||
// TC_TOKEN_INDEX_KEY is imported from tc-token-utils so the value stays in sync
|
const TC_TOKEN_INDEX_KEY = '__index'
|
||||||
// with messages-send/process-message writes (avoids string drift on rename).
|
|
||||||
// Race note: this prune-driven index write may interleave with
|
|
||||||
// buildMergedTcTokenIndexWrite calls from issuance/history-sync paths. Worst
|
|
||||||
// case: a JID resurrected by a stale read gets pruned again on the next 24h
|
|
||||||
// sweep — no data loss, just one extra cycle.
|
|
||||||
const TC_TOKEN_PRUNE_TS_KEY = '__prune_ts'
|
const TC_TOKEN_PRUNE_TS_KEY = '__prune_ts'
|
||||||
const tcTokenKnownJids = new Set<string>()
|
const tcTokenKnownJids = new Set<string>()
|
||||||
const tcTokenRetriedMsgIds = new Set<string>()
|
const tcTokenRetriedMsgIds = new Set<string>()
|
||||||
@@ -210,25 +194,16 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
})()
|
})()
|
||||||
|
|
||||||
/**
|
/** Debounced save of the tctoken JID index (5s) */
|
||||||
* Debounced save of the tctoken JID index (5s).
|
|
||||||
*
|
|
||||||
* Merges with the persisted index instead of overwriting — other layers
|
|
||||||
* (messages-send fire-and-forget issuance, process-message history sync) may
|
|
||||||
* write JIDs to the index via `buildMergedTcTokenIndexWrite` without updating
|
|
||||||
* `tcTokenKnownJids`. Without the merge those JIDs would be silently dropped
|
|
||||||
* the next time this debounced save fires.
|
|
||||||
*/
|
|
||||||
const scheduleTcTokenIndexSave = () => {
|
const scheduleTcTokenIndexSave = () => {
|
||||||
if (tcTokenIndexSaveTimer) clearTimeout(tcTokenIndexSaveTimer)
|
if (tcTokenIndexSaveTimer) clearTimeout(tcTokenIndexSaveTimer)
|
||||||
tcTokenIndexSaveTimer = setTimeout(async () => {
|
tcTokenIndexSaveTimer = setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
const merged = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids)
|
const arr = Array.from(tcTokenKnownJids)
|
||||||
await authState.keys.set({
|
await authState.keys.set({
|
||||||
tctoken: {
|
tctoken: {
|
||||||
...merged,
|
|
||||||
[TC_TOKEN_INDEX_KEY]: {
|
[TC_TOKEN_INDEX_KEY]: {
|
||||||
...merged[TC_TOKEN_INDEX_KEY],
|
token: Buffer.from(JSON.stringify(arr), 'utf8'),
|
||||||
timestamp: unixTimestampSeconds().toString()
|
timestamp: unixTimestampSeconds().toString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1237,7 +1212,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
return await query(stanza)
|
return await query(stanza)
|
||||||
}
|
}
|
||||||
|
|
||||||
const sendRetryRequest = async (node: BinaryNode, forceIncludeKeys = false, decryptionError?: string) => {
|
const sendRetryRequest = async (node: BinaryNode, forceIncludeKeys = false) => {
|
||||||
const { fullMessage } = decodeMessageNode(node, authState.creds.me!.id, authState.creds.me!.lid || '')
|
const { fullMessage } = decodeMessageNode(node, authState.creds.me!.id, authState.creds.me!.lid || '')
|
||||||
const { key: msgKey } = fullMessage
|
const { key: msgKey } = fullMessage
|
||||||
const msgId = msgKey.id!
|
const msgId = msgKey.id!
|
||||||
@@ -1335,39 +1310,39 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
|
const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
|
||||||
const fromJid = node.attrs.from!
|
const fromJid = node.attrs.from!
|
||||||
|
|
||||||
// Derive the Signal error code from the actual decryption failure message.
|
// Check if we should recreate the session
|
||||||
// Sent in the retry receipt so the peer (even another InfiniteAPI instance)
|
let shouldRecreateSession = false
|
||||||
// knows the exact failure type and can recreate the session immediately
|
let recreateReason = ''
|
||||||
// instead of falling back to the 1-hour timeout.
|
|
||||||
//
|
if (enableAutoSessionRecreation && messageRetryManager && retryCount >= 1) {
|
||||||
// Codes mirror RetryReason enum in message-retry-manager.ts:
|
try {
|
||||||
// 0 = UnknownError | 1 = NoSession | 2 = InvalidKey
|
// Check if we have a session with this JID
|
||||||
// 3 = InvalidKeyId | 4 = InvalidMessage | 7 = BadMac
|
const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
|
||||||
//
|
const hasSession = await signalRepository.validateSession(fromJid)
|
||||||
// Uses DECRYPTION_RETRY_CONFIG error lists (single source of truth in
|
|
||||||
// decode-wa-message.ts) so additions to those lists are picked up here
|
// Extract error code from retry node if present (for MAC error detection)
|
||||||
// automatically.
|
const retryNode = getBinaryNodeChild(node, 'retry')
|
||||||
//
|
const errorAttr = retryNode?.attrs?.error
|
||||||
// NOTE: We do NOT delete the session here (receiver side). The Signal Protocol
|
const errorCode = messageRetryManager.parseRetryErrorCode(errorAttr)
|
||||||
// recovers automatically when the sender's pkmsg arrives — it overwrites the
|
|
||||||
// corrupted session. Deleting prematurely creates a race window where no session
|
const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists, errorCode)
|
||||||
// exists, which can cause "No Session" errors on concurrent messages.
|
shouldRecreateSession = result.recreate
|
||||||
const retryErrorCode = (() => {
|
recreateReason = result.reason
|
||||||
if (!decryptionError) return RetryReason.UnknownError
|
|
||||||
// Bad MAC must be checked first — it is also in corruptedSessionErrors
|
if (shouldRecreateSession) {
|
||||||
// but warrants the more specific code 7 over the generic code 4.
|
logger.debug({ fromJid, retryCount, reason: recreateReason, errorCode }, 'recreating session for retry')
|
||||||
if (decryptionError.includes(BAD_MAC_ERROR_TEXT)) return RetryReason.SignalErrorBadMac
|
// Delete existing session to force recreation
|
||||||
// MessageCounterError and other corrupted-session variants
|
// CRITICAL: Use same transaction key as encrypt/decrypt operations to prevent race
|
||||||
if (DECRYPTION_RETRY_CONFIG.corruptedSessionErrors.some(e => decryptionError.includes(e))) return RetryReason.SignalErrorInvalidMessage
|
// Using meId ensures this delete serializes with sendMessage() and other session operations
|
||||||
// Missing / invalid session record
|
await authState.keys.transaction(async () => {
|
||||||
if (DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(e => decryptionError.includes(e)) ||
|
await authState.keys.set({ session: { [sessionId]: null } })
|
||||||
/no\s+(open\s+)?sessions?/i.test(decryptionError)) return RetryReason.SignalErrorNoSession
|
}, authState.creds.me?.id || 'session-operation')
|
||||||
// PreKey / key-id errors
|
forceIncludeKeys = true
|
||||||
if (/pre\s*key/i.test(decryptionError)) return RetryReason.SignalErrorInvalidKeyId
|
}
|
||||||
// Identity / key errors
|
} catch (error) {
|
||||||
if (/invalid\s*key|untrusted\s*identity/i.test(decryptionError)) return RetryReason.SignalErrorInvalidKey
|
logger.warn({ error, fromJid }, 'failed to check session recreation')
|
||||||
return RetryReason.UnknownError
|
}
|
||||||
})()
|
}
|
||||||
|
|
||||||
if (retryCount <= 2) {
|
if (retryCount <= 2) {
|
||||||
// Use new retry manager for phone requests if available
|
// Use new retry manager for phone requests if available
|
||||||
@@ -1408,7 +1383,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
id: node.attrs.id!,
|
id: node.attrs.id!,
|
||||||
t: node.attrs.t!,
|
t: node.attrs.t!,
|
||||||
v: '1',
|
v: '1',
|
||||||
error: retryErrorCode.toString()
|
// ADD ERROR FIELD
|
||||||
|
error: '0'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1427,7 +1403,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
receipt.attrs.participant = node.attrs.participant
|
receipt.attrs.participant = node.attrs.participant
|
||||||
}
|
}
|
||||||
|
|
||||||
if (retryCount > 1 || forceIncludeKeys) {
|
if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
|
||||||
const { update, preKeys } = await getNextPreKeys(authState, 1)
|
const { update, preKeys } = await getNextPreKeys(authState, 1)
|
||||||
|
|
||||||
const [keyId] = Object.keys(preKeys)
|
const [keyId] = Object.keys(preKeys)
|
||||||
@@ -1455,58 +1431,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
}, authState?.creds?.me?.id || 'sendRetryRequest')
|
}, authState?.creds?.me?.id || 'sendRetryRequest')
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Fire-and-forget tctoken re-issuance after a peer's device identity changed.
|
|
||||||
* Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in PARALLEL with the
|
|
||||||
* session refresh (not after it).
|
|
||||||
*
|
|
||||||
* Why parallel and not sequential:
|
|
||||||
* - WA Web invokes this BEFORE assertSessions to maximise the chance the contact
|
|
||||||
* has a fresh tctoken by the time the next outbound send executes.
|
|
||||||
* - Running after assertSessions (the fork's previous behaviour) races with the
|
|
||||||
* next send and risks error 463 when the contact reinstalls and the user replies
|
|
||||||
* immediately afterwards.
|
|
||||||
*
|
|
||||||
* Gated on `entry.senderTimestamp` (we previously issued a token to this peer in the
|
|
||||||
* current bucket window). Preserves the existing senderTimestamp instead of issuing
|
|
||||||
* a fresh one — keeps WA Web's bucket coalescing semantics: same token, same window.
|
|
||||||
*/
|
|
||||||
const reissueTcTokenAfterIdentityChange = (from: string): void => {
|
|
||||||
void (async () => {
|
|
||||||
const normalizedJid = jidNormalizedUser(from)
|
|
||||||
const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN)
|
|
||||||
const tcTokenData = await authState.keys.get('tctoken', [tcJid])
|
|
||||||
const senderTs = tcTokenData?.[tcJid]?.senderTimestamp
|
|
||||||
|
|
||||||
if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
logTcToken('reissue', { jid: normalizedJid, reason: 'identity_changed', senderTimestamp: senderTs })
|
|
||||||
const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
|
|
||||||
const issueJid = await resolveIssuanceJid(
|
|
||||||
normalizedJid,
|
|
||||||
sock.serverProps.lidTrustedTokenIssueToLid,
|
|
||||||
getLIDForPN,
|
|
||||||
getPNForLID
|
|
||||||
)
|
|
||||||
const result = await getPrivacyTokens([issueJid], senderTs)
|
|
||||||
await storeTcTokensFromIqResult({
|
|
||||||
result,
|
|
||||||
fallbackJid: tcJid,
|
|
||||||
keys: authState.keys,
|
|
||||||
getLIDForPN,
|
|
||||||
onNewJidStored: storedJid => {
|
|
||||||
tcTokenKnownJids.add(storedJid)
|
|
||||||
scheduleTcTokenIndexSave()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
logTcToken('reissue_ok', { jid: normalizedJid, reason: 'identity_changed' })
|
|
||||||
})().catch(err => {
|
|
||||||
logTcToken('reissue_fail', { jid: from, error: err?.message })
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleEncryptNotification = async (node: BinaryNode) => {
|
const handleEncryptNotification = async (node: BinaryNode) => {
|
||||||
const from = node.attrs.from
|
const from = node.attrs.from
|
||||||
if (from === S_WHATSAPP_NET) {
|
if (from === S_WHATSAPP_NET) {
|
||||||
@@ -1516,8 +1440,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count')
|
logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count')
|
||||||
if (shouldUploadMorePreKeys) {
|
if (shouldUploadMorePreKeys) {
|
||||||
// Top-up back to INITIAL_PREKEY_COUNT so the pool is always restored to full size
|
await uploadPreKeys()
|
||||||
await uploadPreKeys(Math.max(1, INITIAL_PREKEY_COUNT - count))
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const result = await handleIdentityChange(node, {
|
const result = await handleIdentityChange(node, {
|
||||||
@@ -1526,12 +1449,57 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
validateSession: signalRepository.validateSession,
|
validateSession: signalRepository.validateSession,
|
||||||
assertSessions,
|
assertSessions,
|
||||||
debounceCache: identityAssertDebounce,
|
debounceCache: identityAssertDebounce,
|
||||||
logger,
|
logger
|
||||||
// Fire reissue in parallel with the session refresh, NOT after it.
|
|
||||||
// See reissueTcTokenAfterIdentityChange doc for the rationale.
|
|
||||||
onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// When a session is refreshed (identity change), re-issue tctoken fire-and-forget
|
||||||
|
// WABA Android: reissue stores senderTimestamp + realIssueTimestamp after IQ success
|
||||||
|
if (result.action === 'session_refreshed') {
|
||||||
|
const normalizedJid = jidNormalizedUser(from)
|
||||||
|
resolveTcTokenJid(normalizedJid, getLIDForPN)
|
||||||
|
.then(async tcJid => {
|
||||||
|
const tcData = await authState.keys.get('tctoken', [tcJid])
|
||||||
|
const entry = tcData[tcJid]
|
||||||
|
if (entry?.token?.length && !isTcTokenExpired(entry.timestamp)) {
|
||||||
|
const senderTs = unixTimestampSeconds()
|
||||||
|
logTcToken('reissue', { jid: normalizedJid, reason: 'session_refreshed' })
|
||||||
|
getPrivacyTokens([normalizedJid], senderTs)
|
||||||
|
.then(async (iqResult) => {
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result: iqResult,
|
||||||
|
fallbackJid: normalizedJid,
|
||||||
|
keys: authState.keys,
|
||||||
|
getLIDForPN,
|
||||||
|
onNewJidStored: (storedJid) => {
|
||||||
|
tcTokenKnownJids.add(storedJid)
|
||||||
|
scheduleTcTokenIndexSave()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// Persist senderTimestamp + realIssueTimestamp after IQ success
|
||||||
|
const currentData = await authState.keys.get('tctoken', [tcJid])
|
||||||
|
const currentEntry = currentData[tcJid]
|
||||||
|
await authState.keys.set({
|
||||||
|
tctoken: {
|
||||||
|
[tcJid]: {
|
||||||
|
...currentEntry,
|
||||||
|
token: currentEntry?.token ?? Buffer.alloc(0),
|
||||||
|
senderTimestamp: senderTs,
|
||||||
|
realIssueTimestamp: 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
logTcToken('reissue_ok', { jid: normalizedJid, reason: 'session_refreshed' })
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
logTcToken('reissue_fail', { jid: normalizedJid, error: err?.message })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* ignore resolution errors */
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
if (result.action === 'no_identity_node') {
|
if (result.action === 'no_identity_node') {
|
||||||
logger.info({ node }, 'unknown encrypt notification')
|
logger.info({ node }, 'unknown encrypt notification')
|
||||||
}
|
}
|
||||||
@@ -2152,6 +2120,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
if (resolvedRemoteJid) key.remoteJid = resolvedRemoteJid
|
if (resolvedRemoteJid) key.remoteJid = resolvedRemoteJid
|
||||||
if (resolvedParticipant) key.participant = resolvedParticipant
|
if (resolvedParticipant) key.participant = resolvedParticipant
|
||||||
|
|
||||||
|
if (shouldIgnoreJid(remoteJid!) && remoteJid !== S_WHATSAPP_NET) {
|
||||||
|
logger.trace({ remoteJid }, 'ignoring receipt from jid')
|
||||||
|
await sendMessageAck(node)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const ids = [attrs.id!]
|
const ids = [attrs.id!]
|
||||||
if (Array.isArray(content)) {
|
if (Array.isArray(content)) {
|
||||||
const items = getBinaryNodeChildren(content[0], 'item')
|
const items = getBinaryNodeChildren(content[0], 'item')
|
||||||
@@ -2227,6 +2201,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const handleNotification = async (node: BinaryNode) => {
|
const handleNotification = async (node: BinaryNode) => {
|
||||||
const remoteJid = node.attrs.from
|
const remoteJid = node.attrs.from
|
||||||
|
if (shouldIgnoreJid(remoteJid!) && remoteJid !== S_WHATSAPP_NET) {
|
||||||
|
logger.trace({ remoteJid }, 'ignored notification')
|
||||||
|
await sendMessageAck(node)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
@@ -2240,7 +2219,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
fromMe,
|
fromMe,
|
||||||
participant: node.attrs.participant,
|
participant: node.attrs.participant,
|
||||||
participantAlt,
|
participantAlt,
|
||||||
participantUsername: node.attrs.participant_username,
|
|
||||||
addressingMode,
|
addressingMode,
|
||||||
id: node.attrs.id,
|
id: node.attrs.id,
|
||||||
...(msg.key || {})
|
...(msg.key || {})
|
||||||
@@ -2249,10 +2227,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
msg.messageTimestamp = +node.attrs.t!
|
msg.messageTimestamp = +node.attrs.t!
|
||||||
|
|
||||||
const fullMsg = proto.WebMessageInfo.fromObject(msg) as WAMessage
|
const fullMsg = proto.WebMessageInfo.fromObject(msg) as WAMessage
|
||||||
// Preserve custom WAMessageKey fields (participantAlt, participantUsername,
|
|
||||||
// addressingMode) that proto.WebMessageInfo.fromObject strips because
|
|
||||||
// they aren't part of the proto.MessageKey schema.
|
|
||||||
fullMsg.key = msg.key
|
|
||||||
await upsertMessage(fullMsg, 'append')
|
await upsertMessage(fullMsg, 'append')
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -2263,59 +2237,23 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleMessage = async (node: BinaryNode) => {
|
const handleMessage = async (node: BinaryNode) => {
|
||||||
const encNode = getBinaryNodeChild(node, 'enc')
|
if (shouldIgnoreJid(node.attrs.from!) && node.attrs.from !== S_WHATSAPP_NET) {
|
||||||
const unavailableNode = getBinaryNodeChild(node, 'unavailable')
|
logger.trace({ from: node.attrs.from }, 'ignored message')
|
||||||
|
// Send a clean ACK (no error code) so the server considers the
|
||||||
// msmsg block removed — allow msmsg decryption (required for view-once on linked devices)
|
// message delivered. Using error 500 (UnhandledError) previously
|
||||||
if (unavailableNode?.attrs?.type === 'view_once') {
|
// caused the server to retry delivery, generating duplicate traffic.
|
||||||
const { fullMessage: voMsg } = decryptMessageNode(
|
|
||||||
node,
|
|
||||||
authState.creds.me!.id,
|
|
||||||
authState.creds.me!.lid || '',
|
|
||||||
signalRepository,
|
|
||||||
logger,
|
|
||||||
)
|
|
||||||
voMsg.key.isViewOnce = true
|
|
||||||
|
|
||||||
// Try to request the actual view-once content from the primary phone via PDO
|
|
||||||
// The phone may resend the full media (url, mediaKey, directPath, etc.)
|
|
||||||
console.log(`[VO_PDO] Requesting view-once content via PDO for ${voMsg.key.id} from ${voMsg.key.remoteJid}`)
|
|
||||||
try {
|
|
||||||
const requestId = await requestPlaceholderResend(voMsg.key, {
|
|
||||||
key: { ...voMsg.key },
|
|
||||||
pushName: voMsg.pushName,
|
|
||||||
messageTimestamp: voMsg.messageTimestamp,
|
|
||||||
participant: voMsg.key.participant,
|
|
||||||
participantAlt: voMsg.key.participantAlt
|
|
||||||
})
|
|
||||||
if (requestId && requestId !== 'RESOLVED') {
|
|
||||||
console.log(`[VO_PDO] PDO request sent! requestId=${requestId} — waiting for phone to resend`)
|
|
||||||
} else if (requestId === 'RESOLVED') {
|
|
||||||
console.log(`[VO_PDO] Message arrived during PDO delay!`)
|
|
||||||
} else {
|
|
||||||
console.log(`[VO_PDO] Already requested or no response`)
|
|
||||||
}
|
|
||||||
} catch (err: any) {
|
|
||||||
console.log(`[VO_PDO] PDO request failed: ${err.message} — falling back to placeholder`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Emit placeholder immediately so consumers see the notification
|
|
||||||
// If PDO succeeds, the real message will arrive via messages.upsert later
|
|
||||||
voMsg.message = {
|
|
||||||
viewOnceMessage: {
|
|
||||||
message: {
|
|
||||||
imageMessage: {
|
|
||||||
viewOnce: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const upsertType = node.attrs.offline ? 'append' : 'notify'
|
|
||||||
await upsertMessage(voMsg, upsertType)
|
|
||||||
await sendMessageAck(node)
|
await sendMessageAck(node)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const encNode = getBinaryNodeChild(node, 'enc')
|
||||||
|
// TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
|
||||||
|
if (encNode?.attrs.type === 'msmsg') {
|
||||||
|
logger.debug({ key: node.attrs.key }, 'ignored msmsg')
|
||||||
|
await sendMessageAck(node, NACK_REASONS.MissingMessageSecret)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
fullMessage: msg,
|
fullMessage: msg,
|
||||||
category,
|
category,
|
||||||
@@ -2330,54 +2268,44 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
const alt = msg.key.participantAlt || msg.key.remoteJidAlt
|
const alt = msg.key.participantAlt || msg.key.remoteJidAlt
|
||||||
// Handle LID/PN mappings with optimized hot-path:
|
// Handle LID/PN mappings with hybrid approach:
|
||||||
// - storeLIDPNMappings is fire-and-forget (background) — does NOT block decrypt
|
// - Store mapping operation runs in background (non-critical for decrypt)
|
||||||
// - migrateSession is SYNC (await) — REQUIRED for decrypt to find session
|
// - Session migration MUST complete before decrypt() to avoid "No session record" errors
|
||||||
//
|
// This addresses Codex/Copilot review concerns about race conditions with decrypt()
|
||||||
// SAFETY: normalizeMessageJids has a fast-path that uses key.*Alt directly without
|
|
||||||
// hitting the store, so the just-arrived message normalizes correctly even before
|
|
||||||
// the background store completes. Subsequent messages in the same chat hit the
|
|
||||||
// store after the background write is done (ms later).
|
|
||||||
//
|
|
||||||
// Pre-check (getPNForLID/getLIDForPN) was removed — storeLIDPNMappings has internal
|
|
||||||
// LRU cache + dedup, the pre-check was a redundant store round-trip per inbound
|
|
||||||
// message that added latency under load.
|
|
||||||
//
|
|
||||||
// HISTORICAL: this restores the intent of d73cd28d39 (2026-02-03) which was
|
|
||||||
// partially reverted by c3fc792351 the same day due to a race-condition concern
|
|
||||||
// with migrateSession (kept sync here). storeLIDPNMappings was over-protected:
|
|
||||||
// it persists a mapping that downstream consumers can re-derive from key.*Alt,
|
|
||||||
// while migrateSession actually moves the Signal session record that decrypt()
|
|
||||||
// will load microseconds later — those two have very different criticality.
|
|
||||||
//
|
|
||||||
// DO NOT make migrateSession async — decrypt() depends on the session being at
|
|
||||||
// the correct identifier (LID vs PN) when it runs. Other code paths (USync
|
|
||||||
// device lookup in messages-send.ts) create LID/PN mappings without migrating
|
|
||||||
// the session, so we cannot skip migration even when the mapping already exists.
|
|
||||||
if (!!alt) {
|
if (!!alt) {
|
||||||
const altServer = jidDecode(alt)?.server
|
const altServer = jidDecode(alt)?.server
|
||||||
const primaryJid = msg.key.participant || msg.key.remoteJid!
|
const primaryJid = msg.key.participant || msg.key.remoteJid!
|
||||||
|
|
||||||
if (altServer === 'lid') {
|
if (altServer === 'lid') {
|
||||||
// Fire-and-forget: storeLIDPNMappings has internal cache+dedup,
|
// Check if mapping already exists to avoid unnecessary storage operations
|
||||||
// pre-check (getPNForLID) was redundant.
|
const existingMapping = await signalRepository.lidMapping.getPNForLID(alt)
|
||||||
signalRepository.lidMapping
|
if (!existingMapping) {
|
||||||
.storeLIDPNMappings([{ lid: alt, pn: primaryJid }])
|
// MUST await: normalizeMessageJids() runs after this and needs the mapping
|
||||||
.catch(error => logger.warn({ error, alt, primaryJid }, 'background LID mapping store failed'))
|
// in the LIDMappingStore to resolve LID→PN for events delivered to consumers
|
||||||
|
await signalRepository.lidMapping
|
||||||
|
.storeLIDPNMappings([{ lid: alt, pn: primaryJid }])
|
||||||
|
.catch(error => logger.warn({ error, alt, primaryJid }, 'LID mapping storage failed'))
|
||||||
|
}
|
||||||
|
|
||||||
// CRITICAL: ALWAYS migrate session SYNC, even if mapping exists.
|
// CRITICAL: ALWAYS migrate session, even if mapping exists
|
||||||
// Other code paths (e.g., USync device lookup in messages-send.ts) may create
|
// Other code paths (e.g., USync device lookup in messages-send.ts:310-319)
|
||||||
// mappings via storeLIDPNMappings() without calling migrateSession(). This
|
// may create mappings via storeLIDPNMappings() without calling migrateSession()
|
||||||
// leaves sessions under PN format while decrypt() expects LID format.
|
// This leaves sessions under PN format while decrypt() expects LID format
|
||||||
// Skipping migration based on mapping existence causes "No session record" errors.
|
// Skipping migration based on mapping existence causes "No session record" errors
|
||||||
await signalRepository.migrateSession(primaryJid, alt)
|
await signalRepository.migrateSession(primaryJid, alt)
|
||||||
} else {
|
} else {
|
||||||
// Fire-and-forget: same rationale as above.
|
// Check if reverse mapping exists
|
||||||
signalRepository.lidMapping
|
const existingMapping = await signalRepository.lidMapping.getLIDForPN(alt)
|
||||||
.storeLIDPNMappings([{ lid: primaryJid, pn: alt }])
|
if (!existingMapping) {
|
||||||
.catch(error => logger.warn({ error, alt, primaryJid }, 'background LID mapping store failed'))
|
// MUST await: normalizeMessageJids() runs after this and needs the mapping
|
||||||
|
// in the LIDMappingStore to resolve LID→PN for events delivered to consumers
|
||||||
|
await signalRepository.lidMapping
|
||||||
|
.storeLIDPNMappings([{ lid: primaryJid, pn: alt }])
|
||||||
|
.catch(error => logger.warn({ error, alt, primaryJid }, 'LID mapping storage failed'))
|
||||||
|
}
|
||||||
|
|
||||||
// CRITICAL: ALWAYS migrate session SYNC.
|
// CRITICAL: ALWAYS migrate session, even if mapping exists
|
||||||
|
// Same reasoning as above - mapping existence doesn't guarantee session migration
|
||||||
await signalRepository.migrateSession(alt, primaryJid)
|
await signalRepository.migrateSession(alt, primaryJid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2439,23 +2367,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
{ msgId: msg.key?.id, messageType },
|
{ msgId: msg.key?.id, messageType },
|
||||||
'CTWA: Skipping placeholder resend for unavailable fanout type'
|
'CTWA: Skipping placeholder resend for unavailable fanout type'
|
||||||
)
|
)
|
||||||
// For view-once: emit the message with a viewOnceMessage placeholder
|
|
||||||
// so consumers (zpro, etc.) can detect and display it.
|
|
||||||
// Include a message wrapper so isValidMsg accepts it.
|
|
||||||
if (messageType === 'view_once_unavailable_fanout') {
|
|
||||||
msg.key.isViewOnce = true
|
|
||||||
msg.message = {
|
|
||||||
viewOnceMessage: {
|
|
||||||
message: {
|
|
||||||
imageMessage: {
|
|
||||||
viewOnce: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const upsertType = node.attrs.offline ? 'append' : 'notify'
|
|
||||||
await upsertMessage(msg, upsertType)
|
|
||||||
}
|
|
||||||
metrics.ctwaRecoveryFailures.inc({ reason: 'unavailable_fanout' })
|
metrics.ctwaRecoveryFailures.inc({ reason: 'unavailable_fanout' })
|
||||||
return sendMessageAck(node)
|
return sendMessageAck(node)
|
||||||
}
|
}
|
||||||
@@ -2594,7 +2505,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const encNode = getBinaryNodeChild(node, 'enc')
|
const encNode = getBinaryNodeChild(node, 'enc')
|
||||||
await sendRetryRequest(node, !encNode, errorMessage)
|
await sendRetryRequest(node, !encNode)
|
||||||
if (retryRequestDelayMs) {
|
if (retryRequestDelayMs) {
|
||||||
await delay(retryRequestDelayMs)
|
await delay(retryRequestDelayMs)
|
||||||
}
|
}
|
||||||
@@ -2603,7 +2514,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
// Still attempt retry even if pre-key upload failed
|
// Still attempt retry even if pre-key upload failed
|
||||||
try {
|
try {
|
||||||
const encNode = getBinaryNodeChild(node, 'enc')
|
const encNode = getBinaryNodeChild(node, 'enc')
|
||||||
await sendRetryRequest(node, !encNode, errorMessage)
|
await sendRetryRequest(node, !encNode)
|
||||||
} catch (retryErr) {
|
} catch (retryErr) {
|
||||||
logger.error({ retryErr }, 'Failed to send retry after error handling')
|
logger.error({ retryErr }, 'Failed to send retry after error handling')
|
||||||
}
|
}
|
||||||
@@ -2637,11 +2548,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
await sendReceipt(msg.key.remoteJid!, participant!, [msg.key.id!], type)
|
await sendReceipt(msg.key.remoteJid!, participant!, [msg.key.id!], type)
|
||||||
|
|
||||||
// NOTE: do NOT send view_once_read from a linked device (API).
|
|
||||||
// WA shows view-once as view_once_unavailable_fanout on linked devices — only the
|
|
||||||
// primary phone sends view_once_read when the user actually opens it.
|
|
||||||
// Sending it from a linked device causes WA to flag the account and disables view-once.
|
|
||||||
|
|
||||||
// send ack for history message
|
// send ack for history message
|
||||||
const isAnyHistoryMsg = getHistoryMsg(msg.message!)
|
const isAnyHistoryMsg = getHistoryMsg(msg.message!)
|
||||||
if (isAnyHistoryMsg) {
|
if (isAnyHistoryMsg) {
|
||||||
@@ -3126,40 +3032,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
identifier: string,
|
identifier: string,
|
||||||
exec: (node: BinaryNode) => Promise<void>
|
exec: (node: BinaryNode) => Promise<void>
|
||||||
) => {
|
) => {
|
||||||
// Fast path: ack and drop ignored JIDs before entering the buffer/queue.
|
|
||||||
// Skips type='call' so call events are never silently dropped via
|
|
||||||
// shouldIgnoreJid (preserves InfiniteAPI's pre-existing behavior).
|
|
||||||
// Wrapped in try/catch so a throw from shouldIgnoreJid (user callback)
|
|
||||||
// or sendMessageAck (e.g. websocket closed) is routed through
|
|
||||||
// onUnexpectedError instead of becoming an unhandled rejection —
|
|
||||||
// matches the protection processNodeWithBuffer provides.
|
|
||||||
if (type !== 'call') {
|
|
||||||
try {
|
|
||||||
const from = node.attrs.from
|
|
||||||
let ignoreJid = from
|
|
||||||
if (type === 'receipt' && from) {
|
|
||||||
const attrs = node.attrs
|
|
||||||
const isLid = attrs.from!.includes('lid')
|
|
||||||
const isNodeFromMe = areJidsSameUser(
|
|
||||||
attrs.participant || attrs.from,
|
|
||||||
isLid ? authState.creds.me?.lid : authState.creds.me?.id
|
|
||||||
)
|
|
||||||
ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
|
|
||||||
// Plain ack (no NACK error code) preserves InfiniteAPI's prior
|
|
||||||
// behavior — ignored stanzas are an intentional drop, not a
|
|
||||||
// processing failure, so we don't want server-side retries.
|
|
||||||
await sendMessageAck(node)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
onUnexpectedError(error as Error, identifier)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const isOffline = !!node.attrs.offline
|
const isOffline = !!node.attrs.offline
|
||||||
|
|
||||||
if (isOffline) {
|
if (isOffline) {
|
||||||
@@ -3258,24 +3130,19 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
// Await index load first — prevents overwriting a more complete persisted index
|
// Await index load first — prevents overwriting a more complete persisted index
|
||||||
// if the connection closes before the initial load finishes.
|
// if the connection closes before the initial load finishes.
|
||||||
tcTokenIndexLoaded
|
tcTokenIndexLoaded
|
||||||
.then(async () => {
|
.then(() => {
|
||||||
try {
|
Promise.resolve(
|
||||||
// Same merge-with-persisted invariant as scheduleTcTokenIndexSave —
|
authState.keys.set({
|
||||||
// other layers may have written cross-layer JIDs to the index since
|
|
||||||
// our in-memory set was last updated.
|
|
||||||
const merged = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids)
|
|
||||||
await authState.keys.set({
|
|
||||||
tctoken: {
|
tctoken: {
|
||||||
...merged,
|
|
||||||
[TC_TOKEN_INDEX_KEY]: {
|
[TC_TOKEN_INDEX_KEY]: {
|
||||||
...merged[TC_TOKEN_INDEX_KEY],
|
token: Buffer.from(JSON.stringify([...tcTokenKnownJids]), 'utf8'),
|
||||||
timestamp: unixTimestampSeconds().toString()
|
timestamp: unixTimestampSeconds().toString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch {
|
).catch(() => {
|
||||||
/* non-critical */
|
/* non-critical */
|
||||||
}
|
})
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
/* non-critical */
|
/* non-critical */
|
||||||
|
|||||||
+168
-1214
File diff suppressed because it is too large
Load Diff
@@ -123,11 +123,11 @@ export const makeNewsletterSocket = (config: SocketConfig) => {
|
|||||||
},
|
},
|
||||||
|
|
||||||
newsletterMute: (jid: string) => {
|
newsletterMute: (jid: string) => {
|
||||||
return executeWMexQuery({ input: { newsletter_id: jid, type: 'MUTE_ADMIN_ACTIVITY', value: 'OFF' } }, QueryIds.MUTE, XWAPaths.xwa2_newsletter_mute_v2)
|
return executeWMexQuery({ newsletter_id: jid }, QueryIds.MUTE, XWAPaths.xwa2_newsletter_mute_v2)
|
||||||
},
|
},
|
||||||
|
|
||||||
newsletterUnmute: (jid: string) => {
|
newsletterUnmute: (jid: string) => {
|
||||||
return executeWMexQuery({ input: { newsletter_id: jid, type: 'MUTE_ADMIN_ACTIVITY', value: 'ON' } }, QueryIds.UNMUTE, XWAPaths.xwa2_newsletter_unmute_v2)
|
return executeWMexQuery({ newsletter_id: jid }, QueryIds.UNMUTE, XWAPaths.xwa2_newsletter_unmute_v2)
|
||||||
},
|
},
|
||||||
|
|
||||||
newsletterUpdateName: async (jid: string, name: string) => {
|
newsletterUpdateName: async (jid: string, name: string) => {
|
||||||
|
|||||||
+8
-28
@@ -701,12 +701,10 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prevent multiple concurrent uploads — if one is already running, wait for it and return:
|
// Prevent multiple concurrent uploads
|
||||||
// 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const uploadLogic = async () => {
|
const uploadLogic = async () => {
|
||||||
@@ -786,15 +784,14 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
try {
|
try {
|
||||||
let count = 0
|
let count = 0
|
||||||
const preKeyCount = await getAvailablePreKeysOnServer()
|
const preKeyCount = await getAvailablePreKeysOnServer()
|
||||||
// How many to upload: top-up to INITIAL_PREKEY_COUNT from whatever remains on server
|
if (preKeyCount === 0) count = INITIAL_PREKEY_COUNT
|
||||||
count = Math.max(0, INITIAL_PREKEY_COUNT - preKeyCount)
|
else count = MIN_PREKEY_COUNT
|
||||||
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}`)
|
||||||
|
|
||||||
// Trigger upload when below the replenishment threshold, not when count < topUp amount
|
const lowServerCount = preKeyCount <= count
|
||||||
const lowServerCount = preKeyCount < MIN_PREKEY_COUNT
|
|
||||||
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
|
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
|
||||||
|
|
||||||
const shouldUpload = lowServerCount || missingCurrentPreKey
|
const shouldUpload = lowServerCount || missingCurrentPreKey
|
||||||
@@ -1154,7 +1151,7 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
// Decrement active connections
|
// Decrement active connections
|
||||||
decrementActiveConnections()
|
decrementActiveConnections()
|
||||||
|
|
||||||
clearTimeout(keepAliveReq)
|
clearInterval(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()
|
||||||
@@ -1265,16 +1262,8 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const startKeepAliveRequest = () => {
|
const startKeepAliveRequest = () =>
|
||||||
// Use recursive setTimeout with ±15% jitter to match WA Desktop behaviour
|
(keepAliveReq = setInterval(() => {
|
||||||
// (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()
|
||||||
}
|
}
|
||||||
@@ -1286,7 +1275,6 @@ 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
|
// query() wraps the ping in the query circuit breaker — when that breaker is
|
||||||
@@ -1309,15 +1297,7 @@ 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({
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ 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,8 +27,6 @@ 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
|
||||||
@@ -81,7 +79,6 @@ 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
|
||||||
}
|
}
|
||||||
@@ -89,7 +86,6 @@ 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
|
||||||
@@ -189,8 +185,6 @@ 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,20 +20,17 @@ 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 */
|
||||||
@@ -59,7 +56,6 @@ 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 {
|
||||||
|
|||||||
+2
-15
@@ -19,9 +19,7 @@ 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
|
||||||
@@ -157,7 +155,6 @@ export type MessageReceiptType =
|
|||||||
| 'sender'
|
| 'sender'
|
||||||
| 'inactive'
|
| 'inactive'
|
||||||
| 'played'
|
| 'played'
|
||||||
| 'view_once_read'
|
|
||||||
| undefined
|
| undefined
|
||||||
|
|
||||||
export type MediaConnInfo = {
|
export type MediaConnInfo = {
|
||||||
@@ -181,8 +178,6 @@ 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 */
|
||||||
@@ -995,16 +990,8 @@ export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions &
|
|||||||
|
|
||||||
export type WAMediaUploadFunction = (
|
export type WAMediaUploadFunction = (
|
||||||
encFilePath: string,
|
encFilePath: string,
|
||||||
opts: { fileEncSha256B64: string; mediaType: MediaType; timeoutMs?: number; newsletter?: boolean }
|
opts: { fileEncSha256B64: string; mediaType: MediaType; timeoutMs?: number }
|
||||||
) => Promise<{
|
) => Promise<{ mediaUrl: string; directPath: string; meta_hmac?: string; ts?: number; fbid?: number }>
|
||||||
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_update_user_setting',
|
xwa2_newsletter_mute_v2 = 'xwa2_newsletter_mute_v2',
|
||||||
xwa2_newsletter_unmute_v2 = 'xwa2_newsletter_update_user_setting',
|
xwa2_newsletter_unmute_v2 = 'xwa2_newsletter_unmute_v2',
|
||||||
xwa2_newsletter_follow = 'xwa2_newsletter_join_v2',
|
xwa2_newsletter_follow = 'xwa2_newsletter_follow',
|
||||||
xwa2_newsletter_unfollow = 'xwa2_newsletter_leave_v2',
|
xwa2_newsletter_unfollow = 'xwa2_newsletter_unfollow',
|
||||||
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 = '24404358912487870',
|
FOLLOW = '7871414976211147',
|
||||||
UNFOLLOW = '9767147403369991',
|
UNFOLLOW = '7238632346214362',
|
||||||
MUTE = '31938993655691868',
|
MUTE = '29766401636284406',
|
||||||
UNMUTE = '31938993655691868',
|
UNMUTE = '9864994326891137',
|
||||||
ADMIN_COUNT = '7130823597031706',
|
ADMIN_COUNT = '7130823597031706',
|
||||||
CHANGE_OWNER = '7341777602580933',
|
CHANGE_OWNER = '7341777602580933',
|
||||||
DEMOTE = '6551828931592903',
|
DEMOTE = '6551828931592903',
|
||||||
|
|||||||
@@ -1083,7 +1083,6 @@ 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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -242,14 +242,10 @@ 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 } : {})
|
||||||
}
|
}
|
||||||
@@ -396,23 +392,6 @@ 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
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import EventEmitter from 'events'
|
import EventEmitter from 'events'
|
||||||
import { proto } from '../../WAProto/index.js'
|
|
||||||
import type {
|
import type {
|
||||||
BaileysEvent,
|
BaileysEvent,
|
||||||
BaileysEventEmitter,
|
BaileysEventEmitter,
|
||||||
@@ -891,7 +890,6 @@ const makeBufferData = (): BufferedEventData => {
|
|||||||
chats: {},
|
chats: {},
|
||||||
messages: {},
|
messages: {},
|
||||||
contacts: {},
|
contacts: {},
|
||||||
pastParticipants: {},
|
|
||||||
isLatest: false,
|
isLatest: false,
|
||||||
empty: true
|
empty: true
|
||||||
},
|
},
|
||||||
@@ -969,28 +967,6 @@ 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
|
||||||
@@ -1316,10 +1292,6 @@ 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,
|
||||||
|
|||||||
+13
-46
@@ -1,6 +1,5 @@
|
|||||||
import { pipeline } from 'stream/promises'
|
|
||||||
import { promisify } from 'util'
|
import { promisify } from 'util'
|
||||||
import { createInflate, inflate } from 'zlib'
|
import { 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'
|
||||||
@@ -16,8 +15,7 @@ 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 { DEFAULT_ORIGIN } from '../Defaults'
|
import { downloadContentFromMessage } from './messages-media'
|
||||||
import { downloadContentFromMessage, getUrlFromDirectPath } from './messages-media'
|
|
||||||
|
|
||||||
const inflatePromise = promisify(inflate)
|
const inflatePromise = promisify(inflate)
|
||||||
|
|
||||||
@@ -30,15 +28,16 @@ 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 })
|
||||||
// Pipe decrypted stream directly through zlib inflate.
|
const bufferArray: Buffer[] = []
|
||||||
// Avoids allocating an intermediate buffer for the compressed payload —
|
for await (const chunk of stream) {
|
||||||
// memory peaks during 50MB history syncs drop ~50% (PR upstream #2333).
|
bufferArray.push(chunk)
|
||||||
const inflater = createInflate()
|
}
|
||||||
const chunks: Buffer[] = []
|
|
||||||
inflater.on('data', (chunk: Buffer) => chunks.push(chunk))
|
let buffer: Buffer = Buffer.concat(bufferArray)
|
||||||
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
|
||||||
}
|
}
|
||||||
@@ -315,7 +314,6 @@ 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
|
||||||
})
|
})
|
||||||
@@ -361,7 +359,7 @@ export const processHistoryMessage = (item: proto.IHistorySync, logger?: ILogger
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
chats.push(chat)
|
chats.push({ ...chat })
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break
|
||||||
@@ -376,25 +374,10 @@ 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
|
||||||
@@ -425,23 +408,7 @@ export const downloadAndProcessHistorySyncNotification = async (
|
|||||||
historyMsg = await downloadHistory(msg, options)
|
historyMsg = await downloadHistory(msg, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = processHistoryMessage(historyMsg, logger)
|
return 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,16 +57,6 @@ 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -180,19 +170,6 @@ 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)
|
||||||
|
|||||||
@@ -10,13 +10,7 @@ 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 {
|
import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP, type MediaType } from '../Defaults'
|
||||||
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,
|
||||||
@@ -166,7 +160,7 @@ export const extractImageThumb = async (bufferOrFilePath: Readable | Buffer | st
|
|||||||
height: dimensions.height
|
height: dimensions.height
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
|
} else if ('jimp' in lib && (typeof lib.jimp?.Jimp === 'object' || 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,
|
||||||
@@ -618,7 +612,7 @@ export const downloadEncryptedContent = async (
|
|||||||
|
|
||||||
const output = new Transform({
|
const output = new Transform({
|
||||||
transform(chunk, _, callback) {
|
transform(chunk, _, callback) {
|
||||||
let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk
|
let data = Buffer.concat([remainingBytes, chunk])
|
||||||
|
|
||||||
const decryptLength = toSmallestChunkSize(data.length)
|
const decryptLength = toSmallestChunkSize(data.length)
|
||||||
remainingBytes = data.slice(decryptLength)
|
remainingBytes = data.slice(decryptLength)
|
||||||
@@ -687,10 +681,6 @@ 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 = {
|
||||||
@@ -835,21 +825,11 @@ 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, newsletter }) => {
|
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
||||||
// 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:
|
let urls: { mediaUrl: string; directPath: string; meta_hmac?: string; ts?: number; fbid?: number } | undefined
|
||||||
| {
|
|
||||||
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)
|
||||||
@@ -871,11 +851,7 @@ export const getWAUploadToServer = (
|
|||||||
logger.debug(`uploading to "${hostname}"`)
|
logger.debug(`uploading to "${hostname}"`)
|
||||||
|
|
||||||
const auth = encodeURIComponent(uploadInfo.auth)
|
const auth = encodeURIComponent(uploadInfo.auth)
|
||||||
const mediaPath = (newsletter ? NEWSLETTER_MEDIA_PATH_MAP[mediaType] : undefined) || MEDIA_PATH_MAP[mediaType]
|
const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`
|
||||||
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 {
|
||||||
@@ -892,13 +868,11 @@ export const getWAUploadToServer = (
|
|||||||
|
|
||||||
if (result?.url || result?.direct_path) {
|
if (result?.url || result?.direct_path) {
|
||||||
urls = {
|
urls = {
|
||||||
mediaUrl: result.url || result.direct_path!,
|
mediaUrl: result.url!,
|
||||||
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 {
|
||||||
|
|||||||
+62
-117
@@ -41,11 +41,9 @@ 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'
|
||||||
@@ -196,11 +194,10 @@ export const prepareWAMessageMedia = async (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const fileSha256B64 = fileSha256.toString('base64')
|
const fileSha256B64 = fileSha256.toString('base64')
|
||||||
const { directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
|
const { mediaUrl, directPath } = 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)
|
||||||
@@ -208,12 +205,10 @@ 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 intentionally omitted — newsletters use directPath only
|
url: mediaUrl,
|
||||||
directPath,
|
directPath,
|
||||||
fileSha256,
|
fileSha256,
|
||||||
fileLength,
|
fileLength,
|
||||||
thumbnailDirectPath,
|
|
||||||
thumbnailSha256: thumbnailSha256 ? Buffer.from(thumbnailSha256, 'base64') : undefined,
|
|
||||||
...uploadData,
|
...uploadData,
|
||||||
media: undefined
|
media: undefined
|
||||||
})
|
})
|
||||||
@@ -239,7 +234,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 && typeof uploadData.waveform === 'undefined'
|
const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true
|
||||||
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(
|
||||||
@@ -257,9 +252,7 @@ export const prepareWAMessageMedia = async (
|
|||||||
(async () => {
|
(async () => {
|
||||||
const result = await options.upload(encFilePath, {
|
const result = await options.upload(encFilePath, {
|
||||||
fileEncSha256B64,
|
fileEncSha256B64,
|
||||||
// Use mediaTypeOverride for upload path (e.g. 'viewonce-image' → /o1/mms/image)
|
mediaType,
|
||||||
// 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')
|
||||||
@@ -297,7 +290,7 @@ export const prepareWAMessageMedia = async (
|
|||||||
logger?.debug('computed audio duration')
|
logger?.debug('computed audio duration')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (requiresWaveformProcessing && !uploadData.waveform) {
|
if (requiresWaveformProcessing) {
|
||||||
uploadData.waveform = await getAudioWaveform(filePath, logger)
|
uploadData.waveform = await getAudioWaveform(filePath, logger)
|
||||||
logger?.debug('processed waveform')
|
logger?.debug('processed waveform')
|
||||||
}
|
}
|
||||||
@@ -640,59 +633,6 @@ 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 => {
|
||||||
@@ -708,11 +648,6 @@ 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(
|
||||||
@@ -1293,20 +1228,57 @@ export const generateWAMessageContent = async (
|
|||||||
options.logger?.info('Sending CTA buttons as nativeFlowMessage with viewOnceMessage wrapper')
|
options.logger?.info('Sending CTA buttons as nativeFlowMessage with viewOnceMessage wrapper')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Check for nativeCarousel
|
// Check for nativeCarousel — inline handler (validated on Android, iOS, Web)
|
||||||
|
// Direct interactiveMessage at root (field 45), NO viewOnceMessage wrapper,
|
||||||
|
// NO messageContextInfo, NO biz/bot stanza nodes needed
|
||||||
else if (hasNonNullishProperty(message, 'nativeCarousel')) {
|
else if (hasNonNullishProperty(message, 'nativeCarousel')) {
|
||||||
const carouselMsg = message as any
|
const carouselMsg = message as any
|
||||||
const carouselOptions: CarouselMessageOptions = {
|
const cards = carouselMsg.nativeCarousel.cards || []
|
||||||
cards: carouselMsg.nativeCarousel.cards,
|
const title = carouselMsg.nativeCarousel.title || carouselMsg.title
|
||||||
title: carouselMsg.nativeCarousel.title || carouselMsg.title,
|
const text = carouselMsg.text
|
||||||
text: carouselMsg.text,
|
const footer = carouselMsg.footer
|
||||||
footer: carouselMsg.footer
|
|
||||||
|
const carouselCards = await Promise.all(
|
||||||
|
cards.map(async (card: any) => {
|
||||||
|
const hasMedia = !!(card.image || card.video)
|
||||||
|
const header: any = {
|
||||||
|
title: card.title || '',
|
||||||
|
subtitle: card.footer || '',
|
||||||
|
hasMediaAttachment: hasMedia
|
||||||
|
}
|
||||||
|
if (hasMedia && card.image) {
|
||||||
|
const { imageMessage } = await prepareWAMessageMedia({ image: card.image }, options)
|
||||||
|
if (imageMessage && !imageMessage.height) imageMessage.height = 500
|
||||||
|
if (imageMessage && !imageMessage.width) imageMessage.width = 500
|
||||||
|
header.imageMessage = imageMessage
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
header,
|
||||||
|
body: { text: card.body || '' },
|
||||||
|
footer: card.footer ? { text: card.footer } : undefined,
|
||||||
|
nativeFlowMessage: {
|
||||||
|
buttons: (card.buttons || []).map((btn: any) => {
|
||||||
|
switch (btn.type) {
|
||||||
|
case 'url': return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: btn.text, url: btn.url, merchant_url: btn.url }) }
|
||||||
|
case 'copy': return { name: 'cta_copy', buttonParamsJson: JSON.stringify({ display_text: btn.text, copy_code: btn.copyText }) }
|
||||||
|
case 'call': return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: btn.text, phone_number: btn.phoneNumber }) }
|
||||||
|
default: return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: btn.text, id: btn.id }) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
m.interactiveMessage = {
|
||||||
|
header: { title: title || ' ', hasMediaAttachment: false },
|
||||||
|
body: { text: text || '' },
|
||||||
|
footer: footer ? { text: footer } : undefined,
|
||||||
|
carouselMessage: {
|
||||||
|
cards: carouselCards,
|
||||||
|
messageVersion: 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Pass options for media processing if cards have images/videos
|
|
||||||
const generated = await generateCarouselMessage(carouselOptions, options)
|
|
||||||
// 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
|
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
// Check for nativeList
|
// Check for nativeList
|
||||||
@@ -1752,49 +1724,22 @@ export const generateWAMessageContent = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// For view-once media, upload to the one-time CDN (/o1/mms/*) instead of regular CDN
|
m = await prepareWAMessageMedia(message, options)
|
||||||
// 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) {
|
||||||
// Also set viewOnce=true on the inner media message (required by WA app to render as view-once)
|
m = { viewOnceMessage: { message: m } }
|
||||||
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 (
|
if (hasOptionalProperty(message, 'mentions') && message.mentions?.length) {
|
||||||
(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) {
|
if (key && 'contextInfo' in key && !!key.contextInfo) {
|
||||||
key.contextInfo = key.contextInfo || {}
|
key.contextInfo.mentionedJid = message.mentions
|
||||||
if (message.mentions?.length) {
|
} else if (key) {
|
||||||
key.contextInfo.mentionedJid = message.mentions
|
key.contextInfo = {
|
||||||
}
|
mentionedJid: message.mentions
|
||||||
|
|
||||||
if (message.mentionAll) {
|
|
||||||
key.contextInfo.nonJidMentions = 1
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ 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
|
||||||
@@ -63,163 +62,6 @@ 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
|
||||||
@@ -576,12 +418,6 @@ 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
|
||||||
@@ -606,29 +442,6 @@ 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,
|
||||||
@@ -950,19 +763,12 @@ 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
|
|
||||||
}
|
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -971,7 +777,6 @@ 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,
|
||||||
|
|||||||
@@ -46,7 +46,6 @@ 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
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-122
@@ -1,86 +1,12 @@
|
|||||||
import type { SignalKeyStoreWithTransaction } from '../Types'
|
import type { SignalKeyStoreWithTransaction } from '../Types'
|
||||||
import type { BinaryNode } from '../WABinary'
|
import type { BinaryNode } from '../WABinary'
|
||||||
import {
|
import { getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidNormalizedUser } from '../WABinary'
|
||||||
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
|
||||||
@@ -137,43 +63,6 @@ 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[]
|
||||||
@@ -246,13 +135,7 @@ export async function storeTcTokensFromIqResult({
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// In notifications, tokenNode.attrs.jid is OUR own device JID, not the sender's.
|
const rawJid = jidNormalizedUser(tokenNode.attrs.jid || fallbackJid)
|
||||||
// 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]
|
||||||
@@ -275,13 +158,11 @@ export async function storeTcTokensFromIqResult({
|
|||||||
...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
|
// Resets real_issue_timestamp to null when storing a new token
|
||||||
// (UPDATE wa_trusted_contacts_send SET real_issue_timestamp=null)
|
|
||||||
realIssueTimestamp: null
|
realIssueTimestamp: null
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store under resolved storageJid AND under fallbackJid (PN) for reliable lookup
|
// 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 normalizedFallback = jidNormalizedUser(fallbackJid)
|
||||||
const keysToStore: Record<string, typeof tokenEntry | null> = {
|
const keysToStore: Record<string, typeof tokenEntry | null> = {
|
||||||
[storageJid]: tokenEntry
|
[storageJid]: tokenEntry
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ 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
|
||||||
@@ -59,10 +58,7 @@ const getClientPayload = (config: SocketConfig) => {
|
|||||||
userAgent: getUserAgent(config)
|
userAgent: getUserAgent(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Native protocol (WAM\x05) does not use WebInfo — only web protocol does
|
payload.webInfo = getWebInfo(config)
|
||||||
if (PROTOCOL_MODE !== 'native') {
|
|
||||||
payload.webInfo = getWebInfo(config)
|
|
||||||
}
|
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,37 +13,11 @@ export class USyncContactProtocol implements USyncQueryProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getUserElement(user: USyncUser): BinaryNode {
|
getUserElement(user: USyncUser): BinaryNode {
|
||||||
if (user.phone) {
|
//TODO: Implement type / username fields (not yet supported)
|
||||||
return {
|
|
||||||
tag: 'contact',
|
|
||||||
attrs: {},
|
|
||||||
content: user.phone
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
return {
|
||||||
tag: 'contact',
|
tag: 'contact',
|
||||||
attrs: {}
|
attrs: {},
|
||||||
|
content: user.phone
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
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,4 +2,3 @@ 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,12 +6,11 @@ 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; rawId?: number }
|
export type USyncQueryResultList = { [protocol: string]: unknown; id: string }
|
||||||
|
|
||||||
export type USyncQueryResult = {
|
export type USyncQueryResult = {
|
||||||
list: USyncQueryResultList[]
|
list: USyncQueryResultList[]
|
||||||
@@ -69,8 +68,10 @@ 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 parseNodeList = (content: BinaryNode[]): USyncQueryResultList[] =>
|
const listNode = usyncNode ? getBinaryNodeChild(usyncNode, 'list') : undefined
|
||||||
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)
|
||||||
@@ -88,24 +89,15 @@ export class USyncQuery {
|
|||||||
.filter(([, b]) => b !== null) as [string, unknown][]
|
.filter(([, b]) => b !== null) as [string, unknown][]
|
||||||
)
|
)
|
||||||
: {}
|
: {}
|
||||||
const rawIdAttr = node?.attrs?.['raw_id']
|
acc.push({ ...data, 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,9 +130,4 @@ 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,8 +2,6 @@ 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
|
||||||
|
|
||||||
@@ -22,16 +20,6 @@ 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,52 +297,4 @@ 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()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,17 +1,7 @@
|
|||||||
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 {
|
import { buildTcTokenFromJid, isTcTokenExpired, shouldSendNewTcToken } from '../../Utils/tc-token-utils'
|
||||||
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 */
|
||||||
@@ -858,340 +848,3 @@ 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()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,209 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
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,4 +1,3 @@
|
|||||||
import Long from 'long'
|
|
||||||
import '../index.js'
|
import '../index.js'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
|
|
||||||
@@ -29,91 +28,4 @@ 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')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user