// 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" "database/sql" "encoding/json" "errors" "fmt" "net/http" "github.com/rs/zerolog" "go.mau.fi/util/dbutil" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/id" ) // What the API's jobs read from the bridge (QA-289): how far each login's first sync is, and the // rooms of a login's chats, which room recovery invites the login's owner back to. jobs used to log // in to the bridge database for these; the bridge's enclave keeps that database to itself. Login IDs // (a phone number or an address, say) come in the body, so they stay out of access logs. // // POST /_xessenger/v1/logins/progress {logins: [{id, userId}]} -> {logins: [{id, userId, historyFetched, portals, rooms}]} // POST /_xessenger/v1/logins/portals {id, userId, roomId?} -> {portals: [{id, roomId, bridgeId}]} // maxProgressLogins bounds one progress request; jobs asks about 50 accounts at a time. const maxProgressLogins = 100 type loginOwner struct { ID networkid.UserLoginID `json:"id"` UserID id.UserID `json:"userId"` } type loginProgress struct { loginOwner HistoryFetched bool `json:"historyFetched"` // Portals counts the login's chats, spaces aside; Rooms those of them that have a room. Portals int `json:"portals"` Rooms int `json:"rooms"` } type portalRoom struct { ID networkid.PortalID `json:"id"` RoomID id.RoomID `json:"roomId"` // BridgeID is the chat ID as the room's m.bridge state gives it (channel.id), which room recovery // compares: an HMAC in an encrypted room (scrubBridgeInfo), the chat ID otherwise. BridgeID string `json:"bridgeId"` } func (k *Kit) handleProgress(w http.ResponseWriter, r *http.Request) { var body struct { Logins []loginOwner `json:"logins"` } if !readJSON(w, r, &body) { return } if len(body.Logins) > maxProgressLogins { writeError(w, http.StatusBadRequest, "M_INVALID_PARAM", fmt.Sprintf("At most %d logins at a time", maxProgressLogins)) return } for _, login := range body.Logins { if login.ID == "" || login.UserID == "" { writeError(w, http.StatusBadRequest, "M_INVALID_PARAM", "Every login needs id and userId") return } } ctx := k.requestContext(r) progress, err := readProgress(ctx, k.db, k.br.ID, k.network, body.Logins) if err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to read the logins' sync progress") writeError(w, http.StatusInternalServerError, "M_UNKNOWN", "Failed to read the progress") return } writeJSON(w, http.StatusOK, map[string]any{"logins": progress}) } func (k *Kit) handlePortals(w http.ResponseWriter, r *http.Request) { var body struct { loginOwner RoomID id.RoomID `json:"roomId"` } if !readJSON(w, r, &body) { return } if body.ID == "" || body.UserID == "" { writeError(w, http.StatusBadRequest, "M_INVALID_PARAM", "id and userId are required") return } ctx := k.requestContext(r) portals, err := readPortals(ctx, k.db, k.br.ID, body.loginOwner, body.RoomID) if err == nil { err = k.fillBridgeIDs(ctx, portals) } if err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to read the login's portals") writeError(w, http.StatusInternalServerError, "M_UNKNOWN", "Failed to read the portals") return } writeJSON(w, http.StatusOK, map[string]any{"portals": portals}) } // fillBridgeIDs gives each portal the chat ID its room's m.bridge state shows. Only the rooms of // switched-on users are encrypted, so while nobody is, every one shows the chat ID itself. func (k *Kit) fillBridgeIDs(ctx context.Context, portals []portalRoom) error { for i := range portals { portals[i].BridgeID = string(portals[i].ID) if !k.active() || !k.ghosts.hashing() { continue } encrypted, err := k.conn.StateStore.IsEncrypted(ctx, portals[i].RoomID) if err != nil { return fmt.Errorf("failed to check if %s is encrypted: %w", portals[i].RoomID, err) } if encrypted { portals[i].BridgeID = k.opaqueID("chat", string(portals[i].ID)) } } return nil } // readProgress counts each login's chats and those with a room, skipping spaces, and says whether // its first history sync is done. A login that is not the given user's // is left out. func readProgress(ctx context.Context, db *dbutil.Database, bridgeID networkid.BridgeID, network string, logins []loginOwner) ([]loginProgress, error) { progress := []loginProgress{} for _, login := range logins { var metadata []byte var portals, rooms int err := db.QueryRow(ctx, ` SELECT u.metadata, count(p.id), count(p.mxid) FROM user_login u LEFT JOIN portal p ON p.bridge_id=u.bridge_id AND p.receiver=u.id AND COALESCE(p.room_type, '')<>'space' WHERE u.bridge_id=$1 AND u.id=$2 AND u.user_mxid=$3 GROUP BY u.bridge_id, u.id, u.user_mxid, u.metadata `, bridgeID, login.ID, login.UserID).Scan(&metadata, &portals, &rooms) if err == nil { progress = append(progress, loginProgress{ loginOwner: login, HistoryFetched: historyFetched(network, metadata), Portals: portals, Rooms: rooms, }) } else if !errors.Is(err, sql.ErrNoRows) { return nil, err } } return progress, nil } // historyFetched says whether a login's first history sync is done, from what each network // records in the login's metadata. func historyFetched(network string, metadata []byte) bool { var fields map[string]json.RawMessage _ = json.Unmarshal(metadata, &fields) switch network { case "instagram", "facebook": text, ok := jsonText(fields, "backfill_completed") return ok && text == "true" case "telegram", "line": // Neither records one: Telegram syncs its recent chats right after login, and LINE the recent // messages of every chat each time it connects. The rooms count as they appear. return true default: // WhatsApp, until the chats of its history sync have rooms. text, ok := jsonText(fields, "history_sync_portals_need_creating") return !ok || text == "false" } } // jsonText is a metadata field as Postgres' ->> gives it: a string unquoted, anything else as // written, and no value for a missing field or null. func jsonText(fields map[string]json.RawMessage, key string) (string, bool) { raw, ok := fields[key] if !ok || string(raw) == "null" { return "", false } var text string if json.Unmarshal(raw, &text) == nil { return text, true } return string(raw), true } // readPortals lists the rooms of the login's chats, skipping spaces and chats without a room, by // room ID; with roomID, only that room's chat. A login that is not the given user's has none. func readPortals(ctx context.Context, db *dbutil.Database, bridgeID networkid.BridgeID, login loginOwner, roomID id.RoomID) ([]portalRoom, error) { query := ` SELECT p.id, p.mxid FROM portal p JOIN user_login u ON u.bridge_id=p.bridge_id AND u.id=p.receiver WHERE u.bridge_id=$1 AND u.id=$2 AND u.user_mxid=$3 AND p.mxid IS NOT NULL AND COALESCE(p.room_type, '')<>'space' ` args := []any{bridgeID, login.ID, login.UserID} if roomID != "" { query += " AND p.mxid=$4" args = append(args, roomID) } rows, err := db.Query(ctx, query+" ORDER BY p.mxid", args...) if err != nil { return nil, err } portals, err := dbutil.NewRowIterWithError(rows, func(row dbutil.Scannable) (portal portalRoom, err error) { err = row.Scan(&portal.ID, &portal.RoomID) return }, nil).AsList() if err != nil { return nil, err } if portals == nil { portals = []portalRoom{} } return portals, nil }