Compare commits

..
Author SHA1 Message Date
timedout ce178d86d5 feat(admin): List user memberships route 2026-10-10 23:58:24 +01:00
timedout 02f4f9d88d feat(admin): Create user route 2026-10-10 23:11:37 +01:00
timedout 1deaf99409 feat(admin): List users endpoint 2026-10-05 05:08:36 +01:00
Jade Ellis 1e34bd2ed9 style: Run formatting 2026-10-05 00:27:12 +01:00
stratself d83da6ada7 docs(deploying: Fixes from PR comments 2026-10-03 15:52:20 +00:00
stratself 9377ff7abd fix: Trailing whitespace 2026-10-03 15:52:20 +00:00
stratself 2118eb8501 docs: Move Configuration page below Deploying section 2026-10-03 15:52:20 +00:00
stratself ef0483feb9 docs(deploying): Note the conduwuit name and other small style changes 2026-10-03 15:52:20 +00:00
stratself 25f59e3e2c docs(deploying): Add baseline instructions and buttons for installation
The OverviewGroup thingy is hardcoded for now because figuring out
rspress hooks to read from _meta.json is a pain.
2026-10-03 15:52:20 +00:00
stratself 060eee983d chore: Add changelog to #2252 2026-10-03 15:52:20 +00:00
stratself 7fba194bff docs(deploying): Add missing links and small wording changes to some pages 2026-10-03 15:52:20 +00:00
stratself 7bf6f3bd11 docs(deploying): Shorten the release tracks section 2026-10-03 15:52:20 +00:00
stratself 8b77a559e0 docs(generic): Add small intro 2026-10-03 15:52:20 +00:00
stratself c1d75183d1 docs(deploying): Prioritize FreeBSD page above Nomad and K8s 2026-10-03 15:52:20 +00:00
stratself f9a6171cc5 docs(debian): Add "next steps" redir and fix headings' levels 2026-10-03 15:52:20 +00:00
stratself 5fcc43e803 docs(deploying): redirect all 'next steps' section to main deploying page 2026-10-03 15:52:20 +00:00
stratself 26646f9df6 docs(deploying): Populate the stub Deploying page with useful info
* Detail Continuwuity's release tracks
* Add general update advises
* Add installation and post-installation sections
2026-10-03 15:52:20 +00:00
stratself c221d60654 docs(rpm): Remove instructions to disable GPG checking 2026-10-03 15:40:15 +00:00
stratself 70cce17b7f fix(docs,rpm): Correct path of config file 2026-10-03 15:40:15 +00:00
stratself 2f45a5c794 docs(rpm): Fixes from PR comments 2026-10-03 15:40:15 +00:00
stratself b64f8a76ac chore: Add changelog for #2275 2026-10-03 15:40:15 +00:00
stratself aab456e0e0 docs(rpm): Add basic configuration instructions
Needed as the docs implied it works OOTB. Also moved building and
uninstallation instructions to an Appendix section
2026-10-03 15:40:15 +00:00
Clubs b40204a6c7 docs: changelog for adding !admin token issue registration conditional 2026-10-03 15:37:58 +00:00
Clubs ea16e78092 fix: ensure that registration is enabled before giving tokens from !admin token issue 2026-10-03 15:37:58 +00:00
Erwan Leboucher 56c2d8d901 refactor(media): Simplify preview image handling 2026-10-03 15:35:18 +00:00
Erwan Leboucher 7d8a5f6bab fix(media): Preserve remote preview dimensions without decoding images 2026-10-03 15:35:18 +00:00
Erwan Leboucher de578c2163 fix(media): Validate preview image downloads 2026-10-03 15:35:18 +00:00
timedout c94fa39fd1 fix: Don't panic when a join doesn't include a create event 2026-10-03 15:19:10 +00:00
Ginger 2773ff3e16 feat: Import images correctly from OIDC claims 2026-10-03 15:04:07 +00:00
Ginger 6bbea25034 feat: Allow configuring additional trusted OIDC audiences 2026-10-03 15:03:47 +00:00
Ginger 39bee607c0 refactor: Remove recaptcha-verify 2026-10-03 15:03:34 +00:00
timedout 935ddf1d0f style: Change Allow to Default etc
`ExplicitAllow` -> `Allow`
2026-10-02 18:10:18 +01:00
timedout 495eeedd24 style: Don't return Allow in an else block 2026-10-02 18:10:17 +01:00
timedout 63294f8775 fix: Inverted check 2026-10-02 18:10:17 +01:00
timedout 7243c92dbc chore: add newsfrag 2026-10-02 18:10:17 +01:00
timedout 43ee11bb00 feat: Support MSC4494 2026-10-02 18:10:17 +01:00
Ginger f1d9537b14 fix: Fix startup panic in old migrations 2026-10-02 11:41:37 -04:00
Ginger cb7af18bc2 fix: Make unembed_unsigned_info infallible 2026-10-01 18:43:54 +00:00
Ginger a6fae7498d fix: Don't bump version if it's already bumped 2026-10-01 18:43:54 +00:00
Ginger 48c36d6f17 refactor: Remove some unnecessary macro logic 2026-10-01 18:43:54 +00:00
Ginger 23d07e3d4f refactor: Clean up migration logic 2026-10-01 18:43:54 +00:00
stratself 1220144495 fix: Uncenter 2026-10-01 16:18:43 +00:00
stratself a718aa92eb fix: A word 2026-10-01 16:11:22 +00:00
stratself 4a97dc8c96 docs: Add donate section and backers count badge to README 2026-10-01 16:11:22 +00:00
stratself 8414af2349 fix: Trailing whitespace 2026-10-01 16:11:22 +00:00
stratself 4daf674337 fix: Use div align and br instead of inline css for donate button 2026-10-01 16:11:22 +00:00
stratself 847412367b docs(README): Better colors for some buttons 2026-10-01 16:11:22 +00:00
stratself 95e99a393d docs(README): Add Open Collective donation button 2026-10-01 16:11:22 +00:00
stratself a4faa82f38 docs(README): Tagline concision 2026-10-01 16:11:22 +00:00
stratself e931fdca15 docs(README): Smart linking the contrib page and other improvements
CONTRIBUTION.md is now linked directly when viewed from the repo.

When viewed in the website, links to /CONTRIBUTION.md will be redirected
towards /development/contributing using the `pluginClientRedirects`
options

The other dev docs can also benefit from these hackarounds
2026-10-01 16:11:22 +00:00
stratself db6e70eae8 docs(README): Remove "what are we working on" section
Not a very useful indicator of project progress for now
2026-10-01 16:11:22 +00:00
stratself d97fcc9acd style(docs,README): Remove anchor tags (seems unused for anything) 2026-10-01 16:11:22 +00:00
stratself c087c3cdb8 style(docs,README): Cleanup badge using indirect links 2026-10-01 16:11:22 +00:00
stratself c186879138 fix(docs): Fix header levels in README.md 2026-10-01 16:11:22 +00:00
Renovate Bot 92bc1111ee chore(deps): update dependency cargo-bins/cargo-binstall to v1.24.0 2026-10-01 16:07:21 +00:00
stratself 0989155929 docs(intro): Dehyphenate 2026-10-01 16:05:59 +00:00
stratself 15bb2f7bf5 docs(intro): Fixes from PR comments 2026-10-01 16:05:59 +00:00
stratself a62f7ecc28 docs(intro): Use fednex's tagline from the website 2026-10-01 16:05:59 +00:00
stratself 30266fe3b5 docs: New Jade link 2026-10-01 16:05:59 +00:00
stratself 7d1163e35d fix: Newline 2026-10-01 16:05:59 +00:00
stratself a88da6fd5c fix(docs): Intro page logo resizing 2026-10-01 16:05:59 +00:00
stratself d413a3ebdc chore: Add changelog for #2279 2026-10-01 16:05:59 +00:00
stratself 4dd538219a docs: Rename meta for introduction page to "Introduction" 2026-10-01 16:05:59 +00:00
stratself 413ebc0061 docs(intro): Draw the rest of the introduction page (see notes)
* Add stub Deploying section
* Add Try it out section with short instructions for partnered
  homeservers
* Add Donate section with OC button and individual links
* Add Contact section, move all chatroom and source code buttons there
* Use new `no-zoom` html class to disable image zooms
2026-10-01 16:05:59 +00:00
stratself 2eda5de86b docs(intro): Rewrite intro page from hidden sections of main index 2026-10-01 16:05:59 +00:00
Ginger 931686e84e fix: Fix panic in room creation 2026-09-30 18:49:03 +00:00
Ginger eb602e83a1 chore: Fix clippy lints 2026-09-30 14:47:46 -04:00
Renovate Bot 5c4066cbfd chore(deps): update pre-commit hook crate-ci/typos to v1.50.3 2026-09-30 05:03:27 +00:00
timedout 58d135bc57 fix: Return the actual state at in !admin debug get-state-at
Previously this command actually returned the state *before*, which made debugging with it confusing.
2026-09-29 22:06:48 +01:00
Clubs 684820c7c1 fix: check for user account status before attemping to process email change. 2026-09-29 18:36:35 +00:00
Ginger cbdf978b84 fix: Preserve custom fields in create event content 2026-09-29 17:52:32 +00:00
Ginger 38b7987335 fix: Add invitees as creators for v12+ trusted private chats 2026-09-29 17:52:32 +00:00
stratself 612a261b61 docs(auth): with --> to 2026-09-29 16:26:07 +00:00
stratself b1e51ab0fb docs(internal auth): Redo rego methods (see commit notes)
* Tokens + recaptcha combinations have been removed since they don't
  work. Docstring in config tomlto be removed later
* Method 3 expanded to include both static and admin issued tokens
* Methods 1-3 are the "trusted token flow" and 4-6 are the "untrusted
  captcha flow"
2026-09-29 16:26:07 +00:00
stratself 8f56f99e2f docs(oidc): Incorporate wording fixes wrt subject claim from PR review 2026-09-29 16:26:07 +00:00
stratself 95f65fdba4 docs(auth): Wording fixes according to PR review 2026-09-29 16:26:07 +00:00
stratself 23a0fc1b0f docs(oidc): kanidm --> Kanidm 2026-09-29 16:26:07 +00:00
stratself f49bda81d2 docs(auth): Incorporate changes from PR review comments 2026-09-29 16:26:07 +00:00
stratself f35eb7677c fix: Typo 2026-09-29 16:26:07 +00:00
stratself b2a90f118d docs(deploying): Fix OIDC links
The deploying stub page will be rewritten sooon and the "What's next"
steps should migrate there. In the meantime this helps npm not break
when building the docs
2026-09-29 16:26:07 +00:00
stratself 4b79acba97 chore: Changelog for #2234 2026-09-29 16:26:07 +00:00
stratself 01a83067c6 docs: Remove OIDC page from Guides section
It now resides in the Authentication section
2026-09-29 16:26:07 +00:00
stratself 84cf4196e2 docs(auth): Fix wordings and add links to admin commands
* Add confirmed email + reCAPTCHA registration method as well
2026-09-29 16:26:07 +00:00
stratself 83341062af docs(oidc): Add advanced options section, and more notes for linked accounts 2026-09-29 16:26:07 +00:00
stratself 1d196f24ec docs(auth): Reword sources section a bit 2026-09-29 16:26:07 +00:00
stratself 4631854325 docs(auth): Address concerns from feedback part 1 2026-09-29 16:26:07 +00:00
stratself 26b8e527aa docs(oidc): Add important notice to OIDC breaking legacy logins 2026-09-29 16:26:07 +00:00
stratself c07922fff2 docs(auth): Simplify auth sources section & add client well-known notice 2026-09-29 16:26:07 +00:00
stratself e41435f13c docs(auth): Rename rego page to "internal auth" & add pwd reset details
* Moved around a few paragraphs to fit new title as well
2026-09-29 16:26:07 +00:00
stratself 8c0fcfd108 chore: Add few todos 2026-09-29 16:26:07 +00:00
stratself 516f94d83f docs(auth): Copy stuff from the OIDC guide
The guide would be removed at a later time
2026-09-29 16:26:07 +00:00
stratself 97533eea05 docs(auth): Writeup on auth sources and flows 2026-09-29 16:26:07 +00:00
stratself 062cb5b412 docs(registration): Remove challengeless rego mentions, add rego platforms 2026-09-29 16:26:07 +00:00
stratself 17084a363b docs(registration): Number all the rego methods and add admin commands for emails 2026-09-29 16:26:07 +00:00
stratself ac96b57506 chore(docs): Add some todos 2026-09-29 16:26:07 +00:00
stratself 385f6639c4 docs(auth): Move legacy auth page to rego page (see desc)
The commit moves legacy.mdx to registration.mdx and significantly
shortens it. Instead of explaining every registration option now a table
is provided. Renaming the page because besides registration there is not
much else to explain about legacy auth. If anything, those should be
elaborated on the main authentication.mdx page (i.e. difference between
OAuth and UIAA)

The email section has also been updated with (some) relevant info.
2026-09-29 16:26:07 +00:00
stratself b3a15fc305 docs(auth): Add token-based registration instructions 2026-09-29 16:26:07 +00:00
stratself 979c1b2fc7 docs: Initialize authentication chapter 2026-09-29 16:26:07 +00:00
Ginger 8f2f7f09ed docs: Remove cards from index page 2026-09-29 15:39:26 +00:00
Renovate Bot b59e697ed6 chore(deps): update github-actions-digest 2026-09-29 05:01:36 +00:00
nex 9c0b88f67c chore: Publish admin announcement 2026-09-29 02:30:34 +00:00
Renovate Bot 76e87c93d8 chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.115.13 2026-09-28 05:03:08 +00:00
nex aa40142b87 fix(ci): Disable GitLab mirror 2026-09-28 03:13:34 +00:00
105 changed files with 2102 additions and 1388 deletions

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ runs:
using: composite
steps:
- name: Install sccache
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
uses: https://git.tomfos.tr/tom/sccache-action@v1
- name: Configure sccache
uses: https://github.com/actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
with:
@@ -29,7 +29,7 @@ runs:
steps:
- name: Detect runner OS
id: runner-os
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
uses: https://git.tomfos.tr/actions/detect-versions@v1
- name: Configure cross-compilation architecture
if: inputs.dpkg-arch != ''
+2 -2
View File
@@ -39,7 +39,7 @@ runs:
steps:
- name: Detect runner OS
id: runner-os
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
uses: https://git.tomfos.tr/actions/detect-versions@v1
- name: Configure Cargo environment
shell: bash
@@ -147,7 +147,7 @@ runs:
run: echo "::group::📦 Restoring build cache"
- name: Setup sccache
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
uses: https://git.tomfos.tr/tom/sccache-action@v1
- name: End build cache restore group
shell: bash
+1 -1
View File
@@ -71,7 +71,7 @@ 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@94c31af3204a9f15ab40b35ad084410b905bbc73 # v2
uses: https://github.com/taiki-e/install-action@4cef1412cce204788f482e778a0b9187f9626a29 # v2
with:
tool: git-warp-time,timelord-cli@3.0.1
+7 -7
View File
@@ -37,9 +37,9 @@ creds:
- registry: forgejo.ellis.link
user: "{{env \"BUILTIN_REGISTRY_USER\"}}"
pass: "{{env \"BUILTIN_REGISTRY_PASSWORD\"}}"
- registry: registry.gitlab.com
user: "{{env \"GITLAB_USERNAME\"}}"
pass: "{{env \"GITLAB_TOKEN\"}}"
# - registry: registry.gitlab.com
# user: "{{env \"GITLAB_USERNAME\"}}"
# pass: "{{env \"GITLAB_TOKEN\"}}"
- registry: git.nexy7574.co.uk
user: "{{env \"N7574_GIT_USERNAME\"}}"
pass: "{{env \"N7574_GIT_TOKEN\"}}"
@@ -58,10 +58,10 @@ defaults:
# Sync configuration - each registry gets different image sets
sync:
- source: *source
target: registry.gitlab.com/continuwuity/continuwuity
type: repository
<<: *tags-main
#- source: *source
# target: registry.gitlab.com/continuwuity/continuwuity
# type: repository
# <<: *tags-main
- source: *source
target: ghcr.io/continuwuity/continuwuity
type: repository
+5
View File
@@ -4,6 +4,11 @@ on:
pull_request_target:
types: [opened, reopened]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
auto-label:
name: Apply labels based on changed files
+1 -1
View File
@@ -60,7 +60,7 @@ jobs:
cargo-debian-${{ steps.debian-version.outputs.distribution }}-${{ matrix.arch }}-
- name: Setup sccache
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
uses: https://git.tomfos.tr/tom/sccache-action@v1
- name: Configure sccache environment
run: |
+2
View File
@@ -54,6 +54,8 @@ jobs:
runs-on: ubuntu-latest
needs:
- build
permissions:
contents: write
if: startsWith(github.ref, 'refs/tags/')
steps:
- name: Download binary artifacts
+5
View File
@@ -4,6 +4,11 @@ on:
pull_request_target:
types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
check-changelog:
name: Check changelog is added
+4 -4
View File
@@ -28,13 +28,13 @@ jobs:
- name: Detect runner environment
id: runner-env
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
uses: https://git.tomfos.tr/actions/detect-versions@v1
- 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@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
node-version: 26
node-version: 24
- name: Cache npm dependencies
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
@@ -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@ebbaa1584979971c8614a24965b4405ff95890e0 # v4
uses: https://github.com/cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4
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@ebbaa1584979971c8614a24965b4405ff95890e0 # v4
uses: https://github.com/cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4
with:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+4
View File
@@ -7,6 +7,10 @@ on:
- main
workflow_dispatch:
permissions:
contents: read
pull-requests: read
jobs:
fast-checks:
name: Pre-commit & Formatting
+12 -2
View File
@@ -31,6 +31,11 @@ jobs:
build-release:
name: "Build ${{ matrix.slug }} (release)"
runs-on: dind
permissions:
contents: read
packages: write
attestations: write
id-token: write
strategy:
matrix:
include:
@@ -79,7 +84,6 @@ jobs:
outputs: |
${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }}
type=local,dest=/tmp/binaries
pull: true # Base images were becoming out of date
env:
SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }}
- name: Upload Docker artifacts
@@ -113,6 +117,11 @@ jobs:
name: "Build ${{ matrix.slug }} (max-perf)"
runs-on: dind
needs: build-release
permissions:
contents: read
packages: write
attestations: write
id-token: write
strategy:
matrix:
include:
@@ -163,7 +172,6 @@ jobs:
outputs: |
${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }}
type=local,dest=/tmp/binaries
pull: true # Base images were becoming out of date
env:
SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }}
- name: Upload max-perf Docker artifacts
@@ -199,6 +207,8 @@ jobs:
needs:
- build-release
- build-maxperf
permissions:
contents: write
if: startsWith(github.ref, 'refs/tags/')
steps:
- name: Download binary artifacts
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
name: Renovate
runs-on: ubuntu-latest
container:
image: ghcr.io/renovatebot/renovate:44.104.2@sha256:d19051d0a908e098c7fbba04a16435ef136208bfa47105d59a9fe47059e2bd25
image: ghcr.io/renovatebot/renovate:44.115.13@sha256:c19ab7a16ed7cbe8f7f11e2435e67c727ba90107930d3324c8d1cdec808f0055
options: --tmpfs /tmp:exec
steps:
- name: Checkout
+1 -1
View File
@@ -24,7 +24,7 @@ repos:
- id: check-added-large-files
- repo: https://github.com/crate-ci/typos
rev: v1.50.2
rev: v1.50.3
hooks:
- id: typos
- id: typos
-16
View File
@@ -1,19 +1,3 @@
# Continuwuity v26.9.3 (2026-11-10)
No significant changes.
# Continuwuity v26.9.2 (2026-11-10)
## Bugfixes
- SEC15, reported by @stratself (SEC15)
- SEC31, reported by @tulir (SEC31)
- SEC34, reported by @jade (SEC34)
- SEC36, reported by @nex (SEC36)
- SEC39, reported by @Henry-Hiles (SEC39)
# Continuwuity v26.9.1 (2026-09-28)
## Features
Generated
+13 -29
View File
@@ -896,7 +896,7 @@ dependencies = [
[[package]]
name = "conduwuit"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"aws-lc-rs",
"clap",
@@ -934,7 +934,7 @@ dependencies = [
[[package]]
name = "conduwuit_admin"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"clap",
"conduwuit_api",
@@ -959,7 +959,7 @@ dependencies = [
[[package]]
name = "conduwuit_api"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"axum",
"base64 0.23.1",
@@ -992,7 +992,7 @@ dependencies = [
[[package]]
name = "conduwuit_build_metadata"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"built",
"cargo_metadata",
@@ -1000,7 +1000,7 @@ dependencies = [
[[package]]
name = "conduwuit_core"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"argon2",
"arrayvec",
@@ -1065,7 +1065,7 @@ dependencies = [
[[package]]
name = "conduwuit_database"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"async-channel",
"conduwuit_core",
@@ -1086,7 +1086,7 @@ dependencies = [
[[package]]
name = "conduwuit_macros"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"itertools 0.15.0",
"proc-macro2",
@@ -1096,7 +1096,7 @@ dependencies = [
[[package]]
name = "conduwuit_router"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"axum",
"axum-server",
@@ -1132,7 +1132,7 @@ dependencies = [
[[package]]
name = "conduwuit_service"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"askama",
"assign",
@@ -1162,9 +1162,7 @@ dependencies = [
"openidconnect",
"p256",
"rand 0.10.3",
"recaptcha-verify",
"regex",
"reqwest 0.12.28",
"reqwest 0.13.5",
"resolvematrix",
"ruma",
@@ -1187,7 +1185,7 @@ dependencies = [
[[package]]
name = "conduwuit_web"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"askama",
"async-trait",
@@ -1202,8 +1200,6 @@ dependencies = [
"lettre",
"memory-serve",
"openidconnect",
"recaptcha-verify",
"reqwest 0.12.28",
"ruma",
"serde",
"serde_json",
@@ -2749,7 +2745,6 @@ dependencies = [
"hyper",
"hyper-util",
"rustls",
"rustls-native-certs",
"tokio",
"tokio-rustls",
"tower-service",
@@ -4739,17 +4734,6 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "recaptcha-verify"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "409bf11a93fe93093f3c0254aab67576524f1e0524692615b5b63091dbc88a79"
dependencies = [
"reqwest 0.12.28",
"serde",
"serde_json",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -4829,7 +4813,6 @@ dependencies = [
"pin-project-lite",
"quinn",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"serde",
"serde_json",
@@ -4879,6 +4862,7 @@ dependencies = [
"rustls-platform-verifier",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-rustls",
@@ -5161,7 +5145,7 @@ dependencies = [
[[package]]
name = "ruminuwuity"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"assign",
"http",
@@ -7301,7 +7285,7 @@ dependencies = [
[[package]]
name = "xtask"
version = "26.9.3"
version = "26.9.1"
dependencies = [
"askama",
"cargo_metadata",
+6 -1
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 = "26.9.3"
version = "26.9.1"
[workspace.metadata.crane]
name = "conduwuit"
@@ -163,6 +163,7 @@ features = [
"hickory-dns",
"http2",
"stream",
"form",
]
[workspace.dependencies.serde]
@@ -383,6 +384,7 @@ features = [
"unstable-msc4354",
"unstable-msc4480",
"unstable-msc4466",
"unstable-msc4494",
"unstable-extensible-events",
]
@@ -657,6 +659,9 @@ default-features = false
[workspace.dependencies.ruminuwuity]
package = "ruminuwuity"
path = "src/ruminuwuity"
features = [
"unstable-msc4484"
]
###############################################################################
#
+66 -45
View File
@@ -1,49 +1,77 @@
# continuwuity
# Continuwuity
<!-- ANCHOR: catchphrase -->
## A community-driven [Matrix](https://matrix.org/) homeserver
## A community-driven [Matrix](https://matrix.org/) homeserver in Rust
[![Chat on Matrix][matrix-chat-badge]][matrix-chatroom]
[![Join the space][matrix-space-badge]][matrix-space]
[![Open Collective backers and sponsors][opencollective-contributors-badge]][opencollective]
[![Chat on Matrix](https://img.shields.io/matrix/continuwuity%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix)](https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org) [![Join the space](https://img.shields.io/matrix/space%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix&label=space)](https://matrix.to/#/#space:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org)
<!-- ANCHOR_END: catchphrase -->
[matrix-chat-badge]: https://img.shields.io/matrix/continuwuity%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix
[matrix-chatroom]: https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org
[matrix-space-badge]: https://img.shields.io/matrix/space%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix&label=space
[matrix-space]: https://matrix.to/#/#space:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org
[opencollective-contributors-badge]: https://img.shields.io/opencollective/all/continuwuity
[opencollective]: https://opencollective.com/continuwuity
[continuwuity] is a Matrix homeserver written in Rust.
It's the official community continuation of the [conduwuit](https://github.com/girlbossceo/conduwuit) homeserver.
<!-- ANCHOR: body -->
[![forgejo.ellis.link][forge-badge]][forge-link]
[![Stars][forge-stars-badge]][forge-stars-link]
[![Issues][forge-issues-badge]][forge-issues-link]
[![Pull Requests][forge-pulls-badge]][forge-pulls-link]
[![forgejo.ellis.link](https://img.shields.io/badge/Ellis%20Git-main+packages-green?style=flat&logo=forgejo&labelColor=fff)](https://forgejo.ellis.link/continuwuation/continuwuity) [![Stars](https://forgejo.ellis.link/continuwuation/continuwuity/badges/stars.svg?style=flat)](https://forgejo.ellis.link/continuwuation/continuwuity/stars) [![Issues](https://forgejo.ellis.link/continuwuation/continuwuity/badges/issues/open.svg?style=flat)](https://forgejo.ellis.link/continuwuation/continuwuity/issues?state=open) [![Pull Requests](https://forgejo.ellis.link/continuwuation/continuwuity/badges/pulls/open.svg?style=flat)](https://forgejo.ellis.link/continuwuation/continuwuity/pulls?state=open)
[![GitHub][github-badge]][github-link] ![Stars][github-stars-badge] -
[![Codeberg][codeberg-badge]][codeberg-link] [![Stars][codeberg-stars-badge]][codeberg-stars-link] -
[![GitLab][gitlab-badge]][gitlab-link] [![Stars][gitlab-stars-badge]][gitlab-stars-link]
[![GitHub](https://img.shields.io/badge/GitHub-mirror-blue?style=flat&logo=github&labelColor=fff&logoColor=24292f)](https://github.com/continuwuity/continuwuity) [![Stars](https://img.shields.io/github/stars/continuwuity/continuwuity?style=flat)](https://github.com/continuwuity/continuwuity/stargazers)
<br>
<a href="https://opencollective.com/continuwuity" target="_blank">
<img src="https://opencollective.com/webpack/donate/button.png?color=blue" width="250"/>
</a>
[![GitLab](https://img.shields.io/badge/GitLab-mirror-blue?style=flat&logo=gitlab&labelColor=fff)](https://gitlab.com/continuwuity/continuwuity) [![Stars](https://img.shields.io/gitlab/stars/continuwuity/continuwuity?style=flat)](https://gitlab.com/continuwuity/continuwuity/-/starrers)
[forge-badge]: https://img.shields.io/badge/Ellis%20Git-main+packages-green?style=flat&logo=forgejo&labelColor=fff
[forge-link]: https://forgejo.ellis.link/continuwuation/continuwuity
[forge-stars-badge]: https://forgejo.ellis.link/continuwuation/continuwuity/badges/stars.svg?style=flat&labelColor=fff&color=8a5cd0
[forge-stars-link]: https://forgejo.ellis.link/continuwuation/continuwuity/stars
[forge-issues-badge]: https://forgejo.ellis.link/continuwuation/continuwuity/badges/issues/open.svg?style=flat&labelColor=fff&color=8a5cd0
[forge-issues-link]: https://forgejo.ellis.link/continuwuation/continuwuity/issues?state=open
[forge-pulls-badge]: https://forgejo.ellis.link/continuwuation/continuwuity/badges/pulls/open.svg?style=flat&labelColor=fff&color=8a5cd0
[forge-pulls-link]: https://forgejo.ellis.link/continuwuation/continuwuity/pulls?state=open
[![Codeberg](https://img.shields.io/badge/Codeberg-mirror-2185D0?style=flat&logo=codeberg&labelColor=fff)](https://codeberg.org/continuwuity/continuwuity) [![Stars](https://codeberg.org/continuwuity/continuwuity/badges/stars.svg?style=flat)](https://codeberg.org/continuwuity/continuwuity/stars)
[github-badge]: https://img.shields.io/badge/GitHub-mirror-blue?style=flat&logo=github&labelColor=fff&logoColor=24292f
[github-link]: https://github.com/continuwuity/continuwuity
[github-stars-badge]: https://img.shields.io/github/stars/continuwuity/continuwuity?style=flat
[gitlab-badge]:https://img.shields.io/badge/GitLab-mirror-blue?style=flat&logo=gitlab&labelColor=fff
[gitlab-link]: https://gitlab.com/continuwuity/continuwuity
[gitlab-stars-badge]: https://img.shields.io/gitlab/stars/continuwuity/continuwuity?style=flat
[gitlab-stars-link]: https://gitlab.com/continuwuity/continuwuity/-/starrers
[codeberg-badge]:https://img.shields.io/badge/Codeberg-mirror-2185D0?style=flat&logo=codeberg&labelColor=fff
[codeberg-link]: https://codeberg.org/continuwuity/continuwuity
[codeberg-stars-badge]: https://codeberg.org/continuwuity/continuwuity/badges/stars.svg?style=flat
[codeberg-stars-link]: https://codeberg.org/continuwuity/continuwuity/stars
### Why does this exist?
## Why does this exist?
The original conduwuit project has been archived and is no longer maintained. Rather than letting this Rust-based Matrix homeserver disappear, a group of community contributors have forked the project to continue its development, fix outstanding issues, and add new features.
We aim to provide a stable, well-maintained alternative for current conduwuit users and welcome newcomers seeking a lightweight, efficient Matrix homeserver.
### Who are we?
## Who are we?
We are a group of Matrix enthusiasts, developers and system administrators who have used conduwuit and believe in its potential. Our team includes both previous
contributors to the original project and new developers who want to help maintain and improve this important piece of Matrix infrastructure.
We operate as an open community project, welcoming contributions from anyone interested in improving continuwuity.
### What is Matrix?
## What is Matrix?
[Matrix](https://matrix.org) is an open, federated, and extensible network for
decentralized communication. Users from any Matrix homeserver can chat with users from all
other homeservers over federation. Matrix is designed to be extensible and built on top of.
You can even use bridges such as Matrix Appservices to communicate with users outside of Matrix, like a community on Discord.
### What are the project's goals?
## What are the project's goals?
Continuwuity aims to:
@@ -55,11 +83,11 @@ Continuwuity aims to:
- Create a sustainable development model for long-term maintenance
- Keep a lightweight, efficient codebase that can run on modest hardware
### Can I try it out?
## Can I try it out?
Check out the [documentation](https://continuwuity.org) for installation instructions.
Check out our [website](https://continuwuity.org) for installation instructions. Start with the [deployment section](https://continuwuity.org/deploying).
If you want to try it out as a user, we have some partnered homeservers you can use:
If you want to try it out as a user, we have some partnered homeservers you can join:
* You can head over to [https://federated.nexus](https://federated.nexus/) in your browser.
* Hit the `Apply to Join` button. Once your request has been accepted, you will receive an email with your username and password.
* Head over to [https://app.federated.nexus](https://app.federated.nexus/) and you can sign in there, or use any other matrix chat client you wish elsewhere.
@@ -67,31 +95,20 @@ If you want to try it out as a user, we have some partnered homeservers you can
* There's also [https://continuwuity.rocks/](https://continuwuity.rocks/). You can register a new account using Cinny via [this convenient link](https://app.cinny.in/register/continuwuity.rocks), or you can use Element or another matrix client *that supports registration*.
### What are we working on?
## Can I migrate my data from X?
We're working our way through all of the issues in the [Forgejo project](https://forgejo.ellis.link/continuwuation/continuwuity/issues).
- [Packaging & availability in more places](https://forgejo.ellis.link/continuwuation/continuwuity/issues/747)
- [Appservices bugs & features](https://forgejo.ellis.link/continuwuation/continuwuity/issues?q=&type=all&state=open&labels=178&milestone=0&assignee=0&poster=0)
- [Improving compatibility and spec compliance](https://forgejo.ellis.link/continuwuation/continuwuity/issues?labels=119)
- Automated testing
- [Admin API](https://forgejo.ellis.link/continuwuation/continuwuity/issues/748)
- [Policy-list controlled moderation](https://forgejo.ellis.link/continuwuation/continuwuity/issues/750)
### Can I migrate my data from x?
- Conduwuit: Yes
- Conduit: No, database is now incompatible
- Grapevine: No, database is now incompatible
- Dendrite: No
- Synapse: No
- **Conduwuit**: Yes
- **Conduit**: No, database is now incompatible
- **Grapevine**: No, database is now incompatible
- **Dendrite**: No
- **Synapse**: No
We haven't written up a guide on migrating from incompatible homeservers yet. Reach out to us if you need to do this!
<!-- ANCHOR_END: body -->
## Contribution
See our [Contributing page](CONTRIBUTING.md) for more details.
### Development flow
- Features / changes must developed in a separate branch
@@ -104,7 +121,6 @@ We haven't written up a guide on migrating from incompatible homeservers yet. Re
The main branch is always green!
### Policy on pulling from other forks
We welcome contributions from other forks of conduwuit, subject to our review process.
@@ -117,13 +133,18 @@ When incorporating code from other forks:
- We prioritize stability and compatibility when evaluating external contributions
- Features that align with our project goals will be given priority consideration
<!-- ANCHOR: footer -->
## Donate to us!
#### Contact
If you like what we're doing, consider donating to our [**Open Collective**][opencollective]!
You can also donate individually to each of the maintainers:
- Nex: https://timedout.uk/donate.html
- Jade: https://jade.ellis.link/sponsors
- Ginger: https://github.com/sponsors/gingershaped
## Contact
Join our [Matrix room](https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org) and [space](https://matrix.to/#/#space:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org) to chat with us about the project!
<!-- ANCHOR_END: footer -->
[continuwuity]: https://forgejo.ellis.link/continuwuation/continuwuity
+1
View File
@@ -0,0 +1 @@
Profile banners are now treated as images when imported from OIDC claims, like avatars already were.
+1
View File
@@ -0,0 +1 @@
For deployments using OIDC with `profile_key_import_mode` set to `on_login`, users' avatars will no longer be clobbered if they didn't change their avatar since their last login.
+1
View File
@@ -0,0 +1 @@
Invitees are now added as room creators when creating a v12+ trusted private chat. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Continuwuity now supports configuring additional trusted audience values for deployments using OIDC with an IDP that sends them. Contributed by @ginger
+1
View File
@@ -0,0 +1 @@
Add the Authentication section to document available auth methods for Continuwuity. The "delegated authentication" guide has also been migrated to here. Contributed by @stratself.
+1
View File
@@ -0,0 +1 @@
The deploying page now includes vital general information about installing Continuwuity: release tracks, update steps, and post-installation recommendations. Contributed by @stratself
+1
View File
@@ -0,0 +1 @@
Add some missing instructions on configuring Continuwuity on the RPM page. Users are encouraged to use the [generic deploying docs](https://continuwuity.org/deploying/generic) for the bulk of guidance anyhow. Contributed by @stratself
+1
View File
@@ -0,0 +1 @@
Better, more succinct [introduction page](https://continuwuity.org/introduction.html). Contributed by @stratself
+1
View File
@@ -0,0 +1 @@
Added support for [MSC4494: Membership-based invite blocking](https://github.com/matrix-org/matrix-spec-proposals/pull/4494)
+1
View File
@@ -0,0 +1 @@
"!admin users change-email" now verifies a user exists before attempting to change their email. Contributed by @Clubs.
+1
View File
@@ -0,0 +1 @@
`!admin token issue` can no longer issue registration tokens when `allow_registration` is false. Contributed by @Clubs.
+1
View File
@@ -0,0 +1 @@
Fixed URL preview image MIME types and rejected failed downloads. Contributed by @eleboucher.
+19 -4
View File
@@ -2319,6 +2319,16 @@
#
#additional_scopes = []
# Additional trusted audiences that Continuwuity will accept in the `aud`
# claim of the OIDC token returned by the IDP. If your identity
# provider includes other values in the `aud` claim in addition to the
# client ID, they must be listed here for Continuwuity to accept them.
#
# Most deployments will not need to set this, because most identity
# providers only include the client ID in the `aud` claim by default.
#
#additional_trusted_audiences = []
# The name of the identity provider. If this is set, the login page's
# button reads "Continue with <name>" instead of just "Continue".
#
@@ -2368,10 +2378,15 @@
# Per-room overrides to the user's display name or avatar will be
# preserved by the import process.
#
# SECURITY NOTE: If the `avatar_url` field is set, Continuwuity will
# perform a HTTP GET to the URL in the mapped claim and use the returned
# file as the user's profile picture. Make sure your users are not able
# to set the value of the mapped claim to an arbitrary URL.
# SECURITY NOTE: For the following profile fields, Continuwuity will treat
# the value of the mapped claim as an HTTP URL and upload the file located
# at that URL to its internal media repository:
#
# - `avatar_url`
# - `chat.commet.profile_banner`
#
# If you map these fields to claims, make sure your users cannot set those
# claims to arbitrary URLs.
#
#profile_key_map = { displayname = "name" }
+1 -1
View File
@@ -50,7 +50,7 @@ EOF
# Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.23.0
ENV BINSTALL_VERSION=1.24.0
# 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.23.0
ENV BINSTALL_VERSION=1.24.0
# renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree
+8 -3
View File
@@ -2,7 +2,12 @@
{
"type": "file",
"name": "introduction",
"label": "Continuwuity"
"label": "Introduction"
},
{
"type": "dir",
"name": "deploying",
"label": "Deploying"
},
{
"type": "file",
@@ -11,8 +16,8 @@
},
{
"type": "dir",
"name": "deploying",
"label": "Deploying"
"name": "authentication",
"label": "Authentication"
},
{
"type": "dir",
+35
View File
@@ -0,0 +1,35 @@
# Authentication
This chapter describes various ways to authenticate to Continuwuity.
## Authentication flows
Continuwuity implements the following authentication flows:
- **OAuth login** (also known as **next-gen auth**): clients redirect the user to Continuwuity's own login and registration page to complete the authentication process.
- **Legacy login** (also known as the **User Interactive Authentication** framework): clients provide their own UI to log in to or register with the server directly.
Different sets of clients support different flows, but most clients are moving towards next-gen auth. One can set which login modes are allowed via the `compatibility_mode` variable of the `[global.oauth]` config file section.
:::important Configure your client well-known for OAuth logins
To ensure OAuth logins work, Continuwuity must know the base URL its Client-Server API is being served on:
```toml
[global.well_known]
client = "https://matrix.example.com"
```
Refer to the [delegation](./guides/delegation) documentation for more details.
:::
## Authentication sources
Continuwuity can read user authentication data from the following sources:
- **Internal authentication** - this is the default setup, where Continuwuity reads user authentication data from its local database. It allows for registration, email, and password reset self-service. See the [**internal authentication documentation**](./authentication/internal).
- **Delegated authentication** - in this mode, the server connects to an OpenID Connect identity provider for user authentication. This method allows for integrating with single sign-on services, but enabling it will disable legacy logins. See the [**delegated authentication documentation**](./authentication/oidc).
Only one authentication source can be used at a time.
+12
View File
@@ -0,0 +1,12 @@
[
{
"type": "file",
"name": "internal",
"label": "Internal authentication"
},
{
"type": "file",
"name": "oidc",
"label": "Delegated authentication (OIDC)"
}
]
+46
View File
@@ -0,0 +1,46 @@
# Internal authentication
Continuwuity comes with an internal database for user authentication, which it uses by default. This allows for self-servicing of account registration, linking emails, and password resets.
## Registration
Registration is disabled by default. To enable it, set `allow_registration = true` in your config file and use at least one of the registration methods below.
| Method | Description | Additional configuration needed |
| ------ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| 1 | Admin-issued tokens (recommended) | None. Use the [`!admin token issue`](../reference/admin/token#admin-token-issue) command |
| 2 | Static registration token | `registration_token` or `registration_token_file` |
| 3 | Token + email | Method 1 or 2 + `require_email_for_token_registration = true` in `[global.smtp]`. See [Email configuration](#email-configuration) |
| 4 | Email-only registration | `require_email_for_registration = true` in `[global.smtp]` section. See [Email configuration](#email-configuration) |
| 5 | reCAPTCHA-only registration | `recaptcha_site_key` and `recaptcha_private_site_key` |
| 6 | Email + reCAPTCHA registration | Methods 4 + 5 |
Admin-issued tokens are the recommended registration method. These tokens are well suited for private or invite-only servers, and they can be scoped with an expiry duration or given a usage limit. See the [`!admin token`](../reference/admin/token) commands for more details.
Other registration methods are meant for **untrusted, public registration**. Care must be taken when allowing these modes of operation.
## Email configuration
Continuwuity can be configured to send emails via an SMTP relay of your choice. These are used for verifying user email addresses and sending password reset links to them.
A user is associated with only **one** email address at a time.
All email options are in the `[global.smtp]` block of the [configuration file](../reference/config.mdx), and are toggled on when the block is uncommented. For example:
```toml
[global.smtp]
# Example URI for the user john@example.com on the `mail.example.net` mail server
connection_uri = "smtps://john%40example.com:password@mail.example.net:465"
sender = "John's Continuwuity server <john@example.com>"
```
A user's email address can also be modified by the [`!admin users change-email`](../reference/admin/users#admin-users-change-email) command. To view current user-email associations, use the `!admin users get-email` and `!admin users get-user-by-email` command.
Use [`!admin debug send-test-email`](../reference/admin/debug#admin-debug-send-test-email) to test that your email setup is working.
## Password resets
Password resets in Continuwuity can be made via:
- Self-service password resets. This requires a user's email to have been set up and verified.
- Using the [`!admin users reset-password`](../reference/admin/users#admin-users-reset-password) command.
+103
View File
@@ -0,0 +1,103 @@
# Delegated authentication with OIDC
Continuwuity supports delegating user authentication to an external identity provider that implements the OpenID Connect (OIDC) specification, such as Authentik, Kanidm, or Keycloak.
:::important Delegated authentication and legacy logins
When delegated authentication is configured, Continuwuity will disable its support for legacy logins. **Only clients that support OAuth** will be able to login.
:::
An account on the homeserver can only be associated with one OIDC subject claim - that is, one account on the identity provider - at a time. Linking an account will also prevent the user from deactivating it themselves.
## Instructions
A simple OIDC configuration is as easy as creating a new OIDC application in your identity provider's settings and supplying Continuwuity with the client ID and client secret.
### Configuring the OIDC provider
This guide will use [**Kanidm**][kanidm] as an example, but the described steps are broadly applicable to other identity providers. Contributions for them are welcome.
First, create a new application for Continuwuity in your identity provider.
```sh
# Here, `c10y` is the client ID that Kanidm will use, and `Continuwuity` is the display name.
# Other identity providers may generate a client ID for you.
# Use the domain that clients can reach Continuwuity at, which may not be the same as your server name
# if you have configured well-known delegation.
kanidm system oauth2 create c10y Continuwuity https://matrix.yourdomain.com
```
Configure the redirect URL that Continuwuity uses.
```sh
kanidm system oauth2 add-redirect-url c10y https://matrix.yourdomain.com/_continuwuity/oidc/complete
```
Allow Continuwuity to request the `openid` scope. Other identity providers may not require this step.
```sh
kanidm system oauth2 update-scope-map c10y idm_all_persons openid
```
Find the client secret that was generated. Other identity providers may show this information in their web UI.
```sh
kanidm system oauth2 show-basic-secret c10y
d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr
```
[kanidm]: https://kanidm.com
### Configuring Continuwuity
Configure Continuwuity with the client ID, client secret, and discovery URL provided from the steps above. Kanidm has a different discovery URL for each client, but other identity providers may have a single discovery URL at the root of their domain.
```toml
[global.oauth.oidc]
# `/.well-known/openid-configuration` will be appended automatically
discovery_url = "https://idm.example.com/oauth2/openid/c10y"
# This may be randomly generated by your identity provider. Kanidm requires
# you to set it manually when you create the application.
client_id = "c10y"
# From the previous step
client_secret = "d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr"
```
### Testing that it works
Finally, restart Continuwuity, and log out and back in again. Your client should prompt you to continue in your web browser and open a webpage with the Continuwuity logo that allows you to continue in your identity provider. Once you log in successfully there, you will be prompted to choose a user ID -- to link your existing account, enter its user ID, and then your old password.
Continuwuity offers several additional configuration options to tweak its integration with your identity provider. Review the `[global.oauth.oidc]` section towards the bottom of the [reference configuration](../reference/config) for a complete list of options and documentation.
## Advanced options
### Minting tokens for non-OIDC accounts
With OIDC delegation enabled, accounts without an OIDC mapping (such as bot accounts) can still be created via the admin commands, but will not be able to log in to the homeserver. To accommodate this, homeserver admins can use the [`!admin users issue-token`](../reference/admin/users#admin-users-issue-token) command to issue tokens for them. This command requires the account to have set a local password, which can be done with [`!admin users reset-password`](../reference/admin/users#admin-users-reset-password).
### Manually linking users to OIDC claims
To view associations between local users and their linked subject claim, issue the following command:
```
!admin query raw raw-iter openidsubject_localpart
("1d3fc994-3947-406d-b22c-0fc529baf235", "john")
("ba543628-e6a5-45d8-9bd2-6cc497400136", "jane")
```
These associations can be changed manually with the [`!admin oidc`](../reference/admin/oidc) commands, which are useful to debug some account linkage issues. For example, to link the user `jane` to a new Subject Identifier claim of `721c36a8-ce04-4474-8e97-b62655b07340`:
```
!admin oidc unlink ba543628-e6a5-45d8-9bd2-6cc497400136
Subject `ba543628-e6a5-45d8-9bd2-6cc497400136` unlinked.
!admin oidc link jane 721c36a8-ce04-4474-8e97-b62655b07340
Subject `721c36a8-ce04-4474-8e97-b62655b07340` linked to account @jane:example.com.
!admin query raw raw-iter openidsubject_localpart
("1d3fc994-3947-406d-b22c-0fc529baf235", "john")
("721c36a8-ce04-4474-8e97-b62655b07340", "jane")
```
### Decommissioning OIDC delegation
It is possible to revert to using the internal database for authentication. First, comment out the `[global.oauth.oidc]` section in your config file and restart the homeserver. Then, execute the [`!admin users reset-password --convert-to-local-account`](../reference/admin/users#admin-users-reset-password) for each user to assign them a local password and convert their linked accounts into local ones.
+106 -1
View File
@@ -1,3 +1,108 @@
import { OverviewGroup } from '@rspress/core/theme';
# Deploying
This chapter describes various ways to deploy Continuwuity.
This chapter describes various ways to deploy Continuwuity. Start reading on this page for useful general information, and then proceed to one of the deployment methods.
:::tip Getting help
If you run into any problems while setting up Continuwuity, ask us in [`#continuwuity:continuwuity.org`][support-room] or [open an issue on Forgejo][forgejo-new-issue].
:::
[support-room]: https://matrix.to/#/%23continuwuity:continuwuity.org
[forgejo-new-issue]: https://forgejo.ellis.link/continuwuation/continuwuity/issues/new
## Release tracks
Continuwuity offers two release tracks to accommodate different needs: tracking the **main branch** of the [repository], and following the regular **release schedule**.
### Main branch
As Continuwuity is rapidly evolving software, we encourage deployments to follow the main branch to receive the latest fixes and features. Commits in main are stable and have been thoroughly tested by the maintainers before merging.
To be notified of updates to main, it is best to [**track the `/changelog.d` directory**][changelog-d] in the repository, which contains changelog snippets from merged pull requests. These may contain breaking changes. Then, proceed to update or build Continuwuity according to your deployment method.
[repository]: https://forgejo.ellis.link/continuwuation/continuwuity
[changelog-d]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/changelog.d
### Regular releases
Regular releases are periodic, versioned cutoffs from the main branch from time to time, and can be found on the [Releases] page. They are suitable in cases where updating more frequently is not viable, such as when using third-party packaging.
For regular releases, **always read the release notes before upgrading to a new version**, as they may contain breaking changes that affect your deployment.
[Releases]: https://forgejo.ellis.link/continuwuation/continuwuity/releases
## Installation
:::info Mind the name!
The binary for Continuwuity is called `conduwuit`, and the configuration file `conduwuit.toml`.
:::
To have Continuwuity working, you will generally need to:
1. Have a domain name pointing to your server's IP address - we will be using `example.com` in our guides.
2. Download or build Continuwuity from your preferred source.
3. Configure Continuwuity via the config file or environment variables. See the [Configuration](./configuration.mdx) page for more.
4. Employ a reverse proxy in front of Continuwuity - we will mainly provide examples for Caddy in our guides.
5. And finally, start the Continuwuity service.
Navigate to your preferred method of deploying Continuwuity as listed below, and follow the instructions there.
<OverviewGroup
group={{
items: [
{
"link": "deploying/generic",
"text": "Generic"
},
{
"link": "deploying/docker",
"text": "Docker"
},
{
"link": "deploying/debian",
"text": "Debian"
},
{
"link": "deploying/rpm",
"text": "RPM"
},
{
"link": "deploying/nixos",
"text": "NixOS"
},
{
"link": "deploying/arch-linux",
"text": "Arch Linux"
},
{
"link": "deploying/freebsd",
"text": "FreeBSD"
},
{
"link": "deploying/kubernetes",
"text": "Kubernetes"
},
{
"link": "deploying/nomad",
"text": "Nomad"
}
],
}}
/>
## Post-installation
After Continuwuity is up and running, consider the following:
- For smooth federation, set up a caching resolver according to the [**DNS tuning guide**](./guides/dns.mdx) (strongly recommended).
- To set up Audio/Video communication, see the [**Calls**](./calls.mdx) page.
- See the [**Authentication chapter**] for various ways to access to your homeserver, such as logging in with an external OIDC provider.
- Consult the [**Maintenance**](./maintenance.mdx) page for guidance on maintaining your homeserver.
- If you want to set up an appservice, take a look at the [**Appservice Guide**](./appservices.mdx).
- See the [**Troubleshooting**](./troubleshooting.mdx) page for commonly diagnosed issues.
+5 -5
View File
@@ -29,6 +29,11 @@
"name": "arch-linux",
"label": "Arch Linux"
},
{
"type": "file",
"name": "freebsd",
"label": "FreeBSD"
},
{
"type": "file",
"name": "kubernetes",
@@ -38,10 +43,5 @@
"type": "file",
"name": "nomad",
"label": "Nomad"
},
{
"type": "file",
"name": "freebsd",
"label": "FreeBSD"
}
]
+8 -2
View File
@@ -1,5 +1,11 @@
# Continuwuity for Arch Linux
Continuwuity is available in the `archlinuxcn` repository and AUR with the same package name `continuwuity`, which includes the latest tagged version. The development version is available on AUR as `continuwuity-git`.
Continuwuity is available in the [`archlinuxcn`][archlinuxcn] repository and AUR with the same package name, [`continuwuity`][aur-continuwuity].
Simply install the `continuwuity` package. Configure the service in `/etc/conduwuit/conduwuit.toml`, then enable and start the continuwuity.service.
The development version is available on the AUR as [`continuwuity-git`][aur-continuwuity-git].
[archlinuxcn]: https://www.archlinuxcn.org/
[aur-continuwuity]: https://aur.archlinux.org/packages/continuwuity
[aur-continuwuity-git]: https://aur.archlinux.org/packages/continuwuity-git
Simply install the `continuwuity` package. Configure the service in `/etc/conduwuit/conduwuit.toml`, then enable and start the `continuwuity.service`.
+12 -11
View File
@@ -1,15 +1,17 @@
# Continuwuity for Docker
This page describes how to deploy Continuwuity via Docker containers. Make sure that you have installed `docker` on your system before continuing.
## Preparation
### Choose an image
The following OCI images are available for Continuwuity:
| Image | Notes |
| 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. Built with [CI][release-image] |
| [https://forgejo.ellis.link/continuwuation/continuwuity:**latest**][latest] | Latest tagged release. |
| [https://forgejo.ellis.link/continuwuation/continuwuity:**main**][main] | Latest `main` branch commit. Built with [CI][release-image] |
| [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). |
@@ -210,7 +212,13 @@ docker compose pull
docker compose up -d
```
## Other deployment methods
## What's next?
Navigate to [Post-installation](../deploying.mdx#post-installation) for next steps.
---
## Appendix - Other deployment methods
### Docker - Quick Run
@@ -289,10 +297,3 @@ From there you can access the server's console by running `docker attach <contai
Note that using `CTRL+c` within `docker attach`'s context will forward the signal to the server, stopping it. See [Docker's reference][docker-attach-reference] for more information.
[docker-attach-reference]: https://docs.docker.com/reference/cli/docker/container/attach/
## Next steps
- For smooth federation, set up a caching resolver according to the [**DNS tuning guide**](../guides/dns.mdx) (recommended)
- To set up Audio/Video communication, see the [**Calls**](../calls.mdx) page.
- Consult the [Maintenance](../maintenance.mdx) page for guidance on maintaining your homeserver.
- If you want to set up an appservice, take a look at the [**Appservice Guide**](../appservices.mdx).
+3 -1
View File
@@ -4,4 +4,6 @@ Continuwuity doesn't provide official FreeBSD packages; however, a community-mai
Please see the installation instructions in that repository. Direct any questions to its issue tracker or to [@katie:kat5.dev](https://matrix.to/#/@katie:kat5.dev).
For general BSD support, please join our [Continuwuity BSD](https://matrix.to/#/%23bsd:continuwuity.org) community room.
For general BSD support, please join our [Continuwuity support room][support-room].
[support-room]: https://matrix.to/#/%23continuwuity:continuwuity.org
+4 -12
View File
@@ -1,12 +1,6 @@
# Generic deployment documentation
:::tip Getting help
If you run into any problems while setting up Continuwuity, ask us in
`#continuwuity:continuwuity.org` or [open an issue on
Forgejo][forgejo-new-issue].
:::
[forgejo-new-issue]: https://forgejo.ellis.link/continuwuation/continuwuity/issues/new
This page provides instructions on deploying Continuwuity on a generic Linux distro via a systemd service file. It also contains common routing instructions for reverse proxies.
## Installing Continuwuity
@@ -270,11 +264,9 @@ curl https://example.com/_matrix/client/versions
## What's next?
- For smooth federation, set up a caching resolver according to the [**DNS tuning guide**](../guides/dns.mdx) (recommended)
- To configure OIDC login with an identity provider, see the [**delegated authentication guide**](../guides/oidc.mdx).
- For Audio/Video call functionality see the [**Calls**](../calls.md) page.
- Consult the [Maintenance](../maintenance.mdx) page for guidance on maintaining your homeserver.
- If you want to set up an appservice, take a look at the [**Appservice Guide**](../appservices.md).
Navigate to [Post-installation](../deploying.mdx#post-installation) for next steps.
---
## Appendix
+36 -20
View File
@@ -1,4 +1,4 @@
import { Tab, Tabs} from '@rspress/core/theme';
import { Tab, Tabs } from '@rspress/core/theme';
# RPM Installation Guide
@@ -28,7 +28,7 @@ Available for openSUSE Tumbleweed, Slowroll, and [supported Leap versions](https
## Installation methods
### Stable releases (recommended)
### Stable releases
<Tabs groupId="distro">
<Tab label="Fedora">
@@ -49,6 +49,7 @@ openSUSE packages are available through an openSUSE Build Service project namesp
</Tabs>
### Nightly releases
Nightly versions are built from the latest commit on the `main` branch every 24 hours.
<Tabs groupId="distro">
@@ -68,14 +69,22 @@ In the meantime, you may follow the [generic deployment instructions](generic).
</Tab>
</Tabs>
## Service management and removal
## Configuration
**Systemd service commands**
Consult the [generic deployment instructions](./generic.mdx) for detailed steps. You will at least need to adjust the config file located at `/etc/conduwuit/conduwuit.toml` to suit your needs, and configure a [reverse proxy](./generic.mdx#setting-up-the-reverse-proxy).
## Service management
Now, you can start your Continuwuity service with:
```bash
# Start the service
sudo systemctl start conduwuit
```
Other useful commands include:
```bash
# Enable on boot
sudo systemctl enable conduwuit
@@ -84,27 +93,13 @@ sudo systemctl status conduwuit
# View logs
sudo journalctl -u conduwuit -f
```
**Uninstallation**
```bash
# Stop and disable the service
# Stopping the service
sudo systemctl stop conduwuit
sudo systemctl disable conduwuit
# Remove the package
sudo dnf remove continuwuity # replace `dnf` with `zypper` on openSUSE
```
## Troubleshooting
**GPG key errors**: Temporarily disable GPG checking
```bash
sudo dnf --nogpgcheck install continuwuity
```
**Repository metadata issues**: Clear and rebuild cache
```bash
@@ -122,7 +117,28 @@ dnf --showduplicates list continuwuity
sudo dnf install continuwuity-<version>
```
## Building locally
## What's next?
Navigate to [Post-installation](../deploying.mdx#post-installation) for next steps.
---
## Appendix
### Uninstallation
To uninstall Continuwuity:
```bash
# Stop and disable the service
sudo systemctl stop conduwuit
sudo systemctl disable conduwuit
# Remove the package
sudo dnf remove continuwuity # replace `dnf` with `zypper` on openSUSE
```
### Building locally
<Tabs groupId="distro">
<Tab label="Fedora">
-5
View File
@@ -13,10 +13,5 @@
"type": "file",
"name": "performance",
"label": "Performance tuning"
},
{
"type": "file",
"name": "oidc",
"label": "Delegated authentication"
}
]
-56
View File
@@ -1,56 +0,0 @@
# Configuring delegated authentication
Continuwuity supports delegating user authentication to an external identity provider that implements the OpenID Connect specification, such as Authentik, kanidm, or Keycloak.
:::warning{title="OIDC versus OAuth, and supported clients"}
**OIDC** is not to be confused with **OAuth**. In the context of Matrix, OAuth is the protocol that Matrix clients use to authenticate with the _homeserver_. OIDC is the protocol that the _homeserver_ uses to communicate with the _identity provider_. Continuwuity supports OAuth by default, alongside the legacy **UIAA** authentication framework.
When OIDC is configured, Continuwuity will disable its support for legacy authentication. **Only clients that support OAuth**, such as the Element family of clients, will be able to log in when OIDC is configured. If your client of choice shows an error when you try to log in after configuring OIDC, it likely does not support OAuth. This is an issue with your client, not Continuwuity, and should be reported to your client's developers.
:::
A simple OIDC configuration is as easy as creating a new OIDC application in your identity provider's settings and supplying Continuwuity with the client ID and client secret. This guide will use kanidm as an example, but the described steps are broadly applicable to other identity providers.
First, create a new application for Continuwuity in your identity provider.
```sh
# Here, `c10y` is the client ID that kanidm will use, and `Continuwuity` is the display name.
# Other identity providers may generate a client ID for you.
# Use the domain that clients can reach Continuwuity at, which may not be the same as your server name
# if you have configured well-known delegation.
kanidm system oauth2 create c10y Continuwuity https://matrix.yourdomain.com
```
Configure the redirect URL that Continuwuity uses.
```sh
kanidm system oauth2 add-redirect-url c10y https://matrix.yourdomain.com/_continuwuity/oidc/complete
```
Allow Continuwuity to request the `openid` scope. Other identity providers may not require this step.
```sh
kanidm system oauth2 update-scope-map c10y idm_all_persons openid
```
Find the client secret that was generated. Other identity providers may show this information in their web UI.
```sh
kanidm system oauth2 show-basic-secret c10y
d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr
```
Configure Continuwuity with the client ID, client secret, and discovery URL. kanidm has a different discovery URL for each client, but other identity providers may have a single discovery URL at the root of their domain.
```toml
[global.oauth.oidc]
# `/.well-known/openid-configuration` will be appended automatically
discovery_url = "https://idm.example.com/oauth2/openid/c10y"
# This may be randomly generated by your identity provider. kanidm requires
# you to set it manually when you create the application.
client_id = "c10y"
# From the previous step
client_secret = "d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr"
```
Finally, restart Continuwuity, and log out and back in again. Your client should prompt you to continue in your web browser and open a webpage with the Continuwuity logo that allows you to continue in your identity provider. Once you log in successfully, you will be prompted to choose a user ID -- to link your existing account, enter its user ID, and then your old password when prompted.
Continuwuity offers several additional configuration options to tweak its integration with your identity provider. Review the `[global.oauth.oidc]` section towards the bottom of the [reference configuration](../reference/config) for a complete list of options and documentation.
-28
View File
@@ -32,33 +32,5 @@ beforeFeatures:
link: https://matrix.org/docs/matrix-concepts/elements-of-matrix/
buttonText: Read the Guide
features:
- title: 🚀 High Performance
details: Built with Rust for exceptional speed and efficiency. Designed to run smoothly even on modest hardware.
- title: 🔒 Secure by Default
details: Memory-safe Rust implementation with built-in security features to protect your communication.
- title: 🌐 Matrix Protocol
details: Fully compatible with the Matrix ecosystem. Connect with users across the federated network.
- title: 🛠️ Community Maintained
details: Actively developed by a dedicated community of Matrix enthusiasts and contributors.
- title: 📦 Easy to Deploy
details: Multiple deployment options including Docker, NixOS, and traditional package managers.
- title: 🔌 Appservice Support
details: Bridge to other platforms like Discord, Telegram, and more with Matrix appservices.
doc: false
---
## What is Continuwuity?
Continuwuity is a Matrix homeserver.
Matrix is an open chat network that lets anyone talk to anyone, no matter what server or address they use - sort of like email.
Continuwuity receives and keeps track of all your messages, and delivers what you send to the right people.
## Why is Continuwuity different?
Continuwuity is light and fast, using a fraction of the memory of other major homeservers. It's also simple to set up, and secure by default.
We are a community run project, filled with diverse and friendly people. Everything is built by people who care about the project volunteering their free time.
+86 -70
View File
@@ -1,98 +1,114 @@
<div align="center">
<img src="/assets/logo.svg" width="150"/>
# Continuwuity
## A community-driven [Matrix](https://matrix.org/) homeserver in Rust
</div>
[![Chat on Matrix](https://img.shields.io/matrix/continuwuity%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix)](https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org) [![Join the space](https://img.shields.io/matrix/space%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix&label=space)](https://matrix.to/#/#space:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org)
## What is Continuwuity?
[continuwuity] is a Matrix homeserver written in Rust.
It's the official community continuation of the [conduwuit](https://github.com/girlbossceo/conduwuit) homeserver.
Continuwuity is a Matrix homeserver. [Matrix] is an open chat network that lets anyone talk to anyone, no matter what server or address they use, like email.
[![forgejo.ellis.link](https://img.shields.io/badge/Ellis%20Git-main+packages-green?style=flat&logo=forgejo&labelColor=fff)](https://forgejo.ellis.link/continuwuation/continuwuity) [![Stars](https://forgejo.ellis.link/continuwuation/continuwuity/badges/stars.svg?style=flat)](https://forgejo.ellis.link/continuwuation/continuwuity/stars) [![Issues](https://forgejo.ellis.link/continuwuation/continuwuity/badges/issues/open.svg?style=flat)](https://forgejo.ellis.link/continuwuation/continuwuity/issues?state=open) [![Pull Requests](https://forgejo.ellis.link/continuwuation/continuwuity/badges/pulls/open.svg?style=flat)](https://forgejo.ellis.link/continuwuation/continuwuity/pulls?state=open)
Continuwuity receives and keeps track of all your messages, and delivers what you send to the right people.
[![GitHub](https://img.shields.io/badge/GitHub-mirror-blue?style=flat&logo=github&labelColor=fff&logoColor=24292f)](https://github.com/continuwuity/continuwuity) [![Stars](https://img.shields.io/github/stars/continuwuity/continuwuity?style=flat)](https://github.com/continuwuity/continuwuity/stargazers)
[Matrix]: https://matrix.org
[![GitLab](https://img.shields.io/badge/GitLab-mirror-blue?style=flat&logo=gitlab&labelColor=fff)](https://gitlab.com/continuwuity/continuwuity) [![Stars](https://img.shields.io/gitlab/stars/continuwuity/continuwuity?style=flat)](https://gitlab.com/continuwuity/continuwuity/-/starrers)
## Why is Continuwuity different?
[![Codeberg](https://img.shields.io/badge/Codeberg-mirror-2185D0?style=flat&logo=codeberg&labelColor=fff)](https://codeberg.org/continuwuity/continuwuity) [![Stars](https://codeberg.org/continuwuity/continuwuity/badges/stars.svg?style=flat)](https://codeberg.org/continuwuity/continuwuity/stars)
Continuwuity is light and fast, using a fraction of the resources of other major homeservers. It's also simple to set up, and secure by default.
## Why does this exist?
We are a community-run project, made up of friendly and diverse people. Everything is built by people who care about the project volunteering their free time.
The original conduwuit project has been archived and is no longer maintained. Rather than letting this Rust-based Matrix homeserver disappear, a group of community contributors have forked the project to continue its development, fix outstanding issues, and add new features.
## Deploying Continuwuity
We aim to provide a stable, well-maintained alternative for current conduwuit users and welcome newcomers seeking a lightweight, efficient Matrix homeserver.
Head over to the [**Deploying chapter**](./deploying.mdx) to get started.
## Who are we?
## Try it out!
We are a group of Matrix enthusiasts, developers and system administrators who have used conduwuit and believe in its potential. Our team includes both previous
contributors to the original project and new developers who want to help maintain and improve this important piece of Matrix infrastructure.
If you want to try it out as a user, we have some [partnered homeservers](./community/ops-guidelines.mdx) you can use:
We operate as an open community project, welcoming contributions from anyone interested in improving continuwuity.
**`federated.nexus`** - A community resource hosting multiple FOSS (especially federated) services.
- Go to https://federated.nexus, click on "Apply to Join", and follow the prompts.
- Once your request has been accepted, you will receive an email with your username and password, which you can use to sign in from any Matrix client.
- Remember to change your password after logging in!
## What is Matrix?
**`continuwuity.rocks`** - the demo server, run by us.
- Sign up using any Matrix client, or via this [convenient link][cinny-register] for Cinny.
[Matrix](https://matrix.org) is an open, federated, and extensible network for
decentralized communication. Users from any Matrix homeserver can chat with users from all
other homeservers over federation. Matrix is designed to be extensible and built on top of.
You can even use bridges such as Matrix Appservices to communicate with users outside of Matrix, like a community on Discord.
[cinny-register]: https://app.cinny.in/register/continuwuity.rocks
## What are the project's goals?
## Donate to us {#donate}
continuwuity aims to:
If you like what we're doing, consider donating to our Open Collective via the button below!
- Maintain a stable, reliable Matrix homeserver implementation in Rust
- Improve compatibility and specification compliance with the Matrix protocol
- Fix bugs and performance issues from the original conduwuit
- Add missing features needed by homeserver administrators
- Provide comprehensive documentation and easy deployment options
- Create a sustainable development model for long-term maintenance
- Keep a lightweight, efficient codebase that can run on modest hardware
<div class="no-zoom" align="center">
<br/>
<a href="https://opencollective.com/continuwuity" target="_blank">
<img src="https://opencollective.com/webpack/donate/button@2x.png?color=blue" width="250"/>
</a>
</div>
## Can I try it out?
You can also donate individually to each of the maintainers
Check out the [documentation](https://continuwuity.org) for installation instructions.
- Nex: https://timedout.uk/donate.html
If you want to try it out as a user, we have some partnered homeservers you can use:
* You can head over to [https://federated.nexus](https://federated.nexus/) in your browser.
* Hit the `Apply to Join` button. Once your request has been accepted, you will receive an email with your username and password.
* Head over to [https://app.federated.nexus](https://app.federated.nexus/) and you can sign in there, or use any other matrix chat client you wish elsewhere.
* Your username for matrix will be in the form of `@username:federated.nexus`, however you can simply use the `username` part to log in. Your password is your password.
- Jade: https://jade.ellis.link/sponsors
* There's also [https://continuwuity.rocks/](https://continuwuity.rocks/). You can register a new account using Cinny via [this convenient link](https://app.cinny.in/register/continuwuity.rocks), or you can use Element or another matrix client *that supports registration*.
## What are we working on?
We're working our way through all of the issues in the [Forgejo project](https://forgejo.ellis.link/continuwuation/continuwuity/issues).
- [Packaging & availability in more places](https://forgejo.ellis.link/continuwuation/continuwuity/issues/747)
- [Appservices bugs & features](https://forgejo.ellis.link/continuwuation/continuwuity/issues?q=&type=all&state=open&labels=178&milestone=0&assignee=0&poster=0)
- [Improving compatibility and spec compliance](https://forgejo.ellis.link/continuwuation/continuwuity/issues?labels=119)
- Automated testing
- [Admin API](https://forgejo.ellis.link/continuwuation/continuwuity/issues/748)
- [Policy-list controlled moderation](https://forgejo.ellis.link/continuwuation/continuwuity/issues/750)
## Can I migrate my data from x?
- **Conduwuit**: Yes
- **Conduit**: No, database is now incompatible
- **Grapevine**: No, database is now incompatible
- **Dendrite**: No
- **Synapse**: No
We haven't written up a guide on migrating from incompatible homeservers yet. Reach out to us if you need to do this!
## How can I deploy my own?
- [Deployment options](deploying)
If you want to connect an appservice to continuwuity, take a look at the
[appservices documentation](appservices).
## How can I contribute?
See the [contributor's guide](development/contributing)
- Ginger: https://github.com/sponsors/gingershaped
## Contact
Join our [Matrix room](https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org) and [space](https://matrix.to/#/#space:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org) to chat with us about the project!
[continuwuity]: https://forgejo.ellis.link/continuwuation/continuwuity
<div class="no-zoom" align="center">
[![Chat on Matrix][matrix-chat-badge]][matrix-chatroom]
[![Join the space][matrix-space-badge]][matrix-space]
</div>
[matrix-chat-badge]: https://img.shields.io/matrix/continuwuity%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix
[matrix-chatroom]: https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org
[matrix-space-badge]: https://img.shields.io/matrix/space%3Acontinuwuity.org?server_fqdn=matrix.continuwuity.org&fetchMode=summary&logo=matrix&label=space
[matrix-space]: https://matrix.to/#/#space:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org
Our source code and mirrors can be accessed through these buttons:
<div class="no-zoom" align="center">
[![forgejo.ellis.link][forge-badge]][forge-link]
[![Releases][forge-releases-badge]][forge-releases-link]
[![Stars][forge-stars-badge]][forge-stars-link]
[![Issues][forge-issues-badge]][forge-issues-link]
[![Pull Requests][forge-pulls-badge]][forge-pulls-link]
[![GitHub][github-badge]][github-link] ![Stars][github-stars-badge] -
[![Codeberg][codeberg-badge]][codeberg-link] [![Stars][codeberg-stars-badge]][codeberg-stars-link] -
[![GitLab][gitlab-badge]][gitlab-link] [![Stars][gitlab-stars-badge]][gitlab-stars-link]
</div>
[forge-badge]: https://img.shields.io/badge/Ellis%20Git-main+packages-green?style=flat&logo=forgejo&labelColor=fff
[forge-link]: https://forgejo.ellis.link/continuwuation/continuwuity
[forge-releases-badge]: https://forgejo.ellis.link/continuwuation/continuwuity/badges/release.svg?style=flat&label=Latest%20release&labelColor=fff&color=green
[forge-releases-link]: https://forgejo.ellis.link/continuwuation/continuwuity
[forge-stars-badge]: https://forgejo.ellis.link/continuwuation/continuwuity/badges/stars.svg?style=flat&labelColor=fff&color=8a5cd0
[forge-stars-link]: https://forgejo.ellis.link/continuwuation/continuwuity/stars
[forge-issues-badge]: https://forgejo.ellis.link/continuwuation/continuwuity/badges/issues/open.svg?style=flat&labelColor=fff&color=8a5cd0
[forge-issues-link]: https://forgejo.ellis.link/continuwuation/continuwuity/issues?state=open
[forge-pulls-badge]: https://forgejo.ellis.link/continuwuation/continuwuity/badges/pulls/open.svg?style=flat&labelColor=fff&color=8a5cd0
[forge-pulls-link]: https://forgejo.ellis.link/continuwuation/continuwuity/pulls?state=open
[github-badge]: https://img.shields.io/badge/GitHub-mirror-blue?style=flat&logo=github&labelColor=fff&logoColor=24292f
[github-link]: https://github.com/continuwuity/continuwuity
[github-stars-badge]: https://img.shields.io/github/stars/continuwuity/continuwuity?style=flat&logo=github
[gitlab-badge]:https://img.shields.io/badge/GitLab-mirror-blue?style=flat&logo=gitlab&labelColor=fff
[gitlab-link]: https://gitlab.com/continuwuity/continuwuity
[gitlab-stars-badge]: https://img.shields.io/gitlab/stars/continuwuity/continuwuity?style=flat
[gitlab-stars-link]: https://gitlab.com/continuwuity/continuwuity/-/starrers
[codeberg-badge]:https://img.shields.io/badge/Codeberg-mirror-2185D0?style=flat&logo=codeberg&labelColor=fff
[codeberg-link]: https://codeberg.org/continuwuity/continuwuity
[codeberg-stars-badge]: https://codeberg.org/continuwuity/continuwuity/badges/stars.svg?style=flat
[codeberg-stars-link]: https://codeberg.org/continuwuity/continuwuity/stars
@@ -6,10 +6,10 @@
"message": "Welcome to Continuwuity! Important announcements about the project will appear here."
},
{
"id": 20,
"id": 21,
"mention_room": true,
"date": "2026-09-16",
"message": "[Continuwuity 26.9.0](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v26.9.0) has just been released - this update features a bunch of bug fixes, and some bandwidth saving improvements for sliding sync.\n\nAny questions? Ask in our [support room](https://matrix.to/#/#continuwuity:continuwuity.org)!"
"date": "2026-09-29",
"message": "[Continuwuity 26.9.1](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v26.9.1) has just been released - this update features a fix for a **critical** security issue, please read the release notes for more information."
}
]
}
+7 -3
View File
@@ -2,7 +2,7 @@
This document provides information about downloading and deploying the Debian package. You can also use this guide for other deb-based distributions such as Ubuntu.
### Installation
## Installation
To add the Continuwuation apt repository:
```bash
@@ -26,16 +26,20 @@ The `continuwuity` package conflicts with the old `conduwuit` package and will r
See the [generic deployment guide](/deploying/generic.mdx) for additional information about using the Debian package.
### Configuration
## Configuration
After installation, Continuwuity places the example configuration at `/etc/conduwuit/conduwuit.toml` as the default configuration file. The configuration file indicates which settings you must change before starting the service.
You can customize additional settings by uncommenting and modifying the configuration options in `/etc/conduwuit/conduwuit.toml`.
### Running
## Running
The package uses the `conduwuit.service` systemd unit file to start and stop Continuwuity. The binary installs at `/usr/bin/conduwuit`.
By default, this package assumes that Continuwuity runs behind a reverse proxy. The default configuration options apply (listening on `localhost` and TCP port `6167`). Matrix federation requires a valid domain name and TLS. To federate properly, you must set up TLS certificates and certificate renewal.
For information about setting up a reverse proxy and TLS, consult online documentation and guides. The [generic deployment guide](/deploying/generic.md#setting-up-the-reverse-proxy) documents Caddy, which is the most user-friendly option for reverse proxy configuration.
## What's next?
Navigate to [Post-installation](/deploying#post-installation) for next steps.
+9 -1
View File
@@ -11,6 +11,10 @@ export default defineConfig({
light: '/assets/logo.svg',
dark: '/assets/logo.svg',
},
// Use `.no-zoom` class to disable image zooms
mediumZoom: {
selector: '.rspress-doc :not(.no-zoom *) > img',
},
markdown: {
link: {
checkDeadLinks: {
@@ -26,7 +30,8 @@ export default defineConfig({
'/advanced/delegated.docker-compose.for-traefik.yml',
'/advanced/delegated.docker-compose.with-traefik.yml',
'/calls/livekit.docker-compose.with-caddy-labels.yml',
'/calls/livekit.nginx.conf'
'/calls/livekit.nginx.conf',
'CONTRIBUTING.md'
]
},
},
@@ -92,6 +97,9 @@ export default defineConfig({
}, {
from: "^/source(|_code)$",
to: "https://forgejo.ellis.link/continuwuation/continuwuity",
}, {
from: "^/(CONTRIBUTING.md|contributing)$",
to: "/development/contributing"
}
]
})],
+32 -11
View File
@@ -8,13 +8,15 @@ use std::{
use conduwuit::{
Err, Result, at, debug_error, err, info,
matrix::{
Event,
Event, StateKey,
pdu::{PduEvent, PduId, RawPduId},
},
state_res::EventTypeExt,
trace, utils,
utils::{
stream::{IterStream, ReadyExt},
string::EMPTY,
to_canonical_object,
},
warn,
};
@@ -27,7 +29,9 @@ use resolvematrix::{
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId,
OwnedRoomOrAliasId, OwnedServerName, RoomId, RoomVersionId, UInt,
api::federation::event::get_room_state, events::AnyStateEvent, serde::Raw,
api::federation::event::get_room_state,
events::{AnyStateEvent, StateEventType},
serde::Raw,
};
use service::rooms::{
short::{ShortEventId, ShortRoomId},
@@ -533,19 +537,36 @@ impl crate::Context<'_> {
.collect()
.await;
let pdus: Vec<CanonicalJsonObject> = state_ids
let mut pdus: HashMap<(StateEventType, StateKey), CanonicalJsonObject> = state_ids
.iter()
.try_stream()
.and_then(|id| self.services.rooms.timeline.get_pdu_json(id))
.try_stream::<conduwuit::Error>()
.and_then(|id| async {
let pdu_json = self.services.rooms.timeline.get_pdu_json(id).await?;
let event_type = pdu_json
.get("type")
.and_then(CanonicalJsonValue::as_str)
.expect("event type must be present in events");
let state_key = pdu_json
.get("state_key")
.and_then(CanonicalJsonValue::as_str)
.expect("state keys must be present for events in the room state");
Ok(((event_type.into(), state_key.into()), pdu_json))
})
.try_collect()
.await?;
let json = serde_json::to_string_pretty(&pdus).map_err(|e| {
err!(Database(
"Failed to convert room state events to pretty JSON, possible invalid room \
state events in our database {e}",
))
})?;
let pdu = self.services.rooms.timeline.get_pdu(&event_id).await?;
if let Some(state_key) = pdu.state_key() {
pdus.insert(pdu.kind().with_state_key(state_key), to_canonical_object(pdu)?);
}
let json =
serde_json::to_string_pretty(&pdus.values().collect::<Vec<_>>()).map_err(|e| {
err!(Database(
"Failed to convert room state events to pretty JSON, possible invalid room \
state events in our database {e}",
))
})?;
let out = format!("```json\n{json}\n```");
self.write_str(&out).await
+3
View File
@@ -4,6 +4,9 @@ use service::registration_tokens::TokenExpires;
impl crate::Context<'_> {
pub(super) async fn issue_registration_token(&self, expires: super::TokenExpires) -> Result {
if !self.services.config.allow_registration {
return Err!("Registration has been disabled on this homeserver.");
}
let expires = {
if expires.immortal {
None
+3
View File
@@ -1083,6 +1083,9 @@ impl crate::Context<'_> {
pub(super) async fn change_email(&self, user_id: String, email: Option<String>) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?;
if matches!(self.services.users.status(&user_id).await, AccountStatus::NotFound) {
return Err!("This account does not exist.");
}
let Ok(new_email) = email.map(Address::try_from).transpose() else {
return Err!("Invalid email address.");
};
+1
View File
@@ -1 +1,2 @@
pub mod rooms;
pub mod users;
+1 -1
View File
@@ -6,7 +6,7 @@ use ruminuwuity::admin::continuwuity::rooms;
use crate::{Ruma, client::leave_room};
/// # `PUT /_continuwuity/admin/rooms/{roomID}/ban`
/// # `PUT /_continuwuity/admin/v1/rooms/{roomID}/ban`
///
/// Bans or unbans a room.
pub(crate) async fn ban_room(
+1 -1
View File
@@ -6,7 +6,7 @@ use ruminuwuity::admin::continuwuity::rooms;
use crate::Ruma;
/// # `GET /_continuwuity/admin/rooms/list`
/// # `GET /_continuwuity/admin/v1/rooms/list`
///
/// Lists all rooms known to this server, excluding banned ones.
pub(crate) async fn list_rooms(
+69
View File
@@ -0,0 +1,69 @@
use axum::extract::State;
use conduwuit::{Err, error};
use ruma::{api::client::profile::PropagateTo, profile::ProfileFieldValue};
use ruminuwuity::admin::continuwuity::users::create::v1::{Request, Response};
use service::users::{HashedPassword, ProfileFieldChange};
use crate::router::Ruma;
/// # `POST /_continuwuity/admin/v1/users`
///
/// Creates a new user on the homeserver.
pub(crate) async fn create_user(
State(services): State<crate::State>,
body: Ruma<Request>,
) -> conduwuit::Result<Response> {
let sender_user = body.identity.expect_sender_user()?;
if !services.users.is_admin(sender_user).await {
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
}
if !services.globals.user_is_local(&body.user_id) {
return Err!(Request(InvalidParam("User ID does not belong to this server.")));
}
if services.users.status(&body.user_id).await.is_found() {
return Err!(Request(UserInUse("An account with this user ID already exists.")));
}
services
.users
.create_local_account(
&body.user_id,
body.password
.as_ref()
.and_then(|raw| HashedPassword::new(raw).ok()),
None,
None,
None,
)
.await?;
if body.locked {
services
.users
.lock_account(&body.user_id, sender_user)
.await;
}
if body.suspended {
services
.users
.suspend_account(&body.user_id, sender_user)
.await;
}
for (key, value) in body.profile.clone().unwrap_or_default() {
services
.users
.set_profile_field(
&body.user_id,
ProfileFieldChange::Set(ProfileFieldValue::new(&key, value)?),
PropagateTo::All,
)
.await
.inspect_err(|e| error!(error=?e, %key, "Failed to set profile field"))
.ok();
}
if body.admin {
services.admin.make_user_admin(&body.user_id).await?;
}
Ok(Response::default())
}
+99
View File
@@ -0,0 +1,99 @@
use std::collections::BTreeMap;
use axum::extract::State;
use conduwuit::{
Err,
utils::{TryFutureExtExt, stream::WidebandExt},
};
use futures::StreamExt;
use ruminuwuity::admin::continuwuity::users::list::v1::{QueryFilter, Request, Response, User};
use service::users::AccountStatus;
use crate::router::Ruma;
/// # `GET /_continuwuity/admin/v1/users`
///
/// Lists users on this homeserver
pub(crate) async fn list_users(
State(services): State<crate::State>,
body: Ruma<Request>,
) -> conduwuit::Result<Response> {
if !services
.users
.is_admin(body.identity.expect_sender_user()?)
.await
{
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
}
let limit = body.limit.unwrap_or(100);
let offset = limit.saturating_mul(body.page.unwrap_or_default());
let users = services
.users
.stream_local_users()
.wide_filter_map(|user_id| {
let body = &body;
async move {
let status = services.users.status(&user_id).await;
assert_ne!(
status,
AccountStatus::NotFound,
"Not found users should not appear in stream_local_users"
);
let (deactivated, locked, suspended, admin) = tokio::join!(
std::future::ready(status == AccountStatus::Deactivated),
services.users.is_locked(&user_id).unwrap_or_default(),
services.users.is_suspended(&user_id).unwrap_or_default(),
services.users.is_admin(&user_id),
);
// Exclude deactivated accounts by default
if !deactivated && body.active == Some(QueryFilter::Exclude) {
return None;
}
if deactivated
&& body
.deactivated
.as_ref()
.is_none_or(|d| *d == QueryFilter::Include)
{
return None;
}
// Exclude locked accounts by default
if locked && body.locked != Some(QueryFilter::Include) {
return None;
}
// Include suspended accounts by default
if suspended && body.suspended == Some(QueryFilter::Exclude) {
return None;
}
// Include admins by default
if admin && body.admin == Some(QueryFilter::Exclude) {
return None;
}
Some((user_id, deactivated, suspended, locked, admin))
}
})
.skip(offset)
.wide_then(|(user_id, deactivated, suspended, locked, admin)| async move {
let (displayname, avatar_url) = tokio::join!(
services.users.displayname(&user_id).ok(),
services.users.avatar_url(&user_id).ok(),
);
let user = User {
displayname,
avatar_url,
suspended,
locked,
deactivated,
admin,
};
(user_id, user)
})
.take(limit)
.collect::<BTreeMap<_, _>>()
.await;
Ok(Response::new(users))
}
+3
View File
@@ -0,0 +1,3 @@
pub mod create;
pub mod list;
pub mod rooms;
+134
View File
@@ -0,0 +1,134 @@
use axum::extract::State;
use conduwuit::{
Err, Event, at,
utils::{IterStream, ReadyExt, TryFutureExtExt, stream::WidebandExt},
};
use futures::StreamExt;
use ruma::events::room::member::MembershipState;
use ruminuwuity::admin::continuwuity::users::rooms::v1::{Request, Response, RoomInfo};
use serde::Deserialize;
use crate::router::Ruma;
/// # `GET /_continuwuity/admin/v1/users/{user_id}/rooms`
///
/// Lists the memberships of a user on this server.
pub(crate) async fn list_user_rooms(
State(services): State<crate::State>,
body: Ruma<Request>,
) -> conduwuit::Result<Response> {
if !services
.users
.is_admin(body.identity.expect_sender_user()?)
.await
{
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
}
let limit = body.limit.unwrap_or(100).try_into()?;
let offset = body
.limit
.unwrap_or(100)
.saturating_mul(body.page.unwrap_or_default())
.try_into()?;
let room_ids: Vec<_> = match body.state {
| MembershipState::Join =>
services
.rooms
.state_cache
.rooms_joined(&body.user_id)
.skip(offset)
.take(limit)
.collect()
.await,
| MembershipState::Invite =>
services
.rooms
.state_cache
.rooms_invited(&body.user_id)
.skip(offset)
.take(limit)
.map(at!(0))
.collect()
.await,
| MembershipState::Knock =>
services
.rooms
.state_cache
.rooms_knocked(&body.user_id)
.skip(offset)
.take(limit)
.map(at!(0))
.collect()
.await,
| MembershipState::Leave =>
services
.rooms
.state_cache
.rooms_left(&body.user_id)
.skip(offset)
.take(limit)
.ready_filter_map(|(room_id, pdu)| {
pdu.is_some_and(|pdu| {
pdu.get_content::<ExtractMembership>()
.expect("membership PDU must have a membership field")
.membership
== MembershipState::Leave
})
.then_some(room_id)
})
.collect()
.await,
| MembershipState::Ban =>
services
.rooms
.state_cache
.rooms_left(&body.user_id)
.skip(offset)
.take(limit)
.ready_filter_map(|(room_id, pdu)| {
pdu.is_some_and(|pdu| {
pdu.get_content::<ExtractMembership>()
.expect("membership PDU must have a membership field")
.membership
== MembershipState::Ban
})
.then_some(room_id)
})
.collect()
.await,
| _ => return Err!(Request(InvalidParam("Unknown membership kind: {:?}", body.state))),
};
let resp = room_ids
.into_iter()
.stream()
.wide_then(|room_id| async move {
let (name, avatar, alias, members) = tokio::join!(
services.rooms.state_accessor.get_name(&room_id).ok(),
services.rooms.state_accessor.get_avatar(&room_id),
services
.rooms
.state_accessor
.get_canonical_alias(&room_id)
.ok(),
services.rooms.state_cache.room_members(&room_id).count(),
);
(room_id, RoomInfo {
name,
avatar_url: avatar.into_option().and_then(|a| a.url),
canonical_alias: alias,
member_count: members.try_into().unwrap_or(0),
})
})
.collect()
.await;
Ok(Response::new(resp))
}
#[derive(Deserialize)]
struct ExtractMembership {
pub membership: MembershipState,
}
+10 -2
View File
@@ -267,11 +267,19 @@ pub(crate) async fn get_public_rooms_filtered_helper(
summary.into()
})
.ready_filter_map(|chunk: PublicRoomsChunk| {
if !filter.room_types.is_empty() && !filter.room_types.contains(&RoomTypeFilter::from(chunk.room_type.clone())) {
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(query) = filter
.generic_search_term
.as_ref()
.map(|q| q.to_lowercase())
{
if let Some(name) = &chunk.name {
if name.to_lowercase().contains(&query) {
return Some(chunk);
+3 -18
View File
@@ -523,22 +523,7 @@ where
for (server, response) in futures {
match response {
| Ok(response) => {
let is_wanted = |user_id: &UserId| {
user_id.server_name() == server && device_keys_input.contains_key(user_id)
};
let filtered_master_keys = response
.master_keys
.into_iter()
.filter(|(user_id, _)| is_wanted(user_id));
let filtered_self_signing_keys = response
.self_signing_keys
.into_iter()
.filter(|(user_id, _)| is_wanted(user_id));
let filtered_device_keys = response
.device_keys
.into_iter()
.filter(|(user_id, _)| is_wanted(user_id));
for (user, master_key) in filtered_master_keys {
for (user, master_key) in response.master_keys {
let (master_key_id, mut master_key) = parse_master_key(&user, &master_key)?;
if let Ok(our_master_key) = services
@@ -564,8 +549,8 @@ where
}
}
self_signing_keys.extend(filtered_self_signing_keys);
device_keys.extend(filtered_device_keys);
self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys);
},
| Err(e) => {
failures.insert(server.to_string(), json!({ "error": e.to_string() }));
+4 -1
View File
@@ -55,5 +55,8 @@ fn oauth_router() -> Router<crate::State> {
.route(concat!("/", JWKS_URI_PATH), get(async || Json(json!({"keys": []}))))
.route(concat!("/", TOKEN_PATH), post(token::token_route))
.route(concat!("/", TOKEN_REVOKE_PATH), post(token::revoke_token_route))
.route(concat!("/", DEVICE_AUTHORIZATION_PATH), post(device::device_authorization_route))
.route(
concat!("/", DEVICE_AUTHORIZATION_PATH),
post(device::device_authorization_route),
)
}
+170 -155
View File
@@ -1,18 +1,23 @@
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use axum::extract::State;
use conduwuit::{
Err, Error, Result, debug, debug_info, err, info,
matrix::{StateKey, pdu::PartialPdu},
trace, warn,
trace,
utils::to_canonical_object,
warn,
};
use conduwuit_service::{Services, appservice::RegistrationInfo};
use futures::FutureExt;
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, Int, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId,
OwnedUserId, RoomAliasId, RoomId, RoomVersionId, UserId,
OwnedUserId, RoomAliasId, RoomId,
api::{
client::room::{self, create_room},
client::room::{
self,
create_room::{self, RoomPowerLevelsContentOverride, v3::CreationContent},
},
error::ErrorKind::Forbidden,
},
assign,
@@ -33,13 +38,24 @@ use ruma::{
},
int,
room_version_rules::{AuthorizationRules, RoomIdFormatVersion},
serde::{JsonObject, Raw},
serde::Raw,
};
use ruminuwuity::invite_permission_config::FilterLevel;
use serde_json::{json, value::to_raw_value};
use serde::Deserialize;
use serde_json::value::to_raw_value;
use crate::{Ruma, client::invite_helper};
// We use this to keep around extra data in the `creation_content`
// while still parsing and validating keys that we care about.
#[derive(Deserialize, Default)]
struct FullCreationContent {
#[serde(flatten)]
creation_content: CreationContent,
#[serde(flatten)]
extra_create_keys: CanonicalJsonObject,
}
/// # `POST /_matrix/client/v3/createRoom`
///
/// Creates a new room.
@@ -153,6 +169,12 @@ pub(crate) async fn create_room_route(
return Err!(Request(Forbidden("Publishing rooms to the room directory is not allowed")));
}
// Figure out preset. We need it for preset specific events
let preset = body.preset.clone().unwrap_or(match &body.visibility {
| room::Visibility::Public => RoomPreset::PublicChat,
| _ => RoomPreset::PrivateChat, // Room visibility should not be custom
});
let mut invitees = BTreeSet::new();
for recipient_user in &body.invite {
@@ -191,54 +213,67 @@ pub(crate) async fn create_room_route(
| _ => None,
};
let create_content = match &body.creation_content {
| Some(content) => {
use RoomVersionId::*;
let FullCreationContent { creation_content, mut extra_create_keys } = body
.creation_content
.as_ref()
.map(Raw::deserialize_as_unchecked::<FullCreationContent>)
.transpose()
.map_err(|e| err!(Request(BadJson(error!("Failed to parse creation content: {e}")))))?
.unwrap_or_default();
let mut content = content
.deserialize_as_unchecked::<CanonicalJsonObject>()
.map_err(|e| {
err!(Request(BadJson(error!(
"Failed to deserialise content as canonical JSON: {e}"
))))
})?;
match room_version {
| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 => {
content.insert(
"creator".into(),
json!(&sender_user).try_into().map_err(|e| {
err!(Request(BadJson(debug_error!("Invalid creation content: {e}"))))
})?,
);
},
| _ => {
// V11+ removed the "creator" key
},
}
content.insert(
"room_version".into(),
json!(room_version.as_str())
.try_into()
.map_err(|e| err!(Request(BadJson("Invalid creation content: {e}"))))?,
);
content
},
| None => {
use RoomVersionId::*;
let content = match room_version {
| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 =>
RoomCreateEventContent::new_v1(sender_user.to_owned()),
| _ => RoomCreateEventContent::new_v11(),
};
let mut content =
serde_json::from_str::<CanonicalJsonObject>(to_raw_value(&content)?.get())?;
content.insert("room_version".into(), json!(room_version.as_str()).try_into()?);
content
},
let mut create_event_content = if room_version_rules.authorization.use_room_create_sender {
RoomCreateEventContent::new_v11()
} else {
RoomCreateEventContent::new_v1(sender_user.to_owned())
};
let mut privileged_creators = HashSet::new();
create_event_content.federate = creation_content.federate;
create_event_content.predecessor = creation_content.predecessor;
create_event_content.room_type = creation_content.room_type;
create_event_content.room_version = room_version.clone();
if room_version_rules.authorization.additional_room_creators {
create_event_content.additional_creators = creation_content.additional_creators;
// If we're making a trusted private chat, add the invitees as
// additional creators
if preset == RoomPreset::TrustedPrivateChat {
create_event_content
.additional_creators
.extend(invitees.iter().cloned());
}
// Make sure the primary creator of the room isn't in the additional
// creator list
if create_event_content
.additional_creators
.iter()
.any(|user| user == sender_user)
{
return Err!(Request(InvalidParam(
"The primary creator of the room may not also be an additional creator."
)));
}
// Sort and deduplicate additional creators to avoid any funny business
create_event_content.additional_creators.sort();
create_event_content.additional_creators.dedup();
}
// Track privileged creators so we can remove them from PLs later
if room_version_rules
.authorization
.explicitly_privilege_room_creators
{
privileged_creators.insert(sender_user.to_owned());
if room_version_rules.authorization.additional_room_creators {
privileged_creators.extend(create_event_content.additional_creators.iter().cloned());
}
}
let state_lock = match room_id.clone() {
| Some(room_id) => {
let _short_id = services
@@ -272,13 +307,20 @@ pub(crate) async fn create_room_route(
.map(MilliSecondsSinceUnixEpoch)
};
let mut create_event_content = to_canonical_object(create_event_content)
.expect("should be able to serialize create event content");
// `extra_create_keys` can't clobber any important fields because we
// already pulled them out into `create_event_content`
create_event_content.append(&mut extra_create_keys);
let create_event_id = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
event_type: TimelineEventType::RoomCreate,
content: to_raw_value(&create_content)?,
content: to_raw_value(&create_event_content)?,
state_key: Some(StateKey::new()),
timestamp: custom_origin_server_ts,
..Default::default()
@@ -289,6 +331,7 @@ pub(crate) async fn create_room_route(
)
.boxed()
.await?;
trace!("Created room create event with ID {}", &create_event_id);
let room_id = match room_id.clone() {
| Some(room_id) => room_id,
@@ -330,64 +373,27 @@ pub(crate) async fn create_room_route(
.await?;
// 3. Power levels
let mut power_levels_to_grant = BTreeMap::new();
// Figure out preset. We need it for preset specific events
let preset = body.preset.clone().unwrap_or(match &body.visibility {
| room::Visibility::Public => RoomPreset::PublicChat,
| _ => RoomPreset::PrivateChat, // Room visibility should not be custom
});
// If this room version doesn't privilege creators, grant PLs to them
if !room_version_rules
.authorization
.explicitly_privilege_room_creators
{
power_levels_to_grant.insert(sender_user.to_owned(), int!(100));
let mut power_levels_to_grant = BTreeMap::from_iter([(sender_user.to_owned(), int!(100))]);
let mut creators: Vec<OwnedUserId> = vec![sender_user.to_owned()];
if preset == RoomPreset::TrustedPrivateChat {
for recipient_user in invitees.iter().cloned() {
if room_version_rules
.authorization
.explicitly_privilege_room_creators
{
creators.push(recipient_user);
} else {
if preset == RoomPreset::TrustedPrivateChat {
for recipient_user in invitees.iter().cloned() {
power_levels_to_grant.insert(recipient_user, int!(100));
}
}
}
// Do we care about additional_creators?
if room_version_rules
.authorization
.explicitly_privilege_room_creators
{
// Have they been specified?
if let Some(additional_creators) = create_content.get("additional_creators") {
// Are they a real array?
if let Some(additional_creators) = additional_creators.as_array() {
// Iterate through them
for creator in additional_creators {
// Are they a string?
if let Some(creator) = creator.as_str() {
// Do they parse into a real user ID?
if let Ok(creator) = UserId::parse(creator) {
// Add them to the power levels and creators
creators.push(creator);
}
}
}
}
}
} else {
power_levels_to_grant.insert(sender_user.to_owned(), int!(100));
creators.clear(); // If this vec is not empty, default_power_levels_content will
// treat this as a v12 room
}
let power_levels_content = default_power_levels_content(
body.power_level_content_override
.as_ref()
.map(Raw::cast_ref),
body.power_level_content_override.as_ref(),
&body.visibility,
power_levels_to_grant,
creators,
privileged_creators,
&room_version_rules.authorization,
)?;
@@ -619,74 +625,83 @@ pub(crate) async fn create_room_route(
}
/// creates the power_levels_content for the PDU builder
#[allow(clippy::or_fun_call)]
fn default_power_levels_content(
power_level_content_override: Option<&Raw<RoomPowerLevelsEventContent>>,
power_level_content_override: Option<&Raw<RoomPowerLevelsContentOverride>>,
visibility: &room::Visibility,
users: BTreeMap<OwnedUserId, Int>,
creators: Vec<OwnedUserId>,
mut users: BTreeMap<OwnedUserId, Int>,
creators: HashSet<OwnedUserId>,
authorization_rules: &AuthorizationRules,
) -> Result<serde_json::Value> {
let mut power_levels_content =
serde_json::to_value(assign!(RoomPowerLevelsEventContent::new(authorization_rules), {
users
}))
.unwrap();
) -> Result<RoomPowerLevelsEventContent> {
use ruma::events::TimelineEventType::*;
let mut power_levels_content = power_level_content_override
.map(Raw::cast_ref::<RoomPowerLevelsEventContent>)
.map(Raw::deserialize)
.transpose()
.map_err(|err| err!(Request(BadJson("Invalid power_level_content_override: {err:?}"))))?
.map_or_else(
|| RoomPowerLevelsEventContent::new(authorization_rules),
|mut content| {
if authorization_rules.explicitly_privilege_room_creators {
// If an override was supplied we need to make sure the
// tombstone default is raised to 150
// for v12+. Otherwise, if one wasn't supplied,
// `RoomPowerLevelsEventContent::new` will handle this.
content.events.entry(RoomTombstone).or_insert(int!(150));
}
content
},
);
power_levels_content.users.append(&mut users);
for creator in creators {
power_levels_content.users.remove(&creator);
}
// secure proper defaults of sensitive/dangerous permissions that moderators
// (power level 50) should not have easy access to
power_levels_content["events"]["m.room.power_levels"] =
serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.server_acl"] =
serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.tombstone"] =
serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.encryption"] =
serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.history_visibility"] =
serde_json::to_value(100).expect("100 is valid Value");
let admin_only_events = [
RoomPowerLevels,
RoomServerAcl,
// this will not apply for v12+ rooms since we raised it to 150 earlier
RoomTombstone,
RoomEncryption,
RoomHistoryVisibility,
];
for event_type in admin_only_events {
power_levels_content
.events
.entry(event_type)
.or_insert(int!(100));
}
// always allow users to respond (not post new) to polls. this is primarily
// useful in read-only announcement rooms that post a public poll.
power_levels_content["events"]["org.matrix.msc3381.poll.response"] =
serde_json::to_value(0).expect("0 is valid Value");
power_levels_content["events"]["m.poll.response"] =
serde_json::to_value(0).expect("0 is valid Value");
power_levels_content
.events
.entry(PollResponse)
.or_insert(int!(0));
power_levels_content
.events
.entry(UnstablePollResponse)
.or_insert(int!(0));
// synapse does this too. clients do not expose these permissions. it
// prevents default users from calling public rooms, for obvious reasons.
if *visibility == room::Visibility::Public {
power_levels_content["events"]["m.call.invite"] =
serde_json::to_value(50).expect("50 is valid Value");
power_levels_content["events"]["m.call"] =
serde_json::to_value(50).expect("50 is valid Value");
power_levels_content["events"]["m.call.member"] =
serde_json::to_value(50).expect("50 is valid Value");
power_levels_content["events"]["org.matrix.msc3401.call"] =
serde_json::to_value(50).expect("50 is valid Value");
power_levels_content["events"]["org.matrix.msc3401.call.member"] =
serde_json::to_value(50).expect("50 is valid Value");
}
if let Some(power_level_content_override) = power_level_content_override {
let json: JsonObject = serde_json::from_str(power_level_content_override.json().get())
.map_err(|e| err!(Request(BadJson("Invalid power_level_content_override: {e:?}"))))?;
for (key, value) in json {
power_levels_content[key] = value;
}
}
if !creators.is_empty() {
// Raise the default power level of tombstone to 150
power_levels_content["events"]["m.room.tombstone"] =
serde_json::to_value(150).expect("150 is valid Value");
for creator in creators {
// Omit creators from the power level list altogether
power_levels_content["users"]
.as_object_mut()
.expect("users is an object")
.remove(creator.as_str());
}
power_levels_content
.events
.entry(CallInvite)
.or_insert(int!(50));
power_levels_content
.events
.entry(CallMember)
.or_insert(int!(50));
}
Ok(power_levels_content)
+2 -7
View File
@@ -24,7 +24,7 @@ pub(crate) async fn get_room_event_route(
services.rooms.state_accessor.is_world_readable(room_id)
);
if !joined && !world_readable {
return Err!(Request(NotFound("Event {event_id} not found.")));
return Err!(Request(NotFound("Event {} not found.", event_id)));
}
services
@@ -32,15 +32,10 @@ pub(crate) async fn get_room_event_route(
.timeline
.get_remote_pdu(room_id, event_id)
.await
.map_err(|_| err!(Request(NotFound("Event {event_id} not found."))))?
.map_err(|_| err!(Request(NotFound("Event {} not found.", event_id))))?
},
| Err(e) => return Err(e),
};
if !event.room_id_or_hash().eq(room_id) {
// Return not found instead of invalid param to avoid revealing the
// existence of events the user might not be allowed to know about.
return Err!(Request(NotFound("Event {event_id} not found.")));
}
// NOTE: checked after fetching, as visibility of an unknown event cannot
// be determined (user_can_see_event returns true for those).
+17 -12
View File
@@ -1563,20 +1563,25 @@ where
// joined users
device_list_changes.extend(
services
.rooms
.state_cache
.room_members(room_id)
// Don't send key updates from the sender to the sender
.ready_filter(|user_id| sender_user != *user_id)
// Only send keys if the sender doesn't share an encrypted room with the target
// already
.filter_map(async |user_id| {
share_encrypted_room(services, sender_user, &user_id, Some(room_id))
.rooms
.state_cache
.room_members(room_id)
// Don't send key updates from the sender to the sender
.ready_filter(|user_id| sender_user != *user_id)
// Only send keys if the sender doesn't share an encrypted room with
// the target already
.filter_map(async |user_id| {
share_encrypted_room(
services,
sender_user,
&user_id,
Some(room_id),
)
.map(|res| res.or_some(user_id.clone()))
.await
})
.collect::<Vec<_>>()
.await,
})
.collect::<Vec<_>>()
.await,
);
}
}
+14 -8
View File
@@ -21,7 +21,7 @@ use crate::{admin, client, server};
pub fn build(router: Router<State>, state: State) -> Router<State> {
let config = &state.server.config;
let mut router = router
.ruma_route(&client::appservice_ping)
.ruma_route(&client::appservice_ping)
.ruma_route(&client::get_supported_versions_route)
.ruma_route(&client::get_register_available_route)
.ruma_route(&client::register::register_route)
@@ -61,8 +61,8 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::get_global_account_data_route)
.ruma_route(&client::get_room_account_data_route)
.ruma_route(&client::get_profile_field_route)
.ruma_route(&client::set_profile_field_route)
.ruma_route(&client::delete_profile_field_route)
.ruma_route(&client::set_profile_field_route)
.ruma_route(&client::delete_profile_field_route)
.ruma_route(&client::get_profile_route)
.ruma_route(&client::set_presence_route)
.ruma_route(&client::get_presence_route)
@@ -112,14 +112,17 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::search_users_route)
.ruma_route(&client::get_member_events_route)
.ruma_route(&client::get_protocols_route)
.route("/_matrix/client/unstable/thirdparty/protocols",
get(client::get_protocols_route_unstable))
.route(
"/_matrix/client/unstable/thirdparty/protocols",
get(client::get_protocols_route_unstable),
)
.ruma_route(&client::send_message_event_route)
.ruma_route(&client::send_state_event_for_key_route)
.ruma_route(&client::get_state_events_route)
.ruma_route(&client::get_state_event_for_key_route)
// Ruma doesn't have support for multiple paths for a single endpoint yet, and these routes
// share one Ruma request / response type pair with {get,send}_state_event_for_key_route
// Ruma doesn't have support for multiple paths for a single endpoint yet, and these
// routes share one Ruma request / response type pair with
// {get,send}_state_event_for_key_route
.route(
"/_matrix/client/r0/rooms/{room_id}/state/{event_type}",
get(client::get_state_events_for_empty_key_route)
@@ -194,7 +197,10 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
.ruma_route(&admin::rooms::ban::ban_room)
.ruma_route(&admin::rooms::list::list_rooms);
.ruma_route(&admin::rooms::list::list_rooms)
.ruma_route(&admin::users::list::list_users)
.ruma_route(&admin::users::create::create_user)
.ruma_route(&admin::users::rooms::list_user_rooms);
if config.allow_federation {
router = router
+1
View File
@@ -401,6 +401,7 @@ async fn validate_invite_create_event(
if !state_res::auth_check(
room_version_rules,
pdu,
None,
|_, _| async {
unreachable!("No state should be fetched when processing a lone create event");
},
+22 -5
View File
@@ -17,7 +17,7 @@ use either::{
use figment::providers::{Env, Format, Toml};
pub use figment::{Figment, value::Value as FigmentValue};
use lettre::message::Mailbox;
use openidconnect::{ClientId, ClientSecret, Scope};
use openidconnect::{Audience, ClientId, ClientSecret, Scope};
use regex::RegexSet;
use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
@@ -2800,6 +2800,18 @@ pub struct OidcConfig {
#[serde(default)]
pub additional_scopes: Vec<Scope>,
/// Additional trusted audiences that Continuwuity will accept in the `aud`
/// claim of the OIDC token returned by the IDP. If your identity
/// provider includes other values in the `aud` claim in addition to the
/// client ID, they must be listed here for Continuwuity to accept them.
///
/// Most deployments will not need to set this, because most identity
/// providers only include the client ID in the `aud` claim by default.
///
/// default: []
#[serde(default)]
pub additional_trusted_audiences: BTreeSet<Audience>,
/// The name of the identity provider. If this is set, the login page's
/// button reads "Continue with <name>" instead of just "Continue".
///
@@ -2852,10 +2864,15 @@ pub struct OidcConfig {
/// Per-room overrides to the user's display name or avatar will be
/// preserved by the import process.
///
/// SECURITY NOTE: If the `avatar_url` field is set, Continuwuity will
/// perform a HTTP GET to the URL in the mapped claim and use the returned
/// file as the user's profile picture. Make sure your users are not able
/// to set the value of the mapped claim to an arbitrary URL.
/// SECURITY NOTE: For the following profile fields, Continuwuity will treat
/// the value of the mapped claim as an HTTP URL and upload the file located
/// at that URL to its internal media repository:
///
/// - `avatar_url`
/// - `chat.commet.profile_banner`
///
/// If you map these fields to claims, make sure your users cannot set those
/// claims to arbitrary URLs.
///
/// default: { displayname = "name" }
#[serde(default = "default_profile_key_map")]
+64 -247
View File
@@ -5,21 +5,17 @@ use futures::{
future::{OptionFuture, join, join3},
};
use ruma::{
AnyKeyName, CanonicalJsonObject, Int, OwnedUserId, RoomVersionId, SigningKeyId, UserId,
Int, OwnedUserId, RoomVersionId, UserId,
events::room::{
join_rules::{JoinRule, RoomJoinRulesEventContent},
member::MembershipState,
member::{MembershipState, ThirdPartyInvite},
power_levels::{RoomPowerLevelsEventContent, UserPowerLevel},
third_party_invite::PublicKey,
},
int,
room_version_rules::{RoomIdFormatVersion, RoomVersionRules},
serde::{Raw, base64, base64::Standard},
signatures,
signatures::to_canonical_json_string_for_signing,
third_party_invite::IdentityServerBase64PublicKey,
serde::Raw,
};
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue};
use super::{
@@ -29,7 +25,7 @@ use super::{
deserialize_power_levels_content_redact,
},
};
use crate::{debug, err, error, trace, warn};
use crate::{debug, error, trace, warn};
// FIXME: field extracting could be bundled for `content`
#[derive(Deserialize)]
@@ -52,40 +48,6 @@ struct RoomCreateContentFields {
federate: bool,
}
// Workaround for https://github.com/matrix-org/matrix-spec/issues/2471
#[derive(Deserialize, Debug)]
struct RoomThirdPartyInviteContentFields {
public_key: Option<IdentityServerBase64PublicKey>,
public_keys: Option<Vec<PublicKey>>,
}
// same here sort of (maintainers see https://forgejo.ellis.link/continuwuation/continuwuity-sec/issues/41)
#[derive(Deserialize, Debug)]
struct MemberThirdPartyInviteSignedContent {
signed: ThirdPartyInviteSignedObject,
}
#[derive(Serialize, Deserialize, Debug)]
struct ThirdPartyInviteSignedObject(CanonicalJsonObject);
impl ThirdPartyInviteSignedObject {
#[inline]
fn mxid(&self) -> Option<OwnedUserId> {
self.0
.get("mxid")?
.as_str()
.and_then(|raw| UserId::parse(raw).ok())
}
#[inline]
fn token(&self) -> Option<&str> { self.0.get("token")?.as_str() }
#[inline]
fn signatures(&self) -> Option<CanonicalJsonObject> {
self.0.get("signatures")?.as_object().map(ToOwned::to_owned)
}
}
/// For the given event `kind` what are the relevant auth events that are needed
/// to authenticate this `content`.
///
@@ -99,7 +61,7 @@ pub fn auth_types_for_event(
state_key: Option<&str>,
content: &RawJsonValue,
room_version: &RoomVersionRules,
) -> crate::Result<Vec<(StateEventType, StateKey)>> {
) -> serde_json::Result<Vec<(StateEventType, StateKey)>> {
if kind == &TimelineEventType::RoomCreate {
return Ok(vec![]);
}
@@ -122,7 +84,7 @@ pub fn auth_types_for_event(
#[allow(unused)]
struct RoomMemberContentFields {
membership: Option<Raw<MembershipState>>,
third_party_invite: Option<Raw<MemberThirdPartyInviteSignedContent>>,
third_party_invite: Option<Raw<ThirdPartyInvite>>,
join_authorised_via_users_server: Option<Raw<OwnedUserId>>,
}
@@ -154,24 +116,16 @@ pub fn auth_types_for_event(
auth_types.push(key);
}
if membership == MembershipState::Invite {
if let Some(Ok(t_id)) = content.third_party_invite.map(|t| t.deserialize()) {
let key = (
StateEventType::RoomThirdPartyInvite,
t_id.signed
.token()
.ok_or_else(|| {
err!(Request(BadJson(
"Third party invite content missing a token"
)))
})?
.into(),
);
if !auth_types.contains(&key) {
auth_types.push(key);
}
}
}
// TODO: restore this once 3pid support isn't broken
// if membership == MembershipState::Invite {
// if let Some(Ok(t_id)) = content.third_party_invite.map(|t|
// t.deserialize()) { let key =
// (StateEventType::RoomThirdPartyInvite,
// t_id.signed.token.into()); if !auth_types.contains(&
// key) { auth_types.push(key);
// }
// }
// }
}
}
}
@@ -225,11 +179,12 @@ fn get_user_power_level(
pub async fn auth_check<E, F, Fut>(
room_version: &RoomVersionRules,
incoming_event: &E,
current_third_party_invite: Option<&E>,
fetch_state: F,
create_event: &E,
) -> Result<bool, Error>
where
F: Fn(&StateEventType, &str) -> Fut + Send + Copy,
F: Fn(&StateEventType, &str) -> Fut + Send,
Fut: Future<Output = Option<E>> + Send,
E: Event + Send + Sync,
for<'a> &'a E: Event + Send,
@@ -489,15 +444,13 @@ where
sender,
sender_member_event.as_ref(),
incoming_event,
fetch_state,
current_third_party_invite,
power_levels_event.as_ref(),
join_rules_event.as_ref(),
user_for_join_auth.as_deref(),
&user_for_join_auth_membership,
&room_create_event,
)
.await?
{
)? {
return Ok(false);
}
@@ -686,14 +639,14 @@ where
/// event and the current State.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::cognitive_complexity)]
async fn valid_membership_change<E, F, Fut>(
fn valid_membership_change<E>(
room_version: &RoomVersionRules,
target_user: &UserId,
target_user_membership_event: Option<&E>,
sender: &UserId,
sender_membership_event: Option<&E>,
current_event: &E,
fetch_state: F,
current_third_party_invite: Option<&E>,
power_levels_event: Option<&E>,
join_rules_event: Option<&E>,
user_for_join_auth: Option<&UserId>,
@@ -702,13 +655,11 @@ async fn valid_membership_change<E, F, Fut>(
) -> Result<bool>
where
E: Event + Send + Sync,
F: Fn(&StateEventType, &str) -> Fut + Send + Copy,
Fut: Future<Output = Option<E>> + Send,
for<'a> &'a E: Event + Send,
{
#[derive(Deserialize)]
struct GetThirdPartyInvite {
third_party_invite: Option<Raw<MemberThirdPartyInviteSignedContent>>,
third_party_invite: Option<Raw<ThirdPartyInvite>>,
}
let create_content = from_json_str::<RoomCreateContentFields>(create_room.content().get())?;
let creator = if room_version.authorization.use_room_create_sender {
@@ -950,18 +901,22 @@ where
| MembershipState::Invite => {
// If content has third_party_invite key
trace!("starting target_membership=invite check");
match third_party_invite {
| Some(raw_tp_id) =>
match third_party_invite.and_then(|i| i.deserialize().ok()) {
| Some(tp_id) =>
if target_user_current_membership == MembershipState::Ban {
warn!(?target_user_membership_event_id, "Can't invite banned user");
false
} else {
let Ok(tp_id) = raw_tp_id.deserialize() else {
warn!("Invite third party content is invalid");
return Ok(false);
};
verify_third_party_invite(Some(target_user), sender, &tp_id, fetch_state)
.await
let allow = verify_third_party_invite(
Some(target_user),
sender,
&tp_id,
current_third_party_invite,
);
if !allow {
warn!("Third party invite invalid");
}
allow
},
| _ =>
if !sender_is_joined {
@@ -1480,133 +1435,14 @@ fn get_send_level(
.unwrap_or_else(|| if state_key.is_some() { int!(50) } else { int!(0) })
}
async fn verify_third_party_invite<F, Fut, E>(
target_user: Option<&UserId>,
sender: &UserId,
tp_id: &MemberThirdPartyInviteSignedContent,
fetch_state: F,
) -> bool
where
F: Fn(&StateEventType, &str) -> Fut + Send,
Fut: Future<Output = Option<E>> + Send,
E: Event + Send + Sync,
{
// If content.third_party_invite does not have a signed property, reject.
// ^ This would be a deserialization error before this function call, which
// equates to a rejection
let signed = &tp_id.signed;
// If signed does not have mxid and token properties, reject.
let Some(mxid) = signed.mxid() else {
warn!("Invite third party signed content is missing or has invalid `mxid` property");
return false;
};
let Some(token) = signed.token() else {
warn!("Invite third party signed content is missing or has invalid `token` property");
return false;
};
if let Err(e) = mxid.validate_historical() {
warn!(error=?e, ?mxid, "Invite third party signed content has invalid `mxid` property");
return false;
}
// If mxid does not match state_key, reject.
// N.B. target_user is the state_key
if target_user.is_none_or(|u| u != mxid) {
warn!(?target_user, %mxid, "Invite third party mxid does not match membership state key");
return false;
}
// If there is no m.room.third_party_invite event in the current room state
// with state_key matching token, reject.
let Some(current_third_party_invite) =
fetch_state(&StateEventType::RoomThirdPartyInvite, token).await
else {
warn!("No third party invite associated with the invite's third party invite found");
return false;
};
let Ok(tpi_content) = current_third_party_invite
.get_content::<RoomThirdPartyInviteContentFields>()
.inspect_err(
|e| warn!(error=?e, "Third party invite event content is invalid (cannot deserialize)"),
)
else {
return false;
};
if current_third_party_invite.state_key() != Some(token) {
warn!(
state_key=?current_third_party_invite.state_key(),
%token,
"Third party invite state key mismatch with signed invite token"
);
return false;
}
// If sender does not match sender of the m.room.third_party_invite, reject.
if sender != current_third_party_invite.sender() {
warn!(
?sender,
third_party_invite_sender=%current_third_party_invite.sender(),
"Third party invite sender does not match invite membership sender"
);
return false;
}
// If any signature in signed matches any public key in the
// m.room.third_party_invite event, allow. The public keys are in content of
// m.room.third_party_invite as:
//
// A single public key in the public_key property.
// A list of public keys in the public_keys property.
// NOTE: Technically the two below operations shouldn't be fallible at this
// point in execution, but if we can't de/serialize them now, we won't be
// able to in the future, so rejecting the event is the right way to go.
// We log an error though since this is unexpected.
let Ok(signed_json) = to_canonical_json_string_for_signing(&signed.0).inspect_err(
|e| error!(error=?e, "Canonical signed object cannot be cast to a signing string"),
) else {
return false;
};
let signatures = signed
.signatures()
.unwrap_or_default() // Empty sigs object will never pass so this is fine
.values()
.filter_map(|signatures| signatures.as_object())
.flat_map(|signatures| {
signatures.iter().map(|(key, sig)| {
let key_id = SigningKeyId::<AnyKeyName>::parse(key).ok()?;
base64::Base64::<Standard>::parse(sig.as_str()?)
.map(|parsed| (key_id.algorithm(), parsed))
.ok()
})
})
.flatten()
.collect::<Vec<_>>();
for public_key_bytes in tpi_content
.public_key
.into_iter()
.chain(
tpi_content
.public_keys
.unwrap_or_default()
.iter()
.map(|pk| pk.public_key.clone()),
)
.filter_map(|pk| pk.decode().ok())
{
for (algorithm, signature) in &signatures {
if signatures::verify_canonical_json_bytes(
algorithm,
&public_key_bytes,
signature.as_bytes(),
signed_json.as_bytes(),
)
.is_ok()
{
return true;
}
}
}
warn!("Invite via third party was not signed by any associated public keys");
false
fn verify_third_party_invite(
_target_user: Option<&UserId>,
_sender: &UserId,
_tp_id: &ThirdPartyInvite,
_current_third_party_invite: Option<&impl Event>,
) -> bool {
// TODO: implement proper verification here
true
}
#[cfg(test)]
@@ -1625,7 +1461,7 @@ mod tests {
use serde_json::value::to_raw_value as to_raw_json_value;
use crate::{
matrix::{Event, EventTypeExt},
matrix::{Event, EventTypeExt, Pdu as PduEvent},
state_res::{
StateMap,
event_auth::valid_membership_change,
@@ -1636,8 +1472,8 @@ mod tests {
},
};
#[tokio::test]
async fn test_ban_pass() {
#[test]
fn test_ban_pass() {
let _ = tracing::subscriber::set_default(
tracing_subscriber::fmt().with_test_writer().finish(),
);
@@ -1659,8 +1495,6 @@ mod tests {
);
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
let async_fetch_state =
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
let target_user = charlie();
let sender = alice();
@@ -1672,20 +1506,19 @@ mod tests {
sender,
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
&requester,
&async_fetch_state,
None::<&PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
None,
&MembershipState::Leave,
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
)
.await
.unwrap()
);
}
#[tokio::test]
async fn test_join_non_creator() {
#[test]
fn test_join_non_creator() {
let _ = tracing::subscriber::set_default(
tracing_subscriber::fmt().with_test_writer().finish(),
);
@@ -1707,8 +1540,6 @@ mod tests {
);
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
let async_fetch_state =
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
let target_user = charlie();
let sender = charlie();
@@ -1720,20 +1551,19 @@ mod tests {
sender,
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
&requester,
&async_fetch_state,
None::<&PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
None,
&MembershipState::Leave,
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
)
.await
.unwrap()
);
}
#[tokio::test]
async fn test_join_creator() {
#[test]
fn test_join_creator() {
let _ = tracing::subscriber::set_default(
tracing_subscriber::fmt().with_test_writer().finish(),
);
@@ -1755,8 +1585,6 @@ mod tests {
);
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
let async_fetch_state =
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
let target_user = alice();
let sender = alice();
@@ -1768,20 +1596,19 @@ mod tests {
sender,
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
&requester,
&async_fetch_state,
None::<&PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
None,
&MembershipState::Leave,
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
)
.await
.unwrap()
);
}
#[tokio::test]
async fn test_ban_fail() {
#[test]
fn test_ban_fail() {
let _ = tracing::subscriber::set_default(
tracing_subscriber::fmt().with_test_writer().finish(),
);
@@ -1803,8 +1630,6 @@ mod tests {
);
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
let async_fetch_state =
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
let target_user = alice();
let sender = charlie();
@@ -1816,20 +1641,19 @@ mod tests {
sender,
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
&requester,
&async_fetch_state,
None::<&PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
None,
&MembershipState::Leave,
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
)
.await
.unwrap()
);
}
#[tokio::test]
async fn test_restricted_join_rule() {
#[test]
fn test_restricted_join_rule() {
let _ = tracing::subscriber::set_default(
tracing_subscriber::fmt().with_test_writer().finish(),
);
@@ -1868,8 +1692,6 @@ mod tests {
);
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
let async_fetch_state =
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
let target_user = ella();
let sender = ella();
@@ -1881,14 +1703,13 @@ mod tests {
sender,
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
&requester,
&async_fetch_state,
None::<&PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
Some(alice()),
&MembershipState::Join,
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
)
.await
.unwrap()
);
@@ -1900,20 +1721,19 @@ mod tests {
sender,
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
&requester,
&async_fetch_state,
None::<&PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
Some(ella()),
&MembershipState::Leave,
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
)
.await
.unwrap()
);
}
#[tokio::test]
async fn test_knock() {
#[test]
fn test_knock() {
let _ = tracing::subscriber::set_default(
tracing_subscriber::fmt().with_test_writer().finish(),
);
@@ -1944,8 +1764,6 @@ mod tests {
);
let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned();
let async_fetch_state =
|t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into()));
let target_user = ella();
let sender = ella();
@@ -1957,14 +1775,13 @@ mod tests {
sender,
fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(),
&requester,
&async_fetch_state,
None::<&PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(),
fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(),
None,
&MembershipState::Leave,
&fetch_state(StateEventType::RoomCreate, "".into()).unwrap(),
)
.await
.unwrap()
);
}
+8 -2
View File
@@ -757,8 +757,7 @@ where
Some(state_key),
event.content(),
room_version,
)
.map_err(|e| Error::InvalidPdu(e.to_string()))?;
)?;
trace!(list = ?auth_types, event_id = event.event_id().as_str(), "auth types for event");
let mut auth_state = StateMap::new();
@@ -831,6 +830,12 @@ where
debug!(event_id = event.event_id().as_str(), "Running auth checks");
// The key for this is (eventType + a state_key of the signed token not
// sender) so search for it
let current_third_party = auth_state.iter().find_map(|(_, pdu)| {
(*pdu.event_type() == TimelineEventType::RoomThirdPartyInvite).then_some(pdu)
});
let fetch_state = |ty: &StateEventType, key: &str| {
future::ready(
auth_state
@@ -842,6 +847,7 @@ where
let auth_result = auth_check(
room_version,
&event,
current_third_party,
fetch_state,
&fetch_state(&StateEventType::RoomCreate, "")
.await
+2
View File
@@ -46,5 +46,7 @@ pub fn unstable_features() -> BTreeMap<String, bool> {
("computer.gingershaped.msc4466".to_owned(), true),
// web push (https://github.com/matrix-org/matrix-spec-proposals/pull/4174)
("org.matrix.msc4174".to_owned(), true),
// Membership-based invite blocking (https://github.com/matrix-org/matrix-spec-proposals/pull/4494)
("uk.timedout.msc4494".to_owned(), true),
])
}
+4
View File
@@ -130,6 +130,10 @@ pub(super) static MAPS: &[Descriptor] = &[
},
Descriptor {
name: "openidsubject_currentpictureurl",
..descriptor::DROPPED
},
Descriptor {
name: "openidsubjectprofilefield_url",
..descriptor::RANDOM_SMALL
},
Descriptor {
+2 -1
View File
@@ -11,13 +11,14 @@ version.workspace = true
path = "mod.rs"
[features]
default = ["client", "server"]
default = ["client", "server", "unstable-msc4484"]
client = []
server = []
unstable-exhaustive-types = []
unstable-msc3202 = []
unstable-msc4203 = []
unstable-msc4484 = ["ruma/unstable-msc4484"]
[dependencies]
assign.workspace = true
@@ -1 +1,2 @@
pub mod rooms;
pub mod users;
@@ -1,7 +1,7 @@
pub mod v1 {
use ruma::{
OwnedRoomAliasId, OwnedRoomId, OwnedUserId,
api::{auth_scheme::AccessToken, request, response},
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
metadata,
};
@@ -10,8 +10,9 @@ pub mod v1 {
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/rooms/{room_id}/ban",
}
1.0 => "/_continuwuity/admin/v1/rooms/{room_id}/ban",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[request]
@@ -1,7 +1,7 @@
pub mod v1 {
use ruma::{
OwnedRoomId,
api::{auth_scheme::AccessToken, request, response},
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
metadata,
};
@@ -10,8 +10,9 @@ pub mod v1 {
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/rooms/list",
}
1.0 => "/_continuwuity/admin/v1/rooms/list",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[request]
@@ -0,0 +1,58 @@
pub mod v1 {
use ruma::{
OwnedUserId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
metadata,
profile::UserProfile,
};
metadata! {
method: POST,
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/users",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[request]
pub struct Request {
/// The full user ID to create. Must belong to the server.
pub user_id: OwnedUserId,
/// The password to set for the new user.
///
/// If `None`, the user will not be able to log in.
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub password: Option<String>,
/// The profile fields to set for the user. This can be used to set the
/// new user's display name and profile picture.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<UserProfile>,
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub admin: bool,
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub suspended: bool,
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub locked: bool,
}
#[derive(Default)]
#[response]
pub struct Response;
impl Request {
#[must_use]
pub fn new(user_id: OwnedUserId) -> Self {
Self {
user_id,
password: None,
profile: None,
admin: false,
suspended: false,
locked: false,
}
}
}
}
@@ -0,0 +1,84 @@
pub mod v1 {
use std::collections::BTreeMap;
use ruma::{
OwnedMxcUri, OwnedUserId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
metadata,
};
use serde::{Deserialize, Serialize};
metadata! {
method: GET,
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/users",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Copy)]
pub enum QueryFilter {
/// Always include entities matching this criteria.
#[serde(rename = "include")]
Include,
/// Never include entities matching this criteria.
#[serde(rename = "exclude")]
Exclude,
}
#[derive(Default)]
#[request]
#[serde(default)]
pub struct Request {
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub active: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub deactivated: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub suspended: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub locked: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub admin: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<usize>,
}
#[derive(Default, Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct User {
#[serde(skip_serializing_if = "Option::is_none")]
pub displayname: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<OwnedMxcUri>,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub suspended: bool,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub locked: bool,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub deactivated: bool,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub admin: bool,
}
#[response]
pub struct Response {
#[ruma_api(body)]
pub users: BTreeMap<OwnedUserId, User>,
}
impl Response {
#[must_use]
pub fn new(users: BTreeMap<OwnedUserId, User>) -> Self { Self { users } }
}
}
@@ -0,0 +1,3 @@
pub mod create;
pub mod list;
pub mod rooms;
@@ -0,0 +1,66 @@
pub mod v1 {
use std::collections::BTreeMap;
use ruma::{
OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
events::room::member::MembershipState,
metadata,
};
use serde::{Deserialize, Serialize};
metadata! {
method: GET,
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/users/{user_id}/rooms",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[request]
pub struct Request {
#[ruma_api(path)]
pub user_id: OwnedUserId,
pub state: MembershipState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct RoomInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<OwnedMxcUri>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canonical_alias: Option<OwnedRoomAliasId>,
pub member_count: u32,
}
#[response]
pub struct Response {
pub rooms: BTreeMap<OwnedRoomId, RoomInfo>,
}
impl Request {
#[must_use]
pub fn new(
user_id: OwnedUserId,
state: MembershipState,
limit: Option<u32>,
page: Option<u32>,
) -> Self {
Self { user_id, state, limit, page }
}
}
impl Response {
#[must_use]
pub fn new(rooms: BTreeMap<OwnedRoomId, RoomInfo>) -> Self { Self { rooms } }
}
}
+10 -9
View File
@@ -17,6 +17,7 @@ use wildmatch::WildMatch;
/// MSC4283: https://github.com/matrix-org/matrix-spec-proposals/pull/4283
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterLevel {
Default,
Allow,
Ignore,
Block,
@@ -122,7 +123,7 @@ impl InvitePermissionConfigEventContent {
if self.are_all_blocked() {
FilterLevel::Block
} else if !self.enabled {
FilterLevel::Allow
FilterLevel::Default
} else if Self::matches(&self.allowed_users, user.as_str()) {
FilterLevel::Allow
} else if Self::matches(&self.ignored_users, user.as_str()) {
@@ -140,7 +141,7 @@ impl InvitePermissionConfigEventContent {
if self.are_all_blocked() {
FilterLevel::Block
} else if !self.enabled {
FilterLevel::Allow
FilterLevel::Default
} else {
let server = server.host();
if Self::matches(&self.allowed_servers, server) {
@@ -150,7 +151,7 @@ impl InvitePermissionConfigEventContent {
} else if Self::matches(&self.blocked_servers, server) {
FilterLevel::Block
} else {
FilterLevel::Allow
FilterLevel::Default
}
}
}
@@ -198,13 +199,13 @@ mod tests {
event
.content
.user_filter_level(user_id("@alice:example.com")),
FilterLevel::Allow
FilterLevel::Default
);
assert_eq!(
event
.content
.server_filter_level(server_name("example.com")),
FilterLevel::Allow
FilterLevel::Default
);
}
@@ -245,8 +246,8 @@ mod tests {
..Default::default()
};
assert_eq!(event.user_filter_level(user_id("@alice:goodguys.org")), FilterLevel::Allow);
assert_eq!(event.user_filter_level(user_id("@bob:bar.com")), FilterLevel::Allow);
assert_eq!(event.user_filter_level(user_id("@alice:goodguys.org")), FilterLevel::Default);
assert_eq!(event.user_filter_level(user_id("@bob:bar.com")), FilterLevel::Default);
assert_eq!(
event.user_filter_level(user_id("@kevin:badguys.org:8080")),
FilterLevel::Block
@@ -278,9 +279,9 @@ mod tests {
..Default::default()
};
assert_eq!(event.user_filter_level(user_id("@alice:goodguys.org")), FilterLevel::Allow);
assert_eq!(event.user_filter_level(user_id("@alice:goodguys.org")), FilterLevel::Default);
assert_eq!(event.user_filter_level(user_id("@alice:badguys.org")), FilterLevel::Allow);
assert_eq!(event.user_filter_level(user_id("@bob:bar.com")), FilterLevel::Allow);
assert_eq!(event.user_filter_level(user_id("@bob:bar.com")), FilterLevel::Default);
assert_eq!(event.user_filter_level(user_id("@kevin:badguys.org")), FilterLevel::Block);
}
-2
View File
@@ -117,8 +117,6 @@ url.workspace = true
web-push-native.workspace = true
webpage.workspace = true
webpage.optional = true
recaptcha-verify = { version = "0.2.0", default-features = false }
reqwest_recaptcha = { package = "reqwest", version = "0.12.28", default-features = false, features = ["rustls-tls-native-roots-no-provider"] } # As long as recaptcha-verify's reqwest is outdated
yansi.workspace = true
lettre.workspace = true
resolvematrix.workspace = true
+39 -1
View File
@@ -1,7 +1,7 @@
use std::{sync::Arc, time::Duration};
use async_trait::async_trait;
use conduwuit::{Config, Result, Server, err, trace};
use conduwuit::{Config, Result, Server, err, trace, utils::response::LimitReadExt, warn};
use either::Either;
use hickory_resolver::{
TokioResolver, config::ConnectionConfig, net::runtime::TokioRuntimeProvider,
@@ -9,6 +9,7 @@ use hickory_resolver::{
use ipaddress::IPAddress;
use reqwest::redirect;
use resolvematrix::server::{MatrixResolver, MatrixResolverBuilder};
use serde::Deserialize;
use crate::service;
@@ -178,6 +179,43 @@ impl Service {
.iter()
.all(|cidr| !cidr.includes(ip))
}
#[tracing::instrument(skip_all)]
pub async fn recaptcha_verify(&self, secret: &str, response: &str) -> bool {
#[derive(Deserialize, Default, Debug, Clone)]
struct RecaptchaResponse {
success: bool,
#[serde(rename(deserialize = "error-codes"))]
_error_codes: Option<Vec<String>>,
}
let response = match self
.external_resource
.post("https://www.google.com/recaptcha/api/siteverify")
.form(&[("secret", secret), ("response", response)])
.send()
.await
{
| Ok(response) => response,
| Err(err) => {
warn!("ReCaptcha request failed: {err}");
return false;
},
};
let Ok(response) = response.limit_read_text(1024).await else {
warn!("ReCaptcha response was too large??");
return false;
};
match serde_json::from_str::<RecaptchaResponse>(&response) {
| Ok(response) => response.success,
| Err(err) => {
warn!("ReCaptcha response failed to deserialize: {err}");
false
},
}
}
}
pub fn base(config: &Config) -> Result<reqwest::ClientBuilder> {
+22 -21
View File
@@ -139,13 +139,12 @@ impl Service {
let mut preview_data = preview_data.unwrap_or_default();
let image = self
.services
.client
.url_preview
.get(url)
.send()
.await?
let response = self.services.client.url_preview.get(url).send().await?;
if !response.status().is_success() {
return Err!(Request(Unknown("Image download returned HTTP {}", response.status())));
}
let image = response
.limit_read(
self.services
.server
@@ -156,27 +155,29 @@ impl Service {
)
.await?;
let reader = ImageReader::new(std::io::Cursor::new(&image)).with_guessed_format()?;
let content_type = reader
.format()
.ok_or_else(|| err!(Request(Unknown("Downloaded file is not a supported image"))))?
.to_mime_type();
if preview_data.image_height.is_none() || preview_data.image_width.is_none() {
let (width, height) = reader.into_dimensions().map_err(|error| {
err!(Request(Unknown("Failed to read preview image dimensions: {error}")))
})?;
preview_data.image_width.get_or_insert(width);
preview_data.image_height.get_or_insert(height);
}
let mxc = Mxc {
server_name: self.services.globals.server_name(),
media_id: &random_string(super::MXC_LENGTH),
};
self.create(&mxc, None, None, None, &image).await?;
self.create(&mxc, None, None, Some(content_type), &image)
.await?;
preview_data.image = Some(mxc.to_string());
if preview_data.image_height.is_none() || preview_data.image_width.is_none() {
let cursor = std::io::Cursor::new(&image);
let (width, height) = match ImageReader::new(cursor).with_guessed_format() {
| Err(_) => (None, None),
| Ok(reader) => match reader.into_dimensions() {
| Err(_) => (None, None),
| Ok((width, height)) => (Some(width), Some(height)),
},
};
preview_data.image_width = width;
preview_data.image_height = height;
}
Ok(preview_data)
}
+198 -257
View File
@@ -2,6 +2,7 @@ use std::{
cmp,
collections::{BTreeMap, HashMap},
future::ready,
pin::Pin,
sync::Arc,
time::Instant,
};
@@ -17,7 +18,7 @@ use conduwuit::{
},
warn,
};
use database::{Database, Json};
use database::Json;
use futures::{FutureExt, StreamExt, TryStreamExt};
use itertools::Itertools;
use ruma::{
@@ -34,13 +35,155 @@ use serde_json::value::to_raw_value;
use crate::{Services, media, rooms, rooms::short::ShortStateHash};
/// The current schema version.
/// - If database is opened at greater version we reject with error. The
/// software must be updated for backward-incompatible changes.
/// - If database is opened at lesser version we apply migrations up to this.
/// Note that named-feature migrations may also be performed when opening at
/// equal or lesser version. These are expected to be backward-compatible.
pub(crate) const DATABASE_VERSION: u64 = 19;
type MigrationFn =
for<'a> fn(&'a Services) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
enum DatabaseMigrationStep {
Migration(&'static str, MigrationFn),
VersionBump(u64),
}
static MIGRATIONS: &[DatabaseMigrationStep] = const {
use DatabaseMigrationStep::*;
macro_rules! migration {
($name:expr => $function:path) => {
Migration($name, |services| {
Box::pin(async {
let db = &services.db;
if db["global"].get($name).await.is_not_found() {
info!("Starting migration {}", $name);
let cork = db.cork_and_sync();
$function(services)
.await
.map_err(|err| err!("Failed to run migration {}: {err}", $name))?;
drop(cork);
db["global"].insert($name, []);
db.db.sort()?;
}
Ok(())
})
})
};
($name:ident) => {
// cargo fmt really wants this to be left-aligned, I guess?
migration!(stringify!($name) => $name)
};
}
// When you're writing a migration that makes backwards-incompatible
// changes, you need to use `VersionBump` to keep old versions from
// accepting the new database. The `VersionBump` command should come
// _before_ your migration, which ensures that old versions will reject
// the new database even if the server crashes or restarts while your
// migration is running.
// If your migration is backwards-compatible, meaning that its changes can
// be understood by a version of continuwuity that has not run it, it
// doesn't need a version bump. Use your best discretion when deciding what
// "be understood" means. Also, make sure to add a comment that explains
// why the bump was necessary, for the sake of future developers.
// Database versions should increase monotonically (you'll get a const-eval
// panic if they don't) and linearly. I don't know why conduit skipped
// from 13 to 17, don't bother asking.
&[
// Begin pre-fork logic. We don't have insight into why this works
// the way it does, so there are no comments here.
VersionBump(12),
migration!(fix_push_rule_names),
VersionBump(13),
migration!(fix_server_default_push_rules),
VersionBump(17),
migration!("feat_sha256_media" => media::migrations::migrate_sha256_media),
migration!(fix_bad_double_separator_in_state_cache),
migration!(retroactively_fix_bad_data_from_roomuserid_joined),
migration!(fix_referencedevents_missing_sep),
migration!(fix_readreceiptid_readreceipt_duplicates),
// End pre-fork logic.
// v18: `fix_corrupt_msc4133_fields` will change the `us.cloke.msc4175.tz` field
// in a way that old versions don't understand.
VersionBump(18),
migration!(fix_corrupt_msc4133_fields),
// v19: `populate_userroomid_leftstate_table` will put data in the values of
// `userroomid_leftstate` that old versions will fail to deserialize because
// they expect the values to be empty.
VersionBump(19),
migration!(populate_userroomid_leftstate_table),
// This is backwards compatible because it fixes some data that clients care about but we
// don't.
migration!(fix_local_invite_state),
// v20: Old versions expect remote users to be tracked in `userid_password`. This
// migration moves them to a different keyspace.
VersionBump(20),
migration!(split_userid_password),
// This is backwards compatible because old versions will recreate the keyspace if it's
// missing.
migration!("drop_roomsynctoken_shortstatehash" => obliterate_roomsynctoken_shortstatehash_with_extreme_prejudice),
// v21: `unembed_unsigned_info` will remove `unsigned` data from PDUs that old versions
// expect to be embedded.
VersionBump(21),
// This migration can take several hours on old databases, so we run it in the background
// to keep the service manager from killing us for taking too long to start.
// Future maintainers: !!! BE VERY CAREFUL !!! if you need to write more migrations like
// this! This one is fine because it deletes data that we don't check anymore,
// but migrations which replace existing data that we do check should NOT run in
// the background. If they do, the server will finish starting up and might
// access data that the migration hasn't gotten to yet.
Migration("unembed_unsigned_info", |services| {
Box::pin(async {
if services.db["global"]
.get(b"unembed_unsigned_info")
.await
.is_not_found()
{
let db = services.db.clone();
let metadata = services.rooms.metadata.clone();
let timeline = services.rooms.timeline.clone();
services.server.runtime().spawn(async move {
unembed_unsigned_info(metadata, timeline).await;
db["global"].insert(b"unembed_unsigned_info", []);
});
}
Ok(())
})
}),
// This is backwards compatible because old versions will recreate the keyspace if it's
// missing.
migration!(drop_server_signingkeys),
]
};
pub(crate) const DATABASE_VERSION: u64 = const {
let mut latest_version = 0_u64;
// TODO: refactor once slice iter is const stable
let mut i = 0;
while i < MIGRATIONS.len() {
if let DatabaseMigrationStep::VersionBump(version) = &MIGRATIONS[i] {
if *version > latest_version {
latest_version = *version;
} else {
panic!("Database version must monotonically increase");
}
}
i += 1;
}
latest_version
};
// This should match the first `VersionBump` in `MIGRATIONS`.
const OLDEST_SUPPORTED_VERSION: u64 = 11;
pub(crate) async fn migrations(services: &Services) -> Result<()> {
let users_count = services.users.count().await;
@@ -71,18 +214,11 @@ async fn fresh(services: &Services) -> Result<()> {
services.globals.db.bump_database_version(DATABASE_VERSION);
db["global"].insert(b"feat_sha256_media", []);
db["global"].insert(b"fix_bad_double_separator_in_state_cache", []);
db["global"].insert(b"retroactively_fix_bad_data_from_roomuserid_joined", []);
db["global"].insert(b"fix_referencedevents_missing_sep", []);
db["global"].insert(b"fix_readreceiptid_readreceipt_duplicates", []);
db["global"].insert(b"fix_corrupt_msc4133_fields", []);
db["global"].insert(b"populate_userroomid_leftstate_table", []);
db["global"].insert(b"fix_local_invite_state", []);
db["global"].insert(SPLIT_USERID_PASSWORD, []);
db["global"].insert(DROP_ROOMSYNCTOKEN_SHORTSTATEHASH, []);
db["global"].insert(UNEMBED_UNSIGNED_INFO, []);
db["global"].insert(DROP_OLD_SIGNING_KEYS_STORAGE, []);
for step in MIGRATIONS {
if let DatabaseMigrationStep::Migration(key, _) = step {
db["global"].insert(key, []);
}
}
// Create the admin room and server user on first run
info!("Creating admin room and server user");
@@ -98,35 +234,29 @@ async fn fresh(services: &Services) -> Result<()> {
/// Apply any migrations
async fn migrate(services: &Services) -> Result<()> {
let db = &services.db;
let config = &services.server.config;
if services.globals.db.database_version().await < 11 {
if services.globals.db.database_version().await < OLDEST_SUPPORTED_VERSION {
return Err!(Database(
"Database schema version {} is no longer supported",
"Database schema version {} is too old to migrate. Please use an old version of \
conduwuit to migrate to version 11 and then run Continuwuity again.",
services.globals.db.database_version().await
));
}
if services.globals.db.database_version().await < 12 {
db_lt_12(services)
.await
.map_err(|e| err!("Failed to run v12 migrations: {e}"))?;
for step in MIGRATIONS {
match step {
| DatabaseMigrationStep::Migration(_, migration) => {
migration(services).await?;
},
| DatabaseMigrationStep::VersionBump(version) => {
if services.globals.db.database_version().await < *version {
services.globals.db.bump_database_version(*version);
info!("Bumped database version to {version}.");
}
},
}
}
// This migration can be reused as-is anytime the server-default rules are
// updated.
if services.globals.db.database_version().await < 13 {
db_lt_13(services)
.await
.map_err(|e| err!("Failed to run v13 migrations: {e}"))?;
}
if db["global"].get(b"feat_sha256_media").await.is_not_found() {
media::migrations::migrate_sha256_media(services)
.await
.map_err(|e| err!("Failed to run SHA256 media migration: {e}"))?;
} else if config.media_startup_check {
if services.config.media_startup_check {
info!("Starting media startup integrity check.");
let now = Instant::now();
media::migrations::checkup_sha256_media(services)
@@ -138,154 +268,6 @@ async fn migrate(services: &Services) -> Result<()> {
);
}
if db["global"]
.get(b"fix_bad_double_separator_in_state_cache")
.await
.is_not_found()
{
info!("Running migration 'fix_bad_double_separator_in_state_cache'");
fix_bad_double_separator_in_state_cache(services)
.await
.map_err(|e| {
err!("Failed to run 'fix_bad_double_separator_in_state_cache' migration: {e}")
})?;
}
if db["global"]
.get(b"retroactively_fix_bad_data_from_roomuserid_joined")
.await
.is_not_found()
{
info!("Running migration 'retroactively_fix_bad_data_from_roomuserid_joined'");
retroactively_fix_bad_data_from_roomuserid_joined(services)
.await
.map_err(|e| {
err!(
"Failed to run 'retroactively_fix_bad_data_from_roomuserid_joined' \
migration: {e}"
)
})?;
}
if db["global"]
.get(b"fix_referencedevents_missing_sep")
.await
.is_not_found()
|| services.globals.db.database_version().await < 17
{
info!("Running migration 'fix_referencedevents_missing_sep'");
fix_referencedevents_missing_sep(services)
.await
.map_err(|e| {
err!("Failed to run 'fix_referencedevents_missing_sep' migration': {e}")
})?;
}
if db["global"]
.get(b"fix_readreceiptid_readreceipt_duplicates")
.await
.is_not_found()
|| services.globals.db.database_version().await < 17
{
info!("Running migration 'fix_readreceiptid_readreceipt_duplicates'");
fix_readreceiptid_readreceipt_duplicates(services)
.await
.map_err(|e| {
err!("Failed to run 'fix_readreceiptid_readreceipt_duplicates' migration': {e}")
})?;
}
if services.globals.db.database_version().await < 17 {
services.globals.db.bump_database_version(17);
info!("Migration: Bumped database version to 17");
}
if db["global"]
.get(FIXED_CORRUPT_MSC4133_FIELDS_MARKER)
.await
.is_not_found()
{
info!("Running migration 'fix_corrupt_msc4133_fields'");
fix_corrupt_msc4133_fields(services)
.await
.map_err(|e| err!("Failed to run 'fix_corrupt_msc4133_fields' migration': {e}"))?;
}
if services.globals.db.database_version().await < 18 {
services.globals.db.bump_database_version(18);
info!("Migration: Bumped database version to 18");
}
if db["global"]
.get(POPULATED_USERROOMID_LEFTSTATE_TABLE_MARKER)
.await
.is_not_found()
{
info!("Running migration 'populate_userroomid_leftstate_table'");
populate_userroomid_leftstate_table(services)
.await
.map_err(|e| {
err!("Failed to run 'populate_userroomid_leftstate_table' migration': {e}")
})?;
}
if db["global"]
.get(FIXED_LOCAL_INVITE_STATE_MARKER)
.await
.is_not_found()
{
info!("Running migration 'fix_local_invite_state'");
fix_local_invite_state(services)
.await
.map_err(|e| err!("Failed to run 'fix_local_invite_state' migration': {e}"))?;
}
if services.globals.db.database_version().await < 19 {
services.globals.db.bump_database_version(19);
info!("Migration: Bumped database version to 19");
}
if db["global"].get(SPLIT_USERID_PASSWORD).await.is_not_found() {
info!("Running migration 'split_userid_password'");
split_userid_password(services)
.await
.map_err(|e| err!("Failed to run 'split_userid_password' migration': {e}"))?;
}
if db["global"]
.get(DROP_ROOMSYNCTOKEN_SHORTSTATEHASH)
.await
.is_not_found()
{
info!("Running migration 'drop_roomsynctoken_shortstatehash'");
obliterate_roomsynctoken_shortstatehash_with_extreme_prejudice(services)
.await
.map_err(|e| {
err!("Failed to run 'drop_roomsynctoken_shortstatehash' migration': {e}")
})?;
}
if db["global"].get(UNEMBED_UNSIGNED_INFO).await.is_not_found() {
services.server.runtime().spawn(unembed_unsigned_info(
services.db.clone(),
services.rooms.metadata.clone(),
services.rooms.timeline.clone(),
));
}
if db["global"]
.get(DROP_OLD_SIGNING_KEYS_STORAGE)
.await
.is_not_found()
{
services
.db
.db
.drop_column("server_signingkeys")
.inspect(|()| services.db["global"].insert(DROP_OLD_SIGNING_KEYS_STORAGE, []))
.map_err(|e| err!("Failed to drop server_signingkeys: {e:?}"))?;
}
assert_eq!(
services.globals.db.database_version().await,
DATABASE_VERSION,
@@ -358,7 +340,7 @@ async fn migrate(services: &Services) -> Result<()> {
Ok(())
}
async fn db_lt_12(services: &Services) -> Result<()> {
async fn fix_push_rule_names(services: &Services) -> Result<()> {
for username in &services
.users
.stream_local_users()
@@ -375,11 +357,15 @@ async fn db_lt_12(services: &Services) -> Result<()> {
},
};
let mut account_data: PushRulesEvent = services
let Some(mut account_data) = services
.account_data
.get_global(&user, GlobalAccountDataEventType::PushRules)
.get_global::<PushRulesEvent>(&user, GlobalAccountDataEventType::PushRules)
.await
.expect("Username is invalid");
.ok()
else {
// Skip users with no push rules
continue;
};
let rules_list = &mut account_data.content.global;
@@ -433,12 +419,10 @@ async fn db_lt_12(services: &Services) -> Result<()> {
.await?;
}
services.globals.db.bump_database_version(12);
info!("Migration: 11 -> 12 finished");
Ok(())
}
async fn db_lt_13(services: &Services) -> Result<()> {
async fn fix_server_default_push_rules(services: &Services) -> Result<()> {
for username in &services
.users
.stream_local_users()
@@ -455,11 +439,15 @@ async fn db_lt_13(services: &Services) -> Result<()> {
},
};
let mut account_data: PushRulesEvent = services
let Some(mut account_data) = services
.account_data
.get_global(&user, GlobalAccountDataEventType::PushRules)
.get_global::<PushRulesEvent>(&user, GlobalAccountDataEventType::PushRules)
.await
.expect("Username is invalid");
.ok()
else {
// Skip users with no push rules
continue;
};
let user_default_rules = Ruleset::server_default(&user);
account_data
@@ -478,8 +466,6 @@ async fn db_lt_13(services: &Services) -> Result<()> {
.await?;
}
services.globals.db.bump_database_version(13);
info!("Migration: 12 -> 13 finished");
Ok(())
}
@@ -488,7 +474,6 @@ async fn fix_bad_double_separator_in_state_cache(services: &Services) -> Result<
let db = &services.db;
let roomuserid_joined = &db["roomuserid_joined"];
let _cork = db.cork_and_sync();
let mut iter_count: usize = 0;
roomuserid_joined
@@ -520,9 +505,6 @@ async fn fix_bad_double_separator_in_state_cache(services: &Services) -> Result<
})
.await;
db.db.sort()?;
db["global"].insert(b"fix_bad_double_separator_in_state_cache", []);
info!("Finished fixing");
Ok(())
}
@@ -530,9 +512,6 @@ async fn fix_bad_double_separator_in_state_cache(services: &Services) -> Result<
async fn retroactively_fix_bad_data_from_roomuserid_joined(services: &Services) -> Result<()> {
info!("Retroactively fixing bad data from broken roomuserid_joined");
let db = &services.db;
let _cork = db.cork_and_sync();
let room_ids = services.rooms.metadata.iter_ids().collect::<Vec<_>>().await;
for room_id in &room_ids {
@@ -603,9 +582,6 @@ async fn retroactively_fix_bad_data_from_roomuserid_joined(services: &Services)
.await;
}
db.db.sort()?;
db["global"].insert(b"retroactively_fix_bad_data_from_roomuserid_joined", []);
info!("Finished fixing");
Ok(())
}
@@ -613,10 +589,7 @@ async fn retroactively_fix_bad_data_from_roomuserid_joined(services: &Services)
async fn fix_referencedevents_missing_sep(services: &Services) -> Result {
info!("Fixing missing record separator between room_id and event_id in referencedevents");
let db = &services.db;
let cork = db.cork_and_sync();
let referencedevents = db["referencedevents"].clone();
let referencedevents = services.db["referencedevents"].clone();
let totals: (usize, usize) = (0, 0);
let (total, fixed) = referencedevents
@@ -645,11 +618,8 @@ async fn fix_referencedevents_missing_sep(services: &Services) -> Result {
})
.await;
drop(cork);
info!(?total, ?fixed, "Fixed missing record separators in 'referencedevents'.");
db["global"].insert(b"fix_referencedevents_missing_sep", []);
db.db.sort()
Ok(())
}
async fn fix_readreceiptid_readreceipt_duplicates(services: &Services) -> Result {
@@ -659,7 +629,6 @@ async fn fix_readreceiptid_readreceipt_duplicates(services: &Services) -> Result
info!("Fixing undeleted entries in readreceiptid_readreceipt...");
let db = &services.db;
let cork = db.cork_and_sync();
let readreceiptid_readreceipt = db["readreceiptid_readreceipt"].clone();
let mut cur_room: Option<ArrayId> = None;
@@ -684,14 +653,10 @@ async fn fix_readreceiptid_readreceipt_duplicates(services: &Services) -> Result
})
.await;
drop(cork);
info!(?total, ?fixed, "Fixed undeleted entries in readreceiptid_readreceipt.");
db["global"].insert(b"fix_readreceiptid_readreceipt_duplicates", []);
db.db.sort()
Ok(())
}
const FIXED_CORRUPT_MSC4133_FIELDS_MARKER: &[u8] = b"fix_corrupt_msc4133_fields";
async fn fix_corrupt_msc4133_fields(services: &Services) -> Result {
// Due to an old bug, some conduwuit databases have `us.cloke.msc4175.tz`
// user profile fields with raw strings instead of quoted JSON ones.
@@ -703,7 +668,6 @@ async fn fix_corrupt_msc4133_fields(services: &Services) -> Result {
info!("Fixing corrupted `us.cloke.msc4175.tz` fields...");
let db = &services.db;
let cork = db.cork_and_sync();
let useridprofilekey_value = db["useridprofilekey_value"].clone();
let (total, fixed) = useridprofilekey_value
@@ -742,21 +706,15 @@ async fn fix_corrupt_msc4133_fields(services: &Services) -> Result {
)
.await?;
drop(cork);
info!(?total, ?fixed, "Fixed corrupted `us.cloke.msc4175.tz` fields.");
db["global"].insert(FIXED_CORRUPT_MSC4133_FIELDS_MARKER, []);
db.db.sort()?;
Ok(())
}
const POPULATED_USERROOMID_LEFTSTATE_TABLE_MARKER: &str = "populate_userroomid_leftstate_table";
async fn populate_userroomid_leftstate_table(services: &Services) -> Result {
type KeyVal = (Key, Raw<Option<Pdu>>);
type Key = (OwnedUserId, OwnedRoomId);
let db = &services.db;
let cork = db.cork_and_sync();
let userroomid_leftstate = db["userroomid_leftstate"].clone();
let (total, fixed, _) = userroomid_leftstate
@@ -817,15 +775,10 @@ async fn populate_userroomid_leftstate_table(services: &Services) -> Result {
)
.await?;
drop(cork);
info!(?total, ?fixed, "Fixed entries in `userroomid_leftstate`.");
db["global"].insert(POPULATED_USERROOMID_LEFTSTATE_TABLE_MARKER, []);
db.db.sort()?;
Ok(())
}
const FIXED_LOCAL_INVITE_STATE_MARKER: &str = "fix_local_invite_state";
async fn fix_local_invite_state(services: &Services) -> Result {
// Clean up the effects of !1249 by caching stripped state for invites
@@ -833,7 +786,6 @@ async fn fix_local_invite_state(services: &Services) -> Result {
type Key = (OwnedUserId, OwnedRoomId);
let db = &services.db;
let cork = db.cork_and_sync();
let userroomid_invitestate = db["userroomid_invitestate"].clone();
// for each user invited to a room
@@ -871,20 +823,14 @@ async fn fix_local_invite_state(services: &Services) -> Result {
})
.await?;
drop(cork);
info!(?fixed, "Fixed local invite state cache entries.");
db["global"].insert(FIXED_LOCAL_INVITE_STATE_MARKER, []);
db.db.sort()?;
Ok(())
}
const SPLIT_USERID_PASSWORD: &str = "split_userid_password";
async fn split_userid_password(services: &Services) -> Result {
// Split remote and deactivated users out from the `userid_password` table
let db = &services.db;
let cork = db.cork_and_sync();
let userid_password = db["userid_password"].clone();
let remoteuserid_remoteuser = db["remoteuserid_remoteuser"].clone();
let userid_deactivated = db["userid_deactivated"].clone();
@@ -912,15 +858,11 @@ async fn split_userid_password(services: &Services) -> Result {
})
.await;
drop(cork);
info!(?remote_users, "Split userid_password.");
db["global"].insert(SPLIT_USERID_PASSWORD, []);
db.db.sort()?;
Ok(())
}
const DROP_ROOMSYNCTOKEN_SHORTSTATEHASH: &str = "drop_roomsynctoken_shortstatehash";
async fn obliterate_roomsynctoken_shortstatehash_with_extreme_prejudice(
services: &Services,
) -> Result {
@@ -928,18 +870,14 @@ async fn obliterate_roomsynctoken_shortstatehash_with_extreme_prejudice(
info!("Cleared roomsynctoken_shortstatehash.");
services.db["global"].insert(DROP_ROOMSYNCTOKEN_SHORTSTATEHASH, []);
Ok(())
}
const UNEMBED_UNSIGNED_INFO: &str = "unembed_unsigned_info";
#[tracing::instrument(name = "unembed_unsigned_info", skip_all)]
async fn unembed_unsigned_info(
db: Arc<Database>,
metadata: Arc<rooms::metadata::Service>,
timeline: Arc<rooms::timeline::Service>,
) -> Result {
) {
type Map = BTreeMap<String, Box<serde_json::value::RawValue>>;
info!(
"Starting background migration. This may take a long time, and may cause your server to \
@@ -996,10 +934,13 @@ async fn unembed_unsigned_info(
info!(elapsed=?start.elapsed(), "Migrated {migrated} PDUs in {room_id}");
}
db["global"].insert(UNEMBED_UNSIGNED_INFO, []);
info!(elapsed=?start.elapsed(), total_migrated_pdus=total_migrated, "Finished migration.");
}
async fn drop_server_signingkeys(services: &Services) -> Result<()> {
services.db.db.drop_column("server_signingkeys")?;
info!("Cleared server_signingkeys.");
Ok(())
}
const DROP_OLD_SIGNING_KEYS_STORAGE: &str = "drop_server_signingkeys";
+2 -1
View File
@@ -571,7 +571,8 @@ impl Service {
));
}
let device_id = self.services
let device_id = self
.services
.users
.create_device(
&authorizing_user,
+68 -30
View File
@@ -47,7 +47,7 @@ pub struct Service {
struct Data {
openidsubject_localpart: Arc<Map>,
openidsubject_currentpictureurl: Arc<Map>,
openidsubjectprofilefield_url: Arc<Map>,
}
struct Services {
config: Dep<config::Service>,
@@ -144,7 +144,7 @@ impl crate::Service for Service {
runtime: args.server.runtime().clone(),
db: Data {
openidsubject_localpart: args.db["openidsubject_localpart"].clone(),
openidsubject_currentpictureurl: args.db["openidsubject_currentpictureurl"].clone(),
openidsubjectprofilefield_url: args.db["openidsubjectprofilefield_url"].clone(),
},
client: args.server.config.oauth.oidc.as_ref().map(|config| -> Result<OidcClient> {
Ok(OidcClient {
@@ -214,6 +214,10 @@ impl crate::Service for Service {
}
impl Service {
// Profile keys that will be treated as image URLs and imported
// into the media repository. Keep this synced with the list in the
// doc comment for `profile_key_map` in the config.
const IMAGE_PROFILE_KEYS: &[&str] = &["avatar_url", "chat.commet.profile_banner"];
const SERVER_MISCONFIGURED: &str =
"Identity server is misconfigured. Contact your homeserver's administrator.";
@@ -275,7 +279,7 @@ impl Service {
session: PendingSession,
response: AuthorizationCodeResponse,
) -> Result<Claims, &'static str> {
let Some(OidcClient { machine, client, .. }) = self.client.as_ref() else {
let Some(OidcClient { machine, client, config, .. }) = self.client.as_ref() else {
return Err("Delegated authentication is not enabled on this server.");
};
@@ -293,7 +297,8 @@ impl Service {
.await
.map_err(|err| {
error!(error=?err, "Failed to exchange OIDC authorization code");
"Code exchange failed."
"Code exchange failed. The identity provider may be unreachable. Contact your \
homeserver's administrator."
})?;
let Some(id_token) = token_response.id_token() else {
@@ -301,8 +306,14 @@ impl Service {
return Err(Self::SERVER_MISCONFIGURED);
};
let verifier = machine
.id_token_verifier()
.set_other_audience_verifier_fn(|audience| {
config.additional_trusted_audiences.contains(audience)
});
let claims = id_token
.claims(&machine.id_token_verifier(), &session.nonce)
.claims(&verifier, &session.nonce)
.map_err(|err| {
error!("Failed to verify id token claims: {err}");
Self::SERVER_MISCONFIGURED
@@ -426,41 +437,66 @@ impl Service {
let user_id = user_id.clone();
let subject = claims.subject().to_string();
let profile_key_map = config.profile_key_map.clone();
let openidsubject_currentpictureurl = self.db.openidsubject_currentpictureurl.clone();
let openidsubjectprofilefield_url = self.db.openidsubjectprofilefield_url.clone();
let users = self.services.users.clone();
let media = self.services.media.clone();
let import_task = self.runtime.spawn(async move {
// TODO: once we get support for full profile replacement, use
// that logic instead
for (field, claim) in &profile_key_map {
let Some(value) = all_claims.get(claim).cloned() else {
warn!(?field, ?claim, "IDP provided no value for this mapped claim");
continue;
};
let value = if let Some(picture_url) = value.as_str()
&& field == ProfileFieldName::AvatarUrl.as_str()
&& openidsubject_currentpictureurl
.get(&subject)
.await
.deserialized::<String>()
.ok()
.is_none_or(|current_picture| current_picture != picture_url)
{
match media.download_media(picture_url).await {
| Ok((mxc, size)) => {
openidsubject_currentpictureurl.insert(&subject, picture_url);
info!(?picture_url, ?mxc, ?size, "Downloaded profile picture");
let value = if Self::IMAGE_PROFILE_KEYS.contains(&field.as_str()) {
if let Some(url) = value.as_str() {
// Check the last value the IDP gave us for this
// profile field. We have to track this in a
// separate keyspace because, for fields in
// `IMAGE_PROFILE_KEYS`, what gets saved in
// the user's profile data is a MXC URI that has no
// relationship to the URL the IDP gave us.
if openidsubjectprofilefield_url
.qry(&(&subject, field))
.await
.deserialized::<String>()
.ok()
.is_none_or(|current_url| current_url != url)
{
match media.download_media(url).await {
| Ok((mxc, _)) => {
openidsubjectprofilefield_url.put((&subject, field), url);
info!(?url, ?field, ?mxc, "Downloaded profile image");
ProfileFieldValue::AvatarUrl(mxc)
},
| Err(err) => {
warn!(
?claim,
?picture_url,
"Failed to download profile picture: {err}"
);
ProfileFieldValue::new(
field,
Value::String(mxc.to_string()),
)
.expect("MXC should be valid for this field")
},
| Err(err) => {
warn!(
?field,
?url,
"Failed to download profile image: {err}"
);
continue;
},
}
} else {
// This claim hasn't changed from its previous
// value, don't update it.
continue;
},
}
} else {
warn!(
?claim,
?value,
"Claim value for profile image was not a string"
);
continue;
}
} else {
match ProfileFieldValue::new(field, value.clone()) {
@@ -492,8 +528,10 @@ impl Service {
info!("Profile import complete");
});
// Only wait for import to complete if this is a new account,
// so they see the correct profile information in the account panel
// Only wait for the import to complete if this is a new account,
// so they see the correct profile information in the account panel.
// Otherwise let it run in the background to avoid blocking the
// sign-in process.
if new_account_registered {
let _ = import_task.await;
}
+6 -2
View File
@@ -72,7 +72,10 @@ impl std::fmt::Display for ValidTokenSource {
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
let registration_tokens_from_file = args.server.config.registration_token_file
let registration_tokens_from_file = args
.server
.config
.registration_token_file
.clone()
// If the token file option was set, read the path it points to
.map(std::fs::read_to_string)
@@ -80,7 +83,8 @@ impl crate::Service for Service {
.map_err(|err| err!("Failed to read registration token file: {err}"))
.map(|tokens| {
if let Some(tokens) = tokens {
// If the token file option was set, return the file's lines as tokens
// If the token file option was set, return the file's lines
// as tokens
tokens.lines().map(ToOwned::to_owned).collect()
} else {
// Otherwise, if the option wasn't set, return no tokens
+11 -3
View File
@@ -160,9 +160,15 @@ impl super::Service {
ready(auth_events_by_key.get(&key).map(ToOwned::to_owned))
};
state_res::event_auth::auth_check(room_version_rules, pdu, state_fetch, create_event)
.await
.map_err(|e| err!("Event self-authentication failed: {e:?}"))
state_res::event_auth::auth_check(
room_version_rules,
pdu,
None, // TODO: third party invite
state_fetch,
create_event,
)
.await
.map_err(|e| err!("Event self-authentication failed: {e:?}"))
}
/// Checks that the event passes PDU check 5, which ensures that the event
@@ -236,6 +242,7 @@ impl super::Service {
let auth_check = state_res::event_auth::auth_check(
room_version_rules,
incoming_pdu,
None, // TODO: third party invite
|ty, sk| state_fetch(ty.clone(), sk.into()),
create_event.as_pdu(),
)
@@ -285,6 +292,7 @@ impl super::Service {
state_res::event_auth::auth_check(
room_version_rules,
incoming_pdu,
None, // third-party invite
state_fetch,
create_event.as_pdu(),
)
+36 -7
View File
@@ -520,7 +520,7 @@ impl Service {
let pdu = match Pdu::from_id_val(&event_id, value.clone()) {
| Ok(pdu) => pdu,
| Err(e) => {
debug_warn!("Invalid PDU in send_join response: {e:?}: {value:#?}");
warn!("Invalid PDU in send_join response: {e:?}: {value:#?}");
return state;
},
};
@@ -550,7 +550,7 @@ impl Service {
info!("Going through send_join response auth_chain");
let cork = self.services.db.cork_and_flush();
send_join_response
let send_join_auth_chain = send_join_response
.room_state
.auth_chain
.iter()
@@ -561,10 +561,22 @@ impl Service {
.verify_event_json_no_fetch_add_event_id(pdu, &room_version_rules)
})
.ready_filter_map(Result::ok)
.ready_for_each(|(event_id, value)| {
.ready_fold(Vec::new(), |mut chain, (event_id, value)| {
trace!(%event_id, "Adding PDU as an outlier from send_join auth_chain");
self.services.outlier.add_pdu_outlier(&event_id, &value);
self.services.pdu_metadata.clear_pdu_markers(&event_id);
let state_key = value
.get("state_key")
.and_then(|s| s.as_str())
.unwrap_or_default()
.to_owned();
let event_type = value
.get("type")
.and_then(|s| s.as_str())
.unwrap_or_default()
.to_owned();
chain.push((event_type, state_key));
chain
})
.await;
@@ -578,20 +590,37 @@ impl Service {
let event_id = fetch_state.get(&shortstatekey)?;
self.services.timeline.get_pdu(event_id).await.ok()
};
let Some(create_event) = state_fetch(StateEventType::RoomCreate, "".into()).await else {
let in_auth_chain = send_join_auth_chain
.iter()
.any(|(t, s)| t == "m.room.create" && s.is_empty());
return Err!(BadServerResponse(debug_error!(
?state,
"bad response from {remote_server}: m.room.create event is missing from \
send_join state{}",
if in_auth_chain {
", but it was found in the auth_chain"
} else {
""
}
)));
};
drop(send_join_auth_chain);
let auth_check = state_res::event_auth::auth_check(
&room_version.rules().unwrap(),
&parsed_join_pdu,
None, // TODO: third party invite
|k, s| state_fetch(k.clone(), s.into()),
&state_fetch(StateEventType::RoomCreate, "".into())
.await
.expect("create event is missing from send_join auth"),
&create_event,
)
.await
.map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?;
if !auth_check {
return Err!(Request(Forbidden("Auth check failed")));
return Err!(Request(Forbidden(
"Join event returned by {remote_server} is not self-authorised (try again?)"
)));
}
let resident_before = self
.services
+3 -11
View File
@@ -77,20 +77,12 @@ impl super::Service {
room_id: &RoomId,
event_id: &EventId,
) -> bool {
let currently_member = self.services.state_cache.is_joined(user_id, room_id).await;
let Ok(shortstatehash) = self.pdu_shortstatehash(event_id).await else {
// We haven't calculated the state at this event, so we can't
// properly history visibility check it. This happens for outliers
// and backfilled events. Since continuwuity is primarily targeting
// single-user/trusted deployments, an acceptable compromise for now
// is to ensure that the user is currently joined to the room.
// Federation fails closed here, but if that was replicated for the
// check used for client-server, nobody would be allowed to see
// events before their server started participating in the room.
return currently_member;
return true;
};
let currently_member = self.services.state_cache.is_joined(user_id, room_id).await;
let history_visibility = self
.state_get_content(shortstatehash, &StateEventType::RoomHistoryVisibility, "")
.await
+44 -41
View File
@@ -164,12 +164,12 @@ impl Service {
}
let mut children: Vec<_> = summary
.children_state
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Filter out non-suggested children if suggested_only is set
.filter(|child| !suggested_only || child.content.suggested)
.children_state
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Filter out non-suggested children if suggested_only is set
.filter(|child| !suggested_only || child.content.suggested)
.collect();
children.sort();
let children = children
@@ -323,43 +323,46 @@ impl Service {
};
let (accessible_children, inaccessible_children) = children_state
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Fetch summaries for the children in parallel
.stream()
.broad_then(async |child| {
let summary = {
if let Some(summary) = self.build_local_room_summary(&child.state_key).await {
if self.server_may_see_summary(querying_server, &summary).await {
Accessibility::Accessible(summary)
} else {
Accessibility::Inaccessible
}
} else {
Accessibility::NotFound
}
};
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Fetch summaries for the children in parallel
.stream()
.broad_then(async |child| {
let summary = {
if let Some(summary) = self.build_local_room_summary(&child.state_key).await {
if self.server_may_see_summary(querying_server, &summary).await {
Accessibility::Accessible(summary)
} else {
Accessibility::Inaccessible
}
} else {
Accessibility::NotFound
}
};
(child.state_key, summary)
})
// Sort the children into two Vecs by accessibility
.ready_fold_default(|(mut accessible_children, mut inaccessible_children): (Vec<_>, Vec<_>), (room_id, summary)| {
match summary {
Accessibility::Accessible(summary) => {
accessible_children.push(summary);
},
Accessibility::Inaccessible => {
inaccessible_children.push(room_id);
},
Accessibility::NotFound => {
// Skip inaccessible children
}
}
(child.state_key, summary)
})
// Sort the children into two Vecs by accessibility
.ready_fold_default(
|(mut accessible_children, mut inaccessible_children): (Vec<_>, Vec<_>),
(room_id, summary)| {
match summary {
| Accessibility::Accessible(summary) => {
accessible_children.push(summary);
},
| Accessibility::Inaccessible => {
inaccessible_children.push(room_id);
},
| Accessibility::NotFound => {
// Skip inaccessible children
},
}
(accessible_children, inaccessible_children)
})
.await;
(accessible_children, inaccessible_children)
},
)
.await;
Accessibility::Accessible(assign!(
get_hierarchy::v1::Response::new(SpaceHierarchyParentSummary::new(summary, children_state)),
+35 -118
View File
@@ -3,10 +3,7 @@ use std::{collections::BTreeMap, sync::Arc};
use conduwuit::result::LogErr;
use conduwuit_core::{
Event, Result, err,
matrix::{
event::RelationTypeEqual,
pdu::{PduCount, PduEvent, PduId, RawPduId},
},
matrix::pdu::{PduCount, PduEvent, PduId, RawPduId},
utils::{
ReadyExt,
stream::{TryIgnore, WidebandExt},
@@ -15,14 +12,9 @@ use conduwuit_core::{
use conduwuit_database::{Deserialized, Map};
use futures::{Stream, StreamExt};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedUserId, RoomId, UInt, UserId,
api::{Direction, client::threads::get_threads::v1::IncludeThreads},
events::{
AnySyncMessageLikeEvent, AnySyncTimelineEvent,
relation::{BundledThread, RelationType},
},
serde::Raw,
uint,
CanonicalJsonValue, EventId, OwnedUserId, RoomId, UserId,
api::client::threads::get_threads::v1::IncludeThreads, events::relation::BundledThread,
serde::Raw, uint,
};
use serde_json::json;
@@ -35,7 +27,6 @@ pub struct Service {
struct Services {
short: Dep<rooms::short::Service>,
pdu_metadata: Dep<rooms::pdu_metadata::Service>,
timeline: Dep<rooms::timeline::Service>,
}
@@ -51,7 +42,6 @@ impl crate::Service for Service {
},
services: Services {
short: args.depend::<rooms::short::Service>("rooms::short"),
pdu_metadata: args.depend::<rooms::pdu_metadata::Service>("rooms::pdu_metadata"),
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
},
}))
@@ -61,88 +51,6 @@ impl crate::Service for Service {
}
impl Service {
/// Serializes an event for the `latest_event` of a thread's aggregation,
/// stripping `unsigned` as we don't want to send e.g. txnid to clients.
fn latest_event<E>(event: &E) -> Raw<AnySyncMessageLikeEvent>
where
E: Event,
{
let mut latest_pdu = event.clone().into_pdu();
latest_pdu.unsigned = None;
latest_pdu
.into_format::<Raw<AnySyncTimelineEvent>>()
.cast_unchecked()
}
fn set_thread(unsigned: &mut CanonicalJsonObject, thread: BundledThread) {
let content = serde_json::to_value(thread).expect("to_value always works");
unsigned.insert(
"m.relations".to_owned(),
json!({ "m.thread": content })
.try_into()
.expect("thread is valid json"),
);
}
/// Remove `event` from the aggregation of the thread matching
/// `root_event_id`
pub async fn remove_from_thread<E>(&self, root_event_id: &EventId, event: &E) -> Result
where
E: Event + Send + Sync,
{
let Ok(root_id) = self.services.timeline.get_pdu_id(root_event_id).await else {
return Ok(());
};
let mut root_pdu_json = self
.services
.timeline
.get_pdu_json_from_id(&root_id)
.await
.map_err(|e| err!(Database("Thread root pdu not found: {e:?}")))?;
let Some(CanonicalJsonValue::Object(unsigned)) = root_pdu_json.get_mut("unsigned") else {
return Ok(());
};
let thread: Vec<_> = self
.services
.pdu_metadata
.get_relations(
event.sender(),
&event.room_id_or_hash(),
root_event_id,
PduCount::max(),
usize::MAX,
0,
Direction::Backward,
)
.await
.into_iter()
.filter(|(_, pdu)| RelationType::Thread.relation_type_equal(pdu))
.collect();
match thread.first() {
| Some((_, latest)) => Self::set_thread(
unsigned,
BundledThread::new(
Self::latest_event(latest),
thread.len().try_into().unwrap_or(UInt::MAX),
true,
),
),
| None => {
// No events are left in the thread, or the root is backfilled
unsigned.remove("m.relations");
},
}
self.services
.timeline
.replace_pdu(&root_id, &root_pdu_json)
.await
}
pub async fn add_to_thread<E>(&self, root_event_id: &EventId, event: &E) -> Result
where
E: Event + Send + Sync,
@@ -170,20 +78,11 @@ impl Service {
.await
.map_err(|e| err!(Request(InvalidParam("Thread root pdu not found: {e:?}"))))?;
// get_relations doesn't support backfilled targets, so redactions
// couldn't update the aggregation of a backfilled root
//
// TODO: Support backfilled threads. This needs
// `src/service/rooms/pdu_metadata/mod.rs`'s
// (TODO: Relations with backfilled pdus) to be implemented,
// and then this check can be removed.
if matches!(root_id.pdu_count(), PduCount::Normal(_))
&& let CanonicalJsonValue::Object(unsigned) = root_pdu_json
.entry("unsigned".to_owned())
.or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default()))
if let CanonicalJsonValue::Object(unsigned) = root_pdu_json
.entry("unsigned".to_owned())
.or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default()))
{
let latest_event = Self::latest_event(event);
let thread = match unsigned
if let Some(mut relations) = unsigned
.get("m.relations")
.and_then(|r| r.as_object())
.and_then(|r| r.get("m.thread"))
@@ -191,16 +90,34 @@ impl Service {
serde_json::from_value::<BundledThread>(relations.clone().into()).ok()
}) {
// Thread already existed
| Some(mut thread) => {
thread.count = thread.count.saturating_add(uint!(1));
thread.latest_event = latest_event;
thread
},
// New thread
| None => BundledThread::new(latest_event, uint!(1), true),
};
relations.count = relations.count.saturating_add(uint!(1));
relations.latest_event = Raw::from_json(event.content().to_owned());
Self::set_thread(unsigned, thread);
let content = serde_json::to_value(relations).expect("to_value always works");
unsigned.insert(
"m.relations".to_owned(),
json!({ "m.thread": content })
.try_into()
.expect("thread is valid json"),
);
} else {
// New thread
let relations = BundledThread::new(
Raw::from_json(event.content().to_owned()),
uint!(1),
true,
);
let content = serde_json::to_value(relations).expect("to_value always works");
unsigned.insert(
"m.relations".to_owned(),
json!({ "m.thread": content })
.try_into()
.expect("thread is valid json"),
);
}
self.services
.timeline
+7 -2
View File
@@ -449,7 +449,12 @@ impl super::Service {
// Don't notify the sender of their own events, and don't send from ignored users
.ready_filter(|user| *user != pdu.sender())
.filter_map(|recipient_user| async move {
(!self.services.users.user_is_ignored(pdu.sender(), &recipient_user).await).then_some(recipient_user)
(!self
.services
.users
.user_is_ignored(pdu.sender(), &recipient_user)
.await)
.then_some(recipient_user)
})
.collect()
.await;
@@ -806,7 +811,7 @@ impl super::Service {
.read()
.await
.values()
.map(ToOwned::to_owned) // TODO: is this to_owned expensive?
.map(ToOwned::to_owned) // TODO: is this to_owned expensive?
.collect::<Vec<_>>();
interested_appservices
.stream()
+9 -4
View File
@@ -252,10 +252,15 @@ impl super::Service {
| _ => create_pdu.as_ref().unwrap().as_pdu(),
};
let auth_check =
state_res::auth_check(&room_version_rules, &pdu, auth_fetch, create_event)
.await
.map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?;
let auth_check = state_res::auth_check(
&room_version_rules,
&pdu,
None, // TODO: third_party_invite
auth_fetch,
create_event,
)
.await
.map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?;
if !auth_check {
return Err!(Request(Forbidden("Event is not authorized.")));
+3 -25
View File
@@ -2,11 +2,10 @@ use conduwuit_core::{
Result, err,
matrix::event::Event,
utils::{self},
warn,
};
use ruma::{EventId, events::room::encrypted::Relation};
use ruma::EventId;
use super::{ExtractBody, ExtractRelatesTo};
use super::ExtractBody;
use crate::rooms::short::ShortRoomId;
impl super::Service {
@@ -32,12 +31,6 @@ impl super::Service {
err!(Database(error!(?pdu_id, %event_id, ?e, "PDU ID points to invalid PDU.")))
})?;
let thread_root = match pdu.get_content::<ExtractRelatesTo>() {
| Ok(ExtractRelatesTo { relates_to: Relation::Thread(thread) }) =>
Some(thread.event_id),
| _ => None,
};
if let Ok(content) = pdu.get_content::<ExtractBody>() {
if let Some(body) = content.body {
self.services
@@ -58,21 +51,6 @@ impl super::Service {
err!(Database(error!(%event_id, ?e, "Failed to convert PDU to canonical JSON")))
})?;
self.replace_pdu(&pdu_id, &obj).await?;
// So the thread's root doesn't keep the original content in its
// `latest_event` aggregation
if let Some(thread_root) = thread_root {
self.services
.threads
.remove_from_thread(&thread_root, &pdu)
.await
.inspect_err(|e| {
warn!("Failed to remove redacted event from thread {thread_root}: {e:?}");
})
.ok();
}
Ok(())
self.replace_pdu(&pdu_id, &obj).await
}
}
+2 -5
View File
@@ -156,12 +156,9 @@ impl super::Service {
}
#[cfg(test)]
#[allow(clippy::unreadable_literal)]
mod tests {
use ruma::{
ServerSigningKeyId,
api::federation::discovery::get_server_keys::v2::Response as DirectKeysResponse,
owned_server_name, serde::Raw, server_name,
};
use ruma::{serde::Raw, server_name};
use super::*;
use crate::server_keys::Service;
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more