diff --git a/.agent/skills/merovingian-review/SKILL.md b/.agent/skills/merovingian-review/SKILL.md
index 2165f5383..1257f194b 100644
--- a/.agent/skills/merovingian-review/SKILL.md
+++ b/.agent/skills/merovingian-review/SKILL.md
@@ -1,6 +1,6 @@
---
name: merovingian-review
-description: "Review a Merovingian pull request, branch or local diff against this project's binding rules: docs/coding-rules.md, the security coding rules, the per-module AGENTS.md invariants, the Matrix v1.19 spec, and the change obligations (CHANGELOG, docs, ADR, version bump, PR headings). It targets the defect classes this project has actually shipped. Use when asked to review a PR, branch, diff or commit in this repository, to check a change before merge, to verify a subagent's or another session's work, or to post review comments on a Merovingian PR."
+description: "Review a Merovingian pull request, branch or local diff against this project's binding rules: docs/coding-rules.md, the security coding rules, the per-module AGENTS.md invariants, the Matrix v1.19 spec, and the change obligations (CHANGELOG, docs, ADR, version and PR headings). It targets the defect classes this project has actually shipped. Use when asked to review a PR, branch, diff or commit in this repository, to check a change before merge, to verify a subagent's or another session's work, or to post review comments on a Merovingian PR."
---
# Merovingian review
@@ -22,7 +22,7 @@ against this skill.
| [references/rule-checks.md](references/rule-checks.md) | Grep-able rule checks and judgement checks from the coding and security rules |
| [references/recurring-defects.md](references/recurring-defects.md) | Defect classes this project has shipped and fixed, as questions to ask of a diff |
| [references/tests.md](references/tests.md) | Where a test belongs, required structure, what the gates catch and miss, how to run and read tests |
-| [references/obligations.md](references/obligations.md) | CHANGELOG, docs, ADR, version bump, PR description: rules and commands |
+| [references/obligations.md](references/obligations.md) | CHANGELOG, docs, ADR, version, PR description: rules and commands |
## Modes
@@ -192,7 +192,7 @@ under Verification as not reviewed.
| Tag | Meaning in this project | Blocks merge |
|---|---|---|
| **[Blocker]** | Wrong result, auth or signature bypass, a worker-trust violation, data loss, a crash, a deadlock or timeout, an unbounded cost reachable by an unprivileged client or remote, a weakened conformance assertion, a broken build or test | Yes |
-| **[Major]** | Real defect on a plausible path; incomplete fix; behaviour without a test that fails if reverted; missing CHANGELOG, docs, ADR or version bump the project rules require | Yes, unless the author shows it is wrong |
+| **[Major]** | Real defect on a plausible path; incomplete fix; behaviour without a test that fails if reverted; missing CHANGELOG, docs or ADR the project rules require, or a version change the owner did not ask for | Yes, unless the author shows it is wrong |
| **[Minor]** | Correct but fragile, unclear or wasteful; a missing negative-path test on non-security code; doc drift | No |
| **[Nit]** | Wording, naming, or style no tool owns | Never; collapse them |
@@ -260,10 +260,10 @@ One or two sentences: what the change does, and whether the diff supports what i
## Obligations
| Item | State | Evidence |
-| CHANGELOG bullet in current version, right section | | |
+| CHANGELOG bullet in the newest version's entry, right section | | |
| Docs per docs/AGENTS.md table | | |
| ADR (needed? numbered above all branches? index line?) | | |
-| Version bump (or docs-only exemption) and all places agree | | |
+| Version unchanged from the base unless the owner asked (ADR-0835), and all places agree | | |
| PR description headings | | |
## Evidence log
diff --git a/.agent/skills/merovingian-review/references/module-invariants.md b/.agent/skills/merovingian-review/references/module-invariants.md
index 32e82193c..923ed6f25 100644
--- a/.agent/skills/merovingian-review/references/module-invariants.md
+++ b/.agent/skills/merovingian-review/references/module-invariants.md
@@ -103,6 +103,8 @@ look at every time. Read the `AGENTS.md` itself before judging a change to that
tests. `src/database/AGENTS.md#Security rules — non-negotiable`
- Every BLOB write sets `BoundValue::binary`.
- One transaction is one pooled lease. Never take a second lease while holding one: that deadlocks (ADR-0154).
+ SQLite has exactly one write connection; a change that lets it open more brings back writes refused after
+ SQLite's 5 s busy timeout (ADR-0834).
- A read that combines several tables into one picture of a room runs in one read transaction (ADR-0161).
Federated join writes are single transactions (ADR-0714).
- Reads go by index, never scan. `PersistentStore` mutexes follow ADR-0517. A member added to `PersistentStore`
diff --git a/.agent/skills/merovingian-review/references/obligations.md b/.agent/skills/merovingian-review/references/obligations.md
index cb52df884..c66861ec3 100644
--- a/.agent/skills/merovingian-review/references/obligations.md
+++ b/.agent/skills/merovingian-review/references/obligations.md
@@ -13,24 +13,22 @@ ADR-0000/0001/0543/0740/0741. Only the formats are checked by tooling (`test_cha
upgrading.
- The bullet says what changed for the operator or client, not how, and ends with its ADR or finding ID.
- `CHANGELOG-pre-release.md` is frozen (ADR-0740). Any diff to it is a finding.
-- A docs-only branch adds its bullets to the **current** version's entry and does not bump.
+- Every branch adds its bullets to the **newest** version's entry; it opens a new entry only when the owner asked
+ for a new version (ADR-0835).
## Version
-- One bump per branch, BUILD + 1, except documentation-only changes (ADR-0464). `AGENTS.md` and coding-guidance
- edits count as documentation. Any code, build, packaging or test change means the bump applies.
+- The version changes only when the owner asks (ADR-0835). A branch whose version differs from its base's, with no
+ request from the owner in its PR or linked discussion, is a finding, whatever the branch changes.
- Every place agrees with `meson.build`. The list is in `docs/versioning.md`: `src/main.cpp`,
`src/db_migrate.cpp`, the FreeBSD manifest, the NetBSD Makefile, three RPM specs (each also with a new dated
- `%changelog` entry), the `scripts/build-*.sh` scripts, and the CHANGELOG heading.
-- The number must not be taken by another open branch. Check before approving.
+ `%changelog` entry when the version changes), the `scripts/build-*.sh` scripts, and the CHANGELOG heading.
```bash
-git show origin/main:meson.build | grep -m1 "version:"; grep -m1 "version:" meson.build
+git show :meson.build | grep -m1 "version:"; grep -m1 "version:" meson.build
grep -n 'version = std::string_view' src/main.cpp src/db_migrate.cpp
grep -n '^Version:' packaging/{rpm,rhel,opensuse}/merovingian.spec
grep -nE '^VERSION=' scripts/build-*.sh
-for r in $(git for-each-ref --format='%(refname)' refs/remotes/origin); do
- git show "$r:meson.build" 2>/dev/null | grep -m1 -o "version: '[^']*'" | sed "s|^|$r |"; done | sort -k3 | tail
```
## Docs
diff --git a/AGENTS.md b/AGENTS.md
index d4aae725e..a553e603b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -27,7 +27,9 @@ report any unresolved conflict or unmet requirement. See
- Flag potential bugs or edge cases after the code explanation if relevant.
- With every change, update the relevant docs. See [docs/AGENTS.md](docs/AGENTS.md) for the update table.
- Before creating a new branch from main, pull from origin so that main is up to date.
-- Bump the version number on creating a new branch, except for documentation-only changes. See versioning doc for all the places where the version number needs updating.
+- Never change the version number unless the owner asks for it; a new branch keeps its base's version, and its
+ CHANGELOG bullets go in the newest version's entry. See the [bump policy](docs/versioning.md#bump-policy) and
+ [ADR-0835](docs/adr/0835-the-version-changes-only-when-the-owner-asks.md).
- Update the docs when code change invalidates something.
- Record a decision in the ADR register (`docs/adr/`) whenever you make one. A
decision qualifies when a future reader would otherwise be likely to undo it
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57f9ea3ed..1cde09836 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,43 @@ Changes from 1.0.0, the first production release, onwards; the format is set out
Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md), which is no longer added to
([ADR-0740](docs/adr/0740-the-changelog-starts-at-1-0-0-and-the-pre-release-entries-are-a-frozen-record.md)).
+# Version 1.1.3
+
+## Features
+
+* MatrixRTC calls on LiveKit need no `lk-jwt-service`: `POST .../rtc/livekit/get_token` (MSC4195) issues tokens to
+ joined users; `server.rtc.livekit.url`, `api_url`, `api_key` and `api_secret_file` turn it on (ADR-0829, ADR-0830).
+* A token for another server's SFU is relayed to it over federation, and other servers' joined users get subscribe-only
+ tokens for this server's SFU, judged by the main process and refused to a server the room's ACL denies (ADR-0831).
+* `delegate_delayed_leave` (MSC4195): this server sends a caller's delayed leave once LiveKit no longer shows them,
+ checked every 30 s and sooner on LiveKit's signed webhook, kept across restarts (ADR-0832, ADR-0833).
+* A branch no longer bumps the version: it changes only when the owner asks, and a change adds its bullets to the
+ newest version's entry here (ADR-0835).
+
+## Security Fixes
+
+* LiveKit tokens are HS256, signed only by typed functions that cannot grant room creation, administration or hidden
+ participants; the API secret is read per token and never logged (ADR-0828).
+* LiveKit's webhook is believed only when signed with the API secret for its exact body and recent, and even then only
+ brings a check forward: it never sends or restarts an event (ADR-0833).
+* The federation worker refuses to start if a Landlock rule would let it read the LiveKit API secret file (ADR-0062).
+* A LiveKit call's host lookup counts against the call's deadline: the exchange gets only the time the lookup left,
+ and none starts once the deadline has passed (ADR-0830).
+
+## Bug fixes
+
+* `use_state_after`: a room forked at `since` now gets exactly what changed since what the client was told, read from an
+ in-memory log of state changes, and so does a left room (ADR-0827).
+* SQLite writes share one connection, whatever `database.pool_size` says: a second write connection waited for the
+ first's lock by polling, lost to its back-to-back commits and was refused after 5 s, failing the write (ADR-0834).
+
+## Release notes
+
+Version 1.1.3 is in progress: a LiveKit token service built into the server for MatrixRTC calls, with delegated leaves,
+and an exact `state_after` on `/sync`. It adds migration 004 (`livekit_delegations`). After a restart, the first
+`state_after` sync of each room with news carries its whole state once. A SQLite server no longer refuses writes under
+sustained write load, and `database.pool_size` now applies to PostgreSQL only.
+
# Version 1.1.2
## Features
diff --git a/config/merovingian.conf.bsd.example b/config/merovingian.conf.bsd.example
index c98f366e2..43d0a9f0f 100644
--- a/config/merovingian.conf.bsd.example
+++ b/config/merovingian.conf.bsd.example
@@ -147,8 +147,22 @@ server.http.ipv6_client_prefix_length=64
# server.turn.shared_secret_file=@SYSCONFDIR@/merovingian/turn-secret
# server.turn.ttl_seconds=86400
-# MatrixRTC group calls (optional)
-# The HTTPS URL of an lk-jwt-service (Element's LiveKit authorisation service) that you run beside a LiveKit SFU.
+# MatrixRTC group calls (optional). Choose one of the two ways below; setting both is refused.
+#
+# 1. The built-in token service (MSC4195; restart required). This server hands each caller joined to a room a
+# LiveKit token for your LiveKit SFU, so you run LiveKit only. Set all four of url, api_url, api_key and
+# api_secret_file, or none; a partial set is refused.
+# The SFU address clients connect to: wss, a host, no query or fragment, no trailing slash.
+# server.rtc.livekit.url=wss://livekit.example.org
+# Where this server calls LiveKit's room service: https, or http only to 127.0.0.1 or [::1].
+# server.rtc.livekit.api_url=https://livekit.example.org
+# server.rtc.livekit.api_key=APIexamplekey
+# An owner-only (0400) file holding the API secret, at least 32 bytes, read for each token and never kept.
+# server.rtc.livekit.api_secret_file=@SYSCONFDIR@/merovingian/livekit-secret
+# How long a token can be used to join: 60s to 3600s.
+# server.rtc.livekit.token_lifetime=3600s
+#
+# 2. An external lk-jwt-service (Element's LiveKit authorisation service) that you run beside a LiveKit SFU.
# This server never contacts it: it only tells authenticated clients, and the /.well-known/matrix/client
# document, where it is. Empty means no group-call transport is advertised. Reloadable.
# Clients append /sfu/get or /get_token to it, so write it with no trailing slash and no query: a URL ending in /
diff --git a/config/merovingian.conf.example b/config/merovingian.conf.example
index f8016723d..caa5fbaed 100644
--- a/config/merovingian.conf.example
+++ b/config/merovingian.conf.example
@@ -120,8 +120,22 @@ server.http.ipv6_client_prefix_length=64
# server.turn.shared_secret_file=/etc/merovingian/turn-secret
# server.turn.ttl_seconds=86400
-# MatrixRTC group calls (optional)
-# The HTTPS URL of an lk-jwt-service (Element's LiveKit authorisation service) that you run beside a LiveKit SFU.
+# MatrixRTC group calls (optional). Choose one of the two ways below; setting both is refused.
+#
+# 1. The built-in token service (MSC4195; restart required). This server hands each caller joined to a room a
+# LiveKit token for your LiveKit SFU, so you run LiveKit only. Set all four of url, api_url, api_key and
+# api_secret_file, or none; a partial set is refused.
+# The SFU address clients connect to: wss, a host, no query or fragment, no trailing slash.
+# server.rtc.livekit.url=wss://livekit.example.org
+# Where this server calls LiveKit's room service: https, or http only to 127.0.0.1 or [::1].
+# server.rtc.livekit.api_url=https://livekit.example.org
+# server.rtc.livekit.api_key=APIexamplekey
+# An owner-only (0400) file holding the API secret, at least 32 bytes, read for each token and never kept.
+# server.rtc.livekit.api_secret_file=/etc/merovingian/livekit-secret
+# How long a token can be used to join: 60s to 3600s.
+# server.rtc.livekit.token_lifetime=3600s
+#
+# 2. An external lk-jwt-service (Element's LiveKit authorisation service) that you run beside a LiveKit SFU.
# This server never contacts it: it only tells authenticated clients, and the /.well-known/matrix/client
# document, where it is. Empty means no group-call transport is advertised. Reloadable.
# Clients append /sfu/get or /get_token to it, so write it with no trailing slash and no query: a URL ending in /
diff --git a/docs/AGENTS.md b/docs/AGENTS.md
index dc1bb6946..caf3f462c 100644
--- a/docs/AGENTS.md
+++ b/docs/AGENTS.md
@@ -8,7 +8,7 @@ new documents.
| Document | What to add/update |
|---|---|
-| `../CHANGELOG.md` (repo root) | Describe what changed. Add a new `# Version X.Y.Z` entry when the version changes, with exactly the headings `## Features`, `## Security Fixes`, `## Bug fixes` and `## Release notes`: bullets of two lines at most, and one short release-notes paragraph ([changelog format](versioning.md#changelog-format), [ADR-0741](adr/0741-each-changelog-version-has-features-security-fixes-bug-fixes-and-release-notes.md)). Documentation-only changes add bullets to the current version's entry without a bump. Never add to `../CHANGELOG-pre-release.md`, the frozen record of the 0.x series ([ADR-0740](adr/0740-the-changelog-starts-at-1-0-0-and-the-pre-release-entries-are-a-frozen-record.md)). |
+| `../CHANGELOG.md` (repo root) | Describe what changed. Add a new `# Version X.Y.Z` entry only when the owner asks for a new version, with exactly the headings `## Features`, `## Security Fixes`, `## Bug fixes` and `## Release notes`: bullets of two lines at most, and one short release-notes paragraph ([changelog format](versioning.md#changelog-format), [ADR-0741](adr/0741-each-changelog-version-has-features-security-fixes-bug-fixes-and-release-notes.md)). Every other change, documentation-only or not, adds bullets to the newest version's entry and never changes the version ([ADR-0835](adr/0835-the-version-changes-only-when-the-owner-asks.md)). Never add to `../CHANGELOG-pre-release.md`, the frozen record of the 0.x series ([ADR-0740](adr/0740-the-changelog-starts-at-1-0-0-and-the-pre-release-entries-are-a-frozen-record.md)). |
## Update when the matching domain changes
@@ -17,7 +17,7 @@ new documents.
| `coding-rules.md` | A project-wide coding rule is added, changed, or removed. Maintain the rule here; the root `AGENTS.md` requires this document rather than copying its rules. |
| `security-coding-rules.md` | A security-relevant rule is added, changed, or removed in any module `AGENTS.md` file |
| `testing-standards.md` | A new testing convention is adopted |
-| `versioning.md` | Version scheme changes; see also the version bump table |
+| `versioning.md` | Version scheme or bump policy changes; see also its table of version locations |
| `auth-identity.md` | Auth, session token, or identity changes |
| `crypto-boundary.md` | Crypto interface, key management, or signing changes |
| `database-persistence.md` | Schema changes (migrations), store interface changes |
diff --git a/docs/adr/0062-federation-worker-holds-no-secret-files-secrets-arrive-over-inherited-fds.md b/docs/adr/0062-federation-worker-holds-no-secret-files-secrets-arrive-over-inherited-fds.md
index 5b181b41a..db69a2f23 100644
--- a/docs/adr/0062-federation-worker-holds-no-secret-files-secrets-arrive-over-inherited-fds.md
+++ b/docs/adr/0062-federation-worker-holds-no-secret-files-secrets-arrive-over-inherited-fds.md
@@ -621,8 +621,9 @@ in the rule set" is not enough: the required read-write grant on the SQLite
database's *directory* would silently expose a master key an operator placed
beside the database. At startup, before applying the ruleset, the worker
checks every rule against `platform::worker_landlock_secret_paths()` (the
-master key, both TLS private keys, both database URI files, and the
-registration token file) with `platform::find_landlock_rule_covering_secret`,
+master key, both TLS private keys, both database URI files, the
+registration token file, the SMTP password file, the TURN shared secret, the LiveKit API secret
+file (ADR-0830) and the appservice registration files) with `platform::find_landlock_rule_covering_secret`,
and refuses to start if any rule equals or is an ancestor of one. Paths are
compared by component after `std::filesystem::weakly_canonical`, matching
how the kernel resolves the rule's path, so a symlink cannot hide an overlap
diff --git a/docs/adr/0154-pool-database-write-connections.md b/docs/adr/0154-pool-database-write-connections.md
index 9723e3485..14c3bff0f 100644
--- a/docs/adr/0154-pool-database-write-connections.md
+++ b/docs/adr/0154-pool-database-write-connections.md
@@ -48,3 +48,8 @@ copies of it; `bootstrap_local_database` applies `database.pool_size` through
a fresh connection dying mid-transaction always did.
* A replaced SQLite file is not reopened by pooled handles until restart (they keep the file they
opened, which is also what the DB-10 no-follow checks protected).
+
+## Links
+
+* Refined by [ADR-0834](0834-sqlite-writes-share-one-pooled-connection.md): SQLite writes use one pooled connection,
+ because the busy timeout does not absorb contention between this process's own connections.
diff --git a/docs/adr/0349-an-outbound-answer-main-does-not-verify-comes-over-mains-own-connection.md b/docs/adr/0349-an-outbound-answer-main-does-not-verify-comes-over-mains-own-connection.md
index 5b9dc82aa..d161b0391 100644
--- a/docs/adr/0349-an-outbound-answer-main-does-not-verify-comes-over-mains-own-connection.md
+++ b/docs/adr/0349-an-outbound-answer-main-does-not-verify-comes-over-mains-own-connection.md
@@ -65,6 +65,7 @@ signed material.
| `federation.backfill.state_ids_failed` | the IDs name the state a later event is judged against | no (the PDUs they lead to are verified, the choice of IDs is not) | direct |
| `timestamp_to_event.ask` | the event ID and timestamp decide which event is offered | no (the event is verified, the choice is not) | direct |
| `space_hierarchy.fetch` | room summaries shown to the client | no | direct |
+| `livekit.relay` | relays a LiveKit token and SFU URL from the server the client named; a 403/400 is relayed | no | direct |
| `room.join.remote.make_join_failed` | keeps the template's `prev_events`, `auth_events`, `depth`, content | no | direct |
| `room.join.remote.send_join_failed` | state and auth chain, and the status | per event only | direct |
| `room.leave.remote.make_leave_failed` | template; a 403/404 ends an invite locally | no | direct |
diff --git a/docs/adr/0464-documentation-only-changes-do-not-require-a-version-bump.md b/docs/adr/0464-documentation-only-changes-do-not-require-a-version-bump.md
index 1f4401053..e5f3ce37b 100644
--- a/docs/adr/0464-documentation-only-changes-do-not-require-a-version-bump.md
+++ b/docs/adr/0464-documentation-only-changes-do-not-require-a-version-bump.md
@@ -1,6 +1,6 @@
# Documentation-only changes do not require a version bump
-* Status: accepted
+* Status: superseded by [ADR-0835](0835-the-version-changes-only-when-the-owner-asks.md)
* Date: 2026-11-05
## Context and Problem Statement
@@ -32,3 +32,7 @@ The maintained policy is in [versioning](../versioning.md#bump-policy).
### Negative Consequences
* Authors must check whether later changes make a branch more than documentation-only.
+
+## Links
+
+* Superseded by [ADR-0835](0835-the-version-changes-only-when-the-owner-asks.md)
diff --git a/docs/adr/0647-versions-from-1-0-0-are-major-minor-build.md b/docs/adr/0647-versions-from-1-0-0-are-major-minor-build.md
index 370816fd5..b1b0d6dea 100644
--- a/docs/adr/0647-versions-from-1-0-0-are-major-minor-build.md
+++ b/docs/adr/0647-versions-from-1-0-0-are-major-minor-build.md
@@ -1,6 +1,6 @@
# Versions from 1.0.0 are MAJOR.MINOR.BUILD
-* Status: accepted
+* Status: accepted; its per-branch `BUILD` increment is superseded by [ADR-0835](0835-the-version-changes-only-when-the-owner-asks.md)
* Date: 2026-11-11
## Context and Problem Statement
@@ -43,4 +43,5 @@ Chosen option: "`MAJOR.MINOR.BUILD`".
## Links
* Supersedes [ADR-0047](0047-keep-project-phase-out-of-the-version-string.md)
+* Partly superseded by [ADR-0835](0835-the-version-changes-only-when-the-owner-asks.md): the per-branch `BUILD` increment
* [docs/versioning.md](../versioning.md)
diff --git a/docs/adr/0819-a-state-after-delta-compares-the-two-states.md b/docs/adr/0819-a-state-after-delta-compares-the-two-states.md
index 663bfac96..e95eced11 100644
--- a/docs/adr/0819-a-state-after-delta-compares-the-two-states.md
+++ b/docs/adr/0819-a-state-after-delta-compares-the-two-states.md
@@ -1,6 +1,6 @@
# A `state_after` delta compares the two states, and every change it finds is sent under lazy-loading
-* Status: accepted
+* Status: accepted (the baseline at `since` and the chain walk are superseded by [ADR-0827](0827-a-state-after-delta-is-measured-from-an-in-memory-log-of-resolved-state-changes.md); the lazy-loading rules stand)
* Date: 2026-11-16
## Context and Problem Statement
diff --git a/docs/adr/0822-the-rtc-transport-is-advertised-as-type-livekit-with-livekit-service-url.md b/docs/adr/0822-the-rtc-transport-is-advertised-as-type-livekit-with-livekit-service-url.md
index dd7a1bfb2..96f915fd7 100644
--- a/docs/adr/0822-the-rtc-transport-is-advertised-as-type-livekit-with-livekit-service-url.md
+++ b/docs/adr/0822-the-rtc-transport-is-advertised-as-type-livekit-with-livekit-service-url.md
@@ -33,6 +33,9 @@ Element Call understand only that type.
A future reader must not "fix" the type to the MSC's stable name `m.livekit` without also adding the token
endpoints.
+*Superseded in part by [ADR-0829](0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md):
+the token endpoints exist for the built-in service. With it configured, the transport is `{"type":"livekit","url":...}`,
+and the stable answer also lists `m.livekit`. The external service is still advertised as this record says.*
## Pros and Cons of the Options
diff --git a/docs/adr/0827-a-state-after-delta-is-measured-from-an-in-memory-log-of-resolved-state-changes.md b/docs/adr/0827-a-state-after-delta-is-measured-from-an-in-memory-log-of-resolved-state-changes.md
new file mode 100644
index 000000000..cf57b83ca
--- /dev/null
+++ b/docs/adr/0827-a-state-after-delta-is-measured-from-an-in-memory-log-of-resolved-state-changes.md
@@ -0,0 +1,133 @@
+# A `state_after` delta is measured from an in-memory log of resolved state changes
+
+* Status: accepted
+* Date: 2026-11-17
+
+Technical Story: review of 1.1.1, https://github.com/OMG-Software/Merovingian/pull/595#discussion_r4593957508
+
+## Context and Problem Statement
+
+[ADR-0819](0819-a-state-after-delta-compares-the-two-states.md)
+measured an incremental `state_after` from the state recorded for the newest event at or below `since`. A client is
+told the room's *resolved* state, which on a forked room is not that event's recorded state. Take a fork at `since`
+whose resolution picks branch A while the newest event records branch B:
+
+1. The client is told A.
+2. Resolution later moves the key to B.
+3. The delta compares B with B and sends nothing.
+
+The client keeps A for ever, and `state_after` exists so that a client can stop reading state from the timeline.
+
+A backfilled event ordered at or below `since` can stand in for the anchor in the same way. The left-room delta had the
+same baseline.
+
+How can a delta be exact against what the client was told, at the cost rules of `src/sync/AGENTS.md`?
+
+- A room with no news costs nothing.
+- There is no whole-state read on the common path.
+- There is no per-request scan of a room's rows under `runtime.mutex`.
+
+## Decision Drivers
+
+* The delta must equal the difference between the state told at `since` and the state told now, for every graph shape.
+* A window of messages must read no state.
+* Every writer of current state already runs under `runtime.mutex` in the main process, as does every sync.
+
+## Considered Options
+
+* Store each response's state per token (refused in ADR-0819 for its cost)
+* Send the whole state whenever the room is forked
+* A persisted table of state changes (migration 004)
+* An in-memory log of resolved state changes, keyed by the sync position from which a client sees each one
+
+## Decision Outcome
+
+Chosen option: the in-memory log, `database::StateChangeLog` (`PersistentStore::state_change_log`), read through
+`sync::resolved_state_at`, `sync::resolved_state_changes` and `sync::resolved_state_event_at`.
+
+* **What is recorded.** Every change to a room's current state in the main process is recorded: room, key, previous
+ event and new event.
+ - Every such change goes through one of four store functions, and each records: `apply_store_event_with_state`,
+ `apply_current_state`, `store_state` and `remove_current_state_rows`.
+ - `apply_room_snapshot` forgets the room instead (a reload replaces the room's state wholesale).
+ - The federation worker never starts the log, so it records nothing.
+* **Where a change is filed.** A change is filed at the stream ordering of the event whose storing made it, raised to
+ one above the highest position a sync has answered at (`note_served`, called where `sync_json` fixes
+ `sync_position`).
+ - So no change is ever filed at or below a position a client was already told about.
+ - The state as of a served position is therefore fixed once served: the current state, with each key changed above
+ the position put back to the value its first such change replaced.
+ - A backfilled event ordered below `since` is filed above it.
+* **Why the delta is exact.** The state told at `since` and the state told now are both read from this one record, so
+ their difference is exact. Specifically:
+ - A key that state resolution moved back is found.
+ - A key that changed and changed back is not sent.
+ - A key removed from the state is not sent, since `state_after` cannot express a removal.
+ - The whole-state answers (an initial sync, `full_state=true`, a join in the window) are the same rebuilt state, so
+ a later delta starts from what was really said.
+ - A lazy-loaded sender's member as of the position is looked up the same way.
+* **Left rooms.** A left room's delta is the state readable as of the leave (`room_read_access_for`, unchanged) minus the
+ state told at `since`.
+* **News check.** `select_sync_rooms` counts a logged change above `since` as news for a `state_after` client, because
+ a change with no event of its own in the room is still a change.
+* **Cost.**
+ - A delta reads the room's changes above `since`, counted in the log's `rows_examined`, plus one lookup by key per
+ key they name: nothing for a window of messages.
+ - `has_change_after` is one map lookup.
+ - Rebuilding a whole state reads the room's state rows once, which is what the whole-state answers already did.
+* **What is not covered.** The log covers a position only above the position the process started at, and only at or
+ above a room's horizon. A position outside that falls back as follows:
+ - A `since` at or below the start was answered by an earlier process, or comes from a database restored or upgraded
+ from one, so it is never trusted for a delta. The room's whole resolved state is sent once (an update the client
+ already holds is harmless), and the next sync is a delta again. Upgraded databases need nothing more.
+ - When the log does not cover the position itself, the state ADR-0247 reads is sent. A delta from that position is
+ then never taken, so the two cannot disagree.
+* **Bounds.**
+ - At most 1,024 changes per room and 65,536 in all. Past either bound the oldest change is dropped.
+ - Dropping a room's change raises that room's horizon: a `since` below it is not covered, and the room's whole
+ state is sent once.
+
+This supersedes the part of ADR-0819 that chose the baseline and the chain walk (`state_changes_along_chain`, now
+removed). ADR-0819's lazy-loading rules stand.
+
+### Positive Consequences
+
+* The delta is exact against what each response said, for forks, resolutions that move a key back, and backfill.
+* A window of messages costs nothing. No migration, and no write to any transaction.
+
+### Negative Consequences
+
+* After a restart, the first `state_after` sync of each room with news sends that room's whole state once.
+* A change made with no event that raises the stream (for example a state group recorded later for an old event) is
+ filed above the last served position, and reaches clients when the stream next moves. As before, this happens as soon
+ as any event is stored anywhere on the server. If the process stops first, the change waits for the room's next
+ event, which is then sent with the room's whole state.
+* The log uses memory: at most 65,536 changes of a few event IDs each.
+
+## Pros and Cons of the Options
+
+### Store each response's state per token
+
+* Bad, because it costs a room's whole state per response, per device.
+
+### Send the whole state whenever the room is forked
+
+* Bad, because a room that stays forked (common over federation) would send its whole state on every sync.
+
+### A persisted table of state changes (migration 004)
+
+* Good, because a restart would not cost one whole state per room.
+* Bad, because it needs a migration on both backends, a row in every writer's transaction (including state
+ resolution's corrections), its own bound and pruning, worker classification and an upgrade answer. The answer for an
+ upgraded database would still be "send the whole state once", so the gain is only the first sync after each restart.
+
+### An in-memory log
+
+* Good, because it is exact, costs nothing for a window of messages, and touches no schema.
+* Bad, because it starts empty at every start-up (see Negative Consequences).
+
+## Links
+
+* Supersedes the baseline and the chain walk of [ADR-0819](0819-a-state-after-delta-compares-the-two-states.md)
+* Keeps the access rule of [ADR-0820](0820-a-left-rooms-state-after-stops-at-what-the-user-may-read.md)
+* Relates to [ADR-0247](0247-no-sync-position-passes-a-stream-ordering-still-being-committed.md)
diff --git a/docs/adr/0828-livekit-tokens-are-signed-and-verified-only-through-typed-hs256-functions-in-the-crypto-boundary.md b/docs/adr/0828-livekit-tokens-are-signed-and-verified-only-through-typed-hs256-functions-in-the-crypto-boundary.md
new file mode 100644
index 000000000..4a6c2f8d9
--- /dev/null
+++ b/docs/adr/0828-livekit-tokens-are-signed-and-verified-only-through-typed-hs256-functions-in-the-crypto-boundary.md
@@ -0,0 +1,91 @@
+# LiveKit tokens are signed and verified only through typed HS256 functions in the crypto boundary
+
+* Status: accepted
+* Date: 2026-11-17
+
+## Context and Problem Statement
+
+The built-in MatrixRTC token service (MSC4195) hands clients LiveKit access tokens and calls LiveKit's room service,
+and LiveKit signs the webhooks it sends. All three are JSON Web Tokens signed with HS256 (HMAC-SHA256) under the
+LiveKit API secret. The project has HMAC-SHA1 for coturn only (ADR-0480) and no HMAC-SHA256, and a general
+"sign these bytes" function would let any later code mint tokens with any rights, under the one secret that controls
+the SFU.
+
+## Decision Drivers
+
+* A token never grants `roomCreate` to a participant, `roomAdmin`, `hidden`, or any right this server did not decide on.
+* No new dependency, and no hand-written primitive.
+* A webhook is accepted only under a MAC check that cannot be steered by the token itself.
+
+## Considered Options
+
+* A general `hmac_sha256(key, message)` and a JWT builder outside the crypto boundary.
+* OpenSSL's `HMAC` with `EVP_sha256()`, as `hmac_sha1` uses.
+* Typed signers and one verifier in `src/crypto/LiveKitToken.cpp`, over libsodium's `crypto_auth_hmacsha256`.
+
+## Decision Outcome
+
+Chosen option: typed signers and one verifier over libsodium, because no caller can widen what a token says, and
+libsodium's HMAC-SHA256 is already in the build.
+
+* `crypto/LiveKitToken.hpp` declares exactly four operations:
+ * `sign_livekit_participant_token(api_key, api_secret, LiveKitParticipantGrant)`. The grant type holds the MSC4195
+ identity and room name, one `can_publish` flag (which sets `canPublish` and `canPublishData` together), and
+ `nbf`/`exp`. It has no field for `roomCreate`, `roomAdmin`, `roomList`, `roomRecord`, `ingressAdmin`, `hidden`,
+ `canUpdateOwnMetadata`, a name, metadata or attributes, so no participant token can carry them. `roomJoin` and
+ `canSubscribe` are always true.
+ * `sign_livekit_room_create_token(api_key, api_secret, nbf, exp)`: `video` is `{"roomCreate":true}` and nothing else,
+ with no `sub` and no `room`. It is used for `CreateRoom` only.
+ * `sign_livekit_room_admin_token(api_key, api_secret, room_name, nbf, exp)`: `video` is `{"room":,
+ "roomAdmin":true}` and nothing else, with no `sub`. LiveKit limits `roomAdmin` to the room named, and the room name
+ must be an MSC4195 name (43 standard base64 characters). It is used for `GetParticipant` only, by MSC4195's
+ delegated delayed leave.
+ * `verify_hs256_token(token, secret)`, for LiveKit's webhook requests. It bounds the token at 4,096 bytes, requires
+ exactly three non-empty unpadded URL-safe base64 segments, computes HMAC-SHA256 over the first two segments as
+ received, and compares it with the third in constant time (`constant_time_equal`, 32 bytes). It decodes the header
+ and payload only after the MAC matches, returns them undecided, and never reads the header's `alg`: an
+ `alg: none` or any other algorithm claim cannot change what is checked. The caller judges every claim.
+* The HMAC is libsodium's `crypto_auth_hmacsha256_init`/`update`/`final`, which takes a key of any length, as RFC 7518
+ section 3.2 requires. It stays in an anonymous namespace; the state is wiped after use. It is not exported.
+* Every value placed in a token is checked before it is written, so the JSON needs no escaping:
+ * the API key is 1 to 128 ASCII letters, digits, `_`, `-` and `.`;
+ * the identity and room are 43 characters of the standard base64 alphabet;
+ * `nbf` is not negative and `exp` is after it.
+* The payload's keys are in lexical order. Its characters cannot form a base64 group of 62 or 63, so the encoded
+ payload has no `-` or `_`. Element Call reads it with `atob`, which knows only the standard alphabet, so the signer
+ refuses (rather than emits) a payload that would contain either.
+* The secret must be at least 32 bytes, for signing and verifying alike. The caller reads it per use from its file into
+ a `core::SecretBuffer`. This file holds no secret.
+* HMAC-SHA1 stays for coturn alone (ADR-0480). Nothing here uses it.
+
+### Positive Consequences
+
+* A participant token's rights are fixed by a type, and the tests pin the exact bytes of every token kind against
+ vectors computed apart from this code (Python's `hmac`). The verifier is checked against RFC 7515 Appendix A.1.
+* A future LiveKit call that needs a different grant must add a typed signer here, under review, and record the
+ call in an ADR.
+
+### Negative Consequences
+
+* A new LiveKit grant cannot be added from the homeserver module alone. That is the point: the one-room `roomAdmin`
+ token for `GetParticipant` was added here, with its own vector, when the delegated delayed leave needed it.
+
+## Pros and Cons of the Options
+
+### A general HMAC-SHA256 and a JWT builder outside the boundary
+
+* Good, because it is flexible.
+* Bad, because any caller could sign a token with `roomAdmin` or `hidden` under the SFU's secret.
+
+### OpenSSL `HMAC` with SHA-256
+
+* Good, because it matches `hmac_sha1`.
+* Bad, because libsodium already offers HMAC-SHA256 with an arbitrary-length key, and the boundary prefers libsodium
+ where it has the primitive (ADR-0014); OpenSSL was admitted for SHA-1 only because libsodium has none.
+
+## Links
+
+* Refines [ADR-0480](0480-turn-credentials-come-from-a-coturn-shared-secret-file-through-an-openssl-hmac-sha1.md) and [ADR-0014](0014-confine-cryptographic-primitives-behind-providers.md)
+* [MSC4195](https://github.com/matrix-org/matrix-spec-proposals/blob/6d49798949e1b31023565d4ff1c7fe10f4cacf83/proposals/4195-matrixrtc-livekit.md)
+* [RFC 7515 Appendix A.1](https://www.rfc-editor.org/rfc/rfc7515#appendix-A.1),
+ [RFC 7518 section 3.2](https://www.rfc-editor.org/rfc/rfc7518#section-3.2)
diff --git a/docs/adr/0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md b/docs/adr/0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md
new file mode 100644
index 000000000..682b3a798
--- /dev/null
+++ b/docs/adr/0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md
@@ -0,0 +1,151 @@
+# The built-in LiveKit token service issues tokens only to users this server finds joined
+
+* Status: accepted
+* Date: 2026-11-17
+
+Technical Story: MatrixRTC slice 4. The owner chose the homeserver flow only, the external service kept but mutually
+exclusive, users of other servers relayed out and admitted subscribe-only, and delegated delayed leave implemented.
+
+## Context and Problem Statement
+
+ADR-0822 lets the operator name an external MatrixRTC authorisation service (Element's `lk-jwt-service`). MSC4195 also
+lets the homeserver issue LiveKit tokens itself (`POST .../rtc/livekit/get_token`), so no second service, OpenID
+round trip or application service is needed. Issuing them means:
+
+* holding the LiveKit API secret, the one secret that controls the SFU;
+* deciding who may join which LiveKit room;
+* calling LiveKit.
+
+Released Element Call (0.28.2) uses this "homeserver flow" for a transport that has a `url` and no
+`livekit_service_url`. It sends `POST /_matrix/client/unstable/io.element.msc4195/rtc/livekit/get_token` with
+`{url, room_id, slot_id, member_id, server_name}` and connects to the transport's `url` with the `jwt` it gets back.
+
+## Decision Drivers
+
+* A token goes only to a caller this server authenticated and finds joined to the room, by its own current state, never
+ by anything the request claims.
+* The SFU never sees a Matrix ID or room ID.
+* The secret is never held for the life of the process, logged, or put in a response.
+* Nothing a request carries decides where this server connects.
+
+## Considered Options
+
+* Keep only the external service (ADR-0822).
+* The built-in service, alongside the external one, both allowed at once.
+* The built-in service, or the external one, never both.
+
+## Decision Outcome
+
+Chosen option: "the built-in service, or the external one, never both". Two ways to authorise calls would leave it
+unclear which one a client is sent to, so a configuration with both is refused at start-up.
+
+### Configuration
+
+The keys below are all restart-required, read at start-up, and refused, never repaired, by `validate()`:
+
+| Key | Rule |
+|---|---|
+| `server.rtc.livekit.url` | The SFU's `wss` URL |
+| `server.rtc.livekit.api_url` | `https`, or `http` only to a loopback IP literal |
+| `server.rtc.livekit.api_key` | 1 to 128 of `A-Za-z0-9_-.` |
+| `server.rtc.livekit.api_secret_file` | An owner-only file; the start-up check is `validate_existing_secret_file_metadata`, as for every secret file |
+| `server.rtc.livekit.token_lifetime` | 60 s to 1 h, default 1 h |
+
+* The four keys `url`, `api_url`, `api_key` and `api_secret_file` go together.
+* With `server.rtc.livekit.service_url` they are refused.
+* The secret is read for each token with `platform::read_secure_secret_line` into a `core::SecretBuffer`, used to sign,
+ and wiped before the response. The `crypto/LiveKitToken` signers refuse a secret shorter than 32 bytes (ADR-0828), so
+ a short one is a 500 and an error log naming no secret.
+
+### Advertisement
+
+* `GET .../rtc/transports` lists `{"type":"livekit","url":}`. The stable path also lists
+ `{"type":"m.livekit","url":...}` after it; MSC4195 names that type, and released clients read only `livekit`.
+* `org.matrix.msc4143.rtc_foci` in the well-known document stays for the external service only. The clients that read
+ it know only the OpenID flow.
+* `/versions` gains `org.matrix.msc4195` and `org.matrix.msc4195.stable`. Each is true exactly when the routes are
+ served.
+
+### Routes
+
+* `POST /_matrix/client/v1/rtc/livekit/get_token` and its unstable `io.element.msc4195` path, authenticated.
+ * A locked account gets the gate's 401.
+ * A suspended account gets the gate's 403 `M_USER_SUSPENDED`: joining a call is participation.
+ * Without the built-in service the route answers 404 `M_UNRECOGNIZED`.
+* The body is a JSON object with string members `url` (at most 2048 bytes), `room_id`, `slot_id` and `member_id` (each
+ 1 to 255 bytes, valid for JSON, `room_id` starting `!`), and an optional `server_name`.
+ * A missing member is 400 `M_MISSING_PARAM`.
+ * Anything else wrong is 400 `M_INVALID_PARAM`.
+ * A body that is not an object is 400 `M_BAD_JSON`.
+* `server_name` absent or equal to this server's name asks for this server's SFU.
+ * `url` must then equal `server.rtc.livekit.url` byte for byte, else 400 `M_INVALID_PARAM` (MSC4195). It is never
+ fetched.
+ * Another server's name is relayed to that server over federation, as ADR-0831 describes; its `url` is that
+ server's to judge.
+
+### Authorisation
+
+* The caller's `memberships` row for `room_id` must say `join`.
+ * That row is this server's projection of the room's current `m.room.member` state, written in the same transaction
+ as the event (ADR-0126).
+ * An unknown room and a room the caller is not joined to are the same 403 `M_FORBIDDEN`.
+ * No field of the request is consulted.
+* The caller's own token always has `canPublish` and `canPublishData` true.
+* Rate limit: 60 a minute per user on each path (built in, `client_rate_limits.per_user.` overrides). The global
+ bound is the ADR-0079 outbound budget each token's LiveKit call takes.
+
+### Names
+
+* The LiveKit room is `base64nopad(SHA-256(canonical JSON [room_id, slot_id]))`.
+* The identity is the same over `[user_id, member_id]`, as MSC4195 specifies and its vectors test.
+* The one exception is the slot `m.call#ROOM`, which is hashed as `m.call#room`. Released Element Call sends the first
+ on the unstable path, MSC4195 names the second, and lk-jwt-service folds them so old and new clients meet in one
+ LiveKit room. No other value is folded.
+
+### Calling LiveKit
+
+* Before a publishing token is issued, the room is created with `CreateRoom` (MSC4195), as ADR-0830 describes.
+* The call takes an ADR-0079 slot first (none is 429 `M_LIMIT_EXCEEDED` with `retry_after_ms`) and runs under one
+ 10-second deadline, clamped by `remote_timeout`.
+* `runtime.mutex` is released for the call only.
+* Any failure (unreachable, timeout, a non-200 answer, an answer over 16 KiB) is 502 `M_UNKNOWN`, and no token is
+ issued.
+
+### Answer and logging
+
+* The answer is `{"jwt": }`.
+* The `livekit` logger records `livekit.token.issued`, `livekit.token.refused`, `livekit.create_room_failed` and
+ `livekit.secret_unavailable`. Each carries `user_id` and `room_id`, and a reason where there is one. It never
+ records the token, the secret, the slot or the member ID (which carries a device ID).
+
+### Positive Consequences
+
+* A deployment needs only LiveKit: no `lk-jwt-service`, no application service registration, no OpenID exchange, and
+ no second copy of the secret.
+* Who may join is decided by the server that holds the room state.
+
+### Negative Consequences
+
+* This server now holds the LiveKit API secret, and the threat model records it.
+* The OpenID flow (`/sfu/get`) is not served. A client that knows only that flow needs the external service.
+
+## Pros and Cons of the Options
+
+### Keep only the external service
+
+* Good, because the secret stays out of this process.
+* Bad, because the external service decides membership by asking the homeserver over OpenID and a well-known lookup.
+ It runs as an application service to do delegated leave, and its identity for `/sfu/get` is the raw Matrix ID.
+
+### Both at once
+
+* Bad, because a client is told about one of two, and the operator cannot tell which.
+
+## Links
+
+* Supersedes in part [ADR-0822](0822-the-rtc-transport-is-advertised-as-type-livekit-with-livekit-service-url.md),
+ which said there is no `/rtc/livekit/*` route; its external service keeps working unchanged.
+* Refined by [ADR-0830](0830-every-call-to-livekit-goes-to-the-configured-address-with-a-token-of-its-own.md) and
+ [ADR-0831](0831-a-federated-livekit-token-request-is-judged-by-main-and-answered-subscribe-only.md)
+* [ADR-0828](0828-livekit-tokens-are-signed-and-verified-only-through-typed-hs256-functions-in-the-crypto-boundary.md)
+* [MSC4195](https://github.com/matrix-org/matrix-spec-proposals/blob/6d49798949e1b31023565d4ff1c7fe10f4cacf83/proposals/4195-matrixrtc-livekit.md)
diff --git a/docs/adr/0830-every-call-to-livekit-goes-to-the-configured-address-with-a-token-of-its-own.md b/docs/adr/0830-every-call-to-livekit-goes-to-the-configured-address-with-a-token-of-its-own.md
new file mode 100644
index 000000000..cd31b21b4
--- /dev/null
+++ b/docs/adr/0830-every-call-to-livekit-goes-to-the-configured-address-with-a-token-of-its-own.md
@@ -0,0 +1,79 @@
+# Every call to LiveKit goes to the configured address with a token of its own
+
+* Status: accepted
+* Date: 2026-11-17
+
+## Context and Problem Statement
+
+The built-in token service (ADR-0829) calls LiveKit's room service. Each call is signed with the API secret, so a call
+to the wrong address would hand that address a token valid on the SFU. A call is also an outbound request made on a
+client's behalf, with what that costs the request pool. This record lists every call and the rules each follows; a new
+call is added here.
+
+## Decision Outcome
+
+### Where a call goes
+
+* A call goes only to `server.rtc.livekit.api_url`, never to an address a request names.
+* Each request builder (`livekit_create_room_request`, `livekit_get_participant_request`) parses the URL again with
+ `http::parse_outbound_url` and holds it to the configuration's rule (`https`, or `http` to a loopback IP literal). It rebuilds the URL from the parsed parts with an
+ explicit port and appends `/twirp/livekit.RoomService/`.
+* `perform_livekit_request` resolves the host with `discovery.upstream().lookup_addresses`, the operator-trusted lookup
+ the application service client uses (ADR-0515). The connection is pinned to the addresses found.
+ * The lookup and the exchange draw from one `OutboundDeadline` of the call's `timeout_seconds`: the exchange gets
+ only what the lookup left, and none is started once it is spent (a timeout). A slow lookup therefore never adds a
+ whole exchange to the call. The lookup itself is a blocking `getaddrinfo` that the deadline cannot interrupt: a
+ resolver slower than the whole budget still holds the thread, the ADR-0079 slot or the job until it answers, as
+ it does for every other caller of `lookup_addresses`.
+ * The SSRF-filtered lookup is not used: the operator chose the address, and LiveKit commonly runs on the same host or
+ LAN.
+* TLS verification is always on and redirects are refused (`http::OutboundClient`).
+
+### How a call is made
+
+* `CreateRoom` is made from a client request with an ADR-0079 slot held, under one deadline, and with `runtime.mutex`
+ released around the call only (`src/homeserver/AGENTS.md`).
+* `GetParticipant` is made by the "livekit-delegations" job (ADR-0832), on its own thread, never from a client request:
+ it holds no request thread and so takes no ADR-0079 slot. The job takes `runtime.mutex` before and after its calls,
+ never during one; each call has 10 seconds, and one run makes at most 16 (`livekit_delegation_checks_per_run`).
+* At most 16 KiB of answer is read (`livekit_response_max_bytes`). Nothing in an answer is returned to a client. Of
+ `CreateRoom`'s answer only the HTTP status is read; of `GetParticipant`'s only the status, the Twirp error `code`
+ and the participant's `state`, which decide whether a delayed event is restarted, sent or left alone.
+
+### What each call may do
+
+* Each call carries its own Twirp bearer token. The token is signed by a typed function in `crypto/LiveKitToken`
+ (ADR-0828), is valid for 60 seconds, and grants only what that call needs.
+
+| Call | Method | Grant | When |
+|---|---|---|---|
+| Create the room | `POST /twirp/livekit.RoomService/CreateRoom`, body `{"name", "empty_timeout": 300, "departure_timeout": 20}` | `video.roomCreate` only | Before a publishing token is issued (MSC4195 MUST) |
+| Look up one participant | `POST /twirp/livekit.RoomService/GetParticipant`, body `{"room", "identity"}` (MSC4195 names) | `video.room` (that room) and `video.roomAdmin` | Each check of a delegated delayed leave (ADR-0832) |
+
+LiveKit has no grant narrower than `roomAdmin` for `GetParticipant`, so that token could also act on participants of
+its one room for its one minute. It is accepted because it names one room, is sent only to the configured address over
+verified TLS (or to a loopback address), and is never stored or logged; this server sends it with `GetParticipant`
+alone. No call removes a participant, ends a room, changes permissions or reads metadata. Adding one is a change to this
+record and a new typed signer, and a call that acts against a participant (for example `RemoveParticipant`) needs the
+owner's decision first.
+
+### Tests
+
+* `HomeserverRuntime::test_livekit_perform` stands in for LiveKit. It is handed the finished request, token included,
+ and returns LiveKit's answer, so tests check the address, the method, the grant and the body without a network.
+
+### Positive Consequences
+
+* A leaked `CreateRoom` token can create a room for one minute and nothing else; a leaked `GetParticipant` token acts
+ on one room for one minute.
+
+### Negative Consequences
+
+* Each publishing token costs one round trip to LiveKit while a request thread waits. The slot and the deadline bound
+ it.
+
+## Links
+
+* Refined by [ADR-0832](0832-a-delegated-delayed-leave-is-restarted-while-livekit-shows-the-participant-and-sent-once-it-does-not.md)
+* Refines [ADR-0829](0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md)
+* [ADR-0079](0079-client-triggered-outbound-proxying-runs-under-a-bounded-in-flight-budget.md)
diff --git a/docs/adr/0831-a-federated-livekit-token-request-is-judged-by-main-and-answered-subscribe-only.md b/docs/adr/0831-a-federated-livekit-token-request-is-judged-by-main-and-answered-subscribe-only.md
new file mode 100644
index 000000000..18ed3ebc4
--- /dev/null
+++ b/docs/adr/0831-a-federated-livekit-token-request-is-judged-by-main-and-answered-subscribe-only.md
@@ -0,0 +1,131 @@
+# A federated LiveKit token request is judged by main and answered subscribe-only
+
+* Status: accepted
+* Date: 2026-11-17
+
+Technical Story: MatrixRTC slice 4. The owner chose "relay out, subscribe-only in".
+
+## Context and Problem Statement
+
+In MSC4195 a client asks its own server for a token for another server's SFU. Its server relays the request to that
+server's `POST /_matrix/federation/v1/rtc/livekit/get_token`, adding `user_id`. The receiving server must refuse:
+
+* when it is not joined to the room (403 `M_FORBIDDEN`);
+* when `user_id` is not of the origin (403 `M_FORBIDDEN`);
+* when the user is not joined (403 `M_FORBIDDEN`);
+* when `url` is not its SFU (400 `M_INVALID_PARAM`).
+
+The relaying server passes 403 `M_FORBIDDEN` and 400 `M_INVALID_PARAM` back to the client, and turns anything else
+into 502 `M_UNKNOWN`.
+
+On this server, inbound federation is parsed by the federation worker. The worker holds no secret and signs nothing
+(ADR-0078). The LiveKit API secret is main's (ADR-0829).
+
+## Decision Drivers
+
+* The worker never sees the API secret and never signs a token.
+* A token goes only to a user this server's own state shows joined, for an origin main verified. Nothing the worker
+ says is believed.
+* A request from another server does not make this server call anything.
+* What this server relays out goes only to a server its state shows in the room, under the client-outbound bounds.
+
+## Decision Outcome
+
+### Inbound: `POST /_matrix/federation/{v1,unstable/io.element.msc4195}/rtc/livekit/get_token`
+
+1. Main verifies the X-Matrix signature in `FederationProxy::handle` and gives the forwarded request one relay permit
+ (ADR-0595). The permit is `WorkerRelayKind::livekit_token` over the request body.
+2. The worker routes the request and relays it to main in a `livekit_token_ingest` frame carrying the body and the
+ origin.
+3. Main admits the frame only when the origin matches the pending request's verified origin
+ (`IpcChannel::matches_pending_origin`) and the body's digest consumes the permit (`consume_pending_relay`). A worker
+ cannot change the origin or the body, or replay a frame.
+4. Main judges the request with `issue_federation_livekit_token`, holding `runtime.mutex`, by its own state:
+ * this server is in the room (`room_state_is_current`: the create event is held and a local user is joined);
+ * the room's current `m.room.server_acl` allows the origin (`room_server_acl_allows`). The room is named in the
+ body, not the path, so the route-level ACL check in `InboundRequest.cpp` never sees it, and an ACL does not change
+ a membership: without this check a denied server whose user is still joined would get a token for the call;
+ * `user_id`'s server is the origin;
+ * the user's current `m.room.member` state is `join`;
+ * `url` is `server.rtc.livekit.url`, byte for byte.
+
+ The first four are one 403 `M_FORBIDDEN`, "No token can be issued for this user in this room.", so a server learns
+ nothing about a room it has no member in. The last is 400 `M_INVALID_PARAM`. A body naming a `server_name` other
+ than this server's is 400 too.
+5. The token is signed in main and returned to the worker, which answers it. The worker answers a refused frame
+ 403 `M_FORBIDDEN`.
+
+### A user of another server subscribes only
+
+* Its token has `canPublish` and `canPublishData` false: MSC4195 lets a server restrict publishing for users of other
+ servers, and this one's SFU carries only its own users' media.
+* No `CreateRoom` call is made for it. MSC4195 says the receiving server "creates the room (if needed)". This server
+ does not, so that a request from another server never makes it call LiveKit.
+* Nothing is lost by skipping the call. A subscriber has nothing to receive until a local user publishes, and that
+ user's own request creates the room. LiveKit's `auto_create` (on by default) covers the order where the subscriber
+ connects first.
+
+### Outbound: a client names another server
+
+When `server_name` is not this server's, `issue_client_livekit_token`:
+
+1. Requires the caller joined here (the same 403 as for this server's SFU).
+2. Requires the named server to have a member joined by this server's roster (`RoomMembers::has_member_of_server`),
+ and the room's server ACL to allow it, else 403 `M_FORBIDDEN` (MSC4195). A server the room denies is not asked.
+3. Takes an ADR-0079 slot (429 without one) and one deadline of 10 seconds, clamped by `remote_timeout`.
+4. Sends `{member_id, room_id, slot_id, url, user_id}` over signed federation (`perform_outbound_call`,
+ `OutboundAnswerTrust::unverified`, at most 8 KiB of answer) to the stable path only, with `runtime.mutex` released
+ for the call.
+5. Relays a 403 `M_FORBIDDEN` and a 400 `M_INVALID_PARAM` with this server's own text, never the other server's
+ (MSC4195: upstream answers are not shown to clients). Anything else is 502 `M_UNKNOWN`.
+6. Passes on only a `jwt` string that is three non-empty base64url segments of at most 4096 bytes. Its claims are the
+ other server's to vouch for; this server does not read them.
+
+The `url` is the other server's to judge and is never fetched here.
+
+### Bounds and logging
+
+* The inbound route is limited per verified origin by `security.federation.per_origin_request_rate`, as every
+ federation endpoint but `/send` is.
+* It costs one secret read and one signature, with no network call.
+* The outbound relay is the client route's own per-user limit (ADR-0829) and the ADR-0079 budget.
+* The `livekit` logger records:
+ * `livekit.federation.issued` (`origin`, `user_id`, `room_id`);
+ * `livekit.federation.refused` (with `reason`);
+ * `livekit.relay.issued` (with `server_name`);
+ * `livekit.relay.refused`;
+ * `livekit.relay.failed`.
+
+ It never records the token or the member ID.
+
+### Positive Consequences
+
+* A federated call works with the secret and the signing in main only, and every judgement is made by the server
+ holding the room state.
+
+### Negative Consequences
+
+* A remote user cannot publish on this server's SFU. A deployment where users of several servers share one SFU
+ needs each server to run its own.
+* No server is known to serve the federation route yet, so the outbound relay has been tested only against this
+ server.
+
+## Pros and Cons of the Options
+
+### Answer the inbound route in main without the worker (`federation_request_should_bypass_worker`)
+
+* Good, because no frame or permit is needed.
+* Bad, because the owner asked for the ADR-0595 relay. Inbound federation is routed by the worker, and main admits
+ only what a permit binds.
+
+### Issue remote users publishing tokens and create the room for them
+
+* Good, because it follows MSC4195's default (SHOULD).
+* Bad, because another server could then make this server call LiveKit and put media on its SFU.
+
+## Links
+
+* Refines [ADR-0829](0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md)
+* [ADR-0595](0595-bind-worker-key-claim-and-query-relays-to-the-verified-request-by-digest.md)
+* [ADR-0078](0078-the-federation-worker-never-signs.md)
+* [ADR-0079](0079-client-triggered-outbound-proxying-runs-under-a-bounded-in-flight-budget.md)
diff --git a/docs/adr/0832-a-delegated-delayed-leave-is-restarted-while-livekit-shows-the-participant-and-sent-once-it-does-not.md b/docs/adr/0832-a-delegated-delayed-leave-is-restarted-while-livekit-shows-the-participant-and-sent-once-it-does-not.md
new file mode 100644
index 000000000..4d94aeb2d
--- /dev/null
+++ b/docs/adr/0832-a-delegated-delayed-leave-is-restarted-while-livekit-shows-the-participant-and-sent-once-it-does-not.md
@@ -0,0 +1,137 @@
+# A delegated delayed leave is restarted while LiveKit shows the participant, and sent once it does not
+
+* Status: accepted
+* Date: 2026-11-17
+
+Technical Story: MatrixRTC slice 4. The owner chose to implement MSC4195's optional delegated delayed leave.
+
+## Context and Problem Statement
+
+A MatrixRTC client schedules a delayed `m.rtc.member` leave (MSC4140, ADR-0823) and restarts it while it is in the
+call, so its membership ends if it vanishes. MSC4195 lets the client hand that work to its homeserver:
+`POST /_matrix/client/v1/rtc/livekit/delegate_delayed_leave` with `{url, room_id, slot_id, member_id, delay_id}`. The
+server then restarts the event while the LiveKit participant is connected and sends it once the participant has
+disconnected. The client, believing the server has the event, stops restarting it and uses a long delay (Element Call
+uses one hour).
+
+What the server does with a delegation decides whether a user's call membership is ended at the right time. Two
+failures matter: ending a membership while the user is still in the call, and keeping one alive after they have left.
+
+## Decision Drivers
+
+* A delegation acts only on a delayed event the delegating user owns, in the room they named, while they are joined.
+* No input the server cannot verify ends or prolongs a membership by itself.
+* When the server cannot tell, the event falls back to its own timer, which is where the client left it.
+* A restart of this server does not drop delegations, so a connected participant is not ended an hour later.
+
+## Decision Outcome
+
+### The request
+
+`POST /_matrix/client/v1/rtc/livekit/delegate_delayed_leave` and the unstable
+`/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`, with an access token and the account
+gate. In order:
+
+1. The built-in token service off: 404 `M_UNRECOGNIZED`.
+2. A body that is not the five strings, within the get_token bounds (`delay_id` at most 64 bytes): 400.
+3. `url` not `server.rtc.livekit.url` byte for byte: 400 `M_INVALID_PARAM` (MSC4195 MUST).
+4. The caller's current membership not `join`: 403 `M_FORBIDDEN`, as get_token answers.
+5. The delayed event not the caller's, not in `room_id`, or not scheduled: 400 `M_INVALID_PARAM`, one answer for all
+ three (MSC4195 MUST), so a delay ID of another user's is not confirmed.
+6. Its delay under 5 minutes: 400 `M_INVALID_PARAM` (MSC4195 MAY). A shorter delay would need a restart more often than
+ LiveKit is polled.
+7. The user holding 20 delegations already, none of them for this key: 429 `M_LIMIT_EXCEEDED`, nothing evicted.
+
+Then the delegation is stored, replacing any of the same (user, room, slot, member) and any of the same delay ID
+(MSC4195 MUST: one per key), and the answer is `{}`. The route is limited per user (30 a minute).
+
+### Stored, so a restart keeps it
+
+Delegations are rows of `livekit_delegations` (migration 004): the delay ID, user, room, slot, member and creation time.
+Nothing else about a delegation needs to survive a restart: after one, every delegation is checked again from the
+start.
+
+### LiveKit decides, by polling
+
+A job in the main process, `livekit-delegations`, checks each delegation about every 30 seconds with LiveKit's
+`GetParticipant` for the delegation's room name and identity (MSC4195 names, ADR-0829), at most 16 calls a run, with
+`runtime.mutex` released for the calls (ADR-0830). Under the lock, before any call, a delegation is dropped (its row
+deleted, the event left as it is), at most 64 a run so that one lock hold stays bounded (each drop is a commit, and
+erasing from the in-memory table costs its size; the rest go on the next run, soon after), when:
+
+* its delayed event is no longer scheduled (sent, cancelled or failed);
+* the user is no longer joined to the room;
+* the token service is no longer configured.
+
+After a call, under the lock again, an answer is applied only to the delegation it was asked for: the same delay ID,
+user, room, slot, member and creation time, with the same LiveKit room name and identity. A delegation stored again
+while the lock was free (another member for the same delay ID, say) is a different participant, and the answer is
+dropped rather than recorded as seeing it.
+
+A run asks the due delegations most overdue first, so with more than 16 due none waits behind the others for ever.
+Each call's token is stamped with the clock when that call is made, not when the run began, so a run made slow by
+LiveKit never sends a token that is about to expire. A checked delegation's next check is 30 seconds after the run's
+calls ended, not after it began: a run that took as long as the interval would otherwise find the same 16 due again,
+and ask them again, while the rest waited.
+
+After a call:
+
+* **Connected** (an answer for the participant in a state other than `DISCONNECTED`): recorded. If less than half the
+ delay remains, the event is restarted through `manage_delayed_event`.
+* **Gone** (Twirp `not_found`, or the participant `DISCONNECTED`): if the participant was seen connected, or the
+ delegation is more than 2 minutes old, the event is sent through `manage_delayed_event` and the delegation dropped.
+ A delegation younger than that is left to wait, for a client still connecting.
+* **Unknown** (LiveKit unreachable, a timeout, any other answer): nothing changes.
+
+The event is restarted only on a "connected" answer to the call just made, never on one remembered from an earlier
+run. When LiveKit cannot be asked, the restarts stop and the event is sent by its own timer: a lost LiveKit ends
+memberships late, never early.
+
+Both actions go through `manage_delayed_event`, as the user's own `restart` and `send` would, so a send is authorised
+against the room when it happens (ADR-0825) and an account refusal applies.
+
+### Webhooks only prompt a check
+
+LiveKit's `participant_joined`, `participant_left` and `participant_connection_aborted` webhooks (ADR-0833) mark the
+matching delegation to be checked at the next run and wake the job. A webhook never restarts or sends an event itself,
+so a webhook that is replayed, reordered or lost changes when a check happens, never its outcome.
+
+### Positive Consequences
+
+* A participant who drops off the SFU leaves the call within about 30 seconds, or at once when the webhook arrives,
+ instead of after the client's delay.
+* A delegation that can no longer be acted on safely falls back to the behaviour the client chose.
+
+### Negative Consequences
+
+* While the server is down, or LiveKit cannot be asked, a vanished participant stays listed until the event's own delay
+ runs out (an hour for Element Call).
+* One `GetParticipant` call per delegation every 30 seconds.
+* Delegation works only for this server's SFU, as MSC4195 says.
+
+## Pros and Cons of the Options
+
+### Act on the webhook alone
+
+* Good, because it is immediate and makes no calls.
+* Bad, because LiveKit's webhooks are delivered at most a few times with no guarantee; a lost `participant_left` keeps a
+ membership alive for as long as the server goes on restarting it.
+
+### Keep delegations in memory only
+
+* Good, because it needs no migration.
+* Bad, because after a restart nothing restarts the delegated events, and every participant still connected is ended
+ when the client's hour runs out.
+
+### Send the leave whenever LiveKit cannot be asked
+
+* Good, because a vanished participant never lingers.
+* Bad, because a LiveKit outage or a slow answer would end every call membership on the server.
+
+## Links
+
+* Refines [ADR-0829](0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md)
+* [ADR-0825](0825-a-due-delayed-event-is-sent-by-one-job-through-the-ordinary-send-path-never-early-and-at-least-once.md)
+* [ADR-0823](0823-delayed-events-are-served-on-the-stable-unstable-and-query-parameter-forms-that-released-clients-send.md)
+* [ADR-0830](0830-every-call-to-livekit-goes-to-the-configured-address-with-a-token-of-its-own.md)
+* [ADR-0833](0833-the-livekit-webhook-is-served-on-the-client-listener-and-trusted-only-to-prompt-a-check.md)
diff --git a/docs/adr/0833-the-livekit-webhook-is-served-on-the-client-listener-and-trusted-only-to-prompt-a-check.md b/docs/adr/0833-the-livekit-webhook-is-served-on-the-client-listener-and-trusted-only-to-prompt-a-check.md
new file mode 100644
index 000000000..975897296
--- /dev/null
+++ b/docs/adr/0833-the-livekit-webhook-is-served-on-the-client-listener-and-trusted-only-to-prompt-a-check.md
@@ -0,0 +1,97 @@
+# The LiveKit webhook is served on the client listener and trusted only to prompt a check
+
+* Status: accepted
+* Date: 2026-11-17
+
+Technical Story: MatrixRTC slice 4, the delegated delayed leave (ADR-0832).
+
+## Context and Problem Statement
+
+LiveKit tells a configured URL about participants joining and leaving by webhook. MSC4195 recommends combining
+webhooks with polling for a delegated leave, since webhooks have no delivery guarantee. A webhook is an unauthenticated
+HTTP request as far as Matrix is concerned: anyone who can reach the URL can send one. What it may change, and how it
+proves it came from the operator's LiveKit, has to be decided.
+
+LiveKit signs each webhook: the `Authorization` header holds an HS256 JWT signed with the API secret, whose `iss` is the
+API key, valid for 5 minutes, and whose `sha256` claim is the standard base64 of the SHA-256 of the body. The body is a
+`WebhookEvent` in protobuf JSON: `event`, `room.name`, `participant.identity`, `id` and `createdAt` (seconds).
+
+## Decision Drivers
+
+* No state changes on a webhook alone (ADR-0832).
+* The check is the one LiveKit's own SDKs make, with nothing weaker.
+* A webhook that is replayed, stale or not for a delegation this server recorded does nothing.
+* A flood of webhooks, forged or real, costs little.
+
+## Decision Outcome
+
+### Where
+
+`POST /_merovingian/livekit/webhook`, a fixed path on the client listener(s). The operator points LiveKit's
+`webhook.urls` at it. The client listener is chosen because the operator's LiveKit already reaches this server's
+client API, and the federation listener is for other servers. With the built-in token service off the path is
+404 `M_UNRECOGNIZED`, as any unknown route.
+
+### Authentication
+
+In order, each failure answering 401 `M_UNAUTHORIZED` with one text and logging `livekit.webhook.refused` with the
+reason:
+
+1. The body is at most 64 KiB (413 above that, before anything is read).
+2. `Authorization` is present: a JWT, with or without a `Bearer ` prefix, at most 4096 bytes.
+3. The JWT verifies with `crypto::verify_hs256_token` under the API secret, read from its file for this request into a
+ `core::SecretBuffer`. The header's `alg` is never read (ADR-0828).
+4. `iss` equals `server.rtc.livekit.api_key`.
+5. `nbf` is not after now plus 60 seconds and `exp` is after now minus 60 seconds: the token is current, with a
+ minute's allowance for clock difference.
+6. `sha256` equals the base64 of the body's SHA-256, compared in constant time, so the body is the one LiveKit signed.
+
+### What an authenticated event may do
+
+* Only `participant_joined`, `participant_left` and `participant_connection_aborted` are read. Others are answered
+ 200 and ignored, so LiveKit does not retry them.
+* `createdAt` within 5 minutes of now, and an `id` (at most 128 bytes) not among the last 1024 seen, else ignored. A
+ replay within the token's own 5 minutes is caught by the `id`; one after is caught by the token's `exp`.
+* The event must name, by `room.name` and `participant.identity`, a delegation this server recorded, created no later
+ than `createdAt`, else ignored. Nothing in the body is used otherwise: no Matrix ID is derived from it.
+ * The match is found through an index by room name and identity (`livekit_delegation_participants`, kept in step
+ with the delegations' progress under `runtime.mutex`), so each signed event costs its matches, never a scan of
+ every user's delegations. Each match is checked again against the progress it names.
+* A match marks that delegation to be checked at the next run of `livekit-delegations` and wakes the job. That is all.
+
+Every authenticated event is answered 200 `{}`.
+
+### Bounds
+
+* The path has the client rate limiter's default per-address limit (600 a minute) and no tighter one: LiveKit sends
+ every room and track event of every call from one address, and a webhook refused for its rate only loses a prompt,
+ since the job's own checks decide.
+* A request costs a secret read, an HMAC and a SHA-256, under `runtime.mutex` only for the delegation lookup.
+
+### Positive Consequences
+
+* Forged, replayed or stale webhooks change nothing, and real ones only bring a check forward.
+
+### Negative Consequences
+
+* LiveKit must be able to reach the client listener's address.
+* A webhook signed with the secret but for an event LiveKit never sent (someone holding the secret) can still only
+ prompt a check.
+
+## Pros and Cons of the Options
+
+### Serve the webhook on a listener of its own
+
+* Good, because it could be bound to loopback only.
+* Bad, because it is a new listener for one route, with its own TLS and configuration, and the signature already
+ restricts who can use the route.
+
+### Act on `participant_left` at once
+
+* Good, because the leave is sent sooner by up to one polling interval.
+* Bad, because a forged-but-signed or reordered webhook would end a membership that LiveKit still shows connected.
+
+## Links
+
+* Refines [ADR-0832](0832-a-delegated-delayed-leave-is-restarted-while-livekit-shows-the-participant-and-sent-once-it-does-not.md)
+* [ADR-0828](0828-livekit-tokens-are-signed-and-verified-only-through-typed-hs256-functions-in-the-crypto-boundary.md)
diff --git a/docs/adr/0834-sqlite-writes-share-one-pooled-connection.md b/docs/adr/0834-sqlite-writes-share-one-pooled-connection.md
new file mode 100644
index 000000000..a8de083e7
--- /dev/null
+++ b/docs/adr/0834-sqlite-writes-share-one-pooled-connection.md
@@ -0,0 +1,86 @@
+# SQLite writes share one pooled connection, whatever database.pool_size says
+
+* Status: accepted
+* Date: 2026-11-18
+
+Technical Story: the DB-7 scenario "concurrent writes to SQLite reuse at most database.pool_size connections" lost
+three of its 64 writes in a full test run on a loaded VM: three writers logged `connection.rejected sqlite_code=5`
+and `transaction.failed stage=open` together, 5.3 s after the store opened. Refines
+[ADR-0154](0154-pool-database-write-connections.md), which assumed that SQLite's 5-second busy timeout absorbs
+contention for its single writer lock.
+
+## Context and Problem Statement
+
+SQLite in rollback-journal mode (`journal_mode = DELETE`, pinned by every connection) has one writer at a time,
+and a connection that wants a lock another connection holds does not queue for it. Its busy handler polls: it
+sleeps 1, 2, 5 ... ms, then every 100 ms, and gives up after 5 s of sleeps (`sqliteDefaultBusyCallback`). A
+committing connection holds PENDING or EXCLUSIVE for the whole commit, journal syncs, database write and database
+sync included (`syncJournal` takes EXCLUSIVE before its first sync), and PENDING refuses every new SHARED lock. A
+pooled connection that commits back to back therefore holds the lock nearly all the time. Its next lease takes the
+lock again within microseconds, while another connection of the same process, polling every 100 ms by then,
+rarely arrives in the gap.
+
+With `database.pool_size` connections allowed, the pool opened a second, third and fourth SQLite connection while
+the first was committing. Each needs a SHARED lock to read the schema when it pins its pragmas, and each of
+them polled against the first for 5 s and was refused: a write the client is told failed, because another write of
+the same process was busy. The same refusal follows for a write that waits behind one slow write for longer than
+5 s.
+
+Should SQLite writes keep up to `database.pool_size` connections?
+
+## Considered Options
+
+* **One SQLite write connection: the SQLite write pool's limit is always 1 (chosen).**
+* Keep `database.pool_size` connections and lengthen the busy timeout, or retry a refused open.
+* Keep `database.pool_size` connections and serialise their transactions with a mutex.
+* Write-ahead logging (`journal_mode = WAL`).
+
+## Decision Outcome
+
+Chosen option: one connection, because SQLite runs one write transaction at a time anyway, so a second connection
+adds no parallelism and only a second place to wait, and that place is SQLite's polling, unfair, time-limited
+busy handler. With one connection, every write of this process waits in the pool, on a condition variable that
+wakes the next writer when a lease ends and never times out, which is how ADR-0154 already waits for a PostgreSQL
+connection.
+
+* `SqliteWritePool` holds a `ConnectionPool` of limit 1, and `set_write_connection_limit` (that is,
+ `database.pool_size`) changes only the PostgreSQL pool. `write_connections_opened` reports 1 for SQLite unless a
+ connection could not be opened.
+* SQLite's busy timeout still governs this process's reads against its writer, and every lock another process
+ takes (`merovingian-db-migrate`, an operator's `sqlite3` shell). A read can still be refused after 5 s of
+ back-to-back commits; that is not changed here.
+
+### Positive Consequences
+
+* No write is refused because another write of this process holds SQLite's lock, however long it holds it.
+* A waiting writer is woken when the lease ends rather than at its next poll, and does no busy polling.
+
+### Negative Consequences
+
+* A write that never ends blocks every later write instead of failing them after 5 s each. A write is one
+ transaction of statements built before the lease is taken, so nothing in it waits on anything but SQLite.
+
+## Pros and Cons of the Options
+
+### Lengthen the busy timeout, or retry a refused open
+
+* Good, because it is a one-line change.
+* Bad, because the wait stays unfair: a longer budget lowers the odds of a refusal under load but keeps it, and
+ every waiter polls. It raises the tolerance instead of removing the contention.
+
+### Several connections, serialised by a mutex
+
+* Bad, because the connections would never be used at once; the extra handles are idle weight, and
+ `database.pool_size` would claim a parallelism that does not exist.
+
+### Write-ahead logging
+
+* Good, because readers would no longer block a writer or be blocked by one.
+* Bad, because the read-only connections refuse WAL on purpose
+ ([ADR-0157](0157-never-open-a-sqlite-database-file-outside-sqlite.md): a read-only connection can still write
+ the WAL index), and the pinned journal mode is a durability decision (#447). Changing them is a decision of its
+ own.
+
+## Links
+
+* Refines [ADR-0154](0154-pool-database-write-connections.md)
diff --git a/docs/adr/0835-the-version-changes-only-when-the-owner-asks.md b/docs/adr/0835-the-version-changes-only-when-the-owner-asks.md
new file mode 100644
index 000000000..77f5f8c78
--- /dev/null
+++ b/docs/adr/0835-the-version-changes-only-when-the-owner-asks.md
@@ -0,0 +1,66 @@
+# The version changes only when the owner asks
+
+* Status: accepted
+* Date: 2026-11-18
+
+Technical Story: the project owner's instruction of 2026-11-18, while a SQLite fix was being stacked on four open
+pull requests (1.1.0 to 1.1.3): "No more auto incrementing versions. We'll only do that when I ask for it."
+
+## Context and Problem Statement
+
+Every branch with a code, build, packaging or test change incremented `BUILD` when it was created
+([ADR-0647](0647-versions-from-1-0-0-are-major-minor-build.md)); documentation-only branches did not
+([ADR-0464](0464-documentation-only-changes-do-not-require-a-version-bump.md)). With several branches open at once,
+each took the next free number, and every rebase of a stacked branch conflicted in the sixteen places that hold the
+version and in the CHANGELOG, whose entries git interleaved. The numbers then said how many branches had been made,
+not what a release contains. When does the version change?
+
+## Considered Options
+
+* **Only when the owner asks; every change adds its CHANGELOG bullets to the newest version's entry (chosen).**
+* Keep one `BUILD` increment per branch.
+* Increment once per merge to `main` instead of per branch.
+
+## Decision Outcome
+
+Chosen option: the owner decides, because the owner asked for it, and a version is then a release decision rather than
+a by-product of branching.
+
+* No branch changes the version on its own, whatever it changes. A branch keeps the version of the branch it is based
+ on, in every location `docs/versioning.md` lists.
+* Every change, documentation-only or not, adds its bullets to the newest `# Version` entry of `CHANGELOG.md` under the
+ existing headings, and updates that entry's release-notes paragraph when an operator needs to know about it. The
+ format rules ([ADR-0741](0741-each-changelog-version-has-features-security-fixes-bug-fixes-and-release-notes.md)) and
+ the check that the newest entry is the version `meson.build` declares are unchanged.
+* When the owner asks for a version, that change sets the version the owner names in every location together, adds its
+ `%changelog` entries to the three RPM specs, and opens a new CHANGELOG entry above the previous one.
+* This supersedes ADR-0464, whose exemption no longer has a rule to except, and the per-branch increment of ADR-0647.
+ ADR-0647's scheme stands: versions are `MAJOR.MINOR.BUILD`, and `MINOR` and `MAJOR` change when the owner decides.
+
+### Positive Consequences
+
+* Parallel and stacked branches no longer conflict over the version, and the CHANGELOG has one entry to add to.
+
+### Negative Consequences
+
+* Two builds from different commits can report the same version until the owner asks for a new one. The commit, not
+ the version string, identifies an unreleased build.
+
+## Pros and Cons of the Options
+
+### One increment per branch
+
+* Good, because every branch's build reports a different version.
+* Bad, because of the conflicts and meaningless numbers above, and because the owner no longer wants it.
+
+### One increment per merge to main
+
+* Good, because only merged work moves the number.
+* Bad, because a merge still picks a number nobody chose for a release, and someone has to make the change at merge
+ time, which the project has no step for.
+
+## Links
+
+* Supersedes [ADR-0464](0464-documentation-only-changes-do-not-require-a-version-bump.md)
+* Partly supersedes [ADR-0647](0647-versions-from-1-0-0-are-major-minor-build.md): the per-branch `BUILD` increment
+* [docs/versioning.md](../versioning.md)
diff --git a/docs/adr/index.md b/docs/adr/index.md
index d1afd2355..a1c0a73e0 100644
--- a/docs/adr/index.md
+++ b/docs/adr/index.md
@@ -457,7 +457,7 @@
* [0510 - The test binaries hash passwords at minimum cost](0510-the-test-binaries-hash-passwords-at-minimum-cost.md)
* [0462 - Use std::invoke for callable dispatch and immediate lambdas](0462-use-std-invoke-for-callable-dispatch-and-immediate-lambdas.md)
* [0463 - Confine unavoidable C API pointers to RAII wrappers](0463-confine-unavoidable-c-api-pointers-to-raii-wrappers.md)
-* [0464 - Documentation-only changes do not require a version bump](0464-documentation-only-changes-do-not-require-a-version-bump.md)
+* [0464 - Documentation-only changes do not require a version bump](0464-documentation-only-changes-do-not-require-a-version-bump.md) — Superseded by ADR-0835: no branch bumps the version, so there is nothing to exempt
* [0465 - Root agent guidance requires the coding rules without copying them](0465-root-agent-guidance-requires-the-coding-rules-without-copying-them.md)
* [0466 - Define one class or struct per file](0466-define-one-class-or-struct-per-file.md)
* [0467 - Type filenames match the type name exactly](0467-type-filenames-match-the-type-name-exactly.md)
@@ -559,7 +559,7 @@
* [0634 - A share of the push delivery budget is kept for gateways that answer, and one host carries an eighth of it](0634-a-share-of-the-push-delivery-budget-is-kept-for-gateways-that-answer-and-a-host-carries-an-eighth.md)
* [0635 - An inbound federation origin is asked about once at a time, and its decision is kept for a short time](0635-an-inbound-federation-origin-is-asked-about-once-at-a-time-and-its-decision-is-kept-for-a-short-time.md)
* [0636 - A blob row is deleted with its last reference, and a removed record holds no reference](0636-a-blob-row-is-deleted-with-its-last-reference-and-a-removed-record-holds-none.md)
-* [0647 - Versions from 1.0.0 are MAJOR.MINOR.BUILD](0647-versions-from-1-0-0-are-major-minor-build.md)
+* [0647 - Versions from 1.0.0 are MAJOR.MINOR.BUILD](0647-versions-from-1-0-0-are-major-minor-build.md) — Partly superseded by ADR-0835: the version changes only when the owner asks, not once per branch
* [0648 - The Complement blocker is waived for 1.0.0 only](0648-the-complement-blocker-is-waived-for-1-0-0-only.md) — Extended by ADR-0744: 1.0.1 is waived too
* [0731 - A spawned worker gets no terminal, and no sandbox profile allows TIOCSTI or TIOCLINUX](0731-a-spawned-worker-gets-no-terminal-and-no-sandbox-profile-allows-tiocsti.md)
* [0732 - Every published attestation check pins the signing workflow and the ref](0732-every-published-attestation-check-pins-the-signing-workflow-and-the-ref.md) — Partly superseded by ADR-0742: every published file is attested by packages.yml
@@ -705,3 +705,12 @@
* [0824 - A delayed event is a stored row that is kept after it is finalised, bounded per user, and deleted with the account](0824-a-delayed-event-is-a-stored-row-kept-after-it-is-finalised-bounded-per-user-and-deleted-with-the-account.md)
* [0825 - A due delayed event is sent by one job through the ordinary send path, never early and at least once](0825-a-due-delayed-event-is-sent-by-one-job-through-the-ordinary-send-path-never-early-and-at-least-once.md)
* [0826 - Delayed events are on by default, with a maximum delay, per-user caps and per-user rate limits](0826-delayed-events-are-on-by-default-with-a-maximum-delay-per-user-caps-and-per-user-rate-limits.md)
+* [0827 - A state_after delta is measured from an in-memory log of resolved state changes](0827-a-state-after-delta-is-measured-from-an-in-memory-log-of-resolved-state-changes.md)
+* [0828 - LiveKit tokens are signed and verified only through typed HS256 functions in the crypto boundary](0828-livekit-tokens-are-signed-and-verified-only-through-typed-hs256-functions-in-the-crypto-boundary.md)
+* [0829 - The built-in LiveKit token service issues tokens only to users this server finds joined](0829-the-built-in-livekit-token-service-issues-tokens-only-to-users-this-server-finds-joined.md)
+* [0830 - Every call to LiveKit goes to the configured address with a token of its own](0830-every-call-to-livekit-goes-to-the-configured-address-with-a-token-of-its-own.md)
+* [0831 - A federated LiveKit token request is judged by main and answered subscribe-only](0831-a-federated-livekit-token-request-is-judged-by-main-and-answered-subscribe-only.md)
+* [0832 - A delegated delayed leave is restarted while LiveKit shows the participant, and sent once it does not](0832-a-delegated-delayed-leave-is-restarted-while-livekit-shows-the-participant-and-sent-once-it-does-not.md)
+* [0833 - The LiveKit webhook is served on the client listener and trusted only to prompt a check](0833-the-livekit-webhook-is-served-on-the-client-listener-and-trusted-only-to-prompt-a-check.md)
+* [0834 - SQLite writes share one pooled connection, whatever database.pool_size says](0834-sqlite-writes-share-one-pooled-connection.md)
+* [0835 - The version changes only when the owner asks](0835-the-version-changes-only-when-the-owner-asks.md)
diff --git a/docs/architecture.md b/docs/architecture.md
index 7bb20b73b..48e108ce9 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -594,6 +594,11 @@ it answers with the published room directory, which any server may request, and
listing reads appservice registration files the worker does not load (ADR-0296, ADR-0461), not because its database
role is denied the data.
+The federation LiveKit token route (`rtc/livekit/get_token`, MSC4195) is bound the same way, as
+`WorkerRelayKind::livekit_token` with a permit over the request body (ADR-0831). Main judges it: the origin main
+verified must be the user's server, and the user must be joined by main's own state. The worker never reads the LiveKit
+configuration or the API secret, and signs nothing.
+
### IPC reader/dispatch split
`ipc::IpcChannel` runs two threads per channel end. The reader thread only routes frames: a `reply_to` frame wakes its pending `send_request` waiter, and request frames are queued for the dispatch thread, which invokes the registered request handler one frame at a time in arrival order. The reader must never run handler code: a handler that blocks on a lock held by a thread that is itself waiting inside `send_request` on the same channel would otherwise wedge frame routing until the `send_request` timeout. That exact cycle previously occurred on every relayed PDU: the worker's relay thread held the worker `runtime.mutex` across its `pdu_ingest` round trip to main, main's `pdu_ingest` handler sent a `room_sync` notification (whose handler needs that same worker mutex) immediately before the `pdu_ingest` response, and the worker's reader thread blocked on the notification before it could route the response — a 60-second stall per PDU that remote origins turned into retry-with-backoff drip feed. The mirror case existed on main: a client-server handler holding main's `runtime.mutex` across a proxied outbound call (e.g. remote `/keys/query`) starved main's reader from routing the worker's `outbound_http_response` whenever a `pdu_ingest` arrived first and blocked inline on the same mutex. For the same reason, the worker handles `room_sync` on `local_pool` rather than on the dispatch thread: `reload_room` needs `runtime.mutex`, and blocking the dispatch thread on it would delay every later queued request frame. On the main side, `WorkerPool` runs every worker-to-main request handler (`pdu_ingest`, `membership_ingest`, `edu_ingest`, `invite_ingest`, query-provider relays) on a dedicated handler pool sized from `federation.worker.relay_threads`; the per-channel IPC dispatch thread only classifies the frame and enqueues the work. This means a slow `pdu_ingest` — which reserves a sync-surface ID, acquires its room stripe, reserves its stream ordering once the event is ready to store (pending until applied, so no sync position passes it, ADR-0247), prepares the update, releases the global runtime lock for the backend commit, and re-acquires it only to apply the result and update membership — no longer serializes all later request frames on that channel behind it, eliminating the single-dispatch-thread throughput bottleneck that made high-rate inbound federation back up and drip-feed. `WorkerPool::stop()` drains `handler_pool_` before stopping the supervisors so no handler thread races the closing channel. Because the handler pool can still be running a `pdu_ingest` when `WorkerSupervisor` needs to stop or restart, the supervisor takes ownership of the `IpcChannel` under `channel_mu_` and releases the lock before calling `IpcChannel::stop()`; otherwise `stop()`'s join of the dispatch thread would deadlock against the same handler calling back into `channel_snapshot()` via `notify_room_changed()`. `WorkerSupervisor::stop()` also bounds its final `waitpid` with `WNOHANG` and escalates through `SIGTERM` to `SIGKILL`, so a TSan-slow or stuck worker child cannot block process shutdown or test teardown.
@@ -642,6 +647,7 @@ Implemented endpoints are grouped below. Matrix v1.19 behaviour is described in
- **Admin**: `GET /admin/safety/reports`, quarantine/release/remove media
- **Push notifications**: `GET /pushers`, `POST /pushers/set`, the Push Rules API (`GET`/`PUT`/`DELETE /pushrules/...`; a user's rules are their `m.push_rules` account data applied over the server defaults by `push::UserPushRules`, ADR-0204), `GET /notifications`. Unread counts are decided by the same rules (`homeserver::PushRuleUnreadClassifier`, ADR-0205), and a failed notification is retried with backoff by the `push-retry` job thread from a bounded in-memory queue (`push::PushRetryQueue`, ADR-0206). Gateway delivery is gated on `server.push.enabled` (default `false`); when enabled, `RoomService.cpp`'s `send_event()` evaluates each local joined recipient's push rules and dispatches Push Gateway API notifications asynchronously — see "Fire-and-forget background work" above and `push` in the module diagram. `GET /notifications` history recording (`database::store_notification`, a synchronous local write, not gateway I/O) happens in that same rule-evaluation step regardless of `push.enabled` or whether the recipient has a pusher — a user with push turned off still needs to see their notifications. Kind `"email"` pushers have their own switch, `server.email.smtp_url` (ADR-0219, ADR-0220): the same step notes a notification in `push::EmailDigestQueue` (no network), and the `email-push` job thread (`homeserver/EmailPush.cpp`) sends each due digest, re-reading the pusher, the account's email 3PID and the badge count under `runtime.mutex` and sending through `email::send_smtp_message` with the mutex released. Only the main process sends email; the federation worker clears `server.email` in its config copy.
- **Search**: `POST /search` — in-memory full-text search (`content.body`/`content.name`/`content.topic`) over `PersistentStore::events`, scoped to the caller's currently-joined, unencrypted rooms; bounded by `ClientApiLimits::max_search_events_scanned` rather than a SQL full-text index (SQLite FTS5/PostgreSQL `tsvector`), to avoid a second, divergent search backend in an architecture that does not otherwise read events from SQL at request time. See `docs/todos/capability-gaps.md` for the deliberately-left-out spec corners.
+- **Calls (MatrixRTC)**: `GET /rtc/transports`; with the built-in LiveKit token service, `POST /rtc/livekit/get_token` and `POST /rtc/livekit/delegate_delayed_leave` (MSC4195), and LiveKit's signed webhook at `POST /_merovingian/livekit/webhook`, answered before the access-token gate (`homeserver/LiveKitTokenService.cpp`, `homeserver/LiveKitDelegations.cpp`). A token goes only to a user main finds joined; a request for another server's SFU is relayed to that server over signed federation; each call to LiveKit (`CreateRoom` on a token request, `GetParticipant` from the `livekit-delegations` job) goes only to `server.rtc.livekit.api_url` with a token of its own signed in `crypto/LiveKitToken.cpp`, with `runtime.mutex` released (ADR-0828 to ADR-0833). The job restarts a delegated delayed leave while LiveKit shows the participant and sends it once LiveKit does not, through `manage_delayed_event`; a webhook only brings a check forward. Delegations are kept in the `livekit_delegations` table (migration 004).
- **Other**: `GET /capabilities`, `GET /voip/turnServer`, OAuth 2.0 server metadata (`auth_metadata`, ADR-0773)
## Sync subsystem
diff --git a/docs/coding-rules.md b/docs/coding-rules.md
index e3f442e90..425e68f8c 100644
--- a/docs/coding-rules.md
+++ b/docs/coding-rules.md
@@ -239,9 +239,10 @@ defects on executed paths; a clean run does not prove that all paths are safe.
bug fix, or experiment. Never make development changes on `main`. Follow the
branch prefix required by the project or tool instructions, and submit changes
through a pull request.
-- Documentation-only changes do not require a version bump. For other changes,
- increment the version once when creating the branch. Update all locations in
- [versioning](versioning.md) together.
+- Do not change the version unless the owner asks for it; a branch keeps the
+ version of its base. When the owner asks, update all locations in
+ [versioning](versioning.md) together. See
+ [ADR-0835](adr/0835-the-version-changes-only-when-the-owner-asks.md).
- Update `CHANGELOG.md` for every change, in the
[changelog format](versioning.md#changelog-format). Use the
[documentation update table](AGENTS.md) to find the other required updates.
diff --git a/docs/crypto-boundary.md b/docs/crypto-boundary.md
index 00665b830..0c2d1b0e3 100644
--- a/docs/crypto-boundary.md
+++ b/docs/crypto-boundary.md
@@ -20,6 +20,15 @@ implementing custom cryptographic primitives.
the coturn REST API defines a TURN password as the base64 of HMAC-SHA1 over the username (ADR-0480). libsodium has no
SHA-1; OpenSSL is already a required dependency, so no new dependency enters the build, but `merovingian-crypto` now
links it. No other code may use SHA-1 for a new purpose.
+- LiveKit tokens (`LiveKitToken.cpp`, ADR-0828): HS256 JWTs, signed with libsodium's `crypto_auth_hmacsha256`, which
+ stays inside the file. There is no general "sign this payload" function: `sign_livekit_participant_token` takes a
+ `LiveKitParticipantGrant`, which cannot express `roomCreate`, `roomAdmin` or `hidden` and always writes
+ `canPublish`, `canPublishData` and `canSubscribe` (LiveKit reads an absent `canPublish` as true), and
+ `sign_livekit_room_create_token` grants `roomCreate` alone, and `sign_livekit_room_admin_token` grants `roomAdmin`
+ over one named MSC4195 room alone (for `GetParticipant`). `verify_hs256_token` checks the signature in constant
+ time and never trusts the header's `alg`. The API secret is a `core::SecretBuffer` the caller reads from its file
+ for each signature; the boundary refuses one shorter than 32 bytes. Pinned vectors are in
+ `tests/unit/test_crypto_livekit_token.cpp`.
- Variable-length comparison uses domain-separated hashing so it does not leak
input length through a premature length check.
- Runtime signing secret material uses `core::SecretBuffer`, backed by
diff --git a/docs/database-persistence.md b/docs/database-persistence.md
index 0194eaaf3..137aee4b3 100644
--- a/docs/database-persistence.md
+++ b/docs/database-persistence.md
@@ -25,8 +25,9 @@ value. Test fixtures that do not exercise persistence select it through
migration statements (`INSERT`/`UPDATE`/`DELETE`) are accepted as no-op
schema-state transitions, enabling backfill and corrective migrations
should a later migration need one.
-- The schema has three steps. `schema::current_schema_version()` is `3`, and
- `migrations/` holds `001_initial_schema.sql`, `002_oauth_tables.sql` and `003_delayed_events.sql`.
+- The schema has four steps. `schema::current_schema_version()` is `4`, and
+ `migrations/` holds `001_initial_schema.sql`, `002_oauth_tables.sql`, `003_delayed_events.sql` and
+ `004_livekit_delegations.sql`.
- Version `1` (`initial_schema`) is the frozen v1 schema. Every pre-1.0 migration (versions 2 to 26 as of
0.12.46) was collapsed into it in 0.12.47
([ADR-0224](adr/0224-pre-1-0-migrations-collapse-into-one-frozen-v1-schema.md)),
@@ -42,12 +43,14 @@ value. Test fixtures that do not exercise persistence select it through
`stream_ordering` is deliberately unindexed) Nothing is seeded or backfilled: the old
state-transition backfill and state-group seeding only ever mattered for
upgrading existing databases and no longer exist. The compiled catalog in
- `src/database/Migration.cpp` has three upgrade steps (version `1`,
- `initial_schema`; version `2`, `oauth_tables`; version `3`, `delayed_events`) and three downgrade steps, newest
- first (`drop_delayed_events` to version `2`, `drop_oauth_tables` to version `1`, then `drop_initial_schema` to
- version `0`, which drops every v1 table).
+ `src/database/Migration.cpp` has four upgrade steps (version `1`,
+ `initial_schema`; version `2`, `oauth_tables`; version `3`, `delayed_events`; version `4`, `livekit_delegations`)
+ and four downgrade steps, newest first (`drop_livekit_delegations` to version `3`, `drop_delayed_events` to
+ version `2`, `drop_oauth_tables` to version `1`, then `drop_initial_schema` to version `0`, which drops every v1
+ table).
`migrations/001_initial_schema.sql` is the frozen record of v1,
- `002_oauth_tables.sql` of version 2 and `003_delayed_events.sql` of version 3; a unit test requires each file to
+ `002_oauth_tables.sql` of version 2, `003_delayed_events.sql` of version 3 and `004_livekit_delegations.sql` of
+ version 4; a unit test requires each file to
match the build's step statement for statement.
- Version `2` (`oauth_tables`, 1.1.0) adds the OAuth 2.0 tables
([ADR-0776](adr/0776-an-oauth-session-is-a-row-keyed-by-user-and-device-and-the-token-tables-do-not-change.md)),
@@ -111,6 +114,29 @@ value. Test fixtures that do not exercise persistence select it through
memory is finalised even when the finalising commit fails (the function says so), and the database row still
reads `scheduled`, so the next start-up sends it again (at least once, ADR-0825). Every other function changes
memory only after the commit.
+- Version `4` (`livekit_delegations`, ADR-0832) adds one table for delayed leave events the LiveKit token service
+ keeps alive for a user (MSC4195 `delegate_delayed_leave`), and changes no existing table:
+ - `livekit_delegations` (`delay_id TEXT PRIMARY KEY`, then `user_id`, `room_id`, `slot_id`, `member_id` and
+ `created_ms`, all `TEXT NOT NULL`: `created_ms` is wall-clock milliseconds since the epoch as decimal text), with
+ `idx_livekit_delegations_user_id` on `user_id`, which serves the delete at deactivation. `delay_id` is the
+ `delayed_events.delay_id` of the delayed event; there is no foreign key, the store keeps its rules in code. One row
+ per (user, room, slot, member): MSC4195 allows one delegation per key.
+ - Caps, enforced by `store_livekit_delegation` and again when hydrating (`LiveKitDelegationStore.hpp`,
+ `LiveKitDelegationTable.hpp`): `delay_id` 1 to 64 bytes, and 1 to 255 bytes for `user_id`, `room_id`, `slot_id`
+ and `member_id`, none holding a NUL byte. A row outside them is refused, never truncated.
+ - Writes: `store_livekit_delegation` deletes the row holding the same key, deletes the row holding the same delay ID
+ and inserts the new row in one transaction, so a new delay ID for a key replaces the old delegation;
+ `delete_livekit_delegation` deletes one row (success also when there was none); and
+ `delete_livekit_delegations_of_user` deletes all of a user's rows, always running the `DELETE` so a row hydration
+ skipped does not outlive the account, and runs beside `delete_delayed_events_of_user` at account deactivation. Every
+ write is bound parameters only, and memory changes only after the commit returns true.
+ - In memory: `PersistentStore::livekit_delegations` (`LiveKitDelegationTable`), hydrated on both backends (neither
+ loads it for the federation worker profile), with no lock of its own (`runtime.mutex` serialises it). It indexes the
+ rows by delay ID and by (user, room, slot, member) and counts them per user; `rows()` lists them in insertion
+ order. A row the loader cannot read is skipped, never repaired and never guessed: an empty or over-long field, a
+ `created_ms` that is not decimal digits fitting 64 bits, or a duplicate delay ID or key (the first by delay ID
+ wins). The count skipped is `PersistentStore::livekit_delegation_rows_skipped_at_load`, logged once at start-up as
+ `livekit_delegations.rows_skipped_at_load`.
- The schema registry is split by version
([ADR-0778](adr/0778-the-schema-is-built-from-per-version-tables-and-each-migration-step-from-what-its-version-adds.md)):
`initial_schema_definitions()` is what v1 created, and the SQLite and
@@ -699,6 +725,12 @@ value. Test fixtures that do not exercise persistence select it through
memory only: at most 1024 entries, the oldest dropped first, each naming the
group that holds the state before an event for a room, a resolution context and
sorted distinct prev groups. The same three writers forget the room.
+ `PersistentStore::state_change_log` is a `StateChangeLog` (ADR-0827), in memory
+ only and started by the main process after hydration: every change to a room's
+ current state, filed at the sync position from which a client sees it, at most
+ 1024 per room and 65536 in all, the oldest dropped first. The four writers of
+ `current_state` record into it and `apply_room_snapshot` forgets the room;
+ `/sync`'s `state_after` reads it. No table backs it, so nothing is migrated.
**In-memory indexes (F-07, F-15, ADR-0325).** The three tables are mirrored in
memory by `StateGroupTable`, `StateGroupEntryTable` and `EventStateGroupTable`
@@ -950,9 +982,9 @@ value. Test fixtures that do not exercise persistence select it through
(`[fixture]`, one per backend) open it, run `migrate_*_schema_to`, start the runtime on it and read back the users,
access tokens, rooms, events, media, account data, pusher and device keys the manifest lists, then send a new
event signed with the old release's key. Opening the 1.0.3 database applies migration 002 (the OAuth 2.0 tables), so
- the scenarios first assert the v1 to v3 steps ran: the schema version is `current_schema_version()`, the ledger gained the
- `oauth_tables` and `delayed_events` rows, and `oauth_clients`, `oauth_sessions` and `delayed_events` exist and take a row (the fixture
- held none of them before). They then assert everything the manifest lists is still served.
+ the scenarios first assert the v1 to v4 steps ran: the schema version is `current_schema_version()`, the ledger gained the
+ `oauth_tables`, `delayed_events` and `livekit_delegations` rows, and `oauth_clients`, `oauth_sessions`, `delayed_events`
+ and `livekit_delegations` exist and take a row (the fixture held none of them before). They then assert everything the manifest lists is still served.
The PostgreSQL scenario needs `MEROVINGIAN_TEST_POSTGRESQL_URI` and reports itself skipped without it.
- Both stores read the migration ledger in numeric order
(`ORDER BY CAST(version AS INTEGER)`): `schema_migrations.version` is `TEXT`, and
@@ -1266,7 +1298,8 @@ migration's table cannot go unclassified:
`login_tokens`, `appservice_txn_cursor`, `appservice_outbox`, `deferred_pdus`,
`receipts`, `appservice_directory`, `media_pending_uploads`, `oauth_clients` and `oauth_sessions` (migration
002; every OAuth 2.0 endpoint runs in main), `delayed_events` (migration 003; the federation worker sends no events
- and holds no signing key, so it never reads a scheduled event), plus six tables `Schema.cpp`
+ and holds no signing key, so it never reads a scheduled event), `livekit_delegations` (migration 004; the token
+ service runs in main and the worker keeps no delayed event alive), plus six tables `Schema.cpp`
declares but that no runtime code path (main's or the worker's) ever
populates or queries — `event_json`, `key_backups`, `push_rules`,
`rate_limits`, `room_versions`, `state_group_edges` — vestigial from
@@ -1320,7 +1353,11 @@ membership is `invite` or `knock`, or deletes it; a new reader must check the me
### Write connection pool (DB-7, 0.12.26)
Persisted writes reuse connections from a per-store `ConnectionPool` instead of opening one per
-transaction: at most `database.pool_size` (16) are in use at once, and a write waits for a free one.
+transaction, and a write waits for a free one. On PostgreSQL at most `database.pool_size` (16) are in use at
+once. On SQLite there is always exactly one write connection, whatever `database.pool_size` says (ADR-0834):
+SQLite runs one write transaction at a time, and a second connection of this process waiting for the first's
+lock would poll SQLite's busy handler, lose to the first connection's back-to-back commits and be refused after
+5 s. Writers wait in the pool instead, without a time limit, and are woken in turn.
PostgreSQL connections assume the runtime role once when opened; a pooled one is reused only while idle
(`PQTRANS_IDLE`) with nothing to read on its socket, so one the server has closed is replaced. SQLite
connections keep their pragmas and `foreign_keys=ON`. Reads, migrations and the worker's read-only store
diff --git a/docs/http-transport.md b/docs/http-transport.md
index 9c4e3f238..73ad60977 100644
--- a/docs/http-transport.md
+++ b/docs/http-transport.md
@@ -823,7 +823,10 @@ Built-in per-endpoint refinements inside a tier: device and key APIs at
120/60s, search at 20/60s, thumbnails at 240/60s, and the delayed-event management and lookup paths (both prefixes, ADR-0826) at 3000/60s. Search requests do real
work (a bounded in-memory
scan, see `ClientApiLimits::max_search_events_scanned`) rather than a cheap
-lookup. The built-in per-user caps are 5/60s on `/login`, 4/60s on `/login/get_token` (ADR-0548), 30/60s on the two `preview_url` routes (ADR-0213) and 30/60s on `/_matrix/media/v1/create` (ADR-0212). The delayed-event management and lookup paths (`/_matrix/client/v1/delayed_events/` and `/_matrix/client/unstable/org.matrix.msc4140/delayed_events/`) are 120/60s per user, and the dedicated scheduling paths (`.../rooms/{roomId}/delayed_event/...`, both prefixes) 60/60s per user (ADR-0826); each path template is its own bucket.
+lookup. The built-in per-user caps are 5/60s on `/login`, 4/60s on `/login/get_token` (ADR-0548), 30/60s on the two `preview_url` routes (ADR-0213) and 30/60s on `/_matrix/media/v1/create` (ADR-0212). The delayed-event management and lookup paths (`/_matrix/client/v1/delayed_events/` and `/_matrix/client/unstable/org.matrix.msc4140/delayed_events/`) are 120/60s per user, and the dedicated scheduling paths (`.../rooms/{roomId}/delayed_event/...`, both prefixes) 60/60s per user (ADR-0826). The two LiveKit `get_token` paths are 60/60s per user (ADR-0829) and the two
+`delegate_delayed_leave` paths 30/60s per user (ADR-0832); LiveKit's webhook, `/_merovingian/livekit/webhook`, has only
+the default per-IP limit, because LiveKit sends every event from one address (ADR-0833). Each path template is its own
+bucket.
The per-user tier keys on the *authenticated* user, which before a login
succeeds is nobody — so a `/login` guessing spree against one account spread
@@ -849,7 +852,8 @@ Per-IP policy resolution is most-specific-first:
`client_rate_limits.default_per_ip`.
Per-user resolution: `client_rate_limits.per_user.` first, then
-the built-in per-user caps (`/login`, `/login/get_token`, `preview_url`, media `create`, the delayed-event paths); routes with neither have no per-user cap (the
+the built-in per-user caps (`/login`, `/login/get_token`, `preview_url`, media `create`, the delayed-event paths, the
+LiveKit `get_token` and `delegate_delayed_leave` paths); routes with neither have no per-user cap (the
per-IP cap still applies). Tier names are `auth_sensitive`, `media`, `sync`,
`federation`, `admin`, `generic`; an unknown name is a parse-time finding, not a
silently ignored key. All `client_rate_limits.*` changes require a server
diff --git a/docs/log-filtering.md b/docs/log-filtering.md
index 15d4a6345..9249a455a 100644
--- a/docs/log-filtering.md
+++ b/docs/log-filtering.md
@@ -134,6 +134,7 @@ used as the first argument to `observability::log_diagnostic` and `log_diagnosti
| `tls` | TLS context set-up and handshake accept or reject |
| `oauth` | OAuth 2.0 client registration, eviction at the cap, and stored metadata that no longer validates |
| `delayed_events` | Delayed events: scheduled, restarted, cancelled, sent, failed, a failed outcome write and a failed prune; never event content or a state key. The count of rows skipped at load is a start-up warning from the process entry point, not this module |
+| `livekit` | The built-in LiveKit token service: a token issued or refused, to a local user, to another server's user, or relayed from another server; a failed `CreateRoom` call and an unreadable API secret; a delegated delayed leave stored, refused, dropped, sent or failing to restart or send (`livekit.delegation.*`); a refused webhook (`livekit.webhook.refused`, warning, with the reason only) and one that prompted a check (`livekit.webhook.prompted`). Each names the user and room (and the server, for federation); never the token, the API secret, the device or member ID, the slot or the delay ID |
Unrecognised module names are accepted and the level is recorded —
there is no error. Restart the server to apply.
diff --git a/docs/matrix-v1.19-client-server-api.md b/docs/matrix-v1.19-client-server-api.md
index a3291849f..0b1a83c86 100644
--- a/docs/matrix-v1.19-client-server-api.md
+++ b/docs/matrix-v1.19-client-server-api.md
@@ -514,7 +514,7 @@ In each case below the spec leaves the choice to the server; the owner decided t
- **An identifier over 255 bytes is refused (ADR-0613).** `GET /profile/{userId}` and `GET /directory/room/{roomAlias}` answer `400 M_INVALID_PARAM` before any lookup. The spec limits a user ID and a room alias to 255 bytes.
- **Unset profile fields are absent.** `GET /profile/{userId}`, the user directory and `/search` `profile_info` leave out a `displayname` or `avatar_url` that is not set, instead of sending an empty string.
- **`GET /rooms/{roomId}/messages` with `lazy_load_members`.** `state` holds only the `m.room.member` events of the senders of the returned `chunk` (no other state). Redundant membership events are not tracked across calls, so a sender's membership is sent on every page (the spec's `include_redundant_members` default permits it).
-- **`use_state_after` on `/sync` (1.1.1, ADR-0818 to ADR-0820).** With `use_state_after=true`, joined and left rooms answer `state_after`, present even when empty, and omit `state`; with `false` or absent, the reverse. It is the state as of the response's position: all of it with no `since`, `full_state=true` or a join in the window, otherwise what differs from the state at `since`, including what the timeline carries, what the timeline filter hid and a key state resolution moved back, also on a `limited` sync. A left room's stops at the user's leave and always holds their own membership; `full_state` does not make it whole, but a room the user joined and left inside one window (or rejoined and left again) gets its whole readable state as of the leave, as the client held none of it. Invited and knocked rooms have no `state_after` in the spec and get none. With `lazy_load_members`, every member change is sent and each timeline sender's member is as of the end of the timeline. Sliding sync is unchanged.
+- **`use_state_after` on `/sync` (1.1.1, ADR-0818 to ADR-0820).** With `use_state_after=true`, joined and left rooms answer `state_after`, present even when empty, and omit `state`; with `false` or absent, the reverse. It is the state as of the response's position: all of it with no `since`, `full_state=true` or a join in the window, otherwise what differs from the state the client was told at `since`, including what the timeline carries, what the timeline filter hid and a key state resolution moved back, also on a `limited` sync and on a room forked at `since` (1.1.3, ADR-0827: measured from an in-memory log of resolved state changes; a `since` from before a restart gets the room's whole state once). A left room's stops at the user's leave and always holds their own membership; `full_state` does not make it whole, but a room the user joined and left inside one window (or rejoined and left again) gets its whole readable state as of the leave, as the client held none of it. Invited and knocked rooms have no `state_after` in the spec and get none. With `lazy_load_members`, every member change is sent and each timeline sender's member is as of the end of the timeline. Sliding sync is unchanged.
- **Lazy-loading on `/context` and `/sync` (0.12.73).** `GET /context` with `lazy_load_members` returns as `state` only the member events of the senders of `events_before`, `event` and `events_after` (stateless, redundancy allowed). `GET /sync` with `room.state.lazy_load_members` (the `timeline` flag does nothing) sends, besides the non-member state the room would carry without lazy-loading (the state filter still applies, and an incremental sync is a delta), the member events of the delivered timeline's senders, every member change in the gap of a limited sync, and the user's own membership on joining or `full_state=true`. A member the client acknowledged through its `since` is skipped (best effort, in memory, per user, device and `filter`); `include_redundant_members=true` and `full_state=true` skip nothing. `full_state=true` is now honoured for joined rooms. `use_state_after` is implemented (1.1.0, below).
- **Initial `/sync` carries `m.push_rules`.** An initial `/sync` (no usable `since`) always holds a global `m.push_rules` account-data event with the user's effective ruleset (the server defaults plus their changes), if the filter's `account_data` admits it. An incremental `/sync` carries it only after a change.
- **A hole in the event graph makes a joined room's `/sync` timeline `limited` (ADR-0289).** The spec defines `limited` by the filter `limit` and leaves events the server never received over federation unspecified; an event in the window whose `prev_events` are not all held (no row, or an outlier with no state group; rejected, soft-failed and backfilled events count as held, ADR-0290) starts a limited timeline at that event, with `prev_batch` for `/messages` to reach what lies before. A limited incremental sync carries the state at the start of the timeline. Sliding sync is unchanged.
@@ -539,7 +539,9 @@ In each case below the spec leaves the choice to the server; the owner decided t
- **`POST /users/{userId}/report` (v1.14, ADR-0482).** Needs an access token and is rate-limited. The body is a JSON object whose `reason`, when present, is a string (`400 M_BAD_JSON` otherwise). A local user ID no account holds is `404 M_NOT_FOUND` and stores nothing; a user of another server is accepted without a lookup. It is stored as an audit row `trust_safety.account.accept_report` (reporter, reported user), one per pair, listed by `GET /admin/safety/reports`; a repeat answers `200` without a second row. The reporter need share no room with the reported user.
- **Password reset by email (ADR-0481).** `POST /account/password/email/requestToken` (no token) answers `200` with `sid` and `submit_url` for every well-formed request, whether or not an account holds the address, and emails an 8-character code only to an active account's address; it never answers `M_THREEPID_NOT_FOUND` or `M_THREEPID_IN_USE`. A repeat with the same or a lower `send_attempt` returns the same `sid` and sends nothing. With no relay (`server.email.smtp_url`) it is `400 M_THREEPID_MEDIUM_NOT_SUPPORTED`. The client posts `{sid, client_secret, token}` to `submit_url` (`/_matrix/client/unstable/org.merovingian/account/password/email/submitToken`, this server's own path, the Identity Service `submitToken` shape): `{"success":true}`, or `400 M_TOKEN_INCORRECT`, `M_INVALID_PARAM` or `M_SESSION_EXPIRED` (five wrong codes end the session; sessions last 15 minutes). `POST /account/password` with no access token and `auth: {type: "m.login.email.identity", threepid_creds: {sid, client_secret}}` then sets the password of the account that holds the address (`401` with the flows for a missing or unvalidated stage, `400 M_WEAK_PASSWORD` for a weak password and the session is kept for a retry) and, with `logout_devices` (the default), revokes every token of the account. `POST /account/password/msisdn/requestToken` is `400 M_THREEPID_MEDIUM_NOT_SUPPORTED` (no SMS).
-- **MatrixRTC transport discovery (MSC4143, not in v1.19; ADR-0822).** `GET /_matrix/client/v1/rtc/transports` answers `{"transports":[{"type":"livekit","livekit_service_url":""}]}` and `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports` answers `{"rtc_transports":[...]}`, both needing an access token; with `server.rtc.livekit.service_url` empty they answer `{"transports":[]}` and `{}`. `/versions` always lists `org.matrix.msc4143` and `org.matrix.msc4143.stable`, and the well-known document gains `org.matrix.msc4143.rtc_foci` when a URL is set. There is no `m.livekit` transport and no `/rtc/livekit/*` route.
+- **MatrixRTC transport discovery (MSC4143, not in v1.19; ADR-0822).** `GET /_matrix/client/v1/rtc/transports` answers `{"transports":[{"type":"livekit","livekit_service_url":""}]}` and `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports` answers `{"rtc_transports":[...]}`, both needing an access token; with `server.rtc.livekit.service_url` empty they answer `{"transports":[]}` and `{}`. `/versions` always lists `org.matrix.msc4143` and `org.matrix.msc4143.stable`, and the well-known document gains `org.matrix.msc4143.rtc_foci` when a URL is set. With the built-in token service on (`server.rtc.livekit.url`, ADR-0829) the transports are instead `livekit` with `url`, and, on the stable route only, `m.livekit` with the same `url`; the well-known document gains no member for it.
+- **LiveKit token service (MSC4195, not in v1.19; ADR-0829 to ADR-0831).** `POST /_matrix/client/v1/rtc/livekit/get_token` and `POST /_matrix/client/unstable/io.element.msc4195/rtc/livekit/get_token`, access token and the standard account gate, body `{room_id, slot_id, member_id, url, server_name?}` (every member a string; `room_id`, `slot_id`, `member_id` at most 255 bytes, `url` at most 2048; anything else `400 M_BAD_JSON` or `M_INVALID_PARAM`). Answers `{"jwt":...}`. A caller whose current membership is not `join` gets `403 M_FORBIDDEN`, alike for a room that does not exist. For this server (`server_name` absent or this server's name), a `url` that is not `server.rtc.livekit.url` byte for byte is `400 M_INVALID_PARAM`, and the LiveKit room is created before answering: an unreachable or failing LiveKit is `502 M_UNKNOWN`. For another server named in `server_name`, the request is relayed over federation only when that server has a member joined (`403 M_FORBIDDEN` otherwise); its `403 M_FORBIDDEN` and `400 M_INVALID_PARAM` are passed on in this server's words and anything else is `502 M_UNKNOWN`. Without an outbound slot the answer is `429 M_LIMIT_EXCEEDED`; per-user limit 60/60s. With the service off both routes are `404 M_UNRECOGNIZED`. `/versions` lists `org.matrix.msc4195` and `org.matrix.msc4195.stable`, true when the service is on. The federation route `POST /_matrix/federation/v1/rtc/livekit/get_token` (and its `io.element.msc4195` unstable form) issues a subscribe-only token for a joined user of the requesting server.
+- **Delegated delayed leave (MSC4195, not in v1.19; ADR-0832, ADR-0833).** `POST /_matrix/client/v1/rtc/livekit/delegate_delayed_leave` and `POST /_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`, access token and the account gate, body `{url, room_id, slot_id, member_id, delay_id}` (strings; `delay_id` at most 64 bytes). In order: `404 M_UNRECOGNIZED` with the built-in service off; `400 M_BAD_JSON`, `M_MISSING_PARAM` or `M_INVALID_PARAM` for the body; `400 M_INVALID_PARAM` for a `url` that is not `server.rtc.livekit.url`; `403 M_FORBIDDEN` when the caller is not joined; one `400 M_INVALID_PARAM` for a delayed event that is unknown, another user's, in another room or no longer scheduled, and one for a delay under 5 minutes; `429 M_LIMIT_EXCEEDED` at 20 delegations per user. Answers `200 {}`; a new `delay_id` for the same room, slot and member replaces the old delegation. Without an access token the answer is `401`, never `404`, so Element Call's empty probe finds the route. Per-user limit 30/60s. `POST /_merovingian/livekit/webhook` (not a Matrix route) takes LiveKit's signed webhooks on the client listener, without an access token: `404 M_UNRECOGNIZED` with the service off, `413` over 64 KiB, `401 M_UNAUTHORIZED` unless signed by the configured LiveKit key for that body, else `200 {}`.
- **Delayed events (MSC4140; in the v1.20 spec text, not in v1.19; ADR-0823 to ADR-0826).** All nine routes need an access token and the standard account gate; `?user_id=` masquerade works as on other routes. Schedule: `PUT /v3/rooms/{roomId}/delayed_event/{eventType}/{txnId}` and `PUT /unstable/org.matrix.msc4140/rooms/{roomId}/delayed_event/{eventType}/{txnId}`; a request to `PUT /v3/rooms/{roomId}/send/{eventType}/{txnId}` or `PUT /v3/rooms/{roomId}/state/{eventType}/{stateKey}` (also the no-state-key and empty-state-key forms) that carries `?org.matrix.msc4140.delay=` is always scheduled, never sent at once, and answers `403 M_FORBIDDEN` when the feature is disabled (the other body-sending routes, `POST .../send` and `PUT .../redact/...`, answer `400 M_INVALID_PARAM` when the parameter is present, and the application-service `?ts=` is ignored on a delayed request); a delay that is not a decimal integer of at least 1, or is repeated, is `400 M_INVALID_PARAM`, and one over `server.delayed_events.max_delay_ms` is `400` (`M_DELAY_TOO_LARGE` on the v3 dedicated path, `ORG.MATRIX.MSC4140_DELAY_TOO_LARGE` on the others); a user at `max_scheduled_per_user` gets `429 M_LIMIT_EXCEEDED`; content over 65,536 bytes is `413 M_TOO_LARGE`. Manage: `POST /v1/delayed_events/{delayId}/{send|cancel|restart}` and `POST /unstable/org.matrix.msc4140/delayed_events/{delayId}/{send|cancel|restart}`, and, under the unstable prefix only, `POST /unstable/org.matrix.msc4140/delayed_events/{delayId}` with `{"action":"send"|"cancel"|"restart"}` (there is no `POST /v1/delayed_events/{delayId}`; any other last segment is `404 M_UNRECOGNIZED`). Look up: `GET /v1/delayed_events/{delayId}` and `GET /unstable/org.matrix.msc4140/delayed_events/{delayId}`. A delay ID that is unknown and one that belongs to another user both answer `404 M_NOT_FOUND` with `Delayed event not found.`; a repeated action on a finalised event answers `200` or `409 M_UNKNOWN`, and one on an event being sent answers `409`. `/versions` lists `org.matrix.msc4140` and `org.matrix.msc4140.stable` (each true when the feature is enabled), and `/capabilities` lists `m.delayed_events` and `org.matrix.msc4140.delayed_events` (`max_delay_ms`, `max_scheduled`; zeros when disabled). The event a delayed event became carries `unsigned.delay_id` for the user who scheduled it. The listing endpoint (MSC4486) is not routed (`404 M_UNRECOGNIZED`); sticky events (MSC4354) are not supported.
- **`GET /voip/turnServer` with `server.turn.uris` (ADR-0821)** answers one `uris` entry per configured URI, in the configured order; `server.turn.server` still gives one.
- **`GET /voip/turnServer` with `server.turn.shared_secret_file` (ADR-0480)** answers per-user credentials in the coturn REST API format: `username` `:`, `password` the base64 HMAC-SHA1 of it under the secret, `ttl` `server.turn.ttl_seconds`.
diff --git a/docs/threat-model.md b/docs/threat-model.md
index 045eb40fe..116f59019 100644
--- a/docs/threat-model.md
+++ b/docs/threat-model.md
@@ -36,6 +36,9 @@
SSRF-filtered; namespace matching; masquerading)
- Identity Service client (outbound `store-invite`/`bind`/`unbind`/`requestToken`)
- Push gateway delivery (outbound, client-supplied URL, no operator allowlist)
+- The built-in LiveKit token service (1.1.3): the LiveKit API secret, tokens handed to clients, the `CreateRoom` and
+ `GetParticipant` calls to the operator's LiveKit, the federation `rtc/livekit/get_token` route in both directions, the
+ delegated delayed leave and the LiveKit webhook (see below)
- Email pushers (outbound SMTP to an operator-configured relay; a client-supplied recipient address)
- Federation worker IPC channel (local process boundary)
- MSC4186 sliding-sync connection state (client-chosen `conn_id`)
@@ -3363,3 +3366,78 @@ ever logged; (j) the federation worker: it never reads the table and sends nothi
after a crash in the window between the send and its record, or when a `send` request throws after the event was stored (it has no catch, the event stays scheduled and can be sent again later); a wall clock stepped forwards brings deadlines forward by
the step; a suspended account's delayed events fail rather than send, so the server does not end a suspended
participant's call membership; the feature is on by default.
+
+### The built-in LiveKit token service (1.1.3, ADR-0828 to ADR-0833)
+
+New surface: a long-lived secret, `server.rtc.livekit.api_secret_file`, whose holder can mint any token for the
+operator's LiveKit, including administrative ones; two client routes that hand out tokens; an outbound call to
+LiveKit's room service; a federation route, served for other servers and called on other servers; a client route that
+hands this server a user's delayed leave and a job that restarts or sends it on what LiveKit says; and an
+unauthenticated webhook route for LiveKit. Threats and mitigations:
+
+(a) The secret leaking. It is a path to an owner-only (`0400`) file, checked at start-up, read into a
+`core::SecretBuffer` for each signature and wiped after, never held for the life of the process, never logged and
+never in a response. Signing is in `src/crypto/` through typed functions only (ADR-0828): the participant grant cannot
+express `roomCreate`, `roomAdmin` or `hidden`; one other signer grants `roomCreate` alone, and the last `roomAdmin` over
+one named room alone, for `GetParticipant`. The federation
+worker never reads the configuration or the secret, and its Landlock secret-path guard (`worker_landlock_secret_paths`)
+refuses to start the worker if a rule, such as the SQLite database directory grant, would cover the secret file.
+
+(b) A token for someone who should not have one. A token goes only to a caller this server authenticated (access token,
+account gate) and finds joined by its own current room state, never by the request: a user not joined, and a room that
+does not exist, get the same 403. A federated request is judged by main, for the origin main verified, and needs the
+user to be of that origin and joined by this server's state, and the room's server ACL to allow the origin (the room is
+named in the body, so the route-level ACL check does not cover it, and an ACL leaves a denied server's users joined); the
+four refusals are one 403, so a server learns nothing about a room it has no member in (ADR-0831). A relay goes only to a
+server the room's ACL allows.
+
+(c) More rights than a call needs. A local user's token joins one room and may publish and subscribe; another
+server's user's token may only subscribe. Lifetime is 60 to 3600 seconds. The room name and identity are MSC4195's
+hashes, so the SFU does not learn Matrix IDs.
+
+(d) SSRF and outbound abuse. The `url` in a request is only compared, byte for byte, with the configured SFU and never
+fetched. `CreateRoom` goes only to `server.rtc.livekit.api_url`, which is `https` or loopback `http`, with a token of
+its own lasting 60 seconds, one ADR-0079 outbound slot, one deadline of at most 10 seconds, a 16 KiB answer cap and the
+runtime lock released for the call only (ADR-0830). A relay to another server goes only to one this server's roster
+shows in the room, signed, under the same slot and deadline, with an 8 KiB answer cap; only a well-formed `jwt` is
+passed on, and that server's error text never is.
+
+(e) Cost and flooding. The client routes are limited to 60 a minute per user and share the client outbound budget.
+The federation route is limited per origin by `security.federation.per_origin_request_rate` and costs a secret read and
+a signature, with no network call: a request from another server never makes this server call LiveKit.
+
+(f) The worker forging a request. The inbound route reaches main only through the ADR-0595 relay: a permit over the
+body, bound to the request main authenticated, used once, with the origin checked against the pending request's.
+
+(g) A delegation acting on someone else's event. The delayed event must be the caller's own (looked up by owner, so
+another user's ID is the same 400 as an unknown one), scheduled, in the named room, and the caller joined to it by this
+server's state; it is bound to that delay ID, room, slot and member and is dropped when the event stops being
+scheduled, the user leaves or the service is turned off. The job acts only through `manage_delayed_event`, so a send is
+authorised against the room when it happens, as the user's own send would be. At most 20 per user, 30 requests a
+minute, and a delay of at least 5 minutes (ADR-0832).
+
+(h) LiveKit's answers ending a membership early. Only a `not_found` or `DISCONNECTED` answer for a participant seen
+connected, or never seen after 2 minutes, sends the leave; anything else (no answer, a timeout, another error) changes
+nothing and leaves the event to its own timer, and a restart needs a "connected" answer to the call just made. A
+LiveKit that is down or lies about a participant being present can only delay a leave by as long as it keeps saying so
+(the client's own leave and the user's own actions still work); one that lies about a participant being gone ends
+that membership early, which the operator's own SFU could do anyway. `GetParticipant` goes only to `api_url`, from
+the job's thread, at most 16 per run, 10 seconds each, with the runtime lock released, and its token can act on one
+room for one minute: LiveKit has no narrower grant for it (ADR-0830).
+
+(i) A forged or replayed webhook. `POST /_merovingian/livekit/webhook` takes no access token, so it is authenticated as
+LiveKit authenticates it: one `Authorization` header, an HS256 JWT checked in constant time under the API secret with
+the issuer equal to the API key (constant time), `nbf` and `exp` current within 60 seconds, and a `sha256` claim equal
+to the body's hash, so the body is the one LiveKit signed; the body is at most 64 KiB, and the route is 404 with the
+service off (ADR-0833). Even an authentic webhook is only a prompt: it is read only for a recorded delegation created
+before the event, only if `createdAt` is within 5 minutes and its `id` is not one of the last 1024 seen, and then it
+only brings that delegation's next check forward. It never sends or restarts an event, so a forged or replayed webhook
+can at most cost one `GetParticipant` call. Each unauthenticated request costs a secret file read and an HMAC, limited
+by the default per-address rate.
+
+Residual risk: a token stays usable for its lifetime after the user leaves the room, and a participant already
+connected stays in the call until LiveKit removes them (this server does not call `RemoveParticipant`); anyone who can
+read the secret file can mint any LiveKit token, and could forge webhooks (which only prompt checks); a delegated leave
+depends on LiveKit's view of the call, so a LiveKit that keeps reporting a vanished participant keeps their membership
+alive; the relay, the inbound route, the delegation job and the webhook have been tested only against this server and
+a local stand-in for LiveKit, never another implementation or a real LiveKit.
diff --git a/docs/todos/capability-gaps.md b/docs/todos/capability-gaps.md
index 586abd72d..dc83f0730 100644
--- a/docs/todos/capability-gaps.md
+++ b/docs/todos/capability-gaps.md
@@ -48,7 +48,9 @@ When adding a capability, record what is *missing* as explicitly as what works.
| Endpoint | Status | Needs |
| --- | --- | --- |
| `GET /_matrix/client/v1/auth_metadata` and the MSC2965 unstable path | `spec-covered` | The OAuth 2.0 server metadata, served while `server.oauth.enabled` is true (ADR-0773); `404 M_UNRECOGNIZED` while it is off. Registration, the authorisation pages, the token endpoint (code and refresh grants), revocation, the account pages at `/_merovingian/account` (all six account management actions), the `m.oauth` UIA stage, the `legacy_api_enabled=false` switch and the hand-off for OAuth 2.0 aware clients (`m.login.sso` with `oauth_aware_preferred`) are served (ADR-0779 to ADR-0802), and so is the device authorization grant with `server.oauth.device_grant_enabled=true` (ADR-0804 to ADR-0806). An OAuth session still cannot add an email address or mint a login token (no page; `403 M_FORBIDDEN`). Element X's QR-code login needs the MSC4108 rendezvous API, which is not in spec v1.19 and not part of 1.1.0 (owner decision), so it stays unavailable although the device authorization grant is served. Nothing here has yet been tried with Element X or in a real browser; see the open items in `docs/todos/oauth-2-0-api.md`. |
-| `GET /_matrix/client/v1/rtc/transports` and the MSC4143 unstable path | `runtime-wired` | MatrixRTC transport discovery (MSC4143, not in the v1.19 spec): advertises the operator's `lk-jwt-service` (`server.rtc.livekit.service_url`) as type `livekit` (ADR-0822). Gap: no built-in token service (`m.livekit`, `/rtc/livekit/*`). |
+| `GET /_matrix/client/v1/rtc/transports` and the MSC4143 unstable path | `runtime-wired` | MatrixRTC transport discovery (MSC4143, not in the v1.19 spec): advertises the operator's `lk-jwt-service` (`server.rtc.livekit.service_url`) as type `livekit` (ADR-0822). With the built-in token service on, advertises `livekit` and `m.livekit` with the SFU `url` instead (ADR-0829). |
+| `POST /_matrix/client/v1/rtc/livekit/get_token`, the `io.element.msc4195` path, and the federation `rtc/livekit/get_token` | `runtime-wired` | MSC4195, not in the v1.19 spec: the built-in LiveKit token service issues tokens to users this server finds joined, creates the LiveKit room first, relays a request for another server's SFU over federation and answers other servers' joined users with subscribe-only tokens (ADR-0829 to ADR-0831). Gap: no real client, LiveKit SFU or other homeserver has been run against it; the OpenID `/sfu/get` flow is not served. |
+| `POST /_matrix/client/v1/rtc/livekit/delegate_delayed_leave`, the `io.element.msc4195` path, and `POST /_merovingian/livekit/webhook` | `runtime-wired` | MSC4195's delegated delayed leave: stored per user, room, slot and member (migration 004), checked every 30 s with LiveKit's `GetParticipant` by the `livekit-delegations` job, which restarts the event while the participant is in the call and sends it once LiveKit no longer shows them; LiveKit's signed webhooks bring a check forward (ADR-0832, ADR-0833). Gap: tested only against a local stand-in for LiveKit, never a real SFU or Element Call; a participant who vanishes is noticed within 30 s without webhooks. |
| Delayed events: `PUT .../delayed_event/{eventType}/{txnId}`, `?org.matrix.msc4140.delay=` on `/send` and `/state`, `POST` and `GET .../delayed_events/{delayId}` (stable, `org.matrix.msc4140` and query forms) | `runtime-wired` | MSC4140, in the v1.20 spec text and not in v1.19: schedule, restart, cancel, send and look up a delayed event, kept in the `delayed_events` table (migration 003) and sent by the `delayed-events` job through the ordinary send path (ADR-0823 to ADR-0826). Not implemented: the listing endpoint (MSC4486, `404 M_UNRECOGNIZED`) and sticky events (MSC4354). No real client (Element X, Element Web, Element Call, lk-jwt-service) has been run against it yet. |
| `GET /_matrix/client/v3/voip/turnServer` | `spec-covered` | Static TURN credentials from `server.turn.*` configuration, or per-user time-limited coturn shared-secret credentials when `server.turn.shared_secret_file` is set (`src/homeserver/TurnCredentials.cpp`, ADR-0480). `server.turn.uris` advertises several URIs (ADR-0821). |
| Unrouted v1.19 operations | `not-started` | These answer `404 M_UNRECOGNIZED` (most are asserted as `(implementation gap)` scenarios in `tests/conformance/test_client_server_conformance.cpp`): legacy `GET /v3/events`, `GET /v3/events/{eventId}`, `GET /v3/initialSync`; `GET /.well-known/matrix/policy_server` and `GET /.well-known/matrix/support`. `POST /v1/login/get_token` (off unless `security.login_token.enabled`; UIA password every call; single-use in-memory tokens, ADR-0548) and `GET /v3/admin/whois/{userId}` (devices only: the server records no IP, user agent or last-seen time, so `connections` is always empty) are implemented (CS8). The two `/account/password/*/requestToken` routes are routed (email: ADR-0481; msisdn answers `400 M_THREEPID_MEDIUM_NOT_SUPPORTED`). User reporting, redaction, the appservice ping and the appservice network directory have their own rows. |
@@ -69,7 +71,7 @@ When adding a capability, record what is *missing* as explicitly as what works.
| `POST /_matrix/client/v3/rooms/{roomId}/receipt/{receiptType}/{eventId}` | `spec-covered` | 0.12.30: accepts `m.read`, `m.read.private`, and `m.fully_read`; rejects unknown types with 400 `M_INVALID_PARAM`, non-members with 403 `M_FORBIDDEN`, and malformed bodies with 400 `M_BAD_JSON`. `m.read` and `m.read.private` are durable receipt rows (ADR-0169), keyed by `(room, type, user, thread_id)`, so restarts preserve read positions. `thread_id` is optional for `m.read`/`m.read.private`, must be a non-empty string naming `main` or a thread root in this room, and is carried by `/sync` `m.receipt` events and federated `m.read` EDUs. `m.read` is public and federated; `m.read.private` is visible only to its sender and is not federated. `m.fully_read` is accepted without `thread_id`, rejected if `thread_id` is supplied, and stored as the owner's `m.fully_read` room account data rather than a receipt; it never appears in `m.receipt` or a federation EDU. Invalid `thread_id` values (including a non-root room event ID) return 400 `M_INVALID_PARAM`. 0.12.60: `/sync` delivers one `m.receipt` event per thread categorisation (unthreaded, `main`, each thread root), so a user's unthreaded and threaded `m.read` for one event both arrive; sliding sync's receipts extension still holds one event per room and keeps the latest receipt on such a clash. **Gap:** the optional 400 for "The event_id is not related to the thread_id" is not checked; the root's existence and main-timeline classification are checked, but the acknowledged event's relationship to it is not. |
| `POST /_matrix/client/v3/user_directory/search` | `spec-covered` | 0.12.60: searches only the users visible to the requester (a shared joined room, or joined to a `public` or `world_readable` room), as Complement expects; the spec allows searching more. Remote users are still not queried (the spec says SHOULD). |
| `POST /_matrix/client/v3/delete_devices` | `spec-covered` | |
-| `GET /_matrix/client/v3/sync` | `spec-covered` | Unread-notification counts are relative to the user's read receipts, partitioned by thread (an unthreaded receipt covers every earlier event, a threaded one only its thread; 0.12.30), and bound to the response snapshot. 0.12.30: the `unread_thread_notifications` filter flag (on `room.timeline`) returns per-thread counts and limits `unread_notifications` to the main timeline, and a non-state event the user sends reads its own thread up to itself (ADR-0170). The `summary` object (`m.joined_member_count`, `m.invited_member_count`, `m.heroes`) is now emitted for every joined room and covered by conformance tests. `filter_id` parameter now wired and conformance-covered; sync-only stream tokens now bound to the response snapshot for to-device delivery so room keys queued during response construction remain pending for the next sync. 0.12.59: a joined room's `state` on an initial sync (or a newly joined room) is the state up to the start of the timeline, not current state. An incremental sync with a limited timeline sends the whole state up to the start of the timeline as `state`, which covers the gap between `since` and the timeline's start (not as a delta), and `state_after` holds what changed in the gap. 0.12.60: `rooms.leave` lists rooms the user left **or was banned from**; each holds the filtered timeline (types, senders, `contains_url` now apply to a `/sync` timeline, and a `limit` of 0 means none) up to the leave or ban, as the user may see it, and an initial sync's `state` as of the start of that timeline (as of the leave when it is empty). An incremental sync reports a leave once, after `since`; `include_leave` lists left rooms on an initial sync only. A forgotten room is never listed (the spec says so, although Complement `TestRoomForget` expects its leave in the next incremental sync). Timeline events carry `unsigned.membership` (the requesting user's membership at the event, `leave` before they had one) and, for the device that sent them, `unsigned.transaction_id`; the same two on `GET /rooms/{roomId}/event/{eventId}`. 0.12.71: sliding sync's timeline and `required_state` events carry the same two fields, and no read path serves a stored event's `unsigned` (a received PDU is stored without it; ADR-0402). **Not done:** both fields are absent from `/messages`, `/context`, `/relations` and `/search`, and transaction-ID idempotency is still scoped to the user, not the device (the spec scopes it to a device). 0.12.60: an initial `/sync` always carries a global `m.push_rules` event with the effective ruleset (defaults plus changes), as Complement expects; an incremental one only after a change. **Lazy-loading of room members (0.12.73, ADR-0450 to ADR-0454).** With `room.state.lazy_load_members`, `state` holds the non-member state as before and only these member events: the senders of the delivered timeline (as of its start, skipped when the client has acknowledged that very event through its `since`), every member change in the gap of a limited sync, and the user's own on joining or `full_state`. Redundancy is tracked in memory per (user, device, filter, room) and lost on restart; `include_redundant_members` and `full_state=true` bypass it. The same flag on `room.timeline` does nothing, and the state filter's `types`/`senders` apply to the members. `full_state=true` is now honoured for joined rooms. Not done: sliding sync. 1.1.1: `use_state_after` answers `state_after` and omits `state` for joined and left rooms, on initial and incremental sync, with `full_state` and with `lazy_load_members` (ADR-0818 to ADR-0820); invited and knocked rooms have no such field. **Not done (accepted limit, ADR-0819):** after a state fork at `since`, a key that state resolution later flips back to the value recorded at `since` is not sent in `state_after`, because the delta compares against the state recorded for the event at `since`, not the state the client was told; `full_state=true` repairs the client. Storing each response's state per token would close it and was refused for its cost. |
+| `GET /_matrix/client/v3/sync` | `spec-covered` | Unread-notification counts are relative to the user's read receipts, partitioned by thread (an unthreaded receipt covers every earlier event, a threaded one only its thread; 0.12.30), and bound to the response snapshot. 0.12.30: the `unread_thread_notifications` filter flag (on `room.timeline`) returns per-thread counts and limits `unread_notifications` to the main timeline, and a non-state event the user sends reads its own thread up to itself (ADR-0170). The `summary` object (`m.joined_member_count`, `m.invited_member_count`, `m.heroes`) is now emitted for every joined room and covered by conformance tests. `filter_id` parameter now wired and conformance-covered; sync-only stream tokens now bound to the response snapshot for to-device delivery so room keys queued during response construction remain pending for the next sync. 0.12.59: a joined room's `state` on an initial sync (or a newly joined room) is the state up to the start of the timeline, not current state. An incremental sync with a limited timeline sends the whole state up to the start of the timeline as `state`, which covers the gap between `since` and the timeline's start (not as a delta), and `state_after` holds what changed in the gap. 0.12.60: `rooms.leave` lists rooms the user left **or was banned from**; each holds the filtered timeline (types, senders, `contains_url` now apply to a `/sync` timeline, and a `limit` of 0 means none) up to the leave or ban, as the user may see it, and an initial sync's `state` as of the start of that timeline (as of the leave when it is empty). An incremental sync reports a leave once, after `since`; `include_leave` lists left rooms on an initial sync only. A forgotten room is never listed (the spec says so, although Complement `TestRoomForget` expects its leave in the next incremental sync). Timeline events carry `unsigned.membership` (the requesting user's membership at the event, `leave` before they had one) and, for the device that sent them, `unsigned.transaction_id`; the same two on `GET /rooms/{roomId}/event/{eventId}`. 0.12.71: sliding sync's timeline and `required_state` events carry the same two fields, and no read path serves a stored event's `unsigned` (a received PDU is stored without it; ADR-0402). **Not done:** both fields are absent from `/messages`, `/context`, `/relations` and `/search`, and transaction-ID idempotency is still scoped to the user, not the device (the spec scopes it to a device). 0.12.60: an initial `/sync` always carries a global `m.push_rules` event with the effective ruleset (defaults plus changes), as Complement expects; an incremental one only after a change. **Lazy-loading of room members (0.12.73, ADR-0450 to ADR-0454).** With `room.state.lazy_load_members`, `state` holds the non-member state as before and only these member events: the senders of the delivered timeline (as of its start, skipped when the client has acknowledged that very event through its `since`), every member change in the gap of a limited sync, and the user's own on joining or `full_state`. Redundancy is tracked in memory per (user, device, filter, room) and lost on restart; `include_redundant_members` and `full_state=true` bypass it. The same flag on `room.timeline` does nothing, and the state filter's `types`/`senders` apply to the members. `full_state=true` is now honoured for joined rooms. Not done: sliding sync. 1.1.1: `use_state_after` answers `state_after` and omits `state` for joined and left rooms, on initial and incremental sync, with `full_state` and with `lazy_load_members` (ADR-0818 to ADR-0820); invited and knocked rooms have no such field. 1.1.3: the delta is measured from the resolved state the client was told at `since`, read from an in-memory log of state changes, so a fork at `since`, a key resolution moves back and a backfilled event are all sent exactly; a `since` from before a restart gets the room's whole state once (ADR-0827). |
| `GET /_matrix/client/v3/keys/changes` | `spec-covered` | Requires and validates `from` and `to` sync tokens, decodes them to `sync_stream_id` boundaries, and filters `changed`/`left` device-list changes to that half-open range. Conformance coverage includes missing/invalid parameters and an upper-bound test proving `to` excludes later changes. |
| Remote device-list cache | `spec-covered` | Server-Server API v1.19 "Device Management". 0.12.81 (G14, ADR-0560, ADR-0561): the list of a remote user who shares a joined room with a local user is filled from `GET /user/devices/{userId}` (its `stream_id` places later updates) and kept in memory, bounded per user and in all. `m.device_list_update` EDUs apply in `stream_id` order; a `prev_id` above the snapshot that was never applied, or an empty one, marks the list stale and the next `/keys/query` fetches it again; `m.signing_key_update` does the same. An update that changes nothing is no longer reported in `device_lists.changed`. Not persisted: a restart refills on demand. Complement `TestDeviceListsUpdateOverFederation` (three subtests) stays skip-listed until it is run against this change. |
| `POST /_matrix/client/v4/sync` and `POST /_matrix/client/unstable/org.matrix.msc4186/sync` (MSC4186 Simplified Sliding Sync) | `spec-covered` | Advertised via `unstable_features["org.matrix.msc4186"] = true` and the compatibility alias `unstable_features["org.matrix.simplified_msc3575"] = true`; the stable `v4` endpoint is now also routed and accepts the same request shape. Implements named lists with windowed `ranges` or singular `range`, SYNC/INVALIDATE/INSERT/DELETE/UPDATE ops, per-room state/timeline, room subscriptions, and all five extensions (to_device, e2ee, account_data, receipts, typing). Long-poll parks in the notifier's registry and holds no sync-pool thread while it waits (ADR-0569); `pos` and `timeout` may be supplied in query parameters or in the JSON body. List + `room_subscriptions` merge: when a room is in both a list window and a `room_subscriptions` entry, `required_state` is the superset (dedup + wildcard-aware), `timeline_limit` is the max, and `include_heroes` is OR'd (previously the subscription overrode the list wholesale) — landed 0.11.9. Multi-list combination: a room in MORE THAN ONE list window now has ALL matching list windows combined (left-fold over `combine_room_configs`, associative+commutative) with each other and the `room_subscriptions` entry, not just the first matching list — landed 0.11.10. Access control (CSAZ-1): a `room_subscriptions` entry is served only for a room the caller has joined; an invited room yields `invite_state` only (no timeline or `required_state`); any other membership omits the room, and the receipts/typing extensions drop rooms the caller has not joined. `timeline_limit` is clamped to 100, and more than 256 subscriptions or 256 `required_state` pairs is a 400 `M_INVALID_PARAM` (`sync::room_access_for`, `sliding_sync_request_limit_violation`). Truncated timelines (0.12.45): a room carries `limited` when its timeline holds fewer events than it could, `prev_batch` (a `/messages` `from`) on every non-empty timeline, `num_live`, and on a grown `timeline_limit` resends its latest events with `expanded_timeline`, answering without long-polling once per request `pos` (ADR-0221). Remaining: broader MSC4186 conformance fixtures, subscription timeline pruning, and `bump_stamp`, which is never sent (Element X orders its room list by it). |
diff --git a/docs/user-manual.md b/docs/user-manual.md
index f6ac9c013..262b4ac65 100644
--- a/docs/user-manual.md
+++ b/docs/user-manual.md
@@ -825,17 +825,80 @@ support.
#### Voice and video calls — `server.rtc.*` and `server.turn.*`
-Merovingian does not carry call media. A call needs a service you run beside it:
+Merovingian does not carry call media. A call needs a media service you run beside it:
- **1:1 calls** need a TURN server such as coturn. Configure it with `server.turn.*` (above).
-- **Group calls (MatrixRTC)** need a LiveKit SFU plus Element's `lk-jwt-service`, the authorisation service that
- hands a caller a LiveKit token. `lk-jwt-service` checks who is calling through this server's existing OpenID
- endpoints (`/_matrix/client/v3/user/{userId}/openid/request_token` and the federation `openid/userinfo`), so it must
- be able to reach this server over HTTPS. Merovingian only tells clients where it is.
+- **Group calls (MatrixRTC)** need a LiveKit SFU, and something that hands each caller a LiveKit token. Choose one:
+ - **The built-in token service** (`server.rtc.livekit.url` and the keys beside it). This server issues the tokens
+ itself (MSC4195), to users it finds joined to the room. You run LiveKit only.
+ - **An external `lk-jwt-service`** (`server.rtc.livekit.service_url`). Element's service issues the tokens and
+ checks who is calling through this server's OpenID endpoints
+ (`/_matrix/client/v3/user/{userId}/openid/request_token` and the federation `openid/userinfo`), so it must be able
+ to reach this server over HTTPS. Merovingian only tells clients where it is.
+
+ The two cannot be combined: setting `service_url` together with any built-in key refuses the configuration.
+
+##### The built-in token service — `server.rtc.livekit.*`
+
+Set all four of `url`, `api_url`, `api_key` and `api_secret_file`, or none. A partial set refuses the configuration
+(ADR-0829). Every key below requires a restart.
+
+| Key | Default | When to change |
+|---|---|---|
+| `server.rtc.livekit.url` | (empty) | The SFU's WebSocket address that clients connect to, for example `wss://livekit.example.org`. It must be an absolute `wss` URL with a host, no user name or password, no query or `#fragment`, a path that does not end in `/`, and at most 2048 bytes. Clients are told this address, and a token request naming any other `url` for this server is refused. |
+| `server.rtc.livekit.api_url` | (empty) | Where this server calls LiveKit's room service, for example `https://livekit.example.org`. `https`, or `http` only to `127.0.0.1` or `[::1]` when LiveKit runs on the same host; otherwise the same rules as `url`. Only this address is ever called (ADR-0830). |
+| `server.rtc.livekit.api_key` | (empty) | The LiveKit API key, 1 to 128 ASCII letters, digits, `_`, `-` and `.`. |
+| `server.rtc.livekit.api_secret_file` | (empty) | Path to an owner-read-only file (mode `0400`, as every secret file) holding the matching API secret, at least 32 bytes, on its first line. The file is read each time a token is signed and never kept in memory; the server refuses to start if its owner or mode is wrong. |
+| `server.rtc.livekit.token_lifetime` | `3600s` | How long an issued token can be used to join, `60s` to `3600s` (or `1m` to `60m`). A participant already in the call stays in it after the token expires. |
+
+What the service does:
+
+- A client asks `POST /_matrix/client/v1/rtc/livekit/get_token` (or the unstable
+ `/_matrix/client/unstable/io.element.msc4195/rtc/livekit/get_token`) for a room. The caller must be joined to the
+ room by this server's own current state; anyone else gets 403 `M_FORBIDDEN`, the same answer whether or not the room
+ exists.
+- Before answering, the server asks LiveKit to create the call's room (`CreateRoom`, at most 10 seconds, with a token
+ of its own allowed only to create rooms). If LiveKit cannot be reached, the client gets 502 and no token.
+- The token lets its holder join that one LiveKit room, publish and subscribe. It never grants room creation,
+ administration or hidden participation. The LiveKit room name and participant identity are hashes (MSC4195), so the
+ SFU does not learn Matrix user, device or room IDs.
+- A user of another server joined to the room can get a token from this server for its SFU, through that user's
+ server over federation (`POST /_matrix/federation/v1/rtc/livekit/get_token`). That token may subscribe but not
+ publish, and no LiveKit call is made for it (ADR-0831).
+- When a local user asks for a token for another server's SFU, this server relays the request to that server over
+ federation, but only to a server it finds in the room.
+- Token requests are rate limited per user (60 a minute by default; override with `client_rate_limits.per_user.` for each path)
+ and share the outbound-request budget of other client-triggered calls. Federated requests are limited per server by
+ `security.federation.per_origin_request_rate`.
+- The `livekit` logger records each issued or refused token with the user and room, never the token, the secret or
+ the device.
+- A client may hand this server its call membership's delayed leave
+ (`POST /_matrix/client/v1/rtc/livekit/delegate_delayed_leave`, or the `io.element.msc4195` unstable path), so the
+ leave is sent when it drops out of the call even if it vanishes without a word (ADR-0832). The delayed event must be
+ the caller's own, scheduled, in a room the caller is joined to, with a delay of at least 5 minutes; a user holds at
+ most 20 delegations, and asking is limited to 30 a minute per user. The `livekit-delegations` job asks LiveKit about
+ each delegation every 30 seconds (`GetParticipant`, with a token of its own valid for that one room): while the
+ participant is in the call it restarts the event once less than half the delay is left, and once LiveKit no longer
+ shows the participant it sends the event at once. A participant never seen in the call is given 2 minutes to
+ connect. If LiveKit cannot be reached nothing is restarted, so the event is sent by its own timer: a lost LiveKit
+ ends memberships late, never early. Delegations survive a restart.
+- To end memberships within seconds rather than within 30 seconds, point LiveKit's webhooks at this server:
+ `webhook.urls: ["https:///_merovingian/livekit/webhook"]` and `webhook.api_key: ` in
+ LiveKit's configuration (ADR-0833). The path is served on the client listener only while the built-in service is on.
+ A webhook is accepted only when signed by LiveKit with this API key and secret, for its exact body, and recent; it
+ then only makes the job check that participant at once. A webhook never sends or restarts an event by itself, so a
+ forged or replayed one can at most cause an early check. Without webhooks everything still works, 30 seconds slower.
+
+With the service on, `GET /_matrix/client/v1/rtc/transports` lists `{"type":"livekit","url":""}`
+and, on the stable path only, the same with type `m.livekit`. `/_matrix/client/versions` adds `org.matrix.msc4195`
+and `org.matrix.msc4195.stable`. The `.well-known` `org.matrix.msc4143.rtc_foci` member is not served by the built-in
+service, because the older clients that read it expect `lk-jwt-service`'s OpenID flow.
+
+##### An external `lk-jwt-service` — `server.rtc.livekit.service_url`
| Key | Default | When to change |
|---|---|---|
-| `server.rtc.livekit.service_url` | (empty) | The HTTPS URL of your `lk-jwt-service`, for example `https://livekit-jwt.example.org/lk-jwt-service`. Empty means no group-call transport is advertised. Clients build `/sfu/get` and `/get_token` by appending to it, so give the address without a trailing `/` and without a query: `https://host`, `https://host:8443` and `https://host/jwt` are accepted, `https://host/` and `https://host/jwt?x=1` are refused. It must be an absolute `https` URL with a host, no user name or password, no `#fragment`, no whitespace and at most 2048 bytes; anything else refuses the configuration. The server never contacts this URL. |
+| `server.rtc.livekit.service_url` | (empty) | The HTTPS URL of your `lk-jwt-service`, for example `https://livekit-jwt.example.org/lk-jwt-service`. Empty means no external service is advertised. Clients build `/sfu/get` and `/get_token` by appending to it, so give the address without a trailing `/` and without a query: `https://host`, `https://host:8443` and `https://host/jwt` are accepted, `https://host/` and `https://host/jwt?x=1` are refused. It must be an absolute `https` URL with a host, no user name or password, no `#fragment`, no whitespace and at most 2048 bytes; anything else refuses the configuration. The server never contacts this URL. This key is reloadable. |
With the key set, an authenticated client reading `GET /_matrix/client/v1/rtc/transports` (or the older
`GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports`) learns a transport of type `livekit` with that
@@ -856,11 +919,6 @@ start-up; anything outside the range, or not a boolean or unsigned integer, refu
| `server.delayed_events.max_scheduled_per_user` | `100` | `1` to `1000` | Scheduled events one user may hold. |
| `server.delayed_events.max_finalised_per_user` | `100` | `1` to `1000` | Finalised events kept per user (and for at most 7 days). |
-Not implemented yet:
-
-- **A built-in token service.** There is no `/_matrix/client/v1/rtc/livekit/*` endpoint and the transport type
- `m.livekit` is not advertised; you must run `lk-jwt-service` yourself.
-
##### Delayed events and call membership
A call member who loses connection should stop being listed. With delayed events (MSC4140) the client schedules the
@@ -876,8 +934,10 @@ joins without a delayed leave. The endpoints are listed in
The wire shapes were taken from the source of Element Web 1.12.35, Element X 26.11.0, Element Call 0.28.2 and
`lk-jwt-service` 0.10.0 at those releases (ADR-0823). No real client has been run against this server yet.
-`lk-jwt-service` 0.10.0 manages a delegated leave as an application service acting for the user, so an operator who
-wants that registers it as an application service whose user namespace covers the local users; see the
+With the built-in token service, a delegated leave is handled by this server itself (see
+[the built-in token service](#the-built-in-token-service-serverrtclivekit) above). With an external `lk-jwt-service`,
+0.10.0 manages a delegated leave as an application service acting for the user, so an operator who wants that
+registers it as an application service whose user namespace covers the local users; see the
[application service section](#application-service-api-appservice).
What you will notice in operation (ADR-0824, ADR-0825):
@@ -1236,7 +1296,7 @@ federation port `8448`.
| `database.role` | `runtime` | Use `migration` only with `merovingian-db-migrate`. |
| `database.migration_role` | (empty) | PostgreSQL role assumed for the DDL/migration phase only. Must be set together with `database.runtime_role`. |
| `database.runtime_role` | (empty) | PostgreSQL role assumed to serve requests, dropping DDL rights. Both empty issues no `SET ROLE`, leaving an existing single-role deployment unchanged. |
-| `database.pool_size` | `16` | Database connections persisted writes keep and use at once; a write waits for a free one rather than opening another (DB-7, ADR-0154). Requires restart. |
+| `database.pool_size` | `16` | PostgreSQL connections persisted writes keep and use at once; a write waits for a free one rather than opening another (DB-7, ADR-0154). SQLite writes always share one connection, since SQLite runs one write at a time (ADR-0834). Requires restart. |
| `database.sqlite_path` | `/var/lib/merovingian/merovingian.sqlite3` | Path for SQLite single-file store. Commented out in the shipped example, which defaults to PostgreSQL. The file itself must not be a symlink and is created `0600`; missing directories are created `0700`. Directories that already exist may be symlinks (for example `/var/lib/merovingian` pointing at a data volume). |
#### PostgreSQL TLS admission
@@ -1929,6 +1989,7 @@ Default route-aware policies applied when no override is configured:
| URL previews (`/_matrix/client/v1/media/preview_url`, `/_matrix/media/v3/preview_url`) | 30/60s per user |
| Asynchronous upload reservations (`/_matrix/media/v1/create`) | 30/60s per user |
| Delayed-event scheduling paths (`.../rooms/{roomId}/delayed_event/{eventType}/{txnId}`, both prefixes) | 60/60s per user |
+| LiveKit token requests (`/_matrix/client/v1/rtc/livekit/get_token`, `/_matrix/client/unstable/io.element.msc4195/rtc/livekit/get_token`) | 60/60s per user |
| Generic client APIs | 600/60s per IP fallback |
Example overrides:
@@ -2017,7 +2078,8 @@ take effect.
| `presence.*` | Restart required |
| `database.pool_size` | Restart required |
| `server.turn.*` | Reloadable |
-| `server.rtc.*` | Reloadable |
+| `server.rtc.livekit.service_url` | Reloadable |
+| `server.rtc.livekit.*` (the built-in token service) | Restart required |
| `server.delayed_events.*` | Restart required |
| `security.trust_safety.*` | Reloadable |
| `security.access_token_lifetime_ms` / `security.refresh_token_lifetime_ms` / `security.audit_log_retention_days` | Reloadable |
diff --git a/docs/versioning.md b/docs/versioning.md
index d1627a937..9ce94d12c 100644
--- a/docs/versioning.md
+++ b/docs/versioning.md
@@ -5,13 +5,10 @@
From 1.0.0 Merovingian uses **`MAJOR.MINOR.BUILD`**
([ADR-0647](adr/0647-versions-from-1-0-0-are-major-minor-build.md)).
-`BUILD` is the working counter: feature, fix, and packaging branches increment
-it by one, exactly as `PATCH` did before 1.0.0. The bump policy below is
-unchanged. Documentation-only changes do not require a version bump
-([ADR-0464](adr/0464-documentation-only-changes-do-not-require-a-version-bump.md)).
-
-`MINOR` and `MAJOR` change only when the owner decides. The decision states the
-version that follows.
+No part of the version changes on its own: `BUILD`, `MINOR` and `MAJOR` all
+change only when the owner asks, and the request states the version that follows
+([ADR-0835](adr/0835-the-version-changes-only-when-the-owner-asks.md)). See the
+bump policy below.
**Project phase is declared in `README.md` and `CHANGELOG.md`, never encoded in
the version number** ([ADR-0647](adr/0647-versions-from-1-0-0-are-major-minor-build.md), which restates the rule
@@ -28,26 +25,34 @@ long, and a new series did not restart at `.0` (`0.9.25` to `0.10.1`, `0.10.63`
to `0.11.4`). `1.0.0` was cut when the project reached production. Beta was
declared at `v0.10.59`. These rules no longer apply.
-## Bump policy
+From 1.0.0 until 2026-11-18, every branch with a code, build, packaging or test
+change incremented `BUILD` once when it was created, and documentation-only
+branches did not ([ADR-0647](adr/0647-versions-from-1-0-0-are-major-minor-build.md),
+[ADR-0464](adr/0464-documentation-only-changes-do-not-require-a-version-bump.md)).
+That is why 1.0.x and 1.1.x moved one number per branch. It no longer applies.
-**One bump per branch, when the branch is created, except for documentation-only changes.** Update `CHANGELOG.md`
-and every version location below together before the branch's first commit.
-Do not increment again on intermediate commits. Before raising the PR, verify
-that the version remains consistent with the base branch; if another branch
-has used that version in the meantime, update all locations together to the
-next available build number. There is no separate merge-time bump.
+## Bump policy
-The one exception is the `release.yml` fix that let 1.0.0 publish: the owner
-kept it at 1.0.0 and moved the unpublished `v1.0.0` tag to it
+**The version changes only when the owner asks for it**
+([ADR-0835](adr/0835-the-version-changes-only-when-the-owner-asks.md)). No branch
+changes it on its own, whatever the branch changes: code, build, packaging,
+tests or documentation. A branch keeps the version of the branch it is based on,
+in every location below.
+
+Every change adds its notes as bullets to the newest `# Version` entry of
+`CHANGELOG.md`, in the [changelog format](#changelog-format): new behaviour or
+guidance under `Features`, a vulnerability under `Security Fixes`, any other
+correction under `Bug fixes`. Update that entry's release-notes paragraph when an
+operator needs to know about the change.
+
+When the owner asks for a version, that change sets the version the owner names
+in every location below in one commit, adds the dated `%changelog` entry to each
+RPM spec, and opens a new `# Version` entry at the top of `CHANGELOG.md` for the
+changes that follow.
+
+The `release.yml` fix that let 1.0.0 publish kept 1.0.0 and moved the
+unpublished `v1.0.0` tag to it
([ADR-0651](adr/0651-the-v1-0-0-tag-moves-to-the-release-workflow-fix-without-a-version-bump.md)).
-It is not a precedent.
-
-For a documentation-only branch, keep the current version and add the change
-notes as bullets in its `CHANGELOG.md` entry: new guidance under `Features`, a
-correction under `Bug fixes`. Changes to coding
-guidance and `AGENTS.md` files are documentation changes. If the branch later
-includes code, build, or packaging changes, apply the bump policy before
-committing those changes.
## Changelog format
@@ -136,19 +141,19 @@ than the others.
a new dated entry for every version — the `Version:` field alone is not
sufficient for `rpmbuild` to accept the spec.
- Historical version strings in `CHANGELOG.md`, `CHANGELOG-pre-release.md` and every spec
- `%changelog` are records, not live values; do not edit them when bumping.
+ `%changelog` are records, not live values; do not edit them when the version changes.
- `CHANGELOG.md` starts at 1.0.0. The 0.x entries are in `CHANGELOG-pre-release.md`, a frozen record that
nothing is added to ([ADR-0740](adr/0740-the-changelog-starts-at-1-0-0-and-the-pre-release-entries-are-a-frozen-record.md)).
- `tests/tooling/test_packages_workflow.py` enforces that every file in the table
above carries the current `meson.build` version. Run it (or `python build.py
- vm`) after a bump to catch any location that was missed.
+ vm`) after a version change to catch any location that was missed.
## Release process
1. Update `main` from `origin`, then create a feature or fix branch from it.
-2. Unless the changes are documentation-only, increment the build number in every location above and add its changelog section.
-3. Make the changes and keep that version for intermediate commits.
-4. Before raising the PR, check version consistency and conflicts with the base branch.
+2. Make the changes without touching the version, and add their bullets to the newest `CHANGELOG.md` entry.
+3. Only when the owner asks for a version: set it in every location above and open its changelog entry.
+4. Before raising the PR, check that the version and the CHANGELOG agree with the base branch and do not conflict.
5. Raise a PR. CI builds the configured platform artifacts and runs the test suite;
see [platform-support.md](platform-support.md) for the artifact matrix.
6. Merge to `main`. The `publish-latest` CI job replaces the rolling GitHub
diff --git a/include/merovingian/config/Config.hpp b/include/merovingian/config/Config.hpp
index 8e64a21fb..2cfb4a608 100644
--- a/include/merovingian/config/Config.hpp
+++ b/include/merovingian/config/Config.hpp
@@ -37,6 +37,10 @@ inline constexpr std::uint64_t min_delayed_event_delay_ms = 1'000U;
inline constexpr std::uint64_t max_delayed_event_delay_ms = 2'678'400'000U; // 31 days
inline constexpr std::uint32_t max_delayed_events_per_user = 1'000U;
+// server.rtc.livekit.token_lifetime range (ADR-0829).
+inline constexpr std::uint32_t min_livekit_token_lifetime_seconds = 60U;
+inline constexpr std::uint32_t max_livekit_token_lifetime_seconds = 3'600U;
+
class Config final
{
public:
diff --git a/include/merovingian/config/LiveKitTokenServiceConfig.hpp b/include/merovingian/config/LiveKitTokenServiceConfig.hpp
new file mode 100644
index 000000000..69714f6c2
--- /dev/null
+++ b/include/merovingian/config/LiveKitTokenServiceConfig.hpp
@@ -0,0 +1,34 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include
+#include
+
+namespace merovingian::config
+{
+
+// The built-in MatrixRTC token service (MSC4195; ADR-0829): this server issues LiveKit tokens for the operator's
+// LiveKit SFU itself. Off unless all of `url`, `api_url`, `api_key` and `api_secret_file` are set; validate() refuses
+// a partial set, and refuses it together with `server.rtc.livekit.service_url`, so a validated config with `url` set
+// has the service on. Every key is read at start-up, so a change needs a restart.
+struct LiveKitTokenServiceConfig final
+{
+ // `server.rtc.livekit.url`: the SFU's WebSocket URL, sent to clients as the transport's `url` and the only `url` a
+ // token request may name. An absolute `wss` URL with a host, no userinfo, query or fragment, a path that does not
+ // end in `/`, at most 2048 bytes.
+ std::string url{};
+ // `server.rtc.livekit.api_url`: where this server calls LiveKit's room service. `https`, or `http` to a loopback IP
+ // literal (`127.0.0.1`, `[::1]`) when LiveKit runs on the same host; otherwise the same rules as `url`.
+ std::string api_url{};
+ // `server.rtc.livekit.api_key`: the API key, written as each token's `iss`. 1 to 128 ASCII letters, digits, `_`,
+ // `-` and `.`.
+ std::string api_key{};
+ // `server.rtc.livekit.api_secret_file`: an owner-only (0400) file holding the API secret, at least 32 bytes on its
+ // first line. Read for each use into a `core::SecretBuffer` and never kept.
+ std::string api_secret_file{};
+ // `server.rtc.livekit.token_lifetime`: how long an issued token can be used to join. 60 to 3600 seconds.
+ std::uint32_t token_lifetime_seconds{3600U};
+};
+
+} // namespace merovingian::config
diff --git a/include/merovingian/config/RtcConfig.hpp b/include/merovingian/config/RtcConfig.hpp
index 20acf4567..eb2816b85 100644
--- a/include/merovingian/config/RtcConfig.hpp
+++ b/include/merovingian/config/RtcConfig.hpp
@@ -2,13 +2,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
+#include "merovingian/config/LiveKitTokenServiceConfig.hpp"
+
#include
namespace merovingian::config
{
-// MatrixRTC transport discovery (MSC4143, MSC4195; ADR-0822). This server never fetches or proxies anything here: it
-// only tells authenticated clients where the operator's own MatrixRTC authorisation service is.
+// MatrixRTC (MSC4143, MSC4195). Either this server tells clients where the operator's own external authorisation
+// service is (`livekit_service_url`, ADR-0822), or it issues LiveKit tokens itself (`token_service`, ADR-0829); never
+// both.
struct RtcConfig final
{
// The HTTPS URL of an external MatrixRTC authorisation service (Element's `lk-jwt-service`) that the operator
@@ -18,6 +21,8 @@ struct RtcConfig final
// control character and at most 2048 bytes, or whose path ends in `/`. A URL with no path (`https://host`,
// `https://host:8443`) is accepted.
std::string livekit_service_url{};
+ // The built-in token service.
+ LiveKitTokenServiceConfig token_service{};
};
} // namespace merovingian::config
diff --git a/include/merovingian/crypto/LiveKitParticipantGrant.hpp b/include/merovingian/crypto/LiveKitParticipantGrant.hpp
new file mode 100644
index 000000000..7d54b3299
--- /dev/null
+++ b/include/merovingian/crypto/LiveKitParticipantGrant.hpp
@@ -0,0 +1,27 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include
+#include
+
+namespace merovingian::crypto
+{
+
+// What a LiveKit participant token says (ADR-0828). The token always grants `roomJoin` and `canSubscribe` in `room`
+// and nothing else but what is here: there is no field for `roomCreate`, `roomAdmin`, `roomList`, `roomRecord`,
+// `ingressAdmin`, `hidden`, `canUpdateOwnMetadata`, a name, metadata or attributes, so no token built from this type
+// can carry them.
+struct LiveKitParticipantGrant final
+{
+ // The MSC4195 participant identity and room name: unpadded standard base64 of a SHA-256, 43 characters each.
+ std::string identity{};
+ std::string room{};
+ // `canPublish` and `canPublishData` together.
+ bool can_publish{false};
+ // Seconds since the Unix epoch. `expires` is after `not_before`.
+ std::int64_t not_before{0};
+ std::int64_t expires{0};
+};
+
+} // namespace merovingian::crypto
diff --git a/include/merovingian/crypto/LiveKitToken.hpp b/include/merovingian/crypto/LiveKitToken.hpp
new file mode 100644
index 000000000..895e24d3e
--- /dev/null
+++ b/include/merovingian/crypto/LiveKitToken.hpp
@@ -0,0 +1,65 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "merovingian/crypto/LiveKitParticipantGrant.hpp"
+#include "merovingian/crypto/VerifiedHs256Token.hpp"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace merovingian::crypto
+{
+
+// LiveKit's tokens are JWTs signed with HMAC-SHA256 under the API secret (ADR-0828). The MAC is libsodium's
+// `crypto_auth_hmacsha256` and is not exposed: this file signs exactly three kinds of token, each built here from typed
+// claims, and verifies one. There is no function that signs bytes a caller chose.
+
+// The shortest API secret accepted. LiveKit refuses shorter secrets itself.
+inline constexpr auto livekit_api_secret_min_bytes = std::size_t{32U};
+// The longest API key and token accepted.
+inline constexpr auto livekit_api_key_max_bytes = std::size_t{128U};
+inline constexpr auto hs256_token_max_bytes = std::size_t{4096U};
+
+// Whether `api_key` can be a LiveKit API key here: 1 to `livekit_api_key_max_bytes` of ASCII letters, digits, `_`, `-`
+// and `.`. The key is a token's `iss`; this alphabet needs no JSON escaping.
+[[nodiscard]] auto livekit_api_key_is_valid(std::string_view api_key) noexcept -> bool;
+
+// Whether `value` is an MSC4195 identity or room name: 43 characters of the standard base64 alphabet, no padding.
+[[nodiscard]] auto livekit_name_is_valid(std::string_view value) noexcept -> bool;
+
+// The participant token for `grant`, signed with `api_secret`:
+// `{"alg":"HS256","typ":"JWT"}` and the claims `exp`, `iss` (`api_key`), `nbf`, `sub` (the identity) and `video`
+// (`room`, `roomJoin` true, `canSubscribe` true, `canPublish` and `canPublishData` from the grant). nullopt when the
+// key, a name, the times (`expires` not after `not_before`, or negative) or the secret (shorter than
+// `livekit_api_secret_min_bytes`) is not valid, or libsodium fails. Every character of its payload segment comes from
+// the standard and URL-safe base64 alphabets alike (no `-` or `_`), which Element Call's decoder needs.
+[[nodiscard]] auto sign_livekit_participant_token(std::string_view api_key, std::span api_secret,
+ LiveKitParticipantGrant const& grant) -> std::optional;
+
+// The service token for one call of LiveKit's room service: `video` holds `roomCreate` true and nothing else, `sub` and
+// `room` are absent. For `CreateRoom` only. nullopt on the same refusals as above.
+[[nodiscard]] auto sign_livekit_room_create_token(std::string_view api_key, std::span api_secret,
+ std::int64_t not_before, std::int64_t expires)
+ -> std::optional;
+
+// The service token for reading one participant of one room (`GetParticipant`, ADR-0830): `video` holds `room`
+// (`room_name`) and `roomAdmin` true and nothing else; `sub` is absent. LiveKit's `roomAdmin` covers only the room
+// named, so this token cannot act on any other room or create one. nullopt on the refusals above, or when
+// `room_name` is not an MSC4195 room name.
+[[nodiscard]] auto sign_livekit_room_admin_token(std::string_view api_key, std::span api_secret,
+ std::string_view room_name, std::int64_t not_before,
+ std::int64_t expires) -> std::optional;
+
+// Verifies that `token` is three unpadded URL-safe base64 segments whose third is the HMAC-SHA256 under `secret` of the
+// first two joined by `.`, compared in constant time, and returns the decoded header and payload. The header's `alg`
+// is never consulted: only HMAC-SHA256 is ever checked. nullopt for a token longer than `hs256_token_max_bytes`, a
+// malformed segment, a short secret or a MAC that does not match.
+[[nodiscard]] auto verify_hs256_token(std::string_view token, std::span secret)
+ -> std::optional;
+
+} // namespace merovingian::crypto
diff --git a/include/merovingian/crypto/VerifiedHs256Token.hpp b/include/merovingian/crypto/VerifiedHs256Token.hpp
new file mode 100644
index 000000000..e6fa56a04
--- /dev/null
+++ b/include/merovingian/crypto/VerifiedHs256Token.hpp
@@ -0,0 +1,18 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include
+
+namespace merovingian::crypto
+{
+
+// The decoded parts of an HS256 token whose MAC `verify_hs256_token` checked. Nothing in them has been judged: the
+// caller parses both and checks every claim it relies on.
+struct VerifiedHs256Token final
+{
+ std::string header_json{};
+ std::string payload_json{};
+};
+
+} // namespace merovingian::crypto
diff --git a/include/merovingian/database/LiveKitDelegationRowText.hpp b/include/merovingian/database/LiveKitDelegationRowText.hpp
new file mode 100644
index 000000000..8a622d8ce
--- /dev/null
+++ b/include/merovingian/database/LiveKitDelegationRowText.hpp
@@ -0,0 +1,25 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "merovingian/database/PersistentLiveKitDelegation.hpp"
+
+#include
+#include
+#include
+#include
+
+namespace merovingian::database
+{
+
+// The number of columns of a `livekit_delegations` row, in the order the loaders select them: `delay_id`, `user_id`,
+// `room_id`, `slot_id`, `member_id`, `created_ms`.
+inline constexpr auto livekit_delegation_row_columns = std::size_t{6U};
+
+// The strict reading of one stored `livekit_delegations` row, shared by both backends' loaders. Nullopt (the row is
+// skipped, never repaired or guessed) unless there are at least `livekit_delegation_row_columns` columns, each text
+// column is storable (`livekit_delegation_is_storable`) and `created_ms` is one or more ASCII digits that fit 64 bits.
+[[nodiscard]] auto parse_livekit_delegation_row(std::span columns)
+ -> std::optional;
+
+} // namespace merovingian::database
diff --git a/include/merovingian/database/LiveKitDelegationStore.hpp b/include/merovingian/database/LiveKitDelegationStore.hpp
new file mode 100644
index 000000000..fd7ff422d
--- /dev/null
+++ b/include/merovingian/database/LiveKitDelegationStore.hpp
@@ -0,0 +1,34 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "merovingian/database/PersistentLiveKitDelegation.hpp"
+
+#include
+
+namespace merovingian::database
+{
+
+struct PersistentStore;
+
+// The LiveKit delegations of migration 004 (ADR-0832). Every function here reads or writes
+// `PersistentStore::livekit_delegations` and, for a write, the database in one transaction with bound parameters
+// only. Memory changes only after the commit returns true. None takes a lock; in main the caller holds
+// `runtime.mutex`. The caps are in LiveKitDelegationTable.hpp.
+
+// Stores `row` as the one delegation of its (user, room, slot, member): in one transaction the row holding the same
+// key, if any, and the row holding the same delay ID, if any, are deleted and `row` is inserted (MSC4195: one
+// delegation per key, and a new delay ID replaces the old). False, writing nothing, when a field is empty, over its
+// cap or holds a NUL byte, or the commit fails.
+[[nodiscard]] auto store_livekit_delegation(PersistentStore& store, PersistentLiveKitDelegation row) -> bool;
+
+// Deletes the delegation of `delay_id`. True when the row is gone, also when there was none; false only when the
+// commit fails, with memory unchanged.
+[[nodiscard]] auto delete_livekit_delegation(PersistentStore& store, std::string_view delay_id) -> bool;
+
+// Deletes every delegation of `user_id`. Always runs the DELETE, even when memory holds no row for the user: a row that
+// hydration skipped is in the database and must not survive a deactivation. False only when the commit fails, with
+// memory unchanged.
+[[nodiscard]] auto delete_livekit_delegations_of_user(PersistentStore& store, std::string_view user_id) -> bool;
+
+} // namespace merovingian::database
diff --git a/include/merovingian/database/LiveKitDelegationTable.hpp b/include/merovingian/database/LiveKitDelegationTable.hpp
new file mode 100644
index 000000000..0437495ff
--- /dev/null
+++ b/include/merovingian/database/LiveKitDelegationTable.hpp
@@ -0,0 +1,86 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "merovingian/database/PersistentLiveKitDelegation.hpp"
+#include "merovingian/database/StateGroupKeyHash.hpp"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace merovingian::database
+{
+
+// Caps on what one row holds, enforced where the row is stored and where it is read back: an oversized row is
+// refused, never truncated.
+inline constexpr auto max_livekit_delegation_delay_id_bytes = std::size_t{64U};
+// The user, room, slot and member IDs.
+inline constexpr auto max_livekit_delegation_field_bytes = std::size_t{255U};
+
+// Whether `row` may be stored: every text field non-empty, within its cap and free of NUL (PostgreSQL TEXT cannot hold
+// one and the table's key joins its parts with one).
+[[nodiscard]] auto livekit_delegation_is_storable(PersistentLiveKitDelegation const& row) noexcept -> bool;
+
+// The in-memory copy of `livekit_delegations` (migration 004, ADR-0832). The class owns the rows and shows them
+// read-only, so a writer that bypasses it does not compile and its indexes cannot drift from the rows. Indexes: by
+// delay ID, by (user, room, slot, member) and a row count per user; the rows themselves are kept in insertion order.
+// An erase renumbers the positions the two lookups hold, which costs the table's size; delegations are few and end
+// rarely. The table has no lock: a reader needs exclusion from writers (in main, `runtime.mutex`). A pointer it
+// returns is valid until the next write. Copy and move are defaulted: the indexes hold positions into the vector, so
+// they stay valid in the copy.
+class LiveKitDelegationTable final
+{
+public:
+ // The row for `delay_id`, or nullptr.
+ [[nodiscard]] auto find(std::string_view delay_id) const -> PersistentLiveKitDelegation const*;
+ // The row of (`user_id`, `room_id`, `slot_id`, `member_id`), or nullptr.
+ [[nodiscard]] auto find_by_key(std::string_view user_id, std::string_view room_id, std::string_view slot_id,
+ std::string_view member_id) const -> PersistentLiveKitDelegation const*;
+ // How many rows `user_id` holds.
+ [[nodiscard]] auto count_of_user(std::string_view user_id) const -> std::size_t;
+ [[nodiscard]] auto size() const noexcept -> std::size_t
+ {
+ return m_rows.size();
+ }
+ // Every row, in insertion order.
+ [[nodiscard]] auto rows() const noexcept -> std::vector const&
+ {
+ return m_rows;
+ }
+
+ // The remaining members are for the store functions (LiveKitDelegationStore.hpp) and hydration only.
+
+ // Adds `row`. False, and nothing changes, when it is not storable (`livekit_delegation_is_storable`), its delay ID
+ // is held or another row holds the same key.
+ auto insert(PersistentLiveKitDelegation row) -> bool;
+ // Removes the row for `delay_id`. False when absent.
+ auto erase(std::string_view delay_id) -> bool;
+ // Removes the row holding the key. False when absent.
+ auto erase_key(std::string_view user_id, std::string_view room_id, std::string_view slot_id,
+ std::string_view member_id) -> bool;
+ // Removes every row of `user_id`, returning how many.
+ auto erase_user(std::string_view user_id) -> std::size_t;
+ // Removes every row, for hydration.
+ auto clear() noexcept -> void;
+
+private:
+ template
+ using KeyedBy = std::unordered_map>;
+
+ auto erase_at(std::size_t position) -> void;
+ // Rebuilds both position indexes from the rows.
+ auto reindex() -> void;
+
+ std::vector m_rows{};
+ // Delay ID -> position in `m_rows`.
+ KeyedBy m_by_delay_id{};
+ // (user NUL room NUL slot NUL member) -> position in `m_rows`.
+ KeyedBy m_by_key{};
+ KeyedBy m_user_counts{};
+};
+
+} // namespace merovingian::database
diff --git a/include/merovingian/database/Migration.hpp b/include/merovingian/database/Migration.hpp
index 19c5ec693..524de73e1 100644
--- a/include/merovingian/database/Migration.hpp
+++ b/include/merovingian/database/Migration.hpp
@@ -29,6 +29,9 @@ namespace merovingian::database
// Migration 003 (1.1.2): the delayed-events table (ADR-0824).
[[nodiscard]] auto delayed_events_migration() -> MigrationStep;
[[nodiscard]] auto downgrade_delayed_events_migration() -> MigrationStep;
+// Migration 004: the LiveKit delegations table (ADR-0832).
+[[nodiscard]] auto livekit_delegations_migration() -> MigrationStep;
+[[nodiscard]] auto downgrade_livekit_delegations_migration() -> MigrationStep;
[[nodiscard]] auto upgrade_migration_catalog() -> std::vector;
[[nodiscard]] auto downgrade_migration_catalog() -> std::vector;
[[nodiscard]] auto migration_plan_for(SchemaState const& state) -> MigrationPlan;
diff --git a/include/merovingian/database/PersistentLiveKitDelegation.hpp b/include/merovingian/database/PersistentLiveKitDelegation.hpp
new file mode 100644
index 000000000..12ad7091f
--- /dev/null
+++ b/include/merovingian/database/PersistentLiveKitDelegation.hpp
@@ -0,0 +1,26 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include
+#include
+
+namespace merovingian::database
+{
+
+// Migration 004 (ADR-0832): one delegation (`livekit_delegations`) of a delayed `m.rtc.member` leave event to the
+// LiveKit token service (MSC4195 `delegate_delayed_leave`). While the user's LiveKit participant is connected the
+// server keeps the delayed event (`delay_id`, a `delayed_events.delay_id`) alive. One row per (user, room, slot,
+// member). `created_ms` is wall-clock milliseconds since the Unix epoch. A row never changes except through
+// `LiveKitDelegationTable`.
+struct PersistentLiveKitDelegation final
+{
+ std::string delay_id{};
+ std::string user_id{};
+ std::string room_id{};
+ std::string slot_id{};
+ std::string member_id{};
+ std::uint64_t created_ms{0U};
+};
+
+} // namespace merovingian::database
diff --git a/include/merovingian/database/PersistentStore.hpp b/include/merovingian/database/PersistentStore.hpp
index 743b5eddb..5a30fc22e 100644
--- a/include/merovingian/database/PersistentStore.hpp
+++ b/include/merovingian/database/PersistentStore.hpp
@@ -13,6 +13,7 @@
#include "merovingian/database/ExaminedRows.hpp"
#include "merovingian/database/ForwardExtremityTable.hpp"
#include "merovingian/database/KeyBackupDigest.hpp"
+#include "merovingian/database/LiveKitDelegationTable.hpp"
#include "merovingian/database/MediaBlobRead.hpp"
#include "merovingian/database/MembershipProjection.hpp"
#include "merovingian/database/MembershipStoreResult.hpp"
@@ -88,6 +89,7 @@
#include "merovingian/database/RowKeyIndex.hpp"
#include "merovingian/database/SchemaState.hpp"
#include "merovingian/database/StateBeforeMemo.hpp"
+#include "merovingian/database/StateChangeLog.hpp"
#include "merovingian/database/StateGroupEntryTable.hpp"
#include "merovingian/database/StateGroupTable.hpp"
#include "merovingian/database/TableLoadProfile.hpp"
@@ -257,10 +259,10 @@ struct PersistentStoreOpenResult;
namespace detail
{
// DB-7, ADR-0154: each backend's pool of write connections, defined in its
- // own source file. Shared, not copied, by copies of a store.
+ // own source file. Shared, not copied, by copies of a store. Only the
+ // PostgreSQL pool's limit can be set: SQLite's is one (ADR-0834).
struct SqliteWritePool;
struct PostgresqlWritePool;
- auto set_write_pool_limit(SqliteWritePool& pool, std::uint32_t limit) -> void;
auto set_write_pool_limit(PostgresqlWritePool& pool, std::uint32_t limit) -> void;
[[nodiscard]] auto write_pool_opened(SqliteWritePool const& pool) -> std::uint64_t;
[[nodiscard]] auto write_pool_opened(PostgresqlWritePool const& pool) -> std::uint64_t;
@@ -583,6 +585,14 @@ struct PersistentStore final
// not digits or is out of range, a boolean that is not "true" or "false", an unknown status, a duplicate key). The
// rows stay in the database. The homeserver warns once at start-up when this is not zero.
std::size_t delayed_event_rows_skipped_at_load{0U};
+ // Migration 004 (ADR-0832): `livekit_delegations`, MSC4195 delayed leaves delegated to the LiveKit token service.
+ // Read and write through LiveKitDelegationStore.hpp; it has no lock of its own, so in main `runtime.mutex`
+ // serialises it. The federation worker never holds it.
+ LiveKitDelegationTable livekit_delegations{};
+ // How many `livekit_delegations` rows the last hydration skipped because they were not read exactly (an empty or
+ // over-long field, a `created_ms` that is not digits, a duplicate delay ID or key). The rows stay in the database.
+ // The homeserver warns once at start-up when this is not zero.
+ std::size_t livekit_delegation_rows_skipped_at_load{0U};
std::vector appservice_txn_cursors{};
// Events queued for appservices, kept sorted by (appservice_id, stream_ordering). See
// PersistentAppserviceOutboxEntry.
@@ -613,6 +623,12 @@ struct PersistentStore final
// How many times each room's current state, or the status or JSON of one of its events, has changed
// (`room_state_revision`, ADR-0624). In memory only.
std::unordered_map room_state_revisions{};
+ // Every change to a room's current state since start-up, by the sync position from which a client sees it, for
+ // `/sync`'s `state_after` (ADR-0827). In memory only, and inactive until the main process starts it. The four
+ // writers of current state (`apply_store_event_with_state`, `apply_current_state`, `store_state` and
+ // `remove_current_state_rows`) record into it, and `apply_room_snapshot` forgets the room. A new writer of `state`
+ // records too.
+ StateChangeLog state_change_log{};
// Stored events parsed for state resolution, for tests that prove cost.
ExaminedRows state_events_parsed{};
// Test-only capture of committed statements (AUTH-11). Empty and disabled
@@ -643,10 +659,11 @@ struct PersistentStore final
// stripe locks because capture access is independent of any room. Held by
// value (ADR-0517) so PersistentStore stays copyable and moveable; a copy gets its own mutex.
core::CopyableMutex statement_capture_mutex{};
- // DB-7, ADR-0154: persisted writes reuse at most this many connections
- // (database.pool_size, applied by set_write_connection_limit), instead of
- // opening one per transaction. The pool of the store's backend is created
- // when the store is opened; copies share it.
+ // DB-7, ADR-0154: persisted writes to PostgreSQL reuse at most this many
+ // connections (database.pool_size, applied by set_write_connection_limit),
+ // instead of opening one per transaction; SQLite writes reuse one
+ // (ADR-0834). The pool of the store's backend is created when the store is
+ // opened; copies share it.
std::uint32_t write_connection_limit{16U};
std::shared_ptr sqlite_write_pool{}; // SHARED_PTR: reviewed - shared by store copies.
std::shared_ptr // SHARED_PTR: reviewed - shared by store copies.
@@ -728,9 +745,10 @@ static_assert(std::is_nothrow_move_constructible_v &&
[[nodiscard]] auto validate_persistent_store(PersistentStore const& store) -> MigrationValidationResult;
[[nodiscard]] auto commit_persistent_transaction(PersistentStore& store,
std::vector const& statements) -> bool;
-// DB-7, ADR-0154: caps the connections persisted writes keep and use at once
-// (database.pool_size). A write waits for a free connection rather than opening
-// another. Takes effect for the next write.
+// DB-7, ADR-0154: caps the PostgreSQL connections persisted writes keep and use
+// at once (database.pool_size). A write waits for a free connection rather than
+// opening another. Takes effect for the next write. SQLite writes always share
+// one connection and ignore it (ADR-0834).
auto set_write_connection_limit(PersistentStore& store, std::uint32_t limit) -> void;
// Connections ever opened for persisted writes (both backends' pools).
[[nodiscard]] auto write_connections_opened(PersistentStore const& store) -> std::uint64_t;
@@ -961,7 +979,10 @@ auto rebuild_invite_indexes(PersistentStore& store) -> void;
[[nodiscard]] auto store_room_with_membership(PersistentStore& store, PersistentRoom room,
PersistentMembership membership) -> bool;
[[nodiscard]] auto store_event(PersistentStore& store, PersistentEvent event) -> bool;
-[[nodiscard]] auto store_state(PersistentStore& store, PersistentStateEvent state) -> bool;
+// `causing_stream_ordering` is the stream ordering of the event whose storing made this change, 0 for none; the state
+// change log files the change there or above (ADR-0827).
+[[nodiscard]] auto store_state(PersistentStore& store, PersistentStateEvent state,
+ std::uint64_t causing_stream_ordering = 0U) -> bool;
// The statements that make `state` current, replacing `previous_event_id`
// (empty for a key with no current_state row yet), and record the transition.
@@ -970,8 +991,10 @@ auto rebuild_invite_indexes(PersistentStore& store) -> void;
[[nodiscard]] auto prepare_current_state(PersistentStateEvent state, std::string previous_event_id)
-> PreparedCurrentState;
// Mirrors a committed prepare_current_state into current_state and the
-// state_transitions index.
-auto apply_current_state(PersistentStore& store, PreparedCurrentState const& prepared) -> void;
+// state_transitions index, and records the change in the state change log as made by the event at
+// `causing_stream_ordering` (0 for none, ADR-0827).
+auto apply_current_state(PersistentStore& store, PreparedCurrentState const& prepared,
+ std::uint64_t causing_stream_ordering = 0U) -> void;
// True when `state` names a stored event of that type and state key in that room.
[[nodiscard]] auto state_matches_stored_event(PersistentStore const& store, PersistentStateEvent const& state) -> bool;
// With `membership`, also writes that membership row and invite change in the same
@@ -989,9 +1012,11 @@ auto apply_current_state(PersistentStore& store, PreparedCurrentState const& pre
MembershipProjection projection) -> bool;
// Removes `keys` (event type, state key) from `room_id`'s current state and writes `memberships`, in one transaction,
// then mirrors both, keeping the state indexes in step (ADR-0615). Costs the rows of the rooms that lose or move a row.
+// Each key removed is recorded in the state change log as made by the event at `causing_stream_ordering` (ADR-0827).
[[nodiscard]] auto remove_current_state_rows(PersistentStore& store, std::string_view room_id,
std::vector> const& keys,
- std::vector const& memberships) -> bool;
+ std::vector const& memberships,
+ std::uint64_t causing_stream_ordering = 0U) -> bool;
// DB-4: makes each `membership` row agree with its room's current m.room.member
// state event, which is the user's membership (Matrix v1.19 "m.room.member").
// A row is rewritten to the event's membership when the row is missing, when it
diff --git a/include/merovingian/database/Schema.hpp b/include/merovingian/database/Schema.hpp
index 1b08d11d9..5cd309b8d 100644
--- a/include/merovingian/database/Schema.hpp
+++ b/include/merovingian/database/Schema.hpp
@@ -16,7 +16,8 @@ namespace merovingian::database
[[nodiscard]] auto current_schema_version() noexcept -> std::uint32_t;
// The schema split (ADR-0778). The tables and indexes migration `version` creates: version 1 is the frozen v1
-// schema, version 2 the OAuth 2.0 tables, version 3 the delayed-events table; any other version adds none. A migration step is built from these.
+// schema, version 2 the OAuth 2.0 tables, version 3 the delayed-events table, version 4 the LiveKit delegations table;
+// any other version adds none. A migration step is built from these.
[[nodiscard]] auto schema_definitions_added_by(std::uint32_t version) -> std::vector;
[[nodiscard]] auto schema_indexes_added_by(std::uint32_t version) -> std::vector;
// Exactly what v1 created, which the SQLite and PostgreSQL bootstraps build before any later step runs.
diff --git a/include/merovingian/database/SqliteWritePool.hpp b/include/merovingian/database/SqliteWritePool.hpp
index 045c9072c..3a6b6ab7c 100644
--- a/include/merovingian/database/SqliteWritePool.hpp
+++ b/include/merovingian/database/SqliteWritePool.hpp
@@ -10,10 +10,17 @@
namespace merovingian::database::detail
{
+// ADR-0834: one SQLite write connection, whatever database.pool_size says.
+// SQLite runs one write transaction at a time; a second connection of this
+// process would wait for the first's lock in SQLite's polling busy handler,
+// lose to its back-to-back commits and be refused after 5 s. Writers wait in
+// the pool instead, without a time limit.
struct SqliteWritePool final
{
- explicit SqliteWritePool(std::uint32_t limit)
- : pool{limit}
+ static constexpr auto connection_limit = std::uint32_t{1U};
+
+ SqliteWritePool()
+ : pool{connection_limit}
{
}
ConnectionPool pool;
diff --git a/include/merovingian/database/StateChangeLog.hpp b/include/merovingian/database/StateChangeLog.hpp
new file mode 100644
index 000000000..38cd9c013
--- /dev/null
+++ b/include/merovingian/database/StateChangeLog.hpp
@@ -0,0 +1,112 @@
+// SPDX-FileCopyrightText: 2026 James Chapman
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "merovingian/database/ExaminedRows.hpp"
+
+#include
+#include
+#include