// 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" "encoding/json" "mime" "net/http" "net/url" "strings" "maunium.net/go/mautrix/id" ) // Some provisioning answers carry pictures by MXC: a contact's (resolve_identifier, contacts, // search_users, create_dm) and the account's own (whoami shows each login's profile, whose picture // the bridges copy from the account's ghost). bridgev2 takes them from the ghost, whose picture is // uploaded encrypted while the contact is only in encrypted rooms (ghostIntent.UploadMedia), so that // MXC holds ciphertext nobody can show. These answers already name the contact to the API that asked, // so the extension gives them the picture's plaintext copy instead, uploaded by the bot like the // copies for rooms that are not encrypted. Encrypted rooms keep no plaintext picture either way. // provisioningPictureRoutes are the provisioning endpoints whose answers carry pictures, with the // prefix bridgev2 mounts its provisioning API on. var provisioningPictureRoutes = []string{ "GET /_matrix/provision/v3/whoami", "GET /_matrix/provision/v3/contacts", "POST /_matrix/provision/v3/search_users", "GET /_matrix/provision/v3/resolve_identifier/{identifier}", "POST /_matrix/provision/v3/create_dm/{identifier}", } // wrapProvisioning puts plaintext pictures in the answers of provisioningPictureRoutes. bridgev2 // mounts its provisioning API on the prefix only when the bridge starts, after the extension // attached; these more specific routes take the requests first and hand them on to it. func (k *Kit) wrapProvisioning(router *http.ServeMux) { handler := k.provisioningPictures(router) for _, pattern := range provisioningPictureRoutes { router.Handle(pattern, handler) } } func (k *Kit) provisioningPictures(router *http.ServeMux) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { provisioning, _ := router.Handler(&http.Request{Method: http.MethodGet, URL: &url.URL{Path: "/_matrix/provision/"}}) if !k.box.Ready() { // Without the store key nothing was uploaded encrypted. provisioning.ServeHTTP(w, r) return } answer := &bufferedAnswer{header: make(http.Header), status: http.StatusOK} provisioning.ServeHTTP(answer, r) body := answer.body.Bytes() if contentType, _, _ := mime.ParseMediaType(answer.header.Get("Content-Type")); answer.status == http.StatusOK && contentType == "application/json" { if replaced, err := k.plaintextAnswerPictures(r.Context(), body); err != nil { k.log.Err(err).Str("path", r.URL.Path).Msg("Failed to read a provisioning answer for its pictures") } else { body = replaced } } for key, values := range answer.header { if key != "Content-Length" { w.Header()[key] = values } } w.WriteHeader(answer.status) _, _ = w.Write(body) }) } // plaintextAnswerPictures replaces each picture uploaded encrypted in a JSON answer with its // plaintext copy. A picture whose copy cannot be made is left out rather than shown broken. func (k *Kit) plaintextAnswerPictures(ctx context.Context, body []byte) ([]byte, error) { decoder := json.NewDecoder(bytes.NewReader(body)) decoder.UseNumber() var answer any if err := decoder.Decode(&answer); err != nil { return nil, err } changed := false // replace returns the value to keep, or false to leave a picture out. var replace func(value any) (any, bool) replace = func(value any) (any, bool) { switch value := value.(type) { case map[string]any: for key, item := range value { if kept, ok := replace(item); ok { value[key] = kept } else { delete(value, key) } } case []any: for i, item := range value { if kept, ok := replace(item); ok { value[i] = kept } } case string: if !strings.HasPrefix(value, "mxc://") { return value, true } plaintext, err := k.plaintextPicture(ctx, k.bot.ASIntent, id.ContentURIString(value)) if err != nil { k.log.Err(err).Str("mxc", value).Msg("Failed to make a plaintext copy of a picture for a provisioning answer") changed = true return nil, false } else if string(plaintext) != value { changed = true return string(plaintext), true } } return value, true } answer, _ = replace(answer) if !changed { return body, nil } var out bytes.Buffer encoder := json.NewEncoder(&out) encoder.SetEscapeHTML(false) if err := encoder.Encode(answer); err != nil { return nil, err } return out.Bytes(), nil } // bufferedAnswer keeps a provisioning answer to change it before it is sent. type bufferedAnswer struct { header http.Header status int body bytes.Buffer wrote bool } func (b *bufferedAnswer) Header() http.Header { return b.header } func (b *bufferedAnswer) WriteHeader(status int) { if !b.wrote { b.status, b.wrote = status, true } } func (b *bufferedAnswer) Write(data []byte) (int, error) { b.wrote = true return b.body.Write(data) }