// 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" "encoding/json" "errors" "fmt" "strings" "github.com/rs/zerolog" "maunium.net/go/mautrix/bridgev2/database" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/crypto" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // The encrypted state events the app reads (docs/e2ee/work-plan.md 4.3). The server sees only the // outer m.room.encrypted state event, whose state key is ":". const ( roomMetaType = "com.xessenger.room_meta" memberProfileType = "com.xessenger.member_profile" ) type roomMeta struct { V int `json:"v"` Name *string `json:"name"` Avatar *event.EncryptedFileInfo `json:"avatar"` Network string `json:"network"` Kind string `json:"kind"` } type memberProfile struct { V int `json:"v"` Displayname *string `json:"displayname"` Avatar *event.EncryptedFileInfo `json:"avatar"` Handle memberHandle `json:"handle"` } type memberHandle struct { Phone string `json:"phone,omitempty"` Email string `json:"email,omitempty"` Username string `json:"username,omitempty"` } var errNoCrypto = errors.New("encryption is not running") // memberArrived is called when a user was invited to or joined an encrypted room. When that is the // room's owner, the room's metadata and its members' profiles are sent if they have not been: the // owner's devices get room keys only from then on, so state encrypted earlier would be lost to them. // State of the bridge's own goes again in any case, what of it changed since it last went: given while // the owner was away, it was only kept (sendBridgeState). It is read under the room's lock, so that // state given as the owner comes back is kept by then, or goes as they are back. func (k *Kit) memberArrived(ctx context.Context, roomID id.RoomID, userID id.UserID) { if k.roomOwner(ctx, roomID) != userID { return } if _, done := k.metaSent.Load(roomID); !done { go k.sendAllMeta(k.backgroundContext(), roomID) } else if len(k.opts.EncryptedState) > 0 { go func() { ctx := k.backgroundContext() if err := k.sendBridgeStatesAgain(ctx, roomID); err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Msg("Failed to send the bridge's encrypted room state once the owner was back") } }() } } // resendMeta sends a room's encrypted metadata and its members' profiles again, in a new outbound // session, when they went out and its owner is in it: an identity who reads the room from now on (a // member invited, or one whose devices are trusted only now) never got the keys of the state encrypted // before, which stays as it was sent until it changes. A room whose metadata never went out waits for // its owner (memberArrived). // // The room is noted before what went out is forgotten, and the note cleared once all of it went again, // so that a send that failed is done again with the next member sync (syncRoomMembers, every // trustInterval), when no invite asks for it any more. What went out is forgotten and the session // dropped under the metadata lock: state sent in between would go in the old session and keep its // fingerprint, which the send again would then skip. The caller holds the room's member lock // (memberLock), so that a room's metadata goes again once at a time, and no send again clears the note // of another that failed. func (k *Kit) resendMeta(ctx context.Context, roomID id.RoomID) error { mach := k.machine() if mach == nil || !k.ownerPresent(ctx, roomID) { return nil } lock := k.roomLock(roomID) lock.Lock() again, err := k.store.forgetSentMeta(ctx, roomID) if err != nil { err = fmt.Errorf("failed to forget the encrypted metadata sent into %s: %w", roomID, err) } else if again { // The session the room has may have gone out before the reader's devices could get it. if err = mach.CryptoStore.RemoveOutboundGroupSession(ctx, roomID); err != nil { err = fmt.Errorf("failed to drop the outbound session of %s before sending the metadata again: %w", roomID, err) } } lock.Unlock() if err != nil || !again { return err } k.metaSent.Delete(roomID) if !k.sendAllMeta(ctx, roomID) { return fmt.Errorf("failed to send the encrypted metadata of %s again", roomID) } else if err = k.store.metaResent(ctx, roomID); err != nil { return fmt.Errorf("failed to clear the note that the metadata of %s goes again: %w", roomID, err) } return nil } // roomMetaAgainNetworks are the networks whose bridges send their rooms' metadata again once // (noteRoomMetaAgain): their mautrix-go, built with Go 1.27, left the empty state key out of the plaintext of // encrypted state (mautrix-state-key.patch), and the app refused the room metadata. var roomMetaAgainNetworks = map[string]bool{"telegram": true, "line": true} // noteRoomMetaAgain notes once, on such a network, the rooms whose room metadata the bridge sent, for it to go // again (resendRoomMeta). A note that failed is taken at the next start. func (k *Kit) noteRoomMetaAgain(ctx context.Context) { if !roomMetaAgainNetworks[k.network] { return } noted, err := k.store.noteRoomMetaAgain(ctx) if err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to note the rooms whose metadata goes out again") } else if noted > 0 { zerolog.Ctx(ctx).Warn().Int64("rooms", noted).Msg("Noted the rooms whose metadata goes out again") } } // resendRoomMeta sends the room metadata of the rooms noted for it (noteRoomMetaAgain) again, as their portals // have it, when encryption starts and every trustInterval after it for what did not go: the room metadata alone, // in the room's session. A room whose owner is out of it, or that has no portal, has its note cleared: what its // metadata last said was forgotten as it was noted, so it goes as the owner comes back (memberArrived) or the // portal changes. A send that failed keeps its note. func (k *Kit) resendRoomMeta(ctx context.Context) { rooms, err := k.store.roomMetaAgain(ctx) if err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to read the rooms whose metadata goes out again") return } else if len(rooms) == 0 { return } sent, skipped, failed := 0, 0, 0 for roomID := range rooms { went, err := k.resendRoomMetaOf(ctx, roomID) if err == nil { err = k.store.roomMetaWentAgain(ctx, roomID) } switch { case err != nil: failed++ zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Msg("Failed to send the room's metadata again") case went: sent++ default: skipped++ } } zerolog.Ctx(ctx).Warn().Int("rooms", len(rooms)).Int("sent", sent).Int("skipped", skipped).Int("failed", failed). Msg("Sent the rooms' metadata again") } // resendRoomMetaOf sends a noted room's metadata again, and reports whether it went: not when the room's owner is // out of it, as the homeserver has it too (ownerJoinedOnHomeserver), it has no portal, or the same went since it // was noted. An owner joined on the homeserver whose join the state store did not take, or members not read, are // an error, tried again. func (k *Kit) resendRoomMetaOf(ctx context.Context, roomID id.RoomID) (bool, error) { if !k.ownerPresent(ctx, roomID) { if err := k.ownerJoinedOnHomeserver(ctx, roomID); errors.Is(err, errRoomOwnerAway) { return false, nil } else if err != nil { return false, err } } went, err := k.sendRoomMetaWent(ctx, roomID) if errors.Is(err, errNoPortal) { return false, nil } return went, err } // resendMetaTo sends the metadata again into the encrypted rooms of other users' that the user is in, // once the user's devices are trusted: a member is invited before they are switched on here // (members.go). What fails goes again with the next member sync of the room's owner. The keys of what // came before go to the user as a room key bundle (history.go), noted before the trust (noteHistoryOf). func (k *Kit) resendMetaTo(ctx context.Context, userID id.UserID) { if k.conn == nil || k.conn.StateStore == nil || k.br == nil { return } rooms, err := k.conn.StateStore.FindSharedRooms(ctx, userID) if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("user_id", userID).Msg("Failed to find the rooms to send the metadata into again") return } member := false defer func() { if member { k.queueHistory() } }() for _, roomID := range rooms { if !k.inOthersRoom(ctx, roomID, userID) { continue } member = true lock := k.memberLock(roomID) lock.Lock() err = k.resendMeta(ctx, roomID) lock.Unlock() if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("user_id", userID).Msg("Failed to send the metadata again") } } } // ownerPresent reports whether the room's owner is in it, so that their devices receive the key of // what is encrypted now. func (k *Kit) ownerPresent(ctx context.Context, roomID id.RoomID) bool { owner := k.roomOwner(ctx, roomID) return owner != "" && k.conn.StateStore.IsMembership(ctx, roomID, owner, event.MembershipJoin, event.MembershipInvite) } // queueRoomMeta sends a room's metadata after bridgev2 changed its name, topic or picture. Before the // owner is in the room it waits for memberArrived. func (k *Kit) queueRoomMeta(ctx context.Context, roomID id.RoomID) { if !k.ownerPresent(ctx, roomID) { return } if err := k.sendRoomMeta(ctx, roomID); err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Msg("Failed to send encrypted room metadata") } } // queueMemberProfile sends a ghost's profile into a room it joined or was invited to. func (k *Kit) queueMemberProfile(ctx context.Context, roomID id.RoomID, ghostID networkid.UserID) { if !k.ownerPresent(ctx, roomID) { return } if err := k.sendMemberProfile(ctx, roomID, ghostID); err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Str("ghost_id", string(ghostID)).Msg("Failed to send encrypted member profile") } } // sendAllMeta sends a room's metadata and its members' profiles, and reports whether all of it went. func (k *Kit) sendAllMeta(ctx context.Context, roomID id.RoomID) bool { log := zerolog.Ctx(ctx).With().Stringer("room_id", roomID).Logger() if err := k.sendRoomMeta(ctx, roomID); err != nil { log.Err(err).Msg("Failed to send encrypted room metadata") return false } members, err := k.conn.StateStore.GetRoomMembers(ctx, roomID, event.MembershipJoin, event.MembershipInvite) if err != nil { log.Err(err).Msg("Failed to list room members for their encrypted profiles") return false } failed := false for userID := range members { if ghostID, ok := k.hashedGhostID(ctx, userID); ok { if err = k.sendMemberProfile(ctx, roomID, ghostID); err != nil { log.Err(err).Str("ghost_id", string(ghostID)).Msg("Failed to send encrypted member profile") failed = true } } } if err = k.sendBridgeStatesAgain(ctx, roomID); err != nil { log.Err(err).Msg("Failed to send the bridge's encrypted room state") failed = true } if !failed { k.metaSent.Store(roomID, true) } return !failed } func (k *Kit) sendRoomMeta(ctx context.Context, roomID id.RoomID) error { _, err := k.sendRoomMetaWent(ctx, roomID) if errors.Is(err, errNoPortal) { // Spaces and management rooms have no metadata the app shows. return nil } return err } // errNoPortal is a room without a portal: a space or a management room, whose metadata the app does // not show. var errNoPortal = fmt.Errorf("%w: the room has no portal", errRoomMetaHeld) // sendRoomMetaWent is sendRoomMeta reporting whether the metadata went (false: it went before as it is // now), and a room without a portal as errNoPortal. func (k *Kit) sendRoomMetaWent(ctx context.Context, roomID id.RoomID) (bool, error) { portal, err := k.br.GetPortalByMXID(ctx, roomID) if err != nil { return false, err } else if portal == nil { return false, errNoPortal } // The portal is read under the room's lock: a send that read it before it changed would take the // lock after the send of the change, and send what it read over it (the send as the owner comes in, // and migrate's name of a moved group sent at once). lock := k.roomLock(roomID) lock.Lock() defer lock.Unlock() meta := roomMeta{V: 1, Network: k.network, Kind: "group"} if portal.RoomType == database.RoomTypeDM { meta.Kind = "dm" } if k.network == "email" { meta.Kind = "mail" } if portal.Name != "" { name := portal.Name meta.Name = &name } picture := &statePicture{avatar: &meta.Avatar, source: portal.AvatarMXC} return k.sendEncryptedStateWent(ctx, roomID, roomMetaType, "", &meta, picture) } func (k *Kit) sendMemberProfile(ctx context.Context, roomID id.RoomID, ghostID networkid.UserID) error { hashed := k.ghosts.hashed(ghostID) if hashed == "" { return errNoGhostKey } ghost, err := k.br.GetExistingGhostByID(ctx, ghostID) if err != nil || ghost == nil { return err } profile := memberProfile{V: 1, Handle: handleOf(ghost.Identifiers)} if ghost.Name != "" { name := ghost.Name profile.Displayname = &name } picture := &statePicture{avatar: &profile.Avatar, source: ghost.AvatarMXC} return k.sendEncryptedStateOnce(ctx, roomID, memberProfileType, hashed.String(), &profile, picture) } // handleOf reads a ghost's identifiers (tel:+82..., mailto:..., or a network's username scheme). func handleOf(identifiers []string) memberHandle { var handle memberHandle for _, identifier := range identifiers { scheme, value, ok := strings.Cut(identifier, ":") if !ok || value == "" { continue } switch scheme { case "tel": if handle.Phone == "" { handle.Phone = value } case "mailto": if handle.Email == "" { handle.Email = value } default: if handle.Username == "" { handle.Username = value } } } return handle } // ghostProfileChanged sends a ghost's new profile into the encrypted rooms its hashed ghost is in. func (k *Kit) ghostProfileChanged(ctx context.Context, g *ghostIntent) { if !k.active() || g.hashed == nil { return } go k.refreshMemberProfiles(k.backgroundContext(), g.id, g.hashed.Matrix.UserID) } func (k *Kit) refreshMemberProfiles(ctx context.Context, ghostID networkid.UserID, hashed id.UserID) { rooms, err := k.store.roomsOf(ctx, hashed, true) if err != nil { zerolog.Ctx(ctx).Err(err).Str("ghost_id", string(ghostID)).Msg("Failed to list the hashed ghost's rooms") return } for _, roomID := range rooms { if k.isEncrypted(ctx, roomID) { k.queueMemberProfile(ctx, roomID, ghostID) } } } // sendEncryptedStateOnce sends encrypted state unless the same content was the last sent under that // key, so that repeated syncs do not add events. The picture it shows is the copy its slot shows // (slotPicture), worked out while the room's metadata goes out one event at a time, so that a slot // never shows a copy again after another event of it let go of the copy. func (k *Kit) sendEncryptedStateOnce(ctx context.Context, roomID id.RoomID, eventType, stateKey string, content any, picture *statePicture) error { lock := k.roomLock(roomID) lock.Lock() defer lock.Unlock() return k.sendEncryptedStateLocked(ctx, roomID, eventType, stateKey, content, picture) } // sendEncryptedStateLocked is sendEncryptedStateOnce with the room's lock held. func (k *Kit) sendEncryptedStateLocked(ctx context.Context, roomID id.RoomID, eventType, stateKey string, content any, picture *statePicture) error { _, err := k.sendEncryptedStateWent(ctx, roomID, eventType, stateKey, content, picture) return err } // sendEncryptedStateWent is sendEncryptedStateLocked reporting whether the state went: false when the // same content was the last sent under that key. func (k *Kit) sendEncryptedStateWent(ctx context.Context, roomID id.RoomID, eventType, stateKey string, content any, picture *statePicture) (bool, error) { outerKey := eventType + ":" + stateKey if picture != nil { file, err := k.slotPicture(ctx, roomID, outerKey, picture.source) if err != nil { return false, err } *picture.avatar = file } data, mac, err := k.metaFingerprint(roomID, outerKey, content) if err != nil { return false, err } previous, err := k.store.sentMeta(ctx, roomID, outerKey) if err != nil { return false, err } else if previous == mac { return false, nil } if err = k.sendEncryptedState(ctx, roomID, event.Type{Type: eventType, Class: event.StateEventType}, stateKey, json.RawMessage(data)); err != nil { return false, err } if err = k.store.putSentMeta(ctx, roomID, outerKey, mac); err != nil { return false, err } return true, nil } // encryptedState is the state of the bridge's own of that type (Options.EncryptedState), if it is one. func (k *Kit) encryptedState(eventType event.Type) (EncryptedState, bool) { for _, state := range k.opts.EncryptedState { if state.Type.Type == eventType.Type { return state, true } } return EncryptedState{}, false } func bridgeStateKey(roomID id.RoomID, eventType event.Type) string { return string(roomID) + "\x00" + eventType.Type } // sendBridgeState sends state of the bridge's own (EncryptedState) into an encrypted room, and keeps it // to send again with the room's metadata. While the room's owner is not in the room it only keeps it, // held (heldState): the owner's devices get room keys only from then on, and it goes once they are // back (memberArrived, or sendHeldState when that failed), though the metadata went before the owner // left. What fails to go is not kept: the bridge keeps what it had (the mail bridge its portal's // labels), as does the room. func (k *Kit) sendBridgeState(ctx context.Context, roomID id.RoomID, state EncryptedState, stateKey string, content any) error { if stateKey != "" { return fmt.Errorf("%s goes under the empty state key", state.Type.Type) } data, err := json.Marshal(content) if err != nil { return err } lock := k.roomLock(roomID) lock.Lock() defer lock.Unlock() key := bridgeStateKey(roomID, state.Type) previous, hadPrevious := k.bridgeState.Load(key) k.bridgeState.Store(key, json.RawMessage(data)) if !k.ownerPresent(ctx, roomID) { k.heldState.Store(key, roomID) return nil } if err = k.sendEncryptedStateLocked(ctx, roomID, state.Type.Type, "", json.RawMessage(data), nil); err != nil { if hadPrevious { k.bridgeState.Store(key, previous) } else { k.bridgeState.Delete(key) } return err } k.heldState.Delete(key) return nil } // sendBridgeStatesAgain sends each of the room's states of the bridge's own again (sendBridgeStateAgain). func (k *Kit) sendBridgeStatesAgain(ctx context.Context, roomID id.RoomID) error { var errs []error for _, state := range k.opts.EncryptedState { if err := k.sendBridgeStateAgain(ctx, roomID, state); err != nil { errs = append(errs, fmt.Errorf("%s: %w", state.Type.Type, err)) } } return errors.Join(errs...) } // sendHeldState sends state of the bridge's own that waits to go (heldState): given while the room's // owner was away, or failed to go again since. What waits for an owner still away keeps waiting // (sendBridgeStateAgain). The watch of the switched-on users' keys (watchTrust) calls it when // encryption starts and every trustInterval after. func (k *Kit) sendHeldState(ctx context.Context) { rooms := map[id.RoomID]bool{} k.heldState.Range(func(_, roomID any) bool { rooms[roomID.(id.RoomID)] = true return true }) for roomID := range rooms { if err := k.sendBridgeStatesAgain(ctx, roomID); err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Msg("Failed to send the bridge's encrypted room state kept for the owner") } } } // sendBridgeStateAgain sends state of the bridge's own again: with the room's metadata (sendAllMeta), // once the room's owner is back (memberArrived), and while it waits to go (sendHeldState). What goes is // what the bridge last gave, or what the room's state says now (Current) when it gave none since it // started, or what it gave failed to go. While the owner is not in the room it waits instead, held // (heldState), and so does what fails to go: the bridge took it as given (the mail bridge recorded it in // its portal) and does not give it again until it changes. func (k *Kit) sendBridgeStateAgain(ctx context.Context, roomID id.RoomID, state EncryptedState) error { key := bridgeStateKey(roomID, state.Type) _, given := k.bridgeState.Load(key) read := !given for { var current json.RawMessage if read && state.Current != nil { // Read outside the room's lock: the bridge may give state holding a lock of its own (the mail // bridge's threadLock). content, err := state.Current(ctx, roomID) if err == nil && content != nil { current, err = json.Marshal(content) } if err != nil { k.heldState.Store(key, roomID) return err } } lock := k.roomLock(roomID) lock.Lock() // What the bridge gave meanwhile goes rather than what Current read before. data, given := k.bridgeState.Load(key) if !given && !read { // What the bridge gave failed to go meanwhile, and went with it: the room's state is read after all. lock.Unlock() read = true continue } err := k.sendBridgeStateAgainLocked(ctx, roomID, state, key, data, given, current) lock.Unlock() return err } } // sendBridgeStateAgainLocked is the send of sendBridgeStateAgain with the room's lock held: data when // the bridge gave it, current (what the room's state says, nil for none) when not. func (k *Kit) sendBridgeStateAgainLocked(ctx context.Context, roomID id.RoomID, state EncryptedState, key string, data any, given bool, current json.RawMessage) error { if !given { if current == nil { k.heldState.Delete(key) return nil } k.bridgeState.Store(key, current) data = current } if !k.ownerPresent(ctx, roomID) { // The owner left since: their devices would not get the room key. k.heldState.Store(key, roomID) return nil } if err := k.sendEncryptedStateLocked(ctx, roomID, state.Type.Type, "", data.(json.RawMessage), nil); err != nil { k.heldState.Store(key, roomID) return err } k.heldState.Delete(key) return nil } // statePicture is the picture an encrypted metadata event shows: its avatar in the content sent, set // from the picture as bridgev2 knows it ("" for none). type statePicture struct { avatar **event.EncryptedFileInfo source id.ContentURIString } // metaFingerprint is what an encrypted metadata event sends, and its keyed fingerprint: a plain hash of // a name or phone number could be checked against guesses by whoever reads the bridge database. func (k *Kit) metaFingerprint(roomID id.RoomID, outerKey string, content any) ([]byte, string, error) { data, err := json.Marshal(content) if err != nil { return nil, "", err } mac, err := k.store.metaMAC(roomID, outerKey, data) return data, mac, err } // sendEncryptedState encrypts a state event with the room's Megolm session (MSC4362: the plaintext // holds the inner type and state key) and sends it as the bridge bot. func (k *Kit) sendEncryptedState(ctx context.Context, roomID id.RoomID, eventType event.Type, stateKey string, content any) error { mach := k.machine() if mach == nil { return errNoCrypto } encrypted, err := mach.EncryptMegolmEventWithStateKey(ctx, roomID, eventType, &stateKey, content) if errors.Is(err, crypto.ErrSessionExpired) || errors.Is(err, crypto.ErrSessionNotShared) || errors.Is(err, crypto.ErrNoGroupSession) { users, usersErr := k.roomUsers(ctx, roomID) if usersErr != nil { return usersErr } if err = mach.ShareGroupSession(ctx, roomID, users); err != nil { return fmt.Errorf("failed to share group session: %w", err) } encrypted, err = mach.EncryptMegolmEventWithStateKey(ctx, roomID, eventType, &stateKey, content) } if err != nil { return fmt.Errorf("failed to encrypt state event: %w", err) } slot := eventType.Type + ":" + stateKey resp, err := k.conn.Bot.SendStateEvent(ctx, roomID, event.EventEncrypted, slot, encrypted) if err != nil { return err } // Its picture, or that it has none, is written down for the slot (mediarefs.go). Until that is // kept, the state does not count as sent and goes again. data, err := json.Marshal(content) if err == nil { err = k.noteState(ctx, roomID, resp.EventID, slot, data) } if err != nil { return fmt.Errorf("failed to keep the picture of encrypted state to write down: %w", err) } return nil } // roomUsers lists the room's members who get its keys: everybody joined or invited except the bot // and ghosts, as mautrix's own encryption does. func (k *Kit) roomUsers(ctx context.Context, roomID id.RoomID) ([]id.UserID, error) { members, err := k.conn.StateStore.GetRoomMembers(ctx, roomID, event.MembershipJoin, event.MembershipInvite) if err != nil { return nil, err } users := make([]id.UserID, 0, len(members)) for userID := range members { if userID == k.conn.Bot.UserID || k.ghosts.isHashedShape(userID) { continue } if _, isGhost := k.inner.ParseGhostMXID(userID); isGhost { continue } users = append(users, userID) } return users, nil }