// 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 ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "net/http" "strings" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/database" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/bridgev2/provisionutil" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // Every bridge answers these methods over Olm (requests.go) as its provisioning API answers the server // (bridgev2/matrix/provisioning.go, through provisionutil): finding somebody on the network // (user.resolve, user.search) and making a group of people or adding them to one (group.create, // group.invite). The app asks them for a switched-on user instead of the server, so that the group's // name and the people's numbers never pass it (docs/e2ee/work-plan.md 4.13). A network that cannot do // one is answered unknown_method. // // The people are named by their ghosts as the user's encrypted rooms show them, hashed (ghost.go): what // the bridge answers names them so too, and it takes the plaintext ghosts and network IDs as well. const ( // groupTimeout bounds making a group or adding people to one, as the API bounded create_group. groupTimeout = 90 * time.Second // maxGroupParticipants is as many people as one request puts in a group, as the API took // (apps/api/src/matrix/new-group.ts). maxGroupParticipants = 50 // requestLifetime is how long the answer of a request done once is kept for the same request again. requestLifetime = 7 * 24 * time.Hour ) // errRequestUnsettled is a request done once that is still being done, or whose first try failed in a // way that may have done it all the same: it is answered unavailable. var errRequestUnsettled = errors.New("the request was asked before and has no answer to give again") func (k *Kit) networkMethods() []Method { return []Method{ {Name: "user.resolve", Call: k.resolveUser}, {Name: "user.search", Call: k.searchUsers}, {Name: "group.create", Call: k.createGroup, Timeout: groupTimeout}, {Name: "group.invite", Room: true, Call: k.inviteToGroup, Timeout: groupTimeout}, } } // networkError is err as a request's error, by the status and errcode provisioning answered it with // (bridgev2/matrix RespondWithError: what the error writes, M_UNKNOWN 500 for an error that writes // nothing), as the API took them (apps/api/src/matrix/new-group.ts): what the network cannot do at all // (M_UNRECOGNIZED), nothing found (M_NOT_FOUND, or 404), and what it refuses as asked (M_INVALID_PARAM // and the like, or any other 4xx but 408 and 429, which may go another time). Anything else is // answered unavailable. func networkError(err error) error { var writable interface { error Write(http.ResponseWriter) } if !errors.As(err, &writable) { return err } answer := &errorAnswer{} writable.Write(answer) var body struct { ErrCode string `json:"errcode"` } _ = json.Unmarshal(answer.body.Bytes(), &body) status := answer.status switch { case body.ErrCode == mautrix.MUnrecognized.ErrCode: return fmt.Errorf("%w: %w", ErrUnsupported, err) case body.ErrCode == mautrix.MNotFound.ErrCode, status == http.StatusNotFound: return fmt.Errorf("%w: %w", ErrRequestNotFound, err) case body.ErrCode == mautrix.MInvalidParam.ErrCode, body.ErrCode == mautrix.MBadJSON.ErrCode, body.ErrCode == mautrix.MNotJSON.ErrCode, body.ErrCode == mautrix.MTooLarge.ErrCode, status >= 400 && status < 500 && status != http.StatusRequestTimeout && status != http.StatusTooManyRequests: return fmt.Errorf("%w: %w", ErrBadRequest, err) } return err } // errorAnswer is what an error writes as provisioning's answer (networkError): its status and body. type errorAnswer struct { header http.Header status int body bytes.Buffer } func (a *errorAnswer) Header() http.Header { if a.header == nil { a.header = http.Header{} } return a.header } func (a *errorAnswer) WriteHeader(status int) { if a.status == 0 { a.status = status } } func (a *errorAnswer) Write(data []byte) (int, error) { a.WriteHeader(http.StatusOK) return a.body.Write(data) } // resolveUser answers user.resolve {identifier}: somebody on the network by a number, a username or // their ghost, as GET /v3/resolve_identifier/{identifier} answers, without starting a chat with them. func (k *Kit) resolveUser(ctx context.Context, req *Request) (json.RawMessage, error) { var params struct { Identifier string `json:"identifier"` } if json.Unmarshal(req.Params, ¶ms) != nil || strings.TrimSpace(params.Identifier) == "" || len(params.Identifier) > maxRequestField { return nil, ErrBadRequest } resp, err := provisionutil.ResolveIdentifier(ctx, req.Login, params.Identifier, false) if err != nil { return nil, networkError(err) } else if resp == nil { return nil, ErrRequestNotFound } k.foundGhost(ctx, req.Login.Bridge, resp) return json.Marshal(resp) } // foundGhost names somebody found on the network by their ghost as the user's encrypted rooms show it, // hashed: the ghost the network gave, or else the one their ID makes, as the API made it from the ID // (apps/api/src/matrix/new-group.ts). The app cannot make a hashed ghost itself. func (k *Kit) foundGhost(ctx context.Context, br *bridgev2.Bridge, found *provisionutil.RespResolveIdentifier) { if found.MXID == "" && found.ID != "" { found.MXID = br.Matrix.FormatGhostMXID(found.ID) } found.MXID = k.wireGhost(ctx, found.MXID) } // searchUsers answers user.search {query}: the network's search, as POST /v3/search_users answers it, // with as many of its results as an answer carries, in the network's order: a method about no room // answers no file (requests.go). func (k *Kit) searchUsers(ctx context.Context, req *Request) (json.RawMessage, error) { var params struct { Query string `json:"query"` } if json.Unmarshal(req.Params, ¶ms) != nil || strings.TrimSpace(params.Query) == "" || len(params.Query) > maxRequestField { return nil, ErrBadRequest } resp, err := provisionutil.SearchUsers(ctx, req.Login, params.Query) if err != nil { return nil, networkError(err) } results := []json.RawMessage{} size := len(`{"results":[]}`) for _, result := range resp.Results { k.foundGhost(ctx, req.Login.Bridge, result) encoded, err := json.Marshal(result) if err != nil { return nil, err } else if size+len(encoded)+1 > MaxInlineResult { zerolog.Ctx(ctx).Debug().Int("results", len(resp.Results)).Int("answered", len(results)).Msg("Answering a search with the results an answer carries") break } size += len(encoded) + 1 results = append(results, encoded) } return json.Marshal(map[string]any{"results": results}) } // createGroup answers group.create {type, name, participants}: a group made on the network with the // people given, by their ghosts or network IDs (the app finds them first with user.resolve and // user.search), and its portal room, as POST /v3/create_group/{type} answers. The room is made as any // of the login's portal rooms is, encrypted for a switched-on user, who is invited to it. A request is // done once (answerOnce): asked again, it is answered as it was. func (k *Kit) createGroup(ctx context.Context, req *Request) (json.RawMessage, error) { var params struct { Type string `json:"type"` Name *event.RoomNameEventContent `json:"name"` Participants []networkid.UserID `json:"participants"` } if json.Unmarshal(req.Params, ¶ms) != nil || len(params.Type) > maxRequestField || len(params.Participants) == 0 || len(params.Participants) > maxGroupParticipants { return nil, ErrBadRequest } for _, participant := range params.Participants { if participant == "" || len(participant) > maxRequestField { return nil, ErrBadRequest } } if params.Type == "" { params.Type = "group" } return k.answerOnce(ctx, req, func() (json.RawMessage, error) { resp, err := provisionutil.CreateGroup(ctx, req.Login, &bridgev2.GroupCreateParams{Type: params.Type, Participants: params.Participants, Name: params.Name}) if err != nil { return nil, networkError(err) } for _, failed := range resp.FailedParticipants { failed.UserMXID = k.wireGhost(ctx, failed.UserMXID) } return json.Marshal(resp) }) } // answerOnce does what a request asks once: asked again, as the app does when no answer came, it is // answered as the first time for requestLifetime, without doing it again. It is the same request only // asked of the same method, about the same room and by the same sender (requestKey). While the first // is still being done, or when it failed in a way that may have done it all the same (the network did // not answer in time, say), it is answered unavailable, as the API answered a group it could not tell // was made with 409. What surely did nothing (nothing found, refused as asked, not done by the network) // may be asked again. func (k *Kit) answerOnce(ctx context.Context, req *Request, do func() (json.RawMessage, error)) (json.RawMessage, error) { key := requestKey(req) claimed, answer, err := k.store.claimRequest(ctx, req.Login.ID, key, time.Now()) if err != nil { return nil, fmt.Errorf("failed to note the request: %w", err) } else if !claimed && answer != nil { return answer, nil } else if !claimed { return nil, errRequestUnsettled } answer, err = do() // Past the call's deadline, which may be why it failed. saveCtx := context.WithoutCancel(ctx) switch { case err == nil: if err := k.store.settleRequest(saveCtx, req.Login.ID, key, answer); err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to keep a request's answer for the same request again") } return answer, nil case errors.Is(err, ErrRequestNotFound), errors.Is(err, ErrBadRequest), errors.Is(err, ErrUnsupported): if err := k.store.forgetRequest(saveCtx, req.Login.ID, key); err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to let a refused request be asked again") } } return nil, err } // requestKey is what answerOnce keeps a request under for its login: the request's ID with the method // asked, the room it is about and who asked it, hashed. The same ID asked of another method, about // another room or by somebody else is another request, not answered with what was kept for the first: // who may no longer ask about a room does not get what was answered about it by naming another room. func requestKey(req *Request) string { var room id.RoomID if req.Portal != nil { room = req.Portal.MXID } key := sha256.New() for _, part := range []string{req.Method, string(room), string(req.Sender), req.RequestID} { // Each after its length, so that no two requests run together into the same. fmt.Fprintf(key, "%d:%s,", len(part), part) } return hex.EncodeToString(key.Sum(nil)) } // forgetOldRequests lets the answers of requests done once go requestLifetime after they were asked, // whether or not another request comes: the watch of the switched-on users' keys (watchTrust) calls it // when encryption starts and every trustInterval after. func (k *Kit) forgetOldRequests(ctx context.Context) { if err := k.store.forgetOldRequests(ctx, time.Now()); err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to forget the requests done once that are a week old") } } // groupFailure is somebody group.invite did not add, and why: "already" in the room, "invalid" for a // Matrix user who is no ghost of this bridge, "failed" when the network did not add them. type groupFailure struct { Participant string `json:"participant"` Reason string `json:"reason"` } // inviteToGroup answers group.invite {room_id, participants}: the people given, by their ghosts or // network IDs, added to the room's group on the network as its login, as the network takes a Matrix // invite of the login's user (bridgev2's Portal.handleMatrixMembership), which the API sent with the // token of the connection's holder. The room's members follow once the network tells the bridge. Each // is answered by the ghost the room shows, hashed in an encrypted room and the plaintext one in a room // from before the user was switched on: {"invited": [ghost], "failed": [{participant, reason}]}. // // The network is asked to add each person once: one given again, by another of their names, is // answered as the first was, and the request is done once (answerOnce). Asked again, a network may // answer that somebody it added is in the group already, as a failure, and the room's members may not // have followed yet to tell. When the network does not answer in time whether it added somebody, whom // the request added is not known: it is answered unavailable, as a group that may have been made, and // not done again. func (k *Kit) inviteToGroup(ctx context.Context, req *Request) (json.RawMessage, error) { var params struct { Participants []string `json:"participants"` } if json.Unmarshal(req.Params, ¶ms) != nil || len(params.Participants) == 0 || len(params.Participants) > maxGroupParticipants { return nil, ErrBadRequest } else if req.Portal.RoomType == database.RoomTypeDM { // As the API answered: people are added to a group, and a chat of two is none. return nil, ErrBadRequest } for _, participant := range params.Participants { if participant == "" || len(participant) > maxRequestField { return nil, ErrBadRequest } } api, ok := req.Login.Client.(bridgev2.MembershipHandlingNetworkAPI) if !ok { return nil, ErrUnsupported } return k.answerOnce(ctx, req, func() (json.RawMessage, error) { answer := struct { Invited []id.UserID `json:"invited"` Failed []groupFailure `json:"failed"` }{Invited: []id.UserID{}, Failed: []groupFailure{}} encrypted := k.isEncrypted(ctx, req.Portal.MXID) // Why each person asked of the network was not added, "" for one who was. asked := map[networkid.UserID]string{} for _, participant := range params.Participants { ghostID, ok := participantGhost(req.Login.Bridge, id.UserID(participant)) reason, again := asked[ghostID] if !ok { reason = "invalid" } else if !again { var invited id.UserID var err error if invited, reason, err = k.inviteOne(ctx, api, req, encrypted, ghostID); err != nil { return nil, err } asked[ghostID] = reason if reason == "" { answer.Invited = append(answer.Invited, invited) } } if reason != "" { answer.Failed = append(answer.Failed, groupFailure{Participant: participant, Reason: reason}) } } return json.Marshal(answer) }) } // participantGhost is the network ID of somebody group.invite is given by their ghost, hashed or not, // or by the network ID user.resolve answers; false for a Matrix user who is no ghost of this bridge (a // person of the homeserver, the bot). func participantGhost(br *bridgev2.Bridge, userID id.UserID) (networkid.UserID, bool) { if ghostID, ok := br.Matrix.ParseGhostMXID(userID); ok { return ghostID, true } else if strings.HasPrefix(string(userID), "@") { return "", false } return networkid.UserID(userID), true } // inviteOne adds somebody to the group of the request's room by their network ID: it returns their // ghost as the room shows it, hashed when the room is encrypted (the network may add them as another of // its users), or why they were not added. It returns an error when the network did not answer in time, // past the call's deadline or its own: it may have added them all the same. func (k *Kit) inviteOne(ctx context.Context, api bridgev2.MembershipHandlingNetworkAPI, req *Request, encrypted bool, ghostID networkid.UserID) (id.UserID, string, error) { br := req.Login.Bridge shown := func(ghostID networkid.UserID) id.UserID { plaintext := br.Matrix.FormatGhostMXID(ghostID) if !encrypted { return plaintext } return k.wireGhost(ctx, plaintext) } log := zerolog.Ctx(ctx).With().Stringer("participant", shown(ghostID)).Logger() if membership, err := k.conn.StateStore.GetMembership(ctx, req.Portal.MXID, shown(ghostID)); err != nil { log.Err(err).Msg("Failed to read a participant's membership") return "", "failed", nil } else if membership == event.MembershipJoin || membership == event.MembershipInvite { return "", "already", nil } ghost, err := br.GetGhostByID(ctx, ghostID) if err != nil { log.Err(err).Msg("Failed to get a participant's ghost") return "", "failed", nil } target := ghost.Intent.GetMXID().String() change := &bridgev2.MatrixMembershipChange{ MatrixRoomMeta: bridgev2.MatrixRoomMeta[*event.MemberEventContent]{ MatrixEventBase: bridgev2.MatrixEventBase[*event.MemberEventContent]{ // No such event is in the room: the room shows what the network does. Event: &event.Event{Type: event.StateMember, StateKey: &target, Sender: req.Login.UserMXID, RoomID: req.Portal.MXID, Timestamp: time.Now().UnixMilli()}, Content: &event.MemberEventContent{Membership: event.MembershipInvite}, Portal: req.Portal, }, IsStateRequest: true, PrevContent: &event.MemberEventContent{Membership: event.MembershipLeave}, }, Target: ghost, Type: bridgev2.Invite, } result, err := api.HandleMatrixMembership(ctx, change) if err != nil && (ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded)) { return "", "", fmt.Errorf("the network did not answer in time whether it added a participant: %w", err) } else if err != nil { log.Err(err).Msg("The network did not add a participant to the group") return "", "failed", nil } else if result != nil && result.RedirectTo != "" && result.RedirectTo != ghostID { return shown(result.RedirectTo), "", nil } return shown(ghostID), "", nil } // wireGhost is a ghost as the user's encrypted rooms show it, hashed (wireUser); "" stays "". func (k *Kit) wireGhost(ctx context.Context, userID id.UserID) id.UserID { if userID == "" { return "" } return k.wireUser(ctx, userID) }