How to proxy flatpak apps through tor with torsocks?

Is it possible to configure Flatpak apps so as to proxy their network connections through tor? I have tried with torsocks, which works fine with apps installed to /usr/bin and the like. But apps packaged with Flatpak throws an error.

Example: running Element.

torsocks -i flatpak run im.riot.Riot

opens the app but outputs the error

ERROR: ld.so: object '/usr/lib64/torsocks/libtorsocks.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.

I assume it has something to do with sandbox permissions. I have given Element flatpak access to the network, and tried giving it access to all system files, libraries and configurations. I also set manually permissions to access /usr/lib64/torsocks/libtorsocks.so /usr/bin/torsocks /usr/lib64/torsocks /usr/bin/tor /etc/tor and /usr/share/tor

I’m trying to use the Flatpak version so I can avoid compiling from source.

OS: Fedora 36

I’m afraid you have to build Element from source (at least convert deb designed for debian to rpm with alien) and use a powerful redsocks proxifier (based on iptables). Note: by default redsocks sends DNS queries directly, not through a proxy and you need to run the proxying application from another user.
redsocks is very difficult to set up, but worth it. It can even proxy VirtualBox.

But the easiest way is to use the web version of Element and configure the proxy in your browser. Disable WebRTC, HTTP3 (QUIC), IPv6, and proxy.failover to prevent leaks.
In Firefox, these options are in about:config:
media.peerconnection.enabled (false)
network.http.http3.enable (false)
network.dns.disableIPv6 (true)
network.notify.IPv6 (false)
network.proxy.failover_direct (should be false)
network.proxy.socks_remote_dns (true)
It is not recommended to logout of the browser and clear cookies. You can have a separate browser for this.

Thank you for your reply, meonriox. I can confirm that, following the instructions in the link you provided, Element will not proxy its traffic through tor, even though gsettings are adjusted. But using the web version with a Firefox set up to proxy with torsocks, it is working as expected. This seems the safest option.

I’m not trying to proxy all system traffic through tor, as that would cause more general issues (and anyway, Tails would be a much better option in that case). But having some apps run through tor is desirable.