Compare commits

..
Author SHA1 Message Date
Jade Ellis 1aa44f9834 chore: Release 2026-04-17 10:50:19 +01:00
Renovate Bot b5b8d62622 chore(deps): update ruma digest to d00b51a 2026-04-17 09:30:25 +00:00
Renovate Bot b9b3cddf70 chore(deps): update rust crate ctor to 0.10.0 2026-04-17 08:15:37 +00:00
Renovate Bot 62166f3cf8 chore(deps): update dependency typescript to v6.0.3 2026-04-17 08:14:02 +00:00
Renovate Bot ed1fe717b9 chore(deps): update https://github.com/taiki-e/install-action digest to a2352fc 2026-04-17 08:13:49 +00:00
Renovate Bot 69e4689b24 chore(deps): update https://github.com/cloudflare/wrangler-action digest to 9acf94a 2026-04-17 08:13:35 +00:00
Renovate Bot cace197237 chore(deps): pin actions/cache action to 27d5ce7 2026-04-17 08:12:53 +00:00
Jade 49e6d18ac6 ci: Use inherited secrets 2026-04-16 14:29:42 +00:00
Sebastian Spaeth bf6783cb83 ci: add all possible credentials
When running the mirror-images step from within the release-image workflow
we receive error messages such as

> msg="Failed to sync" target=ghcr.io/continuwuity/continuwuity:v0.5.0-rc.7
> source=forgejo.ellis.link/continuwuation/continuwuity:v0.5.0-rc.7
> error="failed to send blob post, ref
> ghcr.io/continuwuity/continuwuity@sha256:74976f7b85018b5abd867333bc783c7230d985a4b0af595bbf55964e25afe6ef:
> unauthorized"

So, we will need to define our credentials in the release-image workflow too
it seems, when we pull in the mirror-image workflow.
This is a test by adding all credentials that are defined in mirror-images.yml
Probably we don't need them all, but if this does not work, the whole approach
is flawed and we can remove everyting again.

If it works, we should remove unneccessary credentials until we found the
required ones.
2026-04-15 19:34:33 +00:00
éźera 2ca7149a7f feat: allow deprioritizing servers for join requests
Implements #1549.
2026-04-15 13:24:42 +00:00
Renovate Bot bedec72489 chore(deps): update https://github.com/taiki-e/install-action digest to eea29cf 2026-04-15 13:23:55 +00:00
Sebastian Spaeth 80861b5f12 ci: actions/cache@v3|4 -> actions/cache@v5
Update to use actions/cache@v5 in our CI
2026-04-15 13:22:43 +00:00
Renovate Bot f2d7654572 chore(deps): update rust crate sha2 to 0.11.0 2026-04-15 13:22:30 +00:00
Renovate Bot bb037ca9f4 chore(deps): update dependency cargo-bins/cargo-binstall to v1.18.1 2026-04-15 13:21:59 +00:00
Renovate Bot fd236876af chore(deps): update https://github.com/regclient/actions digest to f3c6d87 2026-04-15 13:21:46 +00:00
Renovate Bot 130b07f0e1 chore(deps): update pre-commit hook crate-ci/typos to v1.45.1 2026-04-15 13:21:38 +00:00
Jade 4dbf7f7673 ci: Remove unnecessary concurrency block 2026-04-15 13:21:11 +00:00
stratself ed76f50e71 fix(docs): Apply more changes to improve clarity and grammar
* CONTINUWUITY_WELL_KNOWN requires a "Struct", not a JSON array
* Fix all instances of Intl English to English English
* Typo/grammar nits fixings
2026-04-15 13:18:59 +00:00
stratself 1fe13b927d fix(docs): Remove bash shell indicator 2026-04-15 13:18:59 +00:00
stratself b11989504a fix(docs): Apply some suggestions to improve docs clarity
* fix(docs): Change all "commandline" to "command-line"
* fix(docs): Standardize "config options" as the word to use for config
  file params
2026-04-15 13:18:59 +00:00
stratself 87fa184af7 docs: Remove the manually-generated env var reference page and its links
Maybe configuration.mdx could be rewritten for better clarity on
converting between config param <-> env var
2026-04-15 13:18:59 +00:00
stratself aa9d43fad6 docs: Add order of config priority and rewrite --execute command info
* fix(docs): smaller wordings

May need to consider a separate section for "runtime configuration"
i.e. --execute and --maintenance modes
2026-04-15 13:18:59 +00:00
stratself cbcada087b docs: Rework environment variable section in Configuration docs
* docs: Move detailed explanations in Env Var ref page to Config page
* docs: Add env var example for double nested configs and array
  declaration
2026-04-15 13:18:59 +00:00
stratself 9489369b75 docs: Add Env Var reference page to navigation bar 2026-04-15 13:18:59 +00:00
stratself 9d11f56393 docs(delegation): Add remark on .well-knowns against alt setups
* Also incorporate feedback from PR comments
2026-04-15 09:53:26 +00:00
stratself 72eabc9796 docs(delegation): Add section for manually serving .well-knowns files
* Also add note on default support contacts
* Also add individual env vars for .well-knowns
2026-04-15 09:53:26 +00:00
stratself 2ca758425c fix(docs): Remove matrix. subdomains in composes
Delegation can be re-added in future commits
2026-04-15 09:52:18 +00:00
stratself 991859a9e4 ci: Ignore changelog.d/ dir changes when building images/bins
.mdx files were also added to ignored paths for extras
2026-04-15 09:51:00 +00:00
Sebastian Spaeth b202e82c26 ci: Fix mirror-images step
Blind attempt at fixing the:
> 'runs-on' key not defined in Release Docker Image/merge-release
> 'runs-on' key not defined in Release Docker Image/merge-maxperf

Errors in the release-image CI
2026-04-15 06:40:33 +02:00
Sebastian Spaeth a7fc905490 ci: Run mirror-images less often
Run it once a night for regular cleanup etc and after each release-image
workflow instead of doing it blindly every 2 hours.

This will only run the mirror job if BOTH build types were
successful, but it is better than nothing, and we have the nightly run
to pick up everything else.

Thanks @jade for the quick feedback and hand-holding in creating this.
2026-04-14 23:30:01 +02:00
ginger d482e0ae3a chore: Fix changelog 2026-04-14 13:20:03 +00:00
stratself eccdb285b8 docs(dns,troubleshooting): Grammar edits and few fixes
Add "DNS server overload" title to one of the sections
2026-04-13 17:44:01 +00:00
stratself 682c82d38b fix(docs,dns): Correct value for dnsproxy option, and a word 2026-04-13 17:44:01 +00:00
stratself dae95740d2 docs(dns): Remove None section, add dedicated Forwarders section 2026-04-13 17:44:01 +00:00
stratself 194252f446 docs(dns): Add dnsproxy's version of Serve Stale, remove Prefetch advice
Prefetch can make sense, but most homeserver IPs are static anyways
2026-04-13 17:44:01 +00:00
stratself b12275a660 chore: Add newsfrag for #1601 2026-04-13 17:44:01 +00:00
stratself 583a63ad30 chore(docs): Add DNS tuning navigation 2026-04-13 17:44:01 +00:00
stratself 3d08c0c4b4 docs(troubleshooting): Add section on intermittent fed failures
Also some wordfixings in dns docs
2026-04-13 17:44:01 +00:00
stratself 9d237d105f docs(troubleshooting): shorten dns section and link to dns tuning guide 2026-04-13 17:44:01 +00:00
stratself f20dfaeee4 docs(dns): Clarity changes and some additions 2026-04-13 17:44:01 +00:00
stratself 17e95a404c docs(dns): Add main content 2026-04-13 17:44:01 +00:00
stratself 6978cbbe60 docs(dns): Initialize dns docs 2026-04-13 17:44:01 +00:00
stratself 955a695138 docs(docker): New "Other" section and move Docker section there
* Also add warning that server name cannot be changed
* Some other copyediting
2026-04-13 17:34:36 +00:00
stratself 33091822b7 docs(docker,delegation): revert delegation changes, small wording fixes 2026-04-13 17:34:36 +00:00
stratself 27fcd7fe3a docs(docker,delegation): Fix .well-known docs - check below for details
.well-known env var in example composes now point to `example.com:443`,
and are turned on by default for Caddy labels and the Traefik configs.
For the Caddyfile example, they're left uncommented. Added small
bulletpoint on how to use this env var. Consistencize all the
.well-known comments inside these composes.

I don't want to overly fix the example composes and get it wrong, so
this small change should be enough. Split-domain deployments are fully
outsourced to the Delegation page now, and some changes are also made
there to be more comprehensive.
2026-04-13 17:34:36 +00:00
stratself 7f92659a98 docs(docker): Revert to mounting /etc/resolv.conf as configs: won't work
* Fix wording to make mounting resolv.conf more imperative
* Linting and other changes
2026-04-13 17:34:36 +00:00
stratself 8bebec6687 docs(docker): Update links for DNS tuning guide 2026-04-13 17:34:36 +00:00
stratself feabb732f9 fix(docs): exclude local .yml URLs from dead link checking 2026-04-13 17:34:36 +00:00
stratself 7354c64034 chore: Add changelog for #1594 2026-04-13 17:34:36 +00:00
stratself dccf1b97c8 docs(docker): Rewrite Docker DNS workaround with custom resolv.conf
Instead of /etc/resolv.conf on host. This works around the
systemd-resolved footgunning issue and provide an inline way to
configure resolvers, separate from that of the host system.
2026-04-13 17:34:36 +00:00
stratself 8dfdd1f662 docs(docker): Document the new initial registration flow
* Also add a note disclaiming that Docker is for demo purposes only
* Use port 8008 for Docker Quick Run instructions
* Remove the steps to create first admin user

I do believe "Docker - Quick Run" should be moved to after Docker
Compose section, but will want to discuss this before advancing
2026-04-13 17:34:36 +00:00
stratself 6a8850b556 docs(docker): Make example ymls raw-viewable and other copyedit fixes
* Move all *.yml files to docs/public/deploying so they can be viewable
  as raw files on the webpage
* Link to those files with "(view raw)"
* Move minimal environment variables to Docker Compose section
* Unheading the Docker Quick Run stuff to prepare deprioritizing them
* Remove redundant Registry column in Image table
* Rename reverse proxy subsections to have software name as first word
2026-04-13 17:34:36 +00:00
stratself a575e21598 docs(docker): Remove dynamic.yml file and related config lines
The file defines an HSTS middleware and cipher suite prefs, which
should not be needed for a simple deployment
2026-04-13 17:34:36 +00:00
stratself eeeb23b634 docs(docker): Add Caddy via Caddyfile deployment and prioritise them
* Add compose and included Caddyfile using caddy:latest official image
* Rename old Caddy files as caddy-labels.yml and new one as caddy.yml
* Remove external: true network in caddy-labels.yml to simplify docs
* Move all Caddy selections to top, unprioritize Traefik and other RPs
2026-04-13 17:34:36 +00:00
stratself aa53b01b69 docs(docker): Consistencize all domains to example.com and port to 8008
Included some additional comments. .well-known Delegation seems to be
much more convenient for traefik + caddy. How they're documented can be
decided in a future commit.
2026-04-13 17:34:36 +00:00
stratself b55cb5580c docs(docker): Remove unnecessary parts from all current compose files
* Remove unnecessary c10y env vars
* Remove unnecessary comment about image build and vim
* Remove references to Element-Web

Other changes like unified port and domain names will be in a future
commit
2026-04-13 17:34:36 +00:00
stratself fbdaa32743 docs(docker): Merge Prerequisites and Images into "Preparation" section
* docs: Remove Matrix Federation Requirements for simpler deployments
* docs: Remove redundant env vars in Docker - Quick Run
2026-04-13 17:34:36 +00:00
stratself aa0bd60ba4 docs(docker): Upsection headings by one level
* docs: "Docker - Quick Run" and "Docker Compose" are now two top-level
  sections
* docs: Mark building your images as "(Optional)"
* docs: Move calls to "Next step" section
2026-04-13 17:34:36 +00:00
stratself cc1706bb83 docs(docker): Rework section on available images
* docs: Make "Available Images" a top-level option, to be followed by
  Docker and Docker Compose sections in a future commit
* docs: Make "Mirrors" a subsection of "Available images", and add
  links to the mirrors themselves
* docs: Use indirect linkages to URLs for better maintainability
* docs: Remove initial sentence and its reference to the (advanced)
  building your image flow
* docs: Recommend `latest` OCI tag and include link to
2026-04-13 17:34:36 +00:00
Renovate Bot 604316eebe chore(deps): update https://github.com/taiki-e/install-action digest to d0f2322 2026-04-13 09:56:49 +00:00
Renovate Bot a5af7b39bd chore(deps): pin dependencies 2026-04-13 05:22:53 +00:00
Renovate Bot d83483abb2 chore(deps): update ghcr.io/renovatebot/renovate docker tag to v43.111.0 2026-04-13 05:02:21 +00:00
Jade Ellis fb286017f3 ci: Just remove the cache dance action 2026-04-12 19:41:12 +01:00
Renovate Bot cf73f13a11 chore(deps): update dependency cargo-bins/cargo-binstall to v1.18.0 2026-04-12 18:31:23 +00:00
Jade Ellis 420c28873c ci: Skip cache dance if cache isn't available 2026-04-12 18:35:46 +01:00
Jade Ellis fdb40c9758 ci: Compare against the merge base to avoid unneded triggers 2026-04-12 17:36:22 +01:00
Jade Ellis d961fb1515 ci: Rename changelog check workflow 2026-04-12 16:33:38 +00:00
Jade Ellis 44ebf1f526 ci: Fail when changelog is missing 2026-04-12 16:33:38 +00:00
Jade Ellis f02a08de57 ci: Use labels for changelog rather than comments 2026-04-12 16:33:38 +00:00
Jade Ellis ab241f8f65 chore(deps): Update sd-notify 2026-04-12 16:36:28 +01:00
Renovate Bot 45d316999a chore(deps): update rust crate sd-notify to 0.5.0 2026-04-12 15:33:08 +00:00
Jade Ellis b81aea642a fix(deps): Upgrade crypto crates to matching versions 2026-04-12 16:29:02 +01:00
Renovate Bot f3e8160d9b chore(deps): update rust crate hmac to 0.13.0 2026-04-12 15:03:55 +00:00
300 changed files with 8254 additions and 7479 deletions

No files matched your search

@@ -44,7 +44,7 @@ runs:
- name: Login to builtin registry
if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }}
uses: docker/login-action@v4
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4
with:
registry: ${{ env.BUILTIN_REGISTRY }}
username: ${{ inputs.registry_user }}
@@ -52,7 +52,7 @@ runs:
- name: Set up Docker Buildx
if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }}
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4
with:
# Use persistent BuildKit if BUILDKIT_ENDPOINT is set (e.g. tcp://buildkit:8125)
driver: ${{ env.BUILDKIT_ENDPOINT != '' && 'remote' || 'docker-container' }}
@@ -61,7 +61,7 @@ runs:
- name: Extract metadata (tags) for Docker
if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }}
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6
with:
flavor: |
latest=auto
@@ -67,7 +67,7 @@ runs:
uses: ./.forgejo/actions/rust-toolchain
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4
with:
# Use persistent BuildKit if BUILDKIT_ENDPOINT is set (e.g. tcp://buildkit:8125)
driver: ${{ env.BUILDKIT_ENDPOINT != '' && 'remote' || 'docker-container' }}
@@ -75,11 +75,11 @@ runs:
- name: Set up QEMU
if: ${{ env.BUILDKIT_ENDPOINT == '' }}
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4
- name: Login to builtin registry
if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }}
uses: docker/login-action@v4
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4
with:
registry: ${{ env.BUILTIN_REGISTRY }}
username: ${{ inputs.registry_user }}
@@ -87,7 +87,7 @@ runs:
- name: Extract metadata (labels, annotations) for Docker
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6
with:
images: ${{ inputs.images }}
# default labels & annotations: https://github.com/docker/metadata-action/blob/master/src/meta.ts#L509
@@ -111,59 +111,3 @@ runs:
- uses: ./.forgejo/actions/timelord
id: timelord
- name: Cache Rust registry
if: ${{ env.BUILDKIT_ENDPOINT == '' }}
uses: actions/cache@v3
with:
path: |
.cargo/git
.cargo/git/checkouts
.cargo/registry
.cargo/registry/src
key: continuwuity-rust-registry-image-${{hashFiles('**/Cargo.lock') }}
- name: Cache cargo target
if: ${{ env.BUILDKIT_ENDPOINT == '' }}
id: cache-cargo-target
uses: actions/cache@v3
with:
path: |
cargo-target${{ env.CPU_SUFFIX }}-${{ inputs.slug }}-${{ inputs.profile }}
key: continuwuity-cargo-target${{ env.CPU_SUFFIX }}-${{ inputs.slug }}-${{ inputs.profile }}-${{hashFiles('**/Cargo.lock') }}-${{steps.rust-toolchain.outputs.rustc_version}}
- name: Cache apt cache
if: ${{ env.BUILDKIT_ENDPOINT == '' }}
id: cache-apt
uses: actions/cache@v3
with:
path: |
var-cache-apt-${{ inputs.slug }}
key: continuwuity-var-cache-apt-${{ inputs.slug }}
- name: Cache apt lib
if: ${{ env.BUILDKIT_ENDPOINT == '' }}
id: cache-apt-lib
uses: actions/cache@v3
with:
path: |
var-lib-apt-${{ inputs.slug }}
key: continuwuity-var-lib-apt-${{ inputs.slug }}
- name: inject cache into docker
if: ${{ env.BUILDKIT_ENDPOINT == '' }}
uses: https://github.com/reproducible-containers/buildkit-cache-dance@v3.3.2
with:
cache-map: |
{
".cargo/registry": "/usr/local/cargo/registry",
".cargo/git/db": "/usr/local/cargo/git/db",
"cargo-target${{ env.CPU_SUFFIX }}-${{ inputs.slug }}-${{ inputs.profile }}": {
"target": "/app/target",
"id": "cargo-target${{ env.CPU_SUFFIX }}-${{ inputs.slug }}-${{ inputs.profile }}"
},
"var-cache-apt-${{ inputs.slug }}": "/var/cache/apt",
"var-lib-apt-${{ inputs.slug }}": "/var/lib/apt",
"${{ steps.timelord.outputs.database-path }}":"/timelord"
}
skip-extraction: ${{ steps.cache.outputs.cache-hit }}
+1 -1
View File
@@ -33,7 +33,7 @@ runs:
echo "version=$(rustup --version)" >> $GITHUB_OUTPUT
- name: Cache rustup toolchains
if: steps.rustup-version.outputs.version == ''
uses: actions/cache@v3
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
~/.rustup
@@ -57,7 +57,7 @@ runs:
- name: Check for LLVM cache
id: cache
uses: actions/cache@v4
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/usr/bin/clang-*
@@ -120,7 +120,7 @@ runs:
- name: Install additional packages
if: inputs.extra-packages != ''
uses: https://github.com/awalsh128/cache-apt-pkgs-action@latest
uses: https://github.com/awalsh128/cache-apt-pkgs-action@2c09a5e66da6c8016428a2172bd76e5e4f14bb17 # latest
with:
packages: ${{ inputs.extra-packages }}
version: 1.0
+2 -2
View File
@@ -65,7 +65,7 @@ runs:
- name: Cache toolchain binaries
id: toolchain-cache
uses: actions/cache@v4
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
.cargo/bin
@@ -76,7 +76,7 @@ runs:
- name: Cache Cargo registry and git
id: registry-cache
uses: actions/cache@v4
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
.cargo/registry/index
+5 -5
View File
@@ -31,7 +31,7 @@ runs:
- name: Restore binary cache
id: binary-cache
uses: actions/cache/restore@v4
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/usr/share/rust/.cargo/bin
@@ -71,13 +71,13 @@ runs:
- name: Install timelord-cli and git-warp-time
if: steps.check-binaries.outputs.need-install == 'true'
uses: https://github.com/taiki-e/install-action@v2
uses: https://github.com/taiki-e/install-action@a2352fc6ce487f030a3aa709482d57823eadfb37 # v2
with:
tool: git-warp-time,timelord-cli@3.0.1
- name: Save binary cache
if: steps.check-binaries.outputs.need-install == 'true'
uses: actions/cache/save@v4
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/usr/share/rust/.cargo/bin
@@ -87,7 +87,7 @@ runs:
- name: Restore timelord cache with fallbacks
id: timelord-restore
uses: actions/cache/restore@v4
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: ${{ env.TIMELORD_CACHE_PATH }}
key: ${{ env.TIMELORD_KEY }}
@@ -114,7 +114,7 @@ runs:
timelord sync --source-dir ${{ env.TIMELORD_PATH }} --cache-dir ${{ env.TIMELORD_CACHE_PATH }}
- name: Save updated timelord cache immediately
uses: actions/cache/save@v4
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: ${{ env.TIMELORD_CACHE_PATH }}
key: ${{ env.TIMELORD_KEY }}
+2 -2
View File
@@ -54,13 +54,13 @@ jobs:
fi
- name: Checkout repository with full history
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
fetch-depth: 0
ref: ${{ github.ref_name }}
- name: Cache Cargo registry
uses: actions/cache@v4
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
~/.cargo/registry
+4 -4
View File
@@ -30,14 +30,14 @@ jobs:
echo "Fedora version: $VERSION"
- name: Checkout repository with full history
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
fetch-depth: 0
ref: ${{ github.ref_name }}
- name: Cache DNF packages
uses: actions/cache@v4
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/var/cache/dnf
@@ -47,7 +47,7 @@ jobs:
dnf-fedora${{ steps.fedora.outputs.version }}-
- name: Cache Cargo registry
uses: actions/cache@v4
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
~/.cargo/registry
@@ -57,7 +57,7 @@ jobs:
cargo-fedora${{ steps.fedora.outputs.version }}-
- name: Cache Rust build dependencies
uses: actions/cache@v4
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
~/rpmbuild/BUILD/*/target/release/deps
+33 -42
View File
@@ -1,13 +1,8 @@
name: Check Changelog
name: Checks / Changelog
on:
pull_request_target:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
cancel-in-progress: true
types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
permissions:
contents: read
@@ -16,11 +11,11 @@ permissions:
jobs:
check-changelog:
name: Check for changelog
name: Check changelog is added
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
@@ -33,9 +28,9 @@ jobs:
git fetch origin ${GITHUB_BASE_REF}
# Check for Added (A) or Modified (M) files in changelog.d
CHANGELOG_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF} HEAD -- changelog.d/)
CHANGELOG_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF}...HEAD -- changelog.d/)
SRC_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF} HEAD -- src/)
SRC_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF}...HEAD -- src/)
echo "Changes in changelog.d/:"
echo "$CHANGELOG_CHANGES"
@@ -54,7 +49,7 @@ jobs:
echo "src_changed=false" >> $GITHUB_OUTPUT
fi
- name: Manage PR Comment
- name: Manage PR Labels
uses: https://github.com/actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
env:
HAS_CHANGELOG: ${{ steps.check_files.outputs.has_changelog }}
@@ -63,41 +58,37 @@ jobs:
script: |
const hasChangelog = process.env.HAS_CHANGELOG === 'true';
const srcChanged = process.env.SRC_CHANGED === 'true';
const commentSignature = '<!-- changelog-check-action -->';
const commentBody = `${commentSignature}\nPlease add a changelog fragment to \`changelog.d/\` describing your changes.`;
const { data: currentUser } = await github.rest.users.getAuthenticated();
const { data: comments } = await github.rest.issues.listComments({
const { data: pullRequest } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
pull_number: context.issue.number,
});
const botComment = comments.find(comment =>
comment.user.id === currentUser.id &&
comment.body.includes(commentSignature)
);
const currentLabels = pullRequest.labels.map(l => l.name);
const shouldWarn = srcChanged && !hasChangelog;
if (!shouldWarn) {
if (botComment) {
console.log('Changelog found or not required. Deleting existing warning comment.');
await github.rest.issues.deleteComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: botComment.id,
});
}
if (hasChangelog) {
console.log('PR has changelog');
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels: ['Changelog/Added'],
});
} else if (currentLabels.includes('Changelog/None')) {
console.log('PR has Changelog/None label, skipping.');
} else if (srcChanged) {
console.log('PR is missing changelog');
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels: ['Changelog/Missing'],
});
core.setFailed("Missing changelog entry (detected)");
} else if (currentLabels.includes('Changelog/Missing')) {
core.setFailed("Missing changelog entry (label)");
} else {
if (!botComment) {
console.log('Changelog missing and required. Creating warning comment.');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: commentBody,
});
}
console.log('Changelog not needed');
// Changelog is probably not needed
}
+5 -5
View File
@@ -21,7 +21,7 @@ jobs:
steps:
- name: Sync repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
fetch-depth: 0
@@ -32,12 +32,12 @@ jobs:
- name: Setup Node.js
if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20'
uses: https://github.com/actions/setup-node@v6
uses: https://github.com/actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version: 22
- name: Cache npm dependencies
uses: actions/cache@v3
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: ~/.npm
key: continuwuity-rspress-${{ steps.runner-env.outputs.slug }}-${{ steps.runner-env.outputs.arch }}-node-${{ steps.runner-env.outputs.node_version }}-${{ hashFiles('package-lock.json') }}
@@ -56,7 +56,7 @@ jobs:
- name: Deploy to Cloudflare Pages (Production)
if: github.ref == 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != ''
uses: https://github.com/cloudflare/wrangler-action@v3
uses: https://github.com/cloudflare/wrangler-action@9acf94ace14e7dc412b076f2c5c20b8ce93c79cd # v3
with:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
@@ -64,7 +64,7 @@ jobs:
- name: Deploy to Cloudflare Pages (Preview)
if: github.ref != 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != ''
uses: https://github.com/cloudflare/wrangler-action@v3
uses: https://github.com/cloudflare/wrangler-action@9acf94ace14e7dc412b076f2c5c20b8ce93c79cd # v3
with:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+2 -2
View File
@@ -24,7 +24,7 @@ jobs:
steps:
- name: 📦 Setup Node.js
uses: https://github.com/actions/setup-node@v6
uses: https://github.com/actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version: "22"
@@ -121,7 +121,7 @@ jobs:
- name: 🚀 Deploy to Cloudflare Pages
if: vars.CLOUDFLARE_PROJECT_NAME != ''
id: deploy
uses: https://github.com/cloudflare/wrangler-action@v3
uses: https://github.com/cloudflare/wrangler-action@9acf94ace14e7dc412b076f2c5c20b8ce93c79cd # v3
with:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+7 -4
View File
@@ -2,8 +2,11 @@ name: Mirror Container Images
on:
schedule:
# Run every 2 hours
- cron: "0 */2 * * *"
# Run nightly
- cron: "25 2 * * *"
workflow_call:
workflow_dispatch:
inputs:
dry_run:
@@ -38,7 +41,7 @@ jobs:
DOCKER_MIRROR_TOKEN: ${{ secrets.DOCKER_MIRROR_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
@@ -52,7 +55,7 @@ jobs:
# repositories: continuwuity
- name: Install regsync
uses: https://github.com/regclient/actions/regsync-installer@main
uses: https://github.com/regclient/actions/regsync-installer@f3c6d87835906c175eb6ccfc18b348b69bb447e7 # main
- name: Check what images need mirroring
run: |
+2 -2
View File
@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
@@ -47,7 +47,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
+18 -6
View File
@@ -9,6 +9,9 @@ on:
paths-ignore:
- "*.md"
- "**/*.md"
- "*.mdx"
- "**/*.mdx"
- "changelog.d/**"
- ".gitlab-ci.yml"
- ".gitignore"
- "renovate.json"
@@ -43,7 +46,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
- name: Prepare Docker build environment
@@ -59,7 +62,7 @@ jobs:
registry_password: ${{ secrets.BUILTIN_REGISTRY_PASSWORD || secrets.GITHUB_TOKEN }}
- name: Build and push Docker image by digest
id: build
uses: docker/build-push-action@v7
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7
with:
context: .
file: "docker/Dockerfile"
@@ -97,7 +100,7 @@ jobs:
needs: build-release
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
- name: Create multi-platform manifest
@@ -130,7 +133,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
- name: Prepare max-perf Docker build environment
@@ -146,7 +149,7 @@ jobs:
registry_password: ${{ secrets.BUILTIN_REGISTRY_PASSWORD || secrets.GITHUB_TOKEN }}
- name: Build and push max-perf Docker image by digest
id: build
uses: docker/build-push-action@v7
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7
with:
context: .
file: "docker/Dockerfile"
@@ -184,7 +187,7 @@ jobs:
needs: build-maxperf
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: false
- name: Create max-perf manifest
@@ -195,3 +198,12 @@ jobs:
images: ${{ env.IMAGE_PATH }}
registry_user: ${{ vars.BUILTIN_REGISTRY_USER || github.actor }}
registry_password: ${{ secrets.BUILTIN_REGISTRY_PASSWORD || secrets.GITHUB_TOKEN }}
mirror_images:
name: "Mirror Images"
runs-on: ubuntu-latest
needs:
- merge-maxperf
- merge-release
secrets: inherit
uses: ./.forgejo/workflows/mirror-images.yml
+8 -8
View File
@@ -43,11 +43,11 @@ jobs:
name: Renovate
runs-on: ubuntu-latest
container:
image: ghcr.io/renovatebot/renovate:43.59.4@sha256:f951508dea1e7d71cbe6deca298ab0a05488e7631229304813f630cc06010892
image: ghcr.io/renovatebot/renovate:43.111.0@sha256:da5fcac20c48d9792aac9c61fd234531bfa8df61263a39387cd8920263ca4768
options: --tmpfs /tmp:exec
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
show-progress: false
@@ -55,7 +55,7 @@ jobs:
run: /usr/local/renovate/node -e 'console.log(`node heap limit = ${require("v8").getHeapStatistics().heap_size_limit / (1024 * 1024)} Mb`)'
- name: Restore renovate repo cache
uses: actions/cache/restore@v4
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/tmp/renovate/cache/renovate/repository
@@ -64,7 +64,7 @@ jobs:
renovate-repo-cache-
- name: Restore renovate package cache
uses: actions/cache/restore@v4
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/tmp/renovate/cache/renovate/renovate-cache-sqlite
@@ -73,7 +73,7 @@ jobs:
renovate-package-cache-
- name: Restore renovate OSV cache
uses: actions/cache/restore@v4
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/tmp/osv
@@ -109,7 +109,7 @@ jobs:
- name: Save renovate repo cache
if: always()
uses:
actions/cache/save@v4
actions/cache/save@v5
with:
path: |
/tmp/renovate/cache/renovate/repository
@@ -117,7 +117,7 @@ jobs:
- name: Save renovate package cache
if: always()
uses: actions/cache/save@v4
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/tmp/renovate/cache/renovate/renovate-cache-sqlite
@@ -125,7 +125,7 @@ jobs:
- name: Save renovate OSV cache
if: always()
uses: actions/cache/save@v4
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: |
/tmp/osv
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
update-flake-hashes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
persist-credentials: true
token: ${{ secrets.FORGEJO_TOKEN }}
+1 -1
View File
@@ -24,7 +24,7 @@ repos:
- id: check-added-large-files
- repo: https://github.com/crate-ci/typos
rev: v1.45.0
rev: v1.45.1
hooks:
- id: typos
- id: typos
Generated
+223 -119
View File
@@ -618,7 +618,7 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest",
"digest 0.10.7",
]
[[package]]
@@ -630,6 +630,15 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block-buffer"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
dependencies = [
"hybrid-array",
]
[[package]]
name = "block2"
version = "0.6.2"
@@ -884,6 +893,12 @@ dependencies = [
"cc",
]
[[package]]
name = "cmov"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f88a43d011fc4a6876cb7344703e297c71dda42494fee094d5f7c76bf13f746"
[[package]]
name = "color_quant"
version = "1.1.0"
@@ -921,7 +936,7 @@ dependencies = [
[[package]]
name = "conduwuit"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"clap",
"conduwuit_admin",
@@ -955,9 +970,8 @@ dependencies = [
[[package]]
name = "conduwuit_admin"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"assign",
"clap",
"conduwuit_api",
"conduwuit_core",
@@ -979,9 +993,8 @@ dependencies = [
[[package]]
name = "conduwuit_api"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"assign",
"async-trait",
"axum",
"axum-client-ip",
@@ -1005,18 +1018,17 @@ dependencies = [
"rand 0.10.1",
"reqwest",
"ruma",
"ruminuwuity",
"serde",
"serde_html_form",
"serde_json",
"sha1",
"sha1 0.11.0",
"tokio",
"tracing",
]
[[package]]
name = "conduwuit_build_metadata"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"built",
"cargo_metadata",
@@ -1024,11 +1036,10 @@ dependencies = [
[[package]]
name = "conduwuit_core"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"argon2",
"arrayvec",
"assign",
"axum",
"axum-extra",
"bytes",
@@ -1080,7 +1091,7 @@ dependencies = [
"tikv-jemallocator",
"tokio",
"tokio-metrics",
"toml 1.1.2+spec-1.1.0",
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-core",
"tracing-subscriber",
@@ -1089,7 +1100,7 @@ dependencies = [
[[package]]
name = "conduwuit_database"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"async-channel",
"conduwuit_core",
@@ -1109,7 +1120,7 @@ dependencies = [
[[package]]
name = "conduwuit_macros"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"cargo_toml",
"itertools 0.14.0",
@@ -1120,9 +1131,8 @@ dependencies = [
[[package]]
name = "conduwuit_router"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"assign",
"axum",
"axum-client-ip",
"axum-server",
@@ -1157,10 +1167,9 @@ dependencies = [
[[package]]
name = "conduwuit_service"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"askama",
"assign",
"async-trait",
"base64 0.22.1",
"blurhash",
@@ -1189,13 +1198,12 @@ dependencies = [
"regex",
"reqwest",
"ruma",
"ruminuwuity",
"rustyline-async",
"sd-notify",
"serde",
"serde-saphyr",
"serde_json",
"sha2",
"sha2 0.11.0",
"termimad",
"tokio",
"tracing",
@@ -1206,10 +1214,9 @@ dependencies = [
[[package]]
name = "conduwuit_web"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"askama",
"assign",
"async-trait",
"axum",
"axum-extra",
@@ -1290,6 +1297,16 @@ dependencies = [
"typewit",
]
[[package]]
name = "continuwuity-admin-api"
version = "0.1.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"ruma-common",
"serde",
"serde_json",
]
[[package]]
name = "convert_case"
version = "0.10.0"
@@ -1514,10 +1531,19 @@ dependencies = [
]
[[package]]
name = "ctor"
version = "0.9.1"
name = "crypto-common"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1c888a2a4f677017373fb6c01e13e318dd9e78758445ed5eb985e355d3f8281"
checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710"
dependencies = [
"hybrid-array",
]
[[package]]
name = "ctor"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95d0d11eb38e7642efca359c3cf6eb7b2e528182d09110165de70192b0352775"
dependencies = [
"ctor-proc-macro",
"dtor",
@@ -1530,6 +1556,15 @@ version = "0.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7ab264ea985f1bd27887d7b21ea2bb046728e05d11909ca138d700c494730db"
[[package]]
name = "ctutils"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
dependencies = [
"cmov",
]
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
@@ -1539,7 +1574,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"curve25519-dalek-derive",
"digest",
"digest 0.10.7",
"fiat-crypto",
"rustc_version",
"subtle",
@@ -1681,11 +1716,22 @@ version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"block-buffer 0.10.4",
"crypto-common 0.1.7",
"subtle",
]
[[package]]
name = "digest"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4850db49bf08e663084f7fb5c87d202ef91a3907271aff24a94eb97ff039153c"
dependencies = [
"block-buffer 0.12.0",
"crypto-common 0.2.1",
"ctutils",
]
[[package]]
name = "dispatch2"
version = "0.3.1"
@@ -1716,11 +1762,21 @@ dependencies = [
"litrs",
]
[[package]]
name = "draupnir-antispam"
version = "0.1.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"ruma-common",
"serde",
"serde_json",
]
[[package]]
name = "dtor"
version = "0.6.0"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30e4690622ab6700ced40fc370a3f07b7d111f0154bb6fb08f73b4c8834f75b6"
checksum = "17f72721db8027a4e96dd6fb50d2a1d32259c9d3da1b63dee612ccd981e14293"
dependencies = [
"dtor-proc-macro",
]
@@ -1755,8 +1811,9 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
dependencies = [
"curve25519-dalek",
"ed25519",
"rand_core 0.6.4",
"serde",
"sha2",
"sha2 0.10.9",
"subtle",
"zeroize",
]
@@ -2339,7 +2396,7 @@ dependencies = [
"http",
"httpdate",
"mime",
"sha1",
"sha1 0.10.6",
]
[[package]]
@@ -2419,11 +2476,11 @@ dependencies = [
[[package]]
name = "hmac"
version = "0.12.1"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
"digest 0.11.2",
]
[[package]]
@@ -2511,6 +2568,15 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"
[[package]]
name = "hybrid-array"
version = "0.4.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214"
dependencies = [
"typenum",
]
[[package]]
name = "hyper"
version = "1.9.0"
@@ -2870,20 +2936,30 @@ dependencies = [
[[package]]
name = "js_option"
version = "0.2.0"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7dd3e281add16813cf673bf74a32249b0aa0d1c8117519a17b3ada5e8552b3c"
checksum = "68421373957a1593a767013698dbf206e2b221eefe97a44d98d18672ff38423c"
dependencies = [
"serde_core",
"serde",
]
[[package]]
name = "konst"
version = "0.4.3"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f660d5f887e3562f9ab6f4a14988795b694099d66b4f5dedc02d197ba9becb1d"
checksum = "4381b9b00c55f251f2ebe9473aef7c117e96828def1a7cb3bd3f0f903c6894e9"
dependencies = [
"const_panic",
"konst_kernel",
"typewit",
]
[[package]]
name = "konst_kernel"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4b1eb7788f3824c629b1116a7a9060d6e898c358ebff59070093d51103dcc3c"
dependencies = [
"typewit",
]
@@ -3042,9 +3118,9 @@ dependencies = [
[[package]]
name = "link-section"
version = "0.0.12"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52437d47b0358721ec869cc7374b2a21f7b2237af9b439c0391341a1fbfbf1b"
checksum = "468808413fa8bdf0edbe61c2bbc182dfc59885b94f496cf3fb42c9c96b1e0149"
[[package]]
name = "linked-hash-map"
@@ -3214,6 +3290,16 @@ dependencies = [
"walkdir",
]
[[package]]
name = "meowlnir-antispam"
version = "0.1.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"ruma-common",
"serde",
"serde_json",
]
[[package]]
name = "mime"
version = "0.3.17"
@@ -4494,27 +4580,31 @@ dependencies = [
[[package]]
name = "ruma"
version = "0.14.1"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.10.1"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"assign",
"continuwuity-admin-api",
"draupnir-antispam",
"js_int",
"js_option",
"meowlnir-antispam",
"ruma-appservice-api",
"ruma-client-api",
"ruma-common",
"ruma-events",
"ruma-federation-api",
"ruma-identifiers-validation",
"ruma-identity-service-api",
"ruma-push-gateway-api",
"ruma-signatures",
"ruma-state-res",
"web-time",
]
[[package]]
name = "ruma-appservice-api"
version = "0.14.1"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.10.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"js_int",
"ruma-common",
@@ -4525,12 +4615,13 @@ dependencies = [
[[package]]
name = "ruma-client-api"
version = "0.22.1"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.18.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"as_variant",
"assign",
"bytes",
"date_header",
"http",
"js_int",
"js_option",
@@ -4547,15 +4638,14 @@ dependencies = [
[[package]]
name = "ruma-common"
version = "0.17.1"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.13.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"as_variant",
"base64 0.22.1",
"bytes",
"date_header",
"form_urlencoded",
"getrandom 0.4.2",
"getrandom 0.2.17",
"http",
"indexmap",
"js_int",
@@ -4568,6 +4658,7 @@ dependencies = [
"serde",
"serde_html_form",
"serde_json",
"smallvec",
"thiserror 2.0.18",
"time",
"tracing",
@@ -4575,34 +4666,37 @@ dependencies = [
"uuid",
"web-time",
"wildmatch",
"zeroize",
]
[[package]]
name = "ruma-events"
version = "0.32.1"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.28.1"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"as_variant",
"indexmap",
"js_int",
"js_option",
"percent-encoding",
"pulldown-cmark",
"regex",
"ruma-common",
"ruma-identifiers-validation",
"ruma-macros",
"serde",
"serde_json",
"smallvec",
"thiserror 2.0.18",
"tracing",
"url",
"web-time",
"wildmatch",
"zeroize",
]
[[package]]
name = "ruma-federation-api"
version = "0.13.1"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.9.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"bytes",
"headers",
@@ -4615,7 +4709,6 @@ dependencies = [
"rand 0.10.1",
"ruma-common",
"ruma-events",
"ruma-signatures",
"serde",
"serde_json",
"thiserror 2.0.18",
@@ -4624,19 +4717,28 @@ dependencies = [
[[package]]
name = "ruma-identifiers-validation"
version = "0.12.0"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.9.5"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"js_int",
"thiserror 2.0.18",
]
[[package]]
name = "ruma-identity-service-api"
version = "0.9.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"js_int",
"ruma-common",
"serde",
]
[[package]]
name = "ruma-macros"
version = "0.17.1"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.13.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"as_variant",
"cfg-if",
"proc-macro-crate",
"proc-macro2",
@@ -4644,13 +4746,13 @@ dependencies = [
"ruma-identifiers-validation",
"serde",
"syn",
"toml 1.1.2+spec-1.1.0",
"toml 0.8.23",
]
[[package]]
name = "ruma-push-gateway-api"
version = "0.13.0"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.9.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"js_int",
"ruma-common",
@@ -4661,46 +4763,21 @@ dependencies = [
[[package]]
name = "ruma-signatures"
version = "0.19.0"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
version = "0.15.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=d00b51a8669b21689c4eb47fb81f3a8b27c3e371#d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
dependencies = [
"base64 0.22.1",
"ed25519-dalek",
"memchr",
"pkcs8",
"rand 0.10.1",
"rand_core 0.6.4",
"ruma-common",
"serde_json",
"sha2",
"sha2 0.10.9",
"subslice",
"thiserror 2.0.18",
]
[[package]]
name = "ruma-state-res"
version = "0.15.0"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=ce7ea072a3d47f1e674bb4badcb2af15b30e4088#ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
dependencies = [
"js_int",
"ruma-common",
"ruma-events",
"ruma-signatures",
"serde",
"serde_json",
"thiserror 2.0.18",
"tracing",
]
[[package]]
name = "ruminuwuity"
version = "0.5.7-alpha.1"
dependencies = [
"assign",
"ruma",
"serde",
"serde_json",
"wildmatch",
]
[[package]]
name = "rust-librocksdb-sys"
version = "0.42.0+10.10.1"
@@ -4902,9 +4979,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "sd-notify"
version = "0.4.5"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b943eadf71d8b69e661330cb0e2656e31040acf21ee7708e2c238a0ec6af2bf4"
checksum = "3e4ef7359e694bfaf1dd27a30f9d760b54c00dfae9f19bd0c05a39bc9128fe76"
dependencies = [
"libc",
]
@@ -5129,9 +5206,9 @@ dependencies = [
[[package]]
name = "serde_html_form"
version = "0.4.0"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0946d52b4b7e28823148aebbeceb901012c595ad737920d504fa8634bb099e6f"
checksum = "b2f2d7ff8a2140333718bb329f5c40fc5f0865b84c426183ce14c97d2ab8154f"
dependencies = [
"form_urlencoded",
"indexmap",
@@ -5212,7 +5289,18 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest",
"digest 0.10.7",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures 0.3.0",
"digest 0.11.2",
]
[[package]]
@@ -5223,7 +5311,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest",
"digest 0.10.7",
]
[[package]]
name = "sha2"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
dependencies = [
"cfg-if",
"cpufeatures 0.3.0",
"digest 0.11.2",
]
[[package]]
@@ -5235,7 +5334,7 @@ dependencies = [
"async-trait",
"bytes",
"hex",
"sha2",
"sha2 0.10.9",
"tokio",
]
@@ -5412,6 +5511,15 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subslice"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0a8e4809a3bb02de01f1f7faf1ba01a83af9e8eabcd4d31dd6e413d14d56aae"
dependencies = [
"memchr",
]
[[package]]
name = "subtle"
version = "2.6.1"
@@ -5740,19 +5848,6 @@ dependencies = [
"winnow 0.7.15",
]
[[package]]
name = "toml"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee"
dependencies = [
"serde_core",
"serde_spanned 1.1.1",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"winnow 1.0.1",
]
[[package]]
name = "toml_datetime"
version = "0.6.11"
@@ -6051,6 +6146,15 @@ name = "typewit"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc19094686c694eb41b3b99dcc2f2975d4b078512fa22ae6c63f7ca318bdcff7"
dependencies = [
"typewit_proc_macros",
]
[[package]]
name = "typewit_proc_macros"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e36a83ea2b3c704935a01b4642946aadd445cea40b10935e3f8bd8052b8193d6"
[[package]]
name = "uname"
@@ -6816,7 +6920,7 @@ dependencies = [
[[package]]
name = "xtask"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
dependencies = [
"askama",
"cargo_metadata",
+33 -34
View File
@@ -12,7 +12,7 @@ license = "Apache-2.0"
# See also `rust-toolchain.toml`
readme = "README.md"
repository = "https://forgejo.ellis.link/continuwuation/continuwuity"
version = "0.5.7-alpha.1"
version = "0.5.7-alpha.2"
[workspace.metadata.crane]
name = "conduwuit"
@@ -39,7 +39,7 @@ features = ["ffi", "std", "union"]
version = "0.7.0"
[workspace.dependencies.ctor]
version = "0.9.0"
version = "0.10.0"
[workspace.dependencies.cargo_toml]
version = "0.22"
@@ -47,9 +47,9 @@ default-features = false
features = ["features"]
[workspace.dependencies.toml]
version = "1.0.0"
version = "0.9.5"
default-features = false
features = ["parse", "serde"]
features = ["parse"]
[workspace.dependencies.sanitize-filename]
version = "0.6.0"
@@ -60,7 +60,7 @@ default-features = false
# used for TURN server authentication
[workspace.dependencies.hmac]
version = "0.12.1"
version = "0.13.0"
default-features = false
# used for checking if an IP is in specific subnets / CIDR ranges easier
@@ -68,7 +68,7 @@ default-features = false
version = "0.1.3"
[workspace.dependencies.rand]
version = "0.10.1"
version = "0.10.0"
# Used for the http request / response body type for Ruma endpoints used with reqwest
[workspace.dependencies.bytes]
@@ -167,7 +167,7 @@ version = "1.1.0"
# Used for ruma wrapper
[workspace.dependencies.serde_html_form]
version = "0.4.0"
version = "0.2.6"
# Used for password hashing
[workspace.dependencies.argon2]
@@ -340,48 +340,51 @@ version = "0.1.88"
[workspace.dependencies.lru-cache]
version = "0.1.2"
[workspace.dependencies.assign]
version = "1.1.1"
# Used for matrix spec type definitions and helpers
[workspace.dependencies.ruma]
# version = "0.14.1"
git = "https://github.com/gingershaped/ruwuma.git"
rev = "ce7ea072a3d47f1e674bb4badcb2af15b30e4088"
git = "https://forgejo.ellis.link/continuwuation/ruwuma"
#branch = "conduwuit-changes"
rev = "d00b51a8669b21689c4eb47fb81f3a8b27c3e371"
features = [
"compat",
"rand",
"appservice-api-c",
"client-api",
"federation-api",
"push-gateway-api-c",
"state-res",
"rand",
"markdown",
"push-gateway-api-c",
"unstable-exhaustive-types",
"ring-compat",
"compat-upload-signatures",
"identifiers-validation",
"unstable-unspecified",
"unstable-msc2448",
"unstable-msc2666",
"unstable-msc2867",
"unstable-msc2870",
"unstable-msc3026",
"unstable-msc3061",
"unstable-msc3814",
"unstable-msc3245",
"unstable-msc3381",
"unstable-msc3489",
"unstable-msc3930",
"unstable-msc3266",
"unstable-msc3381", # polls
"unstable-msc3489", # beacon / live location
"unstable-msc3575",
"unstable-msc3930", # polls push rules
"unstable-msc4075",
"unstable-msc4095",
"unstable-msc4121",
"unstable-msc4125",
"unstable-msc4155",
"unstable-msc4186",
"unstable-msc4195",
"unstable-msc4203",
"unstable-msc4310",
"unstable-msc4373",
"unstable-msc4380",
"unstable-msc4143",
"unstable-msc4406",
"unstable-msc4439",
"unstable-msc4203", # sending to-device events to appservices
"unstable-msc4210", # remove legacy mentions
"unstable-extensible-events",
"unstable-pdu",
"unstable-msc4155",
"unstable-msc4143", # livekit well_known response
"unstable-msc4284",
"unstable-msc4439", # pgp_key in .well_known/matrix/support
]
[workspace.dependencies.rust-rocksdb]
@@ -397,11 +400,11 @@ features = [
]
[workspace.dependencies.sha2]
version = "0.10.8"
version = "0.11.0"
default-features = false
[workspace.dependencies.sha1]
version = "0.10.6"
version = "0.11.0"
default-features = false
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
@@ -478,7 +481,7 @@ default-features = false
features = ["resource"]
[workspace.dependencies.sd-notify]
version = "0.4.5"
version = "0.5.0"
default-features = false
[workspace.dependencies.hardened_malloc-rs]
@@ -654,10 +657,6 @@ default-features = false
package = "conduwuit"
path = "src/main"
[workspace.dependencies.ruminuwuity]
package = "ruminuwuity"
path = "src/ruminuwuity"
###############################################################################
#
# Release profiles
-1
View File
@@ -1 +0,0 @@
Switched from Continuwuity's fork of Ruma back to upstream Ruma, unblocking exciting new features such as OAuth login. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Refactored docker docs to include new initial token workflow, and add Caddyfile example. Contributed by @stratself.
+1
View File
@@ -0,0 +1 @@
Add DNS tuning guide for Continuwuity. Users are recommended to set up a local caching resolver following the guide's advice. Contributed by @stratself
+1
View File
@@ -0,0 +1 @@
Implemented option to deprioritize servers for room join requests. Contributed by @ezera.
+26
View File
@@ -573,6 +573,18 @@
#
#allow_public_room_directory_over_federation = false
# Allow guests/unauthenticated users to access TURN credentials.
#
# This is the equivalent of Synapse's `turn_allow_guests` config option.
# This allows any unauthenticated user to call the endpoint
# `/_matrix/client/v3/voip/turnServer`.
#
# It is unlikely you need to enable this as all major clients support
# authentication for this endpoint and prevents misuse of your TURN server
# from potential bots.
#
#turn_allow_guests = false
# Set this to true to lock down your server's public room directory and
# only allow admins to publish rooms to the room directory. Unpublishing
# is still allowed by all users with this enabled.
@@ -1397,6 +1409,20 @@
#
#ignore_messages_from_server_names = []
# List of server names that continuwuity will deprioritize (try last) when
# a client requests to join a room.
#
# This can be used to potentially speed up room join requests, by
# deprioritizing sending join requests through servers that are known to
# be large or slow.
#
# continuwuity will still send join requests to servers in this list if
# the room couldn't be joined via other servers it federates with.
#
# example: ["example.com"]
#
#deprioritize_joins_through_servers = []
# Send messages from users that the user has ignored to the client.
#
# There is no way for clients to receive messages sent while a user was
+1 -1
View File
@@ -48,7 +48,7 @@ EOF
# Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.17.9
ENV BINSTALL_VERSION=1.18.1
# renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree
+1 -1
View File
@@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \
# Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.17.9
ENV BINSTALL_VERSION=1.18.1
# renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree
-5
View File
@@ -69,11 +69,6 @@
"label": "Configuration Reference",
"name": "/reference/config"
},
{
"type": "file",
"label": "Environment Variables",
"name": "/reference/environment-variables"
},
{
"type": "dir",
"label": "Admin Command Reference",
+6
View File
@@ -3,5 +3,11 @@
"type": "file",
"name": "delegation",
"label": "Delegation / split-domain"
},
{
"type": "file",
"name": "dns",
"label": "DNS tuning (recommended)"
}
]
+53 -4
View File
@@ -18,12 +18,14 @@ Then, in the `[global.well_known]` section of your config file, add the followin
```toml
[global.well_known]
# defaults to port :443 if not specified
client = "https://matrix.example.com"
# port number MUST be specified
server = "matrix.example.com:443"
# (optional) customize your support contacts
# Defaults to members of the admin room if unset
#support_page =
#support_role = "m.role.admin"
#support_email =
@@ -42,9 +44,13 @@ services:
client=https://matrix.example.com,
server=matrix.example.com:443
}
# You can also configure individual `.well-knowns` like this
# CONTINUWUITY_WELL_KNOWN__CLIENT: https://matrix.example.com
# CONTINUWUITY_WELL_KNOWN__SERVER: matrix.example.com:443
```
## Serving with a reverse proxy
## Reverse proxying well-known files to Continuwuity
After doing the steps above, Continuwuity will serve these 3 JSON files:
@@ -94,9 +100,7 @@ Restart Continuwuity and your reverse proxy. Once that's done, visit these route
<summary>`https://example.com/.well-known/matrix/server`</summary>
```json
{
"m.server": "matrix.example.com:443"
}
{ "m.server": "matrix.example.com:443" }
```
</details>
@@ -115,12 +119,57 @@ Restart Continuwuity and your reverse proxy. Once that's done, visit these route
</details>
### Serving well-known files manually
Instead of configuring `[global.well_known]` options and reverse proxying well-known URIs, you can serve these files directly as static JSON that match the ones above. This is useful if your base domain points to a different physical server, and reverse proxying isn't feasible.
<details>
<summary>Example Caddyfile **for the base domain**</summary>
```
https://example.com {
respond /.well-known/matrix/server 200 {
body `{"m.server":"matrix.example.com:443"}`
}
handle /.well-known/matrix/client {
header Access-Control-Allow-Origin *
respond <<JSON
{
"m.homeserver": {
"base_url": "https://matrix.example.com/"
}
}
JSON
}
}
```
</details>
Remember to set the `Access-Control-Allow-Origin: *` header in your `/.well-known/matrix/client` path for web clients to work.
## Troubleshooting
Check with the [Matrix Connectivity Tester][federation-tester] to see that it's working.
[federation-tester]: https://federationtester.mtrnord.blog/
### Cannot log in with web clients
Make sure there is an `Access-Control-Allow-Origin: *` header in your `/.well-known/matrix/client` path. While Continuwuity serves this header by default, it may be dropped by reverse proxies or other middlewares.
### Issues with alternative setups
As Matrix clients prioritize well-known URIs for their destination, this can lead to issues with alternative methods of accessing the server that doesn't use a publicly routeable IP and domain name. You will probably find yourself connecting to non-existent/undesired URLs in certain cases like:
- Accessing to the server via localhost IPs (e.g. for testing purposes)
- Accessing the server from behind a VPN, or from alternative networks (such as from an onionsite)
In these scenarios, further configurations would be needed. Refer to the [Related Documentation](#related-documentation) section for resolution steps and see how they could apply to your use case.
---
## Using SRV records (not recommended)
+165
View File
@@ -0,0 +1,165 @@
# DNS Tuning (recommended)
For federation, Matrix homeservers conduct an enormous amount of DNS requests, sometimes up to thousands of queries per minute. Normal DNS resolvers are simply not designed for this load, and running Continuwuity with them will likely result in various [DNS and federation errors](../troubleshooting#dns-issues).
To solve this issue, it is strongly recommended to self-host a high-quality, external caching DNS resolver for Continuwuity. This guide will use [Unbound][unbound] as the recommended example, but the general principle applies to any resolver.
[unbound]: https://wiki.archlinux.org/title/Unbound
## Overview
For generic deployments, install your resolver of choice and configure `/etc/resolv.conf` to point to it. The resolver should ideally reside on the same host as Continuwuity.
```txt title="/etc/resolv.conf"
nameserver 127.0.0.1
```
**Avoid using `systemd-resolved`** as it does **not** perform very well under high load, and we have identified its DNS caching to not be very effective.
### For Docker users
Docker bridge networks uses a non-performant resolver to intercept and respond to container hostnames, and **this should also be avoided**. Instead, mount a custom `/etc/resolv.conf` file into the container, and hardcode a resolver address to bypass Docker's.
It is recommended to run a dedicated resolver container for Continuwuity, as to separate from the host's resolver setup. To do this, create a custom bridge network and IP range, and explicitly define an IP address for the resolver container.
<details>
<summary>Example Docker deployment with unbound</summary>
```yaml title="docker-compose.yml"
networks:
matrix_net:
ipam:
driver: default
config:
- subnet: "10.10.10.0/24"
services:
homeserver:
# ...
volume:
- ./continuwuity-resolv.conf:/etc/resolv.conf:ro
unbound:
# ...
networks:
matrix_net:
ipv4_address: 10.10.10.20
```
```txt title="continuwuity-resolv.conf"
nameserver 10.10.10.20
```
</details>
### For IPv4-only users
If you don't have IPv6 connectivity, changing `ip_lookup_strategy` to only resolve for IPv4 will reduce unnecessary AAAA queries.
```toml title="continuwuity.toml"
[global]
# 1 - Ipv4Only (Only query for A records, no AAAA/IPv6)
ip_lookup_strategy = 1
```
## Unbound
[Unbound][unbound] is the recommended resolver to run with Continuwuity. For Docker users, the `docker.io/madnuttah/unbound` image ([Github repo][madnuttah-unbound-repo]) can be used.
After installation, you can tune `/etc/unbound/unbound.conf` values according to your needs. While Continuwuity cannot recommend a "works-for-everyone" Unbound DNS setup guide, the official [Unbound tuning guide][unbound-tuning-guide] and the [Unbound Arch Linux wiki page][unbound-arch-linux] may be of interest.
Some values that are commonly tuned include:
- Increase `rrset-cache-size` and `msg-cache-size` to something much higher than the default `4M`, such as `64M`.
- Increase `discard-timeout` to something like `4800` to wait longer for upstream resolvers, as recursion can take a long time to respond to some domains. Continuwuity default to `dns_timeout = 10` seconds, so dropping requests early would lead to unnecessary retries and/or failures.
### Using a forwarder (optional)
Unbound by default employs **recursive resolution** and contacts many servers around the world. If this is not performant enough, consider forwarding your queries to public resolvers to benefit from their CDNs and get faster responses.
However, most popular upstreams (such as Google DNS or Quad9) employ IP ratelimiting, so a generous cache is still needed to avoid making too many queries.
DNS-over-TLS forwarders may also be used should you need on-the-wire encryption, but TLS overhead causes some speed penalties.
If you want to use forwarders, configure it as follows:
<details>
<summary>unbound.conf</summary>
```
# Use cloudflare public resolvers as an example
forward-zone:
name: "."
forward-addr: 1.0.0.1@53
forward-addr: 1.1.1.1@53
# Also use IPv6 ones if you're dual-stack
# forward-addr: 2606:4700:4700::1001@53
# forward-addr: 2606:4700:4700::1111@53
# alternatively, use DNS-over-TLS for forwarders.
# forward-zone:
# name: "."
# forward-tls-upstream: yes
# forward-addr: 1.0.0.1@853#cloudflare-dns.com
# forward-addr: 1.1.1.1@853#cloudflare-dns.com
# forward-addr: 2606:4700:4700::1001@853#cloudflare-dns.com
# forward-addr: 2606:4700:4700::1111@853#cloudflare-dns.com
```
</details>
[madnuttah-unbound-repo]: https://github.com/madnuttah/unbound-docker/
[unbound-tuning-guide]: https://unbound.docs.nlnetlabs.nl/en/latest/topics/core/performance.html
[unbound-arch-linux]: https://wiki.archlinux.org/title/Unbound
## Other resolvers
### dnsproxy
[Dnsproxy][dnsproxy] and its sister product [AdGuard Home][adguard-home] are known to work with Continuwuity and has an official Docker image. They have support for DNS-over-HTTPS as well as DNS-over-QUIC, but not recursion.
To best utilise dnsproxy, you should enable proper caching with `--cache` and set `--cache-size` to something bigger, like `64000000`.
[dnsproxy]: https://github.com/AdguardTeam/dnsproxy
[adguard-home]: https://github.com/AdguardTeam/AdGuardHome
### dnsmasq
[dnsmasq][arch-linux-dnsmasq] can possibly work with Continuwuity, though it only supports forwarding rather than recursion. Increase the `cache-size` to something like `30000` for better caching performance.
However, `dnsmasq` does not support TCP fallback which can be problematic when receiving large DNS responses such as from large SRV records. If you still want to use dnsmasq, make sure you disable `dns_tcp_fallback` in Continuwuity config.
[arch-linux-dnsmasq]: https://wiki.archlinux.org/title/Dnsmasq
### Technitium
[Technitium][technitium] supports recursion as well as a myriad of forwarding protocols, allows saving cache to disk natively, and does work well with Continuwuity. Its default configurations however ratelimits single-IP requests by a lot, and hence must be changed. You may consult this [community guide][technitium-continuwuity] for more details on setting up a dedicated Technitium for Continuwuity.
[technitium]: https://github.com/TechnitiumSoftware/DnsServer
[technitium-continuwuity]: https://muoi.me/~stratself/articles/technitium-continuwuity/
## Testing
As a rough stress test, you can run `!admin query resolver flush-cache -a` or `!admin server clear-caches` to trigger a netburst of DNS queries. If your resolver can handle these loads without problem, then it should be ready for regular Continuwuity activity.
To test connectivity against a specific server, use `!admin debug ping <SERVER_NAME>` and `!admin debug resolve-true-destination <SERVER_NAME>`.
Note that it is expected that not all servers will be resolved, as some of them may be temporarily offline, have broken DNS and/or discovery configuration, or have been decommissioned.
## Further steps
- (Recommended) Set **`dns_cache_entries = 0`** inside Continuwuity and fully rely on the more performant external resolver.
- Consider employing **persistent cache to disk**, so your resolver can still run without hassle after a restart. Unbound, via [Cache DB module][unbound-cachedb], can use Redis as a storage backend for this feature.
- Consider [enabling **Serve Stale**][unbound-serve-stale] functionality to serve expired data beyond DNS TTLs. Since most Matrix homeservers have static IPs, this should help improve federation with them especially when upstream resolvers have timed out. For dnsproxy, this corresponds to its [optimistic caching options][dnsproxy-usage].
- If you still experience DNS performance issues, another step could be to **disable DNSSEC** (which is computationally expensive) at a cost of slightly decreased security. On Unbound this is done by commenting out `trust-anchors` config options and removing the `validator` module.
- Some users have reported that setting `query_over_tcp_only = true` in Continuwuity has improved DNS reliability at a slight performance cost due to TCP overhead. Generally this is not needed if your resolver and homeserver is on the same machine.
[unbound-cachedb]: https://unbound.docs.nlnetlabs.nl/en/latest/manpages/unbound.conf.html#cache-db-module-options
[unbound-serve-stale]: https://wiki.archlinux.org/title/Unbound#Serving_expired_records
[dnsproxy-usage]: https://github.com/AdguardTeam/dnsproxy#usage
+67 -43
View File
@@ -2,66 +2,90 @@
This chapter describes various ways to configure Continuwuity.
## Basics
## Configuration file
Continuwuity uses a config file for the majority of the settings, but also supports
setting individual config options via commandline.
Continuwuity uses a TOML config file for all of its settings. This is the recommended way to configure Continuwuity. Please refer to the [example config file](./reference/config.mdx) for all of these settings.
Please refer to the [example config
file](./reference/config.mdx) for all of those
settings.
You can specify the config file to be used by Continuwuity with the command-line flag `-c` or `--config`:
The config file to use can be specified on the commandline when running
Continuwuity by specifying the `-c`, `--config` flag. Alternatively, you can use
the environment variable `CONTINUWUITY_CONFIG` to specify the config file to be
used; see [the section on environment variables](#environment-variables) for
more information.
```bash
./conduwuit -c /path/to/continuwuity.toml
```
## Option commandline flag
Alternatively, you can use the environment variable `CONTINUWUITY_CONFIG` to specify the config file to be used; see [the section on environment variables](#environment-variables) for more information.
Continuwuity supports setting individual config options in TOML format from the
`-O` / `--option` flag. For example, you can set your server name via `-O
server_name=\"example.com\"`.
## Environment variables
All of the options in the config file can also be specified by using environment variables. This is ideal for containerised deployments and infrastructure-as-code scenarios.
The environment variable names are represented in all caps and prefixed with `CONTINUWUITY_`. They are mapped to config options in the ways demonstrated below:
```bash
# Top-level options (those inside the [global] section) are simply capitalised
CONTINUWUITY_SERVER_NAME="matrix.example.com"
CONTINUWUITY_PORT="8008"
CONTINUWUITY_DATABASE_PATH="/var/lib/continuwuity"
# Nested config sections use double underscores `__`
# This maps to the `server` field of the [global.well_known] section in TOML
CONTINUWUITY_WELL_KNOWN__SERVER="example.com:443"
# This maps to the `base_url` field of the `[global.antispam.draupnir]` section in TOML
CONTINUWUITY_ANTISPAM__DRAUPNIR__BASE_URL="https://draupnir.example.com"
# Alternatively, you can pass a (quoted) struct to define an entire section
# This maps to the [global.well_known] section
CONTINUWUITY_WELL_KNOWN="{ client=https://example.com,server=example.com:443 }"
```
### Alternative prefixes
For backwards compatibility, Continuwuity also supports the following environment variable prefixes, in order of descending priority:
- `CONDUWUIT_*` (compatibility)
- `CONDUIT_*` (legacy)
As an example, the environment variable `CONTINUWUITY_CONFIG` can also be expressed as `CONDUWUIT_CONFIG` or `CONDUIT_CONFIG`.
## Option command-line flag
Continuwuity also supports setting individual config options in TOML format from the `-O` / `--option` flag. For example, you can set your server name via `-O server_name=\"example.com\"`.
Note that the config is parsed as TOML, and shells like `bash` will remove quotes. Therefore, if the config option is a string, quote escapes must be properly handled. If the config option is a number or a boolean, this does not apply.
Note that the config is parsed as TOML, and shells like bash will remove quotes.
So unfortunately it is required to escape quotes if the config option takes a
string. This does not apply to options that take booleans or numbers:
- `--option allow_registration=true` works ✅
- `-O max_request_size=99999999` works ✅
- `-O server_name=example.com` does not work ❌
- `--option log=\"debug\"` works ✅
- `--option server_name='"example.com'"` works ✅
## Execute commandline flag
## Order of priority
Continuwuity supports running admin commands on startup using the commandline
argument `--execute`. The most notable use for this is to create an admin user
on first startup.
The above configuration methods are prioritised, in descending order, as below:
The syntax of this is a standard admin command without the prefix such as
`./conduwuit --execute "users create_user june"`
- Command-line `-o`/`--option` flags
- Environment variables
- `CONTINUWUITY_*` variables
- `CONDUWUIT_*` variables
- `CONDUIT_*` variables
- Config file
An example output of a success is:
```
Therefore, you can use environment variables or the options flags to override values in the config file.
---
## Executing startup commands
Continuwuity supports running admin commands on startup using the command-line flag `--execute`. This is treated as a standard admin command, without the need for the `!admin` prefix. For example, to create a new user:
```bash
# Equivalent to `!admin users create_user june`
./conduwuit --execute "users create_user june"
INFO conduwuit_service::admin::startup: Startup command #0 completed:
Created user with user_id: @june:girlboss.ceo and password: `<redacted>`
```
This commandline argument can be paired with the `--option` flag.
Alternatively, you can configure `CONTINUWUITY_ADMIN_EXECUTE` or the config file value `admin_execute` with a list of commands.
## Environment variables
All of the settings that are found in the config file can be specified by using
environment variables. The environment variable names should be all caps and
prefixed with `CONTINUWUITY_`.
For example, if the setting you are changing is `max_request_size`, then the
environment variable to set is `CONTINUWUITY_MAX_REQUEST_SIZE`.
To modify config options not in the `[global]` context such as
`[global.well_known]`, use the `__` suffix split:
`CONTINUWUITY_WELL_KNOWN__SERVER`
Conduit and conduwuit's environment variables are also supported for backwards
compatibility, via the `CONDUIT_` and `CONDUWUIT_` prefixes respectively (e.g.
`CONDUIT_SERVER_NAME`).
This command-line argument can be paired with the `--option` flag.
@@ -1,76 +0,0 @@
# Continuwuity - Behind Traefik Reverse Proxy
services:
homeserver:
### If you already built the continuwuity image with 'docker build' or want to use the Docker Hub image,
### then you are ready to go.
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
volumes:
- db:/var/lib/continuwuity
#- ./continuwuity.toml:/etc/continuwuity.toml
networks:
- proxy
labels:
- "traefik.enable=true"
- "traefik.http.routers.continuwuity.rule=(Host(`matrix.example.com`) || (Host(`example.com`) && PathPrefix(`/.well-known/matrix`)))"
- "traefik.http.routers.continuwuity.entrypoints=websecure" # your HTTPS entry point
- "traefik.http.routers.continuwuity.tls=true"
- "traefik.http.routers.continuwuity.service=continuwuity"
- "traefik.http.services.continuwuity.loadbalancer.server.port=6167"
# possibly, depending on your config:
# - "traefik.http.routers.continuwuity.tls.certresolver=letsencrypt"
environment:
CONTINUWUITY_SERVER_NAME: your.server.name.example # EDIT THIS
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_PORT: 6167 # should match the loadbalancer traefik label
CONTINUWUITY_MAX_REQUEST_SIZE: 20000000 # in bytes, ~20 MB
CONTINUWUITY_ALLOW_REGISTRATION: 'true'
CONTINUWUITY_REGISTRATION_TOKEN: 'YOUR_TOKEN' # A registration token is required when registration is allowed.
#CONTINUWUITY_YES_I_AM_VERY_VERY_SURE_I_WANT_AN_OPEN_REGISTRATION_SERVER_PRONE_TO_ABUSE: 'true'
CONTINUWUITY_ALLOW_FEDERATION: 'true'
CONTINUWUITY_ALLOW_CHECK_FOR_UPDATES: 'true'
CONTINUWUITY_TRUSTED_SERVERS: '["matrix.org"]'
#CONTINUWUITY_LOG: warn,state_res=warn
CONTINUWUITY_ADDRESS: 0.0.0.0
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
# We need some way to serve the client and server .well-known json. The simplest way is via the CONTINUWUITY_WELL_KNOWN
# variable / config option, there are multiple ways to do this, e.g. in the continuwuity.toml file, and in a separate
# see the override file for more information about delegation
CONTINUWUITY_WELL_KNOWN: |
{
client=https://your.server.name.example,
server=your.server.name.example:443
}
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
ulimits: # Continuwuity uses quite a few file descriptors, and on some systems it defaults to 1024, so you can tell docker to increase it
nofile:
soft: 1048567
hard: 1048567
### Uncomment if you want to use your own Element-Web App.
### Note: You need to provide a config.json for Element and you also need a second
### Domain or Subdomain for the communication between Element and Continuwuity
### Config-Docs: https://github.com/vector-im/element-web/blob/develop/docs/config.md
# element-web:
# image: vectorim/element-web:latest
# restart: unless-stopped
# volumes:
# - ./element_config.json:/app/config.json
# networks:
# - proxy
# depends_on:
# - homeserver
volumes:
db:
networks:
# This is the network Traefik listens to, if your network has a different
# name, don't forget to change it here and in the docker-compose.override.yml
proxy:
external: true
# vim: ts=2:sw=2:expandtab
@@ -1,60 +0,0 @@
services:
caddy:
# This compose file uses caddy-docker-proxy as the reverse proxy for Continuwuity!
# For more info, visit https://github.com/lucaslorentz/caddy-docker-proxy
image: lucaslorentz/caddy-docker-proxy:ci-alpine
ports:
- 80:80
- 443:443
environment:
- CADDY_INGRESS_NETWORKS=caddy
networks:
- caddy
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data:/data
restart: unless-stopped
labels:
caddy: example.com
caddy.reverse_proxy: /.well-known/matrix/* homeserver:6167
homeserver:
### If you already built the Continuwuity image with 'docker build' or want to use a registry image,
### then you are ready to go.
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
volumes:
- db:/var/lib/continuwuity
- /etc/resolv.conf:/etc/resolv.conf:ro # Use the host's DNS resolver rather than Docker's.
#- ./continuwuity.toml:/etc/continuwuity.toml
environment:
CONTINUWUITY_SERVER_NAME: example.com # EDIT THIS
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_PORT: 6167
CONTINUWUITY_MAX_REQUEST_SIZE: 20000000 # in bytes, ~20 MB
CONTINUWUITY_ALLOW_REGISTRATION: 'true'
CONTINUWUITY_REGISTRATION_TOKEN: 'YOUR_TOKEN' # A registration token is required when registration is allowed.
#CONTINUWUITY_YES_I_AM_VERY_VERY_SURE_I_WANT_AN_OPEN_REGISTRATION_SERVER_PRONE_TO_ABUSE: 'true'
CONTINUWUITY_ALLOW_FEDERATION: 'true'
CONTINUWUITY_ALLOW_CHECK_FOR_UPDATES: 'true'
CONTINUWUITY_TRUSTED_SERVERS: '["matrix.org"]'
#CONTINUWUITY_LOG: warn,state_res=warn
CONTINUWUITY_ADDRESS: 0.0.0.0
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
# Required for .well-known delegation - edit these according to your chosen domain
CONTINUWUITY_WELL_KNOWN__CLIENT: https://matrix.example.com
CONTINUWUITY_WELL_KNOWN__SERVER: matrix.example.com:443
networks:
- caddy
labels:
caddy: matrix.example.com
caddy.reverse_proxy: "{{upstreams 6167}}"
volumes:
db:
networks:
caddy:
external: true
@@ -1,160 +0,0 @@
# Continuwuity - Behind Traefik Reverse Proxy
services:
homeserver:
### If you already built the Continuwuity image with 'docker build' or want to use the Docker Hub image,
### then you are ready to go.
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
volumes:
- db:/var/lib/continuwuity
- /etc/resolv.conf:/etc/resolv.conf:ro # Use the host's DNS resolver rather than Docker's.
#- ./continuwuity.toml:/etc/continuwuity.toml
networks:
- proxy
labels:
- "traefik.enable=true"
- "traefik.http.routers.continuwuity.rule=(Host(`matrix.example.com`) || (Host(`example.com`) && PathPrefix(`/.well-known/matrix`)))"
- "traefik.http.routers.continuwuity.entrypoints=websecure"
- "traefik.http.routers.continuwuity.tls.certresolver=letsencrypt"
- "traefik.http.services.continuwuity.loadbalancer.server.port=6167"
# Uncomment and adjust the following if you want to use middleware
# - "traefik.http.routers.continuwuity.middlewares=secureHeaders@file"
environment:
CONTINUWUITY_SERVER_NAME: your.server.name.example # EDIT THIS
CONTINUWUITY_TRUSTED_SERVERS: '["matrix.org"]'
CONTINUWUITY_ALLOW_REGISTRATION: 'false' # After setting a secure registration token, you can enable this
CONTINUWUITY_REGISTRATION_TOKEN: "" # This is a token you can use to register on the server
#CONTINUWUITY_REGISTRATION_TOKEN_FILE: "" # Alternatively you can configure a path to a token file to read
CONTINUWUITY_ADDRESS: 0.0.0.0
CONTINUWUITY_PORT: 6167 # you need to match this with the traefik load balancer label if you're want to change it
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
### Uncomment and change values as desired, note that Continuwuity has plenty of config options, so you should check out the example example config too
# Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging
# CONTINUWUITY_LOG: info # default is: "warn,state_res=warn"
# CONTINUWUITY_ALLOW_ENCRYPTION: 'true'
# CONTINUWUITY_ALLOW_FEDERATION: 'true'
# CONTINUWUITY_ALLOW_CHECK_FOR_UPDATES: 'true'
# CONTINUWUITY_ALLOW_INCOMING_PRESENCE: true
# CONTINUWUITY_ALLOW_OUTGOING_PRESENCE: true
# CONTINUWUITY_ALLOW_LOCAL_PRESENCE: true
# CONTINUWUITY_WORKERS: 10
# CONTINUWUITY_MAX_REQUEST_SIZE: 20000000 # in bytes, ~20 MB
# CONTINUWUITY_NEW_USER_DISPLAYNAME_SUFFIX = "🏳<200d>⚧"
# We need some way to serve the client and server .well-known json. The simplest way is via the CONTINUWUITY_WELL_KNOWN
# variable / config option, there are multiple ways to do this, e.g. in the continuwuity.toml file, and in a separate
# reverse proxy, but since you do not have a reverse proxy and following this guide, this example is included
CONTINUWUITY_WELL_KNOWN: |
{
client=https://your.server.name.example,
server=your.server.name.example:443
}
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
ulimits: # Continuwuity uses quite a few file descriptors, and on some systems it defaults to 1024, so you can tell docker to increase it
nofile:
soft: 1048567
hard: 1048567
### Uncomment if you want to use your own Element-Web App.
### Note: You need to provide a config.json for Element and you also need a second
### Domain or Subdomain for the communication between Element and Continuwuity
### Config-Docs: https://github.com/vector-im/element-web/blob/develop/docs/config.md
# element-web:
# image: vectorim/element-web:latest
# restart: unless-stopped
# volumes:
# - ./element_config.json:/app/config.json
# networks:
# - proxy
# depends_on:
# - homeserver
traefik:
image: "traefik:latest"
container_name: "traefik"
restart: "unless-stopped"
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:z"
- "acme:/etc/traefik/acme"
#- "./traefik_config:/etc/traefik:z"
labels:
- "traefik.enable=true"
# middleware redirect
- "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
# global redirect to https
- "traefik.http.routers.redirs.rule=hostregexp(`{host:.+}`)"
- "traefik.http.routers.redirs.entrypoints=web"
- "traefik.http.routers.redirs.middlewares=redirect-to-https"
configs:
- source: dynamic.yml
target: /etc/traefik/dynamic.yml
environment:
TRAEFIK_LOG_LEVEL: DEBUG
TRAEFIK_ENTRYPOINTS_WEB: true
TRAEFIK_ENTRYPOINTS_WEB_ADDRESS: ":80"
TRAEFIK_ENTRYPOINTS_WEB_HTTP_REDIRECTIONS_ENTRYPOINT_TO: websecure
TRAEFIK_ENTRYPOINTS_WEBSECURE: true
TRAEFIK_ENTRYPOINTS_WEBSECURE_ADDRESS: ":443"
TRAEFIK_ENTRYPOINTS_WEBSECURE_HTTP_TLS_CERTRESOLVER: letsencrypt
#TRAEFIK_ENTRYPOINTS_WEBSECURE_HTTP_MIDDLEWARES: secureHeaders@file # if you want to enabled STS
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT: true
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_EMAIL: # Set this to the email you want to receive certificate expiration emails for
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_KEYTYPE: EC384
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_HTTPCHALLENGE: true
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_HTTPCHALLENGE_ENTRYPOINT: web
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_STORAGE: "/etc/traefik/acme/acme.json"
# Since Traefik 3.6.3, paths with certain "encoded characters" are now blocked by default; we need a couple, or else things *will* break
TRAEFIK_ENTRYPOINTS_WEBSECURE_HTTP_ENCODEDCHARACTERS_ALLOWENCODEDSLASH: true
TRAEFIK_ENTRYPOINTS_WEBSECURE_HTTP_ENCODEDCHARACTERS_ALLOWENCODEDHASH: true
TRAEFIK_PROVIDERS_DOCKER: true
TRAEFIK_PROVIDERS_DOCKER_ENDPOINT: "unix:///var/run/docker.sock"
TRAEFIK_PROVIDERS_DOCKER_EXPOSEDBYDEFAULT: false
TRAEFIK_PROVIDERS_FILE: true
TRAEFIK_PROVIDERS_FILE_FILENAME: "/etc/traefik/dynamic.yml"
configs:
dynamic.yml:
content: |
# Optionally set STS headers, like in https://hstspreload.org
# http:
# middlewares:
# secureHeaders:
# headers:
# forceSTSHeader: true
# stsIncludeSubdomains: true
# stsPreload: true
# stsSeconds: 31536000
tls:
options:
default:
cipherSuites:
- TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
- TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
- TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
minVersion: VersionTLS12
volumes:
db:
acme:
networks:
proxy:
# vim: ts=2:sw=2:expandtab
-45
View File
@@ -1,45 +0,0 @@
# Continuwuity
services:
homeserver:
### If you already built the Continuwuity image with 'docker build' or want to use a registry image,
### then you are ready to go.
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
ports:
- 8448:6167
volumes:
- db:/var/lib/continuwuity
#- ./continuwuity.toml:/etc/continuwuity.toml
environment:
CONTINUWUITY_SERVER_NAME: your.server.name # EDIT THIS
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_PORT: 6167
CONTINUWUITY_MAX_REQUEST_SIZE: 20000000 # in bytes, ~20 MB
CONTINUWUITY_ALLOW_REGISTRATION: 'true'
CONTINUWUITY_REGISTRATION_TOKEN: 'YOUR_TOKEN' # A registration token is required when registration is allowed.
#CONTINUWUITY_YES_I_AM_VERY_VERY_SURE_I_WANT_AN_OPEN_REGISTRATION_SERVER_PRONE_TO_ABUSE: 'true'
CONTINUWUITY_ALLOW_FEDERATION: 'true'
CONTINUWUITY_ALLOW_CHECK_FOR_UPDATES: 'true'
CONTINUWUITY_TRUSTED_SERVERS: '["matrix.org"]'
#CONTINUWUITY_LOG: warn,state_res=warn
CONTINUWUITY_ADDRESS: 0.0.0.0
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
#
### Uncomment if you want to use your own Element-Web App.
### Note: You need to provide a config.json for Element and you also need a second
### Domain or Subdomain for the communication between Element and Continuwuity
### Config-Docs: https://github.com/vector-im/element-web/blob/develop/docs/config.md
# element-web:
# image: vectorim/element-web:latest
# restart: unless-stopped
# ports:
# - 8009:80
# volumes:
# - ./element_config.json:/app/config.json
# depends_on:
# - homeserver
volumes:
db:
+188 -194
View File
@@ -1,257 +1,251 @@
# Continuwuity for Docker
## Docker
## Preparation
To run Continuwuity with Docker, you can either build the image yourself or pull
it from a registry.
### Choose an image
### Use a registry
The following OCI images are available for Continuwuity:
Available OCI images:
| Image | Notes |
| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| [https://forgejo.ellis.link/continuwuation/continuwuity:**latest**][latest] | Latest tagged release. (recommended) |
| [https://forgejo.ellis.link/continuwuation/continuwuity:**main**][main] | Latest `main` branch commit. |
| [https://forgejo.ellis.link/continuwuation/continuwuity:**latest-maxperf**][latest-maxperf] | Latest tagged release, [performance optimised version](./generic.mdx#performance-optimised-builds). |
| [https://forgejo.ellis.link/continuwuation/continuwuity:**main-maxperf**][main-maxperf] | Latest `main` branch commit, [performance optimised version](./generic.mdx#performance-optimised-builds). |
| Registry | Image | Notes |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| Forgejo Registry | [forgejo.ellis.link/continuwuation/continuwuity:latest](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/latest) | Latest tagged image. |
| Forgejo Registry | [forgejo.ellis.link/continuwuation/continuwuity:main](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/main) | Main branch image. |
| Forgejo Registry | [forgejo.ellis.link/continuwuation/continuwuity:latest-maxperf](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/latest-maxperf) | [Performance optimised version.](./generic.mdx#performance-optimised-builds) |
| Forgejo Registry | [forgejo.ellis.link/continuwuation/continuwuity:main-maxperf](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/main-maxperf) | [Performance optimised version.](./generic.mdx#performance-optimised-builds) |
[latest]: https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/latest
[main]: https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/main
[latest-maxperf]: https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/latest-maxperf
[main-maxperf]: https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/main-maxperf
**Example:**
If you want a specific version or commit hash, you can browse for them [here][oci-all-versions].
```bash
docker image pull forgejo.ellis.link/continuwuation/continuwuity:main-maxperf
```
Images are also mirrored to these locations automatically, on a schedule:
#### Mirrors
- `ghcr.io/continuwuity/continuwuity` ([Github Registry][ghcr-io])
- `docker.io/jadedblueeyes/continuwuity` ([Docker Hub][docker-hub])
- `registry.gitlab.com/continuwuity/continuwuity` ([Gitlab Registry][gitlab-registry])
- `git.nexy7574.co.uk/mirrored/continuwuity` ([Nexy's forge][nexy-forge]. Releases only, no `main` tags)
Images are mirrored to multiple locations automatically, on a schedule:
[oci-all-versions]: https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/versions
[ghcr-io]: https://github.com/continuwuity/continuwuity/pkgs/container/continuwuity/versions?filters%5Bversion_type%5D=tagged
[docker-hub]: https://hub.docker.com/r/jadedblueeyes/continuwuity/
[gitlab-registry]: https://gitlab.com/continuwuity/continuwuity/container_registry/8871720
[nexy-forge]: https://git.nexy7574.co.uk/mirrored/-/packages/container/continuwuity/versions
- `ghcr.io/continuwuity/continuwuity`
- `docker.io/jadedblueeyes/continuwuity`
- `registry.gitlab.com/continuwuity/continuwuity`
- `git.nexy7574.co.uk/mirrored/continuwuity` (releases only, no `main`)
### Quick Run
Get a working Continuwuity server with an admin user in four steps:
#### Prerequisites
### Prerequisites
Continuwuity requires HTTPS for Matrix federation. You'll need:
- A domain name pointing to your server
- A reverse proxy with SSL/TLS certificates (Traefik, Caddy, nginx, etc.)
- A domain name pointing to your server's IP address - we will be using `example.com` in this guide.
- A reverse proxy with SSL/TLS certificates (Traefik, Caddy, nginx, etc.) - see [Docker Compose](#docker-compose) for complete examples.
- Port `:443` (for Client-Server traffic) and `:8448` (for federation traffic) opened on your server's firewall.
See [Docker Compose](#docker-compose) for complete examples.
- Alternatively, if you want both client and federation traffic on `:443`, you can configure `CONTINUWUITY_WELL_KNOWN` following some of the [examples](#choose-your-reverse-proxy) below.
#### Environment Variables
- `CONTINUWUITY_SERVER_NAME` - Your Matrix server's domain name
- `CONTINUWUITY_DATABASE_PATH` - Where to store your database (must match the
volume mount)
- `CONTINUWUITY_ADDRESS` - Bind address (use `0.0.0.0` to listen on all
interfaces)
- `CONTINUWUITY_ALLOW_REGISTRATION` - Set to `false` to disable registration, or
use with `CONTINUWUITY_REGISTRATION_TOKEN` to require a token (see
[reference](../reference/environment-variables.mdx#registration--user-configuration)
for details)
See the
[Environment Variables Reference](../reference/environment-variables.mdx) for
more configuration options.
#### 1. Pull the image
```bash
docker pull forgejo.ellis.link/continuwuation/continuwuity:latest
```
#### 2. Start the server with initial admin user
```bash
docker run -d \
-p 6167:6167 \
-v continuwuity_db:/var/lib/continuwuity \
-e CONTINUWUITY_SERVER_NAME="matrix.example.com" \
-e CONTINUWUITY_DATABASE_PATH="/var/lib/continuwuity" \
-e CONTINUWUITY_ADDRESS="0.0.0.0" \
-e CONTINUWUITY_ALLOW_REGISTRATION="false" \
--name continuwuity \
forgejo.ellis.link/continuwuation/continuwuity:latest \
/sbin/conduwuit --execute "users create-user admin"
```
Replace `matrix.example.com` with your actual server name and `admin` with
your preferred username.
#### 3. Get your admin password
```bash
docker logs continuwuity 2>&1 | grep "Created user"
```
You'll see output like:
```
Created user with user_id: @admin:matrix.example.com and password: `[auto-generated-password]`
```
#### 4. Configure your reverse proxy
Configure your reverse proxy to forward HTTPS traffic to Continuwuity. See
[Docker Compose](#docker-compose) for examples.
Once configured, log in with any Matrix client using `@admin:matrix.example.com`
and the generated password. You'll automatically be invited to the admin room
where you can manage your server.
### Docker Compose
Docker Compose is the recommended deployment method. These examples include
reverse proxy configurations for Matrix federation.
#### Matrix Federation Requirements
For Matrix federation to work, you need to serve `.well-known/matrix/client` and
`.well-known/matrix/server` endpoints. You can achieve this either by:
1. **Using a well-known service** - The compose files below include an nginx
container to serve these files
2. **Using Continuwuity's built-in delegation** (easier for Traefik) - Configure
delegation files in your config, then proxy `/.well-known/matrix/*` to
Continuwuity
**Traefik example using built-in delegation:**
```yaml
labels:
traefik.http.routers.continuwuity.rule: >-
(Host(`matrix.example.com`) ||
(Host(`example.com`) && PathPrefix(`/.well-known/matrix`)))
```
This routes your Matrix domain and well-known paths to Continuwuity.
#### Creating Your First Admin User
Add the `--execute` command to create an admin user on first startup. In your
compose file, add under the `continuwuity` service:
```yaml
services:
continuwuity:
image: forgejo.ellis.link/continuwuation/continuwuity:latest
command: /sbin/conduwuit --execute "users create-user admin"
# ... rest of configuration
```
Then retrieve the auto-generated password:
```bash
docker compose logs continuwuity | grep "Created user"
```
#### Choose Your Reverse Proxy
Select the compose file that matches your setup:
:::note DNS Performance
Docker's default DNS resolver can cause performance issues with Matrix
federation. If you experience slow federation or DNS timeouts, you may need to
use your host's DNS resolver instead. Add this volume mount to the
`continuwuity` service:
```yaml
volumes:
- /etc/resolv.conf:/etc/resolv.conf:ro
```
See [Troubleshooting - DNS Issues](../troubleshooting.mdx#potential-dns-issues-when-using-docker)
for more details and alternative solutions.
:::tip Split-domain setups
For more setups with `.well-known` delegation and split-domain deployments, consult the [Delegation/Split-domain](../advanced/delegation) page.
:::
##### For existing Traefik setup
## Docker Compose
Docker Compose is the recommended deployment method for Continuwuity containers. The following environment variables will be set:
- `CONTINUWUITY_SERVER_NAME` - Your Matrix server's domain name. **This CANNOT be changed later without a data wipe.**
- `CONTINUWUITY_DATABASE_PATH` - Where to store your database. This must match the docker volume mount.
- `CONTINUWUITY_ADDRESS` - Bind address (for Docker, use `0.0.0.0` to listen on all interfaces).
Alternatively, you can specify a path to mount the configuration file using the `CONTINUWUITY_CONFIG` environment variable.
See the [reference configuration](../reference/config) page for all config options, and the [Configuration page](../configuration#environment-variables) on how to convert them into Environment Variables.
### Choose Your Reverse Proxy
These examples include reverse proxy configurations for Matrix federation, which will route your Matrix domain (and optionally .well-known paths) to Continuwuity.
:::note Docker DNS Performance
Docker's default DNS resolver are known to [cause timeout issues](../troubleshooting#dns-issues) for Matrix federation. To bypass it and use a more performant resolver, mount a custom `/etc/resolv.conf` config file into the Continuwuity container.
```yaml title='docker-compose.yml'
services:
homeserver:
# ...
volumes:
- ./continuwuity-resolv.conf:/etc/resolv.conf
```
```txt title='continuwuity-resolv.conf'
nameserver 1.0.0.1
nameserver 1.1.1.1
```
Consult the [**DNS tuning guide (recommended)**](../advanced/dns.mdx) for full solutions to this issue.
:::
#### Caddy (using Caddyfile)
<details>
<summary>docker-compose.for-traefik.yml</summary>
<summary>docker-compose.with-caddy.yml ([view raw](/deploying/docker-compose.with-caddy.yml))</summary>
```yaml file="./docker-compose.for-traefik.yml"
```yaml file="../public/deploying/docker-compose.with-caddy.yml"
```
</details>
##### With Traefik included
#### Caddy (using labels)
<details>
<summary>docker-compose.with-traefik.yml</summary>
<summary>docker-compose.with-caddy-labels.yml ([view raw](/deploying/docker-compose.with-caddy-labels.yml))</summary>
```yaml file="./docker-compose.with-traefik.yml"
```yaml file="../public/deploying/docker-compose.with-caddy-labels.yml"
```
</details>
##### With Caddy Docker Proxy
#### Traefik (for existing setup)
<details>
<summary>docker-compose.with-caddy.yml</summary>
<summary>docker-compose.for-traefik.yml ([view raw](/deploying/docker-compose.for-traefik.yml))</summary>
Replace all `example.com` placeholders with your own domain.
```yaml file="./docker-compose.with-caddy.yml"
```
If you don't already have a network for Caddy to monitor, create one first:
```bash
docker network create caddy
```
</details>
##### For other reverse proxies
<details>
<summary>docker-compose.yml</summary>
```yaml file="./docker-compose.yml"
```yaml file="../public/deploying/docker-compose.for-traefik.yml"
```
</details>
##### Override file for customisation
#### Traefik included
<details>
<summary>docker-compose.override.yml</summary>
<summary>docker-compose.with-traefik.yml ([view raw](/deploying/docker-compose.with-traefik.yml))</summary>
```yaml file="./docker-compose.override.yml"
```yaml file="../public/deploying/docker-compose.with-traefik.yml"
```
</details>
#### Starting Your Server
#### Traefik (as override file)
1. Choose your compose file and rename it to `docker-compose.yml`
<details>
<summary>docker-compose.override.yml ([view raw](/deploying/docker-compose.override.yml))</summary>
```yaml file="../public/deploying/docker-compose.override.yml"
```
</details>
#### For other reverse proxies
<details>
<summary>docker-compose.yml ([view raw](/deploying/docker-compose.yml))</summary>
```yaml file="../public/deploying/docker-compose.yml"
```
</details>
You will then need to point your reverse proxy towards Continuwuity at `127.0.0.1:8008`. See the [Other reverse proxies](generic.mdx#setting-up-the-reverse-proxy) section of the Generic page for further routing details.
### Starting Your Server
1. Choose your compose file from the above, and rename it to `docker-compose.yml`. Replace `example.com` with your homeserver's domain name, and edit other values as you see fit.
2. If using the override file, rename it to `docker-compose.override.yml` and
edit your values
edit your values.
3. Start the server:
```bash
docker compose up -d
```
```bash
docker compose up -d
```
4. Check your server logs for a registration token:
```bash
docker-compose logs continuwuity 2>&1
```
You'll see output as below.
```
In order to use your new homeserver, you need to create its
first user account.
Open your Matrix client of choice and register an account
on example.com using registration token x5keUZ811RqvLsNa .
Pick your own username and password!
```
5. Log in to your server with any Matrix client, and register for an account with the registration token from step 4. You'll automatically be invited to the admin room where you can [manage your server](../reference/admin).
See the [generic deployment guide](generic.mdx) for more deployment options.
### Building Custom Images
## Testing
Test that your setup works by following these [instructions](./generic.mdx#how-do-i-know-it-works)
## Other deployment methods
### Docker - Quick Run
:::note For testing only
The instructions below are only meant for a quick demo of Continuwuity.
For production deployment, we recommend using [Docker Compose](#docker-compose)
:::
Get a working Continuwuity server with an admin user in four steps:
1. Pull the image
```bash
docker pull forgejo.ellis.link/continuwuation/continuwuity:latest
```
2. Start the server for the first time. Replace `example.com` with your actual server name.
```bash
docker run -d \
-p 8008:8008 \
-v continuwuity_db:/var/lib/continuwuity \
-e CONTINUWUITY_SERVER_NAME="example.com" \
-e CONTINUWUITY_DATABASE_PATH="/var/lib/continuwuity" \
-e CONTINUWUITY_ADDRESS="0.0.0.0" \
-e CONTINUWUITY_ALLOW_REGISTRATION="false" \
--name continuwuity \
forgejo.ellis.link/continuwuation/continuwuity:latest \
/sbin/conduwuit
```
3. Fetch the one-time initial registration token
```bash
docker logs continuwuity 2>&1
```
You'll see output as below.
```
In order to use your new homeserver, you need to create its
first user account.
Open your Matrix client of choice and register an account
on example.com using registration token x5keUZ811RqvLsNa .
Pick your own username and password!
```
4. Configure your reverse proxy to forward HTTPS traffic to Continuwuity at port 8008. See [Docker Compose](#docker-compose) for examples.
Once configured, log in to your server with any Matrix client, and register for an account with the registration token from step 3. You'll automatically be invited to the admin room where you can [manage your server](../reference/admin).
### (Optional) Building Custom Images
For information on building your own Continuwuity Docker images, see the
[Building Docker Images](../development/index.mdx#building-docker-images)
section in the development documentation.
## Voice communication
## Next steps
See the [Calls](../calls.mdx) page.
- For smooth federation, set up a caching resolver according to the [**DNS tuning guide**](../advanced/dns.mdx) (recommended)
- To set up Audio/Video communication, see the [**Calls**](../calls.mdx) page.
- If you want to set up an appservice, take a look at the [**Appservice
Guide**](../appservices.mdx).
@@ -0,0 +1,44 @@
# Continuwuity - Behind Traefik Reverse Proxy
services:
homeserver:
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
volumes:
- db:/var/lib/continuwuity
- ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's
#- ./continuwuity.toml:/etc/continuwuity.toml
networks:
- proxy
labels:
- "traefik.enable=true"
- "traefik.http.routers.continuwuity.rule=(Host(`example.com`))"
- "traefik.http.routers.continuwuity.entrypoints=websecure" # your HTTPS entry point
- "traefik.http.routers.continuwuity.tls=true"
- "traefik.http.routers.continuwuity.service=continuwuity"
- "traefik.http.services.continuwuity.loadbalancer.server.port=8008"
# possibly, depending on your config:
# - "traefik.http.routers.continuwuity.tls.certresolver=letsencrypt"
environment:
CONTINUWUITY_SERVER_NAME: example.com
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_ADDRESS: 0.0.0.0
CONTINUWUITY_PORT: 8008 # This must match with traefik's loadbalancer label
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
# Serve .well-known files to tell others to reach Continuwuity on port :443
CONTINUWUITY_WELL_KNOWN: |
{
client=https://example.com,
server=example.com:443
}
volumes:
db:
networks:
# This is the network Traefik listens to, if your network has a different
# name, don't forget to change it here and in the docker-compose.override.yml
proxy:
external: true
@@ -6,11 +6,13 @@ services:
- "traefik.enable=true"
- "traefik.docker.network=proxy" # Change this to the name of your Traefik docker proxy network
- "traefik.http.routers.to-continuwuity.rule=Host(`<SUBDOMAIN>.<DOMAIN>`)" # Change to the address on which Continuwuity is hosted
- "traefik.http.routers.to-continuwuity.rule=Host(`example.com`)" # Change to the address on which Continuwuity is hosted
- "traefik.http.routers.to-continuwuity.tls=true"
- "traefik.http.routers.to-continuwuity.tls.certresolver=letsencrypt"
- "traefik.http.routers.to-continuwuity.middlewares=cors-headers@docker"
- "traefik.http.services.to_continuwuity.loadbalancer.server.port=6167"
# This must match with CONTINUWUITY_PORT (default: 8008)
- "traefik.http.services.to_continuwuity.loadbalancer.server.port=8008"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowOriginList=*"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowHeaders=Origin, X-Requested-With, Content-Type, Accept, Authorization"
@@ -18,19 +20,7 @@ services:
# If you want to have your account on <DOMAIN>, but host Continuwuity on a subdomain,
# you can let it only handle the well known file on that domain instead
#- "traefik.http.routers.to-matrix-wellknown.rule=Host(`<DOMAIN>`) && PathPrefix(`/.well-known/matrix`)"
#- "traefik.http.routers.to-matrix-wellknown.rule=Host(`example.com`) && PathPrefix(`/.well-known/matrix`)"
#- "traefik.http.routers.to-matrix-wellknown.tls=true"
#- "traefik.http.routers.to-matrix-wellknown.tls.certresolver=letsencrypt"
#- "traefik.http.routers.to-matrix-wellknown.middlewares=cors-headers@docker"
### Uncomment this if you uncommented Element-Web App in the docker-compose.yml
# element-web:
# labels:
# - "traefik.enable=true"
# - "traefik.docker.network=proxy" # Change this to the name of your Traefik docker proxy network
# - "traefik.http.routers.to-element-web.rule=Host(`<SUBDOMAIN>.<DOMAIN>`)" # Change to the address on which Element-Web is hosted
# - "traefik.http.routers.to-element-web.tls=true"
# - "traefik.http.routers.to-element-web.tls.certresolver=letsencrypt"
# vim: ts=2:sw=2:expandtab
@@ -0,0 +1,49 @@
services:
caddy:
# This compose file uses caddy-docker-proxy as the reverse proxy for Continuwuity!
# For more info, visit https://github.com/lucaslorentz/caddy-docker-proxy
image: lucaslorentz/caddy-docker-proxy:ci-alpine
ports:
- 80:80
- 443:443
environment:
- CADDY_INGRESS_NETWORKS=caddy
networks:
- caddy
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data:/data
restart: unless-stopped
homeserver:
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
volumes:
- db:/var/lib/continuwuity
- ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's
#- ./continuwuity.toml:/etc/continuwuity.toml
environment:
CONTINUWUITY_SERVER_NAME: example.com
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_ADDRESS: 0.0.0.0
CONTINUWUITY_PORT: 8008
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
# Serve .well-known files to tell others to reach Continuwuity on port :443
CONTINUWUITY_WELL_KNOWN: |
{
client=https://example.com,
server=example.com:443
}
networks:
- caddy
labels:
caddy: example.com
caddy.reverse_proxy: "{{upstreams 8008}}"
volumes:
db:
networks:
caddy:
@@ -0,0 +1,55 @@
services:
caddy:
image: docker.io/caddy:latest
ports:
- 80:80
- 443:443
- 8448:8448
networks:
- caddy
volumes:
- ./data:/data
restart: unless-stopped
configs:
- source: Caddyfile
target: /etc/caddy/Caddyfile
homeserver:
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
volumes:
- db:/var/lib/continuwuity
- ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's
#- ./continuwuity.toml:/etc/continuwuity.toml
environment:
CONTINUWUITY_SERVER_NAME: example.com
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_ADDRESS: 0.0.0.0
CONTINUWUITY_PORT: 8008
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
## (Optional) Serve .well-known files to tell others to reach Continuwuity on port :443
## If you do this, remove all routes to port :8448 from the compose and Caddyfile
# CONTINUWUITY_WELL_KNOWN: |
# {
# client=https://example.com,
# server=example.com:443
# }
networks:
- caddy
networks:
caddy:
volumes:
db:
configs:
dynamic.yml:
content: |
https://example.com, https://example.com:8448 {
reverse_proxy http://homeserver:8008
}
@@ -0,0 +1,84 @@
# Continuwuity - Behind Traefik Reverse Proxy
services:
homeserver:
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
volumes:
- db:/var/lib/continuwuity
- ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's
#- ./continuwuity.toml:/etc/continuwuity.toml
networks:
- proxy
labels:
- "traefik.enable=true"
- "traefik.http.routers.continuwuity.rule=(Host(`example.com`))"
- "traefik.http.routers.continuwuity.entrypoints=websecure"
- "traefik.http.routers.continuwuity.tls.certresolver=letsencrypt"
- "traefik.http.services.continuwuity.loadbalancer.server.port=8008"
environment:
CONTINUWUITY_SERVER_NAME: example.com
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_ADDRESS: 0.0.0.0
CONTINUWUITY_PORT: 8008 # This must match with traefik's loadbalancer label
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
# Serve .well-known files to tell others to reach Continuwuity on port :443
CONTINUWUITY_WELL_KNOWN: |
{
client=https://example.com,
server=example.com:443
}
traefik:
image: "traefik:latest"
container_name: "traefik"
restart: "unless-stopped"
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:z"
- "acme:/etc/traefik/acme"
labels:
- "traefik.enable=true"
# middleware redirect
- "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
# global redirect to https
- "traefik.http.routers.redirs.rule=hostregexp(`{host:.+}`)"
- "traefik.http.routers.redirs.entrypoints=web"
- "traefik.http.routers.redirs.middlewares=redirect-to-https"
environment:
TRAEFIK_LOG_LEVEL: DEBUG
TRAEFIK_ENTRYPOINTS_WEB: true
TRAEFIK_ENTRYPOINTS_WEB_ADDRESS: ":80"
TRAEFIK_ENTRYPOINTS_WEB_HTTP_REDIRECTIONS_ENTRYPOINT_TO: websecure
TRAEFIK_ENTRYPOINTS_WEBSECURE: true
TRAEFIK_ENTRYPOINTS_WEBSECURE_ADDRESS: ":443"
TRAEFIK_ENTRYPOINTS_WEBSECURE_HTTP_TLS_CERTRESOLVER: letsencrypt
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT: true
# CHANGE THIS to desired email for ACME
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_EMAIL: user@example.com
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_HTTPCHALLENGE: true
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_HTTPCHALLENGE_ENTRYPOINT: web
TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_STORAGE: "/etc/traefik/acme/acme.json"
# Since Traefik 3.6.3, paths with certain "encoded characters" are now blocked by default; we need a couple, or else things *will* break
TRAEFIK_ENTRYPOINTS_WEBSECURE_HTTP_ENCODEDCHARACTERS_ALLOWENCODEDSLASH: true
TRAEFIK_ENTRYPOINTS_WEBSECURE_HTTP_ENCODEDCHARACTERS_ALLOWENCODEDHASH: true
TRAEFIK_PROVIDERS_DOCKER: true
TRAEFIK_PROVIDERS_DOCKER_ENDPOINT: "unix:///var/run/docker.sock"
TRAEFIK_PROVIDERS_DOCKER_EXPOSEDBYDEFAULT: false
volumes:
db:
acme:
networks:
proxy:
+31
View File
@@ -0,0 +1,31 @@
# Continuwuity
services:
homeserver:
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
command: /sbin/conduwuit
ports:
- 127.0.0.1:8008:8008
volumes:
- db:/var/lib/continuwuity
- ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's
#- ./continuwuity.toml:/etc/continuwuity.toml
environment:
CONTINUWUITY_SERVER_NAME: example.com # EDIT THIS
CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity
CONTINUWUITY_ADDRESS: 0.0.0.0
CONTINUWUITY_PORT: 8008
#CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above
## (Optional) Serve .well-known files to tell others to reach Continuwuity on port :443
## If you do this, remove all routes to port :8448 on your reverse proxy
# CONTINUWUITY_WELL_KNOWN: |
# {
# client=https://example.com,
# server=example.com:443
# }
volumes:
db:
-5
View File
@@ -4,11 +4,6 @@
"name": "config",
"label": "Configuration"
},
{
"type": "file",
"name": "environment-variables",
"label": "Environment Variables"
},
{
"type": "file",
"name": "admin",
-281
View File
@@ -1,281 +0,0 @@
# Environment Variables
Continuwuity can be configured entirely through environment variables, making it
ideal for containerised deployments and infrastructure-as-code scenarios.
This is a convenience reference and may not be exhaustive. The
[Configuration Reference](./config.mdx) is the primary source for all
configuration options.
## Prefix System
Continuwuity supports three environment variable prefixes for backwards
compatibility:
- `CONTINUWUITY_*` (current, recommended)
- `CONDUWUIT_*` (compatibility)
- `CONDUIT_*` (legacy)
All three prefixes work identically. Use double underscores (`__`) to represent
nested configuration sections from the TOML config.
**Examples:**
```bash
# Simple top-level config
CONTINUWUITY_SERVER_NAME="matrix.example.com"
CONTINUWUITY_PORT="8008"
# Nested config sections use double underscores
# This maps to [database] section in TOML
CONTINUWUITY_DATABASE__PATH="/var/lib/continuwuity"
# This maps to [tls] section in TOML
CONTINUWUITY_TLS__CERTS="/path/to/cert.pem"
```
## Configuration File Override
You can specify a custom configuration file path:
- `CONTINUWUITY_CONFIG` - Path to continuwuity.toml (current)
- `CONDUWUIT_CONFIG` - Path to config file (compatibility)
- `CONDUIT_CONFIG` - Path to config file (legacy)
## Essential Variables
These are the minimum variables needed for a working deployment:
| Variable | Description | Default |
| ---------------------------- | ---------------------------------- | ---------------------- |
| `CONTINUWUITY_SERVER_NAME` | Your Matrix server's domain name | Required |
| `CONTINUWUITY_DATABASE_PATH` | Path to RocksDB database directory | `/var/lib/conduwuit` |
| `CONTINUWUITY_ADDRESS` | IP address to bind to | `["127.0.0.1", "::1"]` |
| `CONTINUWUITY_PORT` | Port to listen on | `8008` |
## Network Configuration
| Variable | Description | Default |
| -------------------------------- | ----------------------------------------------- | ---------------------- |
| `CONTINUWUITY_ADDRESS` | Bind address (use `0.0.0.0` for all interfaces) | `["127.0.0.1", "::1"]` |
| `CONTINUWUITY_PORT` | HTTP port | `8008` |
| `CONTINUWUITY_UNIX_SOCKET_PATH` | UNIX socket path (alternative to TCP) | - |
| `CONTINUWUITY_UNIX_SOCKET_PERMS` | Socket permissions (octal) | `660` |
## Database Configuration
| Variable | Description | Default |
| ------------------------------------------ | --------------------------- | -------------------- |
| `CONTINUWUITY_DATABASE_PATH` | RocksDB data directory | `/var/lib/conduwuit` |
| `CONTINUWUITY_DATABASE_BACKUP_PATH` | Backup directory | - |
| `CONTINUWUITY_DATABASE_BACKUPS_TO_KEEP` | Number of backups to retain | `1` |
| `CONTINUWUITY_DB_CACHE_CAPACITY_MB` | Database read cache (MB) | - |
| `CONTINUWUITY_DB_WRITE_BUFFER_CAPACITY_MB` | Write cache (MB) | - |
## Cache Configuration
| Variable | Description |
| ---------------------------------------- | ------------------------ |
| `CONTINUWUITY_CACHE_CAPACITY_MODIFIER` | LRU cache multiplier |
| `CONTINUWUITY_PDU_CACHE_CAPACITY` | PDU cache entries |
| `CONTINUWUITY_AUTH_CHAIN_CACHE_CAPACITY` | Auth chain cache entries |
## DNS Configuration
Configure DNS resolution behaviour for federation and external requests.
| Variable | Description | Default |
| ------------------------------------ | ---------------------------- | -------- |
| `CONTINUWUITY_DNS_CACHE_ENTRIES` | Max DNS cache entries | `32768` |
| `CONTINUWUITY_DNS_MIN_TTL` | Minimum cache TTL (seconds) | `10800` |
| `CONTINUWUITY_DNS_MIN_TTL_NXDOMAIN` | NXDOMAIN cache TTL (seconds) | `259200` |
| `CONTINUWUITY_DNS_ATTEMPTS` | Retry attempts | - |
| `CONTINUWUITY_DNS_TIMEOUT` | Query timeout (seconds) | - |
| `CONTINUWUITY_DNS_TCP_FALLBACK` | Allow TCP fallback | - |
| `CONTINUWUITY_QUERY_ALL_NAMESERVERS` | Query all nameservers | - |
| `CONTINUWUITY_QUERY_OVER_TCP_ONLY` | TCP-only queries | - |
## Request Configuration
| Variable | Description |
| ------------------------------------ | ----------------------------- |
| `CONTINUWUITY_MAX_REQUEST_SIZE` | Max HTTP request size (bytes) |
| `CONTINUWUITY_REQUEST_CONN_TIMEOUT` | Connection timeout (seconds) |
| `CONTINUWUITY_REQUEST_TIMEOUT` | Overall request timeout |
| `CONTINUWUITY_REQUEST_TOTAL_TIMEOUT` | Total timeout |
| `CONTINUWUITY_REQUEST_IDLE_TIMEOUT` | Idle timeout |
| `CONTINUWUITY_REQUEST_IDLE_PER_HOST` | Idle connections per host |
## Federation Configuration
Control how your server federates with other Matrix servers.
| Variable | Description | Default |
| ---------------------------------------------- | ----------------------------- | ------- |
| `CONTINUWUITY_ALLOW_FEDERATION` | Enable federation | `true` |
| `CONTINUWUITY_FEDERATION_LOOPBACK` | Allow loopback federation | - |
| `CONTINUWUITY_FEDERATION_CONN_TIMEOUT` | Connection timeout | - |
| `CONTINUWUITY_FEDERATION_TIMEOUT` | Request timeout | - |
| `CONTINUWUITY_FEDERATION_IDLE_TIMEOUT` | Idle timeout | - |
| `CONTINUWUITY_FEDERATION_IDLE_PER_HOST` | Idle connections per host | - |
| `CONTINUWUITY_TRUSTED_SERVERS` | JSON array of trusted servers | - |
| `CONTINUWUITY_QUERY_TRUSTED_KEY_SERVERS_FIRST` | Query trusted first | - |
| `CONTINUWUITY_ONLY_QUERY_TRUSTED_KEY_SERVERS` | Only query trusted | - |
**Example:**
```bash
# Trust matrix.org for key verification
CONTINUWUITY_TRUSTED_SERVERS='["matrix.org"]'
```
## Registration & User Configuration
Control user registration and account creation behaviour.
| Variable | Description | Default |
| ------------------------------------------ | --------------------- | ------- |
| `CONTINUWUITY_ALLOW_REGISTRATION` | Enable registration | `true` |
| `CONTINUWUITY_REGISTRATION_TOKEN` | Token requirement | - |
| `CONTINUWUITY_SUSPEND_ON_REGISTER` | Suspend new accounts | - |
| `CONTINUWUITY_NEW_USER_DISPLAYNAME_SUFFIX` | Display name suffix | 🏳️‍⚧️ |
| `CONTINUWUITY_RECAPTCHA_SITE_KEY` | reCAPTCHA site key | - |
| `CONTINUWUITY_RECAPTCHA_PRIVATE_SITE_KEY` | reCAPTCHA private key | - |
**Example:**
```bash
# Disable open registration
CONTINUWUITY_ALLOW_REGISTRATION="false"
# Require a registration token
CONTINUWUITY_REGISTRATION_TOKEN="your_secret_token_here"
```
## Feature Configuration
| Variable | Description | Default |
| ---------------------------------------------------------- | -------------------------- | ------- |
| `CONTINUWUITY_ALLOW_ENCRYPTION` | Enable E2EE | `true` |
| `CONTINUWUITY_ALLOW_ROOM_CREATION` | Enable room creation | - |
| `CONTINUWUITY_ALLOW_UNSTABLE_ROOM_VERSIONS` | Allow unstable versions | - |
| `CONTINUWUITY_DEFAULT_ROOM_VERSION` | Default room version | `v11` |
| `CONTINUWUITY_REQUIRE_AUTH_FOR_PROFILE_REQUESTS` | Auth for profiles | - |
| `CONTINUWUITY_ALLOW_PUBLIC_ROOM_DIRECTORY_OVER_FEDERATION` | Federate directory | - |
| `CONTINUWUITY_ALLOW_PUBLIC_ROOM_DIRECTORY_WITHOUT_AUTH` | Unauth directory | - |
| `CONTINUWUITY_ALLOW_DEVICE_NAME_FEDERATION` | Device names in federation | - |
## TLS Configuration
Built-in TLS support is primarily for testing. **For production deployments,
especially when federating on the internet, use a reverse proxy** (Traefik,
Caddy, nginx) to handle TLS termination.
| Variable | Description |
| --------------------------------- | ------------------------- |
| `CONTINUWUITY_TLS__CERTS` | TLS certificate file path |
| `CONTINUWUITY_TLS__KEY` | TLS private key path |
| `CONTINUWUITY_TLS__DUAL_PROTOCOL` | Support TLS 1.2 + 1.3 |
**Example (testing only):**
```bash
CONTINUWUITY_TLS__CERTS="/etc/letsencrypt/live/matrix.example.com/fullchain.pem"
CONTINUWUITY_TLS__KEY="/etc/letsencrypt/live/matrix.example.com/privkey.pem"
```
## Logging Configuration
Control log output format and verbosity.
| Variable | Description | Default |
| ------------------------------ | ------------------ | ------- |
| `CONTINUWUITY_LOG` | Log filter level | - |
| `CONTINUWUITY_LOG_COLORS` | ANSI colours | `true` |
| `CONTINUWUITY_LOG_SPAN_EVENTS` | Log span events | `none` |
| `CONTINUWUITY_LOG_THREAD_IDS` | Include thread IDs | - |
**Examples:**
```bash
# Set log level to info
CONTINUWUITY_LOG="info"
# Enable debug logging for specific modules
CONTINUWUITY_LOG="warn,continuwuity::api=debug"
# Disable colours for log aggregation
CONTINUWUITY_LOG_COLORS="false"
```
## Observability Configuration
| Variable | Description |
| ---------------------------------------- | --------------------- |
| `CONTINUWUITY_ALLOW_OTLP` | Enable OpenTelemetry |
| `CONTINUWUITY_OTLP_FILTER` | OTLP filter level |
| `CONTINUWUITY_OTLP_PROTOCOL` | Protocol (http/grpc) |
| `CONTINUWUITY_TRACING_FLAME` | Enable flame graphs |
| `CONTINUWUITY_TRACING_FLAME_FILTER` | Flame graph filter |
| `CONTINUWUITY_TRACING_FLAME_OUTPUT_PATH` | Output directory |
| `CONTINUWUITY_SENTRY` | Enable Sentry |
| `CONTINUWUITY_SENTRY_ENDPOINT` | Sentry DSN |
| `CONTINUWUITY_SENTRY_SEND_SERVER_NAME` | Include server name |
| `CONTINUWUITY_SENTRY_TRACES_SAMPLE_RATE` | Sample rate (0.0-1.0) |
## Admin Configuration
Configure admin users and automated command execution.
| Variable | Description | Default |
| ------------------------------------------ | -------------------------------- | ----------------- |
| `CONTINUWUITY_ADMINS_LIST` | JSON array of admin user IDs | - |
| `CONTINUWUITY_ADMINS_FROM_ROOM` | Derive admins from room | - |
| `CONTINUWUITY_ADMIN_ESCAPE_COMMANDS` | Allow `\` prefix in public rooms | - |
| `CONTINUWUITY_ADMIN_CONSOLE_AUTOMATIC` | Auto-activate console | - |
| `CONTINUWUITY_ADMIN_EXECUTE` | JSON array of startup commands | - |
| `CONTINUWUITY_ADMIN_EXECUTE_ERRORS_IGNORE` | Ignore command errors | - |
| `CONTINUWUITY_ADMIN_SIGNAL_EXECUTE` | Commands on SIGUSR2 | - |
| `CONTINUWUITY_ADMIN_ROOM_TAG` | Admin room tag | `m.server_notice` |
**Examples:**
```bash
# Create admin user on startup
CONTINUWUITY_ADMIN_EXECUTE='["users create-user admin", "users make-user-admin admin"]'
# Specify admin users directly
CONTINUWUITY_ADMINS_LIST='["@alice:example.com", "@bob:example.com"]'
```
## Media & URL Preview Configuration
| Variable | Description |
| ---------------------------------------------------- | ------------------ |
| `CONTINUWUITY_URL_PREVIEW_BOUND_INTERFACE` | Bind interface |
| `CONTINUWUITY_URL_PREVIEW_DOMAIN_CONTAINS_ALLOWLIST` | Domain allowlist |
| `CONTINUWUITY_URL_PREVIEW_DOMAIN_EXPLICIT_ALLOWLIST` | Explicit allowlist |
| `CONTINUWUITY_URL_PREVIEW_DOMAIN_EXPLICIT_DENYLIST` | Explicit denylist |
| `CONTINUWUITY_URL_PREVIEW_MAX_SPIDER_SIZE` | Max fetch size |
| `CONTINUWUITY_URL_PREVIEW_TIMEOUT` | Fetch timeout |
| `CONTINUWUITY_IP_RANGE_DENYLIST` | IP range denylist |
## Tokio Runtime Configuration
These can be set as environment variables or CLI arguments:
| Variable | Description |
| ----------------------------------------- | -------------------------- |
| `TOKIO_WORKER_THREADS` | Worker thread count |
| `TOKIO_GLOBAL_QUEUE_INTERVAL` | Global queue interval |
| `TOKIO_EVENT_INTERVAL` | Event interval |
| `TOKIO_MAX_IO_EVENTS_PER_TICK` | Max I/O events per tick |
| `CONTINUWUITY_RUNTIME_HISTOGRAM_INTERVAL` | Histogram bucket size (μs) |
| `CONTINUWUITY_RUNTIME_HISTOGRAM_BUCKETS` | Bucket count |
| `CONTINUWUITY_RUNTIME_WORKER_AFFINITY` | Enable worker affinity |
## See Also
- [Configuration Reference](./config.mdx) - Complete TOML configuration
documentation
- [Admin Commands](./admin/) - Admin command reference
+14 -59
View File
@@ -45,75 +45,30 @@ log into the server account (`@conduit`) from a web client
## DNS issues
### Potential DNS issues when using Docker
### DNS server overload
Docker's DNS setup for containers in a non-default network intercepts queries to
enable resolving of container hostnames to IP addresses. However, due to
performance issues with Docker's built-in resolver, this can cause DNS queries
to take a long time to resolve, resulting in federation issues.
If your server experience any of the following symptoms:
This is particularly common with Docker Compose, as custom networks are easily
created and configured.
- Spurious server log entries with "DNS No connections available", "mismatching responding nameservers", or "error sending request"
- Excessively long room joins (30+ minutes) as seen from server logs
- Partial or non-functional outbound federation
Symptoms of this include excessively long room joins (30+ minutes) from very
long DNS timeouts, log entries of "mismatching responding nameservers",
and/or partial or non-functional inbound/outbound federation.
This is likely due to your DNS server being overloaded. Most likely, these problems are encountered in the following scenarios:
This is not a bug in continuwuity. Docker's default DNS resolver is not suitable
for heavy DNS activity, which is normal for federated protocols like Matrix.
- Homeservers hosted on a machine that uses `systemd-resolved`.
- Docker deployments which use the bridge network's forwarding resolver.
Workarounds:
Matrix federation is extremely heavy and sends wild amounts of DNS requests. This makes normal resolvers like the ones above unsuitable for its activity. Ultimately, the best solution/fix for this is to selfhost a high quality caching DNS resolver such as Unbound, and configure Continuwuity to use it.
- Use DNS over TCP via the config option `query_over_tcp_only = true`
- Bypass Docker's default DNS setup and instead allow the container to use and communicate with your host's DNS servers. Typically, this can be done by mounting the host's `/etc/resolv.conf`.
Follow the [**DNS tuning guide**](./advanced/dns) for details on setting it up.
### DNS No connections available error message
### Intermittent federation failures to a specific server
If you receive spurious amounts of error logs saying "DNS No connections
available", this is due to your DNS server (servers from `/etc/resolv.conf`)
being overloaded and unable to handle typical Matrix federation volume. Some
users have reported that the upstream servers are rate-limiting them as well
when they get this error (e.g. popular upstreams like Google DNS).
There may be circumstances where servers fail to connect to each other, probably due to a bad DNS cache. In such cases, issuing `!admin debug ping <SERVER_NAME>` would return some errors.
Matrix federation is extremely heavy and sends wild amounts of DNS requests.
Unfortunately this is by design and has only gotten worse with more
server/destination resolution steps. Synapse also expects a very perfect DNS
setup.
To fix this, you can run `!admin query resolver flush-cache <SERVER_NAME>` to clear the bad cache for that domain, and outbound requests should work again.
There are some ways you can reduce the amount of DNS queries, but ultimately
the best solution/fix is selfhosting a high quality caching DNS server like
[Unbound][unbound-arch] without any upstream resolvers, and without DNSSEC
validation enabled.
DNSSEC validation is highly recommended to be **disabled** due to DNSSEC being
very computationally expensive, and is extremely susceptible to denial of
service, especially on Matrix. Many servers also strangely have broken DNSSEC
setups and will result in non-functional federation.
Continuwuity cannot provide a "works-for-everyone" Unbound DNS setup guide, but
the [official Unbound tuning guide][unbound-tuning] and the [Unbound Arch Linux wiki page][unbound-arch]
may be of interest. Disabling DNSSEC on Unbound is commenting out trust-anchors
config options and removing the `validator` module.
**Avoid** using `systemd-resolved` as it does **not** perform very well under
high load, and we have identified its DNS caching to not be very effective.
dnsmasq can possibly work, but it does **not** support TCP fallback which can be
problematic when receiving large DNS responses such as from large SRV records.
If you still want to use dnsmasq, make sure you **disable** `dns_tcp_fallback`
in Continuwuity config.
Raising `dns_cache_entries` in Continuwuity config from the default can also assist
in DNS caching, but a full-fledged external caching resolver is better and more
reliable.
If you don't have IPv6 connectivity, changing `ip_lookup_strategy` to match
your setup can help reduce unnecessary AAAA queries
(`1 - Ipv4Only (Only query for A records, no AAAA/IPv6)`).
If your DNS server supports it, some users have reported enabling
`query_over_tcp_only` to force only TCP querying by default has improved DNS
reliability at a slight performance cost due to TCP overhead.
You may also use `!admin server clear-caches` or `!admin query resolver flush-cache -a` to clear all server/resolver caches, in case of failures with many domains. However, note that this significantly increases your server load for a short period.
## RocksDB / database issues
+3 -3
View File
@@ -3297,9 +3297,9 @@
"license": "0BSD"
},
"node_modules/typescript": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz",
"integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==",
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
+14
View File
@@ -11,6 +11,20 @@ export default defineConfig({
light: '/assets/logo.svg',
dark: '/assets/logo.svg',
},
markdown: {
link: {
checkDeadLinks: {
excludes: [
'/deploying/docker-compose.with-caddy.yml',
'/deploying/docker-compose.with-caddy-labels.yml',
'/deploying/docker-compose.for-traefik.yml',
'/deploying/docker-compose.with-traefik.yml',
`/deploying/docker-compose.override.yml`,
`/deploying/docker-compose.yml`
]
},
},
},
themeConfig: {
socialLinks: [
{
-1
View File
@@ -84,7 +84,6 @@ ctor.workspace = true
futures.workspace = true
lettre.workspace = true
log.workspace = true
assign.workspace = true
ruma.workspace = true
serde_json.workspace = true
serde-saphyr.workspace = true
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::Context;
#[implement(Context, params = "<'_>")]
pub(super) async fn check_all_users(&self) -> Result {
let timer = tokio::time::Instant::now();
let users = self.services.users.stream().collect::<Vec<_>>().await;
let users = self.services.users.iter().collect::<Vec<_>>().await;
let query_time = timer.elapsed();
let total = users.len();
+24 -37
View File
@@ -79,14 +79,12 @@ pub(super) async fn parse_pdu(&self) -> Result {
}
let string = self.body[1..self.body.len().saturating_sub(1)].join("\n");
let room_version_rules = RoomVersionId::V12.rules().unwrap();
match serde_json::from_str(&string) {
| Err(e) => return Err!("Invalid json in command body: {e}"),
| Ok(value) => match ruma::signatures::reference_hash(&value, &room_version_rules) {
| Ok(value) => match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
| Err(e) => return Err!("Could not parse PDU JSON: {e:?}"),
| Ok(hash) => {
let event_id = EventId::parse(format!("${hash}"));
let event_id = OwnedEventId::parse(format!("${hash}"));
match serde_json::from_value::<PduEvent>(serde_json::to_value(value)?) {
| Err(e) => return Err!("EventId: {event_id:?}\nCould not parse event: {e}"),
| Ok(pdu) => write!(self, "EventId: {event_id:?}\n{pdu:#?}"),
@@ -121,7 +119,7 @@ pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
} else {
"PDU found in our database"
};
write!(self, "{msg}\n```json\n{text}\n```")
write!(self, "{msg}\n```json\n{text}\n```",)
},
}
.await
@@ -189,7 +187,10 @@ pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: b
for event_id in list {
if force {
match self.get_remote_pdu(event_id.clone(), server.clone()).await {
match self
.get_remote_pdu(event_id.to_owned(), server.clone())
.await
{
| Err(e) => {
failed_count = failed_count.saturating_add(1);
self.services
@@ -204,7 +205,7 @@ pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: b
},
}
} else {
self.get_remote_pdu(event_id.clone(), server.clone())
self.get_remote_pdu(event_id.to_owned(), server.clone())
.await?;
success_count = success_count.saturating_add(1);
}
@@ -236,10 +237,10 @@ pub(super) async fn get_remote_pdu(
match self
.services
.sending
.send_federation_request(
&server,
ruma::api::federation::event::get_event::v1::Request::new(event_id.clone()),
)
.send_federation_request(&server, ruma::api::federation::event::get_event::v1::Request {
event_id: event_id.clone(),
include_unredacted_content: None,
})
.await
{
| Err(e) => {
@@ -329,9 +330,9 @@ pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
match self
.services
.sending
.send_unauthenticated_request(
.send_federation_request(
&server,
ruma::api::federation::discovery::get_server_version::v1::Request::new(),
ruma::api::federation::discovery::get_server_version::v1::Request {},
)
.await
{
@@ -360,7 +361,7 @@ pub(super) async fn force_device_list_updates(&self) -> Result {
self.services
.users
.stream()
.for_each(async |user_id| self.services.users.mark_device_key_update(&user_id).await)
.for_each(|user_id| self.services.users.mark_device_key_update(user_id))
.await;
write!(self, "Marked all devices for all users as having new keys to update").await
@@ -429,16 +430,9 @@ pub(super) async fn verify_json(&self) -> Result {
}
let string = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
let room_version_rules = RoomVersionId::V12.rules().unwrap();
match serde_json::from_str::<CanonicalJsonObject>(&string) {
| Err(e) => return Err!("Invalid json: {e}"),
| Ok(value) => match self
.services
.server_keys
.verify_json(&value, &room_version_rules)
.await
{
| Ok(value) => match self.services.server_keys.verify_json(&value, None).await {
| Err(e) => return Err!("Signature verification failed: {e}"),
| Ok(()) => write!(self, "Signature correct"),
},
@@ -451,15 +445,9 @@ pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result {
use ruma::signatures::Verified;
let mut event = self.services.rooms.timeline.get_pdu_json(&event_id).await?;
let room_version_rules = RoomVersionId::V12.rules().unwrap();
event.remove("event_id");
let msg = match self
.services
.server_keys
.verify_event(&event, &room_version_rules)
.await
{
let msg = match self.services.server_keys.verify_event(&event, None).await {
| Err(e) => return Err(e),
| Ok(Verified::Signatures) => "signatures OK, but content hash failed (redaction).",
| Ok(Verified::All) => "signatures and hashes OK.",
@@ -556,17 +544,16 @@ pub(super) async fn force_set_room_state_from_server(
};
let room_version = self.services.rooms.state.get_room_version(&room_id).await?;
let room_version_rules = room_version.rules().unwrap();
let mut state: HashMap<u64, OwnedEventId> = HashMap::new();
let remote_state_response = self
.services
.sending
.send_federation_request(
&server_name,
get_room_state::v1::Request::new(at_event_id, room_id.clone()),
)
.send_federation_request(&server_name, get_room_state::v1::Request {
room_id: room_id.clone(),
event_id: at_event_id,
})
.await?;
for pdu in remote_state_response.pdus.clone() {
@@ -589,7 +576,7 @@ pub(super) async fn force_set_room_state_from_server(
for result in remote_state_response.pdus.iter().map(|pdu| {
self.services
.server_keys
.validate_and_add_event_id(pdu, &room_version_rules)
.validate_and_add_event_id(pdu, &room_version)
}) {
let Ok((event_id, value)) = result.await else {
continue;
@@ -621,7 +608,7 @@ pub(super) async fn force_set_room_state_from_server(
for result in remote_state_response.auth_chain.iter().map(|pdu| {
self.services
.server_keys
.validate_and_add_event_id(pdu, &room_version_rules)
.validate_and_add_event_id(pdu, &room_version)
}) {
let Ok((event_id, value)) = result.await else {
continue;
@@ -638,7 +625,7 @@ pub(super) async fn force_set_room_state_from_server(
.services
.rooms
.event_handler
.resolve_state(&room_id, &room_version_rules, state)
.resolve_state(&room_id, &room_version, state)
.await?;
info!("Compressing new room state");
+2 -2
View File
@@ -111,7 +111,7 @@ pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result
.rooms
.state_cache
.rooms_joined(&user_id)
.then(async |room_id| get_room_info(self.services, &room_id).await)
.then(|room_id| get_room_info(self.services, room_id))
.collect()
.await;
@@ -129,6 +129,6 @@ pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```",))
.await
}
+4 -5
View File
@@ -6,8 +6,7 @@ use conduwuit::{
warn,
};
use conduwuit_service::media::Dim;
use ruma::{OwnedEventId, OwnedMxcUri, OwnedServerName};
use service::media::mxc::Mxc;
use ruma::{Mxc, OwnedEventId, OwnedMxcUri, OwnedServerName};
use crate::{admin_command, utils::parse_local_user_id};
@@ -262,7 +261,7 @@ pub(super) async fn delete_past_remote_media(
)
.await?;
self.write_str(&format!("Deleted {deleted_count} total files."))
self.write_str(&format!("Deleted {deleted_count} total files.",))
.await
}
@@ -272,7 +271,7 @@ pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
let deleted_count = self.services.media.delete_from_user(&user_id).await?;
self.write_str(&format!("Deleted {deleted_count} total files."))
self.write_str(&format!("Deleted {deleted_count} total files.",))
.await
}
@@ -331,7 +330,7 @@ pub(super) async fn delete_all_from_server(
}
}
self.write_str(&format!("Deleted {deleted_count} total files."))
self.write_str(&format!("Deleted {deleted_count} total files.",))
.await
}
+5 -5
View File
@@ -16,8 +16,8 @@ use futures::{AsyncWriteExt, future::FutureExt, io::BufWriter};
use ruma::{
EventId,
events::{
relation::{InReplyTo, Reply},
room::message::{Relation, RoomMessageEventContent},
relation::InReplyTo,
room::message::{Relation::Reply, RoomMessageEventContent},
},
};
use service::{
@@ -38,7 +38,6 @@ pub(super) fn dispatch(services: Arc<Services>, command: CommandInput) -> Proces
}
#[tracing::instrument(skip_all, name = "admin", level = "info")]
#[allow(clippy::result_large_err)]
async fn handle_command(services: Arc<Services>, command: CommandInput) -> ProcessorResult {
AssertUnwindSafe(Box::pin(process_command(services, &command)))
.catch_unwind()
@@ -278,8 +277,9 @@ fn reply(
mut content: RoomMessageEventContent,
reply_id: Option<&EventId>,
) -> RoomMessageEventContent {
content.relates_to =
reply_id.map(|event_id| Relation::Reply(Reply::new(InReplyTo::new(event_id.to_owned()))));
content.relates_to = reply_id.map(|event_id| Reply {
in_reply_to: InReplyTo { event_id: event_id.to_owned() },
});
content
}
+2 -2
View File
@@ -50,7 +50,7 @@ async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Resu
while let Some((name, CachedDest { dest, host, expire })) = destinations.next().await {
if let Some(server_name) = server_name.as_ref() {
if name != *server_name {
if name != server_name {
continue;
}
}
@@ -76,7 +76,7 @@ async fn overrides_cache(&self, server_name: Option<String>) -> Result {
overrides.next().await
{
if let Some(server_name) = server_name.as_ref() {
if name != *server_name {
if name != server_name {
continue;
}
}
+2 -1
View File
@@ -41,6 +41,7 @@ pub(super) async fn process(subcommand: RoomAliasCommand, context: &Context<'_>)
.rooms
.alias
.local_aliases_for_room(&room_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -53,7 +54,7 @@ pub(super) async fn process(subcommand: RoomAliasCommand, context: &Context<'_>)
.rooms
.alias
.all_local_aliases()
.map(|(room_id, alias)| (room_id, alias.to_owned()))
.map(|(room_id, alias)| (room_id.to_owned(), alias.to_owned()))
.collect::<Vec<_>>()
.await;
let query_time = timer.elapsed();
+8
View File
@@ -101,6 +101,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.room_servers(&room_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -117,6 +118,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.server_rooms(&server)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -133,6 +135,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.room_members(&room_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -149,6 +152,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.local_users_in_room(&room_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -165,6 +169,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.active_local_users_in_room(&room_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -207,6 +212,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.room_useroncejoined(&room_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -223,6 +229,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.room_members_invited(&room_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -269,6 +276,7 @@ pub(super) async fn process(subcommand: RoomStateCacheCommand, context: &Context
.rooms
.state_cache
.rooms_joined(&user_id)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
+4 -1
View File
@@ -104,6 +104,7 @@ async fn get_shared_rooms(&self, user_a: OwnedUserId, user_b: OwnedUserId) -> Re
.rooms
.state_cache
.get_shared_rooms(&user_a, &user_b)
.map(ToOwned::to_owned)
.collect()
.await;
let query_time = timer.elapsed();
@@ -216,7 +217,8 @@ async fn iter_users2(&self) -> Result {
let result: Vec<_> = self.services.users.stream().collect().await;
let result: Vec<_> = result
.into_iter()
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
.map(ruma::UserId::as_bytes)
.map(String::from_utf8_lossy)
.collect();
let query_time = timer.elapsed();
@@ -252,6 +254,7 @@ async fn list_devices(&self, user_id: OwnedUserId) -> Result {
.services
.users
.all_device_ids(&user_id)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.await;
+3 -3
View File
@@ -3,7 +3,7 @@ use std::fmt::Write;
use clap::Subcommand;
use conduwuit::{Err, Result};
use futures::StreamExt;
use ruma::{OwnedRoomAliasId, OwnedRoomId, RoomAliasId};
use ruma::{OwnedRoomAliasId, OwnedRoomId};
use crate::Context;
@@ -52,7 +52,7 @@ pub(super) async fn process(command: RoomAliasCommand, context: &Context<'_>) ->
| RoomAliasCommand::Which { ref room_alias_localpart } => {
let room_alias_str =
format!("#{}:{}", room_alias_localpart, services.globals.server_name());
let room_alias = match RoomAliasId::parse(room_alias_str) {
let room_alias = match OwnedRoomAliasId::parse(room_alias_str) {
| Ok(alias) => alias,
| Err(err) => {
return Err!("Failed to parse alias: {err}");
@@ -139,7 +139,7 @@ pub(super) async fn process(command: RoomAliasCommand, context: &Context<'_>) ->
.rooms
.alias
.all_local_aliases()
.map(|(room_id, localpart)| (room_id, localpart.into()))
.map(|(room_id, localpart)| (room_id.into(), localpart.into()))
.collect::<Vec<(OwnedRoomId, String)>>()
.await;
+4 -4
View File
@@ -22,14 +22,14 @@ pub(super) async fn list_rooms(
.metadata
.iter_ids()
.filter_map(|room_id| async move {
(!exclude_disabled || !self.services.rooms.metadata.is_disabled(&room_id).await)
(!exclude_disabled || !self.services.rooms.metadata.is_disabled(room_id).await)
.then_some(room_id)
})
.filter_map(|room_id| async move {
(!exclude_banned || !self.services.rooms.metadata.is_banned(&room_id).await)
(!exclude_banned || !self.services.rooms.metadata.is_banned(room_id).await)
.then_some(room_id)
})
.then(async |room_id| get_room_info(self.services, &room_id).await)
.then(|room_id| get_room_info(self.services, room_id))
.then(|(room_id, total_members, name)| async move {
let local_members: Vec<_> = self
.services
@@ -72,7 +72,7 @@ pub(super) async fn list_rooms(
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len()))
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len(),))
.await
}
+2 -2
View File
@@ -43,7 +43,7 @@ pub(super) async fn process(command: RoomDirectoryCommand, context: &Context<'_>
.rooms
.directory
.public_rooms()
.then(async |room_id| get_room_info(services, &room_id).await)
.then(|room_id| get_room_info(services, room_id))
.collect()
.await;
@@ -67,7 +67,7 @@ pub(super) async fn process(command: RoomDirectoryCommand, context: &Context<'_>
.join("\n");
context
.write_str(&format!("Rooms (page {page}):\n```\n{body}\n```"))
.write_str(&format!("Rooms (page {page}):\n```\n{body}\n```",))
.await
},
}
+2 -1
View File
@@ -46,6 +46,7 @@ async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> R
.then(|| self.services.globals.user_is_local(user_id))
.unwrap_or(true)
})
.map(ToOwned::to_owned)
.filter_map(|user_id| async move {
Some((
self.services
@@ -66,7 +67,7 @@ async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> R
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```"))
self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```",))
.await
}
+14 -10
View File
@@ -71,7 +71,7 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
debug!("Room specified is a room ID, banning room ID");
room_id.clone()
room_id.to_owned()
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
| Ok(room_alias) => room_alias,
@@ -89,7 +89,7 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
locally, if not using get_alias_helper to fetch room ID remotely"
);
match self.services.rooms.alias.resolve_alias(&room_alias).await {
match self.services.rooms.alias.resolve_alias(room_alias).await {
| Ok((room_id, servers)) => {
debug!(
%room_id,
@@ -116,6 +116,7 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
.rooms
.state_cache
.room_members(&room_id)
.map(ToOwned::to_owned)
.ready_filter(|user| self.services.globals.user_is_local(user))
.boxed();
@@ -139,6 +140,7 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
.rooms
.alias
.local_aliases_for_room(&room_id)
.map(ToOwned::to_owned)
.for_each(|local_alias| async move {
self.services
.rooms
@@ -203,7 +205,7 @@ async fn ban_list_of_rooms(&self) -> Result {
},
};
room_ids.push(room_id.clone());
room_ids.push(room_id.to_owned());
}
if room_alias_or_id.is_room_alias_id() {
@@ -213,7 +215,7 @@ async fn ban_list_of_rooms(&self) -> Result {
.services
.rooms
.alias
.resolve_local_alias(&room_alias)
.resolve_local_alias(room_alias)
.await
{
| Ok(room_id) => room_id,
@@ -227,7 +229,7 @@ async fn ban_list_of_rooms(&self) -> Result {
.services
.rooms
.alias
.resolve_alias(&room_alias)
.resolve_alias(room_alias)
.await
{
| Ok((room_id, servers)) => {
@@ -282,6 +284,7 @@ async fn ban_list_of_rooms(&self) -> Result {
.rooms
.state_cache
.room_members(&room_id)
.map(ToOwned::to_owned)
.ready_filter(|user| self.services.globals.user_is_local(user))
.boxed();
@@ -306,6 +309,7 @@ async fn ban_list_of_rooms(&self) -> Result {
.rooms
.alias
.local_aliases_for_room(&room_id)
.map(ToOwned::to_owned)
.for_each(|local_alias| async move {
self.services
.rooms
@@ -344,9 +348,9 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
};
debug!("Room specified is a room ID, unbanning room ID");
self.services.rooms.metadata.ban_room(&room_id, false);
self.services.rooms.metadata.ban_room(room_id, false);
room_id.clone()
room_id.to_owned()
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
| Ok(room_alias) => room_alias,
@@ -368,7 +372,7 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
.services
.rooms
.alias
.resolve_local_alias(&room_alias)
.resolve_local_alias(room_alias)
.await
{
| Ok(room_id) => room_id,
@@ -378,7 +382,7 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
room ID over federation"
);
match self.services.rooms.alias.resolve_alias(&room_alias).await {
match self.services.rooms.alias.resolve_alias(room_alias).await {
| Ok((room_id, servers)) => {
debug!(
%room_id,
@@ -449,6 +453,6 @@ async fn list_banned_rooms(&self, no_details: bool) -> Result {
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```",))
.await
}
+2 -2
View File
@@ -159,8 +159,8 @@ pub(super) async fn list_features(&self) -> Result {
let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
.lock()
.expect("locked")
.values()
.flat_map(|f| f.iter())
.iter()
.flat_map(|(_, f)| f.iter())
.collect::<Vec<_>>();
enabled_features.sort_unstable();
+63 -55
View File
@@ -9,18 +9,20 @@ use api::client::{
};
use conduwuit::{
Err, Result, debug_warn, error, info,
matrix::{Event, pdu::PartialPdu},
matrix::{Event, pdu::PduBuilder},
utils::{self, ReadyExt},
warn,
};
use futures::{FutureExt, StreamExt};
use lettre::Address;
use ruma::{
OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, ServerName,
UserId, assign,
OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, UserId,
events::{
RoomAccountDataEventType,
room::{power_levels::RoomPowerLevelsEventContent, redaction::RoomRedactionEventContent},
RoomAccountDataEventType, StateEventType,
room::{
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
redaction::RoomRedactionEventContent,
},
tag::{TagEvent, TagEventContent, TagInfo},
},
};
@@ -39,7 +41,7 @@ pub(super) async fn list_users(&self) -> Result {
.services
.users
.list_local_users()
.map(|id| id.as_str().to_owned())
.map(ToString::to_string)
.collect()
.await;
@@ -101,12 +103,11 @@ pub(super) async fn create_user(&self, username: String, password: Option<String
ruma::events::GlobalAccountDataEventType::PushRules
.to_string()
.into(),
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent::new(
ruma::events::push_rules::PushRulesEventContent::new(
ruma::push::Ruleset::server_default(&user_id),
),
))
.unwrap(),
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent {
content: ruma::events::push_rules::PushRulesEventContent {
global: ruma::push::Ruleset::server_default(&user_id),
},
})?,
)
.await?;
@@ -291,12 +292,7 @@ pub(super) async fn reset_password(
self.services
.users
.all_device_ids(&user_id)
.for_each(async |device_id| {
self.services
.users
.remove_device(&user_id, &device_id)
.await;
})
.for_each(|device_id| self.services.users.remove_device(&user_id, device_id))
.await;
write!(self, "\nAll existing sessions have been logged out.").await?;
}
@@ -441,7 +437,7 @@ pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
.rooms
.state_cache
.rooms_joined(&user_id)
.then(async |room_id| get_room_info(self.services, &room_id).await)
.then(|room_id| get_room_info(self.services, room_id))
.collect()
.await;
@@ -458,7 +454,7 @@ pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms {user_id} Joined ({}):\n```\n{body}\n```", rooms.len()))
self.write_str(&format!("Rooms {user_id} Joined ({}):\n```\n{body}\n```", rooms.len(),))
.await
}
@@ -510,7 +506,7 @@ pub(super) async fn force_join_list_of_local_users(
.rooms
.state_cache
.room_members(&room_id)
.ready_any(|user_id| server_admins.contains(&user_id))
.ready_any(|user_id| server_admins.contains(&user_id.to_owned()))
.await
{
return Err!("There is not a single server admin in the room.",);
@@ -624,7 +620,7 @@ pub(super) async fn force_join_all_local_users(
.rooms
.state_cache
.room_members(&room_id)
.ready_any(|user_id| server_admins.contains(&user_id))
.ready_any(|user_id| server_admins.contains(&user_id.to_owned()))
.await
{
return Err!("There is not a single server admin in the room.",);
@@ -637,6 +633,7 @@ pub(super) async fn force_join_all_local_users(
.services
.users
.list_local_users()
.map(UserId::to_owned)
.collect::<Vec<_>>()
.await
{
@@ -687,7 +684,7 @@ pub(super) async fn force_join_room(
);
join_room_by_id_helper(self.services, &user_id, &room_id, None, &servers, &None).await?;
self.write_str(&format!("{user_id} has been joined to {room_id}."))
self.write_str(&format!("{user_id} has been joined to {room_id}.",))
.await
}
@@ -719,7 +716,7 @@ pub(super) async fn force_leave_room(
.boxed()
.await?;
self.write_str(&format!("{user_id} has left {room_id}."))
self.write_str(&format!("{user_id} has left {room_id}.",))
.await
}
@@ -733,34 +730,42 @@ pub(super) async fn force_demote(&self, user_id: String, room_id: OwnedRoomOrAli
"Parsed user_id must be a local user"
);
let state_lock = self.services.rooms.state.mutex.lock(room_id.as_str()).await;
let state_lock = self.services.rooms.state.mutex.lock(&room_id).await;
let mut room_power_levels = self
let room_power_levels: Option<RoomPowerLevelsEventContent> = self
.services
.rooms
.state_accessor
.get_room_power_levels(&room_id)
.await;
.room_state_get_content(&room_id, &StateEventType::RoomPowerLevels, "")
.await
.ok();
let user_can_demote_self =
room_power_levels.user_can_change_user_power_level(&user_id, &user_id);
let user_can_demote_self = room_power_levels
.as_ref()
.is_some_and(|power_levels_content| {
RoomPowerLevels::from(power_levels_content.clone())
.user_can_change_user_power_level(&user_id, &user_id)
}) || self
.services
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomCreate, "")
.await
.is_ok_and(|event| event.sender() == user_id);
if !user_can_demote_self {
return Err!("User is not allowed to modify their own power levels in the room.",);
}
room_power_levels.users.remove(&user_id);
let mut power_levels_content = room_power_levels.unwrap_or_default();
power_levels_content.users.remove(&user_id);
let event_id = self
.services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(
String::new(),
&RoomPowerLevelsEventContent::try_from(room_power_levels)
.expect("PLs should be valid for room version"),
),
PduBuilder::state(String::new(), &power_levels_content),
&user_id,
Some(&room_id),
&state_lock,
@@ -788,7 +793,7 @@ pub(super) async fn make_user_admin(&self, user_id: String) -> Result {
.boxed()
.await?;
self.write_str(&format!("{user_id} has been granted admin privileges."))
self.write_str(&format!("{user_id} has been granted admin privileges.",))
.await
}
@@ -806,7 +811,9 @@ pub(super) async fn put_room_tag(
.account_data
.get_room(&room_id, &user_id, RoomAccountDataEventType::Tag)
.await
.unwrap_or_else(|_| TagEvent::new(TagEventContent::new(BTreeMap::new())));
.unwrap_or(TagEvent {
content: TagEventContent { tags: BTreeMap::new() },
});
tags_event
.content
@@ -843,7 +850,9 @@ pub(super) async fn delete_room_tag(
.account_data
.get_room(&room_id, &user_id, RoomAccountDataEventType::Tag)
.await
.unwrap_or_else(|_| TagEvent::new(TagEventContent::new(BTreeMap::new())));
.unwrap_or(TagEvent {
content: TagEventContent { tags: BTreeMap::new() },
});
tags_event.content.tags.remove(&tag.clone().into());
@@ -873,7 +882,9 @@ pub(super) async fn get_room_tags(&self, user_id: String, room_id: OwnedRoomId)
.account_data
.get_room(&room_id, &user_id, RoomAccountDataEventType::Tag)
.await
.unwrap_or_else(|_| TagEvent::new(TagEventContent::new(BTreeMap::new())));
.unwrap_or(TagEvent {
content: TagEventContent { tags: BTreeMap::new() },
});
self.write_str(&format!("```\n{:#?}\n```", tags_event.content.tags))
.await
@@ -910,19 +921,19 @@ pub(super) async fn redact_event(&self, event_id: OwnedEventId) -> Result {
.rooms
.state
.mutex
.lock(event.room_id_or_hash().as_str())
.lock(&event.room_id_or_hash())
.await;
self.services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
PduBuilder {
redacts: Some(event.event_id().to_owned()),
..PartialPdu::timeline(&assign!(RoomRedactionEventContent::new_v1(), {
..PduBuilder::timeline(&RoomRedactionEventContent {
redacts: Some(event.event_id().to_owned()),
reason: Some(reason),
}))
})
},
event.sender(),
Some(&event.room_id_or_hash()),
@@ -952,7 +963,7 @@ pub(super) async fn force_leave_remote_room(
.resolve_with_servers(
&room_id,
if let Some(v) = via.clone() {
Some(vec![ServerName::parse(v)?])
Some(vec![OwnedServerName::parse(v)?])
} else {
None
},
@@ -965,7 +976,7 @@ pub(super) async fn force_leave_remote_room(
);
let mut vias: HashSet<OwnedServerName> = HashSet::new();
if let Some(via) = via {
vias.insert(ServerName::parse(via)?);
vias.insert(OwnedServerName::parse(via)?);
}
for server in vias_raw {
vias.insert(server);
@@ -1040,12 +1051,7 @@ pub(super) async fn logout(&self, user_id: String) -> Result {
self.services
.users
.all_device_ids(&user_id)
.for_each(async |device_id| {
self.services
.users
.remove_device(&user_id, &device_id)
.await;
})
.for_each(|device_id| self.services.users.remove_device(&user_id, device_id))
.await;
self.write_str(&format!("User {user_id} has been logged out from all devices."))
.await
@@ -1123,9 +1129,11 @@ pub(super) async fn get_user_by_email(&self, email: String) -> Result {
match self.services.threepid.get_localpart_for_email(&email).await {
| Some(localpart) => {
let user_id =
UserId::parse(format!("@{localpart}:{}", self.services.globals.server_name()))
.unwrap();
let user_id = OwnedUserId::parse(format!(
"@{localpart}:{}",
self.services.globals.server_name()
))
.unwrap();
self.write_str(&format!("{email} belongs to {user_id}."))
.await
-2
View File
@@ -92,9 +92,7 @@ lettre.workspace = true
log.workspace = true
rand.workspace = true
reqwest.workspace = true
assign.workspace = true
ruma.workspace = true
ruminuwuity.workspace = true
serde_html_form.workspace = true
serde_json.workspace = true
serde.workspace = true
+7 -4
View File
@@ -1,8 +1,10 @@
use axum::extract::State;
use conduwuit::{Err, Result, info, utils::ReadyExt, warn};
use futures::{FutureExt, StreamExt};
use ruma::{OwnedRoomAliasId, events::room::message::RoomMessageEventContent};
use ruminuwuity::admin::continuwuity::rooms;
use ruma::{
OwnedRoomAliasId, continuwuity_admin_api::rooms,
events::room::message::RoomMessageEventContent,
};
use crate::{Ruma, client::leave_room};
@@ -34,6 +36,7 @@ pub(crate) async fn ban_room(
.rooms
.state_cache
.room_members(&body.room_id)
.map(ToOwned::to_owned)
.ready_filter(|user| services.globals.user_is_local(user))
.boxed();
let mut evicted = Vec::new();
@@ -60,9 +63,9 @@ pub(crate) async fn ban_room(
.rooms
.alias
.local_aliases_for_room(&body.room_id)
.collect()
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.await;
for alias in &aliases {
info!("Removing alias {} for banned room {}", alias, body.room_id);
services
+3 -4
View File
@@ -1,8 +1,7 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use futures::StreamExt;
use ruma::OwnedRoomId;
use ruminuwuity::admin::continuwuity::rooms;
use ruma::{OwnedRoomId, continuwuity_admin_api::rooms};
use crate::Ruma;
@@ -23,8 +22,8 @@ pub(crate) async fn list_rooms(
.metadata
.iter_ids()
.filter_map(|room_id| async move {
if !services.rooms.metadata.is_banned(&room_id).await {
Some(room_id.clone())
if !services.rooms.metadata.is_banned(room_id).await {
Some(room_id.to_owned())
} else {
None
}
+67 -43
View File
@@ -1,15 +1,15 @@
use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduwuit::{
Err, Result, err, info,
pdu::PartialPdu,
Err, Event, Result, err, info,
pdu::PduBuilder,
utils::{ReadyExt, stream::BroadbandExt},
};
use conduwuit_service::Services;
use futures::{FutureExt, StreamExt};
use lettre::{Address, message::Mailbox};
use ruma::{
OwnedRoomId, UserId,
OwnedRoomId, OwnedUserId, UserId,
api::client::{
account::{
ThirdPartyIdRemovalStatus, change_password, check_registration_token_validity,
@@ -18,10 +18,12 @@ use ruma::{
},
uiaa::{AuthFlow, AuthType},
},
assign,
events::room::{
member::{MembershipState, RoomMemberEventContent},
power_levels::RoomPowerLevelsEventContent,
events::{
StateEventType,
room::{
member::{MembershipState, RoomMemberEventContent},
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
},
},
};
use service::{mailer::messages, uiaa::Identity};
@@ -85,7 +87,7 @@ pub(crate) async fn get_register_available_route(
return Err!(Request(Exclusive("Username is reserved by an appservice.")));
}
Ok(get_username_availability::v3::Response::new(true))
Ok(get_username_availability::v3::Response { available: true })
}
/// # `POST /_matrix/client/r0/account/password`
@@ -141,7 +143,7 @@ pub(crate) async fn change_password_route(
.await?
};
let sender_user = UserId::parse(format!(
let sender_user = OwnedUserId::parse(format!(
"@{}:{}",
identity.localpart.expect("localpart should be known"),
services.globals.server_name()
@@ -159,7 +161,7 @@ pub(crate) async fn change_password_route(
.users
.all_device_ids(&sender_user)
.ready_filter(|id| *id != body.sender_device())
.for_each(async |id| services.users.remove_device(&sender_user, &id).await)
.for_each(|id| services.users.remove_device(&sender_user, id))
.await;
// Remove all pushers except the ones associated with this session
@@ -173,8 +175,8 @@ pub(crate) async fn change_password_route(
.get_pusher_device(&pushkey)
.await
.ok()
.as_ref()
.is_some_and(|pusher_device| pusher_device != body.sender_device())
.filter(|pusher_device| pusher_device != body.sender_device())
.is_some()
.then_some(pushkey)
})
.for_each(async |pushkey| {
@@ -192,7 +194,7 @@ pub(crate) async fn change_password_route(
.await;
}
Ok(change_password::v3::Response::new())
Ok(change_password::v3::Response {})
}
/// # `POST /_matrix/client/v3/account/password/email/requestToken`
@@ -213,7 +215,7 @@ pub(crate) async fn request_password_change_token_via_email_route(
};
let user_id =
UserId::parse(format!("@{localpart}:{}", services.globals.server_name())).unwrap();
OwnedUserId::parse(format!("@{localpart}:{}", services.globals.server_name())).unwrap();
let display_name = services.users.displayname(&user_id).await.ok();
let session = services
@@ -249,10 +251,11 @@ pub(crate) async fn whoami_route(
.map_err(|_| {
err!(Request(Forbidden("Application service has not registered this user.")))
})? && body.appservice_info.is_none();
Ok(assign!(whoami::v3::Response::new(body.sender_user().to_owned(), is_guest), {
Ok(whoami::v3::Response {
user_id: body.sender_user().to_owned(),
device_id: body.sender_device.clone(),
}))
is_guest,
})
}
/// # `POST /_matrix/client/r0/account/deactivate`
@@ -307,7 +310,9 @@ pub(crate) async fn deactivate_route(
.await;
}
Ok(deactivate::v3::Response::new(ThirdPartyIdRemovalStatus::Success))
Ok(deactivate::v3::Response {
id_server_unbind_result: ThirdPartyIdRemovalStatus::Success,
})
}
/// # `GET /_matrix/client/v1/register/m.login.registration_token/validity`
@@ -325,7 +330,7 @@ pub(crate) async fn check_registration_token_validity(
.await
.is_some();
Ok(check_registration_token_validity::v1::Response::new(valid))
Ok(check_registration_token_validity::v1::Response { valid })
}
/// Runs through all the deactivation steps:
@@ -349,7 +354,13 @@ pub async fn full_user_deactivate(
.await;
}
services.users.clear_profile(user_id).await;
services
.users
.all_profile_keys(user_id)
.ready_for_each(|(profile_key, _)| {
services.users.set_profile_key(user_id, &profile_key, None);
})
.await;
services
.pusher
@@ -361,49 +372,62 @@ pub async fn full_user_deactivate(
// TODO: Rescind all user invites
let mut pdu_queue: Vec<(PartialPdu, &OwnedRoomId)> = Vec::new();
let mut pdu_queue: Vec<(PduBuilder, &OwnedRoomId)> = Vec::new();
for room_id in all_joined_rooms {
let room_power_levels = services
.rooms
.state_accessor
.get_room_power_levels(room_id)
.await;
.room_state_get_content::<RoomPowerLevelsEventContent>(
room_id,
&StateEventType::RoomPowerLevels,
"",
)
.await
.ok();
let user_can_demote_self =
room_power_levels.user_can_change_user_power_level(user_id, user_id);
room_power_levels
.as_ref()
.is_some_and(|power_levels_content| {
RoomPowerLevels::from(power_levels_content.clone())
.user_can_change_user_power_level(user_id, user_id)
}) || services
.rooms
.state_accessor
.room_state_get(room_id, &StateEventType::RoomCreate, "")
.await
.is_ok_and(|event| event.sender() == user_id);
if user_can_demote_self
&& let Ok(mut power_levels_content) =
RoomPowerLevelsEventContent::try_from(room_power_levels)
{
if user_can_demote_self {
let mut power_levels_content = room_power_levels.unwrap_or_default();
power_levels_content.users.remove(user_id);
let pl_evt = PartialPdu::state(String::new(), &power_levels_content);
let pl_evt = PduBuilder::state(String::new(), &power_levels_content);
pdu_queue.push((pl_evt, room_id));
}
// Leave the room
pdu_queue.push((
PartialPdu::state(
user_id.to_string(),
&RoomMemberEventContent::new(MembershipState::Leave),
),
PduBuilder::state(user_id.to_string(), &RoomMemberEventContent {
avatar_url: None,
blurhash: None,
membership: MembershipState::Leave,
displayname: None,
join_authorized_via_users_server: None,
reason: None,
is_direct: None,
third_party_invite: None,
redact_events: None,
}),
room_id,
));
// TODO: Redact all messages sent by the user in the room
}
for (pdu, room_id) in pdu_queue {
let state_lock = services.rooms.state.mutex.lock(room_id.as_str()).await;
let _ = services
.rooms
.timeline
.build_and_append_pdu(pdu, user_id, Some(room_id.as_ref()), &state_lock)
.await;
}
super::update_all_rooms(services, pdu_queue, user_id)
.boxed()
.await;
for room_id in all_joined_rooms {
services.rooms.state_cache.forget(room_id, user_id);
}
+18 -15
View File
@@ -20,11 +20,7 @@ use ruma::{
},
uiaa::{AuthFlow, AuthType},
},
assign,
events::{
GlobalAccountDataEventType, push_rules::PushRulesEvent,
room::message::RoomMessageEventContent,
},
events::{GlobalAccountDataEventType, room::message::RoomMessageEventContent},
push,
};
use serde_json::value::RawValue;
@@ -213,15 +209,23 @@ pub(crate) async fn register_route(
None,
&user_id,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(PushRulesEvent::new(
push::Ruleset::server_default(&user_id).into(),
))
.expect("should be able to serialize push rules"),
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent {
content: ruma::events::push_rules::PushRulesEventContent {
global: push::Ruleset::server_default(&user_id),
},
})?,
)
.await?;
// Generate new device id if the user didn't specify one
let (token, device) = if !body.inhibit_login {
let no_device = body.inhibit_login
|| body
.appservice_info
.as_ref()
.is_some_and(|aps| aps.registration.device_management);
let (token, device) = if !no_device {
// Don't create a device for inhibited logins
let device_id = if is_guest { None } else { body.device_id.clone() }
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
@@ -239,14 +243,12 @@ pub(crate) async fn register_route(
Some(client.to_string()),
)
.await?;
debug_info!(%user_id, %device_id, "User account was created");
(Some(new_token), Some(device_id))
} else {
// Don't create a device for inhibited logins
(None, None)
};
debug_info!(%user_id, ?device, "User account was created");
// If the user registered with an email, associate it with their account.
if let Some(identity) = identity
&& let Some(email) = identity.email
@@ -391,12 +393,13 @@ pub(crate) async fn register_route(
}
}
Ok(assign!(register::v3::Response::new(user_id), {
Ok(register::v3::Response {
access_token: token,
user_id,
device_id: device,
refresh_token: None,
expires_in: None,
}))
})
}
/// Determine which flows and parameters should be presented when
+6 -2
View File
@@ -133,7 +133,9 @@ pub(crate) async fn delete_3pid_route(
let sender_user = body.sender_user();
if body.medium != Medium::Email {
return Ok(delete_3pid::v3::Response::new(ThirdPartyIdRemovalStatus::NoSupport));
return Ok(delete_3pid::v3::Response {
id_server_unbind_result: ThirdPartyIdRemovalStatus::NoSupport,
});
}
if services
@@ -145,5 +147,7 @@ pub(crate) async fn delete_3pid_route(
return Err!(Request(ThreepidNotFound("Your account has no associated email.")));
}
Ok(delete_3pid::v3::Response::new(ThirdPartyIdRemovalStatus::Success))
Ok(delete_3pid::v3::Response {
id_server_unbind_result: ThirdPartyIdRemovalStatus::Success,
})
}
+9 -6
View File
@@ -7,7 +7,10 @@ use ruma::{
get_global_account_data, get_room_account_data, set_global_account_data,
set_room_account_data,
},
events::{AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent},
events::{
AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent,
RoomAccountDataEventType,
},
serde::Raw,
};
use serde::Deserialize;
@@ -37,7 +40,7 @@ pub(crate) async fn set_global_account_data_route(
)
.await?;
Ok(set_global_account_data::v3::Response::new())
Ok(set_global_account_data::v3::Response {})
}
/// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`
@@ -62,7 +65,7 @@ pub(crate) async fn set_room_account_data_route(
)
.await?;
Ok(set_room_account_data::v3::Response::new())
Ok(set_room_account_data::v3::Response {})
}
/// # `GET /_matrix/client/r0/user/{userId}/account_data/{type}`
@@ -84,7 +87,7 @@ pub(crate) async fn get_global_account_data_route(
.await
.map_err(|_| err!(Request(NotFound("Data not found."))))?;
Ok(get_global_account_data::v3::Response::new(account_data.content))
Ok(get_global_account_data::v3::Response { account_data: account_data.content })
}
/// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`
@@ -106,7 +109,7 @@ pub(crate) async fn get_room_account_data_route(
.await
.map_err(|_| err!(Request(NotFound("Data not found."))))?;
Ok(get_room_account_data::v3::Response::new(account_data.content))
Ok(get_room_account_data::v3::Response { account_data: account_data.content })
}
async fn set_account_data(
@@ -116,7 +119,7 @@ async fn set_account_data(
event_type_s: &str,
data: &RawJsonValue,
) -> Result {
if event_type_s == "m.fully_read" {
if event_type_s == RoomAccountDataEventType::FullyRead.to_cow_str() {
return Err!(Request(BadJson(
"This endpoint cannot be used for marking a room as fully read (setting \
m.fully_read)"
+1 -1
View File
@@ -1,7 +1,7 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use futures::future::{join, join3};
use ruminuwuity::admin::{get_suspended, set_suspended};
use ruma::api::client::admin::{get_suspended, set_suspended};
use crate::Ruma;
+4 -7
View File
@@ -1,9 +1,6 @@
use axum::extract::State;
use conduwuit::{Err, Result, err};
use ruma::{
api::{appservice::ping, client::appservice::request_ping},
assign,
};
use ruma::api::{appservice::ping, client::appservice::request_ping};
use crate::Ruma;
@@ -43,12 +40,12 @@ pub(crate) async fn appservice_ping(
.sending
.send_appservice_request(
appservice_info.registration.clone(),
assign!(ping::send_ping::v1::Request::new(), {
ping::send_ping::v1::Request {
transaction_id: body.transaction_id.clone(),
}),
},
)
.await?
.expect("We already validated if an appservice URL exists above");
Ok(request_ping::v1::Response::new(timer.elapsed()))
Ok(request_ping::v1::Response { duration: timer.elapsed() })
}
+33 -29
View File
@@ -3,6 +3,7 @@ use std::cmp::Ordering;
use axum::extract::State;
use conduwuit::{Err, Result, err};
use conduwuit_service::Services;
use futures::{FutureExt, future::try_join};
use ruma::{
UInt, UserId,
api::client::backup::{
@@ -27,7 +28,7 @@ pub(crate) async fn create_backup_version_route(
.key_backups
.create_backup(body.sender_user(), &body.algorithm)?;
Ok(create_backup_version::v3::Response::new(version))
Ok(create_backup_version::v3::Response { version })
}
/// # `PUT /_matrix/client/r0/room_keys/version/{version}`
@@ -43,7 +44,7 @@ pub(crate) async fn update_backup_version_route(
.update_backup(body.sender_user(), &body.version, &body.algorithm)
.await?;
Ok(update_backup_version::v3::Response::new())
Ok(update_backup_version::v3::Response {})
}
/// # `GET /_matrix/client/r0/room_keys/version`
@@ -59,9 +60,9 @@ pub(crate) async fn get_latest_backup_info_route(
.await
.map_err(|_| err!(Request(NotFound("Key backup does not exist."))))?;
let (count, etag) = get_count_etag(&services, body.sender_user(), &version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &version).await?;
Ok(get_latest_backup_info::v3::Response::new(algorithm, count, etag, version))
Ok(get_latest_backup_info::v3::Response { algorithm, count, etag, version })
}
/// # `GET /_matrix/client/v3/room_keys/version/{version}`
@@ -79,9 +80,14 @@ pub(crate) async fn get_backup_info_route(
err!(Request(NotFound("Key backup does not exist at version {:?}", body.version)))
})?;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await?;
Ok(get_backup_info::v3::Response::new(algorithm, count, etag, body.version.clone()))
Ok(get_backup_info::v3::Response {
algorithm,
count,
etag,
version: body.version.clone(),
})
}
/// # `DELETE /_matrix/client/r0/room_keys/version/{version}`
@@ -99,7 +105,7 @@ pub(crate) async fn delete_backup_version_route(
.delete_backup(body.sender_user(), &body.version)
.await;
Ok(delete_backup_version::v3::Response::new())
Ok(delete_backup_version::v3::Response {})
}
/// # `PUT /_matrix/client/r0/room_keys/keys`
@@ -134,9 +140,9 @@ pub(crate) async fn add_backup_keys_route(
}
}
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await?;
Ok(add_backup_keys::v3::Response::new(etag, count))
Ok(add_backup_keys::v3::Response { count, etag })
}
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}`
@@ -169,9 +175,9 @@ pub(crate) async fn add_backup_keys_for_room_route(
.await?;
}
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await?;
Ok(add_backup_keys_for_room::v3::Response::new(etag, count))
Ok(add_backup_keys_for_room::v3::Response { count, etag })
}
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
@@ -269,9 +275,9 @@ pub(crate) async fn add_backup_keys_for_session_route(
.await?;
}
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await?;
Ok(add_backup_keys_for_session::v3::Response::new(etag, count))
Ok(add_backup_keys_for_session::v3::Response { count, etag })
}
/// # `GET /_matrix/client/r0/room_keys/keys`
@@ -286,7 +292,7 @@ pub(crate) async fn get_backup_keys_route(
.get_all(body.sender_user(), &body.version)
.await;
Ok(get_backup_keys::v3::Response::new(rooms))
Ok(get_backup_keys::v3::Response { rooms })
}
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}`
@@ -301,7 +307,7 @@ pub(crate) async fn get_backup_keys_for_room_route(
.get_room(body.sender_user(), &body.version, &body.room_id)
.await;
Ok(get_backup_keys_for_room::v3::Response::new(sessions))
Ok(get_backup_keys_for_room::v3::Response { sessions })
}
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
@@ -319,7 +325,7 @@ pub(crate) async fn get_backup_keys_for_session_route(
err!(Request(NotFound(debug_error!("Backup key not found for this user's session."))))
})?;
Ok(get_backup_keys_for_session::v3::Response::new(key_data))
Ok(get_backup_keys_for_session::v3::Response { key_data })
}
/// # `DELETE /_matrix/client/r0/room_keys/keys`
@@ -334,9 +340,9 @@ pub(crate) async fn delete_backup_keys_route(
.delete_all_keys(body.sender_user(), &body.version)
.await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await?;
Ok(delete_backup_keys::v3::Response::new(etag, count))
Ok(delete_backup_keys::v3::Response { count, etag })
}
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}`
@@ -351,9 +357,9 @@ pub(crate) async fn delete_backup_keys_for_room_route(
.delete_room_keys(body.sender_user(), &body.version, &body.room_id)
.await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await?;
Ok(delete_backup_keys_for_room::v3::Response::new(etag, count))
Ok(delete_backup_keys_for_room::v3::Response { count, etag })
}
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
@@ -368,24 +374,22 @@ pub(crate) async fn delete_backup_keys_for_session_route(
.delete_room_key(body.sender_user(), &body.version, &body.room_id, &body.session_id)
.await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await?;
Ok(delete_backup_keys_for_session::v3::Response::new(etag, count))
Ok(delete_backup_keys_for_session::v3::Response { count, etag })
}
async fn get_count_etag(
services: &Services,
sender_user: &UserId,
version: &str,
) -> (UInt, String) {
let count: UInt = services
) -> Result<(UInt, String)> {
let count = services
.key_backups
.count_keys(sender_user, version)
.await
.try_into()
.expect("number of keys should fit into a UInt");
.map(TryInto::try_into);
let etag = services.key_backups.get_etag(sender_user, version).await;
let etag = services.key_backups.get_etag(sender_user, version).map(Ok);
(count, etag)
Ok(try_join(count, etag).await?)
}
+12 -13
View File
@@ -5,11 +5,8 @@ use conduwuit::{Result, Server};
use ruma::{
RoomVersionId,
api::client::discovery::get_capabilities::{
self,
v3::{
Capabilities, GetLoginTokenCapability, RoomVersionStability, RoomVersionsCapability,
ThirdPartyIdChangesCapability,
},
self, Capabilities, GetLoginTokenCapability, RoomVersionStability,
RoomVersionsCapability, ThirdPartyIdChangesCapability,
},
};
use serde_json::json;
@@ -28,17 +25,19 @@ pub(crate) async fn get_capabilities_route(
Server::available_room_versions().collect();
let mut capabilities = Capabilities::default();
capabilities.room_versions = RoomVersionsCapability::new(
services.server.config.default_room_version.clone(),
capabilities.room_versions = RoomVersionsCapability {
available,
);
default: services.server.config.default_room_version.clone(),
};
// Only allow 3pid changes if SMTP is configured
capabilities.thirdparty_id_changes =
ThirdPartyIdChangesCapability::new(services.mailer.mailer().is_some());
capabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability {
enabled: services.mailer.mailer().is_some(),
};
capabilities.get_login_token =
GetLoginTokenCapability::new(services.server.config.login_via_existing_session);
capabilities.get_login_token = GetLoginTokenCapability {
enabled: services.server.config.login_via_existing_session,
};
// MSC4133 capability
capabilities.set("uk.tcpip.msc4133.profile_fields", json!({"enabled": true}))?;
@@ -57,5 +56,5 @@ pub(crate) async fn get_capabilities_route(
capabilities.set("uk.timedout.msc4323", json!({"suspend": true, "lock": false}))?;
}
Ok(get_capabilities::v3::Response::new(capabilities))
Ok(get_capabilities::v3::Response { capabilities })
}
+3 -5
View File
@@ -12,9 +12,7 @@ use futures::{
FutureExt, StreamExt, TryFutureExt, TryStreamExt,
future::{OptionFuture, join, join3, try_join3},
};
use ruma::{
OwnedEventId, UserId, api::client::context::get_context, assign, events::StateEventType,
};
use ruma::{OwnedEventId, UserId, api::client::context::get_context, events::StateEventType};
use crate::{
Ruma,
@@ -215,7 +213,7 @@ pub(crate) async fn get_context_route(
.collect()
.await;
Ok(assign!(get_context::v3::Response::new(), {
Ok(get_context::v3::Response {
event: base_event.map(at!(1)).map(Event::into_format),
start: events_before
@@ -245,5 +243,5 @@ pub(crate) async fn get_context_route(
.collect(),
state,
}))
})
}
+13 -13
View File
@@ -2,14 +2,10 @@ use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduwuit::{Err, Result, at};
use futures::StreamExt;
use ruma::{
api::client::dehydrated_device::{
delete_dehydrated_device::unstable as delete_dehydrated_device,
get_dehydrated_device::unstable as get_dehydrated_device,
get_events::unstable as get_events,
put_dehydrated_device::unstable as put_dehydrated_device,
},
assign,
use ruma::api::client::dehydrated_device::{
delete_dehydrated_device::unstable as delete_dehydrated_device,
get_dehydrated_device::unstable as get_dehydrated_device, get_events::unstable as get_events,
put_dehydrated_device::unstable as put_dehydrated_device,
};
use crate::Ruma;
@@ -37,7 +33,7 @@ pub(crate) async fn put_dehydrated_device_route(
.set_dehydrated_device(sender_user, body.body)
.await?;
Ok(put_dehydrated_device::Response::new(device_id))
Ok(put_dehydrated_device::Response { device_id })
}
/// # `DELETE /_matrix/client/../dehydrated_device`
@@ -55,7 +51,7 @@ pub(crate) async fn delete_dehydrated_device_route(
services.users.remove_device(sender_user, &device_id).await;
Ok(delete_dehydrated_device::Response::new(device_id))
Ok(delete_dehydrated_device::Response { device_id })
}
/// # `GET /_matrix/client/../dehydrated_device`
@@ -71,7 +67,10 @@ pub(crate) async fn get_dehydrated_device_route(
let device = services.users.get_dehydrated_device(sender_user).await?;
Ok(get_dehydrated_device::Response::new(device.device_id, device.device_data))
Ok(get_dehydrated_device::Response {
device_id: device.device_id,
device_data: device.device_data,
})
}
/// # `GET /_matrix/client/../dehydrated_device/{device_id}/events`
@@ -115,7 +114,8 @@ pub(crate) async fn get_dehydrated_events_route(
.collect()
.await;
Ok(assign!(get_events::Response::new(events), {
Ok(get_events::Response {
events,
next_batch: next_batch.as_ref().map(ToString::to_string),
}))
})
}
+46 -23
View File
@@ -25,7 +25,7 @@ pub(crate) async fn get_devices_route(
.collect()
.await;
Ok(get_devices::v3::Response::new(devices))
Ok(get_devices::v3::Response { devices })
}
/// # `GET /_matrix/client/r0/devices/{deviceId}`
@@ -41,7 +41,7 @@ pub(crate) async fn get_device_route(
.await
.map_err(|_| err!(Request(NotFound("Device not found."))))?;
Ok(get_device::v3::Response::new(device))
Ok(get_device::v3::Response { device })
}
/// # `PUT /_matrix/client/r0/devices/{deviceId}`
@@ -73,16 +73,19 @@ pub(crate) async fn update_device_route(
.update_device_metadata(sender_user, &body.device_id, &device)
.await?;
Ok(update_device::v3::Response::new())
Ok(update_device::v3::Response {})
},
| Err(_) => {
let Some(appservice) = appservice else {
return Err!(Request(NotFound("Device not found.")));
};
if !appservice.registration.device_management {
return Err!(Request(NotFound("Device not found.")));
}
debug!(
"Creating new device for {sender_user} from appservice {} as device ID does not \
exist",
"Creating new device for {sender_user} from appservice {} as MSC4190 is enabled \
and device ID does not exist",
appservice.registration.id
);
@@ -99,7 +102,7 @@ pub(crate) async fn update_device_route(
)
.await?;
return Ok(update_device::v3::Response::new());
return Ok(update_device::v3::Response {});
},
}
}
@@ -121,28 +124,39 @@ pub(crate) async fn delete_device_route(
let sender_user = body.sender_user();
let appservice = body.appservice_info.as_ref();
// Appservices get to skip UIAA for this endpoint
if appservice.is_none() {
// Prompt the user to confirm with their password using UIAA
let _ = services
.uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
.await?;
if appservice.is_some_and(|appservice| appservice.registration.device_management) {
debug!(
"Skipping UIAA for {sender_user} as this is from an appservice and MSC4190 is \
enabled"
);
services
.users
.remove_device(sender_user, &body.device_id)
.await;
return Ok(delete_device::v3::Response {});
}
// Prompt the user to confirm with their password using UIAA
let _ = services
.uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
.await?;
services
.users
.remove_device(sender_user, &body.device_id)
.await;
Ok(delete_device::v3::Response::new())
Ok(delete_device::v3::Response {})
}
/// # `POST /_matrix/client/v3/delete_devices`
///
/// Deletes the given list of devices.
///
/// - Requires UIAA to verify user password.
/// - Requires UIAA to verify user password unless from an appservice with
/// MSC4190 enabled.
///
/// For each device:
/// - Invalidates access token
@@ -157,18 +171,27 @@ pub(crate) async fn delete_devices_route(
let sender_user = body.sender_user();
let appservice = body.appservice_info.as_ref();
// Appservices get to skip UIAA for this endpoint
if appservice.is_none() {
// Prompt the user to confirm with their password using UIAA
let _ = services
.uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
.await?;
if appservice.is_some_and(|appservice| appservice.registration.device_management) {
debug!(
"Skipping UIAA for {sender_user} as this is from an appservice and MSC4190 is \
enabled"
);
for device_id in &body.devices {
services.users.remove_device(sender_user, device_id).await;
}
return Ok(delete_devices::v3::Response {});
}
// Prompt the user to confirm with their password using UIAA
let _ = services
.uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
.await?;
for device_id in &body.devices {
services.users.remove_device(sender_user, device_id).await;
}
Ok(delete_devices::v3::Response::new())
Ok(delete_devices::v3::Response {})
}
+140 -50
View File
@@ -1,16 +1,23 @@
use std::iter::once;
use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduwuit::{
Err, Result, err, info,
Err, Event, Result, RoomVersion, err, info,
utils::{
TryFutureExtExt,
math::Expected,
result::FlatOk,
stream::{ReadyExt, WidebandExt},
},
};
use conduwuit_service::Services;
use futures::StreamExt;
use futures::{
FutureExt, StreamExt, TryFutureExt,
future::{join, join4, join5},
};
use ruma::{
RoomId, ServerName, UInt, UserId,
OwnedRoomId, RoomId, ServerName, UInt, UserId,
api::{
client::{
directory::{
@@ -21,9 +28,15 @@ use ruma::{
},
federation,
},
assign,
directory::{Filter, PublicRoomsChunk, RoomNetwork, RoomTypeFilter},
events::StateEventType,
directory::{Filter, PublicRoomJoinRule, PublicRoomsChunk, RoomNetwork, RoomTypeFilter},
events::{
StateEventType,
room::{
create::RoomCreateEventContent,
join_rules::{JoinRule, RoomJoinRulesEventContent},
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
},
},
uint,
};
use tokio::join;
@@ -96,11 +109,12 @@ pub(crate) async fn get_public_rooms_route(
err!(Request(Unknown(warn!(?body.server, "Failed to return /publicRooms: {e}"))))
})?;
Ok(assign!(get_public_rooms::v3::Response::new(response.chunk), {
Ok(get_public_rooms::v3::Response {
chunk: response.chunk,
prev_batch: response.prev_batch,
next_batch: response.next_batch,
total_room_count_estimate: response.total_room_count_estimate,
}))
})
}
/// # `PUT /_matrix/client/r0/directory/list/room/{roomId}`
@@ -183,7 +197,7 @@ pub(crate) async fn set_room_visibility_route(
},
}
Ok(set_room_visibility::v3::Response::new())
Ok(set_room_visibility::v3::Response {})
}
/// # `GET /_matrix/client/r0/directory/list/room/{roomId}`
@@ -198,13 +212,13 @@ pub(crate) async fn get_room_visibility_route(
return Err!(Request(NotFound("Room not found")));
}
let visibility = if services.rooms.directory.is_public_room(&body.room_id).await {
room::Visibility::Public
} else {
room::Visibility::Private
};
Ok(get_room_visibility::v3::Response::new(visibility))
Ok(get_room_visibility::v3::Response {
visibility: if services.rooms.directory.is_public_room(&body.room_id).await {
room::Visibility::Public
} else {
room::Visibility::Private
},
})
}
pub(crate) async fn get_public_rooms_filtered_helper(
@@ -222,24 +236,24 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.sending
.send_federation_request(
other_server,
assign!(federation::directory::get_public_rooms_filtered::v1::Request::new(), {
federation::directory::get_public_rooms_filtered::v1::Request {
limit,
since: since.map(ToOwned::to_owned),
filter: assign!(Filter::new(), {
filter: Filter {
generic_search_term: filter.generic_search_term.clone(),
room_types: filter.room_types.clone(),
}),
},
room_network: RoomNetwork::Matrix,
}),
},
)
.await?;
return Ok(assign!(get_public_rooms_filtered::v3::Response::new(), {
return Ok(get_public_rooms_filtered::v3::Response {
chunk: response.chunk,
prev_batch: response.prev_batch,
next_batch: response.next_batch,
total_room_count_estimate: response.total_room_count_estimate,
}));
});
}
// Use limit or else 10, with maximum 100
@@ -270,24 +284,16 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.rooms
.directory
.public_rooms()
.wide_then(async |room_id| {
let summary = services
.rooms
.summary
.build_local_room_summary(&room_id)
.await
.expect("room in public room directory should exist");
summary.into()
})
.ready_filter_map(|chunk: PublicRoomsChunk| {
.map(ToOwned::to_owned)
.wide_then(|room_id| public_rooms_chunk(services, room_id))
.ready_filter_map(|chunk| {
if !filter.room_types.is_empty() && !filter.room_types.contains(&RoomTypeFilter::from(chunk.room_type.clone())) {
return None;
}
if let Some(query) = filter.generic_search_term.as_ref().map(|q| q.to_lowercase()) {
if let Some(name) = &chunk.name {
if name.to_lowercase().contains(&query) {
if name.as_str().to_lowercase().contains(&query) {
return Some(chunk);
}
}
@@ -314,7 +320,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.collect()
.await;
all_rooms.sort_by_key(|r| std::cmp::Reverse(r.num_joined_members));
all_rooms.sort_by(|l, r| r.num_joined_members.cmp(&l.num_joined_members));
let total_room_count_estimate = UInt::try_from(all_rooms.len())
.unwrap_or_else(|_| uint!(0))
@@ -329,12 +335,12 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.ge(&limit)
.then_some(format!("n{}", num_since.expected_add(limit)));
Ok(assign!(get_public_rooms_filtered::v3::Response::new(), {
Ok(get_public_rooms_filtered::v3::Response {
chunk,
prev_batch,
next_batch,
total_room_count_estimate,
}))
})
}
/// Checks whether the given user ID is allowed to publish the target room to
@@ -350,25 +356,109 @@ async fn user_can_publish_room(
// Server admins can always publish to their own room directory.
return Ok(true);
}
let (room_version, room_creators, power_levels) = join!(
let (create_event, room_version, power_levels_content) = join!(
services
.rooms
.state_accessor
.room_state_get(room_id, &StateEventType::RoomCreate, ""),
services.rooms.state.get_room_version(room_id),
services.rooms.state_accessor.get_room_creators(room_id),
services.rooms.state_accessor.get_room_power_levels(room_id),
services
.rooms
.state_accessor
.room_state_get_content::<RoomPowerLevelsEventContent>(
room_id,
&StateEventType::RoomPowerLevels,
""
)
);
let room_version = room_version
.as_ref()
.map_err(|_| err!(Request(NotFound("Unknown room"))))?;
let room_version_rules = room_version.rules().unwrap();
if room_version_rules
.authorization
let create_event = create_event.map_err(|_| err!(Request(NotFound("Unknown room"))))?;
if RoomVersion::new(room_version)
.expect("room version must be supported")
.explicitly_privilege_room_creators
&& room_creators.contains(user_id)
{
return Ok(true);
let create_content: RoomCreateEventContent =
serde_json::from_str(create_event.content().get())
.map_err(|_| err!(Database("Invalid event content for m.room.create")))?;
let is_creator = create_content
.additional_creators
.unwrap_or_default()
.into_iter()
.chain(once(create_event.sender().to_owned()))
.any(|sender| sender == user_id);
if is_creator {
return Ok(true);
}
}
match power_levels_content.map(RoomPowerLevels::from) {
| Ok(pl) => Ok(pl.user_can_send_state(user_id, StateEventType::RoomCanonicalAlias)),
| Err(e) =>
if e.is_not_found() {
Ok(create_event.sender() == user_id)
} else {
Err!(Database("Invalid event content for m.room.power_levels: {e}"))
},
}
}
async fn public_rooms_chunk(services: &Services, room_id: OwnedRoomId) -> PublicRoomsChunk {
let name = services.rooms.state_accessor.get_name(&room_id).ok();
let room_type = services.rooms.state_accessor.get_room_type(&room_id).ok();
let canonical_alias = services
.rooms
.state_accessor
.get_canonical_alias(&room_id)
.ok();
let avatar_url = services.rooms.state_accessor.get_avatar(&room_id);
let topic = services.rooms.state_accessor.get_room_topic(&room_id).ok();
let world_readable = services.rooms.state_accessor.is_world_readable(&room_id);
let join_rule = services
.rooms
.state_accessor
.room_state_get_content(&room_id, &StateEventType::RoomJoinRules, "")
.map_ok(|c: RoomJoinRulesEventContent| match c.join_rule {
| JoinRule::Public => PublicRoomJoinRule::Public,
| JoinRule::Knock => "knock".into(),
| JoinRule::KnockRestricted(_) => "knock_restricted".into(),
| _ => "invite".into(),
});
let guest_can_join = services.rooms.state_accessor.guest_can_join(&room_id);
let num_joined_members = services.rooms.state_cache.room_joined_count(&room_id);
let (
(avatar_url, canonical_alias, guest_can_join, join_rule, name),
(num_joined_members, room_type, topic, world_readable),
) = join(
join5(avatar_url, canonical_alias, guest_can_join, join_rule, name),
join4(num_joined_members, room_type, topic, world_readable),
)
.boxed()
.await;
PublicRoomsChunk {
avatar_url: avatar_url.into_option().unwrap_or_default().url,
canonical_alias,
guest_can_join,
join_rule: join_rule.unwrap_or_default(),
name,
num_joined_members: num_joined_members
.map(TryInto::try_into)
.map(Result::ok)
.flat_ok()
.unwrap_or_else(|| uint!(0)),
room_id,
room_type,
topic,
world_readable,
}
Ok(power_levels.user_can_send_state(user_id, StateEventType::RoomCanonicalAlias))
}
+61 -45
View File
@@ -5,7 +5,7 @@ use std::{
use axum::extract::State;
use conduwuit::{
Err, Result, debug, debug_warn, err,
Err, Error, Result, debug, debug_warn, err,
result::NotFound,
utils::{IterStream, stream::WidebandExt},
};
@@ -14,14 +14,16 @@ use futures::{StreamExt, stream::FuturesUnordered};
use ruma::{
OneTimeKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
api::{
client::keys::{
claim_keys, get_key_changes, get_keys, upload_keys,
upload_signatures::{self},
upload_signing_keys,
client::{
error::ErrorKind,
keys::{
claim_keys, get_key_changes, get_keys, upload_keys,
upload_signatures::{self},
upload_signing_keys,
},
},
federation,
},
assign,
encryption::CrossSigningKey,
serde::Raw,
};
@@ -113,12 +115,12 @@ pub(crate) async fn upload_keys_route(
}
}
let one_time_key_counts = services
.users
.count_one_time_keys(sender_user, sender_device)
.await;
Ok(upload_keys::v3::Response::new(one_time_key_counts))
Ok(upload_keys::v3::Response {
one_time_key_counts: services
.users
.count_one_time_keys(sender_user, sender_device)
.await,
})
}
/// # `POST /_matrix/client/r0/keys/query`
@@ -212,7 +214,7 @@ pub(crate) async fn upload_signing_keys_route(
)
.await?;
Ok(upload_signing_keys::v3::Response::new())
Ok(upload_signing_keys::v3::Response {})
}
async fn check_for_new_keys(
@@ -224,7 +226,8 @@ async fn check_for_new_keys(
) -> Result<Option<upload_signing_keys::v3::Response>> {
debug!("checking for existing keys");
let mut empty = false;
if master_signing_key.is_some() {
if let Some(master_signing_key) = master_signing_key {
let (key, value) = parse_master_key(user_id, master_signing_key)?;
let result = services
.users
.get_master_key(None, user_id, &|_| true)
@@ -232,12 +235,16 @@ async fn check_for_new_keys(
if result.is_not_found() {
empty = true;
} else {
return Err!(Request(Forbidden(
"Tried to change an existing master key, UIA required"
)));
let existing_master_key = result?;
let (existing_key, existing_value) = parse_master_key(user_id, &existing_master_key)?;
if existing_key != key || existing_value != value {
return Err!(Request(Forbidden(
"Tried to change an existing master key, UIA required"
)));
}
}
}
if user_signing_key.is_some() {
if let Some(user_signing_key) = user_signing_key {
let key = services.users.get_user_signing_key(user_id).await;
if key.is_not_found() && !empty {
return Err!(Request(Forbidden(
@@ -245,12 +252,15 @@ async fn check_for_new_keys(
)));
}
if !key.is_not_found() {
return Err!(Request(Forbidden(
"Tried to change an existing user signing key, UIA required"
)));
let existing_signing_key = key?.deserialize()?;
if existing_signing_key != user_signing_key.deserialize()? {
return Err!(Request(Forbidden(
"Tried to change an existing user signing key, UIA required"
)));
}
}
}
if self_signing_key.is_some() {
if let Some(self_signing_key) = self_signing_key {
let key = services
.users
.get_self_signing_key(None, user_id, &|_| true)
@@ -262,16 +272,19 @@ async fn check_for_new_keys(
)));
}
if !key.is_not_found() {
return Err!(Request(Forbidden(
"Tried to update an existing self signing key, UIA required"
)));
let existing_signing_key = key?.deserialize()?;
if existing_signing_key != self_signing_key.deserialize()? {
return Err!(Request(Forbidden(
"Tried to update an existing self signing key, UIA required"
)));
}
}
}
if empty {
return Ok(None);
}
Ok(Some(upload_signing_keys::v3::Response::new()))
Ok(Some(upload_signing_keys::v3::Response {}))
}
/// # `POST /_matrix/client/r0/keys/signatures/upload`
@@ -330,7 +343,7 @@ pub(crate) async fn upload_signatures_route(
}
}
Ok(upload_signatures::v3::Response::new())
Ok(upload_signatures::v3::Response { failures: BTreeMap::new() })
}
/// # `POST /_matrix/client/r0/keys/changes`
@@ -350,17 +363,18 @@ pub(crate) async fn get_key_changes_route(
let from = body
.from
.parse()
.map_err(|_| err!(Request(InvalidParam("Invalid `from`."))))?;
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?;
let to = body
.to
.parse()
.map_err(|_| err!(Request(InvalidParam("Invalid `to`."))))?;
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?;
device_list_updates.extend(
services
.users
.keys_changed(sender_user, Some(from), Some(to))
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.await,
);
@@ -371,18 +385,18 @@ pub(crate) async fn get_key_changes_route(
device_list_updates.extend(
services
.users
.room_keys_changed(&room_id, Some(from), Some(to))
.room_keys_changed(room_id, Some(from), Some(to))
.map(|(user_id, _)| user_id)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.await,
);
}
Ok(get_key_changes::v3::Response::new(
device_list_updates.into_iter().collect(),
// TODO
vec![],
))
Ok(get_key_changes::v3::Response {
changed: device_list_updates.into_iter().collect(),
left: Vec::new(), // TODO
})
}
pub(crate) async fn get_keys_helper<F>(
@@ -419,10 +433,10 @@ where
let mut devices = services.users.all_device_ids(user_id).boxed();
while let Some(device_id) = devices.next().await {
if let Ok(mut keys) = services.users.get_device_keys(user_id, &device_id).await {
if let Ok(mut keys) = services.users.get_device_keys(user_id, device_id).await {
let metadata = services
.users
.get_device_metadata(user_id, &device_id)
.get_device_metadata(user_id, device_id)
.await
.map_err(|_| {
err!(Database("all_device_keys contained nonexistent device."))
@@ -431,7 +445,7 @@ where
add_unsigned_device_display_name(&mut keys, metadata, include_display_names)
.map_err(|_| err!(Database("invalid device keys in database")))?;
container.insert(device_id.clone(), keys);
container.insert(device_id.to_owned(), keys);
}
}
@@ -492,7 +506,8 @@ where
device_keys_input_fed.insert(user_id.to_owned(), keys.clone());
}
let request = federation::keys::get_keys::v1::Request::new(device_keys_input_fed);
let request =
federation::keys::get_keys::v1::Request { device_keys: device_keys_input_fed };
let response = tokio::time::timeout(
timeout,
services.sending.send_federation_request(server, request),
@@ -546,13 +561,13 @@ where
}
}
Ok(assign!(get_keys::v3::Response::new(), {
Ok(get_keys::v3::Response {
failures,
device_keys,
master_keys,
self_signing_keys,
user_signing_keys,
}))
})
}
fn add_unsigned_device_display_name(
@@ -561,8 +576,7 @@ fn add_unsigned_device_display_name(
include_display_names: bool,
) -> serde_json::Result<()> {
if let Some(display_name) = metadata.display_name {
let mut object =
keys.deserialize_as_unchecked::<serde_json::Map<String, serde_json::Value>>()?;
let mut object = keys.deserialize_as::<serde_json::Map<String, serde_json::Value>>()?;
let unsigned = object.entry("unsigned").or_insert_with(|| json!({}));
if let serde_json::Value::Object(unsigned_object) = unsigned {
@@ -628,7 +642,9 @@ pub(crate) async fn claim_keys_helper(
timeout,
services.sending.send_federation_request(
server,
federation::keys::claim_keys::v1::Request::new(one_time_keys_input_fed),
federation::keys::claim_keys::v1::Request {
one_time_keys: one_time_keys_input_fed,
},
),
)
.await
@@ -651,5 +667,5 @@ pub(crate) async fn claim_keys_helper(
}
}
Ok(assign!(claim_keys::v3::Response::new(one_time_keys), { failures: failures }))
Ok(claim_keys::v3::Response { failures, one_time_keys })
}
+81 -36
View File
@@ -9,11 +9,11 @@ use conduwuit::{
use conduwuit_core::error;
use conduwuit_service::{
Services,
media::{Dim, FileMeta, MXC_LENGTH},
media::{CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN, Dim, FileMeta, MXC_LENGTH},
};
use reqwest::Url;
use ruma::{
UserId,
Mxc, UserId,
api::client::{
authenticated_media::{
get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
@@ -21,9 +21,7 @@ use ruma::{
},
media::create_content,
},
assign,
};
use service::media::mxc::Mxc;
use crate::Ruma;
@@ -32,9 +30,9 @@ pub(crate) async fn get_media_config_route(
State(services): State<crate::State>,
_body: Ruma<get_media_config::v1::Request>,
) -> Result<get_media_config::v1::Response> {
Ok(get_media_config::v1::Response::new(ruma_from_usize(
services.server.config.max_request_size,
)))
Ok(get_media_config::v1::Response {
upload_size: ruma_from_usize(services.server.config.max_request_size),
})
}
/// # `POST /_matrix/media/v3/upload`
@@ -84,9 +82,10 @@ pub(crate) async fn create_content_route(
.flatten()
});
Ok(assign!(create_content::v3::Response::new(mxc.to_string().into()), {
Ok(create_content::v3::Response {
content_uri: mxc.to_string().into(),
blurhash: blurhash.flatten(),
}))
})
}
/// # `GET /_matrix/client/v1/media/thumbnail/{serverName}/{mediaId}`
@@ -115,7 +114,7 @@ pub(crate) async fn get_content_thumbnail_route(
content,
content_type,
content_disposition,
} = match fetch_thumbnail_meta(&services, &mxc, user, body.timeout_ms, &dim).await {
} = match fetch_thumbnail(&services, &mxc, user, body.timeout_ms, &dim).await {
| Ok(meta) => meta,
| Err(conduwuit::Error::Io(e)) => match e.kind() {
| std::io::ErrorKind::NotFound =>
@@ -129,14 +128,13 @@ pub(crate) async fn get_content_thumbnail_route(
| Err(_) => return Err!(Request(Unknown("Unknown error when fetching thumbnail."))),
};
let content_disposition =
make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None);
Ok(get_content_thumbnail::v1::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
Ok(get_content_thumbnail::v1::Response {
file: content.expect("entire file contents"),
content_type: content_type.map(Into::into),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition,
))
})
}
/// # `GET /_matrix/client/v1/media/download/{serverName}/{mediaId}`
@@ -163,7 +161,7 @@ pub(crate) async fn get_content_route(
content,
content_type,
content_disposition,
} = match fetch_file_meta(&services, &mxc, user, body.timeout_ms).await {
} = match fetch_file(&services, &mxc, user, body.timeout_ms, None).await {
| Ok(meta) => meta,
| Err(conduwuit::Error::Io(e)) => match e.kind() {
| std::io::ErrorKind::NotFound => return Err!(Request(NotFound("Media not found."))),
@@ -176,14 +174,13 @@ pub(crate) async fn get_content_route(
| Err(_) => return Err!(Request(Unknown("Unknown error when fetching file."))),
};
let content_disposition =
make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None);
Ok(get_content::v1::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
Ok(get_content::v1::Response {
file: content.expect("entire file contents"),
content_type: content_type.map(Into::into),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition,
))
})
}
/// # `GET /_matrix/client/v1/media/download/{serverName}/{mediaId}/{fileName}`
@@ -211,7 +208,7 @@ pub(crate) async fn get_content_as_filename_route(
content,
content_type,
content_disposition,
} = match fetch_file_meta(&services, &mxc, user, body.timeout_ms).await {
} = match fetch_file(&services, &mxc, user, body.timeout_ms, None).await {
| Ok(meta) => meta,
| Err(conduwuit::Error::Io(e)) => match e.kind() {
| std::io::ErrorKind::NotFound => return Err!(Request(NotFound("Media not found."))),
@@ -224,17 +221,13 @@ pub(crate) async fn get_content_as_filename_route(
| Err(_) => return Err!(Request(Unknown("Unknown error when fetching file."))),
};
let content_disposition = make_content_disposition(
content_disposition.as_ref(),
content_type.as_deref(),
Some(&body.filename),
);
Ok(get_content_as_filename::v1::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
Ok(get_content_as_filename::v1::Response {
file: content.expect("entire file contents"),
content_type: content_type.map(Into::into),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition,
))
})
}
/// # `GET /_matrix/client/v1/media/preview_url`
@@ -285,6 +278,58 @@ pub(crate) async fn get_media_preview_route(
})
}
async fn fetch_thumbnail(
services: &Services,
mxc: &Mxc<'_>,
user: &UserId,
timeout_ms: Duration,
dim: &Dim,
) -> Result<FileMeta> {
let FileMeta {
content,
content_type,
content_disposition,
} = fetch_thumbnail_meta(services, mxc, user, timeout_ms, dim).await?;
let content_disposition = Some(make_content_disposition(
content_disposition.as_ref(),
content_type.as_deref(),
None,
));
Ok(FileMeta {
content,
content_type,
content_disposition,
})
}
async fn fetch_file(
services: &Services,
mxc: &Mxc<'_>,
user: &UserId,
timeout_ms: Duration,
filename: Option<&str>,
) -> Result<FileMeta> {
let FileMeta {
content,
content_type,
content_disposition,
} = fetch_file_meta(services, mxc, user, timeout_ms).await?;
let content_disposition = Some(make_content_disposition(
content_disposition.as_ref(),
content_type.as_deref(),
filename,
));
Ok(FileMeta {
content,
content_type,
content_disposition,
})
}
async fn fetch_thumbnail_meta(
services: &Services,
mxc: &Mxc<'_>,
+47 -65
View File
@@ -6,16 +6,15 @@ use conduwuit::{
Err, Result, err,
utils::{content_disposition::make_content_disposition, math::ruma_from_usize},
};
use conduwuit_service::media::{CORP_CROSS_ORIGIN, Dim, FileMeta};
use conduwuit_service::media::{CACHE_CONTROL_IMMUTABLE, CORP_CROSS_ORIGIN, Dim, FileMeta};
use reqwest::Url;
use ruma::{
Mxc,
api::client::media::{
create_content, get_content, get_content_as_filename, get_content_thumbnail,
get_media_config, get_media_preview,
},
assign,
};
use service::media::mxc::Mxc;
use crate::{Ruma, RumaResponse, client::create_content_route};
@@ -26,9 +25,9 @@ pub(crate) async fn get_media_config_legacy_route(
State(services): State<crate::State>,
_body: Ruma<get_media_config::v3::Request>,
) -> Result<get_media_config::v3::Response> {
Ok(get_media_config::v3::Response::new(ruma_from_usize(
services.server.config.max_request_size,
)))
Ok(get_media_config::v3::Response {
upload_size: ruma_from_usize(services.server.config.max_request_size),
})
}
/// # `GET /_matrix/media/v1/config`
@@ -154,16 +153,13 @@ pub(crate) async fn get_content_legacy_route(
None,
);
Ok(assign!(
get_content::v3::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
Ok(get_content::v3::Response {
file: content.expect("entire file contents"),
content_type: content_type.map(Into::into),
content_disposition: Some(content_disposition),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
})
},
| _ =>
if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
@@ -181,16 +177,13 @@ pub(crate) async fn get_content_legacy_route(
None,
);
Ok(assign!(
get_content::v3::Response::new(
response.file,
response.content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
Ok(get_content::v3::Response {
file: response.file,
content_type: response.content_type,
content_disposition: Some(content_disposition),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
})
} else {
Err!(Request(NotFound("Media not found.")))
},
@@ -251,15 +244,13 @@ pub(crate) async fn get_content_as_filename_legacy_route(
Some(&body.filename),
);
Ok(assign!(get_content_as_filename::v3::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
Ok(get_content_as_filename::v3::Response {
file: content.expect("entire file contents"),
content_type: content_type.map(Into::into),
content_disposition: Some(content_disposition),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
})
},
| _ =>
if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
@@ -277,16 +268,13 @@ pub(crate) async fn get_content_as_filename_legacy_route(
None,
);
Ok(assign!(
get_content_as_filename::v3::Response::new(
response.file,
response.content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
Ok(get_content_as_filename::v3::Response {
content_disposition: Some(content_disposition),
content_type: response.content_type,
file: response.file,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
})
} else {
Err!(Request(NotFound("Media not found.")))
},
@@ -347,16 +335,13 @@ pub(crate) async fn get_content_thumbnail_legacy_route(
None,
);
Ok(assign!(
get_content_thumbnail::v3::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
}
))
Ok(get_content_thumbnail::v3::Response {
file: content.expect("entire file contents"),
content_type: content_type.map(Into::into),
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition: Some(content_disposition),
})
},
| _ =>
if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
@@ -374,16 +359,13 @@ pub(crate) async fn get_content_thumbnail_legacy_route(
None,
);
Ok(assign!(
get_content_thumbnail::v3::Response::new(
response.file,
response.content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
}
))
Ok(get_content_thumbnail::v3::Response {
file: response.file,
content_type: response.content_type,
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition: Some(content_disposition),
})
} else {
Err!(Request(NotFound("Media not found.")))
},
+14 -13
View File
@@ -1,5 +1,5 @@
use axum::extract::State;
use conduwuit::{Err, Result, matrix::pdu::PartialPdu};
use conduwuit::{Err, Result, matrix::pdu::PduBuilder};
use ruma::{
api::client::membership::ban_user,
events::room::member::{MembershipState, RoomMemberEventContent},
@@ -24,29 +24,30 @@ pub(crate) async fn ban_user_route(
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;
let mut content = services
let current_member_content = services
.rooms
.state_accessor
.get_member(&body.room_id, &body.user_id)
.await
.unwrap_or_else(|_| RoomMemberEventContent::new(MembershipState::Ban));
content.membership = MembershipState::Ban;
content.reason.clone_from(&body.reason);
content.displayname = None;
content.avatar_url = None;
content.is_direct = None;
content.join_authorized_via_users_server = None;
content.third_party_invite = None;
// TODO(upstream): MSC4293
services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(body.user_id.to_string(), &content),
PduBuilder::state(body.user_id.to_string(), &RoomMemberEventContent {
membership: MembershipState::Ban,
reason: body.reason.clone(),
displayname: None, // display name may be offensive
avatar_url: None, // avatar may be offensive
is_direct: None,
join_authorized_via_users_server: None,
third_party_invite: None,
redact_events: body.redact_events,
..current_member_content
}),
sender_user,
Some(&body.room_id),
&state_lock,
+45 -54
View File
@@ -2,19 +2,18 @@ use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduwuit::{
Err, Result, debug_error, err, info,
matrix::{event::gen_event_id_canonical_json, pdu::PartialPdu},
matrix::{event::gen_event_id_canonical_json, pdu::PduBuilder},
warn,
};
use futures::FutureExt;
use ruma::{
RoomId, UserId,
api::{
client::membership::invite_user::{self, v3::InviteUserId},
federation::membership::create_invite,
api::{client::membership::invite_user, federation::membership::create_invite},
events::{
invite_permission_config::FilterLevel,
room::member::{MembershipState, RoomMemberEventContent},
},
events::room::member::{MembershipState, RoomMemberEventContent},
};
use ruminuwuity::invite_permission_config::FilterLevel;
use service::Services;
use super::banned_room_check;
@@ -52,11 +51,7 @@ pub(crate) async fn invite_user_route(
.await?;
match &body.recipient {
| invite_user::v3::InvitationRecipient::UserId(InviteUserId {
user_id: recipient_user,
reason,
..
}) => {
| invite_user::v3::InvitationRecipient::UserId { user_id: recipient_user } => {
let sender_filter_level = services
.users
.invite_filter_level(recipient_user, sender_user)
@@ -64,7 +59,7 @@ pub(crate) async fn invite_user_route(
if !matches!(sender_filter_level, FilterLevel::Allow) {
// drop invites if the sender has the recipient filtered
return Ok(invite_user::v3::Response::new());
return Ok(invite_user::v3::Response {});
}
if let Ok(target_user_membership) = services
@@ -100,13 +95,13 @@ pub(crate) async fn invite_user_route(
sender_user,
recipient_user,
&body.room_id,
reason.clone(),
body.reason.clone(),
false,
)
.boxed()
.await?;
Ok(invite_user::v3::Response::new())
Ok(invite_user::v3::Response {})
},
| _ => {
Err!(Request(NotFound("User not found.")))
@@ -146,17 +141,18 @@ pub(crate) async fn invite_helper(
let (pdu, pdu_json, invite_room_state) = {
let state_lock = services.rooms.state.mutex.lock(room_id).await;
let mut content = RoomMemberEventContent::new(MembershipState::Invite);
content.displayname = services.users.displayname(recipient_user).await.ok();
content.avatar_url = services.users.avatar_url(recipient_user).await.ok();
content.is_direct = Some(is_direct);
content.reason = reason;
let content = RoomMemberEventContent {
avatar_url: services.users.avatar_url(recipient_user).await.ok(),
is_direct: Some(is_direct),
reason,
..RoomMemberEventContent::new(MembershipState::Invite)
};
let (pdu, pdu_json) = services
.rooms
.timeline
.create_hash_and_sign_event(
PartialPdu::state(recipient_user.to_string(), &content),
PduBuilder::state(recipient_user.to_string(), &content),
sender_user,
Some(room_id),
&state_lock,
@@ -172,39 +168,32 @@ pub(crate) async fn invite_helper(
let room_version_id = services.rooms.state.get_room_version(room_id).await?;
let mut request = create_invite::v2::Request::new(
room_id.to_owned(),
(*pdu.event_id).to_owned(),
room_version_id.clone(),
services
.sending
.convert_to_outgoing_federation_event(pdu_json.clone())
.await,
invite_room_state,
);
request.via = services
.rooms
.state_cache
.servers_route_via(room_id)
.await
.ok();
let response = services
.sending
.send_federation_request(recipient_user.server_name(), request)
.send_federation_request(recipient_user.server_name(), create_invite::v2::Request {
room_id: room_id.to_owned(),
event_id: (*pdu.event_id).to_owned(),
room_version: room_version_id.clone(),
event: services
.sending
.convert_to_outgoing_federation_event(pdu_json.clone())
.await,
invite_room_state,
via: services
.rooms
.state_cache
.servers_route_via(room_id)
.await
.ok(),
})
.await?;
// We do not add the event_id field to the pdu here because of signature and
// hashes checks
let (event_id, value) = gen_event_id_canonical_json(
&response.event,
&room_version_id
.rules()
.expect("room version should have defined rules"),
)
.map_err(|e| {
err!(Request(BadJson(warn!("Could not convert event to canonical JSON: {e}"))))
})?;
let (event_id, value) = gen_event_id_canonical_json(&response.event, &room_version_id)
.map_err(|e| {
err!(Request(BadJson(warn!("Could not convert event to canonical JSON: {e}"))))
})?;
if pdu.event_id != event_id {
return Err!(Request(BadJson(warn!(
@@ -240,18 +229,20 @@ pub(crate) async fn invite_helper(
let state_lock = services.rooms.state.mutex.lock(room_id).await;
let mut content = RoomMemberEventContent::new(MembershipState::Invite);
content.displayname = services.users.displayname(recipient_user).await.ok();
content.avatar_url = services.users.avatar_url(recipient_user).await.ok();
content.blurhash = services.users.blurhash(recipient_user).await.ok();
content.is_direct = Some(is_direct);
content.reason = reason;
let content = RoomMemberEventContent {
displayname: services.users.displayname(recipient_user).await.ok(),
avatar_url: services.users.avatar_url(recipient_user).await.ok(),
blurhash: services.users.blurhash(recipient_user).await.ok(),
is_direct: Some(is_direct),
reason,
..RoomMemberEventContent::new(MembershipState::Invite)
};
services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(recipient_user.to_string(), &content),
PduBuilder::state(recipient_user.to_string(), &content),
sender_user,
Some(room_id),
&state_lock,
+127 -59
View File
@@ -7,7 +7,7 @@ use conduwuit::{
matrix::{
StateKey,
event::{gen_event_id, gen_event_id_canonical_json},
pdu::{PartialPdu, PduEvent},
pdu::{PduBuilder, PduEvent},
state_res,
},
result::FlatOk,
@@ -24,8 +24,10 @@ use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId,
RoomVersionId, UserId,
api::{
client::membership::{join_room_by_id, join_room_by_id_or_alias},
error::{ErrorKind, IncompatibleRoomVersionErrorData},
client::{
error::ErrorKind,
membership::{join_room_by_id, join_room_by_id_or_alias},
},
federation::{self},
},
canonical_json::to_canonical_value,
@@ -87,6 +89,7 @@ pub(crate) async fn join_room_by_id_route(
.rooms
.state_cache
.servers_invite_via(&body.room_id)
.map(ToOwned::to_owned)
.collect()
.await;
@@ -110,6 +113,7 @@ pub(crate) async fn join_room_by_id_route(
servers.sort_unstable();
servers.dedup();
shuffle(&mut servers);
let servers = deprioritize(servers, &services.config.deprioritize_joins_through_servers);
join_room_by_id_helper(
&services,
@@ -165,6 +169,7 @@ pub(crate) async fn join_room_by_id_or_alias_route(
.rooms
.state_cache
.servers_invite_via(&room_id)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.await,
);
@@ -205,7 +210,11 @@ pub(crate) async fn join_room_by_id_or_alias_route(
)
.await?;
let addl_via_servers = services.rooms.state_cache.servers_invite_via(&room_id);
let addl_via_servers = services
.rooms
.state_cache
.servers_invite_via(&room_id)
.map(ToOwned::to_owned);
let addl_state_servers = services
.rooms
@@ -218,7 +227,7 @@ pub(crate) async fn join_room_by_id_or_alias_route(
.iter()
.map(|event| event.get_field("sender"))
.filter_map(FlatOk::flat_ok)
.map(|user: OwnedUserId| user.server_name().to_owned())
.map(|user: &UserId| user.server_name().to_owned())
.stream()
.chain(addl_via_servers)
.collect()
@@ -233,6 +242,7 @@ pub(crate) async fn join_room_by_id_or_alias_route(
},
};
let servers = deprioritize(servers, &services.config.deprioritize_joins_through_servers);
let join_room_response = join_room_by_id_helper(
&services,
sender_user,
@@ -244,7 +254,7 @@ pub(crate) async fn join_room_by_id_or_alias_route(
.boxed()
.await?;
Ok(join_room_by_id_or_alias::v3::Response::new(join_room_response.room_id))
Ok(join_room_by_id_or_alias::v3::Response { room_id: join_room_response.room_id })
}
pub async fn join_room_by_id_helper(
@@ -275,7 +285,7 @@ pub async fn join_room_by_id_helper(
.await
{
debug_warn!("{sender_user} is already joined in {room_id}");
return Ok(join_room_by_id::v3::Response::new(room_id.to_owned()));
return Ok(join_room_by_id::v3::Response { room_id: room_id.into() });
}
if let Err(e) = services
@@ -375,15 +385,12 @@ async fn join_room_by_id_helper_remote(
info!("make_join finished");
let room_version = make_join_response.room_version.unwrap_or(RoomVersionId::V1);
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
let room_version_id = make_join_response.room_version.unwrap_or(RoomVersionId::V1);
if !services.server.supported_room_version(&room_version) {
if !services.server.supported_room_version(&room_version_id) {
// How did we get here?
return Err!(BadServerResponse(
"Remote room version {room_version} is not supported by conduwuit"
"Remote room version {room_version_id} is not supported by conduwuit"
));
}
@@ -396,7 +403,7 @@ async fn join_room_by_id_helper_remote(
let join_authorized_via_users_server = {
use RoomVersionId::*;
if !matches!(room_version, V1 | V2 | V3 | V4 | V5 | V6 | V7) {
if !matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) {
join_event_stub
.get("content")
.map(|s| {
@@ -418,32 +425,36 @@ async fn join_room_by_id_helper_remote(
.expect("Timestamp is valid js_int value"),
),
);
let mut join_content = RoomMemberEventContent::new(MembershipState::Join);
join_content.displayname = services.users.displayname(sender_user).await.ok();
join_content.avatar_url = services.users.avatar_url(sender_user).await.ok();
join_content.blurhash = services.users.blurhash(sender_user).await.ok();
join_content.reason = reason;
join_content
.join_authorized_via_users_server
.clone_from(&join_authorized_via_users_server);
join_event_stub.insert(
"content".to_owned(),
to_canonical_value(join_content).expect("event is valid, we just created it"),
to_canonical_value(RoomMemberEventContent {
displayname: services.users.displayname(sender_user).await.ok(),
avatar_url: services.users.avatar_url(sender_user).await.ok(),
blurhash: services.users.blurhash(sender_user).await.ok(),
reason,
join_authorized_via_users_server: join_authorized_via_users_server.clone(),
..RoomMemberEventContent::new(MembershipState::Join)
})
.expect("event is valid, we just created it"),
);
// Remove event id if it exists
join_event_stub.remove("event_id");
// We keep the "event_id" in the pdu only in v1 or
// v2 rooms
match room_version_id {
| RoomVersionId::V1 | RoomVersionId::V2 => {},
| _ => {
join_event_stub.remove("event_id");
},
}
// In order to create a compatible ref hash (EventID) the `hashes` field needs
// to be present
services
.server_keys
.hash_and_sign_event(&mut join_event_stub, &room_version_rules)?;
.hash_and_sign_event(&mut join_event_stub, &room_version_id)?;
// Generate event id
let event_id = gen_event_id(&join_event_stub, &room_version_rules)?;
let event_id = gen_event_id(&join_event_stub, &room_version_id)?;
// Add event_id back
join_event_stub
@@ -453,14 +464,15 @@ async fn join_room_by_id_helper_remote(
let mut join_event = join_event_stub;
info!("Asking {remote_server} for send_join in room {room_id}");
let send_join_request = federation::membership::create_join_event::v2::Request::new(
room_id.to_owned(),
event_id.clone(),
services
let send_join_request = federation::membership::create_join_event::v2::Request {
room_id: room_id.to_owned(),
event_id: event_id.clone(),
omit_members: false,
pdu: services
.sending
.convert_to_outgoing_federation_event(join_event.clone())
.await,
);
};
let send_join_response = match services
.sending
@@ -484,7 +496,7 @@ async fn join_room_by_id_helper_remote(
);
let (signed_event_id, signed_value) =
gen_event_id_canonical_json(signed_raw, &room_version_rules).map_err(|e| {
gen_event_id_canonical_json(signed_raw, &room_version_id).map_err(|e| {
err!(Request(BadJson(warn!(
"Could not convert event to canonical JSON: {e}"
))))
@@ -559,7 +571,7 @@ async fn join_room_by_id_helper_remote(
.then(|pdu| {
services
.server_keys
.validate_and_add_event_id_no_fetch(pdu, &room_version_rules)
.validate_and_add_event_id_no_fetch(pdu, &room_version_id)
.inspect_err(|e| {
debug_warn!("Could not validate send_join response room_state event: {e:?}");
})
@@ -607,7 +619,7 @@ async fn join_room_by_id_helper_remote(
.then(|pdu| {
services
.server_keys
.validate_and_add_event_id_no_fetch(pdu, &room_version_rules)
.validate_and_add_event_id_no_fetch(pdu, &room_version_id)
})
.ready_filter_map(Result::ok)
.ready_for_each(|(event_id, value)| {
@@ -628,7 +640,7 @@ async fn join_room_by_id_helper_remote(
};
let auth_check = state_res::event_auth::auth_check(
&room_version.rules().unwrap(),
&state_res::RoomVersion::new(&room_version_id)?,
&parsed_join_pdu,
None, // TODO: third party invite
|k, s| state_fetch(k.clone(), s.into()),
@@ -735,7 +747,8 @@ async fn join_room_by_id_helper_local(
// This is a restricted room, check if we can complete the join requirements
// locally.
let needs_auth_user =
user_can_perform_restricted_join(services, sender_user, room_id).await;
user_can_perform_restricted_join(services, sender_user, room_id, &room_version)
.await;
if needs_auth_user.is_ok_and(is_true!()) {
// If there was an error or the value is false, we'll try joining over
// federation. Since it's Ok(true), we can authorise this locally.
@@ -748,19 +761,21 @@ async fn join_room_by_id_helper_local(
}
}
let mut content = RoomMemberEventContent::new(MembershipState::Join);
content.displayname = services.users.displayname(sender_user).await.ok();
content.avatar_url = services.users.avatar_url(sender_user).await.ok();
content.blurhash = services.users.blurhash(sender_user).await.ok();
content.reason.clone_from(&reason);
content.join_authorized_via_users_server = auth_user;
let content = RoomMemberEventContent {
displayname: services.users.displayname(sender_user).await.ok(),
avatar_url: services.users.avatar_url(sender_user).await.ok(),
blurhash: services.users.blurhash(sender_user).await.ok(),
reason: reason.clone(),
join_authorized_via_users_server: auth_user,
..RoomMemberEventContent::new(MembershipState::Join)
};
// Try normal join first
let Err(error) = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(sender_user.to_string(), &content),
PduBuilder::state(sender_user.to_string(), &content),
sender_user,
Some(room_id),
&state_lock,
@@ -809,16 +824,16 @@ async fn make_join_request(
"Asking {remote_server} for make_join (attempt {make_join_counter}/{})",
servers.len()
);
let mut request = federation::membership::prepare_join_event::v1::Request::new(
room_id.to_owned(),
sender_user.to_owned(),
);
request.ver = services.server.supported_room_versions().collect();
let make_join_response = services
.sending
.send_federation_request(remote_server, request)
.send_federation_request(
remote_server,
federation::membership::prepare_join_event::v1::Request {
room_id: room_id.to_owned(),
user_id: sender_user.to_owned(),
ver: services.server.supported_room_versions().collect(),
},
)
.await;
trace!("make_join response: {:?}", make_join_response);
@@ -851,17 +866,14 @@ async fn make_join_request(
rules, but is unable to authorise a join for us. Will continue trying."
);
},
| ErrorKind::IncompatibleRoomVersion(IncompatibleRoomVersionErrorData {
room_version,
..
}) => {
| ErrorKind::IncompatibleRoomVersion { room_version } => {
warn!(
"{remote_server} reports the room we are trying to join is \
v{room_version}, which we do not support."
);
return Err(e);
},
| ErrorKind::Forbidden => {
| ErrorKind::Forbidden { .. } => {
warn!("{remote_server} refuses to let us join: {e}.");
return Err(e);
},
@@ -880,3 +892,59 @@ async fn make_join_request(
info!("All {} servers were unable to assist in joining {room_id} :(", servers.len());
Err!(BadServerResponse("No server available to assist in joining."))
}
/// Moves deprioritized servers (if any) to the back of the list.
///
/// No-op if we aren't given any servers to deprioritize.
fn deprioritize(
servers: Vec<OwnedServerName>,
deprioritized: &[OwnedServerName],
) -> Vec<OwnedServerName> {
if deprioritized.is_empty() {
return servers;
}
let (mut depr, mut servers): (Vec<_>, Vec<_>) =
servers.into_iter().partition(|s| deprioritized.contains(s));
servers.append(&mut depr);
servers
}
#[cfg(test)]
mod tests {
use ruma::OwnedServerName;
use super::*;
#[test]
fn deprioritizing_servers_works() -> Result<(), Box<dyn std::error::Error>> {
let servers = vec![
"example.com".try_into()?,
"slow.invalid".try_into()?,
"example.org".try_into()?,
];
let depr = vec!["slow.invalid".try_into()?];
let expected: Vec<OwnedServerName> = vec![
"example.com".try_into()?,
"example.org".try_into()?,
"slow.invalid".try_into()?,
];
let servers = deprioritize(servers, &depr);
assert_eq!(servers, expected);
Ok(())
}
#[test]
fn empty_deprioritized_is_noop() -> Result<(), Box<dyn std::error::Error>> {
let servers = vec![
"example.com".try_into()?,
"slow.invalid".try_into()?,
"example.org".try_into()?,
];
let depr_servers = deprioritize(servers.clone(), &[]);
assert_eq!(depr_servers, servers);
Ok(())
}
}
+15 -11
View File
@@ -1,6 +1,9 @@
use axum::extract::State;
use conduwuit::{Err, Result, matrix::pdu::PartialPdu};
use ruma::{api::client::membership::kick_user, events::room::member::MembershipState};
use conduwuit::{Err, Result, matrix::pdu::PduBuilder};
use ruma::{
api::client::membership::kick_user,
events::room::member::{MembershipState, RoomMemberEventContent},
};
use crate::Ruma;
@@ -15,9 +18,9 @@ pub(crate) async fn kick_user_route(
if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;
let Ok(mut event) = services
let Ok(event) = services
.rooms
.state_accessor
.get_member(&body.room_id, &body.user_id)
@@ -38,17 +41,18 @@ pub(crate) async fn kick_user_route(
)));
}
event.membership = MembershipState::Leave;
event.reason.clone_from(&body.reason);
event.is_direct = None;
event.join_authorized_via_users_server = None;
event.third_party_invite = None;
services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(body.user_id.to_string(), &event),
PduBuilder::state(body.user_id.to_string(), &RoomMemberEventContent {
membership: MembershipState::Leave,
reason: body.reason.clone(),
is_direct: None,
join_authorized_via_users_server: None,
third_party_invite: None,
..event
}),
sender_user,
Some(&body.room_id),
&state_lock,
+81 -73
View File
@@ -6,7 +6,7 @@ use conduwuit::{
Err, Result, debug, debug_info, debug_warn, err, info,
matrix::{
event::gen_event_id,
pdu::{PartialPdu, PduEvent},
pdu::{PduBuilder, PduEvent},
},
result::FlatOk,
trace,
@@ -15,8 +15,8 @@ use conduwuit::{
};
use futures::{FutureExt, StreamExt};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedUserId, RoomId, UserId,
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, RoomId,
RoomVersionId, UserId,
api::{
client::knock::knock_room,
federation::{self},
@@ -73,6 +73,7 @@ pub(crate) async fn knock_room_route(
.rooms
.state_cache
.servers_invite_via(&room_id)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
.await,
);
@@ -112,7 +113,11 @@ pub(crate) async fn knock_room_route(
)
.await?;
let addl_via_servers = services.rooms.state_cache.servers_invite_via(&room_id);
let addl_via_servers = services
.rooms
.state_cache
.servers_invite_via(&room_id)
.map(ToOwned::to_owned);
let addl_state_servers = services
.rooms
@@ -125,7 +130,7 @@ pub(crate) async fn knock_room_route(
.iter()
.map(|event| event.get_field("sender"))
.filter_map(FlatOk::flat_ok)
.map(|user: OwnedUserId| user.server_name().to_owned())
.map(|user: &UserId| user.server_name().to_owned())
.stream()
.chain(addl_via_servers)
.collect()
@@ -183,7 +188,7 @@ async fn knock_room_by_id_helper(
.await
{
debug_warn!("{sender_user} is already knocked in {room_id}");
return Ok(knock_room::v3::Response::new(room_id.into()));
return Ok(knock_room::v3::Response { room_id: room_id.into() });
}
if let Ok(membership) = services
@@ -334,27 +339,34 @@ async fn knock_room_helper_local(
) -> Result {
debug_info!("We can knock locally");
let room_version = services.rooms.state.get_room_version(room_id).await?;
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
let room_version_id = services.rooms.state.get_room_version(room_id).await?;
if !room_version_rules.authorization.knocking {
if matches!(
room_version_id,
RoomVersionId::V1
| RoomVersionId::V2
| RoomVersionId::V3
| RoomVersionId::V4
| RoomVersionId::V5
| RoomVersionId::V6
) {
return Err!(Request(Forbidden("This room does not support knocking.")));
}
let mut content = RoomMemberEventContent::new(MembershipState::Knock);
content.displayname = services.users.displayname(sender_user).await.ok();
content.avatar_url = services.users.avatar_url(sender_user).await.ok();
content.blurhash = services.users.blurhash(sender_user).await.ok();
content.reason.clone_from(&reason.clone());
let content = RoomMemberEventContent {
displayname: services.users.displayname(sender_user).await.ok(),
avatar_url: services.users.avatar_url(sender_user).await.ok(),
blurhash: services.users.blurhash(sender_user).await.ok(),
reason: reason.clone(),
..RoomMemberEventContent::new(MembershipState::Knock)
};
// Try normal knock first
let Err(error) = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(sender_user.to_string(), &content),
PduBuilder::state(sender_user.to_string(), &content),
sender_user,
Some(room_id),
&state_lock,
@@ -369,18 +381,19 @@ async fn knock_room_helper_local(
return Err(error);
}
warn!("We couldn't do the knock locally, maybe federation can help to satisfy the knock");
let (make_knock_response, remote_server) =
make_knock_request(services, sender_user, room_id, servers).await?;
info!("make_knock finished");
let room_version = make_knock_response.room_version;
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
let room_version_id = make_knock_response.room_version;
if !services.server.supported_room_version(&room_version) {
return Err!(BadServerResponse("Remote room version {room_version} is not supported"));
if !services.server.supported_room_version(&room_version_id) {
return Err!(BadServerResponse(
"Remote room version {room_version_id} is not supported by conduwuit"
));
}
let mut knock_event_stub = serde_json::from_str::<CanonicalJsonObject>(
@@ -411,17 +424,24 @@ async fn knock_room_helper_local(
);
knock_event_stub.insert(
"content".to_owned(),
to_canonical_value(content).expect("event is valid, we just created it"),
to_canonical_value(RoomMemberEventContent {
displayname: services.users.displayname(sender_user).await.ok(),
avatar_url: services.users.avatar_url(sender_user).await.ok(),
blurhash: services.users.blurhash(sender_user).await.ok(),
reason,
..RoomMemberEventContent::new(MembershipState::Knock)
})
.expect("event is valid, we just created it"),
);
// In order to create a compatible ref hash (EventID) the `hashes` field needs
// to be present
services
.server_keys
.hash_and_sign_event(&mut knock_event_stub, &room_version_rules)?;
.hash_and_sign_event(&mut knock_event_stub, &room_version_id)?;
// Generate event id
let event_id = gen_event_id(&knock_event_stub, &room_version_rules)?;
let event_id = gen_event_id(&knock_event_stub, &room_version_id)?;
// Add event_id
knock_event_stub
@@ -431,14 +451,14 @@ async fn knock_room_helper_local(
let knock_event = knock_event_stub;
info!("Asking {remote_server} for send_knock in room {room_id}");
let send_knock_request = federation::membership::create_knock_event::v1::Request::new(
room_id.to_owned(),
event_id.clone(),
services
let send_knock_request = federation::knock::send_knock::v1::Request {
room_id: room_id.to_owned(),
event_id: event_id.clone(),
pdu: services
.sending
.convert_to_outgoing_federation_event(knock_event.clone())
.await,
);
};
services
.sending
@@ -500,14 +520,11 @@ async fn knock_room_helper_remote(
info!("make_knock finished");
let room_version = make_knock_response.room_version;
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
let room_version_id = make_knock_response.room_version;
if !services.server.supported_room_version(&room_version) {
if !services.server.supported_room_version(&room_version_id) {
return Err!(BadServerResponse(
"Remote room version {room_version} is not supported by conduwuit"
"Remote room version {room_version_id} is not supported by conduwuit"
));
}
@@ -528,26 +545,26 @@ async fn knock_room_helper_remote(
.expect("Timestamp is valid js_int value"),
),
);
let mut knock_content = RoomMemberEventContent::new(MembershipState::Knock);
knock_content.displayname = services.users.displayname(sender_user).await.ok();
knock_content.avatar_url = services.users.avatar_url(sender_user).await.ok();
knock_content.blurhash = services.users.blurhash(sender_user).await.ok();
knock_content.reason = reason;
knock_event_stub.insert(
"content".to_owned(),
to_canonical_value(knock_content).expect("event is valid, we just created it"),
to_canonical_value(RoomMemberEventContent {
displayname: services.users.displayname(sender_user).await.ok(),
avatar_url: services.users.avatar_url(sender_user).await.ok(),
blurhash: services.users.blurhash(sender_user).await.ok(),
reason,
..RoomMemberEventContent::new(MembershipState::Knock)
})
.expect("event is valid, we just created it"),
);
// In order to create a compatible ref hash (EventID) the `hashes` field needs
// to be present
services
.server_keys
.hash_and_sign_event(&mut knock_event_stub, &room_version_rules)?;
.hash_and_sign_event(&mut knock_event_stub, &room_version_id)?;
// Generate event id
let event_id = gen_event_id(&knock_event_stub, &room_version_rules)?;
let event_id = gen_event_id(&knock_event_stub, &room_version_id)?;
// Add event_id
knock_event_stub
@@ -557,18 +574,18 @@ async fn knock_room_helper_remote(
let knock_event = knock_event_stub;
info!("Asking {remote_server} for send_knock in room {room_id}");
let request = federation::membership::create_knock_event::v1::Request::new(
room_id.to_owned(),
event_id.clone(),
services
let send_knock_request = federation::knock::send_knock::v1::Request {
room_id: room_id.to_owned(),
event_id: event_id.clone(),
pdu: services
.sending
.convert_to_outgoing_federation_event(knock_event.clone())
.await,
);
};
let send_knock_response = services
.sending
.send_federation_request(&remote_server, request)
.send_federation_request(&remote_server, send_knock_request)
.await?;
info!("send_knock finished");
@@ -587,17 +604,7 @@ async fn knock_room_helper_remote(
let state = send_knock_response
.knock_room_state
.iter()
.map(|event| {
#[allow(deprecated)]
let raw_value = match event {
| federation::membership::RawStrippedState::Stripped(raw_state) =>
&raw_state.clone().into_json(),
| federation::membership::RawStrippedState::Pdu(raw_value) => raw_value,
| _ => panic!("unknown raw stripped state type"),
};
serde_json::from_str::<CanonicalJsonObject>(raw_value.get())
})
.map(|event| serde_json::from_str::<CanonicalJsonObject>(event.clone().into_json().get()))
.filter_map(Result::ok);
let mut state_map: HashMap<u64, OwnedEventId> = HashMap::new();
@@ -622,7 +629,7 @@ async fn knock_room_helper_remote(
continue;
};
let event_id = gen_event_id(&event, &room_version_rules)?;
let event_id = gen_event_id(&event, &room_version_id)?;
let shortstatekey = services
.rooms
.short
@@ -702,7 +709,7 @@ async fn make_knock_request(
sender_user: &UserId,
room_id: &RoomId,
servers: &[OwnedServerName],
) -> Result<(federation::membership::prepare_knock_event::v1::Response, OwnedServerName)> {
) -> Result<(federation::knock::create_knock_event_template::v1::Response, OwnedServerName)> {
let mut make_knock_response_and_server =
Err!(BadServerResponse("No server available to assist in knocking."));
@@ -715,15 +722,16 @@ async fn make_knock_request(
info!("Asking {remote_server} for make_knock ({make_knock_counter})");
let mut request = federation::membership::prepare_knock_event::v1::Request::new(
room_id.to_owned(),
sender_user.to_owned(),
);
request.ver = services.server.supported_room_versions().collect();
let make_knock_response = services
.sending
.send_federation_request(remote_server, request)
.send_federation_request(
remote_server,
federation::knock::create_knock_event_template::v1::Request {
room_id: room_id.to_owned(),
user_id: sender_user.to_owned(),
ver: services.server.supported_room_versions().collect(),
},
)
.await;
trace!("make_knock response: {make_knock_response:?}");
+34 -27
View File
@@ -3,13 +3,13 @@ use std::collections::HashSet;
use axum::extract::State;
use conduwuit::{
Err, Pdu, Result, debug_info, debug_warn, err,
matrix::{event::gen_event_id, pdu::PartialPdu},
matrix::{event::gen_event_id, pdu::PduBuilder},
utils::{self, FutureBoolExt, future::ReadyEqExt},
warn,
};
use futures::{FutureExt, StreamExt, pin_mut};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedServerName, RoomId, UserId,
CanonicalJsonObject, CanonicalJsonValue, OwnedServerName, RoomId, RoomVersionId, UserId,
api::{
client::membership::leave_room,
federation::{self},
@@ -42,7 +42,11 @@ pub(crate) async fn leave_room_route(
// Make a user leave all their joined rooms, rescinds knocks, forgets all rooms,
// and ignores errors
pub async fn leave_all_rooms(services: &Services, user_id: &UserId) {
let rooms_joined = services.rooms.state_cache.rooms_joined(user_id);
let rooms_joined = services
.rooms
.state_cache
.rooms_joined(user_id)
.map(ToOwned::to_owned);
let rooms_invited = services
.rooms
@@ -138,17 +142,18 @@ pub async fn leave_room(
.await;
match user_member_event_content {
| Ok(mut content) => {
content.membership = MembershipState::Leave;
content.reason = reason;
content.join_authorized_via_users_server = None;
content.is_direct = None;
| Ok(content) => {
services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(user_id.to_string(), &content),
PduBuilder::state(user_id.to_string(), &RoomMemberEventContent {
membership: MembershipState::Leave,
reason,
join_authorized_via_users_server: None,
is_direct: None,
..content
}),
user_id,
Some(room_id),
&state_lock,
@@ -221,6 +226,7 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
.rooms
.state_cache
.servers_invite_via(room_id)
.map(ToOwned::to_owned)
.collect::<HashSet<OwnedServerName>>()
.await,
);
@@ -254,7 +260,7 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
.filter_map(|event| event.get_field("sender").ok().flatten())
.filter_map(|sender: &str| UserId::parse(sender).ok())
.filter_map(|sender| {
if !services.globals.user_is_local(&sender) {
if !services.globals.user_is_local(sender) {
Some(sender.server_name().to_owned())
} else {
None
@@ -283,10 +289,10 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
.sending
.send_federation_request(
remote_server.as_ref(),
federation::membership::prepare_leave_event::v1::Request::new(
room_id.to_owned(),
user_id.to_owned(),
),
federation::membership::prepare_leave_event::v1::Request {
room_id: room_id.to_owned(),
user_id: user_id.to_owned(),
},
)
.await;
@@ -323,10 +329,6 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
)));
}
let room_version_rules = room_version_id
.rules()
.expect("room version should have defined rules");
let mut leave_event_stub = serde_json::from_str::<CanonicalJsonObject>(
make_leave_response.event.get(),
)
@@ -364,16 +366,21 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
}
// room v3 and above removed the "event_id" field from remote PDU format
leave_event_stub.remove("event_id");
match room_version_id {
| RoomVersionId::V1 | RoomVersionId::V2 => {},
| _ => {
leave_event_stub.remove("event_id");
},
}
// In order to create a compatible ref hash (EventID) the `hashes` field needs
// to be present
services
.server_keys
.hash_and_sign_event(&mut leave_event_stub, &room_version_rules)?;
.hash_and_sign_event(&mut leave_event_stub, &room_version_id)?;
// Generate event id
let event_id = gen_event_id(&leave_event_stub, &room_version_rules)?;
let event_id = gen_event_id(&leave_event_stub, &room_version_id)?;
// Add event_id back
leave_event_stub
@@ -386,14 +393,14 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
.sending
.send_federation_request(
&remote_server,
federation::membership::create_leave_event::v2::Request::new(
room_id.to_owned(),
event_id.clone(),
services
federation::membership::create_leave_event::v2::Request {
room_id: room_id.to_owned(),
event_id: event_id.clone(),
pdu: services
.sending
.convert_to_outgoing_federation_event(leave_event.clone())
.await,
),
},
)
.await?;
+72 -48
View File
@@ -9,7 +9,7 @@ use conduwuit::{
use futures::{FutureExt, StreamExt, future::join};
use ruma::{
api::client::membership::{
get_member_events::{self},
get_member_events::{self, v3::MembershipEventFilter},
joined_members::{self, v3::RoomMember},
},
events::{
@@ -43,20 +43,20 @@ pub(crate) async fn get_member_events_route(
return Err!(Request(Forbidden("You don't have permission to view this room.")));
}
let chunk = services
.rooms
.state_accessor
.room_state_full(&body.room_id)
.ready_filter_map(Result::ok)
.ready_filter(|((ty, _), _)| *ty == StateEventType::RoomMember)
.map(at!(1))
.ready_filter_map(|pdu| membership_filter(pdu, membership, not_membership))
.map(Event::into_format)
.collect()
.boxed()
.await;
Ok(get_member_events::v3::Response::new(chunk))
Ok(get_member_events::v3::Response {
chunk: services
.rooms
.state_accessor
.room_state_full(&body.room_id)
.ready_filter_map(Result::ok)
.ready_filter(|((ty, _), _)| *ty == StateEventType::RoomMember)
.map(at!(1))
.ready_filter_map(|pdu| membership_filter(pdu, membership, not_membership))
.map(Event::into_format)
.collect()
.boxed()
.await,
})
}
/// # `POST /_matrix/client/r0/rooms/{roomId}/joined_members`
@@ -78,46 +78,70 @@ pub(crate) async fn joined_members_route(
return Err!(Request(Forbidden("You don't have permission to view this room.")));
}
let joined = services
.rooms
.state_cache
.room_members(&body.room_id)
.broad_then(|user_id| async move {
let mut member = RoomMember::new();
let (display_name, avatar_url) = join(
services.users.displayname(&user_id).ok(),
services.users.avatar_url(&user_id).ok(),
)
.await;
member.display_name = display_name;
member.avatar_url = avatar_url;
Ok(joined_members::v3::Response {
joined: services
.rooms
.state_cache
.room_members(&body.room_id)
.map(ToOwned::to_owned)
.broad_then(|user_id| async move {
let (display_name, avatar_url) = join(
services.users.displayname(&user_id).ok(),
services.users.avatar_url(&user_id).ok(),
)
.await;
(user_id, member)
})
.collect()
.await;
Ok(joined_members::v3::Response::new(joined))
(user_id, RoomMember { display_name, avatar_url })
})
.collect()
.await,
})
}
fn membership_filter<Pdu: Event>(
pdu: Pdu,
membership_state_filter: Option<&MembershipState>,
not_membership_state_filter: Option<&MembershipState>,
for_membership: Option<&MembershipEventFilter>,
not_membership: Option<&MembershipEventFilter>,
) -> Option<impl Event> {
let membership_state_filter = match for_membership {
| Some(MembershipEventFilter::Ban) => MembershipState::Ban,
| Some(MembershipEventFilter::Invite) => MembershipState::Invite,
| Some(MembershipEventFilter::Knock) => MembershipState::Knock,
| Some(MembershipEventFilter::Leave) => MembershipState::Leave,
| Some(_) | None => MembershipState::Join,
};
let not_membership_state_filter = match not_membership {
| Some(MembershipEventFilter::Ban) => MembershipState::Ban,
| Some(MembershipEventFilter::Invite) => MembershipState::Invite,
| Some(MembershipEventFilter::Join) => MembershipState::Join,
| Some(MembershipEventFilter::Knock) => MembershipState::Knock,
| Some(_) | None => MembershipState::Leave,
};
let evt_membership = pdu.get_content::<RoomMemberEventContent>().ok()?.membership;
if let Some(membership_state_filter) = membership_state_filter
&& *membership_state_filter != evt_membership
{
return None;
if for_membership.is_some() && not_membership.is_some() {
if membership_state_filter != evt_membership
|| not_membership_state_filter == evt_membership
{
None
} else {
Some(pdu)
}
} else if for_membership.is_some() && not_membership.is_none() {
if membership_state_filter != evt_membership {
None
} else {
Some(pdu)
}
} else if not_membership.is_some() && for_membership.is_none() {
if not_membership_state_filter == evt_membership {
None
} else {
Some(pdu)
}
} else {
Some(pdu)
}
if let Some(not_membership_state_filter) = not_membership_state_filter
&& *not_membership_state_filter == evt_membership
{
return None;
}
Some(pdu)
}
+9 -8
View File
@@ -47,14 +47,15 @@ pub(crate) async fn joined_rooms_route(
State(services): State<crate::State>,
body: Ruma<joined_rooms::v3::Request>,
) -> Result<joined_rooms::v3::Response> {
let joined_rooms = services
.rooms
.state_cache
.rooms_joined(body.sender_user())
.collect()
.await;
Ok(joined_rooms::v3::Response::new(joined_rooms))
Ok(joined_rooms::v3::Response {
joined_rooms: services
.rooms
.state_cache
.rooms_joined(body.sender_user())
.map(ToOwned::to_owned)
.collect()
.await,
})
}
/// Checks if the room is banned in any way possible and the sender user is not
+11 -10
View File
@@ -1,5 +1,5 @@
use axum::extract::State;
use conduwuit::{Err, Result, matrix::pdu::PartialPdu};
use conduwuit::{Err, Result, matrix::pdu::PduBuilder};
use ruma::{
api::client::membership::unban_user,
events::room::member::{MembershipState, RoomMemberEventContent},
@@ -18,9 +18,9 @@ pub(crate) async fn unban_user_route(
if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;
let mut current_member_content = services
let current_member_content = services
.rooms
.state_accessor
.get_member(&body.room_id, &body.user_id)
@@ -34,17 +34,18 @@ pub(crate) async fn unban_user_route(
)));
}
current_member_content.membership = MembershipState::Leave;
current_member_content.reason.clone_from(&body.reason);
current_member_content.join_authorized_via_users_server = None;
current_member_content.third_party_invite = None;
current_member_content.is_direct = None;
services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(body.user_id.to_string(), &current_member_content),
PduBuilder::state(body.user_id.to_string(), &RoomMemberEventContent {
membership: MembershipState::Leave,
reason: body.reason.clone(),
join_authorized_via_users_server: None,
third_party_invite: None,
is_direct: None,
..current_member_content
}),
sender_user,
Some(&body.room_id),
&state_lock,
+10 -13
View File
@@ -26,17 +26,15 @@ use ruma::{
DeviceId, RoomId, UserId,
api::{
Direction,
client::{filter::RoomEventFilter, message::get_message_events},
error::{ErrorKind, SenderIgnoredErrorData},
client::{error::ErrorKind, filter::RoomEventFilter, message::get_message_events},
},
assign,
events::{
AnyStateEvent, StateEventType,
TimelineEventType::{self, *},
invite_permission_config::FilterLevel,
},
serde::Raw,
};
use ruminuwuity::invite_permission_config::FilterLevel;
use tracing::warn;
use crate::Ruma;
@@ -76,6 +74,7 @@ pub(crate) async fn get_message_events_route(
InsecureClientIp(client_ip): InsecureClientIp,
body: Ruma<get_message_events::v3::Request>,
) -> Result<get_message_events::v3::Response> {
debug_assert!(IGNORED_MESSAGE_TYPES.is_sorted(), "IGNORED_MESSAGE_TYPES is not sorted");
let sender_user = body.sender_user();
let sender_device = body.sender_device.as_deref();
let room_id = &body.room_id;
@@ -200,12 +199,12 @@ pub(crate) async fn get_message_events_route(
.map(Event::into_format)
.collect();
Ok(assign!(get_message_events::v3::Response::new(), {
Ok(get_message_events::v3::Response {
start: from.to_string(),
end: next_token.as_ref().map(PduCount::to_string),
chunk: chunk,
state: state,
}))
chunk,
state,
})
}
pub(crate) async fn lazy_loading_witness<'a, I>(
@@ -302,7 +301,7 @@ where
{
// exclude Synapse's dummy events from bloating up response bodies. clients
// don't need to see this.
if event.kind().to_string() == "org.matrix.dummy_event" {
if event.kind().to_cow_str() == "org.matrix.dummy_event" {
return Ok(true);
}
@@ -324,7 +323,7 @@ where
if server_ignored {
// the sender's server is ignored, so ignore this event
return Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::new()),
ErrorKind::SenderIgnored { sender: None },
"The sender's server is ignored by this server.",
));
}
@@ -333,9 +332,7 @@ where
// the recipient of this PDU has the sender ignored, and we're not
// configured to send ignored messages to clients
return Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender(
event.sender().to_owned(),
)),
ErrorKind::SenderIgnored { sender: Some(event.sender().to_owned()) },
"You have ignored this sender.",
));
}
+3 -2
View File
@@ -15,7 +15,6 @@ pub(super) mod media;
pub(super) mod media_legacy;
pub(super) mod membership;
pub(super) mod message;
pub(super) mod mutual_rooms;
pub(super) mod openid;
pub(super) mod presence;
pub(super) mod profile;
@@ -36,6 +35,7 @@ pub(super) mod thirdparty;
pub(super) mod threads;
pub(super) mod to_device;
pub(super) mod typing;
pub(super) mod unstable;
pub(super) mod unversioned;
pub(super) mod user_directory;
pub(super) mod voip;
@@ -60,10 +60,10 @@ pub(super) use media_legacy::*;
pub(super) use membership::*;
pub use membership::{join_room_by_id_helper, leave_all_rooms, leave_room, remote_leave_room};
pub(super) use message::*;
pub(super) use mutual_rooms::*;
pub(super) use openid::*;
pub(super) use presence::*;
pub(super) use profile::*;
pub use profile::{update_all_rooms, update_avatar_url, update_displayname};
pub use push::recreate_push_rules_and_return;
pub(super) use push::*;
pub(super) use read_marker::*;
@@ -82,6 +82,7 @@ pub(super) use thirdparty::*;
pub(super) use threads::*;
pub(super) use to_device::*;
pub(super) use typing::*;
pub(super) use unstable::*;
pub(super) use unversioned::*;
pub(super) use user_directory::*;
pub(super) use voip::*;
-36
View File
@@ -1,36 +0,0 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use futures::StreamExt;
use ruma::api::client::membership::mutual_rooms;
use crate::Ruma;
/// # `GET /_matrix/client/unstable/uk.half-shot.msc2666/user/mutual_rooms`
///
/// Gets all the rooms the sender shares with the specified user.
///
/// An implementation of [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666)
#[tracing::instrument(skip_all, name = "mutual_rooms", level = "info")]
pub(crate) async fn get_mutual_rooms_route(
State(services): State<crate::State>,
body: Ruma<mutual_rooms::unstable::Request>,
) -> Result<mutual_rooms::unstable::Response> {
let sender_user = body.sender_user();
if sender_user == body.user_id {
return Err!(Request(Unknown("You cannot request rooms in common with yourself.")));
}
if !services.users.exists(&body.user_id).await {
return Ok(mutual_rooms::unstable::Response::new(vec![]));
}
let mutual_rooms = services
.rooms
.state_cache
.get_shared_rooms(sender_user, &body.user_id)
.collect()
.await;
Ok(mutual_rooms::unstable::Response::new(mutual_rooms))
}
+5 -5
View File
@@ -29,10 +29,10 @@ pub(crate) async fn create_openid_token_route(
.users
.create_openid_token(&body.user_id, &access_token)?;
Ok(account::request_openid_token::v3::Response::new(
Ok(account::request_openid_token::v3::Response {
access_token,
TokenType::Bearer,
services.server.name.clone(),
Duration::from_secs(expires_in),
))
token_type: TokenType::Bearer,
matrix_server_name: services.server.name.clone(),
expires_in: Duration::from_secs(expires_in),
})
}
+6 -7
View File
@@ -2,10 +2,7 @@ use std::time::Duration;
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::client::presence::{get_presence, set_presence},
assign,
};
use ruma::api::client::presence::{get_presence, set_presence};
use crate::Ruma;
@@ -29,7 +26,7 @@ pub(crate) async fn set_presence_route(
.set_presence(body.sender_user(), &body.presence, None, None, body.status_msg.clone())
.await?;
Ok(set_presence::v3::Response::new())
Ok(set_presence::v3::Response {})
}
/// # `GET /_matrix/client/r0/presence/{userId}/status`
@@ -79,11 +76,13 @@ pub(crate) async fn get_presence_route(
.map(|millis| Duration::from_millis(millis.into())),
};
Ok(assign!(get_presence::v3::Response::new(presence.content.presence), {
Ok(get_presence::v3::Response {
// TODO: Should ruma just use the presenceeventcontent type here?
status_msg,
currently_active: presence.content.currently_active,
last_active_ago,
}))
presence: presence.content.presence,
})
},
| _ => Err!(Request(NotFound("Presence state for this user was not found"))),
}
+379 -284
View File
@@ -1,26 +1,229 @@
use std::collections::BTreeMap;
use axum::extract::State;
use conduwuit::{Err, Result, matrix::pdu::PartialPdu};
use conduwuit::{
Err, Result,
matrix::pdu::PduBuilder,
utils::{IterStream, future::TryExtExt, stream::TryIgnore},
warn,
};
use conduwuit_service::Services;
use futures::StreamExt;
use futures::{
FutureExt, StreamExt, TryStreamExt,
future::{join, join3, join4},
};
use ruma::{
UserId,
OwnedMxcUri, OwnedRoomId, UserId,
api::{
client::profile::{
delete_profile_field, get_profile, get_profile_field, set_profile_field,
get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name,
},
federation,
},
assign,
events::room::member::{MembershipState, RoomMemberEventContent},
presence::PresenceState,
profile::{ProfileFieldName, ProfileFieldValue},
};
use serde_json::{Value, to_value};
use crate::Ruma;
/// # `PUT /_matrix/client/r0/profile/{userId}/displayname`
///
/// Updates the displayname.
///
/// - Also makes sure other users receive the update using presence EDUs
pub(crate) async fn set_displayname_route(
State(services): State<crate::State>,
body: Ruma<set_display_name::v3::Request>,
) -> Result<set_display_name::v3::Response> {
let sender_user = body.sender_user();
if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
if *sender_user != body.user_id && body.appservice_info.is_none() {
return Err!(Request(Forbidden("You cannot update the profile of another user")));
}
let all_joined_rooms: Vec<OwnedRoomId> = services
.rooms
.state_cache
.rooms_joined(&body.user_id)
.map(ToOwned::to_owned)
.collect()
.await;
update_displayname(&services, &body.user_id, body.displayname.clone(), &all_joined_rooms)
.boxed()
.await;
if services.config.allow_local_presence {
// Presence update
services
.presence
.ping_presence(&body.user_id, &PresenceState::Online)
.await?;
}
Ok(set_display_name::v3::Response {})
}
/// # `GET /_matrix/client/v3/profile/{userId}/displayname`
///
/// Returns the displayname of the user.
///
/// - If user is on another server and we do not have a local copy already fetch
/// displayname over federation
pub(crate) async fn get_displayname_route(
State(services): State<crate::State>,
body: Ruma<get_display_name::v3::Request>,
) -> Result<get_display_name::v3::Response> {
if !services.globals.user_is_local(&body.user_id) {
// Create and update our local copy of the user
if let Ok(response) = services
.sending
.send_federation_request(
body.user_id.server_name(),
federation::query::get_profile_information::v1::Request {
user_id: body.user_id.clone(),
field: None, // we want the full user's profile to update locally too
},
)
.await
{
if !services.users.exists(&body.user_id).await {
services.users.create(&body.user_id, None, None).await?;
}
services
.users
.set_displayname(&body.user_id, response.displayname.clone());
services
.users
.set_avatar_url(&body.user_id, response.avatar_url.clone());
services
.users
.set_blurhash(&body.user_id, response.blurhash.clone());
return Ok(get_display_name::v3::Response { displayname: response.displayname });
}
}
if !services.users.exists(&body.user_id).await {
// Return 404 if this user doesn't exist and we couldn't fetch it over
// federation
return Err!(Request(NotFound("Profile was not found.")));
}
Ok(get_display_name::v3::Response {
displayname: services.users.displayname(&body.user_id).await.ok(),
})
}
/// # `PUT /_matrix/client/v3/profile/{userId}/avatar_url`
///
/// Updates the `avatar_url` and `blurhash`.
///
/// - Also makes sure other users receive the update using presence EDUs
pub(crate) async fn set_avatar_url_route(
State(services): State<crate::State>,
body: Ruma<set_avatar_url::v3::Request>,
) -> Result<set_avatar_url::v3::Response> {
let sender_user = body.sender_user();
if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
if *sender_user != body.user_id && body.appservice_info.is_none() {
return Err!(Request(Forbidden("You cannot update the profile of another user")));
}
let all_joined_rooms: Vec<OwnedRoomId> = services
.rooms
.state_cache
.rooms_joined(&body.user_id)
.map(ToOwned::to_owned)
.collect()
.await;
update_avatar_url(
&services,
&body.user_id,
body.avatar_url.clone(),
body.blurhash.clone(),
&all_joined_rooms,
)
.boxed()
.await;
if services.config.allow_local_presence {
// Presence update
services
.presence
.ping_presence(&body.user_id, &PresenceState::Online)
.await
.ok();
}
Ok(set_avatar_url::v3::Response {})
}
/// # `GET /_matrix/client/v3/profile/{userId}/avatar_url`
///
/// Returns the `avatar_url` and `blurhash` of the user.
///
/// - If user is on another server and we do not have a local copy already fetch
/// `avatar_url` and blurhash over federation
pub(crate) async fn get_avatar_url_route(
State(services): State<crate::State>,
body: Ruma<get_avatar_url::v3::Request>,
) -> Result<get_avatar_url::v3::Response> {
if !services.globals.user_is_local(&body.user_id) {
// Create and update our local copy of the user
if let Ok(response) = services
.sending
.send_federation_request(
body.user_id.server_name(),
federation::query::get_profile_information::v1::Request {
user_id: body.user_id.clone(),
field: None, // we want the full user's profile to update locally as well
},
)
.await
{
if !services.users.exists(&body.user_id).await {
services.users.create(&body.user_id, None, None).await?;
}
services
.users
.set_displayname(&body.user_id, response.displayname.clone());
services
.users
.set_avatar_url(&body.user_id, response.avatar_url.clone());
services
.users
.set_blurhash(&body.user_id, response.blurhash.clone());
return Ok(get_avatar_url::v3::Response {
avatar_url: response.avatar_url,
blurhash: response.blurhash,
});
}
}
if !services.users.exists(&body.user_id).await {
// Return 404 if this user doesn't exist and we couldn't fetch it over
// federation
return Err!(Request(NotFound("Profile was not found.")));
}
let (avatar_url, blurhash) = join(
services.users.avatar_url(&body.user_id).ok(),
services.users.blurhash(&body.user_id).ok(),
)
.await;
Ok(get_avatar_url::v3::Response { avatar_url, blurhash })
}
/// # `GET /_matrix/client/v3/profile/{userId}`
///
/// Returns the displayname, avatar_url, blurhash, and custom profile fields of
@@ -32,296 +235,188 @@ pub(crate) async fn get_profile_route(
State(services): State<crate::State>,
body: Ruma<get_profile::v3::Request>,
) -> Result<get_profile::v3::Response> {
let Some(profile) = fetch_full_profile(&services, &body.user_id).await else {
return Err!(Request(NotFound("This user's profile could not be fetched.")));
};
Ok(get_profile::v3::Response::from_iter(profile))
}
pub(crate) async fn get_profile_field_route(
State(services): State<crate::State>,
body: Ruma<get_profile_field::v3::Request>,
) -> Result<get_profile_field::v3::Response> {
let value = fetch_profile_field(&services, &body.user_id, body.field.clone()).await?;
Ok(assign!(get_profile_field::v3::Response::default(), { value }))
}
pub(crate) async fn set_profile_field_route(
State(services): State<crate::State>,
body: Ruma<set_profile_field::v3::Request>,
) -> Result<set_profile_field::v3::Response> {
if body.user_id != body.sender_user()
&& !(body.appservice_info.is_some()
|| services.admin.user_is_admin(body.sender_user()).await)
{
return Err!(Request(Forbidden("You may not change other users' profile data.")));
}
if !services.globals.user_is_local(&body.user_id) {
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
}
set_profile_field(&services, &body.user_id, ProfileFieldChange::Set(body.value.clone()))
.await;
Ok(set_profile_field::v3::Response::new())
}
pub(crate) async fn delete_profile_field_route(
State(services): State<crate::State>,
body: Ruma<delete_profile_field::v3::Request>,
) -> Result<delete_profile_field::v3::Response> {
if body.user_id != body.sender_user()
&& !(body.appservice_info.is_some()
|| services.admin.user_is_admin(body.sender_user()).await)
{
return Err!(Request(Forbidden("You may not change other users' profile data.")));
}
if !services.globals.user_is_local(&body.user_id) {
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
}
set_profile_field(&services, &body.user_id, ProfileFieldChange::Delete(body.field.clone()))
.await;
Ok(delete_profile_field::v3::Response::new())
}
async fn fetch_full_profile(
services: &Services,
user_id: &UserId,
) -> Option<BTreeMap<String, Value>> {
// If the user exists locally, fetch their local profile
if services.users.exists(user_id).await {
return Some(get_local_profile(services, user_id).await);
}
// Otherwise ask their homeserver
let Ok(response) = services
.sending
.send_federation_request(
user_id.server_name(),
federation::query::get_profile_information::v1::Request::new(user_id.to_owned()),
)
.await
else {
return None;
};
// Update our local copies of their profile fields
services.users.clear_profile(user_id).await;
for (field, value) in response.iter() {
let Ok(value) = ProfileFieldValue::new(field, value.to_owned()) else {
// Skip malformed fields
continue;
};
set_profile_field(services, user_id, ProfileFieldChange::Set(value)).await;
}
Some(BTreeMap::from_iter(response))
}
async fn fetch_profile_field(
services: &Services,
user_id: &UserId,
field: ProfileFieldName,
) -> Result<Option<ProfileFieldValue>> {
// If the user exists locally, fetch their local profile field
if services.globals.user_is_local(user_id) {
return Ok(get_local_profile_field(services, user_id, field).await);
}
// Otherwise ask their homeserver
let Ok(response) = services
.sending
.send_federation_request(
user_id.server_name(),
assign!(federation::query::get_profile_information::v1::Request::new(user_id.to_owned()), {
field: Some(field.clone())
}),
)
.await
else {
return Err!(Request(NotFound(
"User's homeserver could not provide this profile field."
)));
};
if let Some(value) = response.get(field.as_str()).map(ToOwned::to_owned) {
if let Ok(value) = ProfileFieldValue::new(field.as_str(), value) {
set_profile_field(services, user_id, ProfileFieldChange::Set(value.clone())).await;
Ok(Some(value))
} else {
Err!(Request(Unknown(
"User's homeserver returned malformed data for this profile field."
)))
}
} else {
set_profile_field(services, user_id, ProfileFieldChange::Delete(field)).await;
Ok(None)
}
}
pub(crate) async fn get_local_profile(
services: &Services,
user_id: &UserId,
) -> BTreeMap<String, Value> {
let mut profile = BTreeMap::new();
// Get displayname and avatar_url independently because `all_profile_keys`
// doesn't include them
for field in [ProfileFieldName::AvatarUrl, ProfileFieldName::DisplayName] {
let key = field.as_str().to_owned();
if let Some(value) = get_local_profile_field(services, user_id, field).await {
profile.insert(key, value.value().into_owned());
}
}
// Insert all other profile fields
let mut all_fields = services.users.all_profile_keys(user_id);
while let Some((key, value)) = all_fields.next().await {
profile.insert(key, value);
}
profile
}
pub(crate) async fn get_local_profile_field(
services: &Services,
user_id: &UserId,
field: ProfileFieldName,
) -> Option<ProfileFieldValue> {
let value = match field.clone() {
| ProfileFieldName::AvatarUrl => services
.users
.avatar_url(user_id)
// Create and update our local copy of the user
if let Ok(response) = services
.sending
.send_federation_request(
body.user_id.server_name(),
federation::query::get_profile_information::v1::Request {
user_id: body.user_id.clone(),
field: None,
},
)
.await
.ok()
.map(to_value)
.transpose()
.expect("converting avatar url to value should succeed"),
| ProfileFieldName::DisplayName => services
.users
.displayname(user_id)
.await
.ok()
.map(to_value)
.transpose()
.expect("converting displayname to value should succeed"),
| other => services
.users
.profile_key(user_id, other.as_str())
.await
.ok(),
}?;
{
if !services.users.exists(&body.user_id).await {
services.users.create(&body.user_id, None, None).await?;
}
Some(
ProfileFieldValue::new(field.as_str(), value)
.expect("local profile field should be valid"),
)
}
enum ProfileFieldChange {
Set(ProfileFieldValue),
Delete(ProfileFieldName),
}
impl ProfileFieldChange {
fn field_name(&self) -> ProfileFieldName {
match self {
| &Self::Delete(ref name) => name.clone(),
| &Self::Set(ref value) => value.field_name(),
}
}
fn value(&self) -> Option<Value> {
if let Self::Set(value) = self {
Some(value.value().into_owned())
} else {
None
}
}
}
async fn set_profile_field(services: &Services, user_id: &UserId, change: ProfileFieldChange) {
let field_name = change.field_name();
match change {
| ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)) => {
services
.users
.set_displayname(user_id, Some(displayname).filter(|dn| !dn.is_empty()));
},
| ProfileFieldChange::Set(ProfileFieldValue::AvatarUrl(avatar_url)) => {
.set_displayname(&body.user_id, response.displayname.clone());
services
.users
.set_avatar_url(user_id, Some(avatar_url).filter(|av| av.is_valid()));
},
| ProfileFieldChange::Delete(ProfileFieldName::DisplayName) => {
services.users.set_displayname(user_id, None);
},
| ProfileFieldChange::Delete(ProfileFieldName::AvatarUrl) => {
services.users.set_avatar_url(user_id, None);
},
| other =>
if other.field_name().as_str() == "blurhash" {
if let Some(Value::String(blurhash)) = other.value() {
services.users.set_blurhash(user_id, Some(blurhash));
} else {
services.users.set_blurhash(user_id, None);
}
} else {
.set_avatar_url(&body.user_id, response.avatar_url.clone());
services
.users
.set_blurhash(&body.user_id, response.blurhash.clone());
for (profile_key, profile_key_value) in &response.custom_profile_fields {
services.users.set_profile_key(
user_id,
other.field_name().as_str(),
other.value(),
&body.user_id,
profile_key,
Some(profile_key_value.clone()),
);
},
}
return Ok(get_profile::v3::Response {
displayname: response.displayname,
avatar_url: response.avatar_url,
blurhash: response.blurhash,
custom_profile_fields: response.custom_profile_fields,
});
}
}
// If the user is local and changed their displayname or avatar_url, update it
// in all their joined rooms
if matches!(field_name, ProfileFieldName::AvatarUrl | ProfileFieldName::DisplayName)
&& services.users.is_active_local(user_id).await
{
let displayname = services.users.displayname(user_id).await.ok();
let avatar_url = services.users.avatar_url(user_id).await.ok();
let membership_content = assign!(
RoomMemberEventContent::new(MembershipState::Join), { displayname, avatar_url }
);
if !services.users.exists(&body.user_id).await {
// Return 404 if this user doesn't exist and we couldn't fetch it over
// federation
return Err!(Request(NotFound("Profile was not found.")));
}
let mut all_joined_rooms = services.rooms.state_cache.rooms_joined(user_id);
let (avatar_url, blurhash, displayname, custom_profile_fields) = join4(
services.users.avatar_url(&body.user_id).ok(),
services.users.blurhash(&body.user_id).ok(),
services.users.displayname(&body.user_id).ok(),
services.users.all_profile_keys(&body.user_id).collect(),
)
.await;
while let Some(room_id) = all_joined_rooms.next().await {
let state_lock = services.rooms.state.mutex.lock(room_id.as_str()).await;
Ok(get_profile::v3::Response {
avatar_url,
blurhash,
displayname,
custom_profile_fields,
})
}
let _ = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu::state(user_id.to_string(), &membership_content),
user_id,
Some(&room_id),
&state_lock,
)
.await;
}
pub async fn update_displayname(
services: &Services,
user_id: &UserId,
displayname: Option<String>,
all_joined_rooms: &[OwnedRoomId],
) {
let (current_avatar_url, current_blurhash, current_displayname) = join3(
services.users.avatar_url(user_id).ok(),
services.users.blurhash(user_id).ok(),
services.users.displayname(user_id).ok(),
)
.await;
if services.config.allow_local_presence {
// Send a presence EDU to indicate the profile changed
let _ = services
.presence
.ping_presence(user_id, &PresenceState::Online)
.await;
if displayname == current_displayname {
return;
}
services.users.set_displayname(user_id, displayname.clone());
// Send a new join membership event into all joined rooms
let avatar_url = &current_avatar_url;
let blurhash = &current_blurhash;
let displayname = &displayname;
let all_joined_rooms: Vec<_> = all_joined_rooms
.iter()
.try_stream()
.and_then(|room_id: &OwnedRoomId| async move {
let pdu = PduBuilder::state(user_id.to_string(), &RoomMemberEventContent {
displayname: displayname.clone(),
membership: MembershipState::Join,
avatar_url: avatar_url.clone(),
blurhash: blurhash.clone(),
join_authorized_via_users_server: None,
reason: None,
is_direct: None,
third_party_invite: None,
redact_events: None,
});
Ok((pdu, room_id))
})
.ignore_err()
.collect()
.await;
update_all_rooms(services, all_joined_rooms, user_id)
.boxed()
.await;
}
pub async fn update_avatar_url(
services: &Services,
user_id: &UserId,
avatar_url: Option<OwnedMxcUri>,
blurhash: Option<String>,
all_joined_rooms: &[OwnedRoomId],
) {
let (current_avatar_url, current_blurhash, current_displayname) = join3(
services.users.avatar_url(user_id).ok(),
services.users.blurhash(user_id).ok(),
services.users.displayname(user_id).ok(),
)
.await;
if current_avatar_url == avatar_url && current_blurhash == blurhash {
return;
}
services.users.set_avatar_url(user_id, avatar_url.clone());
services.users.set_blurhash(user_id, blurhash.clone());
// Send a new join membership event into all joined rooms
let avatar_url = &avatar_url;
let blurhash = &blurhash;
let displayname = &current_displayname;
let all_joined_rooms: Vec<_> = all_joined_rooms
.iter()
.try_stream()
.and_then(|room_id: &OwnedRoomId| async move {
let pdu = PduBuilder::state(user_id.to_string(), &RoomMemberEventContent {
avatar_url: avatar_url.clone(),
blurhash: blurhash.clone(),
membership: MembershipState::Join,
displayname: displayname.clone(),
join_authorized_via_users_server: None,
reason: None,
is_direct: None,
third_party_invite: None,
redact_events: None,
});
Ok((pdu, room_id))
})
.ignore_err()
.collect()
.await;
update_all_rooms(services, all_joined_rooms, user_id)
.boxed()
.await;
}
pub async fn update_all_rooms(
services: &Services,
all_joined_rooms: Vec<(PduBuilder, &OwnedRoomId)>,
user_id: &UserId,
) {
for (pdu_builder, room_id) in all_joined_rooms {
let state_lock = services.rooms.state.mutex.lock(room_id).await;
if let Err(e) = services
.rooms
.timeline
.build_and_append_pdu(pdu_builder, user_id, Some(room_id), &state_lock)
.await
{
warn!(%user_id, %room_id, "Failed to update/send new profile join membership update in room: {e}");
}
}
}
+42 -36
View File
@@ -3,13 +3,13 @@ use conduwuit::{Err, Error, Result, err};
use conduwuit_service::Services;
use ruma::{
CanonicalJsonObject, CanonicalJsonValue,
api::{
client::push::{
api::client::{
error::ErrorKind,
push::{
delete_pushrule, get_pushers, get_pushrule, get_pushrule_actions,
get_pushrule_enabled, get_pushrules_all, get_pushrules_global_scope, set_pusher,
set_pushrule, set_pushrule_actions, set_pushrule_enabled,
},
error::ErrorKind,
},
events::{
GlobalAccountDataEventType,
@@ -80,7 +80,9 @@ pub(crate) async fn get_pushrules_all_route(
global_ruleset.update_with_server_default(Ruleset::server_default(sender_user));
let ty = GlobalAccountDataEventType::PushRules;
let event = PushRulesEvent::new(PushRulesEventContent::new(global_ruleset.clone()));
let event = PushRulesEvent {
content: PushRulesEventContent { global: global_ruleset.clone() },
};
services
.account_data
@@ -89,7 +91,7 @@ pub(crate) async fn get_pushrules_all_route(
}
};
Ok(get_pushrules_all::v3::Response::new(global_ruleset))
Ok(get_pushrules_all::v3::Response { global: global_ruleset })
}
/// # `GET /_matrix/client/r0/pushrules/global/`
@@ -114,20 +116,21 @@ pub(crate) async fn get_pushrules_global_route(
// user somehow has non-existent push rule event. recreate it and return server
// default silently
let global_ruleset = Ruleset::server_default(sender_user);
let event = PushRulesEvent::new(PushRulesEventContent::new(global_ruleset.clone()));
let ty = GlobalAccountDataEventType::PushRules;
let event = PushRulesEvent {
content: PushRulesEventContent {
global: Ruleset::server_default(sender_user),
},
};
services
.account_data
.update(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(event)?,
)
.update(None, sender_user, ty.to_string().into(), &serde_json::to_value(event)?)
.await?;
return Ok(get_pushrules_global_scope::v3::Response::new(global_ruleset));
return Ok(get_pushrules_global_scope::v3::Response {
global: Ruleset::server_default(sender_user),
});
};
let account_data_content =
@@ -170,16 +173,16 @@ pub(crate) async fn get_pushrules_global_route(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(PushRulesEvent::new(PushRulesEventContent::new(
global_ruleset.clone(),
)))
&serde_json::to_value(PushRulesEvent {
content: PushRulesEventContent { global: global_ruleset.clone() },
})
.expect("to json always works"),
)
.await?;
}
};
Ok(get_pushrules_global_scope::v3::Response::new(global_ruleset))
Ok(get_pushrules_global_scope::v3::Response { global: global_ruleset })
}
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
@@ -213,7 +216,7 @@ pub(crate) async fn get_pushrule_route(
.map(Into::into);
if let Some(rule) = rule {
Ok(get_pushrule::v3::Response::new(rule))
Ok(get_pushrule::v3::Response { rule })
} else {
Err!(Request(NotFound("Push rule not found.")))
}
@@ -272,7 +275,7 @@ pub(crate) async fn set_pushrule_route(
.update(None, sender_user, ty.to_string().into(), &serde_json::to_value(account_data)?)
.await?;
Ok(set_pushrule::v3::Response::new())
Ok(set_pushrule::v3::Response {})
}
/// # `GET /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/actions`
@@ -306,7 +309,7 @@ pub(crate) async fn get_pushrule_actions_route(
.map(|rule| rule.actions().to_owned())
.ok_or_else(|| err!(Request(NotFound("Push rule not found."))))?;
Ok(get_pushrule_actions::v3::Response::new(actions))
Ok(get_pushrule_actions::v3::Response { actions })
}
/// # `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/actions`
@@ -339,7 +342,7 @@ pub(crate) async fn set_pushrule_actions_route(
.update(None, sender_user, ty.to_string().into(), &serde_json::to_value(account_data)?)
.await?;
Ok(set_pushrule_actions::v3::Response::new())
Ok(set_pushrule_actions::v3::Response {})
}
/// # `GET /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/enabled`
@@ -357,7 +360,7 @@ pub(crate) async fn get_pushrule_enabled_route(
|| body.rule_id.as_str() == PredefinedOverrideRuleId::ContainsDisplayName.as_str()
|| body.rule_id.as_str() == PredefinedOverrideRuleId::RoomNotif.as_str()
{
return Ok(get_pushrule_enabled::v3::Response::new(false));
return Ok(get_pushrule_enabled::v3::Response { enabled: false });
}
let event: PushRulesEvent = services
@@ -373,7 +376,7 @@ pub(crate) async fn get_pushrule_enabled_route(
.map(ruma::push::AnyPushRuleRef::enabled)
.ok_or_else(|| err!(Request(NotFound("Push rule not found."))))?;
Ok(get_pushrule_enabled::v3::Response::new(enabled))
Ok(get_pushrule_enabled::v3::Response { enabled })
}
/// # `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/enabled`
@@ -406,7 +409,7 @@ pub(crate) async fn set_pushrule_enabled_route(
.update(None, sender_user, ty.to_string().into(), &serde_json::to_value(account_data)?)
.await?;
Ok(set_pushrule_enabled::v3::Response::new())
Ok(set_pushrule_enabled::v3::Response {})
}
/// # `DELETE /_matrix/client/r0/pushrules/global/{kind}/{ruleId}`
@@ -448,7 +451,7 @@ pub(crate) async fn delete_pushrule_route(
.update(None, sender_user, ty.to_string().into(), &serde_json::to_value(account_data)?)
.await?;
Ok(delete_pushrule::v3::Response::new())
Ok(delete_pushrule::v3::Response {})
}
/// # `GET /_matrix/client/r0/pushers`
@@ -460,7 +463,9 @@ pub(crate) async fn get_pushers_route(
) -> Result<get_pushers::v3::Response> {
let sender_user = body.sender_user();
Ok(get_pushers::v3::Response::new(services.pusher.get_pushers(sender_user).await))
Ok(get_pushers::v3::Response {
pushers: services.pusher.get_pushers(sender_user).await,
})
}
/// # `POST /_matrix/client/r0/pushers/set`
@@ -488,18 +493,19 @@ pub async fn recreate_push_rules_and_return(
services: &Services,
sender_user: &ruma::UserId,
) -> Result<get_pushrules_all::v3::Response> {
let global_ruleset = Ruleset::server_default(sender_user);
let event = PushRulesEvent::new(PushRulesEventContent::new(global_ruleset.clone()));
let ty = GlobalAccountDataEventType::PushRules;
let event = PushRulesEvent {
content: PushRulesEventContent {
global: Ruleset::server_default(sender_user),
},
};
services
.account_data
.update(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(event)?,
)
.update(None, sender_user, ty.to_string().into(), &serde_json::to_value(event)?)
.await?;
Ok(get_pushrules_all::v3::Response::new(global_ruleset))
Ok(get_pushrules_all::v3::Response {
global: Ruleset::server_default(sender_user),
})
}
+31 -21
View File
@@ -8,8 +8,7 @@ use ruma::{
api::client::{read_marker::set_read_marker, receipt::create_receipt},
events::{
RoomAccountDataEventType,
fully_read::{FullyReadEvent, FullyReadEventContent},
receipt::{Receipt, ReceiptEvent, ReceiptEventContent, ReceiptType},
receipt::{ReceiptThread, ReceiptType},
},
};
@@ -29,7 +28,9 @@ pub(crate) async fn set_read_marker_route(
let sender_user = body.sender_user();
if let Some(event) = &body.fully_read {
let fully_read_event = FullyReadEvent::new(FullyReadEventContent::new(event.to_owned()));
let fully_read_event = ruma::events::fully_read::FullyReadEvent {
content: ruma::events::fully_read::FullyReadEventContent { event_id: event.clone() },
};
services
.account_data
@@ -61,16 +62,19 @@ pub(crate) async fn set_read_marker_route(
if services.config.allow_local_read_receipts
&& !services.users.is_suspended(sender_user).await?
{
let receipt_content = [(
let receipt_content = BTreeMap::from_iter([(
event.to_owned(),
BTreeMap::from_iter([(
ReceiptType::Read,
BTreeMap::from_iter([(
sender_user.to_owned(),
Receipt::new(MilliSecondsSinceUnixEpoch::now()),
ruma::events::receipt::Receipt {
ts: Some(MilliSecondsSinceUnixEpoch::now()),
thread: ReceiptThread::Unthreaded,
},
)]),
)]),
)];
)]);
services
.rooms
@@ -78,10 +82,10 @@ pub(crate) async fn set_read_marker_route(
.readreceipt_update(
sender_user,
&body.room_id,
&ReceiptEvent::new(
body.room_id.clone(),
ReceiptEventContent::from_iter(receipt_content),
),
&ruma::events::receipt::ReceiptEvent {
content: ruma::events::receipt::ReceiptEventContent(receipt_content),
room_id: body.room_id.clone(),
},
)
.await;
}
@@ -107,7 +111,7 @@ pub(crate) async fn set_read_marker_route(
.private_read_set(&body.room_id, sender_user, count);
}
Ok(set_read_marker::v3::Response::new())
Ok(set_read_marker::v3::Response {})
}
/// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}`
@@ -144,8 +148,11 @@ pub(crate) async fn create_receipt_route(
match body.receipt_type {
| create_receipt::v3::ReceiptType::FullyRead => {
let fully_read_event =
FullyReadEvent::new(FullyReadEventContent::new(body.event_id.clone()));
let fully_read_event = ruma::events::fully_read::FullyReadEvent {
content: ruma::events::fully_read::FullyReadEventContent {
event_id: body.event_id.clone(),
},
};
services
.account_data
.update(
@@ -157,16 +164,19 @@ pub(crate) async fn create_receipt_route(
.await?;
},
| create_receipt::v3::ReceiptType::Read => {
let receipt_content = [(
let receipt_content = BTreeMap::from_iter([(
body.event_id.clone(),
BTreeMap::from_iter([(
ReceiptType::Read,
BTreeMap::from_iter([(
sender_user.to_owned(),
Receipt::new(MilliSecondsSinceUnixEpoch::now()),
ruma::events::receipt::Receipt {
ts: Some(MilliSecondsSinceUnixEpoch::now()),
thread: ReceiptThread::Unthreaded,
},
)]),
)]),
)];
)]);
services
.rooms
@@ -174,10 +184,10 @@ pub(crate) async fn create_receipt_route(
.readreceipt_update(
sender_user,
&body.room_id,
&ReceiptEvent::new(
body.room_id.clone(),
ReceiptEventContent::from_iter(receipt_content),
),
&ruma::events::receipt::ReceiptEvent {
content: ruma::events::receipt::ReceiptEventContent(receipt_content),
room_id: body.room_id.clone(),
},
)
.await;
},
@@ -208,5 +218,5 @@ pub(crate) async fn create_receipt_route(
},
}
Ok(create_receipt::v3::Response::new())
Ok(create_receipt::v3::Response {})
}
+9 -10
View File
@@ -1,8 +1,8 @@
use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduwuit::{Err, Result, matrix::pdu::PartialPdu};
use conduwuit::{Err, Result, matrix::pdu::PduBuilder};
use ruma::{
api::client::redact::redact_event, assign, events::room::redaction::RoomRedactionEventContent,
api::client::redact::redact_event, events::room::redaction::RoomRedactionEventContent,
};
use crate::Ruma;
@@ -28,19 +28,18 @@ pub(crate) async fn redact_event_route(
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;
let event_id = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
PduBuilder {
redacts: Some(body.event_id.clone()),
..PartialPdu::timeline(
&assign!(RoomRedactionEventContent::new_v11(body.event_id.clone()), {
reason: body.reason.clone()
}),
)
..PduBuilder::timeline(&RoomRedactionEventContent {
redacts: Some(body.event_id.clone()),
reason: body.reason.clone(),
})
},
sender_user,
Some(&body.room_id),
@@ -50,5 +49,5 @@ pub(crate) async fn redact_event_route(
drop(state_lock);
Ok(redact_event::v3::Response::new(event_id))
Ok(redact_event::v3::Response { event_id })
}
Loaded 100 of 300 files, more files were not shown because too many files have changed in this diff. Show more