// 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" "fmt" "reflect" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2/matrix" "maunium.net/go/mautrix/crypto" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // cryptoHook wraps bridgev2's end-to-bridge encryption so that, each time it (re)initializes, the // extension gets hold of its Olm machine: to encrypt state events, to keep reply and reaction // targets inside the ciphertext (MSC4392), to read the identities of the users it switches on, and to // encrypt what the bot sends without the intents (message statuses, error notices). type cryptoHook struct { matrix.Crypto kit *Kit } func (c *cryptoHook) Init(ctx context.Context) error { if err := c.Crypto.Init(ctx); err != nil { return err } return c.kit.cryptoReady(ctx, c.Crypto) } // Reset starts the syncer itself, after the extension has wrapped the new client's syncer. func (c *cryptoHook) Reset(ctx context.Context, startAfterReset bool) error { err := c.Crypto.Reset(ctx, false) if readyErr := c.kit.cryptoReady(ctx, c.Crypto); err == nil { err = readyErr } if err == nil && startAfterReset { go c.Crypto.Start() } return err } func (k *Kit) cryptoReady(ctx context.Context, inner matrix.Crypto) error { log := zerolog.Ctx(ctx) client := inner.Client() mach := machineOf(client) if mach == nil { k.mach.Store(nil) log.Error().Msg("Could not reach the bridge's Olm machine; nobody can be switched on") return nil } mach.MSC4392Relations = k.main.Config.Encryption.MSC4392 // State the user's app sends encrypted (MSC4362: a group's new name, for instance) keeps its // state key once decrypted, so bridgev2 handles it as the state event it is. mach.AllowEncryptedState = true k.mach.Store(mach) k.conn.Bot.Crypto = &botCrypto{inner: inner} if _, wrapped := client.Syncer.(*identitySyncer); !wrapped { client.Syncer = &identitySyncer{Syncer: client.Syncer, kit: k, mach: mach} } if err := k.distrustHolders(ctx, machineCrypto{mach: mach}); err != nil { k.mach.Store(nil) return fmt.Errorf("failed to keep the holders' devices untrusted: %w", err) } if err := k.distrustWaitingMembers(ctx, machineCrypto{mach: mach}); err != nil { k.mach.Store(nil) return fmt.Errorf("failed to keep the devices of members not switched on untrusted: %w", err) } go k.watchTrust(k.backgroundContext(), mach) // The identifiers of the ghosts made before the bridge kept them, and their profiles again (identifiers.go). go k.fillIdentifiers(k.backgroundContext()) // What extensions wait on encryption for (WhenEncrypting). k.runWhenEncrypting() // What waits to be written down since before the bridge stopped (mediarefs.go). k.refs.startSending(k.backgroundContext()) return nil } // machineOf finds the Olm machine bridgev2 keeps inside its crypto client's syncer, which embeds it. func machineOf(client *mautrix.Client) *crypto.OlmMachine { if client == nil || client.Syncer == nil { return nil } syncer := client.Syncer if wrapped, ok := syncer.(*identitySyncer); ok { syncer = wrapped.Syncer } value := reflect.ValueOf(syncer) if value.Kind() == reflect.Pointer { value = value.Elem() } if value.Kind() != reflect.Struct { return nil } field := value.FieldByName("OlmMachine") if !field.IsValid() || !field.CanInterface() { return nil } mach, _ := field.Interface().(*crypto.OlmMachine) return mach } // botCrypto lets the bot's own client encrypt what it sends outside the intents in encrypted // rooms (bridgev2 sends message statuses and error notices that way); mautrix's client calls it for // rooms its state store knows to be encrypted. type botCrypto struct { inner matrix.Crypto } var _ mautrix.CryptoHelper = (*botCrypto)(nil) func (b *botCrypto) Encrypt(ctx context.Context, roomID id.RoomID, eventType event.Type, content any) (*event.EncryptedEventContent, error) { wrapped := &event.Content{Parsed: content} if original, ok := content.(*event.Content); ok { copied := *original wrapped = &copied } if err := b.inner.Encrypt(ctx, roomID, eventType, wrapped); err != nil { return nil, err } encrypted, ok := wrapped.Parsed.(*event.EncryptedEventContent) if !ok { return nil, errors.New("encryption returned no encrypted content") } return encrypted, nil } func (b *botCrypto) Decrypt(ctx context.Context, evt *event.Event) (*event.Event, error) { return b.inner.Decrypt(ctx, evt) } func (b *botCrypto) WaitForSession(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, timeout time.Duration) bool { return b.inner.WaitForSession(ctx, roomID, senderKey, sessionID, timeout) } func (b *botCrypto) RequestSession(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, userID id.UserID, deviceID id.DeviceID) { b.inner.RequestSession(ctx, roomID, senderKey, sessionID, userID, deviceID) } func (b *botCrypto) Init(context.Context) error { return nil }