// Copyright (c) 2026 Xessenger // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package bridgekit import ( "context" "slices" "strings" "github.com/rs/zerolog" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // The members of a switched-on user's login (members.go) act on its messenger as the user does: what // they send into the login's encrypted rooms goes out as the account's own, in its name and without // the sender's name bridgev2's relay mode would put in front, as the API sends what a workspace that // links the connection does with the user's token. bridgev2 takes to a portal's messenger only the // events of the user whose login receives it (Portal.FindPreferredLogin), so a member's event is // handed on to it as the user's. The member's own event stays in the room as it was sent. // // memberEventTypes are the events of the app's that bridgev2 takes to the network: messages (edits and // replies among them), stickers, polls, reactions and redactions, which delete a message or take a // reaction back. Read receipts are taken as the user's too (readAsOwner). A member's membership stays // theirs; com.beeper.delete_chat and com.beeper.accept_message_request the API sends with the user's // token, and the API never changed a room's name, topic, picture or power levels for a linked // workspace. var memberEventTypes = []event.Type{ event.EventMessage, event.EventSticker, event.EventUnstablePollStart, event.EventUnstablePollResponse, event.EventReaction, event.EventRedaction, } // installMemberEvents puts actAsOwner and readAsOwner in front of bridgev2's Matrix event handlers and // of the extension's refusal, installed before it (refuse.go), which then looks at a member's event as // the user's. func (k *Kit) installMemberEvents() { for _, eventType := range memberEventTypes { k.conn.EventProcessor.PrependHandler(eventType, k.actAsOwner) } k.conn.EventProcessor.PrependHandler(event.EphemeralEventReceipt, k.readAsOwner) } // actAsOwner hands bridgev2 a member's event in one of the user's encrypted rooms as the user's // (roomMembers). Two kinds stay the member's, which bridgev2 then takes nowhere for them: // - Of the events the user's account may not send unencrypted (refuse.go), an unencrypted one. A // member's app encrypts them as the user's does; decrypted ones come from the member's devices // this bridge pinned (verification_levels.send). // - A message bridgev2 could take as a command (isCommand): a member sends as the account, but does // not run the bridge's commands on the user's login, such as logging it out. func (k *Kit) actAsOwner(ctx context.Context, evt *event.Event) { // Members are people of this homeserver (validMembers): the ghosts' and the bot's events, most of // a room's, are not looked up. if !k.active() || !k.isHomeserverUser(evt.Sender) || (!evt.Mautrix.WasEncrypted && k.refuses(evt.Type)) || k.isCommand(evt) { return } owner, members := k.roomMembers(ctx, evt.RoomID) if owner == "" || !slices.Contains(members, evt.Sender) { return } zerolog.Ctx(ctx).Debug(). Stringer("event_type", evt.Type). Stringer("room_id", evt.RoomID). Stringer("member", evt.Sender). Stringer("owner", owner). Stringer("event_id", evt.ID). Msg("Handing a member's event to the bridge as the switched-on user's") evt.Sender = owner } // readAsOwner takes the read receipts of the members in one of the user's encrypted rooms as the // user's, which bridgev2 sends to the messenger as the account's: the API marks what a workspace that // links the connection read with the user's token. The user's own receipt of the same message stays. func (k *Kit) readAsOwner(ctx context.Context, evt *event.Event) { if !k.active() { return } content, ok := evt.Content.Parsed.(*event.ReceiptEventContent) if !ok || !k.personRead(*content) { return } owner, members := k.roomMembers(ctx, evt.RoomID) if owner == "" || len(members) == 0 { return } for _, receipts := range *content { read := receipts[event.ReceiptTypeRead] for _, member := range members { receipt, ok := read[member] if !ok { continue } delete(read, member) if _, own := read[owner]; !own { read[owner] = receipt } } } } // personRead reports whether somebody of this homeserver read in content: the ghosts' receipts, most of // them, are not looked up. func (k *Kit) personRead(content event.ReceiptEventContent) bool { for _, receipts := range content { for userID := range receipts[event.ReceiptTypeRead] { if k.isHomeserverUser(userID) { return true } } } return false } // roomMembers returns the switched-on user whose login receives the portal of an encrypted room, with // that login's members; "" for any other room, and for a room the user left (ownerLeft): the members // act as the user only where the user is. func (k *Kit) roomMembers(ctx context.Context, roomID id.RoomID) (id.UserID, []id.UserID) { if !k.isEncrypted(ctx, roomID) { return "", nil } portal, err := k.br.GetPortalByMXID(ctx, roomID) if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Msg("Failed to get the portal of an encrypted room") return "", nil } else if portal == nil { return "", nil } owner := k.portalOwner(ctx, portal.PortalKey) if owner == "" || k.ownerLeft(ctx, roomID, owner) { return "", nil } return owner, k.membersOf(owner)[portal.Receiver] } // isCommand reports whether bridgev2 could take a message as a command (Bridge.QueueMatrixEvent): one // whose text starts with the command prefix, with or without a reply or per-message profile fallback in // front, which bridgev2 takes off first. func (k *Kit) isCommand(evt *event.Event) bool { if evt.Type != event.EventMessage { return false } msg, ok := evt.Content.Parsed.(*event.MessageEventContent) if !ok { return false } prefix := k.br.Config.CommandPrefix bodies := []string{msg.Body, event.TrimReplyFallbackText(msg.Body)} if profile := msg.BeeperPerMessageProfile; profile != nil && profile.Displayname != "" { for _, body := range bodies[:2] { bodies = append(bodies, strings.TrimPrefix(body, profile.Displayname+": ")) } } return slices.ContainsFunc(bodies, func(body string) bool { return strings.HasPrefix(body, prefix) }) }