Compare commits

...
Author SHA1 Message Date
Ginger 52026bb0f1 chore: Formatting 2026-06-29 09:41:59 -04:00
Ginger aed8e7d769 fix: Adjust error code 2026-06-29 09:35:51 -04:00
Ginger 32fb6f247a fix: Use a LRU cache for storing pending auth code grants 2026-06-29 09:35:51 -04:00
Ginger 90e14abecb fix: Spacing 2026-06-29 09:35:51 -04:00
Ginger 6ced2511e4 chore: Clippy fixes 2026-06-29 09:35:51 -04:00
Ginger 93407ade03 fix: Accessibility improvements 2026-06-29 09:35:51 -04:00
Ginger 6742d9237a fix: More CSS tweaks 2026-06-29 09:35:51 -04:00
Ginger a32c7d0d9a fix: Set correct default for registration terms config section 2026-06-29 09:35:51 -04:00
Ginger 761a6a53d0 fix: Check for existing device when creating oauth session 2026-06-29 09:35:51 -04:00
Ginger c56c035c15 fix: Use RFC-compliant error responses for OAuth endpoints 2026-06-29 09:35:51 -04:00
Ginger c804bf5780 fix: Force trusted flow UI for first-run registration 2026-06-29 09:35:51 -04:00
Ginger b87afeef80 fix: Panic when trying to check an unknown UIAA stage type 2026-06-29 09:35:51 -04:00
Ginger d0c7a62ce7 fix: Use the right error code for CAPTCHA errors 2026-06-29 09:35:50 -04:00
Ginger 47582d1922 refactor: Update logic for checking if a username is available 2026-06-29 09:35:50 -04:00
Ginger 36a30f16b1 fix: CSS adjustments 2026-06-29 09:35:50 -04:00
Ginger 52ec6bc6da fix: Adjust error codes to comply with MSC4190 2026-06-29 09:35:50 -04:00
Ginger 74788dcb19 feat: Mark spec version 1.15 as supported 2026-06-29 09:35:50 -04:00
Ginger b35b72c34a feat: Add a page with some information about the server 2026-06-29 09:35:50 -04:00
Ginger c1fc76040a fix: Correct config file example section name 2026-06-29 09:35:50 -04:00
Ginger d1449d6575 chore: My Giant Future 2026-06-29 09:35:50 -04:00
Ginger 9fdeb61c1a feat: Improve account panel UI for locked and suspended accounts 2026-06-29 09:35:50 -04:00
Ginger 7c7d6762e2 fix: Include query parameters in link back to login on register page 2026-06-29 09:35:50 -04:00
Ginger eda46d63a8 fix: CSS tweaks 2026-06-29 09:35:50 -04:00
Ginger 9fc9063c83 feat: Improve registration UI in first-run mode 2026-06-29 09:35:50 -04:00
Ginger 430347fc66 fix: Minor wording improvements 2026-06-29 09:35:50 -04:00
Ginger 9df5c68d3c fix: Set default for allow_deactivation 2026-06-29 09:35:50 -04:00
Ginger 3ca068c985 fix: Fix registration terms example in config 2026-06-29 09:35:50 -04:00
Ginger 138ec05cf2 feat: Implement support for prompt=create in the authorization code flow 2026-06-29 09:35:50 -04:00
Ginger c7e5c8df22 fix: Don't let logged-in users access the registration page 2026-06-29 09:35:50 -04:00
Ginger 91afbd122f feat: Allow self-service deactivation to be disabled 2026-06-29 09:35:50 -04:00
Ginger daaf09cb26 refactor: Use more consistent terminology for email validation pages 2026-06-29 09:35:50 -04:00
Ginger e8d6fa565e feat: Add support for registering accounts with the web UI 2026-06-29 09:35:50 -04:00
Ginger 47af5d3a39 refactor: Change template context to allow using a CSP nonce 2026-06-29 09:35:49 -04:00
Ginger 63b5fd04be fix: Minor CSS improvements 2026-06-29 09:35:49 -04:00
Ginger d59a5c63f9 fix: Remove errant whitespace in device details 2026-06-29 09:35:48 -04:00
Ginger 16aaeae21c chore: News fragment 2026-06-29 09:35:48 -04:00
Ginger e60310eacc feat: Allow configuring the OAuth compatibility mode 2026-06-29 09:35:48 -04:00
Ginger 7b98ae54b5 fix: Use button styling for account management link on index page 2026-06-29 09:35:48 -04:00
Ginger d67d6ca895 fix: Use the right text color on input elements 2026-06-29 09:35:48 -04:00
Ginger 86d9e9e6a9 feat: Add support for account management deeplinks 2026-06-29 09:35:48 -04:00
Ginger b37480d6b2 fix: Return the correct error code for expired access tokens 2026-06-29 09:35:48 -04:00
Ginger 0d806a2038 feat: Add a page for viewing a device's details 2026-06-29 09:35:48 -04:00
Ginger 19700a081e fix: Use SameSite=Lax for session cookie 2026-06-29 09:35:48 -04:00
Ginger ed1b175fa4 feat: Allow devices to be removed from the account panel 2026-06-29 09:35:48 -04:00
Ginger a91fc7041a feat: Implement oauth token revocation 2026-06-29 09:35:48 -04:00
Ginger 18c59e036f chore: Clippy fixes 2026-06-29 09:35:48 -04:00
Ginger df3f646c92 feat: Implement oauth auth code and refresh token flows 2026-06-29 09:35:48 -04:00
Ginger fb6e5d2838 chore: Clippy fixes 2026-06-29 09:35:48 -04:00
Ginger 33be65a865 feat: Implement a web-based account management dashboard 2026-06-29 09:35:45 -04:00
Ginger 975ec24167 feat: Implement oauth service and client registration 2026-06-29 09:03:54 -04:00
Renovate Bot e8378e86fd chore(deps): update rust-zerover-patch-updates 2026-06-29 13:02:39 +00:00
Renovate Bot 57366ac90a chore(deps): update rust crate serde-saphyr to 0.0.28 2026-06-29 13:02:24 +00:00
Renovate Bot 9f8a716dc1 chore(deps): update node-patch-updates to v2.0.15 2026-06-29 13:01:10 +00:00
Renovate Bot 27367bac18 chore(deps): update github-actions-non-major 2026-06-29 05:03:03 +00:00
timedout 458e0b53ac style: Reformat 2026-06-27 18:41:43 +01:00
timedout 2d65d47498 fix: Load bearing mut refs 2026-06-27 18:37:33 +01:00
timedout e4922814b9 refactor: Add better documentation to sender service, add additional logging traces
This is a surprise tool that will help us later!
2026-06-27 18:37:33 +01:00
timedout 064028689c style: Add documentation to execute module of sender service 2026-06-27 18:37:33 +01:00
timedout 124241238e refactor: Rename "synapse"-related federation methods to "slow"
I won't even comment on how stupid that naming was.
2026-06-27 18:37:33 +01:00
timedout 967e2cc54f refactor: Split the users service into several modules
Also resolvers several lints, including needless async on create_user
2026-06-27 18:37:33 +01:00
timedout 6fdeadc356 style: Refactor admin crate, drop admin_command macro
`admin_command` depended on `implement`, which is now gone.
2026-06-27 18:37:26 +01:00
timedout 478560daae style: Remove now dead code 2026-06-27 18:36:44 +01:00
timedout 0310b4b2c5 style: Remove implement entirely 2026-06-27 18:36:44 +01:00
timedout 3eb4257ae8 style: Remove remaining implement imports 2026-06-27 18:36:44 +01:00
timedout f1d3db0ea3 style: Eliminate implement 2026-06-27 18:36:44 +01:00
timedout e7b302955f style: Eliminate implement database 2026-06-27 18:36:44 +01:00
timedout 85122c62cd style: Eliminate implement in database map keys 2026-06-27 18:36:44 +01:00
timedout ba0ffee7cf fix: Style errors and compile problems 2026-06-27 18:36:44 +01:00
timedout 86e1101b40 style: Remove implement for database pool 2026-06-27 18:36:44 +01:00
timedout fdcb7e3957 style: Remove implement for config Manager 2026-06-27 18:36:44 +01:00
timedout c54e56a73e style: Remove implement for AccessCheck, rename check to assert 2026-06-27 18:36:44 +01:00
timedout fed9a599d9 style: Refactor remaining parts of admin service 2026-06-27 18:36:44 +01:00
timedout 0bb97a53c5 style: Refactor account_data service 2026-06-27 18:36:44 +01:00
timedout 9b76c9a085 feat: Support arbitrary room versions while creating the admin room
Also changes the default power levels so people stop shooting their feet off
2026-06-27 18:36:44 +01:00
timedout 6f20b7bc3f style: Refactor config service 2026-06-27 18:36:44 +01:00
timedout 580d9b0318 style: Refactor federation service 2026-06-27 18:36:44 +01:00
timedout ae572ec108 style: Refactor key_backups service 2026-06-27 18:36:44 +01:00
timedout b1c5b3d000 style: Refactor media service 2026-06-27 18:36:44 +01:00
timedout 0c9230f35e style: Document & refactor resolver service
good riddance to this thing
2026-06-27 18:36:44 +01:00
timedout 77dab8fd20 style: Document & refactor rooms/alias service 2026-06-27 18:36:44 +01:00
timedout 10b5ca8e3a style: Document & refactor rooms/directory service 2026-06-27 18:36:44 +01:00
timedout f9eed42cb7 style: Document & refactor rooms/directory service 2026-06-27 18:36:44 +01:00
timedout 19f4c24c00 style: Document & refactor rooms/event_handler service 2026-06-27 18:36:44 +01:00
timedout 0a162b7bc4 style: Document & refactor rooms/lazy_loading service 2026-06-27 18:36:44 +01:00
timedout 0d1b130127 style: Document & refactor rooms/metadata service 2026-06-27 18:36:44 +01:00
timedout 5e0e82e7e8 style: Document & refactor rooms/outlier service 2026-06-27 18:36:44 +01:00
timedout 4bf0816bcc style: Document & refactor rooms/search service 2026-06-27 18:36:44 +01:00
timedout ecbe035b36 style: Document & refactor rooms/short service 2026-06-27 18:36:44 +01:00
timedout 4d30ee5d33 style: Document & refactor rooms/state_accessor service 2026-06-27 18:36:44 +01:00
timedout 4844c6ae3e style: Document & refactor rooms/state_cache service 2026-06-27 18:36:44 +01:00
timedout 6603798d60 style: Document & refactor rooms/state_compressor service 2026-06-27 18:36:44 +01:00
timedout 199f6eb67b style: Document & refactor rooms/user and rooms/timeline services 2026-06-27 18:36:44 +01:00
timedout aa2f506996 style: Document & refactor sending service 2026-06-27 18:36:44 +01:00
timedout a3994fe1a3 style: Document & refactor server_keys service 2026-06-27 18:36:44 +01:00
timedout 6312ff8088 style: Document & refactor sync service 2026-06-27 18:36:44 +01:00
timedout 17cff1fb36 style: Document & refactor users service 2026-06-27 18:36:44 +01:00
timedout aff6315ae1 style: Document moderation service 2026-06-27 18:36:44 +01:00
timedout 574d3e9164 style: Use impl instead of implement in moderation service 2026-06-27 18:36:44 +01:00
31a05b9c 21e93f8feb chore: changelog 2026-06-27 01:05:53 +01:00
31a05b9c 4b2f032ae6 feat: get-state-at admin command 2026-06-27 01:05:48 +01:00
Jade Ellis 8a495a7d7f fix(ci): Correct remote ref fetch 2026-06-27 01:00:33 +01:00
Jade Ellis cee51d5717 fix(ci): Correct remote ref fetch 2026-06-27 00:57:45 +01:00
Jade Ellis 0483d3e155 ci: Don't checkout repo in pull_request_target 2026-06-27 00:54:31 +01:00
timedout 2a4b9f9323 fix: Check are_all_blocked in server_filter_level 2026-06-24 20:13:17 +01:00
timedout 63a1a3d9ab feat: Advertise stable prefix in unstable features 2026-06-24 20:05:34 +01:00
timedout f19f5c71a5 chore(1875): Remove extra changelog entry 2026-06-24 19:13:35 +01:00
timedout b009ffd31c chore(1875): Add changelogs 2026-06-24 19:03:38 +01:00
timedout b6baf66399 feat: Support MSC4380 invite blocking
fix: Re-add silently dropped support for MSC4155
2026-06-24 18:59:49 +01:00
ginger 6dac46e1ad Update SECURITY.md 2026-06-24 13:00:27 +00:00
ginger 4d40e20fdd docs: Fix typo 2026-06-23 14:56:14 +00:00
Renovate Bot 3b455218f5 chore(deps): update rust crate itertools to 0.15.0 2026-06-23 13:53:25 +00:00
Renovate Bot de24fcbb8c chore(deps): update dependency cargo-bins/cargo-binstall to v1.20.1 2026-06-23 13:38:23 +00:00
Renovate Bot 2adb9a7941 chore(deps): update actions/checkout action to v7 2026-06-23 13:20:40 +00:00
Renovate Bot d81f4df61c chore(deps): update rust crate itertools to 0.15.0 2026-06-23 13:20:22 +00:00
Renovate Bot 6b259d15ee chore(deps): update rust-non-major 2026-06-23 13:20:10 +00:00
Renovate Bot eeef60d540 chore(deps): update github-actions-digest 2026-06-23 05:01:57 +00:00
Renovate Bot a01035e63a chore(deps): update github-actions-non-major to v43.234.0 2026-06-22 05:03:19 +00:00
stratself 52c1544e6f fix: Correct date in announcements 2026-06-21 02:36:32 +00:00
Jade Ellis ed38212391 fix(ci): Correct version regex in debian build 2026-06-21 01:03:14 +01:00
Jade 86fe98c90d chore: Admin announcement 2026-06-20 23:32:56 +00:00
Henry-Hiles 4078062331 fix: change the update-flake-hashes repo to work with the new rust.nix structure 2026-06-20 15:35:09 -04:00
Henry-Hiles 40935cf96a fix: use toolchain declared in rust-toolchain.toml for cross rust-std 2026-06-20 15:32:33 -04:00
Henry-Hiles 182c5a120e fix: add rocksdb as a flake package
This fixes the flake-hashes workflow.
2026-06-20 13:45:25 -04:00
Henry-Hiles 8e71ed7b63 fix: dynamically link rocksdb on dynamic nix builds
Fixes liburing error.
2026-06-20 13:19:35 -04:00
timedout 4696cbb751 fix: SEC12 2026-06-20 16:03:43 +01:00
timedout ebea06b687 fix: SEC11 2026-06-20 16:03:43 +01:00
timedout 62b58e1a6a fix: SEC16 2026-06-20 16:03:37 +01:00
Henry-Hiles 1ba90deeba chore: Change build workflows to run every week
Old behavior was to run every day, which is wasteful.
2026-06-19 22:58:32 -04:00
Henry-Hiles 71ed283141 chore: enable __structuredAttrs on build
This is a good practice for modern nix packages
2026-06-20 02:43:52 +00:00
Henry-Hiles a7ae7b2e75 fix: resolve review comment about Haswell CPUs 2026-06-20 02:43:52 +00:00
Henry-Hiles 0d45ae7e21 chore: more descriptive name for binary build step of workflow 2026-06-20 02:43:52 +00:00
Henry-Hiles 61e121ad5c feat: improve docs for building with nix 2026-06-20 02:43:52 +00:00
Henry-Hiles 31960beb75 fix: fix max-perf-static packages not statically linking 2026-06-20 02:43:52 +00:00
Henry-Hiles bdd9b6b50c chore: add changelog 2026-06-20 02:43:52 +00:00
Henry-Hiles 216033cf20 feat: add build-nix workflow 2026-06-20 02:43:52 +00:00
Henry-Hiles 95ddb1bbe5 feat: add max-perf package 2026-06-20 02:43:52 +00:00
Henry-Hiles 1ad4ca0f67 feat: add static binary build instructions to docs 2026-06-20 02:43:52 +00:00
Henry-Hiles 95790d8152 fix: don't do check on all builds
Checks can be done with `nix flake check`, no need to slow down build process with this.
2026-06-20 02:43:52 +00:00
Henry-Hiles 02c61b3840 fix: remove un-needed env vars that crane sets automatically 2026-06-20 02:43:52 +00:00
Henry-Hiles 6ee501ac69 feat: static builds using nix, including cross 2026-06-20 02:43:52 +00:00
spaetz 252ebb4642 CI: Remove the clang detection
tomfos.tr act-runner image removed the possibility to install the latest LLVM using an installer script, so let us also remove the detection and just live with the distro's clang image.
2026-06-19 11:23:53 +00:00
Renovate Bot 0fb95df7a5 chore(deps): update rust crate tower-http to 0.7.0 2026-06-18 05:03:03 +00:00
Jade Ellis a72eda19f1 chore: Release 2026-06-17 15:12:50 +01:00
Jade Ellis 4fc808114f chore: Release 2026-06-17 15:05:23 +01:00
Ginger e3a9549824 fix: Correctly sync newly created rooms 2026-06-16 23:41:51 -04:00
Ginger 073c033ab8 fix: Don't panic on missing SSH in sliding sync 2026-06-16 23:41:51 -04:00
Ginger 6e42be95bc fix: Additional sync logic fixes 2026-06-16 23:41:51 -04:00
Ginger 1a77f57af5 fix: Upgrade warning on room load failures to error 2026-06-16 23:41:51 -04:00
Ginger d427df0238 fix: Don't panic on missing SSH 2026-06-16 23:41:51 -04:00
Ginger f9f3ebe571 fix: Calculate state at end of last sync correctly 2026-06-16 23:41:51 -04:00
Ginger 5969c1ae94 chore: News fragments 2026-06-16 23:41:51 -04:00
Ginger 523016a42b feat: Add support for state_after 2026-06-16 23:41:51 -04:00
Ginger 7c42f6075b feat: Remove all uses of roomsynctoken_shortstatehash 2026-06-16 23:41:51 -04:00
Renovate Bot bc37f7fc5b chore(deps): update rust crate serde-saphyr to 0.0.27 2026-06-16 18:29:02 +00:00
284 changed files with 9897 additions and 4491 deletions

No files matched your search

+1 -1
View File
@@ -71,7 +71,7 @@ runs:
- name: Install timelord-cli and git-warp-time - name: Install timelord-cli and git-warp-time
if: steps.check-binaries.outputs.need-install == 'true' if: steps.check-binaries.outputs.need-install == 'true'
uses: https://github.com/taiki-e/install-action@15449e3094499af05d8d964a1c884208e4b8b595 # v2 uses: https://github.com/taiki-e/install-action@9e1e5806d4a4822de933115878265be9aaa786d9 # v2
with: with:
tool: git-warp-time,timelord-cli@3.0.1 tool: git-warp-time,timelord-cli@3.0.1
+5 -16
View File
@@ -10,7 +10,7 @@ on:
- "v*.*.*" - "v*.*.*"
workflow_dispatch: workflow_dispatch:
schedule: schedule:
- cron: '30 0 * * *' - cron: '30 0 * * 1'
jobs: jobs:
build: build:
@@ -41,20 +41,9 @@ jobs:
# else # else
# echo "No workaround needed for llvm-project#153385" # echo "No workaround needed for llvm-project#153385"
# fi # fi
- name: Pick compatible clang version
id: clang-version
run: |
# both latest need to use clang-23, but oldstable and previous can just use clang
if [[ "${{ matrix.container }}" == "ubuntu-latest" ]]; then
echo "Using clang-23 package for ${{ matrix.container }}"
echo "version=clang-23" >> $GITHUB_OUTPUT
else
echo "Using default clang package for ${{ matrix.container }}"
echo "version=clang" >> $GITHUB_OUTPUT
fi
- name: Checkout repository with full history - name: Checkout repository with full history
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
fetch-depth: 0 fetch-depth: 0
ref: ${{ github.ref_name }} ref: ${{ github.ref_name }}
@@ -93,10 +82,10 @@ jobs:
# VERSION is the package version, COMPONENT is used in # VERSION is the package version, COMPONENT is used in
# apt's repository config like a git repo branch # apt's repository config like a git repo branch
VERSION=$BASE_VERSION VERSION=$BASE_VERSION
if [[ ${{ forge.ref_name }} =~ ^v+[0-9]\.+[0-9]\.+[0-9]$ ]]; then if [[ ${{ forge.ref_name }} =~ ^v+[0-9]+\.+[0-9]+\.+[0-9]+$ ]]; then
# Use the "stable" component for tagged semver releases # Use the "stable" component for tagged semver releases
COMPONENT="stable" COMPONENT="stable"
elif [[ ${{ forge.ref_name }} =~ ^v+[0-9]\.+[0-9]\.+[0-9] ]]; then elif [[ ${{ forge.ref_name }} =~ ^v+[0-9]+\.+[0-9]+\.+[0-9]+ ]]; then
# Use the "unstable" component for tagged semver pre-releases # Use the "unstable" component for tagged semver pre-releases
COMPONENT="unstable" COMPONENT="unstable"
else else
@@ -130,7 +119,7 @@ jobs:
run: | run: |
apt-get update -y apt-get update -y
# Build dependencies for rocksdb # Build dependencies for rocksdb
apt-get install -y liburing-dev ${{ steps.clang-version.outputs.version }} apt-get install -y liburing-dev clang
- name: Run cargo-deb - name: Run cargo-deb
id: cargo-deb id: cargo-deb
+2 -2
View File
@@ -16,7 +16,7 @@ on:
# - '.forgejo/workflows/build-fedora.yml' # - '.forgejo/workflows/build-fedora.yml'
workflow_dispatch: workflow_dispatch:
schedule: schedule:
- cron: '30 0 * * *' - cron: '30 0 * * 2'
jobs: jobs:
build: build:
@@ -30,7 +30,7 @@ jobs:
echo "Fedora version: $VERSION" echo "Fedora version: $VERSION"
- name: Checkout repository with full history - name: Checkout repository with full history
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
fetch-depth: 0 fetch-depth: 0
ref: ${{ github.ref_name }} ref: ${{ github.ref_name }}
+71
View File
@@ -0,0 +1,71 @@
name: Build / Static via Nix
concurrency:
group: "build-nix-${{ forge.ref }}"
cancel-in-progress: true
on:
push:
tags:
- "v*.*.*"
workflow_dispatch:
schedule:
- cron: '30 0 * * 3'
jobs:
build:
name: "Build ${{ matrix.filename }} Binary"
runs-on: ubuntu-latest
strategy:
matrix:
include:
- package: default-static-x86_64
filename: conduwuit-linux-static-amd64
- package: default-static-aarch64
filename: conduwuit-linux-static-arm64
- package: max-perf-static-aarch64
filename: conduwuit-linux-static-arm64-maxperf
- package: max-perf-haswell-static-x86_64
filename: conduwuit-haswell-linux-static-amd64-maxperf
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
- name: Install Lix
uses: https://github.com/samueldr/lix-gha-installer-action@a0fee77b2a98bb7c5c0ed7ae6d6ad4903dbdad0d
with:
extra_nix_config: experimental-features = nix-command flakes flake-self-attrs
- name: Build static binary
run: |
nix build .#${{ matrix.package }}
install -D result/bin/conduwuit /tmp/binaries/${{ matrix.filename }}
- name: Upload binary artifact
uses: forgejo/upload-artifact@v4
with:
name: ${{ matrix.filename }}
path: /tmp/binaries/${{ matrix.filename }}
release-binaries:
name: "Release Binaries"
runs-on: ubuntu-latest
needs:
- build
permissions:
contents: write
if: startsWith(github.ref, 'refs/tags/')
steps:
- name: Download binary artifacts
uses: forgejo/download-artifact@v4
with:
pattern: conduwuit*
path: binaries
merge-multiple: true
- name: Create Release and Upload
uses: https://github.com/softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
with:
draft: true
files: binaries/*
+7 -11
View File
@@ -14,23 +14,19 @@ jobs:
name: Check changelog is added name: Check changelog is added
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
persist-credentials: false
sparse-checkout: .
- name: Check for changelog entry - name: Check for changelog entry
id: check_files id: check_files
run: | run: |
git fetch origin ${GITHUB_BASE_REF} AUTH=$(echo -n "x-access-token:${{ secrets.GITHUB_TOKEN }}" | base64 -w 0)
git config --global http.${{ github.server_url }}/.extraheader "Authorization: basic $AUTH"
git clone "${{ github.event.repository.clone_url }}" repo.git --bare
git -C repo.git fetch origin pull/${{ github.event.pull_request.number }}/head
# Check for Added (A) or Modified (M) files in changelog.d # Check for Added (A) or Modified (M) files in changelog.d
CHANGELOG_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF}...HEAD -- changelog.d/) CHANGELOG_CHANGES=$(git -C repo.git diff --name-status ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} -- changelog.d/)
SRC_CHANGES=$(git diff --name-status origin/${GITHUB_BASE_REF}...HEAD -- src/) SRC_CHANGES=$(git -C repo.git diff --name-status ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} -- src/)
echo "Changes in changelog.d/:" echo "Changes in changelog.d/:"
echo "$CHANGELOG_CHANGES" echo "$CHANGELOG_CHANGES"
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
steps: steps:
- name: Sync repository - name: Sync repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
fetch-depth: 0 fetch-depth: 0
+2 -2
View File
@@ -41,7 +41,7 @@ jobs:
DOCKER_MIRROR_TOKEN: ${{ secrets.DOCKER_MIRROR_TOKEN }} DOCKER_MIRROR_TOKEN: ${{ secrets.DOCKER_MIRROR_TOKEN }}
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
@@ -55,7 +55,7 @@ jobs:
# repositories: continuwuity # repositories: continuwuity
- name: Install regsync - name: Install regsync
uses: https://github.com/regclient/actions/regsync-installer@14f9d37db17b5dc41fefd1ffdd1af4b9e2490560 # main uses: https://github.com/regclient/actions/regsync-installer@4b4db1dcc7dad75ad67a788a380f75a20cc8a040 # main
- name: Check what images need mirroring - name: Check what images need mirroring
run: | run: |
+3 -3
View File
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
@@ -48,7 +48,7 @@ jobs:
rust: ${{ steps.filter.outputs.rust }} rust: ${{ steps.filter.outputs.rust }}
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
@@ -70,7 +70,7 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
+5 -5
View File
@@ -46,7 +46,7 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
- name: Prepare Docker build environment - name: Prepare Docker build environment
@@ -100,7 +100,7 @@ jobs:
needs: build-release needs: build-release
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
- name: Create multi-platform manifest - name: Create multi-platform manifest
@@ -133,7 +133,7 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
- name: Prepare max-perf Docker build environment - name: Prepare max-perf Docker build environment
@@ -187,7 +187,7 @@ jobs:
needs: build-maxperf needs: build-maxperf
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: false persist-credentials: false
- name: Create max-perf manifest - name: Create max-perf manifest
@@ -216,7 +216,7 @@ jobs:
path: binaries path: binaries
merge-multiple: true merge-multiple: true
- name: Create Release and Upload - name: Create Release and Upload
uses: https://github.com/softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3 uses: https://github.com/softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
with: with:
draft: true draft: true
files: binaries/* files: binaries/*
+2 -2
View File
@@ -43,11 +43,11 @@ jobs:
name: Renovate name: Renovate
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: ghcr.io/renovatebot/renovate:43.222.1@sha256:b9af3f59f3f4d92b2c41e9f4ca3ffe92400503f20158d0bd67d07a3fdbe781d2 image: ghcr.io/renovatebot/renovate:43.246.1@sha256:5965c08f8ca5baff8dc9bf3a32c44ca71fef843ad94880e9696d46e1d722b0fa
options: --tmpfs /tmp:exec options: --tmpfs /tmp:exec
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
show-progress: false show-progress: false
+3 -3
View File
@@ -14,7 +14,7 @@ jobs:
update-flake-hashes: update-flake-hashes:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with: with:
persist-credentials: true persist-credentials: true
token: ${{ secrets.FORGEJO_TOKEN }} token: ${{ secrets.FORGEJO_TOKEN }}
@@ -27,7 +27,7 @@ jobs:
- name: Get new toolchain hash - name: Get new toolchain hash
run: | run: |
# Set the current sha256 to an empty hash to make `nix build` calculate a new one # Set the current sha256 to an empty hash to make `nix build` calculate a new one
awk '/fromToolchainFile *\{/{found=1; print; next} found && /sha256 =/{sub(/sha256 = .*/, "sha256 = lib.fakeSha256;"); found=0} 1' nix/rust.nix > temp.nix awk '/fromToolchainName *\{/{found=1; print; next} found && /sha256 =/{sub(/sha256 = .*/, "sha256 = lib.fakeSha256;"); found=0} 1' nix/rust.nix > temp.nix
mv temp.nix nix/rust.nix mv temp.nix nix/rust.nix
# Build continuwuity and filter for the new hash # Build continuwuity and filter for the new hash
@@ -39,7 +39,7 @@ jobs:
sed -i "s|lib.fakeSha256|\"$new_hash\"|" nix/rust.nix sed -i "s|lib.fakeSha256|\"$new_hash\"|" nix/rust.nix
echo "New hash:" echo "New hash:"
awk -F'"' '/fromToolchainFile/{found=1; next} found && /sha256 =/{print $2; found=0}' nix/rust.nix awk -F'"' '/fromToolchainName/{found=1; next} found && /sha256 =/{print $2; found=0}' nix/rust.nix
echo "Expected new hash:" echo "Expected new hash:"
cat new_toolchain_hash.txt cat new_toolchain_hash.txt
Generated
+160 -59
View File
@@ -130,9 +130,9 @@ checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
[[package]] [[package]]
name = "arrayvec" name = "arrayvec"
version = "0.7.6" version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" checksum = "f02882884d3e1bc524fb12c79f107f6ad0e1cfd498c536ffb494301740995dfe"
dependencies = [ dependencies = [
"serde", "serde",
] ]
@@ -560,9 +560,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]] [[package]]
name = "bytes" name = "bytes"
version = "1.11.1" version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
[[package]] [[package]]
name = "bytesize" name = "bytesize"
@@ -805,7 +805,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit" name = "conduwuit"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"aws-lc-rs", "aws-lc-rs",
"clap", "clap",
@@ -843,7 +843,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_admin" name = "conduwuit_admin"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"assign", "assign",
"clap", "clap",
@@ -868,7 +868,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_api" name = "conduwuit_api"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"assign", "assign",
"async-trait", "async-trait",
@@ -889,7 +889,7 @@ dependencies = [
"http-body-util", "http-body-util",
"hyper", "hyper",
"ipaddress", "ipaddress",
"itertools 0.14.0", "itertools 0.15.0",
"lettre", "lettre",
"log", "log",
"rand 0.10.1", "rand 0.10.1",
@@ -906,7 +906,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_build_metadata" name = "conduwuit_build_metadata"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"built", "built",
"cargo_metadata", "cargo_metadata",
@@ -914,7 +914,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_core" name = "conduwuit_core"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"argon2", "argon2",
"arrayvec", "arrayvec",
@@ -942,7 +942,7 @@ dependencies = [
"http-body-util", "http-body-util",
"hyper-util", "hyper-util",
"ipaddress", "ipaddress",
"itertools 0.14.0", "itertools 0.15.0",
"lettre", "lettre",
"libc", "libc",
"libloading 0.9.0", "libloading 0.9.0",
@@ -980,7 +980,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_database" name = "conduwuit_database"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"async-channel", "async-channel",
"conduwuit_core", "conduwuit_core",
@@ -1001,10 +1001,10 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_macros" name = "conduwuit_macros"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"cargo_toml", "cargo_toml",
"itertools 0.14.0", "itertools 0.15.0",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn",
@@ -1012,7 +1012,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_router" name = "conduwuit_router"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"assign", "assign",
"axum", "axum",
@@ -1044,13 +1044,13 @@ dependencies = [
"serde_json", "serde_json",
"tokio", "tokio",
"tower", "tower",
"tower-http", "tower-http 0.7.0",
"tracing", "tracing",
] ]
[[package]] [[package]]
name = "conduwuit_service" name = "conduwuit_service"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"askama", "askama",
"assign", "assign",
@@ -1070,7 +1070,7 @@ dependencies = [
"http", "http",
"image", "image",
"ipaddress", "ipaddress",
"itertools 0.14.0", "itertools 0.15.0",
"lettre", "lettre",
"log", "log",
"loole", "loole",
@@ -1088,6 +1088,7 @@ dependencies = [
"serde", "serde",
"serde-saphyr", "serde-saphyr",
"serde_json", "serde_json",
"serde_urlencoded",
"sha2 0.11.0", "sha2 0.11.0",
"termimad", "termimad",
"tokio", "tokio",
@@ -1099,7 +1100,7 @@ dependencies = [
[[package]] [[package]]
name = "conduwuit_web" name = "conduwuit_web"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"askama", "askama",
"assign", "assign",
@@ -1107,18 +1108,29 @@ dependencies = [
"axum", "axum",
"axum-extra", "axum-extra",
"base64 0.22.1", "base64 0.22.1",
"conduwuit_api",
"conduwuit_build_metadata", "conduwuit_build_metadata",
"conduwuit_core", "conduwuit_core",
"conduwuit_database",
"conduwuit_service", "conduwuit_service",
"form_urlencoded",
"futures", "futures",
"lettre",
"memory-serve", "memory-serve",
"rand 0.10.1", "rand 0.10.1",
"recaptcha-verify",
"reqwest 0.12.28",
"ruma", "ruma",
"serde", "serde",
"serde_json",
"serde_urlencoded",
"thiserror", "thiserror",
"tower-http", "tower-http 0.7.0",
"tower-sec-fetch", "tower-sec-fetch",
"tower-sessions",
"tower-sessions-core",
"tracing", "tracing",
"url",
"validator", "validator",
] ]
@@ -1534,6 +1546,9 @@ name = "deranged"
version = "0.5.8" version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
"serde_core",
]
[[package]] [[package]]
name = "derive_more" name = "derive_more"
@@ -2036,9 +2051,9 @@ dependencies = [
[[package]] [[package]]
name = "granit-parser" name = "granit-parser"
version = "0.0.2" version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7e736dfe3881c53a7dce0685eb18202d0d9fe6911782f9870946eb9ee89d778" checksum = "14668345710c92cb04181d9268407067689327d4b055273e3c4179a0777ee6a1"
dependencies = [ dependencies = [
"arraydeque", "arraydeque",
"smallvec", "smallvec",
@@ -2641,6 +2656,15 @@ dependencies = [
"either", "either",
] ]
[[package]]
name = "itertools"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
dependencies = [
"either",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.18" version = "1.0.18"
@@ -2894,9 +2918,9 @@ dependencies = [
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.32" version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]] [[package]]
name = "loole" name = "loole"
@@ -3945,9 +3969,9 @@ dependencies = [
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.45" version = "1.0.46"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
] ]
@@ -4112,7 +4136,7 @@ dependencies = [
"tokio", "tokio",
"tokio-rustls", "tokio-rustls",
"tower", "tower",
"tower-http", "tower-http 0.6.11",
"tower-service", "tower-service",
"url", "url",
"wasm-bindgen", "wasm-bindgen",
@@ -4157,7 +4181,7 @@ dependencies = [
"tokio-rustls", "tokio-rustls",
"tokio-util", "tokio-util",
"tower", "tower",
"tower-http", "tower-http 0.6.11",
"tower-service", "tower-service",
"url", "url",
"wasm-bindgen", "wasm-bindgen",
@@ -4386,7 +4410,7 @@ dependencies = [
[[package]] [[package]]
name = "ruminuwuity" name = "ruminuwuity"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"assign", "assign",
"ruma", "ruma",
@@ -4458,9 +4482,9 @@ dependencies = [
[[package]] [[package]]
name = "rustls" name = "rustls"
version = "0.23.40" version = "0.23.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"
dependencies = [ dependencies = [
"aws-lc-rs", "aws-lc-rs",
"log", "log",
@@ -4636,9 +4660,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry" name = "sentry"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "931a20b0da02350676e3d6d3c9028d58eaa448cf42a866712eec5845a505421e" checksum = "1975064d9f3d9d87a7c8f0371f7fac10d876906ca3e39faad72e61c263ff9b87"
dependencies = [ dependencies = [
"cfg_aliases", "cfg_aliases",
"httpdate", "httpdate",
@@ -4656,9 +4680,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-backtrace" name = "sentry-backtrace"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "911ee36abf5b7fa335fccd5f54361ba9c16baea5f0c3bb361a687b6c195c21cf" checksum = "134f552b6b147f77aeee46ece875d67a8bfc1d56fe3860d78446ed4c25bb5f9f"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"regex", "regex",
@@ -4667,9 +4691,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-contexts" name = "sentry-contexts"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b9d7d469e9e22741c17ca23fb8b42d79861590eb7cf330f3da34fc1e4bc1bc6" checksum = "98482b938fb1f31ecd23506fb7f08b2ba20d60b9cc72581b1205a9acd31d32fa"
dependencies = [ dependencies = [
"hostname", "hostname",
"libc", "libc",
@@ -4681,9 +4705,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-core" name = "sentry-core"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "545dc562b6758d646ac19e1407f4ebc26d452111386743e03323464bc48bb2e0" checksum = "7cff96247f4dc36867511d108709e703eb354143e7893319d763d2dd1edb4f48"
dependencies = [ dependencies = [
"rand 0.9.4", "rand 0.9.4",
"sentry-types", "sentry-types",
@@ -4694,9 +4718,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-debug-images" name = "sentry-debug-images"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "660e9def38a573a869a182f7e90f58aaaa460f38b92b31fd1755ec537193bb48" checksum = "b603a51b083141062a142d73e36391b14244b4bd0bfe28bcd80e8327bb1d7698"
dependencies = [ dependencies = [
"findshlibs", "findshlibs",
"sentry-core", "sentry-core",
@@ -4704,9 +4728,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-log" name = "sentry-log"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c13b9313bdd6a9db19e65ac0e4754e64dea6f18cdd15444656abb050db4538d" checksum = "74df4d09a38fd59da258269ffd7f344bd308470117d68eda5a95b4fbd65683d0"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"log", "log",
@@ -4715,9 +4739,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-panic" name = "sentry-panic"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "772d9de150c8ca910c835353c85f434457348fdd21208f9b3da3574202b1dc5d" checksum = "61de3f4a1fc77d4c57e8bacd8ef064c26aaa88ea5b2541a761d37c7c3703b9a9"
dependencies = [ dependencies = [
"sentry-backtrace", "sentry-backtrace",
"sentry-core", "sentry-core",
@@ -4725,9 +4749,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-tower" name = "sentry-tower"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2abea154597936d5df2d39fbe8aac16d584de6b3572c70c39558764d9d2efe15" checksum = "2d5cb61301e328cbd42d2fede094aca746674b359fcd9c44691f027820e8fe59"
dependencies = [ dependencies = [
"http", "http",
"pin-project", "pin-project",
@@ -4739,9 +4763,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-tracing" name = "sentry-tracing"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c51ec9620a4d398dcdf7ee90effbf8d8691cfa24e91978bfa8565cac039d4980" checksum = "bc59b27dae3bb495e37e6d62d252214840a2e7e1875531ee9fa2953df8985537"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"sentry-backtrace", "sentry-backtrace",
@@ -4752,9 +4776,9 @@ dependencies = [
[[package]] [[package]]
name = "sentry-types" name = "sentry-types"
version = "0.48.2" version = "0.48.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "041359745a44dd2e14fe21b7510fe7ca8b5beffce6636a0b52e5bc7d5f736887" checksum = "8d7e78132ccfb4a1c777b959fb2944d1f6d5145bffe6be2a98ee6b25d244f72c"
dependencies = [ dependencies = [
"debugid", "debugid",
"hex", "hex",
@@ -4779,19 +4803,19 @@ dependencies = [
[[package]] [[package]]
name = "serde-saphyr" name = "serde-saphyr"
version = "0.0.26" version = "0.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcc7fe48e34d02a97bc8e6253b8b91e5a47fe2c47eaacb5149cefbb69922eaf0" checksum = "a15e3bc297370dc9c526bcf0986f29167a9286cfaad404f2f572b3074dabe5ec"
dependencies = [ dependencies = [
"ahash", "ahash",
"annotate-snippets", "annotate-snippets",
"base64 0.22.1", "base64 0.21.7",
"encoding_rs_io", "encoding_rs_io",
"getrandom 0.3.4", "getrandom 0.3.4",
"granit-parser", "granit-parser",
"nohash-hasher", "nohash-hasher",
"num-traits", "num-traits",
"serde", "serde_core",
"smallvec", "smallvec",
"zmij", "zmij",
] ]
@@ -5144,9 +5168,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.117" version = "2.0.118"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -5607,6 +5631,22 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "tower-cookies"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "151b5a3e3c45df17466454bb74e9ecedecc955269bdedbf4d150dfa393b55a36"
dependencies = [
"axum-core",
"cookie",
"futures-util",
"http",
"parking_lot",
"pin-project-lite",
"tower-layer",
"tower-service",
]
[[package]] [[package]]
name = "tower-http" name = "tower-http"
version = "0.6.11" version = "0.6.11"
@@ -5627,10 +5667,33 @@ dependencies = [
"tower", "tower",
"tower-layer", "tower-layer",
"tower-service", "tower-service",
"tracing",
"url", "url",
] ]
[[package]]
name = "tower-http"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b11f75e912b0c2be01b63d8cf8057b8c3f97cf34abb3d431a3a4c8675498e233"
dependencies = [
"async-compression",
"bitflags",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
"percent-encoding",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]] [[package]]
name = "tower-layer" name = "tower-layer"
version = "0.3.3" version = "0.3.3"
@@ -5655,6 +5718,44 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tower-sessions"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "518dca34b74a17cadfcee06e616a09d2bd0c3984eff1769e1e76d58df978fc78"
dependencies = [
"async-trait",
"http",
"time",
"tokio",
"tower-cookies",
"tower-layer",
"tower-service",
"tower-sessions-core",
"tracing",
]
[[package]]
name = "tower-sessions-core"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "568531ec3dfcf3ffe493de1958ae5662a0284ac5d767476ecdb6a34ff8c6b06c"
dependencies = [
"async-trait",
"axum-core",
"base64 0.22.1",
"futures",
"http",
"parking_lot",
"rand 0.9.4",
"serde",
"serde_json",
"thiserror",
"time",
"tokio",
"tracing",
]
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.44" version = "0.1.44"
@@ -6481,7 +6582,7 @@ dependencies = [
[[package]] [[package]]
name = "xtask" name = "xtask"
version = "0.5.9" version = "26.6.0-alpha.1"
dependencies = [ dependencies = [
"askama", "askama",
"cargo_metadata", "cargo_metadata",
+7 -4
View File
@@ -12,7 +12,7 @@ license = "Apache-2.0"
# See also `rust-toolchain.toml` # See also `rust-toolchain.toml`
readme = "README.md" readme = "README.md"
repository = "https://forgejo.ellis.link/continuwuation/continuwuity" repository = "https://forgejo.ellis.link/continuwuation/continuwuity"
version = "0.5.9" version = "26.6.0-alpha.1"
[workspace.metadata.crane] [workspace.metadata.crane]
name = "conduwuit" name = "conduwuit"
@@ -124,7 +124,7 @@ default-features = false
features = ["util"] features = ["util"]
[workspace.dependencies.tower-http] [workspace.dependencies.tower-http]
version = "0.6.8" version = "0.7.0"
default-features = false default-features = false
features = [ features = [
"add-extension", "add-extension",
@@ -164,7 +164,7 @@ features = ["raw_value"]
# Used for appservice registration files # Used for appservice registration files
[workspace.dependencies.serde-saphyr] [workspace.dependencies.serde-saphyr]
version = "0.0.26" version = "0.0.28"
# Used to load forbidden room/user regex from config # Used to load forbidden room/user regex from config
[workspace.dependencies.serde_regex] [workspace.dependencies.serde_regex]
@@ -316,7 +316,7 @@ default-features = false
# Used to make working with iterators easier, was already a transitive depdendency # Used to make working with iterators easier, was already a transitive depdendency
[workspace.dependencies.itertools] [workspace.dependencies.itertools]
version = "0.14.0" version = "0.15.0"
# to parse user-friendly time durations in admin commands # to parse user-friendly time durations in admin commands
#TODO: overlaps chrono? #TODO: overlaps chrono?
@@ -559,6 +559,9 @@ features = ["std"]
[workspace.dependencies.nonzero_ext] [workspace.dependencies.nonzero_ext]
version = "0.3.0" version = "0.3.0"
[workspace.dependencies.serde_urlencoded]
version = "0.7.1"
# #
# Patches # Patches
# #
+1
View File
@@ -23,6 +23,7 @@ We appreciate the efforts of security researchers and the community in identifyi
1. **Contact members of the team directly** over E2EE private message. 1. **Contact members of the team directly** over E2EE private message.
- [@jade:ellis.link](https://matrix.to/#/@jade:ellis.link) - [@jade:ellis.link](https://matrix.to/#/@jade:ellis.link)
- [@nex:nexy7574.co.uk](https://matrix.to/#/@nex:nexy7574.co.uk) - [@nex:nexy7574.co.uk](https://matrix.to/#/@nex:nexy7574.co.uk)
- [@ginger:gingershaped.computer](https://matrix.to/#/@ginger:gingershaped.computer)
2. **Email the security team** at [security@continuwuity.org](mailto:security@continuwuity.org). This is not E2EE, so don't include sensitive details. 2. **Email the security team** at [security@continuwuity.org](mailto:security@continuwuity.org). This is not E2EE, so don't include sensitive details.
3. **Do not disclose the vulnerability publicly** until it has been addressed 3. **Do not disclose the vulnerability publicly** until it has been addressed
4. **Provide detailed information** about the vulnerability, including: 4. **Provide detailed information** about the vulnerability, including:
+1
View File
@@ -0,0 +1 @@
Users may now be forbidden from deactivating their own accounts with the new `allow_deactivation` config option. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Added support for Matrix 1.16's `state_after` feature, allowing clients which understand it to sync room state changes more reliably. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Added support for authenticating clients using the new OAuth 2.0 login API. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Added static builds using Nix, allowing for Continuwuity on musl. During this, we also introduced a `max-perf-haswell` package, separating it from `max-perf`, so you may want to swap to this if you are on NixOS. Contributed by @Henry-Hiles (QuadRadical).
+1
View File
@@ -0,0 +1 @@
Added support for MSC4380 invite blocking, which has become part of the Matrix specification in v1.18. Contributed by @nex.
+1
View File
@@ -0,0 +1 @@
Added `!admin debug get-state-at` command
+1
View File
@@ -0,0 +1 @@
Adjusted legacy sync logic to no longer use the `roomsynctoken_shortstatehash` database column. Once this change has been confirmed to be stable and reliable, a future update will remove it entirely, significantly decreasing database sizes. Contributed by @ginger.
+37 -9
View File
@@ -521,17 +521,15 @@
# #
#recaptcha_private_site_key = #recaptcha_private_site_key =
# Policy documents, such as terms and conditions or a privacy policy, # Controls whether users are allowed to deactivate their own accounts
# which users must agree to when registering an account. # through the account management panel or their Matrix clients. Server
# admins can always deactivate users using the relevant admin commands.
# #
# Example: # Note that, in some jurisdictions, you may be legally required to honor
# ```ignore # users who request to deactivate their accounts if you set this option
# [global.registration_terms.privacy_policy] # to `false`.
# en = { name = "Privacy Policy", url = "https://homeserver.example/en/privacy_policy.html" }
# es = { name = "Política de Privacidad", url = "https://homeserver.example/es/privacy_policy.html" }
# ```
# #
#registration_terms = {} #allow_deactivation = true
# Controls whether encrypted rooms and events are allowed. # Controls whether encrypted rooms and events are allowed.
# #
@@ -1987,3 +1985,33 @@
# `require_email_for_registration`. # `require_email_for_registration`.
# #
#require_email_for_token_registration = false #require_email_for_token_registration = false
#[global.registration_terms]
# The language code to provide to clients along with the policy documents.
#
#language = "en"
# Policy documents, such as terms and conditions or a privacy policy,
# which users must agree to when registering an account.
#
# Example:
# ```ignore
# [global.registration_terms.documents]
# privacy_policy = { name = "Privacy Policy", url = "https://homeserver.example/en/privacy_policy.html" }
# ```
#
#documents =
#[global.oauth]
# The compatibility mode to use for OAuth.
#
# - "disabled": OAuth will be unavailable. Users will only be able to log
# in using legacy authentication.
# - "hybrid": OAuth and legacy authentication will both be available. Some
# clients may only use one or the other.
# - "exclusive": Only OAuth will be available. Clients which require
# legacy authentication will be unable to log in.
#
#compatibility_mode = "hybrid"
+1 -1
View File
@@ -50,7 +50,7 @@ EOF
# Developer tool versions # Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.20.0 ENV BINSTALL_VERSION=1.20.1
# renovate: datasource=github-releases depName=psastras/sbom-rs # renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1 ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree # 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 # Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.20.0 ENV BINSTALL_VERSION=1.20.1
# renovate: datasource=github-releases depName=psastras/sbom-rs # renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1 ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree # renovate: datasource=crate depName=lddtree
+8 -2
View File
@@ -47,9 +47,15 @@ and, for amd64, target the haswell CPU architecture.
### Nix ### Nix
Theres a Nix package defined in our flake, available for Linux and MacOS. Add continuwuity as an input to your flake, and use `inputs.continuwuity.packages.${system}.default` to get a working Continuwuity package. If you wish to generate a static binary, you can do so using Nix: `nix build git+https://forgejo.ellis.link/continuwuation/continuwuity#packageName`, where `packageName` is one of:
If you simply wish to generate a binary using Nix, you can run `nix build git+https://forgejo.ellis.link/continuwuation/continuwuity` to generate a binary in `result/bin/conduwuit`. - `default-static-x86_64`
- `default-static-aarch64`
- `max-perf-static-x86_64`
- `max-perf-haswell-static-x86_64`
- `max-perf-static-aarch64`
`max-perf` takes longer to build, but has more runtime optimizations. Haswell builds are optimized for modern CPUs.
### Compiling ### Compiling
+8 -1
View File
@@ -47,9 +47,16 @@ The NixOS module provides these configuration options:
- `extraEnvironment`: Extra environment variables to pass to the Continuwuity server - `extraEnvironment`: Extra environment variables to pass to the Continuwuity server
- `package`: The Continuwuity package to use, defaults to `pkgs.matrix-continuwuity` - `package`: The Continuwuity package to use, defaults to `pkgs.matrix-continuwuity`
- You may want to override this to be from our flake, for faster updates and unstable versions: - You may want to override this to be from our flake, for faster updates and unstable versions:
```nix ```nix
package = inputs.continuwuity.packages.${pkgs.stdenv.hostPlatform.system}.default; package = inputs.continuwuity.packages.${pkgs.stdenv.hostPlatform.system}.packageName;
``` ```
Where `packageName` is one of:
- `default`
- `max-perf`: Takes longer to build, but has more runtime optimizations
- `max-perf-haswell`: Optimized for modern CPUs, don't use if your CPU is not Haswell or later.
- `admin.enable`: Whether to add the `conduwuit` binary to `PATH` for administration (enabled by default) - `admin.enable`: Whether to add the `conduwuit` binary to `PATH` for administration (enabled by default)
- `settings`: The Continuwuity configuration - `settings`: The Continuwuity configuration
@@ -6,10 +6,10 @@
"message": "Welcome to Continuwuity! Important announcements about the project will appear here." "message": "Welcome to Continuwuity! Important announcements about the project will appear here."
}, },
{ {
"id": 13, "id": 14,
"mention_room": true, "mention_room": true,
"date": "2026-05-08", "date": "2026-06-20",
"message": "[v0.5.9](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v0.5.9) has been released, fixing a few low-severity federation-related vulnerabilities. It is recommended you read the changelog and update as soon as possible. There are no new features or other changes in this release, only related bugfixes. Deployments tracking the main branch should also update to the latest commit." "message": "[v0.5.10](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v0.5.10) has been released. It is a security release, so we suggest you update as soon as possible. Don't forget to also join [our announcements room](https://matrix.to/#/!jIdNjSM5X-V5JVx2h2kAhUZIIQ08GyzPL55NFZAH1vM/%24K1ISNKIqfNiZzsNVCaTt2E7ZtNeP6Dsy6sbz9l3rO0A?via=ellis.link&via=gingershaped.computer&via=matrix.org)."
} }
] ]
} }
+1 -1
View File
@@ -10,7 +10,7 @@ Please check that your issues are not due to problems with your Docker setup.
### Slow joins to rooms ### Slow joins to rooms
Some slowness is to be expected if you're the first person on your homserver to join a room (which will Some slowness is to be expected if you're the first person on your homeserver to join a room (which will
always be the case for single-user homeservers). In this situation, your homeserver has to verify the signatures of always be the case for single-user homeservers). In this situation, your homeserver has to verify the signatures of
all of the state events sent by other servers before your join. To make this process as fast as possible, make sure you have all of the state events sent by other servers before your join. To make this process as fast as possible, make sure you have
multiple fast, trusted servers listed in `trusted_servers` in your configuration, and ensure multiple fast, trusted servers listed in `trusted_servers` in your configuration, and ensure
-14
View File
@@ -1,14 +0,0 @@
{ inputs, ... }:
{
perSystem =
{
pkgs,
self',
...
}:
{
_module.args.craneLib = (inputs.crane.mkLib pkgs).overrideToolchain (
pkgs: self'.packages.stable-toolchain
);
};
}
-1
View File
@@ -1,7 +1,6 @@
{ {
imports = [ imports = [
./rust.nix ./rust.nix
./crane.nix
./packages ./packages
./devshell.nix ./devshell.nix
./fmt.nix ./fmt.nix
+4 -3
View File
@@ -1,7 +1,6 @@
{ { inputs, ... }: {
perSystem = perSystem =
{ {
craneLib,
self', self',
lib, lib,
pkgs, pkgs,
@@ -9,7 +8,9 @@
}: }:
{ {
# basic nix shell containing all things necessary to build continuwuity in all flavors manually (on x86_64-linux) # basic nix shell containing all things necessary to build continuwuity in all flavors manually (on x86_64-linux)
devShells.default = craneLib.devShell { devShells.default =
(inputs.crane.mkLib pkgs).overrideToolchain (pkgs: self'.packages.stable-toolchain).devShell
{
packages = [ packages = [
self'.packages.rocksdb self'.packages.rocksdb
pkgs.nodejs pkgs.nodejs
+13 -5
View File
@@ -2,14 +2,14 @@
lib, lib,
self, self,
stdenv, stdenv,
liburing, rocksdb,
craneLib, craneLib,
pkg-config, pkg-config,
liburing,
rustPlatform, rustPlatform,
cargoExtraArgs ? "", cargoExtraArgs ? "",
rustflags ? "", rustflags ? "",
target_cpu ? null, target_cpu ? null,
rocksdb,
profile ? "release", profile ? "release",
}: }:
let let
@@ -28,18 +28,26 @@ let
}; };
attrs = { attrs = {
__structuredAttrs = true;
strictDeps = true;
inherit src; inherit src;
nativeBuildInputs = [ nativeBuildInputs = [
pkg-config pkg-config
rustPlatform.bindgenHook rustPlatform.bindgenHook
]; ];
buildInputs = lib.optionals stdenv.hostPlatform.isLinux [ liburing ]; buildInputs = lib.optionals stdenv.hostPlatform.isLinux [ liburing ];
env = { env = {
ROCKSDB_INCLUDE_DIR = "${rocksdb}/include";
ROCKSDB_LIB_DIR = "${rocksdb}/lib";
CARGO_PROFILE = profile; CARGO_PROFILE = profile;
RUSTFLAGS = rustflags; RUSTFLAGS = rustflags;
} }
// (lib.optionalAttrs (rocksdb != null) {
ROCKSDB_INCLUDE_DIR = "${rocksdb}/include";
ROCKSDB_LIB_DIR = "${rocksdb}/lib";
})
// (lib.optionalAttrs (target_cpu != null) { // (lib.optionalAttrs (target_cpu != null) {
TARGET_CPU = target_cpu; TARGET_CPU = target_cpu;
}); });
@@ -51,7 +59,7 @@ craneLib.buildPackage (
cargoArtifacts = craneLib.buildDepsOnly attrs; cargoArtifacts = craneLib.buildDepsOnly attrs;
# Needed to make continuwuity link to rocksdb # Needed to make continuwuity link to rocksdb
postFixup = lib.optionalString stdenv.hostPlatform.isLinux '' postFixup = lib.optionalString (stdenv.hostPlatform.isLinux && rocksdb != null) ''
old_rpath="$(patchelf --print-rpath $out/bin/conduwuit)" old_rpath="$(patchelf --print-rpath $out/bin/conduwuit)"
extra_rpath="${ extra_rpath="${
lib.makeLibraryPath [ lib.makeLibraryPath [
+60 -7
View File
@@ -1,4 +1,5 @@
{ {
inputs,
self, self,
... ...
}: }:
@@ -6,32 +7,84 @@
perSystem = perSystem =
{ {
self', self',
lib,
pkgs, pkgs,
inputs',
system,
craneLib, craneLib,
mkToolchain,
... ...
}: }:
{ {
packages = { packages =
rocksdb = pkgs.callPackage ./rocksdb.nix { }; let
mkPackages =
pkgs:
let
fnx = inputs'.fenix.packages;
isStatic = pkgs.stdenv.hostPlatform.isMusl;
craneLib = (inputs.crane.mkLib pkgs).overrideToolchain (
_:
if isStatic then
fnx.combine [
self'.packages.stable-toolchain
(mkToolchain fnx.targets.${pkgs.stdenv.hostPlatform.config}).rust-std
]
else
self'.packages.stable-toolchain
);
default = pkgs.callPackage ./continuwuity.nix { default = pkgs.callPackage ./continuwuity.nix {
inherit self craneLib; inherit self craneLib;
inherit (self'.packages) rocksdb;
liburing = (if isStatic then pkgs.pkgsStatic else pkgs).liburing;
rocksdb = if isStatic then null else self'.packages.rocksdb;
# extra features via `cargoExtraArgs` # extra features via `cargoExtraArgs`
cargoExtraArgs = "-F http3"; cargoExtraArgs = "-F http3";
# extra RUSTFLAGS via `rustflags` # extra RUSTFLAGS via `rustflags`
# the stuff below is required for http3 # the stuff below is required for http3
rustflags = "--cfg reqwest_unstable"; rustflags = "--cfg reqwest_unstable";
}; };
# users may also override this with other cargo profiles to build for other feature sets # users may also override this with other cargo profiles to build for other feature sets
# for features configuration see `default` package which enables http3 by default # for features configuration see `default` package which enables http3 by default
# example: different compilation profile and different target_cpu max-perf = default.override {
max-perf-haswell = self'.packages.default.override {
# compiles explicitly for haswell arch cpus
target_cpu = "haswell";
# compiles slower but with more thorough optimizations # compiles slower but with more thorough optimizations
profile = "release-max-perf"; profile = "release-max-perf";
}; };
max-perf-haswell = max-perf.override {
# compiles explicitly for haswell arch cpus
target_cpu = "haswell";
}; };
in
{
inherit default max-perf max-perf-haswell;
};
in
{
rocksdb = pkgs.callPackage ./rocksdb.nix { };
}
// (mkPackages pkgs)
// (lib.mapAttrs' (name: value: lib.nameValuePair "${name}-static-x86_64" value) (
mkPackages (
import inputs.nixpkgs {
localSystem = system;
crossSystem = "x86_64-unknown-linux-musl";
}
)
))
// (lib.mapAttrs' (name: value: lib.nameValuePair "${name}-static-aarch64" value) (
mkPackages (
import inputs.nixpkgs {
localSystem = system;
crossSystem = "aarch64-unknown-linux-musl";
}
)
));
}; };
} }
+13 -9
View File
@@ -2,23 +2,27 @@
{ {
perSystem = perSystem =
{ {
system,
lib, lib,
inputs',
pkgs, pkgs,
... ...
}: }:
{
packages =
let let
fnx = inputs.fenix.packages.${system}; mkToolchain =
target:
stable-toolchain = fnx.fromToolchainFile { target.fromToolchainName {
file = inputs.self + "/rust-toolchain.toml"; name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel;
# See also `rust-toolchain.toml`
sha256 = "sha256-mvUGEOHYJpn3ikC5hckneuGixaC+yGrkMM/liDIDgoU="; sha256 = "sha256-mvUGEOHYJpn3ikC5hckneuGixaC+yGrkMM/liDIDgoU=";
}; };
in in
{
_module.args = { inherit mkToolchain; };
packages =
let
fnx = inputs'.fenix.packages;
stable-toolchain = (mkToolchain fnx).toolchain;
in
{ {
inherit stable-toolchain; inherit stable-toolchain;
+25 -25
View File
@@ -383,18 +383,18 @@
} }
}, },
"node_modules/@rspress/core": { "node_modules/@rspress/core": {
"version": "2.0.14", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.14.tgz", "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.15.tgz",
"integrity": "sha512-k59i08zwBGgHrjHw8CK1m4CeTrKPvZRmV54bxubQl6AdDdmhJK6WrNg3UthwWmd38scKtqF40ATXDE8RMiNcNA==", "integrity": "sha512-epLmUXYscNRw/GtQZx2oknoBE9wKbCrUGEOrQEDI4Qq8X32GdM4d7itzuHsliY7q3IbffKx8rMVbvlmygEocTQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@mdx-js/mdx": "^3.1.1", "@mdx-js/mdx": "^3.1.1",
"@mdx-js/react": "^3.1.1", "@mdx-js/react": "^3.1.1",
"@rsbuild/core": "^2.0.9", "@rsbuild/core": "^2.0.15",
"@rsbuild/plugin-react": "~2.0.1", "@rsbuild/plugin-react": "~2.0.1",
"@rspress/shared": "2.0.14", "@rspress/shared": "2.0.15",
"@shikijs/rehype": "^4.0.2", "@shikijs/rehype": "^4.2.0",
"@types/unist": "^3.0.3", "@types/unist": "^3.0.3",
"@unhead/react": "^2.1.15", "@unhead/react": "^2.1.15",
"body-scroll-lock": "4.0.0-beta.0", "body-scroll-lock": "4.0.0-beta.0",
@@ -407,22 +407,22 @@
"mdast-util-mdxjs-esm": "^2.0.1", "mdast-util-mdxjs-esm": "^2.0.1",
"medium-zoom": "1.1.0", "medium-zoom": "1.1.0",
"nprogress": "^0.2.0", "nprogress": "^0.2.0",
"react": "^19.2.6", "react": "^19.2.7",
"react-dom": "^19.2.6", "react-dom": "^19.2.7",
"react-lazy-with-preload": "^2.2.1", "react-lazy-with-preload": "^2.2.1",
"react-reconciler": "0.33.0", "react-reconciler": "0.33.0",
"react-render-to-markdown": "19.1.0", "react-render-to-markdown": "19.1.0",
"react-router-dom": "^7.15.1", "react-router-dom": "^7.15.1",
"rehype-external-links": "^3.0.0", "rehype-external-links": "^3.0.0",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"remark-cjk-friendly": "^2.0.1", "remark-cjk-friendly": "^2.3.1",
"remark-cjk-friendly-gfm-strikethrough": "^2.0.1", "remark-cjk-friendly-gfm-strikethrough": "^2.1.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
"remark-mdx": "^3.1.1", "remark-mdx": "^3.1.1",
"remark-parse": "^11.0.0", "remark-parse": "^11.0.0",
"remark-stringify": "^11.0.0", "remark-stringify": "^11.0.0",
"scroll-into-view-if-needed": "^3.1.0", "scroll-into-view-if-needed": "^3.1.0",
"shiki": "^4.0.2", "shiki": "^4.2.0",
"unified": "^11.0.5", "unified": "^11.0.5",
"unist-util-remove": "^4.0.0", "unist-util-remove": "^4.0.0",
"unist-util-visit": "^5.1.0", "unist-util-visit": "^5.1.0",
@@ -436,9 +436,9 @@
} }
}, },
"node_modules/@rspress/plugin-client-redirects": { "node_modules/@rspress/plugin-client-redirects": {
"version": "2.0.14", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.14.tgz", "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.15.tgz",
"integrity": "sha512-/WpbWUiepQglpPeplxCnELe2c7VdBUxPiICPAVnS1ZxAFdYkIpW0C+Vbk1t08kZqx8EAZGu+s6Zy43zyQpjdxg==", "integrity": "sha512-bPf/KIHH7Y6huLTtK6JXwRfxM7zKjksoxm46+IBsF1wisw0doKkEKR9HwJydxWnykyKBbA2cuZOaoT4h174Z1w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -449,9 +449,9 @@
} }
}, },
"node_modules/@rspress/plugin-sitemap": { "node_modules/@rspress/plugin-sitemap": {
"version": "2.0.14", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.14.tgz", "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.15.tgz",
"integrity": "sha512-Gpone22PvXGfGRSyi/WM8IXgsvKhNspXqHjtPD3g62jX8SJL3kpj2YZ2V28WEkg672fICauUYXrpre74Rddcsw==", "integrity": "sha512-z1hbyGP79ZXdSGJxiWw7ZjmX8qW0q9nXMDxr14cVEg/wdj7ToVzGtZHw0wvTPE0YiKG3BMiGkVNfE1rdOaPXiQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -462,14 +462,14 @@
} }
}, },
"node_modules/@rspress/shared": { "node_modules/@rspress/shared": {
"version": "2.0.14", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.14.tgz", "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.15.tgz",
"integrity": "sha512-sCe9tAo+s9tR4DmFSjMyHOxQvhzTSYXkkMUfVEo5w+uMCNXXGAIC6D0xAVDMHq1jIFF9ix47VxzlCo+CYNS14g==", "integrity": "sha512-o8aYwEzNuTmWnmKe91ntPv+34u3RbtAe+rcK9XC5MANOlgncwOaCs3bUa8/B1/llwyLoNgrpi+VB9bEiU11ZRQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rsbuild/core": "^2.0.9", "@rsbuild/core": "^2.0.15",
"@shikijs/rehype": "^4.0.2", "@shikijs/rehype": "^4.2.0",
"unified": "^11.0.5" "unified": "^11.0.5"
} }
}, },
@@ -3058,9 +3058,9 @@
} }
}, },
"node_modules/remark-cjk-friendly": { "node_modules/remark-cjk-friendly": {
"version": "2.1.0", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.1.0.tgz", "resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.3.1.tgz",
"integrity": "sha512-ZWGDfTJNLEZ1gap+pd33K13ZhRAWgVDqxKA7JIlBs5IDu+qvbiWl/pEbeuxzRrWyrrkeFFoTnvNw00iW9mBcow==", "integrity": "sha512-f+pKZRxCRwNEGFBKNRAZAqU91GIK1SAo3ZyFHWRUgC9zcxRR0BXKd6YwqgSsxtW0rNpUDtONj7H5nje2WL3fcA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
+1 -1
View File
@@ -16,7 +16,7 @@ use crate::{
}; };
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[command(name = conduwuit_core::name(), version = conduwuit_core::version())] #[command(name = conduwuit_core::BRANDING, version = conduwuit_core::version())]
pub enum AdminCommand { pub enum AdminCommand {
#[command(subcommand)] #[command(subcommand)]
/// Commands for managing appservices /// Commands for managing appservices
+2 -6
View File
@@ -1,9 +1,7 @@
use conduwuit::{Err, Result, checked}; use conduwuit::{Err, Result, checked};
use futures::{FutureExt, StreamExt, TryFutureExt}; use futures::{FutureExt, StreamExt, TryFutureExt};
use crate::admin_command; impl crate::Context<'_> {
#[admin_command]
pub(super) async fn register(&self) -> Result { pub(super) async fn register(&self) -> Result {
let body = &self.body; let body = &self.body;
let body_len = self.body.len(); let body_len = self.body.len();
@@ -33,7 +31,6 @@ pub(super) async fn register(&self) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result { pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
match self match self
.services .services
@@ -47,7 +44,6 @@ pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result { pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result {
match self match self
.services .services
@@ -64,7 +60,6 @@ pub(super) async fn show_appservice_config(&self, appservice_identifier: String)
.await .await
} }
#[admin_command]
pub(super) async fn list_registered(&self) -> Result { pub(super) async fn list_registered(&self) -> Result {
self.services self.services
.appservice .appservice
@@ -78,3 +73,4 @@ pub(super) async fn list_registered(&self) -> Result {
}) })
.await .await
} }
}
+2 -2
View File
@@ -1,10 +1,9 @@
use conduwuit::Result; use conduwuit::Result;
use conduwuit_macros::implement;
use futures::StreamExt; use futures::StreamExt;
use crate::Context; use crate::Context;
#[implement(Context, params = "<'_>")] impl Context<'_> {
pub(super) async fn check_all_users(&self) -> Result { pub(super) async fn check_all_users(&self) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let users = self.services.users.stream().collect::<Vec<_>>().await; let users = self.services.users.stream().collect::<Vec<_>>().await;
@@ -21,3 +20,4 @@ pub(super) async fn check_all_users(&self) -> Result {
)) ))
.await .await
} }
}
+114 -85
View File
@@ -6,7 +6,7 @@ use std::{
}; };
use conduwuit::{ use conduwuit::{
Err, Result, debug_error, err, info, Err, Result, at, debug_error, err, info,
matrix::{ matrix::{
Event, Event,
pdu::{PduEvent, PduId, RawPduId}, pdu::{PduEvent, PduId, RawPduId},
@@ -31,44 +31,6 @@ use service::rooms::{
}; };
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
use crate::admin_command;
#[admin_command]
pub(super) async fn echo(&self, message: Vec<String>) -> Result {
let message = message.join(" ");
self.write_str(&message).await
}
#[admin_command]
pub(super) async fn get_auth_chain(&self, event_id: OwnedEventId) -> Result {
let Ok(event) = self.services.rooms.timeline.get_pdu_json(&event_id).await else {
return Err!("Event not found.");
};
let room_id_str = event
.get("room_id")
.and_then(CanonicalJsonValue::as_str)
.ok_or_else(|| err!(Database("Invalid event in database")))?;
let room_id = <&RoomId>::try_from(room_id_str)
.map_err(|_| err!(Database("Invalid room id field in event in database")))?;
let start = Instant::now();
let count = self
.services
.rooms
.auth_chain
.event_ids_iter(room_id, once(event_id.as_ref()))
.ready_filter_map(Result::ok)
.count()
.await;
let elapsed = start.elapsed();
let out = format!("Loaded auth chain with length {count} in {elapsed:?}");
self.write_str(&out).await
}
#[derive(Clone, Copy, Eq, PartialEq)] #[derive(Clone, Copy, Eq, PartialEq)]
enum NodeStatus { enum NodeStatus {
Normal(bool), Normal(bool),
@@ -115,7 +77,41 @@ fn render_node(
Ok(()) Ok(())
} }
#[admin_command] impl crate::Context<'_> {
pub(super) async fn echo(&self, message: Vec<String>) -> Result {
let message = message.join(" ");
self.write_str(&message).await
}
pub(super) async fn get_auth_chain(&self, event_id: OwnedEventId) -> Result {
let Ok(event) = self.services.rooms.timeline.get_pdu_json(&event_id).await else {
return Err!("Event not found.");
};
let room_id_str = event
.get("room_id")
.and_then(CanonicalJsonValue::as_str)
.ok_or_else(|| err!(Database("Invalid event in database")))?;
let room_id = <&RoomId>::try_from(room_id_str)
.map_err(|_| err!(Database("Invalid room id field in event in database")))?;
let start = Instant::now();
let count = self
.services
.rooms
.auth_chain
.event_ids_iter(room_id, once(event_id.as_ref()))
.ready_filter_map(Result::ok)
.count()
.await;
let elapsed = start.elapsed();
let out = format!("Loaded auth chain with length {count} in {elapsed:?}");
self.write_str(&out).await
}
pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result { pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
let node_status = async |event_id: &EventId, missing: bool| -> NodeStatus { let node_status = async |event_id: &EventId, missing: bool| -> NodeStatus {
if self if self
@@ -184,7 +180,8 @@ pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
continue; continue;
} }
let current_node_id = node_id_for(&current_event_id, &mut node_ids, &mut next_node_id); let current_node_id =
node_id_for(&current_event_id, &mut node_ids, &mut next_node_id);
let current_status = node_status(&current_event_id, false).await; let current_status = node_status(&current_event_id, false).await;
render_node( render_node(
@@ -268,7 +265,6 @@ pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
self.write_str(&graph).await self.write_str(&graph).await
} }
#[admin_command]
pub(super) async fn parse_pdu(&self) -> Result { pub(super) async fn parse_pdu(&self) -> Result {
if self.body.len() < 2 if self.body.len() < 2
|| !self.body[0].trim().starts_with("```") || !self.body[0].trim().starts_with("```")
@@ -287,7 +283,8 @@ pub(super) async fn parse_pdu(&self) -> Result {
| Ok(hash) => { | Ok(hash) => {
let event_id = EventId::parse(format!("${hash}")); let event_id = EventId::parse(format!("${hash}"));
match serde_json::from_value::<PduEvent>(serde_json::to_value(value)?) { match serde_json::from_value::<PduEvent>(serde_json::to_value(value)?) {
| Err(e) => return Err!("EventId: {event_id:?}\nCould not parse event: {e}"), | Err(e) =>
return Err!("EventId: {event_id:?}\nCould not parse event: {e}"),
| Ok(pdu) => write!(self, "EventId: {event_id:?}\n{pdu:#?}"), | Ok(pdu) => write!(self, "EventId: {event_id:?}\n{pdu:#?}"),
} }
}, },
@@ -296,7 +293,6 @@ pub(super) async fn parse_pdu(&self) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result { pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
let mut outlier = false; let mut outlier = false;
let mut pdu_json = self let mut pdu_json = self
@@ -342,7 +338,6 @@ pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn get_short_pdu( pub(super) async fn get_short_pdu(
&self, &self,
shortroomid: ShortRoomId, shortroomid: ShortRoomId,
@@ -371,8 +366,11 @@ pub(super) async fn get_short_pdu(
.await .await
} }
#[admin_command] pub(super) async fn get_remote_pdu_list(
pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: bool) -> Result { &self,
server: OwnedServerName,
force: bool,
) -> Result {
if !self.services.server.config.allow_federation { if !self.services.server.config.allow_federation {
return Err!("Federation is disabled on this homeserver.",); return Err!("Federation is disabled on this homeserver.",);
} }
@@ -425,13 +423,13 @@ pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: b
} }
} }
let out = let out = format!(
format!("Fetched {success_count} remote PDUs successfully with {failed_count} failures"); "Fetched {success_count} remote PDUs successfully with {failed_count} failures"
);
self.write_str(&out).await self.write_str(&out).await
} }
#[admin_command]
pub(super) async fn get_remote_pdu( pub(super) async fn get_remote_pdu(
&self, &self,
event_id: OwnedEventId, event_id: OwnedEventId,
@@ -459,15 +457,17 @@ pub(super) async fn get_remote_pdu(
{ {
| Err(e) => { | Err(e) => {
return Err!( return Err!(
"Remote server did not have PDU or failed sending request to remote server: {e}" "Remote server did not have PDU or failed sending request to remote server: \
{e}"
); );
}, },
| Ok(response) => { | Ok(response) => {
let json: CanonicalJsonObject = let json: CanonicalJsonObject = serde_json::from_str(response.pdu.get())
serde_json::from_str(response.pdu.get()).map_err(|e| { .map_err(|e| {
warn!( warn!(
"Requested event ID {event_id} from server but failed to convert from \ "Requested event ID {event_id} from server but failed to convert \
RawValue to CanonicalJsonObject (malformed event/response?): {e}" from RawValue to CanonicalJsonObject (malformed event/response?): \
{e}"
); );
err!(Request(Unknown( err!(Request(Unknown(
"Received response from server but failed to parse PDU" "Received response from server but failed to parse PDU"
@@ -489,7 +489,9 @@ pub(super) async fn get_remote_pdu(
| Err(e) => { | Err(e) => {
warn!("Failed to parse PDU: {e}"); warn!("Failed to parse PDU: {e}");
info!("Full PDU: {:?}", &response.pdu); info!("Full PDU: {:?}", &response.pdu);
return Err!("Failed to parse PDU remote server {server} sent us: {e}"); return Err!(
"Failed to parse PDU remote server {server} sent us: {e}"
);
}, },
}; };
@@ -504,7 +506,43 @@ pub(super) async fn get_remote_pdu(
.await .await
} }
#[admin_command] pub(super) async fn get_state_at(&self, event_id: OwnedEventId) -> Result {
self.bail_restricted()?;
let shortstatehash = self
.services
.rooms
.state_accessor
.pdu_shortstatehash(&event_id)
.await?;
let state_ids: Vec<OwnedEventId> = self
.services
.rooms
.state_accessor
.state_full_ids(shortstatehash)
.map(at!(1))
.collect()
.await;
let pdus: Vec<CanonicalJsonObject> = state_ids
.iter()
.try_stream()
.and_then(|id| self.services.rooms.timeline.get_pdu_json(id))
.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 out = format!("```json\n{json}\n```");
self.write_str(&out).await
}
pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result { pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -524,8 +562,8 @@ pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result {
let json = serde_json::to_string_pretty(&room_state).map_err(|e| { let json = serde_json::to_string_pretty(&room_state).map_err(|e| {
err!(Database( err!(Database(
"Failed to convert room state events to pretty JSON, possible invalid room state \ "Failed to convert room state events to pretty JSON, possible invalid room \
events in our database {e}", state events in our database {e}",
)) ))
})?; })?;
@@ -533,7 +571,6 @@ pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result {
self.write_str(&out).await self.write_str(&out).await
} }
#[admin_command]
pub(super) async fn ping(&self, server: OwnedServerName) -> Result { pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
if server == self.services.globals.server_name() { if server == self.services.globals.server_name() {
return Err!("Not allowed to send federation requests to ourselves."); return Err!("Not allowed to send federation requests to ourselves.");
@@ -569,7 +606,6 @@ pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn force_device_list_updates(&self) -> Result { pub(super) async fn force_device_list_updates(&self) -> Result {
// Force E2EE device list updates for all users // Force E2EE device list updates for all users
self.services self.services
@@ -581,7 +617,6 @@ pub(super) async fn force_device_list_updates(&self) -> Result {
write!(self, "Marked all devices for all users as having new keys to update").await write!(self, "Marked all devices for all users as having new keys to update").await
} }
#[admin_command]
pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result { pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result {
let handles = &["console"]; let handles = &["console"];
@@ -603,7 +638,8 @@ pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool)
}, },
| Ok(()) => { | Ok(()) => {
let value = &self.services.server.config.log; let value = &self.services.server.config.log;
let out = format!("Successfully changed log level back to config value {value}"); let out =
format!("Successfully changed log level back to config value {value}");
return self.write_str(&out).await; return self.write_str(&out).await;
}, },
} }
@@ -634,7 +670,6 @@ pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool)
Err!("No log level was specified.") Err!("No log level was specified.")
} }
#[admin_command]
pub(super) async fn verify_json(&self) -> Result { pub(super) async fn verify_json(&self) -> Result {
if self.body.len() < 2 if self.body.len() < 2
|| !self.body[0].trim().starts_with("```") || !self.body[0].trim().starts_with("```")
@@ -661,7 +696,6 @@ pub(super) async fn verify_json(&self) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result { pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result {
use ruma::signatures::Verified; use ruma::signatures::Verified;
@@ -683,7 +717,6 @@ pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result {
self.write_str(msg).await self.write_str(msg).await
} }
#[admin_command]
#[tracing::instrument(skip(self), level = "info")] #[tracing::instrument(skip(self), level = "info")]
pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -695,7 +728,9 @@ pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
.server_in_room(&self.services.server.name, &room_id) .server_in_room(&self.services.server.name, &room_id)
.await .await
{ {
return Err!("We are not participating in the room / we don't know about the room ID.",); return Err!(
"We are not participating in the room / we don't know about the room ID.",
);
} }
let first_pdu = self let first_pdu = self
@@ -710,7 +745,6 @@ pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.write_str(&out).await self.write_str(&out).await
} }
#[admin_command]
#[tracing::instrument(skip(self), level = "info")] #[tracing::instrument(skip(self), level = "info")]
pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -722,7 +756,9 @@ pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
.server_in_room(&self.services.server.name, &room_id) .server_in_room(&self.services.server.name, &room_id)
.await .await
{ {
return Err!("We are not participating in the room / we don't know about the room ID."); return Err!(
"We are not participating in the room / we don't know about the room ID."
);
} }
let latest_pdu = self let latest_pdu = self
@@ -737,7 +773,6 @@ pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.write_str(&out).await self.write_str(&out).await
} }
#[admin_command]
#[tracing::instrument(skip(self), level = "info")] #[tracing::instrument(skip(self), level = "info")]
pub(super) async fn force_set_room_state_from_server( pub(super) async fn force_set_room_state_from_server(
&self, &self,
@@ -754,7 +789,9 @@ pub(super) async fn force_set_room_state_from_server(
.server_in_room(&self.services.server.name, &room_id) .server_in_room(&self.services.server.name, &room_id)
.await .await
{ {
return Err!("We are not participating in the room / we don't know about the room ID."); return Err!(
"We are not participating in the room / we don't know about the room ID."
);
} }
let at_event_id = match at_event { let at_event_id = match at_event {
@@ -811,7 +848,9 @@ pub(super) async fn force_set_room_state_from_server(
}; };
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| { let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
debug_error!("Invalid PDU in fetching remote room state PDUs response: {value:#?}"); debug_error!(
"Invalid PDU in fetching remote room state PDUs response: {value:#?}"
);
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}"))) err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
})?; })?;
@@ -896,7 +935,6 @@ pub(super) async fn force_set_room_state_from_server(
.await .await
} }
#[admin_command]
pub(super) async fn get_signing_keys( pub(super) async fn get_signing_keys(
&self, &self,
server_name: Option<OwnedServerName>, server_name: Option<OwnedServerName>,
@@ -932,7 +970,6 @@ pub(super) async fn get_signing_keys(
self.write_str(&out).await self.write_str(&out).await
} }
#[admin_command]
pub(super) async fn get_verify_keys(&self, server_name: Option<OwnedServerName>) -> Result { pub(super) async fn get_verify_keys(&self, server_name: Option<OwnedServerName>) -> Result {
let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone()); let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone());
@@ -952,7 +989,6 @@ pub(super) async fn get_verify_keys(&self, server_name: Option<OwnedServerName>)
self.write_str(&out).await self.write_str(&out).await
} }
#[admin_command]
pub(super) async fn resolve_true_destination( pub(super) async fn resolve_true_destination(
&self, &self,
server_name: OwnedServerName, server_name: OwnedServerName,
@@ -979,7 +1015,6 @@ pub(super) async fn resolve_true_destination(
self.write_str(&msg).await self.write_str(&msg).await
} }
#[admin_command]
pub(super) async fn memory_stats(&self, opts: Option<String>) -> Result { pub(super) async fn memory_stats(&self, opts: Option<String>) -> Result {
const OPTS: &str = "abcdefghijklmnopqrstuvwxyz"; const OPTS: &str = "abcdefghijklmnopqrstuvwxyz";
@@ -1003,7 +1038,7 @@ pub(super) async fn memory_stats(&self, opts: Option<String>) -> Result {
} }
#[cfg(tokio_unstable)] #[cfg(tokio_unstable)]
#[admin_command]
pub(super) async fn runtime_metrics(&self) -> Result { pub(super) async fn runtime_metrics(&self) -> Result {
let out = self.services.server.metrics.runtime_metrics().map_or_else( let out = self.services.server.metrics.runtime_metrics().map_or_else(
|| "Runtime metrics are not available.".to_owned(), || "Runtime metrics are not available.".to_owned(),
@@ -1021,14 +1056,13 @@ pub(super) async fn runtime_metrics(&self) -> Result {
} }
#[cfg(not(tokio_unstable))] #[cfg(not(tokio_unstable))]
#[admin_command]
pub(super) async fn runtime_metrics(&self) -> Result { pub(super) async fn runtime_metrics(&self) -> Result {
self.write_str("Runtime metrics require building with `tokio_unstable`.") self.write_str("Runtime metrics require building with `tokio_unstable`.")
.await .await
} }
#[cfg(tokio_unstable)] #[cfg(tokio_unstable)]
#[admin_command]
pub(super) async fn runtime_interval(&self) -> Result { pub(super) async fn runtime_interval(&self) -> Result {
let out = self.services.server.metrics.runtime_interval().map_or_else( let out = self.services.server.metrics.runtime_interval().map_or_else(
|| "Runtime metrics are not available.".to_owned(), || "Runtime metrics are not available.".to_owned(),
@@ -1039,13 +1073,11 @@ pub(super) async fn runtime_interval(&self) -> Result {
} }
#[cfg(not(tokio_unstable))] #[cfg(not(tokio_unstable))]
#[admin_command]
pub(super) async fn runtime_interval(&self) -> Result { pub(super) async fn runtime_interval(&self) -> Result {
self.write_str("Runtime metrics require building with `tokio_unstable`.") self.write_str("Runtime metrics require building with `tokio_unstable`.")
.await .await
} }
#[admin_command]
pub(super) async fn time(&self) -> Result { pub(super) async fn time(&self) -> Result {
let now = SystemTime::now(); let now = SystemTime::now();
let now = utils::time::format(now, "%+"); let now = utils::time::format(now, "%+");
@@ -1053,7 +1085,6 @@ pub(super) async fn time(&self) -> Result {
self.write_str(&now).await self.write_str(&now).await
} }
#[admin_command]
pub(super) async fn database_stats( pub(super) async fn database_stats(
&self, &self,
property: Option<String>, property: Option<String>,
@@ -1073,7 +1104,6 @@ pub(super) async fn database_stats(
.await .await
} }
#[admin_command]
pub(super) async fn database_files(&self, map: Option<String>, level: Option<i32>) -> Result { pub(super) async fn database_files(&self, map: Option<String>, level: Option<i32>) -> Result {
let mut files: Vec<_> = self.services.db.db.file_list().collect::<Result<_>>()?; let mut files: Vec<_> = self.services.db.db.file_list().collect::<Result<_>>()?;
@@ -1104,14 +1134,12 @@ pub(super) async fn database_files(&self, map: Option<String>, level: Option<i32
.await .await
} }
#[admin_command]
pub(super) async fn trim_memory(&self) -> Result { pub(super) async fn trim_memory(&self) -> Result {
conduwuit::alloc::trim(None)?; conduwuit::alloc::trim(None)?;
writeln!(self, "done").await writeln!(self, "done").await
} }
#[admin_command]
pub(super) async fn send_test_email(&self) -> Result { pub(super) async fn send_test_email(&self) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -1138,3 +1166,4 @@ pub(super) async fn send_test_email(&self) -> Result {
Ok(()) Ok(())
} }
}
+8
View File
@@ -95,6 +95,14 @@ pub enum DebugCommand {
room_id: OwnedRoomOrAliasId, room_id: OwnedRoomOrAliasId,
}, },
/// Gets all the room state events at the specified event.
///
/// State at event might not be available for some PDUs, such as rejected
/// ones.
GetStateAt {
event_id: OwnedEventId,
},
/// Get and display signing keys from local cache or remote server. /// Get and display signing keys from local cache or remote server.
GetSigningKeys { GetSigningKeys {
server_name: Option<OwnedServerName>, server_name: Option<OwnedServerName>,
+3 -8
View File
@@ -1,6 +1,6 @@
use conduwuit::{Err, Result}; use conduwuit::{Err, Result};
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, clap::Subcommand)] #[derive(Debug, clap::Subcommand)]
@@ -11,31 +11,25 @@ pub enum TesterCommand {
Timer, Timer,
} }
impl crate::Context<'_> {
#[rustfmt::skip] #[rustfmt::skip]
#[admin_command]
async fn panic(&self) -> Result { async fn panic(&self) -> Result {
panic!("panicked") panic!("panicked")
} }
#[rustfmt::skip] #[rustfmt::skip]
#[admin_command]
async fn failure(&self) -> Result { async fn failure(&self) -> Result {
Err!("failed") Err!("failed")
} }
#[inline(never)] #[inline(never)]
#[rustfmt::skip] #[rustfmt::skip]
#[admin_command]
async fn tester(&self) -> Result { async fn tester(&self) -> Result {
self.write_str("Ok").await self.write_str("Ok").await
} }
#[inline(never)] #[inline(never)]
#[rustfmt::skip] #[rustfmt::skip]
#[admin_command]
async fn timer(&self) -> Result { async fn timer(&self) -> Result {
let started = std::time::Instant::now(); let started = std::time::Instant::now();
timed(self.body); timed(self.body);
@@ -43,6 +37,7 @@ async fn timer(&self) -> Result {
let elapsed = started.elapsed(); let elapsed = started.elapsed();
self.write_str(&format!("completed in {elapsed:#?}")).await self.write_str(&format!("completed in {elapsed:#?}")).await
} }
}
#[inline(never)] #[inline(never)]
#[rustfmt::skip] #[rustfmt::skip]
+11 -7
View File
@@ -4,23 +4,21 @@ use conduwuit::{Err, Result, utils::response::LimitReadExt};
use futures::StreamExt; use futures::StreamExt;
use ruma::{OwnedRoomId, OwnedServerName, OwnedUserId}; use ruma::{OwnedRoomId, OwnedServerName, OwnedUserId};
use crate::{admin_command, get_room_info}; use crate::get_room_info;
#[admin_command] impl crate::Context<'_> {
pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
self.services.rooms.metadata.disable_room(&room_id, true); self.services.rooms.metadata.disable_room(&room_id, true);
self.write_str("Room disabled.").await self.write_str("Room disabled.").await
} }
#[admin_command]
pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
self.services.rooms.metadata.disable_room(&room_id, false); self.services.rooms.metadata.disable_room(&room_id, false);
self.write_str("Room enabled.").await self.write_str("Room enabled.").await
} }
#[admin_command]
pub(super) async fn incoming_federation(&self) -> Result { pub(super) async fn incoming_federation(&self) -> Result {
let msg = { let msg = {
let map = self let map = self
@@ -37,7 +35,14 @@ pub(super) async fn incoming_federation(&self) -> Result {
); );
for (r, (e, i)) in map.iter() { for (r, (e, i)) in map.iter() {
let elapsed = i.elapsed(); let elapsed = i.elapsed();
writeln!(msg, "{} {}: {}m{}s", r, e, elapsed.as_secs() / 60, elapsed.as_secs() % 60)?; writeln!(
msg,
"{} {}: {}m{}s",
r,
e,
elapsed.as_secs() / 60,
elapsed.as_secs() % 60
)?;
} }
msg msg
}; };
@@ -45,7 +50,6 @@ pub(super) async fn incoming_federation(&self) -> Result {
self.write_str(&msg).await self.write_str(&msg).await
} }
#[admin_command]
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result { pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
let response = self let response = self
.services .services
@@ -93,7 +97,6 @@ pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName
.await .await
} }
#[admin_command]
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result { pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
if user_id.server_name() == self.services.server.name { if user_id.server_name() == self.services.server.name {
return Err!( return Err!(
@@ -128,3 +131,4 @@ pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```")) self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
.await .await
} }
}
+32 -30
View File
@@ -9,9 +9,9 @@ use conduwuit_service::media::Dim;
use ruma::{OwnedEventId, OwnedMxcUri, OwnedServerName}; use ruma::{OwnedEventId, OwnedMxcUri, OwnedServerName};
use service::media::mxc::Mxc; use service::media::mxc::Mxc;
use crate::{admin_command, utils::parse_local_user_id}; use crate::utils::parse_local_user_id;
#[admin_command] impl crate::Context<'_> {
pub(super) async fn delete( pub(super) async fn delete(
&self, &self,
mxc: Option<OwnedMxcUri>, mxc: Option<OwnedMxcUri>,
@@ -59,8 +59,8 @@ pub(super) async fn delete(
mxc_urls.push(final_url); mxc_urls.push(final_url);
} else { } else {
info!( info!(
"Found a URL in the event ID {event_id} but did not start \ "Found a URL in the event ID {event_id} but did not \
with mxc://, ignoring" start with mxc://, ignoring"
); );
} }
} }
@@ -73,26 +73,29 @@ pub(super) async fn delete(
if let Some(info) = info_obj { if let Some(info) = info_obj {
if let Some(thumbnail_url) = info.get("thumbnail_url") { if let Some(thumbnail_url) = info.get("thumbnail_url") {
debug!("Found a thumbnail_url in info key: {thumbnail_url}"); debug!(
"Found a thumbnail_url in info key: {thumbnail_url}"
);
if thumbnail_url.to_string().starts_with("\"mxc://") { if thumbnail_url.to_string().starts_with("\"mxc://") {
debug!( debug!(
"Pushing thumbnail URL {thumbnail_url} to list of \ "Pushing thumbnail URL {thumbnail_url} to list \
MXCs to delete" of MXCs to delete"
); );
let final_thumbnail_url = let final_thumbnail_url =
thumbnail_url.to_string().replace('"', ""); thumbnail_url.to_string().replace('"', "");
mxc_urls.push(final_thumbnail_url); mxc_urls.push(final_thumbnail_url);
} else { } else {
info!( info!(
"Found a thumbnail URL in the event ID {event_id} \ "Found a thumbnail URL in the event ID \
but did not start with mxc://, ignoring" {event_id} but did not start with mxc://, \
ignoring"
); );
} }
} else { } else {
info!( info!(
"No \"thumbnail_url\" key in \"info\" key, assuming no \ "No \"thumbnail_url\" key in \"info\" key, assuming \
thumbnails." no thumbnails."
); );
} }
} }
@@ -114,8 +117,8 @@ pub(super) async fn delete(
mxc_urls.push(final_url); mxc_urls.push(final_url);
} else { } else {
warn!( warn!(
"Found a URL in the event ID {event_id} but did not \ "Found a URL in the event ID {event_id} but did \
start with mxc://, ignoring" not start with mxc://, ignoring"
); );
} }
} else { } else {
@@ -131,8 +134,8 @@ pub(super) async fn delete(
} }
} else { } else {
return Err!( return Err!(
"Event ID does not have a \"content\" key, this is not a message or an \ "Event ID does not have a \"content\" key, this is not a message or \
event type that contains media.", an event type that contains media.",
); );
} }
}, },
@@ -155,11 +158,15 @@ pub(super) async fn delete(
.await .await
{ {
| Ok(()) => { | Ok(()) => {
debug_info!("Successfully deleted {mxc_url} from filesystem and database"); debug_info!(
"Successfully deleted {mxc_url} from filesystem and database"
);
mxc_deletion_count = mxc_deletion_count.saturating_add(1); mxc_deletion_count = mxc_deletion_count.saturating_add(1);
}, },
| Err(e) => { | Err(e) => {
debug_warn!("Failed to delete {mxc_url}, ignoring error and skipping: {e}"); debug_warn!(
"Failed to delete {mxc_url}, ignoring error and skipping: {e}"
);
continue; continue;
}, },
} }
@@ -167,8 +174,8 @@ pub(super) async fn delete(
return self return self
.write_str(&format!( .write_str(&format!(
"Deleted {mxc_deletion_count} total MXCs from our database and the filesystem \ "Deleted {mxc_deletion_count} total MXCs from our database and the \
from event ID {event_id}." filesystem from event ID {event_id}."
)) ))
.await; .await;
} }
@@ -179,7 +186,6 @@ pub(super) async fn delete(
) )
} }
#[admin_command]
pub(super) async fn delete_list(&self) -> Result { pub(super) async fn delete_list(&self) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -224,13 +230,13 @@ pub(super) async fn delete_list(&self) -> Result {
} }
self.write_str(&format!( self.write_str(&format!(
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our database \ "Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our \
and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from the database.", database and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from \
the database.",
)) ))
.await .await
} }
#[admin_command]
pub(super) async fn delete_past_remote_media( pub(super) async fn delete_past_remote_media(
&self, &self,
duration: String, duration: String,
@@ -266,7 +272,6 @@ pub(super) async fn delete_past_remote_media(
.await .await
} }
#[admin_command]
pub(super) async fn delete_all_from_user(&self, username: String) -> Result { pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
let user_id = parse_local_user_id(self.services, &username)?; let user_id = parse_local_user_id(self.services, &username)?;
@@ -276,7 +281,6 @@ pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn delete_all_from_server( pub(super) async fn delete_all_from_server(
&self, &self,
server_name: OwnedServerName, server_name: OwnedServerName,
@@ -284,7 +288,8 @@ pub(super) async fn delete_all_from_server(
) -> Result { ) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media { if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media
{
return Err!("This command only works for remote media by default.",); return Err!("This command only works for remote media by default.",);
} }
@@ -335,7 +340,6 @@ pub(super) async fn delete_all_from_server(
.await .await
} }
#[admin_command]
pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result { pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
let mxc: Mxc<'_> = mxc.as_str().try_into()?; let mxc: Mxc<'_> = mxc.as_str().try_into()?;
let metadata = self.services.media.get_metadata(&mxc).await; let metadata = self.services.media.get_metadata(&mxc).await;
@@ -343,7 +347,6 @@ pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
self.write_str(&format!("```\n{metadata:#?}\n```")).await self.write_str(&format!("```\n{metadata:#?}\n```")).await
} }
#[admin_command]
pub(super) async fn get_remote_file( pub(super) async fn get_remote_file(
&self, &self,
mxc: OwnedMxcUri, mxc: OwnedMxcUri,
@@ -366,7 +369,6 @@ pub(super) async fn get_remote_file(
.await .await
} }
#[admin_command]
pub(super) async fn get_remote_thumbnail( pub(super) async fn get_remote_thumbnail(
&self, &self,
mxc: OwnedMxcUri, mxc: OwnedMxcUri,
@@ -392,7 +394,6 @@ pub(super) async fn get_remote_thumbnail(
.await .await
} }
#[admin_command]
pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result { pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result {
if all { if all {
self.services.media.clear_url_previews().await; self.services.media.clear_url_previews().await;
@@ -407,3 +408,4 @@ pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) ->
self.write_str(&format!("Deleted cached URL preview for: {url}")) self.write_str(&format!("Deleted cached URL preview for: {url}"))
.await .await
} }
}
+1 -1
View File
@@ -26,7 +26,7 @@ extern crate conduwuit_api as api;
extern crate conduwuit_core as conduwuit; extern crate conduwuit_core as conduwuit;
extern crate conduwuit_service as service; extern crate conduwuit_service as service;
pub(crate) use conduwuit_macros::{admin_command, admin_command_dispatch}; pub(crate) use conduwuit_macros::admin_command_dispatch;
pub(crate) use crate::{context::Context, utils::get_room_info}; pub(crate) use crate::{context::Context, utils::get_room_info};
+3 -3
View File
@@ -4,7 +4,7 @@ use conduwuit_database::Deserialized as _;
use futures::StreamExt; use futures::StreamExt;
use ruma::{OwnedRoomId, OwnedUserId, exports::serde::Serialize}; use ruma::{OwnedRoomId, OwnedUserId, exports::serde::Serialize};
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -31,7 +31,7 @@ pub enum AccountDataCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
async fn changes_since( async fn changes_since(
&self, &self,
user_id: OwnedUserId, user_id: OwnedUserId,
@@ -51,7 +51,6 @@ async fn changes_since(
.await .await
} }
#[admin_command]
async fn account_data_get( async fn account_data_get(
&self, &self,
user_id: OwnedUserId, user_id: OwnedUserId,
@@ -78,3 +77,4 @@ async fn account_data_get(
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{json}\n```")) self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{json}\n```"))
.await .await
} }
}
+27 -19
View File
@@ -13,7 +13,7 @@ use conduwuit_service::Services;
use futures::{FutureExt, Stream, StreamExt, TryStreamExt}; use futures::{FutureExt, Stream, StreamExt, TryStreamExt};
use tokio::time::Instant; use tokio::time::Instant;
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -159,7 +159,7 @@ pub enum RawCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
pub(super) async fn compact( pub(super) async fn compact(
&self, &self,
map: Option<Vec<String>>, map: Option<Vec<String>>,
@@ -223,7 +223,6 @@ pub(super) async fn compact(
.await .await
} }
#[admin_command]
pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result { pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY); let prefix = prefix.as_deref().unwrap_or(EMPTY);
@@ -238,7 +237,6 @@ pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>
.await .await
} }
#[admin_command]
pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result { pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result {
writeln!(self, "```").boxed().await?; writeln!(self, "```").boxed().await?;
@@ -257,8 +255,11 @@ pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Resu
.await .await
} }
#[admin_command] pub(super) async fn raw_keys_sizes(
pub(super) async fn raw_keys_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result { &self,
map: Option<String>,
prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY); let prefix = prefix.as_deref().unwrap_or(EMPTY);
let timer = Instant::now(); let timer = Instant::now();
@@ -279,8 +280,11 @@ pub(super) async fn raw_keys_sizes(&self, map: Option<String>, prefix: Option<St
.await .await
} }
#[admin_command] pub(super) async fn raw_keys_total(
pub(super) async fn raw_keys_total(&self, map: Option<String>, prefix: Option<String>) -> Result { &self,
map: Option<String>,
prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY); let prefix = prefix.as_deref().unwrap_or(EMPTY);
let timer = Instant::now(); let timer = Instant::now();
@@ -297,8 +301,11 @@ pub(super) async fn raw_keys_total(&self, map: Option<String>, prefix: Option<St
.await .await
} }
#[admin_command] pub(super) async fn raw_vals_sizes(
pub(super) async fn raw_vals_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result { &self,
map: Option<String>,
prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY); let prefix = prefix.as_deref().unwrap_or(EMPTY);
let timer = Instant::now(); let timer = Instant::now();
@@ -320,8 +327,11 @@ pub(super) async fn raw_vals_sizes(&self, map: Option<String>, prefix: Option<St
.await .await
} }
#[admin_command] pub(super) async fn raw_vals_total(
pub(super) async fn raw_vals_total(&self, map: Option<String>, prefix: Option<String>) -> Result { &self,
map: Option<String>,
prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY); let prefix = prefix.as_deref().unwrap_or(EMPTY);
let timer = Instant::now(); let timer = Instant::now();
@@ -339,7 +349,6 @@ pub(super) async fn raw_vals_total(&self, map: Option<String>, prefix: Option<St
.await .await
} }
#[admin_command]
pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result { pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result {
writeln!(self, "```").await?; writeln!(self, "```").await?;
@@ -347,7 +356,10 @@ pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Resu
let timer = Instant::now(); let timer = Instant::now();
prefix prefix
.as_deref() .as_deref()
.map_or_else(|| map.raw_stream().boxed(), |prefix| map.raw_stream_prefix(prefix).boxed()) .map_or_else(
|| map.raw_stream().boxed(),
|prefix| map.raw_stream_prefix(prefix).boxed(),
)
.map_ok(apply!(2, String::from_utf8_lossy)) .map_ok(apply!(2, String::from_utf8_lossy))
.map_ok(apply!(2, Cow::into_owned)) .map_ok(apply!(2, Cow::into_owned))
.try_for_each(|keyval| writeln!(self, "{keyval:?}")) .try_for_each(|keyval| writeln!(self, "{keyval:?}"))
@@ -359,7 +371,6 @@ pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Resu
.await .await
} }
#[admin_command]
pub(super) async fn raw_keys_from( pub(super) async fn raw_keys_from(
&self, &self,
map: String, map: String,
@@ -382,7 +393,6 @@ pub(super) async fn raw_keys_from(
.await .await
} }
#[admin_command]
pub(super) async fn raw_iter_from( pub(super) async fn raw_iter_from(
&self, &self,
map: String, map: String,
@@ -404,7 +414,6 @@ pub(super) async fn raw_iter_from(
.await .await
} }
#[admin_command]
pub(super) async fn raw_del(&self, map: String, key: String) -> Result { pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
let map = self.services.db.get(&map)?; let map = self.services.db.get(&map)?;
let timer = Instant::now(); let timer = Instant::now();
@@ -415,7 +424,6 @@ pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn raw_get(&self, map: String, key: String) -> Result { pub(super) async fn raw_get(&self, map: String, key: String) -> Result {
let map = self.services.db.get(&map)?; let map = self.services.db.get(&map)?;
let timer = Instant::now(); let timer = Instant::now();
@@ -427,12 +435,12 @@ pub(super) async fn raw_get(&self, map: String, key: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn raw_maps(&self) -> Result { pub(super) async fn raw_maps(&self) -> Result {
let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect(); let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect();
self.write_str(&format!("{list:#?}")).await self.write_str(&format!("{list:#?}")).await
} }
}
fn with_maps_or<'a>( fn with_maps_or<'a>(
map: Option<&'a str>, map: Option<&'a str>,
+6 -5
View File
@@ -3,7 +3,7 @@ use conduwuit::{Err, Result, utils::time};
use futures::StreamExt; use futures::StreamExt;
use ruma::OwnedServerName; use ruma::OwnedServerName;
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -39,7 +39,7 @@ pub enum ResolverCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Result { async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Result {
use service::resolver::cache::CachedDest; use service::resolver::cache::CachedDest;
@@ -63,7 +63,6 @@ async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Resu
Ok(()) Ok(())
} }
#[admin_command]
async fn overrides_cache(&self, server_name: Option<String>) -> Result { async fn overrides_cache(&self, server_name: Option<String>) -> Result {
use service::resolver::cache::CachedOverride; use service::resolver::cache::CachedOverride;
@@ -82,14 +81,15 @@ async fn overrides_cache(&self, server_name: Option<String>) -> Result {
} }
let expire = time::format(expire, "%+"); let expire = time::format(expire, "%+");
self.write_str(&format!("| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n")) self.write_str(&format!(
"| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n"
))
.await?; .await?;
} }
Ok(()) Ok(())
} }
#[admin_command]
async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result { async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result {
if all { if all {
self.services.resolver.cache.clear().await; self.services.resolver.cache.clear().await;
@@ -103,3 +103,4 @@ async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result
Err!("Missing name. Supply a name or use --all to flush the whole cache.") Err!("Missing name. Supply a name or use --all to flush the whole cache.")
} }
} }
}
+3 -3
View File
@@ -3,7 +3,7 @@ use conduwuit::{PduCount, Result, utils::stream::TryTools};
use futures::TryStreamExt; use futures::TryStreamExt;
use ruma::OwnedRoomOrAliasId; use ruma::OwnedRoomOrAliasId;
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -23,7 +23,7 @@ pub enum RoomTimelineCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
pub(super) async fn last(&self, room_id: OwnedRoomOrAliasId) -> Result { pub(super) async fn last(&self, room_id: OwnedRoomOrAliasId) -> Result {
let room_id = self.services.rooms.alias.resolve(&room_id).await?; let room_id = self.services.rooms.alias.resolve(&room_id).await?;
@@ -37,7 +37,6 @@ pub(super) async fn last(&self, room_id: OwnedRoomOrAliasId) -> Result {
self.write_str(&format!("{result:#?}")).await self.write_str(&format!("{result:#?}")).await
} }
#[admin_command]
pub(super) async fn pdus( pub(super) async fn pdus(
&self, &self,
room_id: OwnedRoomOrAliasId, room_id: OwnedRoomOrAliasId,
@@ -59,3 +58,4 @@ pub(super) async fn pdus(
self.write_str(&format!("```\n{result:#?}\n```")).await self.write_str(&format!("```\n{result:#?}\n```")).await
} }
}
+3 -3
View File
@@ -2,7 +2,7 @@ use clap::Subcommand;
use conduwuit::Result; use conduwuit::Result;
use ruma::{OwnedEventId, OwnedRoomOrAliasId}; use ruma::{OwnedEventId, OwnedRoomOrAliasId};
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -17,7 +17,7 @@ pub enum ShortCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
pub(super) async fn short_event_id(&self, event_id: OwnedEventId) -> Result { pub(super) async fn short_event_id(&self, event_id: OwnedEventId) -> Result {
let shortid = self let shortid = self
.services .services
@@ -29,7 +29,6 @@ pub(super) async fn short_event_id(&self, event_id: OwnedEventId) -> Result {
self.write_str(&format!("{shortid:#?}")).await self.write_str(&format!("{shortid:#?}")).await
} }
#[admin_command]
pub(super) async fn short_room_id(&self, room_id: OwnedRoomOrAliasId) -> Result { pub(super) async fn short_room_id(&self, room_id: OwnedRoomOrAliasId) -> Result {
let room_id = self.services.rooms.alias.resolve(&room_id).await?; let room_id = self.services.rooms.alias.resolve(&room_id).await?;
@@ -37,3 +36,4 @@ pub(super) async fn short_room_id(&self, room_id: OwnedRoomOrAliasId) -> Result
self.write_str(&format!("{shortid:#?}")).await self.write_str(&format!("{shortid:#?}")).await
} }
}
+20 -24
View File
@@ -3,7 +3,7 @@ use conduwuit::Result;
use futures::stream::StreamExt; use futures::stream::StreamExt;
use ruma::{OwnedDeviceId, OwnedRoomId, OwnedUserId}; use ruma::{OwnedDeviceId, OwnedRoomId, OwnedUserId};
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -92,7 +92,7 @@ pub enum UsersCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
async fn get_shared_rooms(&self, user_a: OwnedUserId, user_b: OwnedUserId) -> Result { async fn get_shared_rooms(&self, user_a: OwnedUserId, user_b: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result: Vec<_> = self let result: Vec<_> = self
@@ -108,7 +108,6 @@ async fn get_shared_rooms(&self, user_a: OwnedUserId, user_b: OwnedUserId) -> Re
.await .await
} }
#[admin_command]
async fn get_backup_session( async fn get_backup_session(
&self, &self,
user_id: OwnedUserId, user_id: OwnedUserId,
@@ -128,7 +127,6 @@ async fn get_backup_session(
.await .await
} }
#[admin_command]
async fn get_room_backups( async fn get_room_backups(
&self, &self,
user_id: OwnedUserId, user_id: OwnedUserId,
@@ -147,7 +145,6 @@ async fn get_room_backups(
.await .await
} }
#[admin_command]
async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result { async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self.services.key_backups.get_all(&user_id, &version).await; let result = self.services.key_backups.get_all(&user_id, &version).await;
@@ -157,7 +154,6 @@ async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result
.await .await
} }
#[admin_command]
async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> Result { async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self let result = self
@@ -171,7 +167,6 @@ async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> R
.await .await
} }
#[admin_command]
async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result { async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self let result = self
@@ -185,7 +180,6 @@ async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
.await .await
} }
#[admin_command]
async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result { async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self.services.key_backups.get_latest_backup(&user_id).await; let result = self.services.key_backups.get_latest_backup(&user_id).await;
@@ -195,10 +189,10 @@ async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result {
.await .await
} }
#[admin_command]
async fn iter_users(&self) -> Result { async fn iter_users(&self) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result: Vec<OwnedUserId> = self.services.users.stream().map(Into::into).collect().await; let result: Vec<OwnedUserId> =
self.services.users.stream().map(Into::into).collect().await;
let query_time = timer.elapsed(); let query_time = timer.elapsed();
@@ -206,7 +200,6 @@ async fn iter_users(&self) -> Result {
.await .await
} }
#[admin_command]
async fn iter_users2(&self) -> Result { async fn iter_users2(&self) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result: Vec<_> = self.services.users.stream().collect().await; let result: Vec<_> = self.services.users.stream().collect().await;
@@ -221,7 +214,6 @@ async fn iter_users2(&self) -> Result {
.await .await
} }
#[admin_command]
async fn count_users(&self) -> Result { async fn count_users(&self) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self.services.users.count().await; let result = self.services.users.count().await;
@@ -231,7 +223,6 @@ async fn count_users(&self) -> Result {
.await .await
} }
#[admin_command]
async fn list_devices(&self, user_id: OwnedUserId) -> Result { async fn list_devices(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let devices = self let devices = self
@@ -247,7 +238,6 @@ async fn list_devices(&self, user_id: OwnedUserId) -> Result {
.await .await
} }
#[admin_command]
async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result { async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let devices = self let devices = self
@@ -262,8 +252,11 @@ async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result {
.await .await
} }
#[admin_command] async fn get_device_metadata(
async fn get_device_metadata(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { &self,
user_id: OwnedUserId,
device_id: OwnedDeviceId,
) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let device = self let device = self
.services .services
@@ -276,7 +269,6 @@ async fn get_device_metadata(&self, user_id: OwnedUserId, device_id: OwnedDevice
.await .await
} }
#[admin_command]
async fn get_devices_version(&self, user_id: OwnedUserId) -> Result { async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let device = self.services.users.get_devicelist_version(&user_id).await; let device = self.services.users.get_devicelist_version(&user_id).await;
@@ -286,8 +278,11 @@ async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
.await .await
} }
#[admin_command] async fn count_one_time_keys(
async fn count_one_time_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { &self,
user_id: OwnedUserId,
device_id: OwnedDeviceId,
) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self let result = self
.services .services
@@ -300,7 +295,6 @@ async fn count_one_time_keys(&self, user_id: OwnedUserId, device_id: OwnedDevice
.await .await
} }
#[admin_command]
async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self let result = self
@@ -314,7 +308,6 @@ async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId)
.await .await
} }
#[admin_command]
async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result { async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self.services.users.get_user_signing_key(&user_id).await; let result = self.services.users.get_user_signing_key(&user_id).await;
@@ -324,7 +317,6 @@ async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result {
.await .await
} }
#[admin_command]
async fn get_master_key(&self, user_id: OwnedUserId) -> Result { async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self let result = self
@@ -338,8 +330,11 @@ async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
.await .await
} }
#[admin_command] async fn get_to_device_events(
async fn get_to_device_events(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { &self,
user_id: OwnedUserId,
device_id: OwnedDeviceId,
) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let result = self let result = self
.services .services
@@ -352,3 +347,4 @@ async fn get_to_device_events(&self, user_id: OwnedUserId, device_id: OwnedDevic
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.await .await
} }
}
+3 -3
View File
@@ -2,10 +2,10 @@ use conduwuit::{Err, Result};
use futures::StreamExt; use futures::StreamExt;
use ruma::OwnedRoomId; use ruma::OwnedRoomId;
use crate::{PAGE_SIZE, admin_command, get_room_info}; use crate::{PAGE_SIZE, get_room_info};
impl crate::Context<'_> {
#[allow(clippy::fn_params_excessive_bools)] #[allow(clippy::fn_params_excessive_bools)]
#[admin_command]
pub(super) async fn list_rooms( pub(super) async fn list_rooms(
&self, &self,
page: Option<usize>, page: Option<usize>,
@@ -76,9 +76,9 @@ pub(super) async fn list_rooms(
.await .await
} }
#[admin_command]
pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result {
let result = self.services.rooms.metadata.exists(&room_id).await; let result = self.services.rooms.metadata.exists(&room_id).await;
self.write_str(&format!("{result}")).await self.write_str(&format!("{result}")).await
} }
}
+3 -3
View File
@@ -3,7 +3,7 @@ use conduwuit::{Err, Result, utils::ReadyExt};
use futures::StreamExt; use futures::StreamExt;
use ruma::OwnedRoomId; use ruma::OwnedRoomId;
use crate::{admin_command, admin_command_dispatch}; use crate::admin_command_dispatch;
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -26,7 +26,7 @@ pub enum RoomInfoCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> Result { async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> Result {
let room_name = self let room_name = self
.services .services
@@ -70,7 +70,6 @@ async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> R
.await .await
} }
#[admin_command]
async fn view_room_topic(&self, room_id: OwnedRoomId) -> Result { async fn view_room_topic(&self, room_id: OwnedRoomId) -> Result {
let Ok(room_topic) = self let Ok(room_topic) = self
.services .services
@@ -85,3 +84,4 @@ async fn view_room_topic(&self, room_id: OwnedRoomId) -> Result {
self.write_str(&format!("Room topic:\n```\n{room_topic}\n```")) self.write_str(&format!("Room topic:\n```\n{room_topic}\n```"))
.await .await
} }
}
+32 -31
View File
@@ -8,7 +8,7 @@ use conduwuit::{
use futures::{FutureExt, StreamExt}; use futures::{FutureExt, StreamExt};
use ruma::{OwnedRoomId, OwnedRoomOrAliasId, RoomAliasId, RoomId, RoomOrAliasId}; use ruma::{OwnedRoomId, OwnedRoomOrAliasId, RoomAliasId, RoomId, RoomOrAliasId};
use crate::{admin_command, admin_command_dispatch, get_room_info}; use crate::{admin_command_dispatch, get_room_info};
#[admin_command_dispatch] #[admin_command_dispatch]
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
@@ -45,7 +45,7 @@ pub enum RoomModerationCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result { async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
debug!("Got room alias or ID: {}", room); debug!("Got room alias or ID: {}", room);
@@ -62,8 +62,8 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
| Ok(room_id) => room_id, | Ok(room_id) => room_id,
| Err(e) => { | Err(e) => {
return Err!( return Err!(
"Failed to parse room ID {room}. Please note that this requires a full room \ "Failed to parse room ID {room}. Please note that this requires a full \
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \ room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}" (`#roomalias:example.com`): {e}"
); );
}, },
@@ -77,8 +77,8 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
| Ok(room_alias) => room_alias, | Ok(room_alias) => room_alias,
| Err(e) => { | Err(e) => {
return Err!( return Err!(
"Failed to parse room ID {room}. Please note that this requires a full room \ "Failed to parse room ID {room}. Please note that this requires a full \
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \ room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}" (`#roomalias:example.com`): {e}"
); );
}, },
@@ -104,8 +104,8 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
} }
} else { } else {
return Err!( return Err!(
"Room specified is not a room ID or room alias. Please note that this requires a \ "Room specified is not a room ID or room alias. Please note that this requires \
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \ a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`)", (`#roomalias:example.com`)",
); );
}; };
@@ -154,12 +154,12 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
self.services.rooms.metadata.disable_room(&room_id, true); // disable federation self.services.rooms.metadata.disable_room(&room_id, true); // disable federation
self.write_str( self.write_str(
"Room banned, removed all our local users, and disabled incoming federation with room.", "Room banned, removed all our local users, and disabled incoming federation with \
room.",
) )
.await .await
} }
#[admin_command]
async fn ban_list_of_rooms(&self) -> Result { async fn ban_list_of_rooms(&self) -> Result {
if self.body.len() < 2 if self.body.len() < 2
|| !self.body[0].trim().starts_with("```") || !self.body[0].trim().starts_with("```")
@@ -183,7 +183,8 @@ async fn ban_list_of_rooms(&self) -> Result {
match <&RoomOrAliasId>::try_from(room) { match <&RoomOrAliasId>::try_from(room) {
| Ok(room_alias_or_id) => { | Ok(room_alias_or_id) => {
if let Ok(admin_room_id) = self.services.admin.get_admin_room().await { if let Ok(admin_room_id) = self.services.admin.get_admin_room().await {
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(admin_room_alias) if room.to_owned().eq(&admin_room_id)
|| room.to_owned().eq(admin_room_alias)
{ {
warn!("User specified admin room in bulk ban list, ignoring"); warn!("User specified admin room in bulk ban list, ignoring");
continue; continue;
@@ -219,8 +220,9 @@ async fn ban_list_of_rooms(&self) -> Result {
| Ok(room_id) => room_id, | Ok(room_id) => room_id,
| _ => { | _ => {
debug!( debug!(
"We don't have this room alias to a room ID locally, \ "We don't have this room alias to a room ID \
attempting to fetch room ID over federation" locally, attempting to fetch room ID over \
federation"
); );
match self match self
@@ -241,8 +243,8 @@ async fn ban_list_of_rooms(&self) -> Result {
}, },
| Err(e) => { | Err(e) => {
warn!( warn!(
"Failed to resolve room alias {room} to a room \ "Failed to resolve room alias {room} to a \
ID: {e}" room ID: {e}"
); );
continue; continue;
}, },
@@ -264,8 +266,8 @@ async fn ban_list_of_rooms(&self) -> Result {
}, },
| Err(e) => { | Err(e) => {
warn!( warn!(
"Error parsing room \"{room}\" during bulk room banning, ignoring error and \ "Error parsing room \"{room}\" during bulk room banning, ignoring error \
logging here: {e}" and logging here: {e}"
); );
continue; continue;
}, },
@@ -287,8 +289,8 @@ async fn ban_list_of_rooms(&self) -> Result {
while let Some(ref user_id) = users.next().await { while let Some(ref user_id) = users.next().await {
debug!( debug!(
"Attempting leave for user {user_id} in room {room_id} (ignoring all errors, \ "Attempting leave for user {user_id} in room {room_id} (ignoring all \
evicting admins too)", errors, evicting admins too)",
); );
if let Err(e) = leave_room(self.services, user_id, &room_id, None) if let Err(e) = leave_room(self.services, user_id, &room_id, None)
@@ -323,21 +325,20 @@ async fn ban_list_of_rooms(&self) -> Result {
} }
self.write_str(&format!( self.write_str(&format!(
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, and \ "Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, \
disabled incoming federation with the room." and disabled incoming federation with the room."
)) ))
.await .await
} }
#[admin_command]
async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result { async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
let room_id = if room.is_room_id() { let room_id = if room.is_room_id() {
let room_id = match RoomId::parse(&room) { let room_id = match RoomId::parse(&room) {
| Ok(room_id) => room_id, | Ok(room_id) => room_id,
| Err(e) => { | Err(e) => {
return Err!( return Err!(
"Failed to parse room ID {room}. Please note that this requires a full room \ "Failed to parse room ID {room}. Please note that this requires a full \
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \ room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}" (`#roomalias:example.com`): {e}"
); );
}, },
@@ -352,8 +353,8 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
| Ok(room_alias) => room_alias, | Ok(room_alias) => room_alias,
| Err(e) => { | Err(e) => {
return Err!( return Err!(
"Failed to parse room ID {room}. Please note that this requires a full room \ "Failed to parse room ID {room}. Please note that this requires a full \
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \ room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}" (`#roomalias:example.com`): {e}"
); );
}, },
@@ -374,8 +375,8 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
| Ok(room_id) => room_id, | Ok(room_id) => room_id,
| _ => { | _ => {
debug!( debug!(
"We don't have this room alias to a room ID locally, attempting to fetch \ "We don't have this room alias to a room ID locally, attempting to \
room ID over federation" fetch room ID over federation"
); );
match self.services.rooms.alias.resolve_alias(&room_alias).await { match self.services.rooms.alias.resolve_alias(&room_alias).await {
@@ -399,8 +400,8 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
room_id room_id
} else { } else {
return Err!( return Err!(
"Room specified is not a room ID or room alias. Please note that this requires a \ "Room specified is not a room ID or room alias. Please note that this requires \
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \ a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`)", (`#roomalias:example.com`)",
); );
}; };
@@ -410,7 +411,6 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
.await .await
} }
#[admin_command]
async fn list_banned_rooms(&self, no_details: bool) -> Result { async fn list_banned_rooms(&self, no_details: bool) -> Result {
let room_ids: Vec<OwnedRoomId> = self let room_ids: Vec<OwnedRoomId> = self
.services .services
@@ -452,3 +452,4 @@ async fn list_banned_rooms(&self, no_details: bool) -> Result {
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```")) self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
.await .await
} }
}
+6 -19
View File
@@ -7,9 +7,7 @@ use conduwuit::{
}; };
use futures::TryStreamExt; use futures::TryStreamExt;
use crate::admin_command; impl crate::Context<'_> {
#[admin_command]
pub(super) async fn uptime(&self) -> Result { pub(super) async fn uptime(&self) -> Result {
let elapsed = self let elapsed = self
.services .services
@@ -22,7 +20,6 @@ pub(super) async fn uptime(&self) -> Result {
self.write_str(&format!("{result}.")).await self.write_str(&format!("{result}.")).await
} }
#[admin_command]
pub(super) async fn show_config(&self) -> Result { pub(super) async fn show_config(&self) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -30,7 +27,6 @@ pub(super) async fn show_config(&self) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result { pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
// The path argument is only what's optionally passed via the admin command, // The path argument is only what's optionally passed via the admin command,
// so we need to merge it with the existing paths if any were given at startup. // so we need to merge it with the existing paths if any were given at startup.
@@ -59,12 +55,11 @@ pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn memory_usage(&self) -> Result { pub(super) async fn memory_usage(&self) -> Result {
let services_usage = self.services.memory_usage().await?; let services_usage = self.services.memory_usage().await?;
let database_usage = self.services.db.db.memory_usage()?; let database_usage = self.services.db.db.memory_usage()?;
let allocator_usage = let allocator_usage = conduwuit::alloc::memory_usage()
conduwuit::alloc::memory_usage().map_or(String::new(), |s| format!("\nAllocator:\n{s}")); .map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
self.write_str(&format!( self.write_str(&format!(
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}", "Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
@@ -72,14 +67,12 @@ pub(super) async fn memory_usage(&self) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn clear_caches(&self) -> Result { pub(super) async fn clear_caches(&self) -> Result {
self.services.clear_cache().await; self.services.clear_cache().await;
self.write_str("Done.").await self.write_str("Done.").await
} }
#[admin_command]
pub(super) async fn list_backups(&self) -> Result { pub(super) async fn list_backups(&self) -> Result {
self.services self.services
.db .db
@@ -90,7 +83,6 @@ pub(super) async fn list_backups(&self) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn backup_database(&self) -> Result { pub(super) async fn backup_database(&self) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -110,7 +102,6 @@ pub(super) async fn backup_database(&self) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result { pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
let message = message.join(" "); let message = message.join(" ");
self.services.admin.send_text(&message).await; self.services.admin.send_text(&message).await;
@@ -118,7 +109,6 @@ pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
self.write_str("Notice was sent to #admins").await self.write_str("Notice was sent to #admins").await
} }
#[admin_command]
pub(super) async fn reload_mods(&self) -> Result { pub(super) async fn reload_mods(&self) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -127,15 +117,14 @@ pub(super) async fn reload_mods(&self) -> Result {
self.write_str("Reloading server...").await self.write_str("Reloading server...").await
} }
#[admin_command]
#[cfg(unix)] #[cfg(unix)]
pub(super) async fn restart(&self, force: bool) -> Result { pub(super) async fn restart(&self, force: bool) -> Result {
use conduwuit::utils::sys::current_exe_deleted; use conduwuit::utils::sys::current_exe_deleted;
if !force && current_exe_deleted() { if !force && current_exe_deleted() {
return Err!( return Err!(
"The server cannot be restarted because the executable changed. If this is expected \ "The server cannot be restarted because the executable changed. If this is \
use --force to override." expected use --force to override."
); );
} }
@@ -144,7 +133,6 @@ pub(super) async fn restart(&self, force: bool) -> Result {
self.write_str("Restarting server...").await self.write_str("Restarting server...").await
} }
#[admin_command]
pub(super) async fn shutdown(&self) -> Result { pub(super) async fn shutdown(&self) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -154,7 +142,6 @@ pub(super) async fn shutdown(&self) -> Result {
self.write_str("Shutting down server...").await self.write_str("Shutting down server...").await
} }
#[admin_command]
pub(super) async fn list_features(&self) -> Result { pub(super) async fn list_features(&self) -> Result {
let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
.lock() .lock()
@@ -186,7 +173,6 @@ pub(super) async fn list_features(&self) -> Result {
self.write_str(&features).await self.write_str(&features).await
} }
#[admin_command]
pub(super) async fn build_info(&self) -> Result { pub(super) async fn build_info(&self) -> Result {
use conduwuit::build_metadata::built; use conduwuit::build_metadata::built;
@@ -247,3 +233,4 @@ pub(super) async fn build_info(&self) -> Result {
self.write_str(&info).await self.write_str(&info).await
} }
}
+29 -6
View File
@@ -1,9 +1,8 @@
use conduwuit::{Err, Result, utils}; use conduwuit::{Err, Result, utils};
use conduwuit_macros::admin_command;
use futures::StreamExt; use futures::StreamExt;
use service::registration_tokens::TokenExpires; use service::registration_tokens::TokenExpires;
#[admin_command] impl crate::Context<'_> {
pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result { pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
let expires = { let expires = {
if expires.immortal { if expires.immortal {
@@ -15,7 +14,9 @@ pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
} else if let Some(max_age) = expires } else if let Some(max_age) = expires
.max_age .max_age
.as_deref() .as_deref()
.map(|max_age| utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?)) .map(|max_age| {
utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?)
})
.transpose()? .transpose()?
{ {
Some(TokenExpires::AfterTime(max_age)) Some(TokenExpires::AfterTime(max_age))
@@ -37,10 +38,32 @@ pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
"Never expires".to_owned() "Never expires".to_owned()
} }
)) ))
.await .await?;
if self
.services
.config
.oauth
.compatibility_mode
.oauth_available()
{
self.write_str(&format!(
"\nInvite link using this token: {}",
self.services
.config
.get_client_domain()
.join(&format!(
"{}/account/register/?flow=trusted&token={token}",
conduwuit::ROUTE_PREFIX
))
.unwrap()
))
.await?;
}
Ok(())
} }
#[admin_command]
pub(super) async fn revoke_token(&self, token: String) -> Result { pub(super) async fn revoke_token(&self, token: String) -> Result {
let Some(token) = self let Some(token) = self
.services .services
@@ -56,7 +79,6 @@ pub(super) async fn revoke_token(&self, token: String) -> Result {
self.write_str("Token revoked successfully.").await self.write_str("Token revoked successfully.").await
} }
#[admin_command]
pub(super) async fn list_tokens(&self) -> Result { pub(super) async fn list_tokens(&self) -> Result {
let tokens: Vec<_> = self let tokens: Vec<_> = self
.services .services
@@ -74,3 +96,4 @@ pub(super) async fn list_tokens(&self) -> Result {
Ok(()) Ok(())
} }
}
+58 -201
View File
@@ -1,13 +1,10 @@
use std::{ use std::collections::{BTreeMap, HashSet};
collections::{BTreeMap, HashSet},
fmt::Write as _,
};
use api::client::{ use api::client::{
full_user_deactivate, leave_room, recreate_push_rules_and_return, remote_leave_room, full_user_deactivate, leave_room, recreate_push_rules_and_return, remote_leave_room,
}; };
use conduwuit::{ use conduwuit::{
Err, Result, debug_warn, error, info, Err, Result, debug_warn, info,
matrix::{Event, pdu::PartialPdu}, matrix::{Event, pdu::PartialPdu},
utils::{self, ReadyExt}, utils::{self, ReadyExt},
warn, warn,
@@ -26,14 +23,14 @@ use ruma::{
use service::users::HashedPassword; use service::users::HashedPassword;
use crate::{ use crate::{
admin_command, get_room_info, get_room_info,
utils::{parse_active_local_user_id, parse_local_user_id}, utils::{parse_active_local_user_id, parse_local_user_id},
}; };
const AUTO_GEN_PASSWORD_LENGTH: usize = 25; const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
const BULK_JOIN_REASON: &str = "Bulk force joining this room as initiated by the server admin."; const BULK_JOIN_REASON: &str = "Bulk force joining this room as initiated by the server admin.";
#[admin_command] impl crate::Context<'_> {
pub(super) async fn list_users(&self) -> Result { pub(super) async fn list_users(&self) -> Result {
let users: Vec<_> = self let users: Vec<_> = self
.services .services
@@ -50,136 +47,25 @@ pub(super) async fn list_users(&self) -> Result {
self.write_str(&plain_msg).await self.write_str(&plain_msg).await
} }
#[admin_command]
pub(super) async fn create_user(&self, username: String, password: Option<String>) -> Result { pub(super) async fn create_user(&self, username: String, password: Option<String>) -> Result {
// Validate user id let user_id = self
let user_id = parse_local_user_id(self.services, &username)?; .services
if let Err(e) = user_id.validate_strict() {
if self.services.config.emergency_password.is_none() {
return Err!("Username {user_id} contains disallowed characters or spaces: {e}");
}
}
if self.services.users.exists(&user_id).await {
return Err!("User {user_id} already exists");
}
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
// Create user
self.services
.users .users
.create(&user_id, Some(HashedPassword::new(&password)?)) .determine_registration_user_id(Some(username), None, None)
.await?; .await?;
// Default to pretty displayname let password = HashedPassword::new(
let mut displayname = user_id.localpart().to_owned(); &password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH)),
)?;
// If `new_user_displayname_suffix` is set, registration will push whatever
// content is set to the user's display name with a space before it
if !self
.services
.server
.config
.new_user_displayname_suffix
.is_empty()
{
write!(displayname, " {}", self.services.server.config.new_user_displayname_suffix)?;
}
self.services self.services
.users .users
.set_displayname(&user_id, Some(displayname)); .create_local_account(&user_id, password, None)
// Initial account data
self.services
.account_data
.update(
None,
&user_id,
ruma::events::GlobalAccountDataEventType::PushRules
.to_string()
.into(),
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent::new(
ruma::events::push_rules::PushRulesEventContent::new(
ruma::push::Ruleset::server_default(&user_id),
),
))
.unwrap(),
)
.await?;
if !self.services.server.config.auto_join_rooms.is_empty() {
for room in &self.services.server.config.auto_join_rooms {
let Ok(room_id) = self.services.rooms.alias.resolve(room).await else {
error!(
%user_id,
"Failed to resolve room alias to room ID when attempting to auto join {room}, skipping"
);
continue;
};
if !self
.services
.rooms
.state_cache
.server_in_room(self.services.globals.server_name(), &room_id)
.await
{
warn!(
"Skipping room {room} to automatically join as we have never joined before."
);
continue;
}
if let Some(room_server_name) = room.server_name() {
match self
.services
.rooms
.membership
.join_room(
&user_id,
&room_id,
Some("Automatically joining this room upon registration".to_owned()),
&[
self.services.globals.server_name().to_owned(),
room_server_name.to_owned(),
],
)
.await
{
| Ok(_response) => {
info!("Automatically joined room {room} for user {user_id}");
},
| Err(e) => {
// don't return this error so we don't fail registrations
error!(
"Failed to automatically join room {room} for user {user_id}: {e}"
);
self.services
.admin
.send_text(&format!(
"Failed to automatically join room {room} for user {user_id}: \
{e}"
))
.await; .await;
},
} self.write_str(&format!("Created user {user_id}")).await
}
}
} }
// we dont add a device since we're not the user, just the creator
// Make the first user to register an administrator and disable first-run mode.
self.services.firstrun.empower_first_user(&user_id).await?;
self.write_str(&format!("Created user with user_id: {user_id} and password: `{password}`"))
.await
}
#[admin_command]
pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result { pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result {
// Validate user id // Validate user id
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -215,7 +101,6 @@ pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) ->
.await .await
} }
#[admin_command]
pub(super) async fn suspend(&self, user_id: String) -> Result { pub(super) async fn suspend(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -240,7 +125,6 @@ pub(super) async fn suspend(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn unsuspend(&self, user_id: String) -> Result { pub(super) async fn unsuspend(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -258,7 +142,6 @@ pub(super) async fn unsuspend(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn reset_password( pub(super) async fn reset_password(
&self, &self,
logout: bool, logout: bool,
@@ -269,12 +152,13 @@ pub(super) async fn reset_password(
if user_id == self.services.globals.server_user { if user_id == self.services.globals.server_user {
return Err!( return Err!(
"Not allowed to set the password for the server account. Please use the emergency \ "Not allowed to set the password for the server account. Please use the \
password config option.", emergency password config option.",
); );
} }
let new_password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH)); let new_password =
password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
self.services self.services
.users .users
@@ -302,32 +186,6 @@ pub(super) async fn reset_password(
Ok(()) Ok(())
} }
#[admin_command]
pub(super) async fn issue_password_reset_link(&self, username: String) -> Result {
use conduwuit_service::password_reset::{PASSWORD_RESET_PATH, RESET_TOKEN_QUERY_PARAM};
self.bail_restricted()?;
let mut reset_url = self
.services
.config
.get_client_domain()
.join(PASSWORD_RESET_PATH)
.unwrap();
let user_id = parse_local_user_id(self.services, &username)?;
let token = self.services.password_reset.issue_token(user_id).await?;
reset_url
.query_pairs_mut()
.append_pair(RESET_TOKEN_QUERY_PARAM, &token.token);
self.write_str(&format!("Password reset link issued for {username}: {reset_url}"))
.await?;
Ok(())
}
#[admin_command]
pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) -> Result { pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) -> Result {
if self.body.len() < 2 if self.body.len() < 2
|| !self.body[0].trim().starts_with("```") || !self.body[0].trim().starts_with("```")
@@ -350,7 +208,9 @@ pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) ->
| Err(e) => { | Err(e) => {
self.services self.services
.admin .admin
.send_text(&format!("{username} is not a valid username, skipping over: {e}")) .send_text(&format!(
"{username} is not a valid username, skipping over: {e}"
))
.await; .await;
continue; continue;
@@ -398,7 +258,9 @@ pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) ->
| Ok(()) => { | Ok(()) => {
deactivation_count = deactivation_count.saturating_add(1); deactivation_count = deactivation_count.saturating_add(1);
if !no_leave_rooms { if !no_leave_rooms {
info!("Forcing user {user_id} to leave all rooms apart of deactivate-all"); info!(
"Forcing user {user_id} to leave all rooms apart of deactivate-all"
);
let all_joined_rooms: Vec<OwnedRoomId> = self let all_joined_rooms: Vec<OwnedRoomId> = self
.services .services
.rooms .rooms
@@ -429,7 +291,6 @@ pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) ->
.await .await
} }
#[admin_command]
pub(super) async fn list_invited_rooms(&self, user_id: String) -> Result { pub(super) async fn list_invited_rooms(&self, user_id: String) -> Result {
// Validate user id // Validate user id
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -468,11 +329,13 @@ pub(super) async fn list_invited_rooms(&self, user_id: String) -> Result {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n"); .join("\n");
self.write_str(&format!("Rooms {user_id} is Invited to ({}):\n```\n{body}\n```", rooms.len())) self.write_str(&format!(
"Rooms {user_id} is Invited to ({}):\n```\n{body}\n```",
rooms.len()
))
.await .await
} }
#[admin_command]
pub(super) async fn reject_all_invites(&self, user_id: String) -> Result { pub(super) async fn reject_all_invites(&self, user_id: String) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -505,7 +368,6 @@ pub(super) async fn reject_all_invites(&self, user_id: String) -> Result {
self.write_str("Successfully rejected all invites.").await self.write_str("Successfully rejected all invites.").await
} }
#[admin_command]
pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result { pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
// Validate user id // Validate user id
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -536,7 +398,6 @@ pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn force_join_list_of_local_users( pub(super) async fn force_join_list_of_local_users(
&self, &self,
room_id: OwnedRoomOrAliasId, room_id: OwnedRoomOrAliasId,
@@ -551,8 +412,8 @@ pub(super) async fn force_join_list_of_local_users(
if !yes_i_want_to_do_this { if !yes_i_want_to_do_this {
return Err!( return Err!(
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to force \ "You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
bulk join all specified local users.", force bulk join all specified local users.",
); );
} }
@@ -618,7 +479,9 @@ pub(super) async fn force_join_list_of_local_users(
| Err(e) => { | Err(e) => {
self.services self.services
.admin .admin
.send_text(&format!("{username} is not a valid username, skipping over: {e}")) .send_text(&format!(
"{username} is not a valid username, skipping over: {e}"
))
.await; .await;
continue; continue;
@@ -641,7 +504,9 @@ pub(super) async fn force_join_list_of_local_users(
successful_joins = successful_joins.saturating_add(1); successful_joins = successful_joins.saturating_add(1);
}, },
| Err(e) => { | Err(e) => {
debug_warn!("Failed force joining {user_id} to {room_id} during bulk join: {e}"); debug_warn!(
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
);
failed_joins = failed_joins.saturating_add(1); failed_joins = failed_joins.saturating_add(1);
}, },
} }
@@ -654,7 +519,6 @@ pub(super) async fn force_join_list_of_local_users(
.await .await
} }
#[admin_command]
pub(super) async fn force_join_all_local_users( pub(super) async fn force_join_all_local_users(
&self, &self,
room_id: OwnedRoomOrAliasId, room_id: OwnedRoomOrAliasId,
@@ -662,8 +526,8 @@ pub(super) async fn force_join_all_local_users(
) -> Result { ) -> Result {
if !yes_i_want_to_do_this { if !yes_i_want_to_do_this {
return Err!( return Err!(
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to force \ "You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
bulk join all local users.", force bulk join all local users.",
); );
} }
@@ -722,7 +586,9 @@ pub(super) async fn force_join_all_local_users(
successful_joins = successful_joins.saturating_add(1); successful_joins = successful_joins.saturating_add(1);
}, },
| Err(e) => { | Err(e) => {
debug_warn!("Failed force joining {user_id} to {room_id} during bulk join: {e}"); debug_warn!(
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
);
failed_joins = failed_joins.saturating_add(1); failed_joins = failed_joins.saturating_add(1);
}, },
} }
@@ -735,7 +601,6 @@ pub(super) async fn force_join_all_local_users(
.await .await
} }
#[admin_command]
pub(super) async fn force_join_room( pub(super) async fn force_join_room(
&self, &self,
user_id: String, user_id: String,
@@ -768,7 +633,6 @@ pub(super) async fn force_join_room(
.await .await
} }
#[admin_command]
pub(super) async fn force_leave_room( pub(super) async fn force_leave_room(
&self, &self,
user_id: String, user_id: String,
@@ -800,8 +664,11 @@ pub(super) async fn force_leave_room(
.await .await
} }
#[admin_command] pub(super) async fn force_demote(
pub(super) async fn force_demote(&self, user_id: String, room_id: OwnedRoomOrAliasId) -> Result { &self,
user_id: String,
room_id: OwnedRoomOrAliasId,
) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
let room_id = self.services.rooms.alias.resolve(&room_id).await?; let room_id = self.services.rooms.alias.resolve(&room_id).await?;
@@ -851,7 +718,6 @@ pub(super) async fn force_demote(&self, user_id: String, room_id: OwnedRoomOrAli
.await .await
} }
#[admin_command]
pub(super) async fn make_user_admin(&self, user_id: String) -> Result { pub(super) async fn make_user_admin(&self, user_id: String) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
assert!( assert!(
@@ -869,7 +735,6 @@ pub(super) async fn make_user_admin(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn put_room_tag( pub(super) async fn put_room_tag(
&self, &self,
user_id: String, user_id: String,
@@ -901,12 +766,12 @@ pub(super) async fn put_room_tag(
.await?; .await?;
self.write_str(&format!( self.write_str(&format!(
"Successfully updated room account data for {user_id} and room {room_id} with tag {tag}" "Successfully updated room account data for {user_id} and room {room_id} with tag \
{tag}"
)) ))
.await .await
} }
#[admin_command]
pub(super) async fn delete_room_tag( pub(super) async fn delete_room_tag(
&self, &self,
user_id: String, user_id: String,
@@ -935,13 +800,12 @@ pub(super) async fn delete_room_tag(
.await?; .await?;
self.write_str(&format!( self.write_str(&format!(
"Successfully updated room account data for {user_id} and room {room_id}, deleting room \ "Successfully updated room account data for {user_id} and room {room_id}, deleting \
tag {tag}" room tag {tag}"
)) ))
.await .await
} }
#[admin_command]
pub(super) async fn get_room_tags(&self, user_id: String, room_id: OwnedRoomId) -> Result { pub(super) async fn get_room_tags(&self, user_id: String, room_id: OwnedRoomId) -> Result {
let user_id = parse_active_local_user_id(self.services, &user_id).await?; let user_id = parse_active_local_user_id(self.services, &user_id).await?;
@@ -956,7 +820,6 @@ pub(super) async fn get_room_tags(&self, user_id: String, room_id: OwnedRoomId)
.await .await
} }
#[admin_command]
pub(super) async fn redact_event(&self, event_id: OwnedEventId) -> Result { pub(super) async fn redact_event(&self, event_id: OwnedEventId) -> Result {
let Ok(event) = self let Ok(event) = self
.services .services
@@ -1014,7 +877,6 @@ pub(super) async fn redact_event(&self, event_id: OwnedEventId) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn force_leave_remote_room( pub(super) async fn force_leave_remote_room(
&self, &self,
user_id: String, user_id: String,
@@ -1055,7 +917,6 @@ pub(super) async fn force_leave_remote_room(
.await .await
} }
#[admin_command]
pub(super) async fn lock(&self, user_id: String) -> Result { pub(super) async fn lock(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -1082,7 +943,6 @@ pub(super) async fn lock(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn unlock(&self, user_id: String) -> Result { pub(super) async fn unlock(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -1096,7 +956,6 @@ pub(super) async fn unlock(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn logout(&self, user_id: String) -> Result { pub(super) async fn logout(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -1128,7 +987,6 @@ pub(super) async fn logout(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn disable_login(&self, user_id: String) -> Result { pub(super) async fn disable_login(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -1154,7 +1012,6 @@ pub(super) async fn disable_login(&self, user_id: String) -> Result {
.await .await
} }
#[admin_command]
pub(super) async fn enable_login(&self, user_id: String) -> Result { pub(super) async fn enable_login(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -1170,7 +1027,6 @@ pub(super) async fn enable_login(&self, user_id: String) -> Result {
self.write_str(&format!("{user_id} can now log in.")).await self.write_str(&format!("{user_id} can now log in.")).await
} }
#[admin_command]
pub(super) async fn get_email(&self, user_id: String) -> Result { pub(super) async fn get_email(&self, user_id: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
@@ -1190,7 +1046,6 @@ pub(super) async fn get_email(&self, user_id: String) -> Result {
} }
} }
#[admin_command]
pub(super) async fn get_user_by_email(&self, email: String) -> Result { pub(super) async fn get_user_by_email(&self, email: String) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -1200,8 +1055,10 @@ pub(super) async fn get_user_by_email(&self, email: String) -> Result {
match self.services.threepid.get_localpart_for_email(&email).await { match self.services.threepid.get_localpart_for_email(&email).await {
| Some(localpart) => { | Some(localpart) => {
let user_id = let user_id = UserId::parse(format!(
UserId::parse(format!("@{localpart}:{}", self.services.globals.server_name())) "@{localpart}:{}",
self.services.globals.server_name()
))
.unwrap(); .unwrap();
self.write_str(&format!("{email} belongs to {user_id}.")) self.write_str(&format!("{email} belongs to {user_id}."))
@@ -1213,7 +1070,6 @@ pub(super) async fn get_user_by_email(&self, email: String) -> Result {
} }
} }
#[admin_command]
pub(super) async fn change_email(&self, user_id: String, email: Option<String>) -> Result { pub(super) async fn change_email(&self, user_id: String, email: Option<String>) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
@@ -1246,8 +1102,8 @@ pub(super) async fn change_email(&self, user_id: String, email: Option<String>)
if let Some(current_email) = current_email { if let Some(current_email) = current_email {
self.write_str(&format!( self.write_str(&format!(
"The associated email of {user_id} has been changed from {current_email} to \ "The associated email of {user_id} has been changed from \
{new_email}." {current_email} to {new_email}."
)) ))
.await .await
} else { } else {
@@ -1264,14 +1120,14 @@ pub(super) async fn change_email(&self, user_id: String, email: Option<String>)
.await; .await;
self.write_str(&format!( self.write_str(&format!(
"The associated email of {user_id} has been removed (it was {current_email})." "The associated email of {user_id} has been removed (it was \
{current_email})."
)) ))
.await .await
}, },
} }
} }
#[admin_command]
pub(super) async fn reset_push_rules(&self, user_id: String) -> Result { pub(super) async fn reset_push_rules(&self, user_id: String) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
if !self.services.users.is_active(&user_id).await { if !self.services.users.is_active(&user_id).await {
@@ -1281,3 +1137,4 @@ pub(super) async fn reset_push_rules(&self, user_id: String) -> Result {
self.write_str("Reset user's push rules to the server default.") self.write_str("Reset user's push rules to the server default.")
.await .await
} }
}
-6
View File
@@ -29,12 +29,6 @@ pub enum UserCommand {
password: Option<String>, password: Option<String>,
}, },
/// Issue a self-service password reset link for a user.
IssuePasswordResetLink {
/// Username of the user who may use the link
username: String,
},
/// Get a user's associated email address. /// Get a user's associated email address.
GetEmail { GetEmail {
user_id: String, user_id: String,
+28 -45
View File
@@ -24,7 +24,7 @@ use ruma::{
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
}, },
}; };
use service::{mailer::messages, uiaa::Identity, users::HashedPassword}; use service::{mailer::messages, uiaa::UiaaInitiator, users::HashedPassword};
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH}; use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{Ruma, router::ClientIdentity}; use crate::{Ruma, router::ClientIdentity};
@@ -49,39 +49,16 @@ pub(crate) async fn get_register_available_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_username_availability::v3::Request>, body: Ruma<get_username_availability::v3::Request>,
) -> Result<get_username_availability::v3::Response> { ) -> Result<get_username_availability::v3::Response> {
// Validate user id let _ = services
let user_id = .users
match UserId::parse_with_server_name(&body.username, services.globals.server_name()) { .determine_registration_user_id(
| Ok(user_id) => { Some(body.username.clone()),
if let Err(e) = user_id.validate_strict() { None,
return Err!(Request(InvalidUsername(debug_warn!( body.identity
"Username {} contains disallowed characters or spaces: {e}", .as_ref()
body.username .and_then(ClientIdentity::appservice_info),
)))); )
} .await?;
user_id
},
| Err(e) => {
return Err!(Request(InvalidUsername(debug_warn!(
"Username {} is not valid: {e}",
body.username
))));
},
};
// Check if username is creative enough
if services.users.exists(&user_id).await {
return Err!(Request(UserInUse("User ID is not available.")));
}
if let Some(ClientIdentity::Appservice { appservice_info, .. }) = &body.identity
&& !appservice_info.is_user_match(&user_id)
{
return Err!(Request(Exclusive("Username is not in an appservice namespace.")));
} else if services.appservice.is_exclusive_user_id(&user_id).await {
return Err!(Request(Exclusive("Username is reserved by an appservice.")));
}
Ok(get_username_availability::v3::Response::new(true)) Ok(get_username_availability::v3::Response::new(true))
} }
@@ -109,12 +86,7 @@ pub(crate) async fn change_password_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<change_password::v3::Request>, body: Ruma<change_password::v3::Request>,
) -> Result<change_password::v3::Response> { ) -> Result<change_password::v3::Response> {
let identity = if let Some(user_id) = body let identity = if let Some(identity) = body.identity.as_ref() {
.identity
.as_ref()
.map(ClientIdentity::expect_sender_user)
.transpose()?
{
// A signed-in user is trying to change their password, prompt them for their // A signed-in user is trying to change their password, prompt them for their
// existing one // existing one
@@ -124,7 +96,10 @@ pub(crate) async fn change_password_route(
&body.auth, &body.auth,
vec![AuthFlow::new(vec![AuthType::Password])], vec![AuthFlow::new(vec![AuthType::Password])],
Box::default(), Box::default(),
Some(Identity::from_user_id(user_id)), Some(UiaaInitiator::new(
identity.expect_sender_user()?,
identity.sender_device(),
)),
) )
.await? .await?
} else { } else {
@@ -280,16 +255,24 @@ pub(crate) async fn deactivate_route(
) -> Result<deactivate::v3::Response> { ) -> Result<deactivate::v3::Response> {
// Authentication for this endpoint is technically optional, // Authentication for this endpoint is technically optional,
// but we require the user to be logged in // but we require the user to be logged in
let sender_user = body let identity = body
.identity .identity
.as_ref() .as_ref()
.map(ClientIdentity::expect_sender_user) .ok_or_else(|| err!(Request(MissingToken("Missing access token."))))?;
.ok_or_else(|| err!(Request(MissingToken("Missing access token."))))??;
let sender_user = identity.expect_sender_user()?;
if !services.config.allow_deactivation {
return Err!(Request(Forbidden(
"You may not deactivate your own account. Contact your server's administrator for \
assistance."
)));
}
// Prompt the user to confirm with their password using UIAA // Prompt the user to confirm with their password using UIAA
let _ = services let _ = services
.uiaa .uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user))) .authenticate_password(&body.auth, sender_user, identity.sender_device(), None)
.await?; .await?;
// Remove profile pictures and display name // Remove profile pictures and display name
+50 -286
View File
@@ -1,17 +1,15 @@
use std::{collections::HashMap, fmt::Write}; use std::collections::HashMap;
use axum::extract::State; use axum::extract::State;
use axum_client_ip::ClientIp; use axum_client_ip::ClientIp;
use conduwuit::{ use conduwuit::{
Err, Result, debug_info, error, info, Err, Result, debug_info, info,
utils::{self}, utils::{self},
warn,
}; };
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::{FutureExt, StreamExt}; use futures::StreamExt;
use lettre::{Address, message::Mailbox}; use lettre::{Address, message::Mailbox};
use ruma::{ use ruma::{
OwnedUserId, UserId,
api::client::{ api::client::{
account::{ account::{
register::{self, LoginType, RegistrationKind}, register::{self, LoginType, RegistrationKind},
@@ -20,11 +18,6 @@ use ruma::{
uiaa::{AuthFlow, AuthType}, uiaa::{AuthFlow, AuthType},
}, },
assign, assign,
events::{
GlobalAccountDataEventType, push_rules::PushRulesEvent,
room::message::RoomMessageEventContent,
},
push,
}; };
use serde_json::value::RawValue; use serde_json::value::RawValue;
use service::{mailer::messages, users::HashedPassword}; use service::{mailer::messages, users::HashedPassword};
@@ -32,8 +25,6 @@ use service::{mailer::messages, users::HashedPassword};
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH}; use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::Ruma; use crate::Ruma;
const RANDOM_USER_ID_LENGTH: usize = 10;
/// # `POST /_matrix/client/v3/register` /// # `POST /_matrix/client/v3/register`
/// ///
/// Register an account on this homeserver. /// Register an account on this homeserver.
@@ -52,8 +43,6 @@ pub(crate) async fn register_route(
return Err!(Request(GuestAccessForbidden("Guests may not register on this server."))); return Err!(Request(GuestAccessForbidden("Guests may not register on this server.")));
} }
let emergency_mode_enabled = services.config.emergency_password.is_some();
// Allow registration if it's enabled in the config file or if this is the first // Allow registration if it's enabled in the config file or if this is the first
// run (so the first user account can be created) // run (so the first user account can be created)
let allow_registration = let allow_registration =
@@ -71,99 +60,59 @@ pub(crate) async fn register_route(
))); )));
} }
let identity = if body.identity.is_some() { let user_id = if body.body.login_type == Some(LoginType::ApplicationService) {
// Appservices can skip auth let Some(appservice_info) = &body.identity else {
None return Err!(Request(Forbidden(
"Only appservices can use the appservice login type."
)));
};
let user_id = services
.users
.determine_registration_user_id(body.username.clone(), None, Some(appservice_info))
.await?;
services.users.create(&user_id, None)?;
user_id
} else { } else {
// Perform UIAA to determine the user's identity // Perform UIAA to determine the user's identity
let (flows, params) = create_registration_uiaa_session(&services).await?; let (flows, params) = create_registration_uiaa_session(&services).await?;
Some( let identity = services
services
.uiaa .uiaa
.authenticate(&body.auth, flows, params, None) .authenticate(&body.auth, flows, params, None)
.await?,
)
};
// If the user didn't supply a username but did supply an email, use
// the email's user as their initial localpart to avoid falling back to
// a randomly generated localpart
let supplied_username = body.username.clone().or_else(|| {
if let Some(identity) = &identity
&& let Some(email) = &identity.email
{
Some(email.user().to_owned())
} else {
None
}
});
let user_id =
determine_registration_user_id(&services, supplied_username, emergency_mode_enabled)
.await?; .await?;
if body.body.login_type == Some(LoginType::ApplicationService) { let password = if let Some(password) = &body.password {
// For appservice logins, make sure that the user ID is in the appservice's HashedPassword::new(password)?
// namespace
match body.identity {
| Some(ref info) =>
if !info.is_user_match(&user_id) && !emergency_mode_enabled {
return Err!(Request(Exclusive(
"Username is not in an appservice namespace."
)));
},
| _ => {
return Err!(Request(MissingToken("Missing appservice token.")));
},
}
} else if services.appservice.is_exclusive_user_id(&user_id).await && !emergency_mode_enabled
{
// For non-appservice logins, ban user IDs which are in an appservice's
// namespace (unless emergency mode is enabled)
return Err!(Request(Exclusive("Username is reserved by an appservice.")));
}
let password = if body.identity.is_some() {
None
} else if let Some(password) = body.password.as_deref() {
Some(HashedPassword::new(password)?)
} else { } else {
return Err!(Request(InvalidParam("A password must be provided"))); return Err!(Request(InvalidParam("A password must be provided.")));
}; };
// Create user let user_id = services
services.users.create(&user_id, password).await?; .users
.determine_registration_user_id(body.username.clone(), identity.email.as_ref(), None)
// Set an initial display name .await?;
let mut displayname = user_id.localpart().to_owned();
// Apply the new user displayname suffix, if it's set
if !services.globals.new_user_displayname_suffix().is_empty() && body.identity.is_none() {
write!(displayname, " {}", services.server.config.new_user_displayname_suffix)?;
}
services services
.users .users
.set_displayname(&user_id, Some(displayname.clone())); .create_local_account(&user_id, password, identity.email)
.await;
// Initial account data user_id
services };
.account_data
.update( let (token, device) = if !body.inhibit_login {
None, // If UIAA is disabled, we can't create a device. In that case only appservices
&user_id, // can reach this point in the first place, so we return an error for them.
GlobalAccountDataEventType::PushRules.to_string().into(), if !services.config.oauth.compatibility_mode.uiaa_available() {
&serde_json::to_value(PushRulesEvent::new( return Err!(Request(AppserviceLoginUnsupported(
push::Ruleset::server_default(&user_id).into(), "User-interactive appservice registration is not available on this server."
)) )));
.expect("should be able to serialize push rules"), }
)
.await?;
// Generate new device id if the user didn't specify one // Generate new device id if the user didn't specify one
let (token, device) = if !body.inhibit_login {
let device_id = body let device_id = body
.device_id .device_id
.clone() .clone()
@@ -179,6 +128,7 @@ pub(crate) async fn register_route(
&user_id, &user_id,
&device_id, &device_id,
&new_token, &new_token,
None,
body.initial_device_display_name.clone(), body.initial_device_display_name.clone(),
Some(client.to_string()), Some(client.to_string()),
) )
@@ -189,118 +139,7 @@ pub(crate) async fn register_route(
(None, None) (None, None)
}; };
debug_info!(%user_id, ?device, "User account was created"); debug_info!(%user_id, ?device, "New account created via legacy registration");
// If the user registered with an email, associate it with their account.
if let Some(identity) = identity
&& let Some(email) = identity.email
{
// This may fail if the email is already in use, but we already check for that
// in `/requestToken`, so ignoring the error is acceptable here in the rare case
// that an email is sniped by another user between the `/requestToken` request
// and the `/register` request.
let _ = services
.threepid
.associate_localpart_email(user_id.localpart(), &email)
.await;
}
let device_display_name = body.initial_device_display_name.as_deref().unwrap_or("");
if body.identity.is_none() {
if !device_display_name.is_empty() {
let notice = format!(
"New user \"{user_id}\" registered on this server from IP {client} and device \
display name \"{device_display_name}\""
);
info!("{notice}");
if services.server.config.admin_room_notices {
services.admin.notice(&notice).await;
}
} else {
let notice = format!("New user \"{user_id}\" registered on this server.");
info!("{notice}");
if services.server.config.admin_room_notices {
services.admin.notice(&notice).await;
}
}
}
// Make the first user to register an administrator and disable first-run mode.
let was_first_user = services.firstrun.empower_first_user(&user_id).await?;
// If the registering user was not the first and we're suspending users on
// register, suspend them.
if !was_first_user && services.config.suspend_on_register {
// Note that we can still do auto joins for suspended users
services
.users
.suspend_account(&user_id, &services.globals.server_user)
.await;
// And send an @room notice to the admin room, to prompt admins to review the
// new user and ideally unsuspend them if deemed appropriate.
if services.server.config.admin_room_notices {
services
.admin
.send_loud_message(RoomMessageEventContent::text_plain(format!(
"User {user_id} has been suspended as they are not the first user on this \
server. Please review and unsuspend them if appropriate."
)))
.await
.ok();
}
}
if body.identity.is_none() && !services.server.config.auto_join_rooms.is_empty() {
for room in &services.server.config.auto_join_rooms {
let Ok(room_id) = services.rooms.alias.resolve(room).await else {
error!(
"Failed to resolve room alias to room ID when attempting to auto join \
{room}, skipping"
);
continue;
};
if !services
.rooms
.state_cache
.server_in_room(services.globals.server_name(), &room_id)
.await
{
warn!(
"Skipping room {room} to automatically join as we have never joined before."
);
continue;
}
if let Some(room_server_name) = room.server_name() {
match services
.rooms
.membership
.join_room(
&user_id,
&room_id,
Some("Automatically joining this room upon registration".to_owned()),
&[services.globals.server_name().to_owned(), room_server_name.to_owned()],
)
.boxed()
.await
{
| Err(e) => {
// don't return this error so we don't fail registrations
error!(
"Failed to automatically join room {room} for user {user_id}: {e}"
);
},
| _ => {
info!("Automatically joined room {room} for user {user_id}");
},
}
}
}
}
Ok(assign!(register::v3::Response::new(user_id), { Ok(assign!(register::v3::Response::new(user_id), {
access_token: token, access_token: token,
@@ -372,21 +211,21 @@ async fn create_registration_uiaa_session(
// Require all users to agree to the terms and conditions, if configured // Require all users to agree to the terms and conditions, if configured
let terms = &services.config.registration_terms; let terms = &services.config.registration_terms;
if !terms.is_empty() { if !terms.documents.is_empty() {
let mut terms = let mut terms_map = HashMap::new();
serde_json::to_value(terms.clone()).expect("failed to serialize terms");
// Insert a dummy `version` field for (id, document) in &terms.documents {
for (_, documents) in terms.as_object_mut().unwrap() { terms_map.insert(id.to_owned(), serde_json::json!({
let documents = documents.as_object_mut().unwrap(); terms.language.clone(): serde_json::to_value(document).expect("should be able to serialize document")
}));
documents.insert("version".to_owned(), "latest".into());
} }
terms_map.insert("version".to_owned(), "latest".into());
params.insert( params.insert(
AuthType::Terms.as_str().to_owned(), AuthType::Terms.as_str().to_owned(),
serde_json::json!({ serde_json::json!({
"policies": terms, "policies": terms_map,
}), }),
); );
@@ -419,81 +258,6 @@ async fn create_registration_uiaa_session(
Ok((flows, params)) Ok((flows, params))
} }
async fn determine_registration_user_id(
services: &Services,
supplied_username: Option<String>,
emergency_mode_enabled: bool,
) -> Result<OwnedUserId> {
if let Some(supplied_username) = supplied_username {
// The user gets to pick their username. Do some validation to make sure it's
// acceptable.
// Don't allow registration with forbidden usernames.
if services
.globals
.forbidden_usernames()
.is_match(&supplied_username)
&& !emergency_mode_enabled
{
return Err!(Request(Forbidden("Username is forbidden")));
}
// Create and validate the user ID
let user_id = match UserId::parse_with_server_name(
&supplied_username,
services.globals.server_name(),
) {
| Ok(user_id) => {
if let Err(e) = user_id.validate_strict() {
// Unless we are in emergency mode, we should follow synapse's behaviour on
// not allowing things like spaces and UTF-8 characters in usernames
if !emergency_mode_enabled {
return Err!(Request(InvalidUsername(debug_warn!(
"Username {supplied_username} contains disallowed characters or \
spaces: {e}"
))));
}
}
// Don't allow registration with user IDs that aren't local
if !services.globals.user_is_local(&user_id) {
return Err!(Request(InvalidUsername(
"Username {supplied_username} is not local to this server"
)));
}
user_id
},
| Err(e) => {
return Err!(Request(InvalidUsername(debug_warn!(
"Username {supplied_username} is not valid: {e}"
))));
},
};
if services.users.exists(&user_id).await {
return Err!(Request(UserInUse("User ID is not available.")));
}
Ok(user_id)
} else {
// The user didn't specify a username. Generate a username for
// them.
loop {
let user_id = UserId::parse_with_server_name(
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
services.globals.server_name(),
)
.unwrap();
if !services.users.exists(&user_id).await {
break Ok(user_id);
}
}
}
}
/// # `POST /_matrix/client/v3/register/email/requestToken` /// # `POST /_matrix/client/v3/register/email/requestToken`
/// ///
/// Requests a validation email for the purpose of registering a new account. /// Requests a validation email for the purpose of registering a new account.
+7 -4
View File
@@ -11,7 +11,7 @@ use ruma::{
}, },
thirdparty::{Medium, ThirdPartyIdentifierInit}, thirdparty::{Medium, ThirdPartyIdentifierInit},
}; };
use service::{mailer::messages, uiaa::Identity}; use service::mailer::messages;
use crate::{Ruma, router::ClientIdentity}; use crate::{Ruma, router::ClientIdentity};
@@ -124,15 +124,18 @@ pub(crate) async fn add_3pid_route(
.uiaa .uiaa
.authenticate_password( .authenticate_password(
&body.auth, &body.auth,
Some(Identity::from_user_id(body.identity.expect_sender_user()?)), body.identity.expect_sender_user()?,
body.identity.sender_device(),
None,
) )
.await?; .await?;
let email = services let email = services
.threepid .threepid
.consume_valid_session(&body.sid, &body.client_secret) .get_valid_session(&body.sid, &body.client_secret)
.await .await
.map_err(|message| err!(Request(ThreepidAuthFailed("{message}"))))?; .map_err(|message| err!(Request(ThreepidAuthFailed("{message}"))))?
.consume();
services services
.threepid .threepid
+5 -7
View File
@@ -8,7 +8,6 @@ use ruma::{
self, delete_device, delete_devices, get_device, get_devices, update_device, self, delete_device, delete_devices, get_device, get_devices, update_device,
}, },
}; };
use service::uiaa::Identity;
use crate::{Ruma, client::DEVICE_ID_LENGTH}; use crate::{Ruma, client::DEVICE_ID_LENGTH};
@@ -95,6 +94,7 @@ pub(crate) async fn update_device_route(
&device_id, &device_id,
&appservice.registration.as_token, &appservice.registration.as_token,
None, None,
None,
Some(client.to_string()), Some(client.to_string()),
) )
.await?; .await?;
@@ -119,14 +119,13 @@ pub(crate) async fn delete_device_route(
body: Ruma<delete_device::v3::Request>, body: Ruma<delete_device::v3::Request>,
) -> Result<delete_device::v3::Response> { ) -> Result<delete_device::v3::Response> {
let sender_user = body.identity.expect_sender_user()?; let sender_user = body.identity.expect_sender_user()?;
let appservice = body.identity.appservice_info();
// Appservices get to skip UIAA for this endpoint // Appservices get to skip UIAA for this endpoint
if appservice.is_none() { if let Some(sender_device) = body.identity.sender_device() {
// Prompt the user to confirm with their password using UIAA // Prompt the user to confirm with their password using UIAA
let _ = services let _ = services
.uiaa .uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user))) .authenticate_password(&body.auth, sender_user, Some(sender_device), None)
.await?; .await?;
} }
@@ -155,14 +154,13 @@ pub(crate) async fn delete_devices_route(
body: Ruma<delete_devices::v3::Request>, body: Ruma<delete_devices::v3::Request>,
) -> Result<delete_devices::v3::Response> { ) -> Result<delete_devices::v3::Response> {
let sender_user = body.identity.expect_sender_user()?; let sender_user = body.identity.expect_sender_user()?;
let appservice = body.identity.appservice_info();
// Appservices get to skip UIAA for this endpoint // Appservices get to skip UIAA for this endpoint
if appservice.is_none() { if let Some(sender_device) = body.identity.sender_device() {
// Prompt the user to confirm with their password using UIAA // Prompt the user to confirm with their password using UIAA
let _ = services let _ = services
.uiaa .uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user))) .authenticate_password(&body.auth, sender_user, Some(sender_device), None)
.await?; .await?;
} }
+7 -2
View File
@@ -26,7 +26,7 @@ use ruma::{
serde::Raw, serde::Raw,
}; };
use serde_json::json; use serde_json::json;
use service::uiaa::Identity; use service::oauth::OAuthTicket;
use crate::Ruma; use crate::Ruma;
@@ -205,7 +205,12 @@ pub(crate) async fn upload_signing_keys_route(
{ {
let _ = services let _ = services
.uiaa .uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user))) .authenticate_password(
&body.auth,
sender_user,
body.identity.sender_device(),
Some(OAuthTicket::CrossSigningReset),
)
.await?; .await?;
} }
+3
View File
@@ -16,6 +16,7 @@ pub(super) mod media_legacy;
pub(super) mod membership; pub(super) mod membership;
pub(super) mod message; pub(super) mod message;
pub(super) mod mutual_rooms; pub(super) mod mutual_rooms;
pub(super) mod oauth;
pub(super) mod openid; pub(super) mod openid;
pub(super) mod presence; pub(super) mod presence;
pub(super) mod profile; pub(super) mod profile;
@@ -61,6 +62,7 @@ pub(super) use membership::*;
pub use membership::{leave_all_rooms, leave_room, remote_leave_room}; pub use membership::{leave_all_rooms, leave_room, remote_leave_room};
pub(super) use message::*; pub(super) use message::*;
pub(super) use mutual_rooms::*; pub(super) use mutual_rooms::*;
pub(super) use oauth::*;
pub(super) use openid::*; pub(super) use openid::*;
pub(super) use presence::*; pub(super) use presence::*;
pub(super) use profile::*; pub(super) use profile::*;
@@ -73,6 +75,7 @@ pub(super) use report::*;
pub(super) use room::*; pub(super) use room::*;
pub(super) use search::*; pub(super) use search::*;
pub(super) use send::*; pub(super) use send::*;
pub use session::handle_login;
pub(super) use session::*; pub(super) use session::*;
pub(super) use space::*; pub(super) use space::*;
pub(super) use state::*; pub(super) use state::*;
+56
View File
@@ -0,0 +1,56 @@
use axum::{
Json, Router,
extract::{Request, State},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::method_routing::{get, post},
};
use const_str::concat;
use http::StatusCode;
use serde_json::json;
pub(crate) use server_metadata::*;
mod register_client;
mod server_metadata;
mod token;
const BASE_PATH: &str = concat!(conduwuit_core::ROUTE_PREFIX, "/oauth2/");
const AUTH_CODE_PATH: &str = "grant/authorization_code";
const JWKS_URI_PATH: &str = "client/keys.json";
const CLIENT_REGISTER_PATH: &str = "client/register";
const TOKEN_REVOKE_PATH: &str = "client/revoke";
const TOKEN_PATH: &str = "grant/token";
const ACCOUNT_MANAGEMENT_PATH: &str = concat!(conduwuit_core::ROUTE_PREFIX, "/account/deeplink");
pub(crate) fn router(state: crate::State) -> Router<crate::State> {
Router::new()
.nest(BASE_PATH, oauth_router())
.route(
"/.well-known/openid-configuration",
get(
// TODO(unspecced): used by old versions of the matrix-js-sdk
async |State(services): State<crate::State>| {
Json(authorization_server_metadata(&services).await)
},
),
)
.layer(middleware::from_fn_with_state(
state,
async |State(state): State<crate::State>, request: Request, next: Next| -> Response {
if state.config.oauth.compatibility_mode.oauth_available() {
next.run(request).await
} else {
(StatusCode::NOT_FOUND, "OAuth is unavailable on this server").into_response()
}
},
))
}
fn oauth_router() -> Router<crate::State> {
Router::new()
.route(concat!("/", CLIENT_REGISTER_PATH), post(register_client::register_client_route))
// TODO(unspecced): used by old versions of the matrix-js-sdk
.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))
}
+28
View File
@@ -0,0 +1,28 @@
use axum::{
Json,
extract::State,
response::{IntoResponse, Response},
};
use http::StatusCode;
use serde::Serialize;
use service::oauth::client_metadata::ClientMetadata;
#[derive(Serialize)]
struct RegisteredClient {
client_id: String,
#[serde(flatten)]
metadata: ClientMetadata,
}
pub(crate) async fn register_client_route(
State(services): State<crate::State>,
Json(metadata): Json<ClientMetadata>,
) -> Result<Response, Response> {
let client_id = services
.oauth
.register_client(&metadata)
.await
.map_err(|err| (StatusCode::BAD_REQUEST, Json(err)).into_response())?;
Ok(Json(RegisteredClient { client_id, metadata }).into_response())
}
+62
View File
@@ -0,0 +1,62 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::client::discovery::get_authorization_server_metadata::{
self, v1::AccountManagementAction,
},
serde::Raw,
};
use serde_json::{Value, json};
use service::Services;
use crate::{
Ruma,
client::oauth::{
ACCOUNT_MANAGEMENT_PATH, AUTH_CODE_PATH, CLIENT_REGISTER_PATH, JWKS_URI_PATH, TOKEN_PATH,
TOKEN_REVOKE_PATH,
},
};
pub(crate) async fn get_authorization_server_metadata_route(
State(services): State<crate::State>,
_body: Ruma<get_authorization_server_metadata::v1::Request>,
) -> Result<get_authorization_server_metadata::v1::Response> {
if !services.config.oauth.compatibility_mode.oauth_available() {
return Err!(Request(Unrecognized("OAuth is unavailable on this server")));
}
let metadata = Raw::new(&authorization_server_metadata(&services).await).unwrap();
Ok(get_authorization_server_metadata::v1::Response::new(metadata.cast_unchecked()))
}
pub(crate) async fn authorization_server_metadata(services: &Services) -> Value {
let endpoint_base = services
.config
.get_client_domain()
.join(super::BASE_PATH)
.unwrap();
json!({
"account_management_uri": endpoint_base.join(ACCOUNT_MANAGEMENT_PATH).unwrap(),
"account_management_actions_supported": [
AccountManagementAction::AccountDeactivate,
AccountManagementAction::CrossSigningReset,
AccountManagementAction::DeviceDelete,
AccountManagementAction::DeviceView,
AccountManagementAction::DevicesList,
AccountManagementAction::Profile,
],
"authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(),
"code_challenge_methods_supported": ["S256"],
"grant_types_supported": ["authorization_code", "refresh_token"],
"issuer": services.config.get_client_domain(),
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
"prompt_values_supported": ["create"],
"registration_endpoint": endpoint_base.join(CLIENT_REGISTER_PATH).unwrap(),
"response_modes_supported": ["query", "fragment"],
"response_types_supported": ["code"],
"revocation_endpoint": endpoint_base.join(TOKEN_REVOKE_PATH).unwrap(),
"token_endpoint": endpoint_base.join(TOKEN_PATH).unwrap(),
})
}
+23
View File
@@ -0,0 +1,23 @@
use axum::{Form, Json, extract::State, response::IntoResponse};
use http::StatusCode;
use service::oauth::grant::{RevokeTokenRequest, TokenRequest};
pub(crate) async fn token_route(
State(services): State<crate::State>,
Form(request): Form<TokenRequest>,
) -> impl IntoResponse {
match services.oauth.issue_token(request).await {
| Ok(response) => Ok(Json(response)),
| Err(err) => Err((StatusCode::BAD_REQUEST, Json(err))),
}
}
pub(crate) async fn revoke_token_route(
State(services): State<crate::State>,
Form(request): Form<RevokeTokenRequest>,
) -> impl IntoResponse {
match services.oauth.revoke_token(request.token).await {
| Ok(()) => Ok(StatusCode::OK),
| Err(err) => Err((StatusCode::BAD_REQUEST, Json(err))),
}
}
+35 -16
View File
@@ -21,7 +21,7 @@ use ruma::{
}, },
login::{ login::{
self, self,
v3::{DiscoveryInfo, HomeserverInfo}, v3::{DiscoveryInfo, HomeserverInfo, LoginInfo},
}, },
logout, logout_all, logout, logout_all,
}, },
@@ -29,7 +29,6 @@ use ruma::{
}, },
assign, assign,
}; };
use service::uiaa::Identity;
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH}; use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::Ruma; use crate::Ruma;
@@ -44,6 +43,12 @@ pub(crate) async fn get_login_types_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
_body: Ruma<get_login_types::v3::Request>, _body: Ruma<get_login_types::v3::Request>,
) -> Result<get_login_types::v3::Response> { ) -> Result<get_login_types::v3::Response> {
if !services.config.oauth.compatibility_mode.uiaa_available() {
return Err!(Request(Unrecognized(
"User-interactive authentication is not available on this server."
)));
}
Ok(get_login_types::v3::Response::new(vec![ Ok(get_login_types::v3::Response::new(vec![
get_login_types::v3::LoginType::Password(PasswordLoginType::default()), get_login_types::v3::LoginType::Password(PasswordLoginType::default()),
get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()), get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()),
@@ -53,7 +58,7 @@ pub(crate) async fn get_login_types_route(
])) ]))
} }
pub(crate) async fn handle_login( pub async fn handle_login(
services: &Services, services: &Services,
identifier: Option<&UserIdentifier>, identifier: Option<&UserIdentifier>,
password: &str, password: &str,
@@ -87,6 +92,10 @@ pub(crate) async fn handle_login(
return Err!(Request(InvalidParam("User ID does not belong to this homeserver"))); return Err!(Request(InvalidParam("User ID does not belong to this homeserver")));
} }
if services.users.is_deactivated(&user_id).await? {
return Err!(Request(UserDeactivated("This account has been deactivated.")));
}
if services.users.is_locked(&user_id).await? { if services.users.is_locked(&user_id).await? {
return Err!(Request(UserLocked("This account has been locked."))); return Err!(Request(UserLocked("This account has been locked.")));
} }
@@ -119,19 +128,29 @@ pub(crate) async fn login_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<login::v3::Request>, body: Ruma<login::v3::Request>,
) -> Result<login::v3::Response> { ) -> Result<login::v3::Response> {
if !services.config.oauth.compatibility_mode.uiaa_available() {
return match body.login_info {
| LoginInfo::ApplicationService(_) => {
Err!(Request(AppserviceLoginUnsupported(
"User-interactive appservice login is not available on this server."
)))
},
| _ => {
Err!(Request(Unrecognized(
"User-interactive authentication is not available on this server."
)))
},
};
}
let emergency_mode_enabled = services.config.emergency_password.is_some(); let emergency_mode_enabled = services.config.emergency_password.is_some();
// Validate login method // Validate login method
// TODO: Other login methods
let user_id = match &body.login_info { let user_id = match &body.login_info {
#[allow(deprecated)] #[allow(deprecated)]
| login::v3::LoginInfo::Password(login::v3::Password { | LoginInfo::Password(login::v3::Password { identifier, password, user, .. }) =>
identifier, handle_login(&services, identifier.as_ref(), password, user.as_ref()).await?,
password, | LoginInfo::Token(login::v3::Token { token, .. }) => {
user,
..
}) => handle_login(&services, identifier.as_ref(), password, user.as_ref()).await?,
| login::v3::LoginInfo::Token(login::v3::Token { token, .. }) => {
debug!("Got token login type"); debug!("Got token login type");
if !services.server.config.login_via_existing_session { if !services.server.config.login_via_existing_session {
return Err!(Request(Unknown("Token login is not enabled."))); return Err!(Request(Unknown("Token login is not enabled.")));
@@ -139,7 +158,7 @@ pub(crate) async fn login_route(
services.users.find_from_login_token(token).await? services.users.find_from_login_token(token).await?
}, },
#[allow(deprecated)] #[allow(deprecated)]
| login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService { | LoginInfo::ApplicationService(login::v3::ApplicationService {
identifier, identifier,
user, user,
.. ..
@@ -173,7 +192,6 @@ pub(crate) async fn login_route(
user_id user_id
}, },
| _ => { | _ => {
debug!("/login json_body: {:?}", &body.json_body);
return Err!(Request(Unknown( return Err!(Request(Unknown(
debug_warn!(?body.login_info, "Invalid or unsupported login type") debug_warn!(?body.login_info, "Invalid or unsupported login type")
))); )));
@@ -203,7 +221,7 @@ pub(crate) async fn login_route(
if device_exists { if device_exists {
services services
.users .users
.set_token(&user_id, &device_id, &token) .set_token(&user_id, &device_id, &token, None)
.await?; .await?;
} else { } else {
services services
@@ -212,6 +230,7 @@ pub(crate) async fn login_route(
&user_id, &user_id,
&device_id, &device_id,
&token, &token,
None,
body.initial_device_display_name.clone(), body.initial_device_display_name.clone(),
Some(client.to_string()), Some(client.to_string()),
) )
@@ -250,7 +269,7 @@ pub(crate) async fn login_token_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_login_token::v1::Request>, body: Ruma<get_login_token::v1::Request>,
) -> Result<get_login_token::v1::Response> { ) -> Result<get_login_token::v1::Response> {
if !services.server.config.login_via_existing_session { if !services.config.login_via_existing_session {
return Err!(Request(Forbidden("Login via an existing session is not enabled"))); return Err!(Request(Forbidden("Login via an existing session is not enabled")));
} }
@@ -259,7 +278,7 @@ pub(crate) async fn login_token_route(
// Prompt the user to confirm with their password using UIAA // Prompt the user to confirm with their password using UIAA
let _ = services let _ = services
.uiaa .uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user))) .authenticate_password(&body.auth, sender_user, body.identity.sender_device(), None)
.await?; .await?;
let login_token = utils::random_string(TOKEN_LENGTH); let login_token = utils::random_string(TOKEN_LENGTH);
+7
View File
@@ -48,6 +48,13 @@ async fn load_timeline(
ending_count: Option<PduCount>, ending_count: Option<PduCount>,
limit: usize, limit: usize,
) -> Result<TimelinePdus> { ) -> Result<TimelinePdus> {
if let (Some(starting_count), Some(ending_count)) = (starting_count, ending_count) {
debug_assert!(
starting_count <= ending_count,
"starting count {starting_count} > ending count {ending_count}"
);
}
let mut pdu_stream = match starting_count { let mut pdu_stream = match starting_count {
| Some(starting_count) => { | Some(starting_count) => {
let last_timeline_count = services let last_timeline_count = services
+63 -70
View File
@@ -38,6 +38,7 @@ use ruma::{
uint, uint,
}; };
use service::{account_data::AnyRawAccountDataEvent, rooms::short::ShortStateHash}; use service::{account_data::AnyRawAccountDataEvent, rooms::short::ShortStateHash};
use tokio::pin;
use super::{load_timeline, share_encrypted_room}; use super::{load_timeline, share_encrypted_room};
use crate::client::{ use crate::client::{
@@ -96,12 +97,19 @@ pub(super) async fn load_joined_room(
); );
} }
let state_events =
StateEvents::with_events(state_events.into_iter().map(Event::into_format).collect());
let joined_room = assign!(JoinedRoom::new(), { let joined_room = assign!(JoinedRoom::new(), {
account_data, account_data,
summary: summary.unwrap_or_default(), summary: summary.unwrap_or_default(),
unread_notifications: notification_counts.unwrap_or_default(), unread_notifications: notification_counts.unwrap_or_default(),
timeline, timeline,
state: RoomState::Before(StateEvents::with_events(state_events.into_iter().map(Event::into_format).collect())), state: if sync_context.use_state_after {
RoomState::After(state_events)
} else {
RoomState::Before(state_events)
},
ephemeral, ephemeral,
unread_thread_notifications: BTreeMap::new(), unread_thread_notifications: BTreeMap::new(),
}); });
@@ -344,7 +352,7 @@ struct ShortStateHashes {
#[tracing::instrument(level = "debug", skip_all)] #[tracing::instrument(level = "debug", skip_all)]
async fn fetch_shortstatehashes( async fn fetch_shortstatehashes(
services: &Services, services: &Services,
SyncContext { last_sync_end_count, current_count, .. }: SyncContext<'_>, SyncContext { last_sync_end_count, .. }: SyncContext<'_>,
room_id: &RoomId, room_id: &RoomId,
) -> Result<ShortStateHashes> { ) -> Result<ShortStateHashes> {
// the room state currently. // the room state currently.
@@ -354,46 +362,45 @@ async fn fetch_shortstatehashes(
.rooms .rooms
.state .state
.get_room_shortstatehash(room_id) .get_room_shortstatehash(room_id)
.map_err(|_| err!(Database(error!("Room {room_id} has no state")))); .map_err(|_| err!(Database(error!("Room {room_id} has no state"))))
.await?;
// the room state as of the end of the last sync. // The room state as of the end of the last sync.
// this will be None if we are doing an initial sync or if we just joined this // This will be None if we are doing an initial sync.
// room.
let last_sync_end_shortstatehash = let last_sync_end_shortstatehash =
OptionFuture::from(last_sync_end_count.map(|last_sync_end_count| { OptionFuture::from(last_sync_end_count.map(async |last_sync_end_count| {
// look up the shortstatehash saved by the last sync's call to pin! {
// `associate_token_shortstatehash` let pdus = services
.rooms
.timeline
.pdus(room_id, Some(PduCount::Normal(last_sync_end_count)))
.ignore_err();
}
match pdus.next().await {
| Some((_, pdu_after_last_sync_end)) => {
trace!(?pdu_after_last_sync_end.event_id, "pdu at last sync end");
Some(
services services
.rooms .rooms
.user .state_accessor
.get_token_shortstatehash(room_id, last_sync_end_count) .pdu_shortstatehash(&pdu_after_last_sync_end.event_id)
.inspect_err(move |_| { .await
debug_warn!( .map_err(|err| {
token = last_sync_end_count, err!("Last sync end PDU has no shortstatehash: {err}")
"Room has no shortstatehash for this token" }),
); )
}) },
.ok() | None => {
// No events have been sent since the last sync, or we just joined this room
None
},
}
})) }))
.map(Option::flatten) .await
.map(Ok); .flatten()
.transpose()?;
let (current_shortstatehash, last_sync_end_shortstatehash) =
try_join(current_shortstatehash, last_sync_end_shortstatehash).await?;
/*
associate the `current_count` with the `current_shortstatehash`, so we can
use it on the next sync as the `last_sync_end_shortstatehash`.
TODO: the table written to by this call grows extremely fast, gaining one new entry for each
joined room on _every single sync request_. we need to find a better way to remember the shortstatehash
between syncs.
*/
services
.rooms
.user
.associate_token_shortstatehash(room_id, current_count, current_shortstatehash)
.await;
Ok(ShortStateHashes { Ok(ShortStateHashes {
current_shortstatehash, current_shortstatehash,
@@ -452,6 +459,7 @@ async fn build_state_events(
syncing_user, syncing_user,
last_sync_end_count, last_sync_end_count,
full_state, full_state,
use_state_after,
.. ..
} = sync_context; } = sync_context;
@@ -460,32 +468,15 @@ async fn build_state_events(
last_sync_end_shortstatehash, last_sync_end_shortstatehash,
} = shortstatehashes; } = shortstatehashes;
// the spec states that the `state` property only includes state events up to if timeline.pdus.is_empty() {
// the beginning of the timeline, so we determine the state of the syncing room // If the timeline is empty there can't possibly be any changes to the state
// as of the first timeline event. NOTE: this explanation is not entirely return Ok(vec![]);
// accurate; see the implementation of `build_state_incremental`.
let timeline_start_shortstatehash = async {
if let Some((_, pdu)) = timeline.pdus.front() {
if let Ok(shortstatehash) = services
.rooms
.state_accessor
.pdu_shortstatehash(&pdu.event_id)
.await
{
return shortstatehash;
} }
}
current_shortstatehash
};
// the user IDs of members whose membership needs to be sent to the client, if // the user IDs of members whose membership needs to be sent to the client, if
// lazy-loading is enabled. // lazy-loading is enabled.
let lazily_loaded_members = let lazily_loaded_members =
prepare_lazily_loaded_members(services, sync_context, room_id, timeline.senders()); prepare_lazily_loaded_members(services, sync_context, room_id, timeline.senders()).await;
let (timeline_start_shortstatehash, lazily_loaded_members) =
join(timeline_start_shortstatehash, lazily_loaded_members).await;
// compute the state delta between the previous sync and this sync. // compute the state delta between the previous sync and this sync.
match (last_sync_end_count, last_sync_end_shortstatehash) { match (last_sync_end_count, last_sync_end_shortstatehash) {
@@ -494,16 +485,14 @@ async fn build_state_events(
is Some (meaning the syncing user didn't just join this room for the first time ever), and `full_state` is false, is Some (meaning the syncing user didn't just join this room for the first time ever), and `full_state` is false,
then use `build_state_incremental`. then use `build_state_incremental`.
*/ */
| (Some(last_sync_end_count), Some(last_sync_end_shortstatehash)) if !full_state => | (Some(_), Some(last_sync_end_shortstatehash)) if !full_state =>
build_state_incremental( build_state_incremental(
services, services,
syncing_user, syncing_user,
room_id,
PduCount::Normal(last_sync_end_count),
last_sync_end_shortstatehash, last_sync_end_shortstatehash,
timeline_start_shortstatehash,
current_shortstatehash, current_shortstatehash,
timeline, timeline,
use_state_after,
lazily_loaded_members.as_ref(), lazily_loaded_members.as_ref(),
) )
.boxed() .boxed()
@@ -517,7 +506,9 @@ async fn build_state_events(
build_state_initial( build_state_initial(
services, services,
syncing_user, syncing_user,
timeline_start_shortstatehash, current_shortstatehash,
timeline,
use_state_after,
lazily_loaded_members.as_ref(), lazily_loaded_members.as_ref(),
) )
.boxed() .boxed()
@@ -598,10 +589,14 @@ async fn check_joined_since_last_sync(
ShortStateHashes { last_sync_end_shortstatehash, .. }: ShortStateHashes, ShortStateHashes { last_sync_end_shortstatehash, .. }: ShortStateHashes,
SyncContext { syncing_user, .. }: SyncContext<'_>, SyncContext { syncing_user, .. }: SyncContext<'_>,
) -> Result<bool> { ) -> Result<bool> {
// fetch the syncing user's membership event during the last sync. let Some(last_sync_end_shortstatehash) = last_sync_end_shortstatehash else {
// this will be None if `previous_sync_end_shortstatehash` is None. // For initial syncs always return false, since there's no "last sync" for the
let membership_during_previous_sync = match last_sync_end_shortstatehash { // user to have joined since.
| Some(last_sync_end_shortstatehash) => services return Ok(false);
};
// Fetch the syncing user's membership event during the last sync.
let membership_during_previous_sync = services
.rooms .rooms
.state_accessor .state_accessor
.state_get_content( .state_get_content(
@@ -611,9 +606,7 @@ async fn check_joined_since_last_sync(
) )
.await .await
.inspect_err(|_| debug_warn!("User has no previous membership")) .inspect_err(|_| debug_warn!("User has no previous membership"))
.ok(), .ok();
| None => None,
};
// TODO: If the requesting user got state-reset out of the room, this // TODO: If the requesting user got state-reset out of the room, this
// will be `true` when it shouldn't be. this function should never be called // will be `true` when it shouldn't be. this function should never be called
+13 -25
View File
@@ -4,7 +4,7 @@ use conduwuit::{
trace, trace,
utils::{self, IterStream, future::ReadyEqExt, stream::WidebandExt as _}, utils::{self, IterStream, future::ReadyEqExt, stream::WidebandExt as _},
}; };
use futures::{StreamExt, future::join}; use futures::StreamExt;
use ruma::{ use ruma::{
EventId, OwnedRoomId, RoomId, EventId, OwnedRoomId, RoomId,
api::client::sync::sync_events::v3::{ api::client::sync::sync_events::v3::{
@@ -181,6 +181,9 @@ pub(super) async fn load_left_room(
.collect::<Vec<_>>() .collect::<Vec<_>>()
.await; .await;
let state_events =
StateEvents::with_events(state_events.into_iter().map(Event::into_format).collect());
Ok(Some(assign!(LeftRoom::new(), { Ok(Some(assign!(LeftRoom::new(), {
account_data: RoomAccountData::new(), account_data: RoomAccountData::new(),
timeline: assign!(Timeline::new(), { timeline: assign!(Timeline::new(), {
@@ -188,7 +191,11 @@ pub(super) async fn load_left_room(
prev_batch: Some(current_count.to_string()), prev_batch: Some(current_count.to_string()),
events: raw_timeline_pdus, events: raw_timeline_pdus,
}), }),
state: State::Before(StateEvents::with_events(state_events.into_iter().map(Event::into_format).collect())), state: if sync_context.use_state_after {
State::After(state_events)
} else {
State::Before(state_events)
},
}))) })))
} }
@@ -233,29 +240,8 @@ async fn build_left_state_and_timeline(
) )
.await?; .await?;
let timeline_start_shortstatehash = async {
if let Some((_, pdu)) = timeline.pdus.front() {
if let Ok(shortstatehash) = services
.rooms
.state_accessor
.pdu_shortstatehash(&pdu.event_id)
.await
{
return shortstatehash;
}
}
// the timeline generally should not be empty (see the TODO further down),
// but in case it is we use `leave_shortstatehash` as the state to
// send
leave_shortstatehash
};
let lazily_loaded_members = let lazily_loaded_members =
prepare_lazily_loaded_members(services, sync_context, room_id, timeline.senders()); prepare_lazily_loaded_members(services, sync_context, room_id, timeline.senders()).await;
let (timeline_start_shortstatehash, lazily_loaded_members) =
join(timeline_start_shortstatehash, lazily_loaded_members).await;
// TODO: calculate incremental state for incremental syncs. // TODO: calculate incremental state for incremental syncs.
// always calculating initial state _works_ but returns more data and does // always calculating initial state _works_ but returns more data and does
@@ -263,7 +249,9 @@ async fn build_left_state_and_timeline(
let mut state = build_state_initial( let mut state = build_state_initial(
services, services,
syncing_user, syncing_user,
timeline_start_shortstatehash, leave_shortstatehash,
&timeline,
sync_context.use_state_after,
lazily_loaded_members.as_ref(), lazily_loaded_members.as_ref(),
) )
.await?; .await?;
+7 -4
View File
@@ -11,12 +11,11 @@ use std::{
use axum::extract::State; use axum::extract::State;
use axum_client_ip::ClientIp; use axum_client_ip::ClientIp;
use conduwuit::{ use conduwuit::{
Err, Result, at, extract_variant, Err, Result, at, error, extract_variant,
utils::{ utils::{
ReadyExt, TryFutureExtExt, ReadyExt, TryFutureExtExt,
stream::{BroadbandExt, Tools, WidebandExt}, stream::{BroadbandExt, Tools, WidebandExt},
}, },
warn,
}; };
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture}; use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture};
@@ -111,6 +110,9 @@ struct SyncContext<'a> {
/// The sync filter, which the client uses to specify what data should be /// The sync filter, which the client uses to specify what data should be
/// included in the sync response. /// included in the sync response.
filter: &'a FilterDefinition, filter: &'a FilterDefinition,
/// Whether the state at the end of the timeline should be used when
/// calculating state diffs for sync.
use_state_after: bool,
} }
impl<'a> SyncContext<'a> { impl<'a> SyncContext<'a> {
@@ -264,6 +266,7 @@ pub(crate) async fn build_sync_events(
current_count, current_count,
full_state, full_state,
filter: &filter, filter: &filter,
use_state_after: body.use_state_after,
}; };
let joined_rooms = services let joined_rooms = services
@@ -276,7 +279,7 @@ pub(crate) async fn build_sync_events(
match joined_room { match joined_room {
| Ok((room, updates)) => Some((room_id, room, updates)), | Ok((room, updates)) => Some((room_id, room, updates)),
| Err(err) => { | Err(err) => {
warn!(?err, %room_id, "error loading joined room"); error!(?err, %room_id, "error loading joined room");
None None
}, },
} }
@@ -305,7 +308,7 @@ pub(crate) async fn build_sync_events(
| Ok(Some(left_room)) => Some((room_id, left_room)), | Ok(Some(left_room)) => Some((room_id, left_room)),
| Ok(None) => None, | Ok(None) => None,
| Err(err) => { | Err(err) => {
warn!(?err, %room_id, "error loading joined room"); error!(?err, %room_id, "error loading joined room");
None None
}, },
} }
+60 -143
View File
@@ -1,11 +1,8 @@
use std::{collections::BTreeSet, ops::ControlFlow}; use std::collections::HashSet;
use conduwuit::{ use conduwuit::{
Result, at, is_equal_to, Result, at,
matrix::{ matrix::{Event, pdu::PduEvent},
Event,
pdu::{PduCount, PduEvent},
},
utils::{ utils::{
BoolExt, IterStream, ReadyExt, TryFutureExtExt, BoolExt, IterStream, ReadyExt, TryFutureExtExt,
stream::{BroadbandExt, TryIgnore}, stream::{BroadbandExt, TryIgnore},
@@ -16,9 +13,7 @@ use conduwuit_service::{
rooms::{lazy_loading::MemberSet, short::ShortStateHash}, rooms::{lazy_loading::MemberSet, short::ShortStateHash},
}; };
use futures::{FutureExt, StreamExt}; use futures::{FutureExt, StreamExt};
use itertools::Itertools; use ruma::{OwnedEventId, UserId, events::StateEventType};
use ruma::{OwnedEventId, RoomId, UserId, events::StateEventType};
use service::rooms::short::ShortEventId;
use tracing::trace; use tracing::trace;
use crate::client::TimelinePdus; use crate::client::TimelinePdus;
@@ -38,14 +33,22 @@ use crate::client::TimelinePdus;
pub(super) async fn build_state_initial( pub(super) async fn build_state_initial(
services: &Services, services: &Services,
sender_user: &UserId, sender_user: &UserId,
timeline_start_shortstatehash: ShortStateHash, timeline_end_shortstatehash: ShortStateHash,
timeline: &TimelinePdus,
use_state_after: bool,
lazily_loaded_members: Option<&MemberSet>, lazily_loaded_members: Option<&MemberSet>,
) -> Result<Vec<PduEvent>> { ) -> Result<Vec<PduEvent>> {
let event_ids_in_timeline: HashSet<_> =
timeline.pdus.iter().map(|pdu| &pdu.1.event_id).collect();
// load the keys and event IDs of the state events at the start of the timeline // load the keys and event IDs of the state events at the start of the timeline
let (shortstatekeys, event_ids): (Vec<_>, Vec<_>) = services let (shortstatekeys, event_ids): (Vec<_>, Vec<_>) = services
.rooms .rooms
.state_accessor .state_accessor
.state_full_ids(timeline_start_shortstatehash) .state_full_ids(timeline_end_shortstatehash)
.ready_filter(|(_, event_id)| {
use_state_after || !event_ids_in_timeline.contains(event_id)
})
.unzip() .unzip()
.await; .await;
@@ -92,82 +95,32 @@ pub(super) async fn build_state_initial(
pub(super) async fn build_state_incremental<'a>( pub(super) async fn build_state_incremental<'a>(
services: &Services, services: &Services,
sender_user: &'a UserId, sender_user: &'a UserId,
room_id: &RoomId,
last_sync_end_count: PduCount,
last_sync_end_shortstatehash: ShortStateHash, last_sync_end_shortstatehash: ShortStateHash,
timeline_start_shortstatehash: ShortStateHash,
timeline_end_shortstatehash: ShortStateHash, timeline_end_shortstatehash: ShortStateHash,
timeline: &TimelinePdus, timeline: &TimelinePdus,
use_state_after: bool,
lazily_loaded_members: Option<&'a MemberSet>, lazily_loaded_members: Option<&'a MemberSet>,
) -> Result<Vec<PduEvent>> { ) -> Result<Vec<PduEvent>> {
/* let mut state_event_ids: HashSet<OwnedEventId> = HashSet::new();
NB: a limited sync is one where `timeline.limited == true`. Synapse calls this a "gappy" sync internally.
The algorithm implemented in this function is, currently, quite different from the algorithm vaguely described
by the Matrix specification. This is because the specification's description of the `state` property does not accurately
reflect how Synapse behaves, and therefore how client SDKs behave. Notable differences include:
1. We do not compute the delta using the naive approach of "every state event from the end of the last sync
up to the start of this sync's timeline". see below for details.
2. If lazy-loading is enabled, we include lazily-loaded membership events. The specific users to include are determined
elsewhere and supplied to this function in the `lazily_loaded_members` parameter.
*/
/*
the `state` property of an incremental sync which isn't limited are _usually_ empty.
(note: the specification says that the `state` property is _always_ empty for limited syncs, which is incorrect.)
however, if an event in the timeline (`timeline.pdus`) merges a split in the room's DAG (i.e. has multiple `prev_events`),
the state at the _end_ of the timeline may include state events which were merged in and don't exist in the state
at the _start_ of the timeline. because this is uncommon, we check here to see if any events in the timeline
merged a split in the DAG.
see: https://github.com/element-hq/synapse/issues/16941
*/
let timeline_is_linear = timeline.pdus.is_empty() || {
let last_pdu_of_last_sync = services
.rooms
.timeline
.pdus_rev(room_id, Some(last_sync_end_count.saturating_add(1)))
.boxed()
.next()
.await
.transpose()
.expect("last sync should have had some PDUs")
.map(at!(1));
// make sure the prev_events of each pdu in the timeline refer only to the
// previous pdu
timeline
.pdus
.iter()
.try_fold(last_pdu_of_last_sync.map(|pdu| pdu.event_id), |prev_event_id, (_, pdu)| {
if let Ok(pdu_prev_event_id) = pdu.prev_events.iter().exactly_one() {
if prev_event_id
.as_ref()
.is_none_or(is_equal_to!(pdu_prev_event_id))
{
return ControlFlow::Continue(Some(pdu_prev_event_id.to_owned()));
}
}
trace!( trace!(
"pdu {:?} has split prev_events (expected {:?}): {:?}", %use_state_after,
pdu.event_id, prev_event_id, pdu.prev_events %last_sync_end_shortstatehash,
%timeline_end_shortstatehash,
"computing state for incremental sync"
); );
ControlFlow::Break(())
})
.is_continue()
};
if timeline_is_linear && !timeline.limited { // Fetch lazy-loaded membership events if lazy-loading is enabled
// if there are no splits in the DAG and the timeline isn't limited, then if let Some(lazily_loaded_members) = lazily_loaded_members
// `state` will always be empty unless lazy loading is enabled. && !lazily_loaded_members.is_empty()
{
trace!("including lazy membership events for members: {:?}", lazily_loaded_members);
if let Some(lazily_loaded_members) = lazily_loaded_members { services
if !timeline.pdus.is_empty() { .rooms
// lazy loading is enabled, so we return the membership events which were .short
// requested by the caller. .multi_get_eventid_from_short::<'_, OwnedEventId, _>(
let lazy_membership_events: Vec<_> = lazily_loaded_members lazily_loaded_members
.iter() .iter()
.stream() .stream()
.broad_filter_map(|user_id| async move { .broad_filter_map(|user_id| async move {
@@ -178,71 +131,24 @@ pub(super) async fn build_state_incremental<'a>(
services services
.rooms .rooms
.state_accessor .state_accessor
.state_get( .state_get_shortid(
timeline_start_shortstatehash, timeline_end_shortstatehash,
&StateEventType::RoomMember, &StateEventType::RoomMember,
user_id.as_str(), user_id.as_str(),
) )
.ok() .ok()
.await .await
}),
)
.ignore_err()
.ready_for_each(|event_id| {
state_event_ids.insert(event_id);
}) })
.collect()
.await; .await;
if !lazy_membership_events.is_empty() {
trace!(
"syncing lazy membership events for members: {:?}",
lazy_membership_events
.iter()
.map(|pdu| pdu.state_key().unwrap())
.collect::<Vec<_>>()
);
}
return Ok(lazy_membership_events);
}
} }
// lazy loading is disabled, `state` is empty. // Fetch the state events added since the last sync.
return Ok(vec![]); services
}
/*
at this point, either the timeline is `limited` or the DAG has a split in it. this necessitates
computing the incremental state (which may be empty).
NOTE: this code path does not use the `lazy_membership_events` parameter. any changes to membership will be included
in the incremental state. therefore, the incremental state may include "redundant" membership events,
which we do not filter out because A. the spec forbids lazy-load filtering if the timeline is `limited`,
and B. DAG splits which require sending extra membership state events are (probably) uncommon enough that
the performance penalty is acceptable.
*/
trace!(%timeline_is_linear, %timeline.limited, "computing state for incremental sync");
// fetch the shorteventids of state events in the timeline
let state_events_in_timeline: BTreeSet<ShortEventId> = services
.rooms
.short
.multi_get_or_create_shorteventid(timeline.pdus.iter().filter_map(|(_, pdu)| {
if pdu.state_key().is_some() {
Some(pdu.event_id.as_ref())
} else {
None
}
}))
.collect()
.await;
trace!("{} state events in timeline", state_events_in_timeline.len());
/*
fetch the state events which were added since the last sync.
specifically we fetch the difference between the state at the last sync and the state at the _end_
of the timeline, and then we filter out state events in the timeline itself using the shorteventids we fetched.
this is necessary to account for splits in the DAG, as explained above.
*/
let state_diff = services
.rooms .rooms
.short .short
.multi_get_eventid_from_short::<'_, OwnedEventId, _>( .multi_get_eventid_from_short::<'_, OwnedEventId, _>(
@@ -252,18 +158,29 @@ pub(super) async fn build_state_incremental<'a>(
.state_added((last_sync_end_shortstatehash, timeline_end_shortstatehash)) .state_added((last_sync_end_shortstatehash, timeline_end_shortstatehash))
.await? .await?
.stream() .stream()
.ready_filter_map(|(_, shorteventid)| { .map(at!(1)),
if state_events_in_timeline.contains(&shorteventid) {
None
} else {
Some(shorteventid)
}
}),
) )
.ignore_err(); .ignore_err()
.ready_for_each(|event_id| {
state_event_ids.insert(event_id);
})
.await;
// finally, fetch the PDU contents and collect them into a vec if !use_state_after {
let state_diff_pdus = state_diff // If state_after isn't enabled, filter out state events which also exist
// in the timeline. If splits exist in the DAG, this may not be exactly the same
// thing as the state diff ending at the start of the timeline, but Synapse
// also does this and it's technically more useful behavior anyway.
// See: https://github.com/element-hq/synapse/issues/16941
for (_, pdu) in &timeline.pdus {
state_event_ids.remove(pdu.event_id());
}
}
// Finally, fetch the PDU contents and collect them into a vec
let state_diff_pdus = state_event_ids
.stream()
.broad_filter_map(|event_id| async move { .broad_filter_map(|event_id| async move {
services services
.rooms .rooms
+25 -6
View File
@@ -15,7 +15,7 @@ use conduwuit::{
BoolExt, FutureBoolExt, IterStream, ReadyExt, TryFutureExtExt, BoolExt, FutureBoolExt, IterStream, ReadyExt, TryFutureExtExt,
future::ReadyEqExt, future::ReadyEqExt,
math::{ruma_from_usize, usize_from_ruma}, math::{ruma_from_usize, usize_from_ruma},
stream::WidebandExt, stream::{TryIgnore, WidebandExt},
}, },
warn, warn,
}; };
@@ -41,6 +41,7 @@ use ruma::{
uint, uint,
}; };
use service::account_data::AnyRawAccountDataEvent; use service::account_data::AnyRawAccountDataEvent;
use tokio::pin;
use super::share_encrypted_room; use super::share_encrypted_room;
use crate::{ use crate::{
@@ -69,7 +70,6 @@ pub(crate) async fn sync_events_v5_route(
ClientIp(client_ip): ClientIp, ClientIp(client_ip): ClientIp,
body: Ruma<sync_events::v5::Request>, body: Ruma<sync_events::v5::Request>,
) -> Result<sync_events::v5::Response> { ) -> Result<sync_events::v5::Response> {
debug_assert!(DEFAULT_BUMP_TYPES.is_sorted(), "DEFAULT_BUMP_TYPES is not sorted");
let sender_user = body.identity.expect_sender_user()?; let sender_user = body.identity.expect_sender_user()?;
let sender_device = body.identity.expect_sender_device()?; let sender_device = body.identity.expect_sender_device()?;
@@ -858,12 +858,31 @@ where
continue; continue;
}; };
let since_shortstatehash = services let since_shortstatehash = async {
pin! {
let pdus_rev = services
.rooms .rooms
.user .timeline
.get_token_shortstatehash(room_id, globalsince) .pdus_rev(room_id, Some(PduCount::Normal(globalsince.saturating_sub(1))))
.ignore_err();
}
let (count, pdu_at_last_sync_end) = pdus_rev.next().await?;
if matches!(count, PduCount::Backfilled(_)) {
None
} else {
Some(
services
.rooms
.state_accessor
.pdu_shortstatehash(&pdu_at_last_sync_end.event_id)
.await .await
.ok(); .expect("pdu should have a shortstatehash"),
)
}
}
.await;
let encrypted_room = services let encrypted_room = services
.rooms .rooms
+2 -2
View File
@@ -35,8 +35,8 @@ pub(crate) async fn get_supported_versions_route(
/// `/_matrix/federation/v1/version` /// `/_matrix/federation/v1/version`
pub(crate) async fn conduwuit_server_version() -> Result<impl IntoResponse> { pub(crate) async fn conduwuit_server_version() -> Result<impl IntoResponse> {
Ok(Json(serde_json::json!({ Ok(Json(serde_json::json!({
"name": conduwuit::version::name(), "name": conduwuit::BRANDING,
"version": conduwuit::version::version(), "version": conduwuit::version(),
}))) })))
} }
+2 -42
View File
@@ -3,8 +3,7 @@ use conduwuit::{Err, Result};
use ruma::{ use ruma::{
api::client::discovery::{ api::client::discovery::{
discover_homeserver::{self, HomeserverInfo}, discover_homeserver::{self, HomeserverInfo},
discover_policy_server, discover_policy_server, discover_support,
discover_support::{self, Contact, ContactRole},
}, },
assign, assign,
}; };
@@ -67,46 +66,7 @@ pub(crate) async fn well_known_support(
.as_ref() .as_ref()
.map(ToString::to_string); .map(ToString::to_string);
let email_address = services.config.well_known.support_email.clone(); let contacts = services.admin.get_support_contacts().await;
let matrix_id = services.config.well_known.support_mxid.clone();
let pgp_key = services.config.well_known.support_pgp_key.clone();
// TODO: support defining multiple contacts in the config
let mut contacts: Vec<Contact> = vec![];
let role = services
.config
.well_known
.support_role
.clone()
.unwrap_or(ContactRole::Admin);
// Add configured contact if at least one contact method is specified
let configured_contact = match (matrix_id, email_address) {
| (Some(matrix_id), email_address) =>
Some(assign!(Contact::with_matrix_id(role, matrix_id), { email_address })),
| (None, Some(email_address)) => Some(Contact::with_email_address(role, email_address)),
| (None, None) => None,
};
if let Some(mut configured_contact) = configured_contact {
configured_contact.pgp_key = pgp_key;
contacts.push(configured_contact);
}
// Try to add admin users as contacts if no contacts are configured
if contacts.is_empty() {
let admin_users = services.admin.get_admins().await;
for user_id in &admin_users {
if *user_id == services.globals.server_user {
continue;
}
contacts.push(Contact::with_matrix_id(ContactRole::Admin, user_id.to_owned()));
}
}
if contacts.is_empty() && support_page.is_none() { if contacts.is_empty() && support_page.is_none() {
// No admin room, no configured contacts, and no support page // No admin room, no configured contacts, and no support page
+1
View File
@@ -1,4 +1,5 @@
#![type_length_limit = "16384"] //TODO: reduce me #![type_length_limit = "16384"] //TODO: reduce me
#![recursion_limit = "256"] // My Giant Async Function
#![allow(clippy::toplevel_ref_arg)] #![allow(clippy::toplevel_ref_arg)]
extern crate conduwuit_core as conduwuit; extern crate conduwuit_core as conduwuit;
+5 -3
View File
@@ -10,7 +10,7 @@ use axum::{
response::{IntoResponse, Redirect}, response::{IntoResponse, Redirect},
routing::{any, get, post}, routing::{any, get, post},
}; };
use conduwuit::{Server, err}; use conduwuit::err;
pub(super) use conduwuit_service::state::State; pub(super) use conduwuit_service::state::State;
use http::{Uri, uri}; use http::{Uri, uri};
@@ -18,8 +18,8 @@ use self::handler::RouterExt;
pub(super) use self::{args::Args as Ruma, auth::ClientIdentity, response::RumaResponse}; pub(super) use self::{args::Args as Ruma, auth::ClientIdentity, response::RumaResponse};
use crate::{admin, client, server}; use crate::{admin, client, server};
pub fn build(router: Router<State>, server: &Server) -> Router<State> { pub fn build(router: Router<State>, state: State) -> Router<State> {
let config = &server.config; let config = &state.server.config;
let mut router = router 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_supported_versions_route)
@@ -186,6 +186,8 @@ pub fn build(router: Router<State>, server: &Server) -> Router<State> {
.ruma_route(&client::well_known_policy_server) .ruma_route(&client::well_known_policy_server)
.ruma_route(&client::get_rtc_transports) .ruma_route(&client::get_rtc_transports)
.ruma_route(&client::room_initial_sync_route) .ruma_route(&client::room_initial_sync_route)
.ruma_route(&client::get_authorization_server_metadata_route)
.merge(client::oauth::router(state))
.route("/_conduwuit/server_version", get(client::conduwuit_server_version)) .route("/_conduwuit/server_version", get(client::conduwuit_server_version))
.route("/_continuwuity/server_version", get(client::conduwuit_server_version)) .route("/_continuwuity/server_version", get(client::conduwuit_server_version))
.ruma_route(&admin::rooms::ban::ban_room) .ruma_route(&admin::rooms::ban::ban_room)
+31 -4
View File
@@ -1,6 +1,7 @@
use std::any::{Any, TypeId}; use std::any::{Any, TypeId};
use conduwuit::{Err, Result, err}; use conduwuit::{Err, Error, Result, err};
use http::StatusCode;
use ruma::{ use ruma::{
DeviceId, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId, DeviceId, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
api::{ api::{
@@ -10,12 +11,15 @@ use ruma::{
AuthScheme, NoAccessToken, NoAuthentication, AuthScheme, NoAccessToken, NoAuthentication,
}, },
client, client,
error::{ErrorKind, UnknownTokenErrorData},
federation::authentication::ServerSignatures, federation::authentication::ServerSignatures,
}, },
assign,
}; };
use service::{ use service::{
Services, Services,
server_keys::{PubKeyMap, PubKeys}, server_keys::{PubKeyMap, PubKeys},
users::AccessTokenStatus,
}; };
use crate::{router::args::AuthQueryParams, service::appservice::RegistrationInfo}; use crate::{router::args::AuthQueryParams, service::appservice::RegistrationInfo};
@@ -162,7 +166,23 @@ impl CheckAuth for AccessToken {
query: AuthQueryParams, query: AuthQueryParams,
route: TypeId, route: TypeId,
) -> Result<Self::Identity> { ) -> Result<Self::Identity> {
if let Ok((sender_user, sender_device)) = services.users.find_from_token(&output).await { if output.is_empty() {
return Err!(Request(Unauthorized("Missing access token.")));
}
if let Some((sender_user, sender_device, status)) =
services.users.find_from_token(&output).await
{
// If the token is expired we return a soft logout
if matches!(status, AccessTokenStatus::Expired) {
return Err(Error::Request(
ErrorKind::UnknownToken(
assign!(UnknownTokenErrorData::new(), { soft_logout: true }),
),
"This token has expired".into(),
StatusCode::UNAUTHORIZED,
));
}
// Locked users can only use /logout and /logout/all // Locked users can only use /logout and /logout/all
if services if services
.users .users
@@ -173,7 +193,7 @@ impl CheckAuth for AccessToken {
if !(route == TypeId::of::<client::session::logout::v3::Request>() if !(route == TypeId::of::<client::session::logout::v3::Request>()
|| route == TypeId::of::<client::session::logout_all::v3::Request>()) || route == TypeId::of::<client::session::logout_all::v3::Request>())
{ {
return Err!(Request(Unauthorized("Your account is locked."))); return Err!(Request(UserLocked("Your account is locked.")));
} }
} }
@@ -224,7 +244,11 @@ impl CheckAuth for AccessToken {
appservice_info: Box::new(appservice_info), appservice_info: Box::new(appservice_info),
}) })
} else { } else {
Err!(Request(Unauthorized("Invalid access token."))) Err(Error::Request(
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
"Invalid token".into(),
StatusCode::UNAUTHORIZED,
))
} }
} }
} }
@@ -259,6 +283,9 @@ impl CheckAuth for AppserviceToken {
_query: AuthQueryParams, _query: AuthQueryParams,
_route: TypeId, _route: TypeId,
) -> Result<Self::Identity> { ) -> Result<Self::Identity> {
if output.is_empty() {
return Err!(Request(Unauthorized("Missing access token.")));
}
let Ok(appservice_info) = services.appservice.find_from_token(&output).await else { let Ok(appservice_info) = services.appservice.find_from_token(&output).await else {
return Err!(Request(Unauthorized("Invalid appservice token."))); return Err!(Request(Unauthorized("Invalid appservice token.")));
}; };
+1 -1
View File
@@ -32,7 +32,7 @@ pub(crate) async fn get_backfill_route(
room_id: &body.room_id, room_id: &body.room_id,
event_id: None, event_id: None,
} }
.check() .assert()
.await?; .await?;
if !services if !services
.rooms .rooms
+1 -1
View File
@@ -44,7 +44,7 @@ pub(crate) async fn get_event_route(
room_id, room_id,
event_id: Some(&body.event_id), event_id: Some(&body.event_id),
} }
.check() .assert()
.await?; .await?;
if !services if !services
+1 -1
View File
@@ -23,7 +23,7 @@ pub(crate) async fn get_event_authorization_route(
room_id: &body.room_id, room_id: &body.room_id,
event_id: None, event_id: None,
} }
.check() .assert()
.await?; .await?;
if services if services
+1 -1
View File
@@ -26,7 +26,7 @@ pub(crate) async fn get_missing_events_route(
room_id: &body.room_id, room_id: &body.room_id,
event_id: None, event_id: None,
} }
.check() .assert()
.await?; .await?;
if !services if !services
+7
View File
@@ -676,6 +676,13 @@ async fn handle_edu_direct_to_device(
messages messages
.into_iter() .into_iter()
.stream() .stream()
.broad_filter_map(|(target_user_id, map)| async move {
services
.users
.is_active_local(&target_user_id)
.await
.then_some((target_user_id, map))
})
.for_each_concurrent(automatic_width(), |(target_user_id, map)| { .for_each_concurrent(automatic_width(), |(target_user_id, map)| {
handle_edu_direct_to_device_user(services, target_user_id, sender, &ev_type, map) handle_edu_direct_to_device_user(services, target_user_id, sender, &ev_type, map)
}) })
+1 -1
View File
@@ -21,7 +21,7 @@ pub(crate) async fn get_room_state_route(
room_id: &body.room_id, room_id: &body.room_id,
event_id: None, event_id: None,
} }
.check() .assert()
.await?; .await?;
if services if services
+1 -1
View File
@@ -22,7 +22,7 @@ pub(crate) async fn get_room_state_ids_route(
room_id: &body.room_id, room_id: &body.room_id,
event_id: None, event_id: None,
} }
.check() .assert()
.await?; .await?;
if services if services
+7 -3
View File
@@ -1,4 +1,4 @@
use conduwuit::{Err, Result, implement, is_false}; use conduwuit::{Err, Result, is_false};
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::{FutureExt, future::OptionFuture, join}; use futures::{FutureExt, future::OptionFuture, join};
use ruma::{EventId, RoomId, ServerName}; use ruma::{EventId, RoomId, ServerName};
@@ -10,8 +10,11 @@ pub(super) struct AccessCheck<'a> {
pub(super) event_id: Option<&'a EventId>, pub(super) event_id: Option<&'a EventId>,
} }
#[implement(AccessCheck, params = "<'_>")] impl AccessCheck<'_> {
pub(super) async fn check(&self) -> Result { /// Asserts that the server has access to the room and event (if any).
/// If the server is permitted, `Ok(())` is returned. Otherwise, a Forbidden
/// error is returned.
pub(super) async fn assert(&self) -> Result {
let acl_check = self let acl_check = self
.services .services
.rooms .rooms
@@ -59,3 +62,4 @@ pub(super) async fn check(&self) -> Result {
Ok(()) Ok(())
} }
}
+2 -2
View File
@@ -11,8 +11,8 @@ pub(crate) async fn get_server_version_route(
) -> Result<get_server_version::v1::Response> { ) -> Result<get_server_version::v1::Response> {
Ok(assign!(get_server_version::v1::Response::new(), { Ok(assign!(get_server_version::v1::Response::new(), {
server: Some(assign!(get_server_version::v1::Server::new(), { server: Some(assign!(get_server_version::v1::Server::new(), {
name: Some(conduwuit::version::name().into()), name: Some(conduwuit::BRANDING.into()),
version: Some(conduwuit::version::version().into()), version: Some(conduwuit::version().into()),
})), })),
})) }))
} }
+18 -20
View File
@@ -10,7 +10,7 @@ use std::{
}; };
use super::Config; use super::Config;
use crate::{Result, implement}; use crate::Result;
/// The configuration manager is an indirection to reload the configuration for /// The configuration manager is an indirection to reload the configuration for
/// the server while it is running. In order to not burden or clutter the many /// the server while it is running. In order to not burden or clutter the many
@@ -39,26 +39,8 @@ impl Manager {
active: AtomicPtr::new(Arc::into_raw(config).cast_mut()), active: AtomicPtr::new(Arc::into_raw(config).cast_mut()),
} }
} }
}
impl Drop for Manager {
fn drop(&mut self) {
let config = self.active.swap(null_mut(), Ordering::AcqRel);
// SAFETY: The active pointer was set using an Arc::into_raw(). We're obliged to
// reconstitute that into Arc otherwise it will leak.
unsafe { Arc::from_raw(config) };
}
}
impl Deref for Manager {
type Target = Arc<Config>;
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
}
/// Update the active configuration, returning prior configuration. /// Update the active configuration, returning prior configuration.
#[implement(Manager)]
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all, level = "info")]
pub fn update(&self, config: Config) -> Result<Arc<Config>> { pub fn update(&self, config: Config) -> Result<Arc<Config>> {
let config = Arc::new(config); let config = Arc::new(config);
@@ -70,7 +52,6 @@ pub fn update(&self, config: Config) -> Result<Arc<Config>> {
Ok(unsafe { Arc::from_raw(old) }) Ok(unsafe { Arc::from_raw(old) })
} }
#[implement(Manager)]
fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> { fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
let config = self.active.load(Ordering::Acquire); let config = self.active.load(Ordering::Acquire);
@@ -100,6 +81,23 @@ fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
// of this scenario are thus astronomical. // of this scenario are thus astronomical.
unsafe { std::mem::transmute(config) } unsafe { std::mem::transmute(config) }
} }
}
impl Drop for Manager {
fn drop(&mut self) {
let config = self.active.swap(null_mut(), Ordering::AcqRel);
// SAFETY: The active pointer was set using an Arc::into_raw(). We're obliged to
// reconstitute that into Arc otherwise it will leak.
unsafe { Arc::from_raw(config) };
}
}
impl Deref for Manager {
type Target = Arc<Config>;
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
}
#[tracing::instrument( #[tracing::instrument(
name = "miss", name = "miss",
+81 -13
View File
@@ -4,7 +4,7 @@ pub mod manager;
pub mod proxy; pub mod proxy;
use std::{ use std::{
collections::{BTreeMap, BTreeSet, HashMap}, collections::{BTreeMap, BTreeSet},
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
path::PathBuf, path::PathBuf,
}; };
@@ -655,19 +655,25 @@ pub struct Config {
/// even if `recaptcha_site_key` is set. /// even if `recaptcha_site_key` is set.
pub recaptcha_private_site_key: Option<String>, pub recaptcha_private_site_key: Option<String>,
/// Policy documents, such as terms and conditions or a privacy policy, /// display: nested
/// which users must agree to when registering an account.
///
/// Example:
/// ```ignore
/// [global.registration_terms.privacy_policy]
/// en = { name = "Privacy Policy", url = "https://homeserver.example/en/privacy_policy.html" }
/// es = { name = "Política de Privacidad", url = "https://homeserver.example/es/privacy_policy.html" }
/// ```
///
/// default: {}
#[serde(default)] #[serde(default)]
pub registration_terms: HashMap<String, HashMap<String, TermsDocument>>, pub registration_terms: RegistrationTerms,
/// display: nested
#[serde(default)]
pub oauth: OauthConfig,
/// Controls whether users are allowed to deactivate their own accounts
/// through the account management panel or their Matrix clients. Server
/// admins can always deactivate users using the relevant admin commands.
///
/// Note that, in some jurisdictions, you may be legally required to honor
/// users who request to deactivate their accounts if you set this option
/// to `false`.
///
/// default: true
#[serde(default = "true_fn")]
pub allow_deactivation: bool,
/// Controls whether encrypted rooms and events are allowed. /// Controls whether encrypted rooms and events are allowed.
#[serde(default = "true_fn")] #[serde(default = "true_fn")]
@@ -2351,6 +2357,29 @@ pub struct SmtpConfig {
pub require_email_for_token_registration: bool, pub require_email_for_token_registration: bool,
} }
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.registration_terms",
optional = "true"
)]
pub struct RegistrationTerms {
/// The language code to provide to clients along with the policy documents.
///
/// default: "en"
#[serde(default = "default_terms_language")]
pub language: String,
/// Policy documents, such as terms and conditions or a privacy policy,
/// which users must agree to when registering an account.
///
/// Example:
/// ```ignore
/// [global.registration_terms.documents]
/// privacy_policy = { name = "Privacy Policy", url = "https://homeserver.example/en/privacy_policy.html" }
/// ```
pub documents: BTreeMap<String, TermsDocument>,
}
/// A policy document for use with a m.login.terms stage. /// A policy document for use with a m.login.terms stage.
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TermsDocument { pub struct TermsDocument {
@@ -2358,6 +2387,43 @@ pub struct TermsDocument {
pub url: String, pub url: String,
} }
#[derive(Clone, Debug, Default, Deserialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.oauth",
optional = "true"
)]
pub struct OauthConfig {
/// The compatibility mode to use for OAuth.
///
/// - "disabled": OAuth will be unavailable. Users will only be able to log
/// in using legacy authentication.
/// - "hybrid": OAuth and legacy authentication will both be available. Some
/// clients may only use one or the other.
/// - "exclusive": Only OAuth will be available. Clients which require
/// legacy authentication will be unable to log in.
///
/// default: "hybrid"
pub compatibility_mode: OAuthMode,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuthMode {
Disabled,
#[default]
Hybrid,
Exclusive,
}
impl OAuthMode {
#[must_use]
pub fn uiaa_available(&self) -> bool { matches!(self, Self::Disabled | Self::Hybrid) }
#[must_use]
pub fn oauth_available(&self) -> bool { matches!(self, Self::Hybrid | Self::Exclusive) }
}
const DEPRECATED_KEYS: &[&str] = &[ const DEPRECATED_KEYS: &[&str] = &[
"cache_capacity", "cache_capacity",
"conduit_cache_capacity_modifier", "conduit_cache_capacity_modifier",
@@ -2738,3 +2804,5 @@ fn default_client_response_timeout() -> u64 { 120 }
fn default_client_shutdown_timeout() -> u64 { 15 } fn default_client_shutdown_timeout() -> u64 { 15 }
fn default_sender_shutdown_timeout() -> u64 { 5 } fn default_sender_shutdown_timeout() -> u64 { 5 }
fn default_terms_language() -> String { "en".to_owned() }
+1
View File
@@ -161,6 +161,7 @@ impl Error {
match self { match self {
| Self::Federation(origin, error) => format!("Answer from {origin}: {error}"), | Self::Federation(origin, error) => format!("Answer from {origin}: {error}"),
| Self::Ruma(error) => response::ruma_error_message(error), | Self::Ruma(error) => response::ruma_error_message(error),
| Self::Request(_, message, _) => message.clone().into_owned(),
| _ => format!("{self}"), | _ => format!("{self}"),
} }
} }
+1 -4
View File
@@ -73,11 +73,8 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
// 413 // 413
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE, | TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
// 405
| Unrecognized => StatusCode::METHOD_NOT_ALLOWED,
// 404 // 404
| NotFound => StatusCode::NOT_FOUND, | Unrecognized | NotFound => StatusCode::NOT_FOUND,
// 403 // 403
| GuestAccessForbidden | GuestAccessForbidden
+6 -9
View File
@@ -7,19 +7,16 @@
use std::sync::OnceLock; use std::sync::OnceLock;
static BRANDING: &str = "continuwuity"; pub const BRANDING: &str = "continuwuity";
static WEBSITE: &str = "https://continuwuity.org"; pub const ROUTE_PREFIX: &str = "/_continuwuity";
static SEMANTIC: &str = env!("CARGO_PKG_VERSION"); pub const WEBSITE: &str = "https://continuwuity.org";
pub const SEMANTIC: &str = env!("CARGO_PKG_VERSION");
static VERSION: OnceLock<String> = OnceLock::new(); static VERSION: OnceLock<String> = OnceLock::new();
static VERSION_UA: OnceLock<String> = OnceLock::new(); static VERSION_UA: OnceLock<String> = OnceLock::new();
static USER_AGENT: OnceLock<String> = OnceLock::new(); static USER_AGENT: OnceLock<String> = OnceLock::new();
static USER_AGENT_MEDIA: OnceLock<String> = OnceLock::new(); static USER_AGENT_MEDIA: OnceLock<String> = OnceLock::new();
#[inline]
#[must_use]
pub fn name() -> &'static str { BRANDING }
#[inline] #[inline]
pub fn version() -> &'static str { VERSION.get_or_init(init_version) } pub fn version() -> &'static str { VERSION.get_or_init(init_version) }
@@ -32,10 +29,10 @@ pub fn user_agent() -> &'static str { USER_AGENT.get_or_init(init_user_agent) }
#[inline] #[inline]
pub fn user_agent_media() -> &'static str { USER_AGENT_MEDIA.get_or_init(init_user_agent_media) } pub fn user_agent_media() -> &'static str { USER_AGENT_MEDIA.get_or_init(init_user_agent_media) }
fn init_user_agent() -> String { format!("{}/{} (bot; +{WEBSITE})", name(), version_ua()) } fn init_user_agent() -> String { format!("{BRANDING}/{} (bot; +{WEBSITE})", version_ua()) }
fn init_user_agent_media() -> String { fn init_user_agent_media() -> String {
format!("{}/{} (embedbot; facebookexternalhit/1.1; +{WEBSITE})", name(), version_ua()) format!("{BRANDING}/{} (embedbot; facebookexternalhit/1.1; +{WEBSITE})", version_ua())
} }
fn init_version_ua() -> String { fn init_version_ua() -> String {
+6 -4
View File
@@ -1,9 +1,9 @@
use ruma::{RoomVersionId, canonical_json::redact_content_in_place}; use ruma::{RoomVersionId, canonical_json::redact_content_in_place};
use serde_json::{Value as JsonValue, json, value::to_raw_value}; use serde_json::{Value as JsonValue, json, value::to_raw_value};
use crate::{Err, Result, err, implement}; use crate::{Err, Result, err};
#[implement(super::Pdu)] impl super::Pdu {
pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) -> Result { pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) -> Result {
let Some(rules) = room_version_id.rules() else { let Some(rules) = room_version_id.rules() else {
return Err!("Cannot redact event for unknown room version {room_version_id}"); return Err!("Cannot redact event for unknown room version {room_version_id}");
@@ -11,8 +11,9 @@ pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) ->
self.unsigned = None; self.unsigned = None;
let mut content = serde_json::from_str(self.content.get()) let mut content = serde_json::from_str(self.content.get()).map_err(|e| {
.map_err(|e| err!(Request(BadJson("Failed to deserialize content into type: {e}"))))?; err!(Request(BadJson("Failed to deserialize content into type: {e}")))
})?;
redact_content_in_place(&mut content, &rules.redaction, self.kind.to_string()); redact_content_in_place(&mut content, &rules.redaction, self.kind.to_string());
@@ -30,3 +31,4 @@ pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) ->
Ok(()) Ok(())
} }
}
+6 -8
View File
@@ -4,14 +4,14 @@ use ruma::MilliSecondsSinceUnixEpoch;
use serde_json::value::{RawValue as RawJsonValue, Value as JsonValue, to_raw_value}; use serde_json::value::{RawValue as RawJsonValue, Value as JsonValue, to_raw_value};
use super::Pdu; use super::Pdu;
use crate::{Result, err, implement, result::LogErr}; use crate::{Result, err, result::LogErr};
impl Pdu {
/// Set the `unsigned` field of the PDU using only information in the PDU. /// Set the `unsigned` field of the PDU using only information in the PDU.
/// Some unsigned data is already set within the database (eg. prev events, /// Some unsigned data is already set within the database (eg. prev events,
/// threads). Once this is done, other data must be calculated from the database /// threads). Once this is done, other data must be calculated from the
/// (eg. relations) This is for server-to-client events. /// database (eg. relations) This is for server-to-client events.
/// Backfill handles this itself. /// Backfill handles this itself.
#[implement(Pdu)]
pub fn set_unsigned(&mut self, user_id: Option<&ruma::UserId>) { pub fn set_unsigned(&mut self, user_id: Option<&ruma::UserId>) {
if Some(self.sender.borrow()) != user_id { if Some(self.sender.borrow()) != user_id {
self.remove_transaction_id().log_err().ok(); self.remove_transaction_id().log_err().ok();
@@ -19,7 +19,6 @@ pub fn set_unsigned(&mut self, user_id: Option<&ruma::UserId>) {
self.add_age().log_err().ok(); self.add_age().log_err().ok();
} }
#[implement(Pdu)]
pub fn remove_transaction_id(&mut self) -> Result { pub fn remove_transaction_id(&mut self) -> Result {
use BTreeMap as Map; use BTreeMap as Map;
@@ -38,7 +37,6 @@ pub fn remove_transaction_id(&mut self) -> Result {
Ok(()) Ok(())
} }
#[implement(Pdu)]
pub fn add_age(&mut self) -> Result { pub fn add_age(&mut self) -> Result {
use BTreeMap as Map; use BTreeMap as Map;
@@ -60,8 +58,7 @@ pub fn add_age(&mut self) -> Result {
Ok(()) Ok(())
} }
#[implement(Pdu)] pub fn add_relation(&mut self, name: &str, pdu: Option<&Self>) -> Result {
pub fn add_relation(&mut self, name: &str, pdu: Option<&Pdu>) -> Result {
use serde_json::Map; use serde_json::Map;
let mut unsigned: Map<String, JsonValue> = self let mut unsigned: Map<String, JsonValue> = self
@@ -86,3 +83,4 @@ pub fn add_relation(&mut self, name: &str, pdu: Option<&Pdu>) -> Result {
Ok(()) Ok(())
} }
}
+3
View File
@@ -21,6 +21,8 @@ pub fn versions() -> Vec<String> {
"v1.12".to_owned(), "v1.12".to_owned(),
"v1.13".to_owned(), "v1.13".to_owned(),
"v1.14".to_owned(), "v1.14".to_owned(),
"v1.15".to_owned(),
"v1.16".to_owned(),
] ]
} }
@@ -43,5 +45,6 @@ pub fn unstable_features() -> BTreeMap<String, bool> {
("uk.timedout.msc4323".to_owned(), true), /* agnostic suspend (https://github.com/matrix-org/matrix-spec-proposals/pull/4323) */ ("uk.timedout.msc4323".to_owned(), true), /* agnostic suspend (https://github.com/matrix-org/matrix-spec-proposals/pull/4323) */
("org.matrix.msc4155".to_owned(), true), /* invite filtering (https://github.com/matrix-org/matrix-spec-proposals/pull/4155) */ ("org.matrix.msc4155".to_owned(), true), /* invite filtering (https://github.com/matrix-org/matrix-spec-proposals/pull/4155) */
("computer.gingershaped.msc4466".to_owned(), true), /* profile change propagation (https://github.com/matrix-org/matrix-spec-proposals/pull/4466) */ ("computer.gingershaped.msc4466".to_owned(), true), /* profile change propagation (https://github.com/matrix-org/matrix-spec-proposals/pull/4466) */
("org.matrix.msc4380.stable".to_owned(), true),
]) ])
} }
+2 -5
View File
@@ -34,14 +34,11 @@ pub use ::tracing;
pub use conduwuit_build_metadata as build_metadata; pub use conduwuit_build_metadata as build_metadata;
pub use config::Config; pub use config::Config;
pub use error::Error; pub use error::Error;
pub use info::{ pub use info::version::*;
version,
version::{name, version},
};
pub use matrix::{Event, EventTypeExt, Pdu, PduCount, PduEvent, PduId, pdu, state_res}; pub use matrix::{Event, EventTypeExt, Pdu, PduCount, PduEvent, PduId, pdu, state_res};
pub use parking_lot::{Mutex as SyncMutex, RwLock as SyncRwLock}; pub use parking_lot::{Mutex as SyncMutex, RwLock as SyncRwLock};
pub use server::Server; pub use server::Server;
pub use utils::{implement, result, result::Result}; pub use utils::{result, result::Result};
pub use crate as conduwuit_core; pub use crate as conduwuit_core;
-2
View File
@@ -22,8 +22,6 @@ mod tests;
pub mod time; pub mod time;
pub mod with_lock; pub mod with_lock;
pub use ::conduwuit_macros::implement;
pub use self::{ pub use self::{
arrayvec::ArrayVecExt, arrayvec::ArrayVecExt,
bool::BoolExt, bool::BoolExt,
+16 -10
View File
@@ -61,17 +61,23 @@ pub fn format(ts: SystemTime, str: &str) -> String {
pub fn pretty(d: Duration) -> String { pub fn pretty(d: Duration) -> String {
use Unit::*; use Unit::*;
let fmt = |w, f, u| format!("{w}.{f} {u}"); let fmt = |w, u| {
let gen64 = |w, f, u| fmt(w, (f * 100.0) as u32, u); if w == 1 {
let gen128 = |w, f, u| gen64(u64::try_from(w).expect("u128 to u64"), f, u); format!("{w} {u}")
} else {
format!("{w} {u}s")
}
};
let gen64 = |w, u| fmt(w, u);
let gen128 = |w, u| gen64(u64::try_from(w).expect("u128 to u64"), u);
match whole_and_frac(d) { match whole_and_frac(d) {
| (Days(whole), frac) => gen64(whole, frac, "days"), | (Days(whole), _) => gen64(whole, "day"),
| (Hours(whole), frac) => gen64(whole, frac, "hours"), | (Hours(whole), _) => gen64(whole, "hour"),
| (Mins(whole), frac) => gen64(whole, frac, "minutes"), | (Mins(whole), _) => gen64(whole, "minute"),
| (Secs(whole), frac) => gen64(whole, frac, "seconds"), | (Secs(whole), _) => gen64(whole, "second"),
| (Millis(whole), frac) => gen128(whole, frac, "milliseconds"), | (Millis(whole), _) => gen128(whole, "millisecond"),
| (Micros(whole), frac) => gen128(whole, frac, "microseconds"), | (Micros(whole), _) => gen128(whole, "microsecond"),
| (Nanos(whole), frac) => gen128(whole, frac, "nanoseconds"), | (Nanos(whole), _) => gen128(whole, "nanosecond"),
} }
} }
@@ -27,3 +27,12 @@ pub fn continue_exponential_backoff(
let min = cmp::min(min, max); let min = cmp::min(min, max);
elapsed < min elapsed < min
} }
/// Determines the minimum number of backoff seconds
#[must_use]
pub fn min_exp_backoff_duration(min: u64, max: u64, retries: u32) -> Duration {
let min = Duration::from_secs(min)
.saturating_mul(retries)
.saturating_mul(retries);
Duration::from_secs(max).min(min)
}
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff. Show more