// 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 ( "crypto/hmac" "crypto/sha256" "encoding/base32" "fmt" "regexp" "maunium.net/go/mautrix/bridgev2/bridgeconfig" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/id" ) // hashLength is how many base32 characters of the HMAC a hashed ghost keeps: 130 bits. const hashLength = 26 var lowerBase32 = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding) // ghostNames names ghosts in encrypted rooms: @_:, the prefix being the bridge's (wa, ig, fb, tg, ln, em). Without the key, // which only the bridge's enclave can open, the server cannot tell whose phone number or address a // hashed ghost stands for, nor compute the ghost of a number it knows. type ghostNames struct { key []byte cfg *bridgeconfig.Config domain string hashedRe *regexp.Regexp } func newGhostNames(cfg *bridgeconfig.Config, key []byte) (*ghostNames, error) { if len(key) != 0 && len(key) != 32 { return nil, fmt.Errorf("the ghost key must be 32 bytes, not %d", len(key)) } names := &ghostNames{cfg: cfg, domain: cfg.Homeserver.Domain} if len(key) == 32 { names.key = append([]byte(nil), key...) } names.hashedRe = cfg.MakeUserIDRegex(fmt.Sprintf("([a-z2-7]{%d})", hashLength)) return names, nil } func (g *ghostNames) hashing() bool { return g != nil && g.key != nil } // hashed returns the hashed ghost of a network user, "" without a key. func (g *ghostNames) hashed(userID networkid.UserID) id.UserID { if !g.hashing() { return "" } mac := hmac.New(sha256.New, g.key) mac.Write([]byte(userID)) digest := lowerBase32.EncodeToString(mac.Sum(nil))[:hashLength] return id.NewUserID(g.cfg.AppService.FormatUsername(digest), g.domain) } // isHashedShape reports whether an MXID has the shape of a hashed ghost of this bridge. No network ID // a bridge names a ghost after takes that shape once escaped: WhatsApp, Telegram, Instagram and // Messenger IDs are digits (WhatsApp's LID ones "lid-" and digits), a LINE mid is 33 characters and an // escaped mail address holds "=40". func (g *ghostNames) isHashedShape(userID id.UserID) bool { return g.hashedRe.MatchString(string(userID)) }