From 8fd355360c372900ce68fcce759c8b12c9f1766a Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Sun, 25 Oct 2026 19:34:54 +0000 Subject: [PATCH 01/42] connector: relay WhatsApp pairing WebSockets through the client --- go.mod | 2 +- go.sum | 4 ++-- pkg/connector/login.go | 37 +++++++++++++++++++++++-------------- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/go.mod b/go.mod index 0c70c3d..8b3a49b 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( golang.org/x/sync v0.24.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - maunium.net/go/mautrix v0.32.0 + maunium.net/go/mautrix v0.32.1-0.20261025192835-58302644df53 ) require ( diff --git a/go.sum b/go.sum index 576ec24..0ed138f 100644 --- a/go.sum +++ b/go.sum @@ -103,5 +103,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M= maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA= -maunium.net/go/mautrix v0.32.0 h1:xuAZzzyWce0pFkBhV/MCLFiJdVs2rFkY3Eep7hNng4I= -maunium.net/go/mautrix v0.32.0/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= +maunium.net/go/mautrix v0.32.1-0.20261025192835-58302644df53 h1:bL8PdtUUkpuHNO+r7fnyzrSUk3b8d7+f/E/r1HInRkg= +maunium.net/go/mautrix v0.32.1-0.20261025192835-58302644df53/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= diff --git a/pkg/connector/login.go b/pkg/connector/login.go index 387d780..af397e9 100644 --- a/pkg/connector/login.go +++ b/pkg/connector/login.go @@ -137,6 +137,7 @@ var ( _ bridgev2.LoginProcessDisplayAndWait = (*WALogin)(nil) _ bridgev2.LoginProcessUserInput = (*WALogin)(nil) _ bridgev2.LoginProcessWithOverride = (*WALogin)(nil) + _ bridgev2.LoginProcessWithParams = (*WALogin)(nil) _ bridgev2.LoginProcessWebAuthn = (*WALogin)(nil) ) @@ -144,6 +145,14 @@ const LoginConnectWait = 30 * time.Second const LoginPairPhoneWait = 30 * time.Second func (wl *WALogin) Start(ctx context.Context) (*bridgev2.LoginStep, error) { + return wl.StartWithParams(ctx, bridgev2.LoginStartParams{}) +} + +func (wl *WALogin) StartWithOverride(ctx context.Context, old *bridgev2.UserLogin) (*bridgev2.LoginStep, error) { + return wl.StartWithParams(ctx, bridgev2.LoginStartParams{Override: old}) +} + +func (wl *WALogin) StartWithParams(ctx context.Context, params bridgev2.LoginStartParams) (*bridgev2.LoginStep, error) { wl.Main.firstClientConnectOnce.Do(wl.Main.onFirstClientConnect) device := wl.Main.DeviceStore.NewDevice() wl.Client = whatsmeow.NewClient(device, waLog.Zerolog(wl.Log)) @@ -153,8 +162,20 @@ func (wl *WALogin) Start(ctx context.Context) (*bridgev2.LoginStep, error) { if err := wl.Main.updateProxy(ctx, wl.Client, true); err != nil { return nil, err } + if params.WebSocketHTTP != nil { + wl.Client.SetPreLoginHTTPClient(&http.Client{Transport: params.WebSocketHTTP}) + } if wl.PhoneCode { + if params.Override != nil { + phoneNumber := fmt.Sprintf("+%s", params.Override.ID) + wl.Log.Debug(). + Str("phone_number", phoneNumber). + Msg("Auto-submitting phone number for relogin") + return wl.SubmitUserInput(ctx, map[string]string{ + "phone_number": phoneNumber, + }) + } return &bridgev2.LoginStep{ Type: bridgev2.LoginStepTypeUserInput, StepID: LoginStepIDPhoneNumber, @@ -184,20 +205,6 @@ func (wl *WALogin) Start(ctx context.Context) (*bridgev2.LoginStep, error) { return makeQRStep(wl.QRs[0]), nil } -func (wl *WALogin) StartWithOverride(ctx context.Context, old *bridgev2.UserLogin) (*bridgev2.LoginStep, error) { - step, err := wl.Start(ctx) - if err == nil && step != nil && old != nil && step.StepID == LoginStepIDPhoneNumber { - phoneNumber := fmt.Sprintf("+%s", old.ID) - wl.Log.Debug(). - Str("phone_number", phoneNumber). - Msg("Auto-submitting phone number for relogin") - return wl.SubmitUserInput(ctx, map[string]string{ - "phone_number": phoneNumber, - }) - } - return step, err -} - func (wl *WALogin) SubmitUserInput(ctx context.Context, input map[string]string) (*bridgev2.LoginStep, error) { err := wl.Client.Connect() if err != nil { @@ -316,6 +323,8 @@ func (wl *WALogin) handleEvent(rawEvt any) { wl.LoginError = ErrUnexpectedDisconnect case *events.ManualLoginReconnect: wl.Received515.Set() + // PairSuccess is dispatched separately and may arrive after the 515. + return default: wl.Log.Warn().Type("event_type", evt).Msg("Got unexpected event") return From 8f1937b25941872fa1abbff73970ef35e0b8870e Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 26 Oct 2026 06:18:12 -0400 Subject: [PATCH 02/42] msgconv/rich-response: don't include raw data if the message would be too large (#996) --- pkg/msgconv/wa-rich-response.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkg/msgconv/wa-rich-response.go b/pkg/msgconv/wa-rich-response.go index 41ac9ab..28a648c 100644 --- a/pkg/msgconv/wa-rich-response.go +++ b/pkg/msgconv/wa-rich-response.go @@ -66,10 +66,15 @@ func (mc *MessageConverter) convertUnifiedRichResponseMessage(ctx context.Contex Extra: extra, } } + content := format.HTMLToContent(htmlBuf.String()) + if len(data)+len(content.Body)+len(content.FormattedBody) > 40000 { + delete(extra, "fi.mau.whatsapp.rich_message") + delete(extra, "fi.mau.whatsapp.non_json_rich_message") + } extra["fi.mau.whatsapp.rich_response_id"] = rrMsg.ResponseID return &bridgev2.ConvertedMessagePart{ Type: event.EventMessage, - Content: new(format.HTMLToContent(htmlBuf.String())), + Content: &content, Extra: extra, } } From 56a19a1d10b3ed17b0409174a9327bde9fefd96b Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 26 Oct 2026 06:18:46 -0400 Subject: [PATCH 03/42] msgconv/from-whatsapp: count mentions when cutting off long messages (#995) --- pkg/msgconv/wa-text.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/pkg/msgconv/wa-text.go b/pkg/msgconv/wa-text.go index 1a01633..52874fd 100644 --- a/pkg/msgconv/wa-text.go +++ b/pkg/msgconv/wa-text.go @@ -48,22 +48,28 @@ func (mc *MessageConverter) convertTextMessage(ctx context.Context, msg *waE2E.M } func (mc *MessageConverter) cutOffLongMessage(content *event.MessageEventContent) { - if len(content.FormattedBody) <= 20000 && len(content.Body) <= 20000 { + size := len(content.Body) + len(content.FormattedBody) + if content.Mentions != nil { + for _, userID := range content.Mentions.UserIDs { + size += len(userID) + } + } + if size <= 40000 { return } + if content.Mentions != nil { + content.Mentions.UserIDs = slices.DeleteFunc(content.Mentions.UserIDs, mc.Bridge.IsGhostMXID) + } if content.FormattedBody == "" { if len(content.Body) > 40000 { content.Body = content.Body[:40000] + "\n\n[long message cut off]" } - } else if len(content.Body) > 500 { + } else if len(content.FormattedBody) > 20000 && len(content.Body) > 500 { content.Body = content.Body[:500] + "[...]" } if len(content.FormattedBody) > 40000 { content.FormattedBody = content.FormattedBody[:40000] + "
[long message cut off]" } - if content.Mentions != nil { - content.Mentions.UserIDs = slices.DeleteFunc(content.Mentions.UserIDs, mc.Bridge.IsGhostMXID) - } } func (mc *MessageConverter) parseFormatting(content *event.MessageEventContent, allowInlineURL, forceHTML bool) { From 1678681af7a849b66ababf66a928d874db5186da Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 26 Oct 2026 06:24:17 -0400 Subject: [PATCH 04/42] chatinfo: don't create rooms for newsletters that no longer exist (#993) --- pkg/connector/backfill.go | 2 +- pkg/connector/chatinfo.go | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index f1fc56e..629039d 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -435,7 +435,7 @@ func (wa *WhatsAppClient) createPortalsFromHistorySync(ctx context.Context) { return } wrappedInfo, err := wa.getChatInfo(ctx, conv.ChatJID, conv, true) - if errors.Is(err, whatsmeow.ErrNotInGroup) || errors.Is(err, whatsmeow.ErrGroupNotFound) { + if errors.Is(err, whatsmeow.ErrNotInGroup) || errors.Is(err, whatsmeow.ErrGroupNotFound) || errors.Is(err, ErrNewsletterNotFound) { log.Debug().Err(err).Stringer("chat_jid", conv.ChatJID). Msg("Skipping creating room because the user is not a participant") //err = wa.Main.DB.Message.DeleteAllInChat(ctx, wa.UserLogin.ID, conv.ChatJID) diff --git a/pkg/connector/chatinfo.go b/pkg/connector/chatinfo.go index 61b9e74..ce8c739 100644 --- a/pkg/connector/chatinfo.go +++ b/pkg/connector/chatinfo.go @@ -31,6 +31,7 @@ func (wa *WhatsAppClient) GetChatInfo(ctx context.Context, portal *bridgev2.Port } var ErrBroadcastList = errors.New("broadcast list bridging is currently not supported") +var ErrNewsletterNotFound = errors.New("newsletter doesn't exist") func (wa *WhatsAppClient) getChatInfo(ctx context.Context, portalJID types.JID, conv *wadb.Conversation, isNew bool) (wrapped *bridgev2.ChatInfo, err error) { switch portalJID.Server { @@ -56,6 +57,8 @@ func (wa *WhatsAppClient) getChatInfo(ctx context.Context, portalJID types.JID, info, err := wa.Client.GetNewsletterInfo(ctx, portalJID) if err != nil { return nil, err + } else if info == nil || info.ID.IsEmpty() { + return nil, ErrNewsletterNotFound } wrapped = wa.wrapNewsletterInfo(ctx, info) default: From 2759bc5ea25237fee4645e9e2c131f014362cfb7 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Mon, 26 Oct 2026 14:17:07 +0200 Subject: [PATCH 05/42] msgconv/from-whatsapp: add support for encrypted direct media --- go.mod | 2 +- go.sum | 4 ++-- pkg/msgconv/wa-media.go | 4 +++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 0c70c3d..4dc9322 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( golang.org/x/sync v0.24.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - maunium.net/go/mautrix v0.32.0 + maunium.net/go/mautrix v0.32.1-0.20261026114918-8c92262134ae ) require ( diff --git a/go.sum b/go.sum index 576ec24..b698912 100644 --- a/go.sum +++ b/go.sum @@ -103,5 +103,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M= maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA= -maunium.net/go/mautrix v0.32.0 h1:xuAZzzyWce0pFkBhV/MCLFiJdVs2rFkY3Eep7hNng4I= -maunium.net/go/mautrix v0.32.0/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= +maunium.net/go/mautrix v0.32.1-0.20261026114918-8c92262134ae h1:4SY5+nh2B968L5NmMGmF0WPRbV9D1yFLP8U+JASuHXg= +maunium.net/go/mautrix v0.32.1-0.20261026114918-8c92262134ae/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= diff --git a/pkg/msgconv/wa-media.go b/pkg/msgconv/wa-media.go index 20a1a14..ff7008b 100644 --- a/pkg/msgconv/wa-media.go +++ b/pkg/msgconv/wa-media.go @@ -91,7 +91,9 @@ func (mc *MessageConverter) convertMediaMessage( var err error portal := getPortal(ctx) idOverride := getEditTargetID(ctx) - preparedMedia.URL, err = portal.Bridge.Matrix.GenerateContentURI(ctx, waid.MakeMediaID(messageInfo, idOverride, portal.Receiver, getMediaIDVersion(msg))) + preparedMedia.URL, preparedMedia.File, err = portal.Bridge.GenerateContentURI( + ctx, portal.MXID, waid.MakeMediaID(messageInfo, idOverride, portal.Receiver, getMediaIDVersion(msg)), + ) if err != nil { panic(fmt.Errorf("failed to generate content URI: %w", err)) } From 960b4ed000a6d8da7b6a1d3094bc73389b637830 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Mon, 26 Oct 2026 14:54:30 +0200 Subject: [PATCH 06/42] client: send unified session on connect Closes #992 --- go.mod | 2 +- go.sum | 4 ++-- pkg/connector/client.go | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 4dc9322..c58cd7c 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,7 @@ require ( github.com/yuin/goldmark v1.8.6 go.mau.fi/util v0.11.0 go.mau.fi/webp v0.3.0 - go.mau.fi/whatsmeow v0.0.0-20261016130820-0b0a1cdac3e2 + go.mau.fi/whatsmeow v0.0.0-20261026125351-1fbae988179a golang.org/x/image v0.47.0 golang.org/x/net v0.61.0 golang.org/x/sync v0.24.0 diff --git a/go.sum b/go.sum index b698912..df5df11 100644 --- a/go.sum +++ b/go.sum @@ -71,8 +71,8 @@ go.mau.fi/util v0.11.0 h1:JNEpkVRxfTdJUC0DIGKiRlLKzl4G/qLX/eVzoP7QuwY= go.mau.fi/util v0.11.0/go.mod h1:04AEFVsc4zNdIkDC1gkdqbg/nZFolHY50pyXh2DSy7s= go.mau.fi/webp v0.3.0 h1:gVHQZtz21Ziwj+CDuklbX9mqpsnDIFKxs/BJyV7iZzA= go.mau.fi/webp v0.3.0/go.mod h1:rlZFTev+dYxhvk+XNBP/5GcTt4gXmzAB4DU0aGUYIQo= -go.mau.fi/whatsmeow v0.0.0-20261016130820-0b0a1cdac3e2 h1:+EhsWM5VeE5Vu3KRlk3PmYAY0lEYkbhI5W4mTmM9X/Q= -go.mau.fi/whatsmeow v0.0.0-20261016130820-0b0a1cdac3e2/go.mod h1:iY4lm61nTLWsNiIE1EmHUZwhKGBeoV4dhnVE2uMtNoQ= +go.mau.fi/whatsmeow v0.0.0-20261026125351-1fbae988179a h1:ZyCV/mWfRkutxs5R0K3v+oyTbF4huprSlPZg/LEFQ7k= +go.mau.fi/whatsmeow v0.0.0-20261026125351-1fbae988179a/go.mod h1:iY4lm61nTLWsNiIE1EmHUZwhKGBeoV4dhnVE2uMtNoQ= go.mau.fi/zeroconfig v0.2.0 h1:e/OGEERqVRRKlgaro7E6bh8xXiKFSXB3eNNIud7FUjU= go.mau.fi/zeroconfig v0.2.0/go.mod h1:J0Vn0prHNOm493oZoQ84kq83ZaNCYZnq+noI1b1eN8w= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= diff --git a/pkg/connector/client.go b/pkg/connector/client.go index cd52be2..4181235 100644 --- a/pkg/connector/client.go +++ b/pkg/connector/client.go @@ -84,6 +84,7 @@ func (wa *WhatsAppConnector) LoadUserLogin(ctx context.Context, login *bridgev2. w.Client.ManualHistorySyncDownload = true w.Client.SendReportingTokens = true w.Client.AutomaticMessageRerequestFromPhone = true + w.Client.UnifiedSessionInterval = 24 * time.Hour w.Client.GetMessageForRetry = w.trackNotFoundRetry w.Client.PreRetryCallback = w.trackFoundRetry w.Client.BackgroundEventCtx = w.UserLogin.Log.WithContext(wa.Bridge.BackgroundCtx) From 322485c5a983682b0023bb94281a9ce08a29be8a Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 26 Oct 2026 12:14:24 -0400 Subject: [PATCH 07/42] handlewhatsapp: match own phone number in bot chat receipts (#1000) --- pkg/connector/handlewhatsapp.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pkg/connector/handlewhatsapp.go b/pkg/connector/handlewhatsapp.go index e7a9b65..4ba4f10 100644 --- a/pkg/connector/handlewhatsapp.go +++ b/pkg/connector/handlewhatsapp.go @@ -514,6 +514,10 @@ func (wa *WhatsAppClient) handleWAReceipt(ctx context.Context, evt *events.Recei } else if evt.Chat.Server == types.NewsletterServer { messageSender = evt.Chat } + var messageSenderAlt types.JID + if evt.MessageSender.IsEmpty() && evt.Chat.Server == types.BotServer { + messageSenderAlt = wa.JID + } var chatAlt types.JID if evt.Chat.Server == types.DefaultUserServer { chatLID, _ := wa.GetStore().LIDs.GetLIDForPN(ctx, evt.Chat) @@ -527,6 +531,9 @@ func (wa *WhatsAppClient) handleWAReceipt(ctx context.Context, evt *events.Recei if !chatAlt.IsEmpty() { targets = append(targets, waid.MakeMessageID(chatAlt, messageSender, id)) } + if !messageSenderAlt.IsEmpty() { + targets = append(targets, waid.MakeMessageID(evt.Chat, messageSenderAlt, id)) + } } senderLID := evt.Sender if senderLID.Server == types.DefaultUserServer && !evt.SenderAlt.IsEmpty() { From 57e055c3adb94c63849ac35ecc89a5f32ef3de74 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 26 Oct 2026 16:42:19 +0000 Subject: [PATCH 08/42] lidmigrate: move Meta AI phone number portals to the bot JID (#998) --- pkg/connector/backfill.go | 8 ++++++-- pkg/connector/connector.go | 4 ++++ pkg/connector/lidmigrate.go | 28 ++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index 629039d..0e319e2 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -249,7 +249,9 @@ func (wa *WhatsAppClient) handleWAHistorySync( } else { totalMessageCount += len(conv.GetMessages()) } - if jid.Server == types.DefaultUserServer { + if jid == types.MetaAIJID { + jid = types.NewMetaAIJID + } else if jid.Server == types.DefaultUserServer { lid, err := wa.GetStore().LIDs.GetLIDForPN(ctx, jid) if err != nil { log.Err(err).Stringer("pn", jid).Msg("Failed to get LID for phone number in history sync") @@ -803,7 +805,9 @@ func (wa *WhatsAppClient) handleOnDemandHistorySync(ctx context.Context, blob *w zerolog.Ctx(ctx).Err(err).Str("jid", conv.GetID()).Msg("Failed to parse portal JID") continue } - if portalJID.Server == types.DefaultUserServer { + if portalJID == types.MetaAIJID { + portalJID = types.NewMetaAIJID + } else if portalJID.Server == types.DefaultUserServer { lid, err := wa.GetStore().LIDs.GetLIDForPN(ctx, portalJID) if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("lid", portalJID).Msg("Failed to get LID for phone number in on-demand history sync") diff --git a/pkg/connector/connector.go b/pkg/connector/connector.go index d7261d3..fb3cdc8 100644 --- a/pkg/connector/connector.go +++ b/pkg/connector/connector.go @@ -164,6 +164,10 @@ func (wa *WhatsAppConnector) Start(ctx context.Context) error { if err != nil { return fmt.Errorf("failed to migrate to LID DMs: %w", err) } + err = wa.migrateMetaAIPortals(ctx) + if err != nil { + return fmt.Errorf("failed to migrate Meta AI portals: %w", err) + } go func() { err = wa.syncMismatchingGhosts(wa.Bridge.BackgroundCtx) if err != nil { diff --git a/pkg/connector/lidmigrate.go b/pkg/connector/lidmigrate.go index ec1c700..befef07 100644 --- a/pkg/connector/lidmigrate.go +++ b/pkg/connector/lidmigrate.go @@ -47,6 +47,8 @@ func (wa *WhatsAppClient) FindAltTargetMessage(ctx context.Context, targetMsg ne if err != nil { return nil, err } + } else if parsed.Chat == types.NewMetaAIJID { + altChat = types.MetaAIJID } if !altSender.IsEmpty() { altSenderID := *parsed @@ -58,6 +60,8 @@ func (wa *WhatsAppClient) FindAltTargetMessage(ctx context.Context, targetMsg ne altChatID.Chat = altChat if altSender.Server == types.DefaultUserServer { altChatID.Sender = altSender + } else if parsed.Sender == types.NewMetaAIJID { + altChatID.Sender = types.MetaAIJID } alts = append(alts, altChatID.String()) } @@ -211,6 +215,30 @@ func (wa *WhatsAppConnector) migrateToLIDDMs(ctx context.Context) error { return nil } +func (wa *WhatsAppConnector) migrateMetaAIPortals(ctx context.Context) error { + if wa.Bridge.Background || wa.Bridge.DB.KV.Get(ctx, "whatsapp_meta_ai_portals_migrated") == "true" { + return nil + } + log := zerolog.Ctx(ctx).With().Str("action", "migrate meta ai portals").Logger() + const findMetaAIPortals = "SELECT id, receiver FROM portal WHERE bridge_id=$1 AND id=$2" + portalKeys, err := scanPortalKey.NewRowIter(wa.Bridge.DB.Query(ctx, findMetaAIPortals, wa.Bridge.ID, waid.MakePortalID(types.MetaAIJID))).AsList() + if err != nil { + return fmt.Errorf("failed to get Meta AI portals: %w", err) + } + for _, key := range portalKeys { + res, err := wa.reIDPhoneDMToLID(ctx, types.MetaAIJID, types.NewMetaAIJID, key.Receiver) + if err != nil { + return fmt.Errorf("failed to re-ID Meta AI portal for %s: %w", key.Receiver, err) + } + log.Info(). + Str("receiver", string(key.Receiver)). + Stringer("result", res). + Msg("Re-ID'd Meta AI phone number portal") + } + wa.Bridge.DB.KV.Set(ctx, "whatsapp_meta_ai_portals_migrated", "true") + return nil +} + func (wa *WhatsAppConnector) syncMismatchingGhosts(ctx context.Context) error { if wa.Bridge.Background || wa.Bridge.DB.KV.Get(ctx, "whatsapp_lid_avatars_resynced") == "true" { return nil From 870414b015739dec7087ea4660b33e11b7f0a237 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 26 Oct 2026 17:58:59 +0000 Subject: [PATCH 09/42] commands: add reset-appstate command (#994) --- pkg/connector/commands.go | 52 +++++++++++++++++++++++++++++++++----- pkg/connector/connector.go | 2 +- 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/pkg/connector/commands.go b/pkg/connector/commands.go index 037d24e..120d05e 100644 --- a/pkg/connector/commands.go +++ b/pkg/connector/commands.go @@ -148,13 +148,7 @@ func fnSync(ce *commands.Event) { case "appstate": names := appstate.AllPatchNames[:] if len(ce.Args) > 1 { - names = exslices.CastFuncFilter(ce.Args[1:], func(name string) (appstate.WAPatchName, bool) { - if !slices.Contains(appstate.AllPatchNames[:], appstate.WAPatchName(name)) { - ce.Reply("Invalid app state name `%s`", name) - return "", false - } - return appstate.WAPatchName(name), true - }) + names = parseAppStateNames(ce, ce.Args[1:]) } for _, name := range names { err := wa.Client.FetchAppState(ce.Ctx, name, true, false) @@ -174,6 +168,50 @@ func fnSync(ce *commands.Event) { } } +func parseAppStateNames(ce *commands.Event, args []string) []appstate.WAPatchName { + return exslices.CastFuncFilter(args, func(name string) (appstate.WAPatchName, bool) { + if !slices.Contains(appstate.AllPatchNames[:], appstate.WAPatchName(name)) { + ce.Reply("Invalid app state name `%s`", name) + return "", false + } + return appstate.WAPatchName(name), true + }) +} + +var cmdResetAppState = &commands.FullHandler{ + Func: fnResetAppState, + Name: "reset-appstate", + Help: commands.HelpMeta{ + Section: commands.HelpSectionAdmin, + Description: "Ask your phone to reset broken app state. This logs out all linked devices.", + Args: "", + }, + RequiresLogin: true, +} + +func fnResetAppState(ce *commands.Event) { + login := ce.User.GetDefaultLogin() + if login == nil { + ce.Reply("Login not found") + return + } + if len(ce.Args) == 0 { + ce.Reply("Usage: `$cmdprefix reset-appstate `\n\nThis logs out all linked devices, including the bridge. You'll have to log in again afterwards.") + return + } + names := parseAppStateNames(ce, ce.Args) + if len(names) != len(ce.Args) { + return + } + wa := login.Client.(*WhatsAppClient) + _, err := wa.Client.SendPeerMessage(ce.Ctx, whatsmeow.BuildFatalAppStateExceptionNotification(names...)) + if err != nil { + ce.Reply("Failed to send app state reset request: %v", err) + return + } + ce.Reply("Sent app state reset request. Your phone should log out all linked devices shortly, after which you can log in again.") +} + var cmdInviteLink = &commands.FullHandler{ Func: fnInviteLink, Name: "invite-link", diff --git a/pkg/connector/connector.go b/pkg/connector/connector.go index fb3cdc8..94c66eb 100644 --- a/pkg/connector/connector.go +++ b/pkg/connector/connector.go @@ -110,7 +110,7 @@ func (wa *WhatsAppConnector) Init(bridge *bridgev2.Bridge) { wa.DB = wadb.New(bridge.ID, bridge.DB.Database, bridge.Log.With().Str("db_section", "whatsapp").Logger()) wa.MsgConv.DB = wa.DB wa.Bridge.Commands.(*commands.Processor).AddHandlers( - cmdAccept, cmdSync, cmdInviteLink, cmdResolveLink, cmdJoin, + cmdAccept, cmdSync, cmdResetAppState, cmdInviteLink, cmdResolveLink, cmdJoin, ) wa.mediaEditCache = make(MediaEditCache) wa.unmigratedDMs = exsync.NewSet[networkid.PortalKey]() From bb09b7584cc7ac28a4a2fdcd17b71fa2af2f6d36 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Tue, 27 Oct 2026 10:42:29 +0000 Subject: [PATCH 10/42] msgconv/from-matrix: convert non-h264 videos when sending (#987) --- pkg/msgconv/from-matrix.go | 58 +++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/pkg/msgconv/from-matrix.go b/pkg/msgconv/from-matrix.go index 192b8a6..ba2adc2 100644 --- a/pkg/msgconv/from-matrix.go +++ b/pkg/msgconv/from-matrix.go @@ -27,12 +27,15 @@ import ( "image/color" "image/jpeg" "net/http" + "os" + "path/filepath" "slices" "strconv" "strings" "time" "github.com/rs/zerolog" + "go.mau.fi/util/exmime" "go.mau.fi/util/ffmpeg" "go.mau.fi/util/ptr" "go.mau.fi/util/random" @@ -515,6 +518,56 @@ func (mc *MessageConverter) convertToWebP(img []byte) ([]byte, int, error) { return webpBuffer.Bytes(), size, nil } +func convertUnsupportedVideoCodec(ctx context.Context, data []byte, mime string) ([]byte, string, error) { + if !ffmpeg.Supported() || !ffmpeg.ProbeSupported() { + return data, mime, nil + } + log := zerolog.Ctx(ctx) + tempdir, err := os.MkdirTemp("", "mautrix_whatsapp_video_*") + if err != nil { + log.Warn().Err(err).Msg("Failed to create temp dir for video, sending it as-is") + return data, mime, nil + } + defer os.RemoveAll(tempdir) + inputPath := filepath.Join(tempdir, "input"+exmime.ExtensionFromMimetype(mime)) + err = os.WriteFile(inputPath, data, 0600) + if err != nil { + log.Warn().Err(err).Msg("Failed to write video to temp file, sending it as-is") + return data, mime, nil + } + probe, err := ffmpeg.Probe(ctx, inputPath) + if err != nil { + log.Warn().Err(err).Msg("Failed to probe video, sending it as-is") + return data, mime, nil + } + videoSupported := !slices.ContainsFunc(probe.Streams, func(stream *ffmpeg.Stream) bool { + return stream.CodecType == "video" && stream.Disposition.AttachedPic == 0 && stream.CodecName != "h264" + }) + audioSupported := !slices.ContainsFunc(probe.Streams, func(stream *ffmpeg.Stream) bool { + return stream.CodecType == "audio" && stream.CodecName != "aac" + }) + if videoSupported && audioSupported { + return data, mime, nil + } + videoArgs := []string{"-c:v", "copy"} + if !videoSupported { + videoArgs = []string{ + "-pix_fmt", "yuv420p", "-c:v", "h264", "-b:v", "2M", + "-filter:v", "crop='floor(in_w/2)*2:floor(in_h/2)*2'", + } + } + outputPath := filepath.Join(tempdir, "output.mp4") + err = ffmpeg.ConvertPathWithDestination(ctx, inputPath, outputPath, nil, append(videoArgs, "-c:a", "aac", "-movflags", "+faststart"), false) + if err != nil { + return nil, mime, err + } + converted, err := os.ReadFile(outputPath) + if err != nil { + return nil, mime, err + } + return converted, "video/mp4", nil +} + func (mc *MessageConverter) getOriginalBridgedSticker(ctx context.Context, info *event.BridgedSticker) (*types.StickerPackItem, error) { if info == nil || info.Network != StickerSourceID || !strings.HasPrefix(info.PackURL, StickerPackURLPrefix) || info.ID == "" { return nil, nil @@ -609,7 +662,10 @@ func (mc *MessageConverter) reuploadFileToWhatsApp( case event.MsgVideo: switch mime { case "video/mp4", "video/3gpp": - // allowed + data, mime, err = convertUnsupportedVideoCodec(ctx, data, mime) + if err != nil { + return nil, nil, mime, fmt.Errorf("%w (%s to h264): %w", bridgev2.ErrMediaConvertFailed, mime, err) + } case "video/webm", "video/quicktime": sourceFormat := "webm" if mime == "video/quicktime" { From 76c59bd05db9c53dfd4d9181a73c605f52091976 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Tue, 27 Oct 2026 10:42:50 +0000 Subject: [PATCH 11/42] backfill: mark history sync messages read up to the unread count (#1001) --- go.mod | 2 +- go.sum | 4 ++-- pkg/connector/backfill.go | 19 +++++++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index c58cd7c..fc19065 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( golang.org/x/sync v0.24.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - maunium.net/go/mautrix v0.32.1-0.20261026114918-8c92262134ae + maunium.net/go/mautrix v0.32.1-0.20261026145030-920bc073ba8d ) require ( diff --git a/go.sum b/go.sum index df5df11..2775f5f 100644 --- a/go.sum +++ b/go.sum @@ -103,5 +103,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M= maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA= -maunium.net/go/mautrix v0.32.1-0.20261026114918-8c92262134ae h1:4SY5+nh2B968L5NmMGmF0WPRbV9D1yFLP8U+JASuHXg= -maunium.net/go/mautrix v0.32.1-0.20261026114918-8c92262134ae/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= +maunium.net/go/mautrix v0.32.1-0.20261026145030-920bc073ba8d h1:DsMn0i7cBKcQZ0AVxJm9hfWAu6xJdjRrf457EtXxyNY= +maunium.net/go/mautrix v0.32.1-0.20261026145030-920bc073ba8d/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index 0e319e2..54edbaa 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -595,9 +595,28 @@ func (wa *WhatsAppClient) FetchMessages(ctx context.Context, params bridgev2.Fet resp.HasMore = hasMore resp.Forward = params.Forward resp.MarkRead = markRead + if params.Forward && !markRead && conv != nil && !ptr.Val(conv.MarkedAsUnread) { + resp.ReadUpTo = historySyncReadUpTo(resp.Messages, int(ptr.Val(conv.UnreadCount))) + } return resp, nil } +func historySyncReadUpTo(messages []*bridgev2.BackfillMessage, unreadCount int) time.Time { + if unreadCount <= 0 { + return time.Time{} + } + for i := len(messages) - 1; i >= 0; i-- { + if messages[i].Sender.IsFromMe { + continue + } + unreadCount-- + if unreadCount == 0 { + return messages[i].Timestamp.Add(-time.Nanosecond) + } + } + return time.Time{} +} + func (wa *WhatsAppClient) deleteHistorySyncMessages(ctx context.Context, portalJID types.JID, newestTS, oldestTS uint64) { var err error var rows int64 From 021504afb01a5f117dd3ffa368f5a3afe8b19f51 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Tue, 27 Oct 2026 12:28:53 +0000 Subject: [PATCH 12/42] msgconv/wa-media: fix sticker dimension scaling for small non-square stickers (#991) --- pkg/msgconv/wa-media.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/msgconv/wa-media.go b/pkg/msgconv/wa-media.go index ff7008b..30c6b30 100644 --- a/pkg/msgconv/wa-media.go +++ b/pkg/msgconv/wa-media.go @@ -255,10 +255,10 @@ func fixStickerDimensions(info *event.FileInfo) { info.Width = WhatsAppStickerSize info.Height = WhatsAppStickerSize } else if info.Width > info.Height { - info.Height /= info.Width / WhatsAppStickerSize + info.Height = info.Height * WhatsAppStickerSize / info.Width info.Width = WhatsAppStickerSize } else { - info.Width /= info.Height / WhatsAppStickerSize + info.Width = info.Width * WhatsAppStickerSize / info.Height info.Height = WhatsAppStickerSize } } From 51b5c5e5fb764435f278883adf63a6dc25842e0f Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Tue, 27 Oct 2026 16:45:29 +0000 Subject: [PATCH 13/42] msgconv/from-whatsapp: bridge live location start as m.location (#1002) --- pkg/msgconv/wa-location.go | 101 +++++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 33 deletions(-) diff --git a/pkg/msgconv/wa-location.go b/pkg/msgconv/wa-location.go index 4a1e043..52f3f13 100644 --- a/pkg/msgconv/wa-location.go +++ b/pkg/msgconv/wa-location.go @@ -30,6 +30,40 @@ import ( "maunium.net/go/mautrix/event" ) +func formatCoordinates(lat, long float64) string { + latChar := 'N' + if lat < 0 { + latChar = 'S' + } + longChar := 'E' + if long < 0 { + longChar = 'W' + } + return fmt.Sprintf("%.4f° %c %.4f° %c", math.Abs(lat), latChar, math.Abs(long), longChar) +} + +func addLocationThumbnail(ctx context.Context, content *event.MessageEventContent, thumbnail []byte) { + if len(thumbnail) == 0 { + return + } + thumbnailMime := http.DetectContentType(thumbnail) + thumbnailURL, thumbnailFile, err := getIntent(ctx).UploadMedia(ctx, getPortal(ctx).MXID, thumbnail, "thumb.jpeg", thumbnailMime) + if err != nil { + return + } + cfg, _, _ := image.DecodeConfig(bytes.NewReader(thumbnail)) + content.Info = &event.FileInfo{ + ThumbnailInfo: &event.FileInfo{ + Size: len(thumbnail), + Width: cfg.Width, + Height: cfg.Height, + MimeType: thumbnailMime, + }, + ThumbnailURL: thumbnailURL, + ThumbnailFile: thumbnailFile, + } +} + func (mc *MessageConverter) convertLocationMessage(ctx context.Context, msg *waE2E.LocationMessage) (*bridgev2.ConvertedMessagePart, *waE2E.ContextInfo) { url := msg.GetURL() if len(url) == 0 { @@ -37,15 +71,7 @@ func (mc *MessageConverter) convertLocationMessage(ctx context.Context, msg *waE } name := msg.GetName() if len(name) == 0 { - latChar := 'N' - if msg.GetDegreesLatitude() < 0 { - latChar = 'S' - } - longChar := 'E' - if msg.GetDegreesLongitude() < 0 { - longChar = 'W' - } - name = fmt.Sprintf("%.4f° %c %.4f° %c", math.Abs(msg.GetDegreesLatitude()), latChar, math.Abs(msg.GetDegreesLongitude()), longChar) + name = formatCoordinates(msg.GetDegreesLatitude(), msg.GetDegreesLongitude()) } content := &event.MessageEventContent{ @@ -55,24 +81,7 @@ func (mc *MessageConverter) convertLocationMessage(ctx context.Context, msg *waE FormattedBody: fmt.Sprintf(`Location: %s
%s`, html.EscapeString(url), html.EscapeString(name), html.EscapeString(msg.GetAddress())), GeoURI: fmt.Sprintf("geo:%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude()), } - - if len(msg.GetJPEGThumbnail()) > 0 { - thumbnailMime := http.DetectContentType(msg.GetJPEGThumbnail()) - thumbnailURL, thumbnailFile, err := getIntent(ctx).UploadMedia(ctx, getPortal(ctx).MXID, msg.GetJPEGThumbnail(), "thumb.jpeg", thumbnailMime) - if err == nil { - cfg, _, _ := image.DecodeConfig(bytes.NewReader(msg.GetJPEGThumbnail())) - content.Info = &event.FileInfo{ - ThumbnailInfo: &event.FileInfo{ - Size: len(msg.GetJPEGThumbnail()), - Width: cfg.Width, - Height: cfg.Height, - MimeType: thumbnailMime, - }, - ThumbnailURL: thumbnailURL, - ThumbnailFile: thumbnailFile, - } - } - } + addLocationThumbnail(ctx, content, msg.GetJPEGThumbnail()) return &bridgev2.ConvertedMessagePart{ Type: event.EventMessage, @@ -81,14 +90,40 @@ func (mc *MessageConverter) convertLocationMessage(ctx context.Context, msg *waE } func (mc *MessageConverter) convertLiveLocationMessage(ctx context.Context, msg *waE2E.LiveLocationMessage) (*bridgev2.ConvertedMessagePart, *waE2E.ContextInfo) { + if msg.DegreesLatitude == nil || msg.DegreesLongitude == nil { + content := &event.MessageEventContent{ + Body: "Started sharing live location", + MsgType: event.MsgNotice, + } + if len(msg.GetCaption()) > 0 { + content.Body += ": " + msg.GetCaption() + } + content.Body += "\n\nUse the WhatsApp app to see the location." + return &bridgev2.ConvertedMessagePart{ + Type: event.EventMessage, + Content: content, + }, msg.GetContextInfo() + } + + lat, long := msg.GetDegreesLatitude(), msg.GetDegreesLongitude() + url := fmt.Sprintf("https://maps.google.com/?q=%.5f,%.5f", lat, long) + name := formatCoordinates(lat, long) + const note = "Live updates are only visible in the WhatsApp app." + body := fmt.Sprintf("Live location: %s\n%s", name, url) + formattedBody := fmt.Sprintf(`Live location: %s`, html.EscapeString(url), html.EscapeString(name)) + if caption := msg.GetCaption(); len(caption) > 0 { + body += "\n" + caption + formattedBody += "
" + html.EscapeString(caption) + } content := &event.MessageEventContent{ - Body: "Started sharing live location", - MsgType: event.MsgNotice, + MsgType: event.MsgLocation, + Body: body + "\n\n" + note, + Format: event.FormatHTML, + FormattedBody: formattedBody + "

" + note, + GeoURI: fmt.Sprintf("geo:%.5f,%.5f", lat, long), } - if len(msg.GetCaption()) > 0 { - content.Body += ": " + msg.GetCaption() - } - content.Body += "\n\nUse the WhatsApp app to see the location." + addLocationThumbnail(ctx, content, msg.GetJPEGThumbnail()) + return &bridgev2.ConvertedMessagePart{ Type: event.EventMessage, Content: content, From 88f5fc738ca4c0abc7ec3792131233a72f56f2a2 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Wed, 28 Oct 2026 20:33:06 +0000 Subject: [PATCH 14/42] lidmigrate: remove phone number ghosts that rejoined LID DMs (#990) --- pkg/connector/connector.go | 4 +++ pkg/connector/lidmigrate.go | 72 +++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/pkg/connector/connector.go b/pkg/connector/connector.go index 94c66eb..19caace 100644 --- a/pkg/connector/connector.go +++ b/pkg/connector/connector.go @@ -173,6 +173,10 @@ func (wa *WhatsAppConnector) Start(ctx context.Context) error { if err != nil { wa.Bridge.Log.Err(err).Msg("Failed to sync mismatching ghosts") } + err = wa.removeRejoinedPNGhosts(wa.Bridge.BackgroundCtx) + if err != nil { + wa.Bridge.Log.Err(err).Msg("Failed to remove rejoined PN ghosts") + } }() return nil } diff --git a/pkg/connector/lidmigrate.go b/pkg/connector/lidmigrate.go index befef07..17b2428 100644 --- a/pkg/connector/lidmigrate.go +++ b/pkg/connector/lidmigrate.go @@ -18,6 +18,7 @@ package connector import ( "context" + "errors" "fmt" "time" @@ -25,9 +26,11 @@ import ( "go.mau.fi/util/dbutil" "go.mau.fi/whatsmeow/types" + "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/event" + "maunium.net/go/mautrix/id" "go.mau.fi/mautrix-whatsapp/pkg/waid" ) @@ -295,3 +298,72 @@ func (wa *WhatsAppConnector) syncMismatchingGhosts(ctx context.Context) error { wa.Bridge.DB.KV.Set(ctx, "whatsapp_lid_avatars_resynced", "true") return nil } + +func (wa *WhatsAppConnector) removeRejoinedPNGhosts(ctx context.Context) error { + if wa.Bridge.Background || wa.Bridge.DB.KV.Get(ctx, "whatsapp_lid_dm_pn_ghosts_removed") == "true" { + return nil + } + log := zerolog.Ctx(ctx).With().Str("action", "remove rejoined pn ghosts").Logger() + const findLIDPortals = "SELECT id, mxid FROM portal WHERE bridge_id=$1 AND room_type='dm' AND id LIKE '%@lid' AND mxid IS NOT NULL" + lidPortals, err := scanLIDPortal.NewRowIter(wa.Bridge.DB.Query(ctx, findLIDPortals, wa.Bridge.ID)).AsList() + if err != nil { + return fmt.Errorf("failed to get LID portals: %w", err) + } + var removed, failed int + for _, portal := range lidPortals { + lid, err := waid.ParsePortalID(portal.ID) + if err != nil || lid.Server != types.HiddenUserServer { + continue + } + pn, err := wa.DeviceStore.LIDMap.GetPNForLID(ctx, lid) + if err != nil { + return fmt.Errorf("failed to get PN for LID portal %s: %w", portal.ID, err) + } else if pn.IsEmpty() { + continue + } + pnUserID := waid.MakeUserID(pn) + member, err := wa.Bridge.Matrix.GetMemberInfo(ctx, portal.MXID, wa.Bridge.Matrix.FormatGhostMXID(pnUserID)) + if err != nil { + log.Warn().Err(err).Stringer("room_id", portal.MXID).Msg("Failed to get PN ghost membership") + failed++ + continue + } else if member == nil || member.Membership != event.MembershipJoin { + continue + } + pnGhost, err := wa.Bridge.GetGhostByID(ctx, pnUserID) + if err != nil { + return fmt.Errorf("failed to get PN ghost for %s: %w", pn, err) + } + _, err = pnGhost.Intent.SendState(ctx, portal.MXID, event.StateMember, pnGhost.Intent.GetMXID().String(), &event.Content{ + Parsed: &event.MemberEventContent{Membership: event.MembershipLeave, Reason: "Migrating to LIDs"}, + Raw: map[string]any{"com.beeper.exclude_from_timeline": true}, + }, time.Time{}) + if err != nil { + log.Err(err).Stringer("room_id", portal.MXID).Stringer("pn", pn).Msg("Failed to remove PN ghost from LID DM") + if !errors.Is(err, mautrix.MForbidden) && !errors.Is(err, mautrix.MNotFound) { + failed++ + } + continue + } + removed++ + } + log.Info(). + Int("removed_ghosts", removed). + Int("failed", failed). + Int("total_lid_portals", len(lidPortals)). + Msg("Finished removing rejoined PN ghosts from LID DMs") + if failed == 0 && ctx.Err() == nil { + wa.Bridge.DB.KV.Set(ctx, "whatsapp_lid_dm_pn_ghosts_removed", "true") + } + return nil +} + +type lidPortal struct { + ID networkid.PortalID + MXID id.RoomID +} + +var scanLIDPortal = dbutil.ConvertRowFn[lidPortal](func(row dbutil.Scannable) (portal lidPortal, err error) { + err = row.Scan(&portal.ID, &portal.MXID) + return +}) From 7a0b4b580875e25169b7afac36d334388424bd4d Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Thu, 29 Oct 2026 10:32:04 +0000 Subject: [PATCH 15/42] login: support client WebSocket tunnels (#1004) --- go.mod | 2 +- go.sum | 4 ++-- pkg/connector/login.go | 36 ++++++++++++++++++++++-------------- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/go.mod b/go.mod index fc19065..b059b8b 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( golang.org/x/sync v0.24.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - maunium.net/go/mautrix v0.32.1-0.20261026145030-920bc073ba8d + maunium.net/go/mautrix v0.32.1-0.20261028161347-0907c3c7611e ) require ( diff --git a/go.sum b/go.sum index 2775f5f..498f286 100644 --- a/go.sum +++ b/go.sum @@ -103,5 +103,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M= maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA= -maunium.net/go/mautrix v0.32.1-0.20261026145030-920bc073ba8d h1:DsMn0i7cBKcQZ0AVxJm9hfWAu6xJdjRrf457EtXxyNY= -maunium.net/go/mautrix v0.32.1-0.20261026145030-920bc073ba8d/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= +maunium.net/go/mautrix v0.32.1-0.20261028161347-0907c3c7611e h1:7F0CBiL2wsWCfZ1gZlAc30fVeLKNMzuIQb9PZ2mPwts= +maunium.net/go/mautrix v0.32.1-0.20261028161347-0907c3c7611e/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= diff --git a/pkg/connector/login.go b/pkg/connector/login.go index 387d780..c5d4c0a 100644 --- a/pkg/connector/login.go +++ b/pkg/connector/login.go @@ -137,6 +137,7 @@ var ( _ bridgev2.LoginProcessDisplayAndWait = (*WALogin)(nil) _ bridgev2.LoginProcessUserInput = (*WALogin)(nil) _ bridgev2.LoginProcessWithOverride = (*WALogin)(nil) + _ bridgev2.LoginProcessWithParams = (*WALogin)(nil) _ bridgev2.LoginProcessWebAuthn = (*WALogin)(nil) ) @@ -144,6 +145,14 @@ const LoginConnectWait = 30 * time.Second const LoginPairPhoneWait = 30 * time.Second func (wl *WALogin) Start(ctx context.Context) (*bridgev2.LoginStep, error) { + return wl.StartWithParams(ctx, bridgev2.LoginStartParams{}) +} + +func (wl *WALogin) StartWithOverride(ctx context.Context, old *bridgev2.UserLogin) (*bridgev2.LoginStep, error) { + return wl.StartWithParams(ctx, bridgev2.LoginStartParams{Override: old}) +} + +func (wl *WALogin) StartWithParams(ctx context.Context, params bridgev2.LoginStartParams) (*bridgev2.LoginStep, error) { wl.Main.firstClientConnectOnce.Do(wl.Main.onFirstClientConnect) device := wl.Main.DeviceStore.NewDevice() wl.Client = whatsmeow.NewClient(device, waLog.Zerolog(wl.Log)) @@ -153,8 +162,20 @@ func (wl *WALogin) Start(ctx context.Context) (*bridgev2.LoginStep, error) { if err := wl.Main.updateProxy(ctx, wl.Client, true); err != nil { return nil, err } + if params.WebSocketHTTP != nil { + wl.Client.SetPreLoginHTTPClient(&http.Client{Transport: params.WebSocketHTTP}) + } if wl.PhoneCode { + if params.Override != nil { + phoneNumber := fmt.Sprintf("+%s", params.Override.ID) + wl.Log.Debug(). + Str("phone_number", phoneNumber). + Msg("Auto-submitting phone number for relogin") + return wl.SubmitUserInput(ctx, map[string]string{ + "phone_number": phoneNumber, + }) + } return &bridgev2.LoginStep{ Type: bridgev2.LoginStepTypeUserInput, StepID: LoginStepIDPhoneNumber, @@ -184,20 +205,6 @@ func (wl *WALogin) Start(ctx context.Context) (*bridgev2.LoginStep, error) { return makeQRStep(wl.QRs[0]), nil } -func (wl *WALogin) StartWithOverride(ctx context.Context, old *bridgev2.UserLogin) (*bridgev2.LoginStep, error) { - step, err := wl.Start(ctx) - if err == nil && step != nil && old != nil && step.StepID == LoginStepIDPhoneNumber { - phoneNumber := fmt.Sprintf("+%s", old.ID) - wl.Log.Debug(). - Str("phone_number", phoneNumber). - Msg("Auto-submitting phone number for relogin") - return wl.SubmitUserInput(ctx, map[string]string{ - "phone_number": phoneNumber, - }) - } - return step, err -} - func (wl *WALogin) SubmitUserInput(ctx context.Context, input map[string]string) (*bridgev2.LoginStep, error) { err := wl.Client.Connect() if err != nil { @@ -316,6 +323,7 @@ func (wl *WALogin) handleEvent(rawEvt any) { wl.LoginError = ErrUnexpectedDisconnect case *events.ManualLoginReconnect: wl.Received515.Set() + return default: wl.Log.Warn().Type("event_type", evt).Msg("Got unexpected event") return From ab1fae7181a25d12bacf40fdb5f77dcbdef002e2 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Thu, 29 Oct 2026 12:57:18 +0000 Subject: [PATCH 16/42] handlematrix: reject empty group names (#1007) --- pkg/connector/handlematrix.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pkg/connector/handlematrix.go b/pkg/connector/handlematrix.go index fec40c3..a37d66f 100644 --- a/pkg/connector/handlematrix.go +++ b/pkg/connector/handlematrix.go @@ -107,6 +107,7 @@ func (wa *WhatsAppClient) HandleMatrixMessage(ctx context.Context, msg *bridgev2 var ErrBroadcastSendDisabled = bridgev2.WrapErrorInStatus(errors.New("sending status messages is disabled")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusUnsupported).WithStatus(event.MessageStatusFail) var ErrBroadcastReactionUnsupported = bridgev2.WrapErrorInStatus(errors.New("reacting to status messages is not currently supported")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusUnsupported).WithStatus(event.MessageStatusFail) var ErrNotCommunityAdmin = bridgev2.WrapErrorInStatus(errors.New("only community admins can send announcements")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusNoPermission).WithStatus(event.MessageStatusFail) +var ErrEmptyGroupName = bridgev2.WrapErrorInStatus(errors.New("WhatsApp group names can't be empty")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusUnsupported).WithStatus(event.MessageStatusFail) func (wa *WhatsAppClient) handleConvertedMatrixMessage(ctx context.Context, msg *bridgev2.MatrixMessage, waMsg *waE2E.Message, req *whatsmeow.SendRequestExtra) (*bridgev2.MatrixMessageResponse, error) { if req == nil { @@ -501,6 +502,8 @@ func (wa *WhatsAppClient) HandleMatrixRoomName(ctx context.Context, msg *bridgev if msg.Portal.RoomType == database.RoomTypeDM { return false, fmt.Errorf("cannot set room name for DM") + } else if msg.Content.Name == "" { + return false, ErrEmptyGroupName } defer wa.mcTrack(msg, time.Now(), &retErr) From 33357ced5ae666d9b8e85a56327f28bfb97a293c Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Thu, 29 Oct 2026 13:15:13 +0000 Subject: [PATCH 17/42] directmedia,handlematrix: report WhatsApp send rejections as permanent failures (#1006) Co-authored-by: Claude Opus 5.5 --- pkg/connector/directmedia.go | 14 +++++++++- pkg/connector/errors.go | 49 +++++++++++++++++++++++++++++++++++ pkg/connector/handlematrix.go | 13 ++++++---- 3 files changed, 70 insertions(+), 6 deletions(-) diff --git a/pkg/connector/directmedia.go b/pkg/connector/directmedia.go index b86f7dc..03ef398 100644 --- a/pkg/connector/directmedia.go +++ b/pkg/connector/directmedia.go @@ -164,7 +164,19 @@ func (wa *WhatsAppConnector) downloadStickerDirectMedia(ctx context.Context, par return nil, fmt.Errorf("no WhatsApp client found on login %s", parsedID.UserLogin) } sticker, err := wa.MsgConv.GetCachedSticker(ctx, waClient.Client, parsedID.Sticker.PackID, parsedID.Sticker.FileHash) - if err != nil { + var httpErr whatsmeow.DownloadHTTPError + if errors.As(err, &httpErr) { + switch httpErr.StatusCode { + case http.StatusNotFound, http.StatusGone: + return nil, mautrix.MNotFound.WithMessage("Sticker pack not found") + case http.StatusUnauthorized, http.StatusForbidden: + return nil, mautrix.MForbidden.WithMessage("WhatsApp denied access to the sticker pack") + case http.StatusTooManyRequests: + return nil, mautrix.MLimitExceeded.WithMessage("Rate limited by WhatsApp while fetching the sticker pack").WithCanRetry(true) + default: + return nil, mautrix.MUnknown.WithMessage("WhatsApp returned HTTP %d while fetching the sticker pack", httpErr.StatusCode).WithStatus(http.StatusBadGateway).WithCanRetry(true) + } + } else if err != nil { return nil, err } else if sticker == nil { return nil, mautrix.MNotFound.WithMessage("Sticker not found in pack") diff --git a/pkg/connector/errors.go b/pkg/connector/errors.go index 1ee1b20..38433d6 100644 --- a/pkg/connector/errors.go +++ b/pkg/connector/errors.go @@ -21,11 +21,16 @@ import ( "errors" "fmt" "net/http" + "strconv" + "strings" + "time" "go.mau.fi/whatsmeow" "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/event" + + "go.mau.fi/mautrix-whatsapp/pkg/waid" ) // wrapConversionError turns a failure to convert a Matrix event into a message status. Nothing has been @@ -85,6 +90,50 @@ func wrapWhatsAppError(err error) error { } } +// wrapSendError turns an error from sending a message to WhatsApp into a message status. +func (wa *WhatsAppClient) wrapSendError(err error) error { + switch sendErrorCode(err) { + case 403: + return bridgev2.WrapErrorInStatus(err). + WithMessage("you don't have permission to do that on WhatsApp"). + WithErrorReason(event.MessageStatusNoPermission). + WithStatus(event.MessageStatusFail). + WithIsCertain(true). + WithSendNotice(true) + case 463: + msg := "WhatsApp has temporarily restricted your account from messaging new contacts" + if until := wa.UserLogin.Metadata.(*waid.UserLoginMetadata).ReachoutTimelockUntil; until.After(time.Now()) { + msg = fmt.Sprintf("WhatsApp has restricted your account from messaging new contacts until %s", until.UTC().Format("Jan 2, 2006 at 3:04 PM MST")) + } + return bridgev2.WrapErrorInStatus(err). + WithMessage(msg). + WithErrorReason(event.MessageStatusNoPermission). + WithStatus(event.MessageStatusFail). + WithIsCertain(true). + WithSendNotice(true) + case 421, 479: + return bridgev2.WrapErrorInStatus(err). + WithMessage("WhatsApp rejected the message"). + WithErrorReason(event.MessageStatusNetworkError). + WithStatus(event.MessageStatusFail). + WithIsCertain(true). + WithSendNotice(true) + default: + return wrapWhatsAppError(err) + } +} + +// sendErrorCode returns the code WhatsApp rejected a message with, which whatsmeow only includes in the +// error text. +func sendErrorCode(err error) int { + if !errors.Is(err, whatsmeow.ErrServerReturnedError) { + return 0 + } + _, codeStr, _ := strings.Cut(err.Error(), whatsmeow.ErrServerReturnedError.Error()+" ") + code, _ := strconv.Atoi(codeStr) + return code +} + // wrapWhatsAppRespError turns an error from a whatsmeow request made during login or provisioning into // an HTTP error, keeping the original error in the chain. Clients retry 429 and 502-504 automatically, // which isn't wanted for provisioning requests, so those statuses aren't used. diff --git a/pkg/connector/handlematrix.go b/pkg/connector/handlematrix.go index a37d66f..d51efcd 100644 --- a/pkg/connector/handlematrix.go +++ b/pkg/connector/handlematrix.go @@ -108,6 +108,7 @@ var ErrBroadcastSendDisabled = bridgev2.WrapErrorInStatus(errors.New("sending st var ErrBroadcastReactionUnsupported = bridgev2.WrapErrorInStatus(errors.New("reacting to status messages is not currently supported")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusUnsupported).WithStatus(event.MessageStatusFail) var ErrNotCommunityAdmin = bridgev2.WrapErrorInStatus(errors.New("only community admins can send announcements")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusNoPermission).WithStatus(event.MessageStatusFail) var ErrEmptyGroupName = bridgev2.WrapErrorInStatus(errors.New("WhatsApp group names can't be empty")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusUnsupported).WithStatus(event.MessageStatusFail) +var ErrAddBlockedByPrivacy = bridgev2.WrapErrorInStatus(errors.New("this user's privacy settings don't allow adding them to groups")).WithErrorAsMessage().WithIsCertain(true).WithSendNotice(true).WithErrorReason(event.MessageStatusNoPermission).WithStatus(event.MessageStatusFail) func (wa *WhatsAppClient) handleConvertedMatrixMessage(ctx context.Context, msg *bridgev2.MatrixMessage, waMsg *waE2E.Message, req *whatsmeow.SendRequestExtra) (*bridgev2.MatrixMessageResponse, error) { if req == nil { @@ -140,7 +141,7 @@ func (wa *WhatsAppClient) handleConvertedMatrixMessage(ctx context.Context, msg if errors.Is(err, whatsmeow.ErrNoPermissionInGroup) { return nil, ErrNotCommunityAdmin } - return nil, wrapWhatsAppError(err) + return nil, wa.wrapSendError(err) } var pickedMessageID networkid.MessageID if resp.Sender == wa.GetLID() { @@ -219,7 +220,7 @@ func (wa *WhatsAppClient) HandleMatrixReaction(ctx context.Context, msg *bridgev Metadata: &waid.ReactionMetadata{ SenderDeviceID: wa.JID.Device, }, - }, wrapWhatsAppError(err) + }, wa.wrapSendError(err) } func (wa *WhatsAppClient) HandleMatrixReactionRemove(ctx context.Context, msg *bridgev2.MatrixReactionRemove) (retErr error) { @@ -249,7 +250,7 @@ func (wa *WhatsAppClient) HandleMatrixReactionRemove(ctx context.Context, msg *b defer wa.mcTrack(msg, time.Now(), &retErr) resp, err := wa.Client.SendMessage(ctx, portalJID, reactionMsg, extra) zerolog.Ctx(ctx).Trace().Any("response", resp).Msg("WhatsApp reaction response") - return wrapWhatsAppError(err) + return wa.wrapSendError(err) } func (wa *WhatsAppClient) HandleMatrixEdit(ctx context.Context, edit *bridgev2.MatrixEdit) (retErr error) { @@ -289,7 +290,7 @@ func (wa *WhatsAppClient) HandleMatrixEdit(ctx context.Context, edit *bridgev2.M ID: editID, }) log.Trace().Any("response", resp).Msg("WhatsApp edit response") - return wrapWhatsAppError(err) + return wa.wrapSendError(err) } func (wa *WhatsAppClient) HandleMatrixMessageRemove(ctx context.Context, msg *bridgev2.MatrixMessageRemove) (retErr error) { @@ -314,7 +315,7 @@ func (wa *WhatsAppClient) HandleMatrixMessageRemove(ctx context.Context, msg *br resp, err := wa.Client.SendMessage(ctx, portalJID, revokeMessage, extra) log.Trace().Any("response", resp).Msg("WhatsApp delete response") - return wrapWhatsAppError(err) + return wa.wrapSendError(err) } func (wa *WhatsAppClient) HandleMatrixReadReceipt(ctx context.Context, receipt *bridgev2.MatrixReadReceipt) (retErr error) { @@ -484,6 +485,8 @@ func (wa *WhatsAppClient) HandleMatrixMembership(ctx context.Context, msg *bridg return nil, wrapWhatsAppError(err) } else if len(resp) == 0 { return nil, fmt.Errorf("no response for participant change") + } else if resp[0].Error == 403 && action == whatsmeow.ParticipantChangeAdd { + return nil, ErrAddBlockedByPrivacy } else if resp[0].Error != 0 { return nil, fmt.Errorf("failed to change participant: code %d", resp[0].Error) } From 123ac4f340b248e1b440ae6715a680b519bcc3de Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Thu, 29 Oct 2026 15:35:40 +0000 Subject: [PATCH 18/42] userinfo: don't clear alt ghost avatar when main ghost has no avatar info (#1008) --- pkg/connector/userinfo.go | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/pkg/connector/userinfo.go b/pkg/connector/userinfo.go index c78b0a8..b109e82 100644 --- a/pkg/connector/userinfo.go +++ b/pkg/connector/userinfo.go @@ -30,7 +30,7 @@ var ResyncJitterSeconds = 3600 func (wa *WhatsAppClient) EnqueueGhostResync(ghost *bridgev2.Ghost) { lastSync := ghost.Metadata.(*waid.GhostMetadata).LastSync.Time - if lastSync.Add(ResyncMinInterval).After(time.Now()) { + if ghost.AvatarID != "" && lastSync.Add(ResyncMinInterval).After(time.Now()) { return } wa.resyncQueueLock.Lock() @@ -118,12 +118,14 @@ func (wa *WhatsAppClient) doGhostResync(ctx context.Context, queue map[types.JID var portals []*bridgev2.Portal for jid, item := range queue { var lastSync time.Time + unknownAvatar := false if item.ghost != nil { lastSync = item.ghost.Metadata.(*waid.GhostMetadata).LastSync.Time + unknownAvatar = item.ghost.AvatarID == "" } else if item.portal != nil { lastSync = item.portal.Metadata.(*waid.PortalMetadata).LastSync.Time } - if lastSync.Add(ResyncMinInterval).After(time.Now()) { + if !unknownAvatar && lastSync.Add(ResyncMinInterval).After(time.Now()) { log.Debug(). Stringer("jid", jid). Time("last_sync", lastSync). @@ -165,7 +167,7 @@ func (wa *WhatsAppClient) doGhostResync(ctx context.Context, queue map[types.JID log.Warn().Stringer("jid", jid).Msg("Didn't get info for puppet in background sync") continue } - userInfo, err := wa.getUserInfo(ctx, jid, info.PictureID, info.PictureID != "" && string(ghost.AvatarID) != info.PictureID) + userInfo, err := wa.getUserInfo(ctx, jid, info.PictureID, ghost.AvatarID == "" || (info.PictureID != "" && string(ghost.AvatarID) != info.PictureID)) if err != nil { log.Err(err).Stringer("jid", jid).Msg("Failed to get user info for puppet in background sync") continue @@ -472,16 +474,19 @@ func (wa *WhatsAppClient) syncAltGhostWithInfo(ctx context.Context, jid types.JI } func makeInfoFromGhost(ghost *bridgev2.Ghost) *bridgev2.UserInfo { - return &bridgev2.UserInfo{ - Identifiers: ghost.Identifiers, - Name: &ghost.Name, - Avatar: &bridgev2.Avatar{ - ID: ghost.AvatarID, - Remove: ghost.AvatarID == "" || ghost.AvatarMXC == "", - MXC: ghost.AvatarMXC, - Hash: ghost.AvatarHash, - }, + info := &bridgev2.UserInfo{ + Identifiers: ghost.Identifiers, + Name: &ghost.Name, IsBot: &ghost.IsBot, ExtraProfile: ghost.ExtraProfile, } + if ghost.AvatarID != "" { + info.Avatar = &bridgev2.Avatar{ + ID: ghost.AvatarID, + Remove: ghost.AvatarMXC == "", + MXC: ghost.AvatarMXC, + Hash: ghost.AvatarHash, + } + } + return info } From e8f1d2b3f65d666ccbbd08d515c261f4c2f2e8ed Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Thu, 29 Oct 2026 22:27:40 +0000 Subject: [PATCH 19/42] msgconv/from-whatsapp: use own profile name for self mentions (#1009) --- pkg/msgconv/from-whatsapp.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pkg/msgconv/from-whatsapp.go b/pkg/msgconv/from-whatsapp.go index 1ff2e02..db18f35 100644 --- a/pkg/msgconv/from-whatsapp.go +++ b/pkg/msgconv/from-whatsapp.go @@ -17,6 +17,7 @@ package msgconv import ( + "cmp" "context" "fmt" "html" @@ -92,7 +93,7 @@ func (mc *MessageConverter) getBasicUserInfo(ctx context.Context, user types.JID portal := getPortal(ctx) login := mc.Bridge.GetCachedUserLoginByID(waid.MakeUserLoginID(pnJID)) if login != nil && (portal.Receiver == "" || portal.Receiver == login.ID) { - return login.UserMXID, ghost.Name, nil + return login.UserMXID, cmp.Or(login.RemoteProfile.Name, ghost.Name), nil } } return ghost.Intent.GetMXID(), ghost.Name, nil From 1f30d5516cd01424b3348c1f4792c60f7fc12931 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Fri, 30 Oct 2026 15:52:27 +0200 Subject: [PATCH 20/42] backfill: drop messages in the whatsapp official updates chat --- pkg/connector/backfill.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index 54edbaa..378b58e 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -246,6 +246,11 @@ func (wa *WhatsAppClient) handleWAHistorySync( } else if jid.Server == types.BroadcastServer { log.Debug().Stringer("chat_jid", jid).Msg("Skipping broadcast list in history sync") continue + } else if jid == types.PSAJID { + // New messages in the official updates chat aren't bridged because they use a different path, + // so drop history as well. This should be removed if the PSA chat gets properly bridged in the future. + log.Debug().Stringer("chat_jid", jid).Msg("Skipping PSA in history sync") + continue } else { totalMessageCount += len(conv.GetMessages()) } From 678d4ebb4fa2ae9796789f7276c6fce0f79982b8 Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Fri, 30 Oct 2026 16:09:59 +0200 Subject: [PATCH 21/42] wadb: re-arm backfill for chats with leftover history sync --- pkg/connector/wadb/upgrades/00-latest-schema.sql | 2 +- .../11-rearm-leftover-history-sync-backfill.sql | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 pkg/connector/wadb/upgrades/11-rearm-leftover-history-sync-backfill.sql diff --git a/pkg/connector/wadb/upgrades/00-latest-schema.sql b/pkg/connector/wadb/upgrades/00-latest-schema.sql index 0f1fef9..c4172d0 100644 --- a/pkg/connector/wadb/upgrades/00-latest-schema.sql +++ b/pkg/connector/wadb/upgrades/00-latest-schema.sql @@ -1,4 +1,4 @@ --- v0 -> v10 (compatible with v3+): Latest revision +-- v0 -> v11 (compatible with v3+): Latest revision CREATE TABLE whatsapp_poll_option_id ( bridge_id TEXT NOT NULL, diff --git a/pkg/connector/wadb/upgrades/11-rearm-leftover-history-sync-backfill.sql b/pkg/connector/wadb/upgrades/11-rearm-leftover-history-sync-backfill.sql new file mode 100644 index 0000000..69e8b1e --- /dev/null +++ b/pkg/connector/wadb/upgrades/11-rearm-leftover-history-sync-backfill.sql @@ -0,0 +1,10 @@ +-- v11 (compatible with v3+): Re-arm backfill for chats with leftover history sync messages +UPDATE backfill_task +SET is_done=false, queue_done=false, dispatched_at=NULL, completed_at=NULL +WHERE (is_done OR queue_done) AND EXISTS ( + SELECT 1 + FROM whatsapp_history_sync_message msg + WHERE msg.bridge_id=backfill_task.bridge_id + AND msg.user_login_id=backfill_task.user_login_id + AND msg.chat_jid=backfill_task.portal_id +); From ae8dcdec4bc4bf775e8b7185cc414c49ed8b48b2 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Fri, 30 Oct 2026 16:09:08 +0200 Subject: [PATCH 22/42] backfill: delete all messages when FetchMessages returns no more history --- pkg/connector/backfill.go | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index 378b58e..7a6fd78 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -593,10 +593,11 @@ func (wa *WhatsAppClient) FetchMessages(ctx context.Context, params bridgev2.Fet } } } - resp, err := wa.convertHistorySyncMessages(ctx, params.Portal, portalJID, messages, true) + resp, err := wa.convertHistorySyncMessages(ctx, params.Portal, portalJID, messages, true, !params.Forward && !hasMore) if err != nil { return nil, fmt.Errorf("failed to convert messages: %w", err) } + // TODO might be better to always set true here and let GetBetween return an empty result to mark as false? resp.HasMore = hasMore resp.Forward = params.Forward resp.MarkRead = markRead @@ -654,6 +655,7 @@ func (wa *WhatsAppClient) convertHistorySyncMessages( portalJID types.JID, messages []*waWeb.WebMessageInfo, explodeOnError bool, + deleteEverything bool, ) (*bridgev2.FetchMessagesResponse, error) { cli := wa.Client if cli == nil { @@ -709,9 +711,11 @@ func (wa *WhatsAppClient) convertHistorySyncMessages( Messages: convertedMessages, Cursor: networkid.PaginationCursor(strconv.FormatUint(oldestTS, 10)), CompleteCallback: func() { - // TODO this only deletes after backfilling. If there's no need for backfill after a relogin, - // the messages will be stuck in the database - wa.deleteHistorySyncMessages(ctx, portalJID, newestTS, oldestTS) + if deleteEverything { + wa.deleteHistorySyncMessages(ctx, portalJID, 1<<62, oldestTS) + } else { + wa.deleteHistorySyncMessages(ctx, portalJID, newestTS, oldestTS) + } if len(mediaRequests) > 0 { go func(ctx context.Context) { for _, req := range mediaRequests { @@ -872,7 +876,7 @@ func (wa *WhatsAppClient) handleOnDemandHistorySync(ctx context.Context, blob *w Int("message_count", len(messages)). Stringer("end_of_history_type", conv.GetEndOfHistoryTransferType()). Msg("Converting messages to bridge from on-demand history sync") - resp, err := wa.convertHistorySyncMessages(ctx, portal, portalJID, messages, false) + resp, err := wa.convertHistorySyncMessages(ctx, portal, portalJID, messages, false, false) if err != nil { return nil, err } From de02399ff8ec8d84d57955565979ccca07ba8b0a Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Fri, 30 Oct 2026 14:43:44 +0000 Subject: [PATCH 23/42] msgconv/from-whatsapp: show view once notice for media with view once flag (#1012) --- pkg/msgconv/wa-media.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pkg/msgconv/wa-media.go b/pkg/msgconv/wa-media.go index 30c6b30..839f4c2 100644 --- a/pkg/msgconv/wa-media.go +++ b/pkg/msgconv/wa-media.go @@ -49,6 +49,9 @@ func (mc *MessageConverter) convertMediaMessage( isViewOnce bool, cachedPart *bridgev2.ConvertedMessagePart, ) (part *bridgev2.ConvertedMessagePart, contextInfo *waE2E.ContextInfo) { + if viewOnceMsg, ok := msg.(MediaMessageWithViewOnce); ok && viewOnceMsg.GetViewOnce() { + isViewOnce = true + } if mc.DisableViewOnce && isViewOnce { body := "You received a view once message. For added privacy, you can only open it on the WhatsApp app." if messageInfo.IsFromMe { @@ -232,6 +235,11 @@ type MediaMessageWithCaption interface { GetCaption() string } +type MediaMessageWithViewOnce interface { + MediaMessage + GetViewOnce() bool +} + type MediaMessageWithDimensions interface { MediaMessage GetHeight() uint32 From 5dd621fdf4232cd9ba837d0bcebac72fcb369884 Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Fri, 30 Oct 2026 16:29:54 +0000 Subject: [PATCH 24/42] login: fix ADV secret rotation ending QR and pairing code logins (#1010) --- pkg/connector/login.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/pkg/connector/login.go b/pkg/connector/login.go index c5d4c0a..ae57ac1 100644 --- a/pkg/connector/login.go +++ b/pkg/connector/login.go @@ -288,6 +288,7 @@ func (wl *WALogin) handleEvent(rawEvt any) { wl.QRs[i] = strings.Replace(code, evt.OldSecret, evt.NewSecret, 1) } wl.ADVRotate.Set() + return case *events.QRScannedWithoutMultidevice: wl.Log.Error().Msg("QR code scanned without multidevice enabled") wl.LoginError = ErrLoginMultideviceNotEnabled @@ -372,9 +373,14 @@ func (wl *WALogin) Wait(ctx context.Context) (*bridgev2.LoginStep, error) { case <-wl.PasskeyRequest.GetChan(): return wl.makePasskeyStep() case <-wl.ADVRotate.GetChan(): - wl.Log.Debug().Msg("ADV secret was rotated, returning new QR immediately") wl.ADVRotate.Clear() - return makeQRStep(wl.QRs[nextIndex]), nil + if currentIndex < 0 || currentIndex >= len(wl.QRs) { + wl.Log.Debug().Msg("ADV secret was rotated, but no QRs are left to return") + wl.Cancel() + return nil, ErrLoginTimeout + } + wl.Log.Debug().Msg("ADV secret was rotated, returning current QR immediately") + return makeQRStep(wl.QRs[currentIndex]), nil case <-wl.LoginComplete.GetChan(): // continue } From 9f8224606920ae9d3aa5bbfc067e1cfe5d8b7475 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Sun, 1 Nov 2026 00:50:14 +0200 Subject: [PATCH 25/42] handlewhatsapp: exclude stream replaced and client outdated from unknown error autoreconnect Closes #1005 --- go.mod | 2 +- go.sum | 4 ++-- pkg/connector/handlewhatsapp.go | 12 ++++++++++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index b059b8b..6e9b503 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( golang.org/x/sync v0.24.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - maunium.net/go/mautrix v0.32.1-0.20261028161347-0907c3c7611e + maunium.net/go/mautrix v0.32.1-0.20261031224934-b69deb427bd7 ) require ( diff --git a/go.sum b/go.sum index 498f286..12cf8f5 100644 --- a/go.sum +++ b/go.sum @@ -103,5 +103,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M= maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA= -maunium.net/go/mautrix v0.32.1-0.20261028161347-0907c3c7611e h1:7F0CBiL2wsWCfZ1gZlAc30fVeLKNMzuIQb9PZ2mPwts= -maunium.net/go/mautrix v0.32.1-0.20261028161347-0907c3c7611e/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= +maunium.net/go/mautrix v0.32.1-0.20261031224934-b69deb427bd7 h1:GpLIqeJTpG0/ti7XA370HgjnSWd/pQxXVGb/FRkayOA= +maunium.net/go/mautrix v0.32.1-0.20261031224934-b69deb427bd7/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= diff --git a/pkg/connector/handlewhatsapp.go b/pkg/connector/handlewhatsapp.go index 4ba4f10..a7d4c91 100644 --- a/pkg/connector/handlewhatsapp.go +++ b/pkg/connector/handlewhatsapp.go @@ -237,7 +237,11 @@ func (wa *WhatsAppClient) handleWAEvent(rawEvt any) (success bool) { }) wa.notifyOfflineSyncWaiter(fmt.Errorf("stream error: %s", message)) case *events.StreamReplaced: - wa.UserLogin.BridgeState.Send(status.BridgeState{StateEvent: status.StateUnknownError, Error: WAStreamReplaced}) + wa.UserLogin.BridgeState.Send(status.BridgeState{ + StateEvent: status.StateUnknownError, + Error: WAStreamReplaced, + BlockAutoReconnect: true, + }) wa.notifyOfflineSyncWaiter(fmt.Errorf("stream replaced")) case *events.KeepAliveTimeout: wa.UserLogin.BridgeState.Send(status.BridgeState{StateEvent: status.StateTransientDisconnect, Error: WAKeepaliveTimeout}) @@ -253,7 +257,11 @@ func (wa *WhatsAppClient) handleWAEvent(rawEvt any) (success bool) { wa.notifyOfflineSyncWaiter(fmt.Errorf("connection failure: %s (%s)", evt.Reason, evt.Message)) case *events.ClientOutdated: wa.UserLogin.Log.Error().Msg("Got a client outdated connect failure. The bridge is likely out of date, please update immediately.") - wa.UserLogin.BridgeState.Send(status.BridgeState{StateEvent: status.StateUnknownError, Error: WAClientOutdated}) + wa.UserLogin.BridgeState.Send(status.BridgeState{ + StateEvent: status.StateUnknownError, + Error: WAClientOutdated, + BlockAutoReconnect: true, + }) wa.notifyOfflineSyncWaiter(fmt.Errorf("client outdated")) case *events.TemporaryBan: wa.UserLogin.BridgeState.Send(status.BridgeState{ From 3a5d6448a8b4d7af1021381891f61c664084099c Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Sun, 1 Nov 2026 12:58:51 +0000 Subject: [PATCH 26/42] backfill: treat own messages from previous LIDs as own (#1017) --- pkg/connector/backfill.go | 3 +++ pkg/connector/client.go | 25 ++++++++++++++++++++++++- pkg/waid/dbmeta.go | 2 ++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index 7a6fd78..fe251e1 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -692,6 +692,9 @@ func (wa *WhatsAppClient) convertHistorySyncMessages( if !wa.ensureAltJIDs(ctx, &evt.Info.MessageSource, false) { return nil, fmt.Errorf("failed to ensure alt JIDs for message %s", evt.Info.ID) } + if evt.Info.IsFromMe { + wa.addPreviousOwnLID(ctx, evt.Info.Sender) + } isViewOnce := evt.IsViewOnce || evt.IsViewOnceV2 || evt.IsViewOnceV2Extension converted, mediaReq := wa.convertHistorySyncMessage( ctx, cli, portal, &evt.Info, evt.Message, evt.RawMessage, isViewOnce, msg.Reactions, diff --git a/pkg/connector/client.go b/pkg/connector/client.go index 4181235..678c8d2 100644 --- a/pkg/connector/client.go +++ b/pkg/connector/client.go @@ -55,6 +55,7 @@ func (wa *WhatsAppConnector) LoadUserLogin(ctx context.Context, login *bridgev2. mediaRetryLock: semaphore.NewWeighted(wa.Config.HistorySync.MediaRequests.MaxAsyncHandle), pushNamesSynced: exsync.NewEvent(), appStateFullSyncAttempted: make(map[appstate.WAPatchName]time.Time), + previousOwnLIDs: exsync.NewSetWithItems(login.Metadata.(*waid.UserLoginMetadata).PreviousOwnLIDs), onDemandHistorySyncRequests: make(map[types.JID]onDemandHistorySyncRequest), @@ -138,6 +139,9 @@ type WhatsAppClient struct { onDemandHistorySyncLock sync.Mutex onDemandHistorySyncRequests map[types.JID]onDemandHistorySyncRequest + + previousOwnLIDs *exsync.Set[types.JID] + previousOwnLIDsLock sync.Mutex } var ( @@ -206,7 +210,26 @@ func (wa *WhatsAppClient) IsThisUser(_ context.Context, userID networkid.UserID) func (wa *WhatsAppClient) IsOwnJID(jid types.JID) bool { return (jid.Server == types.DefaultUserServer && jid.User == wa.JID.User) || - (jid.Server == types.HiddenUserServer && jid.User == wa.GetLID().User) + (jid.Server == types.HiddenUserServer && jid.User == wa.GetLID().User) || + wa.previousOwnLIDs.Has(jid.ToNonAD()) +} + +func (wa *WhatsAppClient) addPreviousOwnLID(ctx context.Context, jid types.JID) { + if jid.Server != types.HiddenUserServer || wa.IsOwnJID(jid) { + return + } + jid = jid.ToNonAD() + wa.previousOwnLIDsLock.Lock() + defer wa.previousOwnLIDsLock.Unlock() + if !wa.previousOwnLIDs.Add(jid) { + return + } + zerolog.Ctx(ctx).Info().Stringer("lid", jid).Msg("Found previous own LID in history sync") + wa.UserLogin.Metadata.(*waid.UserLoginMetadata).PreviousOwnLIDs = wa.previousOwnLIDs.AsList() + err := wa.UserLogin.Save(ctx) + if err != nil { + zerolog.Ctx(ctx).Err(err).Msg("Failed to save user login after adding previous own LID") + } } func (wa *WhatsAppClient) GetLID() types.JID { diff --git a/pkg/waid/dbmeta.go b/pkg/waid/dbmeta.go index 15c0a42..b1a47e0 100644 --- a/pkg/waid/dbmeta.go +++ b/pkg/waid/dbmeta.go @@ -45,6 +45,8 @@ type UserLoginMetadata struct { HistorySyncPortalsNeedCreating bool `json:"history_sync_portals_need_creating,omitzero"` ReachoutTimelockUntil time.Time `json:"reachout_timelock_until,omitzero"` + PreviousOwnLIDs []types.JID `json:"previous_own_lids,omitempty"` + Blocklist *types.Blocklist `json:"blocklist,omitempty"` MData json.RawMessage `json:"mdata,omitempty"` From 07d8e9417b3451f3adb38c48e8047e273c64c6e8 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 2 Nov 2026 11:14:43 +0000 Subject: [PATCH 27/42] client: build whatsmeow HTTP clients from bridge settings (#1016) --- pkg/connector/connector.go | 11 +++++++++- pkg/connector/proxy.go | 45 +++++++++++++++++++++++++------------- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/pkg/connector/connector.go b/pkg/connector/connector.go index 19caace..80b9d95 100644 --- a/pkg/connector/connector.go +++ b/pkg/connector/connector.go @@ -243,7 +243,16 @@ func (wa *WhatsAppConnector) GenerateTransactionID(_ id.UserID, _ id.RoomID, _ e } func (wa *WhatsAppConnector) ResetHTTPTransport() { - // No-op for now, whatsmeow doesn't use the shared transport config yet + for _, login := range wa.Bridge.GetAllCachedUserLogins() { + client := login.Client.(*WhatsAppClient).Client + if client == nil { + continue + } + err := wa.updateProxy(login.Log.WithContext(wa.Bridge.BackgroundCtx), client, false) + if err != nil { + login.Log.Err(err).Msg("Failed to recreate HTTP clients") + } + } } func (wa *WhatsAppConnector) ResetNetworkConnections() { diff --git a/pkg/connector/proxy.go b/pkg/connector/proxy.go index fe1d7ff..8bd6d65 100644 --- a/pkg/connector/proxy.go +++ b/pkg/connector/proxy.go @@ -54,23 +54,38 @@ func (wa *WhatsAppConnector) getProxy(ctx context.Context, reason string) (strin } func (wa *WhatsAppConnector) updateProxy(ctx context.Context, client *whatsmeow.Client, isLogin bool) error { - if wa.Config.ProxyOnlyLogin && !isLogin { - return nil + var proxy string + if !wa.Config.ProxyOnlyLogin || isLogin { + reason := "connect" + if isLogin { + reason = "login" + } + var err error + proxy, err = wa.getProxy(ctx, reason) + if err != nil { + return fmt.Errorf("failed to get proxy address: %w", err) + } } - reason := "connect" - if isLogin { - reason = "login" + settings := wa.Bridge.GetHTTPClientSettings().WithGlobalTimeout(0) + if settings.HTTPProxy == nil { + settings.HTTPProxy = http.ProxyFromEnvironment } - if proxy, err := wa.getProxy(ctx, reason); err != nil { - return fmt.Errorf("failed to get proxy address: %w", err) - } else if proxy == "" { - return nil - } else if err = client.SetProxyAddress(proxy, whatsmeow.SetProxyOptions{ - OnlyLogin: wa.Config.ProxyOnlyLogin, - NoMedia: wa.Config.ProxyOnlyLogin, - }); err != nil { - return fmt.Errorf("failed to set proxy address: %w", err) + proxySettings := settings + if proxy != "" { + var err error + proxySettings, err = settings.WithProxy(proxy) + if err != nil { + return fmt.Errorf("failed to set proxy address: %w", err) + } + } + client.SetPreLoginHTTPClient(proxySettings.Compile()) + if wa.Config.ProxyOnlyLogin { + proxySettings = settings + } + client.SetWebsocketHTTPClient(proxySettings.Compile()) + client.SetMediaHTTPClient(proxySettings.WithResponseHeaderTimeout(0).Compile()) + if proxy != "" { + zerolog.Ctx(ctx).Debug().Msg("Enabled proxy") } - zerolog.Ctx(ctx).Debug().Msg("Enabled proxy") return nil } From 96ce0799be8c962d64cde63ab383a925d7a8fd84 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 2 Nov 2026 12:57:03 +0000 Subject: [PATCH 28/42] handlewhatsapp: don't retry full sync after a recovery response (#1018) --- pkg/connector/handlewhatsapp.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pkg/connector/handlewhatsapp.go b/pkg/connector/handlewhatsapp.go index a7d4c91..4391233 100644 --- a/pkg/connector/handlewhatsapp.go +++ b/pkg/connector/handlewhatsapp.go @@ -970,7 +970,9 @@ func (wa *WhatsAppClient) handleWAAppStateSyncComplete(ctx context.Context, evt defer wa.appStateRecoveryLock.Unlock() meta := wa.UserLogin.Metadata.(*waid.UserLoginMetadata) if ts, exists := meta.AppStateRecoveryAttempted[evt.Name]; exists { - delete(wa.appStateFullSyncAttempted, evt.Name) + if !evt.Recovery { + delete(wa.appStateFullSyncAttempted, evt.Name) + } delete(meta.AppStateRecoveryAttempted, evt.Name) err := wa.UserLogin.Save(ctx) if err != nil { @@ -1008,7 +1010,7 @@ func (wa *WhatsAppClient) handleWAAppStateSyncError(ctx context.Context, evt *ev return } if !evt.FullSync { - if !lastFullSync.IsZero() { + if !lastFullSync.IsZero() && time.Since(lastFullSync) < 48*time.Hour { log.Debug(). Err(evt.Error). Time("last_full_sync_attempt", lastFullSync). From 4be45ddbea7d2aec2fe977cf3ea2d62c485a3a47 Mon Sep 17 00:00:00 2001 From: "indent[bot]" <297468268+indent[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 09:28:04 -0500 Subject: [PATCH 29/42] handlewhatsapp: send media retry edits as the original message sender (#1019) Co-authored-by: Indent --- pkg/connector/events.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pkg/connector/events.go b/pkg/connector/events.go index 481d0d7..7f906e8 100644 --- a/pkg/connector/events.go +++ b/pkg/connector/events.go @@ -474,7 +474,9 @@ func (evt *WAMediaRetry) getRealSender() types.JID { func (evt *WAMediaRetry) GetSender() bridgev2.EventSender { realSender := pickLID(evt.getRealSender(), evt.senderLID) - return evt.wa.makeEventSender(evt.wa.Main.Bridge.BackgroundCtx, realSender) + sender := evt.wa.makeEventSender(evt.wa.Main.Bridge.BackgroundCtx, realSender) + sender.ForceEditOrigSender = true + return sender } func (evt *WAMediaRetry) GetTargetMessage() networkid.MessageID { From e097ba38de1f5d450013eb52b3136f28c7131dea Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Mon, 2 Nov 2026 15:14:20 +0000 Subject: [PATCH 30/42] userinfo: don't copy unauthorized avatar to alt ghost (#1020) --- pkg/connector/userinfo.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/connector/userinfo.go b/pkg/connector/userinfo.go index b109e82..3d5499c 100644 --- a/pkg/connector/userinfo.go +++ b/pkg/connector/userinfo.go @@ -480,7 +480,7 @@ func makeInfoFromGhost(ghost *bridgev2.Ghost) *bridgev2.UserInfo { IsBot: &ghost.IsBot, ExtraProfile: ghost.ExtraProfile, } - if ghost.AvatarID != "" { + if ghost.AvatarID != "" && ghost.AvatarID != "unauthorized" { info.Avatar = &bridgev2.Avatar{ ID: ghost.AvatarID, Remove: ghost.AvatarMXC == "", From 78c5ee3b207d982cab19bec7424279e3fc365071 Mon Sep 17 00:00:00 2001 From: "indent[bot]" <297468268+indent[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:41:06 -0500 Subject: [PATCH 31/42] backfill: expire unanswered on-demand history sync requests after an hour (#1021) Co-authored-by: Indent --- pkg/connector/backfill.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index fe251e1..343b240 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -799,10 +799,12 @@ type onDemandHistorySyncRequest struct { SentAt time.Time } +const onDemandHistorySyncRequestTimeout = 1 * time.Hour + func (wa *WhatsAppClient) startOnDemandHistorySyncRequest(ctx context.Context, portalJID types.JID, msgID types.MessageID) bool { wa.onDemandHistorySyncLock.Lock() defer wa.onDemandHistorySyncLock.Unlock() - if req, inFlight := wa.onDemandHistorySyncRequests[portalJID]; inFlight { + if req, inFlight := wa.onDemandHistorySyncRequests[portalJID]; inFlight && time.Since(req.SentAt) < onDemandHistorySyncRequestTimeout { zerolog.Ctx(ctx).Debug(). Str("in_flight_request_msg_id", req.ID). Stringer("portal_jid", portalJID). From 429320b373d2154cfdcca3e6981e2af9f7f00ee1 Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Tue, 3 Nov 2026 21:35:54 +0000 Subject: [PATCH 32/42] pre-commit: add bridgelint hook (#1022) --- .pre-commit-config.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1bfb536..d6c78bb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -21,9 +21,11 @@ repos: - id: go-mod-tidy - repo: https://github.com/beeper/pre-commit-go - rev: v0.4.2 + rev: v0.5.0 hooks: - id: zerolog-ban-msgf - id: zerolog-use-stringer - id: prevent-literal-http-methods - id: zerolog-ban-global-log + - id: bridgelint + verbose: true From 5ba69ab4ee9c916c488ada28c6086d7ec382225c Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Wed, 4 Nov 2026 16:24:07 +0000 Subject: [PATCH 33/42] backfill: drop history sync notifications whose blob is gone (#1023) --- pkg/connector/backfill.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index 343b240..cbc7eec 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -142,8 +142,16 @@ func (wa *WhatsAppClient) downloadAndSaveWAHistorySyncData(ctx context.Context, Str("peer_data_request_session_id", evt.GetPeerDataRequestSessionID()). Msg("Downloading history sync") blob, err := wa.Client.DownloadHistorySync(log.WithContext(ctx), evt, true) - if err != nil { + if errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith403) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith410) { + log.Err(err).Msg("History sync blob is no longer available, dropping notification") + if err = wa.Main.DB.HSNotif.Delete(ctx, rowid); err != nil { + log.Err(err).Msg("Failed to delete queued history sync notification") + errored = true + } + return + } else if err != nil { log.Err(err).Msg("Failed to download history sync") + errored = true return } if blob.GetSyncType() == waHistorySync.HistorySync_ON_DEMAND { @@ -171,6 +179,7 @@ func (wa *WhatsAppClient) downloadAndSaveWAHistorySyncData(ctx context.Context, }) if err != nil { log.Err(err).Msg("Failed to store history sync notification data") + errored = true } else { resetTimer = blob.GetSyncType() == waHistorySync.HistorySync_INITIAL_BOOTSTRAP || blob.GetSyncType() == waHistorySync.HistorySync_RECENT || From 1d024590d2df575f1f2e184229ace51b0300ff70 Mon Sep 17 00:00:00 2001 From: "indent[bot]" <297468268+indent[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:16:41 -0500 Subject: [PATCH 34/42] userinfo: don't queue @bot ghosts for background resync (#1024) Co-authored-by: Indent --- pkg/connector/userinfo.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pkg/connector/userinfo.go b/pkg/connector/userinfo.go index 3d5499c..b659453 100644 --- a/pkg/connector/userinfo.go +++ b/pkg/connector/userinfo.go @@ -29,12 +29,15 @@ var ResyncLoopInterval = 4 * time.Hour var ResyncJitterSeconds = 3600 func (wa *WhatsAppClient) EnqueueGhostResync(ghost *bridgev2.Ghost) { + jid := waid.ParseUserID(ghost.ID) + if jid.Server == types.BotServer { + return + } lastSync := ghost.Metadata.(*waid.GhostMetadata).LastSync.Time if ghost.AvatarID != "" && lastSync.Add(ResyncMinInterval).After(time.Now()) { return } wa.resyncQueueLock.Lock() - jid := waid.ParseUserID(ghost.ID) if _, exists := wa.resyncQueue[jid]; !exists { wa.resyncQueue[jid] = resyncQueueItem{ghost: ghost} nextResyncIn := time.Until(wa.nextResync).String() From 03859bb3db0b7f597bf93f2f35a7306879b85dcc Mon Sep 17 00:00:00 2001 From: Nick Mills-Barrett Date: Thu, 5 Nov 2026 13:09:38 +0000 Subject: [PATCH 35/42] pre-commit: install bridgelint with the CI Go toolchain (#1030) --- .github/workflows/go.yml | 1 + .pre-commit-config.yaml | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index c9fef73..146b93a 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -30,6 +30,7 @@ jobs: run: | go install golang.org/x/tools/cmd/goimports@latest go install honnef.co/go/tools/cmd/staticcheck@latest + go install github.com/beeper/pre-commit-go/bridgelint@latest export PATH="$HOME/go/bin:$PATH" - name: Run pre-commit diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d6c78bb..1c96b06 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,4 +28,5 @@ repos: - id: prevent-literal-http-methods - id: zerolog-ban-global-log - id: bridgelint + language: system verbose: true From 81f64557ea4f8535a4323135f42569b8e26646a5 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Thu, 5 Nov 2026 09:16:26 -0500 Subject: [PATCH 36/42] handlematrix: ignore thread read receipts Closes #1028 --- go.mod | 2 +- go.sum | 4 ++-- pkg/connector/handlematrix.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 6e9b503..f940c1d 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( golang.org/x/sync v0.24.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - maunium.net/go/mautrix v0.32.1-0.20261031224934-b69deb427bd7 + maunium.net/go/mautrix v0.32.1-0.20261105141340-842796acf445 ) require ( diff --git a/go.sum b/go.sum index 12cf8f5..fb4e878 100644 --- a/go.sum +++ b/go.sum @@ -103,5 +103,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M= maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA= -maunium.net/go/mautrix v0.32.1-0.20261031224934-b69deb427bd7 h1:GpLIqeJTpG0/ti7XA370HgjnSWd/pQxXVGb/FRkayOA= -maunium.net/go/mautrix v0.32.1-0.20261031224934-b69deb427bd7/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= +maunium.net/go/mautrix v0.32.1-0.20261105141340-842796acf445 h1:ZI9Y2YEmjqQDloOCiciHeynTRYjUwK0ZZbNcRH/5NOc= +maunium.net/go/mautrix v0.32.1-0.20261105141340-842796acf445/go.mod h1:tZSwPzw+/0pa0dxGufkh0uJqM84BNxB6e2I0+S0UyjU= diff --git a/pkg/connector/handlematrix.go b/pkg/connector/handlematrix.go index d51efcd..8419850 100644 --- a/pkg/connector/handlematrix.go +++ b/pkg/connector/handlematrix.go @@ -319,7 +319,7 @@ func (wa *WhatsAppClient) HandleMatrixMessageRemove(ctx context.Context, msg *br } func (wa *WhatsAppClient) HandleMatrixReadReceipt(ctx context.Context, receipt *bridgev2.MatrixReadReceipt) (retErr error) { - if !receipt.ReadUpTo.After(receipt.LastRead) { + if receipt.Receipt.IsThread() || !receipt.ReadUpTo.After(receipt.LastRead) { return nil } if receipt.LastRead.IsZero() { From 5640ef311b5aef90ee0d35766ec9c9bf167d25af Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Thu, 5 Nov 2026 15:00:20 +0000 Subject: [PATCH 37/42] muse: mark WASA resync as done on any error (#1026) --- pkg/connector/muse.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pkg/connector/muse.go b/pkg/connector/muse.go index ee6b04d..4a589ce 100644 --- a/pkg/connector/muse.go +++ b/pkg/connector/muse.go @@ -4,7 +4,6 @@ import ( "context" "encoding/base64" "encoding/json" - "errors" "fmt" "runtime/debug" "time" @@ -57,9 +56,9 @@ func (wa *WhatsAppClient) resyncWASARootSecrets(ctx context.Context) { success := true if err := wa.Client.FetchAppState(ctx, appstate.WAPatchRegularHigh, true, false); err != nil { log.Err(err).Msg("Failed to resync WASA root secrets") - // Mark the sync as completed on mismatching LTHash errors, because those can get permanently stuck - // (retrying won't help). In case it's not stuck, a single call should be enough to request a resync. - if !errors.Is(err, appstate.ErrMismatchingLTHash) || ctx.Err() != nil { + // Mark the sync as completed on errors too, because some get permanently stuck (mismatching LTHash, + // expired patch blobs), and a failed full sync already requests app state recovery from the phone. + if ctx.Err() != nil { return } success = false From d574a67a2d22a15af72d953ff5c2d44adfe8562c Mon Sep 17 00:00:00 2001 From: "indent[bot]" <297468268+indent[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:33:02 +0000 Subject: [PATCH 38/42] userinfo: query only the LID when both JIDs of a contact are queued for background resync (#1029) Co-authored-by: Indent --- pkg/connector/userinfo.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/pkg/connector/userinfo.go b/pkg/connector/userinfo.go index b659453..387971e 100644 --- a/pkg/connector/userinfo.go +++ b/pkg/connector/userinfo.go @@ -119,6 +119,7 @@ func (wa *WhatsAppClient) doGhostResync(ctx context.Context, queue map[types.JID var ghostJIDs []types.JID var ghosts []*bridgev2.Ghost var portals []*bridgev2.Portal + selectedGhosts := make(map[types.JID]*bridgev2.Ghost) for jid, item := range queue { var lastSync time.Time unknownAvatar := false @@ -136,12 +137,23 @@ func (wa *WhatsAppClient) doGhostResync(ctx context.Context, queue map[types.JID continue } if item.ghost != nil { - ghosts = append(ghosts, item.ghost) - ghostJIDs = append(ghostJIDs, jid) + selectedGhosts[jid] = item.ghost } else if item.portal != nil { portals = append(portals, item.portal) } } + for jid, ghost := range selectedGhosts { + if jid.Server == types.DefaultUserServer { + lid, err := wa.GetStore().LIDs.GetLIDForPN(ctx, jid) + if err != nil { + log.Warn().Err(err).Stringer("jid", jid).Msg("Failed to get LID for background sync") + } else if _, lidSelected := selectedGhosts[lid]; lidSelected { + continue + } + } + ghosts = append(ghosts, ghost) + ghostJIDs = append(ghostJIDs, jid) + } for _, portal := range portals { wa.UserLogin.QueueRemoteEvent(&simplevent.ChatResync{ EventMeta: simplevent.EventMeta{ From ac29fa5272ed896586320f92dfa63d305883f895 Mon Sep 17 00:00:00 2001 From: Gerardo Rodriguez Date: Fri, 6 Nov 2026 20:37:55 +0000 Subject: [PATCH 39/42] lidmigrate: check homeserver membership when removing rejoined PN ghosts (#1025) --- pkg/connector/lidmigrate.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/pkg/connector/lidmigrate.go b/pkg/connector/lidmigrate.go index 17b2428..4295be6 100644 --- a/pkg/connector/lidmigrate.go +++ b/pkg/connector/lidmigrate.go @@ -300,7 +300,11 @@ func (wa *WhatsAppConnector) syncMismatchingGhosts(ctx context.Context) error { } func (wa *WhatsAppConnector) removeRejoinedPNGhosts(ctx context.Context) error { - if wa.Bridge.Background || wa.Bridge.DB.KV.Get(ctx, "whatsapp_lid_dm_pn_ghosts_removed") == "true" { + if wa.Bridge.Background || wa.Bridge.DB.KV.Get(ctx, "whatsapp_lid_dm_pn_ghosts_removed_v2") == "true" { + return nil + } + stateGetter, ok := wa.Bridge.Matrix.(bridgev2.MatrixConnectorWithArbitraryRoomState) + if !ok { return nil } log := zerolog.Ctx(ctx).With().Str("action", "remove rejoined pn ghosts").Logger() @@ -322,12 +326,14 @@ func (wa *WhatsAppConnector) removeRejoinedPNGhosts(ctx context.Context) error { continue } pnUserID := waid.MakeUserID(pn) - member, err := wa.Bridge.Matrix.GetMemberInfo(ctx, portal.MXID, wa.Bridge.Matrix.FormatGhostMXID(pnUserID)) - if err != nil { + memberEvt, err := stateGetter.GetStateEvent(ctx, portal.MXID, event.StateMember, wa.Bridge.Matrix.FormatGhostMXID(pnUserID).String()) + if errors.Is(err, mautrix.MNotFound) || errors.Is(err, mautrix.MForbidden) { + continue + } else if err != nil { log.Warn().Err(err).Stringer("room_id", portal.MXID).Msg("Failed to get PN ghost membership") failed++ continue - } else if member == nil || member.Membership != event.MembershipJoin { + } else if memberEvt == nil || memberEvt.Content.AsMember().Membership != event.MembershipJoin { continue } pnGhost, err := wa.Bridge.GetGhostByID(ctx, pnUserID) @@ -345,6 +351,12 @@ func (wa *WhatsAppConnector) removeRejoinedPNGhosts(ctx context.Context) error { } continue } + log.Debug(). + Stringer("room_id", portal.MXID). + Stringer("pn", pn). + Stringer("join_sender", memberEvt.Sender). + Time("join_ts", time.UnixMilli(memberEvt.Timestamp)). + Msg("Removed PN ghost from LID DM") removed++ } log.Info(). @@ -353,7 +365,7 @@ func (wa *WhatsAppConnector) removeRejoinedPNGhosts(ctx context.Context) error { Int("total_lid_portals", len(lidPortals)). Msg("Finished removing rejoined PN ghosts from LID DMs") if failed == 0 && ctx.Err() == nil { - wa.Bridge.DB.KV.Set(ctx, "whatsapp_lid_dm_pn_ghosts_removed", "true") + wa.Bridge.DB.KV.Set(ctx, "whatsapp_lid_dm_pn_ghosts_removed_v2", "true") } return nil } From d9b0daca891ac69226931eba5594e0f490aaee51 Mon Sep 17 00:00:00 2001 From: "indent[bot]" <297468268+indent[bot]@users.noreply.github.com> Date: Sat, 7 Nov 2026 09:46:19 -0500 Subject: [PATCH 40/42] msgconv/rich-response: only embed raw rich message JSON if it's canonical (#1033) Co-authored-by: Indent --- pkg/msgconv/wa-rich-response.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pkg/msgconv/wa-rich-response.go b/pkg/msgconv/wa-rich-response.go index 28a648c..e506a64 100644 --- a/pkg/msgconv/wa-rich-response.go +++ b/pkg/msgconv/wa-rich-response.go @@ -29,6 +29,7 @@ import ( "github.com/yuin/goldmark/extension" "go.mau.fi/whatsmeow/types/richresponse" "maunium.net/go/mautrix/bridgev2" + "maunium.net/go/mautrix/crypto/canonicaljson" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/format" "maunium.net/go/mautrix/format/mdext" @@ -36,7 +37,8 @@ import ( func (mc *MessageConverter) convertUnifiedRichResponseMessage(ctx context.Context, data []byte) *bridgev2.ConvertedMessagePart { extra := map[string]any{} - if json.Valid(data) && len(data) < 24*1024 { + _, canonicalErr := canonicaljson.Marshal(json.RawMessage(data)) + if canonicalErr == nil && len(data) < 24*1024 { extra["fi.mau.whatsapp.rich_message"] = json.RawMessage(data) } else if len(data) < 16*1024 { extra["fi.mau.whatsapp.non_json_rich_message"] = base64.StdEncoding.EncodeToString(data) From 5c8c1fc8358c011891fbf6066f289b9ad5fee223 Mon Sep 17 00:00:00 2001 From: "indent[bot]" <297468268+indent[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:09:28 +0000 Subject: [PATCH 41/42] handlewhatsapp: ignore HD replacement messages without replacement content (#1037) Co-authored-by: Indent --- pkg/connector/handlewhatsapp.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pkg/connector/handlewhatsapp.go b/pkg/connector/handlewhatsapp.go index 4391233..e6174b9 100644 --- a/pkg/connector/handlewhatsapp.go +++ b/pkg/connector/handlewhatsapp.go @@ -374,6 +374,14 @@ func (wa *WhatsAppClient) handleWAMessage(ctx context.Context, evt *events.Messa if assocType := messageAssoc.GetAssociationType(); assocType == waE2E.MessageAssociation_HD_IMAGE_DUAL_UPLOAD || assocType == waE2E.MessageAssociation_HD_VIDEO_DUAL_UPLOAD { parentKey := messageAssoc.GetParentMessageKey() protocolMsg, shouldHideEdit := makeHDMediaReplacementEdit(evt.Message, parentKey) + if protocolMsg.GetEditedMessage() == nil { + wa.UserLogin.Log.Debug(). + Str("message_id", evt.Info.ID). + Str("parent_id", parentKey.GetID()). + Stringer("assoc_type", assocType). + Msg("Ignoring HD replacement message without replacement content") + return + } dontRenderEdited = shouldHideEdit wa.UserLogin.Log.Debug(). Str("message_id", evt.Info.ID). From 945474343fcd7579c3d273acb78f6c60c957e2e0 Mon Sep 17 00:00:00 2001 From: "indent[bot]" <297468268+indent[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:09:56 +0000 Subject: [PATCH 42/42] backfill: log stub and message type of unparseable history messages (#1034) Co-authored-by: Indent --- pkg/connector/backfill.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pkg/connector/backfill.go b/pkg/connector/backfill.go index cbc7eec..8f006e0 100644 --- a/pkg/connector/backfill.go +++ b/pkg/connector/backfill.go @@ -298,6 +298,9 @@ func (wa *WhatsAppClient) handleWAHistorySync( Int("msg_index", i). Str("msg_id", rawMsg.GetMessage().GetKey().GetID()). Uint64("msg_time_seconds", rawMsg.GetMessage().GetMessageTimestamp()). + Stringer("stub_type", rawMsg.GetMessage().GetMessageStubType()). + Str("message_type", getMessageType(rawMsg.GetMessage().GetMessage())). + Bool("from_me", rawMsg.GetMessage().GetKey().GetFromMe()). Msg("Dropping historical message due to parse error") log.Trace(). Any("web_message_info", rawMsg.GetMessage()).