Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Enterprise Development Partnership

Tuwunel’s development is directly driven by the needs of its corporate sponsors. For these businesses and governments, communication systems are often critical infrastructure, and Tuwunel forms part of that infrastructure. Our partners create value through features tailored to their specifications and control costs through agreed performance targets. When they need to scale further, we provide the engineering required.

Although Tuwunel is available at no cost and may already meet the needs of many individuals and companies, our partners invest in us to maximize their returns. They do so because our collaboration creates more value than merely using the software for free.

Tuwunel is developing into a highly available, horizontally scalable, specification-compliant Matrix cluster capable of handling high message volumes with low latency through hardware acceleration and robust quality-of-service guarantees. We can do this better together. Partner with Tuwunel and finally get this right.

Proven results

An independent 2026 study compared a single Tuwunel process with an 18-worker Synapse deployment in a 200-user test. Tuwunel completed three of the four benchmark scenarios faster than Synapse.

Researchers at the Federal University of Ceará (UFC), the Federal University of Piauí (UFPI), and Brazil’s Research and Development Center for Communication Security (CEPESC) published A Comparative Performance Study of the Matrix /sync Endpoint on Synapse and Tuwunel at SBRC 2026. The controlled study issued nearly 17,000 /sync requests under increasing load. It was conducted as part of the Brazilian government’s msg gov secure communications project and reflects operational requirements from that project.

Tuwunel delivered lower response times in three of the four version 3 /sync⋆ configurations. The following results are average initial sync response times under the heaviest load tested: 200 concurrent users, each in 300 rooms with 300 members per room.

Sync configuration Synapse, 18 workers Tuwunel, one process Result
1T: timeline 1, lazy members 80.1 s 8.6 s 9.3x faster
5T: timeline 5, lazy members 74.3 s 14.0 s 5.3x faster
10F: timeline 10, full member state 465.3 s 725.9 s Synapse 1.6x faster
20T: timeline 20, lazy members, the Element Web profile 117.5 s 33.8 s 3.5x faster

⋆ Tuwunel has since implemented Simplified Sliding Sync, as recorded in our MSC implementation audit. That implementation postdates the study and has not yet been measured by the same independent benchmark.

Production foundation

Tuwunel is the official successor to conduwuit and is developed by full-time staff. It has an active public codebase, regular releases, institutional users, and existing sponsorship from the Swiss government. Tuwunel is deployed for use by citizens in Switzerland. New sponsors join a working, publicly auditable project with production use, institutional backing, and independent benchmark results, rather than a speculative prototype.

Current status

The clustering initiative starts from a working, independently tested homeserver. We publish the evidence needed for technical due diligence:

  • MSC implementations: Our audit covers Matrix Spec Change proposals, including correctness scores and supporting evidence. Of 200 in-scope merged MSCs, 186 are implemented, for 93% coverage. Across merged and proposed features, 254 MSCs are implemented outright.

  • Complement progress: We run the Matrix homeserver acceptance suite continuously. Tuwunel currently passes over 80% of top-level test groups, with raw results and logs committed to the repository.

  • Synapse Admin API: Tuwunel supports most known endpoints today, including the core user, room, device, registration, and moderation surfaces used by existing tools.

  • Enterprise authentication: Tuwunel has built-in OAuth 2.0 and OIDC, LDAP support, and JWT authentication.

  • Matrix RTC: Tuwunel supports Element Call video and voice conferencing.

Future plans

  1. Tuwunel-native multi-node scale-out. Synapse can distribute work across worker processes that share PostgreSQL and Redis. Our objective is to design scale-out around Tuwunel’s own architecture while retaining its operational simplicity wherever possible. Sponsors fund the architecture, implementation, migration path, and production validation needed to turn that objective into a supported deployment model.

  2. High availability and business continuity. The program targets redundancy, failure recovery, and rolling maintenance across nodes. Concrete availability targets, recovery objectives, and acceptance tests can be agreed with sponsors so that the result maps to real operational and compliance requirements.

  3. Roadmap alignment with sponsor requirements. Funders help select the feature gaps and deployment constraints that matter to their organizations. Each engagement can be organized around documented requirements, milestones, acceptance criteria, and release targets, giving technical and procurement teams a clear delivery path.

  4. Direct enterprise engineering and support. Sponsors receive access to full-time project staff, priority for deployment-critical defects and features, and custom integration work where identity, administration, policy, migration, or infrastructure requirements go beyond the public project’s defaults.

Get in touch

For sponsorship and enterprise inquiries, contact @jason:tuwunel.me on Matrix or at jasonzemos@gmail.com. You can also contact @june:woof.gay on Matrix or at june@girlboss.ceo. General project channels are listed on the introduction page.

Tuwunel

High Performance Matrix Homeserver in Rust!

Documentation Demo Server Support Chat

Tuwunel is a featureful Matrix homeserver you can use instead of Synapse with your favorite client, bridge or bot. It is written entirely in Rust to be a scalable, low-cost, enterprise-ready, community-driven alternative, fully implementing the Matrix Specification for all but the most niche uses.

This project is the official successor to conduwuit after it reached stability. Tuwunel is now used by many companies with a vested interest in its continued development by full-time staff. It is primarily sponsored by the government of Switzerland 🇨🇭 where it is currently deployed for citizens.

Getting Started

Quick Setup

1. Configure by copying and editing the tuwunel-example.toml. The server_name and database_path must be configured. Most users deploy via docker or a distribution package and should follow the appropriate guide instead. This is just a summary for the impatient. See the full documentation.

Tip

Avoid using a sub-domain for your server_name. You can always delegate later with a .well-known file, but you can never change your server_name.

2. Setup TLS certificates. Most users enjoy the Caddy reverse-proxy which automates their certificate renewal. Advanced users can load their own TLS certificates using the configuration and Tuwunel can be deployed without a reverse proxy. Example /etc/caddy/Caddyfile configuration with Element unzipped to /var/www/element:

tuwunel.me, tuwunel.me:8448 {
    reverse_proxy localhost:8008
}
web.tuwunel.me {
    root * /var/www/element/
    file_server
}

caddy reload --config /etc/caddy/Caddyfile

3. Start the server, connect your client and register your username. The first registration is granted server admin.

Tip

Configure a secret registration_token and set allow_registration = true

Help & Support

Security vulnerabilities have their own reporting process; please see SECURITY.md. If you are opposed to using github, or if private discussion is required for any other reason, I would be happy to receive your DM at @jason:tuwunel.me. This will not be bothering me as it would be my pleasure to help you when possible. As an emergency contact you can send an email to jasonzemos@gmail.com.

💜 Tuwunel Support Chat 💜

Our official chat is publicly accessible at #tuwunel:matrix.org. Project staff are present there to offer assistance, and everyone is welcome to ask questions or share their experience running Tuwunel.

Migrating to Tuwunel

Can I migrate from…More about migrating your existing server
conduwuit?✅ Yes. This will be supported at a minimum for one year, but likely indefinitely.
A fork of conduwuit?✅ Yes. The database migrates in place on first boot.
Conduit?✅ Yes. The RocksDB database migrates in place on first boot.
Synapse?❌ Not yet, but this is planned and an important issue. Subscribe to #2.
Any other Conduit fork?❌ No. The migration must be explicitly listed in this table.

Tuwunel💕

Tuwunel’s theme is empathy in communication defined by the works of Edith Stein. Empathy is the basis for how we approach every message and our responsibility to the other in every conversation.

Fund Tuwunel’s next stage

An independent academic study measured a single Tuwunel process outperforming an 18-worker Synapse deployment on /sync in all three lazy-loading configurations tested under heavy load, while Synapse led in the full-state configuration. We are seeking funding for native multi-node scaling, redundancy, and failover while preserving Tuwunel’s simpler operating model. See Enterprise Development Partnership for the benchmark data, current status, and future plans.

How can I deploy my own?

If you want to connect an appservice to Tuwunel, take a look at the appservices documentation.

How can I contribute?

See the contributor’s guide

Deploying into service

Read the Generic guide first regardless of which platform you ultimately use. It explains the universal requirements — binary selection, database configuration, the system user, and the systemd unit — that every other guide builds on.

Choosing a reverse proxy

Tuwunel listens on plain HTTP and requires a reverse proxy to terminate TLS. All guides assume HTTPS is already handled externally.

Caddy is the recommended choice. It handles TLS automatically via Let’s Encrypt, and the full Tuwunel configuration fits in two lines. It also proxies port 8448 (Matrix federation) in the same block with no extra work.

Nginx is a solid choice if you are already running it. The configuration is more verbose but well-documented. Set client_max_body_size to match or exceed Tuwunel’s max_request_size (default 24 MiB), and never use $request_uri in the proxy pass, since it causes subtle breakage.

Warning

Apache and Lighttpd are not supported for Matrix federation. Both alter the X-Matrix authorization header that federation depends on. Nginx and Caddy handle it correctly.

Traefik works well in Docker environments. Note that Traefik cannot serve .well-known files by itself — you need a companion nginx container for federation discovery, or expose port 8448 directly as a Traefik entrypoint. Also check whether you are running a version between 3.6.4–3.6.6 or 2.11.32–2.11.34, which contain a bug that requires an extra workaround flag.

Root-domain delegation

By default, Tuwunel’s server name is the domain that appears in Matrix user IDs (@alice:example.com), which must exactly match the host Tuwunel presents when federating. If you want to host Matrix under a subdomain (matrix.example.com) while users have addresses on the root domain (example.com), configure root-domain delegation. This serves .well-known/matrix/client and .well-known/matrix/server from the root domain pointing to the subdomain, and requires no changes to DNS beyond what is already needed for your web server.

Things to know before getting started

Pick the right binary. Prebuilt binaries for x86_64 come in -v1-, -v2-, and -v3- CPU-optimized variants. Running the wrong one produces an Illegal Instruction crash. The generic guide includes a command to check which variant your CPU supports; -v2- or better is recommended for RocksDB’s CRC32 performance.

Debian and Ubuntu have an apt repository. Instead of downloading packages by hand, add the repository from the Debian guide and install with apt install tuwunel; upgrades then arrive through apt upgrade. Installing the package also adopts an existing conduwuit or Conduit database automatically.

RocksDB is the only supported database. SQLite support has been removed. A RocksDB database from Conduit or a fork of conduwuit migrates in place on first boot: stop the source server, back up its data directory and media, then start Tuwunel against it. Tuwunel reconciles the schema version, room history, account data, and media automatically; no flags are required. For a Conduit source using the content-addressed media layout, set conduit_media_directory_depth and conduit_media_directory_length to match its media.directory_structure: Conduit v0.10.0 stored media flat, so use conduit_media_directory_depth = 0, while v0.10.1 and later shard it (the default). If media lived outside <database_path>/media, set conduit_source_media_path; if it lived in an S3 bucket, see importing media from a Conduit S3 bucket. SQLite databases are not supported.

Port 8448 matters for federation. Clients connect on port 443, but other Matrix homeservers connect on port 8448. Both must be reachable for a fully functional server. NAT hairpinning or split-horizon DNS may be needed for internal clients that need to reach the same domain.

Container images are minimal. Docker and Podman images contain only the binary, a minimal init (tini), and CA certificates — no shell. If you need to inspect a running container you will need to exec into it using the binary directly.

Rootless Podman requires linger. Without loginctl enable-linger, rootless containers stop when the user logs out. The Podman guide uses quadlet files and user-level systemd to handle this correctly.

NixOS has platform-specific workarounds. The community services.matrix-conduit NixOS module defaults to SQLite, requires a manual workaround for UNIX socket support, and conflicts with jemalloc when a hardened profile is enabled. The NixOS guide covers all three.

Migration

Note

Skip this chapter if you are setting up a fresh install of Tuwunel.

Migrating an existing server to Tuwunel

Caution

Always back up your database before migrating. Migrating into Tuwunel from a source listed above is safe: Tuwunel recognizes a foreign database and reconciles its schema version on first boot. Switching a database between two other forks of Conduit can still permanently corrupt it, because all derivatives share one linear database version with no awareness of each other.

Migrating from conduwuit

Migrating from conduwuit to Tuwunel just works. In technical parlance it is a “binary swap.” All you have to do is update to the latest Tuwunel and change the path to the executable from conduwuit to tuwunel.

Anything else named “conduwuit” is still recognized, this includes environment variables with prefixes such as CONDUWUIT_. In fact, CONDUIT_ is still recognized for our legacy users. You may have noticed that various configs, yamls, services, users, and other items were renamed, but if you were a conduwuit user we recommend against changing anything at all. This will keep things simple. If you are not sure please ask. If you found out that something did in fact need to be changed please open an issue immediately.

Migrating from Conduit or a fork of conduwuit

A RocksDB database from Conduit or a fork of conduwuit migrates in place on first boot. Stop the source server, back up its data directory and media, then start Tuwunel against it. Tuwunel recognizes the foreign database, reconciles its schema version, and carries over room history, account data, and media automatically; no flags are required. See the deploying guide for media-layout notes that apply to older Conduit databases.

Configuration

This chapter describes various ways to configure Tuwunel.

Basics

Tuwunel uses a config file for the majority of the settings, but also supports setting individual config options via commandline.

Please refer to the example config file for all of those settings.

The config file to use can be specified on the commandline when running Tuwunel by specifying the -c, --config flag. It is also possible to specify more than one config file.

Alternatively, you can use the environment variable TUWUNEL_CONFIG to specify the config file to used. Conduit’s environment variables are supported for backwards compatibility.

Tuwunel has no default config file path. The packaged services select /etc/tuwunel/tuwunel.toml through TUWUNEL_CONFIG, so running the binary by hand needs -c to read the same file. Every selected path must be a regular file (a symlink to one is fine); a directory or a device is refused at startup.

Important

It is bad practice to uncomment default options without changing them. Many defaults are updated by developers as features evolve and can be essential to expected server function.

Configuration tables

Settings are grouped by subsystem beneath [global]. Bootstrap settings such as server_name and database_path remain at the root:

[global]
server_name = "example.com"
database_path = "/var/lib/tuwunel"

[global.http]
max_request_size = 20000000

[global.rocksdb]
checksums = true

Existing flat names, including max_request_size and rocksdb_checksums, remain supported throughout 2.x. Existing configurations do not need to be rewritten. Configuration regeneration can produce a canonical file when you want to reorganize it.

Existing headerless files remain supported. Use explicit [global.*] headers for new files containing only tables: without any non-table value at the root, table names are interpreted as profiles rather than inferred configuration groups. Do not mix bare root settings with an explicit [global] profile in one file.

New group names, such as http, rocksdb and logging, are reserved for tables. An old unknown scalar under one of these names cannot remain a scalar in the new hierarchy.

Unknown options warn by default, including misspelled settings inside the new groups; configuration.error_on_unknown_opts = true makes them errors. Supported legacy names remain accepted in strict mode and are not newly deprecated. Existing nested sections and dynamic maps keep their existing unknown-key behavior.

Option commandline flag

Tuwunel supports setting individual config options in TOML format from the -O / --option flag. For example, you can set your server name via -O server_name=\"example.com\".

One setting is refused here, as it is from configuration files and the environment: database_restore_backup belongs to --restore-backup alone, since restoring a backup is destructive and must not repeat.

Option paths are relative to global: use rocksdb.checksums, not global.rocksdb.checksums. The option value is TOML, so quote string values for both TOML and your shell:

  • -O registration.enable=true
  • -O http.max_request_size=99999999
  • -O 'logging.filter="debug"'
  • -O 'server_name="example.com"'

Relevance of configuration settings

Settings are read in this order, with later explicit values taking precedence:

  1. The file selected by CONDUIT_CONFIG.
  2. The file selected by CONDUWUIT_CONFIG.
  3. The file selected by TUWUNEL_CONFIG.
  4. Files selected with -c, in command-line order.
  5. Settings supplied through CONDUIT_ environment variables.
  6. Settings supplied through CONDUWUIT_ environment variables.
  7. Settings supplied through TUWUNEL_ environment variables.
  8. Individual -O assignments, in command-line order.

This order applies regardless of spelling. For example, rocksdb.checksums in a later file overrides rocksdb_checksums in an earlier file, and the reverse works too. A later assignment leaves unrelated settings from earlier sources intact. Ordinary array overrides replace the array.

For settings moved into the hierarchy, two spellings of the same setting in one file or one environment namespace are an error, even when their values agree. This includes supported aliases. Use only one spelling per source. Each -O occurrence is a separate source, so repeated assignments use the last occurrence, including a mixture of old and canonical spellings.

Environment variables

Use uppercase names with a supported prefix and double underscores between hierarchy components. Single underscores remain part of a setting’s name. For example, http.max_request_size becomes TUWUNEL_HTTP__MAX_REQUEST_SIZE, and well_known.server becomes TUWUNEL_WELL_KNOWN__SERVER.

Both TUWUNEL_ROCKSDB__CHECKSUMS and the old TUWUNEL_ROCKSDB_CHECKSUMS spelling are supported, but setting both in the same environment namespace is an error. The CONDUIT_ and CONDUWUIT_ prefixes support the same old and canonical paths. The config-file selectors CONDUIT_CONFIG, CONDUWUIT_CONFIG and TUWUNEL_CONFIG keep their existing names.

The restore control described above remains restricted to its dedicated command-line flag.

Execute commandline flag

Tuwunel supports running admin commands on startup using the commandline argument --execute. The most notable use for this is to create an admin user on first startup.

The syntax of this is a standard admin command without the prefix such as ./tuwunel --execute "users create_user june"

An example output of a success is:

INFO tuwunel_service::admin::startup: Startup command #0 completed:
Created user with user_id: @june:girlboss.ceo and password: `<redacted>`

This commandline argument can be paired with the --option flag.

Examples

Example configuration

Example configuration
### Tuwunel Configuration
###
### THIS FILE IS GENERATED. CHANGES/CONTRIBUTIONS IN THE REPO WILL BE
### OVERWRITTEN!
###
### You should rename this file before configuring your server. Changes to
### documentation and defaults can be contributed in source code at
### src/core/config/. This file is generated when building.
###
### Any values pre-populated are the default values for said config option.
###
### At the minimum, you MUST edit all the config options to your environment
### that say "YOU NEED TO EDIT THIS".
###
### For more information, see:
### https://tuwunel.chat/configuration.html


################################################################################
# Global settings
#
# Every setting lives under `[global]`. The first keys below name the
# server and its storage; each `[global.<name>]` section further down is
# optional and keeps its defaults when left out.
#
# Before the first start, set `server_name` and check `database_path`.
# The first start records `server_name` in the database, and a database
# recorded under another name is refused, so changing the name later
# means starting over with an empty database. `database_path` holds the
# database and, by default, uploaded media.
#
# Tips:
# - No config file is read by default. Name one with `TUWUNEL_CONFIG`
#   (or `CONDUWUIT_CONFIG`, `CONDUIT_CONFIG`) or with `-c`/`--config`,
#   which is repeatable and loads after it; later files win. A file that
#   mixes bare keys with a `[global]` header is refused.
# - Environment variables override files: `TUWUNEL_` plus the key path
#   with `__` between levels, so `database.backup.path` becomes
#   `TUWUNEL_DATABASE__BACKUP__PATH`. `-O key=value` overrides both.
# - Keys marked `reloadable: yes` apply on `SIGUSR1` or
#   `!admin server reload-config`; others may need a restart. A reload
#   that changes `server_name` fails.
# - Misspelled keys are ignored, not rejected; most log a warning, and
#   `configuration.error_on_unknown_opts = true` makes that fatal.
#
[global]

# The server_name is the pretty name of this server. It is used as a
# suffix for user and room IDs/aliases.
#
# See the docs for reverse proxying and delegation:
# https://tuwunel.chat/deploying/generic.html#setting-up-the-reverse-proxy
#
# Also see the `[global.well_known]` config section at the very bottom.
#
# Examples of delegation:
# - https://matrix.org/.well-known/matrix/server
# - https://matrix.org/.well-known/matrix/client
#
# YOU NEED TO EDIT THIS. THIS CANNOT BE CHANGED AFTER WITHOUT A DATABASE
# WIPE.
#
# example: "girlboss.ceo"
#
#server_name =

# This is the only directory where tuwunel will save its data, including
# media. Note: this was previously "/var/lib/matrix-conduit".
#
#database_path = "/var/lib/tuwunel"

# Examples:
#
# - No proxy (default):
#
#       proxy = "none"
#
# - For global proxy, create the section at the bottom of this file:
#
#       [global.proxy]
#       global = { url = "socks5h://localhost:9050" }
#
# - To proxy some domains:
#
#       [global.proxy]
#       [[global.proxy.by_domain]]
#       url = "socks5h://localhost:9050"
#       include = ["*.onion", "matrix.myspecial.onion"]
#       exclude = ["*.myspecial.onion"]
#
# Include vs. Exclude:
#
# - If include is an empty list, it is assumed to be `["*"]`.
#
# - If a domain matches both the exclude and include list, the proxy will
#   only be used if it was included because of a more specific rule than
#   it was excluded. In the above example, the proxy would be used for
#   `ordinary.onion`, `matrix.myspecial.onion`, but not
#   `hello.myspecial.onion`.
#
#proxy = "none"

# Arbitrary argument vector for integration testing. Functionality in the
# server is altered or informed for the requirements of integration tests.
# - "smoke" performs a shutdown after startup admin commands rather than
#   hanging on client handling.
#
#test = false

# Indicates the server has started in maintenance mode. Historically
# maintenance mode has been enabled by the command line argument
# `--maintenance` which then sets various configuration items such as
# `listening=false` among others. That is still the case. This option was
# only added as a single source of truth that `--maintenance` mode is
# active.
#
# This option must never be set manually.
#
#maintenance = false

# Enables listener sockets; can be set to false to disable listening. This
# option is intended for developer/diagnostic purposes only.
#
#listening = true

# Directory containing appservice yaml registration files.
#
#appservice_dir = ""

# Apply pending database migrations on startup. This option is intended for
# developer debugging and testing only. Never set this option to false
# unless you have been instructed to do so. Setting this option to false
# may cause permanent damage and permanent loss of data.
#
# Any new database migrations will not be applied on startup, and the
# database schema version will not be adjusted. These migrations and
# schema changes may be expected by the current codebase but may not be
# available when this option is set to false.
#
# Setting this option to false is accepted only after the required local
# state memo invalidation has run once. Start once with this option true if
# startup reports that prerequisite missing. With the marker present,
# false continues to skip migrations as configured.
#
#database_migrations = true


################################################################################
# Server administration
#
# Controls how admin commands run and how their output is posted. Admins
# are the accounts joined to the admin room, `#admins:<server_name>` (see
# `[global.admin.room]`), where a text message starting with `!admin` or
# the server user's ID (`@conduit:<server_name>` by default) runs a
# command. Commands can also run from the terminal console (`--console`),
# at startup (`execute` or `--execute`), or on `SIGUSR2` (`signal_execute`).
#
# Tips:
# - On a new server the first account to register becomes an admin while
#   `registration.grant_admin_to_first_user` is on (the default). Grant more
#   with `!admin users make-user-admin <username>`.
# - To regain admin access, start the server once with
#   `--execute "users make-user-admin <username>"`, or run that command in
#   the console. See
#   <https://tuwunel.chat/troubleshooting.html#lost-access-to-admin-room>.
#
#[global.admin]

# Allows admins to run commands outside the admin room by prefixing
# messages with "\!admin" or "\\!admin".
#
# Follow the prefix with a normal command, as in the "#admins" room; the
# reply is publicly visible in the current room and originates from the
# sender. This is disabled by default because we cannot distinguish a
# typed command from a forwarded message or an account bot's repost.
# Message formatting can also hide a command from the admin.
#
# reloadable: yes
# example: \\!admin debug ping puppygock.gay
#
#escape_commands = false

# Activates the admin console automatically at startup.
#
# The console command-line argument also enables it. Activation requires
# standard input to be a terminal.
#
#console_automatic = false

# Lists admin commands to execute at startup.
#
# The execute command-line argument also configures these commands and
# supports shell commands and environment-variable expansion. A shell
# can, for example, supply `server admin-notice tuwunel has started up at
# $(date)` as the execute argument.
#
# example: ["debug ping puppygock.gay", "debug echo hi"]
#
#execute = []

# Ignores failures in startup admin commands.
#
# When false, a failing command supplied by the execute command-line
# argument or `admin.execute` prevents startup.
#
# reloadable: yes
#
#execute_errors_ignore = false

# Lists admin commands to execute on SIGUSR2.
#
# This is like `admin.execute`, but runs when the signal arrives on
# supporting platforms.
#
# reloadable: yes
#
#signal_execute = []

# Sets the maximum log level captured during admin commands.
#
# The default is info for release builds and debug for debug builds.
#
# reloadable: yes
#
#log_capture = "info"

# Sets the localpart of the server's administrative user.
#
# The identity becomes durable after first boot. Changing it on an
# existing database is unsupported and prevents startup.
#
#server_user_localpart = "conduit"

# Selects a room for user, room, and event reports instead of the admin
# room.
#
# Accepts a room ID or alias, and the server user must be joined with
# permission to post. Reports fall back to the admin room when unset,
# unresolvable, or the server user is not a member.
#
# reloadable: yes
#
#report_room = (none)

# Limits message events used for an admin command's output replies.
#
# Output requiring more events is uploaded to the media repository and
# returned as a text attachment replying to the command. With 1, output
# fitting one event is a single reply and larger output becomes an
# attachment. With 0, output is always an attachment regardless of size.
#
# reloadable: yes
#
#output_max_events = 1

# Posts admin-command output in a thread on the command event instead of
# replies.
#
# Output split across events by `admin.output_max_events` stays in one
# thread. Attachments are also posted in that thread.
#
# reloadable: yes
#
#output_threads = false


################################################################################
# Admin room
#
# The invite-only room whose members are the server's admins. It is created
# the first time the server starts with an empty database, under the alias
# `#admins:<server_name>`, with the server user in charge.
# `!admin users make-user-admin <username>` joins a local account to it.
#
# Tips:
# - `create` and `federate` act only at that first start; changing them
#   later neither creates nor alters the room.
# - The server finds the room through its `#admins:<server_name>` alias and
#   treats it as the admin room only while the server user is joined. With
#   `create` off, the alias removed or the server user gone from the room,
#   there is no admin room and only the server user is an admin.
#
#[global.admin.room]

# Logs guest registrations in the admin room, which may be noisy or
# unnecessary on a public server.
#
# reloadable: yes
#
#log_guest_registrations = false

# Sets the default tag applied to the admin room, with `m.server_notice`
# providing a dedicated, easily accessed shortcut pinned at the bottom of
# the room list in clients such as Element.
#
# reloadable: yes
#
#tag = "m.server_notice"

# Creates the admin room on first startup and should remain enabled for
# users, though developers can disable it in integration tests to reduce
# activity and output.
#
#create = true

# Enables federation for the admin room.
#
# This cannot be changed after the room is created.
#
#federate = true

# Sends administrative notices to the admin room.
#
# These include registrations, password changes, account deactivations,
# and room-directory publications. Update notices and ordinary
# admin-command responses are sent regardless.
#
# reloadable: yes
#
#notices = true


################################################################################
# Application services (bridges and bots)
#
# Registers an appservice inline, instead of through a registration file
# in `appservice_dir` or `!admin appservices register`. Add one table per
# appservice, with its namespaces in `[[global.appservice.<ID>.users]]`,
# `rooms` and `aliases` tables. Inline appservices load at startup; a
# config reload does not apply changes here.
#
# - `<ID>`: your name for this appservice. It becomes the registration
#   `id` used by `!admin appservices` commands (an explicit `id` key must
#   match it), and the bot user is `@<ID>:<server_name>` unless
#   `sender_localpart` is set. It must be unique across all appservices.
#   Lowercase letters, digits, `_` and `-` suit both a bare key and a
#   localpart; anything else must be quoted
#   (`[global.appservice."my.bridge"]`), and an unquoted dot splits the
#   name into nested tables.
#
# `as_token` and `hs_token` are required and must match the bridge's
# registration; `url` is where events are sent (omit it if none are
# needed).
#
# Example:
#
#     [global.appservice.whatsapp]
#     url = "http://127.0.0.1:29318"
#     as_token = "CHANGE_ME_AS_TOKEN"
#     hs_token = "CHANGE_ME_HS_TOKEN"
#
# Tips:
# - An `id` or `as_token` that another registration also uses (inline,
#   in `appservice_dir` or from the admin room) aborts appservice loading
#   at startup, and registrations after it are not loaded; unregister an
#   admin-room copy before moving it here. The admin commands can neither
#   register over nor unregister an inline appservice.
#
#[global.appservice.<ID>]

# The URL for the application service.
#
# Optionally set to `null` if no traffic is required.
#
# On Unix, use `unix:///absolute/path.sock` to connect over a Unix socket.
#
# example: "unix:///run/mautrix-whatsapp/appservice.sock"
#
#url =

# A unique token for application services to use to authenticate requests
# to Homeservers.
#
#as_token =

# A unique token for Homeservers to use to authenticate requests to
# application services.
#
#hs_token =

# The localpart of the user associated with the application service.
#
#sender_localpart =

# Whether requests from masqueraded users are rate-limited.
#
# The sender is excluded.
#
#rate_limited = false

# The external protocols which the application service provides (e.g.
# IRC).
#
#protocols = []

# Whether the application service wants to receive ephemeral data.
#
#receive_ephemeral = false

# Whether the application service wants to do device management, as part
# of MSC4190.
#
#device_management = false

# Whether the application service wants MSC3202 transaction extensions
# (device lists, one-time-key counts, and unused fallback key types).
#
# The registration-file key is `org.matrix.msc3202`; this inline-config
# key is `msc3202_transaction_extensions`.
#
#msc3202_transaction_extensions = false

# Scopes the application service requests, as part of MSC4502.
#
# The registration-file key is `io.element.msc4502.scopes`; this
# inline-config key is `scopes`. The one known scope,
# `urn:matrix:client:io.element.msc4502:rooms:is_joined`, lets the
# appservice ask whether any user or server is joined to a room. An
# unknown scope grants nothing and is logged as a warning at startup.
#
#scopes = []

# The path prefix the application service claims for proxied requests,
# as part of MSC4512.
#
# The registration-file key is `io.element.msc4512.proxy_prefix`; this
# inline-config key is `proxy_prefix`. Authenticated requests under
# `/_matrix/client/<version>/<prefix>` and
# `/_matrix/federation/<version>/<prefix>` are forwarded to `proxy_url`,
# and the appservice may send federation requests under the prefix
# through the MSC4512 `fed_proxy` endpoint. The one allowed prefix is
# `rtc/livekit`. Give it together with `proxy_url`; an invalid claim, or
# one another appservice holds, is ignored with a warning at startup.
#
# example: "rtc/livekit"
#
#proxy_prefix =

# The URL proxied requests under `proxy_prefix` are forwarded to, as part
# of MSC4512.
#
# The registration-file key is `io.element.msc4512.proxy_url`; this
# inline-config key is `proxy_url`. It takes the forms `url` takes,
# `unix:///absolute/path.sock` included.
#
# example: "http://lk-jwt-service:8080"
#
#proxy_url =


################################################################################
# Appservice namespaces
#
# Claims the user IDs, room aliases or room IDs an appservice manages.
# Each `[[...]]` header appends one entry to the list it names, so repeat
# the header for more patterns. The appservice may act only as users
# matching `users` and create only aliases matching `aliases`; the server
# sends it events from rooms that hold its users or match its `aliases` or
# `rooms` entries.
#
# - `<ID>`: the `<ID>` of the `[global.appservice.<ID>]` table this entry
#   belongs to, spelled (and quoted) the same way.
# - `<users|rooms|aliases>`: one of the literal names `users` (user IDs
#   on this server), `aliases` (room aliases) or `rooms` (room IDs). Any
#   other name is ignored without a warning.
#
# `regex` is required. Matching is unanchored (add `^` and `$`),
# case-insensitive for `users` and `aliases`, case-sensitive for `rooms`.
# Write the pattern as a single-quoted TOML string so backslashes stay
# literal.
#
# Example:
#
#     [[global.appservice.whatsapp.users]]
#     exclusive = true
#     regex = '^@whatsapp_.*:example\.com$'
#
# Tips:
# - `exclusive = true` stops ordinary users from registering matching user
#   IDs or creating matching aliases; on `rooms` entries it has no effect.
#
#[[global.appservice.<ID>.<users|rooms|aliases>]]

# Whether this application service has exclusive access to events within
# this namespace.
#
#exclusive = false

# A regular expression defining which values this namespace includes.
#
#regex =


################################################################################
# Appservice HTTP client
#
# Timeouts for the requests the server makes to appservices (bridges and
# bots). The defaults assume each appservice runs on the same host or
# network; raise `timeout` when one is remote or slow to answer.
#
#[global.appservice_client]

# Sets appservice URL read and total timeouts in seconds, defaulting to
# 35 because appservices are generally hosted on the same network.
#
#timeout = 35

# Sets the appservice URL idle connection-pool timeout in seconds.
#
#idle_timeout = 300


################################################################################
# Authentication and sessions
#
# Server-wide credentials and token lifetimes, plus the sub-sections that
# decide how users sign in: `[global.authentication.login]` (accepted login
# methods and SSO presentation), `[global.authentication.oidc]` (the
# built-in OIDC server for next-generation clients),
# `[global.authentication.argon2]` (password-hash cost) and
# `[global.authentication.refresh_token]` (refresh-token expiry and reuse).
# The defaults suit a password-login server. Other sign-in sources have
# their own sections: `[[global.identity_provider]]`, `[global.jwt]` and
# `[global.ldap]`.
#
# Tips:
# - Startup refuses an empty `emergency_password` and the example value
#   shown below; while `ldap.enable` is true the emergency password is
#   ignored with a warning.
# - `mas_secret` only authorizes Matrix Authentication Service provisioning
#   calls under `/_synapse/mas/`. Signing in through MAS also needs an
#   `[[global.identity_provider]]` entry with `brand = "MAS"`; startup warns
#   when it is missing.
# - `access_token_ttl` applies only to sessions holding a refresh token (see
#   `[global.authentication.refresh_token]`) and, under
#   `jwt.expire_access_token`, to JWT logins.
#
#[global.authentication]

# Authenticates Matrix Authentication Service provisioning calls with a
# shared secret.
#
# When set, the `/_synapse/mas/*` endpoints accept only requests bearing
# this exact secret as their bearer token; when unset, they reject every
# request. Use a high-entropy value identical to the secret configured in
# MAS.
#
# reloadable: yes
# example: "kZ2hN5pQ8wXyL4mR7tBfCgJxV3aD6sE1u"
#
#mas_secret =

# Sets the OpenID token lifetime in seconds.
#
# These tokens primarily serve Matrix account integrations, such as
# Vector Integrations in Element, rather than OIDC or OpenID Connect.
#
# reloadable: yes
#
#openid_token_ttl = 3600

# Sets the access-token lifetime in seconds.
#
# For clients supporting refresh tokens, the access token supplied at
# login is invalidated after this interval, soft-logging out the client
# until it refreshes. Under `jwt.expire_access_token`, a JWT login expires
# the same way and needs a fresh JWT instead.
#
# reloadable: yes
#
#access_token_ttl = 604800

# Allows emergency login to the server bot account, currently `@conduit`.
#
# Use it for troubleshooting such as recovering or recreating the admin
# room or inviting yourself back. Other recovery methods are described in
# the [admin-room troubleshooting
# guide](https://tuwunel.chat/troubleshooting.html#lost-access-to-admin-room).
# Unsetting this password logs out all sessions for security.
#
# example: "F670$2CP@Hw8mG7RY1$%!#Ic7YA"
#
#emergency_password =


################################################################################
# Password hashing cost
#
# Sets the Argon2id cost used whenever a password is hashed. Existing hashes
# keep the cost they were created with until that password is next set, so
# a change takes effect gradually. The defaults follow the OWASP
# recommendation.
#
# Tips:
# - Startup and reload refuse a combination Argon2 rejects, such as
#   `m_cost` below eight blocks per lane of `p_cost`, and warn when the cost
#   falls below the weakest OWASP pair listed under `m_cost`.
#
#[global.authentication.argon2]

# Sets the Argon2id working-buffer size for hashing a new password, in 1
# KiB blocks.
#
# Each concurrent password operation retains roughly this much memory
# for its duration, with no concurrency bound. Stored hashes retain their
# parameters until the account's password is next set.
#
# Lowering this weakens resistance to parallel cracking hardware unless
# `authentication.argon2.t_cost` compensates; equivalent-strength
# (`authentication.argon2.m_cost`, `authentication.argon2.t_cost`) pairs
# are (47104, 1), (19456, 2), (12288, 3), (9216, 4), and (7168, 5). The
# default and these pairs follow the [OWASP Argon2id
# recommendation](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id).
#
# reloadable: yes
#
#m_cost = 19456

# Sets the number of Argon2id passes over its working buffer.
#
# Raising this increases CPU cost without changing memory cost. See
# `authentication.argon2.m_cost` for equivalent-strength parameter pairs.
#
# reloadable: yes
#
#t_cost = 2

# Sets the number of lanes in an Argon2id working buffer.
#
# Lanes are computed sequentially here, so raising this changes the hash
# without adding parallelism. `authentication.argon2.m_cost` must be at
# least eight times this value.
#
# reloadable: yes
#
#p_cost = 1


################################################################################
# Login methods
#
# Chooses which login types `/_matrix/client/v3/login` advertises and
# accepts, how long login tokens last, and how clients present single
# sign-on providers. The defaults accept passwords and login tokens, and let
# a signed-in session mint a login token for another device.
#
# Tips:
# - `with_password = false` also turns off `[global.ldap]` sign-in, which
#   arrives as a password login, and refuses password registration.
# - JWT login is switched on by `jwt.enable`, not here; password attempt
#   limits live in `[global.rate_limiting.login]`.
#
#[global.authentication.login]

# Allows an existing session to mint a login token for another client.
#
# This requires interactive authentication and is enabled by default. A
# malicious client could use it to spawn additional sessions, so enabling
# it has security implications.
#
# reloadable: yes
#
#via_existing_session = true

# Enables the login-token route to accept tokens.
#
# The server can generate tokens for authorization flows such as SSO,
# which disabling this may break. This differs from
# `authentication.login.via_existing_session` and lacks that setting's
# security implications: keep this enabled while disabling the other to
# prevent clients from commanding token creation without preventing the
# server from creating tokens.
#
# reloadable: yes
#
#via_token = true

# Enables traditional username-and-password login.
#
# Disable this to allow only other mechanisms, such as SSO. Disabling it
# also refuses password registration, at `/register` and on the native
# OIDC login page, which then offers only the identity providers;
# appservice and guest registration are unaffected.
#
# reloadable: yes
#
#with_password = true

# Sets the login-token lifetime in milliseconds.
#
# These short-lived tokens serve `m.login.token`, allowing existing
# sessions to create new sessions. See
# `authentication.login.via_existing_session`.
#
# reloadable: yes
#
#token_ttl = 120000

# Experimentally replaces the client login provider list with one "Sign
# in with single sign-on" button.
#
# The button links to `/_matrix/client/v3/login/sso/redirect`, attempting
# every configured provider for the same Matrix user; every authorization
# must succeed because providers cannot reliably be skipped. Disabled by
# default, it otherwise lets clients list providers so privacy-conscious
# users can authorize only their choice. For clients that already show
# one button, use the provider configuration's `default` option instead.
#
# reloadable: yes
#
#single_sso = false

# Replaces the client login provider list with one button for a custom
# provider page.
#
# The "Sign in with single sign-on" button links to
# `/_matrix/client/v3/login/sso/redirect`, which the deployment's reverse
# proxy must intercept to serve a custom list. Each entry links or
# redirects to its configured provider at
# `/_matrix/client/v3/login/sso/redirect/<client_id>`. The default false
# lets clients generate their provider list or hide SSO options when none
# are configured.
#
# reloadable: yes
#
#sso_custom_providers_page = false

# Prefers OIDC-aware authentication under
# [MSC3824](https://github.com/matrix-org/matrix-spec-proposals/pull/3824).
#
# When clients find `oauth_aware_preferred` true and support that
# authentication type, they should present it as the only login or
# registration method.
#
# reloadable: yes
#
#oidc_aware_preferred = false


################################################################################
# Built-in OIDC server (next-generation login)
#
# Provides a built-in OAuth 2.0 and OpenID Connect authorization server
# for clients using next-generation Matrix authentication (MSC2965). It
# runs only when `well_known.client` is set (it becomes the issuer URL)
# and at least one `[[global.identity_provider]]` exists or `native_auth`
# is true; otherwise these keys have no effect. Without `native_auth`,
# sign-in goes through the default identity provider; with it, a login
# page offers local accounts alongside the providers.
#
# Minimal example (local accounts):
#
#     [global.well_known]
#     client = "https://matrix.example.com"
#
#     [global.authentication.oidc]
#     native_auth = true
#
# Tips:
# - Whether the OIDC server runs is decided at startup: enabling it on a
#   running server takes a restart.
# - Startup warns when `registration_access_token` is set (no Matrix client
#   sends one), when `require_client_approval` is false, and when
#   `native_auth` has neither password login nor a provider to offer.
# - The endpoint throttle needs both `rc_per_second` and `rc_burst_count`
#   above zero; password checks on the built-in login page count against
#   `[global.rate_limiting.login]` instead.
#
#[global.authentication.oidc]

# Enables native registration and login on the built-in OIDC provider.
#
# This authenticates next-generation Matrix clients against local
# accounts without a third-party `identity_provider`; when false, as by
# default, the provider only brokers authentication through a configured
# upstream provider. When true, requests selecting no provider receive a
# login or registration page and require `well_known.client`; the login
# page offers local accounts and configured providers, with one SSO entry
# under `authentication.login.single_sso` or
# `authentication.login.sso_custom_providers_page`. An explicit `idp_id`
# goes directly to its provider. Registration honors
# `registration.enable`, the registration token, and root
# `registration_terms` exactly as client registration does.
#
# reloadable: yes
#
#native_auth = false

# Sets how long a browser stays signed in after a password sign-in on the
# built-in login page, in seconds.
#
# While it lasts, approving a new device from that browser, as in QR code
# login, goes straight to the approval page without asking for the
# password again. The lifetime counts from the sign-in and is not extended
# by use; a lowered value applies to existing sign-ins at once, a value
# above 7776000 (90 days) counts as 90 days, and 0 turns browser sign-in
# off. Changing the password, deactivating the account or signing out of
# all devices ends it early.
#
# reloadable: yes
#
#browser_session_ttl = 2592000

# Requires OIDC clients to request an
# [MSC2967](https://github.com/matrix-org/matrix-spec-proposals/pull/2967)
# device scope.
#
# When false, clients omitting `urn:matrix:client:device:<id>` receive a
# server-generated device ID echoed in the granted scope. When true,
# authorization-code grants without a device scope are rejected,
# following the proposal's expectation that clients own their device IDs.
#
# reloadable: yes
#
#require_device_scope = false

# Requires [RFC 7636](https://www.rfc-editor.org/rfc/rfc7636) PKCE with
# S256 on OIDC authorization-code grants.
#
# When true, the authorize endpoint rejects requests without
# `code_challenge`, as
# [MSC2964](https://github.com/matrix-org/matrix-spec-proposals/pull/2964)
# mandates for public clients. A supplied challenge must always use S256,
# and `plain` is rejected regardless of this setting. Disable only
# temporarily for a legacy client unable to send a challenge.
#
# reloadable: yes
#
#require_pkce = true

# Rejects OIDC authorization-code grants containing unrecognized scopes
# instead of narrowing the grant.
#
# When false, as by default, unknown scope tokens are dropped and the
# narrowed `scope` is echoed to the client under [RFC
# 6749](https://www.rfc-editor.org/rfc/rfc6749); when true, an unknown
# scope is rejected. `openid` and both spellings of the
# [MSC2967](https://github.com/matrix-org/matrix-spec-proposals/pull/2967)
# device and API scopes are always recognized.
#
# reloadable: yes
#
#strict_scope = false

# Requires an initial access token for dynamic OIDC client registration
# under [RFC 7591](https://www.rfc-editor.org/rfc/rfc7591).
#
# When set, callers must supply it as an `Authorization: Bearer`
# credential; clients that omit it cannot dynamically register for
# next-generation login. Leave empty unless every OAuth client is
# registered out of band.
#
# reloadable: yes
#
#registration_access_token =

# Lists permitted hosts and private-use schemes for dynamically
# registered OIDC redirect URIs.
#
# When nonempty, every redirect URI must match or registration is
# rejected: hosts match case-insensitively, while hostless private-use
# URIs such as `io.element.android:/` match their scheme under [RFC
# 8252](https://www.rfc-editor.org/rfc/rfc8252). For example,
# `["element.io", "io.element.android"]` covers web and mobile clients.
#
# The empty default imposes no registration restriction and vouches for
# no client, so every sign-in remains subject to
# `authentication.oidc.require_client_approval`. Listing an entry vouches
# for any responding client: a scheme covers any device app claiming it
# under [RFC 8252 section
# 8.6](https://www.rfc-editor.org/rfc/rfc8252#section-8.6), and a host
# covers every path.
#
# reloadable: yes
#
#registration_allowed_redirect_hosts = []

# Asks users to approve unvetted OIDC clients before issuing
# authorization codes.
#
# Dynamic registration is open by default, so anyone can register a
# controlled redirect target and send users an authorization link;
# without confirmation, one click gives that client an account
# authorization code. When true, as by default, unvetted sign-ins first
# show an approve/deny page naming the client. A host or private-use
# scheme listed in
# `authentication.oidc.registration_allowed_redirect_hosts` vets its
# client and restores prompt-free sign-in. When showing this prompt,
# allow enough `authentication.login.token_ttl` for users to read it.
#
# reloadable: yes
#
#require_client_approval = true

# Requires `client_uri` in dynamic registration under [RFC
# 7591](https://www.rfc-editor.org/rfc/rfc7591) and
# [MSC2966](https://github.com/matrix-org/matrix-spec-proposals/pull/2966).
#
# When false, as by default, it is optional; any supplied URI still
# requires HTTPS, a host, and no userinfo, and other request URLs must
# share that host or a subdomain. When true, registrations lacking an
# HTTPS `client_uri` fail with `invalid_client_metadata`, enforcing the
# common-base model for every client.
#
# reloadable: yes
#
#registration_require_client_uri = false

# Sets the per-client-IP token-bucket refill rate for OIDC endpoints in
# requests per second.
#
# The throttle is shared across authorize, token, dynamic-registration,
# and device-grant endpoints. The default 0 disables it and preserves
# open access; raise this with `authentication.oidc.rc_burst_count` to
# protect an exposed server. Because the key is client IP, rates that
# limit brute force can also affect many users behind one NAT, so size
# the burst accordingly.
#
# reloadable: yes
#
#rc_per_second = 0

# Sets the token-bucket depth for the OIDC endpoint throttle.
#
# This is the requests one client IP can make in a burst before
# `authentication.oidc.rc_per_second` governs replenishment. It is
# ignored when that refill rate is 0.
#
# reloadable: yes
#
#rc_burst_count = 0


################################################################################
# Refresh-token expiry and reuse
#
# Applies to sessions that hold a refresh token: clients that request one
# at login or registration, and every client signed in through the built-in
# OIDC server. By default refresh tokens never expire, and a replay outside
# the 15-second grace window removes the device. Set `ttl` to expire idle
# sessions (`idle_only`) or sessions of a fixed age;
# `authentication.access_token_ttl` sets the access-token lifetime between
# refreshes.
#
#[global.authentication.refresh_token]

# Sets the refresh-token lifetime in seconds.
#
# Tokens are rejected after this interval;
# `authentication.refresh_token.idle_only` determines whether the
# deadline slides with use or stays fixed at issuance. The default 0
# disables refresh-token expiry entirely. A typical enabled value is
# 259200, or three days.
#
# reloadable: yes
#
#ttl = 0

# Uses the refresh-token lifetime as an idle timeout instead of an
# absolute session lifetime.
#
# With a nonzero `authentication.refresh_token.ttl`, true, the default,
# resets the deadline to now plus that lifetime after each successful
# rotation; false retains an existing deadline rather than extending it. A
# successful grace replay retains its current successor and does not
# reset that successor's deadline. A zero TTL issues replacement tokens
# without expiry.
#
# reloadable: yes
#
#idle_only = true

# Removes the device on refresh-token expiry instead of soft-logging out.
#
# When false, as by default, expiry returns `M_UNKNOWN_TOKEN` with
# `soft_logout: true`, allowing the client to retain E2EE keys and local
# state and reauthenticate on the same device. When true, expiry
# invalidates the access token, deletes the device record, and signals
# `soft_logout: false`; the next session uses a new device and cannot
# recover E2EE history from local state alone, trading usability for the
# [CWE-613](https://cwe.mitre.org/data/definitions/613.html) guarantee.
# Tokens issued with zero TTL do not expire, and changing the current TTL
# does not remove an already stored expiry.
#
# reloadable: yes
#
#hard_logout = false

# Sets the grace window in seconds for a benign refresh-token double
# submission.
#
# After rotation, the spent token is retained for one generation; within
# a nonzero window, a replay can issue a fresh access token while
# retaining its current, resolvable, unexpired successor. An expired
# successor triggers the configured expiry logout, while an unresolvable
# successor is refused without changes.
#
# A token classified as spent outside grace on arrival is rejected, with
# device revocation only when `authentication.refresh_token.reuse_revoke`
# is enabled; zero disables grace. A request current on arrival but spent
# while waiting for the device lock can instead be refused without
# revocation, including at zero grace.
#
# reloadable: yes
#
#reuse_grace = 15

# Revokes the device when refresh-token reuse is detected.
#
# When true, as by default, reuse detected outside
# `authentication.refresh_token.reuse_grace` on arrival removes the
# device under the
# [RFC 6819](https://www.rfc-editor.org/rfc/rfc6819) compromised-session
# model. When false, the replayed request is rejected but the device
# remains intact, a less restrictive behavior operators using another
# OAuth client may prefer.
#
# reloadable: yes
#
#reuse_revoke = true


################################################################################
# Cache sizes
#
# Sizes the RocksDB block caches reserved for specific database columns,
# and the in-memory room state cache (`stateinfo_capacity`). Capacities
# count entries, not bytes. Most columns without a key here share one
# cache carved from `rocksdb.cache_capacity_mb`. Sizes are fixed at
# startup.
#
# Tips:
# - `capacity_modifier` also scales `rocksdb.write_buffer_capacity_mb`,
#   but not `rocksdb.cache_capacity_mb`.
#
#[global.cache]

# Multiplies cache capacities by a floating-point factor.
#
# Increase this value to use spare memory for performance, or reduce it
# when memory is limited. Individual capacities such as
# `cache.auth_chain_capacity` scale with the CPU core count by default.
#
#capacity_modifier = 1.0

# Maximum number of entries in the RocksDB block cache shared by the
# `pduid_pdu` and `eventid_outlierpdu` column families: a PDU's full
# body, keyed by its PDU ID, and the same body keyed by event ID when
# the PDU is an outlier.
#
# This is an entry count, not a byte size. The cache's actual capacity
# in bytes is this value multiplied by an internal per-column-family
# key+value size estimate, then multiplied by `cache.capacity_modifier`.
# Scaled by your CPU core count by default; see
# `cache.capacity_modifier` to scale this along with the other
# individual LRU caches at once.
#
#pdu_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `authchainkey_authchain` column family: a room event's full auth
# chain, keyed by the set of events the chain was derived from.
#
# Same entry-count semantics as `cache.pdu_capacity` above; see there
# for how this becomes a byte capacity and how
# `cache.capacity_modifier` applies.
#
#auth_chain_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `shorteventid_eventid` column family: an event's full event ID,
# looked up from its short event ID.
#
# Same entry-count semantics as `cache.pdu_capacity`.
#
#shorteventid_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `eventid_shorteventid` column family: an event's short event ID,
# looked up from its full event ID.
#
# This is the reverse lookup of `cache.shorteventid_capacity`.
# Same entry-count semantics as `cache.pdu_capacity`.
#
#eventidshort_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `eventid_pduid` column family: an event's PDU ID, looked up from its
# full event ID.
#
# Same entry-count semantics as `cache.pdu_capacity`.
#
#eventid_pdu_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `eventid_backoff` column family: the recent fetch, auth, upgrade, and
# delivery outcomes an event is rate-gated against, keyed by federation
# step, event ID, and time bucket.
#
# Same entry-count semantics as `cache.pdu_capacity`. A server working
# through a large missing-ancestry gap reads this column heavily.
#
#eventid_backoff_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `shortstatekey_statekey` column family: a state event's full state
# key, looked up from its short state key.
#
# Same entry-count semantics as `cache.pdu_capacity`.
#
#shortstatekey_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `statekey_shortstatekey` column family: a state event's short state
# key, looked up from its full state key.
#
# This is the reverse lookup of `cache.shortstatekey_capacity`.
# Same entry-count semantics as `cache.pdu_capacity`.
#
#statekeyshort_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `servernameevent_data` column family: outbound federation events
# (PDUs and EDUs) queued for delivery, keyed by destination server
# name.
#
# Same entry-count semantics as `cache.pdu_capacity`.
#
#servernameevent_data_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `mediaid_lazycontent` column family: preview images staged by the URL
# preview fetcher, keyed by media ID, until a download promotes the row.
#
# Same entry-count semantics as `cache.pdu_capacity`, against a modal
# 256 KiB entry. Staged rows are read once and deleted at promotion, so
# this mostly holds index blocks, and a single outsized preview can
# exceed the whole pool.
#
#mediaid_lazycontent_capacity = 128

# Maximum number of entries in the RocksDB block cache pool shared by the
# `servername_destination` and `servername_override` column families: a
# remote server's resolved federation destination, keyed by server name,
# and the address override for a resolved hostname.
#
# Same entry-count semantics as `cache.pdu_capacity`, counted across the
# pool rather than per column.
#
#resolver_capacity = varies by system

# Maximum number of entries in the RocksDB block cache for the
# `servername_status` column family: a remote server's recent
# reachability outcome, keyed by server name and time bucket.
#
# Same entry-count semantics as `cache.pdu_capacity`.
#
#servername_status_capacity = varies by system

# Maximum number of entries in the in-memory LRU cache of decompressed
# room state (a list of short state-info entries per state hash), used
# by the state compressor to avoid re-walking
# `shortstatehash_statediff` on every lookup.
#
# Unlike the other caches on this page, this one is not backed by
# RocksDB: it is a plain in-process cache sized directly in entries,
# with no per-entry byte-size conversion. `cache.capacity_modifier`
# still applies to it.
#
#stateinfo_capacity = varies by system


################################################################################
# Space hierarchy cache lifetime
#
# How long a room summary used to answer space hierarchy requests is
# cached before it is rebuilt or fetched again. Each entry expires at a
# random time between `ttl_min` and `ttl_max` seconds, which spreads
# refreshes out. Both keys apply on reload.
#
# Tips:
# - `ttl_min` must be below `ttl_max`. Startup and reload refuse an equal
#   or inverted pair.
#
#[global.cache.space_hierarchy]

# Minimum time-to-live in seconds for room summary entries in the spaces
# cache.
#
# reloadable: yes
#
#ttl_min = 10800

# Maximum time-to-live in seconds for room summary entries in the spaces
# cache.
#
# reloadable: yes
#
#ttl_max = 64800


################################################################################
# Client API
#
# Groups settings for how the server answers client requests.
# `[global.client.sync]` bounds sync long polling and turns room hero
# calculation on or off.
#
#[global.client]


################################################################################
# Client sync long polling
#
# Bounds how long a client's sync request may wait for new events before
# the server answers anyway, and whether sync computes room heroes.
#
# Tips:
# - Sliding sync honors only `timeout_max`; `timeout_min` and
#   `timeout_default` apply to legacy `/sync` and to `/events`.
# - Keep `timeout_max` (milliseconds) below `request_timeout` in
#   `[global.http]` (seconds) and below the read timeout of any reverse
#   proxy in front of the server, or long polls fail instead of returning.
#
#[global.client.sync]

# Sets the minimum requested timeout for long-polling sync.
#
# Smaller client requests are clamped up to this value.
#
# reloadable: yes
#
#timeout_min = 5000

# Sets the long-polling sync timeout when the client supplies none in its
# query string.
#
# reloadable: yes
#
#timeout_default = 30000

# Sets the maximum requested timeout for long-polling sync.
#
# Larger client requests are clamped down to this value.
#
# reloadable: yes
#
#timeout_max = 90000

# Calculates room heroes in sliding and legacy client sync.
#
# The Matrix specification requires this calculation, so clients may
# malfunction when it is disabled. Disabling is intended for custom
# software minimizing unused resources; otherwise the savings are
# negligible.
#
# reloadable: yes
#
#calculate_heroes = true


################################################################################
# Room-version compatibility
#
# Carries protections from newer room versions back to rooms on older
# versions. Its single switch is on by default and safe for existing
# rooms; leave it on unless you are debugging state resolution.
#
#[global.compatibility]

# Backports state-reset security mitigations to all supported room
# versions.
#
# This applies project Hydra's State Resolution 2.1 mitigations for room
# version 12 to prior State Resolution 2.0 versions, increasing
# resilience without redefining correctness and making it safe to enable
# for existing rooms. State-reset attacks produce rooms without one
# consensus, so disabling is unnecessary to match servers that disable or
# lack the mitigations, even when replicating their post-reset state is
# desired. The setting exists for developer and debug use and as a
# failsafe instead of being hardcoded.
#
# reloadable: yes
#
#hydra_backports = true


################################################################################
# Configuration loading and reload
#
# Controls how strictly the configuration is checked and whether `SIGUSR1`
# reloads it. By default an unknown key logs a warning and is ignored, and
# `SIGUSR1` (what `systemctl reload` sends with the packaged service units)
# re-reads every configuration source, applying the keys marked
# `reloadable: yes`.
#
# Tips:
# - A reload runs the same checks as startup. If the new configuration
#   fails them, the server keeps the running one and logs why.
#   `server_name` and `http.ip_source` cannot change on reload.
# - `reload_signal` gates only the signal; the admin command
#   `!admin server reload-config` reloads regardless.
# - Guide: <https://tuwunel.chat/deploying/configuration-reload.html>.
#
#[global.configuration]

# Rejects startup when an unknown configuration option is specified,
# whereas the default false warns to allow future deprecation or removal
# of options without breaking existing deployments.
#
# reloadable: yes
#
#error_on_unknown_opts = false

# Reloads configuration on SIGUSR1 on supporting platforms when enabled.
#
# reloadable: yes
#
#reload_signal = true


################################################################################
# Database backups and worker pool
#
# Holds two sub-sections: `[global.database.backup]` for online backups,
# which stay unavailable until `database.backup.path` is set, and
# `[global.database.pool]` for the threads that serve database requests,
# sized from the hardware at startup. The database location is
# `database_path` under `[global]`; engine tuning is in `[global.rocksdb]`.
#
#[global.database]


################################################################################
# Online database backups
#
# Copies the RocksDB database into a backup repository while the server
# keeps running. Backups are unavailable until `path` names a directory
# the server can write to, and even then run only on request, with
# `!admin server backup-database`. Both keys apply on reload.
#
# Tips:
# - `keep` defaults to 1, so each backup replaces the previous one; raise
#   it to retain more.
# - Backups hold the database only. Media stored under `database_path` or
#   in storage providers needs its own copy.
# - For scheduled backups, add `"server backup-database"` to
#   `admin.signal_execute` and send the server `SIGUSR2` from a timer.
# - To restore, stop the server and start it with `--restore-backup`; it
#   replaces the database at `database_path` before opening it. See
#   <https://tuwunel.chat/backups.html>.
#
#[global.database.backup]

# Selects a writable directory for online database backups.
#
# Backups use the RocksDB Backup engine API. See
# https://tuwunel.chat/maintenance.html#backups for setup and
# maintenance.
#
# reloadable: yes
# example: "/opt/tuwunel-db-backups"
#
#path =

# Sets how many online RocksDB backups to retain.
#
# When `database.backup.path` is configured, the oldest backups are
# deleted to enforce this limit. The value must be at least 1;
# `backup-database` returns an error at 0 or below.
#
# reloadable: yes
#
#keep = 1


################################################################################
# Database worker pool
#
# The threads that execute database reads and writes, and the queues that
# feed them. Sizes are derived when the database opens, from the CPU count
# and, where it can be detected, the queue layout of the storage device
# under `database_path`. Changes need a restart.
#
# Tips:
# - Under a cgroup task (pids) limit, as in many containers, startup warns
#   when the pool may exceed it; raise the limit or lower `max_workers`.
# - `[global.runtime.stream]` scales its concurrency from this pool.
#
#[global.database.pool]

# Pins database pool workers to the CPU cores that share their storage
# queue.
#
# It has no effect unless tuwunel was built with the `cpu_affinity`
# feature.
#
#affinity = true

# Sets the number of database frontend pool worker threads.
#
# Match the system I/O capabilities, such as queue depth or
# simultaneous requests in flight. The default is four times the
# available CPU thread count, clamped from 32 through 1024. This
# setting applies only when `database.pool.affinity` is disabled or
# unavailable; otherwise the worker count is determined automatically.
#
#workers = varies by system

# Limits each automatically detected database worker group.
#
# When `database.pool.affinity` is enabled and available, this value is
# multiplied by the number of CPU cores sharing a device queue because
# workers can run on any of those cores. The limit prevents performance
# degradation when thread pooling cannot scale to the full capacity of
# high-end hardware.
#
#workers_limit = 32

# Limits the total number of workers across all database worker groups.
#
# Worker counts are reduced when their sum exceeds this limit, but each
# populated group retains at least one worker, making the populated
# group count the effective floor. The default generally constrains
# larger systems with 16 or more cores. Thread pooling cannot reach
# full hardware capacity, but this limit can be raised on huge systems
# when groups are too small and scheduling overhead is not the
# bottleneck.
#
#max_workers = 2048

# Sets the capacity multiplier for database frontend pool request
# queues.
#
# Each queue capacity is this value multiplied by the pool worker
# count. Tokio tasks submitting requests yield when the queue is full,
# providing flow control that avoids buffer bloat. A value that is too
# low can inhibit throughput.
#
#queue_mult = 4


################################################################################
# Room and user directories
#
# Groups the two discovery directories. `[global.directory.rooms]` covers
# the public room directory: who can list it, who can publish to it, and
# how it is searched. `[global.directory.users]` covers which accounts a
# user search returns.
#
#[global.directory]


################################################################################
# Public room directory
#
# Controls who can read this server's public room directory, who can
# publish rooms to it, and how searches behave. By default only clients
# with an access token can list it, other servers cannot query it over
# federation, and any user whose power level in a room allows changing its
# history visibility can publish that room (guests cannot).
#
# Tips:
# - `lockdown` limits publishing to server admins and appservices, both
#   when a room is created and afterwards.
# - Servers that `[global.federation]` already blocks, through its
#   `forbidden_remote_server_names` or its allowlist, are refused here
#   too; this section's `forbidden_remote_server_names` adds blocks that
#   apply only to browsing a remote server's directory.
# - `forbidden_remote_server_names` takes regular expressions; startup
#   warns about a plain dotted name such as `example.com`, whose dots
#   match any character.
#
#[global.directory.rooms]

# Allows federation access to the public room directory.
#
# Disabling this protects against `/publicRooms` spiders but prevents
# external users from viewing the directory. This is inherently false
# when `federation.enable` is disabled.
#
# reloadable: yes
#
#allow_over_federation = false

# Allows client API queries of the public room directory without an
# access token, exposing it to unauthenticated `/publicRooms` spiders.
#
# reloadable: yes
#
#allow_without_auth = false

# Allows directory searches to match partial room IDs when the search
# starts with "!".
#
# reloadable: yes
#
#allow_public_search_by_id = true

# Allows room-ID searches to return joinable rooms absent from public
# listings.
#
# The default true lets users paste room IDs into search boxes to join,
# matching their expectations even when rooms opt out of public listings.
# Set false to restrict results to rooms discoverable through aliases or
# other queries, specifically those in the public directory. To prevent
# abuse, several room-ID characters must be known before results are
# returned.
#
# reloadable: yes
#
#allow_unlisted_search_by_id = true

# Restricts publishing rooms in the public directory to admins.
#
# All users can still unpublish rooms when this is enabled.
#
# reloadable: yes
#
#lockdown = false

# Blocks outgoing federated room-directory requests to server names
# matching listed regular expressions to prevent users from wandering
# into unwanted servers or spaces.
#
# reloadable: yes
# example: ['badserver\.tld$', 'badphrase', '19dollarfortnitecards']
#
#forbidden_remote_server_names = []


################################################################################
# User directory
#
# Controls which accounts a local user's directory search can find. The
# search covers local accounts and the remote users this server has seen
# in its rooms. By default it returns only users who are in a room with a
# public join rule or share a room with the searcher, and it hides users
# that belong exclusively to an appservice. Other servers cannot query
# it; federation profile lookups are set in `[global.profile]`.
#
# Tips:
# - `show_all_local` lifts the room filter for every account the server
#   knows, including those remote users, not only local accounts.
#
#[global.directory.users]

# Shows all local users in directory searches.
#
# When false, only users in public rooms or rooms shared with the
# searcher appear. Appservice senders and users in exclusive appservice
# namespaces remain hidden unless `directory.users.show_appservice` is
# also enabled.
#
# reloadable: yes
#
#show_all_local = false

# Includes appservice senders and users in exclusive appservice
# namespaces in directory searches.
#
# Normal room-visibility rules still apply unless
# `directory.users.show_all_local` is also enabled.
#
# reloadable: yes
#
#show_appservice = false


################################################################################
# End-to-end encryption
#
# Controls whether local users may use end-to-end encryption, whether the
# server turns it on by itself in new rooms, and how device keys are
# shared. Encryption is allowed by default, and with
# `enabled_by_default_for_room_type` at its default the server never
# enables it on its own; clients decide per room.
#
# Tips:
# - `enabled_by_default_for_room_type` ignores `is_direct`: `invite`
#   applies to every room created with a private preset, DM or not,
#   including a non-public room created without a preset.
# - `allow = false` also stops local users from sending encrypted messages
#   in rooms that are already encrypted.
#
#[global.encryption]

# Allows encrypted rooms and events.
#
# reloadable: yes
#
#allow = true

# Selects which locally created rooms use end-to-end encryption by
# default.
#
# "all" encrypts every created room, while "invite" encrypts rooms using
# the `private_chat` or `trusted_private_chat` preset. The explicit "none"
# value and all other values have no effect.
#
# reloadable: yes
#
#enabled_by_default_for_room_type = "none"

# Limits one-time keys per device across all algorithms.
#
# The default allows 256 keys; there is no known reason for an
# administrator to change it.
#
# reloadable: yes
#
#one_time_key_limit = 256

# Excludes unencrypted rooms when selecting common-room recipients of
# device-list updates.
#
# Enabling this can improve performance on very large servers but may
# violate the specification and client expectations.
#
# reloadable: yes
#
#device_key_update_encrypted_rooms_only = false


################################################################################
# Federation with other homeservers
#
# Controls whether this server federates and which remote servers it
# accepts. Federation is on by default and open to every server not
# matched by `forbidden_remote_server_names`. The subsections tune signing
# key lookup (`[global.federation.keys]`), the federation client
# (`[global.federation.transport]`), history recovery
# (`[global.federation.history]`) and multi-server queries
# (`[global.federation.fanout]`).
#
# To run a closed server, set `enable = false` and restart. Local users and
# rooms keep working; the federation and key endpoints answer
# `403 M_FORBIDDEN`, and requests to other servers are refused.
#
# Tips:
# - Rooms created while federation is off are not marked local-only unless
#   `rooms.federate_by_default` is also false, so they federate once it is
#   back on.
# - Server name lists are regular expressions: an unescaped dot matches any
#   character, and a plain dotted name logs a startup warning. Put escaped
#   patterns in single quotes, since TOML rejects `\.` inside double
#   quotes: `forbidden_remote_server_names = ['^evil\.example$']`.
#
#[global.federation]

# Allows federation with other servers.
#
# Disabling this after installation risks federation breakage and is not
# recommended, although the setting is not permanent.
#
#enable = true

# Derives incoming federation event state from locally held unresolved
# ancestry.
#
# When previous events are stored but unresolved, we derive state locally
# instead of requesting `/state_ids` from the origin server. This
# requires the entire unresolved local ancestry to be present; every
# other case falls back to a federation state fetch. Disabling this
# restores the previous behavior of always fetching.
#
# reloadable: yes
#
#resolve_state_locally = true

# Limits unresolved local events visited by one local state derivation
# before falling back to federation.
#
# This bounds worst-case memory and latency in rooms with a large
# unresolved backlog. A value of 0 disables local derivation entirely.
#
# reloadable: yes
#
#resolve_state_locally_max = 256

# Allows federation requests to this server itself.
#
# This exists mainly for development. Requests to ourselves are
# unintended in ordinary operation and very likely indicate a bug.
#
# reloadable: yes
#
#loopback = false

# Blocks server names matching listed regular expressions from incoming
# and outgoing federation and client joins or remote invites.
#
# These global access controls check room IDs, room aliases, sender
# server names, sender users' server names, inbound federation X-Matrix
# origins, and the outbound federation handler. This server's own name is
# always permitted and exempt from the list.
#
# reloadable: yes
# example: ['badserver\.tld$', 'badphrase', '19dollarfortnitecards']
#
#forbidden_remote_server_names = []

# Experimentally permits only server names matching listed regular
# expressions.
#
# The behavior will change and the `_experimental` suffix will be removed
# in an upcoming release; the matching details otherwise follow
# `federation.forbidden_remote_server_names`. The list is empty and
# inactive by default; any entry activates it and denies nonmatches,
# while this server's own name is always permitted. The denylist still
# applies afterward, allowing a broad match such as
# `'^([^.]+\.)+example\.com$'` here and an exclusion such as
# `'^bad\.example\.com$'` there.
#
# reloadable: yes
# example: ['badserver\.tld$', 'badphrase', '19dollarfortnitecards']
#
#allowed_remote_server_names_experimental = []

# Enforces
# [MSC4311](https://github.com/matrix-org/matrix-spec-proposals/pull/4311)
# create-event validation in federated invite and knock stripped state.
#
# When enabled, an invite is rejected if its `m.room.create` event is
# missing, not a full PDU, bound to a different room, or fails signature
# checks, and such events are dropped from knock stripped state. When
# disabled, as by default, failures are logged but tolerated for
# ecosystem interoperability, except that for room versions 12 and later
# a missing create event, or a full PDU bound cryptographically to a
# different room, is always rejected. A full PDU in knock stripped state
# that fails validation is always omitted, so this setting governs only
# legacy stripped creates for knocks.
#
# reloadable: yes
#
#enforce_stripped_state_pdu_validation = false


################################################################################
# Federation fanout limits
#
# Bounds requests sent to many homeservers at once: `!admin query feds`
# surveys, room summary and space hierarchy lookups, and remote device-key
# queries. `destination_limit` guards only the admin survey, and device-key
# queries take `max_width` but time out after `transport.keys_timeout`
# rather than `timeout`. All three settings apply on reload.
#
#[global.federation.fanout]

# Sets the timeout in seconds for each bounded federation fanout request.
#
# This applies to admin surveys and migrated room fanouts. A server that
# exceeds the deadline is reported as timed out while other destinations
# continue. Keep this below `federation.transport.timeout` and above
# `federation.transport.keys_timeout`.
#
# reloadable: yes
#
#timeout = 15

# Limits concurrency for bounded federation fanouts.
#
# This caps admin surveys and migrated room and key fanouts. Lower values
# trade sweep latency for load without dropping destinations. 0 selects
# the built-in bounded default.
#
# reloadable: yes
#
#max_width = 0

# Limits destinations contacted by an admin feds survey without
# confirmation.
#
# A room exceeding this requires the command's confirmation flag. Higher
# values permit longer diagnostic commands on the serial admin worker.
#
# reloadable: yes
#
#destination_limit = 2048


################################################################################
# Federation history recovery
#
# Limits the work spent filling gaps when an incoming event refers to
# earlier events this server does not hold and, with
# `fetch_unreceived_contexts`, when a client asks for context around an
# event it never received. All settings apply on reload.
#
# Tips:
# - `prev_events_concurrency = 0` is refused at startup and on reload.
#
#[global.federation.history]

# Limits prior events visited by one recovery traversal.
#
# reloadable: yes
#
# Raising this limit increases recovery work; it is not a count of network
# requests.
#
#max_fetch_prev_events = 1024

# Limits simultaneous backward-extremity upgrades during incoming-event
# recovery.
#
# Lower values reduce recovery load at the cost of latency. This does not
# change the protocol `prev_events` bound or
# `federation.history.max_fetch_prev_events`.
#
# reloadable: yes
#
#prev_events_concurrency = 20

# Limits how many milliseconds an incoming timeline event waits for
# missing previous events before federation fetching.
#
# A gap closing within this window skips the fetch. The event-driven wait
# wakes as soon as those events arrive, so the limit is a ceiling on
# added latency rather than a fixed cost. Set to 0 to fetch immediately.
#
# reloadable: yes
#
#fetch_prev_wait_ms = 750

# Enables experimental federation fetching of missing base events for
# room context requests.
#
# For `/_matrix/client/v3/rooms/{roomId}/context/{eventId}` requests
# whose event is not held locally, we fetch it from a room peer and
# persist it before responding instead of returning a 404. This requires
# `federation.enable` and has no effect when federation is disabled.
# Other on-demand federation fetch sites are gated separately.
#
# reloadable: yes
#
#fetch_unreceived_contexts = false

# Limits concurrent server contacts per round of a federation event
# fetch.
#
# This tightens the built-in fanout profile of every fetch kind and never
# widens one. A value of 0 leaves the profiles unchanged.
#
# reloadable: yes
#
#fetch_fanout_max_width = 0

# Limits staged rounds attempted by a federation event fetch before
# giving up.
#
# This tightens the built-in round count of every fetch kind and never
# raises one. A value of 0 leaves the profiles unchanged.
#
# reloadable: yes
#
#fetch_fanout_rounds = 0


################################################################################
# Federation signing keys
#
# Verifying events from other homeservers needs their public signing keys.
# The server asks the origin server first and falls back to the notaries
# in `trusted_servers` (`matrix.org` by default); for joins and knocks it
# asks the notaries first by default. Fetched keys are cached, and every
# setting here applies on reload.
#
# Tips:
# - With `trusted_servers = []`, keys come only from their origin. A server
#   that is offline or unreachable cannot supply keys not already cached,
#   so its events cannot be verified, and joins of large rooms can slow
#   down.
# - `only_query_trusted_servers` with an empty `trusted_servers` leaves no
#   source at all for keys not already cached.
#
#[global.federation.keys]

# Selects trusted notary servers used to gather other servers' public
# keys.
#
# We do not currently support inbound batched key requests, so this list
# should contain only Synapse servers.
#
# reloadable: yes
# example: ["matrix.org", "tchncs.de"]
#
#trusted_servers = ["matrix.org"]

# Queries configured trusted key servers before the origin when enabled.
#
# Querying the origin first offers the best security by reducing exposure
# to a compromised trusted server. Enabling this can maximize federation
# and join performance, but evaluate the other settings that query
# trusted servers first only under specific high-load conditions before
# enabling it globally.
#
# reloadable: yes
#
#query_trusted_servers_first = false

# Queries configured trusted key servers before origins specifically
# during room joins.
#
# This limits exposure to compromised trusted servers to joins, whose
# many origin-key lookups can cause significant delays; it defaults to
# true to mitigate unexpected delays. Set to false when minimizing that
# exposure matters more than latency. This setting is ignored when
# `federation.keys.query_trusted_servers_first` is true.
#
# reloadable: yes
#
#query_trusted_servers_first_on_join = true

# Queries only trusted key servers and never the origin.
#
# This is intended for clusters or custom deployments using
# `federation.keys.trusted_servers` as forwarding agents to cache and
# deduplicate requests. Notary servers do not act as forwarding agents by
# default, so enable this only with a full understanding of the
# deployment.
#
# reloadable: yes
#
#only_query_trusted_servers = false

# Limits keys requested in each trusted-server batch query.
#
# reloadable: yes
#
#trusted_server_batch_size = 192

# Limits simultaneous request batches when querying a trusted server.
#
# reloadable: yes
#
#trusted_server_batch_concurrency = 2


################################################################################
# Federation client transport
#
# Timeouts and connection reuse for requests this server sends to other
# homeservers, such as event, state and key fetches, joins, and remote
# device-key queries. Outgoing transactions (`/send`) use the client in
# `[global.sending]` instead, and connect and whole-request limits come
# from `[global.network.http]`.
#
#[global.federation.transport]

# Sets the federation client read timeout in seconds.
#
# This applies to each read from a remote server rather than the whole
# request, which remains bounded by `network.http.total_timeout`.
#
#timeout = 25

# Sets the timeout in seconds for client-initiated federation key
# lookups.
#
# This covers `/keys/query` and `/keys/claim` against remote servers and
# should be well below `federation.transport.timeout`, so an unresponsive
# server does not outlast the requesting client's send deadline.
# Exceeding this bound records a transient federation failure for the
# remote server, making subsequent lookups back off instead of blocking
# again.
#
#keys_timeout = 8

# Sets the federation client idle connection pool timeout (seconds).
#
#idle_timeout = 25

# Limits idle federation client connections per host, defaulting to one
# because an open connection can generally be reused.
#
#idle_per_host = 1


################################################################################
# HTTP listener
#
# Settings for the server's own HTTP listener, which serves clients and
# other homeservers alike: request size, timeouts, client address
# detection and CORS. Where it listens is set in `[global.http.listen]`,
# response compression in `[global.http.compression]`, and direct TLS in
# `[global.tls]`. Requests the server sends to other hosts are configured
# in `[global.network.http]` instead.
#
# Tips:
# - `max_request_size` also caps requests from other homeservers, and a
#   value under 10 MB (`10000000` bytes) fails startup. A reverse proxy in
#   front needs a body limit at least as large, or big uploads fail there.
# - Behind a reverse proxy, set `ip_source` to the header that proxy
#   writes. A reload that changes `ip_source` is rejected; restart
#   instead.
#
#[global.http]

# Sets the maximum request size for file uploads.
#
# Accepts an integer byte count or a string with an SI/IEC suffix such as
# "24 MiB".
#
#max_request_size = "24 MiB"

# Sets the maximum time in seconds to receive a client request.
#
#receive_timeout = 75

# Sets the maximum time in seconds to process a client request.
#
#request_timeout = 240

# Sets the maximum time in seconds to transmit a client response.
#
#response_timeout = 120

# Sets the grace period in seconds for clean shutdown of client requests.
#
# reloadable: yes
#
#shutdown_timeout = 15

# Selects the client IP source for rate limiting, logging, and security
# tooling.
#
# Password login and password re-entry (UIAA) use the TCP peer address and
# ignore forwarding headers unless a header source is configured, and that
# peer is not limited per address when it is loopback (a local reverse
# proxy or the Unix socket). For other uses, an unset source scans common
# proxy headers in leftmost-IP mode (`X-Forwarded-For`, RFC 7239
# `Forwarded`, `X-Real-IP`, `Fly-Client-IP`, `True-Client-IP`,
# `CF-Connecting-IP`, `CloudFront-Viewer-Address`) before the TCP peer
# address, letting a client spoof its address.
#
# A configured source is used alone, taking the rightmost value of a
# multi-valued header, the one only the proxy appends; password
# authentication requires it even from loopback or trusted peers and
# refuses when it is missing or invalid, and a header source still needs a
# trusted reverse proxy in front of tuwunel. Supported values are
# "connect_info" for direct TCP peers,
# "rightmost_x_forwarded_for" for nginx or Caddy, "rightmost_forwarded"
# for RFC 7239 proxies, "x_real_ip" for nginx `X-Real-IP`,
# "cf_connecting_ip" for Cloudflare or cloudflared, "true_client_ip" for
# Akamai or Cloudflare Enterprise, "fly_client_ip" for Fly.io, and
# "cloudfront_viewer_address" for AWS CloudFront; behind a reverse proxy,
# including one on the Unix socket, select the header it sets, and restart
# the server after changing this setting.
#
#ip_source = "connect_info"

# Selects TCP peer subnets that bypass the configured client IP source.
#
# Matching peers use the insecure header scan and `ConnectInfo` fallback
# used when `http.ip_source` is unset; entries require CIDR prefixes
# (`/32` or `/128` for a single host), while loopback (`127.0.0.0/8`,
# `::1/128`) bypasses extraction without being listed, except for password
# login and password re-entry (UIAA), which require the selected source.
# Use this for locally attached bridges or server-side clients on private
# container or VPN subnets that cannot carry the configured proxy header,
# such as a Docker bridge without `network_mode: host`.
#
# Exclude the address receiving external traffic from your proxy: listing
# a shared bridge subnet containing the proxy, such as a common Compose
# network, also bypasses proxy traffic and defeats `http.ip_source`. Any
# peer in these subnets can forge client IPs through request headers, so
# include only subnets controlled end-to-end; changing this setting
# requires a server restart.
#
#ip_source_trusted_subnets = ["172.18.0.0/16", "fd00::/8"]

# Sets the `Access-Control-Allow-Origin` header included in all
# responses.
#
# Multiple values may be specified. The default empty list produces the
# header value `*`. Configure this only for a specific purpose, because
# incorrect values can degrade or disrupt clients.
#
#access_control_allow_origin = []


################################################################################
# Response compression
#
# Compresses the server's own HTTP responses for clients that accept it.
# Every codec is off by default; a reverse proxy can compress instead.
# Outbound requests negotiate compression separately in
# `[global.network.http]`.
#
#[global.http.compression]

# Compresses the server's HTTP response bodies with zstd.
#
# This has no effect unless tuwunel was built with the `zstd_compression`
# feature. Most users do not need it, and HTTP compression can weaken
# TLS; review https://breachattack.com/ and
# https://wikipedia.org/wiki/BREACH before enabling it.
#
#zstd = false

# Compresses the server's HTTP response bodies with gzip.
#
# This has no effect unless tuwunel was built with the `gzip_compression`
# feature. Most users do not need it, and HTTP compression can weaken
# TLS; review https://breachattack.com/ and
# https://wikipedia.org/wiki/BREACH before enabling it. Servers in many
# rooms may need it to reduce very large response bodies.
#
#gzip = false

# Compresses the server's HTTP response bodies with brotli.
#
# This has no effect unless tuwunel was built with the
# `brotli_compression` feature. Most users do not need it, and HTTP
# compression can weaken TLS; review https://breachattack.com/ and
# https://wikipedia.org/wiki/BREACH before enabling it.
#
#brotli = false


################################################################################
# Listening addresses, ports and Unix socket
#
# By default the server listens for plain HTTP on port 8008 at `127.0.0.1`
# and `::1`, reachable only from the same host, which suits a reverse proxy
# there. It binds every combination of `address` and `port`. Setting
# `unix_socket_path` adds a Unix socket; with `address` left unset, the
# socket replaces the default TCP listeners.
#
# Tips:
# - Listener settings are read once at startup; a reload does not rebind.
# - Sockets passed in by systemd socket activation are served alongside
#   these, as plain HTTP or TLS like the other TCP listeners.
# - Other homeservers connect to port 8448 of `server_name` unless
#   `well_known.server` or a DNS SRV record delegates elsewhere, so a
#   reverse proxy, or this listener with `[global.tls]`, must answer
#   there.
# - The Unix socket always speaks plain HTTP, even with `[global.tls]`.
#
#[global.http.listen]

# Selects the IPv4 or IPv6 addresses on which tuwunel listens.
#
# Docker or container NAT deployments require "0.0.0.0". To listen on
# multiple addresses, use a vector such as ["127.0.0.1", "::1"]. Every
# explicitly configured address must bind or startup fails. The default
# only assumes both loopback families exist, so a default address that
# cannot bind is logged and skipped.
#
#address = ["127.0.0.1", "::1"]

# Selects the ports on which tuwunel listens.
#
# For reverse proxy setup, see
# https://tuwunel.chat/deploying/generic.html#setting-up-the-reverse-proxy.
# Docker deployments should keep this value and map an external port to
# it. To listen on multiple ports, use a vector such as [8080, 8448].
#
#port = 8008

# Selects the UNIX socket on which tuwunel listens.
#
# The reverse proxy must be able to access this socket file. Add the
# proxy to the 'tuwunel' group or grant world read/write access with
# `http.listen.unix_socket_perms` set to at least 666.
#
# example: "/run/tuwunel/tuwunel.sock"
#
#unix_socket_path =

# Sets the default permissions, in octal, for creating the UNIX socket.
#
#unix_socket_perms = 660


################################################################################
# Upstream identity providers (SSO)
#
# Delegates sign-in to external OAuth 2.0 or OpenID Connect providers;
# repeat the `[[global.identity_provider]]` header once per provider. Both
# legacy `m.login.sso` and the built-in OIDC server
# (`[global.authentication.oidc]`) sign users in through these entries.
#
# Each entry needs `brand`, a unique `client_id`, and `client_secret` or
# a readable, nonempty `client_secret_file`; startup refuses a repeated
# `client_id`, a provider with neither secret key, and an unreadable or
# empty `client_secret_file`. `issuer_url` is
# required except for the `github`, `gitlab` and `google` brands.
# Register `well_known.client` followed by
# `/_matrix/client/unstable/login/sso/callback/<client_id>` as the redirect
# URI at the provider; it is the default `callback_url`, so set that
# yourself when `well_known.client` is unset.
#
# Minimal example:
#
#     [[global.identity_provider]]
#     brand = "keycloak"
#     client_id = "tuwunel"
#     client_secret_file = "/etc/tuwunel/.client_secret"
#     issuer_url = "https://sso.example.com/realms/example"
#
# Tips:
# - With several providers, mark one `default = true`; otherwise the first
#   entry serves the bare SSO redirect, and startup warns unless
#   `authentication.login.sso_custom_providers_page` is set.
# - Discovery runs on first use, not at startup: a missing `issuer_url`, or
#   one that differs from the issuer the provider reports, fails sign-in.
# - New accounts from a provider follow its `registration` key, not
#   `registration.enable`.
#
#[[global.identity_provider]]

# The brand-name of the service (e.g. Apple, Facebook, GitHub, GitLab,
# Google) or the software (e.g. keycloak, MAS) providing the identity.
# When a brand is recognized we apply certain defaults to this config
# for your convenience. For certain brands we apply essential internal
# workarounds specific to that provider; it is important to configure this
# field properly when a provider needs to be recognized (like GitHub for
# example).
#
# Several configured providers can share the same brand name. It is not
# case-sensitive. As a convenience for common simple deployments we can
# identify this provider by brand in addition to the unique `client_id` if
# and only if there is a single provider for the brand; see notes for
# `client_id`.
#
#brand =

# The ID of your OAuth application which the provider generates upon
# registration. This ID then uniquely identifies this configuration
# instance itself, becoming the identity provider's ID and must be unique
# and remain unchanged.
#
# As a convenience we also identify this config by `brand` if and only if
# there is a single provider configured for a `brand`. Note carefully that
# multiple providers configured with the same `brand` is not an error and
# this provider will simply not be found when querying by `brand`.
#
#client_id =

# Secret key the provider generated for you along with the `client_id`
# above. Unlike the `client_id`, the `client_secret` can be changed here
# whenever the provider regenerates one for you.
#
#client_secret =

# Secret key to use, read from the file path specified.
#
# Alternative to `client_secret` for deployments that prefer to keep the
# secret outside the config file. When both are configured `client_secret`
# is used and this field is ignored. The file is read at startup and on
# each OAuth exchange, must exist and must be non-empty; leading and
# trailing whitespace is trimmed. Under systemd the path must be visible
# to the service after sandboxing (`ReadWritePaths` / `ProtectHome`),
# typically by placing the file under `/etc/tuwunel/`.
#
# example: "/etc/tuwunel/.client_secret"
#
#client_secret_file =

# Issuer URL the provider publishes for you. We have pre-supplied default
# values for some of the canonical public providers, making this field
# optional based on the `brand` set above. Otherwise it is required to
# find self-hosted providers. It must be identical to what is configured
# and expected by the provider and must never change because we associate
# identities to it. If the `/.well-known/openid-configuration` is not
# found behind this URL see `base_path` below as a workaround.
#
#issuer_url =

# The callback URL configured when registering the OAuth application with
# the provider. Tuwunel's callback URL must be strictly formatted exactly
# as instructed. The URL host must point directly at the matrix server and
# use the following path:
# `/_matrix/client/unstable/login/sso/callback/<client_id>` where
# `<client_id>` is the same one configured for this provider above.
#
#callback_url =

# When more than one identity_provider has been configured and
# `authentication.login.single_sso` is false and
# `authentication.login.sso_custom_providers_page` is false this will
# determine the behavior of the `/_matrix/client/v3/login/sso/redirect`
# endpoint (note the url lacks a trailing `client_id`).
#
# When only one identity_provider is configured it will be interpreted
# as the default and this does not need to be set. Otherwise a default
# *must* be selected for some clients (e.g. fluffychat) to work properly
# when the above conditions require it. To operate out-of-the-box we
# default to one configured provider if none are explicitly default; a
# warning will be logged on startup for this condition.
#
# (EXPERIMENTAL) Multiple providers can be set to default. All providers
# configured with this option set to `true` will associate with the same
# Matrix account when a client flows through
# `/_matrix/client/v3/login/sso/redirect`.
#
# When a user authorizes any provider configured default, the flow will
# include all other providers configured default as well for association.
# NOTE: authorization must succeed for ALL default providers.
#
#default = false

# Optional display-name for this provider instance seen on the login page
# by users. It defaults to `brand`. When configuring multiple providers
# using the same `brand` this can be set to distinguish them.
#
#name =

# Optional icon for the provider. The canonical providers have a default
# icon based on the `brand` supplied above when this is not supplied. Note
# that it uses an MXC url which is curious in the auth-media era and may
# not be reliable.
#
#icon =

# Optional list of scopes to authorize.
#
# An empty array sends `openid email profile`. The exception is
# `brand = "MAS"`, which sends only `openid`: MAS rejects `profile`, and
# its userinfo endpoint returns just `sub` and `username`. Set this to
# request a different subset. The user can further restrict scopes during
# their authorization.
#
#scope = []

# Optional list of userinfo claims which shape and restrict the way we
# compute a Matrix UserId for new registrations. Reviewing Tuwunel's
# documentation will be necessary for a complete description in detail. An
# empty array imposes no restriction here, avoiding generated fallbacks as
# much as possible.
#
# For simplicity we reserve a claim called "unique" which can be listed
# alone to ensure *only* generated ID's are used for registrations.
#
# Note that listing the claim "sub" has special significance and will take
# precedence over all other claims, listed or unlisted. "sub" is not
# normally used to determine a UserId unless explicitly listed here.
#
# As of now arbitrary claims cannot be listed here, we only recognize
# specific hard-coded claims.
#
#userid_claims = []

# Whether userinfo claims may grant access to an existing matching account.
#
# By default we skip matching users and register the first available
# username, falling back to random characters to avoid conflicts; a trusted
# provider instead finds the first matching user and grants access to it,
# which is how an existing matrix account is associated with a provider and
# also how one can be hijacked. A trusted provider's `email` claim is also
# bound to a new account when it sends no `email_verified` claim, where an
# untrusted one must mark it verified. Only set this option to true for
# providers you self-host and control, never for public providers such as
# GitHub or GitLab. An existing user can still be associated with an
# untrusted provider, but only with the command '!admin query oauth
# associate'.
#
#trusted = false

# Setting this option to false will inhibit unique ID's from being
# generated as a last-resort when determining a UserId from a provider's
# claims. In the case of untrusted providers, when all provided claims
# conflict with existing user accounts, a unique fallback ID needs
# to be generated for registration to not be denied with an error.
#
# Set this option to false if you operate a private server or a trusted
# identity provider where random UserId's are undesirable; the result of a
# misconfiguration or other issue where an error is warranted.
#
# This option should be set to true for public servers or some users may
# never be able to register.
#
#unique_id_fallbacks = true

# Controls whether new user registration is possible from this provider.
# When this option is set to false, authorizations from this provider
# only affect existing users and will never result in a new registration
# when the claims fail to match any existing user (in the case of trusted
# providers) or an available username is found (in the case of untrusted
# providers).
#
# When LDAP is enabled, a user found in the LDAP directory counts as an
# existing user and is still provisioned on first login, since the
# directory is the authoritative account store.
#
# Setting this option to false is generally not useful unless there is
# an explicit reason to do so.
#
#registration = true

# Optional extra path components after the issuer_url leading to the
# location of the `.well-known` directory used for discovery. If the path
# starts with a slash it will be treated as absolute, meaning overwriting
# any path in the issuer_url. The path needs to end with a slash. This
# will be empty for specification-compliant providers.
#
#base_path =

# Overrides the `.well-known` location where the provider's openid
# configuration is found. It is very unlikely you will need to set this;
# available for developers or special purposes only.
#
#discovery_url =

# Overrides the authorize URL requested during the grant phase. This is
# generally discovered or derived automatically, but may be required as a
# workaround for any non-standard or undiscoverable provider.
#
#authorization_url =

# Overrides the access token URL; the same caveats apply as with the other
# URL overrides.
#
#token_url =

# Overrides the revocation URL; the same caveats apply as with the other
# URL overrides.
#
#revocation_url =

# Overrides the introspection URL; the same caveats apply as with the
# other URL overrides.
#
#introspection_url =

# Overrides the userinfo URL; the same caveats apply as with the other URL
# overrides.
#
#userinfo_url =

# Whether to perform discovery and adjust this provider's configuration
# accordingly. This defaults to true. When true, it is an error when
# discovery fails and authorizations will not be attempted to the
# provider.
#
#discovery = true

# The duration in seconds before a grant authorization session expires.
#
#grant_session_duration = 300

# Whether to check the redirect cookie during the callback. This is a
# security feature and should remain enabled. This is available for
# developers or deployments which cannot tolerate cookies and are willing
# to tolerate the risks.
#
#check_cookie = true

# Extra query parameters appended to every authorization request sent to
# the identity provider.
#
# E.g. to force re-authentication even if IdP cookies are present:
# [[global.identity_provider]]
# extra_authorization_parameters = { prompt = "login" }
#
#extra_authorization_parameters = {}

# Forward the MSC3824 `action` query parameter from the SSO redirect
# endpoints to this provider as an OpenID Connect `prompt` value.
#
# When a client appends `action=register` to a `/login/sso/redirect`
# request the upstream authorization request carries `prompt=create`
# (the OpenID Connect "Initiating User Registration" extension) so the
# provider can present its registration screen. `action=login` is left
# unforwarded to avoid forcing a re-authentication, and a `prompt` set in
# `extra_authorization_parameters` still applies in that case. An
# action-derived `prompt` takes precedence over one configured there.
#
# Leave this disabled unless the provider supports the `prompt=create`
# registration extension; a provider that does not may reject or ignore
# the request.
#
#forward_action_prompt = false


################################################################################
# JSON Web Token login
#
# Accepts a signed JWT as proof of identity, both as the
# `org.matrix.login.jwt` login type and as a user-interactive
# authentication stage, for deployments where an external system mints
# tokens for its users. The token's `sub` claim is the user's localpart on
# this server, lowercased. Off by default.
#
# Set `enable` and `key`. The default `format` and `algorithm` expect an
# HMAC shared secret with HS256; an issuer signing with ECDSA or EdDSA needs
# its PEM public key in `key` and a matching `format` and `algorithm`.
#
# Minimal example:
#
#     [global.jwt]
#     enable = true
#     key = "replace-with-a-long-random-secret"
#
# Tips:
# - Startup and reload refuse an empty `key` or an unknown `format` while
#   enabled, but a `key` that does not decode or an unsuitable `algorithm`
#   fails only at login.
# - With `register_user` (the default), a valid token for an unknown user
#   creates the account regardless of `registration.enable`.
# - `validate_signature = false` has an effect only in debug builds.
#
#[global.jwt]

# Enable JWT logins
#
# reloadable: yes
#
#enable = false

# Validation key, also called 'secret' in Synapse config. The type of key
# can be configured in 'format', but defaults to the common HMAC which
# is a plaintext shared-secret, so you should keep this value private.
#
# reloadable: yes
#
#key =

# Format of the 'key': HMAC, B64HMAC, ECDSA, or EDDSA, case-insensitive.
#
# HMAC is a plaintext shared secret, and B64HMAC (also spelled HMACB64)
# is the same secret base64-encoded in the standard alphabet with '='
# padding, for random binary secrets that cannot be pasted as text.
# ECDSA and EDDSA are PEM-encoded public keys, EDDSA for Ed25519.
# Startup and reload both refuse an unknown format while JWT is enabled.
#
# reloadable: yes
#
#format = "HMAC"

# Automatically create new user from a valid claim, otherwise access is
# denied for an unknown even with an authentic token.
#
# reloadable: yes
#
#register_user = true

# Expire the access token of a new JWT login and withhold a refresh token.
#
# The access token lasts `authentication.access_token_ttl` seconds
# whatever the client asks for, so staying signed in takes a fresh JWT and
# the token issuer decides how long a login lasts. Off by default because
# a client that cannot obtain a fresh JWT would be signed out for good.
# A JWT login retires the refresh token its device holds, but a client
# that only refreshes never logs in, so remove devices holding a refresh
# token when enabling this. Startup and reload refuse a zero
# `authentication.access_token_ttl` while enabled.
#
# reloadable: yes
#
#expire_access_token = false

# Signature algorithm for validating tokens.
#
# The name must suit the key format: HS256, HS384, or HS512 for HMAC
# and B64HMAC, ES256 or ES384 for ECDSA, and EdDSA for EDDSA.
#
# reloadable: yes
#
#algorithm = "HS256"

# Optional audience claim list. The token must claim one or more values
# from this list when set.
#
# reloadable: yes
#
#audience = []

# Optional issuer claim list. The token must claim one or more values
# from this list when set.
#
# reloadable: yes
#
#issuer = []

# Require expiration claim in the token. This defaults to false for
# synapse migration compatibility.
#
# reloadable: yes
#
#require_exp = false

# Require not-before claim in the token. This defaults to false for
# synapse migration compatibility.
#
# reloadable: yes
#
#require_nbf = false

# Validate expiration time of the token when present. Whether or not it is
# required depends on require_exp, but when present this ensures the token
# is not used after a time.
#
# reloadable: yes
#
#validate_exp = true

# Validate not-before time of the token when present. Whether or not it is
# required depends on require_nbf, but when present this ensures the token
# is not used before a time.
#
# reloadable: yes
#
#validate_nbf = true

# Bypass validation for diagnostic/debug use only.
#
# reloadable: yes
#
#validate_signature = true


################################################################################
# LDAP login
#
# Checks password sign-ins against an LDAP directory and creates the local
# account on first successful bind, regardless of `registration.enable`.
# Off by default; needs the `ldap` build feature, which the default build
# includes.
#
# Set `enable` and `uri`. With both `bind_dn` and `bind_password_file`,
# the server binds as that service account, then searches `base_dn` with
# `filter`; leaving either unset searches anonymously. A `bind_dn`
# containing `{username}` skips the search and binds directly as the user.
#
# Minimal example (search with a service account):
#
#     [global.ldap]
#     enable = true
#     uri = "ldaps://ldap.example.org:636"
#     base_dn = "ou=users,dc=example,dc=org"
#     bind_dn = "cn=ldap-reader,dc=example,dc=org"
#     bind_password_file = "/etc/tuwunel/.ldap_bind_password"
#
# Tips:
# - A search with no match falls back to the local password, and two or
#   more matches refuse the login. Direct bind never falls back, and with a
#   nonempty `admin_filter` it revokes admin from every user who signs in.
# - `authentication.login.with_password = false` turns LDAP login off, and
#   `authentication.emergency_password` is ignored while LDAP is enabled.
# - Only `uri` is checked at startup, and only that it parses as a URL: a
#   missing `uri` or an unreachable directory shows up as failed logins.
#
#[global.ldap]

# Whether to enable LDAP login.
#
# reloadable: yes
# example: "true"
#
#enable = false

# URI of the LDAP server.
#
# reloadable: yes
# example: "ldap://ldap.example.com:389"
#
#uri =

# Root of the searches.
#
# reloadable: yes
# example: "ou=users,dc=example,dc=org"
#
#base_dn =

# Bind DN if anonymous search is not enabled.
#
# You can use the variable `{username}` that will be replaced by the
# entered username. In such case, the password used to bind will be the
# one provided for the login and not the one given by
# `bind_password_file`. Beware: automatically granting admin rights will
# not work if you use this direct bind instead of a LDAP search.
#
# reloadable: yes
# example: "cn=ldap-reader,dc=example,dc=org" or
# "cn={username},ou=users,dc=example,dc=org"
#
#bind_dn = ""

# Path to a file on the system that contains the password for the
# `bind_dn`.
#
# The server must be able to access the file, and it must not be empty.
#
# reloadable: yes
#
#bind_password_file = ""

# Search filter to limit user searches.
#
# You can use the variable `{username}` that will be replaced by the
# entered username for more complex filters.
#
# reloadable: yes
# example: "(&(objectClass=person)(memberOf=matrix))"
#
#filter = "(objectClass=*)"

# Attribute to use to uniquely identify the user.
#
# reloadable: yes
# example: "uid" or "cn"
#
#uid_attribute = "uid"

# Root of the searches for admin users.
#
# Defaults to `base_dn` if empty.
#
# reloadable: yes
# example: "ou=admins,dc=example,dc=org"
#
#admin_base_dn =

# The LDAP search filter to find administrative users for tuwunel.
#
# If left blank, administrative state must be configured manually for each
# user.
#
# You can use the variable `{username}` that will be replaced by the
# entered username for more complex filters.
#
# reloadable: yes
# example: "(objectClass=tuwunelAdmin)" or "(uid={username})"
#
#admin_filter =


################################################################################
# Logging
#
# Controls what the server logs and where the output goes. By default it
# logs at `info` (`debug` in debug builds) to standard output with colors;
# under systemd it writes straight to the journal instead, keeping each
# line's severity.
#
# Tips:
# - Release builds, including the published packages, compile out `debug`
#   and `trace` events (the default `release_max_log_level` Cargo feature),
#   so a more verbose `filter` shows nothing more until you rebuild without
#   that feature.
# - A malformed `filter` stops startup. To change the filter on a running
#   server, use `!admin debug change-log-level <filter>`; `--reset` in
#   place of a filter restores the configured one.
#
#[global.logging]

# Sets the maximum log level, accepting debug, info, warn, or error.
#
# The filter also accepts [tracing-subscriber
# directives](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives).
# Release builds with `release_max_log_level` omit debug and trace levels
# to reduce compiled tracing overhead; debug builds do not apply that
# release cap.
#
#filter = "info"

# Adds ANSI colors to log output.
#
# Colors are suppressed for journald submissions because it treats
# control bytes in formatted lines as binary instead of text.
#
#colors = true

# Selects the compact log format.
#
#compact = false

# Selects span events included in log output.
#
#span_events = "none"

# Allows the log EnvFilter to match values using regular expressions.
#
# This controls `TUWUNEL_LOG` filter matching; see the
# [tracing-subscriber directives
# documentation](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives).
#
#filter_regex = true

# Displays thread IDs in tracing log output.
#
#thread_ids = false

# Redirects logging to standard error.
#
# The default false writes to standard output. Systemd integration
# redirects to standard error as needed without this setting; this option
# serves other deployments requiring redirection.
#
#to_stderr = false

# Submits logs directly to journald instead of the console when running
# under systemd.
#
# Each entry carries its real severity as journal priority, so
# `journalctl -p warning` finds warnings and errors; console capture
# instead assigns one fixed priority. Messages retain console formatting
# and span fields, with target, source location, and all tracing fields
# attached as journal fields, the latter prefixed `F_` for queries such
# as `journalctl F_ROOM_ID='!room:example.com'`. Outside systemd this has
# no effect, and failure to open the journald socket retains console
# output.
#
#journald = true

# Initializes the logging and tracing system when enabled.
#
# When false the system is neither initialized nor operating, whereas an
# empty `logging.filter` leaves it operating but muted. Changes have no
# effect after startup. This is for developers and expert use; prefer an
# empty filter to disabling the system.
#
#enable = true

# Registers the configured logging and tracing system as the global
# handler.
#
# Disabling this is a low-level developer or expert setting similar to
# `logging.enable`, but the system is configured normally and only the
# final global registration is omitted.
#
#global_default = true


################################################################################
# Media repository
#
# Uploads, storage, downloads and the legacy media endpoints, with
# sub-sections for Conduit media import, thumbnails, URL previews and
# video thumbnails. Every key has a working default; with nothing set,
# media is kept in `<database_path>/media` by the built-in local provider
# `media`, which a `[global.storage_provider.media.local]` (or `.s3`,
# `.gcs`) section replaces.
#
# Reads try the providers in `storage_providers`, in name order, until
# one holds the file; uploads go to those in `store_on_providers`, or to
# all of them when it is empty. Any name other than `media` needs its own
# `[global.storage_provider.<ID>.*]` section.
#
# Example (new uploads to S3, older files still read from disk):
#
#     [global.media]
#     storage_providers = ["media", "media_on_s3"]
#     store_on_providers = ["media_on_s3"]
#
#     [global.storage_provider.media_on_s3.s3]
#     bucket = "matrix-media"
#     key = "ACCESS_KEY_ID"
#     secret = "SECRET_ACCESS_KEY"
#
# Tips:
# - The config is refused when `store_on_providers` names a provider
#   missing from `storage_providers`, or `storage_providers` names one
#   (other than `media`) with no `[global.storage_provider.<ID>.*]`
#   section. An S3 or GCS section without `bucket` (or S3 `url`), or a
#   local one with `base_path = ""`, passes that check but is skipped at
#   startup; skipping is an error only when it leaves no enabled provider
#   to receive uploads.
# - Several `storage_providers` with `store_on_providers` empty copies
#   every upload to all of them; a startup warning says so.
# - Copy existing files to a new provider with
#   `!admin query storage sync media media_on_s3`, then drop `media` from
#   both lists.
# - Provider sections are read only at startup, so a config reload that
#   adds, removes or changes one is refused; restart instead.
#
#[global.media]

# Limits the number of concurrent pending asynchronous media uploads per
# user.
#
# reloadable: yes
#
#max_pending_uploads = 5

# Sets the lifetime in seconds before an unused pending MXC URI expires
# and is removed.
#
# reloadable: yes
#
#create_unused_expiration_time = 86400 (24 hours)

# Limits media create requests per second from one user.
#
# reloadable: yes
#
#rc_create_per_second = 10

# Limits the burst count of media create requests from one user.
#
# reloadable: yes
#
#rc_create_burst_count = 50

# Sets the writable space threshold below which local media uploads are
# refused.
#
# Each local storage provider receiving the upload is checked, excluding
# blocks reserved for privileged processes. Media is stored beside the
# database by default, and a full disk prevents database writes, so
# uploads stop first with M_RESOURCE_LIMIT_EXCEEDED and resume when space
# returns. Remote media, URL previews, and thumbnails are never refused.
# Accepts an integer byte count or an SI/IEC string such as "10 GiB"; 0
# disables the check for cases such as a network mount reporting no free
# space.
#
# reloadable: yes
#
#upload_min_free_space = "1 GiB"

# Prevents media from being embedded in frames, including same-origin
# frames.
#
# The default is disabled for compatibility with attachment viewers.
# Enabling it adds `frame-ancestors 'none'` to download and thumbnail
# Content-Security-Policy headers. Changes require a restart, and reverse
# proxy headers may still prevent framing.
#
#deny_framing = false

# Prevents inline styles in media documents.
#
# The default is disabled so browser image viewers retain their
# presentation styles. Enabling it omits `style-src 'unsafe-inline'` from
# download and thumbnail Content-Security-Policy headers. Changes require
# a restart, and reverse proxy headers may still restrict styles.
#
#deny_inline_styles = false

# Enables the legacy unauthenticated Matrix media repository endpoints.
#
# These are `/_matrix/media/*/config`, `/_matrix/media/*/preview_url`,
# `/_matrix/media/*/download/*`, and `/_matrix/media/*/thumbnail/*`. The
# authenticated equivalents are always enabled. The default is false.
#
#allow_legacy = false

# Falls back to requesting legacy unauthenticated media from remote
# servers.
#
# Unauthenticated media was removed around the third quarter of 2024.
# Enabling this adds considerable federation requests that are unlikely
# to succeed.
#
# reloadable: yes
#
#request_legacy = false

# Permits fetching remote legacy content and thumbnails when true.
#
# When false, those remote legacy requests are rejected.
#
# reloadable: yes
#
#freeze_legacy = true

# Checks media directory consistency at startup.
#
# Together with `media.compat_file_link`, this upgrades media when
# switching between Conduit and tuwunel; both options must be enabled.
# Startup checks can also remove database entries for files deleted from
# the media directory. If neither check applies and the directory is
# large, disabling this may reduce startup time.
#
#startup_check = true

# Creates media symlinks for compatibility with Conduit's media
# directory.
#
# This is needed only when planning to use Conduit again; disabling it
# reduces filesystem clutter and symlink management overhead. It is
# disabled by default. Before returning to upstream Conduit, run tuwunel
# at least once with this enabled and allow `media.startup_check` to
# finish before shutdown.
#
#compat_file_link = false

# Removes missing media metadata during startup checks.
#
# Deleting files from the media directory then removes their
# corresponding database entries. This is disabled by default because
# accidentally moving the directory or making it inaccessible would
# otherwise lose database metadata.
#
#prune_missing = false

# Selects storage providers used for media.
#
# Configure each listed name at `global.storage_provider.<NAME>.<brand>`;
# multiple entries support advanced features and future extensions, but
# require checking related settings to avoid resource duplication costs
# and poor performance. The default `["media"]` is an implicit provider
# for the local media directory. Configure
# `global.storage_provider.media.local` to alter it, or omit "media" from
# this list to disable it. Existing deployments should retain "media" as
# a fallback alongside a new provider.
#
# reloadable: yes
#
#storage_providers = ["media"]

# Selects configured storage providers that receive new media.
#
# When not explicitly configured, all entries in
# `media.storage_providers` are used. Each selected provider must also
# appear there. This supports passive migration by writing to a new
# provider while querying the old one as a fallback, for example
# `media.storage_providers = ["media", "media_on_s3"]` with
# `media.store_on_providers = ["media_on_s3"]`.
#
# reloadable: yes
#
#store_on_providers = []

# Redirects local media downloads when the client requests
# `allow_redirect=true` under MSC3860.
#
# If a configured provider can presign the object, such as S3, the server
# returns a 307 redirect to a short-lived URL instead of proxying the
# bytes. Media stored only on the local filesystem is always served
# directly.
#
# reloadable: yes
#
#allow_redirect = false

# Lists server-name regex patterns from which remote media downloads are
# refused.
#
# reloadable: yes
# example: ['badserver\.tld$', 'badphrase', '19dollarfortnitecards']
#
#prevent_downloads_from = []


################################################################################
# Media import
#
# Settings for importing media from a database created by another
# server. Conduit is the only supported source, configured in
# `[global.media.import.conduit]`; nothing here needs setting for a
# database that did not come from Conduit.
#
#[global.media.import]


################################################################################
# Conduit media import
#
# When the server first starts on a database taken over from Conduit, it
# copies each original media file into its own store through the normal
# upload path, so the copies land on the providers that receive uploads
# (see `[global.media]`). With nothing set, the files are read from
# `<database_path>/media` in Conduit's default directory layout.
#
# Set `source_path` when Conduit kept media in another directory, or
# `source_provider` when it kept media in object storage.
#
# Example (importing from an S3 bucket):
#
#     [global.media.import.conduit]
#     source_provider = "conduit_source"
#
#     [global.storage_provider.conduit_source.s3]
#     bucket = "conduit-media"
#     key = "ACCESS_KEY_ID"
#     secret = "SECRET_ACCESS_KEY"
#
# Tips:
# - The import runs once and is then recorded as done; changing these
#   keys afterwards has no effect.
# - The source provider needs no entry in `media.storage_providers`.
#   Keep it out of that list, and keep the list non-empty, so imported
#   files are not also written back into the source.
# - A `source_provider` that names no defined provider, or stays
#   unreachable after a retry, fails startup; the next start repeats the
#   import from the beginning. Missing source files are skipped.
# - When `directory_depth` is non-zero, `directory_length` must be
#   non-zero and their product under 64, or the config is refused.
#
#[global.media.import.conduit]

# Selects Conduit's media directory when importing its database in place.
#
# Leave unset to use `<database_path>/media`, which is Conduit's default
# location.
#
# example: "/var/lib/matrix-conduit/media"
#
#source_path =

# Sets the source media directory sharding depth for a Conduit import.
#
# Use 0 for a flat directory. This must match the source Conduit's
# `media.directory_structure`; the default matches its `Deep { length =
# 2, depth = 2 }`.
#
#directory_depth = 2

# Sets the source shard-segment length for a Conduit media import.
#
# Use it with `media.import.conduit.directory_depth` to describe the
# source directory layout.
#
#directory_length = 2

# Selects the storage provider containing source originals for a Conduit
# S3 import.
#
# Name a `[global.storage_provider.<name>]` entry, or leave unset to read
# the filesystem at `media.import.conduit.source_path`. Configure that
# provider with Conduit's S3 credentials and set `base_path` to Conduit's
# `media.path` prefix. Content-addressed object keys use
# `media.import.conduit.directory_depth` and
# `media.import.conduit.directory_length` for sharding. Restrict
# `media.storage_providers` to destination providers, such as
# `["media"]`, or the importer also copies media back into the read-only
# source bucket.
#
# example: "conduit_source"
#
#source_provider =


################################################################################
# Image thumbnails
#
# Limits on the thumbnails generated on demand from images, and from the
# frames extracted for video thumbnails. Image thumbnails need no setup;
# these keys bound the work each one may cost and how many sources are
# processed at once.
#
# Tips:
# - The config is refused when `max_pixels` is 0 or
#   `animated_concurrency` is outside 1 to 1024.
# - Video thumbnails also need `[global.media.video_thumbnail]`, which is
#   off until its `command` is set.
#
#[global.media.thumbnail]

# Limits the pixel count the thumbnailer will decode.
#
# Images declaring more pixels receive no thumbnail because dimensions
# consume memory regardless of encoded file size; video frames inherit
# the video resolution and share this bound. The default 50 megapixels is
# roughly four 8K frames and exceeds ordinary camera output. Four bytes
# are budgeted per pixel, admitting about 200 MiB per decode by default.
# Size this budget against concurrent requests rather than one decode,
# because thumbnail requests are not otherwise limited in number.
#
# reloadable: yes
#
#max_pixels = 50000000

# Serves animated thumbnails when requested under
# [MSC2705](https://github.com/matrix-org/matrix-spec-proposals/pull/2705).
#
# A requesting client receives an animated GIF when the source has a
# frame sequence and a still otherwise; clients that do not request
# animation always receive a still. Encoding quantizes each frame with
# its own palette and costs much more than a still, so frame count and
# total pixel limits also bound the work. Disabling this produces still
# PNG thumbnails only.
#
# reloadable: yes
#
#animated = true

# Limits the number of frames in an animated thumbnail.
#
# Longer sources are truncated into a shorter loop without notifying the
# client, instead of being refused a thumbnail. Frames also share the
# total `media.thumbnail.max_pixels` budget, so animation stops at
# whichever limit is reached first. Both limits bound work that any
# remote server can request.
#
# reloadable: yes
#
#max_frames = 50

# Limits source jobs admitted for animated thumbnail generation.
#
# A job acquires a slot before reading the full source and holds it
# through source I/O, animated storage, and subsequent still or video
# work until generation returns. A running blocking worker retains the
# slot after request cancellation. Static images and videos also require
# admission because their bytes determine whether animation work is
# needed. Changes require a restart.
#
#animated_concurrency = 4


################################################################################
# URL previews
#
# Link previews the server fetches on behalf of clients, built from the
# page's OpenGraph tags. Previews are off by default: with
# `domain_explicit_allowlist`, `domain_contains_allowlist` and
# `url_contains_allowlist` all empty, every preview request is refused
# and clients are told previews are disabled. To enable previews, list
# the hosts to allow.
#
# Minimal example:
#
#     [global.media.url_preview]
#     domain_explicit_allowlist = ["en.wikipedia.org", "github.com"]
#
# Tips:
# - A host in `domain_explicit_denylist` is refused even when an
#   allowlist admits it, except that `"*"` in any allowlist admits every
#   URL before the denylist is consulted (and draws a startup warning).
# - An allowed URL is still refused when its host is an address in
#   `network.http.ip_range_denylist`, or resolves to one.
# - `check_root_domain` strips only the first label of the host:
#   `en.wikipedia.org` is also checked as `wikipedia.org`, but
#   `en.m.wikipedia.org` only as `m.wikipedia.org`.
#
#[global.media.url_preview]

# Selects an optional source IP address or interface for URL preview
# requests.
#
# When unset, requests are not bound to a specific address or interface.
# Interface names are supported only on Linux, Android, and Fuchsia;
# other platforms can specify an IP address. Use `ip link show` to list
# system interfaces.
#
# example: `"eth0"` or `"1.2.3.4"`
#
#bound_interface =

# Allows URL preview requests to domains containing a listed string.
#
# Matching is by containment rather than equality: "google.com" matches
# both "https://google.com" and
# "http://mymaliciousdomainexamplegoogle.com". A value of "*" allows all
# URL previews. This exposes significant server attack surface and
# requires understanding the risks.
#
# reloadable: yes
#
#domain_contains_allowlist = []

# Allows URL preview requests to explicitly listed domains.
#
# Matching is exact rather than by containment: "google.com" matches
# "https://google.com" and "http://google.com", but not
# "https://mymaliciousdomainexamplegoogle.com". A value of "*" allows all
# URL previews. This exposes significant server attack surface and
# requires understanding the risks.
#
# reloadable: yes
#
#domain_explicit_allowlist = []

# Rejects URL preview requests to explicitly listed domains.
#
# Matching is exact rather than by containment: "google.com" matches
# "https://google.com" and "http://google.com", but not
# "https://mymaliciousdomainexamplegoogle.com". The denylist is checked
# before the allowlists, unless an allowlist holds "*". A value of "*"
# here has no effect.
#
# reloadable: yes
#
#domain_explicit_denylist = []

# Allows URL preview requests to URLs containing a listed string.
#
# Matching is by containment rather than equality: "google.com" matches
# "https://google.com/",
# "https://google.com/url?q=https://mymaliciousdomainexample.com", and
# "https://mymaliciousdomainexample.com/hi/google.com". A value of "*"
# allows all URL previews. This exposes significant server attack surface
# and requires understanding the risks.
#
# reloadable: yes
#
#url_contains_allowlist = []

# Limits the body size read when fetching a URL preview page.
#
# Accepts an integer byte count or an SI/IEC string such as "768 KiB". A
# page whose OpenGraph tags fall beyond the limit produces an empty
# preview, so pages beginning with large script blocks need a larger
# budget.
#
# reloadable: yes
#
#max_spider_size = 786432

# Limits each media item fetched or relayed for a URL preview.
#
# This covers the og:image measurement fetch and lazy-media relay. Media
# with an advertised length above the limit is not registered, and a
# relay that would exceed it is refused. Accepts an integer byte count or
# an SI/IEC string such as "50 MiB".
#
# reloadable: yes
#
#max_media_size = "50 MiB"

# Sets the lifetime in seconds of cached URL previews, including empty
# previews.
#
# Increasing this reduces requests to origins when room history is read
# often, at the cost of serving OpenGraph metadata that may have changed.
# A value of 0 fetches on every request. Raising it beyond seven days
# takes effect at the next restart because the database applies its
# retention floor when opened.
#
# reloadable: yes
#
#cache_ttl = 86400

# Checks the host again with its first label removed when no list admitted
# it.
#
# Only the explicit denylist and allowlist are consulted for the shortened
# name, since a contains entry it holds already matched the full host.
# One label is removed: with "wikipedia.org" in
# `domain_explicit_allowlist`, "en.wikipedia.org" is admitted, while
# "en.m.wikipedia.org" is checked only as "m.wikipedia.org" and refused.
#
# reloadable: yes
#
#check_root_domain = false

# Sets the User-Agent used to fetch preview pages and extract OpenGraph
# tags.
#
# When unset, the versioned server User-Agent is followed by "preview",
# such as "Tuwunel/1.8.1 preview". Some origins serve OpenGraph tags only
# to recognized preview crawlers and otherwise place them beyond
# `media.url_preview.max_spider_size`.
#
# reloadable: yes
#
#user_agent =

# Sets the User-Agent used to fetch and relay URL preview media files.
#
# This covers og:image, og:video, og:audio, and direct links rather than
# their containing pages. When unset, it falls back to
# `media.url_preview.user_agent`, then the versioned server User-Agent.
#
# reloadable: yes
#
#media_user_agent =

# Sets Accept-Language for URL preview page and media requests.
#
# For example, "en-US,en;q=0.9" requests English from sites supporting
# language negotiation, while sites choosing a language solely by IP may
# ignore it. When unset, no Accept-Language header is sent. Changes
# affect new requests; cached previews retain their language until
# expiry.
#
# reloadable: yes
#
#accept_language =


################################################################################
# Video thumbnails
#
# The server decodes no video itself. To thumbnail a video it runs the
# external program named in `command`, such as `ffmpeg`, which must be
# installed where the server runs; the frame it writes is then
# thumbnailed under the limits of `[global.media.thumbnail]`. With
# `command` empty (the default), videos are served without a thumbnail.
#
# Tips:
# - The published container images hold only the `tuwunel` binary and a
#   CA bundle; add the program with a derived image or by mounting a
#   statically linked build.
# - A systemd unit that filters out the `@ipc` syscalls must allow
#   `pipe` and `pipe2` again (`SystemCallFilter=pipe pipe2`, as the
#   packaged units do), or spawning the program fails.
# - A video whose extraction failed is not retried for five minutes, so
#   test a corrected `command` with another video.
# - The config is refused when `timeout` is 0 or `concurrency` is outside
#   1 to 1024.
#
#[global.media.video_thumbnail]

# Selects the program used to extract a still frame for videos uploaded
# without a thumbnail.
#
# We do not decode video internally; we scale and crop the extracted
# frame like any other image, then cache an ordinary thumbnail. The list
# is an argument vector with the program first and its arguments after
# it, executed directly without a shell. Before each call, every argument
# substitutes `{input}` with the temporary source-video path and
# `{width}` and `{height}` with the requested dimensions. The program
# writes one frame to standard output as PNG, JPEG, WebP, or GIF; an
# empty list serves videos without thumbnails.
#
# reloadable: yes
# example: [
# "ffmpeg", "-loglevel", "error", "-i", "{input}", "-vf", "thumbnail",
# "-frames:v", "1", "-f", "image2pipe", "-c:v", "mjpeg", "pipe:1",
# ]
#
#command = []

# Limits the seconds a video thumbnail request can spend extracting a
# frame.
#
# One deadline covers waiting for a slot, staging the video, and running
# the program, preventing queueing from multiplying the timeout. Expiry
# kills the program and anything it spawned, then serves the video
# without a thumbnail. Extraction requires a nonempty
# `media.video_thumbnail.command`.
#
# reloadable: yes
#
#timeout = 30

# Limits simultaneous video thumbnail extractions.
#
# Video decoding costs much more than image scaling, so excess requests
# wait for a slot instead of adding host load. Slots span video staging
# through program exit, also limiting the number of staged videos.
# Increase this when cores are available; changes require a restart. This
# applies only when `media.video_thumbnail.command` is nonempty.
#
#concurrency = 1

# Limits the byte size of staged videos and extracted frames.
#
# Oversized videos are served without thumbnails rather than staged, and
# oversized frames are refused rather than decoded from truncated data.
# Accepts an integer byte count or an SI/IEC string such as "128 MiB".
# Extraction requires a nonempty `media.video_thumbnail.command`.
#
# reloadable: yes
#
#max_size = "128 MiB"

# Selects the directory for staging videos read by thumbnail programs.
#
# Each running program has one file, removed when it exits. When unset, a
# `tmp` subdirectory of the database path keeps large videos off the
# memory-backed `/tmp` commonly provided by service managers. Files left
# by a killed server are reclaimed at startup even when
# `media.video_thumbnail.command` is empty. Extraction itself requires a
# nonempty command.
#
# reloadable: yes
# example: "/var/tmp/tuwunel"
#
#path =


################################################################################
# Outbound networking
#
# How the server reaches other hosts. `[global.network.dns]` configures
# the built-in resolver, `[global.network.discovery]` bounds well-known
# lookups of federation destinations, and `[global.network.http]` sets
# limits and address filtering for outbound HTTP requests. The server's
# own listener is configured under `[global.http]` instead.
#
#[global.network]


################################################################################
# Federation server discovery
#
# Timeouts for fetching `https://<server>/.well-known/matrix/server` from
# other homeservers while working out where to send federation requests.
#
#[global.network.discovery]

# Sets the federation well-known resolution connection timeout in
# seconds.
#
#conn_timeout = 6

# Sets the federation HTTP well-known resolution request timeout in
# seconds.
#
#timeout = 10


################################################################################
# DNS resolver
#
# The server resolves host names for its outbound HTTP requests with its
# own resolver rather than the system library. With `servers` empty it
# takes its nameservers from `/etc/resolv.conf` at startup. Answers are
# kept for at least `min_ttl` (`min_ttl_nxdomain` for missing domains)
# whatever their TTL.
#
# Tips:
# - `servers` entries must be IP addresses with an optional port; a host
#   name fails startup.
# - `passthru_domains` entries are regular expressions; a plain dotted
#   name logs a startup warning because each dot matches any character.
# - Only `passthru_domains` applies on reload; other changes need a
#   restart.
#
#[global.network.dns]

# Selects custom DNS servers instead of the operating system resolvers.
#
# A non-empty list prevents reading `/etc/resolv.conf`. Each entry is an
# IP address with an optional port, defaulting to 53. Servers are
# expected to support both UDP and TCP on that port; enable
# `network.dns.query_over_tcp_only` if any server supports only TCP.
#
# example: ["127.0.0.53", "1.1.1.1:5353", "[fd00::1]:53"]
#
#servers = []

# Sets the maximum DNS memory cache entries; increase cautiously because
# entry sizes vary, and decrease only with an external DNS cache, excluding
# systemd-resolved even when configured to cache.
#
#cache_entries = 32768

# Sets the minimum DNS cache lifetime in seconds, intentionally high by
# default for federation with many servers whose domains have shorter TTLs;
# an external cache merely shifts this load to a cache unaware of the
# application's needs, where honoring low TTLs can increase load.
#
#min_ttl = 10800

# Sets the minimum cached NXDOMAIN lifetime in seconds, defaulting to three
# days because false negatives are very rare and efficient federation
# requires aggressively caching domains assumed not to return rather than
# repeatedly checking them.
#
#min_ttl_nxdomain = 259200

# Sets the number of DNS nameserver retries after a timeout or error.
#
#attempts = 10

# Sets the DNS response timeout in seconds; recursive queries to some
# domains can take several seconds, so avoid overly short timeouts,
# especially with slower hardware or resolvers.
#
#timeout = 10

# Enables TCP fallback after DNS errors.
#
# Disable this if the nameserver does not support it.
#
#tcp_fallback = true

# Enables querying all nameservers until the domain is found.
#
# Hickory resolver calls this "trust_negative_responses". It can avoid
# unnecessary queries when the first nameserver returns NXDOMAIN or an
# empty NOERROR response.
#
#query_all_nameservers = true

# Queries configured nameservers using only TCP instead of UDP, as some
# container deployments require (see [DNS
# troubleshooting](https://tuwunel.chat/troubleshooting.html#potential-dns-issues-when-using-docker)).
#
#query_over_tcp_only = false

# Selects the DNS A/AAAA lookup strategy by number.
#
# Use 1 (Ipv4Only) to query only A records with no AAAA/IPv6, or 2
# (Ipv6Only) to query only AAAA records with no A/IPv4. Use 3
# (Ipv4AndIpv6) to query both in parallel and accept the first successful
# response. Use 4 (Ipv6thenIpv4) to query AAAA then A on failure, or 5
# (Ipv4thenIpv6) to query A then AAAA on failure. Without IPv6
# networking, 1 can improve DNS performance because successful AAAA
# results cannot be used.
#
#ip_lookup_strategy = 5

# Selects domain patterns resolved through the alternative DNS path.
#
# This path has no persistent cache, a very small memory cache, and no
# enforced TTL. It serves internal networks and application services that
# require those properties, and does not support federation or general
# use.
#
# reloadable: yes
# example: ['\.dns\.podman$']
#
#passthru_domains = []

# Resolves application services through the alternative DNS path; when all
# should match, prefer this to listing domains in
# `network.dns.passthru_domains` to avoid regex matching overhead and
# domain list maintenance.
#
#passthru_appservices = false

# Randomizes DNS query case and requires matching answer case to mitigate
# spoofing; occasional logged errors usually indicate DNS overload, it can
# be disabled for servers lacking support, and the false default follows
# reports about popular DNS caches whose possible fixes may allow a future
# release to restore true.
#
#case_randomization = false


################################################################################
# Outbound HTTP requests
#
# Defaults for HTTP requests the server makes to other hosts: federation,
# remote media and URL previews, push gateways, appservices and identity
# providers. The server's own listener is configured in `[global.http]`
# instead. Some clients override the timeouts here:
# `[global.federation.transport]`, `[global.sending]`,
# `[global.appservice_client]`, `[global.push]` and
# `[global.network.discovery]`.
#
# Tips:
# - The default `ip_range_denylist` refuses private, loopback and
#   link-local addresses, including a push gateway or URL preview target
#   on your LAN. Remove just the range you need rather than emptying
#   the list. Appservice requests are not checked against it.
# - An `ip_range_denylist` entry that is not a valid CIDR range fails
#   startup.
# - Outbound proxies are set with `proxy` (the `[global.proxy]` table) or,
#   while `proxy` stays `"none"`, by the `HTTP_PROXY`, `HTTPS_PROXY` and
#   `ALL_PROXY` environment variables.
#
#[global.network.http]

# Limits the size of a response body buffered from a remote server.
#
# This applies to federation requests, push gateway and appservice
# transactions, and remote media fetched for URL previews. Peers cannot
# be trusted to honor requested limits, so the local bound protects
# against a remote exhausting process memory. Accepts an integer byte
# count or a string with an SI/IEC suffix such as "256 MiB".
#
#max_response_size = "256 MiB"

# Sets the default outbound HTTP connection timeout in seconds;
# individual clients may override it.
#
#conn_timeout = 10

# Sets the default outbound HTTP read timeout in seconds; individual
# clients may override it.
#
#timeout = 35

# Sets the default outbound HTTP whole-request timeout in seconds.
#
# Keep it high enough for healthy requests while retaining a timeout
# backstop. Individual clients may override it.
#
#total_timeout = 320

# Sets the default outbound HTTP idle connection pool timeout in seconds;
# individual clients may override it.
#
#idle_timeout = 5

# Sets the default maximum idle outbound HTTP connections per host;
# individual clients may override it.
#
#idle_per_host = 1

# Allows outbound HTTP clients to negotiate gzip response compression.
#
# Clients advertise gzip in `Accept-Encoding` and transparently
# decompress responses for federation, media, and URL preview traffic.
# This is separate from `http.compression.gzip`, which compresses
# tuwunel's own responses. It is enabled by default; disabling it
# prevents both requesting and decompressing gzip. It has no effect
# unless tuwunel was built with the `gzip_compression` feature.
#
#gzip = true

# Allows outbound HTTP clients to negotiate brotli response compression.
#
# Clients advertise brotli in `Accept-Encoding` and transparently
# decompress responses for federation, media, and URL preview traffic.
# This is separate from `http.compression.brotli`, which compresses
# tuwunel's own responses. It is enabled by default; disabling it
# prevents both requesting and decompressing brotli. It has no effect
# unless tuwunel was built with the `brotli_compression` feature.
#
#brotli = true

# Allows outbound HTTP clients to negotiate zstd response compression.
#
# Clients advertise zstd in `Accept-Encoding` and transparently
# decompress responses for federation, media, and URL preview traffic.
# This is separate from `http.compression.zstd`, which compresses
# tuwunel's own responses. It is enabled by default; disabling it
# prevents both requesting and decompressing zstd. It has no effect
# unless tuwunel was built with the `zstd_compression` feature.
#
#zstd = true

# Blocks outbound requests to the listed IPv4 and IPv6 CIDR ranges.
#
# Entries are quoted strings; the defaults cover RFC1918, unroutable,
# loopback, multicast, and testnet addresses for security, and an empty
# vector (`[]`) disables this filter. Application filtering can have
# bypasses, so enforce network boundaries with firewall zones rather than
# treating this as a guarantee.
#
# Proxy endpoints selected through configuration or environment variables
# are exempt so private forward proxies remain reachable, while direct
# requests and locally resolving `socks4` or `socks5` proxies still
# filter destination addresses. HTTP(S) forward proxies and `socks4a` or
# `socks5h` resolve destinations remotely, so their egress policy must
# enforce destination network boundaries instead.
#
# Defaults to:
# ["127.0.0.0/8", "0.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12",
# "192.168.0.0/16", "100.64.0.0/10", "192.0.0.0/24", "169.254.0.0/16",
# "192.88.99.0/24", "198.18.0.0/15", "192.0.2.0/24", "198.51.100.0/24",
# "203.0.113.0/24", "224.0.0.0/4", "::1/128", "::/128", "fe80::/10",
# "fc00::/7", "2001:db8::/32", "ff00::/8", "fec0::/10"]
#
#ip_range_denylist =


################################################################################
# Presence
#
# Controls online, idle and offline status for local users and how it is
# exchanged with other servers. Presence is on by default, both locally and
# over federation, where a local user's status goes only to servers that
# share a room with them.
#
# Tips:
# - To turn presence off, set `allow_local`, `allow_incoming` and
#   `allow_outgoing` all to false; startup and reload refuse
#   `allow_outgoing` without `allow_local`.
# - With `allow_local` off, sync and other client activity stop refreshing
#   each device's last-seen time and IP address.
# - To keep presence between local users but cut its federation traffic,
#   turn off `allow_incoming` and `allow_outgoing` instead.
#
#[global.presence]

# Allows local presence updates and requests.
#
# This must be enabled when using `presence.allow_outgoing`.
#
# reloadable: yes
#
#allow_local = true

# Allows incoming federated presence updates and requests.
#
# This receives updates but sends none unless `presence.allow_outgoing`
# is enabled.
#
# reloadable: yes
#
#allow_incoming = true

# Allows outgoing federated presence updates and requests.
#
# This sends updates but receives none unless `presence.allow_incoming`
# is enabled, and it requires `presence.allow_local`.
#
# reloadable: yes
#
#allow_outgoing = true

# Sets the seconds without presence updates before a user becomes idle,
# defaulting to five minutes.
#
#idle_timeout_s = 300

# Sets the seconds without presence updates before a user becomes
# offline, defaulting to thirty minutes.
#
#offline_timeout_s = 1800

# Enables the presence idle timer for remote users.
#
# Disabling it can reduce resource use on servers participating in many
# large rooms or with limited resources. Some remote users may then show
# incorrect presence states, such as remaining online indefinitely.
#
#timeout_remote_users = true


################################################################################
# User profiles
#
# Controls who can read profiles, whether users can change their own
# display name and avatar, and how much of a remote profile is cached. By
# default the client profile endpoints answer without an access token,
# other servers can look up local profiles, and device names are not
# shared over federation.
#
# Tips:
# - To hide profiles from people outside a user's rooms, set
#   `require_auth` and `limit_requests_to_users_who_share_rooms` together;
#   startup and reload refuse the second alone. Requests from other
#   servers are governed by `allow_inbound_federation_lookups` instead.
#
#[global.profile]

# Requires authentication on profile retrieval endpoints when enabled.
#
# This covers normally unauthenticated GET requests to
# `/_matrix/client/v3/profile/{userId}` and can prevent profile scraping.
#
# reloadable: yes
#
#require_auth = false

# Limits fields retained in a remote user's cached profile.
#
# The count includes `displayname` and `avatar_url` and must exceed zero.
# A refresh exceeding it is rejected without changing the cache. Lowering
# the limit leaves existing profiles intact, but subsequent refreshes
# must fit.
#
# reloadable: yes
#
#max_remote_fields = 100

# Limits selected profile fields in a sync request or stored filter.
#
# This positive limit counts raw selectors before deduplication in
# sliding and legacy sync; requests exceeding it or the 255-byte name
# limit are rejected. Sliding sync retains normalized selections when
# selectors are omitted, so after lowering the limit an oversized
# selection needs replacement or a restarted connection. Unfiltered
# sliding-sync profiles are not limited by this count.
#
# reloadable: yes
#
#max_fields_per_request = 64

# Allows standard users to set or clear display names through the client
# profile API.
#
# Server admins and appservices can always change display names.
#
# reloadable: yes
#
#enable_set_displayname = true

# Allows standard users to set or clear avatars through the client
# profile API.
#
# Server admins and appservices can always change avatars. Unlike
# Synapse's option of the same name, disabling this also stops users
# without an avatar from setting their first one.
#
# reloadable: yes
#
#enable_set_avatar_url = true

# Restricts client profile retrieval to the user themselves or users
# sharing a currently joined room.
#
# Appservices are exempt; other users receive 403 `M_FORBIDDEN`. Startup
# and configuration reload refuse this setting unless
# `profile.require_auth` is also enabled. Federation profile lookups are
# unaffected and remain controlled by
# `profile.allow_inbound_federation_lookups`.
#
# reloadable: yes
#
#limit_requests_to_users_who_share_rooms = false

# Preserves per-room profile overrides when no propagation mode is
# supplied to the profile service.
#
# For such calls, true, the default, skips display-name or avatar changes
# in rooms where that field differs from the prior global profile,
# preserving overrides such as `/myroomnick`; false applies the new
# global value throughout the joined rooms. The client profile endpoints
# supply an explicit mode and default to `all`, so this setting does not
# protect overrides through those endpoints. Clients can request `all`,
# `unchanged`, or `none` with the
# [MSC4466](https://github.com/matrix-org/matrix-spec-proposals/pull/4466)
# `computer.gingershaped.msc4466.propagate_to` query parameter.
#
# reloadable: yes
#
#preserve_room_overrides = true

# Limits the content size of membership events a client sends.
#
# A client state event for `m.room.member` whose content exceeds this many
# bytes is refused with `M_BAD_JSON`, unless it restates the sender's own
# current member event unchanged. On a join, only the extra keys the client
# supplies are measured. Events the server builds, including the profile
# changes it propagates into member events, are not limited by this
# setting.
#
# reloadable: yes
#
#member_event_max_bytes = 4096

# Allows device display names to be federated and seen by external users.
#
# This is inherently false when `federation.enable` is disabled. Leave
# disabled for privacy.
#
# reloadable: yes
#
#allow_device_name_federation = false

# Allows incoming federation profile lookups for local users.
#
# Disabling `/_matrix/federation/v1/query/profile` lookups protects local
# profile information such as display names and can deter scraping, but
# remote users may see a false "this user does not exist" error when
# inviting local users to a room or direct message. This is inherently
# false when `federation.enable` is disabled.
#
# reloadable: yes
#
#allow_inbound_federation_lookups = true


################################################################################
# Push notifications
#
# Controls delivery to the push gateways that clients register for their
# users, and which events reach them. Push works with nothing set here: by
# default the server evaluates each user's push rules and forwards only
# events the rules mark as notifying. `email_delay` decides when notification
# emails go out to users who turn them on.
#
# Tips:
# - Gateway requests obey `network.http.ip_range_denylist`, so with its
#   default a gateway on a loopback or private address is refused.
# - `suppress_when_active` is experimental and logs a warning at startup.
#   It judges activity from presence, so it needs `presence.allow_local`.
#
#[global.push]

# Sets the notification-gateway pusher idle connection-pool timeout.
#
#idle_timeout = 15

# Selects the suffix stripped from a gateway URL before constructing a
# push request.
#
# reloadable: yes
#
#notification_path = "/_matrix/push/v1/notify"

# Sends every message to HTTP pushers without filtering by push rules or
# actions.
#
# This compatibility and special-purpose setting should not normally be
# needed, but can bypass bugs or outdated server-side rule support, let
# clients evaluate rules themselves, or support hosting and custom-pusher
# requirements. It does not alter the notification records shown in the
# notifications pane. Email pushers still mail only what the push rules
# notify for.
#
# reloadable: yes
#
#everything = false

# Evaluates the `im.nheko.msc3664.related_event_match` push-rule
# condition.
#
# The condition matches properties of the event an incoming event relates
# to, enabling reply or reaction notifications for a user's own messages
# that no other condition can express. Enabling it costs one extra event
# lookup for each event carrying a relation. The default
# `.im.nheko.msc3664.reply` rule uses it; disabling evaluation leaves
# that rule present but unable to match replies, although clients
# implementing
# [MSC3664](https://github.com/matrix-org/matrix-spec-proposals/pull/3664)
# may still evaluate it locally.
#
# reloadable: yes
#
#msc3664_related_event_match = false

# Experimentally suppresses HTTP push notifications for active users.
#
# When enabled, users with Online presence and recent activity,
# determined from presence and sync activity, receive no HTTP push
# notifications, reducing duplicate alerts while active on another
# client. The default is disabled to preserve legacy behavior. Email
# pushers ignore this setting; they do not mail messages the user reads
# before `email_delay` ends.
#
# reloadable: yes
#
#suppress_when_active = false

# Seconds an unread notification waits before an email pusher mails it.
#
# Email notifications need `[global.smtp]`; a user receives them when
# their client registers an email pusher for an address verified on their
# account. A notification still unread after this delay is mailed
# together with any others waiting. A room in that mail is then held back
# longer before it can prompt each further mail, up to a day, until the
# user reads it. With a delay of 0, each notification is mailed as it
# arrives and no room is held back.
#
# reloadable: yes
#
#email_delay = 600


################################################################################
# Rate limits
#
# Groups request rate limits by kind of request. It holds
# `[global.rate_limiting.login]` for password sign-in; the built-in OIDC
# endpoints have a separate per-IP throttle,
# `authentication.oidc.rc_per_second`.
#
#[global.rate_limiting]


################################################################################
# Password sign-in limits
#
# Three token buckets guard password checks, each in its own sub-section:
# `[global.rate_limiting.login.failed]` counts wrong passwords per account
# and client address, `[global.rate_limiting.login.address]` counts every
# attempt per client address across accounts, and
# `[global.rate_limiting.login.account]` counts successful sign-ins per
# account from any address. They cover `m.login.password` at `/login` and
# the built-in OIDC login page. Password re-entry for sensitive actions
# (UIAA) has its own `failed` and `address` buckets with the same settings
# and no `account` limit. A refused attempt gets `M_LIMIT_EXCEEDED`.
#
# Tips:
# - Behind a reverse proxy, set `http.ip_source` to the header it writes.
#   Without it, password checks use the TCP peer address: a proxy on the
#   same host (or the Unix socket) gets no per-address limit, and every
#   user behind a proxy on another host shares one address.
# - Sign-ins that `[global.ldap]` decides by binding to the directory are
#   not counted; its fallback to the local password is.
# - Buckets are kept in memory and reset on restart.
#
#[global.rate_limiting.login]


################################################################################
# Successful sign-in limit
#
# Caps how often one account can sign in with a correct password, from any
# address: `burst_count` sign-ins at once, then one more every
# 1/`per_second` seconds. Wrong passwords never count, so guessing cannot
# lock the owner out on this axis. A script that logs in repeatedly can
# reach the default limit.
#
#[global.rate_limiting.login.account]

# Token-bucket refill rate (sign-ins per second) for successful password
# logins to one account.
#
# Applies to `/login` with `m.login.password` (but not to the LDAP binds it
# makes) and to the built-in OIDC login page, keyed on the account rather
# than the client IP. Mirrors Synapse's `rc_login.account` and its default
# of `burst_count` sign-ins, then about one every five and a half minutes;
# once those are used up, a correct password is refused with
# `M_LIMIT_EXCEEDED`.
#
# `0` disables this limit rather than making a bucket that never refills.
#
# reloadable: yes
#
#per_second = 0.003

# Token-bucket depth (burst size) for successful password logins to one
# account.
#
# The number of sign-ins allowed before `per_second` governs. `0` disables
# this limit, as does a `0` rate. The default is Synapse's
# `rc_login.account.burst_count`.
#
# reloadable: yes
#
#burst_count = 5


################################################################################
# Per-address attempt limit
#
# Caps all password attempts from one client address across every account,
# successful or not, bounding password spraying and hashing work:
# `burst_count` attempts at once, then one more every 1/`per_second`
# seconds. Clients behind one NAT, one IPv6 /64, or a reverse proxy on
# another host share a budget unless `http.ip_source` names a forwarding
# header. Without one, a loopback peer (a local proxy or the Unix
# socket) is not limited per address.
#
#[global.rate_limiting.login.address]

# Token-bucket refill rate for password attempts per client address.
#
# IPv6 addresses share a bucket within each /64; clients behind a shared
# address share its allowance.
# Public login and authenticated password re-entry use separate buckets.
# Unless `http.ip_source` names a forwarding header, a loopback peer such
# as a local proxy or the Unix socket is not limited per address; configure
# trusted forwarding behind a proxy to limit its clients by address.
#
# `0` disables this limit rather than making a bucket that never refills.
#
# reloadable: yes
#
#per_second = 1.0

# Token-bucket depth for password attempts per client address.
#
# The number of attempts allowed before `per_second` governs.
# `0` disables this limit, as does a `0` rate.
#
# reloadable: yes
#
#burst_count = 20


################################################################################
# Wrong-password limit
#
# Throttles password guessing against one account from one client address.
# Only wrong passwords, including names that match no account, use up the
# allowance: `burst_count` at once, then one more every 1/`per_second`
# seconds. Other addresses keep their own allowance for the same account.
#
#[global.rate_limiting.login.failed]

# Token-bucket refill rate for wrong passwords per account and client
# address.
#
# Every attempt reserves a token before verification; a correct password
# returns it, while a wrong password keeps it.
# An empty bucket refuses even a correct password from that address,
# without blocking the account from other addresses.
# IPv6 addresses share a bucket within each /64, and authenticated
# password re-entry (UIAA) uses separate buckets from public login.
#
# `0` disables this limit rather than making a bucket that never refills.
#
# reloadable: yes
#
#per_second = 0.17

# Token-bucket depth for wrong passwords per account and client address.
#
# The number of failures allowed before `per_second` governs.
# `0` disables this limit, as does a `0` rate.
#
# reloadable: yes
#
#burst_count = 3


################################################################################
# Federated read receipts
#
# Controls whether read receipts are exchanged with other servers. Both
# directions are on by default. Receipts between users of this server work
# regardless of these keys.
#
#[global.read_receipts]

# Allows receiving read receipts from remote servers.
#
# reloadable: yes
#
#allow_incoming = true

# Allows sending read receipts to remote servers.
#
# reloadable: yes
#
#allow_outgoing = true


################################################################################
# Account registration
#
# Controls who may create an ordinary account through `/register` or the
# built-in OIDC login page, and how new accounts are set up. Off by
# default. Terms users must accept live in
# `[global.registration_terms.<ID>]`, and email verification in
# `[global.smtp]`.
#
# With `enable`, startup also requires a registration token (`token` or
# `token_file`) or a required email stage
# (`smtp.require_email_for_registration` with `smtp.connection_uri`).
# Without one the server refuses to start unless
# `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
# is true, which startup warns about.
#
# Minimal example (token-gated):
#
#     [global.registration]
#     enable = true
#     token_file = "/etc/tuwunel/.reg_token"
#
# Tips:
# - Startup refuses an empty `token` and an empty or unreadable
#   `token_file`; both may be set. Tokens from `!admin token issue` also
#   work at registration but do not satisfy the startup check.
# - Password registration also needs `authentication.login.with_password`.
#   Identity providers (their `registration` key), `jwt.register_user` and
#   LDAP create accounts without `enable`, and `shared_secret` enables
#   `/_synapse/admin/v1/register` independently of it.
#
#[global.registration]

# Appends text to a new user's display name at registration, separated by
# a space.
#
# Conduit used a lightning-bolt emoji for this suffix. Set to an empty
# string to disable it. It is left out when the name leaves no room for
# it under the 256-character display name limit.
#
# reloadable: yes
#
#displayname_suffix = "💕"

# Enables ordinary new account registration.
#
# When false, ordinary registration is disabled; appservice registration
# is exempt from this switch. Without a configured token, registration
# without a second step requires
# `registration.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
# to be true. For token-only registration, configure `registration.token`
# or `registration.token_file`. Ordinary registration also requires
# `authentication.login.with_password`.
#
# reloadable: yes
#
#enable = false

# Opens registration to anyone without restrictions.
#
# This makes the server vulnerable to abuse.
#
# reloadable: yes
#
#yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse = false

# Requires new users to supply this static token when creating an
# account.
#
# Configure this value or use `registration.token_file`. If unset while
# `registration.enable` is true, unrestricted registration requires
# `registration.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
# to be true.
#
# reloadable: yes
# example: "o&^uCtes4HPf0Vu@F20jQeeWE7"
#
#token =

# Reads additional registration tokens from a file.
#
# Separate multiple tokens with whitespace. The file must be nonempty and
# accessible to the server.
#
# reloadable: yes
# example: "/etc/tuwunel/.reg_token"
#
#token_file =

# Enables out-of-band account creation with a pre-shared secret.
#
# The Synapse-style `/_synapse/admin/v1/register` endpoint requires a
# build with `synapse_admin` and is not routed when MAS delegation is
# active. Configure this value or `registration.shared_secret_file`;
# requests authenticate with HMAC-SHA1 keyed by the resolved secret and
# bypass UIAA. The file takes precedence when successfully read. Use a
# high-entropy secret of at least 32 bytes and protect it like a server
# admin's access token.
#
# reloadable: yes
# example: "kZ2hN5pQ8wXyL4mR7tBfCgJxV3aD6sE1u"
#
#shared_secret =

# Reads the registration shared secret from a file.
#
# This takes precedence over `registration.shared_secret` and falls back
# to it only when the file cannot be read. Surrounding whitespace is
# trimmed, so a trailing newline is not part of the secret. A present but
# blank file resolves to no secret without falling back.
#
# reloadable: yes
# example: "/etc/tuwunel/.reg_shared_secret"
#
#shared_secret_file =

# Lists room IDs or aliases that eligible newly registered users
# automatically join.
#
# The server must already participate in each room, and the user must
# satisfy its normal join authorization rules, including for restricted
# rooms. Rooms are processed in configured order, so an earlier join can
# satisfy a later room's membership requirement. Appservice registrations
# are excluded; guests require `registration.guests.allow_auto_join_rooms`.
# Failed joins are logged without failing registration.
#
# reloadable: yes
# example: ["#tuwunel:grin.hu",
# "!l2xV0sd51lraysuRcsWVECge4NULaH3g-ou95vgDgiM"]
#
#auto_join_rooms = []

# Forbids usernames matching listed patterns.
#
# Use regular expressions or plain words for containment matches, as in
# the example. Checks run during username-availability requests and
# registration, with startup warnings for existing local users whose
# names match.
#
# reloadable: yes
# example: ["administrator", "b[a4]dusernam[3e]", "badphrase"]
#
#forbidden_usernames = []

# Grants admin privileges during eligible registration by joining the
# user to the admin room.
#
# The registering user must be neither a guest nor an appservice user,
# and the registration caller must permit the first-user grant. The admin
# room must exist and have exactly one joined member, normally the server
# user; an empty admin room does not qualify.
#
# reloadable: yes
#
#grant_admin_to_first_user = true


################################################################################
# Guest accounts
#
# Guests are password-less accounts with a generated user ID that a client
# can create without credentials. Off by default.
#
# Tips:
# - Guest registration also requires `registration.enable`, then skips
#   interactive auth (token, email and terms stages), so enabling it on a
#   token-gated server lets anyone create guest accounts.
# - New guests are announced in the admin room only with
#   `admin.room.log_guest_registrations`.
#
#[global.registration.guests]

# Allows registrations with user type "guest".
#
# reloadable: yes
#
#enable = false

# Allows guest users to automatically join rooms listed in
# `registration.auto_join_rooms`.
#
# reloadable: yes
#
#allow_auto_join_rooms = false


################################################################################
# Registration terms
#
# Requires new users to accept policy documents, such as terms of service
# or a privacy policy, when they register. Each table adds one document to
# the `m.login.terms` stage of registration and to the built-in sign-up
# page (`authentication.oidc.native_auth`). With none configured,
# registration has no terms stage.
#
# - `<ID>`: the policy id sent to clients, such as `terms_of_service`.
#   Checked at startup: 1 to 255 characters from `0-9 a-z A-Z . _ ~ -`.
#   Bare keys may use `A-Z a-z 0-9 _ -`, so an id with `.` or `~` must be
#   quoted (`[global.registration_terms."tos.v2"]`); an unquoted dot
#   splits the name into nested tables.
#
# `version` and a `[global.registration_terms.<ID>.translations.<LANG>]`
# table are required; give it at least one language.
#
# Minimal example:
#
#     [global.registration_terms.terms_of_service]
#     version = "1.0"
#
#     [global.registration_terms.terms_of_service.translations.en]
#     name = "Terms of Service"
#     url = "https://example.com/terms"
#
# Tips:
# - A terms stage does not satisfy the open-registration startup check:
#   `registration.enable` still needs a registration token or a required
#   email stage.
# - Only new accounts see the terms (appservice and guest registrations
#   skip them); changing `version` does not ask existing users again.
#
#[global.registration_terms.<ID>]

# Version of this policy document, presented to the client. Configuring
# any `[global.registration_terms.<ID>]` block makes registration
# require an `m.login.terms` stage listing every such document; the
# `<ID>` is the policy id sent to clients.
#
# example: "1.2"
# reloadable: yes
#
#version =


################################################################################
# Registration terms translation
#
# One language version of a `[global.registration_terms.<ID>]` document:
# the title and link shown for that language. Every translation's `url`
# is recorded as accepted in the new account's `m.accepted_terms` account
# data.
#
# - `<ID>`: the `<ID>` of the policy table this translation belongs to,
#   spelled (and quoted) the same way.
# - `<LANG>`: the language code, such as `en`, `fr` or `en-US` (RFC 5646;
#   some clients use `en_US`). It is sent as the key for this translation
#   next to the policy's `version`, so it must not be `version`; it is not
#   validated otherwise. Bare keys may use `A-Z a-z 0-9 _ -`; anything
#   else must be quoted, and an unquoted dot splits the name into nested
#   tables.
#
# `name` and `url` are required; a `url` whose scheme is not `http` or
# `https` fails the startup check.
#
# Tips:
# - The built-in sign-up page (`authentication.oidc.native_auth`) links
#   one translation per policy: `en` when present, otherwise the first
#   `<LANG>` in sort order.
#
#[global.registration_terms.<ID>.translations.<LANG>]

# User friendly name of the policy document in this language.
#
# example: "Terms of Service"
# reloadable: yes
#
#name =

# Link to the text of the policy document. Must be a valid http(s) URL.
#
# example: "https://example.org/terms-1.2-en.html"
# reloadable: yes
#
#url =


################################################################################
# QR code sign-in
#
# Relays the short handshake between a new device and a signed-in one
# during QR code sign-in (MSC4108 and MSC4388), before an OAuth device
# grant completes the login. On by default, but sessions can be created
# only while the built-in OIDC server runs, which needs `well_known.client`
# plus an `identity_provider` or `authentication.oidc.native_auth`.
# Sessions live in memory and are lost on restart.
#
# Tips:
# - Reverse proxies must not cache or compress responses under the
#   rendezvous paths; compression weakens the `ETag` and sign-in fails
#   right after the scan. See
#   <https://tuwunel.chat/authentication/qr-login.html>.
#
#[global.rendezvous]

# Enables QR sign-in rendezvous sessions under
# [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)
# and
# [MSC4388](https://github.com/matrix-org/matrix-spec-proposals/pull/4388).
#
# Sessions relay the handshake between two devices before an OAuth
# device-authorization grant completes sign-in, requiring the built-in
# OIDC server. When disabled, clients hide the feature and the endpoints
# return an unrecognized response.
#
# reloadable: yes
#
#enable = true

# Limits rendezvous session payloads in bytes, with a default much larger
# than normal QR sign-in handshake messages.
#
# reloadable: yes
#
#session_max_bytes = 4096

# Sets the rendezvous session lifetime in seconds after its last write.
#
# Each update restarts the window, but the device showing the QR code
# times the whole sign-in against the expiry advertised at creation. The
# default allows time for interactive account login on the approval page.
#
# reloadable: yes
#
#session_ttl = 600

# Limits concurrent rendezvous sessions.
#
# Creating beyond the limit evicts the oldest session instead of failing.
# Zero retains one session so creation remains available.
#
# reloadable: yes
#
#max_sessions = 100

# Requires an access token for
# [MSC4388](https://github.com/matrix-org/matrix-spec-proposals/pull/4388)
# session creation.
#
# When enabled, discovery tells a client without a token that it cannot
# create a session. The
# [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)
# endpoint stays open in either mode.
#
# reloadable: yes
#
#authenticated_only = true

# Sets the per-client-IP refill rate for
# [MSC4388](https://github.com/matrix-org/matrix-spec-proposals/pull/4388)
# rendezvous requests.
#
# Zero is treated as one request per second.
#
# reloadable: yes
#
#rc_per_second = 10

# Sets the token-bucket depth for the rendezvous request throttle under
# [MSC4388](https://github.com/matrix-org/matrix-spec-proposals/pull/4388).
#
# This is the requests one client IP can make in a burst before
# `rendezvous.rc_per_second` governs replenishment. Zero is treated as
# one.
#
# reloadable: yes
#
#rc_burst_count = 20


################################################################################
# RocksDB storage engine
#
# Tunes the RocksDB engine behind the database at `database_path`. Every
# key is read when the database opens, so changes need a restart. The
# defaults assume SSD or NVMe storage, and most keys only trade memory,
# threads or log volume for speed or diagnostics.
#
# The recovery keys are different: `recovery_mode` 2 or 3 and `repair`
# can discard data, so back up `database_path` first and revert them once
# the server starts cleanly.
#
# Tips:
# - On btrfs or ZFS set `allow_fallocate = false`; startup warns while it
#   is left on there. On ZFS also set `direct_io = false`.
# - `recovery_mode` accepts 0 to 3; a larger value panics at startup.
# - `cache.capacity_modifier` also scales `write_buffer_capacity_mb`.
#
#[global.rocksdb]

# Sets the memory available to database read caches as a float in megabytes.
#
# Increasing this may improve performance when memory is available; like
# individual LRU caches, the default scales with CPU core count to 128.0 + (64.0
# * CPU core count).
#
#cache_capacity_mb = varies by system

# Sets the memory available to database write caches as a float in megabytes.
#
# Increasing this may improve performance when memory is available; like
# individual LRU caches, the default scales with CPU core count to 48.0 + (4.0 *
# CPU core count).
#
#write_buffer_capacity_mb = varies by system

# Sets the log level for RocksDB LOG files in the database directory.
#
# This differs from the application log level; tuwunel still reports RocksDB
# errors through tracing or panics on severe errors for safety.
#
#log_level = "error"

# Routes RocksDB log messages to standard error.
#
# `rocksdb.log_level` still filters the emitted records. When disabled,
# RocksDB uses the application's callback logger instead.
#
#log_stderr = false

# Sets the maximum RocksDB LOG file size before rotation.
#
# Accepts an integer byte count or a string with SI/IEC suffix such as "4 MiB".
#
#max_log_file_size = 4194304

# Time in seconds before RocksDB will forcibly rotate logs.
#
#log_time_to_roll = 0

# Uses RocksDB tunings tailored to spinning disks (HDDs).
#
# Leave this disabled on NVMe or SSD storage. When enabled, RocksDB skips
# compaction readahead and parallel file-open threads at startup. This does not
# affect Direct IO; see `rocksdb.direct_io`.
#
#optimize_for_spinning_disks = false

# Enables direct-io to increase database performance via unbuffered I/O.
#
# For more details about direct I/O and RockDB, see:
# https://github.com/facebook/rocksdb/wiki/Direct-IO
#
# Set this option to false if the database resides on a filesystem which
# does not support direct-io like FUSE, or any form of complex filesystem
# setup such as possibly ZFS.
#
#direct_io = true

# Sets the number of RocksDB threads for cleanup, sync, flush, and compaction.
#
# The stored value 0 selects the available logical thread count, with a minimum
# of two.
#
#parallelism_threads = 0

# Sets the maximum number of RocksDB LOG files retained.
#
# This must be at least 1, never 0. The default is 3 because these logs are
# mainly useful for troubleshooting or debugging RocksDB bugs.
#
#max_log_files = 3

# Sets the RocksDB database compression algorithm.
#
# Available options are "zstd", "bz2", "lz4", or "none", which disables
# compression. ZSTD balances speed, storage, IO amplification, and CPU usage;
# LZ4 offers more performance and lower CPU usage with less compression and more
# storage use. See https://github.com/facebook/rocksdb/wiki/Compression for
# details.
#
#compression_algo = "zstd"

# Level of compression the specified compression algorithm for RocksDB to
# use.
#
# Default is 32767, which is internally read by RocksDB as the default
# magic number and translated to the library's default compression level
# as they all differ. See their `kDefaultCompressionLevel`.
#
# Note when using the default value we may override it with a setting
# tailored specifically tuwunel.
#
#compression_level = 32767

# Sets the compression level for the bottommost RocksDB data.
#
# The default 32767 is RocksDB's `kDefaultCompressionLevel`, translated to the
# selected library's default level; tuwunel may override it with a tailored
# setting. Bottommost data is generally old and less frequently accessed, so
# higher compression may be useful; research the chosen algorithm.
#
#bottommost_compression_level = 32767

# Whether to enable RocksDB's "bottommost_compression".
#
# At the expense of more CPU usage, this will further compress the
# database to reduce more storage. It is recommended to use ZSTD
# compression with this for best compression results. This may be useful
# if you're trying to reduce storage usage from the database.
#
# See https://github.com/facebook/rocksdb/wiki/Compression for more details.
#
#bottommost_compression = true

# Sets the database recovery mode for RocksDB WAL corruption.
#
# When corruption prevents startup, use mode 2 (PointInTime) to recover to the
# last good state, seconds or minutes before the crash. Clients may need
# "clear-cache & reload" after this rollback. After recovery succeeds, reset the mode
# to its default and restart. In some cases the corruption error persists for at
# least 30 minutes of operation in PointInTime mode.
#
# Only as a last resort if PointInTime fails, try mode 3
# (SkipAnyCorruptedRecord), which may leave the server inconsistent. Default
# mode 1 (TolerateCorruptedTailRecords) drops only the last entry if corrupted
# during shutdown, with an extraordinarily low risk of desynchronizing clients.
# Mode 0 (AbsoluteConsistency) disables all silent rollback. See
# https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes for mode details
# and https://tuwunel.chat/troubleshooting.html#database-corruption for recovery
# guidance.
#
#recovery_mode = 1

# Enables paranoid SST file checks.
#
# Additional safety checks may improve database consistency at a performance
# cost; see the RocksDB documentation for details:
# https://github.com/facebook/rocksdb/wiki/Online-Verification#columnfamilyoptionsparanoid_file_checks
#
#paranoid_file_checks = false

# Enables runtime checksum verification in RocksDB.
#
# Checksums are enabled by default and usually hardware accelerated with low
# overhead. Older or slower platforms may gain performance by disabling them.
#
#checksums = true

# Enables RocksDB atomic flush mode.
#
# This option is not intended for users and may be removed or ignored in future
# versions. It may improve database integrity at the cost of performance.
#
#atomic_flush = false

# Enables database repair for RocksDB SST corruption.
#
# Use this when the server reports corruption while running or panics,
# especially for errors containing SST after startup; if startup fails, try
# recovery mode first. Back up the database directory before running repair.
# Disable repair mode and restart the server after repair finishes. See
# https://tuwunel.chat/troubleshooting.html#database-corruption for recovery
# details.
#
#repair = false

# Opens RocksDB in read-only mode.
#
# Writes are rejected and missing column families cannot be created. This
# mode is disabled by default.
#
#read_only = false

# Opens RocksDB as a secondary follower of a primary instance.
#
# Writes are rejected while the primary's latest WAL can be replayed into
# this instance's view. Missing column families cannot be created.
#
#secondary = false

# Enables idle CPU priority for the compaction thread.
#
# This is disabled by default to prevent compaction from falling too far behind
# on busy systems.
#
#compaction_prio_idle = false

# Enables idle IO priority for the compaction thread.
#
# This is enabled by default and usually advisable to prevent unexpected server
# lag.
#
#compaction_ioprio_idle = true

# Enables RocksDB compaction.
#
# You should never need to disable this; if troubleshooting or a bug appears to
# require it, contact the tuwunel Matrix room with details. Disabling compaction
# causes explosive database growth, gradually poor performance, excessive disk
# reads and writes, and slower shutdowns and startups.
#
#compaction = true

# Sets the level of database statistics collection from 0 to 6.
#
# Some admin commands that display database statistics require this setting;
# higher levels may affect performance. Level 0 disables statistics, level 1
# disables them in release mode and is the default, levels 2 to 3 have no
# performance impact, levels 3 to 5 may affect performance, and level 6 collects
# all statistics.
#
#stats_level = 1

# Ignores the list of dropped columns set by developers.
#
# This should be set to true when knowingly moving between versions in
# ways which are not recommended or otherwise forbidden, or for
# diagnostic and development purposes; requiring preservation across such
# movements.
#
# The developer's list of dropped columns is meant to safely reduce space
# by erasing data no longer in use. If this is set to true that storage
# will not be reclaimed as intended.
#
#never_drop_columns = false

# Allows RocksDB to preallocate WAL logs.
#
# Normally, RocksDB allocates certain types of files by calling
# fallocate, writing the file contents, then truncating the logs to the
# proper size. This causes pathological disk space usage on btrfs due to
# how it interacts with its Copy-on-Write implementation. On ZFS,
# fallocate(2) for preallocation is unsupported and returns EOPNOTSUPP;
# only `FALLOC_FL_PUNCH_HOLE` and `FALLOC_FL_ZERO_RANGE` are implemented.
#
# Set this to false if you run the server on btrfs or ZFS, and do not
# touch it otherwise.
#
#allow_fallocate = true


################################################################################
# Room creation, versions and lifecycle
#
# Defaults for rooms created here (version, federation, power levels), who
# may create rooms and aliases, which room versions this server accepts,
# and what happens when users leave. Creation defaults apply only to rooms
# created after a change. The room directory is configured separately in
# `[global.directory.rooms]`.
#
# Sub-sections:
#
# - `[global.rooms.delayed_events]`: events scheduled to be sent later
#   (MSC4140).
# - `[global.rooms.extremities]`: forward-extremity pruning.
# - `[global.rooms.invites]`: invite restrictions and automatic acceptance.
# - `[global.rooms.joins]`: server selection when joining remote rooms.
# - `[global.rooms.policy_server]`: room policy servers (MSC4284).
# - `[global.rooms.redaction]`: redaction, retained originals, erasure.
# - `[global.rooms.relations]`: optional edit and reference bundles.
#
# Tips:
# - Startup fails when `default_version` names a version that is not
#   enabled. Stable versions (6 and later) always are; 3 to 5 only while
#   `allow_unstable_versions` is on (the default).
# - `default_power_level_content_override` must be a table, such as
#   `{ users_default = 50 }`; any other value fails startup.
# - `forbidden_alias_names` entries are regular expressions. An entry that
#   reads as a dotted name draws a startup warning; escape the dot
#   (`"a\\.b"`) to match it literally.
#
#[global.rooms]

# Sets the default `m.federate` property for newly created rooms when the
# client does not request one.
#
# When both this setting and `federation.enable` are false, we always
# override the client-requested `m.federate` value to false. Rooms
# permanently retain the setting chosen at creation, so changing this
# value affects only new rooms.
#
# reloadable: yes
#
#federate_by_default = true

# Calls `/forget` on the user's behalf whenever they leave a room.
#
# This implements
# [MSC4267](https://github.com/matrix-org/matrix-spec-proposals/pull/4267),
# automatically forgetting rooms on leave.
#
# reloadable: yes
#
#forget_forced_upon_leave = false

# Requires local departures to be forgotten before pruning a room.
#
# Disabling this lets `prune-empty` delete rooms local users left without
# forgetting. Its force option bypasses this protection; local joins,
# invites, and pending knocks always prevent pruning.
#
# reloadable: yes
#
#prune_require_forgotten = true

# Allows standard users to create rooms.
#
# Appservices and admins can always create rooms.
#
# reloadable: yes
#
#allow_creation = true

# Allows standard users to create room aliases.
#
# Appservices and admins can always create room aliases.
#
# reloadable: yes
#
#allow_alias_creation = true

# Allows joining or creating room versions we do not officially support.
#
# Unstable versions may have flawed specifications or a non-conforming
# implementation, so correct operation is not guaranteed even when
# incorrect behavior is tolerable or unnoticed. We officially support
# versions 6 and later, with slightly experimental support for versions 3
# through 5 that works in practice. Set to false to disable these
# unsupported versions.
#
# reloadable: yes
#
#allow_unstable_versions = true

# Enables experimental room versions for developer use.
#
# Unlike unstable versions, these may be under development, prototype
# specification changes, or present serious risks to server operation or
# database integrity. Set to true only for developer use.
#
# reloadable: yes
#
#allow_experimental_versions = false

# Selects the room version used by default when creating rooms.
#
# The default follows the specification but may follow developer
# recommendations.
# Override it only with an understanding that doing so precludes updates
# to newer versions.
#
# reloadable: yes
#
#default_version =

# Sets default power-level overrides for newly created rooms.
#
# This uses the client `/createRoom` parameter's
# `power_level_content_override` shape and is merged before per-request
# overrides, so clients can still override it per room. Only new rooms
# are affected. Top-level keys replace wholesale rather than deep-merge,
# matching the client parameter: `users` or `events` replaces that entire
# computed default submap.
#
# reloadable: yes
#
#default_power_level_content_override = { users_default = 50 }

# Deactivates users who try to join banned rooms or forbidden room
# aliases or server names.
#
# This includes room aliases or IDs with forbidden server names and makes
# the user leave all rooms; federation activity such as remote invites is
# ignored. It can remove the need for admin intervention when banned
# lists contain only toxic rooms or servers that no good-faith user would
# try to join. The default is false because rooms may be banned for
# non-moderation reasons and this performs full account deactivation.
#
# reloadable: yes
#
#auto_deactivate_banned_room_attempts = false

# Forbids room aliases and room IDs matching listed regular expressions.
#
# Patterns can use regular expressions or simple words for containment
# matches, as in the example. Checks run on room alias creation and
# custom room ID creation, with startup warnings for existing database
# aliases with forbidden aliases or IDs.
#
# reloadable: yes
# example: ["19dollarfortnitecards", "b[4a]droom", "badphrase"]
#
#forbidden_alias_names = []

# Deletes rooms after the last local user leaves.
#
# This experimental feature is disabled by default to avoid surprises,
# but deployments conserving space may enable it; it may default to true
# in a future release. Some paths that remove the last local user do not
# yet invoke deletion, so a room can remain afterward.
#
# reloadable: yes
#
#delete_after_leave = false


################################################################################
# Delayed events (MSC4140)
#
# Lets clients schedule an event to be sent later, then restart its delay,
# cancel it or send it early. Element Call schedules a leave this way, so a
# caller whose client crashes still leaves the call. Scheduled events
# survive a restart, and any that fell due meanwhile are sent on startup.
#
# Tips:
# - Setting either limit to 0 disables delayed events and stops
#   advertising them to clients.
#
#[global.rooms.delayed_events]

# Limits how far ahead an event may be scheduled, in seconds.
#
# reloadable: yes
#
#max_delay_s = 86400

# Limits how many events one user may have scheduled at once.
#
# reloadable: yes
#
#max_scheduled = 100

# Checks a change to the sender's own membership against the room's
# rules when it is scheduled, as every other delayed event is.
#
# When false, such a change is checked only when it is sent, which lets
# a user schedule a join they could not make yet.
#
# reloadable: yes
#
#check_own_membership = true


################################################################################
# Forward-extremity pruning
#
# Forward extremities are a room's newest events that no later event
# references yet; events this server creates cite them as `prev_events`.
# Busy federated rooms can pile them up, so these keys trim the set while
# incoming federation events are processed. The defaults suit most servers.
#
# Tips:
# - `!admin rooms list-extremities` and `!admin rooms prune-extremities`
#   inspect and trim one room on demand.
#
#[global.rooms.extremities]

# Sets the soft cap on forward extremities tracked per room.
#
# When applying an incoming federation event would exceed this cap, we
# prune the least useful leaves from the tracked frontier until it meets
# the cap. Pruned events remain stored and referenceable by other
# servers; we only stop citing them as frontier tips. Events created by
# this server are never pruned, and 0 disables automatic pruning.
#
# reloadable: yes
#
#max = 60

# Sets the emergency bound on a room's forward extremities.
#
# A larger frontier is cut down to this bound in one step, ignoring the
# per-event pruning batch limit. Values at or below
# `rooms.extremities.max` remove pacing entirely and prune straight to
# the cap.
#
# reloadable: yes
#
#emergency_max = 256

# Limits forward extremities pruned by one incoming event between the
# soft cap and emergency bound.
#
# This spreads convergence across events to bound each event's work. A
# value of 0 stops paced pruning and leaves only the emergency bound.
#
# reloadable: yes
#
#prune_batch = 32


################################################################################
# Room invites
#
# Restricts who may send and receive invites, and can accept invites on
# users' behalf. At the defaults neither applies: invites follow the normal
# room rules and wait for the user to answer.
#
# Tips:
# - `auto_accept_direct_only` and `auto_accept_local_only` only narrow
#   `auto_accept`; with `auto_accept = false` they do nothing.
# - `auto_accept` on its own also accepts invites from users on other
#   servers, joining local users to remote rooms; add
#   `auto_accept_local_only` to prevent that.
# - These keys do not filter by server. To refuse everything from a
#   server, invites included, use `federation.forbidden_remote_server_names`.
#
#[global.rooms.invites]

# Blocks non-admin local users from sending local or remote invites and
# non-admin users from receiving remote invites.
#
# Admins can always send and receive all room invites.
#
# reloadable: yes
#
#block_non_admin = false

# Automatically joins local users to any room they are invited to.
#
# The join runs in the background once the invite is recorded, and is
# retried for a short while when a federated invite has not yet settled
# on the inviting server. Users who are deactivated, suspended, or locked
# are never joined.
#
# reloadable: yes
#
#auto_accept = false

# Restricts automatic invite acceptance to direct-message invites.
#
# This restricts `rooms.invites.auto_accept`. The invite must carry
# `is_direct` in its membership content, which clients set when starting
# a direct chat. Invites to any other room are left for the user to
# answer.
#
# reloadable: yes
#
#auto_accept_direct_only = false

# Restricts automatic invite acceptance to invites sent by local users.
#
# This restricts `rooms.invites.auto_accept`. Invites arriving from
# another server are left for the user to answer.
#
# reloadable: yes
#
#auto_accept_local_only = false


################################################################################
# Joining remote rooms
#
# Controls which resident servers this server asks, and how many, when
# joining a room through other servers. At the defaults, servers matching
# `matrix\.org` are tried last and a join request gives up after three
# failed attempts.
#
# Tips:
# - `deprioritize_servers` entries are regular expressions matched against
#   server names. An entry that reads as a dotted name draws a startup
#   warning; write `"example\\.org"`, not `"example.org"`.
#
#[global.rooms.joins]

# Lists server names to try last when joining rooms.
#
# Client-requested joins through these servers try them last, which can
# prevent failed joins caused by a particular server's timeouts.
#
# reloadable: yes
#
#deprioritize_servers = ["matrix\\.org"]

# Limits `make_join` requests within each join attempt.
#
# Each request tries a different server, with each server tried only once
# per attempt. Servers can be retried when the entire join request is
# retried.
#
# reloadable: yes
#
#max_make_join_per_attempt = 48

# Limits join attempts per client join request.
#
# Each attempt contains one or more `make_join` requests bounded by
# `rooms.joins.max_make_join_per_attempt` and one `send_join` request.
# Additional attempts let more servers act as the join server before
# returning the last error to the client.
# The default exceeds one while limiting the risk of exceeding the
# client's request timeout, although exceeding it may sometimes be
# unavoidable.
#
# reloadable: yes
#
#max_attempts_per_request = 3


################################################################################
# Room policy servers (MSC4284)
#
# A room can name a policy server in its `m.room.policy` state event; that
# server is asked to sign each event before it federates. These keys decide
# whether this server takes part. Off by default, in which case policy
# servers are ignored: outgoing events are not sent for signing and
# incoming events are not checked.
#
# Tips:
# - When enabled, an outgoing event the policy server refuses is not sent
#   and the client request fails; an incoming event it refuses is
#   soft-failed. When the policy server cannot be reached, events pass.
# - `request_timeout` has no effect unless `enable = true`.
#
#[global.rooms.policy_server]

# Requests policy-server signatures for outgoing events under
# [MSC4284](https://github.com/matrix-org/matrix-spec-proposals/pull/4284).
#
# For a room with a valid `m.room.policy` state event, we request a
# signature from its policy server's federation `/sign` endpoint before
# federating each event. Refusal aborts the local request; network and
# timeout failures fail open with a warning log so a transient outage
# does not silently take the room offline.
#
# reloadable: yes
#
#enable = false

# Sets the policy-server request timeout in seconds under
# [MSC4284](https://github.com/matrix-org/matrix-spec-proposals/pull/4284).
#
# This applies to outbound `/sign` calls and inbound signature fetches.
#
# reloadable: yes
#
#request_timeout = 5


################################################################################
# Redaction, retained originals and erasure
#
# Governs redactions and what survives them. By default the server keeps
# each redacted event's original content for 60 days, readable by server
# admins and by users whose power level reaches `redact`, and serves erased
# users' events as pruned copies to servers that had no user in the room.
#
# Tips:
# - `retention_seconds = 0` keeps originals forever; otherwise expired
#   originals are removed in an hourly pass.
# - Turning off `save_unredacted_events` stops new copies only; copies
#   already kept stay until `retention_seconds` expires them.
# - `thread_latest_reply_search_limit = 0` fails startup.
#
#[global.rooms.redaction]

# Limits relation rows read by each thread scan during redaction.
#
# Replacing a redacted latest thread reply, and correcting each of a
# member's unread counters after a redacted reply, each read at most this
# many rows; missing, malformed, unrelated, and redacted events consume
# the budget before event filtering. When it runs out, the thread summary
# is omitted and the thread's unread count may stay one too high until a
# thread or unthreaded receipt clears it.
#
# reloadable: yes
#
#thread_latest_reply_search_limit = 1024

# Saves original events before applying redactions.
#
# Retrieve them with `admin debug get-retained-pdu` or
# [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815).
#
# reloadable: yes
#
#save_unredacted_events = true

# Sets the redaction retention period in seconds.
#
# By default the unredacted events are stored for 60 days.
#
# reloadable: yes
#
#retention_seconds = 5184000

# Allows users with `redact` power level to request unredacted events
# under
# [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815).
#
# Server admins can request unredacted events regardless of this setting.
#
# reloadable: yes
#
#allow_room_admins_to_request_unredacted_events = true

# Prevents local users from sending redactions.
#
# This check does not apply to server admins.
#
# reloadable: yes
#
#disable_local = false

# Serves erased senders' events as pruned copies over federation under
# [MSC4025](https://github.com/matrix-org/matrix-spec-proposals/pull/4025).
#
# A requesting server retains the unredacted view only when one of its
# users was joined in the room state at the event. Join handshakes are
# not gated.
#
# reloadable: yes
#
#enforce_erasure_over_federation = true


################################################################################
# Relation bundles
#
# Adds optional edit and reference summaries to events served to clients.
# Both are off by default; most clients build these themselves, so enable
# one only for a client that relies on it. Thread summaries are always
# bundled and do not depend on these keys.
#
#[global.rooms.relations]

# Bundles the latest message edit under
# [MSC3925](https://github.com/matrix-org/matrix-spec-proposals/pull/3925).
#
# Client read endpoints fold the most recent `m.replace` relation into
# `unsigned.m.relations` as the full replacement event. This is opt-in
# and disabled by default because it adds a typed index seek per served
# event and a server-authoritative summary most clients reconstruct
# locally.
#
# reloadable: yes
#
#bundle_edits = false

# Bundles reference relations under
# [MSC2675](https://github.com/matrix-org/matrix-spec-proposals/pull/2675)
# and
# [MSC3267](https://github.com/matrix-org/matrix-spec-proposals/pull/3267).
#
# Client read endpoints fold `m.reference` relations into
# `unsigned.m.relations` as `{ chunk: [{ event_id }, ...] }`. This is
# disabled by default and adds read-time work when enabled; clients can
# resolve references for polls, beacons, and verification directly.
#
# reloadable: yes
#
#bundle_references = false


################################################################################
# Runtime scheduling
#
# Groups internal scheduling settings. `[global.runtime.stream]` sets how
# much work the server's internal streams run at once and how large their
# database request batches are. The defaults adapt to the hardware
# detected at startup.
#
#[global.runtime]


################################################################################
# Stream concurrency
#
# Sets the concurrency (width) and database batch size (amplification) of
# the server's internal streams. With `width_scale` above zero, both are
# recalculated at startup from the `[global.database.pool]` size, using
# `width_default` and `amplification` as the base values. All keys are
# read once at startup.
#
# Tips:
# - Width is clamped to 1 through 1024 and amplification to 32 through
#   32768.
#
#[global.runtime.stream]

# Sets the initial stream concurrency.
#
# The default is 32. The computed
# `runtime.stream.width_scale` overrides this value unless scaling is
# disabled, in which case it provides a fixed stream width.
#
#width_default = 32

# Scales stream concurrency from the detected system capacity.
#
# The base is the database pool worker count derived from hardware
# queue size, such as 32 for SSDs or 64 or 128+ for NVMe; multipliers
# such as 1.5 or 2.0 increase it, while 0.5 improves responsiveness for
# many users at the cost of per-user throughput. The result cannot
# exceed the pool's worker count per queue, because larger values stall
# the Tokio task. A value of 0.0 fixes the width at
# `runtime.stream.width_default`. The default scale of 1.0 matches
# detected system capabilities.
#
#width_scale = 1.0

# Sets the initial request batch amplification factor.
#
# The factor controls batch sizes submitted by each pool worker,
# multiplying stream throughput independently of specific hardware
# characteristics, so it can greatly exceed thread counts or queue
# sizes. Each database query may require several index lookups,
# allowing queries in a batch to progress independently while sharing
# index and data blocks, whether cached or not. Large batches reduce
# complexity. The maximum is 32768, which still requires sufficient
# hardware.
#
#amplification = 1024


################################################################################
# Outbound delivery queue
#
# Timeouts, retry pacing, worker count and startup behavior for the
# outbound queue that delivers federation transactions, appservice
# transactions and push notifications.
#
# Tips:
# - Every startup trims each destination's failed or unfinished
#   deliveries to the first `startup_netburst_keep` and deletes the rest
#   without retrying, whether or not `startup_netburst` is enabled; `-1`
#   keeps them all.
#
#[global.sending]

# Sets the federation sender request timeout in seconds.
#
#timeout = 180

# Sets the federation sender idle connection pool timeout (seconds).
#
#idle_timeout = 180

# Sets the federation sender transaction retry backoff limit (seconds).
#
# reloadable: yes
#
#retry_backoff_limit = 86400

# Sets the grace period in seconds before retrying a federation
# destination that has failed exactly once.
#
# This replaces the quadratic backoff curve for the first retry, so a
# single transient failure does not hold delivery until the next backoff
# window. A second consecutive failure returns to the backoff curve. Set
# to 0 to disable the grace and back off from the first failure.
#
#retry_grace = 15

# Sets the grace period for clean shutdown of federation requests
# (seconds).
#
# reloadable: yes
#
#shutdown_timeout = 5

# Retries failed and incomplete messages to remote servers immediately at
# startup.
#
# This is called bursting; disabling it retries queued messages on a
# paced timer after startup instead of all at once, reducing startup load
# when resources are extremely limited or deployment scale is huge.
#
#startup_netburst = true

# Caps the unsent messages kept per destination at startup.
#
# The cap applies whether or not `sending.startup_netburst` is enabled,
# and messages past it are dropped and never reattempted. -1 keeps every
# message and can consume significant disk, while 0 drops all messages
# without any redelivery attempt.
#
#startup_netburst_keep = 50

# Sets the number of sender task workers and their parallelism.
#
# The default 0 selects the count internally, likely matching Tokio
# worker threads or CPU cores. Set a nonzero value to override that
# count.
#
#workers = 0


################################################################################
# Outbound email (SMTP)
#
# Sends verification mail so users can prove they own an email address:
# at registration, when adding an address, and for password reset. With
# no `connection_uri`, no mail is sent and those requests are refused.
#
# `connection_uri` needs `sender` and `well_known.client` (verification
# links point there), and the `require_email_*` keys need `connection_uri`;
# otherwise startup fails.
#
# Minimal example:
#
#     [global.well_known]
#     client = "https://matrix.example.com"
#
#     [global.smtp]
#     connection_uri = "smtps://user:pass@mail.example.com:465"
#     sender = "Example <noreply@example.com>"
#
# Tips:
# - `require_email_for_registration` with `connection_uri` adds a
#   verified-email stage to registration, which startup accepts in place
#   of the registration token that `registration.enable` otherwise needs.
# - Verification links open `/_tuwunel/3pid/email/validate` under
#   `well_known.client`; the reverse proxy must forward that path.
# - The built-in OIDC sign-up page cannot collect an email address, so it
#   refuses registration while an email is required.
#
#[global.smtp]

# Connection URL for the outbound SMTP relay used to send email
# verification messages. Setting this enables the email subsystem;
# without it no mail is sent.
#
# Use a `smtp://` URL for an unencrypted or STARTTLS connection and a
# `smtps://` URL for implicit TLS. Credentials and the host go inline:
# `smtps://user:pass@host:port`. The port defaults per scheme when
# omitted.
#
# The userinfo component is URL-encoded, so an `@` inside the username
# must be written as `%40` (for example a login of `bot@example.com`
# becomes `smtps://bot%40example.com:pass@host:465`). Other reserved
# characters in the username or password are percent-encoded the same
# way.
#
# example: "smtps://user:pass@mail.example.com:465"
#
#connection_uri =

# The mailbox that outbound verification messages are sent from. Accepts
# either a bare address or a display-name form.
#
# example: "Example <noreply@example.com>"
#
#sender =

# Rejects email domains matching these regular expressions during native
# registration and self-service email addition.
#
# SSO registration and email addresses supplied by identity providers are
# exempt.
#
# Patterns match only the canonical domain: lowercase with `ß` expanded to
# `ss`, without changing plus-addressing or dots. Anchor patterns to match
# whole domains, for example `^example[.]com$` or `(^|[.])example[.]com$`
# to include subdomains; an empty list imposes no domain exclusions.
# Existing bindings and password resets remain usable, while previously
# verified addresses are checked again before native registration or
# self-service addition.
#
# reloadable: yes
#
#forbidden_email_domains = []

# Require a verified email address to complete registration. When set,
# the registration flow does not finish until the user proves control of
# an email address.
#
#require_email_for_registration = false

# Require a verified email address when registering with a registration
# token. When set, token-based registration also demands a verified
# email address.
#
#require_email_for_token_registration = false


################################################################################
# Google Cloud Storage provider
#
# Stores media in a Google Cloud Storage bucket. With no credential keys
# set, credentials come from the environment and finally the instance
# metadata server, so GKE Workload Identity needs no key file.
#
# - `<ID>`: your name for this provider. Media uses a provider only when
#   `media.storage_providers` (default `["media"]`) lists it;
#   `media.store_on_providers` and `media.import.conduit.source_provider`
#   name providers the same way. Listing an undefined id fails startup.
#   `media` is the built-in local provider, and a `media` entry replaces
#   it. Use one backend (`local`, `s3` or `gcs`) per `<ID>`. Bare keys may
#   use `A-Z a-z 0-9 _ -`; anything else must be quoted
#   (`[global.storage_provider."my.media".gcs]`), and an unquoted dot
#   splits the name into nested tables.
#
# `bucket` is the only required key; without it the entry is skipped,
# even when `media.storage_providers` lists it. Skipping it is an error
# only when no enabled provider is left to receive uploads.
#
# Minimal example:
#
#     [global.storage_provider.gcs_media.gcs]
#     bucket = "my-media-bucket"
#
# Tips:
# - `media.storage_providers = ["media", "gcs_media"]` with
#   `media.store_on_providers = ["gcs_media"]` writes new media to GCS and
#   still reads older media from `media`. Without `store_on_providers`,
#   every upload goes to both (startup warns).
# - Providers are built once at startup, so a config reload that adds,
#   removes or changes a provider section is refused; restart instead.
#
#[global.storage_provider.<ID>.gcs]

# The name of the GCS bucket, e.g. "my-media-bucket". Required; an unset
# bucket disables this provider.
#
# A `gs://bucket/path` URL is intentionally not accepted here: the path
# component would not be applied as an object prefix. Set `bucket` and
# `base_path` separately instead.
#
#bucket =

# Optional path prefix within the bucket where all our operations will take
# place.
#
#base_path =

# (expert use) Path to a Google service account key file. Leave unset to
# resolve credentials from the environment, which on GCE/GKE ends at the
# instance metadata server; that is the keyless path and the recommended
# configuration. Setting this requires exported key material.
#
#service_account_path =

# (expert use) Path to an application default credentials file. Leave unset
# to resolve credentials from the environment. Only service-account and
# authorized-user documents are recognised, not every
# external-account/workload-identity-federation file format.
#
#application_credentials_path =

# (expert use) Threshold size for switching to multi-part uploads. This value
# determines what a "large" upload is. The value is a parsed string allowing
# SI or IEC units for convenience.
#
#multipart_threshold = "100 MiB"

# (expert use) Size of each individual part within a multi-part upload. Once
# an upload exceeds `multipart_threshold` the payload is split into parts of
# this size, each sent as a separate request. The value is a parsed string
# allowing SI or IEC units for convenience.
#
#multipart_part_size = "10 MiB"

# (developer use) Allows skipping request signatures.
#
#use_signatures = true

# (developer use) Enables checks performed at startup, such as probing the
# provider. Failures are considered critical startup errors and abort
# startup. When set to false, faulty providers are only discovered on first
# use and will not be fatal errors.
#
# The check is a listing probe: it requires `storage.objects.list`, proves
# neither write nor delete permission, and passes on an empty bucket.
#
#startup_check = true


################################################################################
# Local filesystem storage provider
#
# Stores media files under a local directory. Unless replaced, a built-in
# local provider named `media` keeps media in the `media` directory under
# `database_path`; add a table here to move that directory or to add
# another one.
#
# - `<ID>`: your name for this provider. Media uses a provider only when
#   `media.storage_providers` (default `["media"]`) lists it;
#   `media.store_on_providers` and `media.import.conduit.source_provider`
#   name providers the same way. Listing an undefined id fails startup.
#   `media` is the built-in local provider, and a `media` entry replaces
#   it. Use one backend (`local`, `s3` or `gcs`) per `<ID>`. Bare keys may
#   use `A-Z a-z 0-9 _ -`; anything else must be quoted
#   (`[global.storage_provider."my.media".local]`), and an unquoted dot
#   splits the name into nested tables.
#
# `base_path` is required; an empty value disables the entry. Unless
# `create_if_missing` is set, the directory must already exist or startup
# fails.
#
# Example (moving the built-in `media` directory):
#
#     [global.storage_provider.media.local]
#     base_path = "/srv/tuwunel/media"
#
# Tips:
# - The built-in `media` provider creates its directory; an explicit
#   `media` entry does so only with `create_if_missing`.
# - Providers are built once at startup, so a config reload that adds,
#   removes or changes a provider section is refused; restart instead.
#
#[global.storage_provider.<ID>.local]

# Absolute path to this local filesystem storage provider. Technically the
# provider exists at the filesystem root, and the base_path is prefixed to
# all objects.
#
#base_path =

# Creates the directory on the local filesystem if missing. This is not
# recommended to prevent misconfigured environments and missing mounts
# from silently succeeding.
#
#create_if_missing = false

# Toggles the preservation of a directory after its last file contents are
# removed.
#
#delete_empty_directories = true

# Enables checks performed at startup determining the usability of the
# local directory. Failures will abort the server's startup.
#
#startup_check = true


################################################################################
# S3 storage provider
#
# Stores media in an S3-compatible object store: AWS S3, or another
# service reached through `endpoint`.
#
# - `<ID>`: your name for this provider. Media uses a provider only when
#   `media.storage_providers` (default `["media"]`) lists it;
#   `media.store_on_providers` and `media.import.conduit.source_provider`
#   name providers the same way. Listing an undefined id fails startup.
#   `media` is the built-in local provider, and a `media` entry replaces
#   it. Use one backend (`local`, `s3` or `gcs`) per `<ID>`. Bare keys may
#   use `A-Z a-z 0-9 _ -`; anything else must be quoted
#   (`[global.storage_provider."my.media".s3]`), and an unquoted dot
#   splits the name into nested tables.
#
# Set `url` or `bucket`; with neither, the entry is skipped, even when
# `media.storage_providers` lists it. Skipping it is an error only when no
# enabled provider is left to receive uploads. Keys left unset fall back
# to the standard `AWS_*` environment variables.
#
# Example:
#
#     [global.storage_provider.s3_media.s3]
#     bucket = "my-media-bucket"
#     region = "us-west-2"
#     key = "CHANGE_ME"
#     secret = "CHANGE_ME"
#
# Tips:
# - `media.storage_providers = ["media", "s3_media"]` with
#   `media.store_on_providers = ["s3_media"]` writes new media to S3 and
#   still reads older media from `media`. Without `store_on_providers`,
#   every upload goes to both (startup warns).
# - The path in an `s3://bucket/path` `url` is not used as a prefix; set
#   `base_path` instead.
# - Providers are built once at startup, so a config reload that adds,
#   removes or changes a provider section is refused; restart instead.
#
#[global.storage_provider.<ID>.s3]

# Sets the bucket, and for some forms the region, from an S3 URL.
#
# An `s3://bucket` URL supplies only the bucket, and its path is ignored,
# so set `base_path` for a prefix within the bucket. An AWS `https://` URL
# that names a region (`https://s3.<region>.amazonaws.com/<bucket>` or
# `https://<bucket>.s3.<region>.amazonaws.com`) supplies it too, a
# Cloudflare R2 URL sets it to `auto`, and values taken from the URL
# override `bucket` and `region`.
#
# example: "s3://my-media-bucket"
#
#url =

# The name of the S3 bucket. e.g. "bucketname-123456789-us-west-2-an".
#
#bucket =

# The region of the S3 bucket. e.g. "us-west-2".
#
#region = "us-east-1"

# Your amazon IAM Key ID with access granted to this bucket.
# e.g. "ABCDEFG1X1ZZYYXXWWVV"
#
#key =

# The secret key component which is approx 40 characters of base64.
#
#secret =

# Optional path prefix within the bucket where all our operations will
# take place.
#
#base_path =

# (expert use) Sets the S3 endpoint for self-hosted or other compatible
# services.
#
# A dual-stack AWS or Cloudflare R2 `url` sets its own endpoint, which
# overrides this value.
#
#endpoint =

# (expert use) Turns virtual-hosted-style requests on or off, which some
# self-hosted services need.
#
# A virtual-hosted AWS `url` (`https://<bucket>.s3.<region>.amazonaws.com`)
# turns them on regardless of this value.
#
#use_vhost_request = false

# (expert use) Alternative session-token authentication method.
#
#token =

# (expert use) Associated SSE-KMS key material.
#
#kms =

# (expert use) When configured for the bucket it should be reflected here.
#
#use_bucket_key =

# (expert use) Threshold size for switching to Multi-part uploads. This is
# a quirk of the S3 protocol which requires us to use a different approach
# for "large" uploads. This value determines what a "large" upload is. The
# default value should be sufficient for most providers. The value is a
# parsed string allowing SI or IEC units for convenience.
#
#multipart_threshold = "100 MiB"

# (expert use) Size of each individual part within a Multi-part upload.
# Once an upload exceeds `multipart_threshold` the payload is split into
# parts of this size, each sent as a separate HTTP PUT. Smaller values
# keep individual requests under per-request timeouts on slow uplinks at
# the cost of more round-trips. S3 requires every part except the last
# to be at least 5 MiB. The value is a parsed string allowing SI or IEC
# units for convenience.
#
#multipart_part_size = "10 MiB"

# (developer use) Allows relaxing default requirement forcing HTTPS.
#
#use_https = true

# (developer_use) Allows skipping request header signatures (will be
# reejected by AWS).
#
#use_signatures = true

# (developer_use) Allows disabling request payload signatures.
#
#use_payload_signatures = true

# (developer use) Enables checks performed at startup such as pinging the
# provider. Failures are considered critical startup errors which abort
# startup. When set to false, faulty providers are only discovered with
# first use and will not be fatal errors.
#
# Only set this to false if you expect a provider to be down at startup or
# for development/testing purposes; checks are disabled when the server
# is started in '--maintenance' mode.
#
#startup_check = true


################################################################################
# External telemetry
#
# Sends diagnostics to services outside the server. Both exporters are off
# by default.
#
# - `[global.telemetry.sentry]`: crash, error and performance reports to a
#   Sentry service. Included in the default build.
# - `[global.telemetry.jaeger]`: tracing spans to an OpenTelemetry (OTLP)
#   collector such as Jaeger. Needs a build with the `perf_measurements`
#   Cargo feature.
#
#[global.telemetry]


################################################################################
# Jaeger span export (OpenTelemetry)
#
# Exports tracing spans over OTLP (gRPC) to an OpenTelemetry collector such
# as Jaeger. Off by default, and available only in a build with the
# `perf_measurements` Cargo feature; the default build and the published
# packages ignore these keys.
#
# Tips:
# - There is no key for the collector address. The exporter reads the
#   standard `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` environment variable (or
#   `OTEL_EXPORTER_OTLP_ENDPOINT`) and otherwise sends to
#   `http://localhost:4317`.
# - Spans arrive under the service name `tuwunel`.
# - In a `perf_measurements` build a malformed `filter` stops startup even
#   with `enable` off.
#
#[global.telemetry.jaeger]

# Enables OTLP span export for Jaeger-compatible tracing.
#
# A build with performance measurements installs an OpenTelemetry layer
# when enabled. The default is false, and `telemetry.jaeger.filter`
# selects exported spans.
#
#enable = false

# Selects tracing spans exported to Jaeger-compatible collectors.
#
#filter = "info"


################################################################################
# Sentry error reporting
#
# Reports panics, error-level log events and a sampled share of performance
# traces to a Sentry service. Support is in the default build, but `enable`
# is off, so nothing is sent until you turn it on. Settings are read once at
# startup; a configuration reload neither starts nor stops reporting.
#
# Set `enable = true` to report. `endpoint` takes a Sentry DSN; the default
# DSN reports to the tuwunel project's Sentry
# (`o4509498990067712.ingest.us.sentry.io`). Set your own DSN to keep
# reports in your Sentry.
#
# Tips:
# - Error events carry the log message and its fields, with recent `info`
#   and `warn` log lines attached as breadcrumbs, so reports can include
#   user IDs and room IDs.
# - Sentry fills its own `server_name` field with the machine's hostname
#   unless `send_server_name` replaces it with the Matrix server name. OS
#   and Rust version details are attached to events as well.
# - With `enable` on, a malformed `filter` stops startup.
#
#[global.telemetry.sentry]

# Enables Sentry crash and panic reporting, performance monitoring, and
# metrics, disabled at runtime by default and sent to the default endpoint
# domain `o4509498990067712.ingest.us.sentry.io` unless overridden.
#
#enable = false

# Selects a custom Sentry reporting URL.
#
#endpoint = ""

# Includes `server_name` in Sentry crash reports and metrics.
#
#send_server_name = false

# Sets the fraction of performance-monitoring traces sampled by Sentry.
#
# When Sentry is enabled, this must be between 0.0 and 1.0 inclusive.
# High values may affect performance; 0.0 disables sampling.
#
#traces_sample_rate = 0.15

# Attaches a stack trace to Sentry reports.
#
#attach_stacktrace = false

# Sends panics to Sentry when telemetry is enabled.
#
# This defaults to true, but `telemetry.sentry.enable` must also be
# enabled before any data is sent.
#
#send_panic = true

# Sends errors to Sentry when telemetry is enabled.
#
# This defaults to true but requires Sentry enablement. It applies only
# in release mode and is forced false in debug mode.
#
#send_error = true

# Selects the tracing log level for Sentry breadcrumbs and transactions.
#
#filter = "info"


################################################################################
# Direct TLS
#
# Lets the server terminate TLS itself. Most deployments leave
# `[global.tls]` unset and let a reverse proxy handle HTTPS and
# certificates, in which case every TCP listener speaks plain HTTP. Use it
# when nothing sits in front of the server, together with a public
# `http.listen.address` and the `http.listen.port` values that clients and
# other homeservers connect to.
#
# Set `certs` to a PEM file holding the full certificate chain and `key`
# to its PEM private key; setting only one of the two fails startup.
#
# Minimal example:
#
#     [global.tls]
#     certs = "/etc/tuwunel/tls/fullchain.pem"
#     key = "/etc/tuwunel/tls/privkey.pem"
#
# Tips:
# - TLS covers every TCP listener, including sockets passed by systemd.
#   One port cannot serve TLS while another serves plain HTTP;
#   `dual_protocol` makes every port accept both. The Unix socket stays
#   plain HTTP.
# - The files are read once at startup; restart after renewing the
#   certificate.
# - Builds without the `direct_tls` feature (on by default) refuse to start
#   while `certs` and `key` are set.
#
#[global.tls]

# Path to a valid TLS certificate file; this section requires a build with
# the `direct_tls` Cargo feature.
#
# example: "/path/to/my/certificate.crt"
#
#certs =

# Path to a valid TLS certificate private key.
#
# example: "/path/to/my/certificate.key"
#
#key =

# Controls whether listeners accept both HTTP and HTTPS.
#
# Plain requests are served without redirecting them to HTTPS. This
# weakens transport security and is disabled by default.
#
#dual_protocol = false


################################################################################
# Developer tracing tools
#
# Diagnostics for developers profiling the server. Neither `tokio_console`
# nor `[global.tracing.flame]` does anything in the default build or the
# published packages, so production servers can leave `[global.tracing]`
# out.
#
# Tips:
# - `tokio_console` needs a build with the `tokio_console` Cargo feature
#   and `--cfg tokio_unstable` in `RUSTFLAGS`, and a release build must
#   also drop the default `release_max_log_level` feature. See
#   <https://tuwunel.chat/development.html#debugging-with-tokio-console>.
#
#[global.tracing]

# Enables tokio-console for developer use as described in the
# [tokio-console debugging
# guide](https://tuwunel.chat/development.html#debugging-with-tokio-console).
#
#tokio_console = false


################################################################################
# Tracing span profiles (flame graphs)
#
# Profiles time spent in the server's tracing spans and writes it to a
# folded-stack file for flame-graph tools. Off by default, and it works only
# in a build with the `perf_measurements` Cargo feature, which the default
# build and the published packages leave out.
#
# Tips:
# - In such a build with `enable` on, an unwritable `output_path` or a
#   malformed `filter` stops startup.
# - Output is buffered, so the file is complete only after the server stops.
#
#[global.tracing.flame]

# Collects folded stack profiles of tracing spans through tracing-flame
# when the `perf_measurements` build feature is enabled, for visualization
# with [inferno](https://github.com/jonhoo/inferno),
# [Speedscope](https://www.speedscope.app), or other compatible tools.
#
#enable = false

# Selects tracing spans included in the folded stack profile.
#
#filter = "info"

# Selects the output path for the folded tracing-span profile.
#
#output_path = "./tracing.folded"


################################################################################
# TURN relay for calls
#
# Tells clients which TURN servers relay their legacy Matrix calls, and
# with what credentials, through `/_matrix/client/v3/voip/turnServer`.
# No TURN server is built in; the guide at
# <https://tuwunel.chat/calls/turn.html> uses coturn. With `uris` empty
# and no provider configured (the default), `turnServer` answers 404.
#
# Pick one credential source:
#
# - Shared secret (recommended for your own TURN server): `secret` or
#   `secret_file`, equal to coturn's `static-auth-secret`. Each request
#   gets a fresh username `<expiry>:<user_id>` and HMAC-SHA1 password,
#   valid for `ttl` seconds.
# - Static: `username` and `password`, sent to every client as they are;
#   ignored while a secret is set.
# - Provider: `[global.turn.cloudflare]` for Cloudflare's hosted TURN, or
#   `[global.turn.endpoint]` for any HTTP endpoint that issues expiring
#   credentials. The server URIs come from the provider too, so `uris`,
#   the secret and the static credentials are ignored.
#
# With `uris` set and no source, startup logs a warning and clients
# receive an empty username and password.
#
# Minimal example:
#
#     [global.turn]
#     uris = ["turn:turn.example.com?transport=udp"]
#     secret_file = "/etc/tuwunel/.turn_secret"
#
# Tips:
# - `secret_file` is read on every request, so rotating the secret needs
#   no reload or restart.
# - Guests get 403 from `turnServer` unless `allow_guests` is on.
#
#[global.turn]

# Allows guest users to access TURN credentials.
#
# This is equivalent to Synapse's `turn_allow_guests` setting and permits
# guests to call `/_matrix/client/v3/voip/turnServer`.
#
# reloadable: yes
#
#allow_guests = false

# Supplies a static TURN username when the recommended shared secret
# `turn.secret` is not used.
#
# reloadable: yes
#
#username = false

# Supplies a static TURN password when the recommended shared secret
# `turn.secret` is not used.
#
# reloadable: yes
#
#password = false

# Lists TURN server URIs.
#
# Replace "example.turn.uri" with the TURN domain, such as coturn's
# `realm` setting. For TURN over TLS, replace the `turn:` prefix with
# `turns:`.
#
# reloadable: yes
# example: ["turn:example.turn.uri?transport=udp",
# "turn:example.turn.uri?transport=tcp"]
#
#uris = []

# Supplies the TURN shared secret for HMAC-SHA1 credential generation,
# which is more secure than the traditional static username-and-password
# credentials that remain available when needed.
#
# reloadable: yes
#
#secret = false

# Reads the TURN shared secret from a file.
#
# This takes precedence over `turn.secret` and falls back to it when the
# file cannot be opened. Surrounding whitespace is trimmed so a trailing
# newline is not part of the secret. A present but blank file resolves to
# no secret without falling back.
#
# reloadable: yes
# example: "/etc/tuwunel/.turn_secret"
#
#secret_file =

# Sets the TURN lifetime in seconds.
#
# reloadable: yes
#
#ttl = 86400


################################################################################
# Cloudflare Realtime TURN
#
# Fetches expiring TURN credentials and server URIs from Cloudflare's
# hosted TURN service. Create a TURN key in the Cloudflare dashboard and
# set its key ID and API token here. Cloudflare credentials live at most
# 48 hours, so a longer `turn.ttl` is shortened to that. Only its TURN
# URIs reach clients, without the port 53 ones browsers block.
#
# While `key_id` is set, `turn.uris`, the shared secret and the static
# credentials are ignored. Set this section or `[global.turn.endpoint]`,
# not both.
#
#     [global.turn.cloudflare]
#     key_id = "0123456789abcdef0123456789abcdef"
#     token_file = "/etc/tuwunel/.cloudflare_turn_token"
#
# Tips:
# - One set of credentials is shared by every user and renewed after
#   half its lifetime, so Cloudflare sees about two requests per
#   credential lifetime however many clients ask. No Matrix user ID is
#   sent.
# - `token_file` is read at each renewal, so rotating the token needs no
#   reload or restart.
# - After a failed request Cloudflare is not asked again for a minute;
#   meanwhile clients get whatever credentials are still unexpired, or
#   502.
#
#[global.turn.cloudflare]

# ID of the Cloudflare TURN key; setting it selects this provider.
#
# reloadable: yes
#
#key_id = ""

# API token of the Cloudflare TURN key.
#
# reloadable: yes
#
#token =

# Reads the API token from a file.
#
# This takes precedence over `token` and falls back to it when the file
# cannot be opened. Surrounding whitespace is trimmed.
#
# reloadable: yes
# example: "/etc/tuwunel/.cloudflare_turn_token"
#
#token_file =


################################################################################
# TURN credentials from an HTTP endpoint
#
# Fetches TURN credentials and server URIs from an HTTP endpoint, for a
# TURN service that issues expiring credentials through an API rather
# than sharing a secret. Tuwunel sends `GET <url>` with `service=turn`
# and `ttl=<turn.ttl>` added to the query, and accepts either answer:
#
# - TURN REST API: `{"username", "password", "ttl", "uris"}`, as the
#   STUNner auth service returns from `/`.
# - WebRTC ICE servers: `{"iceServers": [...]}` or a bare list, each
#   entry holding `urls`, `username` and `credential`, as STUNner's
#   `/ice` returns. Clients take one username and password, so entries
#   whose credentials differ from the first entry's are dropped.
#
# Only `turn:` and `turns:` URIs reach clients, as the Matrix spec
# requires; any `stun:` URIs in the answer are left out.
#
# A service with another request or answer shape needs a small adapter
# in front of it. While `url` is set, `turn.uris`, the shared secret and
# the static credentials are ignored.
#
#     [global.turn.endpoint]
#     url = "http://127.0.0.1:8088/"
#     token_file = "/etc/tuwunel/.turn_endpoint_token"
#
# Tips:
# - Query parameters already in `url`, other than `service` and `ttl`,
#   are kept, for a service that takes its API key in the query.
# - One set of credentials is shared by every user and renewed after
#   half its lifetime, so the endpoint sees about two requests per
#   credential lifetime however many clients ask. No Matrix user ID is
#   sent.
# - After a failed request the endpoint is not asked again for a minute;
#   meanwhile clients get whatever credentials are still unexpired, or
#   502.
#
#[global.turn.endpoint]

# URL of the credential endpoint.
#
# reloadable: yes
# example: "http://127.0.0.1:8088/"
#
#url =

# Supplies a bearer token sent in the `Authorization` header.
#
# reloadable: yes
#
#token =

# Reads the bearer token from a file.
#
# This takes precedence over `token` and falls back to it when the file
# cannot be opened. Surrounding whitespace is trimmed.
#
# reloadable: yes
# example: "/etc/tuwunel/.turn_endpoint_token"
#
#token_file =


################################################################################
# Typing notifications
#
# Controls whether typing notifications are exchanged with other servers
# and how long a typing indicator lasts when no stop request arrives.
# Federation is on in both directions by default.
#
# Tips:
# - `client_timeout_min_s` must not exceed `client_timeout_max_s`. Startup
#   and reload refuse an inverted pair.
#
#[global.typing]

# Allows sending typing updates over federation.
#
# reloadable: yes
#
#allow_outgoing = true

# Allows receiving typing updates over federation.
#
# reloadable: yes
#
#allow_incoming = true

# Limits how long a federated user can indicate typing.
#
# reloadable: yes
#
#federation_timeout_s = 30

# Sets the minimum time a local client can indicate typing.
#
# A request to stop typing still takes effect. The minimum applies only
# when no stop request arrives.
#
# reloadable: yes
#
#client_timeout_min_s = 15

# Limits how long a local client can indicate typing.
#
# reloadable: yes
#
#client_timeout_max_s = 45


################################################################################
# Matrix discovery (well-known) responses
#
# Sets what the server answers at `/.well-known/matrix/client`,
# `/.well-known/matrix/server` and `/.well-known/matrix/support`. Clients
# and other servers fetch these files over HTTPS from the `server_name`
# host, so the settings take effect only when requests for that host reach
# the server, directly or through a reverse proxy. An endpoint with nothing
# configured answers 404.
#
# Support contacts and policies have their own tables,
# `[global.well_known.support_contact.<ID>]` and
# `[global.well_known.support_policy.<ID>]`; with `support_page` they make
# up `/.well-known/matrix/support`. `livekit_url` publishes the MatrixRTC
# (Element Call) backend in the client response.
#
# Example for `example.com` served from `matrix.example.com`:
#
#     [global.well_known]
#     client = "https://matrix.example.com"
#     server = "matrix.example.com:443"
#
# Tips:
# - Other features need `client`: startup fails when `smtp.connection_uri`
#   is set without it, and the built-in OIDC server (any
#   `[global.identity_provider]` entry or `authentication.oidc.native_auth`)
#   stays off with a warning.
#
#[global.well_known]

# The server URL that the client well-known file will serve.
#
# This should not contain a port, and should just be a valid HTTPS URL.
# While this is unset, `/.well-known/matrix/client` answers 404 and
# auto-discovery from the server name yields nothing, so the base URL has
# to reach clients some other way. Leave it unset only when a reverse
# proxy or another host publishes that file for this domain.
#
# example: "https://matrix.example.com"
#
#client =

# The server base domain of the URL with a specific port that the server
# well-known file will serve. This should contain a port at the end, and
# should not be a URL.
#
# reloadable: yes
# example: "matrix.example.com:443"
#
#server =

# Publishes a support web page URL at `/.well-known/matrix/support`.
#
# It is served beside the support contacts and policies, and any one of
# the three makes the endpoint answer instead of returning 404.
#
# reloadable: yes
# example: "https://example.com/support"
#
#support_page =

# LiveKit JWT endpoint.
# Required for Element Call / MatrixRTC (MSC4143).
#
# Note: You must also set `client` above to your homeserver URL.
#
# reloadable: yes
#
#livekit_url = ""

# Custom MatrixRTC transports.
#
# If you're looking to setup Element Call / MatrixRTC with Livekit,
# you should not use this option and instead set `livekit_url`.
# This is only required if you want to configure a non-livekit MatrixRTC
# transport. There are no known client implementations that support any
# other transport types.
#
# This option was previously the only way to configure a Livekit
# transport. It has been superseded by `livekit_url`.
#
# Example:
# [global.well_known]
# client = "https://matrix.yourdomain.com"
#
# [[global.well_known.rtc_transports]]
# type = "livekit"
# livekit_service_url = "https://livekit.yourdomain.com"
#
# reloadable: yes
#
#rtc_transports = []


################################################################################
# Support contact
#
# Publishes one contact in the `contacts` list of
# `/.well-known/matrix/support`, where users and other server admins look
# for someone to reach. With no contact, `support_page` or support policy
# configured, the endpoint answers 404.
#
# - `<ID>`: your label for this contact. It is not published; contacts
#   are listed in `<ID>` order, and startup errors name the entry by it.
#   Bare keys may use `A-Z a-z 0-9 _ -`; anything else must be quoted
#   (`[global.well_known.support_contact."ops.team"]`), and an unquoted
#   dot splits the name into nested tables.
#
# `role` is required, normally `m.role.admin` or `m.role.security`;
# `m.role.moderator` and `m.role.dpo` are accepted but published under
# their unstable MSC4121 and MSC4265 names. Startup fails unless at least
# one of `email_address` or `matrix_id` is set.
#
# Example:
#
#     [global.well_known.support_contact.admin]
#     role = "m.role.admin"
#     email_address = "admin@example.com"
#     matrix_id = "@admin:example.com"
#
#[global.well_known.support_contact.<ID>]

# The name of the support role.
#
# example: "m.role.admin"
#
#role =

# The email address for the above support role.
#
# example: "admin@example.com"
#
#email_address =

# The Matrix User ID for the above support role.
#
# example: "@admin:example.com"
#
#matrix_id =

# The PGP key (i.e. OpenPGP) that one may use for encrypted communications
# for the above support role. The value must be a URI. Use a web URL
# pointing to the key (for example "https://example.com/key.asc"), an
# OPENPGPKEY DNS record ("dns:..."), or a fingerprint carried with the
# "openpgp4fpr:" scheme. A bare fingerprint without a scheme, or raw
# inlined key material, is rejected at startup.
#
# As this is a spec proposal (MSC4439), the identifier/prefix for this
# field is currently "dev.zirco.msc4439.pgp_key"
#
# example: "openpgp4fpr:8B77919975EAFA5E2456EE03665FE73077489DB0"
#
#pgp_key =


################################################################################
# Support policy document
#
# Publishes one policy document, such as a privacy policy or terms of
# service, in `/.well-known/matrix/support` (the
# `org.matrix.msc4266.policies` field of MSC4266). These are informational;
# to make new users accept documents at sign-up, use
# `[global.registration_terms.<ID>]`.
#
# - `<ID>`: the policy id published to clients, such as `privacy_policy`.
#   The id is not validated (the spec allows `0-9 a-z A-Z . _ ~ -`). Bare
#   keys may use `A-Z a-z 0-9 _ -`; anything else must be quoted
#   (`[global.well_known.support_policy."privacy.v2"]`), and an unquoted
#   dot splits the name into nested tables.
#
# `version` and a
# `[global.well_known.support_policy.<ID>.policy_translation.<LANG>]`
# table are required; a policy table without them fails to load. Give
# it at least one language.
#
# Minimal example:
#
#     [global.well_known.support_policy.privacy_policy]
#     version = "1.0"
#
#     [global.well_known.support_policy.privacy_policy.policy_translation.en]
#     name = "Privacy Policy"
#     url = "https://example.com/privacy"
#
# Tips:
# - The translation table is `policy_translation` here but `translations`
#   under `[global.registration_terms.<ID>]`.
#
#[global.well_known.support_policy.<ID>]

# Version string of the policy document.
#
# example: "v6.7"
# reloadable: yes
#
#version =


################################################################################
# Support policy translation
#
# One language version of a `[global.well_known.support_policy.<ID>]`
# document: the title and link clients show for that language. Add one
# table per language; `name` and `url` are both required.
#
# - `<ID>`: the `<ID>` of the policy table this translation belongs to,
#   spelled (and quoted) the same way.
# - `<LANG>`: the language code, such as `en`, `fr` or `en-US` (RFC 5646;
#   some clients use `en_US`). It is published as the key for this
#   translation next to the policy's `version`, so it must not be
#   `version`; it is not validated otherwise. Bare keys may use
#   `A-Z a-z 0-9 _ -`; anything else must be quoted, and an unquoted dot
#   splits the name into nested tables.
#
# Example:
#
#     [global.well_known.support_policy.privacy_policy.policy_translation.de]
#     name = "Datenschutzrichtlinie"
#     url = "https://example.com/privacy-de"
#
#[global.well_known.support_policy.<ID>.policy_translation.<LANG>]

# User friendly name of the policy document.
#
# example: "Privacy Policy"
# reloadable: yes
#
#name =

# Link to the test of the policy document. A valid URL must be specified.
#
# example: "https://website.local/privacy-policy"
# reloadable: yes
#
#url =

Debian systemd unit file

Debian systemd unit file
[Unit]
Description=Tuwunel Matrix homeserver
Wants=network-online.target
After=network-online.target
Documentation=https://tuwunel.chat/

[Service]
User=tuwunel
Group=tuwunel
Type=notify
WatchdogSec=30

Environment="TUWUNEL_CONFIG=/etc/tuwunel/tuwunel.toml"
Environment="MALLOC_CONF=background_thread:false"

ExecStart=/usr/sbin/tuwunel

# Type=notify-reload would report completion, but it needs systemd 253 and
# Debian 12 ships 252, where an unparsable Type= silently falls back to simple.
ExecReload=/bin/kill -s USR1 $MAINPID

ReadWritePaths=/var/lib/tuwunel /etc/tuwunel

AmbientCapabilities=
CapabilityBoundingSet=

ManagedOOMPreference=avoid

DevicePolicy=closed
LockPersonality=yes
MemoryDenyWriteExecute=yes
NoNewPrivileges=yes
#ProcSubset=pid
ProtectClock=yes
ProtectControlGroups=yes
ProtectHome=yes
ProtectHostname=yes
ProtectKernelLogs=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
ProtectProc=invisible
ProtectSystem=strict
PrivateDevices=yes
PrivateMounts=yes
PrivateTmp=yes
PrivateUsers=yes
PrivateIPC=yes
RemoveIPC=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service @resources
SystemCallFilter=~@clock @debug @module @mount @reboot @swap @cpu-emulation @obsolete @timer @chown @setuid @privileged @keyring @ipc
# Restore the pipe syscalls subtracted with @ipc above: a configured
# media_video_thumbnail_command is spawned with pipes.
SystemCallFilter=pipe pipe2
# A denied call returns this errno instead of killing the process, so a filter
# trip is indistinguishable from an ordinary permission error and is not logged.
SystemCallErrorNumber=EPERM
#StateDirectory=tuwunel

RuntimeDirectory=tuwunel
RuntimeDirectoryMode=0750

Restart=on-failure
RestartSec=5

TimeoutStopSec=2m
TimeoutStartSec=5m

StartLimitInterval=1m
StartLimitBurst=5

[Install]
WantedBy=multi-user.target
Alias=matrix-tuwunel.service

Systemd socket unit file

Systemd socket unit file
[Unit]
Description=Tuwunel Matrix homeserver socket
Documentation=https://tuwunel.chat/

[Socket]
# Systemd binds this and hands it to Tuwunel at startup, so the server reaches
# a privileged port while holding no capability of its own. Sockets listed here
# are served in addition to the address, port and unix socket in the
# configuration file, and take precedence where the two overlap.
ListenStream=8448
#ListenStream=443
#ListenStream=[::1]:8008

BindIPv6Only=both
Backlog=1024
NoDelay=true

[Install]
WantedBy=sockets.target

Arch Linux systemd unit file

Arch Linux systemd unit file
[Unit]
Description=Tuwunel Matrix homeserver
Wants=network-online.target
After=network-online.target
Documentation=https://tuwunel.chat/
RequiresMountsFor=/var/lib/private/tuwunel

[Service]
DynamicUser=yes
Type=notify-reload
ReloadSignal=SIGUSR1
# Refreshes any credentials the operator adds before the reload signal is sent.
# Absent from the Debian and Red Hat units, whose systemd predates it.
RefreshOnReload=yes
WatchdogSec=30

TTYPath=/dev/tty25
DeviceAllow=char-tty
StandardInput=tty-force
StandardOutput=tty
StandardError=journal+console
TTYReset=yes
# uncomment to allow buffer to be cleared every restart
TTYVTDisallocate=no

TTYColumns=120
TTYRows=40

ReadWritePaths=/etc/tuwunel

AmbientCapabilities=
CapabilityBoundingSet=

ManagedOOMPreference=avoid

DevicePolicy=closed
LockPersonality=yes
MemoryDenyWriteExecute=yes
NoNewPrivileges=yes
#ProcSubset=pid
ProtectClock=yes
ProtectControlGroups=yes
ProtectHome=yes
ProtectHostname=yes
ProtectKernelLogs=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
ProtectProc=invisible
ProtectSystem=strict
PrivateDevices=yes
PrivateMounts=yes
PrivateTmp=yes
PrivateUsers=yes
PrivateIPC=yes
RemoveIPC=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service @resources
SystemCallFilter=~@clock @debug @module @mount @reboot @swap @cpu-emulation @obsolete @timer @chown @setuid @privileged @keyring @ipc
# Restore the pipe syscalls subtracted with @ipc above: a configured
# media_video_thumbnail_command is spawned with pipes.
SystemCallFilter=pipe pipe2
# A denied call returns this errno instead of killing the process, so a filter
# trip is indistinguishable from an ordinary permission error and is not logged.
SystemCallErrorNumber=EPERM
StateDirectory=tuwunel

RuntimeDirectory=tuwunel
RuntimeDirectoryMode=0750

Environment="TUWUNEL_CONFIG=/etc/tuwunel/tuwunel.toml"
BindPaths=/var/lib/private/tuwunel:/var/lib/conduwuit
BindPaths=/var/lib/private/tuwunel:/var/lib/private/conduwuit
BindPaths=/var/lib/private/tuwunel:/var/lib/matrix-conduit
BindPaths=/var/lib/private/tuwunel:/var/lib/private/matrix-conduit

ExecStart=/usr/bin/tuwunel
Restart=on-failure
RestartSec=5

TimeoutStopSec=4m
TimeoutStartSec=5m

StartLimitInterval=1m
StartLimitBurst=5

[Install]
WantedBy=multi-user.target
Alias=matrix-tuwunel.service

Red Hat systemd unit file

Red Hat systemd unit file
[Unit]
Description=Tuwunel Matrix homeserver
Wants=network-online.target
After=network-online.target
Documentation=https://tuwunel.chat/

[Service]
User=tuwunel
Group=tuwunel
Type=notify
WatchdogSec=30

Environment="TUWUNEL_CONFIG=/etc/tuwunel/tuwunel.toml"

ExecStart=/usr/sbin/tuwunel

# Type=notify-reload would report completion, but it needs systemd 253 and
# Enterprise Linux 9 ships 252, where an unparsable Type= falls back to simple.
ExecReload=/bin/kill -s USR1 $MAINPID

ReadWritePaths=/var/lib/tuwunel /etc/tuwunel

AmbientCapabilities=
CapabilityBoundingSet=

ManagedOOMPreference=avoid

DevicePolicy=closed
LockPersonality=yes
MemoryDenyWriteExecute=yes
NoNewPrivileges=yes
#ProcSubset=pid
ProtectClock=yes
ProtectControlGroups=yes
ProtectHome=yes
ProtectHostname=yes
ProtectKernelLogs=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
ProtectProc=invisible
ProtectSystem=strict
PrivateDevices=yes
PrivateMounts=yes
PrivateTmp=yes
PrivateUsers=yes
PrivateIPC=yes
RemoveIPC=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service @resources
SystemCallFilter=~@clock @debug @module @mount @reboot @swap @cpu-emulation @obsolete @timer @chown @setuid @privileged @keyring @ipc
# Restore the pipe syscalls subtracted with @ipc above: a configured
# media_video_thumbnail_command is spawned with pipes.
SystemCallFilter=pipe pipe2
# A denied call returns this errno instead of killing the process, so a filter
# trip is indistinguishable from an ordinary permission error and is not logged.
SystemCallErrorNumber=EPERM

RuntimeDirectory=tuwunel
RuntimeDirectoryMode=0750

Restart=on-failure
RestartSec=5

TimeoutStopSec=2m
TimeoutStartSec=5m

StartLimitInterval=1m
StartLimitBurst=5

[Install]
WantedBy=multi-user.target
Alias=matrix-tuwunel.service

Configuration regeneration

Tuwunel can rebuild an existing configuration with the schema and documentation compiled into the current binary. Explicitly configured values remain active, aliases are rewritten to their canonical paths, and sections follow the current example configuration: global first, then each parent followed by its children, with siblings in alphabetical order. Unset fields remain commented so that future default changes still apply. Dynamic sections such as identity providers, appservices, and storage providers are rendered from their current instances.

Regeneration only writes a configuration document. The standalone command exits before normal server startup and does not open the database. The admin command does not reload the generated file. Loading an existing configuration never rewrites it; regeneration is optional, and supported flat names continue to work throughout 2.x.

Commands

GoalCommandDefault destination
Generate a pristine exampletuwunel --generate-configStandard output.
Regenerate selected configuration filestuwunel --regenerate-config<input>.new beside a single input file.
Regenerate from a running server!admin server regenerate-config <path>The required absolute path on the server.

An optional CLI destination must be attached to the command with =:

tuwunel --generate-config=/etc/tuwunel/tuwunel-example.toml
tuwunel -c /etc/tuwunel/tuwunel.toml \
  --regenerate-config=/etc/tuwunel/tuwunel.toml.new

Regeneration requires at least one existing input file. Select files with -c or --config, or through one of the supported configuration path environment variables. Inputs use the same source order as normal startup. Multiple input files are collapsed into one document and therefore require an explicit destination.

Controls

ControlBehavior
--forceReplace an existing destination after preserving it as <destination>.bak.
--include-envMaterialize configuration values supplied through the environment.
--strip-unknownComment out deprecated and unknown values instead of leaving them active.

The admin command accepts the same controls after its destination path. The environment and unknown-key controls apply only to regeneration, not pristine example generation.

Without --include-env, file-backed values are retained and environment-backed values are identified by comments naming the actual environment variables used, including legacy spellings. This avoids making a temporary environment override persistent. Command-line overrides such as -O are never copied into the generated file.

Using --include-env can copy secrets and temporary overrides from the process environment into the file. Those values remain configured if the environment variables are later removed. Their annotations still name the actual source variables, including legacy spellings or a variable that supplied an entire table.

Deprecated and unknown keys remain active by default, with an explanatory comment. This preserves the behavior and startup warnings of the input. Valid but undocumented keys also remain active. The startup-only database_restore_backup and force_migration controls are never emitted and are named in the command summary when removed.

Output safety

Important

The generated document contains configuration secrets. Store and review it with the same protections as the active configuration.

Tuwunel applies the following safeguards:

  • A new destination is created with mode 0600 on Unix.
  • An existing destination is never replaced unless --force is supplied.
  • Forced replacement preserves the destination’s mode and ownership, and saves its previous contents to an adjacent .bak file. Replacement is refused if that backup already exists. Preserving the ownership of a destination owned by another account needs privilege the service rarely holds; see Destinations under systemd.
  • On macOS, forced replacement also carries the destination’s ACLs and extended attributes onto the replacement, and onto its backup on a best-effort basis.
  • Nonregular destinations, including symbolic links, are refused.
  • Forced replacement is supported on Linux and macOS. Other platforms can write a new destination and replace it manually after review.
  • Writes use a temporary file in the destination directory and are installed atomically.
  • The output is parsed and compared with the selected input values before and after installation.

The admin command returns only the destination and a summary. It does not send the configuration or its secrets to the admin room.

Destinations under systemd

The packaged units confine the server to a small set of writable paths, so ReadWritePaths= decides where the admin command can write, not the file mode alone. The Debian, Red Hat, and Arch units each grant /etc/tuwunel. A destination outside every granted path is refused before anything is written, however permissive its mode.

Regenerating to a new file never depends on ownership, but the granted directory must also be writable by the service account. Forced replacement additionally carries the existing file’s ownership onto its replacement, which succeeds without privilege only when that file already belongs to that account.

Under DynamicUser=yes the account is reallocated on every boot, so it owns neither the configuration directory nor the file in it. Regeneration there needs a destination the service can write, such as the directory named by StateDirectory=, and forced replacement of the active configuration is not available. Review and adopt the result covers installing the generated file afterwards.

The units also answer a blocked system call with EPERM, which reaches the log as an ordinary permission error. When a regeneration failure reports a permission problem on a path that looks writable, compare it against the unit’s ReadWritePaths= and SystemCallFilter= settings before changing anything on disk:

systemctl show tuwunel -p ReadWritePaths -p SystemCallFilter -p User

Limitations

  • Handwritten comments are not carried into the generated document. The default .new output leaves the original available, while forced replacement retains it as .bak.
  • Lexical formatting can change even when the TOML values are equivalent.
  • Headerless input is normalized into [global]. Named profiles other than default and global are refused.
  • Multiple input files lose their layer boundaries in the combined output.
  • Regeneration uses the schema of the binary that runs the command. Canonical output from a 2.x binary is intended for 2.x; it is not promised to load on 1.x. Retain the original configuration or its backup if you need to roll back to 1.x.
  • The generated file is not reloaded or adopted automatically.

Review and adopt the result

The safest workflow leaves the active file untouched:

tuwunel -c /etc/tuwunel/tuwunel.toml --regenerate-config
diff -u /etc/tuwunel/tuwunel.toml /etc/tuwunel/tuwunel.toml.new

Keep the original file available while reviewing any operational notes it contains.

On Linux and macOS, an explicit forced replacement can install the reviewed form while retaining the previous file:

tuwunel -c /etc/tuwunel/tuwunel.toml \
  --regenerate-config=/etc/tuwunel/tuwunel.toml --force

This creates /etc/tuwunel/tuwunel.toml.bak. Remove or archive an existing backup before repeating a forced replacement. Restart Tuwunel or use configuration reload only after reviewing the generated file.

For a running server, write to a new absolute path the service can reach, per Destinations under systemd:

!admin server regenerate-config /etc/tuwunel/tuwunel.toml.new

Review that server-local file before replacing or reloading the active configuration.

Generic deployment documentation

Tip

Getting help: If you run into any problems while setting up Tuwunel open an issue on GitHub.

Installing Tuwunel

Static prebuilt binary

You may simply download the binary that fits your machine architecture (x86_64 or aarch64). Run uname -m to see what you need.

Prebuilt fully static binaries can be downloaded from the latest tagged release here or main CI branch workflow artifact output. These also include .deb packages for Debian or Ubuntu and .rpm packages for Red Hat or Fedora.

Debian and Ubuntu users can instead install and update Tuwunel through the apt repository; see the Debian guide for setup.

The static binaries do not bundle CA certificates. Federation and every other outbound HTTPS request uses the system trust store, so the host needs a CA bundle installed (ca-certificates on Debian and Ubuntu). When running the binary in a minimal image or a chroot, mount the bundle in or set SSL_CERT_FILE to its path.

For the best performance; if using an x86_64 CPU made in the last ~10 years, we recommend using the -v3- optimised packages. See below for a command to check what your system supports. If the server refuses to start or exits with an “Illegal Instruction” error you will need -v2- or -v1- packages instead. The database backend, RocksDB, benefits from -v2- or greater as it features performance critical hardware accelerated CRC32 hashing/checksumming.

Linux users can run this script to display which optimization levels they may choose:

cat /proc/cpuinfo | grep -Po '(avx|sse)[235]' | sort -u | sed 's/avx5/v4/;s/avx2/v3/;s/sse3/v2/;s/sse2/v1/' | sort

Compiling

Alternatively, you may compile the binary yourself. We recommend using Nix to build tuwunel as this has the most guaranteed reproducibiltiy and easiest to get a build environment and output going. This also allows easy cross-compilation.

You can run the nix build -L .#static-x86_64-linux-musl or nix build -L .#static-aarch64-linux-musl commands based on architecture to cross-compile the necessary static binary located at result/bin/tuwunel. This is reproducible with the static binaries produced in our CI.

If wanting to build using standard Rust toolchains, make sure you install:

  • liburing-dev on the compiling machine, and liburing on the target host
  • LLVM and libclang for RocksDB

You can build Tuwunel using cargo build --release. See Build Features for the features a plain build includes and how to change them.

A plain build targets the baseline architecture, which is the -v1- equivalent and gets RocksDB’s software CRC32C. Pass -C target-cpu= to get the hardware implementation the -v2- and -v3- packages use: native when the binary stays on the machine that built it, or a named architecture such as broadwell when it does not.

RUSTFLAGS="-C target-cpu=native" cargo build --release

Add --locked to build against the committed Cargo.lock. Without it Cargo re-resolves the whole dependency graph, which is not the combination that gets tested.

Adding a Tuwunel user

While Tuwunel can run as any user it is better to use dedicated users for different services. This also allows you to make sure that the file permissions are correctly set up.

In Debian, you can use this command to create a Tuwunel user:

sudo adduser --system tuwunel --group --disabled-login --no-create-home

For distros without adduser (or where it’s a symlink to useradd):

sudo useradd -r --shell /usr/bin/nologin --no-create-home tuwunel

Forwarding ports in the firewall or the router

Matrix’s default federation port is port 8448, and clients must be using port 443. If you would like to use only port 443, or a different port, you will need to setup delegation. Tuwunel has config options for doing delegation, or you can configure your reverse proxy to manually serve the necessary JSON files to do delegation (see the [global.well_known] config section and the delegation example).

If Tuwunel runs behind a router or in a container and has a different public IP address than the host system these public ports need to be forwarded directly or indirectly to the port mentioned in the config.

Note for NAT users; if you have trouble connecting to your server from the inside of your network, you need to research your router and see if it supports “NAT hairpinning” or “NAT loopback”.

If your router does not support this feature, you need to research doing local DNS overrides and force your Matrix DNS records to use your local IP internally. This can be done at the host level using /etc/hosts. If you need this to be on the network level, consider something like NextDNS or Pi-Hole.

Setting up a systemd service

Two example systemd units for Tuwunel can be found on the configuration page. You may need to change the ExecStart= path to where you placed the Tuwunel binary if it is not /usr/bin/tuwunel.

On systems where rsyslog is used alongside journald (i.e. Red Hat-based distros and OpenSUSE), put $EscapeControlCharactersOnReceive off inside /etc/rsyslog.conf to allow color in logs.

When running as a systemd service, Tuwunel submits its logs directly to journald with each entry’s severity preserved as the journal priority, so journalctl --priority warning catches Tuwunel’s warnings and errors. Each entry carries the same formatted message as the console output, span fields included, and thread ids when log_thread_ids is enabled. The target and source location are attached as journal fields, and every tracing field is recorded under an F_ prefix, so a single room or event can be pulled out of the journal directly:

journalctl -u tuwunel F_ROOM_ID='!room:example.com'

Set log_journald = false in the config to write plain console output instead. A unit that sends its output to a terminal rather than the journal, as the Arch unit does for the interactive admin console, needs that setting to keep showing log lines there.

The packages also ship a tuwunel.socket unit, disabled by default, for letting systemd open the listening socket instead. That is what allows the server to answer on a privileged port such as 443 or 8448 while holding no capability of its own. See systemd socket activation.

The first boot after an upgrade can run a one-time database migration, and the listener does not open until it finishes. While one is running the unit stays in activating and its status line names the step, how far into it the server is, and how long it has been going, so systemctl status tuwunel answers whether anything is happening:

     Active: activating (start) since Thu 2026-08-27 14:10:47 UTC; 12min ago
     Status: "retroactively_fix_bad_data_from_roomuserid_joined, 412 of 3100, 6.20 minutes"

The same line goes to the journal every fifteen seconds. A step reports a position without a total when it cannot count its remaining work without a second pass over the data; a position that keeps climbing is the signal that the migration is progressing. Do not kill the server to interrupt one. A stop request is honored between steps and the steps that finished are recorded, so the migration resumes on the next start.

If you are using a different database_path other than the systemd unit configured default /var/lib/tuwunel, you need to add your path to the systemd unit’s ReadWritePaths=. This can be done by either directly editing tuwunel.service and reloading systemd, or running systemctl edit tuwunel.service and entering the following:

[Service]
ReadWritePaths=/path/to/custom/database/path

Creating the Tuwunel configuration file

Now we need to create the Tuwunel’s config file in /etc/tuwunel/tuwunel.toml. The example config can be found at tuwunel-example.toml.

Please take a moment to read the config. You need to change at least the server name.

RocksDB is the only supported database backend.

Setting the correct file permissions

If you are using a dedicated user for Tuwunel, you will need to allow it to read the config. To do that you can run this:

sudo chown -R root:root /etc/tuwunel
sudo chmod -R 755 /etc/tuwunel

If you use the default database path you also need to run this:

sudo mkdir -p /var/lib/tuwunel/
sudo chown -R tuwunel:tuwunel /var/lib/tuwunel/
sudo chmod 700 /var/lib/tuwunel/

Setting up the Reverse Proxy

We recommend Caddy as a reverse proxy, as it is trivial to use, handling TLS certificates, reverse proxy headers, etc. transparently with proper defaults. However, Nginx is also well-supported and widely used.

Choose your reverse proxy:

Quick Overview

Regardless of which reverse proxy you choose, you will need to:

  1. Reverse proxy the following routes:

    • /_matrix/ - core Matrix C-S and S-S APIs
    • /_tuwunel/ - ad-hoc Tuwunel routes such as /local_user_count and /server_version
  2. Optionally reverse proxy (recommended):

    • /_synapse/admin/ if you use administration dashboards such as synapse-admin or moderation bots; see the Synapse Admin API page for the served endpoints. Most require an administrator access token. The exception is the /_synapse/admin/v1/register pair, which authenticates by HMAC over registration_shared_secret instead of a token and is served only while that secret is configured, so anyone holding it can create accounts. Restrict this path to trusted networks
    • /_synapse/mas/ if the Matrix Authentication Service reaches Tuwunel through the reverse proxy rather than directly; these endpoints reject every request not bearing the configured mas_secret
    • /.well-known/matrix/client and /.well-known/matrix/server if using Tuwunel to perform delegation (see the [global.well_known] config section and the delegation example)
    • /.well-known/matrix/support if using Tuwunel to send the homeserver admin contact and support page (formerly known as MSC1929)
    • / if you would like to see hewwo from tuwunel woof! at the root
  3. Handle ports:

    • Port 443 (HTTPS) for client-server API
    • Port 8448 for federation (if federating with other homeservers)

Client IP source

Set ip_source when you want Tuwunel to use a spoofing-resistant client IP source for rate limiting, logging, and security tooling. Leave it unset to keep the legacy fallback behavior.

Use ip_source = "connect_info" only when Tuwunel accepts direct TCP connections and should use the TCP peer address. Do not use connect_info for Unix-socket deployments, which have no TCP peer address.

If Tuwunel is behind a trusted reverse proxy, set ip_source to match the header that proxy controls, including when the proxy connects over the Unix socket. Without it, password attempts from a local proxy or the Unix socket get no per-address limit. Caddy, Nginx, and Traefik usually use ip_source = "rightmost_x_forwarded_for". Cloudflare and cloudflared deployments can use ip_source = "cf_connecting_ip" when Cloudflare supplies that header.

Only use header-based values when clients cannot connect to Tuwunel directly. If clients can reach Tuwunel without going through the trusted proxy, they can send forged forwarding headers and choose the IP address Tuwunel sees.

See the following spec pages for more details on well-known files:

Examples of delegation:

Other Reverse Proxies

Specific contributions for other proxies are welcome!

Not Recommended:

  • Apache: While possible, Apache requires special configuration (nocanon in ProxyPass) to prevent corruption of the X-Matrix header.
  • Lighttpd: Its proxy module alters the X-Matrix authorization header, breaking federation functionality.

You are done

Now you can start Tuwunel with:

sudo systemctl start tuwunel

Set it to start automatically when your system boots with:

sudo systemctl enable tuwunel

How do I know it works?

You can open a Matrix client, enter your homeserver and try to register.

You can also use these commands as a quick health check (replace your.server.name).

curl https://your.server.name/_tuwunel/server_version

# If using port 8448
curl https://your.server.name:8448/_tuwunel/server_version

# If federation is enabled
curl https://your.server.name:8448/_matrix/federation/v1/version
  • To check if your server can talk with other homeservers, you can use the Matrix Federation Tester. If you can register but cannot join federated rooms check your config again and also check if the port 8448 is open and forwarded correctly.

What’s next?

Audio/Video calls

For Audio/Video call functionality see the TURN Guide.

Appservices

If you want to set up an appservice, take a look at the Appservice Guide.

Systemd socket activation

Systemd can open listening sockets itself and hand them to Tuwunel at startup. The packages ship a tuwunel.socket unit for this, disabled by default.

Two things make it worth using:

  • Privileged ports without privileges. The shipped service units run with an empty CapabilityBoundingSet=, so Tuwunel cannot bind a port below 1024 on its own. Systemd binds it as PID 1 and passes the open socket down, which is how the server reaches 443 or 8448 while holding no capability itself.
  • The socket outlives the server. systemctl restart tuwunel leaves the listening socket bound, so clients connecting during the restart wait in the accept queue instead of getting a refused connection.

Socket activation needs Linux and a build carrying the systemd feature, which is enabled by default.

Enabling it

The Debian package installs the unit to /usr/lib/systemd/system/tuwunel.socket and the Red Hat packages under the systemd unit directory. None of them enable it, so nothing changes until you do. It listens on port 8448, the federation port, which does not collide with the default configuration:

systemctl enable --now tuwunel.socket
systemctl restart tuwunel.service

The startup log lists every listener, with passed sockets marked:

INFO Listening on ["tcp:127.0.0.1:8008", "tcp:[::1]:8008", "passed:tcp:[::]:8448"]

To listen somewhere else, override the unit rather than editing it. An empty ListenStream= is required first, since systemd appends to list settings instead of replacing them:

systemctl edit tuwunel.socket
[Socket]
ListenStream=
ListenStream=443

How passed sockets combine with the configuration

Passed sockets are served in addition to everything in the configuration file. The address, port and unix_socket_path settings keep working exactly as before, and Tuwunel binds those itself.

Where the two overlap, the passed socket wins and the configured address is skipped, with a line saying so:

INFO Not binding: a listener already answers for it. addr=127.0.0.1:8448

A wildcard address covers every address of its family, and a dual-stack [::] socket covers IPv4 as well, so ListenStream=8448 takes over the configured entries on that port however they are written. A passed unix socket matching unix_socket_path is skipped the same way, which also keeps the socket systemd holds from being unlinked and replaced.

An address you configured that is genuinely unavailable, held by some other process, fails startup rather than disappearing quietly:

There was a problem with the 'address' directive in your configuration:
Failed to bind 127.0.0.1:8448: Address in use (os error 98)

Leaving address unset takes the built-in default instead, which is only a guess that both loopback families exist on the host. An address from that guess is logged at error level and skipped rather than being fatal, so a host without IPv6 still serves on 127.0.0.1; startup fails only once no listener is left.

The common shape for a public deployment is a configuration bound to localhost for a reverse proxy, plus a socket unit for the port that has to be privileged. To serve only passed sockets, point the configuration at a unix socket and leave address unset, which is the one case where Tuwunel binds no TCP address of its own.

Direct TLS

Passed TCP sockets carry TLS exactly like bound TCP listeners. This requires a build with the direct_tls Cargo feature. Setting tls.certs and tls.key applies to every TCP listener Tuwunel serves, so a socket unit listening on 443 serves HTTPS with no further configuration:

[global.tls]
certs = "/etc/tuwunel/tls/fullchain.pem"
key = "/etc/tuwunel/tls/privkey.pem"

tls.dual_protocol works on passed sockets too, serving HTTP and HTTPS on the same passed port.

TLS is a server-wide property for TCP listeners, not a property of an individual socket. Passed and bound TCP listeners cannot use different certificates or mix TLS with plaintext. Unix sockets remain plaintext and can still be used behind a local reverse proxy.

Unix sockets

A socket unit can pass a unix socket instead of a port:

[Socket]
ListenStream=/run/tuwunel/tuwunel.sock
SocketUser=tuwunel
SocketGroup=www-data
SocketMode=0660
RuntimeDirectory=tuwunel
RuntimeDirectoryPreserve=yes

RuntimeDirectory= is needed in the socket unit because the service unit’s own RuntimeDirectory=tuwunel is created when the service starts, which is after the socket unit has already tried to bind inside it. RuntimeDirectoryPreserve= keeps the directory when the socket stops.

Pointing unix_socket_path at the same path is harmless, since the passed socket takes precedence and the configured one is skipped. A different path binds a second unix socket of its own, which is a fine way to serve both.

Restarts

systemctl restart tuwunel.service and systemctl stop tuwunel.service leave the socket unit running and the socket bound. The listener survives, and the server picks the same socket back up when it starts.

The admin command !admin server restart is different. It replaces the running process image in place, and the descriptors systemd passed are closed by that exec, so the restarted server comes back listening only on the addresses in its configuration file. The passed sockets return on the next systemctl restart tuwunel.service, which is the restart to prefer on a socket-activated deployment.

Reloading configuration

Tuwunel re-reads its configuration on SIGUSR1 without restarting or dropping connections. The packaged service units wire systemctl reload to that signal:

systemctl reload tuwunel

If you run the binary directly, send the same signal by hand:

kill -USR1 "$(pidof tuwunel)"

For a container deployment, send the signal from the host with docker kill. The release images have no shell, kill or pidof to run inside them. Their entrypoint is tuwunel, so it receives the signal directly:

docker kill --signal=USR1 <container>

A reload rebuilds the configuration from the same sources the server started with: the files named by TUWUNEL_CONFIG and by --config, the TUWUNEL_-prefixed environment variables merged over them, and finally the -O overrides from the command line. The result is swapped in atomically.

Since the command line is replayed rather than remembered, an option pinned with -O stays pinned across a reload, and editing that key in the file has no effect until the server is restarted without the override.

Configuration that fails to parse or fails validation is rejected and the running configuration is kept, with the reason logged:

ERROR Failed to reload config: ...

Set config_reload_signal = false to make the server ignore SIGUSR1.

How each package delivers the reload

The Arch unit uses Type=notify-reload, so systemctl reload waits for the server to finish reloading before returning. That needs systemd 253.

The Debian and Red Hat units use ExecReload= instead, which works on every systemd version but returns as soon as the signal is delivered. Debian 12 and Enterprise Linux 9 both ship systemd 252, where an unrecognised Type= value is ignored and the service silently falls back to Type=simple, so those two units cannot use the newer mechanism.

Either way the reload reports success to systemd whether or not the new configuration was accepted, because the server carries on serving the old one and is therefore still healthy. The outcome travels in the unit’s status line instead of the exit code:

$ systemctl status tuwunel
     Status: "Configuration rejected: There was a problem with your configuration file: ..."

A successful reload replaces it with Configuration reloaded, and the same reason is logged either way. The line describes the last reload attempt only; a freshly started server reads Running.

What a reload applies

Options documented reloadable: yes in tuwunel-example.toml take effect immediately. Three are rejected outright, failing the whole reload:

  • server_name
  • ip_source
  • any [global.storage_provider.<ID>] section, whether added, removed or changed

Two more are refused outright rather than merely ignored, because the server would refuse to start with them set in a file: maintenance and database_restore_backup. Either one fails the whole reload, not just its own key.

Anything else is accepted, but only takes effect where the server reads it. Listening sockets are the case worth knowing: address, port, unix_socket_path and the [global.tls] settings are consumed once during startup, so changing them needs a restart. None of them are marked reloadable.

Secrets kept in their own files

Several secrets can live in a file of their own rather than inline in the configuration:

OptionContents
registration_token_fileregistration tokens, separated by whitespace
registration_shared_secret_fileshared secret for /_synapse/admin/v1/register
turn_secret_fileTURN HMAC secret
ldap.bind_password_fileLDAP bind password
identity_provider.<id>.client_secret_fileOIDC client secret

Each of these is read at the point it is used, so replacing the contents of the file takes effect on the next request that needs it. No reload and no restart is required. A reload is only needed to change which path an option names.

Systemd credentials

Secrets can be handed to the service by systemd rather than left readable on disk. Add a drop-in with systemctl edit tuwunel.service and point one of the _file options above at the credentials directory, which the %d specifier expands to:

[Service]
LoadCredential=turn_secret:/etc/tuwunel/turn_secret
Environment=TUWUNEL_TURN_SECRET_FILE=%d/turn_secret

Systemd copies the credential into a private tmpfs readable only by the service, so the source file can stay owned by root and unreadable by the tuwunel user. LoadCredentialEncrypted= and ImportCredential= work the same way, as does setting the path in the configuration file directly instead of through the environment.

Credentials are re-materialised each time the service starts, so systemctl restart tuwunel always picks up a changed source file. Having systemctl reload refresh them as well takes RefreshOnReload=, which systemd applies before signalling the server, so the configuration and the secret files are both current by the time the reload runs.

The Arch unit sets it already. It needs systemd 260, which rules it out of the Debian and Red Hat units, since Debian 12 and 13 ship 252 and 257 and Enterprise Linux 9 and 10 ship 252 and 257. On a host new enough to have it, add it in the same drop-in:

[Service]
RefreshOnReload=yes

Older versions log Unknown key name 'RefreshOnReload' and carry on, leaving restart as the way to pick up a rotated credential.

Prefer yes over the narrower RefreshOnReload=credentials. The latter warns on every load when the unit has no credentials configured, and masks the credentials tree in that case.

Reverse Proxy Setup - Caddy

<= Back to Generic Deployment Guide

We recommend Caddy as a reverse proxy, as it is trivial to use, handling TLS certificates, reverse proxy headers, etc. transparently with proper defaults.

Installation

Install Caddy via your preferred method. Refer to the official Caddy installation guide for your distribution.

Configuration

After installing Caddy, create /etc/caddy/conf.d/tuwunel_caddyfile and enter this (substitute your.server.name with your actual server name):

your.server.name, your.server.name:8448 {
    # TCP reverse_proxy
    reverse_proxy localhost:8008
    # UNIX socket (alternative - comment out the line above and uncomment this)
    #reverse_proxy unix//run/tuwunel/tuwunel.sock
}

What this does

  • Handles both port 443 (HTTPS) and port 8448 (Matrix federation) automatically
  • Automatically provisions and renews TLS certificates via Let’s Encrypt
  • Sets all necessary reverse proxy headers correctly
  • Routes all traffic to Tuwunel listening on localhost:8008

Client IP source

By default, Tuwunel treats Caddy as the connecting peer, so registration logs, rate limiting, and security tooling all attribute requests to Caddy’s address rather than the real client. If Caddy is the only way clients can reach Tuwunel, set ip_source = "rightmost_x_forwarded_for" in tuwunel.toml (or TUWUNEL_IP_SOURCE=rightmost_x_forwarded_for in Docker). This makes Tuwunel trust the X-Forwarded-For header that Caddy’s reverse_proxy directive already sets. The same value applies to the Unix-socket reverse_proxy target; without it, password attempts through the socket get no per-address limit.

The setting only takes effect at startup, so restart Tuwunel after changing it.

That’s it! Just start and enable the service and you’re set.

sudo systemctl enable --now caddy

Verification

After starting Caddy, verify it’s working by checking:

curl https://your.server.name/_tuwunel/server_version
curl https://your.server.name:8448/_tuwunel/server_version

Caddy and .well-known

Caddy can serve .well-known/matrix/client and .well-known/matrix/server instead of tuwunel. This is useful when delegating a root domain such as example.com to a subdomain like matrix.example.com, where Caddy on the root domain has no Tuwunel upstream of its own.

In this configuration Caddy bypasses Tuwunel’s CORS layer, so the CORS headers recommended by the Matrix specification must be added explicitly.

Note

Caddyfile uses backticks as an alternative string quote so the inline JSON body (which contains double quotes) does not need escaping. Field names and values inside a header block are space-separated; do not place a colon after the field name.

example.com {
	@matrix path /.well-known/matrix/*
	header @matrix {
		Access-Control-Allow-Origin "*"
		Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
		Access-Control-Allow-Headers "X-Requested-With, Content-Type, Authorization"
		Content-Type "application/json"
	}
	respond /.well-known/matrix/client `{"m.homeserver":{"base_url":"https://matrix.example.com"}}`
	respond /.well-known/matrix/server `{"m.server":"matrix.example.com:443"}`
}

To advertise a MatrixRTC focus (MSC4143) for Element Call, extend the client response with an org.matrix.msc4143.rtc_foci array pointing at your LiveKit JWT service:

respond /.well-known/matrix/client `{"m.homeserver":{"base_url":"https://matrix.example.com"},"org.matrix.msc4143.rtc_foci":[{"type":"livekit","livekit_service_url":"https://rtc.example.com"}]}`

=> Continue with “You’re Done”

Reverse Proxy Setup - Nginx

<= Back to Generic Deployment Guide

This guide shows you how to configure Nginx as a reverse proxy for Tuwunel with TLS support.

Installation

Install Nginx via your preferred method. Most distributions include Nginx in their package repositories:

# Debian/Ubuntu
sudo apt install nginx

# Red Hat/Fedora
sudo dnf install nginx

# Arch Linux
sudo pacman -S nginx

Configuration

Create a new configuration file at /etc/nginx/sites-available/tuwunel (or /etc/nginx/conf.d/tuwunel.conf on some distributions):

upstream tuwunel {
  server 127.0.0.1:8008; # IP and port where tuwunel is listening
}

server {
  # Client-Server API over HTTPS (port 443)
  listen 443 ssl;
  listen [::]:443 ssl;
  # Matrix Federation over HTTPS (port 8448)
  # Only needed if you want to federate with other homeservers
  # Don't forget to open port 8448 in your firewall!
  listen 8448 ssl;
  listen [::]:8448 ssl;
  http2 on;
  server_name matrix.example.com;

  # Nginx standard body size is 1MB, which is quite small for media uploads
  # Increase this to match the max_request_size in your tuwunel.toml
  client_max_body_size 100M;

  # Forward requests to Tuwunel
  location / {
    proxy_pass http://tuwunel;

    # Client address for `ip_source`; replaces any value the client sent
    proxy_set_header X-Forwarded-For $remote_addr;
    # Passes the public hostname. Tuwunel does not currently need this.
    proxy_set_header Host $host;
  }

  # TLS configuration (Let's Encrypt example using certbot)
  ssl_certificate /etc/letsencrypt/live/matrix.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/matrix.example.com/privkey.pem;
}

Important Notes

  • Replace matrix.example.com with your actual server name
  • client_max_body_size: Must match or exceed max_request_size in your tuwunel.toml
  • Do NOT use $request_uri in proxy_pass - while some guides suggest this, it’s not necessary for Tuwunel and can cause issues
  • IPv6: The listen [::]:443 and listen [::]:8448 lines enable IPv6 support. Remove them if you don’t need IPv6

If Nginx is the only way clients can reach Tuwunel, set ip_source = "rightmost_x_forwarded_for" under [global.http] in your tuwunel.toml. This tells Tuwunel to use the trusted X-Forwarded-For value as the client’s IP address.

Important

Restart Tuwunel after changing ip_source. A configuration reload that changes this setting is rejected.

The client setting under [global.well_known] in your tuwunel.toml holds your public HTTPS URL. Tuwunel uses this well_known.client setting to build public URLs for clients. The Host header and the request scheme do not supply those URLs.

TLS Certificates

The example above uses Let’s Encrypt certificates via certbot. To obtain certificates:

sudo certbot certonly --nginx -d matrix.example.com

Certbot will automatically handle renewal. Make sure to reload Nginx after certificate renewal:

sudo systemctl reload nginx

Optional: Timeout Configuration

The default Nginx timeouts are usually sufficient for Matrix operations. Element’s long-polling /sync requests typically run for 30 seconds, which is within Nginx’s default timeouts.

However, if you experience federation retries or dropped long-poll connections, you can extend the timeouts by adding these lines inside your location / blocks:

location / {
  proxy_pass http://tuwunel;
  proxy_set_header X-Forwarded-For $remote_addr;
  proxy_set_header Host $host;

  # Optional: Extend timeouts if experiencing issues
  proxy_read_timeout 300s;
  proxy_send_timeout 300s;
}

Enable the Configuration

If using sites-available/sites-enabled structure:

sudo ln -s /etc/nginx/sites-available/tuwunel /etc/nginx/sites-enabled/

Test the configuration:

sudo nginx -t

If the test passes, reload Nginx:

sudo systemctl reload nginx

Enable Nginx to start on boot:

sudo systemctl enable nginx

Verification

After configuring Nginx, verify it’s working by checking:

curl https://matrix.example.com/_tuwunel/server_version
curl https://matrix.example.com:8448/_tuwunel/server_version

Troubleshooting

Apache Compatibility Note

If you’re considering Apache instead of Nginx: Apache is not well-suited as a reverse proxy for Matrix homeservers. If you must use Apache, you need to use nocanon in your ProxyPass directive to prevent httpd from corrupting the X-Matrix authorization header, which will break federation.

Lighttpd is Not Supported

Lighttpd has known issues with the X-Matrix authorization header, making federation non-functional. We do not recommend using Lighttpd with Tuwunel.


=> Continue with “You’re Done”

Reverse Proxy Setup - Traefik

<= Back to Generic Deployment Guide

Installation

Install Traefik via your preferred method. You can read the official docker quickstart guide or the in-depth walkthrough

Configuration

TLS certificates

You can setup auto renewing certificates with different kinds of acme challenges.

Router configurations

Add tuwunel to your traefik’s network.

services:
    tuwunel:
    # ...
    networks:
        - proxy # your traefik network name
networks:
    proxy: # your traefik network name
        external: true

Be sure to change the your.server.name to your actual tuwunel domain. and the yourcertresolver should be changed to whatever you named it in your traefik config.

You only have to do any one of these methods below.

Labels

To use labels with traefik you need to configure a docker provider.

Then add the labels in your tuwunel’s docker compose file.

services:
    tuwunel:
        # ...
        labels:
            - "traefik.enable=true"
            - "traefik.http.routers.tuwunel.entrypoints=web"
            - "traefik.http.routers.tuwunel.rule=Host(`your.server.name`)"
            - "traefik.http.routers.tuwunel.middlewares=https-redirect@file"
            - "traefik.http.routers.tuwunel-secure.entrypoints=websecure"
            - "traefik.http.routers.tuwunel-secure.rule=Host(`your.server.name`)"
            - "traefik.http.routers.tuwunel-secure.tls=true"
            - "traefik.http.routers.tuwunel-secure.service=tuwunel"
            - "traefik.http.services.tuwunel.loadbalancer.server.port=6167"
            - "traefik.http.routers.tuwunel-secure.tls.certresolver=yourcertresolver"
            - "traefik.docker.network=proxy"

Config File

To use the config file you need to configure a file provider.

Then add this into your config file.

http:
    routers:
        tuwunel:
            entryPoints:
                - "web"
                - "websecure"
            rule: "Host(`your.server.name`)"
            middlewares:
                - https-redirect
            tls:
                certResolver: "yourcertresolver"
            service: tuwunel
    services:
        tuwunel:
            loadBalancer:
                servers:
            # this url should point to your tuwunel installation.
            # this should work if your tuwunel container is named tuwunel and is in the same network as traefik.
                    - url: "http://tuwunel:6167"
                passHostHeader: true

Client IP source

If Traefik is the only way clients can reach Tuwunel, set ip_source = "rightmost_x_forwarded_for" in tuwunel.toml so Tuwunel uses the trusted X-Forwarded-For value.

Federation

If you will use a .well-known file you can use traefik to redirect .well-known/matrix to tuwunel built-in .well-known file.

replace the rule in either of the methods from

Host(`your.server.name`)

to

Host(`your.tuwunel.domain`) || Host(`your.server.name`) && PathPrefix(`/.well-known/matrix`)

If you are not using a .well-known file you will need to add and expose port 8448 to a traefik entrypoint.

You can then add these to your preferred traefik config method. you should replace matrixfederationentry with what you named your entrypoint.

Labels:

            - "traefik.http.routers.matrix-federation.entrypoints=matrixfederationentry"
            - "traefik.http.routers.matrix-federation.rule=Host(`your.server.name`)"
            - "traefik.http.routers.matrix-federation.tls=true"
            - "traefik.http.routers.matrix-federation.service=matrix-federation"
            - "traefik.http.services.matrix-federation.loadbalancer.server.port=6167"
            - "traefik.http.routers.matrix-federation.tls.certresolver=yourcertresolver"

Config file:

        entryPoints:
            - "web"
            - "websecure"
            - "matrixfederationentry"

Important

Encoded Character Filtering options must be set to true. This only applies to traefik version 3.6.4 to 3.6.6 and 2.11.32 to 2.11.34

Verification

After starting Traefik, verify it’s working by checking:

curl https://your.server.name/_tuwunel/server_version
curl https://your.server.name:8448/_tuwunel/server_version

=> Continue with “You’re Done”

Example: using the root domain as the homeserver name

<= Back to Generic Deployment Guide

It is possible to host tuwunel on a subdomain such as matrix.example.com but delegate from example.com as the server name. This means that usernames will be @user:example.com rather than @user:matrix.example.com.

Federating servers and clients accessing tuwunel at example.com will attempt to discover the subdomain by accessing the example.com/.well-known/matrix/client and example.com/.well-known/matrix/server endpoints. These need to be set up to point back to matrix.example.com.

Note

In all of the following examples, replace matrix.example.com with the subdomain where tuwunel is hosted, <PORT> with the external port for federation, and example.com with the domain you want to use as the public-facing homeserver.

Configuration

Make sure the following are set in your configuration file or via environment variables:

  1. Server name: set TUWUNEL_SERVER_NAME=example.com or in the configuration file:
    [global]
    
    # The server_name is the pretty name of this server. It is used as a
    # suffix for user and room IDs/aliases.
    #
    # See the docs for reverse proxying and delegation:
    # https://tuwunel.chat/deploying/generic.html#setting-up-the-reverse-proxy
    #
    # Also see the `[global.well_known]` config section at the very bottom.
    #
    # Examples of delegation:
    # - https://matrix.org/.well-known/matrix/server
    # - https://matrix.org/.well-known/matrix/client
    #
    # YOU NEED TO EDIT THIS. THIS CANNOT BE CHANGED AFTER WITHOUT A DATABASE
    # WIPE.
    #
    # example: "girlboss.ceo"
    #
    server_name = example.com
    
  2. Client-server URL: set TUWUNEL_WELL_KNOWN__CLIENT=https://matrix.example.com or in the configuration file:
    [global.well_known]
    
    # The server URL that the client well-known file will serve. This should
    # not contain a port, and should just be a valid HTTPS URL.
    #
    # example: "https://matrix.example.com"
    #
    client = https://matrix.example.com
    
  3. Server-server federation domain and port: where <PORT> is the external port for federation (default 8448, but often 443 when reverse proxying), set TUWUNEL_WELL_KNOWN__SERVER=matrix.example.com:<PORT> or in the configuration file:
    [global.well_known]
    
    # The server URL that the client well-known file will serve. This should
    # not contain a port, and should just be a valid HTTPS URL.
    #
    # example: "https://matrix.example.com"
    #
    client = https://matrix.example.com
    
    # The server base domain of the URL with a specific port that the server
    # well-known file will serve. This should contain a port at the end, and
    # should not be a URL.
    #
    # example: "matrix.example.com:443"
    #
    server = matrix.example.com:<PORT> # e.g. matrix.example.com:443
    

Serving .well-known endpoints

With the above configuration, tuwunel will generate and serve the appropriate /.well-known/matrix entries for delegation, so these can be served by reverse proxying /.well-known/matrix on example.com to tuwunel. Alternatively, if example.com is not behind a reverse proxy, static JSON files can be served directly.

Option 1: Static JSON files

At a minimum, the following JSON files should be created:

  1. At example.com/.well-known/matrix/client:
    {
        "m.homeserver": {
            "base_url": "https://matrix.example.com/"
        }
    }
    
  2. At example.com/.well-known/matrix/server (substituting <PORT> as above):
    {
        "m.server": "matrix.example.com:<PORT>" // e.g. "matrix.example.com:443"
    }
    

Option 2: Reverse proxy

These are example configurations if example.com is reverse-proxied behind Nginx, Caddy or Traefik.

Note

Replace tuwunel with the URL where tuwunel is listening; this may look like 127.0.0.1:8008, matrix.example.com, or tuwunel if you declared an upstream tuwunel block.

Important

These configurations need to be applied to the reverse proxy for example.com, not matrix.example.com.

Caddy

example.com {
	reverse_proxy /.well-known/matrix/* https://matrix.example.com {
		header_up Host {upstream_hostport}
	}
}

Nginx

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name example.com;

  set $backend "tuwunel";

  location /.well-known/matrix/ {
    proxy_pass http://$backend:6167$request_uri;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_ssl_server_name on;
  }
  
  # The remainder of your nginx configuration for example.com including SSL termination, other locations, etc.
}

Traefik

Change Tuwunel’s router rule to:

Host(`matrix.example.com`) || Host(`example.com`) && PathPrefix(`/.well-known/matrix`)
Labels example
- "traefik.http.routers.tuwunel.rule=Host(`matrix.example.com`) || Host(`example.com`) && PathPrefix(`/.well-known/matrix`)"
- "traefik.http.routers.tuwunel-secure.rule=Host(`matrix.example.com`) || Host(`example.com`) && PathPrefix(`/.well-known/matrix`)"
File example
rule: "Host(`matrix.example.com`) || Host(`example.com`) && PathPrefix(`/.well-known/matrix`)"

Testing

Navigate to example.com/.well-known/matrix/client and example.com/.well-known/matrix/server. These should display results similar to the JSON snippets above.

Entering example.com in the Matrix federation tester should also work.

Additional resources

For a more complete guide, see the Matrix setup with Ansible and Docker documentation on setting up .well-known.

Tuwunel for Alpine Linux

Tuwunel runs on Alpine, and this page covers compiling it there yourself. Building natively on Alpine means the compiler itself runs against musl, which runs into a few things a normal build does not. The recipe below is tested on x86_64 and aarch64, but Alpine is not one of our release build platforms, so treat it as a working recipe rather than a supported configuration.

You may not need to build at all

Alpine packages tuwunel as tuwunel, for x86_64 and aarch64. It lives in edge/testing and is in no stable branch, so apk add tuwunel finds it only on edge with the testing repository enabled. It is packaged by the Alpine community rather than published by this project, so check the version it offers against our releases.

Our own release binaries are fully static and run on Alpine unmodified, and the published container images are built around that same binary. Either of those saves you a long compile. Running one of them in an Alpine container brings its runtime’s defaults into play, which security profiles and limits covers: the task limit that can stop startup, and the seccomp profile that decides whether the database gets io_uring.

If you want to build from source but not natively, the Nix route in Compiling produces a static binary and is reproducible against CI.

Prerequisites

apk add git rust cargo build-base clang-dev linux-headers liburing-dev

What the less obvious ones are for:

  • clang-dev provides libclang, which bindgen uses to generate RocksDB’s Rust bindings. There are no pregenerated bindings, so this is always needed.

  • liburing-dev is needed because io_uring is enabled by default.

  • linux-headers is the one that is easy to miss. /usr/include/liburing.h includes a kernel header, and Alpine’s liburing-dev does not depend on linux-headers, so installing it alone leaves you with a header that cannot be compiled. The build fails inside RocksDB with:

    /usr/include/liburing.h:15:10: fatal error: linux/swab.h: No such file or directory
    

Building

git clone https://github.com/matrix-construct/tuwunel
cd tuwunel
RUSTFLAGS="-C target-feature=-crt-static -C target-cpu=native" cargo build --release

The binary lands in target/release/tuwunel. Set RUSTFLAGS before you start, because changing it later invalidates everything compiled so far and restarts the build.

Configuration is no different from any other platform; see Configuration.

Why -C target-feature=-crt-static

Without it the build fails, so this one is not optional.

On a musl host, Rust links binaries statically by default, and that includes the small helper programs Cargo builds and runs during compilation. Musl’s static C library cannot load shared libraries at runtime, and one of those helpers needs to load libclang to generate RocksDB’s bindings. You get:

Unable to find libclang: "the `libclang` shared library at
/usr/lib/llvm20/lib/libclang.so.20.1.8 could not be opened:
Dynamic loading not supported"

Turning off crt-static makes those helpers dynamically linked, which lets them load libclang normally. There is no way to relax the setting for them alone, because in a native build they and the server are built the same way.

Why -C target-cpu=native

This one is optional and does not fix any failure, but it is worth setting.

On x86_64 the default target has no SSE4.2, so RocksDB compiles in its software checksum implementation and warns about it:

warning: compiling without SSE4.2: CRC will be slow

The warning overstates the cost, which is around one percent of RocksDB’s CPU time, but the flag is free. On aarch64 there is no such warning, and the flag instead enables newer processor features the baseline leaves out.

Use native when the binary stays on the machine that built it. If you plan to move it to other hardware, name a specific architecture instead, such as broadwell on x86_64.

Moving the binary to another machine

The binary this recipe produces is not self-contained, which only matters if you copy it somewhere else, such as into a slim container image. It needs liburing, libstdc++ and libgcc installed. The packages above already bring those in, so the machine that compiled it can run it, but a bare Alpine has none of them and startup fails naming symbols rather than the package:

Error loading shared library liburing.so.2: No such file or directory (needed by ./tuwunel)
Error relocating ./tuwunel: io_uring_submit: symbol not found

Installing them on the target resolves it:

apk add liburing libstdc++ libgcc

If you would rather have a portable binary, use a release artifact or the Nix route above.

Memory behavior on musl

Tuwunel’s own allocations go through jemalloc. RocksDB’s go to musl’s allocator instead, so a musl build splits its heap between the two. This is normal for a musl build rather than a problem with yours; our glibc release binaries use jemalloc throughout.

Both of those follow from how jemalloc is built here. On musl it is compiled with a symbol prefix, so it provides _rjem_malloc, _rjem_free and the rest rather than taking over the plain malloc that RocksDB and the other C libraries call. Tuwunel’s own code calls the prefixed names directly, which is why its allocations still land in jemalloc.

The prefix covers jemalloc’s configuration variable too, so a musl build reads _RJEM_MALLOC_CONF where a glibc build reads MALLOC_CONF. The tuning tuwunel ships with still applies; use the prefixed name to change it, for example to return freed memory to the system sooner:

_RJEM_MALLOC_CONF=muzzy_decay_ms:0 tuwunel

Note

jemalloc ignores the unprefixed name in silence, with no warning that it went unread. If a setting appears to have no effect, check which name the binary actually read.

The same variable prints what a binary is actually running with:

_RJEM_MALLOC_CONF=stats_print:true tuwunel -V

Tuwunel for Arch Linux

Currently Tuwunel is only on the Arch User Repository (AUR).

The Tuwunel AUR packages are community maintained and are not maintained by Tuwunel development team, but the AUR package maintainers are in the Matrix room. Please attempt to verify your AUR package’s PKGBUILD file looks fine before asking for support.

Tuwunel for Debian

Information about downloading and deploying the Debian package. This may also be referenced for other apt-based distros such as Ubuntu.

Installation

It is recommended to see the generic deployment guide for further information if needed as usage of the Debian package is generally related.

An apt repository serves the stable releases for amd64 and arm64. The package is statically linked, so it works on any current Debian or Ubuntu release:

sudo curl -fsSL -o /usr/share/keyrings/tuwunel-archive-keyring.gpg https://apt.f.dog/tuwunel-archive-keyring.gpg
sudo tee /etc/apt/sources.list.d/tuwunel.sources >/dev/null <<EOF
Types: deb
URIs: https://apt.f.dog
Suites: stable
Components: main
Signed-By: /usr/share/keyrings/tuwunel-archive-keyring.gpg
EOF
sudo apt update
sudo apt install tuwunel

Previous releases remain available from the repository and can be selected with, e.g. apt install tuwunel=1.7.1-1.

Migrating from another homeserver

Homeservers of the Conduit lineage (including forks) cannot run alongside Tuwunel and must be uninstalled first. Remove the old package with apt remove, never apt purge, since purging may delete its database:

sudo apt remove conduwuit

Installing the Tuwunel package adopts an existing database automatically by moving it to /var/lib/tuwunel; nothing is copied or deleted, and the data is migrated on the next startup. Databases are discovered at /var/lib/conduwuit and /var/lib/matrix-conduit, and also under /var/lib/private, where systemd keeps the state of services that ran with DynamicUser=. The location a database was adopted from is left behind as a symlink into /var/lib/tuwunel, so a configuration ported from the old server still reaches it, and purging the old package afterwards removes at most that symlink. Nothing else is linked: a fresh installation creates no such symlink, and one left by an earlier version of this package is removed on upgrade unless the configuration sets database_path, since a previous server’s name pointing at the database is one rm -r away from deleting it.

Adoption is skipped while an old homeserver unit is still active, and a database kept on its own mounted filesystem is never moved; in those cases stop the old unit, or mount the filesystem at /var/lib/tuwunel, and run dpkg-reconfigure tuwunel. If a filesystem is already mounted at /var/lib/tuwunel, move the old database’s contents into it instead. Databases from conduwuit and Conduit are supported; for other forks of the lineage, compatibility varies with how far the fork has diverged. If a fork keeps its database somewhere else, stop its service and move that directory to /var/lib/tuwunel before installing.

Port the settings from your old configuration (especially server_name) into /etc/tuwunel/tuwunel.toml before starting the service. Uninstalling Tuwunel never deletes /var/lib/tuwunel, even on purge.

Configuration

When installed, the example config is placed at /etc/tuwunel/tuwunel.toml as the default config. The config mentions things required to be changed before starting.

You can tweak more detailed settings by uncommenting and setting the config options in /etc/tuwunel/tuwunel.toml.

Running

The package uses the tuwunel.service systemd unit file to start and stop Tuwunel. The binary is installed at /usr/sbin/tuwunel.

A tuwunel.socket unit is installed alongside it, disabled, for deployments that want systemd to open the listening socket. It is what lets the server answer on a privileged port such as 443 or 8448 while holding no capability of its own. See systemd socket activation before enabling it, since a passed socket is served in addition to the address in the configuration file rather than replacing it.

This package assumes by default that Tuwunel will be placed behind a reverse proxy. The default config options apply (listening on localhost and TCP port 6167). Matrix federation requires a valid domain name and TLS, so you will need to set up TLS certificates and renewal for it to work properly if you intend to federate.

Consult various online documentation and guides on setting up a reverse proxy and TLS. Caddy is documented at the generic deployment guide as it’s the easiest and most user friendly.

AppArmor

The package installs an AppArmor profile at /etc/apparmor.d/usr.sbin.tuwunel and loads it where AppArmor is enabled, which is the default on Debian and Ubuntu. It takes effect the next time the service starts. A host without the apparmor parser runs the server unconfined instead of failing to start.

The profile grants no capabilities, because the packaged unit already clears the capability bounding set, and it confines writes to the same paths the unit lists in ReadWritePaths, plus the runtime directory: /var/lib/tuwunel, /etc/tuwunel, and /run/tuwunel. Writing to /etc/tuwunel is what config regeneration needs. Reads are wider than writes so a configured TLS certificate or trust store keeps working, and the server is allowed to re-exec itself so that !admin server restart still works.

The profile pins the AppArmor 3.0 policy abi so it parses on Debian 12 and Ubuntu 22.04 as well, whose AppArmor userspace predates 4.0.

Because the profile grants no capabilities, a manual command that has to read the tuwunel-owned configuration runs as that user rather than as root, which needs no capability to override file permissions:

sudo -u tuwunel tuwunel -c /etc/tuwunel/tuwunel.toml --regenerate-config

Deployments that move the database or read TLS material from an unusual location add those paths to /etc/apparmor.d/local/usr.sbin.tuwunel, which the profile includes if present. A configured media_video_thumbnail_command needs an execute rule rather than a path rule there, such as /usr/bin/ffmpeg ix,, since the profile grants no execute permission of its own; its staging directory under the database path is already covered:

echo '/srv/matrix/** rwkl,' >> /etc/apparmor.d/local/usr.sbin.tuwunel
apparmor_parser -r -T -W /etc/apparmor.d/usr.sbin.tuwunel
systemctl restart tuwunel.service

Denials are logged to the audit log. Inspect them with journalctl -k | grep apparmor or aa-status, and report them to the issue tracker. As a temporary measure the profile can be put in complain mode with aa-complain /usr/sbin/tuwunel, which logs what it would have denied and blocks nothing; aa-enforce /usr/sbin/tuwunel restores it.

Confinement inside a container is a separate matter, covered by container security profiles and limits.

Tuwunel for FreeBSD

Tuwunel builds and runs on FreeBSD, but FreeBSD is not a supported platform. Nothing in the CI matrix builds it and no release artifact is published for it. For installation through the FreeBSD ports tree, see Port. The rest of this page records a build from source that was verified end to end, and the handful of things that differ from the platforms we do ship.

Verified against 1.8.3 on FreeBSD 15.1-RELEASE, aarch64 and amd64. The resulting server opens its database, answers the client and federation version endpoints, registers an account, creates a room, sends and reads back a message, reopens a populated database across a restart, and exits cleanly on SIGTERM.

Port

The FreeBSD ports tree provides net-im/tuwunel for aarch64 and amd64.

The port is maintained in the FreeBSD ports tree, not by this project, so the version it carries can trail the latest release. Its page lists the current one.

Install the package:

pkg install tuwunel

Or build the port:

cd /usr/ports/net-im/tuwunel && make install clean

Toolchain

pkg install rust cmake git llvm21 pkgconf gmake curl

rust supplies cargo and rustc; FreeBSD 15.1 carries 1.96.1, which is at or above the rust-version the workspace declares. llvm21 is needed for libclang.so, which rust-librocksdb-sys runs bindgen against; the base system clang does not ship it. Point the build at it with LIBCLANG_PATH.

This is the set that was verified rather than a minimal one. curl is only used by the checks further down this page.

Features

The default feature set includes io_uring and systemd, both of which are Linux only. Every FreeBSD build therefore has to opt out of the defaults and name its features explicitly.

The list below is the default set with io_uring and systemd removed.

Note

The features added to the default set in 2.0 have not yet been tested on FreeBSD.

brotli_compression
bzip2_compression
console
cpu_affinity
direct_tls
element_hacks
email
gcs_storage
gzip_compression
jemalloc
jemalloc_conf
jwt_login
ldap
lz4_compression
markdown
mas
media_thumbnail
oidc
release_max_log_level
s3_storage
sentry_telemetry
synapse_admin
url_preview
zstd_compression

RocksDB on arm64

Nothing extra is needed here now, but a build against an older rust-rocksdb pin fails on aarch64 like this:

rocksdb/util/crc32c_arm64.cc:60:16: error: use of undeclared identifier 'AT_HWCAP'
   60 |   elf_aux_info(AT_HWCAP, &auxv, sizeof(auxv));

crc32c_arm64.cc carried include blocks for __APPLE__ and __OpenBSD__ but none for __FreeBSD__, while its FreeBSD branch calls elf_aux_info(AT_HWCAP, ...). elf_aux_info is declared in <sys/auxv.h> and AT_HWCAP in <sys/elf_common.h>, and neither header was reached on this platform.

The include block landed in rust-rocksdb c6e73b5, so every revision from there on carries it, the one the workspace pins included. Building an older revision needs the headers supplied by hand instead, and <sys/elf_common.h> is not self contained, so <sys/types.h> has to precede it:

export CXXFLAGS="-include sys/types.h -include sys/elf_common.h -include sys/auxv.h"

This affects aarch64 only. crc32c_arm64.cc is not compiled on amd64, so an amd64 build never needed it.

The runtime check then works as intended and RocksDB selects the hardware CRC32C and PMULL paths when the CPU reports them.

RocksDB on amd64

Nothing fails to build here, but the default amd64 build is slower than it needs to be. RocksDB picks its CRC32C implementation when it is compiled, and on x86 there is no runtime fallback:

// NOTE: runtime detection no longer supported on x86

cargo build targets the x86-64 baseline, which carries fxsr, sse and sse2 and nothing else. __SSE4_2__ is therefore never defined, and the table driven software routine is what ends up in the binary, on hardware that has the instruction. Every write-ahead log record is checksummed with it, and so is every record read back during recovery. Table blocks are checksummed with XXH3 instead and are unaffected. librocksdb-sys says so during the build, though cargo hides build warnings from dependencies by default:

compiling without SSE4.2: CRC will be slow (set RUSTFLAGS="-Ctarget-cpu=..."
to optimize RocksDB e.g. -Ctarget-cpu=broadwell)

Raising the target CPU is all it takes:

RUSTFLAGS="-Ctarget-cpu=westmere" cargo build --release -p tuwunel \
    --no-default-features --features ...

sse4.2 alone buys the single stream hardware CRC32. The three way version RocksDB prefers also wants pclmulqdq, and westmere is the oldest -Ctarget-cpu supplying both; anything newer serves. Comparing the two builds confirms it: the baseline one carries RocksDB’s software lookup tables and no crc32c_3way, and the westmere one carries crc32c_3way and no tables. Neither build time nor binary size moved meaningfully.

This is the axis the x86_64-v1 through x86_64-v4 release packages sit on. A build with no -Ctarget-cpu is the v1 one, and nothing selects a higher level for you here.

Building

export LIBCLANG_PATH=/usr/local/llvm21/lib

cargo build --release -p tuwunel --no-default-features \
    --features brotli_compression,bzip2_compression,console,cpu_affinity,direct_tls,element_hacks,email,gcs_storage,gzip_compression,jemalloc,jemalloc_conf,jwt_login,ldap,lz4_compression,markdown,mas,media_thumbnail,oidc,release_max_log_level,s3_storage,sentry_telemetry,synapse_admin,url_preview,zstd_compression

A cold build took about 17 minutes on 8 jobs on aarch64, and about 33 minutes on 4 jobs on amd64, producing a 79 MB and a 92 MB binary respectively. The result is dynamically linked, and against base system libraries only:

$ ldd target/release/tuwunel
	libc++.so.1 => /lib/libc++.so.1
	libcxxrt.so.1 => /lib/libcxxrt.so.1
	libthr.so.3 => /lib/libthr.so.3
	libgcc_s.so.1 => /lib/libgcc_s.so.1
	libc.so.7 => /lib/libc.so.7
	libm.so.5 => /lib/libm.so.5
	libsys.so.7 => /lib/libsys.so.7

Nothing from pkg is needed at run time, so the binary can be copied to a host that has no build toolchain installed.

Running

Configuration is no different from any other platform; see Configuration. A minimal file to prove the build:

[global]
server_name = "example.com"
address = "0.0.0.0"
port = 8008
database_path = "/var/db/tuwunel"
tuwunel -c /usr/local/etc/tuwunel/tuwunel.toml

Running under rc.d

Create an account for the service, install the binary, and give it a database directory:

pw groupadd tuwunel
pw useradd tuwunel -g tuwunel -d /nonexistent -s /usr/sbin/nologin
install -m 755 target/release/tuwunel /usr/local/bin/tuwunel
mkdir -p /usr/local/etc/tuwunel /var/db/tuwunel
chown tuwunel:tuwunel /var/db/tuwunel

Save this as /usr/local/etc/rc.d/tuwunel and chmod 555 it:

#!/bin/sh
#
# PROVIDE: tuwunel
# REQUIRE: LOGIN NETWORKING
# KEYWORD: shutdown

. /etc/rc.subr

name="tuwunel"
rcvar="tuwunel_enable"

load_rc_config $name

: ${tuwunel_enable:="NO"}
: ${tuwunel_runas:="tuwunel"}
: ${tuwunel_rungroup:="tuwunel"}
: ${tuwunel_config:="/usr/local/etc/tuwunel/tuwunel.toml"}

pidfile="/var/run/${name}/${name}.pid"
procname="/usr/local/bin/tuwunel"
command="/usr/sbin/daemon"
command_args="-f -S -T ${name} -p ${pidfile} -u ${tuwunel_runas} ${procname} -c ${tuwunel_config}"

start_precmd="tuwunel_precmd"
tuwunel_precmd()
{
	install -d -o "${tuwunel_runas}" -g "${tuwunel_rungroup}" -m 755 "/var/run/${name}"
}

run_rc_command "$1"
sysrc tuwunel_enable=YES
service tuwunel start

Two details in that script are worth keeping if you rewrite it.

The account variable is tuwunel_runas and not tuwunel_user, because rc.subr gives ${name}_user its own meaning: it drops privileges itself before running the command, after which daemon(8) is no longer root and its own -u fails with initgroups(tuwunel, 1001): Operation not permitted. Only one of the two should be doing the drop.

The pidfile lives in /var/run/tuwunel/ rather than /var/run/, because daemon(8) drops privileges before it writes the pidfile. Writing straight to /var/run/ fails with Permission denied, so start_precmd creates a directory the account owns.

Output goes to syslog under the tuwunel tag. Point a local facility at a file through syslog.conf if you want it separated out.

Differences from the shipped platforms

No io_uring. The feature is Linux only, so RocksDB uses the POSIX I/O backend. This is the same code path every non-Linux build takes.

No systemd integration. Readiness and watchdog notification, socket activation, and the reload handling described in Systemd Socket Activation and Reloading Configuration are all Linux only. Run the server under rc.d or a supervisor of your choice instead.

No CPU feature levels. The build targets the architecture baseline, and nothing selects one of the x86_64-v1 through x86_64-v4 levels the release packages come in. On aarch64 there is nothing to choose. On amd64 the baseline is the v1 level, which costs RocksDB its hardware CRC32C; see RocksDB on amd64 for the flag that raises it.

Tuwunel for NetBSD

Tuwunel builds and runs on NetBSD, but NetBSD is not a supported platform. Nothing in the CI matrix builds it, no release artifact is published for it, and there is no pkgsrc package. This page records a build that was verified end to end, and the handful of things that differ from the platforms we do ship.

Verified against 1.8.3 on NetBSD 11.0, evbarm-aarch64 and amd64. The resulting server opens its database, answers the client and federation version endpoints, registers an account, creates a room, sends and reads back a message, reopens a populated database across a restart, and exits cleanly on SIGTERM.

Contributions for getting Tuwunel into pkgsrc are welcome.

Toolchain

A stock NetBSD install has pkg_add but no pkgin, so bootstrap it first:

export PKG_PATH=https://cdn.NetBSD.org/pub/pkgsrc/packages/NetBSD/amd64/11.0/All/
pkg_add pkgin
echo "https://cdn.NetBSD.org/pub/pkgsrc/packages/NetBSD/amd64/11.0/All" \
    > /usr/pkg/etc/pkgin/repositories.conf
pkgin update

The architecture in those two URLs is the pkgsrc one, amd64 here and aarch64 on evbarm-aarch64. Neither is what uname -m prints on both ports, so substitute it by hand rather than deriving it.

Then install the build dependencies:

pkgin install rust git cmake clang gmake pkgconf curl

rust carries 1.96.0 on both branches, which is at or above the rust-version the workspace declares. The clang package supplies /usr/pkg/lib/libclang.so, which rust-librocksdb-sys runs bindgen against; point the build at it with LIBCLANG_PATH. NetBSD’s base compiler is GCC and does not provide it.

Everything under /usr/pkg needs to be on PATH, which is not the case for a non-interactive ssh command:

export PATH=/usr/pkg/bin:/usr/pkg/sbin:$PATH

This is the set that was verified rather than a minimal one. curl is only used by the checks further down this page.

Features

The default feature set includes io_uring and systemd, both of which are Linux only. Every NetBSD build therefore has to opt out of the defaults and name its features explicitly.

The list below is the default set with io_uring and systemd removed.

Note

The features added to the default set in 2.0 have not yet been tested on NetBSD.

brotli_compression
bzip2_compression
console
cpu_affinity
direct_tls
element_hacks
email
gcs_storage
gzip_compression
jemalloc
jemalloc_conf
jwt_login
ldap
lz4_compression
markdown
mas
media_thumbnail
oidc
release_max_log_level
s3_storage
sentry_telemetry
synapse_admin
url_preview
zstd_compression

Building

export PATH=/usr/pkg/bin:/usr/pkg/sbin:$PATH
export LIBCLANG_PATH=/usr/pkg/lib

cargo build --release -p tuwunel --no-default-features \
    --features brotli_compression,bzip2_compression,console,cpu_affinity,direct_tls,element_hacks,email,gcs_storage,gzip_compression,jemalloc,jemalloc_conf,jwt_login,ldap,lz4_compression,markdown,mas,media_thumbnail,oidc,release_max_log_level,s3_storage,sentry_telemetry,synapse_admin,url_preview,zstd_compression

No source changes or compiler flag workarounds are needed. The pinned RocksDB code probes NetBSD’s exported CPU ID at run time and uses the arm64 CRC32C and PMULL paths when the CPU reports those extensions.

On amd64 the build is equally clean, but it is worth raising the target CPU before running it in anger; see RocksDB on amd64 below.

A cold build took about 66 minutes on 4 jobs on evbarm-aarch64, and about 31 minutes on 4 jobs on amd64, producing a 79 MB and a 94 MB binary respectively. The result is dynamically linked, and against base system libraries only:

$ ldd target/release/tuwunel
	-lstdc++.9 => /usr/lib/libstdc++.so.9
	-lm.0 => /usr/lib/libm.so.0
	-lgcc_s.1 => /usr/lib/libgcc_s.so.1
	-lc.12 => /usr/lib/libc.so.12
	-lpthread.1 => /usr/lib/libpthread.so.1

Nothing under /usr/pkg is needed at run time, so the binary can be copied to a host that has no pkgsrc toolchain installed.

RocksDB on amd64

Nothing fails to build here, but the default amd64 build is slower than it needs to be. RocksDB picks its CRC32C implementation when it is compiled, and on x86 there is no runtime fallback:

// NOTE: runtime detection no longer supported on x86

cargo build targets the x86-64 baseline, which carries fxsr, sse and sse2 and nothing else. __SSE4_2__ is therefore never defined, and the table driven software routine is what ends up in the binary, on hardware that has the instruction. Every write-ahead log record is checksummed with it, and so is every record read back during recovery. Table blocks are checksummed with XXH3 instead and are unaffected. librocksdb-sys says so during the build, though cargo hides build warnings from dependencies by default:

compiling without SSE4.2: CRC will be slow (set RUSTFLAGS="-Ctarget-cpu=..."
to optimize RocksDB e.g. -Ctarget-cpu=broadwell)

Raising the target CPU is all it takes:

RUSTFLAGS="-Ctarget-cpu=westmere" cargo build --release -p tuwunel \
    --no-default-features --features ...

sse4.2 alone buys the single stream hardware CRC32. The three way version RocksDB prefers also wants pclmulqdq, and westmere is the oldest -Ctarget-cpu supplying both; anything newer serves. Comparing the two builds confirms it: the baseline one carries RocksDB’s software lookup tables and no crc32c_3way, and the westmere one carries crc32c_3way and no tables. The tuned build finished a minute and a half faster than the baseline and came out marginally smaller, so the flag costs nothing.

This is the axis the x86_64-v1 through x86_64-v4 release packages sit on. A build with no -Ctarget-cpu is the v1 one, and nothing selects a higher level for you here.

CRC32C ends up in software by default on amd64 because of the compiler target, and the flag above fixes it. On evbarm-aarch64, RocksDB instead probes NetBSD’s exported CPU ID at run time and uses the hardware CRC32C and PMULL paths when available.

Running

Configuration is no different from any other platform; see Configuration. A minimal file to prove the build:

[global]
server_name = "example.com"
address = "0.0.0.0"
port = 8008
database_path = "/var/db/tuwunel"
tuwunel -c /usr/pkg/etc/tuwunel/tuwunel.toml

Running under rc.d

Create an account for the service, install the binary, and give it a database directory:

groupadd tuwunel
useradd -g tuwunel -d /nonexistent -s /sbin/nologin tuwunel
install -m 755 target/release/tuwunel /usr/pkg/bin/tuwunel
mkdir -p /usr/pkg/etc/tuwunel /var/db/tuwunel
chown tuwunel:tuwunel /var/db/tuwunel
install -o tuwunel -g tuwunel -m 640 /dev/null /var/log/tuwunel.log

That last line matters. NetBSD has no daemon(8), so the script below backgrounds the server itself and redirects its output, and rc.subr applies the redirect after it has dropped to tuwunel_user. Without a log file the account already owns, the start fails with sh: cannot create /var/log/tuwunel.log: permission denied.

Save this as /etc/rc.d/tuwunel and chmod 555 it:

#!/bin/sh
#
# PROVIDE: tuwunel
# REQUIRE: DAEMON NETWORKING
# KEYWORD: shutdown

$_rc_subr_loaded . /etc/rc.subr

name="tuwunel"
rcvar=$name
command="/usr/pkg/bin/tuwunel"
command_args="-c /usr/pkg/etc/tuwunel/tuwunel.toml >> /var/log/tuwunel.log 2>&1 &"
tuwunel_user="tuwunel"

load_rc_config $name
run_rc_command "$1"
echo "tuwunel=YES" >> /etc/rc.conf
/etc/rc.d/tuwunel start

Set log_colors = false in the configuration when logging to a file this way. Tuwunel decides on colour from the configuration rather than from whether the sink is a terminal, so the log otherwise accumulates ANSI escapes.

Differences from the shipped platforms

CRC32C and PMULL are detected at run time on arm64. RocksDB reads machdep.cpu0.cpu_id through sysctlbyname and inspects the exported ID_AA64ISAR0_EL1 value. It selects hardware CRC32C when CPU 0 reports the CRC32 extension, and enables the PMULL path when CPU 0 also reports PMULL. If the CRC32 probe fails or the extension is unavailable, checksums use the software fallback. A failed PMULL probe disables only that path. Table blocks use XXH3 and are unaffected.

No io_uring. The feature is Linux only, so RocksDB uses the POSIX I/O backend. This is the same code path every non-Linux build takes.

No systemd integration. Readiness and watchdog notification, socket activation, and the reload handling described in Systemd Socket Activation and Reloading Configuration are all Linux only. Run the server under rc.d or a supervisor of your choice instead.

No CPU feature levels. The build targets the architecture baseline, and nothing selects one of the x86_64-v1 through x86_64-v4 levels the release packages come in. On evbarm-aarch64 there is nothing to choose. On amd64 the baseline is the v1 level, which costs RocksDB its hardware CRC32C; see RocksDB on amd64 for the flag that raises it.

Tuwunel for NixOS

Tuwunel can be acquired by Nix from various places:

  • The flake.nix at the root of the repo
  • The default.nix at the root of the repo
  • From Tuwunel’s binary cache

A community maintained NixOS package is available at tuwunel

Binary cache

Tuwunel publishes prebuilt store paths, so building from the flake does not have to compile RocksDB and the Rust toolchain locally. The cache is public and reading from it needs no account.

SubstituterPublic key
Self-hostedhttps://cache.tuwunel.chatcache.tuwunel.chat-1:ZafUaXiRMozDa9N2SWim6EdzH0EEjWjwfvlTxXvcjLA=
Cachixhttps://tuwunel.cachix.orgtuwunel.cachix.org-1:VRecUeDcaPxtYDA6bnMF3snPM7VYX8K605z4uuG2nWc=

Both are live and either works on its own. Prefer cache.tuwunel.chat: it stores the whole closure, stock nixpkgs paths included, so a build can be satisfied from it without reaching cache.nixos.org at all. The Cachix cache holds only Tuwunel’s own binaries and forked dependencies.

On NixOS, add them to nix.settings:

{
  nix.settings = {
    extra-substituters = [
      "https://cache.tuwunel.chat"
      "https://tuwunel.cachix.org"
    ];
    extra-trusted-public-keys = [
      "cache.tuwunel.chat-1:ZafUaXiRMozDa9N2SWim6EdzH0EEjWjwfvlTxXvcjLA="
      "tuwunel.cachix.org-1:VRecUeDcaPxtYDA6bnMF3snPM7VYX8K605z4uuG2nWc="
    ];
  };
}

Everywhere else, put the same two settings in /etc/nix/nix.conf and restart the daemon:

extra-substituters = https://cache.tuwunel.chat https://tuwunel.cachix.org
extra-trusted-public-keys = cache.tuwunel.chat-1:ZafUaXiRMozDa9N2SWim6EdzH0EEjWjwfvlTxXvcjLA= tuwunel.cachix.org-1:VRecUeDcaPxtYDA6bnMF3snPM7VYX8K605z4uuG2nWc=
sudo systemctl restart nix-daemon

Nix falls through to another substituter or a source build when a cache returns HTTP 404 for a missing path. A reachable cache that returns HTTP 5xx is different: Nix treats that as a transfer error, retries it, and can fail the build. The Tuwunel cache therefore converts reverse-proxy backend failures to 404 for narinfo and NAR reads while continuing to serve cached responses.

With the cachix client installed, cachix use tuwunel writes the Cachix half of that configuration for you.

The repository flake also declares the cache in its nixConfig, but do not rely on that alone. Nix treats a flake’s configuration as untrusted: an interactive build asks whether to accept it, and a non-interactive one skips it with ignoring untrusted flake configuration setting, so an unattended deployment that configured nothing else would quietly build everything from source. Set the two values as shown above, or pass --accept-flake-config.

cache.tuwunel.chat is self-hosted on Tuwunel’s own infrastructure, behind a caching proxy that keeps serving already-fetched paths even if the cache application itself is down.

NixOS module

A NixOS module ships with Nixpkgs as services.matrix-tuwunel, available in 25.11 and unstable. It generates tuwunel.toml from a settings attrset and runs the server under a hardened systemd unit (DynamicUser, ProtectSystem=strict, strict SystemCallFilter).

Minimal configuration:

{
  services.matrix-tuwunel = {
    enable = true;
    settings.global = {
      server_name = "example.com";
      address = [ "127.0.0.1" "::1" ];
      port = [ 6167 ];
      allow_federation = true;
    };
  };
}

Notable defaults:

  • User and group tuwunel (override via services.matrix-tuwunel.user / .group).
  • Database under /var/lib/tuwunel/ (override via services.matrix-tuwunel.stateDirectory).
  • Listens on 127.0.0.1 and ::1 port 6167.

Anything placed under settings.global is written verbatim into the [global] table of tuwunel.toml, so the configuration reference applies directly.

UNIX sockets

The module exposes unix_socket_path and unix_socket_perms directly:

services.matrix-tuwunel.settings.global = {
  unix_socket_path = "/run/tuwunel/tuwunel.sock";
  unix_socket_perms = 660;
};

Leave address unset (or null) when using a socket. The systemd unit already permits AF_UNIX, so no further overrides are needed.

Migrating from services.matrix-conduit

services.matrix-tuwunel replaces the legacy services.matrix-conduit module that older guides reference. Most settings carry over because both render the same TOML schema. When migrating:

  • Disable services.matrix-conduit and enable services.matrix-tuwunel.
  • Confirm the database is RocksDB. Tuwunel dropped SQLite in favor of RocksDB; if you ran a SQLite Conduit, migrate first with conduit_toolbox.
  • Either set services.matrix-tuwunel.stateDirectory to match your existing database_path, or move the database under /var/lib/tuwunel/.

Tuwunel for OpenBSD

Tuwunel builds and runs on OpenBSD, but OpenBSD is not a supported platform. Nothing in the CI matrix builds it, no release artifact is published for it, and there is no port or package. Of the three BSDs this takes the most setup, and one requirement is not optional: the Rust in 7.9-release is too old, so the compiler has to come from -current.

Verified against 1.8.3 on OpenBSD 7.9, arm64 and amd64. The resulting server opens its database, answers the client and federation version endpoints, registers an account, creates a room, sends and reads back a message, reopens a populated database across a restart, and exits cleanly on SIGTERM. That binary was built without jemalloc. A release build with the feature set below, jemalloc included, passed the same checks on both architectures against the tree after 1.9.1.

Contributions for getting Tuwunel into ports are welcome.

The compiler has to come from -current

7.9-release packages Rust 1.94.1. The workspace declares rust-version = "1.95.0" and means it:

error[E0658]: `if let` guards are experimental
   --> src/service/resolver/actual.rs:116:10
    |
116 |         | None if let Some(pos) = dest.as_str().find(':') =>

if let match guards were stabilised in 1.95.0. cargo build --ignore-rust-version skips the manifest check but not the compiler, so it does not help here.

This is the same on both architectures: 7.9-release packages 1.94.1 for arm64 and for amd64.

The -current snapshots carry 1.97.1, which installs and runs on a 7.9 system. The last path element is the package architecture, aarch64 or amd64:

PKG_PATH=https://cdn.openbsd.org/pub/OpenBSD/snapshots/packages/amd64/ \
    pkg_add -u rust

Mixing a snapshot package into a release system is not something OpenBSD supports in general. Nothing else was taken from -current for this build, and rustc and cargo ran without complaint, but treat it as the compromise it is: a build host running -current, or waiting for a release whose rust package is 1.95 or newer, is the cleaner arrangement.

Toolchain

pkg_add git cmake gmake curl
pkg_add -I llvm-21.1.8p4

pkg_add llvm on its own fails with Ambiguous: llvm could be llvm-19.1.7p14 llvm-21.1.8p4 llvm-20.1.8p6 and installs nothing, so name the version. It provides /usr/local/llvm21/lib/libclang.so.0.0, which rust-librocksdb-sys runs bindgen against; point the build at that directory with LIBCLANG_PATH. OpenBSD ships no unversioned libclang.so symlink, which is fine, because bindgen matches the versioned name.

This is the set that was verified rather than a minimal one. curl is only used by the checks further down this page.

Raising the login class limits

This is the step most likely to be missed. The daemon class root logs in under allows a 4 GB data segment and 128 open files, and neither the build nor the server fits in that. Both limits are hard ceilings set by the login class, so ulimit alone cannot lift them.

Append a class to /etc/login.conf:

tuwunel:\
	:datasize-cur=infinity:\
	:datasize-max=infinity:\
	:openfiles-cur=8192:\
	:openfiles-max=16384:\
	:maxproc-cur=1024:\
	:maxproc-max=2048:\
	:stacksize-cur=16M:\
	:tc=daemon:

Rebuild the capability database if one exists, and raise the system wide file table, which defaults to 7030 and would otherwise cap the per-process figure above:

[ -f /etc/login.conf.db ] && cap_mkdb /etc/login.conf
sysctl kern.maxfiles=32768
echo "kern.maxfiles=32768" >> /etc/sysctl.conf

Put the account doing the build into the class and log in again:

usermod -L tuwunel root

ulimit -a should then report nofiles 8192, and a data segment raised well clear of the 4 GB default. infinity means the architecture ceiling rather than a literal absence of one, so arm64 reports unlimited and amd64 reports 128 GB.

Where to build

The installer’s auto layout splits the disk into small partitions, and on an 80 GB disk the only one large enough for a cargo target directory is /home:

$ df -h
/dev/sd0a      986M   85.2M    851M    10%    /
/dev/sd0l     27.8G   18.0K   26.5G     1%    /home
/dev/sd0h     10.5G    146K   10.0G     1%    /usr/local

Set CARGO_TARGET_DIR accordingly rather than building in place.

RocksDB include ordering

Nothing extra is needed here now, but a build against an older rust-rocksdb pin fails on aarch64 like this:

/usr/include/sys/sysctl.h:373:2: error: unknown type name 'u_int64_t'

rocksdb/util/crc32c_arm64.cc has an OpenBSD include block, and it listed <sys/sysctl.h> before <sys/types.h>. OpenBSD’s sysctl.h is not self contained and needs the types first, so the whole header failed to parse. That block has probably never compiled since it was written.

The order is corrected as of rust-rocksdb c6e73b5, which is what the workspace pins. Building an older revision needs the types forced in ahead of everything instead:

export CXXFLAGS="-include sys/types.h"

This affects aarch64 only. crc32c_arm64.cc is not compiled on amd64.

The file then compiles and the runtime check works as written: OpenBSD reads CTL_MACHDEP/CPU_ID_AA64ISAR0 through sysctl and selects the hardware CRC32C path when the CPU reports it.

RocksDB on amd64

Nothing fails to build here, but the default amd64 build is slower than it needs to be. RocksDB picks its CRC32C implementation when it is compiled, and on x86 there is no runtime fallback:

// NOTE: runtime detection no longer supported on x86

cargo build targets the x86-64 baseline, which carries fxsr, sse and sse2 and nothing else. __SSE4_2__ is therefore never defined, and the table driven software routine is what ends up in the binary, on hardware that has the instruction. Every write-ahead log record is checksummed with it, and so is every record read back during recovery. Table blocks are checksummed with XXH3 instead and are unaffected. librocksdb-sys says so during the build, though cargo hides build warnings from dependencies by default:

compiling without SSE4.2: CRC will be slow (set RUSTFLAGS="-Ctarget-cpu=..."
to optimize RocksDB e.g. -Ctarget-cpu=broadwell)

Raising the target CPU is all it takes:

RUSTFLAGS="-Ctarget-cpu=westmere" cargo build --release -p tuwunel \
    --no-default-features --features ...

sse4.2 alone buys the single stream hardware CRC32. The three way version RocksDB prefers also wants pclmulqdq, and westmere is the oldest -Ctarget-cpu supplying both; anything newer serves. Comparing the two builds confirms it: the baseline one carries RocksDB’s software lookup tables and no crc32c_3way, and the westmere one carries crc32c_3way and no tables. Neither build time nor binary size moved meaningfully.

This is the axis the x86_64-v1 through x86_64-v4 release packages sit on. A build with no -Ctarget-cpu is the v1 one, and nothing selects a higher level for you here.

Features

The default feature set includes io_uring and systemd, both of which are Linux only. Every OpenBSD build therefore has to opt out of the defaults and name its features explicitly.

The list below is the default set with io_uring and systemd removed.

Note

The features added to the default set in 2.0 have not yet been tested on OpenBSD.

Warning

Tuwunel 1.9.1 and earlier cannot use jemalloc here: a binary built with it aborts before it starts. Build those releases without jemalloc and jemalloc_conf, which leaves OpenBSD’s own allocator in charge.

Later releases can leave both out too, if you would rather every allocation went through OpenBSD’s allocator and its hardening.

brotli_compression
bzip2_compression
console
cpu_affinity
direct_tls
element_hacks
email
gcs_storage
gzip_compression
jemalloc
jemalloc_conf
jwt_login
ldap
lz4_compression
markdown
mas
media_thumbnail
oidc
release_max_log_level
s3_storage
sentry_telemetry
synapse_admin
url_preview
zstd_compression

On OpenBSD jemalloc is built with a symbol prefix, so Tuwunel’s own allocations go through it while RocksDB and the other C and C++ libraries keep OpenBSD’s allocator. The prefix covers jemalloc’s configuration variable too: to change the tuning Tuwunel ships with, set _RJEM_MALLOC_CONF rather than MALLOC_CONF, and check what a binary is running with:

_RJEM_MALLOC_CONF=stats_print:true tuwunel -V

Building

export PATH=/usr/local/bin:/usr/local/sbin:$PATH
export LIBCLANG_PATH=/usr/local/llvm21/lib
export CARGO_TARGET_DIR=/home/build/target

cargo build --release -p tuwunel --no-default-features \
    --features brotli_compression,bzip2_compression,console,cpu_affinity,direct_tls,element_hacks,email,gcs_storage,gzip_compression,jemalloc,jemalloc_conf,jwt_login,ldap,lz4_compression,markdown,mas,media_thumbnail,oidc,release_max_log_level,s3_storage,sentry_telemetry,synapse_admin,url_preview,zstd_compression

Building the 1.8.3 release rather than the current tree needs one more change. tuwunel_core denies missing_docs, and the OpenBSD arm of available_parallelism in src/core/utils/sys/compute.rs carried no doc comment, so the crate failed to compile on OpenBSD and nowhere else:

error: missing documentation for a function
   --> src/core/utils/sys/compute.rs:131:1
    |
131 | pub fn available_parallelism() -> usize { num_cpus::get() }

Adding a doc comment above it is enough. This is fixed in the tree.

A cold build took about 57 minutes on 2 jobs on arm64, and about 80 minutes on 2 jobs on amd64, producing an 81.6 MB and a 90 MB binary respectively. The amd64 timing is from the tuned build described above, which is the cold one that was measured; the flag does not change build time. The result is dynamically linked, and against base system libraries only:

$ ldd /usr/local/bin/tuwunel
	/usr/lib/libc++.so.12.0
	/usr/lib/libpthread.so.28.1
	/usr/lib/libc++abi.so.9.0
	/usr/lib/libc.so.103.0
	/usr/lib/libm.so.10.1

Nothing from /usr/local/lib is needed at run time, so the binary can be copied to a host with no build toolchain. It still needs its login class limits there.

Cargo wedged twice partway through this build, sleeping with no rustc child and nothing in the system logs, and had to be killed and restarted. It resumes from cache, and the build that completed ran at -j2. If you see a build stop making progress, check whether rustc is still running before assuming it is merely slow.

Running under rc.d

Create an account in the login class from above, install the binary, and give it a database directory:

useradd -c "tuwunel" -d /var/tuwunel -s /sbin/nologin -L tuwunel _tuwunel
install -m 755 /home/build/target/release/tuwunel /usr/local/bin/tuwunel
mkdir -p /etc/tuwunel /var/tuwunel
chown _tuwunel:_tuwunel /var/tuwunel

Save this as /etc/rc.d/tuwunel and chmod 555 it:

#!/bin/ksh

daemon="/usr/local/bin/tuwunel"
daemon_flags="-c /etc/tuwunel/tuwunel.toml"
daemon_user="_tuwunel"
daemon_class="tuwunel"

. /etc/rc.d/rc.subr

rc_bg=YES
rc_reload=NO

rc_cmd $1
rcctl enable tuwunel
rcctl start tuwunel

rc_bg=YES is required: tuwunel runs in the foreground and never forks, so without it rcctl start would block. daemon_class is what carries the raised limits to the server, and is the reason _tuwunel is created with -L tuwunel; without it the daemon runs with 128 file descriptors and will not get far.

A minimal configuration to go with it:

[global]
server_name = "example.com"
address = "127.0.0.1"
port = 8008
database_path = "/var/tuwunel"
log_colors = false

Set log_colors = false whenever the log is not going to a terminal. Tuwunel decides on colour from the configuration rather than from the sink, so the log otherwise accumulates ANSI escapes.

Differences from the shipped platforms

No io_uring. The feature is Linux only, so RocksDB uses the POSIX I/O backend. This is the same code path every non-Linux build takes.

No systemd integration. Readiness and watchdog notification, socket activation, and the reload handling described in Systemd Socket Activation and Reloading Configuration are all Linux only. Use the rc.d script above instead.

No CPU feature levels. The build targets the architecture baseline, and nothing selects one of the x86_64-v1 through x86_64-v4 levels the release packages come in. On arm64 there is nothing to choose. On amd64 the baseline is the v1 level, which costs RocksDB its hardware CRC32C; see RocksDB on amd64 for the flag that raises it.

Tuwunel for Red Hat

Information about downloading and deploying the Red Hat package. This may also be referenced for other rpm-based distros such as CentOS.

Installation

It is recommended to see the generic deployment guide for further information if needed as usage of the RPM package is generally related.

A COPR repository serves the stable releases for x86_64 and aarch64. Builds are provided for Fedora, RHEL, CentOS Stream, AlmaLinux, Amazon Linux, Azure Linux, and openEuler; the full list of targets is on the project page.

sudo dnf install 'dnf-command(copr)'
sudo dnf copr enable trapacid/tuwunel
sudo dnf install tuwunel

On distributions where the copr plugin is unavailable, download the .repo file for your release from the COPR project page into /etc/yum.repos.d/ instead.

Migrating from another homeserver

Homeservers of the Conduit lineage (including forks) cannot run alongside Tuwunel and must be uninstalled first. The package declares a conflict with them, so the transaction is refused rather than leaving two servers claiming one database directory:

sudo dnf remove conduwuit

Installing the Tuwunel package then adopts the existing database by moving it to /var/lib/tuwunel; nothing is copied or deleted, and the data is migrated on the next startup. Databases are discovered at /var/lib/conduwuit and /var/lib/matrix-conduit, and also under /var/lib/private, where systemd keeps the state of a service that ran with DynamicUser=. The location a database was adopted from is left behind as a symlink into /var/lib/tuwunel, so a configuration ported from the old server still reaches it, and a package removed later reaches a symlink rather than the database. Nothing else is linked: a fresh installation creates no such symlink, and one left by an earlier version of this package is removed unless the configuration sets database_path, since a previous server’s name pointing at the database is one rm -r away from deleting it.

Adoption is skipped while an old homeserver unit is still active, and a database on its own filesystem is never moved, since moving it across filesystems would copy the whole database. Stop the old unit, or mount that filesystem at /var/lib/tuwunel, then finish the migration with:

sudo /usr/libexec/tuwunel/adopt-legacy-database

That command is safe to run at any time and does nothing once the database is in place. Port the settings from your old configuration (especially server_name) into /etc/tuwunel/tuwunel.toml before starting the service. Removing Tuwunel leaves /var/lib/tuwunel and its contents alone.

Configuration

When installed, the example config is placed at /etc/tuwunel/tuwunel.toml as the default config. The config mentions things required to be changed before starting.

You can tweak more detailed settings by uncommenting and setting the config options in /etc/tuwunel/tuwunel.toml.

Running

The package uses the tuwunel.service systemd unit file to start and stop Tuwunel. The binary is installed at /usr/sbin/tuwunel.

A tuwunel.socket unit is installed alongside it, disabled, for deployments that want systemd to open the listening socket. It is what lets the server answer on a privileged port such as 443 or 8448 while holding no capability of its own. See systemd socket activation before enabling it, since a passed socket is served in addition to the address in the configuration file rather than replacing it.

This package assumes by default that Tuwunel will be placed behind a reverse proxy. The default config options apply (listening on localhost and TCP port 8008). Matrix federation requires a valid domain name and TLS, so you will need to set up TLS certificates and renewal for it to work properly if you intend to federate.

Consult various online documentation and guides on setting up a reverse proxy and TLS. Caddy is documented at the generic deployment guide as it’s the easiest and most user friendly.

SELinux

On systems with SELinux enabled, the tuwunel-selinux subpackage is installed automatically. It provides the tuwunel_t domain together with file contexts for the binary, /etc/tuwunel, /var/lib/tuwunel, and /run/tuwunel, so no manual labeling is required. The policy covers the client and federation listeners and outbound federation.

The domain runs enforcing. If a denial does occur on your setup, inspect it with ausearch -m avc -ts recent | grep tuwunel, report it to the issue tracker, and as a temporary measure the domain can be switched to permissive with semanage permissive -a tuwunel_t (revert with semanage permissive -d tuwunel_t once resolved).

A reverse proxy running as httpd_t (nginx, Apache) may connect to a listener on a unix socket under /run/tuwunel without further configuration. Proxying to the TCP listener instead is governed by the distribution booleans:

setsebool -P httpd_can_network_connect 1

Paths configured outside the packaged locations, such as a database backup directory, need a file context of their own:

semanage fcontext -a -t tuwunel_var_lib_t '/opt/tuwunel-db-backups(/.*)?'
restorecon -R /opt/tuwunel-db-backups

Podman / Quadlets

Podman and Quadlets are well supported on Redhat-based distributions. See Podman and systemd for examples.

Containers

Tuwunel ships as a small, statically linked OCI image that runs unprivileged on any container runtime. Pick a deployment style based on how you already manage services on the host.

  • Docker. Pull prebuilt images from GHCR or Docker Hub, then run standalone or via one of the provided docker-compose stacks (with Caddy, Traefik, or a bring-your-own reverse proxy).

  • Kubernetes. Community-maintained Helm chart for cluster deployments. Tuwunel itself does not scale horizontally, so the chart runs a single replica with persistent storage.

  • Podman with Quadlets. Rootless deployment managed by systemd user units, suited to single-host setups where containers should behave like native services.

Whichever style you pick, security profiles and limits covers the two runtime defaults that affect this server: the task limit that can stop startup outright, and the seccomp profile that decides whether the database gets io_uring.

Registries

RegistryImageTags
GitHub Registryghcr.io/matrix-construct/tuwunellatest, preview, main
Docker Hubdocker.io/jevolk/tuwunellatest, preview, main

Images

Three rolling tags trade update frequency for confidence.

TagSourceCadenceUse when
:latestMost recent tagged release~monthlyProduction. Default choice.
:previewSelected higher-confidence updates~weeklyYou want fixes between releases without chasing main.
:mainEvery reviewed merge to the main branch~dailyYou track development and accept unknown-risk changes.

Important

We strongly advise tracking the :latest tag when automatically updating.

Tracking :latest gives us the necessary discretion to keep you on the appropriate stable release version. Tracking the :preview tag provides select updates of higher confidence between releases. Tracking the :main branch provides the most frequent updates which have been reviewed and tested with confidence for release, the only remaining risk being the unknown. The publication frequency for these tags are on average monthly, weekly and daily, respectively.

Tuwunel for Docker

Docker

To run tuwunel with Docker you can either build the image yourself or pull it from a registry.

Use a registry

OCI images for tuwunel are available in the registries listed below.

RegistryImageSizeNotes
GitHub Registryghcr.io/matrix-construct/tuwunel:latestMost recent tagged release. Recommended for automated updates (~monthly).
Docker Hubdocker.io/jevolk/tuwunel:latestMost recent tagged release. Recommended for automated updates (~monthly).
GitHub Registryghcr.io/matrix-construct/tuwunel:previewSelected higher-confidence updates between releases (~weekly).
Docker Hubdocker.io/jevolk/tuwunel:previewSelected higher-confidence updates between releases (~weekly).
GitHub Registryghcr.io/matrix-construct/tuwunel:mainEvery reviewed merge to the main branch (~daily).
Docker Hubdocker.io/jevolk/tuwunel:mainEvery reviewed merge to the main branch (~daily).

Run

When you have the image you can simply run it with

docker run -d -p 8448:8008 \
    -v db:/var/lib/tuwunel/ \
    -e TUWUNEL_SERVER_NAME="your.server.name" \
    -e TUWUNEL_ALLOW_REGISTRATION=false \
    --stop-timeout 1800 \
    --name tuwunel $LINK

The --stop-timeout is what lets an upgrade finish its database migration instead of being killed part way through; see Stopping during a migration.

or you can use docker compose.

The -d flag lets the container run in detached mode. You may supply an optional tuwunel.toml config file, the example config can be found here. You can pass in different env vars to change config values on the fly. You can even configure tuwunel completely by using env vars. For an overview of possible values, please take a look at the docker-compose.yml file.

If you just want to test tuwunel for a short time, you can use the --rm flag, which will clean up everything related to your container after you stop it.

Health check

The image ships a HEALTHCHECK which runs tuwunel --health-check: it reads the same configuration as the server, connects to each configured listener, and requests /_tuwunel/server_version. Container platforms report the result as the container’s health status. The probe reads the configuration from the environment and any config file named by TUWUNEL_CONFIG; arguments passed on the container command line are not visible to it, so when configuring via command-line arguments override the health check accordingly. The probe targets the configured listeners, so sockets passed in by a process manager (systemd socket activation) are not covered. The same flag also works outside containers, e.g. as a Kubernetes exec probe.

Stopping during a migration

The first boot after an upgrade can run a one-time database migration, and the listener does not open until it finishes. On a large database that can take many minutes.

A container runtime will not wait that long by default. docker stop and podman stop send SIGTERM, then SIGKILL ten seconds later; Kubernetes allows thirty. A kill part way through a migration leaves the database half migrated, and no admin command repairs that. Raise the grace period so the server is allowed to reach a safe point:

RuntimeSettingDefault
docker run--stop-timeout 180010s
Composestop_grace_period: 30m10s
Podman quadletPodmanArgs=--stop-timeout=1800, plus TimeoutStopSec=183010s
KubernetesterminationGracePeriodSeconds: 180030s

There is no way to carry this in the image, so it has to be set where the container is run. The compose files shipped in this directory already set it, and so does the quadlet unit.

Under a quadlet both deadlines have to be set. The generator writes no TimeoutStopSec= of its own, so systemd’s ninety second default ends the container before podman’s timeout is reached, and StopTimeout= only became a [Container] key in podman 5.0, where an unknown key makes the generator emit no unit at all, so the value reaches podman as a passthrough argument instead.

Tuwunel leaves the migration at the next safe point when it is asked to stop, and the steps that already finished are recorded, so the remainder run on the next start. That only helps if the runtime waits long enough for the current step to end, which is what the settings above buy.

While a migration runs the server logs a line every fifteen seconds naming the step, how far into it the server is, and how long it has been going, so docker logs -f shows work in progress rather than silence:

Database migration in progress progress=repair_short_injectivity_seen / short ids, 1204833 done, 12.55 minutes

A step reports a position without a total when it cannot count its remaining work without a second pass over the data. A position that keeps climbing is the signal that the migration is progressing.

Health during a migration

The health probe answers whether the server is serving, and a migrating one is not, so it fails until the listener opens. That is why the image sets a health start period of thirty minutes: a container inside its start period reports starting rather than unhealthy, and failures there do not count against the retry budget.

Up 12 minutes (health: starting)

An unhealthy container is what invites the docker restart that kills a migration mid-write, so the wide window exists to keep that reading off the screen while the server is doing exactly what it should. A container that reports healthy once leaves the start period behind, and a migration that fails ends the process rather than lingering unhealthy.

Nothing waiting on health is misled by this. A Compose service gated on depends_on: condition: service_healthy waits through starting and runs only once the listener answers, which is the behaviour you want and the reason the probe is not simply made to report healthy while migrating.

Docker-compose

If the docker run command is not for you or your setup, you can also use one of the provided docker-compose files.

Depending on your proxy setup, you can use one of the following files:

When picking the traefik-related compose file, rename it so it matches docker-compose.yml, and rename the override file to docker-compose.override.yml. Edit the latter with the values you want for your server.

When picking the caddy-docker-proxy compose file, it’s important to first create the caddy network before spinning up the containers:

docker network create caddy

After that, you can rename it so it matches docker-compose.yml and spin up the containers!

Additional info about deploying tuwunel can be found here.

Run

If you already have built the image or want to use one from the registries, you can just start the container and everything else in the compose file in detached mode with:

docker compose up -d

Note: Don’t forget to modify and adjust the compose file to your needs.

Nix build

Tuwunel’s Nix images are built using buildLayeredImage. This ensures all OCI images are repeatable and reproducible by anyone, keeps the images lightweight, and can be built offline.

This also ensures portability of our images because buildLayeredImage builds OCI images, not Docker images, and works with other container software.

The OCI images are OS-less with only a very minimal environment of the tini init system, CA certificates, and the tuwunel binary. This does mean there is not a shell, but in theory you can get a shell by adding the necessary layers to the layered image. However it’s very unlikely you will need a shell for any real troubleshooting.

The flake file for the OCI image definition is at nix/pkgs/oci-image/default.nix.

To build an OCI image using Nix, the following outputs can be built:

  • nix build -L .#oci-image (default features, x86_64 glibc)
  • nix build -L .#oci-image-x86_64-linux-musl (default features, x86_64 musl)
  • nix build -L .#oci-image-aarch64-linux-musl (default features, aarch64 musl)
  • nix build -L .#oci-image-x86_64-linux-musl-all-features (all features, x86_64 musl)
  • nix build -L .#oci-image-aarch64-linux-musl-all-features (all features, aarch64 musl)

Use Traefik as Proxy

As a container user, you probably know about Traefik. It is a easy to use reverse proxy for making containerized app and services available through the web. With the two provided files, docker-compose.for-traefik.yml (or docker-compose.with-traefik.yml) and docker-compose.override.yml, it is equally easy to deploy and use tuwunel, with a little caveat. If you already took a look at the files, then you should have seen the well-known service, and that is the little caveat. Traefik is simply a proxy and loadbalancer and is not able to serve any kind of content, but for tuwunel to federate, we need to either expose ports 443 and 8448 or serve two endpoints .well-known/matrix/client and .well-known/matrix/server.

With the service well-known we use a single nginx container that will serve those two files.

Voice communication

See the TURN page.

Podman, Quadlets, and systemd

For a rootless setup, we can use quadlets and systemd to manage the container lifecycle.

Important

If this is the first container managed with quadlets for your user, ensure that linger is enabled so your containers are not killed after logging out.

sudo loginctl enable-linger <username>

Step One

Copy quadlet files to ~/.config/containers/systemd/tuwunel

tuwunel.container

tuwunel container quadlet
# tuwenel.container

[Unit]
Description=Tuwunel Matrix Homeserver

[Container]
ContainerName=tuwunel-homeserver
Image=ghcr.io/matrix-construct/tuwunel:latest
PublishPort=8008:8008
Volume=tuwunel-db:/var/lib/tuwunel/

#Example location in ~/tuwunel/config/
Volume=%h/tuwunel/config/tuwunel.toml:/etc/tuwunel.toml
EnvironmentFile=tuwunel.env

# The first boot after an upgrade can run a database migration that must not be
# interrupted partway, so both stop deadlines have to clear the longest one.
# This is podman's, raising the ten second default it applies to the container
# on the way down. StopTimeout= is the native key for it, but quadlet rejects
# the whole file on an unknown key and only learned that key in podman 5.0, so
# spelling it as a passthrough argument keeps the unit generating on the 4.x
# that Ubuntu 24.04 LTS and RHEL 9 ship.
PodmanArgs=--stop-timeout=1800

# The published image is OCI format, and the OCI image spec carries no
# healthcheck field, so the image's own HEALTHCHECK is invisible to Podman.
# Declaring it here restores the same probe Docker users get. The exec form is
# required: a bare string runs through a shell, and the image has none.
HealthCmd=["/usr/bin/tuwunel", "--health-check"]
HealthInterval=30s
HealthTimeout=15s

# The probe answers whether the server is serving, and a migrating one is not,
# so the start period is what keeps a long first boot reported as starting
# rather than unhealthy. An unhealthy container invites the restart that kills
# a migration mid-write.
HealthStartPeriod=1800s
HealthRetries=3

[Service]
# The other stop deadline. Quadlet writes no TimeoutStopSec= of its own, so
# without this systemd's DefaultTimeoutStopSec (90s) SIGKILLs the container
# cgroup mid-migration however long podman was told to wait.
TimeoutStopSec=1830

# Uncomment when your system is properly configured, restart=always can mask start up errors. 
#Restart=always

[Install]
WantedBy=default.target

tuwunel-db.volume

tuwunel database volume quadlet
[Volume]
VolumeName=tuwunel-db

tuwunel.env

tuwunel environment variable quadlet
TUWUNEL_SERVER_NAME="your.server.tld"
TUWUNEL_PORT=8008
TUWUNEL_MAX_REQUEST_SIZE=20000000
TUWUNEL_ALLOW_REGISTRATION=true
TUWUNEL_REGISTRATION_TOKEN=<replace with a passphrase or random string>
TUWUNEL_ALLOW_FEDERATION=true
TUWUNEL_TRUSTED_SERVERS=["matrix.org"]
TUWUNEL_LOG=info

#Listen on this host for IPv4 and v6
TUWUNEL_ADDRESS=["0.0.0.0", "::"]

#Tell Tuwunel to use the user config file 
TUWUNEL_CONFIG=/etc/tuwunel.toml

mkdir -p ~/.config/containers/systemd/tuwunel

Step Two

Modify tuwunel.env and tuwunel.toml to desired values. This can be saved in your user home directory if desired.

Step Three

  • Reload daemon to generate our systemd unit files:
systemctl --user daemon-reload

Step Four

  • Start tuwunel:
systemctl --user start tuwunel

Logging

To check the logs, run:

systemctl --user status tuwunel

or

podman logs tuwunel-homeserver

Health checking outside a quadlet

The quadlet above declares the health check explicitly, so quadlet users get the same probe Docker users get. A bare podman run of the published image does not, and the reason is worth knowing rather than working around blindly.

The image is published in OCI format, and the health check rides in its config as an extra field, which is where Docker reads it from. Podman does not read that field out of an OCI config (containers/podman#25454, #18904, both open), so it reports no health check at all:

$ podman inspect --format '{{json .HealthCheck}}' ghcr.io/matrix-construct/tuwunel:latest
null
$ docker inspect --format '{{json .Config.Healthcheck}}' ghcr.io/matrix-construct/tuwunel:latest
{"Test":["CMD","tuwunel","--health-check"],...}

Nothing is missing from the image and nothing needs rebuilding in another format. Pass the probe on the command line instead:

podman run -d --name tuwunel \
  --health-cmd '["/usr/bin/tuwunel", "--health-check"]' \
  --health-interval 30s \
  --health-timeout 15s \
  --health-start-period 1800s \
  --health-retries 3 \
  ghcr.io/matrix-construct/tuwunel:latest

The JSON array form is required. A bare string runs through a shell, and the image is built FROM scratch with none. See Health during a migration for why the start period is that wide.

Troubleshooting systemd unit file generation

Look for errors in the output: /usr/lib/systemd/system-generators/podman-system-generator --user --dryrun

Tuwunel for Kubernetes

Tuwunel doesn’t support horizontal scalability or distributed loading natively, however a community maintained Helm Chart is available here to run Tuwunel on Kubernetes: https://github.com/AreYouLoco/tuwunel-helm and the legacy conduwuit version: https://gitlab.cronce.io/charts/conduwuit.

Should changes need to be made, please reach out to the maintainer in our Matrix room as this is not maintained/controlled by the Tuwunel maintainers.

Stopping during a migration

The first boot after an upgrade can run a one-time database migration, and the listener does not open until it finishes. Kubernetes allows 30 seconds by default, which is not enough on a large database, and a kill part way through leaves it half migrated. Raise terminationGracePeriodSeconds on the pod spec past the longest migration, and see Stopping during a migration for the same setting on the other runtimes.

Probes during a migration

tuwunel --health-check answers whether the server is serving. A migrating server is not, so a liveness probe with an ordinary failure threshold kills the container part way through the migration, and under the default restart policy the replacement is killed the same way on the next attempt. Give the pod a startup probe whose budget covers the longest migration; while it is failing, kubelet runs neither the liveness nor the readiness probe, so nothing kills the pod and nothing routes traffic to it.

startupProbe:
  exec: { command: ["tuwunel", "--health-check"] }
  periodSeconds: 10
  failureThreshold: 180        # 30 minutes
livenessProbe:
  exec: { command: ["tuwunel", "--health-check"] }
  periodSeconds: 10
  failureThreshold: 3
readinessProbe:
  exec: { command: ["tuwunel", "--health-check"] }
  periodSeconds: 10
  failureThreshold: 3

A pod with no readiness probe at all is marked ready as soon as its container starts, so a Service will route to a server whose listener has not opened. Configure all three rather than none.

Container security profiles and limits

Tuwunel runs unprivileged under every container runtime’s default security profiles, and needs none of them relaxed. What can stop it is a resource ceiling rather than a security profile, and the two are worth separating before changing either, because the advice that circulates for this server relaxes considerably more than the situation calls for.

Task limits, the default that does stop the server

Podman limits a container to 2,048 tasks by default. Docker takes its limit from the daemon configuration, so it varies by platform; the reports behind this page came from hosts where it was also 2,048.

The database pool sizes itself from the host’s core count, and on a host with many cores the pool alone reaches that ceiling. The server then fails during startup:

Critical error starting server: I/O error: Resource temporarily unavailable (os error 11)

That EAGAIN comes from thread creation, not from the database. Because db_pool_max_workers defaults to 2,048, a 32 core host asks for 2,048 pool threads before the tokio workers and the RocksDB background jobs, and all of them count against the one cgroup limit.

Tuwunel warns when it can see that collision coming, naming both numbers:

WARN The database pool may exceed this container's task limit; raise the task limit
(--pids-limit for docker and podman) or lower db_pool_max_workers.
total_workers=2048 max_tasks=2048

Either remedy works. Raising the runtime’s limit keeps the pool at full size:

RuntimeSetting
Docker, Podman--pids-limit=16384
Podman quadletPodmanArgs=--pids-limit=16384
docker composepids_limit: 16384
Kubernetesthe node’s podPidsLimit

Lowering the pool instead costs some read concurrency and nothing else:

-e TUWUNEL_DB_POOL_MAX_WORKERS=512

seccomp, and what it costs io_uring

The default seccomp profiles of both Podman and Docker allow none of the three io_uring syscalls, so io_uring_setup fails inside a container: ENOSYS under Podman, EPERM under Docker.

This is harmless. The database engine reads either answer as io_uring being unavailable and falls back to synchronous reads, per thread, without interrupting startup. A container that never touches its seccomp profile is a fully working homeserver that gives up some read performance.

To get io_uring back, add those three syscalls to the runtime’s own default profile rather than switching the filter off. Deriving the profile from the installed default keeps it from going stale as that default gains syscalls:

jq '.syscalls += [{"names":["io_uring_enter","io_uring_register","io_uring_setup"],
                   "action":"SCMP_ACT_ALLOW"}]' \
   /usr/share/containers/seccomp.json > tuwunel-seccomp.json

podman run --security-opt seccomp=./tuwunel-seccomp.json ...

docker/seccomp-io-uring.sh in the source tree is the same command with a usage message. Docker compiles its default profile in rather than installing it, so the file above serves Docker too; where containers-common is absent, pass a copy of moby’s profiles/seccomp/default.json instead.

--security-opt seccomp=unconfined also restores io_uring, by discarding the whole syscall filter along the way. The generated profile differs from the runtime’s default by one allowed syscall group.

AppArmor and SELinux do not gate io_uring

AppArmor mediates io_uring only for rings created with SQPOLL. The database engine asks for SINGLE_ISSUER and DEFER_TASKRUN and never for SQPOLL, so apparmor=unconfined is neither needed nor sufficient. Measured on Debian 13 with kernel 6.12, under rootful Podman with containers-default enforcing and under Docker with docker-default enforcing:

AppArmorseccompring the engine createsan SQPOLL ring
enforcingruntime defaultfailsfails
unconfinedruntime defaultfailsfails
enforcingthe profile abovesucceedsPodman denies it

Only the last row distinguishes the two, and only for a ring tuwunel does not create: containers-default grants no io_uring sqpoll permission and docker-default does. Nothing in the engine’s path depends on it.

Rootless Podman applies no AppArmor profile at all, so the option changes nothing there either.

An unlimited memlock and CAP_IPC_LOCK are equally unnecessary. Ring memory has been charged to the cgroup rather than to RLIMIT_MEMLOCK since Linux 5.12, and a ring still initializes with memlock set to zero.

Under SELinux, a bind-mounted database directory needs a label the container can write to, which the :Z volume suffix applies:

podman run -v /srv/tuwunel:/var/lib/tuwunel:Z ...

A named volume is labeled correctly without the suffix. Confinement of a host install is separate from all of this and is documented per package: the RPM ships an SELinux policy module, and the Debian package ships an AppArmor profile.

Authentication systems

Tuwunel gives you fine-grained control over who can register and how users authenticate. This chapter covers everything from basic password login and token-based invitations to the built-in OAuth 2.0 / OpenID Connect server that powers next-generation Matrix auth.

  • Legacy Authentication: control who can register, token-based invitations, guest access, and the basic password and token login options.

  • OIDC Authorization Server: Tuwunel’s built-in OAuth 2.0 / OIDC server for next-generation Matrix clients. It fronts the identity providers below and adds refresh-token, device-grant, and account-management support.

  • Identity Providers: single sign-on through GitHub, Google, Keycloak, and other upstream OAuth/OIDC providers. These also supply the human authentication step for the OIDC server above.

  • LDAP Delegation: delegate user management and password authentication to an LDAP directory.

  • Enterprise JWT: an operator-controlled signing key that can mint a token authenticating as any user.

  • Migrating Databases: preserve provider sign-in to migrated accounts after a supported database migration. The one-time association procedure does not apply to databases created by Tuwunel.

Legacy Authentication

By default, registration is disabled. You must explicitly enable it and choose what conditions, if any, a prospective user must meet before an account is created.

Enabling registration

Set allow_registration = true to enable registration. On its own this is not enough; you must also configure at least one of the following:

  • A registration token (recommended)
  • Required email at registration, with an SMTP connection_uri set
  • The open-registration confirmation flag (not recommended)

Password registration also needs login_with_password left at its default of true. With it disabled, only identity providers can register new accounts.

Token-based registration

A registration token acts as a shared secret that prospective users must supply when creating an account. This is the recommended approach for private or invite-only servers.

Static token — set a single token directly in the config:

allow_registration = true
registration_token = "o&^uCtes4HPf0Vu@F20jQeeWE7"

File-based tokens — read tokens from a file, one per line or separated by whitespace. Useful for rotating tokens without restarting the server:

allow_registration = true
registration_token_file = "/etc/tuwunel/.reg_tokens"

Both options can be set at the same time; tokens from both are accepted.

Admin-issued tokens — generate short-lived or single-use tokens from the admin room without touching the config file:

CommandDescription
!admin token issueIssue a token with no restrictions.
!admin token issue --onceIssue a single-use token (shorthand for --max-uses 1).
!admin token issue --max-uses <N>Issue a token that expires after N uses.
!admin token issue --max-age <duration>Issue a token that expires after a duration (e.g. 30m, 7d).
!admin token revoke <token>Revoke a token immediately.
!admin token listList all active tokens.

Open registration

To allow anyone to register without a token, you must set an additional confirmation flag that acknowledges the abuse risk:

allow_registration = true
yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse = true

This is not recommended for public-facing servers. Consider token-based registration or SSO providers instead.

Email verification

Tuwunel can verify that a user controls an email address by emailing a single-use confirmation link through your own SMTP relay. No external identity server is involved; each verified address binds locally to one account. Email is the only supported medium (phone-number verification is not supported). Verified email is used for adding an address to an account, resetting a forgotten password, and optionally requiring email at registration.

Point Tuwunel at an SMTP relay and set the sender mailbox. The confirmation link is built from well_known.client, so that must also be set and reachable by your users in a browser:

[global.smtp]
connection_uri = "smtps://noreply%40example.com:password@mail.example.com:465"
sender = "Example <noreply@example.com>"

[global.well_known]
client = "https://matrix.example.com"
OptionDefaultDescription
connection_uri(unset)Connection URL for the outbound SMTP relay. Setting it enables the email subsystem; without it, no mail is sent. Use smtp:// for an unencrypted or STARTTLS connection and smtps:// for implicit TLS. Credentials and host go inline (smtps://user:pass@host:port). The userinfo is URL-encoded, so an @ in the username must be written as %40.
sender(unset)The mailbox verification messages are sent from. Accepts a bare address or a display-name form (Example <noreply@example.com>). Required whenever connection_uri is set.

The subsystem is disabled by default and stays inert until connection_uri is set. If a client asks to verify an email while it is disabled, the request is rejected with M_THREEPID_DENIED.

Requiring email at registration

These options gate registration on a verified email address. Both default to off, and both require the email verification subsystem above to be configured.

OptionDefaultDescription
require_email_for_registrationfalseRequire a verified email address to complete registration. When set, the registration flow does not finish until the user proves control of an email address.
require_email_for_token_registrationfalseRequire a verified email address when registering with a registration token. When set, token-based registration also demands a verified email address.

Guest registration

Guest accounts are anonymous sessions that some clients (e.g. Element) create automatically before a user logs in. Guest registration is separate from normal registration and is disabled by default.

OptionDefaultDescription
allow_guest_registrationfalseAllow guest account creation.
log_guest_registrationsfalseLog each guest registration to the admin room. May be noisy on public servers.
allow_guests_auto_join_roomsfalseAllow guest users to auto-join rooms listed in auto_join_rooms.

Login options

These options control which login methods are accepted regardless of how accounts were created.

OptionDefaultDescription
login_with_passwordtrueAccept username and password login. Set to false to enforce SSO-only login; password registration is then refused too, while identity providers can still register new accounts.
login_via_tokentrueAccept m.login.token login tokens. Disabling this can break SSO flows where the server issues a token to complete the login.
login_via_existing_sessiontrueAllow an authenticated session to mint a login token that a second client can use to log in. Requires interactive re-authentication. Disable if you want to prevent clients from spawning additional sessions this way.

Login rate limits

Password sign-in uses three token buckets. A refused attempt gets M_LIMIT_EXCEEDED, with a retry_after_ms unless a limit’s table is full.

  • Wrong passwords: each account and client address pair has its own budget. An attempt reserves a token before checking the password and returns it on success; wrong passwords and unknown accounts keep it. Once exhausted, that pair is refused until a token refills, including attempts with the correct password. Attempts from another address still have their own allowance. Concurrent attempts each reserve a token, so they cannot bypass the limit.
  • Client addresses: all password attempts from one address share a broader budget across accounts, charged before verification and kept on success too. This bounds password spraying and password-verification work.
  • Successful sign-ins: only a verified password consumes the account’s sign-in budget. Wrong guesses never consume it, but an account that has signed in too often is refused even with the correct password.

Public /login and the built-in OIDC login page share the first two budgets. Password re-entry for sensitive actions (UIAA) has separate failed-attempt and address budgets with the same settings, so public login attempts cannot exhaust its allowance. The successful-sign-in budget does not apply to UIAA. LDAP binds made by /login remain outside these limits; an account not found in LDAP that falls back to local password checking is limited.

IPv4 addresses have individual budgets. IPv4-mapped IPv6 addresses use their IPv4 identity, and other IPv6 addresses share budgets within each /64. Clients sharing a NAT address also share its address budget. By default the address comes from the socket peer. A loopback peer, such as a reverse proxy connecting over loopback or any client of the Unix socket, stands for every client behind it, so its attempts are not limited per address and keep only the failed-attempt and successful-sign-in limits. Behind a reverse proxy, configure http.ip_source, restrict backend access to trusted proxies, and have the proxy replace the selected forwarding header with a verified address; this also applies the address budget behind a local proxy or the Unix socket. Do not accept client-supplied forwarding headers unchanged. A proxy that connects from a non-loopback address, including a container on a bridge network, gives all its users one address and allowance unless it forwards the client address. Password login and password UIAA require the selected source even for loopback peers and peers listed in http.ip_source_trusted_subnets; they do not use those peers’ usual extraction bypass. A missing or invalid selected source refuses authentication. At startup and on reload, a warning says when a Unix socket or loopback listener has no per-address limit.

Each limit has its own config section, shown here with its defaults:

[global.rate_limiting.login.failed]
per_second = 0.17
burst_count = 3

[global.rate_limiting.login.account]
per_second = 0.003
burst_count = 5

[global.rate_limiting.login.address]
per_second = 1.0
burst_count = 20

The failed-attempt budget allows three wrong passwords per account/address pair, then about one attempt every six seconds. The address budget allows 20 attempts across accounts, then one per second. The account budget allows five successful sign-ins, then about one every five and a half minutes. Setting either burst_count or per_second to 0 disables that limit.

Separating addresses prevents guesses from one address from exhausting an account’s allowance at another address. It also means distributed guesses from different addresses have separate failed-attempt budgets. Users sharing an address or IPv6 /64 can still affect one another. Existing sessions and non-password login methods (m.login.token, SSO and JWT) are unaffected.

Each table holds at most 65536 entries in memory and resets on restart. Fully refilled buckets can be removed to make room; buckets still limiting are retained. Full failed-attempt and address tables admit untracked pairs and addresses until room frees up, while retaining limits for existing entries. A full successful-sign-in table refuses untracked accounts. Table exhaustion logs a warning.

Token and session lifetimes

OptionDefaultDescription
login_token_ttl120000Lifetime of m.login.token tokens in milliseconds (default: 2 minutes).
access_token_ttl604800Lifetime of access tokens in seconds for clients that support refresh tokens. After expiry the client is soft-logged-out until it refreshes. jwt.expire_access_token applies it to JWT logins too (default: 7 days).
openid_token_ttl3600Lifetime of OpenID 1.0 tokens in seconds. These are used for Matrix account integrations such as Vector Integrations in Element, not for OIDC/OpenID Connect logins (default: 1 hour).

Emergency password

The emergency password lets you log in to the server bot account (@conduit:<server_name>) when normal access is unavailable — for example, if you have lost access to your admin room.

emergency_password = "F670$2CP@Hw8mG7RY1$%!#Ic7YA"

Remove this option and restart the server once you have regained access — all sessions for the bot account are logged out when it is unset. See the troubleshooting guide for other recovery methods.

OIDC Authorization Server (Next-Gen Auth)

Tuwunel ships a built-in OAuth 2.0 / OpenID Connect authorization server. This is the server side of Matrix “next-generation authentication”: clients that support it talk OAuth to Tuwunel directly instead of using the legacy m.login.password or m.login.sso flows.

Tuwunel plays two roles here, and they are easy to confuse:

  • As an authorization server, Tuwunel is what a Matrix client authenticates against. It issues authorization codes, access tokens, and refresh tokens, and it publishes OAuth discovery metadata. That is what this page documents.
  • As a relying party, Tuwunel can delegate authentication to a configured upstream identity provider (GitHub, Google, Keycloak, Authelia, your own Matrix Authentication Service, and so on), covered on the Identity Providers page. Native authentication instead checks local account passwords.

So the OIDC server is the Matrix-facing OAuth layer, while the actual login happens through either native authentication or an upstream identity provider.

Standards implemented

The authorization server implements the following Matrix proposals and IETF specifications. The MSCs define the Matrix profile; the RFCs define the underlying OAuth behavior.

SpecPurpose
MSC3861Next-generation auth for Matrix, the umbrella proposal
MSC2964OAuth 2.0 authorization-code and refresh-token grants
MSC2965Authorization server metadata discovery and the auth_issuer endpoint
MSC2966Dynamic client registration
MSC2967OAuth 2.0 API and device scopes for Matrix
MSC3824OIDC-aware client hint (oidc_aware_preferred)
MSC4191Account-management URL and actions
MSC4312Cross-signing reset requiring SSO re-authentication
MSC4341Device authorization grant (RFC 8628)
RFC 6749The OAuth 2.0 authorization framework
RFC 8414Authorization server metadata document
RFC 7591Dynamic client registration
RFC 7636Proof Key for Code Exchange (PKCE)
RFC 7009Token revocation
RFC 8628Device authorization grant

Enabling the server

The OIDC server needs a client well-known base URL, which becomes the OAuth issuer URL:

[global.well_known]
client = "https://matrix.example.com"

It then activates once at least one way to authenticate users is configured. Choose either or both:

  1. Native accounts. Set oidc_native_auth = true to let clients register and log in against this server’s own accounts, with no third-party provider (see Native authentication).
  2. An upstream identity provider. Add at least one [[global.identity_provider]] block (see Identity Providers) to broker authentication to an external IdP.

If well_known.client is set but neither source is configured, the server logs a warning at startup and does not start. Legacy SSO (the m.login.sso flow) keeps working regardless.

OIDC server (Next-gen auth) requires `well_known.client` to be configured.

How a login flows

For an interactive (browser) client, the authorization-code grant runs like this:

  1. The client discovers the issuer via /_matrix/client/v1/auth_issuer, then fetches the metadata document to learn every endpoint URL.
  2. The client (registering itself first if needed, see Dynamic client registration) sends the user to GET /_tuwunel/oidc/authorize with a PKCE code_challenge.
  3. Tuwunel validates the request. With native authentication enabled, the browser sees a page offering password login and each configured upstream provider. Otherwise Tuwunel redirects to the default provider’s SSO flow (/_matrix/client/v3/login/sso/redirect/<provider>). A client may request a specific provider with an idp_id query parameter to skip the chooser.
  4. The user signs in with a local password or an upstream provider. Tuwunel finishes the exchange at GET /_tuwunel/oidc/_complete.
  5. Tuwunel returns an authorization code to the client, which the client exchanges at POST /_tuwunel/oidc/token for an access token, a refresh token, and (when openid was requested) an ID token.

The device that results is tagged with the provider that authenticated it, so later step-up actions (see Cross-signing protection) re-authenticate against the same provider.

When native authentication is enabled and the request selects no upstream provider, step 3 serves the local login/registration page at GET /_tuwunel/oidc/native. The user can authenticate against a local account or choose one of the configured providers. The flow rejoins at _complete. See Native authentication.

Endpoints

Discovery

EndpointDescription
GET /.well-known/openid-configurationOIDC discovery document (RFC 8414)
GET /_matrix/client/v1/auth_issuerMatrix auth issuer discovery (MSC2965)
GET /_matrix/client/v1/auth_metadataAuthorization server metadata
GET /_matrix/client/unstable/org.matrix.msc2965/auth_issuerUnstable issuer endpoint
GET /_matrix/client/unstable/org.matrix.msc2965/auth_metadataUnstable metadata endpoint

The metadata document advertises response_types_supported = ["code"], code_challenge_methods_supported = ["S256"], ID tokens signed with ES256, and the three grant types authorization_code, refresh_token, and the device grant.

Authorization server

MethodEndpointDescription
GET/_tuwunel/oidc/authorizeAuthorization endpoint; starts the code flow
GET/POST/_tuwunel/oidc/_completeCompletes authorization after the provider callback; the POST is the approval form’s target
GET/POST/_tuwunel/oidc/nativeNative login/registration page and submission (no upstream IdP)
POST/_tuwunel/oidc/tokenToken endpoint; exchanges codes, refresh tokens, and device codes
POST/_tuwunel/oidc/device_authorizationDevice authorization request (RFC 8628)
GET/_tuwunel/oidc/deviceUser-code verification page
GET/POST/_tuwunel/oidc/device_callbackDevice consent and approval
POST/_tuwunel/oidc/revokeToken revocation (RFC 7009)
GET/_tuwunel/oidc/jwksJSON Web Key Set; public keys for verifying issued JWTs
GET/POST/_tuwunel/oidc/userinfoUserinfo claims for a bearer token
POST/_tuwunel/oidc/registrationDynamic client registration (RFC 7591)

Account management

EndpointDescription
GET /_tuwunel/oidc/accountAccount-management page (MSC4191)

Grant types

Authorization code

The default grant for clients that can open a browser, described in How a login flows above. PKCE with the S256 method is required by default; see oidc_require_pkce.

Device authorization grant (RFC 8628)

For clients that cannot easily host a browser redirect (a TV app, a CLI, a constrained device), Tuwunel supports the device grant. The flow:

  1. The device calls POST /_tuwunel/oidc/device_authorization with its client_id (and optional scope). Tuwunel responds with a device_code, a short human-readable user_code, a verification_uri (/_tuwunel/oidc/device), a verification_uri_complete that embeds the user code, an expires_in, and a polling interval.
  2. The device shows the user the user_code and asks them to visit the verification URI on another device (phone or laptop).
  3. The user opens the page and enters the code, unless the link already includes it. With native_auth enabled, they sign in on the built-in login page. Otherwise, they sign in through the identity provider. A browser already signed in to the built-in login page skips the password (see QR code login).
  4. Tuwunel checks the code after sign-in. The user then approves the request on the consent page.
  5. Meanwhile the device polls POST /_tuwunel/oidc/token with grant_type=urn:ietf:params:oauth:grant-type:device_code and its device_code. Until the user approves, the token endpoint answers authorization_pending; once approved it returns the tokens.

User codes are ten characters drawn from a twenty-letter consonant alphabet and displayed grouped with a single hyphen (for example BCDFG-HJKLM). Input is normalized, so case, spaces, and hyphens entered by the user do not matter. A grant lives for thirty minutes, the suggested poll interval is five seconds, and each grant bounds how many times its code may be brought to the consent step before it self-invalidates.

The device-grant endpoints share the same per-IP throttle as the rest of the OIDC surface (see Rate limiting).

Configuration reference

Every option below is hot-reloadable: changing it in the config and reloading takes effect without a restart. All default to preserving the current open behavior, so an existing deployment is unaffected until you opt in.

Token and session lifetimes

OptionDefaultDescription
access_token_ttl604800Access-token lifetime in seconds (7 days). After expiry a refresh-capable client is soft-logged-out until it refreshes. Shared with legacy refresh-token logins, and with JWT logins under jwt.expire_access_token.
refresh_token_ttl0Refresh-token lifetime in seconds. 0 disables refresh-token expiry entirely. A typical enabled value is 259200 (three days).
refresh_token_idle_onlytrueWhen true, each successful refresh slides the deadline forward, so a session in continuous use never expires. When false, the deadline is fixed at first issuance and the user must re-authenticate after refresh_token_ttl regardless of activity.
refresh_token_hard_logoutfalseWhen false, an expired refresh token is rejected with soft_logout: true, letting the client keep its E2EE keys and resume the same device after re-auth. When true, expiry deletes the device entirely and signals soft_logout: false, so the next session is a fresh device.
refresh_token_reuse_grace15Time in seconds during which a client can retry a refresh after losing the response. Set to 0 to disable this grace window. See the retry behavior below.
refresh_token_reuse_revoketrueWhen true, a refresh token replayed outside the grace window removes the device. When false, the replay is rejected but the device is left intact, which an operator fronting another OAuth client may prefer.

When a client retries with a refresh token that has already been used, Tuwunel can issue a fresh access token and keep the replacement refresh token. This requires the retry to arrive within refresh_token_reuse_grace and the replacement token to still be current and unexpired.

If the replacement token has expired, a retry within the grace window triggers the logout behavior selected by refresh_token_hard_logout. If Tuwunel can no longer look up the replacement token, it rejects the retry without changing anything.

Two requests can also try to refresh the same token at the same time. The request that loses that race can be rejected without revoking the device, even when refresh_token_reuse_grace is 0.

Native authentication

OptionDefaultDescription
oidc_native_authfalseWhen true, the OIDC server serves a login and registration page for clients that select no upstream provider. The login page offers local accounts alongside configured identity providers. Requires well_known.client.

With native auth enabled, an authorization request that selects no provider is served GET /_tuwunel/oidc/native instead of an automatic SSO redirect. With single_sso or sso_custom_providers_page set, the page offers one single sign-on entry for the default provider in place of the provider list. Once a provider is chosen, the request can only finish through that provider. A request with prompt=create opens the registration view. Registration there enforces the same allow_registration, registration-token, and registration_terms policy as the Matrix registration endpoint, and the metadata document advertises prompt_values_supported = ["create"] so clients can offer account creation. With login_with_password = false the page drops its password form and registration view, offering only the configured providers, and create is not advertised. Enabling this knob where the OIDC server was not already running takes effect on the next restart.

Authorization hardening

OptionDefaultDescription
oidc_require_pkcetrueRequire a PKCE code_challenge with the S256 method on the authorization-code grant. The plain method is always rejected regardless of this setting. Disable only as a transition aid for a legacy client that cannot send a challenge.
oidc_require_device_scopefalseWhen false, a client that omits the MSC2967 device scope is assigned a server-generated device id, echoed back in the granted scope. When true, the grant is rejected unless the client supplies its own device scope.
oidc_strict_scopefalseWhen false, an unrecognized scope token is dropped and the narrowed scope is echoed back to the client (RFC 6749). When true, an unrecognized scope is rejected outright. openid and the MSC2967 api and device scopes (both spellings) are always recognized.

Dynamic registration controls

OptionDefaultDescription
oidc_registration_access_token(unset)When set, the registration endpoint requires callers to present this value as an Authorization: Bearer credential. Matrix clients have no way to supply one, so any value here blocks next-gen auth for every ordinary client. Leave it unset unless the only callers are ones you register yourself.
oidc_registration_allowed_redirect_hosts[]When non-empty, every redirect_uri presented at registration must match this list, otherwise the registration is rejected. A redirect_uri with a host matches an entry naming that host; a private-use scheme carries no host (RFC 8252, as in io.element.android:/) and matches an entry naming the scheme. Matching ignores case. Empty imposes no restriction at registration, and vouches for no client.
oidc_registration_require_client_urifalseRefuse a registration that carries no client_uri, so every client is held to the host rules in Accepted redirect URIs. When false, a client may omit it, and one that supplies it is still held to those rules.
oidc_require_client_approvaltrueShow the user an approve/deny page naming the client before an authorization code is issued to a client the operator has not vetted. A client is vetted when its redirect host or private-use scheme appears in oidc_registration_allowed_redirect_hosts.

Rate limiting

A single token-bucket throttle, keyed by client IP, covers the authorize, token, registration, and device-grant endpoints.

OptionDefaultDescription
oidc_rc_per_second0Token-bucket refill rate in requests per second. 0 disables the throttle, preserving open access.
oidc_rc_burst_count0Burst depth: how many requests one IP may make before the refill rate governs. Ignored while oidc_rc_per_second is 0.

Because the key is the client IP, a rate low enough to bite a brute-force attempt can also throttle many legitimate users behind a single NAT. Size the burst with that in mind if you enable it.

Dynamic client registration

Matrix clients that support next-gen auth register themselves with Tuwunel before starting the authorization flow, using RFC 7591 at POST /_tuwunel/oidc/registration. By default no pre-configuration of clients is required: any client that supports dynamic registration can authenticate.

To bound which clients may register, use oidc_registration_allowed_redirect_hosts. It restricts registration to clients whose redirect_uri you list, and ordinary Matrix clients keep working so long as they appear in it. List a web client by host and a mobile client by its private-use scheme, so a deployment serving Element X on both platforms reads:

oidc_registration_allowed_redirect_hosts = ["element.io", "io.element.android"]

Accepted redirect URIs

Registration applies the redirect URI rules of the Matrix specification (MSC2966, after RFC 8252 §7), which tie each redirect_uri to the host of the client’s client_uri. The binding keeps the website a client names consistent with where it receives the sign-in. A request that breaks a rule is refused with HTTP 400 and an invalid_redirect_uri or invalid_client_metadata error whose description names the rule.

No redirect_uri may carry a fragment. Beyond that, what a client may register depends on its application_type:

application_typeRedirect URIRule
web (or absent)httpsNo userinfo; the host is the client_uri host or a subdomain of it.
nativeClaimed https (a universal or app link)The same rule as web.
nativehttp on the loopback interfaceThe host is localhost, an IPv4 loopback address such as 127.0.0.1, or [::1]. No port is registered, and any port is accepted at sign-in.
nativePrivate-use schemeNo authority (com.example.app:/callback, not com.example.app://callback), and the scheme begins with the client_uri host in reverse-DNS order (com.example or com.example.app for https://example.com).

client_uri is optional unless oidc_registration_require_client_uri is set. When present it must be an https URL with a host and no userinfo, and logo_uri, tos_uri and policy_uri must sit on its host or a subdomain, as redirects do. A client that sends no client_uri has no host to share, so its https redirects may name any host and any private-use scheme containing a dot is accepted; the approval page then shows the redirect target as the client’s website.

A web client served from your own domain registers that domain as its client_uri. One that keeps its vendor’s homepage there while redirecting to your domain is refused with redirect_uri host must share the client_uri host, whichever application_type it sends. Configure the client with its own origin: for FluffyChat Web, set website, logoUrl, tos and privacyPolicy in its config.json to URLs on the domain serving it.

Approving an unvetted client

Open registration means anyone can register a client pointing at a redirect target they control, then send one of your users an authorization link for it. Nothing in the registration rules can tell that client apart from a legitimate one: they only require a client’s own metadata to be self-consistent, and an attacker’s metadata describes an attacker’s domain consistently.

So by default Tuwunel asks. When the redirect target of a sign-in is not vetted, the user is shown a page naming the client, its website, and where the sign-in is about to be handed, with Approve and Deny buttons; the authorization code is minted only on Approve. A client counts as vetted when its redirect host or private-use scheme appears in oidc_registration_allowed_redirect_hosts. An initial access token deliberately does not vet anything, because closing registration says nothing about the clients that were already registered when you closed it.

Listing the clients you serve therefore restores a sign-in with no extra step, and is the recommended configuration. Understand what an entry vouches for: a scheme entry covers any app on the device that claims that scheme (RFC 8252 §8.6), and a host entry covers every path on that host, an open redirector or user-content subdomain included.

The prompt is a step a person takes, inside a window sized for a machine: login_token_ttl defaults to two minutes, and a user who leaves the page sitting past it has to start the sign-in again. Raise it on a server that shows the prompt routinely.

Set oidc_require_client_approval to false only if you accept that any registered client can be handed a user’s authorization code on a single click. Tuwunel logs a warning naming the option at startup and on every configuration reload while it is disabled.

Closing registration entirely

oidc_registration_access_token is a stricter control that carries a cost worth understanding before you enable it. RFC 7591 §3 makes the initial access token optional and asks the registration endpoint to allow requests that carry none, and MSC2966 defines no such token, so no current Matrix client sends the Authorization header this gate checks. Set it only where every OAuth client is registered out of band by something you operate, and expect ordinary client logins to stop working.

While it is set, Tuwunel logs a warning naming the option at startup and on every configuration reload, and a client that tries to register is refused with M_FORBIDDEN: A valid initial access token is required; this server has oidc_registration_access_token set. Element X surfaces that as a failure to get an OAuth URL and never reaches the login page. Check the environment as well as the configuration file, since the same option is set by TUWUNEL_OIDC_REGISTRATION_ACCESS_TOKEN and by its CONDUWUIT_ and CONDUIT_ legacy equivalents. !admin server show-config masks the value, so the startup warning is what tells you the option is set.

Account management

Tuwunel serves a built-in account-management page at /_tuwunel/oidc/account for users authenticated through the OIDC server. From it a user can:

  • View their active OIDC sessions and see which client and identity provider each belongs to
  • Sort their sessions by name, device ID, IP address, or last activity
  • End individual sessions, or select several and end them together
  • Edit their profile

To end several sessions together, confirm your selection within login_token_ttl (two minutes by default) of signing in to the account-management page. If that time has passed, sign in again and select the sessions again.

The page URL is advertised to clients as account_management_uri in the authorization server metadata (MSC4191).

Cross-signing protection

Devices created through the OIDC server are tracked as OIDC devices. When such a device tries to reset cross-signing keys, Tuwunel requires the user to re-authenticate through the original identity provider using the SSO step of the interactive-auth flow (MSC4312). A client that has lost control of an access token therefore cannot reset cross-signing without the user actively logging in again at the provider.

Administrators can see which devices are OIDC devices through the OAuth admin query commands.

Signing keys

On first startup Tuwunel generates and persists an ECDSA (ES256) signing key. The public half is published at /_tuwunel/oidc/jwks and is used to verify the ID tokens issued by the token endpoint. The key is kept across restarts, so the JWKS URI is stable.

Admin commands

OAuth sessions, provider associations, and revocations are managed from the admin room. The !admin query oauth command family is documented alongside the provider configuration on the Identity Providers page.

QR Code Login

Tuwunel supports the unstable MSC4108 and MSC4388 rendezvous transports for QR code login. A new device and an existing device exchange short-lived handshake messages through a rendezvous session, then the OAuth device authorization grant completes the sign-in.

Requirements

QR code login requires the built-in OIDC authorization server and a configured well_known.client URL. The approving step can use a configured identity_provider. Without one, enable oidc_native_auth to authenticate the approving user against this server’s own accounts.

Configuration

Both rendezvous transports are enabled by default and share one in-memory session pool. These settings are reloadable:

  • rendezvous_enabled defaults to true. It advertises and serves both MSC4108 and MSC4388 rendezvous sessions.
  • rendezvous_session_max_bytes defaults to 4096. It limits one session’s payload size. MSC4388 payloads remain capped at 4096 bytes when this setting is larger.
  • rendezvous_session_ttl defaults to 600. It sets the seconds a session lives after its last write. Devices also time the whole sign-in against the expiry advertised at creation, so the window covers an interactive login on the approval page.
  • rendezvous_max_sessions defaults to 100. It limits concurrent sessions before the oldest is evicted.
  • rendezvous_authenticated_only defaults to true. It requires an access token to create an MSC4388 session. With this setting enabled, the discovery response tells a client without a token that it cannot create a session. MSC4108 remains open.
  • rendezvous_rc_per_second defaults to 10. It sets how many MSC4388 requests each client IP address regains permission to send per second. A zero value is treated as one.
  • rendezvous_rc_burst_count defaults to 20. It sets how many MSC4388 requests each client IP address can send in a burst before waiting for its allowance to refill. A zero value is treated as one.

Both transports share the configured session count, expiry, eviction, and restart behavior. Sessions are held in memory, cleared on restart, and removed lazily after their lifetime expires. Creating a session above the configured count evicts the oldest session. The MSC4388 request limiter is separate from OIDC throttling.

Approving from a signed-in browser

Skipping the password applies to accounts that sign in with a password on this server. With an identity provider, the provider’s own sign-in session decides whether you type anything.

When you sign in with a password on the built-in login page, your browser stays signed in for authentication.oidc.browser_session_ttl seconds, 30 days by default. If you open a new device’s approval page in that browser during this time, you skip the password step. You still need to approve the request.

The lifetime counts from the password sign-in and is not extended by use. Changing your password, deactivating your account or signing out of all devices ends the browser session early.

To approve with a different account, select “Use another account” on the approval page. This signs the browser out and returns you to the login page.

To turn off browser sign-in, set authentication.oidc.browser_session_ttl to 0 in your Tuwunel configuration file and reload the configuration with !admin server reload-config in the admin room. Browsers already signed in then go back to the password page.

Reverse proxies

Do not cache responses under either unstable rendezvous namespace:

  • /_matrix/client/unstable/org.matrix.msc4108/rendezvous
  • /_matrix/client/unstable/io.element.msc4388/rendezvous

For MSC4108, pass the ETag, If-Match, and If-None-Match headers through unchanged. Browser clients also need the server’s Access-Control-Expose-Headers: ETag response header to reach the client unchanged.

Do not compress responses under either namespace. A proxy that compresses a session body has changed its bytes, so it downgrades the strong ETag to a weak one of the form W/"...". The scanning device reads the session, keeps that weakened tag, and sends it back as If-Match when it writes its half of the handshake. If-Match requires a strong match, so the write is refused with 412 and the sign-in fails immediately after the QR code is scanned. Clients report this as a generic error with no further detail.

Tuwunel already sets Cache-Control: no-store, no-transform on every session response, but not every proxy honors it. Session bodies are served as text/plain, which several stock configurations compress by default. In nginx, disable compression for the location:

location /_matrix/client/unstable/org.matrix.msc4108/rendezvous {
    gzip off;
    proxy_pass http://tuwunel;
}

To confirm a proxy is the cause, request a session twice and compare the ETag it returns under Accept-Encoding: gzip against Accept-Encoding: identity. A W/ prefix on the compressed response is the whole diagnosis.

For MSC4388, preserve the Sec-Fetch-* request headers. Tuwunel returns 403 for browser navigation requests to session URLs.

LDAP Authentication

Tuwunel can authenticate password logins against an LDAP directory. When a user logs in with m.login.password, Tuwunel locates them in the directory, verifies the password by binding as that user, and creates a Matrix account on first successful login if one does not yet exist.

LDAP support is a compile-time feature. It is part of the default build; a binary built with --no-default-features needs --features ldap before any of the configuration below has effect.

Enabling LDAP

LDAP is configured under a single [global.ldap] section. The minimum to enable it is the enable flag and a uri:

[global.ldap]
enable = true
uri = "ldaps://ldap.example.org:636"
base_dn = "ou=users,dc=example,dc=org"

The URI scheme decides the transport: ldap:// is plaintext, ldaps:// upgrades to TLS using the system’s installed CAs.

When enable = true, every m.login.password request is routed through LDAP first. Local password authentication still happens as a fallback when the LDAP search returns zero matches — useful for the bootstrap admin account or for service users that should not exist in the directory. If the LDAP search returns two or more matches the login is rejected.

Bind modes

Tuwunel supports three bind strategies, selected by what you put in bind_dn and bind_password_file.

A service account binds to the directory, searches for the user, then Tuwunel re-binds as the user with the supplied password to verify it. This mode is required if you want admin synchronization (see below).

[global.ldap]
enable = true
uri = "ldaps://ldap.example.org:636"
base_dn = "ou=users,dc=example,dc=org"
bind_dn = "cn=ldap-reader,dc=example,dc=org"
bind_password_file = "/etc/tuwunel/.ldap_bind_password"
filter = "(&(objectClass=person)(memberOf=cn=matrix,ou=groups,dc=example,dc=org))"

The bind password is read from bind_password_file rather than placed inline in the config. The file must be readable by the Tuwunel process and must not be empty.

Anonymous search-then-bind

If your directory permits anonymous searches, omit both bind_dn and bind_password_file. Tuwunel skips the initial bind and queries the directory unauthenticated, then re-binds as the user to verify the password.

Direct bind

If bind_dn contains the literal substring {username}, Tuwunel skips the search entirely and binds directly with that DN, substituting the user’s localpart for {username} and using the supplied login password as the bind password:

[global.ldap]
enable = true
uri = "ldaps://ldap.example.org:636"
bind_dn = "cn={username},ou=users,dc=example,dc=org"

This is the simplest mode but has three limitations. It cannot apply a search filter, so anyone in the bind DN’s subtree can log in. Admin synchronization does not work, because Tuwunel never gets a chance to query the directory under a service account. And there is no local-password fallback: that fallback is triggered by a search returning no matches, and this mode runs no search, so every m.login.password request is decided by the directory alone. An account that must keep a working local password, such as a bootstrap admin, cannot log in while direct-bind mode is active.

Configuration reference

FieldDefaultDescription
enablefalseMaster switch for LDAP login. Has no effect unless the binary was built with the ldap feature (on by default).
uri—LDAP server URI. ldap://host:389 for plaintext, ldaps://host:636 for TLS.
base_dn""Subtree under which user searches are rooted.
bind_dn—DN used for the initial bind. Contains {username} for direct-bind mode; otherwise identifies a service account. Omit for anonymous search.
bind_password_file—Path to a file containing the password for bind_dn. Ignored in direct-bind mode (the user’s login password is used).
filter"(objectClass=*)"LDAP search filter applied during user lookup. Supports {username} substitution.
uid_attribute"uid"Attribute that uniquely identifies the user. Returned entries must contain the user’s localpart in this attribute.
admin_base_dn""Subtree for the admin search. Falls back to base_dn when empty.
admin_filter""Filter that selects administrative users. Empty disables admin synchronization entirely. Supports {username} substitution.

The localpart match is case-insensitive — Tuwunel sends a lowercased version of the localpart through {username} substitution and accepts an entry if either the original or lowercased form appears in uid_attribute.

Certificate verification for ldaps:// follows the server-wide allow_invalid_tls_certificates setting rather than any LDAP-specific option. That setting is meant for development and disables verification on every outbound TLS connection, the directory connection included, so an unvalidated certificate is accepted whenever it is on. Leave it off in production: an LDAP simple bind carries the user’s password over that connection.

Admin synchronization

Setting admin_filter to a non-empty value turns the LDAP directory into the source of truth for who is a Tuwunel admin. On every successful LDAP login, Tuwunel runs a second search rooted at admin_base_dn (or base_dn if empty) using admin_filter. Membership in the result set is compared against the user’s current admin status in Tuwunel:

  • In LDAP admin set, not a Tuwunel admin → granted admin.
  • Not in LDAP admin set, currently a Tuwunel admin → admin revoked.
  • Otherwise → no change.

Two examples:

# Admins are users with a custom objectClass.
admin_filter = "(objectClass=tuwunelAdmin)"

# Admins are members of an LDAP group, looked up under a different subtree.
admin_base_dn = "ou=admins,dc=example,dc=org"
admin_filter = "(uid={username})"

Admin synchronization only runs in the search-then-bind modes. In direct-bind mode the admin search is silently skipped; manage admins manually with !admin users make-user-admin and !admin users revoke-admin if you need that combination.

Account lifecycle

The first time a user successfully authenticates against LDAP, Tuwunel auto-creates a local Matrix account for them (the same way Synapse, Nextcloud, and Jellyfin behave). The account is registered with origin "ldap" and a placeholder password value — the local password field is never consulted for an LDAP user, so they can only log in by re-authenticating against the directory.

Subsequent logins reuse the existing account and only update admin status if admin_filter is configured.

Accounts that already existed locally

A directory entry claims any local account sharing its localpart, whatever that account’s origin. If alice registered with a local password before LDAP was enabled, and the directory also holds an entry for alice, her logins are verified by binding against the directory from then on and her local password is no longer consulted. An account created through SSO behaves the same way.

This is deliberate. A directory configured here is treated as an authority on identity, so a successful bind for a localpart establishes that the caller is that user. It also means whoever administers the directory can authenticate as any Tuwunel user whose localpart they are able to add or control. Where directory administrators are not also homeserver administrators, or where filter is scoped more widely than your homeserver’s own user base, narrow filter before enabling LDAP on a server that already has accounts.

Deactivation

Deactivation does not propagate between the two systems in either direction, but it is enforced on both sides at login.

Removing or disabling a user in LDAP prevents future logins and does not deactivate or delete the corresponding Matrix account. Use !admin users deactivate if you also want to remove access to existing sessions and devices.

A Matrix account deactivated with !admin users deactivate is refused at login even when its directory entry is still present and its password still binds successfully. Deactivation also revokes every existing session, so a deactivated user cannot keep using tokens issued before it.

Admin commands for testing

Two admin commands invoke the LDAP code paths directly without going through the login API. They are useful for verifying that filter, uid_attribute, bind_dn, and TLS configuration produce the expected results.

CommandDescription
!admin query users search-ldap @alice:example.orgRun the configured search for a user and print the matching DNs along with their admin status. Returns an empty list if the filter matches nothing.
!admin query users auth-ldap "cn=alice,ou=users,dc=example,dc=org" "<password>"Attempt a direct bind with the given DN and password. Use this to confirm credentials and TLS setup; the password is logged in plaintext to the admin room, so revoke or rotate afterwards.

Both commands are gated by the ldap build feature.

Disabling password login for non-LDAP users

In the search-then-bind modes, Tuwunel falls back to local password verification when the LDAP search returns no matches. To enforce LDAP-only login for everyone (apart from accounts that authenticate via SSO), pair LDAP with a restrictive filter that matches every legitimate user, and remove or invalidate local passwords for accounts that should no longer be able to log in directly. Direct-bind mode already has no fallback, so it enforces this on its own.

Warning

Setting login_with_password = false blocks LDAP logins as well as local password logins. Keep password login enabled if your users sign in through LDAP. With it disabled, only identity provider, JWT, token and appservice logins remain available.

JSON web token for enterprise

Tuwunel can accept signed JSON Web Tokens as proof of identity, both as a login flow (POST /_matrix/client/v3/login with type = org.matrix.login.jwt) and as a User-Interactive Authentication step for sensitive operations.

This is an enterprise feature intended for managed deployments where identity is owned by an external system. Two typical uses:

  • Externalized user management. A hosting provider or corporate identity service mints short-lived JWTs for its users; Tuwunel becomes a stateless consumer of those tokens and creates Matrix accounts on first login.

  • Account override. An operator-controlled signing key can mint a token that authenticates as any user for password resets, key recovery, or legal compliance without modifying the user’s credentials.

JWT login requires the jwt_login build feature, which is included in the default build. If you build without the default features and need JWT login, include jwt_login in your feature selection.

Warning

A binary built without jwt_login refuses to start with enable = true in [global.jwt].

Enabling JWT

The minimum configuration to accept JWTs is enable = true and a key:

[global.jwt]
enable = true
key = "yJKn0!E2g$5Hs!rUv9NQwL@ZmpQ3xVT"

With these defaults, Tuwunel will accept any HS256-signed token whose sub claim is the localpart of an MXID on this server.

POST /_matrix/client/v3/login then accepts:

{
  "type": "org.matrix.login.jwt",
  "token": "<jwt>"
}

GET /_matrix/client/v3/login advertises the flow as long as enable = true.

The sub (subject) claim is the localpart of the user’s MXID. Tuwunel combines it with this server’s server_name to form the full MXID. The subject is lowercased before lookup.

For a server with server_name = "matrix.example.org", a token with "sub": "alice" authenticates as @alice:matrix.example.org. The token issuer must agree with the server on this naming.

Configuration reference

FieldDefaultDescription
enablefalseMaster switch for JWT login. Also gates the UIAA flow.
key""Verification key. Plaintext, base64, or PEM depending on format. Sensitive: keep private when used as an HMAC secret.
format"HMAC"One of HMAC, B64HMAC, ECDSA, EDDSA, in any case (HMACB64 is also accepted for B64HMAC). Selects how key is decoded.
algorithm"HS256"JWT alg header value. Must be compatible with format.
register_usertrueAuto-create a Matrix account on first valid login if the user doesn’t already exist. Set to false to require pre-existing accounts.
expire_access_tokenfalseExpire the access token of a JWT login after access_token_ttl and withhold its refresh token, so the token issuer decides how long a login lasts. See Session lifetime.
audience[]Optional list of accepted aud claim values. When non-empty, tokens must claim at least one entry; aud becomes a required claim.
issuer[]Optional list of accepted iss claim values. When non-empty, tokens must claim at least one entry; iss becomes a required claim.
require_expfalseIf true, tokens without an exp claim are rejected. Defaults to false for Synapse compatibility.
require_nbffalseIf true, tokens without an nbf claim are rejected.
validate_exptrueWhen exp is present, enforce that the token has not expired.
validate_nbftrueWhen nbf is present, enforce that the token has reached its validity window.

key is also accepted under the alias secret to match Synapse config files.

Migrating from Synapse

Synapse’s JWT support uses a configuration of similar shape. To migrate a Synapse experimental_features.jwt_config block:

SynapseTuwunel
enabledenable
secretkey (also accepted as secret for direct migration)
algorithmalgorithm
audiencesaudience
issuerissuer (now a list; wrap a single value as ["..."])

Synapse defaults to optional exp/nbf and accepts the localpart in the sub claim. Tuwunel matches both behaviors out of the box, so a straight key+algorithm port should authenticate the same set of tokens.

Account lifecycle

The first time a token authenticates as a user that does not yet exist:

  • If register_user = true, Tuwunel creates the account with origin "jwt" and a placeholder password marker. The local password field is never read for a JWT-authenticated user; they can only re-authenticate by presenting another valid JWT.
  • If register_user = false, the request fails with M_NOT_FOUND and the account is not created.

Subsequent logins reuse the existing account. A deactivated account is refused with M_USER_DEACTIVATED, as it is for password login; a valid token does not bring it back.

JWT does not synchronize admin status, group membership, or display names; the token grants login only. If you need ongoing identity attribute synchronization, use LDAP or an OIDC identity provider instead.

Session lifetime

A JWT is checked once, at login. The session it opens then follows the usual rules: the access token never expires unless the client asks for a refresh token, and a refresh token keeps the session going for as long as it lasts, which by default is indefinitely. The JWT’s own exp has no say, so a login can far outlast the token that opened it.

Warning

A client that cannot obtain a fresh JWT would be signed out for good. This is why expire_access_token is off by default.

When you enable the option, remove the devices of earlier sessions once. With the option enabled, a JWT login retires its device’s refresh token. A client that only refreshes never logs in again and can keep refreshing. An access token issued without an expiry also keeps working.

Set expire_access_token to let the token issuer decide instead:

[global.jwt]
enable = true
key = "..."
expire_access_token = true
require_exp = true

Every JWT login then gets an access token that expires after access_token_ttl, and no refresh token, even when the client asks for one. Once the token expires the client is soft-logged-out: its requests fail with M_UNKNOWN_TOKEN and soft_logout: true, and it keeps its device and encryption keys. To stay signed in, it logs in with a fresh JWT and the same device_id.

The option also has limits to plan around:

  • The lifetime is server-wide. It comes from access_token_ttl in [global.authentication] (7 days by default), not from the JWT’s exp, and the same setting governs every session holding a refresh token.

  • The JWT itself must expire. A client can log in again with any JWT that is still valid, so have the issuer set exp, and keep require_exp = true to refuse a token without one.

  • Other sign-in routes stay open. Password, LDAP and SSO logins keep their usual lifetimes. A fresh JWT also passes the interactive authentication of /login/get_token, and the login token it yields opens a session outside this option. To hold a JWT-only deployment to the issuer’s decision, close both:

    [global.authentication.login]
    via_existing_session = false
    with_password = false
    

    with_password = false also turns off LDAP sign-in.

UIAA: JWT for account override

When enable = true, the m.login.jwt UIAA stage becomes available alongside m.login.password and m.login.sso for sensitive operations that require interactive re-authentication (deactivate account, change password, add 3PID, etc.).

A JWT presented at the UIAA stage validates the user but does not auto-register: the token’s subject must already exist as a Matrix account. This restriction prevents an account-override flow from accidentally creating new accounts when an operator intends only to substitute identity for an existing one.

A typical operator workflow for a forced password reset:

  1. Sign a JWT with sub set to the target user’s localpart.

  2. Submit it as the auth field of POST /_matrix/client/v3/account/password. The request must carry an access token; without one it is refused with 401 M_MISSING_TOKEN. An operator with no session can open one by logging in with a JWT for the same user (org.matrix.login.jwt, above). That login adds a device to the user’s account, so log it out (POST /_matrix/client/v3/logout) once the password is changed.

    {
      "auth": {
        "type": "org.matrix.login.jwt",
        "token": "<jwt>"
      },
      "new_password": "<new password>"
    }
    
  3. Tuwunel validates the signature, confirms the user exists, and completes the password change without ever consulting the user’s existing credentials.

Limit access to the signing key accordingly. Anyone with the HMAC secret, or the matching ECDSA/EdDSA private key, can authenticate as any user on the server.

Key formats and algorithms

format selects how key is interpreted. algorithm selects the JWT signing algorithm. The two must agree. Format names are case-insensitive. HMACB64 is also accepted for B64HMAC.

Warning

While enable = true, Tuwunel refuses to start or reload its configuration if key is empty or format is not one of the supported names below.

If key cannot be decoded or algorithm does not suit the format, Tuwunel reports the error at each login instead.

FormatAlgorithmKey content
HMAC (default)HS256, HS384, HS512Plaintext shared secret.
B64HMACHS256, HS384, HS512Base64-encoded shared secret, in the standard alphabet (+ and /) with = padding. Use this when the secret contains non-printable bytes.
ECDSAES256, ES384PEM-encoded ECDSA public key.
EDDSAEdDSAPEM-encoded Ed25519 public key.

For asymmetric formats (ECDSA, EDDSA) the key is the public key: Tuwunel only verifies, it never signs. The corresponding private key stays with the issuer.

# HMAC shared secret (Synapse-compatible default)
format = "HMAC"
algorithm = "HS256"
key = "..."

# ECDSA public-key
format = "ECDSA"
algorithm = "ES256"
key = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----"""

Time-bounded tokens

exp (expiration) and nbf (not-before) follow the spec semantics: seconds since the Unix epoch. Configure based on the issuer’s behavior:

  • Issuer always sets exp: set require_exp = true to reject any token without an expiration. validate_exp is true by default.
  • Issuer never sets exp: leave both require_exp and validate_exp at their defaults; tokens without exp are accepted as non-expiring (use cautiously).
  • Mixed: leave require_exp = false and validate_exp = true (the defaults). This is Synapse-compatible: exp is optional but enforced when present.

nbf is symmetric with exp and most deployments leave it unset on both issuer and consumer.

Audience and issuer validation

By default no aud or iss validation is performed. To restrict acceptance to tokens issued by, or destined for, specific systems, set the respective config field:

audience = ["https://matrix.example.org"]
issuer   = ["https://idp.example.org"]

When set, the corresponding claim becomes required in addition to being checked against the allowed list. Multiple values are treated as “any of these is acceptable.”

Identity Providers

Tuwunel can delegate login to external OAuth/OIDC identity providers. Each configured provider appears as an option on the client’s login page. Users are redirected to the provider to authenticate, then returned to Tuwunel which maps their identity to a Matrix account.

The same providers serve two login paths. Legacy clients use them directly through the m.login.sso flow. Next-generation clients reach them indirectly: Tuwunel’s built-in OIDC Authorization Server is what those clients authenticate against, and it in turn redirects the user to a provider configured here to perform the actual login. A working next-gen setup therefore needs at least one provider on this page plus the issuer URL described on the OIDC server page.

Provider guides

Configuring Tuwunel

Each provider is a [[global.identity_provider]] table in your configuration file. Multiple providers can be configured by repeating the table header. Container users please refer to the section on environment variables instead.

Required fields

FieldDescription
brandBrand name of the provider: Apple, Facebook, GitHub, GitLab, Google, Keycloak, MAS, Twitter, or any custom string. Case-insensitive. Known brands get built-in defaults and workarounds.
client_idThe OAuth application ID issued by the provider. This becomes the provider’s unique ID within Tuwunel and must never change — Tuwunel associates stored identities to it.

Authentication

FieldDefaultDescription
client_secretnoneOAuth client secret issued by the provider.
client_secret_filenonePath to a file containing the client secret. Ignored when client_secret is also set. Example: /etc/tuwunel/.github_secret

Discovery

FieldDefaultDescription
issuer_urlbrand defaultProvider’s OIDC issuer URL. Pre-supplied for well-known public providers. Required for self-hosted providers. Must match exactly what the provider expects and must never change.
base_pathbrand defaultExtra path after issuer_url leading to the .well-known directory. GitHub uses login/oauth/, for example. Pre-populated for known brands.
discovery_urlnoneFully overrides the .well-known/openid-configuration location. For developers or non-standard providers.
discoverytrueWhether to perform OIDC discovery at all.

Callback

FieldDescription
callback_urlThe callback URL registered with the provider when you created the OAuth application. Must be exactly: https://<your-matrix-server>/_matrix/client/unstable/login/sso/callback/<client_id>

Login behavior

FieldDefaultDescription
defaultfalseMark this provider as the default for /_matrix/client/v3/login/sso/redirect (the endpoint without a provider ID). Required when multiple providers are configured and some clients (e.g. FluffyChat) need a single redirect target. If exactly one provider is configured it is implicitly the default.
namebrandDisplay name shown on the login page. Useful when multiple providers share the same brand.
iconbrand defaultMXC URI for the provider’s icon. Known brands have built-in icons.
scopeopenid email profile; MAS: openidList of OAuth scopes to request. An empty array uses the default shown here. Users can further restrict scopes during authorization.
forward_action_promptfalseForward the action query parameter from the SSO redirect endpoints to this provider as an OpenID Connect prompt. When enabled, action=register makes the upstream authorization request carry prompt=create so the provider shows its registration screen; action=login is left unforwarded. Only enable it for providers that support the OIDC prompt=create (“Initiating User Registration”) extension. See Registration hints.

(Experimental) Multiple providers can share default = true. All must authorize successfully in sequence.

Provider selection for re-authentication

When a user must sign in again through single sign-on (SSO), Tuwunel uses the provider recorded for their device. If the device has no recorded provider and the account is an SSO account on a server with exactly one provider, Tuwunel uses that provider.

If neither case applies, Tuwunel chooses from the account’s linked providers that are still configured on the server. It uses the default provider if the account is linked to it. If not, it uses the first linked provider in configuration order.

User ID mapping

FieldDefaultDescription
userid_claimsallClaims used to compute the Matrix localpart for new registrations. When empty, Tuwunel avoids generated IDs where possible. The special value "unique" forces generated IDs exclusively. The claim "sub" takes precedence over all others when listed.
trustedfalseInverts user matching: instead of registering a new account when claims conflict with existing users, Tuwunel finds the first matching user and grants access to it. Only set this for providers you self-host and fully control. Never use with public providers (GitHub, GitLab, Google, etc.); it enables account takeover. For migrated databases, prefer durable bulk adoption or individual association to temporarily enabling this option. A trusted provider’s email claim is also bound to a new account when it sends no email_verified claim.
unique_id_fallbackstrueWhen no claim maps cleanly to an available username, generate a unique random localpart as a fallback. Set to false on private servers where random usernames are undesirable — a misconfiguration will produce an error instead.
registrationtrueWhether this provider can create new Matrix accounts. Set to false to restrict the provider to existing users only.

A new account takes its display name from the name claim and its avatar from avatar_url or picture. The email claim becomes the account’s email address when the provider sends a true email_verified claim (a boolean, or the string "true"), or when the provider is trusted and sends no email_verified claim. Any other email_verified value counts as unverified. An address another account already holds stays with that account.

URL overrides

These override endpoints that are normally discovered automatically. Only use them for non-standard or undiscoverable providers.

FieldDescription
authorization_urlOverride the authorization endpoint.
token_urlOverride the token endpoint.
revocation_urlOverride the token revocation endpoint.
introspection_urlOverride the token introspection endpoint.
userinfo_urlOverride the userinfo endpoint.

Session

FieldDefaultDescription
grant_session_duration300Seconds the authorization session stays valid before expiring (default: 5 minutes).
check_cookietrueVerify the redirect cookie during the callback for CSRF protection. Disable only if a reverse proxy strips cookies.

Configuring via environment variables

For container deployments (Docker Compose, Podman, Kubernetes) where mounting a configuration file is inconvenient, every provider field can be set via environment variables instead.

The variable name is built from three parts joined by __ (double underscore):

TUWUNEL_IDENTITY_PROVIDER__<index>__<FIELD>
  • TUWUNEL_IDENTITY_PROVIDER — fixed prefix that maps to the [[global.identity_provider]] table array.
  • <index> — an arbitrary string (typically 0, 1, 2, …) that groups variables belonging to the same provider. All variables sharing the same index are treated as a single [[global.identity_provider]] entry. Indexes are sorted lexicographically, so numeric indexes give a predictable order.
  • <FIELD> — the field name from the tables below, uppercased.

Multiple providers are expressed by using different indexes:

# First provider — GitHub
TUWUNEL_IDENTITY_PROVIDER__0__BRAND="github"
TUWUNEL_IDENTITY_PROVIDER__0__CLIENT_ID="Ov23liYourGitHubClientId"
TUWUNEL_IDENTITY_PROVIDER__0__CLIENT_SECRET="your_github_secret"
TUWUNEL_IDENTITY_PROVIDER__0__CALLBACK_URL="https://matrix.example.com/_matrix/client/unstable/login/sso/callback/Ov23liYourGitHubClientId"

# Second provider — Google (marked as default)
TUWUNEL_IDENTITY_PROVIDER__1__BRAND="google"
TUWUNEL_IDENTITY_PROVIDER__1__CLIENT_ID="123456789-abc.apps.googleusercontent.com"
TUWUNEL_IDENTITY_PROVIDER__1__CLIENT_SECRET="GOCSPX-your_secret"
TUWUNEL_IDENTITY_PROVIDER__1__CALLBACK_URL="https://matrix.example.com/_matrix/client/unstable/login/sso/callback/123456789-abc.apps.googleusercontent.com"
TUWUNEL_IDENTITY_PROVIDER__1__DEFAULT="true"

Every field listed in the tables below has a matching environment variable. For example, trusted = true in TOML becomes TUWUNEL_IDENTITY_PROVIDER__0__TRUSTED="true".

Example configurartions

GitHub

[[global.identity_provider]]
brand = "GitHub"
client_id = "Ov23liYourGitHubClientId"
client_secret = "your_github_client_secret"
callback_url = "https://matrix.example.com/_matrix/client/unstable/login/sso/callback/Ov23liYourGitHubClientId"

GitHub’s issuer_url and base_path are pre-configured. client_id doubles as the provider ID in the callback URL.

Google

[[global.identity_provider]]
brand = "Google"
client_id = "123456789-abc.apps.googleusercontent.com"
client_secret = "GOCSPX-your_secret"
callback_url = "https://matrix.example.com/_matrix/client/unstable/login/sso/callback/123456789-abc.apps.googleusercontent.com"

Self-hosted Keycloak

[[global.identity_provider]]
brand = "Keycloak"
client_id = "tuwunel"
client_secret = "your_keycloak_secret"
issuer_url = "https://sso.example.com/realms/myrealm"
callback_url = "https://matrix.example.com/_matrix/client/unstable/login/sso/callback/tuwunel"
trusted = true

With trusted = true, users whose Keycloak username matches an existing Matrix localpart are granted access to that account. Only use trusted when you control the identity provider.

Matrix Authentication Service (MAS)

[[global.identity_provider]]
brand = "MAS"
client_id = "01J44Q10GR4AMTFZEEF936DTCM"
client_secret = "<client_secret>"
issuer_url = "https://auth.example.com"
callback_url = "https://matrix.example.com/_matrix/client/unstable/login/sso/callback/01J44Q10GR4AMTFZEEF936DTCM"

MAS attaches as an upstream provider; Tuwunel remains its own next-generation auth issuer. See the MAS guide for the full topology, the client registration on the MAS side, and why authorization_url must stay unset.

Common setup patterns

Linking existing users to an identity provider

When SSO is added to a server that already has password-based accounts, the central question is: how does Tuwunel know which provider identity belongs to which existing Matrix account?

The most direct approach is to set trusted = true and list "sub" in userid_claims. The sub claim is the stable, globally unique user identifier that every OIDC provider is required to maintain. Listing it in userid_claims tells Tuwunel to use it as the authoritative match key. Marking the provider as trusted then inverts Tuwunel’s normal logic: instead of registering a new account when it finds no existing match, it looks for an existing Matrix account whose localpart equals the sub value and grants access to it. The result is that logging in through the provider seamlessly picks up the user’s existing account:

[[global.identity_provider]]
brand = "Keycloak"
client_id = "tuwunel"
# ...
trusted = true
userid_claims = ["sub"]

For this to work, the sub value the provider returns for each user must match that user’s Matrix localpart exactly. If your provider allows you to set sub to an arbitrary value, aligning it with the Matrix localpart is the cleanest path. If it does not — for example, if sub is an opaque UUID — you can use a different claim (such as preferred_username) as the match key, or pre-register the link with the admin command described below.

Only ever set trusted = true for identity providers you self-host and fully control. In trusted mode, anyone who can present a matching provider identity gains access to the corresponding Matrix account. Public providers such as GitHub and Google must never be trusted.

Admin-approved association for untrusted providers

When the provider is not trusted — a public service such as GitHub or Google where trusted = true would be unsafe — you can still link an existing Matrix account to a specific provider identity by having an admin pre-approve the connection before the user’s next login.

The admin command registers a set of claims to watch for from that provider. When the user next authenticates, Tuwunel checks the claims returned by the provider against any pending approvals. If every claim in the approval matches what the provider returns, the accounts are linked and the approval is consumed.

!admin query oauth associate <provider_id> @alice:example.com \
  --claim sub=550e8400-e29b-41d4-a716-446655440000

Specify whichever claims uniquely identify the user on that provider. sub is the most reliable because every OIDC provider guarantees it is stable and unique per user.

Pending approvals are held in memory, not the database. The affected user must complete their login before the server is restarted, or the command must be run again.

After a supported database migration, stored provider mappings can be adopted in bulk from the source database. This one-time procedure has additional safety requirements and must be completed before migrated users sign in. See Migrating Databases.

How Tuwunel derives Matrix user IDs from claims

When a user authenticates through a provider for the first time and no existing account is linked, Tuwunel must compute a Matrix localpart from the claims in the provider’s userinfo response. It tries each of the following in order, using the first claim that is present and yields a valid, available username:

  1. preferred_username
  2. username
  3. nickname
  4. login
  5. email — only the portion before the @ is used

The sub claim is deliberately excluded from this default sequence because it is typically an opaque identifier rather than a human-readable name. It is only consulted when explicitly listed in userid_claims, where it always takes precedence over every other claim regardless of list order.

If none of these five claims appear in the userinfo response, or if every derived candidate is already taken by another account, Tuwunel falls back to a randomly generated localpart. This fallback is controlled by unique_id_fallbacks, which defaults to true. On private servers where silent random assignment is unacceptable, set it to false — Tuwunel will return an error instead.

Make sure user profiles on your identity provider contain at least one of the five claims above. If a profile has none of them, Tuwunel has nothing to work with and will resort to the random fallback. The safest choice is to ensure preferred_username is populated on every account, as it is the first claim Tuwunel checks and tends to hold a recognisable, human-readable name that also makes a reasonable Matrix localpart.

The userid_claims field lets you restrict which claims Tuwunel considers and in what order. For example, to use only preferred_username and fall back to the local part of the email address, and never silently generate a random ID:

userid_claims = ["preferred_username", "email"]
unique_id_fallbacks = false

Listing "sub" anywhere in userid_claims elevates it to the highest priority, overriding all other entries. The special value "unique" used alone instructs Tuwunel to always generate a unique random localpart and never attempt to derive one from claims at all.

Registration hints for OAuth-aware clients

Clients that implement MSC3824 OAuth-aware login can append an action parameter to the SSO redirect endpoint to signal whether the user means to log in or to register:

/_matrix/client/v3/login/sso/redirect?action=register

Advertise that Tuwunel understands this flow by setting oidc_aware_preferred = true under Global SSO options.

Tuwunel only delegates the account screen to the provider: the hint is honored by forwarding it upstream rather than by rendering a local page. Enable forward_action_prompt on a provider and an incoming action=register is translated to the OpenID Connect prompt=create parameter on that provider’s authorization request: the provider opens its sign-up screen instead of its sign-in screen. action=login and a missing action are left untouched; a prompt you configure through extra_authorization_parameters still applies in those cases, while for action=register the derived prompt=create takes precedence over it.

prompt=create comes from the OpenID Connect “Initiating User Registration” extension, which not every provider implements. A provider that does not support it may ignore the parameter or reject the request, so the option defaults to off. Enable it only after confirming your provider advertises create in the prompt_values_supported field of its OIDC discovery metadata.

Multiple providers

When multiple providers are configured, each appears separately on the client’s login page (unless single_sso = true). The default field controls which provider /_matrix/client/v3/login/sso/redirect (without a provider ID) redirects to:

[[global.identity_provider]]
brand = "GitHub"
client_id = "github_client_id"
# ...
default = true   # this provider handles the bare SSO redirect

[[global.identity_provider]]
brand = "Google"
client_id = "google_client_id"
# ...

If no provider is explicitly default and exactly one is configured, it becomes the implicit default.

Global SSO options

These top-level options control how SSO providers are presented to clients.

OptionDefaultDescription
single_ssofalse(Experimental) Replace the provider list with a single “Sign in with single sign-on” button at /_matrix/client/v3/login/sso/redirect. All providers are attempted in sequence and all must succeed.
sso_custom_providers_pagefalseReplace the provider list with a single button and expect a reverse proxy to intercept /_matrix/client/v3/login/sso/redirect and serve a custom provider-selection page. Each entry on that page should link to /_matrix/client/v3/login/sso/redirect/<client_id>.
oidc_aware_preferredfalseAdvertise OIDC as the preferred login method (MSC3824). Clients that support next-gen auth will present it as the only option.

Admin commands

These admin room commands help manage OAuth state:

CommandDescription
!admin query oauth list-providersList all configured providers and their provider_id.
!admin query oauth list-usersList all users with an active OAuth session.
!admin query oauth list-sessions [--user @user:example.com]List session_id, optionally filtered by user.
!admin query oauth show-provider <provider_id>Show the active configuration for a provider.
!admin query oauth show-user @user:example.comShow OAuth sessions for a user.
!admin query oauth associate <provider_id> @user:example.com --claim key=valueAssociate an existing Matrix account with future OAuth claims from a provider. Useful for onboarding existing users to SSO.
!admin query oauth adopt <provider_id>Adopt stored provider mappings in bulk after a supported database migration. See Migrating Databases.
!admin query oauth revoke <session_id|@user:example.com>Revoke tokens for a session or all sessions of a user.
!admin query oauth delete <session_id|@user:example.com>Remove OAuth state entirely (destructive). Requires the force option.

Protocol flow reference

  1. The client fetches /_matrix/client/v3/login and finds an m.login.sso entry listing configured providers.
  2. The user selects a provider; the client redirects to /_matrix/client/v3/login/sso/redirect/<client_id>.
  3. Tuwunel redirects the user to the provider’s authorization endpoint.
  4. The provider authenticates the user and redirects back to /_matrix/client/unstable/login/sso/callback/<client_id>.
  5. Tuwunel exchanges the code for tokens, fetches user claims, maps them to a Matrix user ID, and issues a login token back to the client. Redirects on the configured client origin or the OIDC redirect allowlist continue directly. Other web and native clients require the user to confirm the destination first.

The public SSO redirect endpoint ignores loginToken. Provider chains carry the authenticated account internally and require the browser grant cookie at every chained step, even when ordinary single-provider cookie checks are disabled for that provider.

Authelia

Authelia configuration

Add the client in Authelia’s config. The client secret in Authelia must be stored as a hash; use the Authelia CLI generator to produce it (the hash always starts with $pbkdf2).

identity_providers:
  oidc:
    claims_policies:
      tuwunel:
        id_token: ["email", "name", "groups", "preferred_username"]
    clients:
      - client_id: '<client_id>'
        client_name: 'tuwunel'
        client_secret: '<client_secret_hash>'
        claims_policy: "tuwunel"
        public: false
        redirect_uris:
          - "https://<your.matrix.example.com>/_matrix/client/unstable/login/sso/callback/<client_id>"
        scopes:
          - 'openid'
          - 'groups'
          - 'email'
          - 'profile'
        grant_types:
          - 'refresh_token'
          - 'authorization_code'
        response_types:
          - 'code'
        response_modes:
          - 'form_post'
        token_endpoint_auth_method: 'client_secret_post'

Tuwunel configuration

Note

The client_secret value here is the plain-text password, not the hash stored in Authelia. Authelia stores the hash; Tuwunel supplies the password.

[[global.identity_provider]]
brand = "Authelia"
name = "Authelia"
client_id = "<client_id>"
client_secret = "<client_secret_password>"
issuer_url = "https://<your.authelia.example.com>"
callback_url = "https://<your.matrix.example.com>/_matrix/client/unstable/login/sso/callback/<client_id>"

See the Authelia OIDC documentation for full details on the provider side.

Authentik

Authentik is a self-hostable identity provider that speaks OpenID Connect.

Note

This guide was written against Authentik 2025.10; the flow is the same on all later versions through at least 2026.2.

Authentik configuration

From the admin interface, navigate to Applications > Applications and select Create with Provider. Review the items below and click Submit.

Application
  • Application name: the user-facing name shown to your users on the Authentik side.
  • Slug: appears in the issuer URL on the tuwunel side. Pick something short and stable, such as tuwunel.
Provider

Select OAuth2/OpenID Provider.

  • Authorization flow: any built-in flow is fine if you have not created custom ones.
  • Client ID and Client Secret: Authentik generates these. Save both values — tuwunel needs them.
  • Redirect URIs/Origins: set this to https://<your.matrix.example.com>/_matrix/client/unstable/login/sso/callback/<client_id>, substituting your Matrix server’s public hostname and the Client ID from the previous step.
  • All other fields can stay at their defaults.
Bindings

Optional. Add policies here to restrict tuwunel access to a subset of your Authentik users.

Tuwunel configuration

Add an [[global.identity_provider]] entry to your tuwunel.toml:

[[global.identity_provider]]
brand = "Authentik"
client_id = "<client_id>"
client_secret = "<client_secret>"
issuer_url = "https://<your.authentik.example.com>/application/o/<slug>/"
callback_url = "https://<your.matrix.example.com>/_matrix/client/unstable/login/sso/callback/<client_id>"

issuer_url is the application’s slug-based path with a trailing slash. This is the value Authentik returns as the iss claim in issued tokens, and tuwunel discovers all other endpoints from <issuer_url>.well-known/openid-configuration automatically.

If your Authentik instance reports a different iss — for example when running behind a path prefix, or with a non-default Issuer Mode on the provider — override discovery directly:

discovery_url = "https://<your.authentik.example.com>/application/o/<slug>/.well-known/openid-configuration"

Tip

For the full set of identity provider options see the providers reference. For the Authentik side, see the OAuth2/OpenID Connect provider documentation.

Customising the Matrix localpart

By default tuwunel derives a new user’s Matrix localpart from the preferred_username claim Authentik returns — see How tuwunel derives Matrix user IDs from claims. The default Authentik mapping populates preferred_username with the user’s Authentik username, so user foo becomes @foo:example.com.

To decouple the two — for example to give Authentik user foo the localpart @bar:example.com — replace Authentik’s default profile scope with a custom property mapping that returns the localpart you want.

Create a custom property mapping

In the admin interface, navigate to Customization > Property Mappings and select Create. Choose Scope Mapping, then set the Scope name to profile.

In Expression, return a dictionary that exposes the desired localpart as preferred_username. The example below uses a per-user matrix_localpart attribute when set, falling back to the Authentik username:

if "matrix_localpart" in request.user.attributes:
    return {
        "name": request.user.name,
        "given_name": request.user.name,
        "preferred_username": request.user.attributes["matrix_localpart"],
        "nickname": request.user.attributes["matrix_localpart"],
        "groups": [group.name for group in request.user.ak_groups.all()],
    }
return {
    "name": request.user.name,
    "given_name": request.user.name,
    "preferred_username": request.user.username,
    "nickname": request.user.username,
    "groups": [group.name for group in request.user.ak_groups.all()],
}

Note the Name you give the mapping, then click Finish.

Replace the default profile mapping

In Applications > Providers, edit your tuwunel provider, expand Advanced protocol settings, and find the Scopes field.

Move your new mapping from Available Scopes into Selected Scopes with the right arrow (>), then move authentik default OAuth Mapping: OpenID 'profile' out with the left arrow (<). Click Update.

Set the attribute on a user

In Directory > Users, edit the user and add to Attributes:

matrix_localpart: bar

Click Update.

Tip

Users can be allowed to set the attribute themselves through a custom prompt in a Stage Configuration flow. See Authentik’s documentation for details.

Verify

In Applications > Providers, open your provider and click Preview. Select the user under Preview for user; the JWT payload should contain the customised localpart:

{
    "preferred_username": "bar",
    "nickname": "bar"
}

Keycloak

Keycloak is a self-hostable OpenID Connect provider.

Keycloak configuration

  1. Create a client on your Keycloak server:

    • Enable Client Authentication.
    • Set Root URL to https://<your.matrix.example.com>.
    • Add a Valid Redirect URI: https://<your.matrix.example.com>/_matrix/client/unstable/login/sso/callback/<client_id>
    • Set Web Origins to https://<your.matrix.example.com>.
  2. Navigate to the Credentials tab and note the Client Secret.

  3. Note the realm you created the client in.

Tuwunel configuration

Important

Ensure your Matrix .well-known values are being served correctly before starting. You can verify them with matrixtest.

Add the following to your tuwunel.toml. Replace the placeholders with the values from your Keycloak client.

[[global.identity_provider]]
brand = "Keycloak"
client_id = "<client_id_in_keycloak>"
client_secret = "<client_secret_from_credentials_tab>"
issuer_url = "https://<your.keycloak.example.com>/realms/<realm_name>"
callback_url = "https://<your.matrix.example.com>/_matrix/client/unstable/login/sso/callback/<client_id_in_keycloak>"
trusted = true

Setting trusted = true allows users whose Keycloak username matches an existing Matrix localpart to log in to that account via SSO. Only use this for identity providers you self-host and fully control — see Linking existing users.

Environment variables

If you prefer environment variables (e.g. in docker-compose.yaml or a tuwunel.env file):

TUWUNEL_IDENTITY_PROVIDER__0__BRAND="keycloak"
TUWUNEL_IDENTITY_PROVIDER__0__CLIENT_ID="<client_id>"
TUWUNEL_IDENTITY_PROVIDER__0__CLIENT_SECRET="<client_secret>"
TUWUNEL_IDENTITY_PROVIDER__0__ISSUER_URL="https://<your.keycloak.example.com>/realms/<realm_name>"
TUWUNEL_IDENTITY_PROVIDER__0__CALLBACK_URL="https://<your.matrix.example.com>/_matrix/client/unstable/login/sso/callback/<client_id>"
TUWUNEL_IDENTITY_PROVIDER__0__TRUSTED="true"

Matrix Authentication Service (MAS)

Tuwunel can integrate with MAS in two independent directions:

  • For login, Tuwunel acts as an OAuth client and MAS is an upstream OpenID Connect identity provider.
  • For provisioning, MAS acts as a client of Tuwunel’s private compatibility API and manages Matrix users, profiles, and devices. It can also authorize cross-signing key replacement.

They can be enabled independently or together. Each direction has its own credential: the OAuth client secret authenticates Tuwunel to MAS, while mas_secret authenticates MAS to Tuwunel. Generate separate, high-entropy values for them.

Integration model

Tuwunel remains the issuer that Matrix clients use for next-generation authentication. Its built-in OIDC Authorization Server redirects users to MAS for authentication, then Tuwunel issues the tokens its clients use.

This differs from MAS’s delegated-authentication topology with Synapse. In particular:

  • MAS access tokens cannot be used directly against Tuwunel. Point clients at Tuwunel’s issuer, not MAS’s issuer.
  • mas_secret does not delegate login or token issuance. It authorizes MAS to call Tuwunel’s private provisioning API and changes which Synapse-compatible account administration routes Tuwunel serves.

Logging in through MAS therefore always requires a [[global.identity_provider]] entry, whether or not provisioning is enabled.

Configure MAS as a login provider

Register Tuwunel in MAS

Add a confidential OAuth client to the MAS configuration:

clients:
  - client_id: 01J44Q10GR4AMTFZEEF936DTCM
    client_auth_method: client_secret_post
    client_secret: <oauth_client_secret>
    redirect_uris:
      - https://matrix.example.com/_matrix/client/unstable/login/sso/callback/01J44Q10GR4AMTFZEEF936DTCM

MAS requires a statically configured client_id to be a ULID, which is 26 characters of Crockford base32. Use the same value for MAS’s client_id, Tuwunel’s client_id, and the final path segment of the callback URL.

The redirect URI must match exactly. client_secret_post is required for this integration because Tuwunel sends the client ID and secret in the form-encoded token request body. MAS supports either client_secret or client_secret_file. See the upstream MAS client configuration for the complete client schema.

Configure Tuwunel

[[global.identity_provider]]
brand = "MAS"
client_id = "01J44Q10GR4AMTFZEEF936DTCM"
client_secret = "<oauth_client_secret>"
issuer_url = "https://auth.example.com"
callback_url = "https://matrix.example.com/_matrix/client/unstable/login/sso/callback/01J44Q10GR4AMTFZEEF936DTCM"
scope = ["openid"]

The issuer_url must exactly match the issuer value returned by MAS’s /.well-known/openid-configuration. This may differ from MAS’s http.public_base when a separate http.issuer is configured. The MAS HTTP listener must serve both its discovery and oauth resources.

Leave authorization_url unset. It overrides the authorization endpoint, not the provider’s base address. OIDC discovery fills it from MAS’s discovery document. Setting it to the MAS root sends users to the account-management page instead of starting an authorization flow.

Scopes and user information

Current MAS discovery advertises the standard openid and email scopes, but not profile. Its userinfo endpoint requires openid and returns sub and username, which is all Tuwunel needs for this login flow.

Tuwunel 1.8.3 defaults an empty scope to ["openid"] when brand = "MAS". Keeping it explicit also makes the configuration work with Tuwunel 1.8.2 and earlier, whose default included profile and was rejected by MAS.

Optional user and device provisioning

MAS can manage its Tuwunel users through the private /_synapse/mas/* API. This is separate from using MAS as an upstream login provider. Login does not use these routes, and provisioning does not make MAS Tuwunel’s token issuer.

Add a high-entropy shared secret to Tuwunel:

[global]
mas_secret = "<provisioning_secret>"

Configure MAS to reach Tuwunel with the same secret:

matrix:
  kind: synapse
  homeserver: example.com
  endpoint: "https://matrix.example.com"
  secret: "<provisioning_secret>"

Set homeserver to Tuwunel’s server_name. Set endpoint to the base URL that MAS can use to reach Tuwunel. MAS also accepts secret_file instead of an inline secret. See the upstream MAS homeserver configuration for the full matrix schema.

MAS currently documents Synapse as its supported homeserver backend. Use kind: synapse with Tuwunel because Tuwunel implements the same modern private API that MAS uses for Synapse. Do not add Synapse’s matrix_authentication_service configuration to Tuwunel. Tuwunel does not ask MAS to introspect client access tokens.

If MAS connects through a reverse proxy, forward /_synapse/mas/* to Tuwunel. It is preferable to use a private network path when one is available. Every request must carry Authorization: Bearer <provisioning_secret>; a missing or incorrect secret receives 403 Forbidden.

Treat mas_secret as an administrator credential. It authorizes MAS to create, update, lock, unlock, deactivate, reactivate, and erase users; replace verified email bindings; change profiles; create, rename, delete, and reconcile devices; and grant bounded authorization for cross-signing key replacement. Keep the API on a restricted network path where possible and replace the secret if it is disclosed. The routes remain registered when mas_secret is unset, but every request to them receives 403 Forbidden.

Provisioning jobs also require a MAS worker. The normal mas-cli server command starts one. Deployments that run the MAS HTTP service without its bundled worker must run a separate mas-cli worker process. See the upstream MAS running guide for its process model.

Provisioning API surface

Tuwunel implements all twelve routes used by MAS’s modern homeserver client:

AreaMethodEndpointOperation
User lifecycleGET/_synapse/mas/is_localpart_availableCheck whether a localpart can be assigned.
User lifecycleGET/_synapse/mas/query_userReturn the Matrix user ID, profile, and account state.
User lifecyclePOST/_synapse/mas/provision_userCreate or update an account, including its display name, avatar, email bindings, and lock state.
User lifecyclePOST/_synapse/mas/delete_userDeactivate an account and optionally erase its data.
User lifecyclePOST/_synapse/mas/reactivate_userReactivate a deactivated account.
ProfilesPOST/_synapse/mas/set_displaynameSet an account’s display name.
ProfilesPOST/_synapse/mas/unset_displaynameRemove an account’s display name.
DevicesPOST/_synapse/mas/upsert_deviceCreate a device, or update its display name when supplied.
DevicesPOST/_synapse/mas/update_device_display_nameReplace an existing device’s display name.
DevicesPOST/_synapse/mas/delete_deviceRemove a device from the account.
DevicesPOST/_synapse/mas/sync_devicesReconcile the local device inventory to the set supplied by MAS.
Cross-signingPOST/_synapse/mas/allow_cross_signing_resetGrant bounded authorization for cross-signing key replacement.

These are unversioned implementation endpoints intended only for MAS. Setting mas_secret also removes selected Synapse-compatible account administration routes that conflict with MAS ownership, matching Synapse’s delegated-auth behavior. See the Synapse Admin API page for the affected routes. Only set it when MAS will manage accounts on this server.

Changing one nonempty mas_secret to another takes effect on configuration reload. Enabling or disabling MAS by crossing between an empty and nonempty value requires a restart so Tuwunel can rebuild the set of account administration routes it serves.

Match MAS-provisioned users

Ensure the MAS worker finishes provisioning each account before that user’s first SSO login. Configure the same self-hosted MAS identity provider as trusted so its username claim can match the existing account:

trusted = true
userid_claims = ["username"]

Only enable trusted mode when issuer_url names the same MAS instance that provisions this server and you operate and fully control it. A trusted provider can authenticate as any existing Matrix account whose localpart matches a returned username. The brand value selects MAS-specific defaults; it does not establish trust or link the provider to mas_secret.

Do not include "sub" in userid_claims for this topology. Tuwunel gives it precedence over username, while MAS provisions accounts by localpart. Leaving userid_claims empty also works because Tuwunel considers username by default, but setting it explicitly avoids an accidental future claim mismatch.

If every account must be provisioned by MAS before login, also set:

registration = false

This makes an SSO login fail instead of creating an account when provisioning has not completed. It only controls registration through this identity provider. Keep the global allow_registration setting disabled as well if every account creation path must go through MAS. If the provider cannot be trusted, use an admin-approved association for each existing user instead.

Environment variables

The equivalent Tuwunel environment variables are:

TUWUNEL_IDENTITY_PROVIDER__0__BRAND="mas"
TUWUNEL_IDENTITY_PROVIDER__0__CLIENT_ID="01J44Q10GR4AMTFZEEF936DTCM"
TUWUNEL_IDENTITY_PROVIDER__0__CLIENT_SECRET="<oauth_client_secret>"
TUWUNEL_IDENTITY_PROVIDER__0__ISSUER_URL="https://auth.example.com"
TUWUNEL_IDENTITY_PROVIDER__0__CALLBACK_URL="https://matrix.example.com/_matrix/client/unstable/login/sso/callback/01J44Q10GR4AMTFZEEF936DTCM"
TUWUNEL_IDENTITY_PROVIDER__0__SCOPE='["openid"]'
TUWUNEL_MAS_SECRET="<provisioning_secret>"
TUWUNEL_IDENTITY_PROVIDER__0__TRUSTED="true"
TUWUNEL_IDENTITY_PROVIDER__0__USERID_CLAIMS='["username"]'

For strict pre-provisioning, also set TUWUNEL_IDENTITY_PROVIDER__0__REGISTRATION="false". For login without provisioning, omit TUWUNEL_MAS_SECRET. Choose TRUSTED and USERID_CLAIMS according to the account-matching policy described above.

Troubleshooting

  • If the browser stops on the MAS account page, remove authorization_url and let discovery provide the authorization endpoint.
  • If MAS reports that profile is not allowed, request only openid.
  • If provisioning calls receive 403 Forbidden, verify that MAS and Tuwunel use the same nonempty provisioning secret and that the request reaches Tuwunel’s /_synapse/mas/* routes.
  • If a provisioned user receives a separate account after SSO, verify trusted = true, userid_claims = ["username"], and that MAS returns the provisioned localpart as username.
  • If MAS never sends provisioning calls, verify that a MAS worker is running.
  • If a client fails at registration with an M_FORBIDDEN error naming oidc_registration_access_token, unset that option. The gate belongs to Tuwunel’s own OIDC server rather than to MAS, it applies to every client regardless of how MAS is configured, and no Matrix client can satisfy it. See Dynamic client registration.

Migrating Databases

Tuwunel migrates supported RocksDB databases in place during the first startup. Deploying covers the supported migration paths, including the database and media steps. This page describes the additional procedure required to preserve provider-based sign-in to migrated accounts.

Complete this procedure after the first successful Tuwunel startup and before migrated users sign in through the provider.

Applicability

Database and account typeRequired action
Database created by TuwunelNo action is required.
Migrated database with only password, LDAP, or JWT authenticationNo action is required for this procedure.
Migrated database containing OAuth or OIDC accountsAdopt the stored provider associations before users sign in.

Prerequisites

  1. Complete the database migration and confirm that Tuwunel starts normally. An in-place migration must retain the original Matrix server name. Changing the server name is not supported.

  2. Configure the same identity provider on Tuwunel as a [[global.identity_provider]] table. It must represent the upstream identity system that issued the stored subjects, including the same issuer and subject namespace.

  3. List the configured providers and note the correct provider_id:

    !admin query oauth list-providers
    

Warning

The source database stores subjects without identifying the provider that issued them. Tuwunel cannot verify your provider selection. If you select a different provider, an unrelated identity with the same subject value could gain access to a migrated account. Do not use bulk adoption if the source provider cannot be confirmed or if the source server changed providers during the lifetime of the database. Use the per-user association procedure instead.

Adopt provider associations

Run the following command once, substituting the confirmed provider ID:

!admin query oauth adopt <provider_id>

If the database does not contain provider mappings in the recognized source format, the command makes no changes and reports:

No foreign identity column was found.

Otherwise, the command scans the stored subject mappings and reports a set of counters:

adopted=412 already=0 collision=1 absent=3 invalid=0

Interpret the result

CounterMeaningNext step
adoptedA new association points the stored subject to the intended Matrix account.None.
alreadyAn existing association points to the intended Matrix account.None. This is expected for previously adopted rows.
collisionAn existing association cannot be confirmed as the intended one.Inspect the warning. Tuwunel preserves the existing association.
absentThe stored local username does not resolve to a usable account.Check for a missing account or stale source record.
invalidThe stored subject or local username is not valid UTF-8.Inspect the source record. Do not assume an association exists.

The command never replaces an existing association. It is safe to rerun with the same confirmed provider after correcting a reported condition. Rows counted as adopted become already on later runs; collision, absent, and invalid rows retain their status until the underlying condition changes.

Running the command with a different provider creates a separate set of associations. It does not replace or remove associations created by an earlier run. If the wrong provider was selected, prevent further provider logins and repair those associations individually before continuing.

Each new association is committed independently. If a database read error causes the command to fail, associations written earlier in the scan remain in place. Correct the read error and rerun the command.

Verify account access

Review every nonzero collision, absent, or invalid count. Then have at least one migrated user sign in through the provider and confirm that the user reaches the original Matrix account with its rooms, profile, and history.

After the first successful provider login, the following command can display the user’s OAuth sessions:

!admin query oauth show-user @alice:example.com

Adopted associations do not appear in either query oauth list-users or query oauth show-user before that first login. Their absence at that stage does not mean that adoption failed.

If a user has already signed in

Without a provider association, the next provider login does not reliably select the migrated account. Depending on the provider configuration, Tuwunel may create a separate account with a claim-derived or generated local username, or it may reject the login. The original account and its data remain intact; existing signed-in clients or configured recovery methods may still provide access.

Before repairing the association, confirm the separate account and the original account:

  1. Display the separate account’s OAuth sessions and identify the session for the migrated provider:

    !admin query oauth show-user @separate:example.com
    
  2. Pass that session ID to the destructive !admin query oauth delete command with its required force option. Deleting only the relevant session preserves any unrelated provider sessions on the account.

  3. Ensure that the affected identity does not begin another provider login before adoption completes. A concurrent login can recreate the conflicting association.

  4. Rerun adoption for the confirmed provider:

    !admin query oauth adopt <provider_id>
    

    Compare the result with the previous run. The adopted count should increase, the collision count should decrease, and the corresponding warning should no longer appear.

This repair changes the provider association only. It does not delete or merge the separate Matrix account, move activity between accounts, or revoke Matrix devices and access tokens. After adoption succeeds, the next provider login reaches the original account. Existing Matrix sessions on the separate account remain active until they are revoked separately.

If bulk adoption cannot be used safely, remove the conflicting OAuth state and follow the per-user association procedure. The pending per-user association must be consumed by a login before Tuwunel is restarted.

Why this procedure is necessary

During the database migration, Tuwunel reads the source subject mappings to restore the state of provider-authenticated accounts. Those mappings contain a provider subject and Matrix local username, but no provider identity. Tuwunel’s durable login association combines the configured provider identity with the subject, so only the operator can select the correct provider.

The adoption command creates that durable association without replacing an existing one. It does not modify the migrated Matrix account or its data.

  • Identity Providers covers provider configuration and the per-user association procedure.
  • Deploying covers the database and media portions of a migration from conduwuit or Conduit.

Multimedia and storage provision

Tuwunel handles media uploads, remote media fetching, thumbnail generation, URL previews, and blurhash generation. This chapter covers configuration for all of these features, as well as the storage backends that back them.

  • Storage providers — Local filesystem and S3-compatible object storage backends.

  • Media management — Commands for inspecting, deleting, and bulk-removing media, including spam response.

Upload limits

OptionDefaultDescription
max_request_size24 MiBMaximum size of a single media upload. Accepts SI/IEC units, e.g. "50 MiB".
max_pending_media_uploads5Maximum number of in-progress asynchronous uploads a single user can have at once.
media_create_unused_expiration_time86400Seconds before an unused pending MXC URI is expired and removed (default: 24 hours).
media_rc_create_per_second10Maximum media-create requests per second from a single user before rate limiting applies.
media_rc_create_burst_count50Maximum burst size for media-create rate limiting per user.
media_upload_min_free_space1 GiBWritable space below which uploads are refused. Accepts SI/IEC units, e.g. "10 GiB". 0 disables the check.

Refusing uploads when storage is short of space

Media is what fills a disk, and by default it is stored beside the database, which cannot be written once the disk is full. So an upload is refused while the filesystem of any local storage provider it would be written to has less space available than media_upload_min_free_space. The space counted is what an unprivileged process may still write, which leaves out the blocks a filesystem reserves for privileged ones; on Unix, per-user quotas are not counted. The size of the upload itself is not counted either: an upload is taken whenever the space available is at least the option’s value, so keep it well above max_request_size.

A refused upload is answered 403 with M_RESOURCE_LIMIT_EXCEEDED before anything is written, and the server logs a warning naming the storage path and the space left on it. The admin_contact the specification requires that error to carry is empty; clients find the server’s contacts through support discovery.

Nothing else is refused. Messages are sent and read as before, existing media is served, and media fetched from other servers, URL previews and thumbnails are still stored. Uploads resume as soon as the space is back, with nothing restarted. A storage provider that is not a directory is never the reason for a refusal, and neither is a filesystem whose available space cannot be read, though the server logs a warning when it cannot read one. Set the option to 0 to turn the check off, for instance on a network mount that reports no free space.

Legacy media endpoints

Matrix spec version 1.11 introduced authenticated media endpoints. The older unauthenticated endpoints are deprecated but some clients and servers still use them.

OptionDefaultDescription
allow_legacy_mediafalseServe the unauthenticated /_matrix/media/*/ endpoints locally. The authenticated equivalents are always enabled.
request_legacy_mediafalseFall back to unauthenticated requests when fetching media from remote servers. Unauthenticated remote media was removed around 2024Q3; enabling this adds federation traffic that is unlikely to succeed.

Thumbnails

Thumbnails are generated on demand from the original and cached. A request for a picture larger than the original is answered with the original itself rather than an upscale.

OptionDefaultDescription
media_thumbnail_max_pixels50000000Largest picture the thumbnailer will decode, in pixels. Anything larger is served without a thumbnail. Applies to uploaded pictures and to frames extracted from video.
media_thumbnail_animatedtrueWhether an animated thumbnail is generated for a picture that carries a frame sequence. Disabled, none is generated; a source served whole in a thumbnail’s place, one cached while it was on, or a peer’s own answer can still animate.
media_thumbnail_max_frames50Frames an animated thumbnail carries at most. A longer source is truncated and loops short rather than being refused one.
media_thumbnail_animated_concurrency4Source jobs admitted for animated thumbnail generation. A job waits for a slot before reading the complete source. On a live request, it remains occupied through source I/O, animated storage, and subsequent still or video work until generation returns. A running blocking worker retains it after request cancellation. Static images and videos enter the same limit because their bytes determine whether animation work is needed. A restart is required to apply a change.

A still thumbnail is a PNG, and is served as image/png under the filename thumbnail.png rather than the content type or name of the file it came from. A request that permits animation, against a picture that carries a frame sequence, is answered with a GIF instead, served as image/gif under thumbnail.gif. Thumbnails already cached before this was true keep the labelling they were stored with; only newly generated ones are relabelled.

Video thumbnails

Image thumbnails need no further configuration. Video thumbnails do: tuwunel decodes no video itself, so an external program supplies the still frame it thumbnails. Clients that upload a video without a thumbnail of their own otherwise leave nothing to preview.

Point media_video_thumbnail_command at a program that reads a video and writes one frame to standard output. With ffmpeg installed:

media_video_thumbnail_command = [
  "ffmpeg", "-loglevel", "error",
  "-i", "{input}",
  "-vf", "thumbnail",
  "-frames:v", "1",
  "-f", "image2pipe", "-c:v", "mjpeg", "pipe:1",
]

The list is an argument vector, not a shell line: the first entry is the program and the rest are its arguments, passed through without a shell. Every argument has these tokens substituted before each call.

TokenValue
{input}Path of a temporary file holding the source video.
{width}Requested thumbnail width.
{height}Requested thumbnail height.

The frame may be PNG, JPEG, WebP or GIF; tuwunel scales and crops it exactly as it would an uploaded picture, and caches the result, so the program runs once per video and size rather than once per request. The ffmpeg thumbnail filter above picks a representative frame rather than the first, which is often black. The frame comes back at the video’s full resolution; feed {width} and {height} to a scale filter if your users post video large enough for that to matter.

A video whose frame cannot be produced is served whole, as it was before any of this, so a failure costs a preview and nothing else. Failures are logged with the program’s own standard error, which is where a misconfigured command reports itself.

OptionDefaultDescription
media_video_thumbnail_command[]Argument vector of the frame-extraction program. Empty leaves videos without thumbnails.
media_video_thumbnail_timeout30Seconds allowed per request, counted from the request rather than the spawn so a queue cannot compound the wait. On expiry the program and anything it spawned are killed.
media_video_thumbnail_concurrency1Programs permitted to run at once. Requests past this wait for a slot. Raise it where cores are spare; a restart is required to apply a change.
media_video_thumbnail_max_size128 MiBLargest video staged for the program. A larger one is served without a thumbnail.
media_video_thumbnail_path<database_path>/tmpDirectory a video is staged in, one file per running program.

Bounding what a video can cost

Everything the program sees comes from an upload, so three limits stand between a crafted file and the host.

media_video_thumbnail_max_size decides which videos are staged at all, and bounds the frame read back: a program offering more is refused rather than truncated into a decode failure. The staged copy is written mode 0600 into media_video_thumbnail_path and removed as soon as the program exits, on the deadline and on a cancelled request alike. That path defaults to a tmp subdirectory of the database rather than the system temporary directory: /tmp is frequently a tmpfs, where staging a large video spends memory rather than disk.

media_thumbnail_max_pixels bounds the decode. A video’s frame arrives at the video’s own resolution, so a file declaring 100000x100000 would otherwise ask the thumbnailer for the memory to hold it. The dimensions are read from the header and checked before any decoder allocates. The default of 50 megapixels is about four 8K frames, budgeted at four bytes per pixel, and the budget is per in-flight request rather than per server, since thumbnail requests are not otherwise limited in number.

The same limit applies to uploaded pictures, where the equivalent file is a decompression bomb, and there it is a tightening: before this existed the effective ceiling was the image decoder’s own 512 MiB allocation default, around 128 megapixels. A picture between that and the new limit will now be served whole instead of thumbnailed. Raise the value if you serve originals that large.

media_video_thumbnail_timeout and media_video_thumbnail_concurrency bound time and parallelism. On expiry the whole process group is killed, not merely the program tuwunel started, so a wrapper script cannot leave its own decoder running. The same happens when the request is cancelled or the server shuts down.

A video the program fails on, or whose frame the thumbnailer then refuses, is left alone for five minutes rather than retried on the next request. Without that, one upload the decoder chokes on would spend a slot on every thumbnail request it received, at any size, and at the default concurrency of one that is the slot every other video is waiting for. Only the program’s own verdict counts: a request that gave up waiting for a slot, or that reached the front of the queue with too little of its deadline left to give the program a fair run, says nothing about the video and is not remembered. The cost is that fixing a misconfigured command does not take effect for already-failed videos until the interval passes.

The decoder’s memory is not tuwunel’s to cap: it is a separate process. Under systemd it is spawned into the service’s cgroup, so a MemoryMax= on the unit covers it. Note what else that covers, though: the cgroup holds tuwunel too, and tuwunel’s own footprint is dominated by the RocksDB block cache, so a limit chosen for the decoder alone will be far below what the server needs and will get the server killed instead. Size MemoryMax= for the whole service, or leave it unset and rely on the limits above.

Shutdown, reload and restart

A running extraction never delays a shutdown past its own deadline, and never outlives the server that started it.

The program runs inside the request that asked for the thumbnail. On shutdown that request is given the client_shutdown_timeout grace period and is then dropped, which kills the program’s process group, releases its slot and unlinks the staged video. A client that disconnects mid-request has the same effect at once. Nothing waits on the program itself, so the stop time is bounded by the grace period rather than by media_video_thumbnail_timeout.

A configuration reload does not disturb work in flight. An extraction already under way keeps the deadline it computed at entry and finishes under it; the next request reads the new values. The two concurrency settings are the exception, as each sizes a semaphore built at startup.

Two cases skip the orderly path. An in-place restart replaces the running image without unwinding, and a SIGKILL gives nothing a chance to run, so either can leave a staged video behind. Tuwunel reclaims those at startup by sweeping its staging directory, which is why that directory should hold nothing else. Under systemd the decoder is in the unit’s cgroup, so stopping the service kills it along with everything else in the unit.

What the program is exposed to

The video handed to the program is whatever someone uploaded, on your server or on any server you federate with, since a remote original cached locally is thumbnailed the same way. That is the point of the feature and it cannot be otherwise, so it is worth being precise about what does and does not stand behind it.

Nothing uploaded is ever executed. The staged file is written without an execute bit, given a random name and no extension, and passed to the program as a path argument; the program itself comes from your configuration and nowhere else. Renaming an executable to .png, or to anything, changes none of that. There is no shell, so no argument in the video’s name or type can be interpreted as one.

What remains is the decoder’s own parsing of hostile input, which is the same exposure ffmpeg carries anywhere it is pointed at untrusted media. Note that the video/ check is on the content type the uploader declared, so it selects which media are worth trying, not which are safe; assume anything can reach the program. Tuwunel keeps it at arm’s length: a separate process, so a crash or a corrupted heap is not in the server’s address space; a deadline; a process group killed as a unit; one slot at a time by default; and a size limit before anything is staged. Under the packaged units the program also inherits the service sandbox, which is the substantial part of this: no capabilities, NoNewPrivileges=yes, the unit’s syscall allow-list, ProtectSystem=strict, PrivateDevices=yes and MemoryDenyWriteExecute=yes, that last one frustrating the usual step from a memory-safety bug to executing anything.

Choose the decoder accordingly, keep it patched, and prefer a build with only the demuxers you need if you have one.

systemd

The packaged units filter syscalls down to @system-service @resources and then subtract several sets, @ipc among them. pipe2 belongs to @ipc, and spawning the program with pipes needs it, so the units add the two pipe calls back:

SystemCallFilter=pipe pipe2

A unit predating this, including one you have customised yourself, does not carry that line, and the spawn fails with EPERM until it does. Add it as a drop-in rather than editing the unit:

# /etc/systemd/system/tuwunel.service.d/video-thumbnails.conf
[Service]
SystemCallFilter=pipe pipe2

Nothing else in the shipped hardening obstructs the program: /usr stays readable and executable under ProtectSystem=strict, and PrivateDevices=yes still provides the /dev/null the program’s standard input is bound to. The staging directory is already writable, through ReadWritePaths on the Debian and RPM units and through StateDirectory= on the Arch one; point media_video_thumbnail_path somewhere else and you must grant that path yourself.

Prefer a decoder you would already trust with remote media. Nothing about the mechanism is specific to ffmpeg: any program that reads a video and writes one frame will do.

Containers

The published images carry no decoder. Installing ffmpeg from Debian, with --no-install-recommends, adds about 470 MB of codec libraries, and bundling that would charge every deployment for a feature that is off by default. So the program is yours to supply. Two ways, and the second needs no image of your own.

Build an image. The published image is built FROM scratch: it holds the tuwunel binary and a CA bundle, and no shell or package manager to install anything with. The binary is statically linked, so start from Debian and copy it in:

FROM debian:trixie-slim
RUN apt-get update \
 && apt-get install -y --no-install-recommends ca-certificates ffmpeg \
 && rm -rf /var/lib/apt/lists/*
COPY --from=ghcr.io/matrix-construct/tuwunel:latest /usr/bin/tuwunel /usr/bin/tuwunel
EXPOSE 8008 8448
ENTRYPOINT ["tuwunel"]
HEALTHCHECK --interval=30s --timeout=15s --start-period=1800s CMD ["tuwunel", "--health-check"]

The last three lines restate what the published image declares, which a new base does not inherit, and ca-certificates stands in for its CA bundle. Podman keeps the HEALTHCHECK only when it builds with --format docker; otherwise pass the probe when you run the container, as Health checking outside a quadlet shows.

Or mount a decoder in. Because tuwunel runs a program rather than linking a library, a statically linked ffmpeg build is just a file the container needs to see:

--volume /opt/ffmpeg:/usr/local/bin/ffmpeg:ro

with media_video_thumbnail_command pointing at /usr/local/bin/ffmpeg. It must be a static build; one taken from the host will look for libraries the image does not have. This keeps you on the published image and adds one file instead of a dependency tree.

Nothing else about the container needs changing. The program is an ordinary child process, so no added capabilities or privileges, and the default seccomp profile permits the pipe calls that the packaged systemd units have to allow back explicitly. Staged videos land in media_video_thumbnail_path, which defaults inside the database directory, so they go to your data volume rather than the container’s writable layer and a read-only root filesystem is no obstacle.

Blocking remote media

prevent_media_downloads_from is a list of regex patterns matched against server names. Tuwunel refuses to download media originating from any matching server.

prevent_media_downloads_from = [
  "badserver\\.tld$",
  "spammy-phrase",
]

This is useful as a reactive measure after a spam incident. See the Management page for bulk-deletion commands to pair with it.

URL previews

URL previews are disabled unless at least one allowlist is configured. The denylist is checked before the allowlists, except that "*" in any allowlist admits every URL without consulting the denylist. The URL Previews page covers user agents, the spider budget, caching, and troubleshooting an empty preview.

OptionDefaultDescription
url_preview_domain_explicit_allowlist[]Exact domain matches allowed for previewing. "google.com" matches https://google.com but not https://subdomain.google.com. Set to ["*"] to allow all domains.
url_preview_domain_contains_allowlist[]Substring domain matches. "google.com" matches any URL whose domain contains that string — including unrelated domains. Set to ["*"] to allow all domains.
url_preview_url_contains_allowlist[]Substring match against the full URL (not just the domain). Set to ["*"] to allow all URLs.
url_preview_domain_explicit_denylist[]Exact domain matches explicitly blocked. The denylist is checked first, unless an allowlist holds "*". Setting to ["*"] has no effect.
url_preview_check_root_domainfalseWhen enabled, a host no allowlist admits is checked again with its first label removed, against the explicit denylist and allowlist. This reaches one level of subdomain only: with wikipedia.org in url_preview_domain_explicit_allowlist, en.wikipedia.org is allowed but en.m.wikipedia.org is not.
url_preview_max_spider_size786432Maximum bytes read from a page when generating a preview (default: 768 KiB). A page whose OpenGraph tags sit past this point yields an empty preview.
url_preview_max_media_size52428800Maximum size of a single media item fetched or relayed for a URL preview: the og:image measurement fetch and the lazy-media relay. Media larger than this is not registered, and an over-cap relay is refused (default: 50 MiB).
url_preview_cache_ttl86400Seconds a generated preview is cached before the page is fetched again, empty previews included (default: 24 hours). Raise it to spare origins in a room whose history is read often, lower it to pick up changed OpenGraph metadata sooner.
url_preview_bound_interface—Network interface name or IP address to bind when making URL preview requests. Example: "eth0" or "1.2.3.4".
url_preview_user_agent—User-Agent header sent when fetching pages to extract their OpenGraph tags. Defaults to the versioned server User-Agent, e.g. "Tuwunel/1.8.1 preview".
url_preview_media_user_agent—User-Agent header sent when fetching and relaying preview media files themselves. Falls back to url_preview_user_agent.

Note

Setting any allowlist to ["*"] opens significant attack surface — a malicious client could cause the server to make requests to arbitrary URLs on the local network. Use explicit allowlists wherever possible.

og:image, og:video, and og:audio (and direct links to image, video, and audio files) resolve to an mxc:// URI on this server rather than the third-party URL, and are not copied into media storage: requests for that mxc:// URI are relayed — the server fetches the source URL on the client’s behalf (subject to the same SSRF/CIDR checks as everything else on this page, and capped at url_preview_max_media_size) and passes the content through, so the third party sees the server’s address rather than the client’s. Images are the exception to the lazy fetch: one is downloaded while generating the preview to measure og:image:width/og:image:height and matrix:image:size, and those bytes are staged so the first client download does not fetch the origin a second time. og:video:width/og:video:height are populated when the page declares them. Clients cache the results themselves per the immutable cache headers on media downloads. A preview’s mxc:// URI is only as durable as its source URL: if the source expires or changes, later fetches reflect that, unlike uploaded media. Upstream error responses are never relayed as media.

Blurhash

Tuwunel can generate blurhashes for uploaded images, which clients use to show a blurred placeholder before the full image loads. This requires the blurhashing compile-time feature.

Blurhash settings live in a dedicated config section:

[global.blurhashing]
components_x = 4
components_y = 3
blurhash_max_raw_size = 33554432
OptionDefaultDescription
components_x4Horizontal detail components. Higher values produce more detailed hashes at the cost of a larger hash string.
components_y3Vertical detail components.
blurhash_max_raw_size33554432Maximum raw image size (after decoding to pixel data) that will be blurhashed, in bytes (default: ~32 MiB). Set to 0 to disable blurhashing entirely. Should be at or above max_request_size to avoid silently skipping large uploads.

Storage providers

Tuwunel stores media through a configurable provider layer that abstracts over local filesystem and S3-compatible object storage. Multiple providers can be active simultaneously, which enables zero-downtime migrations.

Default storage

Without any explicit configuration, Tuwunel stores media in a subdirectory called media/ inside your database_path. This is represented internally as the implicit provider named "media".

# These are the effective defaults — no configuration required
media_storage_providers = ["media"]
store_media_on_providers = []

When store_media_on_providers is empty, all providers in media_storage_providers receive new uploads. With only the implicit "media" provider active, this is simply the local filesystem.

Configuring providers

Providers are declared as TOML sections named [global.storage_provider.<NAME>.<brand>], where <NAME> is the identifier you reference in media_storage_providers, and <brand> is local, s3 or gcs. For container deployments (Docker Compose, Podman, Kubernetes) where mounting a configuration file is inconvenient, please refer to the section on environment variables instead.

Local filesystem

[global.storage_provider.media.local]
base_path = "/var/lib/tuwunel/media"
create_if_missing = false
delete_empty_directories = true
startup_check = true
FieldDefaultDescription
base_pathrequiredAbsolute path to the storage directory.
create_if_missingfalseCreate the directory if it does not exist. Disabled by default to surface misconfiguration rather than silently creating a wrong path.
delete_empty_directoriestrueRemove directories that become empty after a file is deleted.
startup_checktrueVerify the directory is accessible at startup. Failure aborts startup.

S3 and S3-compatible storage

[global.storage_provider.media_on_s3.s3]
bucket = "my-matrix-media"
region = "us-east-1"
key    = "AKIAIOSFODNN7EXAMPLE"
secret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

Alternatively, supply an S3 URL in place of bucket. An s3:// URL sets only the bucket and its path is ignored, so set an object prefix with base_path:

[global.storage_provider.media_on_s3.s3]
url       = "s3://my-matrix-media"
base_path = "prefix"
key       = "AKIAIOSFODNN7EXAMPLE"
secret    = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

S3 configuration reference

FieldDefaultDescription
urlnoneS3 URL such as s3://bucket, or an AWS https:// bucket URL. An s3:// URL sets only the bucket and its path is ignored; an https://s3.<region>.amazonaws.com/<bucket> or https://<bucket>.s3.<region>.amazonaws.com URL also sets the region, and a Cloudflare R2 URL sets it to auto. Values from the URL override bucket and region. Use base_path for an object prefix.
bucketnoneBucket name.
regionus-east-1AWS region where the bucket resides.
keynoneIAM Access Key ID.
secretnoneIAM Secret Access Key. Not logged or serialized.
tokennoneSession token for temporary credentials. Not logged or serialized.
base_pathnonePath prefix inside the bucket. All objects are stored under this prefix.
endpointnoneOverride the S3 endpoint URL. Required for self-hosted S3-compatible services such as MinIO or DigitalOcean Spaces. A dual-stack AWS or Cloudflare R2 url sets its own endpoint, which overrides this one.
multipart_threshold100 MiBFiles at or above this size use the S3 multipart upload API. Accepts SI/IEC unit strings.
kmsnoneSSE-KMS key ARN for server-side encryption.
use_bucket_keynoneEnable S3 Bucket Keys for KMS encryption. Should match the bucket setting.
use_vhost_requestnoneTurn virtual-hosted-style requests on or off. A virtual-hosted AWS url (https://<bucket>.s3.<region>.amazonaws.com) turns them on regardless.
use_httpstrueRequire HTTPS. Set false only for local development with HTTP-only test endpoints.
startup_checktruePing the bucket at startup to confirm connectivity. Failure aborts startup. Set false if the provider may be unavailable during startup.

Google Cloud Storage

[global]
media_storage_providers = ["media_on_gcs"]

[global.storage_provider.media_on_gcs.gcs]
bucket = "my-matrix-media"

This selects GCS for media storage. Credentials resolve from the environment and fall back to the instance metadata server, so on Google Kubernetes Engine or Compute Engine the server can authenticate as the attached service account with no exported key material. Grant that service account roles/storage.objectAdmin on the bucket, or equivalent object permissions.

Use this rather than pointing the s3 provider at https://storage.googleapis.com. The S3-interoperability endpoint accepts only HMAC keys, which are service-account keys, so it cannot use an attached service account. The constraints/iam.disableServiceAccountKeyCreation policy prevents creating the new service-account keys that this setup would require.

An object prefix is set separately, with base_path:

[global.storage_provider.media_on_gcs.gcs]
bucket    = "my-matrix-media"
base_path = "prefix"

A gs://bucket/path URL is not accepted here, because the path component would not be applied as a prefix.

GCS configuration reference

OptionDefaultDescription
bucketNoneBucket name. Required; an unset bucket disables the provider.
base_pathNoneObject prefix within the bucket. Alias: path.
service_account_pathNonePath to a service account key file. Leave unset to use the environment, which on GCE/GKE ends at the metadata server, the keyless and recommended configuration.
application_credentials_pathNonePath to an application default credentials file. Only service-account and authorized-user documents are recognised.
multipart_threshold100 MiBUpload size above which multipart upload is used.
multipart_part_size10 MiBSize of each part within a multipart upload.
startup_checktruePing the provider at startup; failures abort startup. The probe is a listing operation, so it requires storage.objects.list, passes on an empty bucket, and proves neither write nor delete.

Credential file settings are applied to the environment-derived builder. Do not combine service_account_path with GOOGLE_SERVICE_ACCOUNT_KEY; the underlying client rejects simultaneous service-account path and inline-key credentials. Environment service-account credentials take priority over application_credentials_path.

Media redirects (media_allow_redirect) work without a key as well: with no private key configured, signing goes through the IAM signBlob API, where Google holds the key. That path additionally needs the IAM Service Account Credentials API enabled and iam.serviceAccounts.signBlob on the service account.

Self-hosted S3-compatible services

For MinIO, DigitalOcean Spaces, Cloudflare R2, and similar services, set the endpoint field and disable virtual-hosted-style requests if required:

[global.storage_provider.media_on_s3.s3]
endpoint         = "https://minio.example.com:9000"
bucket           = "matrix-media"
region           = "us-east-1"
key              = "minioadmin"
secret           = "minioadmin"
use_vhost_request = false

Environment variables

The variable name is built from four parts joined by __ (double underscore):

TUWUNEL_STORAGE_PROVIDER__<NAME>__<brand>__<FIELD>
  • TUWUNEL_STORAGE_PROVIDER — fixed prefix that maps to [global.storage_provider].
  • <NAME> — the provider name you reference in media_storage_providers (e.g., MEDIA, MEDIA_ON_S3).
  • <brand> — the provider type: LOCAL or S3.
  • <FIELD> — the field name from the tables below, uppercased.

Local filesystem example

TUWUNEL_STORAGE_PROVIDER__MEDIA__LOCAL__BASE_PATH="/var/lib/tuwunel/media"
TUWUNEL_STORAGE_PROVIDER__MEDIA__LOCAL__CREATE_IF_MISSING="false"

S3 example

TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__BUCKET="my-matrix-media"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__REGION="us-east-1"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__KEY="AKIAIOSFODNN7EXAMPLE"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__SECRET="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

GCS example

TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_GCS__GCS__BUCKET="my-matrix-media"

No credential variables: on GCE/GKE the attached service account is used.

Self-hosted S3-compatible example

TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__ENDPOINT="https://minio.example.com:9000"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__BUCKET="matrix-media"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__REGION="us-east-1"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__KEY="minioadmin"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__SECRET="minioadmin"
TUWUNEL_STORAGE_PROVIDER__MEDIA_ON_S3__S3__USE_VHOST_REQUEST="false"

The media_storage_providers and store_media_on_providers lists are top-level settings and follow the standard env var pattern using TOML array syntax:

TUWUNEL_MEDIA_STORAGE_PROVIDERS='["media", "media_on_s3"]'
TUWUNEL_STORE_MEDIA_ON_PROVIDERS='["media_on_s3"]'

Migrating to a new storage provider

To migrate from local storage to S3 (or between any two providers) without downtime:

Step 1 — Add the new provider and list both in media_storage_providers, but direct new writes only to the new one via store_media_on_providers, then restart (a configuration reload refuses a new provider section):

media_storage_providers  = ["media", "media_on_s3"]
store_media_on_providers = ["media_on_s3"]

[global.storage_provider.media_on_s3.s3]
bucket = "my-matrix-media"
region = "us-east-1"
key    = "AKIAIOSFODNN7EXAMPLE"
secret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

Tuwunel now writes new media to S3 and reads from whichever provider holds the file, trying the providers in name order (media before media_on_s3).

Step 2 — Copy existing files to the new provider using the storage sync admin command:

!admin query storage sync media media_on_s3

This copies all objects present in media but absent from media_on_s3.

Step 3 — Once the sync is complete and verified, remove "media" from both lists and restart or reload the configuration:

media_storage_providers  = ["media_on_s3"]
store_media_on_providers = []

Importing media from a Conduit S3 bucket

When migrating from Conduit (see Deployment), media that lived in an S3 bucket rather than on local disk is imported on first boot, the same way filesystem-backed Conduit media is. Point Tuwunel at the source bucket with a named storage provider, and scope your destination so the import does not write back into it.

The example below imports a Conduit S3 bucket into Tuwunel’s own S3 bucket. A local destination works the same way; only the destination provider differs.

[global]
# Read and write normal media only on the destination, so the import does not
# also copy media back into the read-only source bucket.
media_storage_providers = ["media"]

# Name the provider the importer reads Conduit's originals from.
conduit_source_media_provider = "conduit_source"

# Match Conduit's media.directory_structure. The default Deep { length = 2,
# depth = 2 } is shown; for a flat layout (Conduit v0.10.0) set depth = 0.
conduit_media_directory_depth  = 2
conduit_media_directory_length = 2

# Destination: Tuwunel's own media store.
[global.storage_provider.media.s3]
endpoint = "https://s3.example.com"
bucket   = "tuwunel-media"
region   = "us-east-1"
key      = "AKIAIOSFODNN7EXAMPLE"
secret   = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

# Source: Conduit's existing media bucket, read-only during the import.
[global.storage_provider.conduit_source.s3]
endpoint  = "https://s3.example.com"
bucket    = "conduit-media"
region    = "us-east-1"
key       = "AKIAIOSFODNN7EXAMPLE"
secret    = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
base_path = "media"   # Conduit's media.path prefix; omit if it had none

On first boot Tuwunel reads each original from the source bucket and re-uploads it to the destination through its normal media path. The source object key is reconstructed from the content hash using conduit_media_directory_depth and conduit_media_directory_length, so those must match the source Conduit’s media.directory_structure. If Conduit used a path prefix (its media.path), set the source provider’s base_path to it.

A few things to know:

  • Set media_storage_providers to the destination only. Otherwise the importer also writes a second copy of every file back into the read-only source bucket. It is harmless (the key namespaces differ) but wasteful, and it continues for normal uploads afterward.
  • The import is a copy, not a move. The source bucket is left untouched. Once the migration completes and you have verified your media, remove the conduit_source provider and the conduit_source_media_* settings, then delete the old objects from the source bucket at your convenience.
  • A transient bucket error stops the import safely. If the source bucket is unreachable, Tuwunel retries a few times and then aborts startup with a clear message rather than dropping media. Nothing is left half-migrated: fix the bucket and restart, and the import resumes from the beginning. A genuinely missing object (a metadata entry whose file was already deleted) is skipped, not treated as an error.
  • Thumbnails are regenerated, not imported. Only original files are copied; Tuwunel regenerates thumbnails on demand.
  • For path-style requests (Conduit’s bucket_use_path = true), set use_vhost_request = false on the source provider.

Storage admin commands

These commands are available via !admin query storage and operate directly on provider objects. They are useful for diagnostics, manual migrations, and verifying provider state.

CommandDescription
!admin query storage configsList all configured storage provider configurations.
!admin query storage providersList all active storage provider instances.
!admin query storage debug [<provider>]Print debug information for a provider.
!admin query storage show [-p <provider>] <path>Show object metadata for a given path.
!admin query storage list [-p <provider>] [<prefix>]List objects under an optional prefix.
!admin query storage copy [-p <provider>] [-f] <src> <dst>Copy an object. -f overwrites an existing destination.
!admin query storage move [-p <provider>] [-f] <src> <dst>Move (rename) an object.
!admin query storage delete [-p <provider>] [-v] <path>…Delete one or more objects. -v prints each deletion.
!admin query storage duplicates <src_provider> <dst_provider>List objects that exist in both providers.
!admin query storage differences <src_provider> <dst_provider>List objects present in one provider but not the other.
!admin query storage sync <src_provider> <dst_provider>Copy all objects from src that are missing in dst.

Startup checks

These options control what Tuwunel verifies about stored media at startup.

OptionDefaultDescription
media_startup_checktrueScan the media directory at startup. Removes database entries for files that no longer exist on disk (when prune_missing_media is enabled), and upgrades Conduit-era symlinks (when media_compat_file_link is enabled). Disable if startup is slow due to a large media directory and neither check applies to you.
prune_missing_mediafalseDuring the startup scan, delete database metadata for any media file that is missing from disk. Caution: if the storage directory is temporarily inaccessible or miss-mounted, this will permanently destroy metadata for all affected files.
media_compat_file_linkfalseCreate Conduit-compatible symlinks alongside Tuwunel’s media files. Only needed if you intend to switch back to Conduit. Requires media_startup_check = true to take effect.

URL previews

When a client asks for a preview of a link, the server fetches the page, reads its OpenGraph tags, and returns the title, description, and image it found. This page covers turning that on, the request the server makes, and what to do when a site returns nothing useful.

The configuration options themselves are listed in the Multimedia and Storage chapter.

Enabling previews

URL previews require a build with the url_preview feature and at least one non-empty allowlist, a list of domains or URLs you permit the server to fetch. Every preview request is refused when all three allowlists are empty: url_preview_domain_explicit_allowlist, url_preview_domain_contains_allowlist and url_preview_url_contains_allowlist. A build without the url_preview feature refuses previews regardless of the allowlists.

In either case, the server advertises the m.preview_url capability and its unstable name io.element.msc4452.preview_url as disabled, which well-behaved clients read as “do not ask”.

For example, add these domains to the [global] section of the configuration file your server loads to allow previews of YouTube links:

[global]
url_preview_domain_explicit_allowlist = ["youtube.com", "www.youtube.com", "youtu.be"]

Warning

Setting any allowlist to ["*"] allows every URL. That is a large amount of attack surface. A client can then ask the server to fetch anything the CIDR denylist does not already block. Prefer naming the domains you want.

How a preview is produced

  1. The URL is checked against the allowlists and the CIDR denylist.
  2. The page is fetched with the preview client, sending url_preview_user_agent.
  3. The response body is read up to url_preview_max_spider_size and parsed for og: tags, falling back to twitter: card tags and then to the document <title>.
  4. og:image is fetched once to measure its dimensions, then staged.
  5. The result is cached for url_preview_cache_ttl seconds.

Only the first url_preview_max_spider_size bytes are parsed, so a page that puts a large script block ahead of its <head> metadata can be cut off before the tags appear. The parse still succeeds, so the outcome is an empty preview rather than an error, and clients render a card with nothing in it. The default is 768 KiB, which covers the sites that bury their metadata deepest among those worth previewing. Raising it further costs bandwidth on every page that gets truncated, so treat it as a memory and bandwidth bound rather than a per-site compatibility knob.

User agents

Some sites serve their OpenGraph tags only to an agent they recognise as a link-preview crawler, and serve everyone else a page whose tags sit far past any reasonable spider budget. YouTube is the most common example.

If a site previews correctly from other chat platforms but not from Tuwunel, try presenting as one of the crawlers it already knows:

[global]
url_preview_user_agent = "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)"

The match is on the literal token Discordbot/2.0, case sensitive, anywhere in the header. A string that merely mentions the name does not work:

ValueRecognised
Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)yes
Tuwunel/1.8.3 preview Discordbot/2.0yes
Tuwunel (like Discordbot)no, the version is missing
Tuwunel (like Discordbot)/2.0no, the version is outside the parentheses
discordbot/2.0no, the token is case sensitive

url_preview_media_user_agent sets the agent for the media files themselves (og:image, og:video, og:audio, and direct links to media), which some origins gate differently from their pages. It falls back to url_preview_user_agent when unset.

Both options take effect on systemctl reload tuwunel; see Reloading Configuration.

YouTube

Tuwunel handles two YouTube specifics without configuration.

When a page fetch yields nothing usable and the link points at youtube.com, www.youtube.com, m.youtube.com, music.youtube.com or youtu.be, the server retries against YouTube’s oEmbed endpoint, which answers any agent and returns the title, channel name, and thumbnail in under a kilobyte. This is why YouTube links preview on a stock configuration even though the page itself does not expose its tags.

The channel name lands in og:description, since oEmbed carries no description field of its own.

The endpoint lives on www.youtube.com, and the server picks it rather than finding it named on the page, so it is checked against the allowlists like any other URL. Allowlisting only youtu.be therefore previews the link but skips the retry; include www.youtube.com for the fallback to work.

Requests to those hosts also carry a consent cookie, which suppresses the interstitial Google serves in place of the page in some regions.

Setting a recognised crawler user agent is still worthwhile: the page carries the video description, which oEmbed does not, so previews gain a real description rather than the channel name.

Refreshing a cached preview

A preview is cached for url_preview_cache_ttl seconds, 24 hours by default, including an empty one. Changing the user agent or the spider size does not clear what is already stored, so a link that previewed badly keeps doing so until the entry ages out.

Raising the setting spares origins in a room whose history is read often, at the cost of serving metadata a page has since changed; lowering it does the reverse. It costs no unbounded disk either way: previews are metadata living in a column capped at 128 MiB that drops its oldest entries once full, and a longer lifetime does not copy any more media into storage.

Each entry carries the lifetime in force when it was written, so a change applies to previews generated after it, and the column retaining them picks up a longer lifetime at the next restart.

To refetch one URL immediately and overwrite its cache entry:

!admin media preview <url> --no-cache

The command prints the preview the server would return, which makes it the fastest way to tell a fetch problem from a client problem.

Troubleshooting

Work down this list when a link previews as an empty card.

  1. Is the domain allowlisted? An unlisted domain is refused before any request is made.
  2. Is a stale entry cached? Run !admin media preview <url> --no-cache. If that returns a good preview and the client still shows an empty card, the cache was the problem and the client will catch up.
  3. Does the site need a crawler user agent? If --no-cache also returns an empty result, set url_preview_user_agent as above and try again.
  4. Is the page larger than the spider budget? Raise url_preview_max_spider_size, reload, and run the --no-cache command again; if the preview fills in, the budget was the problem. A debug build reports this directly, logging a warning that names the option when a truncated page yielded nothing, but that warning is compiled out of release builds.
  5. Can the server reach the host at all? A failed fetch returns an error rather than an empty preview, and is logged with the status.

What the server relays

og:image, og:video and og:audio resolve to an mxc:// URI on this server rather than the third-party URL, so the third party sees the server’s address rather than the client’s.

An image is fetched once while the preview is generated, to measure its dimensions, and those bytes are staged so the first client download does not refetch the origin. Video and audio are not fetched at preview time at all: only the URL is recorded, and the source is fetched on the first request for that mxc:// URI, subject to the same address checks as every other outbound request.

An og:video or og:audio that declares a non-media type is not relayed. Those point at an embed player page rather than a file, so handing back an mxc:// URI would give the client markup where it expected media.

What the page declared about that video is still reported: og:video:type alongside og:video:width and og:video:height, whether or not the URL itself could be relayed. Clients read the type to show a preview as playable, so the card offers to open the video at its source instead of appearing to be a still image.

YouTube arrives by both routes. Its og:video is an embed page rather than a video file, so a preview taken from the page reports the type the page declares. A preview recovered through oEmbed has no page metadata to report, so for a document oEmbed marks as a video the server supplies the type itself, text/html, describing the player that document embeds. That value is the server’s, not the origin’s, and it is the only thing on that route that tells a client the link is playable.

Because the source is fetched rather than copied, a preview’s mxc:// URI is only as durable as the URL behind it. If the source changes or expires, later fetches reflect that, unlike uploaded media.

Media management

Tuwunel provides a set of admin room commands for inspecting and deleting media. All commands are invoked in the admin room and prefixed with !admin media.

Inspecting media

get-file-info

!admin media get-file-info <mxc_uri>

Returns the stored metadata for a media file: content type, file size, creation time, and which user uploaded it. Useful for investigating a reported file before deciding whether to delete it.

get-remote-file

!admin media get-remote-file <mxc_uri> [-s <server>] [-t <timeout_ms>]

Fetches a remote media file from the originating server and returns its metadata. The actual content is discarded after fetching so the admin room is not flooded. Default timeout is 10 000 ms.

get-remote-thumbnail

!admin media get-remote-thumbnail <mxc_uri> \
  [-s <server>] [-t <timeout_ms>] [--width <px>] [--height <px>]

Like get-remote-file but requests a thumbnail at the given dimensions (default 800×800). Useful for confirming what a thumbnail looks like without sending it to a client.

Deleting media

Delete a single file

!admin media delete --mxc mxc://example.com/AbCdEfGhIjKl

Removes one media file from the database and from storage. Use get-file-info first to confirm you have the right MXC URI.

Delete media referenced by an event

!admin media delete-by-event --event-id $abc123:example.com

Extracts all MXC URIs from the event (including the primary media URL, thumbnail URL, and encrypted file URL) and deletes each one. Returns the number of files deleted. Useful when a user reports a specific message containing unwanted media.

Delete a list of MXC URIs

Paste a code block of MXC URIs into the admin room, one per line:

!admin media delete-list
```
mxc://example.com/AbCdEfGhIjKl
mxc://example.com/MnOpQrStUvWx
mxc://badserver.tld/YzAbCdEfGhIj
```

Errors on individual URIs are ignored. The command returns the total number deleted and the number that failed to parse.

Delete by time range

!admin media delete-range <duration> --older-than
!admin media delete-range <duration> --newer-than

Deletes remote media whose filesystem modification time falls outside the given duration from now. Exactly one of --older-than or --newer-than must be specified.

Duration format: 30s, 5m, 2h, 7d, etc.

By default only remote media is deleted. To also delete locally-uploaded media, append the confirmation flag:

!admin media delete-range 90d --older-than --yes-i-want-to-delete-local-media

Examples:

# Delete all remote media older than 30 days
!admin media delete-range 30d --older-than

# Delete remote media uploaded in the last hour (e.g. after a spam burst)
!admin media delete-range 1h --newer-than

Delete all media from a local user

!admin media delete-all-from-user <username>

Deletes every media file uploaded by the named local user. The username is the localpart only, without the @ or server name. Errors on individual files are ignored.

Delete all media from a remote server

!admin media delete-all-from-server <server_name>

Deletes every cached copy of remote media originating from the given server. This only affects remotely-fetched media by default. To also remove local uploads that somehow reference the server, add the confirmation flag:

!admin media delete-all-from-server <server_name> \
  --yes-i-want-to-delete-local-media

Responding to a spam incident

The full incident playbook (cached-media delete, federation blocks, invite gating, and the per-room policy-server option) lives in Policy and Moderation > Responding to a spam incident. That chapter is the source of truth; refer to it when an incident is in progress.

Voice and videotelephony systems

There are two ways of setting up voice and video calling for use with Matrix:

  • MatrixRTC/Element Call (using a Livekit backend).
  • Legacy Calling (using a TURN backend).

Which of these is right for your homeserver largely depends on your preferred client. Different clients support different calling methods, but the majority of maintained clients that support calling are moving towards using MatrixRTC. It is also possible to use legacy calls and the newer MatrixRTC concurrently.

To set up MatrixRTC/Element Call, see the MatrixRTC documentation.

To set up legacy calling, see the TURN documentation. Note: if you are also setting up MatrixRTC, additionally review the External TURN Integration section of the MatrixRTC documentation.

MatrixRTC/Element Call Setup

MatrixRTC is the modern Matrix calling framework used by Element Call and other recent clients. The media itself is carried by a Selective Forwarding Unit (SFU); Tuwunel does not embed an SFU, so an external one is required. Livekit is the SFU implementation supported here, paired with the lk-jwt-service which issues the access tokens clients use to join Livekit rooms.

This guide shows you how to deploy MatrixRTC/Element Call using Docker and Docker Compose, as Livekit only provides prebuilt Docker images. It is possible to run Livekit using their installation script, however this method is not supported or recommended.

Note

In the following documentation, yourdomain.com is whatever you have set as server_name in your tuwunel.toml. This needs to be replaced with the actual domain. It is assumed that you will be hosting MatrixRTC at matrix-rtc.yourdomain.com. If you wish to host this service at a different subdomain, this needs to be replaced as well.

Note

This guide provides example configuration for Caddy, Nginx, and Traefik reverse proxies. Others can be used, but the configuration will need to be adapted.

1. Set Up DNS

Create a DNS record for matrix-rtc.yourdomain.com pointing to your server.

2. Initial Setup

  1. Create a directory for your MatrixRTC setup, e.g. mkdir /opt/matrix-rtc.
  2. Change into that directory, e.g. cd /opt/matrix-rtc.
  3. The following steps will require a key and a secret, referred to as MRTCKEY and MRTCSECRET hereafter. It is suggested that MRTCKEY is 20 characters and MRTCSECRET is 64 characters. If you have pwgen installed, you can generate these with pwgen -s -1 20 for MRTCKEY and pwgen -s -1 64 for MRTCSECRET. Make a note of these values for use in later steps.

2.1 Create Docker Compose Containers

Note: If you are using plain Docker rather than Docker Compose, skip to step 2.2.

  1. Create and open a compose.yaml file in your MatrixRTC directory, e.g. nano compose.yaml.
  2. Add the following. MRTCKEY and MRTCSECRET should be replaced with the values generated above.
services:
  matrix-rtc-jwt:
    image: ghcr.io/element-hq/lk-jwt-service:latest
    container_name: matrix-rtc-jwt
    environment:
      - LIVEKIT_JWT_BIND=:8081
      - LIVEKIT_URL=wss://matrix-rtc.yourdomain.com
      - LIVEKIT_KEY=MRTCKEY # Random 20 character string
      - LIVEKIT_SECRET=MRTCSECRET # Random 64 character string
      - LIVEKIT_FULL_ACCESS_HOMESERVERS=yourdomain.com # Your server_name from tuwunel.toml
    restart: unless-stopped
    ports:
      - "8081:8081"

  matrix-rtc-livekit:
    image: livekit/livekit-server:latest
    container_name: matrix-rtc-livekit
    command: --config /etc/livekit.yaml
    restart: unless-stopped
    volumes:
      - ./livekit.yaml:/etc/livekit.yaml:ro
    network_mode: "host"
    # Uncomment the lines below and comment `network_mode: "host"` above to specify port mappings.
#    ports:
#      - "7880:7880/tcp"
#      - "7881:7881/tcp"
#      - "50100-50200:50100-50200/udp"

2.2 Create Livekit Configuration

  1. Create and open a livekit.yaml file in your MatrixRTC directory, e.g. nano livekit.yaml.
  2. Add the following. MRTCKEY and MRTCSECRET should be replaced with the values generated above.
port: 7880
bind_addresses:
  - ""
rtc:
  tcp_port: 7881
  port_range_start: 50100
  port_range_end: 50200
  use_external_ip: true
  enable_loopback_candidate: false
keys:
  MRTCKEY: MRTCSECRET

Note

The enable_loopback_candidate option above causes Livekit to include 127.0.0.1 and ::1 as ICE host candidates. It is intended for deployments where the public IP is mapped to the loopback interface on the host. Set it to true if you have that specific topology. If calls fail only for clients on the same LAN as the server, see the Troubleshooting section.

The use_external_ip option above makes Livekit discover the server’s public IP via STUN and advertise it to clients. This suits a host whose public IP is not bound to a local network interface, such as a cloud VM behind 1:1 NAT (AWS, GCP) or a server behind a router.

If the public IP is bound directly to a network interface, which is typical for a VPS (Hetzner, OVH, netcup, and similar), prefer setting the address explicitly. Replace use_external_ip: true with the following, where EXTERNAL_IP is the server’s public IP:

rtc:
  # ...
  use_external_ip: false
  node_ip: "EXTERNAL_IP"

This matters because Livekit, running with host networking, gathers candidate addresses from every interface on the host, including the Docker bridge gateways (docker0 and per-network br-* addresses, typically 172.17.x.x and up). These cannot be reached from outside, but with use_external_ip: true they are still advertised to clients as ICE host candidates, which can delay or prevent calls from connecting. Setting node_ip advertises only the given address; note that it only takes effect while use_external_ip is false. The built-in TURN server (described further below) also allocates its relay addresses at the node IP.

If your server is behind NAT with a dynamic public address, keep use_external_ip: true and add external_ip_only: true to the rtc block to suppress the bridge addresses instead. Livekit looks up the public address only when it starts, so it also needs a restart whenever that address changes; see Calls stop working after some hours.

3. Configure .well-known

Clients discover MatrixRTC through two surfaces, and Tuwunel serves both: the org.matrix.msc4143.rtc_foci key in .well-known/matrix/client, and the client API endpoint GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports that Element Call and Element X query. That endpoint is answered from tuwunel.toml alone, never from a .well-known file another server hosts, so livekit_url belongs in your Tuwunel configuration either way.

3.1. .well-known served by Tuwunel

Follow this step if your .well-known configuration is served by Tuwunel. Otherwise follow Step 3.2.

  1. Open your tuwunel.toml file, e.g. nano /etc/tuwunel/tuwunel.toml.
  2. Find the line reading #livekit_url = "" and replace it with:
livekit_url = "https://matrix-rtc.yourdomain.com"
  1. Ensure that you have [global.well_known] uncommented above this line. .well-known will not be served correctly otherwise.

3.2. .well-known served independently

Follow this step if you serve your .well-known/matrix files directly. Otherwise follow Step 3.1.

  1. Open your .well-known/matrix/client file, e.g. nano /var/www/.well-known/matrix/client.
  2. Add the following to the end of this file:
  "org.matrix.msc4143.rtc_foci": [
    {
      "type": "livekit",
      "livekit_service_url": "https://matrix-rtc.yourdomain.com"
    }
  ]

The final file should look something like this:

{
  "m.homeserver": {
    "base_url":"https://matrix.yourdomain.com"
  },
  "org.matrix.msc4143.rtc_foci": [
    {
      "type": "livekit",
      "livekit_service_url": "https://matrix-rtc.yourdomain.com"
    }
  ]
}

Note

Serving .well-known yourself covers only one of the two discovery surfaces. Set livekit_url in your tuwunel.toml as well, exactly as in Step 3.1, so the rtc/transports endpoint advertises the same focus. Without it that endpoint answers with an empty list and clients report that the server has no MatrixRTC transport, even though your .well-known is correct. If it names a different URL, current clients use that one instead of your .well-known (see Troubleshooting).

4. Configure Firewall

You will need to allow ports 7881/tcp and 50100:50200/udp through your firewall. If you use UFW: ufw allow 7881/tcp and ufw allow 50100:50200/udp.

If you are behind NAT, you will also need to forward 7880/tcp, 7881/tcp, and 50100:50200/udp to livekit.

5. Configure Reverse Proxy

As reverse proxies can be installed in different ways, step-by-step instructions are not given for this section. If you use Caddy, follow step 5.1; Nginx, follow step 5.2; Traefik, follow step 5.3.

5.1. Caddy

  1. Add the following to your Caddyfile. If you are running Caddy in Docker, replace localhost with matrix-rtc-jwt in the first instance, and matrix-rtc-livekit in the second.
matrix-rtc.yourdomain.com {
    # This is matrix-rtc-jwt
    @jwt_service {
        path /sfu/get* /healthz* /get_token*
    }
    handle @jwt_service {
        reverse_proxy localhost:8081
    }
    # This is livekit
    handle {
        reverse_proxy localhost:7880 {
            header_up Connection "upgrade"
            header_up Upgrade {http.request.header.Upgrade}
        }
    }
}
  1. Restart Caddy.

5.2. Nginx

  1. Add the following to your Nginx configuration. If you are running Nginx in Docker, replace localhost with matrix-rtc-jwt in the first instance, and matrix-rtc-livekit in the second.
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name matrix-rtc.yourdomain.com;

    # Logging
    access_log /var/log/nginx/matrix-rtc.yourdomain.com.log;
    error_log /var/log/nginx/matrix-rtc.yourdomain.com.error;

    # TLS example for certificate obtained from Let's Encrypt.
    ssl_certificate /etc/letsencrypt/live/matrix-rtc.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/matrix-rtc.yourdomain.com/privkey.pem;

    # lk-jwt-service
    location ~ ^/(sfu/get|healthz|get_token) {
        proxy_pass http://localhost:8081;

        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    # livekit
    location / {
       proxy_pass http://localhost:7880;
       proxy_http_version 1.1;

       proxy_set_header Connection "upgrade";
       proxy_set_header Upgrade $http_upgrade;

       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-Server $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto $scheme;

        # Optional timeouts per LiveKit
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}
  1. Restart Nginx.

5.3. Traefik

  1. Add matrix-rtc-jwt and matrix-rtc-livekit to your Traefik network:
services:
  matrix-rtc-jwt:
    # ...
    networks:
        - proxy # your traefik network name

  matrix-rtc-livekit:
    # ...
    networks:
        - proxy # your traefik network name

networks:
    proxy: # your traefik network name
        external: true
  1. Configure routing with either of the methods below.

2.1 Labels

services:
  matrix-rtc-jwt:
    # ...
    labels:
        - "traefik.enable=true"
        - "traefik.http.routers.matrixrtcjwt.entrypoints=websecure"
        - "traefik.http.routers.matrixrtcjwt.rule=Host(`matrix-rtc.yourdomain.com`) && (PathPrefix(`/sfu/get`) || PathPrefix(`/healthz`) || PathPrefix(`/get_token`))"
        - "traefik.http.routers.matrixrtcjwt.tls=true"
        - "traefik.http.routers.matrixrtcjwt.service=matrixrtcjwt"
        - "traefik.http.services.matrixrtcjwt.loadbalancer.server.port=8081"
        - "traefik.http.routers.matrixrtcjwt.tls.certresolver=yourcertresolver" # change to your cert resolver's name
        - "traefik.docker.network=proxy" # your traefik network name

  matrix-rtc-livekit:
    # ...
    labels:
        - "traefik.enable=true"
        - "traefik.http.routers.livekit.entrypoints=websecure"
        - "traefik.http.routers.livekit.rule=Host(`matrix-rtc.yourdomain.com`)"
        - "traefik.http.routers.livekit.tls=true"
        - "traefik.http.routers.livekit.service=livekit"
        - "traefik.http.services.livekit.loadbalancer.server.port=7880"
        - "traefik.http.routers.livekit.tls.certresolver=yourcertresolver" # change to your cert resolver's name
        - "traefik.docker.network=proxy" # your traefik network name

2.2 Config file

http:
    routers:
        matrixrtcjwt:
            entryPoints:
                - "websecure"
            rule: "Host(`matrix-rtc.yourdomain.com`) && (PathPrefix(`/sfu/get`) || PathPrefix(`/healthz`) || PathPrefix(`/get_token`))"
            tls:
                certResolver: "yourcertresolver" # change to your cert resolver's name
            service: matrixrtcjwt
        livekit:
            entryPoints:
                - "websecure"
            rule: "Host(`matrix-rtc.yourdomain.com`)"
            tls:
                certResolver: "yourcertresolver" # change to your cert resolver's name
            service: livekit
    services:
        matrixrtcjwt:
            loadBalancer:
                servers:
                    - url: "http://matrix-rtc-jwt:8081"
                passHostHeader: true
        livekit:
            loadBalancer:
                servers:
                    - url: "http://matrix-rtc-livekit:7880"
                passHostHeader: true

6. Start Docker Containers

Note: If you are using Docker Compose, follow 6.1. If you are using plain Docker, follow 6.2.

6.1 Using Docker Compose

  1. Ensure you are in your matrix-rtc directory, e.g. cd /opt/matrix-rtc.
  2. Start containers: docker compose up -d.

6.2 Using Docker Run

  1. Start matrix-rtc-jwt. MRTCKEY and MRTCSECRET should be replaced with the values generated in Step 2. matrix-rtc.yourdomain.com should be replaced with your MatrixRTC subdomain. yourdomain.com should be replaced with what you have set as server_name in tuwunel.toml.
docker run -d \
  --restart unless-stopped \
  --name matrix-rtc-jwt \
  -p 8081:8081 \
  -e LIVEKIT_JWT_BIND=":8081" \
  -e LIVEKIT_URL="wss://matrix-rtc.yourdomain.com" \
  -e LIVEKIT_KEY="MRTCKEY" \
  -e LIVEKIT_SECRET="MRTCSECRET" \
  -e LIVEKIT_FULL_ACCESS_HOMESERVERS="yourdomain.com" \
  ghcr.io/element-hq/lk-jwt-service:latest
  1. Start matrix-rtc-livekit:
docker run -d \
  --restart unless-stopped \
  --name matrix-rtc-livekit \
  --network host \
  -v /opt/matrix-rtc/livekit.yaml:/etc/livekit.yaml:ro \
  livekit/livekit-server:latest \
  --config /etc/livekit.yaml

Element Call should now be working.

Additional Configuration

Delayed events

Tuwunel supports delayed events with no setup.

Element Call relies on delayed events to remove callers who disappear. When someone joins a call, their client schedules their leave on the server and keeps postponing it while the call runs. If the client crashes or loses its connection, the postponing stops and the server sends the leave, so the caller drops out of the call instead of lingering in it. lk-jwt-service can postpone and send that leave on a caller’s behalf.

The limits are in the [global.rooms.delayed_events] section of your tuwunel.toml configuration file.

SettingLimitDefault
max_delay_sHow far ahead an event may be scheduled, in seconds86400 (one day)
max_scheduledHow many events one user may have pending100

Setting either to 0 disables delayed events and stops advertising them to clients, so callers who drop out stay listed in the call.

Application service mode

Use application services if you want lk-jwt-service to check room membership before issuing call tokens.

The setup above runs lk-jwt-service in its standalone mode, which lk-jwt-service has deprecated. Standalone mode never checks room membership. Any user of a full-access homeserver gets a token for any room. In application service mode, with Tuwunel as its only full-access homeserver, lk-jwt-service asks Tuwunel whether each caller is joined to the call’s room before it issues a token, using MSC4502. This works for callers from other servers too, as long as Tuwunel is in the room.

The registration below also lets clients and other Matrix servers reach lk-jwt-service through Tuwunel, using MSC4512. Tuwunel authenticates requests to /_matrix/client/v1/rtc/livekit/... and /_matrix/federation/v1/rtc/livekit/... and forwards them to lk-jwt-service.

Communication between Matrix servers is called federation. Other homeservers can reach your lk-jwt-service over federation without a public lk-jwt-service URL. In turn, lk-jwt-service can have Tuwunel sign and send federation requests under that prefix, to get your users a token from another server’s lk-jwt-service.

Warning

Keep the tokens secret. The .* users namespace in this registration lets whoever holds ASTOKEN act as any local user. The scope lets them ask about any user or server in any room Tuwunel is in. The proxy prefix lets them send federation requests as your server under /_matrix/federation/<version>/rtc/livekit.

  1. Generate two more random strings, ASTOKEN and HSTOKEN, e.g. with pwgen -s -1 64 for each.
  2. Create a directory for registration files, e.g. mkdir -p /etc/tuwunel/appservices, and write the following to /etc/tuwunel/appservices/lk-jwt-service.yaml, replacing ASTOKEN and HSTOKEN:
id: lk-jwt-service
url: null # lk-jwt-service needs no events
as_token: ASTOKEN
hs_token: HSTOKEN
sender_localpart: _lk_jwt_service
namespaces:
  users:
    - exclusive: false
      regex: ".*"
io.element.msc4502.scopes:
  - "urn:matrix:client:io.element.msc4502:rooms:is_joined"
io.element.msc4512.proxy_prefix: "rtc/livekit"
io.element.msc4512.proxy_url: "http://127.0.0.1:8081" # lk-jwt-service, as Tuwunel reaches it

The namespace is not exclusive, so it reserves no user names. Tuwunel queues no events for a registration whose url is null.

Set proxy_url to an address Tuwunel can use to reach lk-jwt-service. Use the port compose.yaml publishes when Tuwunel runs on the same host. When both containers share a Docker network, use http://matrix-rtc-jwt:8081.

Only one registration may claim rtc/livekit. Tuwunel logs an invalid or already claimed prefix at startup and loads the registration without it.

Warning

An invalid registration file, for example one reusing another registration’s as_token, stops appservice loading at startup. Tuwunel logs the error. That registration and any loaded after it stay unavailable until you fix the file and restart Tuwunel.

  1. Point appservice_dir at that directory in the [global] section of tuwunel.toml and restart Tuwunel:
appservice_dir = "/etc/tuwunel/appservices"

Tuwunel loads every .yaml and .yml file in the directory at each start, so keep other files out of it. Because it reads the file again at every start, a registration key a later release learns takes effect without registering again; a registration made with !admin appservices register instead is stored as the running release understood it, and must be registered again to pick up such a key. An unknown scope grants no permission and is logged as a warning at startup. After restarting, send !admin appservices list in the admin room. Check that the list includes lk-jwt-service. If it does not, check Tuwunel’s startup logs for a registration error.

  1. Give lk-jwt-service the same file and name your homeserver. Open compose.yaml in your MatrixRTC directory. In the matrix-rtc-jwt service, add these settings to environment:
      - LIVEKIT_AS_REGISTRATION_FILE=/etc/lk-jwt-service/registration.yaml
      - LIVEKIT_HS_SERVER_NAME=yourdomain.com # Your server_name from tuwunel.toml

Mount the same registration file in matrix-rtc-jwt:

    volumes:
      - /etc/tuwunel/appservices/lk-jwt-service.yaml:/etc/lk-jwt-service/registration.yaml:ro

With plain Docker, add the same settings as -e LIVEKIT_AS_REGISTRATION_FILE="/etc/lk-jwt-service/registration.yaml", -e LIVEKIT_HS_SERVER_NAME="yourdomain.com" and -v /etc/tuwunel/appservices/lk-jwt-service.yaml:/etc/lk-jwt-service/registration.yaml:ro.

Warning

Keep LIVEKIT_FULL_ACCESS_HOMESERVERS set to yourdomain.com alone. lk-jwt-service’s own endpoints (/sfu/get, /get_token and /delegate_delayed_leave) check room membership only while that list names exactly the server in LIVEKIT_HS_SERVER_NAME. lk-jwt-service logs a warning at startup when the list does not match.

For call tokens requested through Tuwunel, room membership is checked regardless of this list.

  1. lk-jwt-service finds Tuwunel through https://yourdomain.com/.well-known/matrix/client, set up in section 3 above. If the container cannot reach that address, give it Tuwunel’s client API address directly, e.g. LIVEKIT_CS_API_URL_OVERRIDES=yourdomain.com=http://tuwunel:8008.
  2. Recreate the lk-jwt-service container. With Docker Compose, run docker compose up -d from your MatrixRTC directory.

Call tokens through Tuwunel

Element Call gets its call token from the homeserver, and so through Tuwunel, when the advertised transport has a url and no livekit_service_url. Such a transport is configured in the [global.well_known] section of tuwunel.toml:

[[global.well_known.rtc_transports]]
type = "m.livekit"
url = "wss://matrix-rtc.yourdomain.com"

A transport with livekit_service_url, as livekit_url from section 3 produces, keeps clients asking lk-jwt-service directly.

For call checks and container logs, see Troubleshooting.

External TURN Integration

If you follow this guide and also set up Coturn as per the TURN documentation, there will be a port clash between the two services. To avoid this, the following must be added to your coturn.conf:

min-port=50201
max-port=65535

If you have Coturn configured, you can use it as a TURN server for Livekit to improve call reliability. As Coturn allows multiple instances of static-auth-secret, it is suggested that the secret used for Livekit is different to that used for Tuwunel.

  1. Create a secret for Coturn; a random 64-character alphanumeric string is suggested.
  2. Add the following line to the end of your coturn.conf, where AUTH_SECRET is the secret created in Step 1:
static-auth-secret=AUTH_SECRET
  1. Add the following to the end of the rtc block in your livekit.yaml. AUTH_SECRET is the same as above. turn.yourdomain.com should be replaced with your actual TURN domain.
  turn_servers:
    - host: turn.yourdomain.com
      port: 5349
      protocol: tls
      secret: "AUTH_SECRET"

Using the Livekit Built-In TURN Server

Livekit includes a built-in TURN server which can be used in place of an external option. This TURN server will only work with Livekit and is not compatible with traditional Matrix calling. For that, see the TURN documentation.

The TURN server allocates relay addresses at the node IP, so the use_external_ip and node_ip guidance in step 2.2 applies here as well; if Livekit runs in Docker and TURN fails, revisit that step.

Basic Setup

The simplest way to enable this is to add the following to your livekit.yaml:

turn:
  enabled: true
  udp_port: 3478
  relay_range_start: 50300
  relay_range_end: 65535
  domain: matrix-rtc.yourdomain.com

It is strongly recommended that you use network_mode: "host"; however if port mappings are necessary, add the following ports to matrix-rtc-livekit in your compose.yaml:

ports:
      - 3478:3478/udp
      - 50300-65535:50300-65535/udp

You will need to allow ports 3478 and 50300:65535/udp through your firewall. If you use UFW: ufw allow 3478 and ufw allow 50300:65535/udp.

Setup With TLS

To enable TLS for the TURN server, the process is slightly more complicated. Some WebRTC software will not accept certificates provided by Let’s Encrypt; it is therefore suggested that you use ZeroSSL as an alternative.

  1. Create a DNS record for e.g. matrix-turn.yourdomain.com pointing to your server.
  2. Get a certificate for this subdomain.
  3. Add the certificates as volumes for matrix-rtc-livekit in your compose.yaml. For example:
volumes:
      - ./certs/privkey.pem:/certs/privkey.pem:ro
      - ./certs/fullchain.pem:/certs/fullchain.pem:ro
  1. Add the following to the bottom of your livekit.yaml. The values for cert_file and key_file should match where these files are mounted in the container.
turn:
  enabled: true
  udp_port: 3478
  tls_port: 5349
  relay_range_start: 50300
  relay_range_end: 65535
  external_tls: false
  domain: matrix-turn.yourdomain.com
  cert_file: /certs/fullchain.pem
  key_file: /certs/privkey.pem
  1. It is strongly recommended that you use network_mode: "host"; however if port mappings are necessary, add the following ports to matrix-rtc-livekit in your compose.yaml:
ports:
      - 3478:3478/udp
      - 5349:5349/tcp
      - 50300-65535:50300-65535/udp
  1. You will need to allow ports 3478, 5349, and 50300:65535/udp through your firewall. If you use UFW: ufw allow 3478, ufw allow 5349, and ufw allow 50300:65535/udp.
  2. Restart the containers.

Troubleshooting

The easiest way to test your configuration is using the testmatrix utility provided by spaetz. This can be installed using pip install testmatrix if you have Python and pip installed.

To use this utility to test your call setup, you will need an access token for your account. This can be most easily found at the bottom of the “Help & About” section of the Element Web settings, or in the “Developer Tools” section of the Cinny settings.

Once you have testmatrix installed, run the following (YOUR_TOKEN must be replaced with the access token from your client described above):

testmatrix -u @your-user:yourdomain.com -t YOUR_TOKEN yourdomain.com

The output of this command will give you information on whether calls are properly set up.

If all tests are successful, you will get credentials that can be used with the Livekit Connection Tester. This can be used to test the ability of your Livekit service to route calls.

If any of these tests fail, further information can be found in the container logs. Run docker compose logs --follow in the directory where your compose.yaml is located.

Calls connect for some clients but not others

A common failure mode is that calls work for clients outside your local network but fail for clients on the same LAN as the Livekit server, and the failure is browser-dependent (Firefox often breaks while Chromium succeeds, or vice versa).

This is usually a NAT routing issue rather than a Livekit configuration issue. Livekit advertises the server’s public IP as an ICE candidate via STUN. Clients on the same LAN that try to reach that public IP must traverse the router back into the LAN, a feature called “NAT loopback” or “hairpin NAT”. Some routers do not support it, and in that case local clients cannot establish a media path to any candidate that names the public IP. Browsers differ in how aggressively they retry alternative candidates and in how they handle host candidates under mDNS obfuscation, so the same network can break one browser while another works.

The reliable fix is to make local clients resolve the MatrixRTC subdomain to the LAN address, so they bypass the router for that traffic. Most routers expose this as a “local DNS override”, “DNS rewrite”, or “host override” setting. Alternatively, run a small local DNS resolver (dnsmasq, AdGuard Home, Pi-hole) on the network and point LAN clients at it. External clients continue to resolve the subdomain to the public IP via public DNS.

Calls stop working after some hours

If calls work after Livekit starts but begin failing some hours later, and restarting Livekit (or rebooting the server) brings them back until the next time, your public IP address is probably changing. Many home internet connections receive a new address from time to time, some on a fixed schedule.

With use_external_ip: true, Livekit discovers the public address once, when it starts, and advertises it to clients for as long as it runs. After the address changes, clients are still sent the old one and cannot reach Livekit. Keeping your DNS records current, for example with a dynamic DNS client, does not change what Livekit advertises.

To confirm, compare the address in Livekit’s startup log with your current public address while calls are failing:

docker logs matrix-rtc-livekit 2>&1 | grep "using external IPs"
curl -4 https://ifconfig.me

If they differ, Livekit needs a restart whenever the address changes. The script below checks the public address and restarts the container when it has changed. Save it as /usr/local/bin/livekit-ip-watch.sh, set CONTAINER to your Livekit container’s name if it differs (docker ps lists them), and make it executable with sudo chmod +x /usr/local/bin/livekit-ip-watch.sh.

#!/bin/sh
# Restart Livekit whenever the public IP address changes.

CONTAINER=matrix-rtc-livekit
STATE=/var/lib/livekit-ip
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

NEW=$(curl -4 -fsS -m 10 https://ifconfig.me) || exit 0
echo "$NEW" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' || exit 0
OLD=$(cat "$STATE" 2>/dev/null)

if [ "$NEW" != "$OLD" ]; then
    logger -t livekit-ip-watch "Public IP changed from ${OLD:-unknown} to $NEW, restarting $CONTAINER"
    docker restart "$CONTAINER" >/dev/null && echo "$NEW" > "$STATE"
fi

Run it once by hand with sudo /usr/local/bin/livekit-ip-watch.sh. The first run restarts Livekit, since no address has been saved yet, and records the current one in /var/lib/livekit-ip. Then run it every five minutes by adding this line to root’s crontab (sudo crontab -e):

*/5 * * * * /usr/local/bin/livekit-ip-watch.sh

Each restart is logged, and journalctl -t livekit-ip-watch lists them. A call in progress when the address changes still drops; new calls work again once the script has restarted Livekit.

Clients report that the server has no MatrixRTC transport

Element X and Element Call read the server’s transports from GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports, which Tuwunel builds from livekit_url and [[global.well_known.rtc_transports]] in tuwunel.toml. With neither set, the endpoint answers with an empty list and those clients report that no transport is available, even when .well-known/matrix/client carries a correct org.matrix.msc4143.rtc_foci key. This is the usual cause when something other than Tuwunel serves your .well-known.

Check it directly (no access token is needed as of v1.8.2):

curl -s https://matrix.yourdomain.com/_matrix/client/unstable/org.matrix.msc4143/rtc/transports

An empty rtc_transports array means livekit_url is unset. Add it per step 3.1 and restart Tuwunel.

Element X fails every call with OPEN_ID_ERROR

Element X, and other clients built on a current matrix-rust-sdk, fail every call with OPEN_ID_ERROR, while clients that still read .well-known first may keep working. The reverse proxy logs requests for /sfu/get on the wrong host, typically "OPTIONS /sfu/get" 405 on its default or homeserver site. The same error also covers token failures, so this is one cause to check, not the only one.

The usual cause is a livekit_url in tuwunel.toml that names the wrong address (often the homeserver itself) while a separately served .well-known/matrix/client is correct. Current clients ask the rtc/transports endpoint first and read .well-known only when the server does not implement it, so Tuwunel’s answer wins. When Tuwunel serves .well-known itself, both come from the same settings and cannot disagree, so this applies to step 3.2 setups. Compare the two:

curl -s https://matrix.yourdomain.com/_matrix/client/unstable/org.matrix.msc4143/rtc/transports
curl -s https://yourdomain.com/.well-known/matrix/client

Each livekit_service_url must be the same URL in both, the matrix-rtc address from step 3, never the homeserver itself. Entries under [[global.well_known.rtc_transports]] are advertised alongside livekit_url, so remove stale ones. Correct livekit_url and restart Tuwunel.

Element X keeps the previous answer in memory for up to a day and can go on calling the old address after the fix. Closing the app fully clears it (on Android, App info, then Force stop; swiping it away may leave it running). If it still uses the old address, wait: the cached answer expires within a day, and the first call after that may still use it once while the client refreshes.

Docker bridge addresses advertised as candidates

With host networking, Livekit gathers candidate addresses from every interface on the host, including Docker bridge gateways (docker0 and per-network br-* addresses, typically 172.17.x.x and up). If calls fail to connect and the Livekit container log shows bridge addresses in its using external IPs line, clients are being offered unreachable candidates. See step 2.2 for the node_ip and external_ip_only settings that suppress them.

Setting up TURN/STUN

A TURN server relays call traffic and is required to make or receive legacy calls in Matrix. Tuwunel suggests using Coturn for this purpose, which is also available as a Docker image. To use a service instead of running your own TURN server, see Hosted TURN providers.

Note

If you are setting up MatrixRTC and only need a TURN server to improve Livekit call reliability (not legacy calling), Livekit ships its own built-in TURN server. See Using the Livekit Built-In TURN Server in the MatrixRTC documentation. This page covers standalone Coturn and hosted TURN providers for legacy Matrix calls. If you run both Coturn and Livekit, review External TURN Integration for the port allocation considerations.

Configuration

Create a configuration file called coturn.conf containing:

use-auth-secret
static-auth-secret=<a secret key>
realm=<your server domain>

A common way to generate a suitable alphanumeric secret key is by using pwgen -s 64 1.

These same values need to be set in Tuwunel. See the example config in the TURN section for configuring these and restart Tuwunel after.

turn_secret or a path to turn_secret_file must have a value of your coturn static-auth-secret, or use turn_username and turn_password if using legacy username:password TURN authentication (not preferred).

turn_uris must be the list of TURN URIs you would like to send to the client. Typically you will just replace the example domain example.turn.uri with the realm you set from the example config.

If you are using TURN over TLS, you can replace turn: with turns: in the turn_uris config option to instruct clients to attempt to connect to TURN over TLS. This is highly recommended.

If you need unauthenticated access to the TURN URIs, or some clients may be having trouble, you can enable turn_guest_access in Tuwunel which disables authentication for the TURN URI endpoint /_matrix/client/v3/voip/turnServer.

Run

Run the Coturn image using

docker run -d --network=host \
  -v $(pwd)/coturn.conf:/etc/coturn/turnserver.conf \
  coturn/coturn

or docker-compose. For the latter, paste the following section into a file called docker-compose.yml and run docker compose up -d in the same directory.

services:
    turn:
      container_name: coturn-server
      image: docker.io/coturn/coturn
      restart: unless-stopped
      network_mode: "host"
      volumes:
        - ./coturn.conf:/etc/coturn/turnserver.conf

To understand why the host networking mode is used and explore alternative configuration options, please visit Coturn’s Docker documentation.

For security recommendations see Synapse’s Coturn documentation.

The TURN server requires the appropriate ports to be forwarded where your installation is behind NAT. These are currently 3478/tcp, 3478/udp, 5349/tcp, and 5349/udp.

Hosted TURN providers

Instead of running Coturn, you can use a TURN service that issues expiring credentials (a username and password) through an HTTP API. Tuwunel fetches the credentials and server addresses, called URIs, from the provider. Clients receive them through the existing /_matrix/client/v3/voip/turnServer endpoint and need no changes.

Configure only one of the providers below. While a provider is configured, Tuwunel ignores turn.uris, the shared secret and the static credentials. Add the chosen provider section to the configuration file your Tuwunel service loads. Packaged services use /etc/tuwunel/tuwunel.toml; see Configuration if you run Tuwunel another way.

Cloudflare

  1. Create a TURN key for Cloudflare’s Realtime TURN service in the Cloudflare dashboard.
  2. On the machine running Tuwunel, save the key’s API token in /etc/tuwunel/.cloudflare_turn_token. The file must be readable by Tuwunel.
  3. Add the following section to your Tuwunel configuration file, replacing <TURN key ID> with your key’s ID.
[global.turn.cloudflare]
key_id = "<TURN key ID>"
token_file = "/etc/tuwunel/.cloudflare_turn_token"
  1. Reload Tuwunel’s configuration.

Cloudflare credentials last at most 48 hours. Tuwunel shortens a turn.ttl above that limit. It sends clients only Cloudflare’s TURN URIs and excludes those using port 53, because browsers refuse to connect to that port.

Any other provider

Use [global.turn.endpoint] if your provider has an HTTP endpoint that answers GET <url>?service=turn&ttl=<seconds> in either of the formats below. The first is the TURN REST API format, which is also what Matrix clients receive:

{
  "username": "1700000000:example",
  "password": "<password>",
  "ttl": 86400,
  "uris": ["turn:turn.example.com?transport=udp"]
}

The second is a WebRTC ICE server list, either {"iceServers": [...]} or a bare list. Each entry describes a server with urls, username and credential. Matrix clients accept a single username and password. Tuwunel uses the first entry with a nonempty username and password, then drops entries whose credentials differ. In either format, only turn: and turns: URIs reach clients, as the Matrix specification requires.

The STUNner auth service answers in both formats. If your provider’s API uses a different format, you can put an adapter in front of it to translate requests and responses.

  1. If the provider requires a bearer token, save it in /etc/tuwunel/.turn_endpoint_token on the machine running Tuwunel. The file must be readable by Tuwunel.
  2. Add the following section to your Tuwunel configuration file. Replace url with your provider’s credential endpoint. Omit token_file if the provider does not use bearer authentication.
[global.turn.endpoint]
url = "http://127.0.0.1:8088/"
token_file = "/etc/tuwunel/.turn_endpoint_token"
  1. Reload Tuwunel’s configuration.

When token or token_file is set, Tuwunel sends the token in the Authorization header as a bearer token. Query parameters already in url are kept, so an API key in the query is preserved.

Shared credentials and failures

All users share one set of credentials, renewed once half its lifetime has passed. The provider therefore sees about two requests per credential lifetime however many clients ask. Tuwunel never sends it a Matrix user ID.

After a failed request, Tuwunel waits a minute before asking the provider again. During that time, clients receive cached credentials if they have not expired, or a 502 error if no unexpired credentials remain. If requests keep failing, check that Tuwunel can read the token file and that the configured provider URL or Cloudflare key ID is correct.

Application Services

Application services are out-of-process programs that extend the homeserver; most bridges (IRC, XMPP, Discord, Telegram, Slack) are implemented this way. They authenticate with a pair of shared secret tokens and declare namespaces of users and room aliases that they manage.

The upstream reference is the Matrix Application Service API specification.

Registration

Tuwunel supports three registration methods. They coexist and are all loaded on startup.

Admin room

The most convenient method for live deployments. Send !admin appservices register to the admin room with the registration YAML in a code block below:

!admin appservices register
\`\`\`
id: my-bridge
url: http://localhost:29328
as_token: secret-token-a
hs_token: secret-token-b
sender_localpart: my-bridge-bot
namespaces:
  users:
    - exclusive: true
      regex: '@my-bridge_.*:example\.com'
\`\`\`

The registration is persisted in the database and survives restarts. Registering with an existing ID replaces the old entry, unless that ID comes from the server configuration or appservice_dir. No restart is required.

Server configuration

Application services can be declared inline in tuwunel.toml. The TOML section key becomes the registration ID unless id is explicitly set:

[global.appservice.my-bridge]
url = "http://localhost:29328"
as_token = "secret-token-a"
hs_token = "secret-token-b"
sender_localpart = "my-bridge-bot"

[[global.appservice.my-bridge.users]]
exclusive = true
regex = '@my-bridge_.*:example\.com'

Config-file registrations are reloaded on each restart. They cannot be removed with !admin appservices unregister.

Registration file directory

Point appservice_dir at a directory containing YAML registration files. Every .yaml or .yml file in it is loaded at startup:

[global]
appservice_dir = "/etc/tuwunel/appservices"

Files use the same YAML format that bridges produce for Synapse. New or removed files are not picked up without a restart.

Unix sockets

On Unix systems, set the registration URL to an absolute socket path:

url: unix:///run/mautrix-whatsapp/appservice.sock

For an inline registration, use the same URL:

[global.appservice.whatsapp]
url = "unix:///run/mautrix-whatsapp/appservice.sock"

Both unix:///absolute/path.sock and unix:/absolute/path.sock are accepted. The path is literal, without percent-decoding; a path prefix after the socket and TLS over the socket are not supported. The bridge may create the socket after tuwunel starts.

For mautrix-go bridges, set appservice.hostname to /run/mautrix-whatsapp/appservice.sock and appservice.address to unix:///run/mautrix-whatsapp/appservice.sock. A leading / in the hostname selects a socket listener, so the port is optional. The bridge copies its address into the generated registration. Mautrix-python bridges listen on TCP only.

The tuwunel process needs write permission on the bridge’s socket file. Run both services as the same user or give tuwunel access through a shared group.

For the reverse direction, set tuwunel’s unix_socket_path to /run/tuwunel/tuwunel.sock and the bridge’s homeserver.address to unix:///run/tuwunel/tuwunel.sock. See the Unix socket configuration and socket activation guide.

Namespaces

Each registration declares which users, room aliases, and room IDs the appservice claims. Entries under users, aliases, and rooms are lists; each entry has a regex and an optional exclusive flag.

NamespaceMatchesCase
usersUser IDs (@localpart:server)Case-insensitive
aliasesRoom aliases (#alias:server)Case-insensitive
roomsRoom IDs (!opaque:server)Case-sensitive

A regular expression can match part of an ID or alias. Add ^ at the start and $ at the end if you need to match the full string.

When exclusive: true, the homeserver rejects any attempt by a normal user to register a conflicting user ID or room alias. Multiple appservices can share a non-exclusive namespace; exclusive ranges must not overlap.

Configuration reference

Fields under [global.appservice.<ID>]:

FieldDefaultDescription
idsection keyUnique registration ID. Inferred from the TOML section key when omitted.
urlnoneBase URL the homeserver pushes events to, or unix:///absolute/path.sock on Unix. Set to null for receive-only registrations.
as_tokenrequiredToken the appservice sends to the homeserver in Authorization headers.
hs_tokenrequiredToken the homeserver sends to the appservice on every push.
sender_localpartidLocalpart of the appservice bot user. Defaults to the registration ID.
rate_limitedfalseWhether requests from masqueraded virtual users are rate-limited. The bot user is always exempt.
protocols[]Protocols bridged (e.g. ["irc"]). Reported via the /thirdparty/protocols endpoint.
receive_ephemeralfalseInclude ephemeral events (typing notifications, read receipts) in pushes to the appservice.
device_managementfalseAllow the appservice to manage devices on behalf of virtual users (MSC4190).
msc3202_transaction_extensionsfalseInclude end-to-bridge encryption bookkeeping (device-list changes, one-time-key counts, unused fallback key types) in pushes, so encrypting bridges work without a /sync loop (MSC3202, paired with to-device delivery from MSC4203). The registration-file key is org.matrix.msc3202.
scopes[]Permissions the appservice requests, called scopes (MSC4502). The one known scope, urn:matrix:client:io.element.msc4502:rooms:is_joined, lets it ask whether any user or server is joined to a room this server is in. An unknown scope grants no permission. Tuwunel logs it at startup, and !admin appservices register rejects a registration containing one. The registration-file key is io.element.msc4502.scopes.
proxy_prefixnonePath prefix the appservice claims (MSC4512). Set to rtc/livekit, the only allowed prefix, together with proxy_url. Only one appservice may claim it. The registration-file key is io.element.msc4512.proxy_prefix.
proxy_urlnoneBase URL that requests under proxy_prefix are forwarded to, or unix:///absolute/path.sock on Unix (MSC4512). The registration-file key is io.element.msc4512.proxy_url.

With a valid proxy claim, Tuwunel authenticates requests under /_matrix/client/<version>/<prefix> and /_matrix/federation/<version>/<prefix> and forwards them to proxy_url. The appservice may also have Tuwunel sign and send requests to other Matrix servers under that prefix. These server-to-server requests are called federation requests.

At startup, Tuwunel logs and ignores an invalid proxy claim or one another appservice already holds. An otherwise valid registration still loads without the proxy claim. The !admin appservices register command rejects registrations with either problem.

Namespace entries under [[global.appservice.<ID>.users]], aliases, and rooms:

FieldDefaultDescription
exclusivefalseClaim exclusive ownership of matching IDs, blocking regular users from registering them.
regexrequiredRegular expression. Unanchored by default.

Admin commands

All commands run from the admin room (!admin appservices <subcommand>):

CommandDescription
registerRegister or replace an appservice. Paste the YAML in a code block below the command. Config-file registrations cannot be replaced this way.
unregister <id>Remove a database-registered appservice and cancel pending deliveries. Config-file registrations cannot be unregistered this way.
show-config <id>Print the stored registration as YAML.
listList IDs of all loaded appservices.

Server options

These options go in the top-level [global] section:

OptionDefaultDescription
appservice_timeout35Read and total request timeout in seconds, including socket registrations; connect timeout is 5 seconds.
appservice_idle_timeout300Idle connection pool timeout in seconds, including socket registrations.
dns_passthru_appservicesfalseBypass DNS passthru domain matching for all appservice URLs. More efficient than listing each domain in dns_passthru_domains when all appservices share the same network. Does not apply to socket registrations.
proxynoneOutbound HTTP proxy settings do not apply to socket registrations.
show_appservice_users_in_user_directoryfalseInclude appservice senders and users in exclusive appservice user namespaces in user directory searches. They remain subject to the normal room visibility rules unless show_all_local_users_in_user_directory is also enabled; Synapse has no equivalent and always hides them. Reloadable.

Getting help

For setup questions, join #tuwunel:matrix.org or open an issue.

Push Notifications

Tuwunel implements the homeserver side of the Matrix Push Gateway API. Clients create pushers naming their app’s push gateway URL, and Tuwunel posts each notifiable event to that URL. No server-side setup is needed for ordinary hosted gateways. For notifications by email, see Email notifications.

UnifiedPush

UnifiedPush works out of the box. UnifiedPush gateways (embedded in push servers such as ntfy and NextPush, or run standalone) accept the same /_matrix/push/v1/notify requests, so there is no UnifiedPush-specific server support to enable. The gateway discovery response ({"unifiedpush":{"gateway":"matrix"}}) is served by the push server, not by Tuwunel.

Self-hosted gateways on private networks

Outbound requests, push notifications included, refuse loopback and private-range destinations by default (the ip_range_denylist option). A self-hosted gateway on a LAN address, for example an ntfy server on 192.168.0.0/16, is rejected at pusher creation with “HTTP pusher URL is a forbidden remote address”. Narrow ip_range_denylist to admit your gateway’s range. Plain http:// gateway URLs are accepted.

When a forward proxy carries the request, its endpoint is exempt from ip_range_denylist. HTTP(S) forward proxies and socks4a or socks5h resolve destination names remotely, so they must enforce the destination network boundary themselves because Tuwunel cannot inspect that address. Destination addresses remain subject to the denylist for direct requests and for locally resolving socks4 or socks5 proxies, so the LAN guidance above still applies.

Every push notification is sent to the gateway’s Matrix spec path /_matrix/push/v1/notify; this path is not configurable. The notification_push_path option only names the path suffix stripped from the end of a stored pusher URL before that spec path is appended to the remainder. An occurrence anywhere earlier in the URL is left in place, and a URL whose path does not end with the configured value is used unchanged, so leave the option at its default unless your pushers register URLs that end in a different path needing to be removed first.

Email notifications

To offer email notifications to your users, first set up outgoing mail and have users verify their addresses:

  1. Configure the outgoing mail service (SMTP) in [global.smtp] in your Tuwunel configuration file. Use the same setup as email verification. Without it, the server refuses email pushers and the client’s toggle fails.
  2. Have each user verify an email address on their account. The server refuses an email pusher for any other address. It also deletes a pusher whose address is later removed from the account.

Clients such as Element Web offer a toggle for each email address verified on the account. Turning it on registers an email pusher for that address, a request for Tuwunel to email unread notifications. Users stop the emails by turning email notifications off in their client.

Tuwunel waits push.email_delay seconds (600 seconds, or 10 minutes, by default) before an unread notification can trigger an email. A room that appeared in a recent email can make it wait longer. Once a notification is due, Tuwunel includes all other unread notifications waiting for that user in the same email. Notifications the user reads before the email is sent are left out.

Repeated emails about the same room are spaced further apart. After the first email that includes a room, the room must wait the configured delay before it can trigger another email. This wait is capped at one day. Each further email that includes the room multiplies the wait by 144, up to that cap. With the default delay, the wait is one day from the second email onward.

The room’s notifications can still appear sooner in an email triggered by another room. Reading the room resets its wait. Setting push.email_delay to 0 sends notifications as they arrive, without either wait.

Each email is plain text and shows the newest notifications grouped by room, with the sender, time, and start of each message. It shows up to 20 notifications and counts any others at the end. For an encrypted message, it shows the sender and time but replaces the message content with Encrypted message. Rooms link to matrix.to.

Policy and Moderation

This chapter covers the federation-level, room-level, and user-level controls Tuwunel exposes to operators for keeping their server, its users, and the rooms they participate in within a desired policy posture. Most controls fall into one of three layers: configuration (statically applied at startup or reload), admin-room commands (live operator actions), and per-room policy delegation (MSC4284).

Configuration values shown here are documented in the example configuration with their defaults and full per-knob explanation. This page summarises each knob’s role in the moderation toolkit rather than restating the example file.

Federation server blocklists

The largest hammer. Three knobs in tuwunel-example.toml:

  • forbidden_remote_server_names: regex patterns matched against room IDs, room aliases, sender server names, sender users’ server names, inbound X-Matrix origins, and outbound federation handlers. Effectively a global ACL. Matching servers can neither send to nor receive from this homeserver, and local clients cannot join their rooms.
  • allowed_remote_server_names_experimental: an allow-list counterpart. When non-empty, anything not matching is denied. forbidden_remote_server_names is still applied after, so a wide allow (.*\\.example\\.com) plus a narrow deny (bad\\.example\\.com) is a valid composition.
  • forbidden_remote_room_directory_server_names: limits the broader knob to outbound room-directory queries, useful when the goal is to keep users from discovering rooms on a server without cutting all federation with it.

These checks are inexpensive and apply on every relevant code path. Use a regex denylist when a server has crossed a hard line; use the directory-only variant for cases that warrant friction without isolation.

Admin commands for moderation

The admin room (joined automatically on first registration unless create_admin_room = false) accepts the following moderation-relevant commands. Run any command with --help for argument detail.

Rooms

  • !admin rooms moderation ban-room <room>: bans a room, evicts every local user including admins, removes local aliases, unpublishes from the directory, and disables federation with the room.
  • !admin rooms moderation ban-list-of-rooms: bulk variant; takes a code block of room IDs or aliases.
  • !admin rooms moderation unban-room <room>: reverses a ban and re-enables inbound federation handling; the m.federate caveat under Federation below applies here too.
  • !admin rooms moderation list-banned-rooms: lists every banned room.
  • !admin rooms delete <room>: harder than ban; removes the room from the database after evicting users.

Federation

  • !admin federation disable-room <room>: blocks new inbound PDUs for one room without banning it. Useful for stalling a runaway room while investigating.
  • !admin federation enable-room <room>: re-enables inbound handling. Neither command touches the m.federate property of the room’s m.room.create event, which is fixed when the room is created; see Troubleshooting.
  • !admin federation incoming-federation: lists the incoming events whose missing earlier events the server is fetching or processing (room, event, origin server, phase, elapsed time), then the rooms where another federation step, such as a transaction, a join or a backfill, holds the room’s federation lock. A room with a listed event is left out of the second list.
  • !admin federation fetch-support-well-known <server>: fetches a remote server’s .well-known/matrix/support record (administrator and security contacts), letting you raise abuse reports out-of-band before resorting to blocks.

Users

  • !admin users deactivate <user>: deactivates a local account; by default also leaves all rooms. The last active admin cannot be deactivated, by this command or any other route: make another user an admin first.
  • !admin users deactivate-all: bulk variant accepting a code block of usernames.
  • !admin users reject-invites <user>: rejects all pending invites, with an optional reason. Useful when an account has been targeted by an invite flood.
  • !admin users redact-event <event_id>: forcibly redacts an event from a local sender even when the user is offline or unwilling.
  • !admin users force-demote <user> <room>: drops a user’s power level to the room default when permissions allow.
  • !admin users set-profile-key <user> <key> <value>: sets a single profile key (e.g. displayname, avatar_url, m.tz, or a custom key) on a local user, for example to remove an abusive display name. With --clear in place of a value it removes the key instead, and then also accepts a remote user (without --propagate-to), dropping this server’s cached copy of their field. The value returns on their next profile lookup if their server still serves it.
  • !admin users refresh-profile <user>: re-fetches a remote user’s profile from their server and drops cached fields it no longer serves, such as a status the user has since removed. Clients see the removal on their next sync.
  • !admin users delete-room-tag / put-room-tag: room-tag housekeeping; the m.server_notice tag pinned to the admin room is the typical use.

Media

See Multimedia and Storage > Management for the full admin command reference. Tools relevant to moderation:

  • !admin media delete --mxc <mxc_uri>: single-file removal.
  • !admin media delete-by-event --event-id <event_id>: removes every MXC URI referenced by an event.
  • !admin media delete-list: bulk removal from a code block of MXC URIs.
  • !admin media delete-range <duration> --older-than|--newer-than: time-range delete; remote-only by default, local with the --yes-i-want-to-delete-local-media confirmation.
  • !admin media delete-all-from-user <username>: removes every upload by a local user.
  • !admin media delete-all-from-server <server>: drops every cached copy of remote media from the named server.

Media policy

  • prevent_media_downloads_from: regex denylist for remote media downloads. Narrower than forbidden_remote_server_names; the server can still federate, just no media flows in.
  • media_storage_provider (under [media.storage]): when files live in an external provider, deletion semantics still apply through the same admin commands.

Identifier blocklists

Applied at registration, alias creation, and at startup as warnings against existing entries.

  • forbidden_alias_names: regex patterns matched against newly created room aliases and custom room IDs. Existing aliases that match are warned about on startup but not removed.
  • forbidden_usernames: same shape, applied to local username availability checks and registration.

Invite gating

  • block_non_admin_invites: when true, only server admins can send room invites (local or remote) and only admins can receive remote invites. The cheapest mitigation for an invite-spam wave on a small or invite-only server.

Auto-deactivation triggers

  • auto_deactivate_banned_room_attempts: when true, any local user who attempts to join a banned room, an alias matching forbidden_alias_names, or an alias / room ID containing a forbidden_remote_server_names match, is fully deactivated and made to leave every room. Off by default because rooms are sometimes banned for non-moderation reasons.

Per-room policy delegation (MSC4284)

MSC4284 lets a room’s moderators delegate event signing to a third-party policy server whose ed25519 signature must be present on every non-policy event in the room. The signature folds into event.signatures and federates transitively. Tuwunel implements outbound /sign on local sends, inbound verification on federated receives, fetch-on-missing for inbound events without a signature, and refusal/backoff caching to avoid hammering a server that is rate-limiting or has refused.

Two configuration knobs:

  • enable_policy_servers: master switch (default false). When false, Tuwunel ignores policy state entirely. When true, the gate engages only in rooms that carry a valid m.room.policy state event.
  • policy_server_request_timeout: seconds (default 5) for both outbound /sign and inbound signature-fetch requests.

Operator-relevant implications when enabling:

  • Per-room opt-in. The global flag only allows the gate to engage; the room’s own m.room.policy state event is what activates it. Rooms without the state event are unaffected.
  • Latency cost. Every outbound send in a policy-room round-trips to the policy server before federating. The default 5-second cap prevents a single misbehaving policy server from stalling sends indefinitely.
  • Fail-open on transport failure. Network errors and timeouts are logged and the event is sent or accepted unsigned, on the assumption that the next homeserver in the room will pick up the gap.
  • Fail-closed on explicit refusal. A policy server returning 400 M_FORBIDDEN (or, on the unstable variant, 200 OK with no signature for the configured via) causes outbound sends to fail with M_FORBIDDEN, and inbound events to soft-fail.
  • Inbound soft-fails withhold the event, and are reversible. A soft-failed event is kept out of the room timeline and is never relayed to clients, but it stays stored and can still be fetched directly over federation. Contributors include invalid redact permission, an explicit policy-server refusal, and failure to pass authorization against current room state (server-server receipt check 6). The standing verdict is not permanent. It is re-checked whenever federation supplies the event again, on a schedule that widens from five minutes to a day, and is released when the event later passes. An explicit refusal is itself cached for 24 hours, so re-checks inside that window answer from the cache and the policy server is only asked again once it lapses. !admin rooms clear-soft-failed-events <room> drops the stored verdicts for one room to force the question immediately.
  • Soft-failed events do not move the room forward. They are not added to the room’s forward extremities and do not directly drive current state, so a refused membership or power-level change cannot take effect locally. Their committed state remains available when descendant events participate in state resolution.
  • Privacy in encrypted rooms. The PDU is forwarded to the policy server for signing. Ciphertext is opaque, but metadata (sender, timestamp, room, event type) is not. Encrypted-room policy delegation is the room’s call; Tuwunel does not block it.
  • Refusal and rate-limit caching. Per-event refusals and M_LIMIT_EXCEEDED backoffs are persisted, so repeated arrivals of the same event do not re-hit a refusing or throttled server.

For room version compatibility, MSC4416 (the room-version-13 successor that makes a missing or invalid policy signature an auth-rule rejection rather than a soft fail) is not yet active in Tuwunel and depends on upstream typing work. Until v13 ships, “leave it off” is safe; once v13 rooms become common, leaving it off in such a room means accepting events that the rest of the federation will reject.

URL previews and outbound network policy

URL preview generation is a frequent attack surface (SSRF, exfiltration via forced fetches). Tuwunel exposes both a domain policy layer and an IP egress layer.

Domain policy:

  • url_preview_domain_contains_allowlist, url_preview_url_contains_allowlist: permissive contains-match allowlists. The contains-match is intentionally loose; treat as “anything mentioning this string passes”.
  • url_preview_domain_explicit_allowlist: strict equality match on the host.
  • url_preview_domain_explicit_denylist: strict equality match, evaluated before the allowlists unless one of them holds "*".
  • url_preview_check_root_domain: when true, retries the explicit denylist and allowlist against the host with its first label removed, so an explicit allow on wikipedia.org also lets en.wikipedia.org through, but not en.m.wikipedia.org.
  • url_preview_max_spider_size (bytes; SI/IEC suffix accepted): caps the spider response body.
  • url_preview_bound_interface: pins outbound preview requests to a specific interface or source IP. Linux/Android/Fuchsia accept interface names (eth0); other platforms accept addresses.

IP egress:

  • ip_range_denylist: list of IPv4/IPv6 CIDR ranges Tuwunel will not send outbound requests to. Defaults to RFC1918, loopback, multicast, link-local, and the documentation/testnet ranges. This is application-layer enforcement and not a substitute for a host firewall, but it closes the obvious SSRF vectors out of the box. Forward proxy endpoints are exempt. Destination addresses remain filtered for direct requests and for locally resolving socks4 or socks5 proxies. HTTP(S) forward proxies and socks4a or socks5h resolve destinations remotely, so they must enforce their own egress policy. Set to [] only if a firewall is enforcing the same constraints upstream.

Redaction retention and forensics

Moderation actions often hinge on what an event said before redaction.

  • save_unredacted_events (default true): keeps the pre-redaction PDU in storage so admins can recover content for incident review.
  • redaction_retention_seconds (default 60 days): how long unredacted copies live before being dropped. Lower this for tighter privacy posture; raise it when investigations span longer horizons.
  • allow_room_admins_to_request_unredacted_events (default true): lets a user with redact power level retrieve unredacted copies via MSC2815. Server admins can request regardless.
  • disable_local_redactions: blocks local users from sending redactions (server admins exempt). Useful only in archival or read-only deployments; most operators leave this off.

The !admin debug get-retained-pdu command surfaces a retained event from the admin room.

Responding to a spam incident

When a server sends spam media to your users, the typical response is:

1. Identify the source server. Check the MXC URIs in the reported messages. The server name is the authority component: mxc://<server_name>/<media_id>. The sender server on the offending event is the canonical source even when media is hosted elsewhere.

2. Delete cached copies of the spam media.

!admin media delete-all-from-server badserver.tld

3. Block future media downloads from that server. Add the server to prevent_media_downloads_from in your config and reload or restart Tuwunel:

prevent_media_downloads_from = ["badserver\\.tld$"]

4. If the spam arrived within a known time window, use delete-range to catch anything missed:

!admin media delete-range 2h --newer-than

5. If you have a list of specific MXC URIs (e.g. from a moderation tool or a shared blocklist), use delete-list to remove them in bulk.

6. Consider server-level federation blocks via forbidden_remote_server_names if the server is persistently abusive. This blocks all federation traffic, not just media, and so is the right tool only once the source has demonstrated it will not stop.

7. If the spam came as invite floods, set block_non_admin_invites = true to halt all non-admin invite traffic during the incident, then run !admin users reject-invites <user> for affected accounts. Re-enable invites once the source server is blocked.

8. If a single room is the vector (for example, a public room being used to flood a user’s timeline), !admin rooms moderation ban-room <room> evicts your local users and severs federation with the room without affecting other rooms on the same server.

9. For ongoing moderation against a class of senders, consider whether a per-room MSC4284 policy server is appropriate. This delegates per-event signing to a moderation service, with the trade-offs described in Per-room policy delegation above. This is a heavier setup than a one-time response and is worth it only when the room expects sustained policy enforcement.

Backup and Recovery

Tuwunel offers two online ways to preserve a RocksDB database. The managed backup system maintains a backup repository, verifies its contents, applies a retention limit, and supports a built-in restore. Checkpoints are ordinary RocksDB directories intended for operators who prefer to manage copying, retention, and restoration themselves. A conventional offline copy remains the simplest option when downtime is acceptable.

Warning

Online database backups and checkpoints do not include media. Back up the media/ directory and every configured storage provider separately. A copy stored on the same disk as the live database also does not protect against disk loss.

Choosing a method

MethodServer downtimeFormatRetention and restore
Managed online backupNone while creatingRocksDB backup repositoryTuwunel manages retention, verification, and restore
CheckpointNone while creatingDirectly usable RocksDB directoryOperator manages copying, retention, and restore
Offline copyRequiredCopy of database_pathOperator manages retention and restore

Managed online backups

The managed system is the recommended choice when Tuwunel should own the backup lifecycle. Configure a writable repository path and the number of backups to retain:

database_backup_path = "/var/backups/tuwunel"
database_backups_to_keep = 7

Both settings are reloadable. The retention value must be at least one. After each successful backup, RocksDB removes the oldest entries until the repository is within the configured limit.

Create and inspect backups from the admin room:

!admin server backup-database
!admin server list-backups
!admin server verify-backup
!admin server verify-backup 3

verify-backup selects the newest backup when its ID is omitted. Verification confirms that every expected file is present with the recorded size. Restore also verifies file checksums.

Backups can be removed independently of the configured retention limit. The argument is the number of newest backups to keep, not a backup ID:

!admin server delete-backups 3

A value of zero deletes every managed backup.

Restoring a managed backup

The backup repository is not itself a directly usable database directory. Stop Tuwunel, then start the binary once with --restore-backup to restore the most recent backup into database_path:

tuwunel --restore-backup

Pass an ID from list-backups to select a specific backup:

tuwunel --restore-backup=3

Only this command-line argument can select a restore. Tuwunel refuses the equivalent setting from configuration files, the environment, and -O, which prevents an old setting from repeating a restore on a later restart.

Warning

Restore replaces the RocksDB files in database_path. Preserve the current database and media before proceeding so the operation can be reversed if the selected backup is not the intended one.

For a systemd installation, perform the one-time restore as the service user while the normal service is stopped:

systemctl stop tuwunel
sudo -u tuwunel tuwunel --config /etc/tuwunel/tuwunel.toml --restore-backup \
	--maintenance --execute "users clear-one-time-keys" --execute "server shutdown"
systemctl start tuwunel

Maintenance mode prevents the temporary process from serving clients. The startup commands clear the restored one-time keys, as described in One-time keys after a restore, and shut the process down after the restore completes.

With Docker or Podman, append --restore-backup to a one-time container invocation that uses the normal configuration and volumes, then recreate the regular container.

Manual recovery

Prefer the built-in restore whenever the Tuwunel binary can run. If it is not available, a managed backup can be reconstructed manually:

  1. Create a new, empty directory for the recovered database.
  2. Copy the .sst files from $DATABASE_BACKUP_PATH/shared_checksum into it.
  3. Rename each shared file from ######_sxxxxxxxxx.sst to ######.sst.
  4. Copy every file from the selected numbered backup directory into the new directory.
  5. Set database_path to the recovered directory, restore its ownership, and start Tuwunel.

For example, this shell loop performs the shared-file rename from inside the new directory:

for file in *_s*.sst; do
	mv "$file" "$(printf '%s\n' "$file" | sed 's/_s.*/.sst/')"
done

Checkpoints

A full checkpoint is a consistent, directly usable RocksDB directory. RocksDB normally hard-links immutable SST files when the destination permits it, so a checkpoint can be quick to create and initially consumes little additional space. Copy it to independent storage if it must survive loss of the database disk.

Create a checkpoint with the default settings:

!admin server checkpoint-database

Without a path, Tuwunel creates <database_path>/checkpoint-<unix_timestamp>. An explicit destination is often more convenient for an external backup volume:

!admin server checkpoint-database --path /var/backups/tuwunel/checkpoint-2026-08-22

The destination must be new. Tuwunel does not overwrite an existing directory. The server does not track checkpoint directories or apply retention to them.

Checkpoint options

--log-size [bytes] controls the write-ahead log threshold used for a full database checkpoint. Omitting the option, writing it without a value, or setting it to zero forces RocksDB to flush as needed before creating the checkpoint. Keep this default unless retaining recent writes through copied WAL files is a deliberate part of the backup design.

--map <name> exports one column family instead of the complete database. --column is an alias for the same option. A map export always flushes that column family, does not use --log-size, and is not a complete server backup.

Deleting a checkpoint

A checkpoint has no registration or reference in Tuwunel. After it has expired or been copied and verified elsewhere, remove its directory with normal filesystem tools. Removing a checkpoint safely releases its hard links without deleting the live database files.

Warning

Confirm the exact path before removing it. Never remove files from the live database_path individually. For a default checkpoint, the complete checkpoint-<unix_timestamp> child directory is the deletion boundary.

For example:

rm -r /var/lib/tuwunel/checkpoint-1755850800

Restoring a checkpoint

Stop Tuwunel before opening or restoring a checkpoint. Either copy the complete checkpoint into a new database directory and point database_path to it, or replace the old database directory only after preserving it for rollback. Restore directory ownership for the service account and restore media separately. Clear the restored one-time keys as described in One-time keys after a restore. Then start Tuwunel and verify the server before deleting the previous database or source checkpoint.

Scheduling checkpoints with a signal

On Unix systems, admin_signal_execute runs its configured admin commands when Tuwunel receives SIGUSR2. Command strings omit the !admin prefix. This configuration creates a timestamped checkpoint inside database_path for each signal:

admin_signal_execute = ["server checkpoint-database"]

The setting is reloadable. After reloading the configuration or restarting the server, test it once with systemd:

systemctl kill --kill-whom=main --signal=USR2 tuwunel.service

The command result is written to the server log. Successful signal delivery only confirms that systemd sent the signal, so monitor the log and confirm that the new checkpoint directory exists.

A root-owned cron file can request a checkpoint every day at 03:00 in the cron daemon’s local timezone:

# /etc/cron.d/tuwunel-checkpoint
SHELL=/bin/sh
PATH=/usr/bin:/bin

0 3 * * * root systemctl kill --kill-whom=main --signal=USR2 tuwunel.service

Adjust the unit name for the installation. Cron only triggers creation; it does not copy, verify, or expire checkpoints. Add a separate retention process after the checkpoints have reached their independent backup destination.

Offline backups

For the simplest database copy, stop Tuwunel and copy the entire database_path to independent storage. The copied RocksDB directory can be restored without conversion. Copy the media/ directory and any external media storage providers as part of the same backup set.

After restoring a copy, clear its one-time keys before starting the service, as described in One-time keys after a restore.

One-time keys after a restore

Devices upload one-time keys for end-to-end encryption. Restoring a managed backup, a checkpoint, or an offline copy puts the keys claimed since the copy was made back into the pool of available keys. The server would issue them again, but their devices discarded the private halves when they first used them, so a message encrypted with a reissued key cannot be decrypted. Clear the pool before the restored server serves clients.

For a managed backup, use this command while the normal service is stopped. It clears the keys in the one-time restore process before shutting it down:

sudo -u tuwunel tuwunel --config /etc/tuwunel/tuwunel.toml --restore-backup \
	--maintenance --execute "users clear-one-time-keys" --execute "server shutdown"

For a checkpoint or an offline copy, run the same one-time process without --restore-backup after the files are in place and before starting the service:

sudo -u tuwunel tuwunel --config /etc/tuwunel/tuwunel.toml \
	--maintenance --execute "users clear-one-time-keys" --execute "server shutdown"

The command reports how many keys it cleared and from how many devices. If clearing fails, keep the normal service stopped, resolve the reported error, and retry. An interrupted clearing leaves the pool intact for a retry.

If the restored server is already running, issue the same command in the admin room as soon as possible:

!admin users clear-one-time-keys

Each client sees a count of zero at its next sync and uploads new keys. Until then a claim is served the device’s fallback key, which the command keeps. A device that never syncs, such as a dehydrated device, keeps only its fallback key until its owner replaces it. A restored fallback key can itself be stale: a client that rotated its fallback key after the backup was made no longer holds the restored one, and clearing one-time keys does not change that.

Maintaining your Tuwunel setup

Moderation

Tuwunel has moderation through admin room commands. “binary commands” (medium priority) and an admin API (low priority) is planned. Some moderation-related config options are available in the example config such as “global ACLs” and blocking media requests to certain servers. See the example config for the moderation config options under the “Moderation / Privacy / Security” section.

Tuwunel has moderation admin commands for:

  • managing room aliases (!admin rooms alias)
  • managing room directory (!admin rooms directory)
  • managing room banning/blocking and user removal (!admin rooms moderation)
  • managing user accounts (!admin users)
  • fetching /.well-known/matrix/support from servers (!admin federation)
  • blocking incoming federation for certain rooms (not the same as room banning) (!admin federation)
  • deleting media (see the media section)

Any commands with -list in them will require a codeblock in the message with each object being newline delimited. An example of doing this is:

!admin rooms moderation ban-list-of-rooms
```
!roomid1:server.name
#badroomalias1:server.name
!roomid2:server.name
!roomid3:server.name
#badroomalias2:server.name
```

Database (RocksDB)

Generally there is very little you need to do. Compaction is ran automatically based on various defined thresholds tuned for Tuwunel to be high performance with the least I/O amplifcation or overhead. Manually running compaction is not recommended, or compaction via a timer, due to creating unnecessary I/O amplification. RocksDB is built with io_uring support via liburing for improved read performance.

RocksDB troubleshooting can be found in the RocksDB section of troubleshooting.

Compression

Some RocksDB settings can be adjusted such as the compression method chosen. See the RocksDB section in the example config.

btrfs users have reported that database compression does not need to be disabled on Tuwunel as the filesystem already does not attempt to compress. This can be validated by using filefrag -v on a .SST file in your database, and ensure the physical_offset matches (no filesystem compression). It is very important to ensure no additional filesystem compression takes place as this can render unbuffered Direct IO inoperable, significantly slowing down read and write performance. See https://btrfs.readthedocs.io/en/latest/Compression.html#compatibility

Important

Compression is done using the COW mechanism so it’s incompatible with nodatacow. Direct IO read works on compressed files but will fall back to buffered writes and leads to no compression even if force compression is set. Currently nodatasum and compression don’t work together.

btrfs

btrfs is Copy-on-Write, which interacts badly with the way RocksDB allocates its write-ahead logs. Set rocksdb_allow_fallocate = false in tuwunel.toml. Preallocation cannot reserve in-place write space on a CoW filesystem anyway, so there is nothing to lose by turning it off there. Tuwunel warns at startup when database_path is on btrfs and the option is still enabled.

RocksDB preallocates each WAL with fallocate(2), writes to it, then truncates it to the written length on close. btrfs does not split the preallocated extent on truncation: for as long as the file references any part of it, the whole extent stays allocated. A WAL holding a few kilobytes of records can pin tens of megabytes of disk this way.

Obsolete WALs compound it. They are moved to database_path/archive and reaped only once the archive passes 1 GB, which RocksDB measures from the length of the files rather than the space they occupy. Truncated WALs therefore sit there far longer than their real cost warrants, and they accumulate quickly on a server taking live traffic.

The gap between those two numbers is what makes this hard to recognize. du reports the small one; only df or btrfs filesystem usage shows the disk filling. compsize reports both for a directory. Defragmenting does not give the space back, so the files have to be rewritten or removed: setting the option stops any further growth, and an offline copy of database_path (see Offline backups) reclaims what has already accumulated.

ZFS

ZFS has several quirks that interact badly with RocksDB defaults. Apply both the Tuwunel config changes and the dataset properties below.

In tuwunel.toml:

  • rocksdb_direct_io = false. OpenZFS prior to 2.3 silently ignored O_DIRECT and fell back to buffered. OpenZFS 2.3+ honors O_DIRECT only when requests are page-aligned and a multiple of the recordsize, which RocksDB cannot guarantee.
  • rocksdb_allow_fallocate = false. OpenZFS does not implement fallocate(2) preallocation; only FALLOC_FL_PUNCH_HOLE and FALLOC_FL_ZERO_RANGE are supported. Tuwunel warns at startup while this is left enabled on ZFS.
  • Leave rocksdb_optimize_for_spinning_disks = false on NVMe or SSD pools, even when running on ZFS.

On the dataset hosting database_path:

PropertyValueReason
recordsize128K (or 64K)Match RocksDB’s working set. 16K causes severe write amplification on compaction.
primarycachemetadataTuwunel’s block cache already serves data; ARC caching of data duplicates RAM.
compressionoffRocksDB SSTs are already zstd-compressed by Tuwunel.
atimeoffAvoid an FS write per read.
logbiasthroughputRoute ZIL through the normal txg path, which suits append-only WAL traffic.

recordsize takes effect only on files written after the property is changed. After adjusting it, dump the database (offline copy out, wipe the dataset, copy back) so existing SSTs adopt the new recordsize. Without a dump-and-reload, compaction will gradually rewrite into the new recordsize over weeks; pre-existing files keep the old size in the meantime.

For sync write latency, in order of preference: a separate SLOG vdev, then logbias=throughput, then sync=disabled (only if you accept that a host crash may discard the WAL tail; Tuwunel recovers cleanly from this via rocksdb_recovery_mode=1, the default).

Files in database

Do not touch any of the files in the database directory. This must be said due to users being mislead by the .log files in the RocksDB directory, thinking they’re server logs or database logs, however they are critical RocksDB files related to WAL tracking.

The only safe files that can be deleted are the LOG files (all caps). These are the real RocksDB telemetry/log files, however Tuwunel has already configured to only store up to 3 RocksDB LOG files due to generally being useless for average users unless troubleshooting something low-level. If you would like to store nearly none at all, see the rocksdb_max_log_files config option.

Integrity checks

Use the !admin integrity commands in the admin room to check your database for problems. The checks do not change the database.

  1. Run !admin integrity list to see every check and what it verifies.
  2. Run !admin integrity check to run every check available on the open database. To run only certain checks, add their names after the command. Add --limit N to show up to N findings from each check (8 by default).

A check reports clean when it finds no problems. Otherwise, it reports the number of findings and a sample, or failed with the error.

Checks marked (read-only open) compare data across database columns. Writes during a check could look like defects, so these checks run only when the database is opened read-only. On a writable database, !admin integrity check skips them and lists them at the end. If you request one by name, it reports that it needs a read-only open.

Checking with the server stopped

To run the (read-only open) checks, stop the server and open its database read-only for the check.

Warning

Stop the server before opening its database read-only. RocksDB documents a read-only open beside a running server as undefined behavior, and Tuwunel does not refuse one.

Before running the commands below, check your Tuwunel configuration file. An explicit setting takes precedence over --read-only. For example, read_only = false under [global.rocksdb] keeps the database writable. In that case, the read-only open checks are reported as skipped.

For a systemd installation, run the following commands on the server host. The example uses the tuwunel service and user, and the configuration file /etc/tuwunel/tuwunel.toml. Adjust these to match your installation.

systemctl stop tuwunel
sudo -u tuwunel tuwunel --config /etc/tuwunel/tuwunel.toml --read-only \
	-O database_migrations=false --execute "integrity check" \
	--execute "server shutdown"
systemctl start tuwunel

The temporary process prints the findings, then --execute "server shutdown" shuts it down. The last command starts the normal service again. The --read-only option opens the database read-only, subject to the configuration override above. The -O database_migrations=false option skips startup migrations, which write to the database.

If startup reports that the required local state memo invalidation has not run, start once with database_migrations enabled before trying again.

Scheduling a repair

To schedule a repair, run !admin integrity repair NAME --yes-i-know-what-im-doing in the admin room. Replace NAME with one of the supported check names below.

  • pdu-room-ids
  • highlight-keys
  • relation-index
  • thread-summaries (also rebuilds the thread activity index)
  • thread-activity

The repair runs on the next start with database_migrations enabled, before the server begins serving. The command refuses to schedule a repair without the confirmation flag, on a database it cannot write, or for a check whose repair step is not safe to run twice. It gives the reason when it refuses.

Backups

Database backup, checkpoint, and restore procedures are documented on the Backups page.

Media

Media still needs various work, however Tuwunel implements media deletion via:

  • MXC URI or Event ID (unencrypted and attempts to find the MXC URI in the event)
  • Delete list of MXC URIs
  • Delete remote media in the past N seconds/minutes via filesystem metadata on the file created time (btime) or file modified time (mtime)

See the !admin media command for further information. All media in Tuwunel is stored at $DATABASE_DIR/media. This will be configurable soon.

If you are finding yourself needing extensive granular control over media, we recommend looking into Matrix Media Repo. Tuwunel intends to implement various utilities for media, but MMR is dedicated to extensive media management.

Built-in S3 support is also planned, but for now using a “S3 filesystem” on media/ works. Tuwunel also sends a Cache-Control header of 1 year and immutable for all media requests (download and thumbnail) to reduce unnecessary media requests from browsers, reduce bandwidth usage, and reduce load.

Troubleshooting Tuwunel

Important

If you intend on asking for support and you are using Docker, PLEASE triple validate your issues are NOT because you have a misconfiguration in your Docker setup. We must remain focused on supporting Tuwunel issues and cannot budget our time for generic Docker support. Compose file issues or Dockerhub image issues are okay if they are something we can fix.

Tuwunel and Matrix issues

Lost access to admin room

You can reinvite yourself to the admin room through the following methods:

  • Use the --execute "users make_user_admin <username>" Tuwunel binary argument once to invite yourself to the admin room on startup
  • Use the Tuwunel console/CLI to run the users make_user_admin command
  • Or specify the emergency_password config option to allow you to temporarily log into the server account (@conduit) from a web client

A room created with federation disabled cannot federate later

m.federate lives in the room’s m.room.create event, so it is fixed for the life of the room. Element sets it from the “Block anyone not part of <server> from ever joining this room” checkbox, whose own help text says the choice cannot be changed later. Inviting a user from another server into such a room is rejected with:

Auth check failed: MSC4361: room is not federated and target user domain does not match `m.room.create` event's sender domain

Synapse rejects the same event (“This room has been marked as unfederatable”), so the restriction is not specific to Tuwunel.

!admin federation enable-room does not lift it. That command clears an inbound-PDU block set earlier by !admin federation disable-room, a separate mechanism described under Policy and Moderation; run it on a non-federating room and it says so in its reply. The federate_created_rooms config option is no help either: it applies when a room is created, so changing it leaves every existing room alone.

Upgrading the room is not a workaround either: the replacement room inherits m.federate from its predecessor, as it does on Synapse. Moving the conversation to a newly created room is the only remedy.

General potential issues

Potential DNS issues when using Docker

Docker has issues with its default DNS setup that may cause DNS to not be properly functional when running Tuwunel, resulting in federation issues. The symptoms of this have shown in excessively long room joins (30+ minutes) from very long DNS timeouts, log entries of “mismatching responding nameservers”, and/or partial or non-functional inbound/outbound federation.

This is not a Tuwunel issue, and is purely a Docker issue. It is not sustainable for heavy DNS activity which is normal for Matrix federation. The workarounds for this are:

  • Use DNS over TCP via the config option query_over_tcp_only = true
  • Don’t use Docker’s default DNS setup and instead allow the container to use and communicate with your host’s DNS servers (host’s /etc/resolv.conf)

DNS No connections available error message

If you receive spurious amounts of error logs saying “DNS No connections available”, this is due to your DNS server (servers from /etc/resolv.conf) being overloaded and unable to handle typical Matrix federation volume. Some users have reported that the upstream servers are rate-limiting them as well when they get this error (e.g. popular upstreams like Google DNS).

Matrix federation is extremely heavy and sends wild amounts of DNS requests. Unfortunately this is by design and has only gotten worse with more server/destination resolution steps. Synapse also expects a very perfect DNS setup.

There are some ways you can reduce the amount of DNS queries, but ultimately the best solution/fix is selfhosting a high quality caching DNS server like Unbound without any upstream resolvers, and without DNSSEC validation enabled.

DNSSEC validation is highly recommended to be disabled due to DNSSEC being very computationally expensive, and is extremely susceptible to denial of service, especially on Matrix. Many servers also strangely have broken DNSSEC setups and will result in non-functional federation.

Tuwunel cannot provide a “works-for-everyone” Unbound DNS setup guide, but the official Unbound tuning guide and the Unbound Arch Linux wiki page may be of interest. Disabling DNSSEC on Unbound is commenting out trust-anchors config options and removing the validator module.

Avoid using systemd-resolved as it does not perform very well under high load, and we have identified its DNS caching to not be very effective.

dnsmasq can possibly work, but it does not support TCP fallback which can be problematic when receiving large DNS responses such as from large SRV records. If you still want to use dnsmasq, make sure you disable dns_tcp_fallback in Tuwunel config.

Raising dns_cache_entries in Tuwunel config from the default can also assist in DNS caching, but a full-fledged external caching resolver is better and more reliable.

If you don’t have IPv6 connectivity, changing ip_lookup_strategy to match your setup can help reduce unnecessary AAAA queries (1 - Ipv4Only (Only query for A records, no AAAA/IPv6)).

If your DNS server supports it, some users have reported enabling query_over_tcp_only to force only TCP querying by default has improved DNS reliability at a slight performance cost due to TCP overhead.

RocksDB / database issues

Disk fills up but the database does not appear to grow

On btrfs, du can report a database of a few hundred megabytes while df shows tens of gigabytes consumed and still climbing. RocksDB preallocates its write-ahead logs with fallocate(2), and Copy-on-Write keeps the whole preallocated extent pinned after the log is truncated on close, so the space a file occupies bears no relation to its length. Set rocksdb_allow_fallocate = false; see the btrfs section of maintenance for how to confirm the diagnosis and reclaim the space.

Database corruption

There are many causes and varieties of database corruption. There are several methods for mitigation, each with outcomes ranging from a recovered state down to a savage state. This guide has been simplified into a set of universal steps which everyone can follow from the top until they have recovered or reach the end. The details and implications will be explained within each step.

Tip

All command-line -O options can be expressed as environment variables or in the config file based on your deployment’s requirements. Note that --maintenance is equivalent to configuring startup_netburst = false and listening = false.

Important

Always create a backup of the database before running any operation. This is critical for steps 3 and above.

0. Start the server with the following options:

tuwunel --maintenance -O rocksdb_recovery_mode=0

This is actually a “control” and not a method of recovery. If the server starts you either do not have corruption or have deep corruption indicated by very specific errors from rocksdb citing corruption during runtime. If you are certain there is deep corruption skip to step 4, otherwise you are finished without any modifications.

1. Start the server in Tolerate-Corrupted-Tail-Records mode:

tuwunel --maintenance -O rocksdb_recovery_mode=1

The most common corruption scenario is from a loss of power to the hardware (not an application crash, though it is still possible). This is remediated by dropping the most recently written record. It is highly unlikely there will be any impact on the application from this loss. In the best-case the same data is often re-requested over the federation or replaced by a client. In the worst-case clients may need to clear-cache & reload to guarantee correctness. If the server starts you are finished.

2. Start the server in Point-In-Time mode:

tuwunel --maintenance -O rocksdb_recovery_mode=2

Similar to the corruption scenario above but for more severe cases. The most recent records are discarded back to the point where there is no corruption. It is highly unlikely there will be any impact on the application from this loss, but it is more likely than above that clients may need to clear-cache & reload to correctly resynchronize with the server.

3. Start the server in Skip-Any-Corrupted-Record mode:

Warning

Salvage mode potentially impacting the application’s ability to function. We cannot provide support for users who have entered this mode.

tuwunel --maintenance -O rocksdb_recovery_mode=3

Similar to the prior corruption scenarios but for the most severe cases. The database will be inconsistent. It is theoretically possible for the server to continue functioning without notable issue in the best case, but it is completely uncertain what the effect of this operation will be. If the server starts you should immediately export your messages, encryption keys, etc, in a salvage effort and prepare to reinstall.

4. Start the server in repair mode.

Warning

Salvage mode potentially impacting the application’s ability to function. We cannot provide support for users who have entered this mode.

Caution

Always create a backup of the database before entering this mode. The repair is not configurable and not interactive. It may automatically remove more data than anticipated, preventing further salvage efforts.

tuwunel --maintenance -O rocksdb_repair=true

For corruption affecting the bulk database tables not covered by any journal. This will leave the database in an inconsistent and unpredictable state. It is theoretically possible to continue operating the server depending on which records were dropped, such as some historical records which are no longer essential. Nevertheless the impact of this operation is impossible to assess and a successful recovery should be used to salvage data prior to reinstall.

Once finished, restart the server without rocksdb_repair. If no errors persist, restart the server again without maintenance mode.

5. Utilize an external repair tool.

Warning

Salvage mode potentially impacting the application’s ability to function. We cannot provide support for users who have entered this mode.

git clone https://github.com/facebook/rocksdb
cd rocksdb
make -j$(nproc) ldb
./ldb repair --db=/var/lib/tuwunel/ 2>./repair-log.txt

For situations when the repair mode in step 4 failed or produced unexpected results.

Debugging

Note that users should not really be debugging things. If you find yourself debugging and find the issue, please let us know and/or how we can fix it. Various debug commands can be found in !admin debug.

Debug/Trace log level

Tuwunel builds without debug or trace log levels at compile time by default for substantial performance gains in CPU usage and improved compile times. If you need to access debug/trace log levels, you will need to build without the release_max_log_level feature or use our provided release-logging binaries and images.

Changing log level dynamically

Tuwunel supports changing the tracing log environment filter on-the-fly using the admin command !admin debug change-log-level <log env filter>. This accepts a string without quotes the same format as the log config option.

Example: !admin debug change-log-level debug

This can also accept complex filters such as: !admin debug change-log-level info,conduit_service[{dest="example.com"}]=trace,ruma_state_res=trace !admin debug change-log-level info,conduit_service[{dest="example.com"}]=trace,conduit_service[send{dest="example.org"}]=trace

And to reset the log level to the one that was set at startup / last config load, simply pass the --reset flag.

!admin debug change-log-level --reset

Pinging servers

Tuwunel can ping other servers using !admin debug ping <server>. This takes a server name and goes through the server discovery process and queries /_matrix/federation/v1/version. Errors are outputted.

While it does measure the latency of the request, it is not indicative of server performance on either side as that endpoint is completely unauthenticated and simply fetches a string on a static JSON endpoint. It is very low cost both bandwidth and computationally.

Allocator memory stats

!admin server memory-usage reports the memory held by Tuwunel’s caches and the database, not the allocator’s own figures.

If you are a developer, you can view jemalloc’s raw report with !admin debug memory-stats. Please note that this output is extremely large which may only be visible in the Tuwunel console CLI due to PDU size limits, and is not easy for non-developers to understand. When jemalloc is built as part of Tuwunel, statistics collection is disabled, so the report shows the allocator’s configuration but no usage counters.

Matrix RTC test tool

testmatrix is a command line tool for testing various aspects of a matrix server and guiding debugging. Details for troubleshooting Matrix RTC can be found in the Matrix RTC chapter on troubleshooting.

Development

Information about developing the project. If you plan on contributing, see the contributor’s guide. If you are only interested in using it, you can safely ignore this page.

Rust Documentation

Tuwunel’s rustdocs are hosted within this book under the /docs directory. Developers may build the same documentation locally using cargo doc.

Tuwunel project layout

Tuwunel uses a collection of sub-crates, packages, or workspace members that indicate what each general area of code is for. All of the workspace members are under src/. The workspace definition is at the top level Cargo.toml. See the Rust documentation on Workspaces for general questions and information on Cargo workspaces.

Tuwunel’s crates form a directed acyclic-graph without circular dependencies. Listed here from the top are the most abstract down to the most dependent at the bottom. Crates only have visibility into other crates listed above them; they cannot see structs or call functions in any crate listed below them.

  • tuwunel_macros are Tuwunel Rust macros like general helper macros, logging and error handling macros, and syn and procedural macros.

  • tuwunel_core is core Tuwunel functionality like config loading, error definitions, global utilities, logging infrastructure, etc.

  • tuwunel_matrix is the Matrix data model shared by the crates below it: the event and PDU types, room version rules, and the state resolution algorithm. It depends only on tuwunel_core.

  • tuwunel_database is RocksDB encapsulation, interface wrappers, configurations, and our opinionated asynchronous database frontend.

  • tuwunel_service is stateful runtime functionality at the heart of the application. This crate is divided into “services” each with “workers” and queues and all of the moving parts that attend to the tasks of sending messages and notifications, etc. Each service attempts to encapsulate any database tables it requires for its persistent state. Services call other services and they do not form an acyclic graph, for now.

  • tuwunel_api is the contract shared by the HTTP API crates below it: the Ruma request extractor, request authentication, and the response types. It holds no endpoint handlers itself.

  • tuwunel_api_client, tuwunel_api_federation, tuwunel_api_admin, tuwunel_api_oidc and tuwunel_api_mas are the stateless runtime functionality, one crate per API surface: the Matrix Client-Server API, the Server-Server (federation) API, the administration endpoints (the Synapse-compatible admin API and the client admin endpoints), the native OpenID Connect provider, and the Matrix Authentication Service integration. Their http handlers call various services to query or update their state as necessary. They do not interface with raw data or database functions except through a service.

  • tuwunel_admin is a module that implements the admin room as a broad set of command API handlers. Similar to tuwunel_api these handlers also interface with various services as necessary. Currently the admin crate does not call into the API crates as a dependency, but this is not intentional and subject to change.

  • tuwunel_router is the webserver and request handling bits, using axum, tower, tower-http, hyper, etc, and the server state to drive the handlers of the API crates.

  • main is the binary executable. This is where the main() function lives, tokio worker and async initialisation, Sentry initialisation, clap init, and signal handling. If you are adding new Rust features, they must go here. This crate is also capable of compiling as a library for integration testing and embedding.

Notes

It is highly unlikely you will ever need to add a new workspace member, instead look to create a new Service to implement distinct or unique functionality. If you truly find yourself needing another crate, we recommend reaching out to us in the Matrix room for discussions about it beforehand.

The primary inspiration for this design was apart of hot reloadable development, to support “Tuwunel as a library” where specific parts can simply be swapped out. There is evidence Conduit wanted to go this route too as axum is technically an optional feature in Conduit, and can be compiled without the binary or axum library for handling inbound web requests; but it was never completed or worked.

Adding compile-time features

To add a compile-time feature:

  1. Define it in the Cargo.toml of each workspace crate whose code or dependencies it changes. Crates in between do not define it.
  2. Define it in src/main/Cargo.toml, forwarding it to each of those crates. For example, a feature named woof in the api crate is defined there as woof = [] and in main as woof = ["tuwunel-api/woof"].
  3. If the feature is on by default, add it to the default list of main and of each crate defining it.
  4. Add a row to Build Features, with its default membership and any runtime requirement.

A crate’s default also enables the default of each workspace dependency that defines one. This gives the crate the same features when built alone as in the server. See Crate defaults.

Rust / Cargo does not support “workspace level features”, so main is the one place that defines the public features and their defaults, and the crate defaults only mirror it. Our Nix flake collects the default feature set from main’s default alone. It takes that crate’s own feature names and skips the forwarded crate defaults.

List of forked dependencies

During Tuwunel development, we have had to fork some dependencies to support our use-cases in some areas. This ranges from things said upstream project won’t accept for any reason, faster-paced development (unresponsive or slow upstream), Tuwunel-specific usecases, or lack of time to upstream some things.

Debugging with tokio-console

tokio-console can be a useful tool for debugging and profiling. To make a tokio-console-enabled build of Tuwunel, enable the tokio_console feature, disable the default release_max_log_level feature, and set the --cfg tokio_unstable flag to enable experimental tokio APIs. A build might look like this:

RUSTFLAGS="--cfg tokio_unstable" cargo +nightly build \
    --release \
    --no-default-features \
    --features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console

You will also need to enable the tokio_console config option in Tuwunel when starting it. This was due to tokio-console causing gradual memory leak/usage if left enabled.

Contributing guide

If you would like to work on an issue that is not assigned, preferably ask in the Matrix room first at #tuwunel:grin.hu, and comment on it.

Inclusivity and Diversity

All MUST code and write with inclusivity and diversity in mind. See the following page by Google on writing inclusive code and documentation.

This EXPLICITLY forbids usage of terms like “blacklist”/“whitelist” and “master”/“slave”, forbids gender-specific words and phrases, forbids ableist language like “sanity-check”, “cripple”, or “insane”, and forbids culture-specific language (e.g. US-only holidays or cultures).

No exceptions are allowed. Dependencies that may use these terms are allowed but do not replicate the name in your functions or variables.

In addition to language, write and code with the user experience in mind. This is software that intends to be used by everyone, so make it easy and comfortable for everyone to use. 🏳️‍⚧️

Linting and Formatting

It is mandatory all your changes satisfy the lints (clippy, rustc, rustdoc, etc) and your code is formatted via the nightly cargo fmt. A lot of the rustfmt.toml features depend on nightly toolchain. It would be ideal if they weren’t nightly-exclusive features, but they currently still are. CI’s rustfmt uses nightly.

If you need to allow a lint, please make sure it’s either obvious as to why (e.g. clippy saying redundant clone but it’s actually required) or it has a comment saying why. Do not write inefficient code for the sake of satisfying lints. If a lint is wrong and provides a more inefficient solution or suggestion, allow the lint and mention that in a comment.

Variable, comment, function, etc standards

Rust’s default style and standards with regards to function names, variable names, comments, etc applies here.

Software testing

Continuous integration runs Complement protocol compliance tests against Tuwunel. The results are compared against a stored baseline via git diff — both new failures and new passes are flagged. If your changes affect compliance, note it in your pull request and review the result diff uploaded as an artifact.

See Complement Testing for details on how the test harness works and how to run Complement locally against a debug or release build.

Writing documentation

Tuwunel’s website uses mdbook containing rustdoc which are deployed via CI pipeline using GitHub Pages. All documentation is in the docs/ directory at the top level. The compiled mdbook website is also uploaded as an artifact.

  • To build the book locally run mdbook build -d <outdir> . in the project root.

  • To build the book using local stages of the CI pipeline run docker/bake.sh book; the produced docker image will contain it.

  • To build the book using Nix, run: nix/pkgs/complement/bin/nix-build-and-cache just .#book. Exporting CACHIX_AUTH_TOKEN first also uploads the result to the binary cache.

Rust API documentation (rustdoc) is generated from the sourcecode contained in src/ and deployed via CI to a directory within GitHub Pages adjacent to the book. In other contexts mdbook and rustdoc are independent.

  • To build the API documents locally run cargo doc and browse to target/doc/tuwunel/.

  • To build the API documents using local stages of the CI pipeline run docker/bake.sh docs; the produced docker image will contain results in /usr/src/tuwunel/target/x86_64-unknown-linux-gnu/doc (and one can extrapolate for other platforms).

Creating pull requests

Please try to keep contributions to the GitHub. While the mirrors of Tuwunel allow for pull/merge requests, there is no guarantee I will see them in a timely manner. Additionally, please mark WIP or unfinished or incomplete PRs as drafts. This prevents me from having to ping once in a while to double check the status of it, especially when the CI completed successfully and everything so it looks done.

If you open a pull request on one of the mirrors, it is your responsibility to inform me about its existence. In the future I may try to solve this with more repo bots in the Tuwunel Matrix room. There is no mailing list or email-patch support on the sr.ht mirror, but if you’d like to email me a git patch you can do so at jasonzemos@gmail.com.

Direct all PRs/MRs to the main branch.

By sending a pull request or patch, you are agreeing that your changes are allowed to be licenced under the Apache-2.0 licence and all of your conduct is in line with the Contributor’s Covenant, and Tuwunel’s Code of Conduct.

Contribution by users who violate either of these code of conducts will not have their contributions accepted. This includes users who have been banned from Tuwunel Matrix rooms for Code of Conduct violations.

Stale Branch Policy

This section applies to Matrix-Construct members and Tuwunel maintainers

Branches on the matrix-construct/tuwunel repository are centrally maintained. They may be rebased without your consent. Trivial conflicts may be resolved by another maintainer. Please resolve more difficult conflicts as soon as possible. Stale branches may be deleted in some cases; personal repositories are advised for avoiding any such complications.

Protocol Implementation

Specification Compliance

Todo

MSC Implementation Status

The status table lists every memo Tuwunel knows about,

Complement Testing

The Complement results page summarizes runs of the Complement homeserver acceptance suite.

Complement Crypto Testing

The Complement Crypto results page summarizes end-to-end encryption tests run with Matrix Rust SDK clients.

Complement Interoperability

The Complement interoperability page compares runs with Tuwunel and Synapse in both homeserver positions.

Complemau Testing

The Complemau results page summarizes Tuwunel’s Complement-based application service acceptance tests.

Synapse Admin API

The Synapse Admin API status page lists every /_synapse/admin endpoint and whether Tuwunel serves it, so administration dashboards and moderation bots know what to expect.

Tuwunel MSC Implementation Status

Columns

  • Inv: inventory status (matrix-spec-proposals state). One of merged, open, closed, unknown.
  • Status: ✅ yes / 🟨 partial / 🟥 no / ⬛ n/a / ❔ ? (never assessed; a question not yet asked, which is not the same claim as no), followed by a confidence glyph (● high / ◐ med / ○ low / · unknown) that reflects confidence in the assessment, not in the implementation.
  • Impl: two percentages, correct/impl, e.g. 70/80.
    • correct: the share Tuwunel adheres to correctly.
    • impl: the share with any code path attempting adherence, so correct never exceeds impl. Either may be ?.
    • denominator: the MSC’s homeserver-applicable scope, the requirements a homeserver itself must satisfy.
    • requirement: any requirement-shaped statement, not just MUST/SHOULD. Proposals are loosely normative, so “the server returns X” and “this field is added to Y” both count.
  • Spec: the Matrix spec version that first published the MSC, in the Spec compliance gaps section only. 1.0 is the spec before 1.1, when each API carried its own version. next is merged but in no release yet; the newest release is 1.19.

Counts

✅ yes🟨 part🟥 no⬛ n/atotal
292614453121110

Status by inventory bucket

Invyespartnon/atotal
merged189221357281
open6724346181618
closed36158674211

Merged

Sorted by MSC number, highest first. Out-of-scope rows are listed in the Out of scope section.

MSCStatusImplTitleNote
MSC4551🟨 ◐40/70Sliding Sync Extensions: ReceiptsReceipt delivery exists; initial/rescope gaps. Client application excluded.
MSC4548🟨 ◐70/90Sliding Sync Extensions: Account dataClient caching excluded; first-enable and independent room-scope gaps
MSC4543🟨 ◐70/90Sliding Sync Extensions: End-to-end encryptionNo-pos and count rules met; left misses departures, bans; claim race; flag held
MSC4538✅ ●90/100Sliding Sync Extensions: To-Device messagesLimit, ack, drain and flag per MSC; numeric since above position: 200, not 400
MSC4508🟨 ◐60/80Sliding Sync Extensions: Common format and TypingTyping exists; joined-only filtering and scope reentry remain incomplete.
MSC4458✅ ●90/100Handling incoming JSON in the server-server APISigned bodies parsed canonically before auth; refuses -0, which spec maps to 0
MSC4452✅ ●100/100Preview URL capabilities APIStable m.preview_url and unstable alias from one gate; disabled routes 403
MSC4436✅ ●100/100Make server ACLs case insensitiveacl_check.rs:39 uses ruma is_allowed, which matches case insensitively
MSC4423✅ ●100/100Undefine order of room directorydirectory.rs:331 member-count order stays valid once ordering is undefined
MSC4402✅ ◐100/100Consistent redirects for .well-known-files[→ MSC2499?] Global CORS layer covers any 30x; well-known client returns 200 …
MSC4380✅ ●100/100Invite blockingsrc/api/client/sync/{v3.rs,v5/selector.rs} suppress stored invites; createRoo…
MSC4376✅ ●100/100Remove /v1/send_join and /v1/send_leavev1 send_join and v1 send_leave routes are not registered
MSC4356✅ ●100/100Recently used emojiglobal account-data passthrough (2026-06-22 ruling); m.recent_emoji round-trips
MSC4354🟥 ●0/0Sticky EventsNo sticky delivery or expiry paths; client ephemeral maps excluded
MSC4341✅ ●95/100Support for RFC 8628 Device Authorization Grantsrc/api/oidc/device.rs:62; RFC 8628 device grant advertised, minted, polled
MSC4335🟥 ●0/0M_USER_LIMIT_EXCEEDED error codeM_USER_LIMIT_EXCEEDED error code not used
MSC4326✅ ●100/100Device masquerading for appservicesappservice query device_id asserted; M_UNKNOWN_DEVICE-equivalent on missing
MSC4323✅ ●100/100User suspension & locking endpointssrc/api/client/admin.rs four routes at stable v1 paths; m.account_moderation …
MSC4319🟨 ●50/50Room member events for invite and knock rooms in the /sync responsestate/mod.rs:464 puts inviter member in stripped state; no state key
MSC4312✅ ●85/85Resetting cross-signing keys in the OAuth worldcross-signing reset via OAuth account deep-link; dual-stage advertise deferred
MSC4311✅ ●80/90Ensuring the create event is available on invites4-field client create; v12 missing/wrong-room create rejects; rest knob-gated
MSC4307✅ ●100/100Validate that auth_events are in the correct roomauth_event room_id mismatch rejected
MSC4304✅ ●100/100Room Version 12V12 stable and the default room version
MSC4297✅ ●100/100State Resolution v2.1src/service/rooms/state_res/resolve.rs:257 conflicted state subgraph; tests pass
MSC4291✅ ●100/100Room IDs as hashes of the create eventv12 upgrade create event omits deprecated predecessor.event_id
MSC4289✅ ●100/100Explicitly privilege room creatorsRoom v12 creator privilege; complement 22 pass, 0 fail across six named tests
MSC4287✅ ●100/100Sharing key backup preference between clientsglobal account-data passthrough (2026-06-22 ruling); m.key_backup round-trips
MSC4284🟨 ●70/90Policy Serversoutbound /sign, inbound verify, fetch-on-missing, reversible soft-fail
MSC4278✅ ●100/100Media preview controlsglobal+room passthrough ok; seeded-value mutability met; no content validation
MSC4277✅ ●100/100Harmonizing the reporting endpointsall 3 wired; score removed; user report 200 regardless to deter enumeration
MSC4267✅ ●90/100Automatically forgetting rooms on leaveauto-forget on Leave/Ban; stable + unstable capability advertised
MSC4260✅ ●85/90Reporting users (Client-Server API)src/api/client/report.rs:63; admin notification, 404 M_NOT_FOUND on unknown u…
MSC4254✅ ●95/100Usage of [RFC7009] Token Revocation for Matrix client logoutsrc/api/oidc/revoke.rs:37; RFC7009 form-urlencoded; revokes both tokens; 200 …
MSC4239✅ ●100/100Room version 11 as the default room versiondefault is V12, at or above the v11 the MSC suggests
MSC4225✅ ●100/100Specification of an order in which one-time-keys should be issuedOTKs issued in upload order via count_be prefix; src/service/users/keys.rs:99
MSC4222✅ ●95/100Adding state_after to /syncdialects honored; lazy-loaded state_after carries changed members
MSC4213✅ ●90/90Remove server_name parameterjoin/knock use via; server_name still accepted via Ruma fallback
MSC4210✅ ●100/100Remove legacy mentionsdeprecated mention push rules removed at /pushrules read time
MSC4195🟨 ◐10/10MatrixRTC Transport using LiveKit BackendTransport advertisement only; token and leave APIs absent; client media excluded
MSC4191✅ ●100/100Account management for OAuth 2.0 APIall six actions advertised and handled; stable names alias prototypes
MSC4190✅ ●100/100Device management for application services201 on create; M_APPSERVICE_LOGIN_UNSUPPORTED on AS login+register
MSC4189✅ ◐80/100Allowing guests to access uploaded mediaguest tokens accepted on authenticated media routes
MSC4186✅ ●85/88Simplified Sliding Syncsync v5 served with lists, filters, extensions; no expanded_timeline or stubs
MSC4183🟥 ●0/0Additional Error Codes for submitToken endpointsmixed MSC; the submit_url half is homeserver scope and we emit no submit_url
MSC4180✅ ●100/100Add a stable flag to MSC3916stable feature flag for MSC3916 advertised
MSC4178🟨 ●75/90Error codes for requestTokenmsisdn returns M_THREEPID_MEDIUM_NOT_SUPPORTED; bad email returns M_INVALID_P…
MSC4175✅ ●100/100Profile field for user time zonetimezone PUT/DELETE/GET routes; m.tz aliased in profile and over federation
MSC4170✅ ◐100/100403 error responses for profile APIsprofile lookup unrestricted; MUST minimum satisfied
MSC4169✅ ●100/100Backwards-compatible redaction sending using /sendsrc/api/client/send.rs:42; lifts content.redacts into PduBuilder.redacts; adv…
MSC4163✅ ●100/100Make ACLs apply to EDUsACLs applied on receipt and typing EDUs
MSC4156✅ ●100/100Migrate server_name to viavia parameter handled via Ruma
MSC4151✅ ●100/100Reporting rooms (Client-Server API)POST /rooms/{roomId}/report implemented and routed
MSC4143🟨 ◐70/90MatrixRTCDiscovery, upgrade slot copy, delayed leave; no sticky member or transport auth
MSC4140✅ ●80/80Cancellable delayed eventsFull lifecycle, finalised records, sender-only delay_id; no rate limits
MSC4138✅ ●100/100Update allowed HTTP methods in CORS responsesCORS METHODS list includes HEAD and PATCH; excludes CONNECT/TRACE
MSC4133✅ ●85/95Extending User Profile API with Custom Key:Value Pairsendpoints + caps/errcodes; unset legacy 200 omit by choice, 404 key-scoped
MSC4127🟥 ●0/0Removal of query string authsrc/api/router/auth.rs:78 still falls back to request.query.access_token
MSC4115✅ ●85/85membership metadata on eventssrc/core/matrix/pdu/unsigned.rs add_membership; src/service/rooms/state_acces…
MSC4041✅ ◐90/90Use http header Retry-After to enable library-assisted retry handlingRuma error type emits Retry-After header for LimitExceeded responses.
MSC4040✅ ●100/100Update SRV service name to IANA registrationTuwunel queries _matrix-fed first then falls back to _matrix.
MSC4026✅ ◐80/90Allow /versions to optionally accept authenticationversions endpoint accepts optional auth via Ruma
MSC4025✅ ●85/85Local user erasure requestsphase B landed: erased senders serve pruned to clients and federation
MSC4010✅ ●100/100Push rules and account datam.push_rules and m.fully_read rejected on /account_data
MSC4009✅ ●100/100Expanding the Matrix ID grammar to enable E.164 IDsE.164 + character allowed via Ruma localpart validation
MSC3989✅ ●100/100Redact origin property on eventsV11 redaction drops origin via Ruma RedactionRules
MSC3987✅ ●90/90Push actions clean-upunknown push actions ignored as no-ops
MSC3981✅ ●100/100/relations recursion/relations recurse parameter implemented with depth 3
MSC3980✅ ●90/90Dotted Field Consistencyevent_fields trim on /sync; dotted paths use the MSC3873 escape grammar
MSC3970🟨 ◐70/80Scope transaction IDs to devicestxn key is user, device, txn with no path; redact untracked; echo user scoped
MSC3967✅ ●100/100Do not require UIA when first uploading cross signing keyskeys/device_signing/upload skips UIA when user has no existing cross-signing …
MSC3966✅ ●100/100event_property_contains push rule conditionevent_property_contains supported via Ruma push conditions
MSC3958✅ ●100/100Suppress notifications from message editsSuppressEdits push rule provided via Ruma server_default ruleset
MSC3952✅ ◐80/90Intentional MentionsIntentional mentions push rules ride on Ruma server_default; flag advertised.
MSC3943✅ ●100/100Partial joins to nameless rooms should include heroes’ memberships.send_join partial-state response includes hero memberships and their auth chains
MSC3939✅ ●90/90Account lockingLogin and refresh gates implemented; OIDC account-state gates remain pending
MSC3938✅ ●100/100Remove deprecated keyId parameters from /keys endpointsonly the keyless /key/v2/server is routed; no notary /query left to change
MSC3930✅ ●100/100Polls push rules/notificationsDefault poll push rules via ruma server_default; seeded at registration
MSC3925🟨 ●70/70m.replace aggregation with full eventFull m.replace fold; off by default (bundle_edit_relations); backfill unindexed
MSC3916✅ ●90/100Authentication for media access, and new endpoint namesNew /client/v1/media and /federation/v1/media auth endpoints implemented.
MSC3905✅ ●100/100Application services should only be interested in local userssrc/service/appservice/append.rs:66; local-user guard at the three event-inte…
MSC3904✅ ●100/100Room version 10 as the default room versiondefault is V12, at or above the v10 the MSC suggests
MSC3882✅ ●90/100Allow an existing session to sign in a new sessionPOST /login/get_token implemented with UIA
MSC3873✅ ●100/100event_match dotted keysdotted-key escape semantics handled in ruma flattened JSON
MSC3861✅ ●90/95Next-generation auth for Matrix, based on OAuth 2.0/OIDCFlag needs the OIDC server; cores 2964-2967 + merged periphery all yes
MSC3860✅ ◐95/100Media Download RedirectsEmits 307 to presigned object-store URL on allow_redirect; default-off gate
MSC3856✅ ●90/100Threads List APIsrc/api/client/threads.rs:81 roots retained; full API, residual fallbacks
MSC3828✅ ●100/100Content Repository Cross Origin Resource Policy (CORP) Headersmedia endpoints return Cross-Origin-Resource-Policy: cross-origin
MSC3827✅ ●100/100Filtering of /publicRooms by room type/publicRooms supports room_types filter and returns room_type
MSC3824✅ ◐90/100OAuth 2.0 API aware clientsoauth_aware_preferred set; SSO redirect action forwards as OIDC prompt (opt-in)
MSC3823✅ ●100/100Account SuspensionM_USER_SUSPENDED maps to 403; route and handler suspension gates remain
MSC3821✅ ●90/100Update redaction rules, againredact_in_place uses Ruma RedactionRules.V11 with keep third_party_invite.signed
MSC3820✅ ●90/100Room Version 11v11 stable; redaction and auth rules dispatch via Ruma RoomVersionRules
MSC3818✅ ●100/100Copy room type on upgradeupgrade reuses old m.room.create content; type preserved by default
MSC3816✅ ●100/100Clarify Thread Participationcurrent_user_participated recomputed per requester at read time on all paths
MSC3787✅ ●100/100Allowing knocks to restricted roomsKnock-restricted fully wired; remote re-knock reconciles the room server
MSC3786✅ ●100/100Add a default push rule to ignore m.room.server_acl eventsserver_acl predefined push rule via Ruma defaults
MSC3773✅ ●100/100Notifications for threadssrc/service/pusher/notification.rs:143 per-thread counts; src/api/client/sync…
MSC3771✅ ●100/100Read receipts for threadssrc/api/client/read_marker.rs validates+routes thread; receipt and private_re…
MSC3765✅ ●90/100Rich text in room topicsreader prefers m.topic text/plain; topic text now indexed for search
MSC3758✅ ●90/100Add event_property_is push rule condition kindevent_property_is dispatched via Ruma Ruleset::get_actions
MSC3743✅ ●90/100Standardized error response for unknown endpointsM_UNRECOGNIZED 404/405 fallback wired in router
MSC3715✅ ◐100/100Add a pagination direction parameter to /relationsRelations direction and prev_batch reuse implemented; client UI excluded
MSC3706✅ ●90/100Extensions to /_matrix/federation/v2/send_join/{roomId}/{eventId} for parti…send_join supports omit_members, members_omitted, servers_in_room
MSC3667✅ ●100/100Enforce integer power levelsinteger_power_levels enforced via RoomVersionRules from V10+
MSC3666✅ ●90/100Bundled aggregations for server side searchresult + context events bundled; thread always, edit/ref gated default-off
MSC3604✅ ●100/100Room Version 10V10 supported; integer_power_levels and knock_restricted enforced
MSC3589✅ ●100/100Room version 9 as a defaultdefault_room_version defaults to V12 (exceeds V9)
MSC3567✅ ●100/100Allow requesting events from the start/end of the room historyfrom is optional; defaults to start/end based on dir
MSC3550🟥 ◐0/0Add HTTP 403 to possible profile lookup responsesCS /profile returns 403 M_FORBIDDEN when outbound profile lookup disabled
MSC3442✅ ●100/100move the prev_content key to unsignedprev_content placed under unsigned in created/appended PDUs
MSC3440✅ ●80/88MSC3440 Threading via m.thread relation[→ MSC3856] related_by_* filters on /messages+/context; .stable advert; neste…
MSC3419✅ ○100/100Guest State Eventsno guest-specific gate on state-event send path; PL/auth_check applies unifor…
MSC3383✅ ●100/100Include destination in X-Matrix Auth HeaderX-Matrix destination field validated on inbound federation
MSC3375✅ ●100/100Room Version 9room v9 stable; redaction keeps join_authorised_via_users_server
MSC3316✅ ●100/100Proposal to add timestamp massaging to the specappservice ts honored on /send and /state
MSC3289✅ ●100/100Room Version 8room v8 listed stable; restricted join rule auth implemented
MSC3288🟥 ●0/0Add room type to /_matrix/identity/v2/store-invite APIsole clause is addressed to homeservers, so not n/a; no 3PID invite at all
MSC3283✅ ●100/100Expose enable_set_displayname, enable_set_avatar_url and enable_3pid_changes …src/api/client/capabilities.rs explicitly emits m.set_displayname, m.set_avat…
MSC3267🟨 ◐60/80reference relationshipsm.reference bundle added; gated default-off; no ignore/visibility filter
MSC3266✅ ●100/100Room Summary APIsummary endpoint routed at unstable and (via Ruma) stable paths
MSC3231✅ ●100/100Token Authenticated Registrationregistration token UIA + validity endpoint implemented
MSC3226✅ ●100/100Per-room spell checkroom account data passthrough (m.input_language, fractal type); UI excluded
MSC3173✅ ●100/100Expose stripped state events to any potential joinersummary_stripped includes recommended events incl create
MSC3083✅ ●100/100Restricting room membership based on membership in other roomsrestricted_join_rule auth via RoomVersionRules; v8/v9
MSC3069✅ ◐80/100Allow guests to use /account/whoamiwhoami returns is_guest; uses is_deactivated heuristic
MSC3030✅ ●90/100Jump to date API endpointclient+fed handlers, outbound fallback + same-ts order; 3 leaves AS-blocked
MSC2998✅ ●100/100Room Version 7V7 listed in STABLE_ROOM_VERSIONS; full knock support present
MSC2967✅ ●80/90API scopessrc/api/oidc/token.rs:96; stable+unstable device scope honored, surfaced, req…
MSC2966✅ ●85/95Usage of OAuth 2.0 Dynamic Client Registration in MatrixFull RFC 7591/8252 metadata validation; drops unknown grant/response
MSC2965✅ ●90/100OAuth 2.0 Authorization Server Metadata discoveryauth_issuer and auth_metadata routes return OAuth provider metadata
MSC2964✅ ●88/100Usage of OAuth 2.0 authorization code grant and refresh token grantsrc/api/oidc/authorize.rs:57; S256 PKCE now required on the auth-code grant
MSC2946✅ ●90/100Spaces Summaryclient and federation hierarchy endpoints implemented
MSC2918✅ ●90/100Refresh tokens/refresh, expires_in_ms, refresh_token in /login and /register
MSC2874✅ ●100/100Single SSSSSSSS key and default_key account data passthrough; client key choice excluded
MSC2870✅ ◐100/100Protect server ACLs from redactionredaction dispatches on RoomVersionRules.redaction; ruma MSC2870 enabled
MSC2867✅ ◐100/100Marking rooms as unreadclient convention; account data type stored generically
MSC2858✅ ●100/100Multiple SSO Identity Providersidentity_providers in /login flows; /login/sso/redirect/{idpId} routed
MSC2844✅ ●90/90Using a global version number for the entire specificationsrc/api/client/versions.rs advertises v1.1 through v1.15
MSC2832✅ ●100/100Homeserver -> Application Service authorization headersrc/service/appservice/request.rs sends Bearer header and query
MSC2788✅ ●100/100Room version 6 as a defaultdefault_default_room_version is V12 in src/core/config/mod.rs:5752
MSC2778✅ ●100/100Providing authentication method for appservice userssrc/api/client/session/appservice.rs implements m.login.application_service
MSC2765✅ ●100/100Widget avatarsavatar_url in m.widgets kept verbatim; rendering and room widget state excluded
MSC2732✅ ●100/100Olm fallback keyssrc/api/client/keys/claim_keys.rs:86; upload, claim-fallback, sync-unused-lis…
MSC2705✅ ●90/90Animated thumbnailsanimated honored and animated GIF generated; webp output preference unmet
MSC2702✅ ●100/100Content-Disposition usage in the media repoContent-Disposition and inline allowlist enforced for media downloads, thumbn…
MSC2701✅ ◐80/90Media and the Content-Type relationshipOptional Content-Type accepted; stored and returned
MSC2689✅ ◐100/100Allow guests to operate in encrypted roomsAuth treats guests like users; /members open
MSC2677✅ ●80/90Annotations and ReactionsDuplicate annotation rejected; reactions plumbed
MSC2676🟨 ●50/60Message editingedits accepted/relayed; no m.replace bundle or new_content apply
MSC2675🟨 ◐60/75Serverside aggregations of message relationshipsthread+edit+reference bundled (edit/ref gated); reactions unbundled
MSC2674✅ ●90/100Event relationshipsrelates_to handled in append; rel_type tracked
MSC2666✅ ●92/100Get rooms in common with another userv1 stable path + count + cursor pagination; self-query/non-compliant 400
MSC2663✅ ●100/100Errors for dealing with non-existent push rulessrc/api/client/push.rs all 7 endpoints return NotFound
MSC2659✅ ●95/100Application service ping endpointping surfaces M_CONNECTION_TIMEOUT/FAILED and M_BAD_STATUS per spec
MSC2604🟥 ●0/0Parameters for Login Fallbacklogin fallback page is homeserver served, so not n/a; Tuwunel ships no page
MSC2545✅ ◐100/100Image Packs (Emoticons & Stickers)image_pack.rooms passthrough; federated packs never grammar-checked; UX excluded
MSC2540✅ ◐80/80Stricter event validation: JSON compliancecanonical JSON enforced at the parse boundary, not keyed off room version
MSC2526✅ ●100/100Add ability to delete key backupssrc/api/client/backup.rs:134 delete_backup_version_route
MSC2472✅ ●100/100Symmetric SSSSSSSS key metadata and secrets kept verbatim; client crypto and trust excluded
MSC2457✅ ●100/100Invalidating devices during password modificationsrc/api/client/account.rs:41 honors body.logout_devices
MSC2454✅ ●90/90User-Interactive Authentication for SSO-backed homeserversrc/api/router/auth/uiaa.rs:53 sso_flow; sso/uiaa.rs serves fallback
MSC2451✅ ●100/100Remove the query_auth federation endpointNo /query_auth route registered in src/api/router.rs
MSC2432✅ ◐80/90Updated semantics for publishing room aliasesalt_aliases wired; canonical_alias resolve check; rooms/{}/aliases route present
MSC2414✅ ●100/100Make reason and score optional for reporting contentreason and score are Option in ruma report types; route accepts both
MSC2409🟨 ●70/70Proposal to send typing, presence and receipts to appservicestyping+receipt EDUs sent to AS; presence not forwarded
MSC2403✅ ●90/90Add “knock” featureKnock CS+SS endpoints, sync key, public-rooms join_rule all wired
MSC2367✅ ●100/100Allowing Reasons in all Membership Eventsreason field handled in invite/leave/kick/ban/unban/join membership routes
MSC2334✅ ●100/100MSC2334 - Change defaul…Default room version is V12, well past V5
MSC2324🟨 ◐60/100Facilitating early releases of software dependent on spectwo MUST misses: unprefixed unstable SSO callback; stable v1/auth_issuer
MSC2313🟥 ●0/0Moderation policies as rooms (ban lists)no server-side policy-list consumption; bot/client subscribers excluded
MSC2290🟨 ●65/55Separate Endpoints for Binding Threepidsadd endpoint (UIA+dupe) + HS email validation; IS-bind half out of scope
MSC2285✅ ●90/100Private read receiptssrc/api/client/read_marker.rs handles ReadPrivate via private_read_set
MSC2265🟨 ●75/100Proposal for mandating case folding when processing e-mail addressesHS case-folds whole email (ss-fold) before storage; IS migration out of scope
MSC2264✅ ●90/100Add an unstable feature flag to MSC2140 for clients to detect supportflag not advertised; r0.6.0 and later advertised instead, as Synapse does
MSC2263✅ ●80/80Give homeservers the ability to handle their own 3PID registrations/password …HS email registration; binds the address in any UIA stage order
MSC2249✅ ●90/100Require users to have visibility on an event when submitting reportssrc/api/client/report.rs:173 verifies sender is room member; PDU lookup gated
MSC2246✅ ●100/100Asynchronous media uploadsasync media routes wired; create_pending, upload_pending, error codes present
MSC2244🟥 ●0/0Mass redactionsSingle-target redactions only; no array redacts handling
MSC2240✅ ●100/100Room Version 6V6 in STABLE_ROOM_VERSIONS; v6 auth rules and rules engine implemented
MSC2230✅ ●100/100Store Identity Server in Account Datam.identity_server kept verbatim, base_url null too; client IS choice excluded
MSC2229🟨 ●0/20Allowing 3PID Owners to Rebind[→ MSC2290] owner exemption at 3pid/add only; requestToken still rejects the …
MSC2209✅ ●100/100Update auth rules to check notifications key in m.room.power_levelslimit_notifications_power_levels enforced for v6+
MSC2197✅ ●100/100Search Filtering in Public Room Directory over FederationPOST /_matrix/federation/v1/publicRooms with filter implemented
MSC2181✅ ●100/100Add an Error Code for Signaling a Deactivated UserM_USER_DEACTIVATED returned by login paths
MSC2176✅ ●100/100Update the redaction rulesredact_in_place uses room_version_rules.redaction
MSC2175✅ ●100/100Remove the creator field from m.room.create eventscreator() falls back to sender when use_room_create_sender
MSC2174✅ ●100/100move the redacts property to contentsrc/core/matrix/event/redact.rs handles redacts move per room rules
MSC2140🟨 ●50/60Terms of Service API for Identity Servers and Integration Managersno 3pid/unbind or IS relay; accepted_terms and register cleanup present
MSC2134🟥 ●0/0Identity Hash Lookupsno IS lookup client; no hash_details, pepper or v1 fallback code
MSC2078✅ ●90/100Sending Third-Party Request Tokens via the HomeserverHS sends and validates email request tokens itself via magic-link, no id server
MSC2077✅ ●100/100Room version 5src/core/config/room_version.rs:7; v5 unstable but supported
MSC2076🟥 ◐0/10Enforce key-validity periods when validating event signaturesminimum_valid_until_ts passed for fetches; per-event ts check absent
MSC2033✅ ●100/100Proposal to include device IDs in /account/whoamisrc/api/client/account.rs:74 returns device_id in whoami response
MSC2002✅ ●100/100MSC 2002 - Rooms V4v4 in supported_room_versions; ruma rules implement v4
MSC1957🟨 ●50/50Integration manager discoveryaccount-data passthrough only; no m.integrations key in well-known client
MSC1954✅ ●100/100Remove prev_content from the essential keys listmerged; identical to MSC1953; ruma redact omits prev_content
MSC1946✅ ◐80/90Secure Secret Storage and Sharinggeneric account_data + to-device pipe carry secret storage/sharing
MSC1930✅ ●100/100Proposal to add a default push rule for m.room.tombstone eventsruma Ruleset::server_default includes ConditionalPushRule::tombstone()
MSC1929✅ ●100/100MSC1929 Homeserver Admin Contact and Support pagesrc/api/client/well_known.rs:42; multiple contacts via support_contact map
MSC1915🟨 ●60/55MSC 1915 - Add unbind 3PID APIsdelete + deactivate return id_server_unbind_result; IS unbind out of HS scope
MSC1884✅ ●100/100Proposal to replace slashes in event IDsroom v4 supported via ruma EventIdFormatVersion::V3 (URL-safe base64)
MSC1866✅ ◐100/100MSC 1866 - Unsupported Room Version Error Code for Invitesclient invite maps remote unsupported-version to M_UNSUPPORTED_ROOM_VERSION
MSC1831✅ ●100/100Proposal to do SRV lookups after .well-known to discover homeserverssrc/service/resolver/actual.rs:79 well-known before SRV
MSC1819✅ ●100/100Remove references to presence listsduplicate of MSC1818; presence lists not implemented
MSC1812✅ ●100/100MSC 1813 - Federation Make Membership Room Versionsrc/api/server/make_leave.rs:34 and make_join.rs:52 set room_version
MSC1804✅ ●100/100Proposal for advertising capable room versions to clientssrc/api/client/capabilities.rs sets RoomVersionsCapability
MSC1802✅ ●100/100Remove the ‘200’ value from some federation responsessrc/api/server/send_join.rs:30 and send_leave.rs:15 handle v2
MSC1794✅ ●100/100MSC 1794 - Federation v2 Invite APIsrc/api/server/invite.rs:28 implements PUT /federation/v2/invite
MSC1772✅ ●90/90Proposal for Matrix “spaces” (formerly known as “groups as rooms (take 2)”)spaces implemented; src/api/client/space.rs hierarchy + room create with type
MSC1767🟥 ◐0/0Extensible events in Matrixno extensible-events handling; relies on generic event relay
MSC1759🟥 ◐10/20MSC 1759 - Rooms V2v2 algorithm in use for v3+; v2 itself not in supported_room_versions
MSC1756✅ ●90/100Cross-signing devices with device signing keyssrc/api/client/keys/upload_signing_keys.rs and upload_signatures.rs implement…
MSC1753✅ ●100/100client-server capabilities APIsrc/api/client/capabilities.rs handles GET /capabilities incl m.change_password
MSC1730✅ ●100/100Mechanism for redirecting to an alternative server during loginsrc/api/client/session/mod.rs:176 sets well_known on login response
MSC1721✅ ●100/100Rename m.login.cas to m.login.ssosrc/api/client/session/sso.rs and uiaa.rs advertise m.login.sso
MSC1711✅ ◐100/100X.509 certificate verification for federation connectionsreqwest+rustls; tls_fingerprints not exposed; standard CA validation
MSC1708✅ ●90/100.well-known support for server name resolutionsrc/service/resolver/well_known.rs; resolver/actual.rs ordering matches spec
MSC1693✅ ●100/100Specify how to handle rejected events in new state resrejected event handling in iterative auth check matches MSC1442 amendment
MSC1692✅ ●95/100Terms of service at registrationm.login.terms stage built from registration_terms config; UIA completes it
MSC1659✅ ●90/100Changing Event IDs to be Hashesreference_hash event IDs; v3 in UNSTABLE_ROOM_VERSIONS; auth_events as list-o…
MSC1501✅ ●90/90Room version upgradesupgrade endpoint present; tombstone, predecessor, PL freeze all implemented
MSC1466✅ ●100/100Soft Remote Logout Proposalsoft_logout=true returned for expired tokens in 401 responses
MSC1442✅ ●90/100State Resolution: Reloadedstate res v2 implemented in src/service/rooms/state_res/resolve.rs
MSC1219✅ ●82/100Storing megolm keys serversidebetter-key compare in add_key (all PUT routes); 403 M_WRONG_ROOM_KEYS_VERSION

Spec compliance gaps

Merged MSCs (in the live Matrix spec) that Tuwunel does not fully implement. These are the highest-priority items to fix for spec compliance.

MSCStatusImplSpecTitleNote
MSC2265🟨 ●75/1001.1Proposal for mandating case folding when processing e-mail addressesHS case-folds whole email (ss-fold) before storage; IS migration out of scope
MSC4178🟨 ●75/901.13Error codes for requestTokenmsisdn returns M_THREEPID_MEDIUM_NOT_SUPPORTED; bad email returns M_INVALID_P…
MSC2409🟨 ●70/701.13Proposal to send typing, presence and receipts to appservicestyping+receipt EDUs sent to AS; presence not forwarded
MSC3925🟨 ●70/701.7m.replace aggregation with full eventFull m.replace fold; off by default (bundle_edit_relations); backfill unindexed
MSC3970🟨 ◐70/801.7Scope transaction IDs to devicestxn key is user, device, txn with no path; redact untracked; echo user scoped
MSC4143🟨 ◐70/90nextMatrixRTCDiscovery, upgrade slot copy, delayed leave; no sticky member or transport auth
MSC4284🟨 ●70/901.18Policy Serversoutbound /sign, inbound verify, fetch-on-missing, reversible soft-fail
MSC4543🟨 ◐70/90nextSliding Sync Extensions: End-to-end encryptionNo-pos and count rules met; left misses departures, bans; claim race; flag held
MSC4548🟨 ◐70/90nextSliding Sync Extensions: Account dataClient caching excluded; first-enable and independent room-scope gaps
MSC2290🟨 ●65/551.0Separate Endpoints for Binding Threepidsadd endpoint (UIA+dupe) + HS email validation; IS-bind half out of scope
MSC1915🟨 ●60/551.0MSC 1915 - Add unbind 3PID APIsdelete + deactivate return id_server_unbind_result; IS unbind out of HS scope
MSC2324🟨 ◐60/1001.0Facilitating early releases of software dependent on spectwo MUST misses: unprefixed unstable SSO callback; stable v1/auth_issuer
MSC2675🟨 ◐60/751.3Serverside aggregations of message relationshipsthread+edit+reference bundled (edit/ref gated); reactions unbundled
MSC3267🟨 ◐60/801.5reference relationshipsm.reference bundle added; gated default-off; no ignore/visibility filter
MSC4508🟨 ◐60/80nextSliding Sync Extensions: Common format and TypingTyping exists; joined-only filtering and scope reentry remain incomplete.
MSC1957🟨 ●50/50nextIntegration manager discoveryaccount-data passthrough only; no m.integrations key in well-known client
MSC2140🟨 ●50/601.0Terms of Service API for Identity Servers and Integration Managersno 3pid/unbind or IS relay; accepted_terms and register cleanup present
MSC2676🟨 ●50/601.4Message editingedits accepted/relayed; no m.replace bundle or new_content apply
MSC4319🟨 ●50/50nextRoom member events for invite and knock rooms in the /sync responsestate/mod.rs:464 puts inviter member in stripped state; no state key
MSC4551🟨 ◐40/70nextSliding Sync Extensions: ReceiptsReceipt delivery exists; initial/rescope gaps. Client application excluded.
MSC4195🟨 ◐10/10nextMatrixRTC Transport using LiveKit BackendTransport advertisement only; token and leave APIs absent; client media excluded
MSC2229🟨 ●0/201.0Allowing 3PID Owners to Rebind[→ MSC2290] owner exemption at 3pid/add only; requestToken still rejects the …
MSC1759🟥 ◐10/201.0MSC 1759 - Rooms V2v2 algorithm in use for v3+; v2 itself not in supported_room_versions
MSC1767🟥 ◐0/0nextExtensible events in Matrixno extensible-events handling; relies on generic event relay
MSC2076🟥 ◐0/101.0Enforce key-validity periods when validating event signaturesminimum_valid_until_ts passed for fetches; per-event ts check absent
MSC2134🟥 ●0/01.0Identity Hash Lookupsno IS lookup client; no hash_details, pepper or v1 fallback code
MSC2244🟥 ●0/0nextMass redactionsSingle-target redactions only; no array redacts handling
MSC2313🟥 ●0/01.0Moderation policies as rooms (ban lists)no server-side policy-list consumption; bot/client subscribers excluded
MSC2604🟥 ●0/01.1Parameters for Login Fallbacklogin fallback page is homeserver served, so not n/a; Tuwunel ships no page
MSC3288🟥 ●0/01.2Add room type to /_matrix/identity/v2/store-invite APIsole clause is addressed to homeservers, so not n/a; no 3PID invite at all
MSC3550🟥 ◐0/01.2Add HTTP 403 to possible profile lookup responsesCS /profile returns 403 M_FORBIDDEN when outbound profile lookup disabled
MSC4127🟥 ●0/0nextRemoval of query string authsrc/api/router/auth.rs:78 still falls back to request.query.access_token
MSC4183🟥 ●0/01.18Additional Error Codes for submitToken endpointsmixed MSC; the submit_url half is homeserver scope and we emit no submit_url
MSC4335🟥 ●0/01.18M_USER_LIMIT_EXCEEDED error codeM_USER_LIMIT_EXCEEDED error code not used
MSC4354🟥 ●0/0nextSticky EventsNo sticky delivery or expiry paths; client ephemeral maps excluded

Open

Sorted by MSC number, highest first. Out-of-scope rows are listed in the Out of scope section.

MSCStatusImplTitleNote
MSC4578✅ ◐100/100Cross-client Shared Search Indexes of encrypted messagesAccount-data passthrough; client indexing and encryption excluded.
MSC4577✅ ◐100/100Soundboards for MatrixRTC callsAccount-data passthrough works; client playback and SFU grants excluded.
MSC4576🟥 ●0/0Only allow data publishing when also allowing audio/video publishing on LiveK…No LiveKit JWT grant issuance; transport discovery does not satisfy
MSC4574🟥 ●0/0linked state eventsNo m.state_content resolution or linked_event delivery
MSC4573🟥 ●0/0Atomically increasing versioned account dataNo versioned account-data API; client conflict resolution excluded.
MSC4569✅ ◐100/100CalendarRoom account-data passthrough; client calendar semantics excluded.
MSC4565🟥 ●0/0Share additional invite stateInvite handler lacks shared_state selection and wildcard support
MSC4563🟥 ●0/0direct_message push ruleDirect-message push condition absent; client evaluation excluded.
MSC4560🟥 ●0/0Stripped state requests over federationNo stripped-state query endpoints; client preview UI excluded
MSC4559🟥 ●0/0Sliding Sync Extensions: PresenceNo sliding-sync presence extension. Client state handling excluded.
MSC4558🟥 ●0/0Thread namesNo thread-name validation, bundles or push rule; client UI excluded
MSC4556🟥 ●0/0Notary request limitsNo authenticated v3 query or v3 fallback; bare permissions excluded
MSC4547🟥 ●0/0Atomic Account Data Updates via Compare-and-SwapAccount-data CAS absent; client revision generation excluded.
MSC4545🟨 ◐20/20Subprofiles as roomsGeneric subprofiles profile-key storage only; subprofile APIs absent
MSC4544✅ ◐100/100Rich Presences in MatrixProfile-field passthrough; client IPC, expiry and rendering excluded.
MSC4540🟥 ●0/0m.admin capabilityAdmin capability absent; client UI and OAuth step-up excluded.
MSC4537✅ ◐100/100Restore 200 {} for unset profile fieldsUnset legacy fields return {}; custom fields return 404; client scope excluded
MSC4536🟥 ●0/0Additional endpoint for fetching user profilesBulk profile query endpoint and feature advertisement are absent.
MSC4534✅ ●100/100Simple room rulesAccount-data passthrough; m.room.rules.accepted room data stored and synced
MSC4532🟥 ●0/0Revised Social PresenceRevised presence absent; client activity and controls excluded.
MSC4529✅ ◐100/100Client-side profile overridesOpaque account-data storage and sync; client display and encryption excluded
MSC4528🟥 ●0/0M_INCOMPATIBLE_SERVER error codeM_INCOMPATIBLE_SERVER absent from Tuwunel and from the ruma fork
MSC4527🟥 ●0/0State event power levelsno state map in power levels and no MSC4527 room version
MSC4526✅ ◐80/100Improve OAuth 2.0 refresh token grant error handlinginvalid_grant on refresh failures, but every 4xx maps to it, bad params too
MSC4525🟥 ●0/0Paginated Syncno paginated sync endpoint; only MSC4186 simplified sliding sync exists
MSC4524🟥 ●0/0Federation Bi-directional Pingno federation ping or pong route; the cited commit is a Continuwuity branch
MSC4522✅ ●100/100Username colorsCustom profile field passthrough; object value stored and served via MSC4133
MSC4521🟥 ●0/0Adaptive set reconciliationno PinSketch, minisketch or algebraic_v1 digest anywhere in the tree
MSC4519🟨 ●60/80MatrixRTC Transports Registrysrc/api/client/rtc.rs:7 serves the MSC4143-prefixed unstable transports route
MSC4517🟥 ●0/0Federated thirdparty lookupsno server= parameter and no federation thirdparty routes; local lookups only
MSC4514🟥 ●0/0EDU size limitno 65536 byte EDU cap; only the 24 MiB global request body limit applies
MSC4513✅ ◐90/90Standard HTTP status codes for all endpoints, current and futurecentral kind to status map emits 413, 429, 502, 504 with Matrix error bodies
MSC4512✅ ●90/90Delegating parts of the Client-Server and Server-Server API to application se…Unstable keys and paths, rtc/livekit prefix only, TRACE refused
MSC4511🟥 ●0/0Topological query API with sparse fieldsets and Merkleized metadatano topological query endpoint, sparse fieldsets or Merkleized metadata
MSC4509🟥 ●0/0Auto join on accepted knockno auto-join on accepted knock; prev_sender emission is pre-existing
MSC4507🟥 ●0/0Return additional room state from /_matrix/federation/v1/hierarchy/{roomId}federation /hierarchy has no additional_state param or m.public_state
MSC4506🟥 ●0/0Push Rules for Knockingno recipient_permission condition and no .m.rule.knock default rule
MSC4505🟥 ●0/0Push Rules for Live Location Sharingno beacon push rules; ruma’s default ruleset defines none
MSC4504🟨 ◐50/100Using a global version number for the entire specification (v2)Drops spec removals in Y%6 releases it advertises (v1.6, v1.18); not yet live
MSC4503🟥 ●0/0External Protocol Handlesm.external_handle unrecognized; generic MSC4133 passthrough only
MSC4502✅ ●90/90Targeted and unrestricted room member queriesAS registration scope only; no OAuth scopes, so admins cannot hold it
MSC4501✅ ◐100/100Social Media on MatrixProfile-field passthrough works; social event and client conventions excluded
MSC4500🟥 ●0/0State accumulator endpoint and transaction digestsno LtHash accumulator, state_hashes payload or reconciliation endpoint
MSC4499🟨 ◐40/50Strict server signing key caching and key ID uniquenesskeys cached and persisted, but extend() overwrites so last seen wins
MSC4498🟥 ●0/0Holding messages pending moderation (via policy servers)policy server client handles 200 and 400 only; no 202 M_HELD path
MSC4497🟥 ●0/0Filter state events by type in /state endpoint/state returns full room state; no types query parameter
MSC4496🟥 ●0/0Calendar Events, Invites, and Availability in MatrixAvailability APIs absent; client, bridge and optional carrier excluded
MSC4495🟥 ●0/0Selective Presenceno sharing config, no EDU recipients or stream_id, no query endpoint
MSC4494🟥 ●0/0Membership-based invite blockingno deny_public action; msc4380 filter has no mutual-room evaluation
MSC4492✅ ◐90/100Clarify that pagination tokens are directionlessPduCount tokens already directionless and shared across the named endpoints
MSC4491🟥 ●0/0Invite reasons in room creationcreateRoom passes reason None to invite; no invite_reason field
MSC4490🟥 ●0/0Surfacing room contacts when a join or knock does not succeedno contact field on join or knock rejections; MSC4489 also absent
MSC4486🟥 ●0/0Listing delayed events with filtering & paginationMSC4140 delayed events absent entirely, so the list endpoint has no base
MSC4485🟥 ●0/0Homeserver feature controlsno .well-known/matrix/featured route
MSC4484🟥 ●0/0Server Administration OAuth ScopeAdmin OAuth scope absent; client scope-request and step-up UX excluded
MSC4483✅ ●100/100Encrypted Account DataAccount-data passthrough; ADK secret and encrypted envelopes stored opaque
MSC4482✅ ●100/100Ability to bookmark messagesAccount-data passthrough; m.bookmarks_room stored, served, synced opaque
MSC4480🟥 ●0/0MSC4480 Sliding Sync Extension: Sticky EventsSticky-event delivery absent; client duration and duplicate handling excluded
MSC4476✅ ●100/100Image pack roomsAccount-data passthrough; m.image_pack.rooms stored, served, synced opaque
MSC4473🟥 ●0/0Proxied room alias resolutionNo federation v2 query/directory; no signing/proxy logic.
MSC4472🟥 ●0/0Deprecated room version kindNo deprecated stability kind in room_versions capability.
MSC4470🟥 ●0/0Routing reports to non-local destinations/report does not accept must_send_to; no fan-out.
MSC4469🟥 ●0/0Reporting to remote servers (EDU approach)m.report EDU not defined or routed.
MSC4467🟥 ●0/0Improved Room Upgrade APIv3 upgrade only; no v4 endpoint, capability, or migration_schema.
MSC4466🟨 ◐50/70Altering profile change propagationSingle-field propagation works; whole-profile extension and key copying lack
MSC4464🟥 ●0/0verifiable links in profileNo /verify_profile_connection endpoint or verification backend
MSC4462🟥 ◐10/10Links in ProfileIncidental MSC4133 passthrough; no m.connections parsing.
MSC4461✅ ◐100/100Storing per-message profiles for usersPure account data passthrough; generic CS account-data covers it
MSC4457🟥 ●0/0Generic reporting APINo /_matrix/client/v1/safety/report endpoint or harm handling
MSC4456🟥 ●0/0Harms taxonomyNo endpoint accepts or emits harm identifiers; consumers MSC4457/4387 absent
MSC4453🟥 ●0/0Deprecate old room versionsNo deprecated-version policy; client notices and upgrade UI excluded
MSC4450🟥 ●0/0Identity Provider selection for User-Interactive Authentication with Legacy S…UIAA SSO fallback derives idp from session, not idp_id query
MSC4449🟥 ●0/0Updated /members filteringSingle membership filter only; no array support, no mutual-exclusion error
MSC4448🟥 ●0/0Preview URL Site LogosNo matrix:site_logo or msc4448:site_logo in preview_url response
MSC4447🟥 ●0/0Move OpenID userinfo endpoint out of /_matrix/federationOld /federation/v1/openid/userinfo present; new /_matrix/openid/v1/userinfo n…
MSC4446✅ ●90/100Allow moving the fully read marker to older eventsFully-read gated; allow_backward on both routes; racing writes unordered
MSC4445🟥 ◐0/0Clarify /sync timeline orderNo msc4445 unstable_features flags advertised
MSC4441✅ ●100/100Encrypted User Profile Annotations via Account DataAccount-data passthrough; owner-only global store, GET, v3 and v5 sync
MSC4440🟥 ●0/0Profile Biography via Global ProfilesGeneric MSC4133 passthrough only; no m.biography validation
MSC4439🟨 ●70/85Encryption key URIs in /.well-known/matrix/supportcheck.rs:780 validates URI and rejects raw keys; new https MUST unenforced
MSC4438✅ ●100/100Message bookmarks via account dataPure account-data convention; existing endpoints store arbitrary types
MSC4437🟥 ●0/0Endpoint to replace entire profileNo PUT /_matrix/client/v3/profile/{userId} replace-all endpoint
MSC4433🟥 ●0/0Image Packs and Room UpgradesRoom upgrade does not transfer m.room.image_pack or update m.image_pack.rooms
MSC4432🟥 ●0/0Server-wide room name overridesNo m.room.name.server_wide propagation; no capability
MSC4431🟥 ●0/0Personalised room name overridesServer side passively allows m.room.name.private as account data
MSC4430🟥 ●0/0Member KeysMember-key signing and lookup absent; client identity handling excluded
MSC4429✅ ●85/85Profile Updates for Legacy SyncFiltered legacy profile updates; no atomic snapshots or whole-user drops.
MSC4428🟥 ●0/0Stable identifiers for Room MembersNo member_info or unsigned.stable_id added to events or sync
MSC4427🟥 ●10/10Custom banners for user profilesNo m.banner_url handling; MSC4133 plumbing accepts it opaquely
MSC4426✅ ◐90/90User Status Profile FieldsStatus storage and byte limits work; client presentation excluded
MSC4425🟥 ●0/0Ephemeral mediano ephemeral query param; no DELETE on /_matrix/client/v1/media/…/….
MSC4420🟥 ●0/0Duplicate one-time key error response for /keys/uploadadd_one_time_key silently overwrites; no M_DUPLICATE_ONE_TIME_KEY emitted.
MSC4417🟥 ●0/0URL Previews via Appservicesclient preview_url exists; no appservice fan-out or namespace check.
MSC4416🟥 ●0/0Optionally requiring policy server signatures in a roomdepends on MSC4284; no policy-server signature checks anywhere.
MSC4406🟨 ●50/55M_SENDER_IGNORED error codesrc/api/client/{room/event.rs:74,context.rs:86,relations.rs:175}; M_SENDER_IG…
MSC4401🟥 ◐0/0Publishing client capabilities via profilesgeneric profile keys exist; logout cleanup of client_capability missing.
MSC4397✅ ●100/100Tags as Spacesglobal account-data passthrough (2026-06-22 ruling); m.tag_space round-trips
MSC4396🟥 ●0/0Inline linked mediano multipart/mixed event-with-media; no m.media mixin or M_GONE wired.
MSC4388✅ ◐80/100Secure out-of-band channel for sign in with QRHS transport; QR/HPKE excluded; replay eviction and 600s TTL gaps
MSC4387🟥 ●0/0M_SAFETY error codeM_SAFETY errcode not used anywhere in src/; no harms field handling.
MSC4383✅ ●100/100Client-Server Discovery of Server Versionversions.rs:30 server object; :149 advertises net.zemos.msc4383
MSC4382🟥 ●0/0Peppered hash verification for E2EE content moderationNo verification_hash check on report endpoint
MSC4377✅ ●100/100Clarify Image Pack Orderingaccount-data passthrough (2026-06-22 ruling); nested order keys kept verbatim
MSC4371🟥 ●0/0On the elimination of federation transactions.No PUT /_matrix/federation/v2/send/{eventId|eduId} endpoint
MSC4370🟥 ●0/0Federation endpoint for retrieving current extremitiesNo /_matrix/federation/v1/extremities endpoint
MSC4369🟥 ●0/10M_CAPABILITY_NOT_ENABLED error code for when capability is not enabled on an …Endpoints exist but return M_FORBIDDEN/Unknown not M_CAPABILITY_NOT_ENABLED
MSC4368🟥 ●0/0Combine definitions of M_RESOURCE_LIMIT_EXCEEDED error code and m.server_noti…M_RESOURCE_LIMIT_EXCEEDED on upload refusal: no limit_type, admin_contact empty
MSC4367🟥 ●0/0via routes in the published room directoryPublishedRoomsChunk has no via field
MSC4366🟥 ●0/0Resident servers in and around the room directorypublicRooms not filtered to rooms with joined members
MSC4365🟥 ●0/0Canonical ignore list roomsNo ignored_user_list_rooms server-side filtering
MSC4363🟥 ●0/0OAuth step up authenticationNo M_INSUFFICIENT_USER_AUTHENTICATION error or acr_values
MSC4361✅ ●100/100Non-federating Membership Authorization Rule Amendmentssrc/service/rooms/state_res/event_auth/room_member.rs:56; reject m.room.membe…
MSC4360🟥 ●0/0Threads extension to Sliding SyncNo /thread_updates endpoint or threads sliding sync extension
MSC4359🟨 ●50/50“Do not Disturb” notification settingsDnD account data passes through; device removal leaves the per device key
MSC4358🟥 ●0/0Out of room server discoveryNo /discover_common_rooms federation endpoint
MSC4357🟥 ●0/0Live Messages via Event Replacementno live-marker or live_messaging handling; rejection capability absent
MSC4353🟥 ●0/0Per-origin linear chainNo origin_predecessor field or per-origin chain validation
MSC4352🟥 ●0/0Customizable HTTPS permalink base URLs via server discoveryNo permalink_base_url in /.well-known/matrix/client output
MSC4351✅ ●100/100Odd Context LimitsContext handler biases remainder to events_after via div_ceil(2)
MSC4350🟥 ●0/0Permitting encryption impersonation for appservicesNo impersonator field in device keys, no /keys/query handling
MSC4348🟥 ●0/0Portable and serverless accounts in roomsportable accounts (account keys); not implemented
MSC4345🟥 ●0/0Server key identity and room membershipserver key as room identity; massive auth-rule changes; not implemented
MSC4344🟥 ●0/0Strike deprecated SRV service name.deprecated _matrix._tcp SRV still queried
MSC4343🟥 ●0/0Making mass redactions use a new event typem.room.redactions (mass redactions) event not used; depends on MSC2244
MSC4342🟥 ●0/0Limiting the number of devices per user ID30-device limit and M_TOO_MANY_DEVICES not enforced
MSC4339🟥 ●0/0Allow the user directory to return full profilesuser_directory v4 with profile_fields not implemented
MSC4337🟥 ●0/0Appservice API to supplement user profilesappservice profile supplement endpoint not queried
MSC4331🟥 ●0/0Device Account Dataper-device account data routes not implemented
MSC4330🟨 ◐50/50specify HTTP and TLS versions which must be supportedHTTP/2 via axum/hyper available; TLS 1.2+ via rustls; not enforced as MUST
MSC4325🟥 ●0/0Presence privacypresence privacy filtering by m.presence_sharing_config not implemented
MSC4322🟥 ●0/0Simple Media Self-Redaction[→ MSC3911?] media self-redaction; no /media/redact endpoint or EDU
MSC4320🟥 ●0/0Rich PresenceRich Presence m.rpc; no support for activity/media profile field
MSC4309🟥 ●0/0Finalised delayed events on syncfinalised delayed events on /sync; depends on MSC4140; no impl
MSC4308🟥 ●0/0Thread Subscriptions extension to Sliding SyncNo subscription extension or pagination; client reconciliation excluded
MSC4306🟥 ●0/0Thread SubscriptionsNo thread subscription endpoints, push condition or postcontent kind
MSC4305🟥 ●0/0Pushed Authorization Requests (PARs) for OAuth authenticationOIDC auth_metadata lacks PAR endpoint fields
MSC4303🟥 ●0/0Disallowing non-compliant user IDs in roomsno future room version banning non-compliant user IDs
MSC4298🟥 ●0/0Room version components for ‘Redact on ban’no future room version protecting redact_events from redaction
MSC4293🟥 ●0/0Redact on kick/banMSC4293 commit lives only on Continuwuity branches; current tree has no redac…
MSC4282🟥 ●0/0Hint that a /rooms/{room_id}/messages request is interactiveno interactive query parameter on /messages
MSC4279🟥 ●0/0Server notice roomsno notice room presets, no leave_rules, no server_notice room type filter
MSC4271🟥 ◐0/0Recommended enabled-ness for default push rulesno admin override knob; uses Ruma defaults verbatim
MSC4266🟨 ●75/75Policies in /.well-known/matrix/supportmulti-lang policies reachable from config; wire key not unstable-prefixed
MSC4265🟥 ◐10/10Data Protection Officer contact in /.well-known/matrix/supportsupport_role configurable; MSC role string accepted as Custom
MSC4264🟥 ●0/0Tokens for Contacting Accounts or Joining Semi-Public RoomsTokens for contact / semi-public-room joins not implemented
MSC4263🟥 ◐10/10Preventing MXID enumeration via key queriesMUST floor met implicitly; MAY restriction unused
MSC4262🟨 ●70/70Sliding Sync Extension: Profile UpdatesVisible updates and selected initial bases; no atomic snapshots or user drops.
MSC4261✅ ◐80/100“Do not encrypt for device” flagDeviceKeys stored and served raw, so do_not_encrypt survives upload and query
MSC4259🟥 ●0/0Profile Update EDUs for Federationm.profile EDU broadcast not implemented
MSC4258🟥 ●0/0Federated User DirectoryFederated user_directory/search not implemented
MSC4257🟥 ●0/0Profiles Arent Auth: Move profile contents to a separate eventm.room.member.profile separate event not supported
MSC4256🟥 ●0/0RFC 9420 MLS mode MatrixMLS mode rooms not implemented
MSC4255🟥 ●0/0Bulk Profile UpdatesBulk PUT/PATCH /profile not implemented
MSC4250🟥 ●0/0Authenticated media v2 (Cookie authentication for Client-Server API)set_auth_cookie media auth not implemented
MSC4249✅ ●100/100Removal of legacy media endpointsallow_legacy_media defaults to false; legacy disabled
MSC4247✅ ◐100/100User PronounsPronouns use generic profile storage; client language and rendering excluded
MSC4246🟥 ●0/0Sending to-device messages as/to a serverEmpty-localpart server addressing for to-device absent
MSC4244🟥 ●0/0RFC 9420 MLS for MatrixMLS for Matrix not implemented
MSC4243🟥 ●0/0User ID localparts as Account KeysAccount keys / federation query/accounts not implemented
MSC4242🟥 ●0/0State DAGsState DAG event format, authorization and replication absent.
MSC4238✅ ●100/100Pinned events read markerroom account-data passthrough (2026-06-22 ruling); stored, served, synced
MSC4235🟥 ●0/0via query param for hierarchy endpointhierarchy endpoint lacks via query parameter
MSC4234🟥 ●0/0Update app badge counts when rooms are readcleared_notifs read-receipt flag not handled
MSC4233🟥 ●0/0Remembering which server a user knocked throughKnocked-through server not remembered; leave and rejection paths unchanged
MSC4232🟥 ●0/0Attribute-Based Access Control (ABAC)ABAC permissions model; no room version implements it
MSC4228🟥 ●0/0Search Redirectionoptional 403 search redirection not used
MSC4226🟥 ●0/0Reports as roomsreports-as-rooms (m.report room type) not implemented
MSC4224🟥 ●0/0CBOR Serializationapplication/cbor content negotiation not implemented
MSC4223🟥 ●0/0Error code for disallowing threepid unbinding3pid unbind/delete endpoints not implemented at all
MSC4218🟥 ●0/0Improving performance of profile changessynthetic events / m.room.user_profile not implemented
MSC4208🟨 ◐40/50Adding User-Defined Custom Fields to User Global ProfilesMSC4133 fields carry u.* generically; no 512B cap, no disallowed list
MSC4207🟥 ●0/0Media identifier moderation policym.policy.rule.mxc not interpreted
MSC4204🟥 ●0/0m.takedown moderation policy recommendationno m.takedown recommendation handling
MSC4203✅ ●95/100Sending to-device events to appservicesto_device in AS txns with to_user_id/to_device_id; retain (dual /sync)
MSC4201🟥 ●0/10Profiles as Rooms v2only generic /profile/{user} exists; no roomID profile lookup
MSC4198🟥 ●0/0Usage of OIDC login_hintlogin_hint not parsed on authorization, device or account-management paths
MSC4194🟥 ●0/0Batch redaction of events by sender within a room (including soft failed events)POST /rooms/{}/redact/user/{} not wired
MSC4188🟥 ●0/0Handling HTTP 410 Gone Status in Matrix Server Discovery410 Gone not specially handled in well-known resolver
MSC4185🟥 ●0/0Event Visibility APIno can_user_see_event endpoint
MSC4179🟥 ●0/0Moderation event hidingNo m.moderation_hidden; edit fold demands same sender and type as the parent
MSC4177🟥 ●0/0Add upload location hints proposalno m.upload.locations or location query param
MSC4176🟥 ●0/0Translatable Errorsno localized error messages map
MSC4174🟥 ●0/0Web pushNo webpush pusher kind, no /pushers/ack endpoint, no VAPID capability
MSC4173🟥 ●0/0test pusherno /pushers/push test endpoint
MSC4168🟨 ●30/40Update m.space.* state on room upgradesrc/api/client/room/upgrade.rs:447; copies m.space.parent always plus m.space…
MSC4167🟥 ●0/0Copy bans on room upgradebans not copied during room upgrade
MSC4166✅ ●100/100Specify /turnServer response when no TURN servers are availableturnServer returns 404 M_NOT_FOUND when no TURN URIs configured
MSC4165✅ ●100/100Remove own power level on deactivationpower level entry removed for self on deactivation
MSC4164✅ ●100/100Leave all rooms on deactivationdeactivation leaves all joined/invited/knocked rooms
MSC4162🟥 ◐10/10One-Time Key Reset Endpointno /keys/reset; claim ordering is implicit via key prefix iter
MSC4155✅ ●90/100Invite filteringSix glob lists evaluated per sender; blanket block outranks the ignore list
MSC4154✅ ●100/100Request max body sizemax_request_size default 24MB, M_TOO_LARGE returns 413
MSC4152🟥 ●0/0Room labeling and filteringroom labels and /rooms/{roomId}/labels not implemented
MSC4149✅ ●100/100Update CSP Directives for Media RepositoryMSC policy available; frame denial defaults off for attachment compatibility
MSC4145🟥 ●0/0Simple verified accountsm.verified profile field and endpoint not implemented
MSC4141🟥 ●0/0Time based notification filteringtime_and_day push rule condition not supported
MSC4136🟥 ●0/0Shared retry hints between serversretry_hints in /send_join response not implemented
MSC4128✅ ●100/100Error on invalid auth where it is optionalinvalid token returns error even on optional auth endpoints
MSC4125✅ ●90/100Specify servers to join via for federated invitesfederation invite via field used both inbound and outbound
MSC4121✅ ●100/100m.role.moderator /.well-known/matrix/support role.m.role.moderator served via Ruma ContactRole alias and config
MSC4120🟥 ●0/0Allow HEAD on /downloadHEAD on /download not wired; routes mounted via Ruma metadata GET only
MSC4117🟥 ●0/0Reinstating Events (Reversible Redactions)m.room.reinstate (reversible redactions) not implemented
MSC4109🟥 ●0/0Appservices & soft-failed eventsappservice v2/transactions endpoint with soft-failed events absent
MSC4108✅ ◐80/90Mechanism to allow OAuth 2.0 API sign in and E2EE set up via QR codeHS grant and signed-key upload; client QR/E2EE excluded; no login alerts
MSC4106🟥 ●0/0Join as Mutedjoin-as-muted default_membership not implemented
MSC4104🟥 ●0/0Auth Lock: Soft-failure-be-gone!m.auth_lock event and auth-rule not implemented
MSC4103🟥 ◐0/0Make threaded read receipts opt-in in /syncthreaded_read_receipts sync filter not implemented
MSC4102🟥 ◐0/0Clarifying precedence in threaded and unthreaded read receipts in EDUsunthreaded-takes-precedence aggregation rule not enforced
MSC4100🟥 ●0/0Scoped signing keysscoped signing keys / X-Matrix-Scoped not implemented
MSC4096🟥 ●0/0Proposal to make forceTurn option configurable server-sideforceTurn not advertised in well-known
MSC4094🟥 ●0/0Sync Server and Client Times with endpointGET /_matrix/client/v3/get_server_now endpoint missing
MSC4089🟥 ●0/0Delivery Receiptsm.delivery receipts not implemented
MSC4086🟥 ●0/0Event media reference countingevent-media reference counting not implemented
MSC4084🟥 ●0/0Improving security of MSC2244v4 send endpoint with UIA for redactions not implemented
MSC4083🟥 ●0/0Delta-compressed E2EE file transfersdelta-compressed media transfers not implemented
MSC4081🟥 ●0/0Eagerly sharing fallback keys with federated serverseager fallback key sharing not implemented
MSC4080🟥 ●0/0Cryptographic Identities (Client-Owned Identities)cryptographic identities/send_pdus endpoint not implemented
MSC4079🟥 ●0/0Server-Defined Client Landing Pageslanding_page in well-known not implemented
MSC4078🟥 ●0/0Registering pushers against push notification services should forward back fa…upstream_errcode/upstream_error not surfaced from /pushers/set
MSC4075🟥 ●0/0MatrixRTC Notification Event (call ringing)New RTC push defaults absent; client signalling excluded
MSC4074🟥 ●0/0Server side annotation aggregationserver-side annotation aggregation not implemented
MSC4071🟥 ●0/0Pagination Token HeadersNo X-Matrix-Pagination-* header handling.
MSC4062🟨 ◐50/50Add a push rule tweak to disable email notificationCustom tweak round trips through ruma; email pusher ignores dont_email
MSC4060🟥 ●0/0Accept room rules before speakingNo m.room.rules state event or acceptance gating.
MSC4057🟥 ●0/0Static Room AliasesNo .well-known/matrix/rooms lookup before federation directory.
MSC4056🟥 ●0/0Role-Based Access Control (mk II)No m.role / m.role_map RBAC support.
MSC4053🟥 ◐0/0Extensible Events - Mentions mixinNo mixin push rules with room_version_supports condition.
MSC4049🟥 ●0/0Sending events as a server or roomNo room version permitting non-user-ID senders.
MSC4048🟥 ●0/0Authenticated key backupNo m.backup.v2.curve25519-aes-sha2 algorithm or backup_mac handling.
MSC4047🟥 ●0/0Send KeysNo m.room.send_key state event or send-key auth path.
MSC4046🟥 ●0/0Make & send PDU endpointsNone of the four make_pdu/send_pdu endpoints implemented.
MSC4045🟥 ●0/0Deprecating the use of IP addresses in server namesNo room version banning IP-literal server names.
MSC4044🟥 ●0/0Enforcing user ID grammar in roomsNo room version enforcing strict user ID grammar.
MSC4043🟥 ●0/0Presence Override APINo /presence/{userId}/override endpoint.
MSC4042🟥 ●0/0Disabled Presence StateNo fourth presence state; Tuwunel serves online, offline, unavailable, busy
MSC4038🟥 ●0/0Key backup for MLSNo MLS or m.dmls_backup.v1.aes-hmac-sha2 backup algorithm support.
MSC4034🟥 ●0/0Media limitsNo /usage endpoint and no m.storage.* fields in /config.
MSC4033🟥 ●0/0Explicit ordering of events for receiptsNo order field on events or receipts.
MSC4032✅ ●100/100Asset Collectionsaccount-data passthrough (2026-06-22 ruling); both keys stored, served, synced
MSC4031🟥 ●0/0Pre-generating invites and room invite codespre-generated invites and m.room.invite state event not implemented
MSC4029🟨 ◐40/50Fixing X-Matrix request authenticationX-Matrix verification covers basics; canonicalization rules not fully specified
MSC4028🟥 ●0/0Push all encrypted events except for muted roomsNo .m.rule.encrypted_event override in the default ruleset Tuwunel serves
MSC4027🟥 ●0/0Custom Images in Reactionsshortcode 100-byte limit unenforced on send; rendering itself is client scope
MSC4023🟥 ●0/0Thread ID for second-order relationunsigned.thread_id not added to events
MSC4021🟥 ●0/0Archive client controlsm.room.archive_controls not relayed in /publicRooms
MSC4020🟥 ●0/0Room model configurationm.room.create model object flagging not supported
MSC4019🟥 ●0/0Encrypted event relationshipsm.room.relationship_encryption flag not handled by server
MSC4016🟥 ●0/0Streaming and resumable E2EE file transfer with random accessNo tus, no Range, no incremental serve; MSC2246 async upload still buffers
MSC4014🟥 ●0/0Pseudonymous Identitiespseudonymous identities (sender_key, mxid_mapping) not implemented
MSC4011🟥 ●0/0Thumbnail media negotiationthumbnail Accept header negotiation not implemented
MSC4005🟥 ◐0/0Explicit read receipts for sent eventsServer does not auto-generate read receipt on send
MSC4002🟥 ●0/0Walkie talkieNo server side speaker lock; walkie, ptt, floor lock absent from src and ruma
MSC4001🟥 ●0/0Return start of room state at context endpointcontext returns state at LAST event, MSC asks for state at FIRST
MSC4000🟥 ●0/0Forwards fill (/backfill forwards)forwards_fill federation endpoint not implemented
MSC3999🟥 ●0/0Add causal parameter to /timestamp_to_eventtimestamp_to_event causal event_id parameter not supported
MSC3998🟥 ●0/0Add timestamp massaging to /join and /knockjoin/knock ts query param not honored
MSC3997🟥 ●0/0Add timestamp massaging to /createRoomcreateRoom ts query param not honored (always timestamp: None)
MSC3996🟥 ●0/0Encrypted mentions-only roomsm.has_mentions cleartext flag and is_encrypted_mention rule not present
MSC3995🟥 ●0/0Linearized MatrixLinearized Matrix hub/participant architecture not implemented
MSC3994🟥 ●0/0Display why an event caused a notificationrule_kind/rule_id not added to /notifications
MSC3993🟥 ●0/0Room takeoverroom takeover variants not implemented
MSC3991🟥 ●0/0Power level up! Taking the room to new heightsraise own power level above max not allowed
MSC3984🟥 ●0/0Sending key queries to appservicesSending key queries to appservices intentionally removed
MSC3983🟥 ●0/0Sending One-Time Key (OTK) claims to appservicesOTK claim proxy to appservice intentionally removed
MSC3982🟥 ●0/0Limit maximum number of events sent to an ASno 100-event cap on appservice transactions
MSC3964🟥 ●0/0Notifications for room tagsroom_tag push condition not implemented
MSC3963🟥 ●0/0Oblivious Matrix over HTTPSOblivious MoH endpoints absent
MSC3947🟥 ●0/0Allow Clients to Request Searching the User Directory Constrained to Only Hom…exclude_sources parameter on user_directory/search not implemented.
MSC3944🟥 ●0/0Dropping stale send-to-device messagesStale-to-device cancellation/dedup logic not implemented.
MSC3934🟥 ●0/0Bulk push rules change endpointPUT /pushrules_bulk/…/actions and /enabled endpoints not implemented.
MSC3933🟥 ●0/0Core push rules for Extensible EventsExtensible-event default underride push rules not added.
MSC3932🟥 ●0/0Extensible events room version push rule feature flagExtensible-event room version push rule gating not enabled.
MSC3931🟥 ●0/0Push rule condition for room version featuresroom_version_supports push condition not enabled in tuwunel.
MSC3926🟥 ●0/0Disable server-default notifications for bot users by defaultenable_predefined_push_rules registration body field not implemented.
MSC3922🟥 ●0/0Removing SRV records from homeserver discoverySRV record discovery still active; would need code removal.
MSC3917🟥 ●0/0Cryptographically Constrained Room MembershipCryptographic membership (RRK / RSK / signed memberships) not implemented.
MSC3914🟥 ●0/0Matrix native group call push rule.m.rule.room.call push rule + call_started condition not implemented.
MSC3911🟥 ●0/0Linking media to eventsattach_media query, /media/copy, restrictions block in federation media not p…
MSC3909🟥 ●0/0Membership based mutesMembership-based mutes via new mute/leave-mute states; not implemented.
MSC3908🟥 ●0/0Expiring Policy List Recommendationsno policy-list consumer; expiry never read, no expiry-driven reversal
MSC3907🟥 ●0/0Mute Policy Recommendationno policy-list consumer, so m.mute is never applied (suspension exists, unwired)
MSC3901🟥 ◐0/0Deleting Statemeta-MSC of sub-proposals; obsolete-state cleanup not implemented
MSC3896🟥 ●0/0Appservice mediaappservice media namespace not implemented
MSC3895🟥 ●0/0Federation API Behaviour of Partial-State Resident ServersM_UNABLE_DUE_TO_PARTIAL_STATE error code not implemented
MSC3890✅ ●100/100Remotely silence local notificationsdevice removal deletes local_notification_settings via MSC3391 tombstone
MSC3883🟥 ●0/0Fundamental state changesdraft proposal, no concrete API; would require new room version
MSC3881🟥 ●0/0Remotely toggling push notifications for another clientpusher enabled and device_id fields not exposed
MSC3874🟥 ●0/0MSC3874 Loading Messages excluding Threadsrel_types and not_rel_types filters absent; org.matrix.msc3874 not advertised
MSC3872🟥 ◐0/0Order of rooms in Spacesmanual room ordering in spaces; vague proposal, no API defined
MSC3871🟥 ●0/0Gappy timelineNo gaps field on /messages and no org.matrix.msc3871 versions flag
MSC3870🟥 ●0/0Async media upload extension: upload to URLupload_url field and /complete endpoint not implemented
MSC3865✅ ●100/100User-given attributes for usersclient-side; uses generic account_data endpoints already implemented
MSC3864✅ ●100/100User-given attributes for roomsclient-side; uses generic account_data endpoints already implemented
MSC3851🟥 ●0/0Allow custom room presets when creating a roomonly standard RoomPreset variants accepted; no custom string presets
MSC3848🟥 ●0/0Introduce errcodes for specific event sending failures.no M_INSUFFICIENT_POWER/M_NOT_JOINED/M_ALREADY_JOINED errcodes emitted
MSC3847🟥 ●0/0Ignoring invites with policy roomsno policy room handling for m.policies account data
MSC3843🟥 ●0/0Reporting content over federationFederated report endpoint absent; client report handling is separate
MSC3840🟥 ◐0/0Ignore invitesclient-side ignored invites account data; no server behavior required
MSC3839🟥 ●0/0primary-identity-as-keyNo public-key identity or challenge login; five login types, none key-based
MSC3837🟥 ●0/0Cascading profile tags for push rulesno profile_tags array; only single profile_tag handled
MSC3834🟥 ●0/0Opportunistic user key pinning (TOFU)TOFU signing key is client-side; no server hooks
MSC3815✅ ●100/1003D Worldsm.world.profile global account data passthrough; 3D and world state excluded
MSC3814✅ ●90/90Dehydrated devices with SSSSEvents served over GET with from paging; POST kept for older clients
MSC3803✅ ●100/100Matrix Widget API v2m.widgets account data passthrough; widget protocol and room state excluded
MSC3767🟥 ●0/0Time based notification filteringtime_and_day push condition not present
MSC3759🟥 ●0/0Leave event metadata for deactivated usersdeactivation leaves omit m.deactivated metadata
MSC3744🟥 ●0/0Support for flexible authenticationno flexible-auth /register or /account/authenticator endpoints
MSC3726🟥 ●0/0Safer Password-based Authentication with BS-SPEKEopen MSC; no BS-SPEKE login/register/password flows
MSC3723🟥 ●0/0Federation /versionsopen MSC; no /_matrix/federation/versions endpoint
MSC3713🟥 ●0/0Alleviating ACL exhaustion with ACL Slotsopen MSC; no ACL slot state-key handling
MSC3682🟥 ●0/0Sending Account Data to Application ServicesAS transactions do not include account_data field
MSC3673🟥 ●0/0Encrypting ephemeral data unitsbranch MSC; no encrypted EDU envelope support
MSC3672🟥 ●0/0Sharing ephemeral streams of location databranch MSC; no m.beacon EDU support or location streaming
MSC3664✅ ●80/88Pushrules for relationsreply default, relation eval, rule repair; no insert-time lone-key reject
MSC3644🟨 ●50/100Extensible Events: Edits and repliesEdits fold with no m.new_content, but a type-changing edit is dropped
MSC3618🟥 ◐0/0Simplify federation /send responsebranch MSC; tuwunel returns full pdus map per current spec
MSC3593🟥 ●0/0Safety Controls through a generic Administration APInone of the proposed /admin/* endpoints exist; tuwunel uses admin room
MSC3571🟥 ●0/0Aggregation paginationno /aggregations endpoint; no aggregation pagination
MSC3570🟥 ◐0/0Relation history visibility changesno special history visibility for relations; new room version needed
MSC3547🟥 ●0/0Allow appservice bot user to read any rooms the appservice is part ofOnly /joined_members admits an AS; no versions flag, other 6 routes unchanged
MSC3488🟥 ◐10/10m.location: Extending events with location datalocation event types pass through; no m.tile_server in well-known
MSC3480🟥 ◐10/20Make device names privateallow_device_name_federation config gates device name exposure
MSC3469🟥 ○0/0Mandate HTTP Range on Content Repository Endpointsdepends on object_store / hyper response writer for ranges
MSC3468🟥 ●0/0MXC to Hashesno MXC-to-hash endpoints; no /clone or /hash routes
MSC3414🟥 ●0/0Encrypted state eventsno encrypted state event handling or encrypted_state in publicRooms
MSC3395🟥 ●0/0Synthetic Appservice Eventsno synthetic appservice events emitted on register/login/logout
MSC3394🟥 ●0/0New auth rule that only allows someone to post a message in relation to anoth…no auth rule restricting top-level vs threaded messages
MSC3389🟥 ●0/0Redaction changes for events with a relationno m.relates_to preservation in redactions
MSC3386🟥 ●0/0Unified Join Rulesno unified allow_join/allow_knock; no new room version
MSC3385🟨 ◐30/40Bulk small improvements to room upgradesupgrade copies fixed list of state, not all m.* state nor account_data
MSC3361🟥 ●0/0Opportunistic Direct Pushno direct pusher kind or notifications in sync
MSC3360🟥 ●0/0Server Statusno /server/status endpoint or m.server.status event
MSC3359🟥 ●0/0Delayed Pushno jitter pusher field; not advertised in versions
MSC3356🟥 ●0/0Add additional OpenID user info fieldsopenid userinfo returns only sub
MSC3338🟥 ●0/0Adding iframe specifics to preview jsonurl preview has no iframe/oEmbed support
MSC3325🟥 ●0/0Upgrading invite-only roomsupgrade does not switch invite-only rooms to restricted
MSC3277🟥 ●0/0Scheduled messagesno scheduled-message at= query param support
MSC3269🟥 ●0/0An error code for busy serversno M_SERVER_BUSY error code
MSC3262🟥 ●0/0aPAKE authenticationSRP6a aPAKE login/registration not implemented
MSC3230✅ ●100/100Spaces top level orderroom account data passthrough (m.space_order); ordering logic client-side
MSC3219🟥 ●0/0Space Flairspace flair events and member flag not implemented
MSC3216🟥 ●0/0Synchronized access control for Spacesspace-level synchronized PL replication absent
MSC3214✅ ◐90/100Allow overriding m.room.power_levels using initial_stateinitial_state PL effectively replaces default via later append
MSC3202✅ ●88/95Encrypted Appservicesdevice_lists.changed, OTK counts, fallback types under org.matrix.msc3202
MSC3192🟥 ●0/0Batch state endpointbatch_state endpoint not implemented
MSC3189🟥 ●0/0Per-room/per-space profilesper-room/space scoped profile API not implemented
MSC3144🟥 ●0/0Allow Widgets By Default in Private Roomsprivate_chat preset does not lower widgets PL
MSC3079🟥 ●0/0Low Bandwidth Client-Server APIbranch; no CoAP/CBOR/DTLS support
MSC3051🟥 ◐0/0A scalable relation formatopen; m.relations array not handled
MSC3038🟥 ●0/0Typed Typing Notificationsbranch; no events field on typing
MSC3032🟥 ◐20/20Thoughts on updating presenceeffective presence; busy supported, profile-as-rooms absent
MSC3020🟥 ◐0/0Support for private federation networksbranch; same proposal as MSC3018, not implemented
MSC3018🟥 ◐0/0Support for private federation networksbranch; no m.networks capability or network query
MSC3015✅ ●100/100Room state personal overridesoverride.* room account data rides the generic per-room endpoint and sync
MSC3014🟥 ●0/0HTTP Pushers for the full event with extra rooms informationopen; no full_event_with_rooms pusher format
MSC3009✅ ●100/100Websocket transport for client <–> widget communicationsm.widgets account data passthrough; transports field opaque; client ws excluded
MSC3008✅ ●100/100Scoped access for widgetsm.widgets account data passthrough; auth.scopes opaque; OAuth, client excluded
MSC2970🟨 ◐40/50Remove pusher path requirementpath/scheme constraints relaxed; lacks fragment/userinfo/8000-char checks
MSC2962🟥 ●0/0Managing power levels via Spacesno auto_users or m.room.power_level_mappings handling
MSC2961🟥 ◐0/10External Signaturesendpoint accepts arbitrary signature keys; object form discarded
MSC2949✅ ◐100/100Proposal to clarify “Requires auth” and “Rate-limited” in the specown auth and rate policy diverges from spec annotations; client advice excluded
MSC2943🟥 ●0/0Return an event ID for membership endpointsmembership endpoint responses lack event_id
MSC2938🟥 ●0/0Report content to moderatorsModerator report delivery absent; reporting client UX excluded.
MSC2923🟥 ◐0/0Matrix to Matrix connectionsspeculative idea-stage; no concrete API
MSC2895🟨 ●20/30Improving the way membership lists are queriedmembership filter present but single valued; no /rooms, joined_* not deprecated
MSC2883🟥 ●0/0[WIP] Matrix-flavoured MLSWIP MLS; no DMLS support
MSC2882🟥 ◐0/0[WIP] Tempered Transitive TrustWIP; new public_user_signing key, m.device.signature EDU not implemented
MSC2872✅ ●100/100Move the widget title to the rootm.widgets account data passthrough; top-level title opaque; client UI excluded
MSC2855🟥 ◐0/0Server-Initiated Client Clear-Cache & Reloadno clear-cache signal mechanism
MSC2848🟥 ●0/10Globally unique event IDsonly legacy GET /event/:eventId; new room-scoped path absent
MSC2846🟥 ●0/0Decentralizing media through CIDsopen; CID-based MXC URLs not implemented
MSC2845🟥 ◐0/5Thirdparty Lookup API for Telephone Numberssrc/api/client/thirdparty.rs returns empty protocols TODO
MSC2836🟥 ●0/0Threadingadvertises org.matrix.msc2836 in /versions but no event_relationships
MSC2828🟥 ◐0/0Proposal to restrict allowed user IDs over federationno extended_user_id_char auth rule restriction
MSC2815✅ ◐90/100Proposal to allow room moderators to view redacted event contentinclude_unredacted_content honored; admin or redact PL gates access
MSC2812🟥 ●0/0Role-based power structuresrole-based power proposal still draft; no m.role events
MSC2802🟥 ●0/0Full Room Abstractionopen meta proposal to redesign spec; not implementable as-is
MSC2787🟥 ●0/0Portable Identitiesno UPK/UDK/attestation infrastructure
MSC2785🟥 ●0/0Event notification attributes and actionsno notification_attribute_data or notifications_profile endpoints
MSC2782✅ ●90/90Pushers with the full event contentfull_event opt-in works; membership absent, user_is_target now correct
MSC2772🟥 ◐0/0Notifications for Jitsi Callsno .m.jitsi default underride push rules
MSC2757🟥 ●0/0Sign EventsNo event_signing key type; no client signature plumbing
MSC2755🟥 ●0/0Lazy load roomsNo room_limit_by_complexity filter handling
MSC2753🟥 ●0/0Peeking via Sync (Take 2)No /peek or /unpeek; no peek section in sync
MSC2749🟥 ●0/0Per-user E2EE on/off settingNo m.encryption capability; no force/preference logic
MSC2730🟥 ●0/0Verifiable forwarded eventsNo /forward/{targetRoomId}; no signature validation
MSC2716🟥 ●0/0Incrementally importing history into existing roomsNo /batch_send; no m.room.insertion/batch/marker handling
MSC2695🟨 ●40/40Get event by ID over federationFederation /event exists; no client /events/{eventId} revival
MSC2673🟥 ●0/0Notification LevelsNo notification_levels concept; push rules used
MSC2596🟥 ◐0/0Proposal to always allow rescinding invitesVendor room version net.maunium.msc2596 not registered; no rescind exception …
MSC2513🟥 ◐0/10Allow clients to specify content for membership eventsMembership endpoints accept reason only; no content body param
MSC2499🟨 ◐10/30Fixes for Well-known URIssrc/service/resolver/well_known.rs follows redirects; 12288B cap; uses /versions
MSC2487🟥 ◐0/0Filtering for AppservicesNo filter field on appservice registration
MSC2477🟥 ◐0/0User-defined ephemeral events in roomsNo PUT /rooms/{roomId}/ephemeral/{type}/{txnId} route
MSC2474✅ ●100/100Add key backup version to SSSS account dataplaintext version in m.megolm_backup.v1 kept verbatim; client matching excluded
MSC2448🟨 ●70/80Using BlurHash as a Placeholder for Matrix Mediablurhash on profile, federation query, media upload, member events
MSC2444🟨 ●30/30Proposal for implementing peeking over federation (peek API)world_readable allowed on some federation reads; no /peek subscription API
MSC2438🟥 ●0/10Local and Federated User Erasure Requestsdeactivate present but no erase param, no fed/AS erase endpoints
MSC2437✅ ◐100/100Store tagged events in Room Account Datam.tagged_events stored via existing room account_data routes
MSC2413🟥 ●0/0Remove client_secretrequestToken routes served, but client_secret stays required by the ruma type
MSC2391🟥 ●0/0Federation point-queries.No federation point-query state endpoint
MSC2388🟥 ●0/0Toward the EDU-to-PDU transition: Read Receipts.Receipts are EDU only; no m.receipt PDU and no m.read rel_type in either tree
MSC2380🟥 ●0/0Matrix Media Information APINo /media/r0/info/{origin}/{media_id} endpoint
MSC2379🟥 ●0/0MSC 2379: Add /versions endpoint to Appservice API.No /_matrix/app/versions probe code
MSC2375🟥 ◐0/0Appservice Invite StatesAppservice transactions send raw PDU JSON without invite_room_state injection
MSC2370🟥 ●0/0Resolve URL APINo /resolve_url endpoint in source
MSC2326🟥 ●0/0Label based filteringLabel filtering absent; client hashtags and hashing excluded.
MSC2316🟥 ●0/0Federation queries to aid with database recoveryNo /_matrix/federation/v1/query/members route
MSC2315✅ ●100/100Allow users to select “none” as an integration managerm.integrations kept verbatim incl. unstable name; client rendering excluded
MSC2301🟥 ●0/0Proposal for an /info endpoint on the CS APINo /info merger of /versions; no branding fields exposed
MSC2300🟥 ●0/0Proposal for a /ping endpoint on the CS APINo GET /_matrix/client/r0/ping route
MSC2278🟥 ◐0/10Proposal for deleting content for expired and redacted messagesNo DELETE /media client API; only admin-only delete helper
MSC2270🟨 ●30/30Proposal for ignoring invitesm.ignored_room_list absent; generic account-data store only, no sync filter
MSC2228🟥 ●0/0Proposal for self-destructing messagesself_destruct fields not honored
MSC2214🟥 ●0/0Joining upgraded private roomsm.room.previous_member event not implemented
MSC2213🟥 ●0/0Rejoinability of private roomsrejoin_rule field not implemented
MSC2212🟥 ●0/0Third party user power levelsthird_party_users not present in PL handling or auth rules
MSC2211🟥 ●0/0Identity Servers Storing Threepid Hashes at Restno identity-server client at all; IS hash-at-rest storage and API excluded
MSC2199🟥 ●0/0Canonical DMs (server-side middle ground edition)no m.kind in sync summary; uses legacy m.direct account data
MSC2190✅ ◐80/80Allow appservice bots to use /syncappservice token defaults to sender_localpart user
MSC2162🟥 ●0/0Signaling Errors at Bridgesno m.bridge_error on appservice delivery failure; absent in src and ruma
MSC2127🟥 ●0/0Proposal for a federation capabilities APIfederation /capabilities and per-room capabilities not present
MSC2108🟥 ●0/0Sync over Server Sent Eventsno /sync/sse or text/event-stream paths
MSC2102🟥 ◐0/0Enforce Canonical JSON on the wire for the S2S APIno canonical-JSON wire enforcement on inbound S2S
MSC1974🟥 ●0/0Crypto Puzzle Challengeopen; hashcash-style proof-of-work never adopted
MSC1973🟥 ●0/0Hash Key User IDopen; speculative scheme never adopted
MSC1921🟥 ◐0/0Cancellation of 3pid validation tokens3pid cancelToken endpoints not implemented; 3pid stack stubbed
MSC1862🟥 ◐20/20Presence flag for capabilities APIpresence on/off enforced; m.presence not in /capabilities response
MSC1797🟥 ●0/0Proposal for more granular profile error codesbranch; M_USER_NOT_FOUND/M_PROFILE_* error codes not used
MSC1780🟥 ●0/0Add DIDs and DID names as admin accounts to HSopen; m.did medium not supported in 3pid endpoints
MSC1768🟥 ●0/0Proposal to authenticate with public keysopen; m.login.proof.* not implemented
MSC1763🟥 ●?/0Proposal for specifying configurable per-room message retention periods.no m.room.retention support; /retention/configuration endpoint absent
MSC1762🟥 ●0/0Support user-owned identifiers as new 3PID typeno m.did mediums; ruma Medium is email or msisdn; 3PID invites rejected
MSC1740🟥 ◐?/0Using the Accept header to select an encodingno Accept-based content negotiation; only application/json supported
MSC1607🟥 ◐0/0Proposal for room alias grammaralias parsing delegated to Ruma RoomAliasId; no NFKC/punycode/blacklist logic
MSC1236✅ ●100/100Matrix Widget API v2[→ MSC4411] m.widgets via generic account data; widget API/UI and room state …
MSC1228🟥 ●?/0Removing MXIDs from eventsremoving mxids never merged; no user_room_key or pseudo IDs in src

Closed

Sorted by MSC number, highest first. Out-of-scope rows are listed in the Out of scope section.

MSCStatusImplTitleNote
MSC4465🟥 ●0/0On-Demand Fetch for Missing EventsGET /event/{eventId} returns M_NOT_FOUND; no federation fallback.
MSC4463🟥 ◐0/0Backfilling Pinned EventsNo pinned-events backfill on join or on pinned_events update.
MSC4435🟥 ●0/0Room slowmodeNo m.room.slowmode handling
MSC4418✅ ●100/100Make destination a required server authentication fielddestination required on inbound and outbound; cited verbatim in MSC.
MSC4415🟨 ●0/50Make /_matrix/client/v3/admin/whois/{userId} only available to adminswhois is served, but a non admin may still look up their own user
MSC4403🟥 ●0/0Forbid event_id on PDUs received over federationnew room version forbidding event_id on PDUs; com.nhjkl.msc4403.opt2 absent.
MSC4400🟥 ●0/0Remove the depth field from PDUsnew room version removing depth field; com.nhjkl.msc4400.opt1 absent.
MSC4390🟥 ●0/0Room Blocking API[→ MSC4375?] no client admin endpoints for room block/delete; only federation…
MSC4384🟨 ◐?/50Supporting alternative room directory sortingLargest-first sort is hardcoded; no alt-sort hook
MSC4375🟥 ●0/0Admin Room ManagementNo /_matrix/client/v1/admin/rooms/* endpoints
MSC4373🟥 ●0/0Server opt-out of specific EDU typesNo federation EDU-type preference endpoint is registered
MSC4329🟥 ●0/0Inviting with authorizationfederation /v3/invite with create event in state not implemented
MSC4324✅ ◐80/80Fixing MSC4289’s power level for tombstonestombstone PL=150 set; matches highest-anchored intent for default config
MSC4317🟥 ●0/0Signed profile datasigned profile data; no m.signed profile field handling
MSC4316🟥 ●0/0External cross-signing signatures with X.509 certificates and (semi-)automate…X.509 cross-signing; no external signature support
MSC4299✅ ◐100/100trusted usersGeneric account data stores and syncs m.trusted_users; no trust logic to break
MSC4294🟥 ●0/0Ignore and mass ignore invitesno ignored_inviters list, no auto invite cleanup
MSC4276🟥 ●0/0Soft unfailure for self redactionsno self-redaction soft-fail bypass
MSC4231🟨 ◐0/100Backwards compatibility for media captionsthread-root check exists, but reply-bearing fallback parses as Reply; accepted
MSC4214🟥 ●0/0Embedding Widgets in Messagesclosed MSC; m.widget event/capability not implemented
MSC4202🟥 ◐20/20Reporting User Profilesclient report endpoint exists; federation forwarding absent
MSC4184🟥 ●0/0Dynamic Notification Suppressionno m.push_rules_executed field on events
MSC4158✅ ◐80/100MatrixRTC focus information in .well-knownrtc_foci exposed in .well-known/matrix/client
MSC4148🟥 ●0/0Permitting HTTP(S) URLs for SSO IdP iconsSSO IdP icon limited to mxc URIs in config; HTTP(S) not allowed
MSC4124🟥 ●0/0Simple Server Authorizationm.server.knock/participation auth events not implemented
MSC4123🟥 ●0/0Allow knock -> join transitionnew room version with knock to join transition not implemented
MSC4107🟥 ●0/0Feature-focused versioningfeatures key on /versions not added
MSC4098🟥 ●0/0Use the SCIM protocol for provisioningSCIM user provisioning endpoints absent (closed MSC)
MSC4097🟥 ●0/0Interactions between media redirection and authenticationmedia redirect symmetric encryption not implemented
MSC4076🟨 ●60/100Let E2EE clients calculate app badge counts themselves (disable_badge_count)disable_badge_count honored when sending push notifications
MSC4072🟥 ●0/0Handling devices with no one-time keys in /keys/claimMissing/exhausted devices are filtered out, not returned as empty objects.
MSC4059🟥 ●0/0Mutable event contentNo mutable-event EDU or hashes-omitted detection.
MSC4058🟥 ●0/0Additive EventsNo m.additive EDU or unsigned.m.additive metadata pipeline.
MSC4051✅ ◐80/80Using the create event as the room IDV12 RoomVersionRules.room_create_event_id_as_room_id dispatched.
MSC4037✅ ○90/100Thread root is not in the threadReceipts allowed for thread roots; spec wording is mostly client-facing.
MSC4018🟥 ●0/0Reliable call membershipReliable call membership endpoints (PUT/DELETE) not present
MSC4015🟨 ◐70/70Voluntary Bot indicatorsMSC4133 profile serves the bot key; no copy into m.room.member on join
MSC3975🟥 ●0/0rel_type for Repliesm.reply rel_type not handled
MSC3968🟥 ●0/0Poorer featuresm.room.event_features state event not enforced
MSC3961✅ ●90/100Sliding Sync Extension: Typing Notifications[→ MSC4508] sliding sync typing extension implemented
MSC3960✅ ●90/100Sliding Sync Extension: Receipts[→ MSC4551] sliding sync receipts extension implemented
MSC3959✅ ●90/100Sliding Sync Extension: Account Data[→ MSC4548] sliding sync account_data extension implemented
MSC3945🟨 ◐50/50Private device namesFederation hides device names by default; CSAPI /keys/query still leaks them …
MSC3915🟥 ●0/0Owner power levelPL150 owner role / creator-defaults-to-150 not implemented.
MSC3912🟥 ●0/0Redaction of related eventswith_rel_types / with_relations on /redact not implemented.
MSC3902🟥 ◐20/20Faster remote room joins over federation (overview)sends omit_members but immediately fetches full state
MSC3887🟥 ◐0/0List matching push rulesclosed MSC; list-matching in event_match not implemented
MSC3885🟨 ●70/80Sliding Sync Extension: To-Device[→ MSC4538] to_device extension uses its own opaque since token in v5 sync
MSC3884✅ ●90/100Sliding Sync Extension: E2EE[→ MSC4543] sliding sync e2ee extension implemented
MSC3866🟥 ●0/0M_USER_AWAITING_APPROVAL error codeM_USER_AWAITING_APPROVAL error code not implemented
MSC3862🟥 ●0/0event_match (almost) anythingevent_match only matches strings; non-string primitives not converted
MSC3859🟥 ●0/0Add well known media domain proposalno m.media_server in well-known responses
MSC3852🟥 ●0/0Expose user agent information on Devicelast_seen_user_agent not exposed on Device
MSC3782🟥 ●0/0Matrix public key login specm.login.publickey login type not implemented
MSC3779🟥 ●0/0“Owned” state eventsowned state events require new room version
MSC3772🟥 ●0/0Push rule for mutually related eventsrelation_match push condition not implemented
MSC3761🟥 ●0/0State event change controlm.event.acl ACL events for state not implemented
MSC3760🟥 ●0/0State sub-keysstate_subkey requires new room version; not present
MSC3754✅ ●95/100Removing profile information[→ MSC4133?] DELETE profile field route serves avatar_url and displayname; ke…
MSC3741🟥 ●0/0Revealing the useful login flows to clients after a soft logoutlogin does not return per-user flows for soft-logout tokens
MSC3720🟥 ●0/0Account status endpointbranch MSC; no /account_status endpoints (CS or federation)
MSC3659🟥 ●0/0Invite Rulesclosed MSC; no invite_rules account data dispatch
MSC3613🟥 ●0/0Combinatorial join rulesbranch MSC; no combinatorial join_rules array logic in tuwunel
MSC3588✅ ●100/100WIP: MSC3588: Encrypted Stories As Roomsmsc3588.stories.block-list rides the generic account-data store and sync
MSC3585✅ ●100/100Allow the base event to be omitted from /federation/v1/event_auth responseevent_auth handler omits the requested event itself per MSC
MSC3572🟥 ◐0/0Relation aggregation cleanupno relations rename; m.relations only
MSC3523🟥 ●0/0Timeboxed/ranged relations endpointno from_target/to_target query params on /relations
MSC3429🟥 ●0/0Individual room preview APIno /rooms/{id}/preview endpoint
MSC3391✅ ●100/100API to delete account dataBoth DELETE routes reject protected keys before mutation
MSC3306🟥 ●0/0How to count unread messagesnotification_count uses push-rule Notify actions, not MSC3306 algo
MSC3302✅ ●100/100Stories via To-Device-Messagingm.stories.blocklist and m.stories.ignore ride the generic account-data path
MSC3270✅ ●100/100Symmetric megolm backupbackup algorithm, auth_data, session_data kept raw; SSSS secret via account data
MSC3244🟥 ●0/10Room version capabilitiescapabilities lacks room_capabilities knock/restricted info
MSC3174🟥 ●0/0An error code for spam rejectionsM_ANTISPAM_REJECTION error code not used
MSC3137✅ ●100/100Define space room type, subset of MSC1772type:m.space in m.room.create accepted; used in directory and spaces
MSC3125🟥 ●0/0Limits API — Part 5: per-Instance limitsper-instance limits admin API absent
MSC3105🟥 ●0/0Previewing user-interactive flowsOPTIONS preflight for UIA flows not implemented
MSC3073🟥 ●0/0Role based access controlclosed; rbac/m.role not implemented
MSC3060🟥 ●0/0Room labelsbranch; m.room.labels not surfaced in publicRooms
MSC3053🟥 ●0/0Limits API — Part 2: per-Room limitsclosed; no admin/limits endpoints or m.limits.* events
MSC3026✅ ●100/100busy presence statePresenceState::Busy and msc3026.busy_presence flag
MSC3013🟥 ●0/0Encrypted Pushclosed; no encrypted-push algorithm support
MSC3012🟥 ●0/0Post-registration terms of service APIbranched; no /terms endpoint or m.terms account data
MSC3007🟥 ●0/0Forced insertion and room blocking by self-banningclosed; no insert_member power or /insert endpoint
MSC3006🟥 ●0/0Bot Interactionsclosed; bot-interaction event types not implemented
MSC3005🟥 ●0/0Streaming Federation Eventsclosed; no streaming federation transport
MSC2957🟥 ●0/0Cryptographically Concealed CredentialsPAKE-style login flow; closed; not implemented
MSC2912🟥 ●0/0Setting cross-signing keys during registrationno device_signing field accepted by /register
MSC2839🟥 ◐0/0Dynamic User-Interactive Authenticationclosed; UIA flows are static in Tuwunel
MSC2835🟥 ◐0/10Add UIA to the /login endpointclosed; /login does not consume UIA auth dict
MSC2821🟥 ●0/0Test PusherPOST /pushers/push test endpoint not implemented
MSC2810🟨 ●70/70Consistent globs specificationACL and push globs go through wildmatch; the backslash escape is unimplemented
MSC2773🟥 ◐0/0Room kindsclosed; no m.kind summary or m.room.kind handling
MSC2771✅ ●100/100Bookmarksroom account data passthrough (m.bookmarks); client selection, UI excluded
MSC2706🟥 ●0/0IPFS as a media repositoryNo IPFS support; no m.ipfs capability
MSC2704✅ ◐100/100Handling duplicate media on /upload + clarifying the origin of an MXC URIFresh MXC per upload; no dedup
MSC2703✅ ●100/100Media ID grammar32-char alphanumeric media IDs; opaque
MSC2700🟨 ◐50/50Thumbnail requirements for the media repoimage crate handles png/jpeg/gif; no svg/video
MSC2697🟨 ●40/60Device dehydration[→ MSC3814] Dehydration served at the MSC3814 prefix; no claim and no token r…
MSC2654🟥 ●0/0Unread countsNo unread_count in sync; no msc2654 markers
MSC2638🟥 ●0/0Ability for clients to request homeservers to resync device listsNo /devices/refresh endpoint; no msc2638 marker in src
MSC2631✅ ◐80/80Add default_payload to PusherDataruma HttpPusherData flattens custom data; default_payload accepted via passth…
MSC2625🟥 ◐0/0Add mark_unread push rule actionNo mark_unread action; sync exposes only highlight/notification counts
MSC2579✅ ●100/100Improved tagging supportGeneric account-data path carries m.tag.<tag>; ordering rules are client-side
MSC2463🟥 ◐0/0Exclusion of MXIDs in push rules content matchingclosed MSC; no MXID exclusion in push rule content matching
MSC2416✅ ●90/100Add m.login.jwt authentication typem.login.jwt fully wired in session module
MSC2389🟥 ●0/0Toward the EDU-to-PDU transition: Typing.Typing is EDU only; no m.typing PDU; a later message does not end typing
MSC2356🟥 ●0/0Bulk /joined_members endpointNo POST /joined_members bulk endpoint in src/api
MSC2314🟥 ●0/40Backfilling Current Statesrc/api/server/state.rs:14 requires event_id; no current-state branch
MSC2306✅ ◐100/100Removing MSISDN password resetsmsisdn pw reset endpoint absent; ThreepidDenied on msisdn
MSC2271🟥 ●0/0Proposal for TOTP 2FANo TOTP endpoints, no m.login.totp UIA stage
MSC2261✅ ●100/100Allow m.room.aliases events to be redacted by room adminsSubsumed by MSC2432/v6 redaction rules
MSC2260🟨 ●50/50Update the auth rules for m.room.aliases eventsSubsumed by MSC2432/v6 auth rules; aliases sender-domain check enforced
MSC2233🟥 ●0/0Unauthenticated Capabilities APIno /capabilities/server unauthenticated endpoint
MSC2153✅ ●100/100Add a default push rule to ignore m.reaction eventsRuleset::server_default() includes .m.rule.reaction via Ruma
MSC2061✅ ●100/100make the trailing slash on GET /_matrix/key/v2/server/ optionalsrc/api/router.rs:250 routes both /key/v2/server and /server/{key_id}
MSC2000🟥 ●0/0MSC 2000: Proposal for server-side password policiesbranch; no /password_policy endpoint or password validation
MSC1998🟥 ●0/0Two-Factor Authentication Providersclosed; TOTP/recovery 2FA never adopted by spec
MSC1958✅ ●100/100Widget architecture changesrevised m.widgets stored verbatim; client widget rendering and OpenID excluded
MSC1953✅ ●100/100Remove prev_content from the essential keys listruma redact() does not retain prev_content
MSC1943✅ ●100/100Set v3 to be the default room versiondefault room version V12 (>= v3)
MSC1935🟨 ●30/40Key validity enforcement[→ MSC2076] no valid_until_ts enforcement; v4 and v5 supported but listed uns…
MSC1888✅ ●90/100Proposal to send EDUs to appservices[→ MSC2409] appservice receive_ephemeral with EDU push; src/service/sending/s…
MSC1840🟨 ●60/100Typed roomsroom_types filter on sliding sync only; v3 filter API unextended
MSC1796🟥 ◐0/0Proposal for improving notifications for E2E encrypted roomsbranch; m.mentions on encrypted events not honored server-side
MSC1777🟥 ●0/0Proposal for implementing peeking over federation (server pseudousers)branch; server pseudouser peeking not implemented
MSC1776🟥 ●0/0Proposal for implementing peeking via /sync in the CS APIbranch; POST /sync with peek not implemented
MSC1731🟥 ◐0/0Mechanism for redirecting to an alternative server during SSO loginbranch; homeserver query param on sso loginToken redirect not added
MSC1714🟥 ●0/0using the TLS private key to sign federation-signing keysbranch/abandoned 2018; no rsa key id, no TLS-cross-signing in src/api/server/…
MSC1687🟥 ●?/0Proposal for storing an encrypted recovery key on the server to aid recovery …no PBKDF passphrase backup logic; auth_data passes through opaquely
MSC1597🟨 ◐20/30Grammars for identifiers in the Matrix protocolvalidate_strict is dispatched; ruma admits / and +; ID grammars unenforced
MSC1497✅ ●100/100Advertising support of experimental features in the CS APIunstable_features map present in /_matrix/client/versions
MSC1425✅ ●100/100Room Versioningroom versioning fully present; STABLE_ROOM_VERSIONS in core/config
MSC1227✅ ●80/90Proposal for lazy-loading room members to improve initial sync speed and clie…lazy_load_members supported via filter; service in rooms/lazy_loading
MSC1194🟥 ●0/0A way for HSes to remove bindings from ISes (aka unbind)no IS unbind; delete_3pid and deactivate always return no-support
MSC688✅ ●80/100Room Summaries (was: Calculate room names server-side)sync summary with heroes and counts; v3 heroes capped at 5 members
MSC441🟨 ●20/20Support for Reactions / Aggregations[→ MSC2675/MSC2676] relations paging only; no vote coalescing, counts or QoS …

Out of scope

MSCs marked n/a: the homeserver-applicable scope is empty (addressed to an identity server, integration manager, widget or client only, or governance/process), or the MSC is unimplemented and superseded by another MSC. Scope is a property of the proposal, not of what Tuwunel has chosen to build. Listed here for audit; the Inv column carries each row’s inventory bucket in place of the (uniformly empty) Impl cell.

MSCStatusInvTitleNote
MSC4575⬛ ●openMatrixRTC m.full_mesh transportPeer transport and opaque event relay; no new homeserver behavior
MSC4572⬛ ●openMetric for server protocol coverageGovernance and website scoring process; no protocol implementation.
MSC4571⬛ ●openFLOE-encrypted attachmentsClient attachment encryption; opaque ciphertext storage and event relay.
MSC4570⬛ ●openRemote Network Targeting PoliciesBridge metadata and moderation-policy consumers; opaque state relay.
MSC4568⬛ ●openDTMF for MatrixRTCClient keypad and bridge DTMF handling; opaque room-event relay only.
MSC4566⬛ ●openMatrixRTC PSTN signallingClient and bridge signalling; opaque room-event relay only.
MSC4564⬛ ●openAgent status in room messagesAgent emitters and client UI; opaque message metadata.
MSC4555⬛ ●closedMultiple RepliesClient reply arrays and rendering; opaque room-event content.
MSC4553⬛ ●openForwarded messagesClient forwarding and rendering; opaque event content excluded.
MSC4550⬛ ●openExplicit linksClient hyperlink presentation and sender behavior only; opaque event content
MSC4549⬛ ●openAudio metadata for m.audio eventsClient audio metadata; opaque room-event content excluded.
MSC4546⬛ ●openCirclesClient video UX hint; opaque room-event content excluded.
MSC4541⬛ ●openWidget stateWidget rendering and opaque state-event schema only; no homeserver obligations
MSC4533⬛ ●openMatrixRTC widget actions for authenticated livekit realted endpointsWidget delegation excluded; endpoint authorization belongs to MSC4195
MSC4531⬛ ◐openDeprecate legacy VoIPspec deprecation of legacy VoIP; no server behaviour change is required
MSC4518⬛ ●openRegistriesprocess MSC for spec registries; no homeserver behaviour is defined
MSC4515⬛ ●openRTC Transports discovery for widgetswidget API action; the hosting client calls the endpoint, no server scope
MSC4489⬛ ●openPer-room contact state eventclient and bot only; m.room.contact is ordinary room state
MSC4487⬛ ●openDeprecate internal use of matrix.to navigationclient-only; server sends no matrix.to or matrix: URIs
MSC4481⬛ ●openNon-sigil matrix.toclient-only URL format; server emits no matrix.to links
MSC4475⬛ ●openMedia galleries by inline MXC linksInline MXC gallery rendering is client-side; link tracking deferred
MSC4474⬛ ◐openClarify usage of content blocks in Extensible EventsSpec clarification for MSC1767 authors; no homeserver requirement
MSC4471⬛ ●openStreaming ephemeral event updates for room eventsMSC states no homeserver work required; to-device transport suffices
MSC4468⬛ ◐openReporting to communities (via to-device)Pure state-event plus to-device passthrough; no HS-specific work.
MSC4460⬛ ●openExtensible Events - Alternative unstable supportClient-side hybrid extensible-events rendering rules; no Tuwunel dispatch.
MSC4459⬛ ●openImage pack referencesClient-side image pack reference field; homeserver passes events through tran…
MSC4455⬛ ●openCatch-all property for spacesClient orphan filtering only; opaque state relay has zero homeserver scope
MSC4454⬛ ●openDeprecating Spoiler Fallback In Media RepositoryClient spoiler body construction; no homeserver behavior
MSC4451⬛ ●openDeprecate notifications endpointSpec-only deprecation; endpoint still served per MSC
MSC4444⬛ ●closedMalicious PDUsApril Fools joke MSC, status closed
MSC4421⬛ ●closedStandardize the spec on US Englishspec house-style proposal (en-US); no protocol surface.
MSC4414⬛ ●openDesign decision - Errorsdesign-direction proposal with no technical changes.
MSC4413⬛ ◐openRemove private join_ruleprivate join_rule treated as unknown; effective semantics already aligned.
MSC4412⬛ ●openWidget Base PostMessage APIWidget postMessage negotiation; no homeserver footprint
MSC4411⬛ ●openWidget State EventWidget host UI and security excluded; opaque room state only
MSC4409⬛ ●mergedClarify thumbnailing behavior in E2EEClient thumbnail guidance in E2EE; no homeserver requirement
MSC4407⬛ ●openSticky Events (Widget API)widget API for sticky events; no homeserver involvement beyond MSC4354.
MSC4405⬛ ●openDeprecate the emoji method for SAS verificationdeprecates emoji SAS in favor of decimal; client-side method choice.
MSC4404⬛ ●closedCompare emoji by name rather than imageadds accept_languages to to-device verification; client SAS UI guidance.
MSC4392⬛ ●openEncrypted reactions and repliesclient puts m.relates_to inside encrypted payload; server forwards untouched.
MSC4391⬛ ●openSimplified in-room bot commandsin-room bot command UI; state and message events forwarded opaquely.
MSC4389⬛ ●openImage ordering within packsimage pack ordering is account-data; server passes through opaque blobs.
MSC4386⬛ ●openAutomatically sharing secrets after device verificationclient-to-client to-device verification protocol; server forwards opaque events.
MSC4385⬛ ●openPushing secrets to other devicesClient to-device convention; server forwards m.secret.push opaquely
MSC4381⬛ ◐mergedRemove plaintext sender keyRemoval of plaintext sender_key is client-side; server is opaque
MSC4362⬛ ●openSimplified Encrypted State EventsNo encrypt_state_events handling in m.room.encryption
MSC4349⬛ ●openCausal barriers and enforcementcausal barrier terminology and deferred authorization not adopted
MSC4347⬛ ●closedEmoji verification imagesclient-side emoji image rendering for SAS verification; not server
MSC4340⬛ ●openPrompts and partial commands for in room commands.bot command prompts; client-side concern, no server changes
MSC4334⬛ ●openAdd m.room.language state event.m.room.language state event; not whitelisted/handled specially
MSC4333⬛ ●openRoom state API for moderation botsmoderation bot state event; client-side concern
MSC4332⬛ ●openIn-room bot commandsin-room bot commands; client-side concern, no server changes
MSC4321⬛ ●openPolicy Room Upgrade Semanticspolicy room upgrade move/transition semantics not handled
MSC4313⬛ ●mergedRequire HTML <ol> start Attribute supportclient HTML rendering requirement; not applicable to homeserver
MSC4310⬛ ◐closedMatrixRTC decline m.rtc.notificationevent-only MSC; ruma feature enabled, no homeserver-specific behavior
MSC4302⬛ ●openExchanging FHIR resources via Matrix eventsnew event type for FHIR, no server logic
MSC4301⬛ ●closedEvent capability negotiation between clientsclient-to-client capability negotiation
MSC4300⬛ ●openProcessing status requests & responsesclient-to-client status request/response in events
MSC4296⬛ ●openMentions for device IDsclient-side mentions field extension
MSC4295⬛ ●openBot bounce limit - a better loop prevention mechanismBot and bridge bounce logic excluded; event content remains opaque
MSC4292⬛ ●openHandling incompatible room versions in clients[→ MSC4331]
MSC4286⬛ ●openApp store compliant handling of payment links within eventsclient-side HTML rendering attribute
MSC4283⬛ ●openDistinction between Ignore and Blockterminology MSC, no implementation surface
MSC4281⬛ ●closedMitigating Membership Mistakes, or “Invisible” Cryptographyclosed April 1 joke MSC; client-only encryption mode
MSC4274⬛ ●openInline media galleries via msgtypesOpaque gallery content; client composition and rendering excluded
MSC4273⬛ ●openApprove and Disapprove ratings for moderation policiesnew event type for moderation tools, no server logic
MSC4270⬛ ●openMatrix Glossaryglossary/spec doc proposal, not an implementation feature
MSC4269⬛ ●openUnambiguous mentions in bodyclient-side message body composition
MSC4268⬛ ●mergedSharing room keys for past messagesclient-only E2EE key sharing; server only relays to-device and stores media
MSC4253⬛ ●openModifying or rejecting accepted MSCsSpec process MSC; no implementable behavior
MSC4252⬛ ●openExtensible Events modification: State event handlingClient-side guidance for extensible state events
MSC4245⬛ ●openImmutable encryption algorithmencryption_algorithm in m.room.create not honored
MSC4230⬛ ●merged‘Animated’ flag for imagesevent-only; passthrough; merged in spec
MSC4229⬛ ◐closedPass through unsigned data from /keys/upload to /keys-queryNo proposal text exists; the PR closed on the unfilled template
MSC4227⬛ ●openAudio based quick loginno MSC4108 rendezvous support; audio/DTMF login absent
MSC4221⬛ ●openRoom Bannersevent-only; passthrough
MSC4220⬛ ●openLocal call rejection (m.call.reject_locally)event-only; m.call.reject_locally not interpreted
MSC4211⬛ ●openWebXDC on Matrixevent-only; passthrough
MSC4209⬛ ●openUpdating endpoints in-placedeprecation policy clarification; no code
MSC4206⬛ ●openModeration policy auditing and contextm.policy.rule.context not interpreted server-side
MSC4205⬛ ●openHashed moderation policy entitieshashed entity policies not interpreted
MSC4197⬛ ●openCopy-Paste Hintsevent content field; passthrough
MSC4196⬛ ●mergedMatrixRTC voice and video calling application m.callUpgrade-copy clause removed; remaining calling behavior is client scope.
MSC4193⬛ ●openSpoilers on MediaMedia spoiler content and reveal behavior are client scope.
MSC4192⬛ ●openComparison of proposals for ignoring invitescomparison/research document, not a feature
MSC4171⬛ ●openService membersClient-side name and avatar computation; server filtering explicitly rejected
MSC4161⬛ ●openCrypto terminology for non-technical userscrypto terminology guidance for clients
MSC4159⬛ ●mergedRemove the deprecated name attribute on HTML anchor elementsclient-side HTML rendering recommendation
MSC4157⬛ ●openDelayed Events (widget-api)Widget actions and embedding-client translation excluded; no server change.
MSC4153⬛ ●mergedExclude non-cross-signed devicesclient-side cross-signing enforcement and to-device filtering
MSC4150⬛ ●openm.allow recommendation for moderation policy listsm.allow recommendation for policy lists is client-side
MSC4147⬛ ●mergedIncluding device keys with Olm-encrypted to-device messagessender_device_keys in Olm plaintext is client-side
MSC4146⬛ ●closedShared Message Draftsshared message drafts via m.drafts rooms is client-side
MSC4144⬛ ●openPer-message profilesPer-message profile payload and rendering excluded; no homeserver clause.
MSC4142⬛ ●mergedRemove unintentional intentional mentions in repliesclient-side guidance for m.mentions in replies
MSC4139⬛ ●openBot buttons & conversationsm.prompts mixin is client-only event content
MSC4132⬛ ●mergedDeprecate Linking to an Event Against a Room Alias.deprecation of event-on-room-alias URIs is client-only
MSC4131⬛ ●openHandling m.room.encryption eventsclient-side guidance on handling m.room.encryption events
MSC4126⬛ ●mergedDeprecation of query string authdeprecation of query string auth; server still accepts both
MSC4119⬛ ●openVoluntary content flaggingclient-only m.room.context flagging mixin; server is content-agnostic
MSC4114⬛ ●openMatrix as a password managerclient-only password manager via rooms; no server-side requirements
MSC4113⬛ ●closedImage hashes in Policy Listsm.policy.media_hash unknown to server (closed MSC)
MSC4110⬛ ●openFewer Featuresm.room.event_features state event has no special server handling
MSC4101⬛ ●openHashes for unencrypted mediahashes field on unencrypted media info not consumed by server
MSC4095⬛ ●mergedBundled URL previewsOpaque event preview content; client generation and display excluded
MSC4092⬛ ●openEnforce tests around sensitive parts of the specificationprocess MSC about test enforcement; no protocol changes
MSC4077⬛ ●mergedImproved process for handling deprecated HTML featuresprocess MSC for HTML feature deprecation; no server work
MSC4073⬛ ●openShepherd teamsprocess MSC about SCT shepherd teams; not protocol
MSC4069⬛ ●closedInhibit profile propagation[→ MSC4466]
MSC4052⬛ ●closedHiding read receipts UI in certain roomsPure client-side hint via m.hide_ui state event.
MSC4050⬛ ●openMXID verificationPure client/third-party signaling via custom event types.
MSC4039⬛ ●openAccess the Content repository with the Widget APIWidget API extension; entirely client-to-widget scope.
MSC4036⬛ ●closedRoom organization by promoting threadsPure client UI behavior toggled by m.promote_threads state event.
MSC4013⬛ ●openPoll history cacheclient convention using existing relations API
MSC4006⬛ ●openAnswered Elsewhere for VoIPVoIP m.call.hangup reason value, client concern
MSC4004⬛ ●openunified view of identity serviceidentity service API, not homeserver
MSC4003⬛ ●openSemantic table attributesHTML table sanitization is client concern
MSC3985⬛ ●openBreak-out roomsm.breakout state event not handled
MSC3979⬛ ●openRevised feature profilesclient feature profiles, not a homeserver concern
MSC3978⬛ ●closedDeprecate room taggingroom tagging not deprecated; still implemented
MSC3977⬛ ●openIntroductionIETF MIMI framework draft, not a Matrix MSC
MSC3973⬛ ●openSearch users in the user directory with the Widget APIwidget API extension; client/embedder feature
MSC3972⬛ ●closedLexicographical strings as an ordering mechanismclient-side ordering algorithm
MSC3971⬛ ●openSharing image packsimage pack sharing/links not implemented
MSC3969⬛ ●closedSize limitsm.room.size_limits state event not enforced
MSC3956⬛ ●openExtensible Events - Encrypted Eventsclient-side extensible encrypted event format
MSC3955⬛ ●openExtensible Events - Automated event mixin (notices)m.automated mixin for extensible events not implemented
MSC3954⬛ ●openExtensible Events - Text EmotesExtensible m.emote event type not specifically handled.
MSC3949⬛ ●openPower Level TagsPower-level tag state event is client UX; no server enforcement.
MSC3948⬛ ●openRepository room for ThirdroomThirdRoom 3D-asset repository room type; no homeserver semantics.
MSC3946⬛ ◐openDynamic room predecessorOpaque predecessor state and client navigation excluded; scope is empty.
MSC3935⬛ ●openCute Events against social distancingClient-side cute event msgtype; no server behavior.
MSC3927⬛ ●openExtensible Events - AudioExtensible m.audio event type not specifically dispatched.
MSC3923⬛ ●mergedBringing Matrix into the IETF processSpec-process MSC about IETF coordination; no homeserver code.
MSC3919⬛ ●openMatrix Message Format (IETF/MIMI)IETF informational draft on Matrix message format; not a server feature.
MSC3918⬛ ●openMatrix Message Transport (IETF/MIMI)IETF informational draft about Matrix as MIMI transport; not a server feature.
MSC3910⬛ ●closedContent tokens for media[→ MSC3916]
MSC3906⬛ ●closedProtocol to use an existing Matrix client session to complete login and setup…[→ MSC4108] QR sign-in protocol depends on unimplemented rendezvous
MSC3903⬛ ●closedX25519 Elliptic-curve Diffie-Hellman ephemeral for establishing secure channe…[→ MSC4108] client-to-client X25519 ECDH; no server role
MSC3898⬛ ●closedNative Matrix VoIP signalling for cascaded SFUsVoIP SFU signalling is opaque events between clients
MSC3892⬛ ●openCustom Emotes with Encryptioncustom emotes are pure client/state-event feature
MSC3888⬛ ◐openVoice Broadcastvoice broadcast is opaque events, no server change required
MSC3886⬛ ●closedSimple client rendezvous capability[→ MSC4108]
MSC3880⬛ ●opendummy replies for Olmclient-side Olm dummy event behavior
MSC3879⬛ ●openTrusted key forwardsE2EE key forwarding flag is client-side
MSC3869⬛ ●openRead event relations with the Widget APIWidget API extension; homeservers do not implement widget API
MSC3868⬛ ◐openRoom Contributioncustom state event for room contribution, no server requirements
MSC3857⬛ ●openWelcome messages/screeningno m.room.welcome state event handling
MSC3849⬛ ●openObservations and Reinforcementno observation/reinforcement event handling
MSC3846⬛ ●openAllowing widgets to access TURN serverswidget TURN access; client-widget API only
MSC3845⬛ ●openDraft: Expanding policy rooms to reputationno m.opinion recommendation handling
MSC3844⬛ ●mergedRemove “Mjolnir” (policy room) sharing mechanismremoval of unused Mjolnir share endpoint; Tuwunel never implemented it
MSC3842⬛ ●openPower levels on message (extensible) eventsproposal body is TBD; nothing to implement
MSC3825⬛ ◐openObvious relation fallback locationis_falling_back location handled by Ruma types passively
MSC3819⬛ ●openAllowing widgets to send/receive to-device messageswidget to-device is client-widget API only
MSC3817⬛ ●openAllow widgets to create roomswidget API only, no server-side surface
MSC3813⬛ ●openObfuscated eventsobfuscated events; client-side dummy traffic
MSC3812⬛ ●openHint buttons in messageshint buttons in messages; client UI
MSC3796⬛ ◐openAuth/linking for content repo (and enforcing GDPR erasure)[→ MSC3916]
MSC3790⬛ ●closedRegister Clientsclient launcher registry; client-only
MSC3784⬛ ●mergedUsing room type of m.policy for policy roomsRoom type string only; the text leaves all handling to clients
MSC3783⬛ ●mergedFixed base64 for SAS verificationSAS MAC scheme is client-to-client crypto
MSC3780⬛ ●openKnocking on action=joinmatrix-uri client UX fallback for knock
MSC3775⬛ ●openMarkup Locations for Audiovisual Mediaevent content schema for media markup
MSC3768⬛ ●openPush rule action for in-app notifications[→ MSC2625]
MSC3757⬛ ●closedRestricting who can overwrite a state event.[→ MSC4354]
MSC3755⬛ ●openMember pronounspronouns are client member-content fields
MSC3752⬛ ●openMarkup locations for textevent content schema for text markup locations
MSC3751⬛ ●openAllowing widgets to read account dataWidget API permission, not a homeserver concern
MSC3746⬛ ●closedRender image data in reactions[→ MSC4027] image reactions are client-only event content
MSC3735⬛ ◐openAdd device information to m.room_key.withheld messageclient-side to-device field; server relays unchanged
MSC3725⬛ ●openContent warningsclient-side content warning event content; no server changes
MSC3700⬛ ◐mergedDeprecate plaintext sender_keyclient-side ignoring of sender_key/device_id; server is transparent
MSC3676⬛ ◐mergedTransitioning away from reply fallbacks.client-side reply-fallback transition rules; no server gate
MSC3662⬛ ●openAllow Widgets to share user MxIds to the clientwidget-to-client API; no server involvement
MSC3647⬛ ●openBring Your Own Bridge - Decentralising BridgesWIP bridge negotiation; no spec-level details, no server impl
MSC3639⬛ ●openMatrix for the social media use caseclient-side social media room/event conventions; no server changes
MSC3635⬛ ●openEarly Media for VoIPclient-side VoIP signalling; no server changes required
MSC3592⬛ ●openMarkup locations for PDF documentsclient-side PDF markup event types; no server implementation required
MSC3582⬛ ●mergedRemove m.room.message.feedbackfeedback removal; tuwunel never produces or dispatches on m.room.message.feed…
MSC3575⬛ ●closedSliding Sync (aka Sync v3)[→ MSC4186]
MSC3574⬛ ●openMarking up resourcesno m.markup.resource or annotation handling
MSC3554⬛ ●openExtensible Events - Translatable Messagesno lang field handling; ruma feature not enabled
MSC3553⬛ ●openExtensible Events - Videosunstable-msc3553 not enabled in ruma features
MSC3552⬛ ●openExtensible Events - Images and Stickersunstable-msc3552 not enabled in ruma features
MSC3551⬛ ●openExtensible Events - Filesunstable-msc3551 not enabled; no extensible m.file event
MSC3531⬛ ●openLetting moderators hide messages pending moderationclient-only m.visibility event; server explicitly unchanged
MSC3517⬛ ●closed“Mention” Pushrule[→ MSC3952]
MSC3510⬛ ●closedLet users with the same power level kick/ban/demote each other.[→ MSC3915]
MSC3489⬛ ◐openm.beacon: Sharing streams of location data with historyBeacons are plain state and message events; no homeserver clause in the text
MSC3464⬛ ●closedAllow Users to Post on Behalf of Other Usersno m.on_behalf_of or m.allows_on_behalf_of handling
MSC3417⬛ ●openCall room room typecreation_content type=m.call passes through createRoom
MSC3401⬛ ●closedNative Group VoIP signalling[→ MSC4496] only default PL for m.call/m.call.member; no to-device signaling
MSC3382⬛ ●closedInline message AttachmentsPR-style amendment to MSC2881, not a standalone proposal
MSC3381⬛ ●mergedChat PollsPolls are client-side by design; the poll push rules belong to MSC3930
MSC3368⬛ ●openMessage Content Tagsno message-content tag awareness
MSC3309⬛ ●openRoom Countersno m.room.counter event handling
MSC3291⬛ ●mergedMuting in VoIP callsserver passes call events opaquely; ruma has the type
MSC3286⬛ ●closedMedia spoilersserver passes events opaquely; no spoiler-aware code
MSC3282⬛ ●closedExpose enable_set_displayname in capabilities response[→ MSC3283]
MSC3279⬛ ●closedExpose enable_set_displayname in capabilities response[→ MSC3283]
MSC3265⬛ ●closedLogin and SSSS with a Single Passwordclient-only construction; explicitly no server-side changes
MSC3255⬛ ●closedUse SRV record for homeservers discovery by clientsclient-side discovery via SRV; closed proposal
MSC3246⬛ ●openAudio waveforms (extensible events)client message-content field; no server role
MSC3245⬛ ●openVoice messages (using extensible events)client message type; ruma feature enabled but server has no role
MSC3217⬛ ●openClientside hints for a soft kickm.softkick hint on member event not implemented
MSC3215⬛ ●closedAristotle - Moderation in all thingsdecentralized moderation room scheme not implemented
MSC3184⬛ ●openChallenges Messagesclient-only challenge message types
MSC3160⬛ ●openAttach timezone metadata to time information in messagesclient-only HTML <time> markup in messages
MSC3131⬛ ●openVerifying with QR codes v2client-only QR verification v2 method names
MSC3124⬛ ●closedHandling spoilers in plain-text message fallbackclient-only spoiler fallback handling
MSC3122⬛ ●mergedDeprecate starting key verifications without requesting firstclient-only deprecation of to-device verification start
MSC3089⬛ ●openFile treesclient-only data trees on m.space; no server change required
MSC3088⬛ ●openRoom subtypingclient-only m.room.purpose state event; no server change required
MSC3086⬛ ●openAsserted Identity for VoIP Callsclient VoIP event content; server transparent
MSC3077⬛ ●mergedSupport for multi-stream VoIPmerged; sdp_stream_metadata is event content
MSC3074⬛ ●closedProposal for URIs conforming to RFC 3986 syntax.client URI scheme; not a server feature
MSC3068⬛ ●closedCompliance tiersinformational compliance terminology only
MSC3067⬛ ●closedPrevent/remove legacy groups from being in the specmeta MSC; spec-process decision to drop legacy groups
MSC3062⬛ ●openBot verificationclient-only verification method
MSC3061⬛ ●mergedSharing room keys for past messagesclient-only; sender-flagged room key property
MSC2997⬛ ●openAdd t-shirtjoke proposal; t-shirt design
MSC2974⬛ ●openWidgets: Re-exchange capabilitieswidget-side request_capabilities; client-only
MSC2931⬛ ●openWidget navigate permissionwidget navigate capability; client-only
MSC2881⬛ ●closedMessage Attachmentsnew event content schema (m.attachment relation); generic event passthrough
MSC2876⬛ ●closedAllowing widgets to read events in a roomwidget read_events action; client-only
MSC2873⬛ ●openIdentifying clients and user settings in widgetswidget URL template variables and theme_change; client-only
MSC2871⬛ ●openSending approved capabilities back to the widgetwidget-only feature; homeserver not involved
MSC2813⬛ ●openHandling invalid Widget API requestsclient/widget error handling rules
MSC2801⬛ ●mergedMake it explicit that event bodies are untrusted dataspec note: clients should treat events as untrusted
MSC2790⬛ ●openWidgets - Prompting for user input within the clientclient-side widget modal API
MSC2781⬛ ●mergedRemove reply fallbacks from the specificationremoves client-side reply fallback; client behavior change
MSC2779⬛ ●closedClarify that event IDs are globally uniquespec clarification issue; closed; no server behavior change
MSC2775⬛ ◐closedLazy loading room membership over federation[→ MSC3706/MSC3902]
MSC2774⬛ ●mergedGiving widgets their ID so they can communicate[→ MSC4411] client widget URL template variable
MSC2762⬛ ●openAllowing widgets to send/receive eventsclient-side widget API; homeserver not involved
MSC2758⬛ ●mergedCommon grammar for textual identifiersmeta grammar guideline for future identifiers; not directly implementable
MSC2747⬛ ●openTransferring VoIP CallsClient-only m.call.replaces event semantics
MSC2746⬛ ●mergedImproved Signalling for 1:1 VoIPClient-side VoIP; HS relays m.call.* and serves unsigned.age on all read paths
MSC2723⬛ ●openForwarded message metadataClient-side m.forwarded content field only
MSC2713⬛ ●mergedRemove deprecated Identity Service endpointsIdentity Service endpoints; not a homeserver feature
MSC2644⬛ ●openmatrix.to URI syntax v2matrix.to URI syntax; client-only
MSC2630⬛ ◐mergedChecking public keys in SAS verificationClient SAS verification crypto; server transports key.verification events
MSC2618⬛ ●closedHelping others with mandatory implementation guidesSpec process MSC; no homeserver behavior
MSC2611⬛ ●mergedRemove m.login.token User-Interactive Authentication type from the specific…AuthType::Token UIAA not advertised; m.login.token login is unrelated
MSC2610⬛ ●mergedRemove m.login.oauth2 User-Interactive Authentication type from the specifi…AuthType::OAuth2 not advertised; only Password/Sso/Jwt flows
MSC2589⬛ ◐closedImprove repliesClient reply rendering; closed MSC; server ignores reply_body fields
MSC2582⬛ ◐mergedRemove mimetype from EncryptedFile objectRemoves mimetype example from spec; pure spec/client cleanup
MSC2557⬛ ◐mergedClarifications on spoilersClient-only spoiler rendering clarification
MSC2530⬛ ◐mergedBody field as media captionClient rendering of body+filename for media msgtypes
MSC2529⬛ ◐closedUse existing m.room.message/m.text events as captions for images[→ MSC2530] Client-only relation/caption rendering; superseded by MSC2530
MSC2516⬛ ◐closedAdd a new message type for voice messagesClient-only msgtype; server does no msgtype-specific handling
MSC2475⬛ ○closedAPI versioningSpec process meta-MSC about API version naming; closed
MSC2461⬛ ◐closedProposal for Authenticated Content Repository API[→ MSC3916]
MSC2427⬛ ◐openProposal for JSON-based message formattingClient-only message formatting alternative to HTML
MSC2425⬛ ●closedRemove Authentication on /submitToken Identity Service APIIdentity Server endpoint; not a homeserver concern
MSC2422⬛ ◐mergedAllow color as attribute for <font> in messagesClient HTML sanitizer change for <font color>
MSC2399⬛ ◐mergedReporting that decryption keys are withheldClient-only m.room_key.withheld to-device event
MSC2398⬛ ◐openproposal to allow mxc:// in the “a” tag within messagesClient HTML rendering policy for <a href=mxc:>
MSC2390⬛ ◐closedOn the EDU-to-PDU transition.Process MSC; closed; recommends no further EDU use
MSC2385⬛ ◐openDisable URL Previews, alternative methodClient-only url_previews array on m.room.message
MSC2376⬛ ◐closedDisable URL PreviewsClient-only HTML attribute hint; server has no role
MSC2366⬛ ◐mergedKey verification flow additions: m.key.verification.ready and `m.key.verifi…Client-side verification flow over to-device; server transports
MSC2359⬛ ◐closedE2E Encrypted SFU VoIP conferencing via Matrix[→ MSC3401] Architectural sketch for client+SFU; no homeserver requirements
MSC2354⬛ ◐openDevice to device streaming file transfersClient-only WebRTC signaling over event types; server transports opaquely
MSC2346⬛ ●openMSC 2346: Bridge information state eventBridge state schema and client presentation excluded; no homeserver clause.
MSC2320⬛ ●mergedVersions information for identity serversIdentity server endpoint, not homeserver
MSC2312⬛ ●mergedURI scheme for MatrixClient-side URI scheme; no homeserver endpoint required
MSC2299⬛ ●openProposal to add m.textfile msgtypeClient-only msgtype m.textfile
MSC2291⬛ ●openConfiguration to Control CrawlingBot-only advisory state event; no homeserver behavior
MSC2284⬛ ●mergedMaking the identity server optional during discoveryClient-side .well-known FAIL_PROMPT behavior
MSC2241⬛ ◐mergedKey verification in DMsClient-side verification flow over m.room.message; server passes events trans…
MSC2232⬛ ●closedExpose Homeserver Email Configuration in Registration Parametersproposal text is the empty MSC template
MSC2192⬛ ●openInline widgetsclient extensible event m.embed; no server logic
MSC2191⬛ ●mergedMarkup for mathematical messagesclient formatted_body rendering only
MSC2184⬛ ●mergedAllow the HTML <details> tag in messagesclient HTML rendering; no server impact
MSC2063⬛ ◐closedAdd “server information” public API proposalclosed; no real proposal text (template file only)
MSC2010⬛ ●mergedMSC 2010: Proposal to add client-side spoilersclient-side rendering of data-mx-spoiler in formatted_body
MSC1983⬛ ●mergedProposal to add reasons for leaving a roomsrc/api/client/membership/leave.rs:21 passes body.reason to leave
MSC1961⬛ ●mergedIntegration manager authenticationmerged; integration-manager auth API is on the manager, not homeserver
MSC1960⬛ ●mergedOpenID Connect information exchange for widgetsOpenID Connect exchange for widgets; the new flow is widget-to-client, server…
MSC1959⬛ ●openSticker picker APIbranch; sticker picker API on integration manager, not homeserver
MSC1956⬛ ●openIntegrations APIbranch; integrations API is integration-manager scope, not homeserver
MSC1951⬛ ◐closedCustom emoji and sticker packs in Matrixbranch; client/integration manager concept; uses generic rooms
MSC1920⬛ ◐closedAlternative texts for stickersbranch; client-side rendering field on m.sticker; no server logic
MSC1902⬛ ●closedSplitting the media repo into a client-side and server-side component[→ MSC3916]
MSC1849⬛ ◐closedProposal for aggregations via relations[→ MSC2674/MSC2675/MSC2676]
MSC1818⬛ ●closedRemove references to presence listspresence list endpoints absent (compliant by removal)
MSC1781⬛ ●openProposal for associations for DIDs and DID namesidentity-server endpoints for DID validation; not a homeserver concern
MSC1779⬛ ●mergedProposal for Open Governance of Matrix.orggovernance/foundation document; not a homeserver feature
MSC1769⬛ ●openProposal for extensible profiles as roomsbranch; profile-as-rooms not implemented
MSC1722⬛ ●closedSupport for displaying math(s) in messagesclient-side rendering of MathML in formatted_body; servers do not interpret
MSC1719⬛ ●mergedOlm unwedgingclient-only behavior (m.dummy, session re-creation rate-limit)
MSC1717⬛ ◐mergedKey verification mechanismsto_device transport carries m.key.verification.* events
MSC1716⬛ ●openOpen on device APIclient-only m.openondevice event type; nothing server-side to implement
MSC1704⬛ ●mergedmatrix.to permalink navigationserver-side requirement is via= on /join; src/api/client/membership/join.rs:79
MSC1703⬛ ●closedencrypting recovery keys for online megolm backupsamendment PR to MSC1687; closed without merge
MSC1700⬛ ◐closedImproving .well-known discovery of homeserverswell-known client+server discovery served from config
MSC1680⬛ ●closedcross-signing of devices to simplify key verificationempty Google-doc stub; cross-signing specified in MSC1756
MSC1544⬛ ●mergedKey verification using QR codesamendment PR to MSC1543; no separate proposal text
MSC1543⬛ ●mergedBi-directional Key verification using QR codesclient-only QR verification over send-to-device; server is opaque
MSC1318⬛ ●closedProposal for Open Governance of Matrix.org[→ MSC1779] governance proposal; not a homeserver feature
MSC1310⬛ ●closedProposal for a media information APIempty Google-doc stub; media info API never specified
MSC1301⬛ ◐closedProposal for improving authorization for the matrix profile APIlegacy 2018 issue (closed) tracked via redirect; profile-share-room limit not…
MSC1286⬛ ●openFormally spec an API for interacting with integration managerslegacy 2018 issue tracked via cross-repo redirect; integration manager API is…
MSC1267⬛ ●closedInteractive key verification using short authentication stringsstub Google doc; SAS verification specified later (MSC2241+); client-only fea…
MSC1229⬛ ◐openMitigating abuse of the event depth parameter over federationlegacy 2018 issue tracked via redirect; depth-abuse mitigations not implement…
MSC1225⬛ ●closedExtensible event types & fallback in Matrixempty Google-doc stub; extensible events specified later in MSC1767
MSC1215⬛ ●closedGroups as Rooms[→ MSC1772] empty Google-doc stub; groups feature dropped in favor of Spaces
MSC971⬛ ●closedAdd groups stuff to spec[→ MSC1772] groups stuff superseded by Spaces (MSC1772); proposal is doc link…
MSC701⬛ ◐openAuth/linking for content repo (and enforcing GDPR erasure)legacy 2016 issue tracked via redirect; auth/linking for content repo address…
MSC455⬛ ●closedDo we want to specify a matrix:// URI scheme for rooms? (SPEC-5)[→ MSC2312] stub Google doc; matrix:// URI scheme superseded by matrix: URI (…

Tuwunel Complement Test Results

Tuwunel runs the Complement Matrix homeserver acceptance suite. Raw results are committed to tests/complement/results.jsonl; full server and test logs remain local or CI-run artifacts.

Counts

  • Test groups: 224. Passing: 86.6%

    • ✅ pass: 194
    • 🟨 some: 9
    • 🟥 fail: 21
    • ⬛ skip: 0
  • Subtests: 627. Passing: 83.7%

    • ✅ pass: 525
    • 🟥 fail: 94
    • ⬛ skip: 8

All Top-Level Tests

StatusSubtestsTest
✅–ACLs
✅–ACLsForEDUs
✅2/0/0AddAccountData
🟨3/2/1ArchivedRoomsHistory
✅6/0/0AsyncUpload
✅–AvatarUrlUpdate
✅–BannedUserCannotSendJoin
✅–CanRegisterAdmin
✅–CannotKickLeftUser
✅–CannotKickNonPresentUser
✅6/0/0CannotSendKnockViaSendKnockInMSC3787Room
✅6/0/0CannotSendNonJoinViaSendJoinV2
✅6/0/0CannotSendNonKnockViaSendKnock
✅6/0/0CannotSendNonLeaveViaSendLeaveV2
✅5/0/0ChangePassword
✅2/0/0ChangePasswordPushers
🟨1/4/0ClientSpacesSummary
✅–ClientSpacesSummaryJoinRules
✅–ComplementCanCreateValidV12Rooms
✅–Content
✅–ContentCSAPIMediaV1
✅–ContentMediaV1
🟥–CorruptedAuthChain
✅–CumulativeJoinLeaveJoinSync
✅4/0/0DeactivateAccount
✅24/0/1DelayedEvents
✅1/0/0DeletingDeviceRemovesDeviceLocalNotificationSettings
✅–DemotingUsersViaUsersDefault
🟨8/2/0DeviceListUpdates
✅2/0/0DeviceListsUpdateOverFederation
🟥–DeviceListsUpdateOverFederationOnRoomJoin
✅7/0/0DeviceManagement
✅–DisplayNameUpdate
✅3/0/0E2EKeyBackupReplaceRoomKeyRules
✅3/0/0Event
✅2/0/0EventAuth
🟥–EventRelationships
✅–FederatedClientSpaces
🟥–FederatedEventRelationships
✅2/0/0FederationKeyUploadQuery
✅–FederationRedactSendsWithoutEvent
✅–FederationRejectInvite
✅10/0/0FederationRoomsInvite
✅2/0/0FederationSlidingSyncReInviteAfterLeave
✅–FederationThumbnail
✅–FetchEvent
✅–FetchEventNonWorldReadable
✅–FetchEventWorldReadable
✅–FetchHistoricalInvitedEventFromBeforeInvite
✅–FetchHistoricalInvitedEventFromBetweenInvite
✅–FetchHistoricalJoinedEventDenied
✅–FetchHistoricalSharedEvent
✅–FetchMessagesFromNonExistentRoom
✅–Filter
🟥–FilterMessagesByRelType
✅–ForwardExtremityPrune
✅–GapFillingAuthorizedStateEvent
✅–GapFillingDeepChain
✅–GapFillingDroppedStateEventDependents
✅–GapFillingForkResolution
✅2/0/0GapFillingManufacturedGapSoftFail
✅2/0/0GapFillingUnauthorizedStateEvent
✅–GappedSyncLeaveSection
✅3/0/0GetFilteredRoomMembers
✅–GetMissingEventsGapFilling
✅–GetRoomMembers
✅–GetRoomMembersAtPoint
✅4/0/0InboundCanReturnMissingEvents
✅–InboundFederationKeys
✅2/0/0InboundFederationProfile
🟥–InboundFederationRejectsEventsWithRejectedAuthEvents
✅11/0/0InviteFiltering
✅–InviteFromIgnoredUsersDoesNotAppearInSync
✅–IsDirectFlagFederation
✅–IsDirectFlagLocal
✅–JoinFederatedRoomFailOver
✅1/0/0JoinFederatedRoomFromApplicationServiceBridgeUser
✅4/0/0JoinFederatedRoomWithUnverifiableEvents
✅–JoinViaRoomIDAndServerName
✅3/0/0Json
✅7/0/0JumpToDateEndpoint
✅1/0/0KeyChangesLocal
✅–KeyClaimOrdering
✅–KeysQueryWithDeviceIDAsObjectFails
✅–KnockRestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV11
✅–KnockRestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV12
✅–KnockRoomsInPublicRoomsDirectory
✅–KnockRoomsInPublicRoomsDirectoryInMSC3787Room
✅25/0/0Knocking
✅25/0/0KnockingInMSC3787Room
✅–LeakyTyping
✅–LeaveEventInviteRejection
✅–LeaveEventVisibility
✅5/0/0LeftRoomFixture
✅2/0/0LocalPngThumbnail
✅8/0/0Login
✅4/0/0Logout
🟥–MSC3389RedactionPreservesPlainRelation
🟥–MSC3389RedactionPreservesRelation
✅–MSC3389RedactionStripsRelationInOlderVersions
🟥–MSC3757OwnedState
✅–MSC3967
🟥–MSC4242JoinLeaveRejoinPublicRoom
🟥–MSC4242JoinPublicRoomWithRejectedStateDAGEvents
🟥–MSC4242RejectionCascadesOnRejoin
🟥–MSC4242RejoinMergesOldAndNewStateDAGBranches
✅11/0/0MSC4289PrivilegedRoomCreators
✅–MSC4289PrivilegedRoomCreators_Additional
✅–MSC4289PrivilegedRoomCreators_AdditionalCreatorsAndInvited
✅5/0/0MSC4289PrivilegedRoomCreators_AdditionalValidation
✅–MSC4289PrivilegedRoomCreators_InvitedAreCreators
✅–MSC4289PrivilegedRoomCreators_Upgrades
✅–MSC4291RoomIDAsHashOfCreateEvent
✅–MSC4291RoomIDAsHashOfCreateEvent_AuthEventsOmitsCreateEvent
✅–MSC4291RoomIDAsHashOfCreateEvent_CannotSendCreateEvent
✅–MSC4291RoomIDAsHashOfCreateEvent_RoomIDIsOnCreateEvent
✅–MSC4291RoomIDAsHashOfCreateEvent_UpgradedRooms
✅–MSC4297StateResolutionV2_1_includes_conflicted_subgraph
✅–MSC4297StateResolutionV2_1_starts_from_empty_set
🟥0/2/0MSC4308ThreadSubscriptionsSlidingSync
✅3/0/0MSC4311FullEventsOnStrippedStateFederation
✅2/0/0MSC4311RejectInvalidStrippedStateFederation
✅5/0/0MSC4311StrippedStateClientAPI
🟥0/6/0MSC4429ProfileUpdates
✅–MediaConfig
✅25/0/0MediaFilenames
✅4/0/0MediaWithoutFileName
✅4/0/0MediaWithoutFileNameCSMediaV1
🟨3/2/0MembersLocal
🟥–MembershipOnEvents
🟨3/2/0MessagesOverFederation
✅–NetworkPartitionOrdering
✅–NotPresentUserCannotBanOthers
✅–OlderLeftRoomsNotInLeaveSection
🟥–OutboundFederationEventSizeGetMissingEvents
🟥–OutboundFederationIgnoresMissingEventWithBadJSONForRoomVersion6
✅1/0/0OutboundFederationProfile
✅–OutboundFederationSend
🟥0/59/6PartialStateJoin
✅1/0/0PollsLocalPushRules
✅3/0/0PowerLevels
✅5/0/0Presence
✅–PresenceSyncDifferentRooms
✅2/0/0ProfileAvatarURL
✅2/0/0ProfileDisplayName
✅9/0/0PublicRooms
✅–PushRuleCacheHealth
✅5/0/0PushRuleRoomUpgrade
✅5/0/0PushSync
✅1/0/0Redact
🟨22/2/0Registration
✅–Relations
✅–RelationsPagination
✅–RelationsPaginationSync
✅–RemoteAliasRequestsUnderstandUnicode
✅2/0/0RemotePngThumbnail
🟥0/2/0RemotePresence
✅–RemoteTyping
✅4/0/0RemovingAccountData
✅1/0/0RequestEncodingFails
✅5/0/0RestrictedRoomsLocalJoin
✅5/0/0RestrictedRoomsLocalJoinInMSC3787Room
✅–RestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV11
✅–RestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV12
✅5/0/0RestrictedRoomsRemoteJoin
✅5/0/0RestrictedRoomsRemoteJoinInMSC3787Room
✅–RestrictedRoomsRemoteJoinLocalUser
✅–RestrictedRoomsRemoteJoinLocalUserInMSC3787Room
✅–RestrictedRoomsSpacesSummaryFederation
✅–RestrictedRoomsSpacesSummaryLocal
✅5/0/0RoomAlias
✅10/0/0RoomCanonicalAlias
✅15/0/0RoomCreate
✅6/0/0RoomCreationReportsEventsToMyself
✅9/0/0RoomDeleteAlias
✅8/0/0RoomForget
✅–RoomImageRoundtrip
✅10/0/0RoomMembers
✅–RoomMessagesLazyLoading
✅–RoomMessagesLazyLoadingLocalUser
✅–RoomReadMarkers
✅1/0/0RoomReceipts
✅5/0/0RoomSpecificUsernameAtJoin
✅5/0/0RoomSpecificUsernameChange
✅15/0/0RoomState
✅–RoomSummary
✅2/0/0RoomSummaryAllowedRoomIDs
✅9/0/0RoomsInvite
✅7/0/0Search
✅–SendAndFetchMessage
✅–SendJoinPartialStateResponse
✅–SendMessageWithTxn
✅–ServerCapabilities
✅8/0/0ServerNotices
✅–SharedHistoryAfterLeaving
✅–StateDedupRequiresJoinedSender
🟨10/3/0Sync
✅2/0/0SyncFilter
✅3/0/0SyncLeaveSection
✅–SyncOmitsStateChangeOnFilteredEvents
✅2/0/0SyncTimelineGap
✅–TentativeEventualJoiningAfterRejecting
🟨1/7/0ThreadSubscriptions
🟥–ThreadedReceipts
✅–ThreadsEndpoint
✅–ToDeviceMessages
✅1/0/0ToDeviceMessagesOverFederation
✅–TxnIdWithRefreshToken
✅–TxnIdempotency
✅–TxnIdempotencyScopedToDevice
✅–TxnInEvent
✅–TxnScopeOnLocalEcho
✅3/0/0Typing
✅–UnbanViaInvite
🟨4/1/0UnknownEndpoints
✅–UnrejectRejectedEvents
✅8/0/0UploadKey
✅–UploadKeyIdempotency
✅–UploadKeyIdempotencyOverlap
✅–UrlPreview
✅–UserAppearsInChangedDeviceListOnJoinOverFederation
✅1/0/0VersionStructure
✅7/0/0WithoutOwnedState
✅–WriteMDirectAccountData

Tuwunel Complement Crypto Test Results

Tuwunel runs the Complement Crypto end-to-end encryption acceptance suite against Matrix Rust SDK clients. Raw results are committed to tests/complement-crypto/results.jsonl.

Counts

  • Test groups: 26. Passing: 80.8%

    • ✅ pass: 21
    • 🟨 some: 0
    • 🟥 fail: 0
    • ⬛ skip: 5
  • Subtests: 29. Passing: 82.8%

    • ✅ pass: 24
    • 🟥 fail: 0
    • ⬛ skip: 5

All Top-Level Tests

StatusSubtestsTest
✅1/0/0AliceBobEncryptionWorks
✅1/0/0BackupWrongRecoveryKeyFails
✅1/0/0BobCanSeeButNotDecryptHistoryInPublicRoom
✅1/0/0CanBackupKeys
✅1/0/0CanDecryptMessagesAfterInviteButBeforeJoin
✅1/0/0ClientRetriesSendToDevice
✅1/0/0ExistingSessionCannotGetKeysForOfflineServer
✅1/0/0FailedDeviceKeyDownloadRetries
✅1/0/0FailedKeysClaimRetries
✅1/0/0FailedOneTimeKeyUploadRetries
✅1/0/0FallbackKeyIsUsedIfOneTimeKeysRunOut
✅1/0/0NewUserCannotGetKeysForOfflineServer
✅1/0/0OnNewDeviceBobCanSeeButNotDecryptHistoryInPublicRoom
✅1/0/0RoomKeyIsCycledAfterEnoughMessages
✅1/0/0RoomKeyIsCycledAfterEnoughTime
✅1/0/0RoomKeyIsCycledOnDeviceLogout
✅1/0/0RoomKeyIsCycledOnMemberLeaving
✅3/0/0RoomKeyIsNotCycled
⬛0/0/1RoomKeyIsNotCycledOnClientRestart
⬛0/0/1SigkillBeforeKeysUploadResponse
✅2/0/0SpoofedEventSenderHandling
✅1/0/0ToDeviceMessagesAreBatched
⬛0/0/1ToDeviceMessagesAreProcessedInOrder
✅1/0/0ToDeviceMessagesArentLostWhenKeysQueryFails
⬛0/0/1UnprocessedToDeviceMessagesArentLostOnRestart
⬛0/0/1VerificationSAS

Tuwunel Complement Interoperability Test Results

Tuwunel runs Complement with Tuwunel and Synapse assigned to opposite homeserver positions. In the first direction Tuwunel is hs1 and Synapse is hs2; the inverse direction swaps those positions.

These report-only results are a snapshot from August 9, 2026 CI run.

Counts

Tuwunel as hs1

  • Test groups: 205. Passing: 81.5%

    • ✅ pass: 167
    • 🟨 some: 19
    • 🟥 fail: 17
    • ⬛ skip: 2
  • Subtests: 587. Passing: 77.2%

    • ✅ pass: 453
    • 🟥 fail: 121
    • ⬛ skip: 13

Synapse as hs1

  • Test groups: 205. Passing: 92.7%

    • ✅ pass: 190
    • 🟨 some: 9
    • 🟥 fail: 6
    • ⬛ skip: 0
  • Subtests: 612. Passing: 94.6%

    • ✅ pass: 579
    • 🟥 fail: 25
    • ⬛ skip: 8

All Top-Level Tests

Tuwunel as hs1SubtestsSynapse as hs1SubtestsTest
✅–✅–ACLs
✅–✅–ACLsForEDUs
✅2/0/0✅2/0/0AddAccountData
🟨3/2/1✅5/0/1ArchivedRoomsHistory
✅6/0/0✅6/0/0AsyncUpload
✅–✅–AvatarUrlUpdate
✅–✅–BannedUserCannotSendJoin
⬛–✅–CanRegisterAdmin
✅–✅–CannotKickLeftUser
✅–✅–CannotKickNonPresentUser
✅6/0/0✅6/0/0CannotSendKnockViaSendKnockInMSC3787Room
✅6/0/0✅6/0/0CannotSendNonJoinViaSendJoinV2
✅6/0/0✅6/0/0CannotSendNonKnockViaSendKnock
✅6/0/0✅6/0/0CannotSendNonLeaveViaSendLeaveV2
✅5/0/0✅5/0/0ChangePassword
✅2/0/0✅2/0/0ChangePasswordPushers
🟨1/4/0✅5/0/0ClientSpacesSummary
✅–✅–ClientSpacesSummaryJoinRules
✅–✅–ComplementCanCreateValidV12Rooms
✅–🟥–Content
✅–✅–ContentCSAPIMediaV1
✅–✅–ContentMediaV1
🟥–✅–CorruptedAuthChain
✅–✅–CumulativeJoinLeaveJoinSync
✅4/0/0✅4/0/0DeactivateAccount
🟨6/7/1✅17/0/1DelayedEvents
✅1/0/0✅1/0/0DeletingDeviceRemovesDeviceLocalNotificationSettings
✅–✅–DemotingUsersViaUsersDefault
🟨8/2/0🟨9/1/0DeviceListUpdates
✅2/0/0✅2/0/0DeviceListsUpdateOverFederation
🟥–🟥–DeviceListsUpdateOverFederationOnRoomJoin
✅7/0/0✅7/0/0DeviceManagement
✅–✅–DisplayNameUpdate
✅3/0/0✅3/0/0E2EKeyBackupReplaceRoomKeyRules
✅3/0/0✅3/0/0Event
✅2/0/0✅2/0/0EventAuth
🟥–🟥–EventRelationships
✅–✅–FederatedClientSpaces
🟥–🟥–FederatedEventRelationships
🟨1/1/0✅2/0/0FederationKeyUploadQuery
✅–✅–FederationRedactSendsWithoutEvent
✅–✅–FederationRejectInvite
✅10/0/0✅10/0/0FederationRoomsInvite
✅2/0/0✅2/0/0FederationSlidingSyncReInviteAfterLeave
✅–✅–FederationThumbnail
✅–✅–FetchEvent
✅–✅–FetchEventNonWorldReadable
✅–✅–FetchEventWorldReadable
✅–✅–FetchHistoricalInvitedEventFromBeforeInvite
✅–✅–FetchHistoricalInvitedEventFromBetweenInvite
✅–✅–FetchHistoricalJoinedEventDenied
✅–✅–FetchHistoricalSharedEvent
✅–✅–FetchMessagesFromNonExistentRoom
✅–✅–Filter
🟥–✅–FilterMessagesByRelType
✅–✅–GappedSyncLeaveSection
✅3/0/0✅3/0/0GetFilteredRoomMembers
✅–✅–GetMissingEventsGapFilling
✅–✅–GetRoomMembers
🟥–✅–GetRoomMembersAtPoint
🟥0/4/0✅4/0/0InboundCanReturnMissingEvents
✅–✅–InboundFederationKeys
✅2/0/0✅2/0/0InboundFederationProfile
🟥–✅3/0/0InboundFederationRejectsEventsWithRejectedAuthEvents
🟨3/8/0✅11/0/0InviteFiltering
✅–✅–InviteFromIgnoredUsersDoesNotAppearInSync
✅–✅–IsDirectFlagFederation
✅–✅–IsDirectFlagLocal
✅–✅–JoinFederatedRoomFailOver
✅1/0/0✅1/0/0JoinFederatedRoomFromApplicationServiceBridgeUser
✅4/0/0✅4/0/0JoinFederatedRoomWithUnverifiableEvents
✅–✅–JoinViaRoomIDAndServerName
✅3/0/0✅3/0/0Json
✅7/0/0✅7/0/0JumpToDateEndpoint
✅1/0/0✅1/0/0KeyChangesLocal
✅–✅–KeyClaimOrdering
✅–✅–KeysQueryWithDeviceIDAsObjectFails
✅–✅–KnockRestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV11
✅–✅–KnockRestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV12
✅–✅–KnockRoomsInPublicRoomsDirectory
✅–✅–KnockRoomsInPublicRoomsDirectoryInMSC3787Room
✅25/0/0✅25/0/0Knocking
✅25/0/0✅25/0/0KnockingInMSC3787Room
✅–✅–LeakyTyping
✅–✅–LeaveEventInviteRejection
🟥–✅–LeaveEventVisibility
🟨2/3/0✅5/0/0LeftRoomFixture
✅2/0/0🟨1/1/0LocalPngThumbnail
✅8/0/0✅8/0/0Login
✅4/0/0✅4/0/0Logout
🟥–✅11/0/0MSC3757OwnedState
✅–✅–MSC3967
✅11/0/0✅11/0/0MSC4289PrivilegedRoomCreators
✅–✅–MSC4289PrivilegedRoomCreators_Additional
✅–✅–MSC4289PrivilegedRoomCreators_AdditionalCreatorsAndInvited
✅5/0/0✅5/0/0MSC4289PrivilegedRoomCreators_AdditionalValidation
✅–✅–MSC4289PrivilegedRoomCreators_InvitedAreCreators
✅–✅–MSC4289PrivilegedRoomCreators_Upgrades
✅–✅–MSC4291RoomIDAsHashOfCreateEvent
✅–✅–MSC4291RoomIDAsHashOfCreateEvent_AuthEventsOmitsCreateEvent
✅–✅–MSC4291RoomIDAsHashOfCreateEvent_CannotSendCreateEvent
✅–✅–MSC4291RoomIDAsHashOfCreateEvent_RoomIDIsOnCreateEvent
✅–✅–MSC4291RoomIDAsHashOfCreateEvent_UpgradedRooms
✅–✅–MSC4297StateResolutionV2_1_includes_conflicted_subgraph
✅–✅–MSC4297StateResolutionV2_1_starts_from_empty_set
🟥0/2/0✅2/0/0MSC4308ThreadSubscriptionsSlidingSync
✅–✅–MSC4311FullCreateEventOnStrippedState
✅–✅–MediaConfig
🟨19/6/0🟨12/13/0MediaFilenames
✅4/0/0🟨1/3/0MediaWithoutFileName
✅4/0/0✅4/0/0MediaWithoutFileNameCSMediaV1
🟨3/2/0✅5/0/0MembersLocal
🟥–✅–MembershipOnEvents
✅5/0/0🟨3/2/0MessagesOverFederation
✅–✅–NetworkPartitionOrdering
✅–✅–NotPresentUserCannotBanOthers
✅–✅–OlderLeftRoomsNotInLeaveSection
🟥–✅–OutboundFederationEventSizeGetMissingEvents
🟥–✅–OutboundFederationIgnoresMissingEventWithBadJSONForRoomVersion6
✅1/0/0✅1/0/0OutboundFederationProfile
✅–✅–OutboundFederationSend
🟨1/57/7🟨58/1/6PartialStateJoin
✅1/0/0✅1/0/0PollsLocalPushRules
✅3/0/0✅3/0/0PowerLevels
🟨4/1/0✅5/0/0Presence
✅–✅–PresenceSyncDifferentRooms
✅2/0/0✅2/0/0ProfileAvatarURL
✅2/0/0✅2/0/0ProfileDisplayName
✅9/0/0✅9/0/0PublicRooms
✅–✅–PushRuleCacheHealth
🟨3/2/0🟨3/2/0PushRuleRoomUpgrade
✅5/0/0✅5/0/0PushSync
✅1/0/0✅1/0/0Redact
✅19/0/4✅23/0/0Registration
✅–✅–Relations
✅–✅–RelationsPagination
✅–✅–RelationsPaginationSync
✅–✅–RemoteAliasRequestsUnderstandUnicode
🟨1/1/0🟨1/1/0RemotePngThumbnail
🟥0/2/0🟨1/1/0RemotePresence
✅–✅–RemoteTyping
✅4/0/0✅4/0/0RemovingAccountData
✅1/0/0✅1/0/0RequestEncodingFails
✅5/0/0✅5/0/0RestrictedRoomsLocalJoin
✅5/0/0✅5/0/0RestrictedRoomsLocalJoinInMSC3787Room
✅–✅–RestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV11
✅–✅–RestrictedRoomsLocalJoinNoCreatorsUsesPowerLevelsV12
✅5/0/0✅5/0/0RestrictedRoomsRemoteJoin
✅5/0/0✅5/0/0RestrictedRoomsRemoteJoinInMSC3787Room
✅–✅–RestrictedRoomsRemoteJoinLocalUser
✅–✅–RestrictedRoomsRemoteJoinLocalUserInMSC3787Room
✅–✅–RestrictedRoomsSpacesSummaryFederation
✅–✅–RestrictedRoomsSpacesSummaryLocal
✅5/0/0✅5/0/0RoomAlias
✅10/0/0✅10/0/0RoomCanonicalAlias
✅15/0/0✅15/0/0RoomCreate
🟨4/2/0✅6/0/0RoomCreationReportsEventsToMyself
🟨7/2/0✅9/0/0RoomDeleteAlias
🟨6/2/0✅8/0/0RoomForget
✅–✅–RoomImageRoundtrip
✅10/0/0✅10/0/0RoomMembers
✅–✅–RoomMessagesLazyLoading
✅–✅–RoomMessagesLazyLoadingLocalUser
✅–✅–RoomReadMarkers
✅1/0/0✅1/0/0RoomReceipts
✅5/0/0✅5/0/0RoomSpecificUsernameAtJoin
✅5/0/0✅5/0/0RoomSpecificUsernameChange
✅15/0/0✅15/0/0RoomState
✅–🟥–RoomSummary
✅2/0/0✅2/0/0RoomSummaryAllowedRoomIDs
✅9/0/0✅9/0/0RoomsInvite
✅7/0/0✅7/0/0Search
✅–✅–SendAndFetchMessage
✅–🟥–SendJoinPartialStateResponse
✅–✅–SendMessageWithTxn
✅–✅–ServerCapabilities
⬛–✅8/0/0ServerNotices
🟨10/3/0✅12/0/0Sync
✅2/0/0✅2/0/0SyncFilter
✅3/0/0✅3/0/0SyncLeaveSection
✅–✅–SyncOmitsStateChangeOnFilteredEvents
✅2/0/0✅2/0/0SyncTimelineGap
✅–✅–TentativeEventualJoiningAfterRejecting
🟨1/7/0✅8/0/0ThreadSubscriptions
🟥–✅–ThreadedReceipts
✅–✅–ThreadsEndpoint
✅–✅–ToDeviceMessages
✅1/0/0✅1/0/0ToDeviceMessagesOverFederation
✅–✅–TxnIdWithRefreshToken
🟥–✅–TxnIdempotency
✅–✅–TxnIdempotencyScopedToDevice
✅–✅–TxnInEvent
✅–✅–TxnScopeOnLocalEcho
✅3/0/0✅3/0/0Typing
✅–✅–UnbanViaInvite
🟨4/1/0✅5/0/0UnknownEndpoints
✅–✅–UnrejectRejectedEvents
✅8/0/0✅8/0/0UploadKey
✅–✅–UploadKeyIdempotency
✅–✅–UploadKeyIdempotencyOverlap
✅–✅–UrlPreview
✅–✅–UserAppearsInChangedDeviceListOnJoinOverFederation
✅1/0/0✅1/0/0VersionStructure
✅7/0/0✅7/0/0WithoutOwnedState
✅–✅–WriteMDirectAccountData

Tuwunel Complemau Test Results

Tuwunel runs Complemau, its Complement-based application service acceptance suite. Raw results are committed to tests/complement/complemau/results.jsonl.

Counts

  • Test groups: 34. Passing: 85.3%

    • ✅ pass: 29
    • 🟨 some: 0
    • 🟥 fail: 5
    • ⬛ skip: 0
  • Subtests: 63. Passing: 96.8%

    • ✅ pass: 61
    • 🟥 fail: 2
    • ⬛ skip: 0

All Top-Level Tests

StatusSubtestsTest
✅6/0/0ComplemauAppservicePDUInterest
✅–ComplemauAppservicePDUInterestRemoteSender
✅–ComplemauAppserviceReceivesOTKCountsAndFallbackKeys
🟥–ComplemauAppserviceReceivesPresence
✅–ComplemauAppserviceReceivesReceiptOnce
✅–ComplemauAppserviceReceivesToDevice
✅–ComplemauAppserviceReceivesTyping
✅15/0/0ComplemauAppserviceRegistrationLoginAndMSC4190Devices
✅–ComplemauAppserviceRoomAliasQuery
✅–ComplemauAppserviceScopesTypingByInterest
🟥–ComplemauAppserviceServesDeviceKeys
🟥–ComplemauAppserviceServesDeviceKeysOverFederation
🟥–ComplemauAppserviceServesOneTimeKeys
✅3/0/0ComplemauAppserviceThirdPartyEdges
✅2/0/0ComplemauAppserviceThirdPartyLookups
✅2/0/0ComplemauAppserviceThirdPartyProtocols
🟥0/2/0ComplemauAppserviceUserQueries
✅–ComplemauDeviceListsRegistrationGateAndDeviceChanges
✅–ComplemauDeviceListsRemoteRoomSharer
✅4/0/0ComplemauDirectoryExcludesAppserviceUsers
✅5/0/0ComplemauExclusiveNamespaces
✅13/0/0ComplemauMasqueradeAuthentication
✅5/0/0ComplemauMasqueradeDoesNotInferPresence
✅4/0/0ComplemauPingErrorSurfacing
✅–ComplemauPingForcesTransactionRetry
✅2/0/0ComplemauPingRoundTripAndAuthorization
✅–ComplemauReceiptBatchingHasNoLoss
✅–ComplemauToDeviceBurstExcludesUninterestedAppservice
✅–ComplemauToDeviceManyRecipients
✅–ComplemauTransactionBatchCapAndOrdering
✅–ComplemauTransactionDedupAndUniquifier
✅–ComplemauTransactionQueuesAreIndependent
✅–ComplemauTransactionRetryPreservesIDAndContent
✅–ComplemauTransactionSingleInflightAndBatching

Synapse Admin API

Tuwunel serves the Synapse administration API under the /_synapse/admin path so that existing Matrix server administration tools work against it, including administration dashboards such as synapse-admin and ketesa and moderation bots such as Draupnir and Meowlnir.

This page lists every /_synapse/admin endpoint Tuwunel is aware of and whether it is served. Endpoints that are not served return 404 M_UNRECOGNIZED. All endpoints require an administrator access token unless the description says otherwise.

Status

  • ✅ supported: implemented and served today.
  • 🟨 planned: on the current implementation roadmap; not yet served.
  • 🟥 not-implemented: a supportable endpoint that Tuwunel does not serve yet, deferred pending new storage or a subsystem and not on the current roadmap.
  • ⬛ not-applicable: does not apply to Tuwunel’s storage engine or data model, or is intentionally omitted.

Counts

  • Endpoints (method and path): 100
    • ✅ supported: 69
    • 🟨 planned: 1
    • 🟥 not-implemented: 22
    • ⬛ not-applicable: 8

By domain

Domain✅🟨🟥⬛total
Users2018130
Devices and registration tokens1201619
Rooms2000020
Media and statistics8010119
Federation and miscellaneous903012
total691228100

Users

StatusMethodURLDescription
✅GET/_synapse/admin/v1/registerFetch a one-time nonce for shared-secret registration. Unauthenticated; not served when MAS is active.
✅POST/_synapse/admin/v1/registerRegister a user with shared-secret HMAC authentication. Not served when MAS is active.
✅GET/_synapse/admin/v2/usersList and search local users with filtering and pagination.
✅GET/_synapse/admin/v3/usersList users with a tri-state deactivated filter (version 3 of the user list).
✅GET/_synapse/admin/v2/users/{user_id}Return a single user’s account details.
✅PUT/_synapse/admin/v2/users/{user_id}Create or modify a user account, including admin status, deactivation, profile, and third-party ids.
✅POST/_synapse/admin/v1/deactivate/{user_id}Deactivate a user, optionally erasing their data.
✅POST/_synapse/admin/v1/reset_password/{user_id}Reset a user’s password. Not served when MAS is active.
✅GET/_synapse/admin/v1/users/{user_id}/adminReport whether a user is a server administrator. Not served when MAS is active.
🟨PUT/_synapse/admin/v1/users/{user_id}/adminGrant or revoke a user’s server-administrator status.
✅GET/_synapse/admin/v1/users/{user_id}/joined_roomsList the rooms a user is joined to.
✅GET/_synapse/admin/v1/users/{user_id}/membershipsReturn the user’s room memberships as a room-to-state map.
✅GET/_synapse/admin/v1/users/{user_id}/pushersList a user’s configured pushers.
✅GET/_synapse/admin/v1/users/{user_id}/accountdataReturn a user’s global and per-room account data.
✅GET/_synapse/admin/v1/whois/{user_id}Return connection and device information for a user. Also served on the client-server admin path.
✅PUT/_synapse/admin/v1/suspend/{user_id}Suspend or release a user account (MSC4323).
✅POST/_synapse/admin/v1/users/{user_id}/loginMint an access token to act as a user (impersonation). Not served when MAS is active.
🟥POST, DELETE/_synapse/admin/v1/users/{user_id}/shadow_banNot implemented; requires new per-user storage (deferred).
🟥GET, POST, DELETE/_synapse/admin/v1/users/{user_id}/override_ratelimitNot implemented; Tuwunel has no per-user request limiter to override (deferred).
✅POST/_synapse/admin/v1/user/{user_id}/redactRedact a user’s events across their rooms as a background task.
✅GET/_synapse/admin/v1/user/redact_status/{redact_id}Poll the status of a user-redaction task.
🟥GET/_synapse/admin/v1/users/{user_id}/sent_invite_countNot implemented; no timestamp-indexed invite log to count from (deferred).
🟥GET/_synapse/admin/v1/users/{user_id}/cumulative_joined_room_countNot implemented; no timestamp-indexed membership log (deferred).
✅POST/_synapse/admin/v1/users/{user_id}/_allow_cross_signing_replacement_without_uiaAllow cross-signing key replacement without interactive auth for a bounded window.
✅GET/_synapse/admin/v1/threepid/{medium}/users/{address}Look up the local user bound to a third-party identifier (email).
🟥GET/_synapse/admin/v1/auth_providers/{provider}/users/{external_id}Not implemented; requires an external-identifier index (deferred).
⬛GET/_synapse/admin/v1/search_users/{term}Intentionally omitted; undocumented and exposes password hashes.

Devices and registration tokens

StatusMethodURLDescription
✅GET/_synapse/admin/v2/users/{user_id}/devicesList a user’s devices.
✅POST/_synapse/admin/v2/users/{user_id}/devicesCreate a device for a user.
✅GET, PUT, DELETE/_synapse/admin/v2/users/{user_id}/devices/{device_id}Fetch, rename, or delete a specific device.
✅POST/_synapse/admin/v2/users/{user_id}/delete_devicesBulk-delete a set of a user’s devices.
✅GET/_synapse/admin/v1/registration_tokensList registration tokens. Not served when MAS is active.
✅POST/_synapse/admin/v1/registration_tokens/newCreate a registration token. Not served when MAS is active.
✅GET/_synapse/admin/v1/registration_tokens/{token}Return a registration token. Not served when MAS is active.
✅PUT/_synapse/admin/v1/registration_tokens/{token}Update a registration token’s usage cap or expiry. Not served when MAS is active.
✅DELETE/_synapse/admin/v1/registration_tokens/{token}Delete a registration token. Not served when MAS is active.
✅GET/_synapse/admin/v1/username_availableCheck whether a username is available for registration.
🟥POST/_synapse/admin/v1/account_validity/validityNot implemented; requires an account-expiry subsystem (deferred).
⬛GET, PUT/_synapse/admin/v1/experimental_features/{user_id}Not applicable; Tuwunel feature flags are server-wide, not per user.
⬛GET, POST/_synapse/admin/v1/background_updates/enabledNot applicable; RocksDB has no background-update mechanism.
⬛GET/_synapse/admin/v1/background_updates/statusNot applicable; RocksDB has no background-update mechanism.
⬛POST/_synapse/admin/v1/background_updates/start_jobNot applicable; RocksDB has no background-update mechanism.

Rooms

StatusMethodURLDescription
✅GET/_synapse/admin/v1/roomsList and search rooms.
✅GET/_synapse/admin/v1/rooms/{room_id}Return a single room’s details.
✅DELETE/_synapse/admin/v1/rooms/{room_id}Synchronously delete a room and evict its local members.
✅GET/_synapse/admin/v1/rooms/{room_id}/membersList a room’s joined members.
✅GET/_synapse/admin/v1/rooms/{room_id}/stateReturn a room’s full state with an administrator visibility bypass.
✅GET/_synapse/admin/v1/rooms/{room_id}/messagesPage a room’s timeline with an administrator visibility bypass.
✅GET/_synapse/admin/v1/rooms/{room_id}/context/{event_id}Return the events surrounding an event with an administrator visibility bypass.
✅GET/_synapse/admin/v1/rooms/{room_id}/timestamp_to_eventFind the event nearest a timestamp.
✅GET/_synapse/admin/v1/rooms/{room_id}/hierarchyReturn a room’s space hierarchy (local rooms only).
✅GET, PUT/_synapse/admin/v1/rooms/{room_id}/blockRead or set a room’s blocked status.
✅POST/_synapse/admin/v1/rooms/{room_id}/make_room_adminGrant room-administrator power to a user.
✅GET, DELETE/_synapse/admin/v1/rooms/{room_id}/forward_extremitiesInspect or reduce a room’s forward extremities.
✅DELETE/_synapse/admin/v2/rooms/{room_id}Delete a room asynchronously as a background task.
✅GET/_synapse/admin/v2/rooms/delete_status/{delete_id}Poll a room-deletion task by delete id.
✅GET/_synapse/admin/v2/rooms/{room_id}/delete_statusList room-deletion tasks for a room.
✅POST/_synapse/admin/v1/join/{room_id_or_alias}Join a local user to a room as an administrator.
✅POST/_synapse/admin/v1/purge_history/{room_id}Purge a room’s history up to a point in time or an event. An optional trailing event id selects the boundary.
✅GET/_synapse/admin/v1/purge_history_status/{purge_id}Poll a history-purge task.

Media and statistics

StatusMethodURLDescription
✅GET/_synapse/admin/v1/media/{server_name}/{media_id}Return metadata for a media item, including quarantine fields.
✅DELETE/_synapse/admin/v1/media/{server_name}/{media_id}Delete a local media item.
✅POST/_synapse/admin/v1/media/deleteDelete media by age and size. A legacy per-server alias path is also served.
✅POST/_synapse/admin/v1/purge_media_cachePurge cached remote media older than a timestamp.
✅GET/_synapse/admin/v1/users/{user_id}/mediaList media uploaded by a user.
✅DELETE/_synapse/admin/v1/users/{user_id}/mediaDelete media uploaded by a user, one page per call.
✅GET/_synapse/admin/v1/room/{room_id}/mediaList media referenced by a room’s unencrypted events.
🟥POST/_synapse/admin/v1/media/quarantine/{server_name}/{media_id}Not implemented; requires a media quarantine subsystem. The paired unquarantine path is also unserved (deferred).
🟥POST/_synapse/admin/v1/user/{user_id}/media/quarantineNot implemented; requires a media quarantine subsystem (deferred).
🟥POST/_synapse/admin/v1/room/{room_id}/media/quarantineNot implemented; requires a media quarantine subsystem (deferred).
🟥GET/_synapse/admin/v1/media/quarantine_changesNot implemented; requires a media quarantine subsystem (deferred).
🟥POST/_synapse/admin/v1/media/protect/{media_id}Not implemented; requires quarantine-protection storage. The paired unprotect path is also unserved (deferred).
✅GET/_synapse/admin/v1/statistics/users/mediaAggregate per-user media counts and total sizes.
⬛GET/_synapse/admin/v1/statistics/database/roomsNot applicable; a PostgreSQL-only size estimate even in Synapse.
🟥GET/_synapse/admin/v1/event_reportsNot implemented; requires an event-reports store (deferred).
🟥GET, DELETE/_synapse/admin/v1/event_reports/{report_id}Not implemented; requires an event-reports store (deferred).

Federation and miscellaneous

StatusMethodURLDescription
✅GET/_synapse/admin/v1/server_versionReturn the server name and version. Unauthenticated.
✅GET/_synapse/admin/v1/federation/destinationsList federation destinations and their retry state.
✅GET/_synapse/admin/v1/federation/destinations/{destination}Return one destination’s retry state.
✅GET/_synapse/admin/v1/federation/destinations/{destination}/roomsList the rooms shared with a destination.
✅POST/_synapse/admin/v1/federation/destinations/{destination}/reset_connectionClear a destination’s backoff so delivery retries immediately.
✅POST, PUT/_synapse/admin/v1/send_server_noticeSend a server notice to a user. The idempotent form with a transaction id is also served.
✅GET/_synapse/admin/v1/scheduled_tasksList background administrative tasks.
✅GET/_synapse/admin/v1/fetch_event/{event_id}Return a raw event by id, without redaction.
🟥GET/_synapse/admin/v1/user_reportsNot implemented; requires a reports store (deferred).
🟥GET, DELETE/_synapse/admin/v1/user_reports/{report_id}Not implemented; requires a reports store (deferred).

Build Features

The public Cargo feature surface is defined in src/main/Cargo.toml.

Cargo features

FeatureDefaultDescription
brotli_compression✔️Brotli HTTP response compression and outbound response decompression. Enable http.compression.brotli = true; the client must accept Brotli; network.http.brotli controls outbound negotiation.
bzip2_compression✔️Bzip2 compression for RocksDB. Select rocksdb.compression_algo = "bz2".
console✔️Interactive administration console on the terminal. Start with --console; an interactive terminal is needed.
cpu_affinity✔️Pin Tokio worker threads and database pool workers to CPU cores. A build without it leaves thread placement to the operating system, ignores database.pool.affinity, sizes the database pool from database.pool.workers instead of detected storage queues, and counts CPUs with the Rust standard library, which also applies cgroup CPU quotas. OpenBSD counts CPUs with num_cpus either way.
direct_tls✔️Serve HTTPS directly from Tuwunel. Configure the certificate and key in [global.tls].
element_hacks✔️Workarounds for Element: password authentication accepts the deprecated user field, and lazy-loaded syncs always include redundant members. These compatibility workarounds apply without additional runtime configuration.
email✔️Send email through an SMTP relay: verification mail for adding an address, registering and resetting a password, and notification mail for email pushers. Required when smtp.connection_uri is set; a build without it refuses to start then, so it cannot require email at registration. Otherwise such a build answers as a server without SMTP: requests to verify or add an email address are refused, the m.3pid_changes capability reads disabled, new email pushers are refused, and existing ones send nothing. Addresses bound by an identity provider, MAS provisioning, admin commands or the Synapse admin API stay bound and listed.
gcs_storage✔️Store media on Google Cloud Storage through [global.storage_provider.<ID>.gcs] providers. Supports presigned download redirects (media.allow_redirect). Required when such a section sets bucket; a build without it refuses to start then.
gzip_compression✔️Gzip HTTP response compression and outbound response decompression. Enable http.compression.gzip = true; the client must accept Gzip; network.http.gzip controls outbound negotiation.
io_uring✔️RocksDB I/O through io_uring. Requires Linux with kernel support for io_uring; liburing is needed when dynamically linked.
jemalloc✔️Use jemalloc for Tuwunel allocations. MSVC uses the system allocator; dynamically linked jemalloc builds need the allocator library.
jemalloc_conf✔️Apply Tuwunel’s built-in jemalloc tuning. The jemalloc feature must also be enabled; this feature configures the allocator but does not select it.
jemalloc_prof×Compile jemalloc heap profiling support. Enable jemalloc and profiling through the allocator’s runtime configuration; a substituted allocator must support profiling.
jemalloc_stats×Compile jemalloc allocation statistics support. Enable jemalloc; a substituted allocator must support statistics.
jwt_login✔️Authenticate with a JSON Web Token through login (org.matrix.login.jwt) or user-interactive authentication. Configure authentication in [global.jwt]. Also provides the debug create-jwt admin command. Required when jwt.enable is true. A build without this feature rejects that configuration at startup and on reload. Otherwise it behaves as a server with jwt.enable = false and has no debug create-jwt command. ID tokens issued by the native OIDC server are unaffected.
ldap✔️Authenticate users against LDAP. Enable and configure [global.ldap]; an LDAP server is needed.
lz4_compression✔️LZ4 compression for RocksDB. Select rocksdb.compression_algo = "lz4" or "lz4hc".
markdown✔️Render Markdown to HTML in the server’s administrative messages: admin command output, admin room notices and the welcome message, and room and user reports. A build without it sends their Markdown source as plain text.
mas✔️Matrix Authentication Service provisioning API. Required when authentication.mas_secret is set; a build without it refuses to start with a nonempty secret.
media_thumbnail✔️Generate media thumbnails. Video extraction also needs media.video_thumbnail.command and its external program.
oidc✔️Native OIDC server API. Required when well_known.client is set together with authentication.oidc.native_auth or any identity_provider; a build without it refuses to start then. Legacy SSO alone does not need this feature, but SSO with well_known.client set does.
perf_measurements×Export tracing spans and write flamegraph data. Enable telemetry.jaeger.enable with an OTLP collector, or tracing.flame.enable with a writable tracing.flame.output_path.
release_max_log_level✔️Omit debug and trace logging from release builds. Remove this feature to use those log levels in a release build; runtime log filters cannot restore messages omitted at compile time.
s3_storage✔️Store media on Amazon S3 and S3-compatible services through [global.storage_provider.<ID>.s3] providers. Supports presigned download redirects (media.allow_redirect). Required when such a section sets url or bucket; a build without it refuses to start then.
sentry_telemetry✔️Sentry error reporting and tracing integration. Enable telemetry.sentry.enable and configure telemetry.sentry.endpoint.
synapse_admin✔️Synapse admin API, client account suspend and lock endpoints, and the client whois alias. Most endpoints require an administrator token; shared-secret registration requires registration.shared_secret.
systemd✔️Systemd readiness, watchdog, socket activation, and configuration reload notifications. Requires Linux and systemd.
tokio_console×Tokio task instrumentation for tokio-console. Build with --cfg tokio_unstable, enable tracing.tokio_console and logging.global_default, and omit release_max_log_level for release builds.
tuwunel_mods×Hot reloadable development modules. Build with --cfg tuwunel_mods and provide loadable modules; see Hot Reloading.
url_preview✔️Fetch URL previews for clients. Configure media.url_preview.domain_contains_allowlist or media.url_preview.domain_explicit_allowlist for permitted domains.
zstd_compression✔️Zstd HTTP compression/decompression and RocksDB compression. HTTP uses http.compression.zstd = true and client negotiation; network.http.zstd controls outbound negotiation; RocksDB uses rocksdb.compression_algo.

Local filesystem providers, including the default media provider, and the query storage admin commands work independently of gcs_storage and s3_storage.

Journal logging works independently of the systemd feature. It requires logging.journald and the presence of both SYSTEMD_EXEC_PID and JOURNAL_STREAM in the environment.

Important

Some features reject enabling configuration when absent from the build; see the individual descriptions above.

Note

  • The oidc, mas, and synapse_admin features can each be left out independently.

Feature projection and dependency implications

The main crate defines every public feature and forwards it to the workspace crates that apply it. The crate column lists those crates, whether they use the feature in conditional code or to enable a dependency feature. The last column lists direct optional dependencies enabled along the forwarding path and feature changes to existing dependencies.

FeatureCrates involvedDependency implications
brotli_compressionapi, core, router, serviceCompression features on existing HTTP dependencies.
bzip2_compressiondatabaseRocksDB Bzip2 support.
consoleservicerustyline-async, termimad.
cpu_affinitycorecore_affinity.
direct_tlsrouteraxum-server-dual-protocol, rustls.
element_hacksserviceNo optional dependency activated by this feature.
emailservicelettre.
gcs_storageserviceobject_store’s gcp feature, which adds its cloud client and quick-xml.
gzip_compressionapi, core, router, serviceCompression features on existing HTTP dependencies.
io_uringdatabaseRocksDB io_uring support and its native library requirements.
jemalloccore, databasejevmalloc; native allocator build.
jemalloc_confcoreAllocator configuration; does not itself enable jemalloc.
jemalloc_profcoreProfiling on jevmalloc if the allocator is enabled.
jemalloc_statscoreStatistics on jevmalloc if the allocator is enabled.
jwt_loginadmin, api, api-client, corejsonwebtoken’s use_pem feature, which adds pem and simple_asn1. jsonwebtoken itself stays for the native OIDC server.
ldapapi, api-client, serviceldap3.
lz4_compressiondatabaseRocksDB LZ4 support.
markdownserviceRuma’s markdown feature, which adds pulldown-cmark.
masapi-mas, routerOptional workspace crate tuwunel-api-mas.
media_thumbnailserviceimage.
oidcapi-oidc, routerOptional workspace crate tuwunel-api-oidc; service-side issuer code remains compiled without this API feature.
perf_measurementsNoneopentelemetry, opentelemetry-otlp, opentelemetry_sdk, tracing-flame, tracing-opentelemetry.
release_max_log_leveladmin, api, api-admin, api-client, api-federation, api-mas, api-oidc, core, database, matrix, router, serviceLog-level filtering on existing log and tracing dependencies.
s3_storageserviceobject_store’s aws feature, which adds its cloud client, crc-fast, md-5, quick-xml and spin.
sentry_telemetryrouterreqwest, sentry, sentry-tower, sentry-tracing.
synapse_adminapi-admin, routerOptional workspace crate tuwunel-api-admin.
systemdrouter, servicesd-notify on Linux Unix targets.
tokio_consoleNoneconsole-subscriber, plus Tokio tracing support.
tuwunel_modscorelibloading.
url_previewserviceimage, webpage.
zstd_compressionapi, core, database, router, serviceHTTP and RocksDB Zstd support.

Note

  • jemalloc_conf, jemalloc_prof, and jemalloc_stats do not select the allocator themselves.

  • image is shared by thumbnails and URL previews, so removing only one feature can leave that dependency enabled.

  • Shared dependencies can already be enabled by another feature.

Crate defaults

Each workspace crate that defines default lists its own default features and enables the default of each workspace dependency that defines one. A crate built alone, such as with cargo build -p tuwunel_service, gets the same features it has in the full server.

The default of main also enables these crate defaults. A build from the workspace root and a build of -p tuwunel therefore resolve the same features and share compiled artifacts.

To build a crate alone with a dependency’s feature, name the feature through that dependency. For example, use cargo build -p tuwunel_service --features tuwunel-core/jemalloc_prof.

Rust cfg selectors

These configurations are primarily developer debugging, instruments and internal controls. The workspace registers them with check-cfg so rustc accepts their spelling. Build recipes can supply them separately through Rust compiler flags. They can be enabled by default in .cargo/config.toml.

cfg nameOursDefaultCrates involvedDescription
core_intrinsics××coreUses the compiler breakpoint intrinsic rather than the x86_64 breakpoint fallback.
disable✔️×core, database, serviceMarks dormant or unfinished code. Enabling it can introduce conflicting definitions.
panic_trap✔️×mainInternal modular-loader panic-hook path; not a supported standalone build switch.
tokio_unstable××core, main, adminEnables unstable Tokio metrics and runtime controls; also required by tokio_console.
tuwunel_always_prove_sendness✔️×serviceAsks the trait solver to prove OnceServices is Send instead of using its manual implementation; increases compilation work.
tuwunel_always_prove_syncness✔️×serviceAsks the trait solver to prove OnceServices is Sync instead of using its manual implementation; increases compilation work.
tuwunel_debug_logging✔️×corePreserves the requested severity of debug-gated logging macros. Does not override compile-time maximum log levels.
tuwunel_mods✔️×core, mainEnables development hot-reload paths together with the Cargo feature of the same name.
unabridged✔️×database, serviceAdds fine-grained tracing spans.

Note

  • The tokio_console Cargo feature needs tokio_unstable.

  • The tuwunel_mods cfg and Cargo feature must both be enabled for hot reloading. See Hot Reloading for the modular build workflow.

Testing and Delivery

Tuwunel’s CI is built on Docker Buildx Bake, a recipe tree for multi-stage builds that produces cache-friendly multi-layer images. Each layer accomplishes a specific task and its outputs are automatically reused by any subsequent layer that depends on it. The result is a large combinatorial matrix of build configurations where only the final layer — the one that actually differs — must be rebuilt.

The .github/workflows/ directory contains the pipeline description actually used for CI. It is a thin client: switches and patch panels that dispatch to the docker builder, not the mainframe itself. Every job is a path to an invocation of docker buildx bake. The same builder, with the same targets, is available to any developer locally — no service lockin required.

All scripts, Dockerfiles, and the bake configuration live in docker/ at the project root.

Delivery Pipeline

The pipeline is organized into four sequential phases that gate on each other. A failure in any phase blocks all later ones, preventing partially-built deliverables from reaching users.

PhaseAccessDescription
Linteverything (unless masked)format, spelling, security audit, dead links, clippy
Testeverything (unless masked)unit, integration, smoke, Complement, Matrix SDK
Packagemain, test, releases, PRs (limited)binaries, containers, distro packages, docs
Publishmain and tagged releases onlycontainer registries, GitHub Pages

Chapters

Docker Bake System

The builder is implemented using Docker Buildx Bake, a declarative build system for multi-stage Docker builds. All configuration lives in docker/bake.hcl. The shell script docker/bake.sh is the user-facing entry point for invoking it.

A conventional CI system runs sequential jobs that each build everything they need from scratch, or caches at coarse granularity (the whole Cargo registry, the whole target/ directory). Bake instead models the build as a directed acyclic graph of image layers. Intermediate layers are shared across every target that needs them: if deps-build already exists in the cache, every target that depends on it — unit, clippy, install, deb — skips rebuilding it and jumps straight to their unique work.

This is especially valuable for the build matrix: compiling dependencies once per (toolchain, feature set) pair and reusing that layer for all tests and build targets on top of it cuts total CI time dramatically.

Directory layout

FileRole
docker/bake.hclDeclarative target graph; all variables, groups, and targets
docker/bake.shShell wrapper; sets defaults, invokes docker buildx bake
docker/complement.shComplement test orchestrator; runs after bake builds the images
docker/Dockerfile.*“Library functions” — generic, variable-driven build stages

The Dockerfile.* files are intentionally generic: they accept ARG variables and are reused across many targets via Bake’s variable substitution, rather than having one Dockerfile per use case.

Builder setup

Bake requires a named BuildKit builder. Locally, the builder name defaults to owo. In CI it is the GitHub actor name ($GITHUB_ACTOR). Create one with:

cat <<EOF > buildkitd.toml
[system]
  platformsCacheMaxAge = "504h"
[worker.oci]
  enabled = true
  gc = true
  reservedSpace = "64GB"
  maxUsedSpace = "128GB"
[[worker.oci.gcpolicy]]
  reservedSpace = "64GB"
  maxUsedSpace = "128GB"
  all = true
EOF

docker buildx create \
  --name owo \
  --bootstrap \
  --buildkitd-config ./buildkitd.toml \
  --driver docker-container \
  --buildkitd-flags "--allow-insecure-entitlement network.host"

The --allow-insecure-entitlement network.host flag is required for Complement (which needs host networking during testing). It can be omitted if you only need to run other targets.

bake.sh usage

docker/bake.sh is the standard entry point. It accepts target names as positional arguments and reads matrix dimensions from environment variables.

# Basic usage
docker/bake.sh <target> [<target>...]

# With environment overrides (singular form for convenience)
cargo_profile="release" rust_toolchain="msrv" docker/bake.sh install

# Multiple targets
docker/bake.sh fmt clippy

Targets

Bake groups collect multiple targets under one name for convenience:

GroupMembers
lintsaudit, check, clippy, fmt, lychee, typos
testsAll unit, integ, doc, bench targets
smokesmoke-version, smoke-startup, smoke-perf, smoke-valgrind, smoke-nix
integrationrust-sdk-integ, rust-sdk-valgrind
complementAll complement tester/testee targets
installsinstall, static, docker, oci
pkgbook, docs, deb, deb-install, rpm, rpm-install, nix
publishghcr_io, docker_io
defaultA representative single-vector build

Variables

Variables at the top of bake.hcl control every aspect of the build. Most have sensible defaults for local use and are overridden by bake.sh or the CI workflows for production runs.

Single-value selectors

EnvironmentDefaultDescription
cargo_profiletestSingle profile (wrapped into JSON array)
feat_setallSingle feature set
rust_toolchainnightlySingle toolchain
rust_targetx86_64-unknown-linux-gnuSingle Rust target triple
sys_namedebianBase OS name
sys_versiontesting-slimBase OS version
sys_targetx86_64-v1-linux-gnuCPU optimization level

For multi-value matrix runs (as used in CI), set the cargo_profiles, feat_sets, etc. variables directly to JSON arrays.

Multi-value defaults

variable "cargo_profiles"   { default = "[\"test\", \"release\"]"          }
variable "feat_sets"        { default = "[\"none\", \"default\", \"all\"]" }
variable "rust_toolchains"  { default = "[\"nightly\", \"msrv\"]"          }
variable "rust_targets"     { default = "[\"x86_64-unknown-linux-gnu\"]"   }
variable "sys_names"        { default = "[\"debian\"]"                     }
variable "sys_versions"     { default = "[\"testing-slim\"]"               }
variable "sys_targets"      { default = "[\"x86_64-v1-linux-gnu\"]"        }

These are escaped JSON arrays passed as strings.

Target Hierarchy

Every target is a leaf or branch in a single dependency tree. Building a leaf automatically triggers all its transitive dependencies. The tree (bottom to top):

system                      ← Debian base image + runtime packages
  ├── rust                  ← rustup + toolchain installation
  │     └── rustup
  ├── rocksdb-fetch         ← RocksDB source checkout
  │     └── rocksdb-build   ← compiled librocksdb
  │           └── rocksdb
  ├── valgrind              ← Valgrind installation
  └── perf                  ← Linux perf tools

kitchen                     ← build environment (inherits system + rust + rocksdb)
  └── builder               ← adds nproc/env setup

source                      ← project source code (via git checkout)
  └── preparing             ← sets up cargo workspace for chef
        └── ingredients     ← cargo-chef recipe
              └── recipe    ← pre-built dependency layer (cargo-chef cook)

deps-base          ← base dependency compilation
deps-build         ← full dep build (links recipe + kitchen)
deps-build-tests   ← test deps
deps-build-bins    ← binary deps
deps-clippy        ← clippy-specific deps
deps-check         ← check-specific deps

build              ← compiles the main binary
build-tests        ← compiles test binary
build-bins         ← compiles all binaries
build-deb          ← deb packaging build
build-rpm          ← rpm packaging build

# Lint targets (leaves):
fmt  typos  audit  lychee  check  clippy

# Test targets (leaves):
doc  unit  unit-valgrind  integ  integ-valgrind
smoke-version  smoke-startup  smoke-perf  smoke-valgrind  smoke-nix
rust-sdk-integ  rust-sdk-valgrind

# Complement targets (leaves):
complement-base  complement-config
complement-tester  complement-tester-valgrind
complement-testee  complement-testee-valgrind

# Install/package targets (leaves):
install  install-valgrind  install-perf  static
docker  oci
deb  deb-install  rpm  rpm-install  nix  build-nix
book  docs

# Publish targets (leaves):
ghcr_io  docker_io

Build Matrix

Tuwunel’s CI tests a large combinatorial space of build configurations. The matrix has six independent dimensions. Not all combinations are valid or useful, so the bake configuration and workflow files apply exclusions to keep the total job count tractable.

Cargo Profiles

ProfileUseNotes
testMost tests and lintingDebug-like; assertions enabled; fastest to compile
releaseProduction builds and smoke testsThin LTO; the profile shipped to users
benchBenchmarks and ValgrindOptimized with debug symbols for profiling
release-debuginfoRelease + full debug infoFor crash analysis without sacrificing optimization
release-nativePerformance benchmarking on CI hardwaretarget-cpu=native; non-portable; never shipped

Cargo Feature Sets

The feature sets are named groups of Cargo features, defined in docker/bake.hcl as the cargo_feat_sets map.

none

No optional features. Produces the smallest, most minimal binary. Used to verify that nothing in the default code path accidentally depends on an optional feature.

default

The feature set shipped to users in standard packages:

brotli_compression, bzip2_compression, console, cpu_affinity, direct_tls, element_hacks, email, gcs_storage, gzip_compression, io_uring, jemalloc, jemalloc_conf, jwt_login, ldap, lz4_compression, markdown, mas, media_thumbnail, oidc, release_max_log_level, s3_storage, sentry_telemetry, synapse_admin, systemd, url_preview, zstd_compression

logging

All of default without release_max_log_level, so release builds keep the debug and trace log levels.

all

Everything, including release_max_log_level. The most exhaustive compilation target; used for clippy, doc tests, and integration tests.

Note

The feature direct_tls is always added to every build regardless of the selected feature set (cargo_features_always in bake.hcl).

Rust Toolchains

Toolchain keyResolved toUsed for
nightlyThe current nightly (or a specific nightly in CI)Default for all builds; required for some flags and rustfmt options
msrvThe MSRV from rust-toolchain.tomlRelease packages, Nix smoke test
stableThe current stable releaseOne clippy cell (test profile, all features)

The bake.sh script reads rust-toolchain.toml to resolve msrv to the project’s minimum supported Rust version, ensuring released binaries are always built against a pinned toolchain rather than whatever stable happens to be current. Nix additionally verifies this with a SHA256 check in flake.nix.

stable is the moving stable channel, installed when a builder’s toolchain layer is built and refreshed with [ci clean-rust]. Its one clippy cell catches lints that a newer stable adds and that neither the older pin nor nightly reports the same way.

Rust Targets (Cross-compilation)

These are the --target values passed to Cargo:

TargetArchitecture
x86_64-unknown-linux-gnux86_64 Linux (primary)
aarch64-unknown-linux-gnuARM64 Linux

Cross-compilation to aarch64 runs on ARM64 GitHub Actions runners and produces binaries for Raspberry Pi 4+, AWS Graviton, and Apple Silicon (via Rosetta or native under Linux).

64-bit RISC-V is absent from the matrix because no runner provides that architecture, but it does build and run. See RISC-V for the cross-compilation recipe.

32-bit ARM is absent for the same reason, and likewise builds and runs. See 32-bit ARM, which also covers why that port uses a glibc cross toolchain where the RISC-V one uses musl.

CPU Optimization Levels (System Targets)

The sys_target dimension controls which x86_64 microarchitecture level the binary is compiled for. This affects both Rust compiler flags and, for targets that include RocksDB, the native library build.

sys_targetx86_64 levelKey instruction setsRecommended for
x86_64-v1-linux-gnuv1 baselineSSE2Any x86_64 CPU; used for compatibility testing
x86_64-v2-linux-gnuv2+ POPCNT, SSE3, SSE4.1/4.2, SSSE3CPUs from ~2009+; minimum for good RocksDB CRC32 performance
x86_64-v3-linux-gnuv3+ AVX, AVX2, BMI1/2, F16C, FMA, MOVBEHaswell (2013) and newer; the recommended shipping target
x86_64-v4-linux-gnuv4+ AVX-512F/BW/CD/DQ/VLSkylake-X/Ice Lake server; highest throughput
aarch64-v8-linux-gnuARMv8NEON, AES, SHAAll 64-bit ARM

Warning

Running a binary compiled for a higher level than the host CPU supports causes an Illegal Instruction (SIGILL) crash immediately on startup. The generic deployment guide includes a command to determine which level your CPU supports.

RocksDB benefits significantly from hardware CRC32 (available from v2 onward) and from SIMD compression routines (improved further at v3). For production deployments, -v3- binaries are the recommended default.

System Images

The base OS image for build and runtime containers. Currently only one system is tested:

sys_namesys_versionBase image
debiantesting-slimdebian:testing-slim

Linking Mode

Static versus dynamic linking is selected automatically based on the profile and toolchain:

ConditionLinking
release or bench profile with msrv or stable toolchainStatic (-C relocation-model=static, +crt-static)
All other combinationsDynamic (PIC, shared libc)

Static linking produces fully portable binaries that run on any Linux system without matching library versions. Dynamic linking is used during development and testing because it produces faster incremental builds.

Matrix Combinations in Practice

The CI does not test every possible combination — the cross-product of all dimensions would be in the thousands. Instead, each workflow job selects a slice of the matrix appropriate to its task:

JobProfilesFeature setsToolchainsCPU targets
clippytest, release, benchnone, default, allnightly, msrv, stable (one cell)v1
unittestallnightlyv1
benchbenchallnightlyv3
memcheckbenchallnightlyv3
smoketest, releasedefault, allnightlyv1, v3
rust-sdk-integtest, releaseallnightlyv1
complementtest, releaseallnightlyv1
binary (package)releasedefaultmsrvv1, v2, v3, v4, aarch64-v8
container (package)releasedefaultmsrvv3
distro (package)releasedefaultmsrvv1

The test.yml workflow embeds about 51 explicit exclusions to remove combinations that are redundant, impossible, or not worth the resource cost.

Benchmarks and Performance

Tuwunel has three related performance paths. They answer different questions and produce different kinds of output.

PathQuestionOutput
Criterion benchmarksDid a focused operation get faster or slower?Statistical timing and throughput samples
Local perf helperWhere does one benchmark spend CPU time?Hardware counters and a sampled call graph
Complement perf in CIHow does an optimized server behave under a protocol workload?Runtime metrics, hardware counters, and comparisons with prior runs

Run Criterion benchmarks locally

Benchmark targets are declared in each crate’s Cargo.toml. The database codec benchmarks use the ser target in the tuwunel_database package. From the repository root, run the full target with:

cargo +nightly bench -p tuwunel_database --bench ser

Cargo prints the benchmark executable path in its build output. It normally looks like target/release/deps/ser-<hash>. Build that executable without running it when preparing to use the profiling helper:

cargo +nightly bench -p tuwunel_database --bench ser --no-run

Criterion benchmark names form paths. A full path is also a useful filter when running the compiled executable directly:

target/release/deps/ser-<hash> \
  formats/cbor/scalar/database_serialize

The ser target includes database key serialization, CBOR and JSON format comparisons, and allocation-sensitive minicbor cases. Criterion prints timing and throughput estimates and stores its samples beneath target/criterion/.

Compare results on the same machine with the same toolchain, compiler flags, and feature set. Keep other CPU-heavy work off the host during a comparison. Criterion’s baseline and significance controls are appropriate for timing comparisons. The profiling helper below intentionally disables that analysis.

Profile a benchmark with Linux perf

tests/perf runs a compiled Criterion benchmark under Linux perf. It takes three positional arguments:

  1. the benchmark executable;
  2. a Criterion benchmark filter;
  3. an output prefix.

Compile the benchmark first, copy the executable path printed by Cargo, then run:

mkdir -p target/perf

tests/perf \
  target/release/deps/ser-<hash> \
  formats/cbor/scalar/database_serialize \
  target/perf/cbor-scalar

Use a narrow filter unless profiling several cases together is intentional. The helper performs two fixed-duration passes:

  1. perf stat records task time, scheduler activity, faults, instructions, cycles, branches, and cache counters in target/perf/cbor-scalar.stat.
  2. perf record samples a call graph in target/perf/cbor-scalar.data.

Both passes use Criterion’s profiling mode. Criterion iterates the matching benchmark for the requested time without statistical analysis and without updating its stored results. With the default settings, allow about 20 seconds per matching benchmark, plus startup overhead.

Inspect the outputs with:

less target/perf/cbor-scalar.stat
perf report -i target/perf/cbor-scalar.data

The helper accepts these environment controls:

VariableDefaultEffect
PROFILE_SECONDS10Duration of each profiling pass
PERF_COMMANDperfPerf executable to invoke
PERF_EVENTcpu-clockSampling event used by perf record
PERF_FREQUENCY999Sampling frequency used by perf record

For example:

PROFILE_SECONDS=30 \
PERF_EVENT=cycles \
PERF_FREQUENCY=1999 \
tests/perf \
  target/release/deps/ser-<hash> \
  minicbor/tuple/stack_roundtrip \
  target/perf/minicbor-tuple

The perf stat event list is fixed in the helper. The event and frequency variables affect only the sampling pass.

Host requirements

The helper requires Linux perf tools that match the running kernel and permission to open the requested performance events. Some distributions expose /usr/bin/perf as a launcher and require a separate kernel-specific tools package. Point PERF_COMMAND at the working executable when it is elsewhere.

Kernel policy may also restrict hardware counters or sampling to privileged users. The local helper exits on such an error so it cannot silently produce an incomplete profile. Symbol names are retained in the benchmark profile, but complete call stacks still depend on the host’s unwind support and perf setup.

Performance coverage in CI

CI has two separate performance paths. Neither currently acts as an automatic regression threshold.

Criterion Bench job

The Bench job builds and runs the workspace benchmark targets with the nightly toolchain, all features, the optimized bench profile, and the x86_64-v3 system target. The unit bake target runs library benchmarks; the integration bake target runs each registered benchmark executable.

Criterion output is visible in the job log. CI does not currently retain the Criterion sample directory as an artifact, compare it with a named baseline, or fail a run because a timing changed. Treat this lane as benchmark build and execution coverage, not as a stable comparison between shared-runner results.

Complement server profiling

The optimized Compliance (tuwunel) job enables a separate perf wrapper around each Tuwunel testee. This is a full server workload, not the tests/perf helper. The job uses the bench profile, the logging feature set, nightly Rust, and x86_64-v3.

The runner grants CAP_PERFMON, starts each server under perf stat, and collects the report beside the server’s runtime metrics. The job summary can show instructions, cycles, IPC, branch misses, cache and TLB miss rates, and frontend or backend bounds. Branch runs are compared with the main-branch anchor and recent successful runs. Main-branch runs establish the anchor. The raw bundle is uploaded as a complement_runtime_metrics-*.tar.zst artifact.

If perf is missing or event access is denied, the CI wrapper logs a warning and runs the server normally. Hardware-counter rows are omitted in that case.

The workflow currently enables this profiling automatically for the optimized Tuwunel Complement job. It does not expose separate dispatch controls for the event list, sampling rate, or perf enablement. Those values remain part of the CI implementation.

Pipeline Phases

The CI pipeline runs in four sequential phases. Each phase must pass in its entirety before the next begins. This structure is intentional: linting fails fast before expensive test jobs start; tests must pass before build artifacts are created; packages are only published when everything before them succeeded.

Tip

Commit messages can suppress individual phases to avoid waiting for unrelated results when only interested in specific jobs.

Flag in commit messageEffect
[ci no lint]Skip the linting phase
[ci no test]Skip the testing phase
[ci no build]Skip build targets within tests/packages
[ci no package]Skip the package phase
[ci no publish]Skip the publish phase
[ci only it]Run only integration tests

1. Linting Phase

Linting runs first and fails fast. None of the heavier test or build jobs start until every lint check passes. All lint jobs are in docker/ targets invoked through .github/workflows/lint.yml.

Format (fmt)

All Rust source must be formatted with nightly rustfmt. The check runs cargo fmt --check and produces a diff showing every formatting violation if it fails.

  • Dockerfile: docker/Dockerfile.cargo.fmt
  • Bake target: fmt
  • Toolchain: nightly (nightly rustfmt has formatting options stable does not)

Typos (typos)

All text in the repository — source code, comments, and Markdown documentation — is checked for spelling errors using the typos tool.

  • Dockerfile: docker/Dockerfile.cargo.typos
  • Bake target: typos

Security Audit (audit)

cargo audit checks every dependency in Cargo.lock against the RustSec Advisory Database. Any unignored advisory causes a failure. This job runs on branch pushes and all “fat” refs (main, test, release tags); it is skipped on pull requests to avoid blocking contributors on advisories they did not introduce.

  • Bake target: audit
  • Workflow condition: is_branch || is_fat

lychee scans all Markdown files for broken hyperlinks. Internal links (relative paths) and external URLs are both checked.

  • Dockerfile: docker/Dockerfile.cargo.lychee
  • Bake target: lychee

Cargo Check (check)

cargo check is used as a fail-faster form of clippy, although the latter is not gated on the former, the intent is to cancel all other tasks before they inevitably fail on the same error. Only one instance of this is usually run.

  • Bake target: check

Clippy (clippy)

cargo clippy runs with --deny warnings — any lint warning is a build failure. Crucially, clippy runs for every combination of the build matrix: all cargo profiles, all feature sets, msrv and nightly toolchains, plus one cell on the current stable. This catches warnings that only manifest under specific feature combinations or with a specific compiler, which individual developers rarely exercise locally.

  • Bake target: clippy
  • Policy: zero warnings permitted across all matrix dimensions

2. Testing Phase

The testing phase covers correctness at every level, from individual functions to full Matrix protocol compliance. The most complex workflow. Receives matrix selectors and per-test enable flags. Jobs are roughly ordered by cost: cheaper jobs run first; expensive jobs (Nix, Complement) run last or are gated on cheaper jobs passing.

Cargo Doc Tests (doc)

cargo test --doc runs all code examples embedded in rustdoc comments. Runs on release profile with all features and nightly toolchain on x86_64-v1.

  • Bake target: doc

Cargo Unit and Integration Tests (unit)

cargo test runs the module-level unit tests and any crate-associated or binary-associated integration. Runs on test profile with all features and nightly toolchain.

  • Bake target: unit
  • Valgrind variant: unit-valgrind

Cargo Benchmarks (bench)

The workspace benchmark targets are compiled and run with the bench profile, all features, nightly, and the x86_64-v3 system target. Criterion results remain in the job log; CI does not retain a timing baseline or gate on changes.

Valgrind Memory Checking (memcheck)

The integration test binary runs under Valgrind to detect memory errors at runtime. Configured with:

--error-exitcode=1 --exit-on-first-error=yes --undef-value-errors=no --leak-check=no

Runs on bench profile with all features and nightly on x86_64-v3.

  • Bake target: integ-valgrind

Smoke Tests (smoke)

Smoke tests exercise a running Tuwunel binary without a full client. These tests run on main and test branches; some are skipped on pull requests to reduce costs of scaling public contribution.

  • Bake group: smoke
  • Dockerfile: docker/Dockerfile.smoketest

Nix Smoke Test (nix)

This job checks that nix build produces a working binary. The Nix build also runs Cargo unit tests inside the Nix sandbox. Integration tests cannot run there. See Nix tests for the sandbox limitations.

The build also checks its inputs:

  • Requires all dependency Git commits to be reachable from a branch
  • Validates that the SHA256 hash in flake.nix matches the current rust-toolchain.toml version. This catches MSRV bumps where the flake was not updated.

The job runs on branch pushes, main and test included, when the selected matrix includes the release profile, the all feature set, the msrv toolchain and the x86_64-v1-linux-gnu target. Pull requests skip it.

  • Bake target: smoke-nix
  • Dockerfile: docker/Dockerfile.nix

Matrix Rust SDK Integration Tests (rust-sdk-integ)

Runs the matrix-rust-sdk client-server integration test suite against a live Tuwunel process. A Tuwunel binary from a prior build layer is started in the background while cargo test runs the SDK’s integration test crate right in the docker builder.

  • Debug mode (test profile): Exercises code paths with assertions enabled and catches logic errors that only appear with unoptimized code.
  • Release mode (release profile): Ensures tests pass without concurrency hazards or other issues that optimized builds can expose.

For the above two matrix variations rust-sdk-integ is run for both and rust-sdk-valgrind is run for release profile only.

  • Bake targets: rust-sdk-integ, rust-sdk-valgrind
  • Dockerfile: docker/Dockerfile.matrix-rust-sdk

Compliance (complement-tester/complement-testee)

See Complement Testing for full details. Briefly: the Complement suite runs its Go tests against containerized Tuwunel instances via the Docker daemon, verifying conformance to the Matrix client-server and server-server specifications.

The complement job builds two images (tester and testee) via bake.yml. The compliance job then runs docker/complement.sh, extracts result files from the tester container, and runs git diff against the stored baseline. The diff is uploaded as an artifact regardless of pass/fail, so reviewers can see exactly what changed in compliance.

A file named tests/complement/tuwunel.log contains the server logs from the last run extracted from the testee container and is also uploaded as an artifact.

3. Package Phase

The package phase produces all distributable artifacts. It runs after tests pass. The set of artifacts produced varies by branch:

Branch / refArtifacts produced
Pull requestsMinimal: binary for the pushed architecture only
Regular branchesBinaries + containers for x86_64
main / testFull set including distro packages and all CPU variants
Release tags (v*)Full set, identical to main
test branch onlyPost-package install checks (deb and rpm)

rustdoc (docs)

Builds the Rust API documentation with cargo doc. Runs on release profile, all features, nightly, x86_64-v1.

  • Bake target: docs
  • Output: /usr/src/tuwunel/target/<triple>/doc/

mdBook (book)

Builds this documentation site using mdBook. Runs on release profile, msrv, x86_64-v1.

  • Bake target: book
  • Output: /book/

Static Binaries (binary)

Compiles statically linked binaries for all supported targets. Packaged as release assets on GitHub.

  • Bake targets: install (dynamic), static (static), oci, docker
  • CPU variants: x86_64-v1, x86_64-v2, x86_64-v3, x86_64-v4, aarch64-v8 (full set on main/test/release; reduced set on other branches)

Container Images (container)

Builds OCI and Docker images for docker and oci container formats.

  • Bake targets: docker, oci
  • Output: images pushed in the publish phase to GHCR and Docker Hub

Distro Packages (distro)

Builds .deb, .rpm, and Nix packages. Only on main, test, and release tags.

  • Dockerfiles: docker/Dockerfile.cargo.deb, docker/Dockerfile.cargo.rpm

Post-package Checks (checks)

Installs the built .deb and .rpm into a clean environment and verifies the package installs and the binary runs. Only on the test branch, where the most thorough validation is desired.

  • Bake targets: deb-install, rpm-install

4. Publish Phase

The publish phase runs only for main and release tags. All publication happens here — nothing is pushed to external services during earlier phases. This keeps publication atomic: if anything fails before this phase, no partially-complete releases reach users.

GitHub Pages (documents)

Uploads the built mdBook site and rustdoc to GitHub Pages. Skipped for draft releases.

  • Workflow job: documents

Container Registries (containers)

Pushes container images to two registries simultaneously:

  • GitHub Container Registry (ghcr.io/matrix-construct/tuwunel)
  • Docker Hub (docker.io)

Images are compressed with zstd at level 11. Each image is tagged with the Git SHA and branch/tag name.

  • Workflow job: containers

Manifest Bundles (bundles / delivery)

After all per-image pushes complete, manifest lists are assembled that combine multi-architecture images under a single tag. Manifests are pushed to both registries in the delivery job, which depends on bundles and documents both completing first.

Manifest tagApplied to
mainmain branch pushes
previewRelease candidates (-rc, pre-release tags)
latestFull release tags

Matrix Protocol Compliance Testing

Complement is the Matrix protocol compliance test suite. It verifies that a homeserver correctly implements the Matrix client-server and federation specifications by running Go-based tests against live server instances. We maintain a fork at github.com/matrix-construct/complement with fixes for tests that had issues upstream.

Complement works differently from ordinary test runners: it uses the Docker daemon API to create isolated networks and start fresh homeserver instances for each test (or small group of tests). This requires the test runner itself to have access to the Docker socket — which creates a docker-in-docker situation when running inside a container.

Tuwunel’s CI handles this by splitting the work into two images and a shell script:

complement-tester   ← contains the Complement binary (the Go test runner)
complement-testee   ← contains the Tuwunel binary (the system under test)

docker/complement.sh runs complement-tester as a container with:

  • The host Docker socket mounted (-v /var/run/docker.sock:/var/run/docker.sock)
  • Host networking (--network=host) for test containers to communicate

The tester container then orchestrates the test run by telling the host Docker daemon to start complement-testee instances, connect them, and run the tests. The Go code inside the tester runs against these instances, while all the container management happens on the host’s daemon — not truly docker-in-docker.

Running locally

Prerequisites:

  • Docker with BuildKit and a configured builder.
  • network.host entitlement enabled on the builder
Basic run (debug build, all tests)
docker/bake.sh complement-tester complement-testee && docker/complement.sh
Release build
cargo_profile="release" docker/bake.sh complement-tester complement-testee && \
  cargo_profile="release" docker/complement.sh
Release build with the msrv toolchain
export cargo_profile="release"
export rust_toolchain="msrv"
docker/bake.sh complement-tester complement-testee && docker/complement.sh
Run a single test by name
docker/bake.sh complement-tester complement-testee && \
  docker/complement.sh TestAvatarUrlUpdate
Run multiple tests by pattern
docker/bake.sh complement-tester complement-testee && \
  docker/complement.sh "TestAvatarUrlUpdate|TestEvent"

The argument to complement.sh becomes the complement_run regex, passed to Go’s test runner via -run.

View logs from the last run
cat tests/complement/logs.jsonl | jq .

Results and baseline comparison

After each run, complement.sh extracts two files from the tester container:

FileContents
tests/complement/results.jsonlPass/fail result for every test case
tests/complement/logs.jsonlFull verbose output from the test run

The results file is version-controlled. complement.sh runs git diff --exit-code on it: if results match the stored baseline exactly, the script exits 0 (pass). Any change — new failures or new passes — produces a non-zero exit and the diff is printed. In CI, the diff and logs are uploaded as artifacts for review. It tracks changes in compliance. A test that was previously failing and starts passing is caught just as clearly as a regression. The baseline must be deliberately updated when the compliance profile intentionally changes.

Interoperability runs (heterogeneous homeservers)

By default every homeserver Complement spawns (hs1, hs2, …) uses the same complement-testee image, so a run tests Tuwunel against itself. Complement was designed to also test different implementations against each other: it reads a per-homeserver image override from COMPLEMENT_BASE_IMAGE_<hsname> and falls back to the shared COMPLEMENT_BASE_IMAGE for any homeserver without one. An interop run assigns a different image to one or more homeservers so federation is exercised between two distinct servers. These are still honest peers; the only difference is the implementation behind each one.

The most fundamental case is two builds of the same server (for example a release image as hs1 and a development image as hs2). The goal case is a foreign implementation, such as Synapse against Tuwunel.

docker/complement.sh exposes this through a few selectors, in increasing precedence:

SelectorEffect
interop=synapsehs2 runs the published Synapse Complement image
interop_image=<ref>hs2 runs <ref>
interop_hs="hs2 hs4"which homeservers the foreign image owns (default hs2)
COMPLEMENT_BASE_IMAGE_hs2=<ref>raw per-homeserver passthrough

The runner pre-pulls each foreign image into the host daemon (Complement will not pull a missing image itself) and forwards the override into the tester container. The suffix is normalized to lowercase because Complement looks the override up by the literal homeserver name (hs1, hs2).

Synapse vs Tuwunel
docker/bake.sh complement-tester complement-testee && \
  interop=synapse docker/complement.sh "TestFederation.*"

hs1 is Tuwunel and hs2 is Synapse. The Synapse image (ghcr.io/element-hq/synapse/complement-synapse:latest) is published by Synapse’s own CI, so this needs no local Synapse checkout and is reproducible in CI. Override the ref with synapse_image=... for a pinned tag.

Two Tuwunel versions
# build a second testee from another checkout, tag it, then:
interop_image=complement-testee-prev:latest docker/complement.sh "TestFederation.*"
Federation TLS

For cross-implementation federation to work, each homeserver must present a certificate that its peer trusts. Complement generates one Certificate Authority per run and copies it into every container at /complement/ca/. The Tuwunel testee’s entrypoint signs a short-lived federation certificate for its $SERVER_NAME with that CA at startup (mirroring how Synapse, Dendrite, and others behave), so a peer that validates certificates (Synapse does) accepts the connection. Outside Complement, where no run CA is present, the image keeps its baked self-signed certificate.

Results

A heterogeneous run does not match the homogeneous baseline in tests/complement/results.jsonl, so any interop selector switches the run to report-only: results land under tests/complement/interop/ and the baseline gate is skipped. The run prints a pass/fail/skip summary instead. A dedicated interop baseline (to gate the Synapse-vs-Tuwunel matrix on regressions) is a natural follow-up.

In CI

CI carries two interop jobs, both reusing the homogeneous run’s complement-tester and complement-testee images. Interoperability (synapse) runs them against the published Synapse image as hs2; Interoperability Inverted (synapse) swaps the roles so Synapse drives as hs1 and Tuwunel answers as hs2, exercising the responder side. The peer name in both titles comes from complement_interop_peer, which defaults to synapse. Because the runs are report-only they never gate the pipeline; their outcome is the per-run step summary plus the uploaded complement_interop_* artifacts.

Both run by default, on every pipeline. The Main workflow exposes enable_test_complement_interop and enable_test_complement_interop_inverse as dispatch inputs, plus complement_interop_run to narrow the selector. Those two inputs are declared default: false, but the default is inert: they are consumed as fromJSON(inputs.<name> || 'true'), and a false boolean is falsy in a GitHub expression, so the || 'true' branch is taken whether the box is ticked or not. There is no commit-message directive for interop.

To actually skip them, disable the Complement stage: both jobs additionally require enable_complement and enable_complement_debug, so neither runs when Complement is off. The inverted job also requires the forward job’s enable_complement_interop, so it cannot run alone.

Known limitation: blueprint construction

Tests built on Deploy(t, n) construct a shared multi-server blueprint the first time one runs in a package, then redeploy the committed images for each test. The first redeploy of an overridden homeserver, immediately after that construction, currently comes up without its SERVER_NAME. An image whose entrypoint hard-requires that variable (Synapse signs its certificate from it) fails to start for that one test, while later deploys of the same blueprint in the run succeed. Federation queries on a freshly deployed pair (for example the profile tests) are unaffected. This is a Complement-side interaction between blueprint construction and per-homeserver image overrides, not a Tuwunel or Synapse protocol difference.

Image naming

Images are tagged with the full matrix vector so they can be unambiguously matched:

complement-tester--<sys_name>--<sys_version>--<sys_target>
complement-testee--<cargo_profile>--<rust_toolchain>--<rust_target>--<feat_set>--<sys_name>--<sys_version>--<sys_target>

For example, a debug run produces:

complement-tester--debian--testing-slim--x86_64-v1-linux-gnu
complement-testee--test--nightly--x86_64-unknown-linux-gnu--all--debian--testing-slim--x86_64-v1-linux-gnu

Nix-based Complement (unmaintained)

Warning

The workflow described below is not currently maintained and is no longer recommended. It is preserved here for any contributor who wants to reconstitute it.

Tuwunel’s flake.nix provides a complement package that builds a Complement OCI image using Nix. With Nix and direnv installed (run direnv allow after setup):

  • ./bin/complement "$COMPLEMENT_SRC" — build, run, and output logs to the specified paths; also outputs the OCI image to result
  • nix build .#complement — build just the OCI image (a .tar.gz at result)
  • nix build .#linux-complement — for macOS hosts needing a Linux image

Pre-built images from CI artifacts can be placed at complement_oci_image.tar.gz in the project root and used without Nix.

Nix Binary Cache

Building Tuwunel from the flake compiles a pinned Rust toolchain, a patched RocksDB, and liburing before it ever reaches Tuwunel’s own crates. The binary cache holds the results of that work so neither CI nor a contributor has to repeat it.

Reading from the cache is public and needs no credentials. Writing to it needs a token that only the main repository holds.

Cache identity

SubstituterPublic keyProvider
Self-hostedhttps://cache.tuwunel.chatcache.tuwunel.chat-1:ZafUaXiRMozDa9N2SWim6EdzH0EEjWjwfvlTxXvcjLA=Attic behind a caching proxy
Cachixhttps://tuwunel.cachix.orgtuwunel.cachix.org-1:VRecUeDcaPxtYDA6bnMF3snPM7VYX8K605z4uuG2nWc=Cachix

Both are public read, authenticated write, and both are configured everywhere so they run side by side. They differ in what they hold: the self-hosted cache stores the entire closure including stock nixpkgs paths, while Cachix skips anything cache.nixos.org already serves.

Operators configuring a deployment should follow NixOS deployment instead; this page covers how the cache is filled and maintained.

Consuming

The flake declares the substituter in its nixConfig, so nix build, nix develop, and nix run against this repository offer it automatically. Nix applies a flake’s nixConfig without asking only for accounts in trusted-users; otherwise it prompts. Adding the two values to your own nix.conf, or running cachix use tuwunel, avoids the prompt entirely.

A substituter that answers with a 5xx is worse than one that is down. Nix retries and then fails the build, where an unreachable host or a 404 is just a miss it falls through, so a cache that is unhealthy rather than absent can break CI. cache.tuwunel.chat converts reverse-proxy backend failures to 404 for narinfo and NAR reads for exactly this reason. If some other substituter ever fails this way, stop listing it until it recovers.

CI does not rely on nixConfig. The nix-base stage in docker/Dockerfile.nix appends the substituter and key to /etc/nix/nix.conf during image construction, because the stages that realise the tree through default.nix get no effect from a flake’s nixConfig. The values arrive as the nix_substituter and nix_public_key build args, defaulted in docker/bake.hcl.

Populating

Three producers write to the cache. All are inert without a token, so forks and pull requests degrade to read-only rather than failing.

ProducerTriggerScope
smoke-nix stage in docker/Dockerfile.nixEvery branch push that runs the Smoke NixOS joball-features plus its full build closure
nix-pkg stage in docker/Dockerfile.nixTags, main and test, where distro packaging is enabledThe default package plus its full build closure
.github/workflows/nix.ymlVersion tags and manual dispatchEvery package and devShell the flake exposes for the runner’s system

The in-bake pushes are what keep CI fast: they upload build dependencies alongside the output, so a later run substitutes the toolchain and RocksDB instead of rebuilding them. All three call docker/lib/nix_cache_push.sh, which is installed into every layer by docker/Dockerfile.system next to sched_wrap.sh and stays a no-op until a token is mounted. A failed upload never fails the build that produced the paths.

Note which stage runs when. build-nix is not a target any workflow invokes, and nix-pkg only runs where is_fat holds, so smoke-nix is the sole producer on an ordinary branch push. A push added to build-nix alone would never execute in CI, because bake’s inherits copies target attributes rather than creating a stage dependency, and both other stages derive from nix-base.

Publishing with nix.yml

nix.yml enumerates attributes with nix flake show, so outputs added to the flake are published without editing the workflow. Uploads come from the post-build hook installed by cachix-action, which captures every path realised during the job.

A full pass is expensive. The flake currently exposes 32 packages per system, including cross-compiled static binaries, OCI images, and debug variants. Each matrix entry is its own job. Use the attrs dispatch input to publish a subset and max-parallel to bound how much of the runner pool a run takes.

Runner requirements

Unlike the bake targets, nix.yml runs Nix directly on the runner rather than inside a container, so it depends on the runner’s own installation. The .github/actions/install-nix action absorbs the two ways that differs from a hosted runner: it reuses an existing Nix rather than installing over one, and it points build-dir at the runner’s temp directory.

Important

Setting build-dir is required on the self-hosted pool. Nix 2.30 moved build directories under /nix/var/nix/builds, which is root-owned there while the rest of the store belongs to the runner user. Without this setting, every build fails with a permission error while evaluation keeps working and hides the cause.

Tests

Nix builds of the dynamically linked packages run the unit tests to confirm that the nixpkgs-linked build of our own crates works. Static packages skip the check phase.

No Nix build runs the integration tests. The targets under src/main/tests each boot a server. A Nix builder has no network, denies io_uring, and offers no resolver configuration, so these tests cannot run there. The unit and integ CI jobs run them with those facilities available.

Cache contents

The producers upload build closures rather than only final outputs, and the two caches then keep different amounts of that. Cachix skips any path already served by cache.nixos.org, so it holds only the Tuwunel-specific subset: the first all-features upload offered 3988 paths and stored 2158. The self-hosted cache keeps everything, stock nixpkgs paths included, which is deliberate: a complete closure means a build can be satisfied from cache.tuwunel.chat alone without cache.nixos.org being reachable.

Credentials

Each cache has its own write token, and each uploader is gated on its own, so either may be absent without disturbing the other.

SecretCacheAlso needs
CACHIX_AUTH_TOKENCachixnothing
ATTIC_TOKENself-hostedATTIC_ENDPOINT, defaulted to https://cache.tuwunel.chat

ATTIC_ENDPOINT is the Attic server the client logs into, which is not the substituter URL even though the two share a host. The bake path sets it from the attic_endpoint build arg in nix-base, so derived stages inherit it.

For nix.yml the secrets are read directly. For the bake path they are threaded explicitly, because reusable workflows do not inherit secrets:

main.yml  ->  test.yml     ->  bake.yml  ->  docker/bake.sh  ->  docker/bake.hcl
          ->  package.yml  ->

bake.sh never passes a token as a build argument. It only sets cachix_push and attic_push from whether each token is present in its environment; the tokens themselves reach the build as BuildKit secret mounts, declared once on the build-nix bake target and inherited by nix and smoke-nix, then read from /run/secrets inside each stage.

Both cachix_push and attic_push deliberately participate in the layer cache key. Without them, a tokenless build could populate the cache entry for that layer and suppress the upload on the next tokened build of the same tree.

Pushing by hand

nix/pkgs/complement/bin/nix-build-and-cache builds an installable and uploads it:

export CACHIX_AUTH_TOKEN=...
nix/pkgs/complement/bin/nix-build-and-cache just .#all-features

just builds one installable, packages builds everything the flake exposes, and ci builds the tooling CI needs. Set CACHIX_CACHE to target a cache other than tuwunel.

The script also carries an Attic uploader for the self-hosted cache. It stays dormant unless both ATTIC_TOKEN and ATTIC_ENDPOINT are set, and it defaults to no endpoint.

Where the substituter values live

cache.tuwunel.chat is live and configured alongside Cachix. Both substituters and both keys appear in exactly these places, so adding or retiring one is a known edit:

FilePurpose
flake.nixnixConfig offered to anyone building the flake
docker/bake.hclnix_substituter and nix_public_key defaults for CI
.github/workflows/nix.ymlNIX_CONFIG for the publishing workflow
docs/deploying/nixos.mdOperator instructions
This pageContributor reference

docker/Dockerfile.nix carries the same values as ARG defaults, which the bake variables override, so a CI-only change needs no Dockerfile edit. Both extra-substituters and extra-trusted-public-keys are space-separated lists in nix.conf, so a single bake variable holds both entries and no list plumbing is required. Nix queries substituters in priority order and falls through on a miss, so retiring Cachix later is a matter of deleting its entries.

Hot Reloading (“Live” Development)

Note that hot reloading has not been refactored in quite a while and is not guaranteed to work at this time.

Summary

When developing in debug-builds with the nightly toolchain, Tuwunel is modular using dynamic libraries and various parts of the application are hot-reloadable while the server is running: http api handlers, admin commands, services, database, etc. These are all split up into individual workspace crates as seen in the src/ directory. Changes to sourcecode in a crate rebuild that crate and subsequent crates depending on it. Reloading then occurs for the changed crates.

Release builds still produce static binaries which are unaffected. Rust’s soundness guarantees are in full force. Thus you cannot hot-reload release binaries.

Requirements

Currently, this development setup only works on x86_64 and aarch64 Linux glibc. musl explicitly does not support hot reloadable libraries, and does not implement dlclose. macOS does not fully support our usage of RTLD_GLOBAL possibly due to some thread-local issues. This Rust issue may be of relevance, specifically this comment. It may be possible to get it working on only very modern macOS versions such as at least Sonoma, as currently loading dylibs is supported, but not unloading them in our setup, and the cited comment mentions an Apple WWDC confirming there have been TLS changes to somewhat make this possible.

As mentioned above this requires the nightly toolchain. This is due to reliance on various Cargo.toml features that are only available on nightly, most specifically RUSTFLAGS in Cargo.toml. Some of the implementation could also be simpler based on other various nightly features. We hope lots of nightly features start making it out of nightly sooner as there have been dozens of very helpful features that have been stuck in nightly (“unstable”) for at least 5+ years that would make this simpler. We encourage greater community consensus to move these features into stability.

This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C library, macOS, and likely other host architectures are not supported (if other architectures work, feel free to let us know and/or make a PR updating this). This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you happen to have linker issues it’s recommended to try using mold or gold linkers, and please let us know in the Tuwunel Matrix room the linker error and what linker solved this issue so we can figure out a solution. Ideally there should be minimal friction to using this, and in the future a build script (build.rs) may be suitable to making this easier to use if the capabilities allow us.

Usage

As of 19 May 2024, the instructions for using this are:

  1. Have patience. Don’t hesitate to join the Tuwunel Matrix room to receive help using this. As indicated by the various rustflags used and some of the interesting issues linked at the bottom, this is definitely not something the Rust ecosystem or toolchain is used to doing.

  2. Install the nightly toolchain using rustup. You may need to use rustup override set nightly in your local Tuwunel directory, or use cargo +nightly for all actions.

  3. Uncomment cargo-features at the top level / root Cargo.toml

  4. Scroll down to the # Developer profile section and uncomment ALL the rustflags for each dev profile and their respective packages.

  5. In each workspace crate’s Cargo.toml (everything under src/* AND deps/rust-rocksdb/Cargo.toml), uncomment the dylib crate type under [lib].

  6. Due to this rpath issue, you must export the LD_LIBRARY_PATH environment variable to your nightly Rust toolchain library directory. If using rustup (hopefully), use this: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/

  7. Start the server. You can use cargo +nightly run for this along with the standard.

  8. Make some changes where you need to.

  9. In a separate terminal window in the same directory (or using a terminal multiplexer like tmux), run the build Cargo command cargo +nightly build. Cargo should only rebuild what was changed / what’s necessary, so it should not be rebuilding all the crates.

  10. In your Tuwunel server terminal, hit/send CTRL+C signal. This will tell Tuwunel to find which libraries need to be reloaded, and reloads them as necessary.

  11. If there were no errors, it will tell you it successfully reloaded # modules, and your changes should now be visible. Repeat 7 - 9 as needed.

To shutdown Tuwunel in this setup, hit/send CTRL+\. Normal builds still shutdown with CTRL+C as usual.

Steps 1 - 5 are the initial first-time steps for using this. To remove the hot reload setup, revert/comment all the Cargo.toml changes.

As mentioned in the requirements section, if you happen to have some linker issues, try using the -fuse-ld= rustflag and specify mold or gold in all the rustflags definitions in the top level Cargo.toml, and please let us know in the Tuwunel Matrix room the problem. mold can be installed typically through your distro, and gold is provided by the binutils package.

It’s possible a helper script can be made to do all of this, or most preferably a specially made build script (build.rs). cargo watch support will be implemented soon which will eliminate the need to manually run cargo build all together.

Addendum

Conduit was inherited as a single crate without modularity or reloading in its design. Reasonable partitioning and abstraction allowed a split into several crates, though many circular dependencies had to be corrected. The resulting crates now form a directed graph as depicted in figures below. The interfacing between these crates is still extremely broad which is not mitigable.

Initially hot_lib_reload was investigated but found appropriate for a project designed with modularity through limited interfaces, not a large and complex existing codebase. Instead a bespoke solution built directly on libloading satisfied our constraints. This required relatively minimal modifications and zero maintenance burden compared to what would be required otherwise. The technical difference lies with relocation processing: we leverage global bindings (RTLD_GLOBAL) in a very intentional way. Most libraries and off-the-shelf module systems (such as hot_lib_reload) restrict themselves to local bindings (RTLD_LOCAL). This allows them to release software to multiple platforms with much greater consistency, but at the cost of burdening applications to explicitly manage these bindings. In our case with an optional feature for developers, we shrug any such requirement to enjoy the cost/benefit on platforms where global relocations are properly cooperative.

To make use of RTLD_GLOBAL the application has to be oriented as a directed acyclic graph. The primary rule is simple and illustrated in the figure below: no crate is allowed to call a function or use a variable from a crate below it.

When a symbol is referenced between crates they become bound: crates cannot be unloaded until their calling crates are first unloaded. Thus we start the reloading process from the crate which has no callers. There is a small problem though: the first crate is called by the base executable itself! This is solved by using an RTLD_LOCAL binding for just one link between the main executable and the first crate, freeing the executable from all modules as no global binding ever occurs between them.

Proper resource management is essential for reliable reloading to occur. This is a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is remarkably low, generally stemming from poor patterns and practices. Unfortunately static analysis doesn’t enforce reload-safety programmatically (though it could one day), for now hazards can be avoided by knowing a few basic do’s and dont’s:

  1. Understand that code is memory. Just like one is forbidden from referencing free’d memory, one must not transfer control to free’d code. Exposure to this is primarily from two things:

    • Callbacks, which this project makes very little use of.
    • Async tasks, which are addressed below.
  2. Tie all resources to a scope or object lifetime with greatest possible symmetry (locality). For our purposes this applies to code resources, which means async blocks and tokio tasks.

    • Never spawn a task without receiving and storing its JoinHandle.
    • Always wait on join handles before leaving a scope or in another cleanup function called by an owning scope.
  3. Know any minor specific quirks documented in code or here:

    • Don’t use tokio::spawn, instead use our Handle in core/server.rs, which is reachable in most of the codebase via services() or other state. This is due to some bugs or assumptions made in tokio, as it happens in unsafe {} blocks, which are mitigated by circumventing some thread-local variables. Using runtime handles is good practice in any case.

The initial implementation PR is available here.

RISC-V

Tuwunel compiles and runs on 64-bit RISC-V. This is a working port, not a supported platform: nothing in the CI matrix builds it, and no release artifact is published for it. This page records how to reproduce the build and the handful of things that differ from the architectures we do ship.

Verified against 1.8.3 on riscv64gc-unknown-linux-musl. The resulting server opens its database and answers the client and federation version endpoints under emulation.

Why it is not in the build matrix

Every layer in docker/bake.hcl inherits its platform from the system target, which declares platforms exactly once. A bake target therefore builds its whole toolchain and runs its compile inside a container of the target platform, and the workflow matrices exclude any job whose rust_target, sys_target and runner architecture disagree. Each architecture is built natively on a matching runner.

There is no RISC-V runner, so adding a bake target would mean running the compiler itself under emulation. Compiling for RISC-V is cheap; compiling as RISC-V is not. The recipe below cross-compiles instead, pinning the build stages to linux/amd64 and only the runtime stage to linux/riscv64.

Toolchain

The build needs a RISC-V cross toolchain with three properties, and one fix:

RequirementWhy
GCC 12 or newerRocksDB requires -std=c++20; GCC 9, which older musl cross images ship, does not accept it
libstdc++.a and libatomic.a for the targetThe static RocksDB link needs the first; jemalloc emits rustc-link-lib=atomic on any RISC-V target, because GCC opencodes __atomic_exchange_1 as a library call there
libclangrust-librocksdb-sys runs bindgen
Linux UAPI headers in the sysrootSee below

Most musl cross images ship no linux/ or asm/ include tree in their RISC-V sysroot, where their x86_64 sysroot carries several hundred headers. RocksDB’s env/io_posix.cc includes <linux/fs.h> unconditionally on Linux, so the build fails with fatal error: linux/fs.h: No such file or directory. Ubuntu packages the tree as linux-libc-dev-riscv64-cross. UAPI headers are independent of the C library, so the glibc cross package is the correct source for a musl sysroot.

Building a container image

Save this as Dockerfile.riscv64 and build it from the repository root. The repository .dockerignore already excludes target/ and .git.

# syntax=docker/dockerfile:1

ARG RUST_TARGET=riscv64gc-unknown-linux-musl
ARG SYSROOT=/usr/local/musl/riscv64-unknown-linux-musl

# The build stages are pinned to linux/amd64 rather than $BUILDPLATFORM because
# the cross image is published for amd64 only. On an amd64 host the compiler
# runs natively; elsewhere it runs under emulation, which is still far cheaper
# than emulating the compiler as a RISC-V binary.
FROM --platform=linux/amd64 messense/rust-musl-cross:riscv64-musl AS toolchain

ARG SYSROOT
RUN set -eux; \
    apt-get update; \
    apt-get install -y --no-install-recommends linux-libc-dev-riscv64-cross; \
    src="$(dpkg -L linux-libc-dev-riscv64-cross \
        | grep -m1 '/include/linux/fs\.h$' | sed 's|/linux/fs\.h$||')"; \
    cp -a "${src}/." "${SYSROOT}/include/"; \
    test -f "${SYSROOT}/include/linux/fs.h"; \
    test -d "${SYSROOT}/include/asm"

FROM toolchain AS build

WORKDIR /usr/src/tuwunel
COPY .cargo .cargo
COPY Cargo.toml Cargo.lock clippy.toml rustfmt.toml tuwunel-example.toml ./
COPY src src

ARG RUST_TARGET
ARG SYSROOT
ARG FEATURES="brotli_compression,cpu_affinity,element_hacks,email,gcs_storage,gzip_compression,jemalloc,jemalloc_conf,jwt_login,markdown,media_thumbnail,release_max_log_level,s3_storage,systemd,url_preview,zstd_compression"

# RUSTUP_TOOLCHAIN pins the toolchain the image already carries, so that
# rust-toolchain.toml does not send rustup after a same-versioned but
# differently named toolchain and its components.
#
# clang does not recognise the "riscv64gc" architecture that bindgen forwards
# from the Rust triple, and silently falls back to the host headers unless the
# clang triple and sysroot are given explicitly.
RUN --mount=type=cache,target=/root/.cargo/registry,sharing=locked \
    --mount=type=cache,target=/root/.cargo/git,sharing=locked \
    --mount=type=cache,target=/usr/src/tuwunel/target,sharing=locked \
    set -eux; \
    RUSTUP_TOOLCHAIN=stable \
    LIBCLANG_PATH=/usr/lib/x86_64-linux-gnu \
    ROCKSDB_STATIC=1 \
    BINDGEN_EXTRA_CLANG_ARGS="--target=riscv64-unknown-linux-musl --sysroot=${SYSROOT}" \
    cargo build --release --target "${RUST_TARGET}" -p tuwunel \
        --no-default-features --features "${FEATURES}"; \
    install -Dm755 "target/${RUST_TARGET}/release/tuwunel" /out/tuwunel

FROM --platform=linux/riscv64 alpine:latest AS runtime

RUN apk add --no-cache libstdc++ libgcc libatomic ca-certificates

COPY --from=build /out/tuwunel /usr/local/bin/tuwunel

RUN ["/usr/local/bin/tuwunel", "--version"]

EXPOSE 8008
ENTRYPOINT ["/usr/local/bin/tuwunel"]
docker buildx build --platform linux/riscv64 \
    -f Dockerfile.riscv64 -t tuwunel:riscv64 --load .

A cold build takes about fourteen minutes and produces a 45 MB image.

The RUN ["/usr/local/bin/tuwunel", "--version"] line executes under emulation during the build, so a binary that cannot run fails the build rather than shipping.

Both Alpine and Debian publish riscv64 base images, so either works for the runtime stage. Alpine is used here because the binary is linked against musl.

Running under emulation

No extra tooling is required if the host has binfmt_misc handlers registered for RISC-V, which Docker Desktop does by default. Confirm with:

docker buildx inspect | grep riscv64
docker run --rm --platform linux/riscv64 alpine uname -m

Then run the image as usual:

docker run --rm --platform linux/riscv64 -p 8008:8008 tuwunel:riscv64 \
    -O server_name='"example.com"' -O address='"0.0.0.0"' -O port=8008

Startup is unhurried but not slow: the database opens its 133 column families in roughly half a second and the server answers requests within about five seconds of launch.

Compiling with io_uring

The recipe above leaves io_uring out so that the image runs under emulation. The feature does compile and link for RISC-V, and the paragraphs below cover that, but treat it as a compile test only: user-mode emulation does not implement the io_uring syscalls, so none of this says the code works on real hardware.

Two things have to join the toolchain stage. The first is pkg-config, which the base image does not carry. The tree enables plain rust-rocksdb/io-uring, so librocksdb-sys takes the pkg_config::probe_library("liburing") path, and the pkg-config crate shells out to that binary; without it the build fails before it reaches the compiler. The second is liburing built for the target.

liburing has to be compiled with -fPIC. Its build reserves that flag for the shared library and compiles the archive’s objects without it, so linking the position independent executable this target produces otherwise fails with:

liburing.a(setup.ol): relocation R_RISCV_HI20 against `a local symbol' can not
be used when making a shared object; recompile with -fPIC

An x86_64 musl build never hits this, because that target is crt-static and does not produce a position independent executable.

Installing the archive and no shared object leaves -luring resolving to liburing.a, so the binary carries io_uring with no runtime liburing dependency.

RUN apt-get update; \
    apt-get install -y --no-install-recommends pkg-config curl ca-certificates; \
    rm -rf /var/lib/apt/lists/*

ARG LIBURING_VERSION=2.6
RUN set -eux; \
    cd /tmp; \
    curl -fSL "https://github.com/axboe/liburing/archive/refs/tags/liburing-${LIBURING_VERSION}.tar.gz" \
        -o liburing.tgz; \
    tar xf liburing.tgz; \
    cd "liburing-liburing-${LIBURING_VERSION}"; \
    ./configure \
        --cc=riscv64-unknown-linux-musl-gcc \
        --cxx=riscv64-unknown-linux-musl-g++ \
        --prefix="${SYSROOT}"; \
    make -C src liburing.a CC="riscv64-unknown-linux-musl-gcc -fPIC"; \
    install -Dm644 src/liburing.a "${SYSROOT}/lib/liburing.a"; \
    cp -a src/include/liburing.h src/include/liburing "${SYSROOT}/include/"; \
    mkdir -p "${SYSROOT}/lib/pkgconfig"; \
    printf '%s\n' \
        "prefix=${SYSROOT}" \
        'exec_prefix=${prefix}' \
        'libdir=${exec_prefix}/lib' \
        'includedir=${prefix}/include' \
        '' \
        'Name: liburing' \
        "Version: ${LIBURING_VERSION}" \
        'Description: io_uring library' \
        'Libs: -L${libdir} -luring' \
        'Cflags: -I${includedir}' \
        > "${SYSROOT}/lib/pkgconfig/liburing.pc"; \
    rm -rf /tmp/liburing*

Nothing further is needed to make the probe find it when cross-compiling: the cross image exports TARGET_PKG_CONFIG_LIBDIR and TARGET_PKG_CONFIG_ALLOW_CROSS, and the pkg-config crate honours the TARGET_ prefix. Add io_uring to FEATURES and the build proceeds.

Confirm the feature really compiled in rather than being quietly skipped, by looking for RocksDB’s io_uring code in the result:

$ strings -a tuwunel | grep -c io_uring_submit
10
$ strings -a tuwunel | grep -c FinalizeAsyncRead
1

Those message strings, and the rocksdb::FinalizeAsyncRead(io_uring*, io_uring_cqe*, ...) symbol beside them, exist only under ROCKSDB_IOURING_PRESENT. readelf -d should still list no liburing entry, which confirms the static link.

Differences from the shipped architectures

io_uring is off by default here. The recipe above omits it, so a RISC-V image built that way is not feature equivalent to an x86_64 or ARM64 one. It compiles when liburing is added, as described above, but has never been run.

The binary is dynamically linked. Unlike x86_64-unknown-linux-musl, the riscv64gc-unknown-linux-musl target does not enable crt-static by default, which is a property of the Rust target definition rather than of our build:

$ rustc --print cfg --target x86_64-unknown-linux-musl | grep crt-static
target_feature="crt-static"
$ rustc --print cfg --target riscv64gc-unknown-linux-musl | grep crt-static

The result needs musl plus the GCC runtime libraries at run time, which is why the runtime stage installs them. Adding -C target-feature=+crt-static should produce a static binary, at the cost of a full rebuild.

No CPU feature levels. The sys_target dimension has no RISC-V equivalent here. The build targets baseline rv64gc with no profile selection.

Adding it to the build matrix

Should CI ever gain a RISC-V runner, the changes to docker/bake.hcl are small:

  • a riscv64-v1-linux-gnu value for sys_target, which the existing sys_target_triple, sys_target_ver and sys_target_isa helpers already parse correctly
  • a ["linux/riscv64"] branch in the platforms expression on the system target
  • -C link-arg=-l:libatomic.a in the static rustflags, as the RISC-V analogue of the libgcc.a entry that ARM64 carries
  • plain -ftls-model=initial-exec in rocksdb_cxx_flags, with neither ARM64’s -mno-outline-atomics nor x86_64’s -mpclmul
  • no -C target-cpu=, which is set for x86_64 only

The base layers would also need every apt package they install to exist for riscv64.

32-bit ARM

Tuwunel compiles and runs on 32-bit ARM. This is a working port, not a supported platform: nothing in the CI matrix builds it, and no release artifact is published for it. This page records how to reproduce the build and the things that differ from the architectures we do ship.

Verified against 1.8.3 on armv7-unknown-linux-gnueabihf. The resulting server opens its database and answers the client and federation version endpoints under emulation.

Why it is not in the build matrix

Every layer in docker/bake.hcl inherits its platform from the system target, which declares platforms exactly once. A bake target therefore builds its whole toolchain and runs its compile inside a container of the target platform, and the workflow matrices exclude any job whose rust_target, sys_target and runner architecture disagree. Each architecture is built natively on a matching runner.

There is no 32-bit ARM runner, so adding a bake target would mean running the compiler itself under emulation. The recipe below cross-compiles instead, pinning the build stages to linux/amd64 and only the runtime stage to linux/arm/v7.

Toolchain

Use Debian’s armhf cross toolchain, not a musl one. The rest of this section explains why, because the musl route looks correct and fails late.

Debian armhf is ARMv7-A with VFPv3-D16 throughout, which is also what actual 32-bit ARM deployments run, and its GCC and libstdc++ agree with each other:

$ arm-linux-gnueabihf-g++ -dM -E -x c++ /dev/null | grep -E '__ARM_ARCH |LOCK_FREE'
#define __ARM_ARCH 7
#define __GCC_ATOMIC_INT_LOCK_FREE 2

messense/rust-musl-cross:armv7-musleabihf, the image the RISC-V recipe uses for its own architecture, ships a GCC whose default architecture is ARMv5TE despite the ARMv7 tag. Its configure line sets the float ABI but never --with-arch or --with-fpu, so GCC falls back to its built-in ARM default:

$ armv7-unknown-linux-musleabihf-g++ -dM -E -x c++ /dev/null | grep -E '__ARM_ARCH |LOCK_FREE'
#define __ARM_ARCH 5
#define __GCC_ATOMIC_INT_LOCK_FREE 1

Everything in that image’s sysroot is built at that baseline, libstdc++.a included. Because libstdc++-v3/src/c++11/futex.cc is guarded on ATOMIC_INT_LOCK_FREE > 1, it compiles to an empty object there: futex.o is present in the archive but defines no __atomic_futex_unsigned_base symbols at all. Any C++ compiled at ARMv7, where integer atomics are lock free, takes the futex path in <future> and cannot be linked against it. Three RocksDB translation units use std::future, so the failure is unavoidable, and it arrives at the final link after everything has compiled.

A three line program reproduces it without any of our code:

#include <future>
#include <cstdio>
int main() { std::promise<int> p; auto f = p.get_future(); f.wait(); printf("%d\n", f.get()); }
$ armv7-unknown-linux-musleabihf-g++ -O2 -std=c++20 t.cc -o t
$ armv7-unknown-linux-musleabihf-g++ -O2 -std=c++20 -march=armv7-a -mfpu=vfpv3-d16 t.cc -o t
undefined reference to `std::__atomic_futex_unsigned_base::_M_futex_wait_until(...)'
undefined reference to `std::__atomic_futex_unsigned_base::_M_futex_notify_all(unsigned int*)'

The same family’s aarch64-musl image is unaffected, so this is a property of that ARM32 configuration rather than of musl cross toolchains in general. Dropping -mfpu=vfpv3-d16 fails earlier still, with “selected architecture lacks an FPU”, because --with-fpu is unset as well.

The practical consequence is that this port is glibc rather than musl, and the binary is therefore dynamically linked. That is the opposite of what the target itself suggests: unlike riscv64gc-unknown-linux-musl, the musl ARM targets do default crt-static on, so a static build would be the natural outcome if a correctly configured toolchain were available.

Building a container image

Save this as Dockerfile.armv7 and build it from the repository root. The repository .dockerignore already excludes target/ and .git.

# syntax=docker/dockerfile:1

ARG RUST_TARGET=armv7-unknown-linux-gnueabihf
ARG CROSS=arm-linux-gnueabihf
ARG SYSROOT=/usr/arm-linux-gnueabihf

# The build stages are pinned to linux/amd64 rather than $BUILDPLATFORM so that
# the compiler runs natively on an amd64 host. Elsewhere it runs under
# emulation, which is still far cheaper than emulating the compiler as a 32-bit
# ARM binary.
FROM --platform=linux/amd64 rust:1.95.0-bookworm AS toolchain

ARG RUST_TARGET
ARG CROSS

RUN set -eux; \
    apt-get update; \
    apt-get install -y --no-install-recommends \
        g++-arm-linux-gnueabihf libclang-dev clang cmake; \
    rustup target add "${RUST_TARGET}"

# Assert the properties this toolchain is chosen for rather than trusting the
# package name, since the musl image's tag is exactly what misleads.
RUN set -eux; \
    "${CROSS}-g++" -dM -E -x c++ /dev/null | grep -qx '#define __ARM_ARCH 7'; \
    "${CROSS}-g++" -dM -E -x c++ /dev/null | grep -qx '#define __GCC_ATOMIC_INT_LOCK_FREE 2'; \
    find / -name libstdc++.a -path "*${CROSS}*" -print -quit \
        | xargs "${CROSS}-nm" --defined-only | grep -q _M_futex_wait_until

FROM toolchain AS build

WORKDIR /usr/src/tuwunel
COPY .cargo .cargo
COPY Cargo.toml Cargo.lock clippy.toml rustfmt.toml tuwunel-example.toml ./
COPY src src

ARG RUST_TARGET
ARG CROSS
ARG SYSROOT
ARG FEATURES="brotli_compression,cpu_affinity,element_hacks,email,gcs_storage,gzip_compression,jemalloc,jemalloc_conf,jwt_login,markdown,media_thumbnail,release_max_log_level,s3_storage,systemd,url_preview,zstd_compression"

# Pinning the clang triple and sysroot matters more here than on a 64-bit
# target: if bindgen fell back to the host headers it would generate bindings
# with 64-bit long and size_t for an ILP32 target, which links but is wrong.
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
    --mount=type=cache,target=/usr/local/cargo/git,sharing=locked \
    --mount=type=cache,target=/usr/src/tuwunel/target,sharing=locked \
    set -eux; \
    CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER="${CROSS}-gcc" \
    CC_armv7_unknown_linux_gnueabihf="${CROSS}-gcc" \
    CXX_armv7_unknown_linux_gnueabihf="${CROSS}-g++" \
    AR_armv7_unknown_linux_gnueabihf="${CROSS}-ar" \
    LIBCLANG_PATH=/usr/lib/llvm-14/lib \
    ROCKSDB_STATIC=1 \
    BINDGEN_EXTRA_CLANG_ARGS="--target=${CROSS} --sysroot=${SYSROOT}" \
    cargo build --release --target "${RUST_TARGET}" -p tuwunel \
        --no-default-features --features "${FEATURES}"; \
    install -Dm755 "target/${RUST_TARGET}/release/tuwunel" /out/tuwunel

FROM --platform=linux/arm/v7 debian:bookworm-slim AS runtime

RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates \
    && rm -rf /var/lib/apt/lists/*

COPY --from=build /out/tuwunel /usr/local/bin/tuwunel

RUN ["/usr/local/bin/tuwunel", "--version"]

ENV TUWUNEL_DATABASE_PATH=/var/lib/tuwunel
VOLUME /var/lib/tuwunel
EXPOSE 8008
ENTRYPOINT ["/usr/local/bin/tuwunel"]
docker buildx build --platform linux/arm/v7 \
    -f Dockerfile.armv7 -t tuwunel:armv7 --load .

A cold build takes about an hour on an ARM64 host, where the build stages themselves run under amd64 emulation, and produces a 216 MB image holding a 74 MB binary. The RUN ["/usr/local/bin/tuwunel", "--version"] line executes under emulation during the build, so a binary that cannot run fails the build rather than shipping.

The runtime stage uses Debian rather than Alpine because the binary is linked against glibc.

Running under emulation

No extra tooling is required if the host has binfmt_misc handlers registered for 32-bit ARM, which Docker Desktop does by default. Note that docker buildx inspect under-reports here and may omit linux/arm/v7 from its platform list even when it works, so confirm by running something instead:

docker run --rm --platform linux/arm/v7 debian:bookworm-slim uname -m

That prints armv7l. Then run the image as usual:

docker run --rm --platform linux/arm/v7 -p 8008:8008 tuwunel:armv7 \
    -O server_name='"example.com"' -O address='"0.0.0.0"' -O port=8008

Startup is unhurried but not slow: the database opens its 133 column families in about two and a quarter seconds, and the server answers requests within about nine seconds of launch.

Compiling with io_uring

The recipe above leaves io_uring out so that the image runs under emulation. The feature does compile and link for 32-bit ARM, and this section covers that, but treat it as a compile test only: user-mode emulation does not implement the io_uring syscalls, so none of it says the code works on real hardware.

Two things have to join the toolchain stage. The first is pkg-config. The tree enables plain rust-rocksdb/io-uring, so librocksdb-sys takes the pkg_config::probe_library("liburing") path, and the pkg-config crate shells out to that binary. The second is liburing built for the target.

liburing has to be compiled with -fPIC. Its build reserves that flag for the shared library and compiles the archive’s objects without it, which does not suit the position independent executable this target produces. Installing the archive and no shared object leaves -luring resolving to liburing.a, so the binary carries io_uring with no runtime liburing dependency.

RUN apt-get update; \
    apt-get install -y --no-install-recommends pkg-config curl ca-certificates

ARG LIBURING_VERSION=2.6
RUN set -eux; \
    cd /tmp; \
    curl -fSL "https://github.com/axboe/liburing/archive/refs/tags/liburing-${LIBURING_VERSION}.tar.gz" \
        -o liburing.tgz; \
    tar xf liburing.tgz; \
    cd "liburing-liburing-${LIBURING_VERSION}"; \
    ./configure --cc="${CROSS}-gcc" --cxx="${CROSS}-g++" --prefix="${SYSROOT}"; \
    make -C src liburing.a CC="${CROSS}-gcc -fPIC"; \
    install -Dm644 src/liburing.a "${SYSROOT}/lib/liburing.a"; \
    cp -a src/include/liburing.h src/include/liburing "${SYSROOT}/include/"; \
    mkdir -p "${SYSROOT}/lib/pkgconfig"; \
    printf '%s\n' \
        "prefix=${SYSROOT}" \
        'exec_prefix=${prefix}' \
        'libdir=${exec_prefix}/lib' \
        'includedir=${prefix}/include' \
        '' \
        'Name: liburing' \
        "Version: ${LIBURING_VERSION}" \
        'Description: io_uring library' \
        'Libs: -L${libdir} -luring' \
        'Cflags: -I${includedir}' \
        > "${SYSROOT}/lib/pkgconfig/liburing.pc"; \
    rm -rf /tmp/liburing*

Unlike the musl cross images, this base exports no TARGET_PKG_CONFIG_LIBDIR and TARGET_PKG_CONFIG_ALLOW_CROSS, so the probe has to be pointed at the target’s pkgconfig directory itself. Add these to the build environment alongside io_uring in FEATURES, and leave PKG_CONFIG_SYSROOT_DIR unset, since the generated liburing.pc already carries an absolute prefix:

    PKG_CONFIG_ALLOW_CROSS=1 \
    PKG_CONFIG_LIBDIR="${SYSROOT}/lib/pkgconfig" \

Confirm the feature really compiled in rather than being quietly skipped by looking for RocksDB’s io_uring code in the result. These message strings exist only under ROCKSDB_IOURING_PRESENT:

$ strings -a tuwunel | grep -c io_uring_submit
10

readelf -d should still list no liburing entry, which confirms the static link:

$ arm-linux-gnueabihf-readelf -d tuwunel | grep NEEDED
 0x00000001 (NEEDED)   Shared library: [libstdc++.so.6]
 0x00000001 (NEEDED)   Shared library: [libgcc_s.so.1]
 0x00000001 (NEEDED)   Shared library: [libm.so.6]
 0x00000001 (NEEDED)   Shared library: [libc.so.6]

Differences from the shipped architectures

The address space is the operating limit. A 32-bit process has a user address space of a few gigabytes no matter how much memory the machine has, and that ceiling, not the installed RAM, is what bounds the caches. Several defaults scale with the host’s parallelism rather than its memory, so a board with many cores and little address space is the awkward case: db_cache_capacity_mb, db_write_buffer_capacity_mb, pdu_cache_capacity and auth_chain_cache_capacity all grow with the core count, and cache_capacity_modifier scales the caches as a group. Expect to set these explicitly rather than relying on the defaults.

The binary is dynamically linked. It needs glibc plus the GCC runtime libraries, which is a consequence of the toolchain situation described above rather than a property of the target:

$ ldd /usr/local/bin/tuwunel
        libstdc++.so.6 => /lib/arm-linux-gnueabihf/libstdc++.so.6
        libgcc_s.so.1 => /lib/arm-linux-gnueabihf/libgcc_s.so.1
        libm.so.6 => /lib/arm-linux-gnueabihf/libm.so.6
        libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6
        /lib/ld-linux-armhf.so.3

time_t is 32 bits on this baseline. Debian bookworm’s armhf port predates the 64-bit time_t transition and defines __TIMESIZE 32:

$ arm-linux-gnueabihf-gcc -E -dM -x c /dev/null | grep __TIMESIZE
#define __TIMESIZE 32

Rust’s own time handling does not go through glibc’s time_t, so this reaches only RocksDB and the rest of the C++ in the graph, and it has not been traced to a concrete failure here. Building with -D_FILE_OFFSET_BITS=64 -D_TIME_BITS=64 widens it, and a base image newer than bookworm carries the widened type already. Worth knowing before running a 32-bit ARM server long enough for 2038 to matter.

io_uring is off here. The recipe omits it, so a 32-bit ARM image built this way is not feature equivalent to an x86_64 or ARM64 one. It does compile and link, as described below, but has never been run.

No CPU feature levels. The sys_target dimension has no 32-bit ARM equivalent here. The build targets the Debian armhf baseline, ARMv7-A with VFPv3-D16, and selects no profile above it.

ARMv6 needs a toolchain neither route provides. Rust defines targets for it, and the Raspberry Pi 1 and Zero need them, but no build has been produced here because both candidate toolchains rule themselves out.

The musl image for that target, arm-musleabihf, carries the same defect as its ARMv7 sibling. The cc crate compiles for arm-unknown-linux-musleabihf with -march=armv6 -marm -mfpu=vfp, which is ARMv6 with lock free integer atomics, so it takes the futex path and fails against that ARMv5TE libstdc++.a exactly as described above.

The Debian toolchain used here cannot target ARMv6 either, because its runtime libraries are built for the armhf port baseline:

$ arm-linux-gnueabihf-readelf -A /usr/arm-linux-gnueabihf/lib/libstdc++.so.6.0.30
  Tag_CPU_name: "7-A"
  Tag_CPU_arch: v7
  Tag_FP_arch: VFPv3-D16

Compiling our own code at ARMv6 would still link against that, and the result would fault on ARMv6 hardware: the library contains over a thousand dmb instructions, which ARMv6 does not implement. An ARMv6 port therefore needs a toolchain whose C++ runtime is built at that baseline, such as the one Raspberry Pi OS ships.

Adding it to the build matrix

Should CI ever gain a 32-bit ARM runner, the changes to docker/bake.hcl follow the shape the ARM64 entries already have: an armv7-v7-linux-gnu value for sys_target, a ["linux/arm/v7"] branch in the platforms expression on the system target, and -ftls-model=initial-exec in rocksdb_cxx_flags without ARM64’s -mno-outline-atomics or x86_64’s -mpclmul. The -l:libgcc.a entry ARM64 carries is needed here too, since 32-bit ARM resolves helper routines through libgcc that the hardware has no instruction for, __aeabi_uldivmod and the rest of the integer division family among them.

The base layers would also need every apt package they install to exist for armhf, and the address space limits above make a 32-bit runner a poor host for the test suite even once it builds.

Contributor Covenant Code of Conduct

Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

Our Standards

Examples of behavior that contributes to a positive environment for our community include:

  • Demonstrating empathy and kindness toward other people.
  • Being respectful of differing opinions, viewpoints, and experiences.
  • Giving and gracefully accepting constructive feedback.
  • Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience.
  • Focusing on what is best not just for us as individuals, but for the overall community.

Examples of unacceptable behavior include:

  • The use of sexualized language or imagery, and sexual attention or advances of any kind.
  • Trolling, insulting or derogatory comments, and personal or political attacks.
  • Public or private harassment.
  • Publishing others’ private information, such as a physical or email address, without their explicit permission.
  • Other conduct which could reasonably be considered inappropriate in a professional setting.

Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.

Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.

Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement over encrypted DM to <@jason:tuwunel.chat>, <@june:vern.cc>, <@dasha_uwu:linuxping.win> or over email to jasonzemos@gmail.com.

All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident.

Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:

1. Correction

Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.

Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.

2. Warning

Community Impact: A violation through a single incident or series of actions.

Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.

3. Temporary Ban

Community Impact: A serious violation of community standards, including sustained inappropriate behavior.

Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

4. Permanent Ban

Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

Consequence: A permanent ban from any sort of public interaction within the community.

Attribution

This Code of Conduct is adapted from the Contributor Covenant, version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.

Community Impact Guidelines were inspired by Mozilla’s code of conduct enforcement ladder.

For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.