Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc863b340d | |||
| 945d4dcff7 | |||
| 063d72b5a5 | |||
| 9f8b603e28 | |||
| 6c904484e4 | |||
| 5382d03f93 | |||
| 5e602ebbf8 | |||
| 12c400cf1e | |||
| 92085d283a | |||
| 38aa34ffb0 | |||
| 52aa6402c0 | |||
| 8ea7f5434e | |||
| cf72068b6c | |||
| 9165a4941e | |||
| a8d9e308bc | |||
| c29fe8e5ac | |||
| d2ceeaadc4 | |||
| 32a2a9b15c | |||
| 31ac5aeb11 | |||
| 45885c7a01 | |||
| f1b43e26a1 | |||
| a3dd21c9d7 | |||
| e1e3d88a1c | |||
| 758ab6d8af |
+57
-2
@@ -1,7 +1,7 @@
|
|||||||
syntax = "proto3";
|
syntax = "proto3";
|
||||||
package proto;
|
package proto;
|
||||||
|
|
||||||
/// WhatsApp Version: 2.3000.1034274421
|
/// WhatsApp Version: 2.3000.1034621774
|
||||||
|
|
||||||
message ADVDeviceIdentity {
|
message ADVDeviceIdentity {
|
||||||
optional uint32 rawId = 1;
|
optional uint32 rawId = 1;
|
||||||
@@ -74,6 +74,7 @@ message AIMediaCollectionMessage {
|
|||||||
|
|
||||||
message AIMediaCollectionMetadata {
|
message AIMediaCollectionMetadata {
|
||||||
optional string collectionId = 1;
|
optional string collectionId = 1;
|
||||||
|
optional uint32 uploadOrderIndex = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message AIQueryFanout {
|
message AIQueryFanout {
|
||||||
@@ -251,10 +252,12 @@ message AIThreadInfo {
|
|||||||
optional AIThreadClientInfo clientInfo = 2;
|
optional AIThreadClientInfo clientInfo = 2;
|
||||||
message AIThreadClientInfo {
|
message AIThreadClientInfo {
|
||||||
optional AIThreadType type = 1;
|
optional AIThreadType type = 1;
|
||||||
|
optional string sourceChatJid = 2;
|
||||||
enum AIThreadType {
|
enum AIThreadType {
|
||||||
UNKNOWN = 0;
|
UNKNOWN = 0;
|
||||||
DEFAULT = 1;
|
DEFAULT = 1;
|
||||||
INCOGNITO = 2;
|
INCOGNITO = 2;
|
||||||
|
SIDE_CHAT = 3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -403,6 +406,7 @@ message BotCapabilityMetadata {
|
|||||||
RICH_RESPONSE_UR_BLOKS_ENABLED = 55;
|
RICH_RESPONSE_UR_BLOKS_ENABLED = 55;
|
||||||
RICH_RESPONSE_INLINE_LINKS_ENABLED = 56;
|
RICH_RESPONSE_INLINE_LINKS_ENABLED = 56;
|
||||||
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57;
|
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57;
|
||||||
|
JSON_PATCH_STREAMING = 58;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -687,6 +691,7 @@ enum BotMetricsEntryPoint {
|
|||||||
WEB_INTRO_PANEL = 46;
|
WEB_INTRO_PANEL = 46;
|
||||||
WEB_NAVIGATION_BAR = 47;
|
WEB_NAVIGATION_BAR = 47;
|
||||||
GROUP_MEMBER = 54;
|
GROUP_MEMBER = 54;
|
||||||
|
CHATLIST_SEARCH = 55;
|
||||||
}
|
}
|
||||||
message BotMetricsMetadata {
|
message BotMetricsMetadata {
|
||||||
optional string destinationId = 1;
|
optional string destinationId = 1;
|
||||||
@@ -1106,6 +1111,7 @@ message ClientPayload {
|
|||||||
optional bool paaLink = 44;
|
optional bool paaLink = 44;
|
||||||
optional int32 preacksCount = 45;
|
optional int32 preacksCount = 45;
|
||||||
optional int32 processingQueueSize = 46;
|
optional int32 processingQueueSize = 46;
|
||||||
|
repeated string pairedPeripherals = 47;
|
||||||
enum AccountType {
|
enum AccountType {
|
||||||
DEFAULT = 0;
|
DEFAULT = 0;
|
||||||
GUEST = 1;
|
GUEST = 1;
|
||||||
@@ -1628,6 +1634,7 @@ message DeviceCapabilities {
|
|||||||
|
|
||||||
message BusinessBroadcast {
|
message BusinessBroadcast {
|
||||||
optional bool importListEnabled = 1;
|
optional bool importListEnabled = 1;
|
||||||
|
optional bool companionSupportEnabled = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum ChatLockSupportLevel {
|
enum ChatLockSupportLevel {
|
||||||
@@ -1702,6 +1709,7 @@ message DeviceProps {
|
|||||||
optional uint32 thumbnailSyncDaysLimit = 19;
|
optional uint32 thumbnailSyncDaysLimit = 19;
|
||||||
optional uint32 initialSyncMaxMessagesPerChat = 20;
|
optional uint32 initialSyncMaxMessagesPerChat = 20;
|
||||||
optional bool supportManusHistory = 21;
|
optional bool supportManusHistory = 21;
|
||||||
|
optional bool supportHatchHistory = 22;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum PlatformType {
|
enum PlatformType {
|
||||||
@@ -2798,6 +2806,13 @@ message Message {
|
|||||||
optional bool securityNotificationEnabled = 1;
|
optional bool securityNotificationEnabled = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum InsightDeliveryState {
|
||||||
|
SENT = 0;
|
||||||
|
DELIVERED = 1;
|
||||||
|
READ = 2;
|
||||||
|
REPLIED = 3;
|
||||||
|
QUICK_REPLIED = 4;
|
||||||
|
}
|
||||||
message InteractiveMessage {
|
message InteractiveMessage {
|
||||||
optional Header header = 1;
|
optional Header header = 1;
|
||||||
optional Body body = 2;
|
optional Body body = 2;
|
||||||
@@ -3170,6 +3185,16 @@ message Message {
|
|||||||
optional HistorySyncChunkRetryRequest historySyncChunkRetryRequest = 8;
|
optional HistorySyncChunkRetryRequest historySyncChunkRetryRequest = 8;
|
||||||
optional GalaxyFlowAction galaxyFlowAction = 9;
|
optional GalaxyFlowAction galaxyFlowAction = 9;
|
||||||
optional CompanionCanonicalUserNonceFetchRequest companionCanonicalUserNonceFetchRequest = 10;
|
optional CompanionCanonicalUserNonceFetchRequest companionCanonicalUserNonceFetchRequest = 10;
|
||||||
|
optional BizBroadcastInsightsContactListRequest bizBroadcastInsightsContactListRequest = 11;
|
||||||
|
optional BizBroadcastInsightsRefreshRequest bizBroadcastInsightsRefreshRequest = 12;
|
||||||
|
message BizBroadcastInsightsContactListRequest {
|
||||||
|
optional string campaignId = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
message BizBroadcastInsightsRefreshRequest {
|
||||||
|
optional string campaignId = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message CompanionCanonicalUserNonceFetchRequest {
|
message CompanionCanonicalUserNonceFetchRequest {
|
||||||
optional string registrationTraceId = 1;
|
optional string registrationTraceId = 1;
|
||||||
}
|
}
|
||||||
@@ -3244,6 +3269,18 @@ message Message {
|
|||||||
optional CompanionCanonicalUserNonceFetchResponse companionCanonicalUserNonceFetchRequestResponse = 9;
|
optional CompanionCanonicalUserNonceFetchResponse companionCanonicalUserNonceFetchRequestResponse = 9;
|
||||||
optional HistorySyncChunkRetryResponse historySyncChunkRetryResponse = 10;
|
optional HistorySyncChunkRetryResponse historySyncChunkRetryResponse = 10;
|
||||||
optional FlowResponsesCsvBundle flowResponsesCsvBundle = 11;
|
optional FlowResponsesCsvBundle flowResponsesCsvBundle = 11;
|
||||||
|
optional BizBroadcastInsightsContactListResponse bizBroadcastInsightsContactListResponse = 12;
|
||||||
|
message BizBroadcastInsightsContactListResponse {
|
||||||
|
optional string campaignId = 1;
|
||||||
|
optional int64 timestampMs = 2;
|
||||||
|
repeated Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactState contacts = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message BizBroadcastInsightsContactState {
|
||||||
|
optional string contactJid = 1;
|
||||||
|
optional Message.InsightDeliveryState state = 2;
|
||||||
|
}
|
||||||
|
|
||||||
message CompanionCanonicalUserNonceFetchResponse {
|
message CompanionCanonicalUserNonceFetchResponse {
|
||||||
optional string nonce = 1;
|
optional string nonce = 1;
|
||||||
optional string waFbid = 2;
|
optional string waFbid = 2;
|
||||||
@@ -3357,6 +3394,8 @@ message Message {
|
|||||||
COMPANION_CANONICAL_USER_NONCE_FETCH = 9;
|
COMPANION_CANONICAL_USER_NONCE_FETCH = 9;
|
||||||
HISTORY_SYNC_CHUNK_RETRY = 10;
|
HISTORY_SYNC_CHUNK_RETRY = 10;
|
||||||
GALAXY_FLOW_ACTION = 11;
|
GALAXY_FLOW_ACTION = 11;
|
||||||
|
BUSINESS_BROADCAST_INSIGHTS_DELIVERED_TO = 12;
|
||||||
|
BUSINESS_BROADCAST_INSIGHTS_REFRESH = 13;
|
||||||
}
|
}
|
||||||
message PinInChatMessage {
|
message PinInChatMessage {
|
||||||
optional MessageKey key = 1;
|
optional MessageKey key = 1;
|
||||||
@@ -3967,6 +4006,7 @@ message MsgOpaqueData {
|
|||||||
optional string quarantineExtractedText = 48;
|
optional string quarantineExtractedText = 48;
|
||||||
optional int64 pollEndTime = 49;
|
optional int64 pollEndTime = 49;
|
||||||
optional bool pollHideVoterNames = 50;
|
optional bool pollHideVoterNames = 50;
|
||||||
|
optional bool pollAllowAddOption = 52;
|
||||||
message EventLocation {
|
message EventLocation {
|
||||||
optional double degreesLatitude = 1;
|
optional double degreesLatitude = 1;
|
||||||
optional double degreesLongitude = 2;
|
optional double degreesLongitude = 2;
|
||||||
@@ -4083,6 +4123,7 @@ enum MutationProps {
|
|||||||
NCT_SALT_SYNC_ACTION = 80;
|
NCT_SALT_SYNC_ACTION = 80;
|
||||||
BUSINESS_BROADCAST_CAMPAIGN_ACTION = 81;
|
BUSINESS_BROADCAST_CAMPAIGN_ACTION = 81;
|
||||||
BUSINESS_BROADCAST_INSIGHTS_ACTION = 82;
|
BUSINESS_BROADCAST_INSIGHTS_ACTION = 82;
|
||||||
|
CUSTOMER_DATA_ACTION = 83;
|
||||||
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;
|
||||||
@@ -4718,6 +4759,7 @@ message SyncActionValue {
|
|||||||
optional NctSaltSyncAction nctSaltSyncAction = 80;
|
optional NctSaltSyncAction nctSaltSyncAction = 80;
|
||||||
optional BusinessBroadcastCampaignAction businessBroadcastCampaignAction = 81;
|
optional BusinessBroadcastCampaignAction businessBroadcastCampaignAction = 81;
|
||||||
optional BusinessBroadcastInsightsAction businessBroadcastInsightsAction = 82;
|
optional BusinessBroadcastInsightsAction businessBroadcastInsightsAction = 82;
|
||||||
|
optional CustomerDataAction customerDataAction = 83;
|
||||||
message AgentAction {
|
message AgentAction {
|
||||||
optional string name = 1;
|
optional string name = 1;
|
||||||
optional int32 deviceID = 2;
|
optional int32 deviceID = 2;
|
||||||
@@ -4839,6 +4881,20 @@ message SyncActionValue {
|
|||||||
repeated SyncActionValue.CustomPaymentMethod customPaymentMethods = 1;
|
repeated SyncActionValue.CustomPaymentMethod customPaymentMethods = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message CustomerDataAction {
|
||||||
|
optional string chatJid = 1;
|
||||||
|
optional int32 contactType = 2;
|
||||||
|
optional string email = 3;
|
||||||
|
optional string altPhoneNumbers = 4;
|
||||||
|
optional int64 birthday = 5;
|
||||||
|
optional string address = 6;
|
||||||
|
optional int32 acquisitionSource = 7;
|
||||||
|
optional int32 leadStage = 8;
|
||||||
|
optional int64 lastOrder = 9;
|
||||||
|
optional int64 createdAt = 10;
|
||||||
|
optional int64 modifiedAt = 11;
|
||||||
|
}
|
||||||
|
|
||||||
message DeleteChatAction {
|
message DeleteChatAction {
|
||||||
optional SyncActionValue.SyncActionMessageRange messageRange = 1;
|
optional SyncActionValue.SyncActionMessageRange messageRange = 1;
|
||||||
}
|
}
|
||||||
@@ -5351,7 +5407,6 @@ message TemplateButton {
|
|||||||
message ThreadID {
|
message ThreadID {
|
||||||
optional ThreadType threadType = 1;
|
optional ThreadType threadType = 1;
|
||||||
optional MessageKey threadKey = 2;
|
optional MessageKey threadKey = 2;
|
||||||
optional string sourceChatJid = 3;
|
|
||||||
enum ThreadType {
|
enum ThreadType {
|
||||||
UNKNOWN = 0;
|
UNKNOWN = 0;
|
||||||
VIEW_REPLIES = 1;
|
VIEW_REPLIES = 1;
|
||||||
|
|||||||
Vendored
+144
-6
@@ -203,11 +203,13 @@ export namespace proto {
|
|||||||
|
|
||||||
interface IAIMediaCollectionMetadata {
|
interface IAIMediaCollectionMetadata {
|
||||||
collectionId?: (string|null);
|
collectionId?: (string|null);
|
||||||
|
uploadOrderIndex?: (number|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class AIMediaCollectionMetadata implements IAIMediaCollectionMetadata {
|
class AIMediaCollectionMetadata implements IAIMediaCollectionMetadata {
|
||||||
constructor(p?: proto.IAIMediaCollectionMetadata);
|
constructor(p?: proto.IAIMediaCollectionMetadata);
|
||||||
public collectionId?: (string|null);
|
public collectionId?: (string|null);
|
||||||
|
public uploadOrderIndex?: (number|null);
|
||||||
public static create(properties?: proto.IAIMediaCollectionMetadata): proto.AIMediaCollectionMetadata;
|
public static create(properties?: proto.IAIMediaCollectionMetadata): proto.AIMediaCollectionMetadata;
|
||||||
public static encode(m: proto.IAIMediaCollectionMetadata, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IAIMediaCollectionMetadata, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.AIMediaCollectionMetadata;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.AIMediaCollectionMetadata;
|
||||||
@@ -725,11 +727,13 @@ export namespace proto {
|
|||||||
|
|
||||||
interface IAIThreadClientInfo {
|
interface IAIThreadClientInfo {
|
||||||
type?: (proto.AIThreadInfo.AIThreadClientInfo.AIThreadType|null);
|
type?: (proto.AIThreadInfo.AIThreadClientInfo.AIThreadType|null);
|
||||||
|
sourceChatJid?: (string|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class AIThreadClientInfo implements IAIThreadClientInfo {
|
class AIThreadClientInfo implements IAIThreadClientInfo {
|
||||||
constructor(p?: proto.AIThreadInfo.IAIThreadClientInfo);
|
constructor(p?: proto.AIThreadInfo.IAIThreadClientInfo);
|
||||||
public type?: (proto.AIThreadInfo.AIThreadClientInfo.AIThreadType|null);
|
public type?: (proto.AIThreadInfo.AIThreadClientInfo.AIThreadType|null);
|
||||||
|
public sourceChatJid?: (string|null);
|
||||||
public static create(properties?: proto.AIThreadInfo.IAIThreadClientInfo): proto.AIThreadInfo.AIThreadClientInfo;
|
public static create(properties?: proto.AIThreadInfo.IAIThreadClientInfo): proto.AIThreadInfo.AIThreadClientInfo;
|
||||||
public static encode(m: proto.AIThreadInfo.IAIThreadClientInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.AIThreadInfo.IAIThreadClientInfo, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.AIThreadInfo.AIThreadClientInfo;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.AIThreadInfo.AIThreadClientInfo;
|
||||||
@@ -744,7 +748,8 @@ export namespace proto {
|
|||||||
enum AIThreadType {
|
enum AIThreadType {
|
||||||
UNKNOWN = 0,
|
UNKNOWN = 0,
|
||||||
DEFAULT = 1,
|
DEFAULT = 1,
|
||||||
INCOGNITO = 2
|
INCOGNITO = 2,
|
||||||
|
SIDE_CHAT = 3
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1052,7 +1057,8 @@ export namespace proto {
|
|||||||
AI_IMAGINE_UR_TO_NATIVE_LOADING_INDICATOR = 54,
|
AI_IMAGINE_UR_TO_NATIVE_LOADING_INDICATOR = 54,
|
||||||
RICH_RESPONSE_UR_BLOKS_ENABLED = 55,
|
RICH_RESPONSE_UR_BLOKS_ENABLED = 55,
|
||||||
RICH_RESPONSE_INLINE_LINKS_ENABLED = 56,
|
RICH_RESPONSE_INLINE_LINKS_ENABLED = 56,
|
||||||
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57
|
RICH_RESPONSE_UR_IMAGINE_VIDEO = 57,
|
||||||
|
JSON_PATCH_STREAMING = 58
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1738,7 +1744,8 @@ export namespace proto {
|
|||||||
META_AI_SETTINGS = 45,
|
META_AI_SETTINGS = 45,
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IBotMetricsMetadata {
|
interface IBotMetricsMetadata {
|
||||||
@@ -2814,6 +2821,7 @@ export namespace proto {
|
|||||||
paaLink?: (boolean|null);
|
paaLink?: (boolean|null);
|
||||||
preacksCount?: (number|null);
|
preacksCount?: (number|null);
|
||||||
processingQueueSize?: (number|null);
|
processingQueueSize?: (number|null);
|
||||||
|
pairedPeripherals?: (string[]|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class ClientPayload implements IClientPayload {
|
class ClientPayload implements IClientPayload {
|
||||||
@@ -2852,6 +2860,7 @@ export namespace proto {
|
|||||||
public paaLink?: (boolean|null);
|
public paaLink?: (boolean|null);
|
||||||
public preacksCount?: (number|null);
|
public preacksCount?: (number|null);
|
||||||
public processingQueueSize?: (number|null);
|
public processingQueueSize?: (number|null);
|
||||||
|
public pairedPeripherals: string[];
|
||||||
public static create(properties?: proto.IClientPayload): proto.ClientPayload;
|
public static create(properties?: proto.IClientPayload): proto.ClientPayload;
|
||||||
public static encode(m: proto.IClientPayload, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IClientPayload, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.ClientPayload;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.ClientPayload;
|
||||||
@@ -3973,11 +3982,13 @@ export namespace proto {
|
|||||||
|
|
||||||
interface IBusinessBroadcast {
|
interface IBusinessBroadcast {
|
||||||
importListEnabled?: (boolean|null);
|
importListEnabled?: (boolean|null);
|
||||||
|
companionSupportEnabled?: (boolean|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class BusinessBroadcast implements IBusinessBroadcast {
|
class BusinessBroadcast implements IBusinessBroadcast {
|
||||||
constructor(p?: proto.DeviceCapabilities.IBusinessBroadcast);
|
constructor(p?: proto.DeviceCapabilities.IBusinessBroadcast);
|
||||||
public importListEnabled?: (boolean|null);
|
public importListEnabled?: (boolean|null);
|
||||||
|
public companionSupportEnabled?: (boolean|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;
|
||||||
@@ -4152,6 +4163,7 @@ export namespace proto {
|
|||||||
thumbnailSyncDaysLimit?: (number|null);
|
thumbnailSyncDaysLimit?: (number|null);
|
||||||
initialSyncMaxMessagesPerChat?: (number|null);
|
initialSyncMaxMessagesPerChat?: (number|null);
|
||||||
supportManusHistory?: (boolean|null);
|
supportManusHistory?: (boolean|null);
|
||||||
|
supportHatchHistory?: (boolean|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class HistorySyncConfig implements IHistorySyncConfig {
|
class HistorySyncConfig implements IHistorySyncConfig {
|
||||||
@@ -4177,6 +4189,7 @@ export namespace proto {
|
|||||||
public thumbnailSyncDaysLimit?: (number|null);
|
public thumbnailSyncDaysLimit?: (number|null);
|
||||||
public initialSyncMaxMessagesPerChat?: (number|null);
|
public initialSyncMaxMessagesPerChat?: (number|null);
|
||||||
public supportManusHistory?: (boolean|null);
|
public supportManusHistory?: (boolean|null);
|
||||||
|
public supportHatchHistory?: (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;
|
||||||
@@ -7042,6 +7055,14 @@ export namespace proto {
|
|||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum InsightDeliveryState {
|
||||||
|
SENT = 0,
|
||||||
|
DELIVERED = 1,
|
||||||
|
READ = 2,
|
||||||
|
REPLIED = 3,
|
||||||
|
QUICK_REPLIED = 4
|
||||||
|
}
|
||||||
|
|
||||||
interface IInteractiveMessage {
|
interface IInteractiveMessage {
|
||||||
header?: (proto.Message.InteractiveMessage.IHeader|null);
|
header?: (proto.Message.InteractiveMessage.IHeader|null);
|
||||||
body?: (proto.Message.InteractiveMessage.IBody|null);
|
body?: (proto.Message.InteractiveMessage.IBody|null);
|
||||||
@@ -8082,6 +8103,8 @@ export namespace proto {
|
|||||||
historySyncChunkRetryRequest?: (proto.Message.PeerDataOperationRequestMessage.IHistorySyncChunkRetryRequest|null);
|
historySyncChunkRetryRequest?: (proto.Message.PeerDataOperationRequestMessage.IHistorySyncChunkRetryRequest|null);
|
||||||
galaxyFlowAction?: (proto.Message.PeerDataOperationRequestMessage.IGalaxyFlowAction|null);
|
galaxyFlowAction?: (proto.Message.PeerDataOperationRequestMessage.IGalaxyFlowAction|null);
|
||||||
companionCanonicalUserNonceFetchRequest?: (proto.Message.PeerDataOperationRequestMessage.ICompanionCanonicalUserNonceFetchRequest|null);
|
companionCanonicalUserNonceFetchRequest?: (proto.Message.PeerDataOperationRequestMessage.ICompanionCanonicalUserNonceFetchRequest|null);
|
||||||
|
bizBroadcastInsightsContactListRequest?: (proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsContactListRequest|null);
|
||||||
|
bizBroadcastInsightsRefreshRequest?: (proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsRefreshRequest|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class PeerDataOperationRequestMessage implements IPeerDataOperationRequestMessage {
|
class PeerDataOperationRequestMessage implements IPeerDataOperationRequestMessage {
|
||||||
@@ -8096,6 +8119,8 @@ export namespace proto {
|
|||||||
public historySyncChunkRetryRequest?: (proto.Message.PeerDataOperationRequestMessage.IHistorySyncChunkRetryRequest|null);
|
public historySyncChunkRetryRequest?: (proto.Message.PeerDataOperationRequestMessage.IHistorySyncChunkRetryRequest|null);
|
||||||
public galaxyFlowAction?: (proto.Message.PeerDataOperationRequestMessage.IGalaxyFlowAction|null);
|
public galaxyFlowAction?: (proto.Message.PeerDataOperationRequestMessage.IGalaxyFlowAction|null);
|
||||||
public companionCanonicalUserNonceFetchRequest?: (proto.Message.PeerDataOperationRequestMessage.ICompanionCanonicalUserNonceFetchRequest|null);
|
public companionCanonicalUserNonceFetchRequest?: (proto.Message.PeerDataOperationRequestMessage.ICompanionCanonicalUserNonceFetchRequest|null);
|
||||||
|
public bizBroadcastInsightsContactListRequest?: (proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsContactListRequest|null);
|
||||||
|
public bizBroadcastInsightsRefreshRequest?: (proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsRefreshRequest|null);
|
||||||
public static create(properties?: proto.Message.IPeerDataOperationRequestMessage): proto.Message.PeerDataOperationRequestMessage;
|
public static create(properties?: proto.Message.IPeerDataOperationRequestMessage): proto.Message.PeerDataOperationRequestMessage;
|
||||||
public static encode(m: proto.Message.IPeerDataOperationRequestMessage, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.Message.IPeerDataOperationRequestMessage, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestMessage;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestMessage;
|
||||||
@@ -8107,6 +8132,38 @@ export namespace proto {
|
|||||||
|
|
||||||
namespace PeerDataOperationRequestMessage {
|
namespace PeerDataOperationRequestMessage {
|
||||||
|
|
||||||
|
interface IBizBroadcastInsightsContactListRequest {
|
||||||
|
campaignId?: (string|null);
|
||||||
|
}
|
||||||
|
|
||||||
|
class BizBroadcastInsightsContactListRequest implements IBizBroadcastInsightsContactListRequest {
|
||||||
|
constructor(p?: proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsContactListRequest);
|
||||||
|
public campaignId?: (string|null);
|
||||||
|
public static create(properties?: proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsContactListRequest): proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsContactListRequest;
|
||||||
|
public static encode(m: proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsContactListRequest, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsContactListRequest;
|
||||||
|
public static fromObject(d: { [k: string]: any }): proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsContactListRequest;
|
||||||
|
public static toObject(m: proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsContactListRequest, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
||||||
|
public toJSON(): { [k: string]: any };
|
||||||
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IBizBroadcastInsightsRefreshRequest {
|
||||||
|
campaignId?: (string|null);
|
||||||
|
}
|
||||||
|
|
||||||
|
class BizBroadcastInsightsRefreshRequest implements IBizBroadcastInsightsRefreshRequest {
|
||||||
|
constructor(p?: proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsRefreshRequest);
|
||||||
|
public campaignId?: (string|null);
|
||||||
|
public static create(properties?: proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsRefreshRequest): proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsRefreshRequest;
|
||||||
|
public static encode(m: proto.Message.PeerDataOperationRequestMessage.IBizBroadcastInsightsRefreshRequest, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsRefreshRequest;
|
||||||
|
public static fromObject(d: { [k: string]: any }): proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsRefreshRequest;
|
||||||
|
public static toObject(m: proto.Message.PeerDataOperationRequestMessage.BizBroadcastInsightsRefreshRequest, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
||||||
|
public toJSON(): { [k: string]: any };
|
||||||
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
interface ICompanionCanonicalUserNonceFetchRequest {
|
interface ICompanionCanonicalUserNonceFetchRequest {
|
||||||
registrationTraceId?: (string|null);
|
registrationTraceId?: (string|null);
|
||||||
}
|
}
|
||||||
@@ -8326,6 +8383,7 @@ export namespace proto {
|
|||||||
companionCanonicalUserNonceFetchRequestResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.ICompanionCanonicalUserNonceFetchResponse|null);
|
companionCanonicalUserNonceFetchRequestResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.ICompanionCanonicalUserNonceFetchResponse|null);
|
||||||
historySyncChunkRetryResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IHistorySyncChunkRetryResponse|null);
|
historySyncChunkRetryResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IHistorySyncChunkRetryResponse|null);
|
||||||
flowResponsesCsvBundle?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IFlowResponsesCsvBundle|null);
|
flowResponsesCsvBundle?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IFlowResponsesCsvBundle|null);
|
||||||
|
bizBroadcastInsightsContactListResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactListResponse|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class PeerDataOperationResult implements IPeerDataOperationResult {
|
class PeerDataOperationResult implements IPeerDataOperationResult {
|
||||||
@@ -8341,6 +8399,7 @@ export namespace proto {
|
|||||||
public companionCanonicalUserNonceFetchRequestResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.ICompanionCanonicalUserNonceFetchResponse|null);
|
public companionCanonicalUserNonceFetchRequestResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.ICompanionCanonicalUserNonceFetchResponse|null);
|
||||||
public historySyncChunkRetryResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IHistorySyncChunkRetryResponse|null);
|
public historySyncChunkRetryResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IHistorySyncChunkRetryResponse|null);
|
||||||
public flowResponsesCsvBundle?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IFlowResponsesCsvBundle|null);
|
public flowResponsesCsvBundle?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IFlowResponsesCsvBundle|null);
|
||||||
|
public bizBroadcastInsightsContactListResponse?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactListResponse|null);
|
||||||
public static create(properties?: proto.Message.PeerDataOperationRequestResponseMessage.IPeerDataOperationResult): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult;
|
public static create(properties?: proto.Message.PeerDataOperationRequestResponseMessage.IPeerDataOperationResult): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult;
|
||||||
public static encode(m: proto.Message.PeerDataOperationRequestResponseMessage.IPeerDataOperationResult, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.Message.PeerDataOperationRequestResponseMessage.IPeerDataOperationResult, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult;
|
||||||
@@ -8352,6 +8411,44 @@ export namespace proto {
|
|||||||
|
|
||||||
namespace PeerDataOperationResult {
|
namespace PeerDataOperationResult {
|
||||||
|
|
||||||
|
interface IBizBroadcastInsightsContactListResponse {
|
||||||
|
campaignId?: (string|null);
|
||||||
|
timestampMs?: (number|Long|null);
|
||||||
|
contacts?: (proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactState[]|null);
|
||||||
|
}
|
||||||
|
|
||||||
|
class BizBroadcastInsightsContactListResponse implements IBizBroadcastInsightsContactListResponse {
|
||||||
|
constructor(p?: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactListResponse);
|
||||||
|
public campaignId?: (string|null);
|
||||||
|
public timestampMs?: (number|Long|null);
|
||||||
|
public contacts: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactState[];
|
||||||
|
public static create(properties?: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactListResponse): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactListResponse;
|
||||||
|
public static encode(m: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactListResponse, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactListResponse;
|
||||||
|
public static fromObject(d: { [k: string]: any }): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactListResponse;
|
||||||
|
public static toObject(m: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactListResponse, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
||||||
|
public toJSON(): { [k: string]: any };
|
||||||
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IBizBroadcastInsightsContactState {
|
||||||
|
contactJid?: (string|null);
|
||||||
|
state?: (proto.Message.InsightDeliveryState|null);
|
||||||
|
}
|
||||||
|
|
||||||
|
class BizBroadcastInsightsContactState implements IBizBroadcastInsightsContactState {
|
||||||
|
constructor(p?: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactState);
|
||||||
|
public contactJid?: (string|null);
|
||||||
|
public state?: (proto.Message.InsightDeliveryState|null);
|
||||||
|
public static create(properties?: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactState): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactState;
|
||||||
|
public static encode(m: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.IBizBroadcastInsightsContactState, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactState;
|
||||||
|
public static fromObject(d: { [k: string]: any }): proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactState;
|
||||||
|
public static toObject(m: proto.Message.PeerDataOperationRequestResponseMessage.PeerDataOperationResult.BizBroadcastInsightsContactState, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
||||||
|
public toJSON(): { [k: string]: any };
|
||||||
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
interface ICompanionCanonicalUserNonceFetchResponse {
|
interface ICompanionCanonicalUserNonceFetchResponse {
|
||||||
nonce?: (string|null);
|
nonce?: (string|null);
|
||||||
waFbid?: (string|null);
|
waFbid?: (string|null);
|
||||||
@@ -8634,7 +8731,9 @@ export namespace proto {
|
|||||||
COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY = 8,
|
COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY = 8,
|
||||||
COMPANION_CANONICAL_USER_NONCE_FETCH = 9,
|
COMPANION_CANONICAL_USER_NONCE_FETCH = 9,
|
||||||
HISTORY_SYNC_CHUNK_RETRY = 10,
|
HISTORY_SYNC_CHUNK_RETRY = 10,
|
||||||
GALAXY_FLOW_ACTION = 11
|
GALAXY_FLOW_ACTION = 11,
|
||||||
|
BUSINESS_BROADCAST_INSIGHTS_DELIVERED_TO = 12,
|
||||||
|
BUSINESS_BROADCAST_INSIGHTS_REFRESH = 13
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IPinInChatMessage {
|
interface IPinInChatMessage {
|
||||||
@@ -10114,6 +10213,7 @@ export namespace proto {
|
|||||||
quarantineExtractedText?: (string|null);
|
quarantineExtractedText?: (string|null);
|
||||||
pollEndTime?: (number|Long|null);
|
pollEndTime?: (number|Long|null);
|
||||||
pollHideVoterNames?: (boolean|null);
|
pollHideVoterNames?: (boolean|null);
|
||||||
|
pollAllowAddOption?: (boolean|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class MsgOpaqueData implements IMsgOpaqueData {
|
class MsgOpaqueData implements IMsgOpaqueData {
|
||||||
@@ -10164,6 +10264,7 @@ export namespace proto {
|
|||||||
public quarantineExtractedText?: (string|null);
|
public quarantineExtractedText?: (string|null);
|
||||||
public pollEndTime?: (number|Long|null);
|
public pollEndTime?: (number|Long|null);
|
||||||
public pollHideVoterNames?: (boolean|null);
|
public pollHideVoterNames?: (boolean|null);
|
||||||
|
public pollAllowAddOption?: (boolean|null);
|
||||||
public static create(properties?: proto.IMsgOpaqueData): proto.MsgOpaqueData;
|
public static create(properties?: proto.IMsgOpaqueData): proto.MsgOpaqueData;
|
||||||
public static encode(m: proto.IMsgOpaqueData, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IMsgOpaqueData, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.MsgOpaqueData;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.MsgOpaqueData;
|
||||||
@@ -10360,6 +10461,7 @@ export namespace proto {
|
|||||||
NCT_SALT_SYNC_ACTION = 80,
|
NCT_SALT_SYNC_ACTION = 80,
|
||||||
BUSINESS_BROADCAST_CAMPAIGN_ACTION = 81,
|
BUSINESS_BROADCAST_CAMPAIGN_ACTION = 81,
|
||||||
BUSINESS_BROADCAST_INSIGHTS_ACTION = 82,
|
BUSINESS_BROADCAST_INSIGHTS_ACTION = 82,
|
||||||
|
CUSTOMER_DATA_ACTION = 83,
|
||||||
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
|
||||||
@@ -11953,6 +12055,7 @@ export namespace proto {
|
|||||||
nctSaltSyncAction?: (proto.SyncActionValue.INctSaltSyncAction|null);
|
nctSaltSyncAction?: (proto.SyncActionValue.INctSaltSyncAction|null);
|
||||||
businessBroadcastCampaignAction?: (proto.SyncActionValue.IBusinessBroadcastCampaignAction|null);
|
businessBroadcastCampaignAction?: (proto.SyncActionValue.IBusinessBroadcastCampaignAction|null);
|
||||||
businessBroadcastInsightsAction?: (proto.SyncActionValue.IBusinessBroadcastInsightsAction|null);
|
businessBroadcastInsightsAction?: (proto.SyncActionValue.IBusinessBroadcastInsightsAction|null);
|
||||||
|
customerDataAction?: (proto.SyncActionValue.ICustomerDataAction|null);
|
||||||
}
|
}
|
||||||
|
|
||||||
class SyncActionValue implements ISyncActionValue {
|
class SyncActionValue implements ISyncActionValue {
|
||||||
@@ -12030,6 +12133,7 @@ export namespace proto {
|
|||||||
public nctSaltSyncAction?: (proto.SyncActionValue.INctSaltSyncAction|null);
|
public nctSaltSyncAction?: (proto.SyncActionValue.INctSaltSyncAction|null);
|
||||||
public businessBroadcastCampaignAction?: (proto.SyncActionValue.IBusinessBroadcastCampaignAction|null);
|
public businessBroadcastCampaignAction?: (proto.SyncActionValue.IBusinessBroadcastCampaignAction|null);
|
||||||
public businessBroadcastInsightsAction?: (proto.SyncActionValue.IBusinessBroadcastInsightsAction|null);
|
public businessBroadcastInsightsAction?: (proto.SyncActionValue.IBusinessBroadcastInsightsAction|null);
|
||||||
|
public customerDataAction?: (proto.SyncActionValue.ICustomerDataAction|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;
|
||||||
@@ -12436,6 +12540,42 @@ export namespace proto {
|
|||||||
public static getTypeUrl(typeUrlPrefix?: string): string;
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ICustomerDataAction {
|
||||||
|
chatJid?: (string|null);
|
||||||
|
contactType?: (number|null);
|
||||||
|
email?: (string|null);
|
||||||
|
altPhoneNumbers?: (string|null);
|
||||||
|
birthday?: (number|Long|null);
|
||||||
|
address?: (string|null);
|
||||||
|
acquisitionSource?: (number|null);
|
||||||
|
leadStage?: (number|null);
|
||||||
|
lastOrder?: (number|Long|null);
|
||||||
|
createdAt?: (number|Long|null);
|
||||||
|
modifiedAt?: (number|Long|null);
|
||||||
|
}
|
||||||
|
|
||||||
|
class CustomerDataAction implements ICustomerDataAction {
|
||||||
|
constructor(p?: proto.SyncActionValue.ICustomerDataAction);
|
||||||
|
public chatJid?: (string|null);
|
||||||
|
public contactType?: (number|null);
|
||||||
|
public email?: (string|null);
|
||||||
|
public altPhoneNumbers?: (string|null);
|
||||||
|
public birthday?: (number|Long|null);
|
||||||
|
public address?: (string|null);
|
||||||
|
public acquisitionSource?: (number|null);
|
||||||
|
public leadStage?: (number|null);
|
||||||
|
public lastOrder?: (number|Long|null);
|
||||||
|
public createdAt?: (number|Long|null);
|
||||||
|
public modifiedAt?: (number|Long|null);
|
||||||
|
public static create(properties?: proto.SyncActionValue.ICustomerDataAction): proto.SyncActionValue.CustomerDataAction;
|
||||||
|
public static encode(m: proto.SyncActionValue.ICustomerDataAction, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.SyncActionValue.CustomerDataAction;
|
||||||
|
public static fromObject(d: { [k: string]: any }): proto.SyncActionValue.CustomerDataAction;
|
||||||
|
public static toObject(m: proto.SyncActionValue.CustomerDataAction, o?: $protobuf.IConversionOptions): { [k: string]: any };
|
||||||
|
public toJSON(): { [k: string]: any };
|
||||||
|
public static getTypeUrl(typeUrlPrefix?: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
interface IDeleteChatAction {
|
interface IDeleteChatAction {
|
||||||
messageRange?: (proto.SyncActionValue.ISyncActionMessageRange|null);
|
messageRange?: (proto.SyncActionValue.ISyncActionMessageRange|null);
|
||||||
}
|
}
|
||||||
@@ -13959,14 +14099,12 @@ export namespace proto {
|
|||||||
interface IThreadID {
|
interface IThreadID {
|
||||||
threadType?: (proto.ThreadID.ThreadType|null);
|
threadType?: (proto.ThreadID.ThreadType|null);
|
||||||
threadKey?: (proto.IMessageKey|null);
|
threadKey?: (proto.IMessageKey|null);
|
||||||
sourceChatJid?: (string|null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ThreadID implements IThreadID {
|
class ThreadID implements IThreadID {
|
||||||
constructor(p?: proto.IThreadID);
|
constructor(p?: proto.IThreadID);
|
||||||
public threadType?: (proto.ThreadID.ThreadType|null);
|
public threadType?: (proto.ThreadID.ThreadType|null);
|
||||||
public threadKey?: (proto.IMessageKey|null);
|
public threadKey?: (proto.IMessageKey|null);
|
||||||
public sourceChatJid?: (string|null);
|
|
||||||
public static create(properties?: proto.IThreadID): proto.ThreadID;
|
public static create(properties?: proto.IThreadID): proto.ThreadID;
|
||||||
public static encode(m: proto.IThreadID, w?: $protobuf.Writer): $protobuf.Writer;
|
public static encode(m: proto.IThreadID, w?: $protobuf.Writer): $protobuf.Writer;
|
||||||
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.ThreadID;
|
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): proto.ThreadID;
|
||||||
|
|||||||
+1070
-21
File diff suppressed because it is too large
Load Diff
@@ -1 +1 @@
|
|||||||
{"version":[2,3000,1034279434]}
|
{"version":[2,3000,1034641024]}
|
||||||
|
|||||||
+24
-1
@@ -56,10 +56,33 @@ export const PROCESSABLE_HISTORY_TYPES = [
|
|||||||
// 6 hours in milliseconds
|
// 6 hours in milliseconds
|
||||||
const SIX_HOURS_MS = 6 * 60 * 60 * 1000
|
const SIX_HOURS_MS = 6 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the default browser tuple from the BAILEYS_BROWSER env var.
|
||||||
|
* Default: Android companion (SMB_ANDROID) — matches upstream PR #2201.
|
||||||
|
* Pair code auto-detects Android and falls back to Chrome in socket.ts.
|
||||||
|
*
|
||||||
|
* unset / 'android' → Browsers.android('14')
|
||||||
|
* 'android:15' → Browsers.android('15')
|
||||||
|
* 'chrome' / 'macos' → Browsers.macOS('Chrome')
|
||||||
|
*/
|
||||||
|
const resolveDefaultBrowser = (): [string, string, string] => {
|
||||||
|
const env = process.env.BAILEYS_BROWSER?.trim().toLowerCase()
|
||||||
|
if (env === 'chrome' || env === 'macos') {
|
||||||
|
return Browsers.macOS('Chrome')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (env?.startsWith('android:')) {
|
||||||
|
const apiLevel = env.split(':')[1] || '14'
|
||||||
|
return Browsers.android(apiLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Browsers.android('14')
|
||||||
|
}
|
||||||
|
|
||||||
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
export const DEFAULT_CONNECTION_CONFIG: SocketConfig = {
|
||||||
version: version as WAVersion,
|
version: version as WAVersion,
|
||||||
versionCheckIntervalMs: SIX_HOURS_MS,
|
versionCheckIntervalMs: SIX_HOURS_MS,
|
||||||
browser: Browsers.macOS('Chrome'),
|
browser: resolveDefaultBrowser(),
|
||||||
waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
|
waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
|
||||||
connectTimeoutMs: 20_000,
|
connectTimeoutMs: 20_000,
|
||||||
keepAliveIntervalMs: 15_000,
|
keepAliveIntervalMs: 15_000,
|
||||||
|
|||||||
+79
-13
@@ -302,6 +302,25 @@ export function makeLibSignalRepository(
|
|||||||
// Promise instead of each spawning their own DB transactions.
|
// Promise instead of each spawning their own DB transactions.
|
||||||
const migrationInFlight = new Map<string, Promise<{ migrated: number; skipped: number; total: number }>>()
|
const migrationInFlight = new Map<string, Promise<{ migrated: number; skipped: number; total: number }>>()
|
||||||
|
|
||||||
|
// Resolve PN JID to its canonical LID JID for transaction locking.
|
||||||
|
// This prevents PN/LID race conditions where concurrent operations for the
|
||||||
|
// same logical contact acquire different mutex locks because one uses PN
|
||||||
|
// and the other uses LID. (Aligned with WABA behavior — all operations use LID internally.)
|
||||||
|
const resolveCanonicalJid = async(jid: string): Promise<string> => {
|
||||||
|
if (isAnyLidUser(jid)) {
|
||||||
|
return jid
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAnyPnUser(jid)) {
|
||||||
|
const lid = await lidMapping.getLIDForPN(jid)
|
||||||
|
if (lid) {
|
||||||
|
return lid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return jid
|
||||||
|
}
|
||||||
|
|
||||||
const repository: SignalRepositoryWithLIDStore = {
|
const repository: SignalRepositoryWithLIDStore = {
|
||||||
decryptGroupMessage({ group, authorJid, msg }) {
|
decryptGroupMessage({ group, authorJid, msg }) {
|
||||||
const senderName = jidToSignalSenderKeyName(group, authorJid)
|
const senderName = jidToSignalSenderKeyName(group, authorJid)
|
||||||
@@ -396,23 +415,24 @@ export function makeLibSignalRepository(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// If it's not a sync message, we need to ensure atomicity
|
// Use canonical JID (PN→LID resolved) as transaction key to prevent
|
||||||
// For regular messages, we use a transaction to ensure atomicity
|
// PN/LID race conditions on the same logical session.
|
||||||
|
const canonicalJid = await resolveCanonicalJid(jid)
|
||||||
return parsedKeys.transaction(async () => {
|
return parsedKeys.transaction(async () => {
|
||||||
return await doDecrypt()
|
return await doDecrypt()
|
||||||
}, jid)
|
}, canonicalJid)
|
||||||
},
|
},
|
||||||
|
|
||||||
async encryptMessage({ jid, data }) {
|
async encryptMessage({ jid, data }) {
|
||||||
const addr = jidToSignalProtocolAddress(jid)
|
const addr = jidToSignalProtocolAddress(jid)
|
||||||
const cipher = new libsignal.SessionCipher(storage, addr)
|
const cipher = new libsignal.SessionCipher(storage, addr)
|
||||||
|
|
||||||
// Use transaction to ensure atomicity
|
const canonicalJid = await resolveCanonicalJid(jid)
|
||||||
return parsedKeys.transaction(async () => {
|
return parsedKeys.transaction(async () => {
|
||||||
const { type: sigType, body } = await cipher.encrypt(data)
|
const { type: sigType, body } = await cipher.encrypt(data)
|
||||||
const type = sigType === 3 ? 'pkmsg' : 'msg'
|
const type = sigType === 3 ? 'pkmsg' : 'msg'
|
||||||
return { type, ciphertext: Buffer.from(body, 'binary') }
|
return { type, ciphertext: Buffer.from(body, 'binary') }
|
||||||
}, jid)
|
}, canonicalJid)
|
||||||
},
|
},
|
||||||
|
|
||||||
async encryptGroupMessage({ group, meId, data }) {
|
async encryptGroupMessage({ group, meId, data }) {
|
||||||
@@ -654,9 +674,10 @@ export function makeLibSignalRepository(
|
|||||||
// Session exists (guaranteed from device discovery)
|
// Session exists (guaranteed from device discovery)
|
||||||
const fromSession = libsignal.SessionRecord.deserialize(pnSession)
|
const fromSession = libsignal.SessionRecord.deserialize(pnSession)
|
||||||
if (fromSession.haveOpenSession()) {
|
if (fromSession.haveOpenSession()) {
|
||||||
// Queue for bulk update: copy to LID, delete from PN
|
// Queue for bulk update: copy to LID, retain PN session.
|
||||||
|
// WABA retains both PN and LID sessions during migration to avoid
|
||||||
|
// No Session errors if messages arrive via PN before migration completes.
|
||||||
sessionUpdates[lidAddrStr] = fromSession.serialize()
|
sessionUpdates[lidAddrStr] = fromSession.serialize()
|
||||||
sessionUpdates[pnAddrStr] = null
|
|
||||||
|
|
||||||
migratedCount++
|
migratedCount++
|
||||||
}
|
}
|
||||||
@@ -776,6 +797,13 @@ function signalStorage(
|
|||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delayed PreKey deletion: grace period to handle race conditions
|
||||||
|
// where two pkmsg with the same preKeyId arrive nearly simultaneously.
|
||||||
|
// WABA deletes immediately (33ms), but we add a 5-min grace period
|
||||||
|
// because we can't handle "Invalid PreKey ID" errors at the native level.
|
||||||
|
const PREKEY_GRACE_PERIOD_MS = 5 * 60 * 1000 // 5 minutes
|
||||||
|
const pendingPreKeyDeletions = new Map<string, ReturnType<typeof setTimeout>>()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
loadSession: async (id: string) => {
|
loadSession: async (id: string) => {
|
||||||
try {
|
try {
|
||||||
@@ -808,7 +836,26 @@ function signalStorage(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
removePreKey: (id: number) => keys.set({ 'pre-key': { [id]: null } }),
|
removePreKey: (id: number) => {
|
||||||
|
const keyId = id.toString()
|
||||||
|
// Clear any existing timer for this key
|
||||||
|
const existing = pendingPreKeyDeletions.get(keyId)
|
||||||
|
if (existing) {
|
||||||
|
clearTimeout(existing)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule deletion after grace period
|
||||||
|
const timer = setTimeout(async () => {
|
||||||
|
pendingPreKeyDeletions.delete(keyId)
|
||||||
|
try {
|
||||||
|
await keys.set({ 'pre-key': { [id]: null } })
|
||||||
|
} catch {
|
||||||
|
// Keystore may be destroyed if connection closed — safe to ignore
|
||||||
|
}
|
||||||
|
}, PREKEY_GRACE_PERIOD_MS)
|
||||||
|
|
||||||
|
pendingPreKeyDeletions.set(keyId, timer)
|
||||||
|
},
|
||||||
loadSignedPreKey: () => {
|
loadSignedPreKey: () => {
|
||||||
const key = creds.signedPreKey
|
const key = creds.signedPreKey
|
||||||
return {
|
return {
|
||||||
@@ -898,14 +945,24 @@ function signalStorage(
|
|||||||
// IDENTITY KEY CHANGED - contact reinstalled WhatsApp or switched devices
|
// IDENTITY KEY CHANGED - contact reinstalled WhatsApp or switched devices
|
||||||
const previousFingerprint = generateKeyFingerprint(existingKey)
|
const previousFingerprint = generateKeyFingerprint(existingKey)
|
||||||
|
|
||||||
// Delete old session and save new identity key atomically
|
// Delete old session and save new identity key atomically.
|
||||||
|
// Store identity in BOTH LID and PN addresses (WABA stores in both
|
||||||
|
// recipient_account_type=0 and type=1 with CONFLICT_REPLACE).
|
||||||
|
const identityUpdates: Record<string, Uint8Array> = { [wireJid]: identityKey }
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityUpdates[id] = identityKey
|
||||||
|
}
|
||||||
|
|
||||||
await keys.set({
|
await keys.set({
|
||||||
session: { [wireJid]: null },
|
session: { [wireJid]: null },
|
||||||
'identity-key': { [wireJid]: identityKey }
|
'identity-key': identityUpdates
|
||||||
})
|
})
|
||||||
|
|
||||||
// Update cache
|
// Update cache for both addresses
|
||||||
identityKeyCache.set(wireJid, identityKey)
|
identityKeyCache.set(wireJid, identityKey)
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityKeyCache.set(id, identityKey)
|
||||||
|
}
|
||||||
|
|
||||||
// Record metrics
|
// Record metrics
|
||||||
metrics.signalIdentityChanges?.inc({ type: 'changed' })
|
metrics.signalIdentityChanges?.inc({ type: 'changed' })
|
||||||
@@ -941,10 +998,19 @@ function signalStorage(
|
|||||||
|
|
||||||
if (!existingKey) {
|
if (!existingKey) {
|
||||||
// NEW CONTACT - Trust On First Use (TOFU)
|
// NEW CONTACT - Trust On First Use (TOFU)
|
||||||
await keys.set({ 'identity-key': { [wireJid]: identityKey } })
|
// Store in both LID and PN addresses (aligned with WABA dual identity storage)
|
||||||
|
const identityUpdates: Record<string, Uint8Array> = { [wireJid]: identityKey }
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityUpdates[id] = identityKey
|
||||||
|
}
|
||||||
|
|
||||||
// Update cache
|
await keys.set({ 'identity-key': identityUpdates })
|
||||||
|
|
||||||
|
// Update cache for both addresses
|
||||||
identityKeyCache.set(wireJid, identityKey)
|
identityKeyCache.set(wireJid, identityKey)
|
||||||
|
if (wireJid !== id) {
|
||||||
|
identityKeyCache.set(id, identityKey)
|
||||||
|
}
|
||||||
|
|
||||||
// Record metrics
|
// Record metrics
|
||||||
metrics.signalIdentityChanges?.inc({ type: 'new' })
|
metrics.signalIdentityChanges?.inc({ type: 'new' })
|
||||||
|
|||||||
+40
-13
@@ -50,7 +50,8 @@ import {
|
|||||||
isMissingKeyError,
|
isMissingKeyError,
|
||||||
MAX_SYNC_ATTEMPTS,
|
MAX_SYNC_ATTEMPTS,
|
||||||
newLTHashState,
|
newLTHashState,
|
||||||
processSyncAction
|
processSyncAction,
|
||||||
|
resolveLidToPn
|
||||||
} from '../Utils'
|
} from '../Utils'
|
||||||
import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex'
|
import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex'
|
||||||
import processMessage from '../Utils/process-message'
|
import processMessage from '../Utils/process-message'
|
||||||
@@ -757,9 +758,16 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}, authState?.creds?.me?.id || 'resync-app-state')
|
}, authState?.creds?.me?.id || 'resync-app-state')
|
||||||
|
|
||||||
const { onMutation } = newAppStateChunkHandler(isInitialSync)
|
const { onMutation } = newAppStateChunkHandler(isInitialSync)
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
for (const key in globalMutationMap) {
|
for (const key in globalMutationMap) {
|
||||||
const mutation = globalMutationMap[key]
|
const mutation = globalMutationMap[key]
|
||||||
if (!mutation) continue
|
if (!mutation) continue
|
||||||
|
// Normalize LID→PN in sync action index[1] (chat/contact ID)
|
||||||
|
if (mutation.index[1] && isAnyLidUser(mutation.index[1])) {
|
||||||
|
const resolved = await resolveLidToPn(mutation.index[1], lidMapping, logger)
|
||||||
|
if (resolved) mutation.index[1] = resolved
|
||||||
|
}
|
||||||
|
|
||||||
onMutation(mutation)
|
onMutation(mutation)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -912,16 +920,16 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const handlePresenceUpdate = ({ tag, attrs, content }: BinaryNode) => {
|
const handlePresenceUpdate = async ({ tag, attrs, content }: BinaryNode) => {
|
||||||
let presence: PresenceData | undefined
|
let presence: PresenceData | undefined
|
||||||
const jid = attrs.from
|
const rawJid = attrs.from
|
||||||
const participant = attrs.participant || attrs.from
|
const rawParticipant = attrs.participant || attrs.from
|
||||||
if (!jid) {
|
if (!rawJid) {
|
||||||
logger.warn({ attrs }, 'handlePresenceUpdate: jid (attrs.from) is missing, skipping')
|
logger.warn({ attrs }, 'handlePresenceUpdate: jid (attrs.from) is missing, skipping')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
|
if (shouldIgnoreJid(rawJid) && rawJid !== S_WHATSAPP_NET) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -933,7 +941,7 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
} else if (Array.isArray(content)) {
|
} else if (Array.isArray(content)) {
|
||||||
const [firstChild] = content
|
const [firstChild] = content
|
||||||
if (!firstChild) {
|
if (!firstChild) {
|
||||||
logger.warn({ jid }, 'handlePresenceUpdate: firstChild content is empty, skipping')
|
logger.warn({ jid: rawJid }, 'handlePresenceUpdate: firstChild content is empty, skipping')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -952,12 +960,19 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (presence) {
|
if (presence) {
|
||||||
if (!participant) {
|
if (!rawParticipant) {
|
||||||
logger.warn({ jid }, 'handlePresenceUpdate: participant is missing, skipping')
|
logger.warn({ jid: rawJid }, 'handlePresenceUpdate: participant is missing, skipping')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
|
// Resolve LID→PN so consumers always see phone-number JIDs
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
|
const [jid, participant] = await Promise.all([
|
||||||
|
resolveLidToPn(rawJid, lidMapping, logger),
|
||||||
|
resolveLidToPn(rawParticipant, lidMapping, logger)
|
||||||
|
])
|
||||||
|
|
||||||
|
ev.emit('presence.update', { id: jid!, presences: { [participant!]: presence } })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1031,8 +1046,16 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
undefined,
|
undefined,
|
||||||
logger
|
logger
|
||||||
)
|
)
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
for (const key in mutationMap) {
|
for (const key in mutationMap) {
|
||||||
onMutation(mutationMap[key]!)
|
const mutation = mutationMap[key]!
|
||||||
|
// Normalize LID→PN in sync action index[1] (chat/contact ID)
|
||||||
|
if (mutation.index[1] && isAnyLidUser(mutation.index[1])) {
|
||||||
|
const resolved = await resolveLidToPn(mutation.index[1], lidMapping, logger)
|
||||||
|
if (resolved) mutation.index[1] = resolved
|
||||||
|
}
|
||||||
|
|
||||||
|
onMutation(mutation)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1376,8 +1399,12 @@ export const makeChatsSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
ws.on('CB:presence', handlePresenceUpdate)
|
ws.on('CB:presence', (node: BinaryNode) => {
|
||||||
ws.on('CB:chatstate', handlePresenceUpdate)
|
handlePresenceUpdate(node).catch(err => onUnexpectedError(err, 'handling presence update'))
|
||||||
|
})
|
||||||
|
ws.on('CB:chatstate', (node: BinaryNode) => {
|
||||||
|
handlePresenceUpdate(node).catch(err => onUnexpectedError(err, 'handling chatstate update'))
|
||||||
|
})
|
||||||
|
|
||||||
ws.on('CB:ib,,dirty', async (node: BinaryNode) => {
|
ws.on('CB:ib,,dirty', async (node: BinaryNode) => {
|
||||||
const { attrs } = getBinaryNodeChild(node, 'dirty')!
|
const { attrs } = getBinaryNodeChild(node, 'dirty')!
|
||||||
|
|||||||
+43
-7
@@ -1,7 +1,7 @@
|
|||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type { GroupMetadata, GroupParticipant, ParticipantAction, SocketConfig, WAMessageKey } from '../Types'
|
import type { GroupMetadata, GroupParticipant, ParticipantAction, SocketConfig, WAMessageKey } from '../Types'
|
||||||
import { WAMessageAddressingMode, WAMessageStubType } from '../Types'
|
import { WAMessageAddressingMode, WAMessageStubType } from '../Types'
|
||||||
import { generateMessageIDV2, unixTimestampSeconds } from '../Utils'
|
import { generateMessageIDV2, resolveLidToPn, unixTimestampSeconds } from '../Utils'
|
||||||
import {
|
import {
|
||||||
type BinaryNode,
|
type BinaryNode,
|
||||||
getBinaryNodeChild,
|
getBinaryNodeChild,
|
||||||
@@ -17,6 +17,43 @@ import { makeChatsSocket } from './chats'
|
|||||||
export const makeGroupsSocket = (config: SocketConfig) => {
|
export const makeGroupsSocket = (config: SocketConfig) => {
|
||||||
const sock = makeChatsSocket(config)
|
const sock = makeChatsSocket(config)
|
||||||
const { authState, ev, query, upsertMessage } = sock
|
const { authState, ev, query, upsertMessage } = sock
|
||||||
|
const { signalRepository } = sock
|
||||||
|
const { logger } = config
|
||||||
|
|
||||||
|
/** Normalize group metadata participant IDs from LID to PN */
|
||||||
|
const normalizeGroupMetadata = async (metadata: GroupMetadata): Promise<GroupMetadata> => {
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
|
|
||||||
|
// Resolve all participant LIDs in parallel for better performance on large groups
|
||||||
|
await Promise.all(metadata.participants.map(async (p) => {
|
||||||
|
if (isLidUser(p.id)) {
|
||||||
|
if (p.phoneNumber) {
|
||||||
|
p.lid = p.id
|
||||||
|
p.id = p.phoneNumber
|
||||||
|
} else {
|
||||||
|
const resolved = await resolveLidToPn(p.id, lidMapping, logger)
|
||||||
|
if (resolved && resolved !== p.id) {
|
||||||
|
p.lid = p.id
|
||||||
|
p.id = resolved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Normalize owner/subjectOwner if LID (parallel)
|
||||||
|
const [resolvedOwner, resolvedSubjectOwner] = await Promise.all([
|
||||||
|
metadata.owner && isLidUser(metadata.owner)
|
||||||
|
? (metadata.ownerPn || resolveLidToPn(metadata.owner, lidMapping, logger))
|
||||||
|
: null,
|
||||||
|
metadata.subjectOwner && isLidUser(metadata.subjectOwner)
|
||||||
|
? (metadata.subjectOwnerPn || resolveLidToPn(metadata.subjectOwner, lidMapping, logger))
|
||||||
|
: null
|
||||||
|
])
|
||||||
|
if (resolvedOwner) metadata.owner = resolvedOwner
|
||||||
|
if (resolvedSubjectOwner) metadata.subjectOwner = resolvedSubjectOwner
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
}
|
||||||
|
|
||||||
const groupQuery = async (jid: string, type: 'get' | 'set', content: BinaryNode[]) =>
|
const groupQuery = async (jid: string, type: 'get' | 'set', content: BinaryNode[]) =>
|
||||||
query({
|
query({
|
||||||
@@ -31,7 +68,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const groupMetadata = async (jid: string) => {
|
const groupMetadata = async (jid: string) => {
|
||||||
const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
|
const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }])
|
||||||
return extractGroupMetadata(result)
|
return normalizeGroupMetadata(extractGroupMetadata(result))
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupFetchAllParticipating = async () => {
|
const groupFetchAllParticipating = async () => {
|
||||||
@@ -58,16 +95,15 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
if (groupsChild) {
|
if (groupsChild) {
|
||||||
const groups = getBinaryNodeChildren(groupsChild, 'group')
|
const groups = getBinaryNodeChildren(groupsChild, 'group')
|
||||||
for (const groupNode of groups) {
|
for (const groupNode of groups) {
|
||||||
const meta = extractGroupMetadata({
|
const meta = await normalizeGroupMetadata(extractGroupMetadata({
|
||||||
tag: 'result',
|
tag: 'result',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: [groupNode]
|
content: [groupNode]
|
||||||
})
|
}))
|
||||||
data[meta.id] = meta
|
data[meta.id] = meta
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: properly parse LID / PN DATA
|
|
||||||
sock.ev.emit('groups.update', Object.values(data))
|
sock.ev.emit('groups.update', Object.values(data))
|
||||||
|
|
||||||
return data
|
return data
|
||||||
@@ -101,7 +137,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
])
|
])
|
||||||
return extractGroupMetadata(result)
|
return normalizeGroupMetadata(extractGroupMetadata(result))
|
||||||
},
|
},
|
||||||
groupLeave: async (id: string) => {
|
groupLeave: async (id: string) => {
|
||||||
await groupQuery('@g.us', 'set', [
|
await groupQuery('@g.us', 'set', [
|
||||||
@@ -277,7 +313,7 @@ export const makeGroupsSocket = (config: SocketConfig) => {
|
|||||||
),
|
),
|
||||||
groupGetInviteInfo: async (code: string) => {
|
groupGetInviteInfo: async (code: string) => {
|
||||||
const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
|
const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }])
|
||||||
return extractGroupMetadata(results)
|
return normalizeGroupMetadata(extractGroupMetadata(results))
|
||||||
},
|
},
|
||||||
groupToggleEphemeral: async (jid: string, ephemeralExpiration: number) => {
|
groupToggleEphemeral: async (jid: string, ephemeralExpiration: number) => {
|
||||||
const content: BinaryNode = ephemeralExpiration
|
const content: BinaryNode = ephemeralExpiration
|
||||||
|
|||||||
+305
-52
@@ -31,6 +31,7 @@ import {
|
|||||||
aesDecryptCTR,
|
aesDecryptCTR,
|
||||||
aesEncryptGCM,
|
aesEncryptGCM,
|
||||||
cleanMessage,
|
cleanMessage,
|
||||||
|
cleanupCorruptedSession,
|
||||||
Curve,
|
Curve,
|
||||||
decodeMediaRetryNode,
|
decodeMediaRetryNode,
|
||||||
decodeMessageNode,
|
decodeMessageNode,
|
||||||
@@ -41,6 +42,7 @@ import {
|
|||||||
encodeSignedDeviceIdentity,
|
encodeSignedDeviceIdentity,
|
||||||
extractAddressingContext,
|
extractAddressingContext,
|
||||||
getCallStatusFromNode,
|
getCallStatusFromNode,
|
||||||
|
getDecryptionJid,
|
||||||
getHistoryMsg,
|
getHistoryMsg,
|
||||||
getNextPreKeys,
|
getNextPreKeys,
|
||||||
getStatusFromReceiptType,
|
getStatusFromReceiptType,
|
||||||
@@ -49,7 +51,9 @@ import {
|
|||||||
MISSING_KEYS_ERROR_TEXT,
|
MISSING_KEYS_ERROR_TEXT,
|
||||||
NACK_REASONS,
|
NACK_REASONS,
|
||||||
NO_MESSAGE_FOUND_ERROR_TEXT,
|
NO_MESSAGE_FOUND_ERROR_TEXT,
|
||||||
|
normalizeKeyLidToPn,
|
||||||
normalizeMessageJids,
|
normalizeMessageJids,
|
||||||
|
resolveLidToPn,
|
||||||
SERVER_ERROR_CODES,
|
SERVER_ERROR_CODES,
|
||||||
toNumber,
|
toNumber,
|
||||||
unixTimestampSeconds,
|
unixTimestampSeconds,
|
||||||
@@ -65,7 +69,7 @@ import {
|
|||||||
recordMessageReceived,
|
recordMessageReceived,
|
||||||
recordMessageRetry
|
recordMessageRetry
|
||||||
} from '../Utils/prometheus-metrics.js'
|
} from '../Utils/prometheus-metrics.js'
|
||||||
import { isTcTokenExpired, resolveTcTokenJid } from '../Utils/tc-token-utils'
|
import { isTcTokenExpired, resolveTcTokenJid, storeTcTokensFromIqResult } from '../Utils/tc-token-utils'
|
||||||
import {
|
import {
|
||||||
areJidsSameUser,
|
areJidsSameUser,
|
||||||
type BinaryNode,
|
type BinaryNode,
|
||||||
@@ -160,6 +164,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
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>()
|
||||||
|
|
||||||
|
// Deduplicates retry requests per JID within a short window.
|
||||||
|
// When a burst of Bad MAC errors arrives for the same contact,
|
||||||
|
// only the first retry request is sent — the peer resends everything
|
||||||
|
// with a single pkmsg, avoiding the close-session cascade.
|
||||||
|
const retryRequestActiveJids = new Set<string>()
|
||||||
let tcTokenIndexSaveTimer: ReturnType<typeof setTimeout> | undefined
|
let tcTokenIndexSaveTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
let lastTcTokenPruneTs = 0
|
let lastTcTokenPruneTs = 0
|
||||||
|
|
||||||
@@ -365,10 +375,14 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
case 'NotificationNewsletterAdminPromote':
|
case 'NotificationNewsletterAdminPromote':
|
||||||
for (const update of updates) {
|
for (const update of updates) {
|
||||||
if (update.jid && update.user) {
|
if (update.jid && update.user) {
|
||||||
|
const [resolvedAuthor, resolvedUser] = await Promise.all([
|
||||||
|
resolveLidToPn(node.attrs.from!, signalRepository.lidMapping, logger),
|
||||||
|
resolveLidToPn(update.user, signalRepository.lidMapping, logger)
|
||||||
|
])
|
||||||
ev.emit('newsletter-participants.update', {
|
ev.emit('newsletter-participants.update', {
|
||||||
id: update.jid,
|
id: update.jid,
|
||||||
author: node.attrs.from!,
|
author: resolvedAuthor || node.attrs.from!,
|
||||||
user: update.user,
|
user: resolvedUser || update.user,
|
||||||
new_role: 'ADMIN',
|
new_role: 'ADMIN',
|
||||||
action: 'promote'
|
action: 'promote'
|
||||||
})
|
})
|
||||||
@@ -387,7 +401,9 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const handleNewsletterNotification = async (node: BinaryNode) => {
|
const handleNewsletterNotification = async (node: BinaryNode) => {
|
||||||
const from = node.attrs.from!
|
const from = node.attrs.from!
|
||||||
const child = getAllBinaryNodeChildren(node)[0]!
|
const child = getAllBinaryNodeChildren(node)[0]!
|
||||||
const author = node.attrs.participant!
|
const rawAuthor = node.attrs.participant!
|
||||||
|
// Resolve author LID→PN (participant is a user JID that could be LID)
|
||||||
|
const author = await resolveLidToPn(rawAuthor, signalRepository.lidMapping, logger) || rawAuthor
|
||||||
|
|
||||||
logger.info({ from, child }, 'got newsletter notification')
|
logger.info({ from, child }, 'got newsletter notification')
|
||||||
|
|
||||||
@@ -414,10 +430,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
break
|
break
|
||||||
|
|
||||||
case 'participant':
|
case 'participant':
|
||||||
|
const resolvedParticipantUser = await resolveLidToPn(child.attrs.jid!, signalRepository.lidMapping, logger) || child.attrs.jid!
|
||||||
const participantUpdate = {
|
const participantUpdate = {
|
||||||
id: from,
|
id: from,
|
||||||
author,
|
author,
|
||||||
user: child.attrs.jid!,
|
user: resolvedParticipantUser,
|
||||||
action: child.attrs.action!,
|
action: child.attrs.action!,
|
||||||
new_role: child.attrs.role!
|
new_role: child.attrs.role!
|
||||||
}
|
}
|
||||||
@@ -1200,12 +1217,50 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const { key: msgKey } = fullMessage
|
const { key: msgKey } = fullMessage
|
||||||
const msgId = msgKey.id!
|
const msgId = msgKey.id!
|
||||||
|
|
||||||
|
// Per-JID deduplication: when multiple messages from the same contact
|
||||||
|
// fail with Bad MAC simultaneously, only send ONE retry request.
|
||||||
|
// The peer will resend all failed messages when it receives the retry receipt.
|
||||||
|
// For group messages, scope by participant (each participant has its own Signal session).
|
||||||
|
const retryDedupeJid = msgKey.participant
|
||||||
|
? jidNormalizedUser(msgKey.participant)
|
||||||
|
: jidNormalizedUser(node.attrs.from!)
|
||||||
|
if (retryRequestActiveJids.has(retryDedupeJid)) {
|
||||||
|
logger.debug(
|
||||||
|
{ fromJid: retryDedupeJid, msgId },
|
||||||
|
'Skipping duplicate retry request — already in-flight for this JID'
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (messageRetryManager) {
|
if (messageRetryManager) {
|
||||||
// Check if we've exceeded max retries using the new system
|
// Check if we've exceeded max retries using the new system
|
||||||
if (messageRetryManager.hasExceededMaxRetries(msgId)) {
|
if (messageRetryManager.hasExceededMaxRetries(msgId)) {
|
||||||
logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing')
|
logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing')
|
||||||
messageRetryManager.markRetryFailed(msgId)
|
messageRetryManager.markRetryFailed(msgId)
|
||||||
recordMessageFailure('retry', 'max_retries_reached')
|
recordMessageFailure('retry', 'max_retries_reached')
|
||||||
|
|
||||||
|
// Safety net: clean up corrupted sessions only after all retries exhausted.
|
||||||
|
// This avoids the cascading delete loop that occurs when cleanup runs
|
||||||
|
// on every Bad MAC in the hot path (decode-wa-message.ts).
|
||||||
|
// The Signal Protocol recovers naturally via retry+pkmsg for most cases;
|
||||||
|
// this cleanup only runs as a last resort.
|
||||||
|
// For group messages, use participant JID (Signal sessions are per-participant, not per-group).
|
||||||
|
if (autoCleanCorrupted) {
|
||||||
|
const senderJid = msgKey.participant ? jidNormalizedUser(msgKey.participant) : jidNormalizedUser(node.attrs.from!)
|
||||||
|
try {
|
||||||
|
const decryptionJid = await getDecryptionJid(senderJid, signalRepository)
|
||||||
|
const deletedCount = await cleanupCorruptedSession(decryptionJid, signalRepository, logger)
|
||||||
|
if (deletedCount > 0) {
|
||||||
|
logger.info(
|
||||||
|
{ msgId, jid: decryptionJid, targetedDevices: deletedCount },
|
||||||
|
`🔄 Session cleanup (retry exhausted) | Targeted: ${deletedCount} devices`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (cleanupErr) {
|
||||||
|
logger.warn({ msgId, senderJid, err: cleanupErr }, 'Failed to cleanup session after retry exhaustion')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1224,6 +1279,18 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
logger.debug({ retryCount, msgId }, 'reached retry limit, clearing')
|
logger.debug({ retryCount, msgId }, 'reached retry limit, clearing')
|
||||||
await msgRetryCache.del(key)
|
await msgRetryCache.del(key)
|
||||||
recordMessageFailure('retry', 'max_retries_reached')
|
recordMessageFailure('retry', 'max_retries_reached')
|
||||||
|
|
||||||
|
// Safety net cleanup (same as new system above)
|
||||||
|
if (autoCleanCorrupted) {
|
||||||
|
const senderJid = msgKey.participant ? jidNormalizedUser(msgKey.participant) : jidNormalizedUser(node.attrs.from!)
|
||||||
|
try {
|
||||||
|
const decryptionJid = await getDecryptionJid(senderJid, signalRepository)
|
||||||
|
await cleanupCorruptedSession(decryptionJid, signalRepository, logger)
|
||||||
|
} catch (cleanupErr) {
|
||||||
|
logger.warn({ msgId, senderJid, err: cleanupErr }, 'Failed to cleanup session after retry exhaustion')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1232,6 +1299,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
recordMessageRetry('retry')
|
recordMessageRetry('retry')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Register dedup AFTER early-return checks so that max-retries paths
|
||||||
|
// don't block subsequent messages from the same JID for 5 seconds.
|
||||||
|
retryRequestActiveJids.add(retryDedupeJid)
|
||||||
|
setTimeout(() => retryRequestActiveJids.delete(retryDedupeJid), 5_000)
|
||||||
|
|
||||||
const key = `${msgId}:${msgKey?.participant}`
|
const key = `${msgId}:${msgKey?.participant}`
|
||||||
const retryCount = (await msgRetryCache.get<number>(key)) || 1
|
const retryCount = (await msgRetryCache.get<number>(key)) || 1
|
||||||
|
|
||||||
@@ -1242,7 +1314,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
let shouldRecreateSession = false
|
let shouldRecreateSession = false
|
||||||
let recreateReason = ''
|
let recreateReason = ''
|
||||||
|
|
||||||
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
|
if (enableAutoSessionRecreation && messageRetryManager && retryCount >= 1) {
|
||||||
try {
|
try {
|
||||||
// Check if we have a session with this JID
|
// Check if we have a session with this JID
|
||||||
const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
|
const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid)
|
||||||
@@ -1381,6 +1453,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// When a session is refreshed (identity change), re-issue tctoken fire-and-forget
|
// 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') {
|
if (result.action === 'session_refreshed') {
|
||||||
const normalizedJid = jidNormalizedUser(from)
|
const normalizedJid = jidNormalizedUser(from)
|
||||||
resolveTcTokenJid(normalizedJid, getLIDForPN)
|
resolveTcTokenJid(normalizedJid, getLIDForPN)
|
||||||
@@ -1390,9 +1463,36 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
if (entry?.token?.length && !isTcTokenExpired(entry.timestamp)) {
|
if (entry?.token?.length && !isTcTokenExpired(entry.timestamp)) {
|
||||||
const senderTs = unixTimestampSeconds()
|
const senderTs = unixTimestampSeconds()
|
||||||
logTcToken('reissue', { jid: normalizedJid, reason: 'session_refreshed' })
|
logTcToken('reissue', { jid: normalizedJid, reason: 'session_refreshed' })
|
||||||
getPrivacyTokens([normalizedJid], senderTs).catch(err => {
|
getPrivacyTokens([normalizedJid], senderTs)
|
||||||
logTcToken('reissue_fail', { jid: normalizedJid, error: err?.message })
|
.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(() => {
|
.catch(() => {
|
||||||
@@ -1406,8 +1506,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleGroupNotification = (fullNode: BinaryNode, child: BinaryNode, msg: Partial<WAMessage>) => {
|
const handleGroupNotification = async (fullNode: BinaryNode, child: BinaryNode, msg: Partial<WAMessage>) => {
|
||||||
// TODO: Support PN/LID (Here is only LID now)
|
const lidMapping = signalRepository.lidMapping
|
||||||
|
|
||||||
const actingParticipantLid = fullNode.attrs.participant
|
const actingParticipantLid = fullNode.attrs.participant
|
||||||
const actingParticipantPn = fullNode.attrs.participant_pn
|
const actingParticipantPn = fullNode.attrs.participant_pn
|
||||||
@@ -1415,13 +1515,52 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid!
|
const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid!
|
||||||
const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn!
|
const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn!
|
||||||
|
|
||||||
|
// Resolve acting participant to PN — prefer inline PN, fall back to LID→PN resolution
|
||||||
|
const actingParticipant = actingParticipantPn
|
||||||
|
|| await resolveLidToPn(actingParticipantLid, lidMapping, logger)
|
||||||
|
|
||||||
|
// Resolve affected participant to PN
|
||||||
|
const affectedParticipant = affectedParticipantPn
|
||||||
|
|| await resolveLidToPn(affectedParticipantLid, lidMapping, logger)
|
||||||
|
|
||||||
|
// Store LID↔PN mappings from notification attributes
|
||||||
|
const mappingsToStore: Array<{ lid: string; pn: string }> = []
|
||||||
|
if (actingParticipantLid && actingParticipantPn && isLidUser(actingParticipantLid) && isPnUser(actingParticipantPn)) {
|
||||||
|
mappingsToStore.push({ lid: actingParticipantLid, pn: actingParticipantPn })
|
||||||
|
}
|
||||||
|
|
||||||
switch (child?.tag) {
|
switch (child?.tag) {
|
||||||
case 'create':
|
case 'create':
|
||||||
const metadata = extractGroupMetadata(child)
|
const metadata = extractGroupMetadata(child)
|
||||||
|
|
||||||
|
// Normalize group metadata participant IDs to PN
|
||||||
|
for (const p of metadata.participants) {
|
||||||
|
if (isLidUser(p.id)) {
|
||||||
|
// Use inline phoneNumber if available, otherwise resolve via mapping
|
||||||
|
if (p.phoneNumber) {
|
||||||
|
// Store the mapping
|
||||||
|
mappingsToStore.push({ lid: p.id, pn: p.phoneNumber })
|
||||||
|
p.lid = p.id
|
||||||
|
p.id = p.phoneNumber
|
||||||
|
} else {
|
||||||
|
const resolved = await resolveLidToPn(p.id, lidMapping, logger)
|
||||||
|
if (resolved && resolved !== p.id) {
|
||||||
|
p.lid = p.id
|
||||||
|
p.id = resolved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve metadata owner to PN
|
||||||
|
if (metadata.owner && isLidUser(metadata.owner)) {
|
||||||
|
const resolvedOwner = metadata.ownerPn || await resolveLidToPn(metadata.owner, lidMapping, logger)
|
||||||
|
if (resolvedOwner) metadata.owner = resolvedOwner
|
||||||
|
}
|
||||||
|
|
||||||
msg.messageStubType = WAMessageStubType.GROUP_CREATE
|
msg.messageStubType = WAMessageStubType.GROUP_CREATE
|
||||||
msg.messageStubParameters = [metadata.subject]
|
msg.messageStubParameters = [metadata.subject]
|
||||||
msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn }
|
msg.key = { participant: actingParticipant }
|
||||||
|
|
||||||
ev.emit('chats.upsert', [
|
ev.emit('chats.upsert', [
|
||||||
{
|
{
|
||||||
@@ -1433,8 +1572,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
ev.emit('groups.upsert', [
|
ev.emit('groups.upsert', [
|
||||||
{
|
{
|
||||||
...metadata,
|
...metadata,
|
||||||
author: actingParticipantLid,
|
author: actingParticipant
|
||||||
authorPn: actingParticipantPn
|
|
||||||
}
|
}
|
||||||
])
|
])
|
||||||
break
|
break
|
||||||
@@ -1448,8 +1586,13 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
break
|
break
|
||||||
case 'modify':
|
case 'modify':
|
||||||
const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid!)
|
const oldNumbers = await Promise.all(
|
||||||
msg.messageStubParameters = oldNumber || []
|
getBinaryNodeChildren(child, 'participant').map(async p => {
|
||||||
|
const resolved = await resolveLidToPn(p.attrs.jid!, lidMapping, logger)
|
||||||
|
return resolved || p.attrs.jid!
|
||||||
|
})
|
||||||
|
)
|
||||||
|
msg.messageStubParameters = oldNumbers || []
|
||||||
msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
|
msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
|
||||||
break
|
break
|
||||||
case 'promote':
|
case 'promote':
|
||||||
@@ -1460,21 +1603,48 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`
|
const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`
|
||||||
msg.messageStubType = WAMessageStubType[stubType as keyof typeof WAMessageStubType]
|
msg.messageStubType = WAMessageStubType[stubType as keyof typeof WAMessageStubType]
|
||||||
|
|
||||||
const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
|
const participants = await Promise.all(
|
||||||
// TODO: Store LID MAPPINGS
|
getBinaryNodeChildren(child, 'participant').map(async ({ attrs }) => {
|
||||||
return {
|
const rawJid = attrs.jid!
|
||||||
id: attrs.jid!,
|
let id = rawJid
|
||||||
phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
|
let phoneNumber: string | undefined
|
||||||
lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
|
let lid: string | undefined
|
||||||
admin: (attrs.type || null) as GroupParticipant['admin']
|
|
||||||
}
|
if (isLidUser(rawJid)) {
|
||||||
})
|
// Primary is LID — resolve to PN
|
||||||
|
phoneNumber = isPnUser(attrs.phone_number) ? attrs.phone_number : undefined
|
||||||
|
if (phoneNumber) {
|
||||||
|
mappingsToStore.push({ lid: rawJid, pn: phoneNumber })
|
||||||
|
lid = rawJid
|
||||||
|
id = phoneNumber
|
||||||
|
} else {
|
||||||
|
const resolved = await resolveLidToPn(rawJid, lidMapping, logger)
|
||||||
|
if (resolved && resolved !== rawJid) {
|
||||||
|
lid = rawJid
|
||||||
|
id = resolved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (isPnUser(rawJid) && isLidUser(attrs.lid)) {
|
||||||
|
// Primary is PN — store LID for reference
|
||||||
|
lid = attrs.lid
|
||||||
|
mappingsToStore.push({ lid: attrs.lid!, pn: rawJid })
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
phoneNumber,
|
||||||
|
lid,
|
||||||
|
admin: (attrs.type || null) as GroupParticipant['admin']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
participants.length === 1 &&
|
participants.length === 1 &&
|
||||||
// if recv. "remove" message and sender removed themselves
|
// if recv. "remove" message and sender removed themselves
|
||||||
// mark as left
|
// mark as left
|
||||||
(areJidsSameUser(participants[0]!.id, actingParticipantLid) ||
|
(areJidsSameUser(participants[0]!.id, actingParticipant) ||
|
||||||
|
areJidsSameUser(participants[0]!.id, actingParticipantLid) ||
|
||||||
areJidsSameUser(participants[0]!.id, actingParticipantPn)) &&
|
areJidsSameUser(participants[0]!.id, actingParticipantPn)) &&
|
||||||
child.tag === 'remove'
|
child.tag === 'remove'
|
||||||
) {
|
) {
|
||||||
@@ -1525,21 +1695,27 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
case 'created_membership_requests':
|
case 'created_membership_requests':
|
||||||
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
|
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
|
||||||
msg.messageStubParameters = [
|
msg.messageStubParameters = [
|
||||||
JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
|
JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipant }),
|
||||||
'created',
|
'created',
|
||||||
child.attrs.request_method!
|
child.attrs.request_method!
|
||||||
]
|
]
|
||||||
break
|
break
|
||||||
case 'revoked_membership_requests':
|
case 'revoked_membership_requests':
|
||||||
const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid)
|
const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid)
|
||||||
// TODO: LIDMAPPING SUPPORT
|
|
||||||
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
|
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
|
||||||
msg.messageStubParameters = [
|
msg.messageStubParameters = [
|
||||||
JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
|
JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipant }),
|
||||||
isDenied ? 'revoked' : 'rejected'
|
isDenied ? 'revoked' : 'rejected'
|
||||||
]
|
]
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Persist any LID↔PN mappings discovered from notification attributes
|
||||||
|
if (mappingsToStore.length) {
|
||||||
|
await lidMapping.storeLIDPNMappings(mappingsToStore).catch(err => {
|
||||||
|
logger.warn({ err, count: mappingsToStore.length }, 'Failed to store LID↔PN mappings from group notification')
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const processNotification = async (node: BinaryNode) => {
|
const processNotification = async (node: BinaryNode) => {
|
||||||
@@ -1556,11 +1732,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
await handleMexNewsletterNotification(node)
|
await handleMexNewsletterNotification(node)
|
||||||
break
|
break
|
||||||
case 'w:gp2':
|
case 'w:gp2':
|
||||||
// TODO: HANDLE PARTICIPANT_PN
|
await handleGroupNotification(node, child!, result)
|
||||||
handleGroupNotification(node, child!, result)
|
|
||||||
break
|
break
|
||||||
case 'mediaretry':
|
case 'mediaretry':
|
||||||
const event = decodeMediaRetryNode(node)
|
const event = decodeMediaRetryNode(node)
|
||||||
|
// Normalize LID→PN in media retry key before emitting
|
||||||
|
await normalizeKeyLidToPn(event.key, signalRepository.lidMapping, logger)
|
||||||
ev.emit('messages.media-update', [event])
|
ev.emit('messages.media-update', [event])
|
||||||
break
|
break
|
||||||
case 'encrypt':
|
case 'encrypt':
|
||||||
@@ -1591,13 +1768,16 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const setPicture = getBinaryNodeChild(node, 'set')
|
const setPicture = getBinaryNodeChild(node, 'set')
|
||||||
const delPicture = getBinaryNodeChild(node, 'delete')
|
const delPicture = getBinaryNodeChild(node, 'delete')
|
||||||
|
|
||||||
// TODO: WAJIDHASH stuff proper support inhouse
|
{
|
||||||
ev.emit('contacts.update', [
|
const rawPictureJid = jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || ''
|
||||||
{
|
const pictureJid = await resolveLidToPn(rawPictureJid, signalRepository.lidMapping, logger) || rawPictureJid
|
||||||
id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
|
ev.emit('contacts.update', [
|
||||||
imgUrl: setPicture ? 'changed' : 'removed'
|
{
|
||||||
}
|
id: pictureJid,
|
||||||
])
|
imgUrl: setPicture ? 'changed' : 'removed'
|
||||||
|
}
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
if (isJidGroup(from)) {
|
if (isJidGroup(from)) {
|
||||||
const node = setPicture || delPicture
|
const node = setPicture || delPicture
|
||||||
@@ -1635,7 +1815,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const blocklists = getBinaryNodeChildren(child, 'item')
|
const blocklists = getBinaryNodeChildren(child, 'item')
|
||||||
|
|
||||||
for (const { attrs } of blocklists) {
|
for (const { attrs } of blocklists) {
|
||||||
const blocklist = [attrs.jid!]
|
const resolvedBlockJid = await resolveLidToPn(attrs.jid!, signalRepository.lidMapping, logger) || attrs.jid!
|
||||||
|
const blocklist = [resolvedBlockJid]
|
||||||
const type = attrs.action === 'block' ? 'add' : 'remove'
|
const type = attrs.action === 'block' ? 'add' : 'remove'
|
||||||
ev.emit('blocklist.update', { blocklist, type })
|
ev.emit('blocklist.update', { blocklist, type })
|
||||||
}
|
}
|
||||||
@@ -1759,7 +1940,10 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
[storageJid]: {
|
[storageJid]: {
|
||||||
...existing,
|
...existing,
|
||||||
token: Buffer.from(content),
|
token: Buffer.from(content),
|
||||||
timestamp
|
timestamp,
|
||||||
|
// WABA Android: resets real_issue_timestamp when a new incoming token arrives
|
||||||
|
// (UPDATE wa_trusted_contacts_send SET real_issue_timestamp=null)
|
||||||
|
realIssueTimestamp: null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -1849,7 +2033,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
let shouldRecreateSession = false
|
let shouldRecreateSession = false
|
||||||
let recreateReason = ''
|
let recreateReason = ''
|
||||||
|
|
||||||
if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
|
if (enableAutoSessionRecreation && messageRetryManager && retryCount >= 1) {
|
||||||
try {
|
try {
|
||||||
const sessionId = signalRepository.jidToSignalProtocolAddress(participant)
|
const sessionId = signalRepository.jidToSignalProtocolAddress(participant)
|
||||||
|
|
||||||
@@ -1927,6 +2111,15 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
participant: attrs.participant
|
participant: attrs.participant
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Normalize LID→PN in receipt key so events always emit PN JIDs
|
||||||
|
const lidMapping = signalRepository.lidMapping
|
||||||
|
const [resolvedRemoteJid, resolvedParticipant] = await Promise.all([
|
||||||
|
resolveLidToPn(key.remoteJid, lidMapping, logger),
|
||||||
|
resolveLidToPn(key.participant, lidMapping, logger)
|
||||||
|
])
|
||||||
|
if (resolvedRemoteJid) key.remoteJid = resolvedRemoteJid
|
||||||
|
if (resolvedParticipant) key.participant = resolvedParticipant
|
||||||
|
|
||||||
if (shouldIgnoreJid(remoteJid!) && remoteJid !== S_WHATSAPP_NET) {
|
if (shouldIgnoreJid(remoteJid!) && remoteJid !== S_WHATSAPP_NET) {
|
||||||
logger.trace({ remoteJid }, 'ignoring receipt from jid')
|
logger.trace({ remoteJid }, 'ignoring receipt from jid')
|
||||||
await sendMessageAck(node)
|
await sendMessageAck(node)
|
||||||
@@ -1953,12 +2146,13 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
if (attrs.participant) {
|
if (attrs.participant) {
|
||||||
const updateKey: keyof MessageUserReceipt =
|
const updateKey: keyof MessageUserReceipt =
|
||||||
status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp'
|
status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp'
|
||||||
|
const resolvedReceiptUserJid = await resolveLidToPn(attrs.participant, lidMapping, logger) || jidNormalizedUser(attrs.participant)
|
||||||
ev.emit(
|
ev.emit(
|
||||||
'message-receipt.update',
|
'message-receipt.update',
|
||||||
ids.map(id => ({
|
ids.map(id => ({
|
||||||
key: { ...key, id },
|
key: { ...key, id },
|
||||||
receipt: {
|
receipt: {
|
||||||
userJid: jidNormalizedUser(attrs.participant),
|
userJid: jidNormalizedUser(resolvedReceiptUserJid),
|
||||||
[updateKey]: +attrs.t!
|
[updateKey]: +attrs.t!
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
@@ -2071,7 +2265,6 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
authState.creds.me!.lid || '',
|
authState.creds.me!.lid || '',
|
||||||
signalRepository,
|
signalRepository,
|
||||||
logger,
|
logger,
|
||||||
autoCleanCorrupted
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const alt = msg.key.participantAlt || msg.key.remoteJidAlt
|
const alt = msg.key.participantAlt || msg.key.remoteJidAlt
|
||||||
@@ -2087,10 +2280,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
// Check if mapping already exists to avoid unnecessary storage operations
|
// Check if mapping already exists to avoid unnecessary storage operations
|
||||||
const existingMapping = await signalRepository.lidMapping.getPNForLID(alt)
|
const existingMapping = await signalRepository.lidMapping.getPNForLID(alt)
|
||||||
if (!existingMapping) {
|
if (!existingMapping) {
|
||||||
// Store mapping in background (non-critical, doesn't block decrypt)
|
// MUST await: normalizeMessageJids() runs after this and needs the mapping
|
||||||
signalRepository.lidMapping
|
// in the LIDMappingStore to resolve LID→PN for events delivered to consumers
|
||||||
|
await signalRepository.lidMapping
|
||||||
.storeLIDPNMappings([{ lid: alt, pn: primaryJid }])
|
.storeLIDPNMappings([{ lid: alt, pn: primaryJid }])
|
||||||
.catch(error => logger.warn({ error, alt, primaryJid }, 'Background LID mapping storage failed'))
|
.catch(error => logger.warn({ error, alt, primaryJid }, 'LID mapping storage failed'))
|
||||||
}
|
}
|
||||||
|
|
||||||
// CRITICAL: ALWAYS migrate session, even if mapping exists
|
// CRITICAL: ALWAYS migrate session, even if mapping exists
|
||||||
@@ -2103,10 +2297,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
// Check if reverse mapping exists
|
// Check if reverse mapping exists
|
||||||
const existingMapping = await signalRepository.lidMapping.getLIDForPN(alt)
|
const existingMapping = await signalRepository.lidMapping.getLIDForPN(alt)
|
||||||
if (!existingMapping) {
|
if (!existingMapping) {
|
||||||
// Store mapping in background (non-critical)
|
// MUST await: normalizeMessageJids() runs after this and needs the mapping
|
||||||
signalRepository.lidMapping
|
// in the LIDMappingStore to resolve LID→PN for events delivered to consumers
|
||||||
|
await signalRepository.lidMapping
|
||||||
.storeLIDPNMappings([{ lid: primaryJid, pn: alt }])
|
.storeLIDPNMappings([{ lid: primaryJid, pn: alt }])
|
||||||
.catch(error => logger.warn({ error, alt, primaryJid }, 'Background LID mapping storage failed'))
|
.catch(error => logger.warn({ error, alt, primaryJid }, 'LID mapping storage failed'))
|
||||||
}
|
}
|
||||||
|
|
||||||
// CRITICAL: ALWAYS migrate session, even if mapping exists
|
// CRITICAL: ALWAYS migrate session, even if mapping exists
|
||||||
@@ -2607,6 +2802,26 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
await callOfferCache.del(call.id)
|
await callOfferCache.del(call.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Normalize LID→PN in call event JIDs before emitting to consumers
|
||||||
|
const callLidMapping = signalRepository.lidMapping
|
||||||
|
const [resolvedChatId, resolvedFrom, resolvedLinkCreator] = await Promise.all([
|
||||||
|
resolveLidToPn(call.chatId, callLidMapping, logger),
|
||||||
|
resolveLidToPn(call.from, callLidMapping, logger),
|
||||||
|
resolveLidToPn(call.linkCreator, callLidMapping, logger)
|
||||||
|
])
|
||||||
|
if (resolvedChatId) call.chatId = resolvedChatId
|
||||||
|
if (resolvedFrom) call.from = resolvedFrom
|
||||||
|
if (resolvedLinkCreator) call.linkCreator = resolvedLinkCreator
|
||||||
|
// Resolve participant JIDs in parallel
|
||||||
|
if (call.participants) {
|
||||||
|
await Promise.all(call.participants.map(async (p) => {
|
||||||
|
if (p.jid) {
|
||||||
|
const resolved = p.userPn || await resolveLidToPn(p.jid, callLidMapping, logger)
|
||||||
|
if (resolved) p.jid = resolved
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
ev.emit('call', [call])
|
ev.emit('call', [call])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2615,6 +2830,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
|
|
||||||
const handleBadAck = async ({ attrs }: BinaryNode) => {
|
const handleBadAck = async ({ attrs }: BinaryNode) => {
|
||||||
const key: WAMessageKey = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
|
const key: WAMessageKey = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
|
||||||
|
await normalizeKeyLidToPn(key, signalRepository.lidMapping, logger)
|
||||||
|
|
||||||
// WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
|
// WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
|
||||||
// // current hypothesis is that if pash is sent in the ack
|
// // current hypothesis is that if pash is sent in the ack
|
||||||
@@ -2638,6 +2854,24 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
const jid = jidNormalizedUser(attrs.from)
|
const jid = jidNormalizedUser(attrs.from)
|
||||||
logTcToken('error_463', { jid, msgId })
|
logTcToken('error_463', { jid, msgId })
|
||||||
|
|
||||||
|
// WABA Android: error 463 triggers getPrivacyTokens() fire-and-forget
|
||||||
|
// to ensure token is available for the retry below
|
||||||
|
getPrivacyTokens([jid])
|
||||||
|
.then(async (result) => {
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result,
|
||||||
|
fallbackJid: jid,
|
||||||
|
keys: authState.keys,
|
||||||
|
getLIDForPN,
|
||||||
|
onNewJidStored: (storedJid) => {
|
||||||
|
tcTokenKnownJids.add(storedJid)
|
||||||
|
scheduleTcTokenIndexSave()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
logTcToken('fetched', { jid, reason: 'error_463' })
|
||||||
|
})
|
||||||
|
.catch(() => { /* fire-and-forget */ })
|
||||||
|
|
||||||
// Single-retry: wait 1.5s for the server's tctoken notification to arrive,
|
// Single-retry: wait 1.5s for the server's tctoken notification to arrive,
|
||||||
// then resend. A Set prevents infinite retry loops.
|
// then resend. A Set prevents infinite retry loops.
|
||||||
// Composite key (jid:msgId) ensures retries are isolated per destination.
|
// Composite key (jid:msgId) ensures retries are isolated per destination.
|
||||||
@@ -2673,7 +2907,24 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
|
} else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
|
||||||
logTcToken('error_479', { jid: attrs.from, msgId: attrs.id })
|
const jid479 = jidNormalizedUser(attrs.from)
|
||||||
|
logTcToken('error_479', { jid: jid479, msgId: attrs.id })
|
||||||
|
// WABA Android: error 479 (SmaxInvalid) also triggers token re-fetch
|
||||||
|
getPrivacyTokens([jid479])
|
||||||
|
.then(async (result) => {
|
||||||
|
await storeTcTokensFromIqResult({
|
||||||
|
result,
|
||||||
|
fallbackJid: jid479,
|
||||||
|
keys: authState.keys,
|
||||||
|
getLIDForPN,
|
||||||
|
onNewJidStored: (storedJid) => {
|
||||||
|
tcTokenKnownJids.add(storedJid)
|
||||||
|
scheduleTcTokenIndexSave()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
logTcToken('fetched', { jid: jid479, reason: 'error_479' })
|
||||||
|
})
|
||||||
|
.catch(() => { /* fire-and-forget */ })
|
||||||
} else {
|
} else {
|
||||||
logger.warn({ attrs }, 'received error in ack')
|
logger.warn({ attrs }, 'received error in ack')
|
||||||
}
|
}
|
||||||
@@ -2802,10 +3053,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
|
|||||||
// Top-level <relay> stanzas carry TURN server info, tokens and crypto keys
|
// Top-level <relay> stanzas carry TURN server info, tokens and crypto keys
|
||||||
ws.on('CB:relay', async (node: BinaryNode) => {
|
ws.on('CB:relay', async (node: BinaryNode) => {
|
||||||
const callId = node.attrs['call-id']
|
const callId = node.attrs['call-id']
|
||||||
const callCreator = node.attrs['call-creator']
|
const rawCallCreator = node.attrs['call-creator']
|
||||||
// Both callId and callCreator must be present to emit a valid event
|
// Both callId and callCreator must be present to emit a valid event
|
||||||
// (call link relays may arrive without these attrs — just log them)
|
// (call link relays may arrive without these attrs — just log them)
|
||||||
if (callId && callCreator) {
|
if (callId && rawCallCreator) {
|
||||||
|
// Resolve LID→PN for call creator
|
||||||
|
const callCreator = await resolveLidToPn(rawCallCreator, signalRepository.lidMapping, logger) || rawCallCreator
|
||||||
logger.debug(
|
logger.debug(
|
||||||
{ callId, callCreator, uuid: node.attrs.uuid },
|
{ callId, callCreator, uuid: node.attrs.uuid },
|
||||||
'received relay info'
|
'received relay info'
|
||||||
|
|||||||
+36
-995
File diff suppressed because it is too large
Load Diff
+25
-6
@@ -38,7 +38,7 @@ import {
|
|||||||
signedKeyPair,
|
signedKeyPair,
|
||||||
xmppSignedPreKey
|
xmppSignedPreKey
|
||||||
} from '../Utils'
|
} from '../Utils'
|
||||||
import { getPlatformId } from '../Utils/browser-utils'
|
import { getPlatformId, isAndroidBrowser } from '../Utils/browser-utils'
|
||||||
import {
|
import {
|
||||||
CircuitBreaker,
|
CircuitBreaker,
|
||||||
CircuitOpenError,
|
CircuitOpenError,
|
||||||
@@ -634,8 +634,6 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
|
helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
|
||||||
|
|
||||||
logger.info({ browser, helloMsg }, 'connected to WA')
|
|
||||||
|
|
||||||
const init = proto.HandshakeMessage.encode(helloMsg).finish()
|
const init = proto.HandshakeMessage.encode(helloMsg).finish()
|
||||||
|
|
||||||
const result = await awaitNextMessage<Uint8Array>(init)
|
const result = await awaitNextMessage<Uint8Array>(init)
|
||||||
@@ -1352,6 +1350,25 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
id: jidEncode(phoneNumber, 's.whatsapp.net'),
|
||||||
name: '~'
|
name: '~'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pair code companion_platform_id must be Chrome (1) when using Android
|
||||||
|
// browser preset. ANDROID_PHONE (16) causes silent timeout (server ignores),
|
||||||
|
// UWP (21) causes "cannot connect device" rejection. Only Chrome (1) works
|
||||||
|
// for pair code via web protocol (WA\x06\x03). The device still appears as
|
||||||
|
// "Android" in linked devices because DeviceProps.platformType=ANDROID_PHONE
|
||||||
|
// is set separately in the registration node.
|
||||||
|
const isAndroid = isAndroidBrowser(browser)
|
||||||
|
const pairPlatformId = isAndroid ? getPlatformId('Chrome') : getPlatformId(browser[1])
|
||||||
|
const pairPlatformDisplay = isAndroid ? 'Chrome (Mac OS)' : `${browser[1]} (${browser[0]})`
|
||||||
|
|
||||||
|
logger.info({
|
||||||
|
pairCode: pairingCode,
|
||||||
|
jid: authState.creds.me.id,
|
||||||
|
companionPlatformId: pairPlatformId,
|
||||||
|
companionPlatformDisplay: pairPlatformDisplay,
|
||||||
|
isAndroid,
|
||||||
|
}, `pair code requested | companion: ${pairPlatformDisplay} | ${isAndroid ? 'android override -> Chrome' : 'native platform'}`)
|
||||||
|
|
||||||
ev.emit('creds.update', authState.creds)
|
ev.emit('creds.update', authState.creds)
|
||||||
await sendNode({
|
await sendNode({
|
||||||
tag: 'iq',
|
tag: 'iq',
|
||||||
@@ -1384,12 +1401,12 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
{
|
{
|
||||||
tag: 'companion_platform_id',
|
tag: 'companion_platform_id',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: getPlatformId(browser[1])
|
content: pairPlatformId
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'companion_platform_display',
|
tag: 'companion_platform_display',
|
||||||
attrs: {},
|
attrs: {},
|
||||||
content: `${browser[1]} (${browser[0]})`
|
content: pairPlatformDisplay
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
tag: 'link_code_pairing_nonce',
|
tag: 'link_code_pairing_nonce',
|
||||||
@@ -1519,7 +1536,9 @@ export const makeSocket = (config: SocketConfig) => {
|
|||||||
})
|
})
|
||||||
// login complete
|
// login complete
|
||||||
ws.on('CB:success', async (node: BinaryNode) => {
|
ws.on('CB:success', async (node: BinaryNode) => {
|
||||||
logger.info('opened connection to WA')
|
const isAndroid = isAndroidBrowser(browser)
|
||||||
|
const phoneId = authState.creds.me?.id?.split(':')[0]?.split('@')[0] || 'new session'
|
||||||
|
logger.info(`${isAndroid ? '\uD83D\uDCF1' : '\uD83D\uDDA5\uFE0F'} Connected to WA | ${phoneId} | platform: ${isAndroid ? 'SMB_ANDROID' : 'MACOS'} | device: ${isAndroid ? 'Android' : 'Desktop'} | platformType: ${isAndroid ? 'ANDROID_PHONE' : 'CHROME'}`)
|
||||||
clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
|
clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
|
||||||
|
|
||||||
ev.emit('creds.update', { me: { ...authState.creds.me!, lid: node.attrs.lid } })
|
ev.emit('creds.update', { me: { ...authState.creds.me!, lid: node.attrs.lid } })
|
||||||
|
|||||||
+1
-1
@@ -80,7 +80,7 @@ export type SignalDataTypeMap = {
|
|||||||
'app-state-sync-version': LTHashState
|
'app-state-sync-version': LTHashState
|
||||||
'lid-mapping': string
|
'lid-mapping': string
|
||||||
'device-list': string[]
|
'device-list': string[]
|
||||||
tctoken: { token: Buffer; timestamp?: string; senderTimestamp?: number }
|
tctoken: { token: Buffer; timestamp?: string; senderTimestamp?: number; realIssueTimestamp?: number | null }
|
||||||
/** Identity key for Signal Protocol - used for detecting contact reinstalls */
|
/** Identity key for Signal Protocol - used for detecting contact reinstalls */
|
||||||
'identity-key': Uint8Array
|
'identity-key': Uint8Array
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,12 +54,14 @@ export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL
|
|||||||
* Individual sticker in a sticker pack
|
* Individual sticker in a sticker pack
|
||||||
*/
|
*/
|
||||||
export type Sticker = {
|
export type Sticker = {
|
||||||
/** Buffer, Stream or URL of the sticker image (will be converted to WebP if needed) */
|
/** Buffer, Stream or URL of the sticker image (WebP or Lottie/WAS format) */
|
||||||
data: WAMediaUpload
|
data: WAMediaUpload
|
||||||
/** Array of emojis associated with this sticker (max 3 recommended per WhatsApp standards) */
|
/** Array of emojis associated with this sticker (max 3 recommended per WhatsApp standards) */
|
||||||
emojis?: string[]
|
emojis?: string[]
|
||||||
/** Accessibility label for screen readers (max 125 chars for static, 255 for animated) */
|
/** Accessibility label for screen readers (max 125 chars for static, 255 for animated) */
|
||||||
accessibilityLabel?: string
|
accessibilityLabel?: string
|
||||||
|
/** Force Lottie format detection (auto-detected if omitted) */
|
||||||
|
isLottie?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export type BrowsersMap = {
|
|||||||
baileys(browser: string): [string, string, string]
|
baileys(browser: string): [string, string, string]
|
||||||
windows(browser: string): [string, string, string]
|
windows(browser: string): [string, string, string]
|
||||||
appropriate(browser: string): [string, string, string]
|
appropriate(browser: string): [string, string, string]
|
||||||
|
android(apiLevel: string): [string, string, string]
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum DisconnectReason {
|
export enum DisconnectReason {
|
||||||
|
|||||||
@@ -94,7 +94,13 @@ const BROWSER_TO_PLATFORM_ID: ReadonlyMap<string, string> = (() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Map(entries)
|
const map = new Map(entries)
|
||||||
|
// ANDROID → ANDROID_PHONE alias (DeviceProps.PlatformType has ANDROID_PHONE but not ANDROID)
|
||||||
|
if (!map.has('ANDROID') && map.has('ANDROID_PHONE')) {
|
||||||
|
map.set('ANDROID', map.get('ANDROID_PHONE')!)
|
||||||
|
}
|
||||||
|
|
||||||
|
return map
|
||||||
})()
|
})()
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -331,7 +337,8 @@ export const Browsers: BrowsersMap = {
|
|||||||
macOS: (browser: string): [string, string, string] => ['Mac OS', browser, OS_VERSIONS.macOS],
|
macOS: (browser: string): [string, string, string] => ['Mac OS', browser, OS_VERSIONS.macOS],
|
||||||
windows: (browser: string): [string, string, string] => ['Windows', browser, OS_VERSIONS.windows],
|
windows: (browser: string): [string, string, string] => ['Windows', browser, OS_VERSIONS.windows],
|
||||||
baileys: (browser: string): [string, string, string] => ['Baileys', browser, OS_VERSIONS.baileys],
|
baileys: (browser: string): [string, string, string] => ['Baileys', browser, OS_VERSIONS.baileys],
|
||||||
appropriate: (browser: string): [string, string, string] => [getPlatformName(), browser, getAppropriateVersion()]
|
appropriate: (browser: string): [string, string, string] => [getPlatformName(), browser, getAppropriateVersion()],
|
||||||
|
android: (apiLevel: string): [string, string, string] => [apiLevel, 'Android', '']
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -378,7 +385,7 @@ export const getPlatformId = (browser: unknown): string => {
|
|||||||
* properties like 'toString' or 'constructor'.
|
* properties like 'toString' or 'constructor'.
|
||||||
*
|
*
|
||||||
* @param value - Value to check
|
* @param value - Value to check
|
||||||
* @returns True if value is a valid browser preset key ('ubuntu', 'macOS', 'windows', 'baileys', 'appropriate')
|
* @returns True if value is a valid browser preset key ('ubuntu', 'macOS', 'windows', 'baileys', 'appropriate', 'android')
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* isValidBrowserPreset('ubuntu') // true
|
* isValidBrowserPreset('ubuntu') // true
|
||||||
@@ -391,6 +398,16 @@ export const getPlatformId = (browser: unknown): string => {
|
|||||||
* const config = Browsers[userInput]('MyApp')
|
* const config = Browsers[userInput]('MyApp')
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Checks if the browser tuple represents an Android companion device.
|
||||||
|
*
|
||||||
|
* @param browser - Browser tuple [os, platform, version]
|
||||||
|
* @returns True if platform is 'Android' (case-insensitive)
|
||||||
|
*/
|
||||||
|
export const isAndroidBrowser = (browser: [string, string, string]): boolean => {
|
||||||
|
return browser[1]?.toUpperCase() === 'ANDROID'
|
||||||
|
}
|
||||||
|
|
||||||
export const isValidBrowserPreset = (value: unknown): value is keyof BrowsersMap => {
|
export const isValidBrowserPreset = (value: unknown): value is keyof BrowsersMap => {
|
||||||
return typeof value === 'string' && Object.prototype.hasOwnProperty.call(Browsers, value)
|
return typeof value === 'string' && Object.prototype.hasOwnProperty.call(Browsers, value)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
isJidStatusBroadcast,
|
isJidStatusBroadcast,
|
||||||
isLidUser,
|
isLidUser,
|
||||||
isPnUser,
|
isPnUser,
|
||||||
jidDecode
|
|
||||||
// transferDevice
|
// transferDevice
|
||||||
} from '../WABinary'
|
} from '../WABinary'
|
||||||
import { unpadRandomMax16 } from './generics'
|
import { unpadRandomMax16 } from './generics'
|
||||||
@@ -276,7 +275,6 @@ export const decryptMessageNode = (
|
|||||||
meLid: string,
|
meLid: string,
|
||||||
repository: SignalRepositoryWithLIDStore,
|
repository: SignalRepositoryWithLIDStore,
|
||||||
logger: ILogger,
|
logger: ILogger,
|
||||||
autoCleanCorrupted = true
|
|
||||||
) => {
|
) => {
|
||||||
const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
|
const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
|
||||||
return {
|
return {
|
||||||
@@ -422,34 +420,19 @@ export const decryptMessageNode = (
|
|||||||
if (isRetryExhausted) {
|
if (isRetryExhausted) {
|
||||||
logger.error(
|
logger.error(
|
||||||
errorContext,
|
errorContext,
|
||||||
`⚠️ Session corrupted and recovery failed after ${err.attempts} attempts. Auto-cleanup will attempt to recover.`
|
`⚠️ Session corrupted after ${err.attempts} attempts. Retry+pkmsg flow will recover.`
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// First occurrence - log as warning since auto-recovery will attempt
|
// First occurrence - log as warning since auto-recovery will attempt
|
||||||
logger.warn(errorContext, '⚠️ Corrupted session detected - attempting auto-recovery')
|
logger.warn(errorContext, '⚠️ Corrupted session detected - attempting auto-recovery')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Automatic cleanup of corrupted session (if enabled)
|
// Session cleanup is deferred to retry exhaustion (safety net).
|
||||||
// eslint-disable-next-line max-depth
|
// The Signal Protocol handles recovery naturally via retry+pkmsg:
|
||||||
if (autoCleanCorrupted) {
|
// Bad MAC -> retry receipt -> sender re-sends as pkmsg -> new session.
|
||||||
// eslint-disable-next-line max-depth
|
// Deleting sessions here (hot path) causes cascading failures when
|
||||||
try {
|
// multiple messages from the same contact arrive simultaneously.
|
||||||
const deletedCount = await cleanupCorruptedSession(decryptionJid, repository, logger)
|
// See: messages-recv.ts sendRetryRequest() for deferred cleanup.
|
||||||
|
|
||||||
// Mask only user portion of JID for privacy (preserve domain info)
|
|
||||||
const { user, server } = jidDecode(decryptionJid) || {}
|
|
||||||
const maskedUser =
|
|
||||||
user && user.length > 8 ? `${user.substring(0, 4)}****${user.substring(user.length - 4)}` : user
|
|
||||||
const maskedJid = maskedUser && server ? `${maskedUser}@${server}` : decryptionJid
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
{ jid: decryptionJid, maskedJid, targetedDevices: deletedCount },
|
|
||||||
`🔄 Session Reset | JID: ${maskedJid} | Targeted: ${deletedCount} devices | Will recreate on next message`
|
|
||||||
)
|
|
||||||
} catch (cleanupErr) {
|
|
||||||
logger.error({ decryptionJid, err: cleanupErr }, '❌ Failed to cleanup corrupted session')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (isSessionRecord) {
|
} else if (isSessionRecord) {
|
||||||
// Session record errors are transient - retry should handle them
|
// Session record errors are transient - retry should handle them
|
||||||
// eslint-disable-next-line max-depth
|
// eslint-disable-next-line max-depth
|
||||||
@@ -504,53 +487,20 @@ export function isCorruptedSessionError(error: any): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clean up corrupted session by deleting all device sessions for a JID
|
* Clean up corrupted session for a specific device JID.
|
||||||
* Signal Protocol will automatically recreate the session on next message
|
* WABA behavior: DELETE sessions WHERE recipient_id=? AND device_id=?
|
||||||
|
* Only deletes the exact device that was corrupted, not all devices.
|
||||||
|
*
|
||||||
|
* NOTE: This should NOT be called on every Bad MAC error (hot path).
|
||||||
|
* Instead, let the retry+pkmsg flow handle recovery naturally (like WhatsApp does).
|
||||||
|
* Only call this as a safety net when retries are exhausted.
|
||||||
*/
|
*/
|
||||||
async function cleanupCorruptedSession(
|
export async function cleanupCorruptedSession(
|
||||||
jid: string,
|
jid: string,
|
||||||
repository: SignalRepositoryWithLIDStore,
|
repository: SignalRepositoryWithLIDStore,
|
||||||
logger: ILogger
|
logger: ILogger
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
const { user, device } = jidDecode(jid) || {}
|
await repository.deleteSession([jid])
|
||||||
if (!user) {
|
logger.info({ jid }, 'Cleaned up corrupted session for specific device')
|
||||||
logger.warn({ jid }, 'Cannot cleanup session - invalid JID')
|
return 1
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build list of JIDs to delete (primary + secondary devices)
|
|
||||||
const jidsToDelete: string[] = []
|
|
||||||
|
|
||||||
// Determine domain type correctly (handle hosted JIDs)
|
|
||||||
// JID formats:
|
|
||||||
// - PN: user@s.whatsapp.net
|
|
||||||
// - LID: user@lid
|
|
||||||
// - Hosted PN: user@hosted
|
|
||||||
// - Hosted LID: user@hosted.lid
|
|
||||||
const isLID = jid.endsWith('@lid') || jid.endsWith('@hosted.lid')
|
|
||||||
const isHosted = jid.includes('@hosted')
|
|
||||||
|
|
||||||
let domain: string
|
|
||||||
if (isLID) {
|
|
||||||
domain = isHosted ? 'hosted.lid' : 'lid'
|
|
||||||
} else {
|
|
||||||
domain = isHosted ? 'hosted' : 's.whatsapp.net'
|
|
||||||
}
|
|
||||||
|
|
||||||
// Primary device (0)
|
|
||||||
jidsToDelete.push(`${user}@${domain}`)
|
|
||||||
|
|
||||||
// Secondary devices (1-5 common range for Web/Desktop/etc)
|
|
||||||
for (let i = 1; i <= 5; i++) {
|
|
||||||
jidsToDelete.push(`${user}:${i}@${domain}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// If specific device was identified and > 5, ensure it's included
|
|
||||||
if (device !== undefined && device > 5) {
|
|
||||||
jidsToDelete.push(`${user}:${device}@${domain}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
await repository.deleteSession(jidsToDelete)
|
|
||||||
|
|
||||||
return jidsToDelete.length
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -211,15 +211,33 @@ export class MessageRetryManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MAC errors require IMMEDIATE session recreation regardless of history
|
// MAC errors require session recreation, but rate-limited to prevent loops.
|
||||||
// This handles the case where contact reinstalled WhatsApp (identity key changed)
|
// When multiple messages fail with Bad MAC simultaneously, only the first
|
||||||
|
// should trigger recreation; subsequent ones within the cooldown window
|
||||||
|
// piggyback on the same new session established by the retry+pkmsg flow.
|
||||||
if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
|
if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
|
||||||
this.sessionRecreateHistory.set(jid, Date.now())
|
const now = Date.now()
|
||||||
|
const prevTime = this.sessionRecreateHistory.get(jid)
|
||||||
|
const MAC_ERROR_COOLDOWN_MS = 1_000 // 1 second — WABA recovers faster
|
||||||
|
|
||||||
|
if (prevTime && now - prevTime < MAC_ERROR_COOLDOWN_MS) {
|
||||||
|
const reasonName = RetryReason[errorCode] || `code_${errorCode}`
|
||||||
|
this.logger.debug(
|
||||||
|
{ jid, errorCode: reasonName, msSinceLast: now - prevTime },
|
||||||
|
'MAC error session recreation skipped — cooldown active'
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
reason: '',
|
||||||
|
recreate: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sessionRecreateHistory.set(jid, now)
|
||||||
this.statistics.sessionRecreations++
|
this.statistics.sessionRecreations++
|
||||||
const reasonName = RetryReason[errorCode] || `code_${errorCode}`
|
const reasonName = RetryReason[errorCode] || `code_${errorCode}`
|
||||||
metrics.signalMacErrors?.inc({ action: 'session_recreation' })
|
metrics.signalMacErrors?.inc({ action: 'session_recreation' })
|
||||||
metrics.signalSessionRecreations?.inc({ reason: 'mac_error' })
|
metrics.signalSessionRecreations?.inc({ reason: 'mac_error' })
|
||||||
this.logger.warn({ jid, errorCode: reasonName }, 'MAC error detected, forcing immediate session recreation')
|
this.logger.warn({ jid, errorCode: reasonName }, 'MAC error detected, recreating session')
|
||||||
return {
|
return {
|
||||||
reason: `MAC error (${reasonName}) - contact may have reinstalled WhatsApp`,
|
reason: `MAC error (${reasonName}) - contact may have reinstalled WhatsApp`,
|
||||||
recreate: true
|
recreate: true
|
||||||
|
|||||||
+48
-10
@@ -1228,19 +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)
|
|
||||||
// Direct interactiveMessage — no viewOnceMessage wrapper, no root header/body/footer
|
|
||||||
m.interactiveMessage = generated.interactiveMessage
|
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
// Check for nativeList
|
// Check for nativeList
|
||||||
|
|||||||
@@ -19,10 +19,13 @@ import type {
|
|||||||
WAMessage,
|
WAMessage,
|
||||||
WAMessageKey
|
WAMessageKey
|
||||||
} from '../Types'
|
} from '../Types'
|
||||||
|
import type { LIDMappingStore } from '../Signal/lid-mapping'
|
||||||
import { WAMessageStubType } from '../Types'
|
import { WAMessageStubType } from '../Types'
|
||||||
import { getContentType, normalizeMessageContent } from '../Utils/messages'
|
import { getContentType, normalizeMessageContent } from '../Utils/messages'
|
||||||
import {
|
import {
|
||||||
areJidsSameUser,
|
areJidsSameUser,
|
||||||
|
isAnyLidUser,
|
||||||
|
isAnyPnUser,
|
||||||
isHostedLidUser,
|
isHostedLidUser,
|
||||||
isHostedPnUser,
|
isHostedPnUser,
|
||||||
isJidBroadcast,
|
isJidBroadcast,
|
||||||
@@ -125,42 +128,94 @@ export const cleanMessage = (message: WAMessage, meId: string, meLid: string) =>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves a LID JID to its PN equivalent using the LID mapping store.
|
||||||
|
* Returns the original JID if it's not a LID or if no mapping is found.
|
||||||
|
* Safe to call with any JID type (group, newsletter, PN, etc.).
|
||||||
|
*/
|
||||||
|
export const resolveLidToPn = async (
|
||||||
|
jid: string | undefined | null,
|
||||||
|
lidMapping: LIDMappingStore,
|
||||||
|
logger?: ILogger
|
||||||
|
): Promise<string | undefined> => {
|
||||||
|
if (!jid) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAnyLidUser(jid)) {
|
||||||
|
const pn = await lidMapping.getPNForLID(jid)
|
||||||
|
if (pn) {
|
||||||
|
logger?.debug({ lid: jid, pn }, 'Resolved LID to PN')
|
||||||
|
}
|
||||||
|
|
||||||
|
return pn || jid
|
||||||
|
}
|
||||||
|
|
||||||
|
return jid
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalizes a WAMessageKey by resolving LID→PN for remoteJid and participant.
|
||||||
|
*/
|
||||||
|
export const normalizeKeyLidToPn = async (
|
||||||
|
key: WAMessageKey,
|
||||||
|
lidMapping: LIDMappingStore,
|
||||||
|
logger?: ILogger
|
||||||
|
): Promise<void> => {
|
||||||
|
const [resolvedRemoteJid, resolvedParticipant] = await Promise.all([
|
||||||
|
resolveLidToPn(key.remoteJid, lidMapping, logger),
|
||||||
|
resolveLidToPn(key.participant, lidMapping, logger)
|
||||||
|
])
|
||||||
|
if (resolvedRemoteJid) {
|
||||||
|
key.remoteJid = resolvedRemoteJid
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolvedParticipant) {
|
||||||
|
key.participant = resolvedParticipant
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const normalizeMessageJids = async (
|
export const normalizeMessageJids = async (
|
||||||
message: WAMessage,
|
message: WAMessage,
|
||||||
signalRepository: SignalRepositoryWithLIDStore,
|
signalRepository: SignalRepositoryWithLIDStore,
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
const resolveLidToPn = async (jid: string | undefined | null): Promise<string | undefined> => {
|
const lidMapping = signalRepository.lidMapping
|
||||||
if (!jid) {
|
const key = message.key
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isLidUser(jid) || isHostedLidUser(jid)) {
|
// FAST PATH: Use alt JIDs directly when available (avoids LIDMappingStore race condition).
|
||||||
const pn = await signalRepository.lidMapping.getPNForLID(jid)
|
// The stanza always carries both formats (LID + PN) in the attributes.
|
||||||
if (pn) {
|
// When addressing_mode=lid, remoteJid is LID and remoteJidAlt is PN.
|
||||||
logger?.debug({ lid: jid, pn }, 'Resolved LID to PN for inbound message')
|
// When addressing_mode=pn, remoteJid is already PN (no conversion needed).
|
||||||
} else {
|
if (key.remoteJid && isAnyLidUser(key.remoteJid) && key.remoteJidAlt && isAnyPnUser(key.remoteJidAlt)) {
|
||||||
logger?.debug({ lid: jid }, 'PN not found for inbound LID, keeping LID')
|
logger?.debug({ lid: key.remoteJid, pn: key.remoteJidAlt }, 'Resolved remoteJid LID→PN via alt (fast path)')
|
||||||
}
|
key.remoteJid = key.remoteJidAlt
|
||||||
|
|
||||||
return pn || jid
|
|
||||||
}
|
|
||||||
|
|
||||||
return jid
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute both lookups in parallel instead of sequentially to reduce latency
|
if (key.participant && isAnyLidUser(key.participant) && key.participantAlt && isAnyPnUser(key.participantAlt)) {
|
||||||
const [resolvedRemoteJid, resolvedParticipant] = await Promise.all([
|
logger?.debug({ lid: key.participant, pn: key.participantAlt }, 'Resolved participant LID→PN via alt (fast path)')
|
||||||
resolveLidToPn(message.key.remoteJid),
|
key.participant = key.participantAlt
|
||||||
resolveLidToPn(message.key.participant)
|
|
||||||
])
|
|
||||||
|
|
||||||
if (resolvedRemoteJid) {
|
|
||||||
message.key.remoteJid = resolvedRemoteJid
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (resolvedParticipant) {
|
// SLOW PATH: Resolve any remaining LIDs via LIDMappingStore lookup
|
||||||
message.key.participant = resolvedParticipant
|
await normalizeKeyLidToPn(key, lidMapping, logger)
|
||||||
|
|
||||||
|
// Also normalize participantAlt (the alternative JID format — can be LID when addressing_mode=pn)
|
||||||
|
if (key.participantAlt && isAnyLidUser(key.participantAlt)) {
|
||||||
|
const resolved = await resolveLidToPn(key.participantAlt, lidMapping, logger)
|
||||||
|
if (resolved) {
|
||||||
|
key.participantAlt = resolved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize nested message keys (reaction, poll) that may contain LID JIDs
|
||||||
|
const content = normalizeMessageContent(message.message)
|
||||||
|
if (content?.reactionMessage?.key) {
|
||||||
|
await normalizeKeyLidToPn(content.reactionMessage.key, lidMapping, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (content?.pollUpdateMessage?.pollCreationMessageKey) {
|
||||||
|
await normalizeKeyLidToPn(content.pollUpdateMessage.pollCreationMessageKey, lidMapping, logger)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -534,6 +589,12 @@ const processMessage = async (
|
|||||||
'CTWA: Successfully recovered message via placeholder resend'
|
'CTWA: Successfully recovered message via placeholder resend'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Normalize LID→PN in PDO-recovered message key before emitting
|
||||||
|
// eslint-disable-next-line max-depth
|
||||||
|
if (webMessageInfo.key && signalRepository) {
|
||||||
|
await normalizeKeyLidToPn(webMessageInfo.key as WAMessageKey, signalRepository.lidMapping, logger)
|
||||||
|
}
|
||||||
|
|
||||||
// wait till another upsert event is available, don't want it to be part of the PDO response message
|
// wait till another upsert event is available, don't want it to be part of the PDO response message
|
||||||
// TODO: parse through proper message handling utilities (to add relevant key fields)
|
// TODO: parse through proper message handling utilities (to add relevant key fields)
|
||||||
ev.emit('messages.upsert', {
|
ev.emit('messages.upsert', {
|
||||||
@@ -674,9 +735,13 @@ const processMessage = async (
|
|||||||
response: responseMsg
|
response: responseMsg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Normalize creationMsgKey JIDs for the emitted event
|
||||||
|
const normalizedCreationKey = { ...creationMsgKey }
|
||||||
|
await normalizeKeyLidToPn(normalizedCreationKey, signalRepository.lidMapping, logger)
|
||||||
|
|
||||||
ev.emit('messages.update', [
|
ev.emit('messages.update', [
|
||||||
{
|
{
|
||||||
key: creationMsgKey,
|
key: normalizedCreationKey,
|
||||||
update: {
|
update: {
|
||||||
eventResponses: [eventResponse]
|
eventResponses: [eventResponse]
|
||||||
}
|
}
|
||||||
@@ -719,7 +784,7 @@ const processMessage = async (
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)) // ADD SUPPORT FOR LID
|
const participantsIncludesMe = () => participants.find(p => areJidsSameUser(meId, p.id) || areJidsSameUser(meId, p.phoneNumber))
|
||||||
|
|
||||||
switch (message.messageStubType) {
|
switch (message.messageStubType) {
|
||||||
case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
|
case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
|
||||||
|
|||||||
+120
-19
@@ -2,6 +2,7 @@ import { Boom } from '@hapi/boom'
|
|||||||
import { createHash } from 'crypto'
|
import { createHash } from 'crypto'
|
||||||
import { zipSync } from 'fflate'
|
import { zipSync } from 'fflate'
|
||||||
import { promises as fs } from 'fs'
|
import { promises as fs } from 'fs'
|
||||||
|
import { gzipSync, gunzipSync } from 'zlib'
|
||||||
import { proto } from '../../WAProto/index.js'
|
import { proto } from '../../WAProto/index.js'
|
||||||
import type { MediaType } from '../Defaults/index.js'
|
import type { MediaType } from '../Defaults/index.js'
|
||||||
import type { StickerPack, WAMediaUpload, WAMediaUploadFunction } from '../Types/Message.js'
|
import type { StickerPack, WAMediaUpload, WAMediaUploadFunction } from '../Types/Message.js'
|
||||||
@@ -101,6 +102,49 @@ export const isAnimatedWebP = (buffer: Buffer): boolean => {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detecta se um buffer é Lottie JSON (raw ou gzip-compressed/WAS)
|
||||||
|
*
|
||||||
|
* WABA usa mimetype `application/was` para stickers Lottie.
|
||||||
|
* WAS (WhatsApp Animated Sticker) = gzip-compressed Lottie JSON.
|
||||||
|
*
|
||||||
|
* Detecção:
|
||||||
|
* - Gzip (0x1f 0x8b): descomprime e verifica se é Lottie JSON
|
||||||
|
* - JSON bruto: verifica campos Lottie obrigatórios (v, ip, op, layers)
|
||||||
|
*
|
||||||
|
* @param buffer - Buffer to check
|
||||||
|
* @returns true if buffer is Lottie/WAS format
|
||||||
|
*/
|
||||||
|
export const isLottieBuffer = (buffer: Buffer): boolean => {
|
||||||
|
if (buffer.length < 2) return false
|
||||||
|
|
||||||
|
let jsonBuffer: Buffer
|
||||||
|
|
||||||
|
// Check if gzip-compressed (WAS format)
|
||||||
|
if (buffer[0] === 0x1f && buffer[1] === 0x8b) {
|
||||||
|
try {
|
||||||
|
// SECURITY: Limit decompressed output to 50MB to prevent decompression bombs
|
||||||
|
jsonBuffer = gunzipSync(buffer, { maxOutputLength: 50 * 1024 * 1024 }) as Buffer
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
} else if (buffer[0] === 0x7b) {
|
||||||
|
// Starts with '{' - could be raw Lottie JSON
|
||||||
|
jsonBuffer = buffer
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate Lottie JSON structure: must have v, ip, op, AND layers
|
||||||
|
try {
|
||||||
|
const str = jsonBuffer.toString('utf8', 0, Math.min(jsonBuffer.length, 4096))
|
||||||
|
// Quick check for ALL required Lottie fields
|
||||||
|
return str.includes('"v"') && str.includes('"layers"') && str.includes('"ip"') && str.includes('"op"')
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Converte uma imagem para WebP usando Sharp
|
* Converte uma imagem para WebP usando Sharp
|
||||||
* Preserva o buffer original se já for WebP para manter EXIF e animações
|
* Preserva o buffer original se já for WebP para manter EXIF e animações
|
||||||
@@ -114,12 +158,25 @@ export const isAnimatedWebP = (buffer: Buffer): boolean => {
|
|||||||
const convertToWebP = async (
|
const convertToWebP = async (
|
||||||
buffer: Buffer,
|
buffer: Buffer,
|
||||||
logger?: ILogger
|
logger?: ILogger
|
||||||
): Promise<{ webpBuffer: Buffer; isAnimated: boolean }> => {
|
): Promise<{ webpBuffer: Buffer; isAnimated: boolean; isLottie: boolean }> => {
|
||||||
|
// Lottie/WAS: ensure gzip-compressed format (WAS = gzip Lottie JSON)
|
||||||
|
if (isLottieBuffer(buffer)) {
|
||||||
|
let wasBuffer = buffer
|
||||||
|
// Raw Lottie JSON (starts with '{') must be gzipped to produce valid WAS
|
||||||
|
if (buffer[0] === 0x7b) {
|
||||||
|
logger?.trace('Raw Lottie JSON detected, gzip-compressing to WAS format')
|
||||||
|
wasBuffer = gzipSync(buffer) as Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
logger?.trace('Input is Lottie/WAS format')
|
||||||
|
return { webpBuffer: wasBuffer, isAnimated: true, isLottie: true }
|
||||||
|
}
|
||||||
|
|
||||||
// Se já é WebP, preserva o buffer original (mantém EXIF e animações)
|
// Se já é WebP, preserva o buffer original (mantém EXIF e animações)
|
||||||
if (isWebPBuffer(buffer)) {
|
if (isWebPBuffer(buffer)) {
|
||||||
const isAnimated = isAnimatedWebP(buffer)
|
const isAnimated = isAnimatedWebP(buffer)
|
||||||
logger?.trace({ isAnimated }, 'Input is already WebP, preserving original buffer')
|
logger?.trace({ isAnimated }, 'Input is already WebP, preserving original buffer')
|
||||||
return { webpBuffer: buffer, isAnimated }
|
return { webpBuffer: buffer, isAnimated, isLottie: false }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tenta usar Sharp para converter
|
// Tenta usar Sharp para converter
|
||||||
@@ -135,7 +192,7 @@ const convertToWebP = async (
|
|||||||
logger?.trace('Converting image to WebP using Sharp')
|
logger?.trace('Converting image to WebP using Sharp')
|
||||||
const webpBuffer = await lib.sharp.default(buffer).webp().toBuffer()
|
const webpBuffer = await lib.sharp.default(buffer).webp().toBuffer()
|
||||||
|
|
||||||
return { webpBuffer, isAnimated: false }
|
return { webpBuffer, isAnimated: false, isLottie: false }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -338,9 +395,11 @@ export type PrepareStickerPackMessageOptions = {
|
|||||||
*
|
*
|
||||||
* **Especificações WhatsApp:**
|
* **Especificações WhatsApp:**
|
||||||
* - 3-30 stickers por pack (oficial)
|
* - 3-30 stickers por pack (oficial)
|
||||||
* - WebP obrigatório
|
* - WebP ou Lottie/WAS (application/was)
|
||||||
|
* - Stickers: 512x512 pixels (auto-resize)
|
||||||
* - Recomendado: 100KB por sticker estático, 500KB animado
|
* - Recomendado: 100KB por sticker estático, 500KB animado
|
||||||
* - Tray icon: 252x252 pixels
|
* - Tray icon: 96x96 pixels (PNG no ZIP)
|
||||||
|
* - Thumbnail: 252x252 pixels (JPEG, upload separado)
|
||||||
*
|
*
|
||||||
* @param stickerPack - Sticker pack data with stickers, cover, name, publisher
|
* @param stickerPack - Sticker pack data with stickers, cover, name, publisher
|
||||||
* @param options - Upload function and optional logger
|
* @param options - Upload function and optional logger
|
||||||
@@ -464,9 +523,36 @@ export const prepareStickerPackMessage = async (
|
|||||||
// Obtém buffer do sticker
|
// Obtém buffer do sticker
|
||||||
const buffer = await mediaToBuffer(sticker.data, `sticker ${i + 1}`)
|
const buffer = await mediaToBuffer(sticker.data, `sticker ${i + 1}`)
|
||||||
|
|
||||||
// Converte para WebP
|
// Detecta formato e converte se necessário
|
||||||
// eslint-disable-next-line prefer-const
|
// eslint-disable-next-line prefer-const
|
||||||
let { webpBuffer, isAnimated } = await convertToWebP(buffer, logger)
|
let { webpBuffer, isAnimated, isLottie } = await convertToWebP(buffer, logger)
|
||||||
|
|
||||||
|
// Validate explicit isLottie flag — must match detected format
|
||||||
|
if (sticker.isLottie !== undefined && sticker.isLottie !== isLottie) {
|
||||||
|
throw new Boom(
|
||||||
|
`Sticker ${i + 1}: explicit isLottie=${sticker.isLottie} does not match detected format (detected=${isLottie})`,
|
||||||
|
{ statusCode: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WABA: Enforce 512x512 dimensions for WebP stickers (Lottie is vector, skip)
|
||||||
|
if (!isLottie && isWebPBuffer(webpBuffer)) {
|
||||||
|
const lib = await getImageProcessingLibrary()
|
||||||
|
if (lib?.sharp) {
|
||||||
|
const metadata = await lib.sharp.default(webpBuffer).metadata()
|
||||||
|
if (metadata.width !== 512 || metadata.height !== 512) {
|
||||||
|
logger?.trace(
|
||||||
|
{ index: i, width: metadata.width, height: metadata.height },
|
||||||
|
'Resizing sticker to 512x512 (WABA standard)'
|
||||||
|
)
|
||||||
|
webpBuffer = await lib.sharp
|
||||||
|
.default(webpBuffer)
|
||||||
|
.resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
|
||||||
|
.webp()
|
||||||
|
.toBuffer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ENHANCEMENT: Auto-compression if exceeds 1MB (try quality 70, then 50)
|
// ENHANCEMENT: Auto-compression if exceeds 1MB (try quality 70, then 50)
|
||||||
const MAX_STICKER_SIZE = 1024 * 1024 // 1MB
|
const MAX_STICKER_SIZE = 1024 * 1024 // 1MB
|
||||||
@@ -483,7 +569,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
if (lib?.sharp) {
|
if (lib?.sharp) {
|
||||||
// Try quality 70
|
// Try quality 70
|
||||||
try {
|
try {
|
||||||
const compressed70 = await lib.sharp.default(buffer).webp({ quality: 70 }).toBuffer()
|
const compressed70 = await lib.sharp.default(webpBuffer).webp({ quality: 70 }).toBuffer()
|
||||||
|
|
||||||
// eslint-disable-next-line max-depth
|
// eslint-disable-next-line max-depth
|
||||||
if (compressed70.length <= MAX_STICKER_SIZE) {
|
if (compressed70.length <= MAX_STICKER_SIZE) {
|
||||||
@@ -498,7 +584,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// Try quality 50
|
// Try quality 50
|
||||||
const compressed50 = await lib.sharp.default(buffer).webp({ quality: 50 }).toBuffer()
|
const compressed50 = await lib.sharp.default(webpBuffer).webp({ quality: 50 }).toBuffer()
|
||||||
|
|
||||||
// eslint-disable-next-line max-depth
|
// eslint-disable-next-line max-depth
|
||||||
if (compressed50.length <= MAX_STICKER_SIZE) {
|
if (compressed50.length <= MAX_STICKER_SIZE) {
|
||||||
@@ -547,12 +633,13 @@ export const prepareStickerPackMessage = async (
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gera nome do arquivo: hash.webp (deduplicação automática)
|
// Gera nome do arquivo: hash.webp ou hash.was (WABA: plain_file_hash.ext)
|
||||||
const sha256Hash = generateSha256Hash(webpBuffer)
|
const sha256Hash = generateSha256Hash(webpBuffer)
|
||||||
const fileName = `${sha256Hash}.webp`
|
const extension = isLottie ? 'was' : 'webp'
|
||||||
|
const fileName = `${sha256Hash}.${extension}`
|
||||||
|
|
||||||
logger?.trace(
|
logger?.trace(
|
||||||
{ index: i, fileName, sizeKB: finalSizeKB.toFixed(2), isAnimated },
|
{ index: i, fileName, sizeKB: finalSizeKB.toFixed(2), isAnimated, isLottie },
|
||||||
'Sticker processed successfully'
|
'Sticker processed successfully'
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -560,6 +647,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
fileName,
|
fileName,
|
||||||
webpBuffer,
|
webpBuffer,
|
||||||
isAnimated,
|
isAnimated,
|
||||||
|
isLottie,
|
||||||
emojis: sticker.emojis || [],
|
emojis: sticker.emojis || [],
|
||||||
accessibilityLabel: sticker.accessibilityLabel
|
accessibilityLabel: sticker.accessibilityLabel
|
||||||
}
|
}
|
||||||
@@ -578,7 +666,7 @@ export const prepareStickerPackMessage = async (
|
|||||||
for (const result of processedStickers) {
|
for (const result of processedStickers) {
|
||||||
if (!result) continue
|
if (!result) continue
|
||||||
|
|
||||||
const { fileName, webpBuffer, isAnimated, emojis, accessibilityLabel } = result
|
const { fileName, webpBuffer, isAnimated, isLottie, emojis, accessibilityLabel } = result
|
||||||
|
|
||||||
// SECURITY FIX #7: Check if this hash already exists (duplicate sticker)
|
// SECURITY FIX #7: Check if this hash already exists (duplicate sticker)
|
||||||
const existingMetadata = metadataByHash.get(fileName)
|
const existingMetadata = metadataByHash.get(fileName)
|
||||||
@@ -605,13 +693,14 @@ export const prepareStickerPackMessage = async (
|
|||||||
// New sticker - add to ZIP and create metadata
|
// New sticker - add to ZIP and create metadata
|
||||||
stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 as 0 }]
|
stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 as 0 }]
|
||||||
|
|
||||||
|
// WABA: mimetype é 'application/was' para Lottie, 'image/webp' para WebP
|
||||||
const metadata: proto.Message.StickerPackMessage.ISticker = {
|
const metadata: proto.Message.StickerPackMessage.ISticker = {
|
||||||
fileName,
|
fileName,
|
||||||
isAnimated,
|
isAnimated,
|
||||||
emojis,
|
emojis,
|
||||||
accessibilityLabel,
|
accessibilityLabel,
|
||||||
isLottie: false,
|
isLottie,
|
||||||
mimetype: 'image/webp'
|
mimetype: isLottie ? 'application/was' : 'image/webp'
|
||||||
}
|
}
|
||||||
|
|
||||||
metadataByHash.set(fileName, metadata)
|
metadataByHash.set(fileName, metadata)
|
||||||
@@ -636,10 +725,22 @@ export const prepareStickerPackMessage = async (
|
|||||||
logger?.trace('Processing cover image')
|
logger?.trace('Processing cover image')
|
||||||
coverBuffer = await mediaToBuffer(cover, 'cover image')
|
coverBuffer = await mediaToBuffer(cover, 'cover image')
|
||||||
|
|
||||||
// Converte cover para WebP e adiciona ao ZIP
|
// Tray icon uses PNG format, 96x96 pixels (official client standard)
|
||||||
const result = await convertToWebP(coverBuffer, logger)
|
const lib = await getImageProcessingLibrary()
|
||||||
coverWebP = result.webpBuffer
|
if (!lib?.sharp) {
|
||||||
coverFileName = `${stickerPackId}.webp`
|
throw new Boom(
|
||||||
|
'Sharp library is required for cover/tray icon processing. Install with: yarn add sharp',
|
||||||
|
{ statusCode: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
coverWebP = await lib.sharp
|
||||||
|
.default(coverBuffer)
|
||||||
|
.resize(96, 96, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
|
||||||
|
.png()
|
||||||
|
.toBuffer()
|
||||||
|
|
||||||
|
coverFileName = `${stickerPackId}.png`
|
||||||
stickerData[coverFileName] = [new Uint8Array(coverWebP), { level: 0 as 0 }]
|
stickerData[coverFileName] = [new Uint8Array(coverWebP), { level: 0 as 0 }]
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Boom(`Failed to process cover image: ${(error as Error).message}`, {
|
throw new Boom(`Failed to process cover image: ${(error as Error).message}`, {
|
||||||
|
|||||||
@@ -159,7 +159,10 @@ export async function storeTcTokensFromIqResult({
|
|||||||
[storageJid]: {
|
[storageJid]: {
|
||||||
...existingEntry,
|
...existingEntry,
|
||||||
token: Buffer.from(tokenNode.content),
|
token: Buffer.from(tokenNode.content),
|
||||||
timestamp: tokenNode.attrs.t
|
timestamp: tokenNode.attrs.t,
|
||||||
|
// WABA Android: resets real_issue_timestamp to null when storing a new token
|
||||||
|
// (UPDATE wa_trusted_contacts_send SET real_issue_timestamp=null)
|
||||||
|
realIssueTimestamp: null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
|
|||||||
secondary: config.version[1],
|
secondary: config.version[1],
|
||||||
tertiary: config.version[2]
|
tertiary: config.version[2]
|
||||||
},
|
},
|
||||||
platform: proto.ClientPayload.UserAgent.Platform.MACOS,
|
platform: proto.ClientPayload.UserAgent.Platform.WEB,
|
||||||
releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
|
releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
|
||||||
osVersion: '0.1',
|
osVersion: '0.1',
|
||||||
device: 'Desktop',
|
device: 'Desktop',
|
||||||
@@ -64,12 +64,7 @@ const getClientPayload = (config: SocketConfig) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
|
export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
|
||||||
const decoded = jidDecode(userJid)
|
const { user, device } = jidDecode(userJid)!
|
||||||
if (!decoded) {
|
|
||||||
throw new Boom('Invalid user JID', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { user, device } = decoded
|
|
||||||
const payload: proto.IClientPayload = {
|
const payload: proto.IClientPayload = {
|
||||||
...getClientPayload(config),
|
...getClientPayload(config),
|
||||||
passive: true,
|
passive: true,
|
||||||
@@ -158,9 +153,6 @@ export const configureSuccessfulPairing = (
|
|||||||
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
|
||||||
) => {
|
) => {
|
||||||
const msgId = stanza.attrs.id
|
const msgId = stanza.attrs.id
|
||||||
if (!msgId) {
|
|
||||||
throw new Boom('Missing message ID', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
|
const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
|
||||||
|
|
||||||
@@ -176,51 +168,42 @@ export const configureSuccessfulPairing = (
|
|||||||
const bizName = businessNode?.attrs.name
|
const bizName = businessNode?.attrs.name
|
||||||
const jid = deviceNode.attrs.jid
|
const jid = deviceNode.attrs.jid
|
||||||
const lid = deviceNode.attrs.lid
|
const lid = deviceNode.attrs.lid
|
||||||
if (!jid || !lid) {
|
|
||||||
throw new Boom('Missing JID or LID in device node', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
|
const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
|
||||||
if (!details || !hmac) {
|
|
||||||
throw new Boom('Missing ADV signature fields', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
let hmacPrefix = Buffer.from([])
|
let hmacPrefix = Buffer.from([])
|
||||||
if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
|
if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
|
||||||
hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
||||||
}
|
}
|
||||||
|
|
||||||
const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'))
|
const advSign = hmacSign(Buffer.concat([hmacPrefix, details!]), Buffer.from(advSecretKey, 'base64'))
|
||||||
if (Buffer.compare(hmac, advSign) !== 0) {
|
if (Buffer.compare(hmac!, advSign) !== 0) {
|
||||||
throw new Boom('Invalid account signature')
|
throw new Boom('Invalid account signature')
|
||||||
}
|
}
|
||||||
|
|
||||||
const account = proto.ADVSignedDeviceIdentity.decode(details)
|
const account = proto.ADVSignedDeviceIdentity.decode(details!)
|
||||||
const { accountSignatureKey, accountSignature, details: deviceDetails } = account
|
const { accountSignatureKey, accountSignature, details: deviceDetails } = account
|
||||||
if (!accountSignatureKey || !accountSignature || !deviceDetails) {
|
|
||||||
throw new Boom('Missing ADV account fields', { statusCode: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails)
|
const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails!)
|
||||||
|
|
||||||
const accountSignaturePrefix =
|
const accountSignaturePrefix =
|
||||||
deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
|
deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
|
||||||
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
||||||
: WA_ADV_ACCOUNT_SIG_PREFIX
|
: WA_ADV_ACCOUNT_SIG_PREFIX
|
||||||
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public])
|
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails!, signedIdentityKey.public])
|
||||||
if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
|
if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
|
||||||
throw new Boom('Failed to verify account signature')
|
throw new Boom('Failed to verify account signature')
|
||||||
}
|
}
|
||||||
|
|
||||||
const deviceMsg = Buffer.concat([
|
const deviceMsg = Buffer.concat([
|
||||||
WA_ADV_DEVICE_SIG_PREFIX,
|
WA_ADV_DEVICE_SIG_PREFIX,
|
||||||
deviceDetails,
|
deviceDetails!,
|
||||||
signedIdentityKey.public,
|
signedIdentityKey.public,
|
||||||
accountSignatureKey
|
accountSignatureKey!
|
||||||
])
|
])
|
||||||
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
|
account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
|
||||||
|
|
||||||
const identity = createSignalIdentity(lid, accountSignatureKey)
|
const identity = createSignalIdentity(lid!, accountSignatureKey!)
|
||||||
const accountEnc = encodeSignedDeviceIdentity(account, false)
|
const accountEnc = encodeSignedDeviceIdentity(account, false)
|
||||||
|
|
||||||
const reply: BinaryNode = {
|
const reply: BinaryNode = {
|
||||||
@@ -228,7 +211,7 @@ export const configureSuccessfulPairing = (
|
|||||||
attrs: {
|
attrs: {
|
||||||
to: S_WHATSAPP_NET,
|
to: S_WHATSAPP_NET,
|
||||||
type: 'result',
|
type: 'result',
|
||||||
id: msgId
|
id: msgId!
|
||||||
},
|
},
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
@@ -247,7 +230,7 @@ export const configureSuccessfulPairing = (
|
|||||||
|
|
||||||
const authUpdate: Partial<AuthenticationCreds> = {
|
const authUpdate: Partial<AuthenticationCreds> = {
|
||||||
account,
|
account,
|
||||||
me: { id: jid, name: bizName, lid },
|
me: { id: jid!, name: bizName, lid },
|
||||||
signalIdentities: [...(signalIdentities || []), identity],
|
signalIdentities: [...(signalIdentities || []), identity],
|
||||||
platform: platformNode?.attrs.name
|
platform: platformNode?.attrs.name
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user