// 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" "time" "maunium.net/go/mautrix/crypto" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // A switched-on user's master key is pinned when they are switched on (mautrix TOFU). When the // homeserver shows another one, mautrix trusts none of the new identity's devices, so they get no room // keys and their messages are dropped. The server can make such a reset itself with the password it // keeps, so the bridge accepts a new master key only with a proof the server cannot make (work plan // 4.2 ⑥): // // - a signature on the new master key by the pinned identity: the pinned master key, or a device the // pinned identity cross-signed. Accepted at once. // - a proof through the messenger (a code sent to the user's own chat, or signing in to the messenger // again), and 72 hours from when the new key was first seen without a rejection. // // Time alone never accepts a key. A key nothing proves is dropped after 30 days (seen again, it starts // a new wait). The devices the pinned identity cross-signed are told about the new key with an Olm // to-device com.xessenger.identity_change, and a com.xessenger.identity_reject from one of them over // Olm drops the key for good. So does accepting a new key for the pinned one it replaces: the // homeserver could show the old master key again with the signatures it once carried, among them a // device's that the new identity cross-signs too, and the devices the old identity cross-signed (one // the user reset to drop) would be trusted again. const ( // identityWait is how long a proved reset waits for a rejection before it is accepted. identityWait = 72 * time.Hour // identityExpiry is how long a reset nothing proves waits before it is dropped. identityExpiry = 30 * 24 * time.Hour proofCodeSent = "code_sent" proofRelogin = "relogin" proofVerified = "verified" ) var ( eventIdentityChange = event.Type{Type: "com.xessenger.identity_change", Class: event.ToDeviceEventType} eventIdentityReject = event.Type{Type: "com.xessenger.identity_reject", Class: event.ToDeviceEventType} errNotEnabled = errors.New("the user is not switched on") errKeyRejected = errors.New("this master key was rejected, or a newer identity replaced it") ) // identityChangeContent tells a device of the pinned identity that the bridge holds a new master key. // The app warns when it did not make the reset itself and answers with identityRejectContent. Bridge // is the bridge's appservice ID (whatsapp, instagram, facebook, telegram, line, email), as the API // names the bridges. type identityChangeContent struct { Version int `json:"v"` Bridge string `json:"bridge"` UserID id.UserID `json:"user_id"` PinnedMasterKey id.Ed25519 `json:"pinned_master_key"` MasterKey id.Ed25519 `json:"master_key"` FirstSeenAt int64 `json:"first_seen_at"` AcceptAfter int64 `json:"accept_after"` } // identityRejectContent rejects a new master key: from a device of the pinned identity, over Olm. type identityRejectContent struct { Version int `json:"v"` Bridge string `json:"bridge"` MasterKey id.Ed25519 `json:"master_key"` } // identityChanged handles a switched-on user whose master key is not the pinned one. Called with // trustLock held. func (k *Kit) identityChanged(ctx context.Context, c identityCrypto, user *e2eeUser, master id.Ed25519) error { if master == "" { // No cross-signing keys at all: nothing to accept, and no device is trusted. return nil } if rejected, err := k.store.isRejected(ctx, user.MXID, master); err != nil || rejected { return err } now := time.Now() reset, err := k.store.identityReset(ctx, user.MXID) if err != nil { return fmt.Errorf("failed to read the waiting reset: %w", err) } if reset != nil && reset.MasterKey == master && now.After(reset.FirstSeenAt.Add(identityExpiry)) { k.log.Info().Stringer("user_id", user.MXID).Msg("Dropping a new master key nothing proved in 30 days") if err = k.store.deleteIdentityReset(ctx, user.MXID); err != nil { return err } reset = nil } if reset == nil || reset.MasterKey != master { reset = &identityReset{MXID: user.MXID, MasterKey: master, FirstSeenAt: now} if err = k.store.putIdentityReset(ctx, reset); err != nil { return fmt.Errorf("failed to save the waiting reset: %w", err) } k.log.Info().Stringer("user_id", user.MXID).Stringer("master_key", master). Msg("A switched-on user's master key changed; holding it until it is proved") } pinnedDevices, err := k.store.trustedDevices(ctx, user.MXID) if err != nil { return fmt.Errorf("failed to read the pinned identity's devices: %w", err) } if signed, err := signedByPinned(ctx, c, user, master, pinnedDevices); err != nil { return fmt.Errorf("failed to read the signatures on the new master key: %w", err) } else if signed { return k.acceptIdentity(ctx, c, user, reset, "signed by the pinned identity") } if reset.Proof == proofVerified && !now.Before(reset.FirstSeenAt.Add(identityWait)) { return k.acceptIdentity(ctx, c, user, reset, "proved through the messenger") } if reset.NotifiedAt.IsZero() && k.notifyIdentityChange(ctx, c, user, reset, pinnedDevices) { reset.NotifiedAt = now if err = k.store.putIdentityReset(ctx, reset); err != nil { return fmt.Errorf("failed to save the waiting reset: %w", err) } } return nil } // dropWaitingReset forgets the new master key that waited once the homeserver shows the pinned one // again, so that status no longer reports it; seen again later, it starts a new wait. Called with // trustLock held. func (k *Kit) dropWaitingReset(ctx context.Context, user *e2eeUser) error { reset, err := k.store.identityReset(ctx, user.MXID) if err != nil { return fmt.Errorf("failed to read the waiting reset: %w", err) } else if reset == nil { return nil } k.log.Info().Stringer("user_id", user.MXID).Stringer("master_key", reset.MasterKey). Msg("The homeserver shows the pinned master key again; forgetting the new one that waited") if err = k.store.deleteIdentityReset(ctx, user.MXID); err != nil { return fmt.Errorf("failed to drop the waiting reset: %w", err) } return nil } // signedByPinned reports whether the new master key carries a signature by the pinned identity: the // pinned master key, or a device the pinned identity cross-signed, under the key the extension saw it // trusted with. func signedByPinned(ctx context.Context, c identityCrypto, user *e2eeUser, master id.Ed25519, pinnedDevices map[id.DeviceID]id.Ed25519) (bool, error) { signers := make([]keySigner, 0, len(pinnedDevices)+1) if user.PinnedMasterKey != "" { signers = append(signers, keySigner{Name: user.PinnedMasterKey.String(), Key: user.PinnedMasterKey}) } for deviceID, key := range pinnedDevices { signers = append(signers, keySigner{Name: deviceID.String(), Key: key}) } if len(signers) == 0 { return false, nil } return c.MasterKeySignedBy(ctx, user.MXID, master, signers) } // acceptIdentity makes the new master key the pinned one: mautrix trusts its devices from now on, and // the next message in each room shared with the user starts a session that reaches them. func (k *Kit) acceptIdentity(ctx context.Context, c identityCrypto, user *e2eeUser, reset *identityReset, why string) error { if err := c.AcceptMasterKey(ctx, user.MXID, reset.MasterKey); err != nil { return fmt.Errorf("failed to trust the new master key: %w", err) } c.DevicesChanged(ctx, user.MXID) // Failing from here on, the key before stays pinned, and the new key's devices must not stay // trusted until the next look accepts it again: a rejection or the end of the wait may come // first. mautrix cannot go back to the pinned key while the homeserver shows the new one, so it // trusts none of the user's devices, which the next look sets right (checkTrust). takeBack := func() { if _, err := k.distrust(context.WithoutCancel(ctx), c, user.MXID); err != nil { k.log.Err(err).Stringer("user_id", user.MXID).Msg("Failed to take back the trust in a new master key that was not pinned") } } trusted, err := c.TrustedDevices(ctx, user.MXID) if err != nil { takeBack() return fmt.Errorf("failed to read the new identity's devices: %w", err) } k.userLock.Lock() accepted := *user accepted.PinnedMasterKey = reset.MasterKey // The key and the devices it cross-signed together, with the key it replaces retired: a change // seen next is checked against them, never against the devices of the identity before, and the // identity before never comes back. Failing, nothing is saved, and the next look accepts the key // again. err = k.store.pinIdentity(ctx, &accepted, trusted, user.PinnedMasterKey) if err == nil { k.users.Store(user.MXID, &accepted) } k.userLock.Unlock() if err != nil { takeBack() return fmt.Errorf("failed to pin the new master key: %w", err) } k.log.Info().Stringer("user_id", user.MXID).Stringer("master_key", reset.MasterKey).Str("reason", why). Msg("Accepted a switched-on user's new master key") return nil } // toldReset is the devices told about a user's waiting master key. type toldReset struct { masterKey id.Ed25519 devices map[id.DeviceID]bool } // notifyIdentityChange tells each device the pinned identity cross-signed about the new master key, // once: a device whose send failed is tried again on the next look, unless it is gone or has another // signing key. It reports whether none is left to try. Called with trustLock held. func (k *Kit) notifyIdentityChange(ctx context.Context, c identityCrypto, user *e2eeUser, reset *identityReset, pinnedDevices map[id.DeviceID]id.Ed25519) bool { told := k.told[user.MXID] if told.masterKey != reset.MasterKey { told = toldReset{masterKey: reset.MasterKey, devices: make(map[id.DeviceID]bool)} } content := &identityChangeContent{ Version: 1, Bridge: k.network, UserID: user.MXID, PinnedMasterKey: user.PinnedMasterKey, MasterKey: reset.MasterKey, FirstSeenAt: reset.FirstSeenAt.UnixMilli(), AcceptAfter: reset.FirstSeenAt.Add(identityWait).UnixMilli(), } done := true for deviceID, key := range pinnedDevices { if told.devices[deviceID] { continue } err := c.SendToDevice(ctx, user.MXID, deviceID, key, eventIdentityChange, content) if err != nil { k.log.Warn().Err(err).Stringer("user_id", user.MXID).Stringer("device_id", deviceID). Msg("Failed to tell a device of the pinned identity about a new master key") } if err == nil || errors.Is(err, errDeviceGone) { told.devices[deviceID] = true } else { done = false } } if done { delete(k.told, user.MXID) } else { if k.told == nil { k.told = make(map[id.UserID]toldReset) } k.told[user.MXID] = told } return done } // identityRejected handles a com.xessenger.identity_reject: taken only over Olm from a device the // user's pinned identity cross-signed, under the key the extension saw it trusted with. mautrix finds // the sender by its identity key and requires its signing key in the event, and with // mautrix-device-keys.patch a device ID the homeserver lists again with keys of its own carries those // keys, so it does not pass for the device the pinned identity cross-signed. func (k *Kit) identityRejected(ctx context.Context, user *e2eeUser, evt *crypto.DecryptedOlmEvent) { log := k.log.With().Stringer("user_id", user.MXID).Logger() var content identityRejectContent if err := json.Unmarshal(evt.Content.VeryRaw, &content); err != nil || content.MasterKey == "" { log.Warn().Err(err).Msg("Ignoring a malformed identity rejection") return } else if content.Bridge != "" && content.Bridge != k.network { return } k.trustLock.Lock() defer k.trustLock.Unlock() pinnedDevices, err := k.store.trustedDevices(ctx, user.MXID) if err != nil { log.Err(err).Msg("Failed to read the pinned identity's devices for an identity rejection") return } device := evt.SenderDevice if device == nil || pinnedDevices[device.DeviceID] == "" || pinnedDevices[device.DeviceID] != device.SigningKey || evt.Keys.Ed25519 != device.SigningKey { log.Warn().Msg("Ignoring an identity rejection from a device the pinned identity did not cross-sign") return } if content.MasterKey == user.PinnedMasterKey { log.Warn().Msg("Ignoring a rejection of the pinned master key itself") return } if err = k.store.rejectKey(ctx, user.MXID, content.MasterKey, time.Now()); err != nil { log.Err(err).Msg("Failed to save an identity rejection") return } if reset, err := k.store.identityReset(ctx, user.MXID); err == nil && reset != nil && reset.MasterKey == content.MasterKey { err = k.store.deleteIdentityReset(ctx, user.MXID) if err != nil { log.Err(err).Msg("Failed to drop a rejected reset") return } } log.Info().Stringer("device_id", device.DeviceID).Stringer("master_key", content.MasterKey). Msg("A device of the pinned identity rejected a new master key") } // takeIdentityEvents handles the Olm-encrypted to-device events switched-on users sent before mautrix // sees the sync: the Olm machine decrypts each one and handles what it knows (room keys and the like), // and gives back what it does not, where an identity rejection or a request (requests.go) is looked // for. The other events, com.beeper.stream.v1 ones among them, are passed on unparsed, as mautrix and // bridgev2 expect them. func (k *Kit) takeIdentityEvents(ctx context.Context, mach *crypto.OlmMachine, events []*event.Event) []*event.Event { kept := events[:0:0] for _, evt := range events { user := k.user(evt.Sender) if user == nil || evt.Type.Type != event.ToDeviceEncrypted.Type || encryptedWith(evt) != id.AlgorithmOlmV1 { kept = append(kept, evt) continue } evt.Type.Class = event.ToDeviceEventType if err := evt.Content.ParseRaw(evt.Type); err != nil { k.log.Warn().Err(err).Stringer("sender", evt.Sender).Msg("Failed to parse an encrypted to-device event") continue } decrypted := mach.HandleEncryptedEvent(ctx, evt) if decrypted == nil { continue } switch decrypted.Type.Type { case eventIdentityReject.Type: k.identityRejected(ctx, user, decrypted) case eventBridgeRequest.Type: k.takeRequest(user, decrypted) } } return kept } // encryptedWith is the algorithm an encrypted event names, read without parsing the event: mautrix // parses each to-device event itself and drops one that is parsed already. func encryptedWith(evt *event.Event) id.Algorithm { var content struct { Algorithm id.Algorithm `json:"algorithm"` } if json.Unmarshal(evt.Content.VeryRaw, &content) != nil { return "" } return content.Algorithm }