// 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" "errors" "os" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/matrix" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // In an encrypted room a contact's ghost is the hashed one (ghostname.go). bridgev2 keeps thinking // in plaintext ghost MXIDs, so what goes to the server is translated to the hashed MXID (wireUser) // and what comes back to the plaintext one (bridgeUser). A hashed MXID cannot be turned back into a // network ID, so the bridge remembers each one it hands out (xessenger_ghost_hash, sealed). var errNoGhostKey = errors.New("room is encrypted, but the bridge has no ghost key") // ghostIntent is a contact's ghost with two identities: the plaintext one bridgev2 knows (named after // the network ID) for rooms that are not encrypted, and the hashed one for encrypted rooms. bridgev2 // keeps thinking in plaintext MXIDs; every call that names a room goes out as the identity that // room uses. type ghostIntent struct { kit *Kit id networkid.UserID legacy *matrix.ASIntent hashed *matrix.ASIntent } var _ bridgev2.MatrixAPI = (*ghostIntent)(nil) var _ bridgev2.MatrixAPIWithArbitraryRoomState = (*ghostIntent)(nil) func (k *Kit) newGhostIntent(userID networkid.UserID, legacy *matrix.ASIntent) *ghostIntent { ghost := &ghostIntent{kit: k, id: userID, legacy: legacy} if hashed := k.ghosts.hashed(userID); hashed != "" { ghost.hashed = &matrix.ASIntent{Matrix: k.conn.AS.Intent(hashed), Connector: k.conn} } return ghost } // pick returns the identity for a room. Without a ghost key nobody is switched on, so no room is // encrypted for this reason; an encrypted room that somehow has no hashed identity refuses rather // than reveal the plaintext ghost. func (g *ghostIntent) pick(ctx context.Context, roomID id.RoomID) (*matrix.ASIntent, bool, error) { if !g.kit.isEncrypted(ctx, roomID) { return g.legacy, false, nil } else if g.hashed == nil { return nil, true, errNoGhostKey } g.kit.rememberHashed(ctx, g.hashed.Matrix.UserID, g.id) // A hashed ghost is registered the first time a room needs it (mautrix remembers it). registering := Step(ctx, "ghost_register") err := g.hashed.Matrix.EnsureRegistered(ctx) registering() if err != nil { return nil, true, err } return g.hashed, true, nil } func (g *ghostIntent) GetMXID() id.UserID { return g.legacy.GetMXID() } func (g *ghostIntent) IsDoublePuppet() bool { return false } // joinFirst joins a room through EnsureJoined before the ghost sends there for the first time. // mautrix would join on its own while sending, without what EnsureJoined does here: the encrypted // profile of a hashed ghost, the withheld profile of a plaintext one. bridgev2 sends as a ghost that // has not joined when a contact outside the synced member list writes (a large group, a backfill). func (g *ghostIntent) joinFirst(ctx context.Context, roomID id.RoomID, intent *matrix.ASIntent) error { if g.kit.conn.StateStore.IsInRoom(ctx, roomID, intent.Matrix.UserID) { return nil } return g.EnsureJoined(ctx, roomID) } func (g *ghostIntent) SendMessage(ctx context.Context, roomID id.RoomID, eventType event.Type, content *event.Content, extra *bridgev2.MatrixSendExtra) (*mautrix.RespSendEvent, error) { intent, encrypted, err := g.pick(ctx, roomID) if err != nil { return nil, err } else if err = g.joinFirst(ctx, roomID, intent); err != nil { return nil, err } if encrypted { g.kit.rewriteContent(ctx, content) } files := g.kit.beforeSend(eventType, content) resp, err := intent.SendMessage(ctx, roomID, eventType, content, extra) if err == nil { g.kit.afterSend(ctx, roomID, files, resp, extra) } return resp, err } func (g *ghostIntent) SendState(ctx context.Context, roomID id.RoomID, eventType event.Type, stateKey string, content *event.Content, ts time.Time) (*mautrix.RespSendEvent, error) { if eventType == event.StateMember { defer Step(ctx, "ghost_membership")() } intent, encrypted, err := g.pick(ctx, roomID) if err != nil { return nil, err } // Its own membership is how a ghost joins; anything else waits until it has (as in mautrix). if eventType != event.StateMember || stateKey != string(g.legacy.GetMXID()) { if err = g.joinFirst(ctx, roomID, intent); err != nil { return nil, err } } if !encrypted { g.kit.plaintextStatePictures(ctx, roomID, intent, eventType, stateKey, content) return intent.SendState(ctx, roomID, eventType, stateKey, content, ts) } return g.kit.sendEncryptedRoomState(ctx, intent, roomID, eventType, stateKey, content, ts) } func (g *ghostIntent) MarkRead(ctx context.Context, roomID id.RoomID, eventID id.EventID, ts time.Time) error { intent, _, err := g.pick(ctx, roomID) if err != nil { return err } return intent.MarkRead(ctx, roomID, eventID, ts) } func (g *ghostIntent) MarkUnread(ctx context.Context, roomID id.RoomID, unread bool) error { intent, _, err := g.pick(ctx, roomID) if err != nil { return err } return intent.MarkUnread(ctx, roomID, unread) } func (g *ghostIntent) MarkTyping(ctx context.Context, roomID id.RoomID, typingType bridgev2.TypingType, timeout time.Duration) error { intent, _, err := g.pick(ctx, roomID) if err != nil { return err } return intent.MarkTyping(ctx, roomID, typingType, timeout) } func (g *ghostIntent) DownloadMedia(ctx context.Context, uri id.ContentURIString, file *event.EncryptedFileInfo) ([]byte, error) { return g.legacy.DownloadMedia(ctx, uri, file) } func (g *ghostIntent) DownloadMediaToFile(ctx context.Context, uri id.ContentURIString, file *event.EncryptedFileInfo, writable bool, callback func(*os.File) error) error { return g.legacy.DownloadMediaToFile(ctx, uri, file, writable, callback) } // UploadMedia uploads into a room as that room's identity. Without a room, while the contact is only // in encrypted rooms, nothing goes up as its plaintext ghost. Its picture (pictureUpload) is uploaded // encrypted, by the bot, so that neither the picture nor whose it is reaches the server: its key stays // sealed in the bridge database for the encrypted profile events, and a plaintext copy is made from // it only for a room that is not encrypted or a provisioning answer (provision.go). Anything else is // meant to be read without a key, like LINE's inline emoji, and the bot uploads it as it is. func (g *ghostIntent) UploadMedia(ctx context.Context, roomID id.RoomID, data []byte, fileName, mimeType string) (id.ContentURIString, *event.EncryptedFileInfo, error) { if roomID != "" { intent, _, err := g.pick(ctx, roomID) if err != nil { return "", nil, err } return intent.UploadMedia(ctx, roomID, data, fileName, mimeType) } if g.hashed == nil || !g.kit.active() || !g.kit.ready() || g.kit.ghostInPlaintextRoom(ctx, g.id, g.legacy.GetMXID()) { return g.legacy.UploadMedia(ctx, "", data, fileName, mimeType) } else if pictureUpload(fileName) { return g.kit.uploadEncryptedPicture(ctx, data, mimeType) } return g.kit.bot.ASIntent.UploadMedia(ctx, "", data, fileName, mimeType) } func (g *ghostIntent) UploadMediaStream(ctx context.Context, roomID id.RoomID, size int64, requireFile bool, cb bridgev2.FileStreamCallback) (id.ContentURIString, *event.EncryptedFileInfo, error) { if roomID == "" { return g.legacy.UploadMediaStream(ctx, roomID, size, requireFile, cb) } intent, _, err := g.pick(ctx, roomID) if err != nil { return "", nil, err } return intent.UploadMediaStream(ctx, roomID, size, requireFile, cb) } // SetDisplayName sets the plaintext ghost's global profile only while a plaintext room shows it; // encrypted rooms get the name in an encrypted profile event instead, and the hashed ghost never has // a profile. func (g *ghostIntent) SetDisplayName(ctx context.Context, name string) error { defer Step(ctx, "ghost_profile")() if err := g.setLegacyProfile(ctx, func() error { return g.legacy.SetDisplayName(ctx, name) }); err != nil { return err } g.kit.ghostProfileChanged(ctx, g) return nil } func (g *ghostIntent) SetAvatarURL(ctx context.Context, avatarURL id.ContentURIString) error { defer Step(ctx, "ghost_profile")() err := g.setLegacyProfile(ctx, func() error { plaintext, err := g.kit.plaintextPicture(ctx, g.legacy, avatarURL) if err != nil { return err } return g.legacy.SetAvatarURL(ctx, plaintext) }) if err != nil { return err } g.kit.ghostProfileChanged(ctx, g) return nil } func (g *ghostIntent) setLegacyProfile(ctx context.Context, set func() error) error { if !g.kit.active() || g.hashed == nil || g.kit.ghostInPlaintextRoom(ctx, g.id, g.legacy.GetMXID()) { return set() } return g.kit.store.setWithheld(ctx, g.hashed.Matrix.UserID, true) } // SetExtraProfileMeta follows a change of the contact's identifiers, which the encrypted profile // events carry as the handle. They never go to the homeserver's profile, which every room's members // can read, plaintext rooms included: bridgev2 passes them here because the bridge says the // homeserver takes extra profile fields (identifiers.go). func (g *ghostIntent) SetExtraProfileMeta(ctx context.Context, _ any) error { defer Step(ctx, "ghost_profile")() g.kit.ghostProfileChanged(ctx, g) return nil } func (g *ghostIntent) SetProfile(ctx context.Context, data any) error { if g.kit.active() && g.hashed != nil && !g.kit.ghostInPlaintextRoom(ctx, g.id, g.legacy.GetMXID()) { return g.kit.store.setWithheld(ctx, g.hashed.Matrix.UserID, true) } return g.legacy.SetProfile(ctx, data) } func (g *ghostIntent) CreateRoom(ctx context.Context, req *mautrix.ReqCreateRoom) (id.RoomID, error) { return g.kit.createRoom(ctx, g.legacy, req) } func (g *ghostIntent) DeleteRoom(ctx context.Context, roomID id.RoomID, puppetsOnly bool) error { intent, _, err := g.pick(ctx, roomID) if err != nil { return err } return intent.DeleteRoom(ctx, roomID, puppetsOnly) } // EnsureJoined joins a room as its identity. A hashed ghost joining an encrypted room then sends // its encrypted profile there; a plaintext ghost whose profile was withheld gets it set first, so // its join shows its name as before. func (g *ghostIntent) EnsureJoined(ctx context.Context, roomID id.RoomID, params ...bridgev2.EnsureJoinedParams) error { defer Step(ctx, "ghost_join")() intent, encrypted, err := g.pick(ctx, roomID) if err != nil { return err } if !encrypted { g.kit.restoreWithheldProfile(ctx, g) return intent.EnsureJoined(ctx, roomID, params...) } alreadyJoined := g.kit.conn.StateStore.IsInRoom(ctx, roomID, intent.Matrix.UserID) if err = intent.EnsureJoined(ctx, roomID, params...); err != nil { return err } if !alreadyJoined { profiled := Step(ctx, "member_profile") g.kit.queueMemberProfile(ctx, roomID, g.id) profiled() } return nil } func (g *ghostIntent) EnsureInvited(ctx context.Context, roomID id.RoomID, userID id.UserID) error { intent, encrypted, err := g.pick(ctx, roomID) if err != nil { return err } if encrypted { userID = g.kit.wireUser(ctx, userID) } return intent.EnsureInvited(ctx, roomID, userID) } func (g *ghostIntent) TagRoom(ctx context.Context, roomID id.RoomID, tag event.RoomTag, isTagged bool) error { intent, _, err := g.pick(ctx, roomID) if err != nil { return err } return intent.TagRoom(ctx, roomID, tag, isTagged) } func (g *ghostIntent) MuteRoom(ctx context.Context, roomID id.RoomID, until time.Time) error { intent, _, err := g.pick(ctx, roomID) if err != nil { return err } return intent.MuteRoom(ctx, roomID, until) } func (g *ghostIntent) GetEvent(ctx context.Context, roomID id.RoomID, eventID id.EventID) (*event.Event, error) { intent, _, err := g.pick(ctx, roomID) if err != nil { return nil, err } return intent.GetEvent(ctx, roomID, eventID) } func (g *ghostIntent) GetStateEvent(ctx context.Context, roomID id.RoomID, eventType event.Type, stateKey string) (*event.Event, error) { intent, encrypted, err := g.pick(ctx, roomID) if err != nil { return nil, err } if encrypted && eventType == event.StateMember { stateKey = g.kit.wireUser(ctx, id.UserID(stateKey)).String() } evt, err := intent.GetStateEvent(ctx, roomID, eventType, stateKey) if encrypted && evt != nil { g.kit.readState(ctx, evt) } return evt, err } // ghostInPlaintextRoom reports whether the plaintext ghost is in a room that is not encrypted, where // its global profile is what shows its name. A failed check counts as yes: the profile is then set // as it always was. func (k *Kit) ghostInPlaintextRoom(ctx context.Context, ghostID networkid.UserID, legacy id.UserID) bool { rooms, err := k.store.roomsOf(ctx, legacy, true) if err != nil { zerolog.Ctx(ctx).Err(err).Str("ghost_id", string(ghostID)).Msg("Failed to list the ghost's rooms") return true } for _, roomID := range rooms { if !k.isEncrypted(ctx, roomID) { return true } } return false } // restoreWithheldProfile sets the plaintext ghost's global profile that was withheld while only // encrypted rooms had the contact, before the ghost joins a plaintext room. func (k *Kit) restoreWithheldProfile(ctx context.Context, g *ghostIntent) { if !k.active() || g.hashed == nil { return } withheld, err := k.store.isWithheld(ctx, g.hashed.Matrix.UserID) if err != nil || !withheld { return } ghost, err := k.br.GetExistingGhostByID(ctx, g.id) if err != nil || ghost == nil { return } log := zerolog.Ctx(ctx).With().Str("ghost_id", string(g.id)).Logger() if ghost.Name != "" { if err = g.legacy.SetDisplayName(ctx, ghost.Name); err != nil { log.Err(err).Msg("Failed to set withheld ghost name") return } } if ghost.AvatarMXC != "" { plaintext, err := k.plaintextPicture(ctx, g.legacy, ghost.AvatarMXC) if err == nil { err = g.legacy.SetAvatarURL(ctx, plaintext) } if err != nil { log.Err(err).Msg("Failed to set withheld ghost avatar") return } } if err = k.store.setWithheld(ctx, g.hashed.Matrix.UserID, false); err != nil { log.Err(err).Msg("Failed to clear withheld ghost profile mark") } } func (k *Kit) rememberHashed(ctx context.Context, hashed id.UserID, ghostID networkid.UserID) { if _, ok := k.knownHashes.Load(hashed); ok { return } if err := k.store.putGhostHash(ctx, hashed, ghostID); err != nil { zerolog.Ctx(ctx).Err(err).Str("ghost_id", string(ghostID)).Msg("Failed to save hashed ghost") return } k.knownHashes.Store(hashed, ghostID) } // legacyGhost returns the plaintext MXID of a hashed ghost, "" when it is not one. func (k *Kit) legacyGhost(ctx context.Context, userID id.UserID) id.UserID { ghostID, ok := k.hashedGhostID(ctx, userID) if !ok { return "" } return k.inner.FormatGhostMXID(ghostID) } func (k *Kit) hashedGhostID(ctx context.Context, userID id.UserID) (networkid.UserID, bool) { if !k.ghosts.isHashedShape(userID) { return "", false } if ghostID, ok := k.knownHashes.Load(userID); ok { return ghostID.(networkid.UserID), true } ghostID, err := k.store.ghostByHash(ctx, userID) if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("user_id", userID).Msg("Failed to look up hashed ghost") return "", false } else if ghostID == "" { return "", false } k.knownHashes.Store(userID, ghostID) return ghostID, true } // wireUser is the MXID a user is known by in an encrypted room: a plaintext ghost becomes its // hashed ghost, anybody else stays. func (k *Kit) wireUser(ctx context.Context, userID id.UserID) id.UserID { if k.ghosts.isHashedShape(userID) { return userID } ghostID, ok := k.inner.ParseGhostMXID(userID) if !ok { return userID } hashed := k.ghosts.hashed(ghostID) if hashed == "" { return userID } k.rememberHashed(ctx, hashed, ghostID) return hashed } // bridgeUser is the MXID bridgev2 knows a user in an encrypted room by: a hashed ghost becomes the // plaintext ghost. hide is true for a plaintext ghost still in an encrypted room from before it was // switched on, which bridgev2 should not see there (its hashed ghost stands in for it). func (k *Kit) bridgeUser(ctx context.Context, userID id.UserID) (bridgeID id.UserID, hide bool) { if legacy := k.legacyGhost(ctx, userID); legacy != "" { return legacy, false } if _, isGhost := k.inner.ParseGhostMXID(userID); isGhost { return userID, true } return userID, false }