// 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 is the extension every Xessenger bridge runs with (QA-289). // // A bridge installs it with one call before Run (its main.go patch), and it attaches itself once // bridgev2 has been set up: it serves the extension API at /_xessenger/v1/ on the appservice port, // behind the provisioning secret (api.go). It needs no change to mautrix-go. // // It also turns end-to-end encryption on per Matrix user instead of per bridge // (docs/e2ee/work-plan.md 4.2-4.5): the rooms created for a user who is switched on get // m.room.encryption, so bridgev2 encrypts their messages and files, while everybody else's rooms // stay as they are. In those rooms room names, pictures and profiles travel only as encrypted state // events (MSC4362's shape, meta.go), and the bridge drops whatever the user's Matrix account sends // there unencrypted, which the server could otherwise send in the user's name (refuse.go). For that // it wraps the Matrix connector, the bridge bot and the users' double puppets (connector.go, // intents.go). With nobody switched on, every wrapped call passes through unchanged. // // What the bridge database keeps about encrypted rooms is sealed with a key only the bridge's enclave // can derive (keys.go, store.go). package bridgekit import ( "context" "crypto/subtle" "errors" "fmt" "net/http" "os" "strings" "sync" "sync/atomic" "github.com/rs/zerolog" "go.mau.fi/util/dbutil" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/commands" "maunium.net/go/mautrix/bridgev2/matrix" "maunium.net/go/mautrix/bridgev2/matrix/mxmain" "maunium.net/go/mautrix/crypto" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" "xessenger/bridgekit/internal/storeseal" ) // Extension adds routes under /_xessenger/v1/. The router receives requests whose provisioning secret // has been checked, with their full path. type Extension func(br *bridgev2.Bridge, router *http.ServeMux) // Options configure Install. Without keys, Install derives them from the bridge's own key // (XESSENGER_SEAL_KEY_FILE, keys.go); a bridge without that key runs with nobody switched on. type Options struct { // GhostKey is the bridge's ghost_hmac_key, 32 bytes only its enclave can open. Without it nobody // can be switched on: their contacts would keep ghosts named after phone numbers and addresses. GhostKey []byte // StoreKey seals what the bridge database keeps about encrypted rooms, 32 bytes. Without it // nobody can be switched on either. StoreKey []byte // Extensions are installed once the bridge is set up, in order. Extensions []Extension // Methods are what the app may ask of the bridge over Olm besides the extension's own (requests.go). Methods []Method // EncryptedState is room state of the bridge's own that an encrypted room carries only encrypted // (meta.go). EncryptedState []EncryptedState } // EncryptedState is room state of the bridge's own whose content is the user's, as a mail room's // labels, sent under the empty state key. An encrypted room carries it as it carries its metadata // (meta.go): encrypted by the bot's Megolm session (MSC4362), never in plaintext, sent while the room's // owner is in it and again whenever the metadata goes again. A room that is not encrypted gets it in // plaintext, as the bridge sent it. type EncryptedState struct { Type event.Type // Current is what the room's state says now, nil for none: what the bridge sends with the room's // metadata when it has not sent the state there since it started (a room the history move made, the // bridge started again). It is asked without the room's lock, as the bridge may send into the room // while it holds locks of its own. Current func(ctx context.Context, roomID id.RoomID) (any, error) } // Kit is the installed extension of one bridge. type Kit struct { opts Options main *mxmain.BridgeMain br *bridgev2.Bridge conn *matrix.Connector log zerolog.Logger db *dbutil.Database // network is the bridge's appservice ID (whatsapp, instagram, facebook, telegram, line, email). network string ghosts *ghostNames box *storeseal.Sealer store *store // refs writes down the files of encrypted rooms at the API (mediarefs.go), nil without its URL. refs *mediaRefs // identifiersFilled is set once the ghosts' identifiers are being filled in (identifiers.go). identifiersFilled atomic.Bool // whenEncrypting are what extensions run once the bridge's encryption runs (WhenEncrypting), under // whenEncryptingLock. whenEncrypting []func(ctx context.Context) whenEncryptingLock sync.Mutex // inner is bridgev2's own Matrix connector, which the wrapper in Bridge.Matrix calls through. inner bridgev2.MatrixConnector bot *botIntent crypto *cryptoHook mach atomic.Pointer[crypto.OlmMachine] // enabled counts the users switched on: with none, every check below is skipped. enabled atomic.Int64 users sync.Map // id.UserID -> *e2eeUser, replaced (never changed) under userLock members sync.Map // id.UserID -> loginMembers of a switched-on user, replaced under userLock (members.go) userLock sync.Mutex encrypted sync.Map // id.RoomID -> true, once a room is known to be encrypted (it never stops) trustLock sync.Mutex // one trust check at a time (trust.go) told map[id.UserID]toldReset // devices told about each waiting reset, under trustLock knownHashes sync.Map // id.UserID (hashed ghost) -> networkid.UserID portalKeys sync.Map // id.RoomID (deterministic local room ID) -> pendingPortal owners sync.Map // id.RoomID -> id.UserID, the switched-on user an encrypted room belongs to newRooms sync.Map // id.RoomID -> newRoom, a portal's room made, until bridgev2 is seen to have it (members.go) metaSent sync.Map // id.RoomID -> true once the room's metadata and member profiles went out metaLock sync.Map // id.RoomID -> *sync.Mutex // bridgeState is the content last given of each room's state of the bridge's own (EncryptedState), // keyed by bridgeStateKey, for sending it again with the room's metadata. bridgeState sync.Map // heldState has the keys (bridgeStateKey) of what of it waits to go, each with its room: given while // the room's owner was away, or failed to go again. memberArrived and sendHeldState send it. heldState sync.Map memberSyncs sync.Map // id.UserID -> *memberSync, bringing a user's rooms in line with their members memberLocks sync.Map // id.RoomID -> *sync.Mutex, held while the room's members are brought in line (members.go) // history sends the keys of rooms to the identities who read them late (history.go). history historySend // methods are the requests the app may make over Olm by name, and requestSlots holds one value for // each being answered (requests.go). methods map[string]Method requestSlots chan struct{} } // ErrNotReady is returned while the bridge has not attached the extension yet. var ErrNotReady = errors.New("bridgekit is not attached yet") // Install makes the bridge run with the extension. It must be called before m.Run: it attaches // itself in PostInit, after any PostInit the bridge set. func Install(m *mxmain.BridgeMain, opts Options) *Kit { kit := &Kit{opts: opts, main: m} previousInit := m.PostInit m.PostInit = func() { if previousInit != nil { previousInit() } if err := kit.attach(); err != nil { m.Log.WithLevel(zerolog.FatalLevel).Err(err).Msg("Failed to install the Xessenger bridge extension") os.Exit(19) } } return kit } func (k *Kit) attach() error { m := k.main if m.Bridge == nil || m.Matrix == nil || m.Config == nil { return ErrNotReady } k.br, k.conn, k.db = m.Bridge, m.Matrix, m.DB k.log = m.Log.With().Str("component", "xessenger").Logger() k.network = m.Config.AppService.ID k.inner = m.Bridge.Matrix botAS, ok := m.Bridge.Bot.(*matrix.ASIntent) if !ok { return fmt.Errorf("unexpected bridge bot type %T", m.Bridge.Bot) } ctx := k.log.WithContext(context.Background()) keySource := "options" if k.opts.GhostKey == nil && k.opts.StoreKey == nil { ghostKey, storeKey, err := sealedKeys(k.network) if err != nil { return err } keySource = "seal key" if ghostKey == nil { // Without its key, an unsealed bridge reads the keys unsealing left in its kv_store. if ghostKey, storeKey, err = unsealedKeys(ctx, k.db, k.br.DB.KV); err != nil { return err } keySource = "kv_store" } if ghostKey == nil { keySource = "none" } k.opts.GhostKey, k.opts.StoreKey = ghostKey, storeKey } var err error if k.ghosts, err = newGhostNames(m.Config, k.opts.GhostKey); err != nil { return err } if k.box, err = storeseal.New(k.opts.StoreKey); err != nil { return err } k.store = newStore(k.db, k.br.ID, k.box, k.log) if err = k.store.upgrade(ctx); err != nil { return fmt.Errorf("failed to upgrade the xessenger tables: %w", err) } // Room metadata the network's mautrix-go sent with its empty state key left out goes again (meta.go). k.noteRoomMetaAgain(ctx) users, err := k.store.enabledUsers(ctx) if err != nil { return fmt.Errorf("failed to load switched-on users: %w", err) } if len(users) > 0 && !k.ready() { // Their rooms are encrypted: going on without the keys would name contacts by phone number // and address in them, or leave their messages unencrypted. return fmt.Errorf("%d users are switched on, but the ghost or store key is missing or encryption is off", len(users)) } if api := os.Getenv(apiURLEnv); api != "" { if k.refs, err = newMediaRefs(k, api, m.Config.Provisioning.SharedSecret); err != nil { k.log.Err(err).Msg("The files of encrypted rooms cannot be written down; nobody can be switched on") } } if len(users) > 0 && k.refs == nil { // Their rooms stay encrypted; their files wait to be written down until the URL is set. k.log.Error().Msgf("%d users are switched on, but %s is not set: the files of their rooms are not written down for deletion", len(users), apiURLEnv) } // The members first, as a switch-on keeps them (members.go). if err = k.loadMembers(ctx); err != nil { return err } for _, user := range users { k.users.Store(user.MXID, user) } k.enabled.Store(int64(len(users))) if m.Config.Encryption.Allow && (!k.ghosts.hashing() || !k.box.Ready()) { // Without the bridge's seal key (or the keys an unsealed bridge keeps) the bot's Olm account // and cross-signing keys would be stored unsealed (bridge-seal), and nobody could be switched // on anyway: the bridge runs without encryption until the key is there. k.log.Warn().Msg("The bridge has no seal key and no unsealed keys; running without encryption") m.Config.Encryption.Allow, m.Config.Encryption.Default, m.Config.Encryption.Require = false, false, false k.conn.Crypto = nil } k.bot = &botIntent{kit: k, ASIntent: botAS} m.Bridge.Matrix = &connector{Connector: k.conn, kit: k} k.keepIdentifiers() m.Bridge.Bot = k.bot if k.conn.Crypto != nil { k.crypto = &cryptoHook{Crypto: k.conn.Crypto, kit: k} k.conn.Crypto = k.crypto } k.installRefusal() // After the refusal, to run before it (membersend.go). k.installMemberEvents() // Last, to read the events before anything changes them (mediarefs.go). k.installMediaRefs() // What the app may ask over Olm (requests.go). k.installRequests() k.replaceCommands() router := http.NewServeMux() k.routes(router) if err := k.secureLogins(); err != nil { return err } for _, extension := range k.opts.Extensions { extension(k.br, router) } k.conn.AS.Router.Handle("/_xessenger/v1/", k.authenticate(router)) k.wrapProvisioning(k.conn.AS.Router) k.log.Info(). Int("switched_on_users", len(users)). Str("keys", keySource). Bool("ghost_key", k.ghosts.hashing()). Bool("store_key", k.box.Ready()). Bool("encryption", k.conn.Crypto != nil). Msg("Xessenger bridge extension attached") return nil } // replaceCommands replaces the bridgev2 commands that assert the bridge's Matrix connector, bot or a // double puppet is bridgev2's own type, which the extension now wraps: discard-megolm-session, // set-pl and ping-matrix (bridgev2/matrix/cmdadmin.go, cmddoublepuppet.go). The command processor // recovers their panics, but the commands would fail. func (k *Kit) replaceCommands() { proc, ok := k.br.Commands.(*commands.Processor) if !ok { return } discard := *matrix.CommandDiscardMegolmSession discard.Func = func(ce *commands.Event) { if k.conn.Crypto == nil { ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled") return } k.conn.Crypto.ResetSession(ce.Ctx, ce.RoomID) ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from the remote network.") } setPowerLevel := *matrix.CommandSetPowerLevel setPowerLevelFunc := setPowerLevel.Func setPowerLevel.Func = func(ce *commands.Event) { ce.Bot = k.bot.ASIntent setPowerLevelFunc(ce) } ping := *matrix.CommandPingMatrix ping.Func = func(ce *commands.Event) { var puppet *matrix.ASIntent switch intent := ce.User.DoublePuppet(ce.Ctx).(type) { case *userIntent: puppet = intent.ASIntent case *matrix.ASIntent: puppet = intent } if puppet == nil { ce.Reply("You don't have double puppeting enabled.") return } resp, err := puppet.Matrix.Whoami(ce.Ctx) if err != nil { ce.Reply("Failed to validate Matrix login: %v", err) } else if puppet.Matrix.SetAppServiceUserID && resp.DeviceID == "" { ce.Reply("Confirmed valid access token for %s (appservice double puppeting)", resp.UserID) } else { ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID) } } proc.AddHandlers(&discard, &setPowerLevel, &ping) } // ready reports whether users can be switched on: both keys are there and the bridge has // encryption allowed. func (k *Kit) ready() bool { return k.ghosts.hashing() && k.box.Ready() && k.main.Config.Encryption.Allow } // active reports whether anybody is switched on. func (k *Kit) active() bool { return k.enabled.Load() > 0 } // user returns a switched-on user, nil for anybody else. func (k *Kit) user(mxid id.UserID) *e2eeUser { if !k.active() { return nil } value, ok := k.users.Load(mxid) if !ok { return nil } return value.(*e2eeUser) } // isEncrypted reports whether a room is encrypted, which in this bridge means it belongs to a // switched-on user: bridgev2 then encrypts what it sends there, and the extension routes ghosts, // metadata and checks for that room. func (k *Kit) isEncrypted(ctx context.Context, roomID id.RoomID) bool { if roomID == "" || !k.active() { return false } if _, ok := k.encrypted.Load(roomID); ok { return true } encrypted, err := k.conn.StateStore.IsEncrypted(ctx, roomID) if err != nil { // A room whose state cannot be read is treated as encrypted: sending a contact's real // ghost or a plaintext name there could not be taken back. zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Msg("Failed to check if room is encrypted, treating it as encrypted") return true } if encrypted { k.encrypted.Store(roomID, true) } return encrypted } func (k *Kit) markEncrypted(roomID id.RoomID) { k.encrypted.Store(roomID, true) } // machine returns the bridge's Olm machine, nil until end-to-bridge encryption has started. func (k *Kit) machine() *crypto.OlmMachine { return k.mach.Load() } func (k *Kit) roomLock(roomID id.RoomID) *sync.Mutex { lock, _ := k.metaLock.LoadOrStore(roomID, &sync.Mutex{}) return lock.(*sync.Mutex) } // backgroundContext is a context for work that outlives the request that started it. func (k *Kit) backgroundContext() context.Context { if k.br.BackgroundCtx != nil { return k.log.WithContext(k.br.BackgroundCtx) } return k.log.WithContext(context.Background()) } // authenticate accepts only the provisioning shared secret. The provisioning API also takes Matrix // access tokens, which the server can mint for anyone, so they are not accepted here. func (k *Kit) authenticate(next http.Handler) http.Handler { secret := k.main.Config.Provisioning.SharedSecret return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if len(secret) < 16 || secret == "disable" || !ok || subtle.ConstantTimeCompare([]byte(token), []byte(secret)) != 1 { writeError(w, http.StatusUnauthorized, "M_UNKNOWN_TOKEN", "Invalid provisioning secret") return } next.ServeHTTP(w, r) }) }