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

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