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
Ginger 0932c929c3 chore: Clippy fixes >:( 2026-06-16 12:36:24 -04:00
Ginger 8f4e95b4b9 fix: Fix compile errors caused by hickory upgrade 2026-06-16 12:19:37 -04:00
Renovate Bot e84d1f02af chore(deps): lock file maintenance 2026-06-16 12:57:54 +00:00
Renovate Bot 772a326ac1 chore(deps): update hickory-dns monorepo to 0.26.0 2026-06-16 12:51:12 +00:00
Renovate Bot 6276a632cc chore(deps): update github-actions-digest 2026-06-16 05:02:02 +00:00
ginger bb48bd50bb chore: Prek fixes 2026-06-15 16:59:57 +00:00
Cease 3fb7586875 docs: remove network tags from config and improve clarity on comments 2026-06-15 16:59:57 +00:00
Cease e8cfde49ae docs: additional livekit caddy-docker-proxy cleanup 2026-06-15 16:59:57 +00:00
Cease 7af4b392b3 docs: clean up caddy-docker-proxy section as requested 2026-06-15 16:59:57 +00:00
Cease 2bdc498f18 docs: add example caddy-docker-proxy configuration 2026-06-15 16:59:57 +00:00
Renovate Bot 9dfd143cc6 chore(deps): update dependency cargo-bins/cargo-binstall to v1.20.0 2026-06-15 13:01:48 +00:00
Renovate Bot 721ebbf340 chore(deps): update rust-non-major 2026-06-15 13:01:35 +00:00
Renovate Bot 0a5d136a32 chore(deps): update github-actions-non-major to v43.222.1 2026-06-15 05:03:07 +00:00
Jonathan Bouligny 0ece17b6a0 fix: Trim whitespace in is_admin_command
Lets users run commands even with a space before the !admin prefix.
2026-06-11 15:20:34 +00:00
Renovate Bot 7d945bbd5d chore(deps): update rust-zerover-patch-updates 2026-06-08 13:31:37 +00:00
Renovate Bot 42039b2090 chore(deps): update rust crate serde_regex to v1.2.0 2026-06-08 13:31:07 +00:00
Renovate Bot dd7ca6b12e chore(deps): update node-patch-updates to v2.0.14 2026-06-08 05:09:52 +00:00
Renovate Bot b1c6be012a chore(deps): update ghcr.io/renovatebot/renovate docker tag to v43.214.6 2026-06-08 05:03:29 +00:00
Renovate Bot 835308628e chore(deps): update pre-commit hook crate-ci/typos to v1.47.2 2026-06-04 05:03:57 +00:00
renovate c1486f425e chore(Nix): Updated flake hashes 2026-06-03 03:15:35 +00:00
Renovate Bot c80896dcb0 chore(deps): update rust to v1.96.0 2026-06-03 03:15:35 +00:00
Renovate Bot 77b12692bb chore(deps): update rust-non-major 2026-06-03 03:12:24 +00:00
Renovate Bot 57237e831a chore(deps): update rust-zerover-patch-updates 2026-06-03 03:11:53 +00:00
nex d62c48ebf7 chore: Update GitHub username in FUNDING.yml 2026-06-02 18:28:09 +00:00
timedout e2e85b962a style: Resolve lint failure 2026-06-02 16:35:32 +01:00
Helix K 788697d563 chore: News fragment 2026-06-02 16:35:32 +01:00
Helix K 64ecd762be chore: Remove MSC4373 support 2026-06-02 16:35:31 +01:00
Renovate Bot 5cb0db6f31 chore(deps): update github-actions-digest 2026-06-02 05:03:05 +00:00
Henry-Hiles 58e41d48c7 fix: grammar in delete all media command not found error 2026-06-01 13:40:44 -04:00
Renovate Bot 67466b015b chore(deps): update ghcr.io/renovatebot/renovate docker tag to v43.205.3 2026-06-01 05:03:05 +00:00
Renovate Bot 0ea68f27a2 chore(deps): update pre-commit hook crate-ci/typos to v1.47.0 2026-05-29 05:06:07 +00:00
Ginger a3e57dbab4 fix: Add unstable feature flag 2026-05-28 20:14:22 +00:00
Ginger 7ece15bb1a chore: News fragment 2026-05-28 20:14:22 +00:00
Ginger 336b32dead feat: Add support for MSC4466 2026-05-28 20:14:22 +00:00
timedout 1faa09b6ce fix: Don't ping presence for devices which claim to be offline
Fixes https://github.com/gomuks/gomuks/issues/722.

Reviewed-by: Ginger <ginger@gingershaped.computer>
2026-05-28 09:38:32 -04:00
Ginger d7a51c7107 refactor: Allow for client identities with no user ID 2026-05-27 12:15:16 -04:00
Ginger 30c9d6d2df chore: Clippy fixes 2026-05-26 18:26:02 +00:00
Ginger 74841b6711 refactor: Represent route auth information in the type system 2026-05-26 18:26:02 +00:00
timedout dabbdc7517 fix: Don't be so aggressive when validating policy server signatures 2026-05-26 16:16:48 +01:00
361 changed files with 24271 additions and 18561 deletions

No files matched your search

@@ -75,7 +75,7 @@ runs:
- name: Set up QEMU - name: Set up QEMU
if: ${{ env.BUILDKIT_ENDPOINT == '' }} if: ${{ env.BUILDKIT_ENDPOINT == '' }}
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4 uses: docker/setup-qemu-action@06116385d9baf250c9f4dcb4858b16962ea869c3 # v4
- name: Login to builtin registry - name: Login to builtin registry
if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }} if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }}
+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@920ab1831fbf4fb3ef75c8ead83556c918bb7290 # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@c70ad64367908075211b10dcd2ab9fad4bfa1816 # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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.195.3@sha256:868dffc3d6a46f42dfefe48b6978cc063d8df9c1d58a93a694c8989afa503e34 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # 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
+1 -1
View File
@@ -1,4 +1,4 @@
github: [JadedBlueEyes, nexy7574, gingershaped] github: [JadedBlueEyes, timedoutuk, gingershaped]
custom: custom:
- https://timedout.uk/donate.html - https://timedout.uk/donate.html
- https://jade.ellis.link/sponsors - https://jade.ellis.link/sponsors
+1 -1
View File
@@ -24,7 +24,7 @@ repos:
- id: check-added-large-files - id: check-added-large-files
- repo: https://github.com/crate-ci/typos - repo: https://github.com/crate-ci/typos
rev: v1.46.2 rev: v1.47.2
hooks: hooks:
- id: typos - id: typos
- id: typos - id: typos
Generated
+375 -210
View File
File diff suppressed because it is too large. Load diff
+10 -7
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]
@@ -296,7 +296,7 @@ default-features = false
features = ["env", "toml"] features = ["env", "toml"]
[workspace.dependencies.hickory-resolver] [workspace.dependencies.hickory-resolver]
version = "0.25.2" version = "0.26.0"
default-features = false default-features = false
features = [ features = [
"serde", "serde",
@@ -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?
@@ -344,7 +344,7 @@ version = "1.1.1"
[workspace.dependencies.ruma] [workspace.dependencies.ruma]
# version = "0.14.1" # version = "0.14.1"
git = "https://github.com/ruma/ruma.git" git = "https://github.com/ruma/ruma.git"
rev = "9c9dccc93f054bbd28f23f630223fffa6289ecbc" rev = "3ecd80b92794d2d93f657a7b3db62d4be237526b"
features = [ features = [
"appservice-api-c", "appservice-api-c",
"client-api", "client-api",
@@ -373,12 +373,12 @@ features = [
"unstable-msc4195", "unstable-msc4195",
"unstable-msc4203", "unstable-msc4203",
"unstable-msc4310", "unstable-msc4310",
"unstable-msc4373",
"unstable-msc4380", "unstable-msc4380",
"unstable-msc4143", "unstable-msc4143",
"unstable-msc4293", "unstable-msc4293",
"unstable-msc4406", "unstable-msc4406",
"unstable-msc4439", "unstable-msc4439",
"unstable-msc4466",
"unstable-extensible-events", "unstable-extensible-events",
] ]
@@ -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 support for MSC4466, which allows clients to customize how changes to a user's global profile are propagated. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Devices which set their presence as "offline" will no longer be considered for presence updates. Contributed by @timedout.
+1
View File
@@ -0,0 +1 @@
Added example configuration using caddy-docker-proxy in the livekit setup section of the docs. Contributed by @Cease
+1
View File
@@ -0,0 +1 @@
Fixed admin commands being ignored when they had leading whitespace before admin commands. Contributed by @kitvonsnookerz.
+1
View File
@@ -0,0 +1 @@
Remove support for MSC4373, as the MSC is now closed. Contributed by @vel.
+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.19.1 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.19.1 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
+69
View File
@@ -187,6 +187,75 @@ All paths should be forwarded to LiveKit by default, with the exception of the f
``` ```
</details> </details>
<details>
<summary>Example docker compose file with caddy-docker-proxy labels</summary>
```yaml
# This setup assumes all containers share the same bridge network
services:
lk-jwt-service:
image: ghcr.io/element-hq/lk-jwt-service:latest
container_name: lk-jwt-service
# lk-jwt-service environment config here..
labels:
caddy: livekit.example.com
caddy.@lk-jwt-service.path: "/sfu/get* /healthz* /get_token*"
caddy.reverse_proxy: "@lk-jwt-service {{upstreams 8081}}"
livekit:
image: livekit/livekit-server:latest
container_name: livekit
command: --config /etc/livekit.yaml
restart: unless-stopped
labels:
caddy: livekit.example.com
caddy.reverse_proxy: "{{upstreams 7880}}"
volumes:
- ./livekit.yaml:/etc/livekit.yaml:ro
ports:
- "127.0.0.1:7880:7880/tcp"
- "7881:7881/tcp"
- "50100-50200:50100-50200/udp"
caddy:
image: lucaslorentz/caddy-docker-proxy:ci-alpine
ports:
- 80:80
- 443:443
environment:
- CADDY_INGRESS_NETWORKS=caddy
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data:/data
restart: unless-stopped
labels:
# If you already configured `[global.well_known]` with Continuwuity,
# comment out the *_respond labels and add this line
# caddy.reverse_proxy: /.well-known/matrix/* homeserver:8008
caddy.1_respond: /.well-known/matrix/server {"m.server":"matrix.example.com:443"}
caddy.2_respond: /.well-known/matrix/client {"m.server":{"base_url":"https://matrix.example.com"},"m.homeserver":{"base_url":"https://matrix.example.com"},"org.matrix.msc4143.rtc_foci":[{"type":"livekit","livekit_service_url":"https://livekit.example.com"}]}
# If you are having problems with continuwuity serving headers uncomment
# the header section below.
# caddy: example.com
# caddy.0_header: "*"
# caddy.0_header.Access-Control-Allow-Origin: "*"
# caddy.0_header.Access-Control-Allow-Methods: "GET, POST, OPTIONS"
# caddy.0_header.Access-Control-Allow-Headers: "Authorization"
# caddy.0_header.Content-Type: "application/json"
homeserver:
image: forgejo.ellis.link/continuwuation/continuwuity:latest
restart: unless-stopped
# add additional environment, volume, and network config here...
labels:
caddy: matrix.example.com
caddy.reverse_proxy: "{{upstreams 8008}}"
```
</details>
### 6. Start Everything ### 6. Start Everything
+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
Generated
+18 -18
View File
@@ -3,11 +3,11 @@
"advisory-db": { "advisory-db": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1779575509, "lastModified": 1781566179,
"narHash": "sha256-wXKYURZz76ZC5lbuDA1oVQA/MxSB3pSJ1raF1HG0oIc=", "narHash": "sha256-Tqv8I586fYzWpEW/Smq/JqESFa3DVVzVWsnAMtvhy/I=",
"owner": "rustsec", "owner": "rustsec",
"repo": "advisory-db", "repo": "advisory-db",
"rev": "831c50f4a4304068f125e603add6a8839f08b3eb", "rev": "74e084413d979d52d2f93b1d93b1ab7b9ee648f5",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -18,11 +18,11 @@
}, },
"crane": { "crane": {
"locked": { "locked": {
"lastModified": 1779130139, "lastModified": 1780532242,
"narHash": "sha256-BLrtr42azquO7MdGFU5a7KiMl3YpFlTeIXqy1fT5GlQ=", "narHash": "sha256-D+BsdpxmtUwtqGoY0IXPhHgTlmqgcZKCEo1oMyn7ep0=",
"owner": "ipetkov", "owner": "ipetkov",
"repo": "crane", "repo": "crane",
"rev": "edb38893982a3338972bb4a2ec7ce7c29ba10fd9", "rev": "59a82a1222dd3b2080b5cc52a1a2e8d5f1b77f37",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -39,11 +39,11 @@
"rust-analyzer-src": "rust-analyzer-src" "rust-analyzer-src": "rust-analyzer-src"
}, },
"locked": { "locked": {
"lastModified": 1779612045, "lastModified": 1781527054,
"narHash": "sha256-+7lfNVnmXJDkiRYHd5NoNwYoyUcc0LcXPaIJqjO7VWM=", "narHash": "sha256-1fX9ev2Fh5QoKQ41G9dYutjo5j/jywu6tZse5Eb1Ck4=",
"owner": "nix-community", "owner": "nix-community",
"repo": "fenix", "repo": "fenix",
"rev": "d7be747f0a65af378de515fc3cee131bf99a008f", "rev": "8c2e51dffefc040a21975da7abf6f252c8c9b783",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -89,11 +89,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1779508470, "lastModified": 1781074563,
"narHash": "sha256-Ap9KJX+5xHIn3bPIpfNgT6MEXdAECECwo4/rmlQD74M=", "narHash": "sha256-md8WlXOlfnIeHeOScMTTHFyf2d6iaTwPl2apR5EQ3P4=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "29916453413845e54a65b8a1cf996842300cd299", "rev": "9ae611a455b90cf061d8f332b977e387bda8e1ca",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -132,11 +132,11 @@
"rust-analyzer-src": { "rust-analyzer-src": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1779569060, "lastModified": 1781453968,
"narHash": "sha256-NSnk5D+3KEfRdbgPijs33N2RAKSG6A74SwfnynLcouo=", "narHash": "sha256-+V3nK4pCngbmgyVGXY6Kkrlevp4ocPkJJLf2aqwkDNA=",
"owner": "rust-lang", "owner": "rust-lang",
"repo": "rust-analyzer", "repo": "rust-analyzer",
"rev": "987ea33645ab1c709b1df6823038abcb2fe8973e", "rev": "cc272809a173c2c11d0e479d639c811c1eacf049",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -153,11 +153,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1775636079, "lastModified": 1780220602,
"narHash": "sha256-pc20NRoMdiar8oPQceQT47UUZMBTiMdUuWrYu2obUP0=", "narHash": "sha256-eynAfOmbmxJnkp7YewvCEbShNnnYJ9gLLqkzsYtBPeM=",
"owner": "numtide", "owner": "numtide",
"repo": "treefmt-nix", "repo": "treefmt-nix",
"rev": "790751ff7fd3801feeaf96d7dc416a8d581265ba", "rev": "db947814a175b7ca6ded66e21383d938df01c227",
"type": "github" "type": "github"
}, },
"original": { "original": {
-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
+29 -28
View File
@@ -1,7 +1,6 @@
{ { inputs, ... }: {
perSystem = perSystem =
{ {
craneLib,
self', self',
lib, lib,
pkgs, pkgs,
@@ -9,34 +8,36 @@
}: }:
{ {
# 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 =
packages = [ (inputs.crane.mkLib pkgs).overrideToolchain (pkgs: self'.packages.stable-toolchain).devShell
self'.packages.rocksdb {
pkgs.nodejs packages = [
pkgs.pkg-config self'.packages.rocksdb
] pkgs.nodejs
++ lib.optionals pkgs.stdenv.isLinux [ pkgs.pkg-config
pkgs.liburing
pkgs.rust-jemalloc-sys-unprefixed
];
env = {
LIBCLANG_PATH = lib.makeLibraryPath [ pkgs.llvmPackages.libclang.lib ];
LD_LIBRARY_PATH = lib.makeLibraryPath (
[
pkgs.stdenv.cc.cc.lib
] ]
++ lib.optionals pkgs.stdenv.isLinux [ ++ lib.optionals pkgs.stdenv.isLinux [
pkgs.liburing pkgs.liburing
pkgs.jemalloc pkgs.rust-jemalloc-sys-unprefixed
] ];
);
} env = {
// lib.optionalAttrs pkgs.stdenv.isLinux { LIBCLANG_PATH = lib.makeLibraryPath [ pkgs.llvmPackages.libclang.lib ];
PKG_CONFIG_PATH = lib.makeSearchPath "lib/pkgconfig" [ LD_LIBRARY_PATH = lib.makeLibraryPath (
pkgs.liburing.dev [
]; pkgs.stdenv.cc.cc.lib
}; ]
}; ++ lib.optionals pkgs.stdenv.isLinux [
pkgs.liburing
pkgs.jemalloc
]
);
}
// lib.optionalAttrs pkgs.stdenv.isLinux {
PKG_CONFIG_PATH = lib.makeSearchPath "lib/pkgconfig" [
pkgs.liburing.dev
];
};
};
}; };
} }
+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 [
+74 -21
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
default = pkgs.callPackage ./continuwuity.nix { mkPackages =
inherit self craneLib; pkgs:
inherit (self'.packages) rocksdb; let
# extra features via `cargoExtraArgs` fnx = inputs'.fenix.packages;
cargoExtraArgs = "-F http3";
# extra RUSTFLAGS via `rustflags`
# the stuff below is required for http3
rustflags = "--cfg reqwest_unstable";
};
# 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
# example: different compilation profile and different target_cpu isStatic = pkgs.stdenv.hostPlatform.isMusl;
max-perf-haswell = self'.packages.default.override {
# compiles explicitly for haswell arch cpus craneLib = (inputs.crane.mkLib pkgs).overrideToolchain (
target_cpu = "haswell"; _:
# compiles slower but with more thorough optimizations if isStatic then
profile = "release-max-perf"; 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 {
inherit self craneLib;
liburing = (if isStatic then pkgs.pkgsStatic else pkgs).liburing;
rocksdb = if isStatic then null else self'.packages.rocksdb;
# extra features via `cargoExtraArgs`
cargoExtraArgs = "-F http3";
# extra RUSTFLAGS via `rustflags`
# the stuff below is required for http3
rustflags = "--cfg reqwest_unstable";
};
# 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
max-perf = default.override {
# compiles slower but with more thorough optimizations
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,22 +2,26 @@
{ {
perSystem = perSystem =
{ {
system,
lib, lib,
inputs',
pkgs, pkgs,
... ...
}: }:
let
mkToolchain =
target:
target.fromToolchainName {
name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel;
sha256 = "sha256-mvUGEOHYJpn3ikC5hckneuGixaC+yGrkMM/liDIDgoU=";
};
in
{ {
_module.args = { inherit mkToolchain; };
packages = packages =
let let
fnx = inputs.fenix.packages.${system}; fnx = inputs'.fenix.packages;
stable-toolchain = (mkToolchain fnx).toolchain;
stable-toolchain = fnx.fromToolchainFile {
file = inputs.self + "/rust-toolchain.toml";
# See also `rust-toolchain.toml`
sha256 = "sha256-gh/xTkxKHL4eiRXzWv8KP7vfjSk61Iq48x47BEDFgfk=";
};
in in
{ {
inherit stable-toolchain; inherit stable-toolchain;
+205 -156
View File
@@ -125,14 +125,14 @@
} }
}, },
"node_modules/@rsbuild/core": { "node_modules/@rsbuild/core": {
"version": "2.0.7", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.0.7.tgz", "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.0.15.tgz",
"integrity": "sha512-LsBONEzsjzOAqO72ot39eI7g53zSfF9QuDXTu4ks8IUX+EZsxRSniQfc+1zVA6a6y3b9KUUtG96avoMLKbWklQ==", "integrity": "sha512-O8vmMhZu1YImO6jOqt/K/vlJSvkq7UtSq5YM1DIlcEd9LW8Gf6/dkQ1B2KPI6F+hSMFBnTTTumdcIowSLCw97g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rspack/core": "~2.0.4", "@rspack/core": "~2.0.8",
"@swc/helpers": "^0.5.21" "@swc/helpers": "^0.5.23"
}, },
"bin": { "bin": {
"rsbuild": "bin/rsbuild.js" "rsbuild": "bin/rsbuild.js"
@@ -150,9 +150,9 @@
} }
}, },
"node_modules/@rsbuild/plugin-react": { "node_modules/@rsbuild/plugin-react": {
"version": "2.0.0", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/@rsbuild/plugin-react/-/plugin-react-2.0.0.tgz", "resolved": "https://registry.npmjs.org/@rsbuild/plugin-react/-/plugin-react-2.0.1.tgz",
"integrity": "sha512-/1gzt39EGUSFEqB83g46QoOwsgv172HI18i6au1b6lgIaX4sv9stuX4ijdHbHCp8PqYEq+MyQ99jIQMO6I+etg==", "integrity": "sha512-n5m3VxEm6m3Dv1VkI0WnxsildySJ6M+QjGIzkZDy5UebRCIJ1Q/hlQVyhofBL6C+AcsF9fGjlHQkeiteXJSr3Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -169,28 +169,28 @@
} }
}, },
"node_modules/@rspack/binding": { "node_modules/@rspack/binding": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.0.8.tgz",
"integrity": "sha512-/QeJDPUw/lWkBJESG264KA9u6/rAjvoJhKncU4rkTi5Ap45kue5HTgOzr0ufxKdd2Xl72fjFBuqlKmtFDD5LiQ==", "integrity": "sha512-3uZ+y8aQxq33ty2srMxg2Nu0XuBI6vVrG50rkDaXqwWqOohfgGUSfFuQK7EnSUNy4aFUQlCG6NHialQHJov0wg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optionalDependencies": { "optionalDependencies": {
"@rspack/binding-darwin-arm64": "2.0.4", "@rspack/binding-darwin-arm64": "2.0.8",
"@rspack/binding-darwin-x64": "2.0.4", "@rspack/binding-darwin-x64": "2.0.8",
"@rspack/binding-linux-arm64-gnu": "2.0.4", "@rspack/binding-linux-arm64-gnu": "2.0.8",
"@rspack/binding-linux-arm64-musl": "2.0.4", "@rspack/binding-linux-arm64-musl": "2.0.8",
"@rspack/binding-linux-x64-gnu": "2.0.4", "@rspack/binding-linux-x64-gnu": "2.0.8",
"@rspack/binding-linux-x64-musl": "2.0.4", "@rspack/binding-linux-x64-musl": "2.0.8",
"@rspack/binding-wasm32-wasi": "2.0.4", "@rspack/binding-wasm32-wasi": "2.0.8",
"@rspack/binding-win32-arm64-msvc": "2.0.4", "@rspack/binding-win32-arm64-msvc": "2.0.8",
"@rspack/binding-win32-ia32-msvc": "2.0.4", "@rspack/binding-win32-ia32-msvc": "2.0.8",
"@rspack/binding-win32-x64-msvc": "2.0.4" "@rspack/binding-win32-x64-msvc": "2.0.8"
} }
}, },
"node_modules/@rspack/binding-darwin-arm64": { "node_modules/@rspack/binding-darwin-arm64": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.0.8.tgz",
"integrity": "sha512-0Q1QXFEsZfDc4opiDnb8q50KlBbC2VovViDaYlMJZBzvjAo325mh3itXPfz7YZ31M+TxRE7TUiJXH3ltiV1Hdg==", "integrity": "sha512-vCgbgH7B7qom+uID+RCZsTCOYFb9wC4/4+1U6rMfytrXGVJ72eNQs2tbdjOl0lb18CT3N/n+VkWynUiLk84GwA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -202,9 +202,9 @@
] ]
}, },
"node_modules/@rspack/binding-darwin-x64": { "node_modules/@rspack/binding-darwin-x64": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.0.8.tgz",
"integrity": "sha512-oO5J2QYf7+H+aYRj85EiGrDOoDEE9EDDl7NgXv46iWvIF0wXowEHXqnjMFxHxRq2Vf6scT+0yYQX9blWcvMWAA==", "integrity": "sha512-satPm2PD4B7jDTVlVAdvMVdUszwLvWUEnUDzLb77mvVkezKNDZmuhb+e8s+FfKs8hJpNbZ9VAejuA2rr8o985w==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -216,9 +216,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-arm64-gnu": { "node_modules/@rspack/binding-linux-arm64-gnu": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.0.8.tgz",
"integrity": "sha512-BEk6mIYBK4BihW9qXXITJORrVXecTlkRjrqhgefili4xjXtLdcUnxAm9sN/2oJ8m378n2h33qDh4gr2orPBFWQ==", "integrity": "sha512-pSI+npPQE/uDtiboqvcOIRJbEV2+B+H1xffmko/gw50la92oTUW60kVULFwsb6L0+GVCzIcwX3yq60GtYIn+Ug==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -233,9 +233,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-arm64-musl": { "node_modules/@rspack/binding-linux-arm64-musl": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.0.8.tgz",
"integrity": "sha512-Hyt3z1RwNcSMIoaoWLN4Hb/696/O5JPukf8rXQASvf2UkC+X3ij7tr+8lMSYi3Zysi1QL375CnT4fNoABEW0JA==", "integrity": "sha512-igjJ43yxWQ72GZqjDDZSSHax9/Vg+6rLMmOvFglTJUkQpB4Tyvu/YjW+WRjYj2xRw6blOjLxUSJWASvuSqqlvg==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -250,9 +250,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-x64-gnu": { "node_modules/@rspack/binding-linux-x64-gnu": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.0.8.tgz",
"integrity": "sha512-xHorBPBZAg0Pn9Q0k9dWZ9euowieDxcSOzQ9JhTCmhDY6wZH5M/kCBFlCs/OQeW5/NUArW3x3MwEdO/0QJHMxg==", "integrity": "sha512-zrkoEOnqj1hOEBO5T2I/2Ts2HSJsYFh1qXwMpK4dMJFGGNWDfNeUa6/LF5uq3VINF3JUl7RL47AgrucoSZJXPA==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -267,9 +267,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-x64-musl": { "node_modules/@rspack/binding-linux-x64-musl": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.0.8.tgz",
"integrity": "sha512-QLxEGUXofF0kVNU12Y2NT3Qi9lGs+WbnYpapVeb+2IXtrAXJfU7Rhy7lAp5GLMzYMQNrKKL9SVnTWKbODbNW9Q==", "integrity": "sha512-6CtDaGZjNDvJd9TBp7a9zABbrPORO21W96+3ZcGBn0YNUPUk4ARxIxrTTpeJ/1F41QDM8AYIkGDdqEYMqTYBsA==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -284,9 +284,9 @@
] ]
}, },
"node_modules/@rspack/binding-wasm32-wasi": { "node_modules/@rspack/binding-wasm32-wasi": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.0.8.tgz",
"integrity": "sha512-YhN8HkiH46ONU9tm5dyoXDImDWGpU7E4SPqGI4OyAVF0445uIChurIUmTIOYcD6cg81GGeIjozWJOcb635Dcqw==", "integrity": "sha512-Yf4SiqTUroT5Ju+te0YAY2xxKOb35tECsO21v7hYyGa705wrgoAK/MmF7enOvs9GR1iZIqgiLD/wxsIxl8GjJw==",
"cpu": [ "cpu": [
"wasm32" "wasm32"
], ],
@@ -300,9 +300,9 @@
} }
}, },
"node_modules/@rspack/binding-win32-arm64-msvc": { "node_modules/@rspack/binding-win32-arm64-msvc": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.0.8.tgz",
"integrity": "sha512-MUlYIz82xQRN0aoiXXyEBrNVUwiOSSFRi7nuCgUKduaSdlbPWzCY31IdtOygZ06LVp5JIGUEtyqSrjQq4FrMRw==", "integrity": "sha512-8NCuiQsAhXrwRBy57QZoypqrws/zLBkaQVGiB8hksr6v++8hNigNjqpQARLbd0iyMuHsQQ++8+auGk6xlDXmzw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -314,9 +314,9 @@
] ]
}, },
"node_modules/@rspack/binding-win32-ia32-msvc": { "node_modules/@rspack/binding-win32-ia32-msvc": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.0.8.tgz",
"integrity": "sha512-D7UcIFMzlY2yhhyuW4Ej15gBWmTwUM5DxuObl3Kv31qRv/pmV3MsqUeG5m2dqLbUxzqPH87qnp0cArbkJQ1b+w==", "integrity": "sha512-bxiekytbX7V9KFAra+HkwtNWC6pYfHEBBZFpiT0xUs3mCFOmAAFVBsBSQsoCP9AdCEXoMAvNdnrHNw3iov4OZw==",
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
@@ -328,9 +328,9 @@
] ]
}, },
"node_modules/@rspack/binding-win32-x64-msvc": { "node_modules/@rspack/binding-win32-x64-msvc": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.0.8.tgz",
"integrity": "sha512-MnYKPfdrAEbtpKg/1SZ6cNtzreIRyQJK4APbxLLPXENdTH5QXQkaTjLMKEeJcJ51FRhI/+yNpOUm2oTHdCQ1Og==", "integrity": "sha512-7zPs8YCe/ZVJTwd+5lpB0CP0tkn2pONf/T1ycmVY76u21Nrwt8mXQGc/2yH2eWP4B7fikYBr3hGr7mpR2fajqQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -342,20 +342,20 @@
] ]
}, },
"node_modules/@rspack/core": { "node_modules/@rspack/core": {
"version": "2.0.4", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.0.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.0.8.tgz",
"integrity": "sha512-OuxdQeeKWQpNvFBRDOcnoSaQvp6E4APM/6JJMM/k0p6oL1TEFQVGdNu3VGY4mRAsebnNBXapMVMhj+v66Bn2pg==", "integrity": "sha512-+NLGJf8gZxihDmMFzjlly3toc2SMjeDmuvz0/Cai9AMdV4F+Pqcnt2BA9V4e3SY2jmhJQtPwgyyLtR1RiJO77g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rspack/binding": "2.0.4" "@rspack/binding": "2.0.8"
}, },
"engines": { "engines": {
"node": "^20.19.0 || >=22.12.0" "node": "^20.19.0 || >=22.12.0"
}, },
"peerDependencies": { "peerDependencies": {
"@module-federation/runtime-tools": "^0.24.1 || ^2.0.0", "@module-federation/runtime-tools": "^0.24.1 || ^2.0.0",
"@swc/helpers": ">=0.5.1" "@swc/helpers": "^0.5.23"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
"@module-federation/runtime-tools": { "@module-federation/runtime-tools": {
@@ -383,18 +383,18 @@
} }
}, },
"node_modules/@rspress/core": { "node_modules/@rspress/core": {
"version": "2.0.13", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.13.tgz", "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.15.tgz",
"integrity": "sha512-lbaBA5eqh7wKdH98TUQEI+SfS3Z6YgaNCup3X+ttrYVLOrxN8PJvbedo6fFAcl+wP3XLy6D0pcnnzAgu8y3tdg==", "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.7", "@rsbuild/core": "^2.0.15",
"@rsbuild/plugin-react": "~2.0.0", "@rsbuild/plugin-react": "~2.0.1",
"@rspress/shared": "2.0.13", "@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.13", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.13.tgz", "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.15.tgz",
"integrity": "sha512-dP753ASTvH6eDtSEulcqq2lE/kTSdOWSCw0nzvXG+7atTWTHDp6z47uH3CGD8E78cBuKyEi4OH+U7V0EtCTc0Q==", "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.13", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.13.tgz", "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.15.tgz",
"integrity": "sha512-JtkNlxNuA7BzknKIrLvLQkSk0XVi7OXzrE76ma/cLvleccNWr8LGrHtrac4IrDr+HauK4WKTM2JaHGGHUdOUKw==", "integrity": "sha512-z1hbyGP79ZXdSGJxiWw7ZjmX8qW0q9nXMDxr14cVEg/wdj7ToVzGtZHw0wvTPE0YiKG3BMiGkVNfE1rdOaPXiQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -462,26 +462,26 @@
} }
}, },
"node_modules/@rspress/shared": { "node_modules/@rspress/shared": {
"version": "2.0.13", "version": "2.0.15",
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.13.tgz", "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.15.tgz",
"integrity": "sha512-LmDfr7+MDNWRBbxcNoWkW68A35oRonpDJq2Jlx3L8GCzG4sAsyd6Yw0DebTWAxx7hVOXGMf37nEf1J4aOLEZfg==", "integrity": "sha512-o8aYwEzNuTmWnmKe91ntPv+34u3RbtAe+rcK9XC5MANOlgncwOaCs3bUa8/B1/llwyLoNgrpi+VB9bEiU11ZRQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rsbuild/core": "^2.0.7", "@rsbuild/core": "^2.0.15",
"@shikijs/rehype": "^4.0.2", "@shikijs/rehype": "^4.2.0",
"unified": "^11.0.5" "unified": "^11.0.5"
} }
}, },
"node_modules/@shikijs/core": { "node_modules/@shikijs/core": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.2.0.tgz",
"integrity": "sha512-jLJtSJeuFffqX6/inRE1zqU5aFv2hrszvYgq3OjbAgFRZiWv7abKMDdQzYxuSDfmUPQozZvI/kuy6VMTvnvqTQ==", "integrity": "sha512-Hc87Ab1Ld/vEbZRCbwx344I5v+4RU8CVToUTRkqXL1+TjbuOp9U5Xa0M23V4GEWHxVn+yO5otb+HkQVm3ptWQQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/primitive": "4.1.0", "@shikijs/primitive": "4.2.0",
"@shikijs/types": "4.1.0", "@shikijs/types": "4.2.0",
"@shikijs/vscode-textmate": "^10.0.2", "@shikijs/vscode-textmate": "^10.0.2",
"@types/hast": "^3.0.4", "@types/hast": "^3.0.4",
"hast-util-to-html": "^9.0.5" "hast-util-to-html": "^9.0.5"
@@ -491,13 +491,13 @@
} }
}, },
"node_modules/@shikijs/engine-javascript": { "node_modules/@shikijs/engine-javascript": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.2.0.tgz",
"integrity": "sha512-YquhawCUgaBfhsS72e2Y/dI59gCBNPHu3fEO/tvLaXrTssxZrY5ddjtNLTwndrMgPo8b3IscE+xoICDzpTmlFQ==", "integrity": "sha512-fjETeq1k5ffyXqRgS6+3hpvqseLalp1kjNfRbXpUgWR8FpZ1CmQfiNHovc5lncYjt/Vg5JK/WJEmLahjwMa0og==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/types": "4.1.0", "@shikijs/types": "4.2.0",
"@shikijs/vscode-textmate": "^10.0.2", "@shikijs/vscode-textmate": "^10.0.2",
"oniguruma-to-es": "^4.3.6" "oniguruma-to-es": "^4.3.6"
}, },
@@ -506,13 +506,13 @@
} }
}, },
"node_modules/@shikijs/engine-oniguruma": { "node_modules/@shikijs/engine-oniguruma": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.2.0.tgz",
"integrity": "sha512-axLpjVs45YBvvINa+dJF+NPW+KtFkNXsFr4SDw2BMj9GdeMnGxVB9PQb2xXlJYovslt/nz6giedAyOANkfc7hg==", "integrity": "sha512-hTorK1dffPkpbMUk6Z+828PgRo7d07HbnizoP0hNPFjhxMHctj0Px/qoHeGMYafc6ju+u9iMldN4JbVzNQM++g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/types": "4.1.0", "@shikijs/types": "4.2.0",
"@shikijs/vscode-textmate": "^10.0.2" "@shikijs/vscode-textmate": "^10.0.2"
}, },
"engines": { "engines": {
@@ -520,26 +520,26 @@
} }
}, },
"node_modules/@shikijs/langs": { "node_modules/@shikijs/langs": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.2.0.tgz",
"integrity": "sha512-nwOMruEkbgdZfQ/b8CgpNBVOpvG1k0N5tbmgiFeqsan401+x3ILqlzZJowSla4Agmq4hG2Uf2wh5jLTEhR8VSg==", "integrity": "sha512-bwrVRlJ0wUhZxAbVdvBbv2TTC9yLsh4C/IO5Ofz0T8MQntgDvyVnkbjw9vi50r1kx7RCIJdnJnjZAwmAsXFLZQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/types": "4.1.0" "@shikijs/types": "4.2.0"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
} }
}, },
"node_modules/@shikijs/primitive": { "node_modules/@shikijs/primitive": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.2.0.tgz",
"integrity": "sha512-zx2/2Uwj2q9X3KSyYREEhXO23xBw5WUhP4orK2lE4r+t9JGITmEe0JH+wPmJhqHpOT2bRRs6lAL945+LDvOAGw==", "integrity": "sha512-NOq+DtUkVBJtZMVXL5A0vI0Xk8nvDYaXetFHSJFlOqjDZIVhIPRYFdGkSoElDqNuegikcc3A76SNUa8dTqtAYA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/types": "4.1.0", "@shikijs/types": "4.2.0",
"@shikijs/vscode-textmate": "^10.0.2", "@shikijs/vscode-textmate": "^10.0.2",
"@types/hast": "^3.0.4" "@types/hast": "^3.0.4"
}, },
@@ -548,16 +548,16 @@
} }
}, },
"node_modules/@shikijs/rehype": { "node_modules/@shikijs/rehype": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/rehype/-/rehype-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/rehype/-/rehype-4.2.0.tgz",
"integrity": "sha512-HQwltCcO2/UiFz44/8whyji4rP1VghLu++MgvQn+lQA8/gvuycGkay8DH8o8VAOvLBDKGOkBEw7cC1Cm33GObQ==", "integrity": "sha512-ST3EWye/dwF1gWskczJNBnwFtDzEQ9ceytXZtyc/GfwR5V0qJrkoSGZO55O3SAKDDsXkTDcsfwd9pVe7ROlAHg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/types": "4.1.0", "@shikijs/types": "4.2.0",
"@types/hast": "^3.0.4", "@types/hast": "^3.0.4",
"hast-util-to-string": "^3.0.1", "hast-util-to-string": "^3.0.1",
"shiki": "4.1.0", "shiki": "4.2.0",
"unified": "^11.0.5", "unified": "^11.0.5",
"unist-util-visit": "^5.1.0" "unist-util-visit": "^5.1.0"
}, },
@@ -566,22 +566,22 @@
} }
}, },
"node_modules/@shikijs/themes": { "node_modules/@shikijs/themes": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.2.0.tgz",
"integrity": "sha512-emCcTnUM7yO2wltYbaxm+yLvcCI4+h8XBKc4KmJ7EZUXoSGjcCHifkI//R4OFit9ewpg7H2/9tjOuXrT2v/Knw==", "integrity": "sha512-RX8IHYeLv8Cu2W6ruc3RxUqWn0IYCqSrMBzi/uRGAmfyDNOnNO5BF/Px7o97n4XTpmFTo5GbRaazuOWj+2ak2w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/types": "4.1.0" "@shikijs/types": "4.2.0"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
} }
}, },
"node_modules/@shikijs/types": { "node_modules/@shikijs/types": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.2.0.tgz",
"integrity": "sha512-3EQWX54fMpniOrDblzAhiwiJwpiTMW6+B9DWyUd9ska483tbayFYuw47UxwuPknI31bKnySfVQ/QW+jFL4rFdA==", "integrity": "sha512-VT/MKtlpOhEPZloSH3Pb9WCZEBDoQVMa9jedp5UAwmJOar1DVc9DRODAxmYPW9M93IK4ryuqRejFfmlvlVDemw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -600,9 +600,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@swc/helpers": { "node_modules/@swc/helpers": {
"version": "0.5.21", "version": "0.5.23",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.21.tgz", "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
"integrity": "sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg==", "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
@@ -668,9 +668,9 @@
} }
}, },
"node_modules/@types/mdx": { "node_modules/@types/mdx": {
"version": "2.0.13", "version": "2.0.14",
"resolved": "https://registry.npmjs.org/@types/mdx/-/mdx-2.0.13.tgz", "resolved": "https://registry.npmjs.org/@types/mdx/-/mdx-2.0.14.tgz",
"integrity": "sha512-+OWZQfAYyio6YkJb3HLxDrvnx6SWWDbC0zVPfBRzUk0/nqoDyf6dNxQi3eArPe8rJ473nobTMQ/8Zk+LxJ+Yuw==", "integrity": "sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg==",
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
@@ -682,9 +682,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "19.2.15", "version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.15.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-eRwcGNHve+E8qtEQSSRl6urh+rFop4v8gm6O8rGv25CodbvFdLjA1vVQ1KkiFE0w0UPOnb8tDiFKL5lp0rtY5Q==", "integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
@@ -723,9 +723,9 @@
} }
}, },
"node_modules/acorn": { "node_modules/acorn": {
"version": "8.16.0", "version": "8.17.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"bin": { "bin": {
@@ -1821,6 +1821,53 @@
"url": "https://opencollective.com/unified" "url": "https://opencollective.com/unified"
} }
}, },
"node_modules/mdast-util-to-markdown-cjk-friendly": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly/-/mdast-util-to-markdown-cjk-friendly-1.0.0.tgz",
"integrity": "sha512-BoaAm8mlJ+LAYz0Qs532Y3ciTuQYgBUPZcSFbvC/ZKmEMAKgulw84YvQK1gI34t/vL2euSfuaWlqczkTBgamkw==",
"dev": true,
"license": "MIT",
"dependencies": {
"mdast-util-to-markdown": "^2.1.2",
"micromark-extension-cjk-friendly-util": "3.0.1",
"micromark-util-symbol": "^2.0.1"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@types/mdast": "*"
},
"peerDependenciesMeta": {
"@types/mdast": {
"optional": true
}
}
},
"node_modules/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough/-/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-1.0.0.tgz",
"integrity": "sha512-1ePVfB4P/vz3xSsm6H3D32r6VYGErxclnuLLFK02/2ReF+UdEKm7caulK6Vm0LBIp5gPRtB2Z1OYDznCkX3k2w==",
"dev": true,
"license": "MIT",
"dependencies": {
"mdast-util-gfm-strikethrough": "^2.0.0",
"mdast-util-to-markdown": "^2.1.2",
"micromark-extension-cjk-friendly-util": "3.0.1",
"micromark-util-symbol": "^2.0.1"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@types/mdast": "*"
},
"peerDependenciesMeta": {
"@types/mdast": {
"optional": true
}
}
},
"node_modules/mdast-util-to-string": { "node_modules/mdast-util-to-string": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",
@@ -2742,9 +2789,9 @@
} }
}, },
"node_modules/property-information": { "node_modules/property-information": {
"version": "7.1.0", "version": "7.2.0",
"resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz",
"integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"funding": { "funding": {
@@ -2753,9 +2800,9 @@
} }
}, },
"node_modules/react": { "node_modules/react": {
"version": "19.2.6", "version": "19.2.7",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
"integrity": "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==", "integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -2763,16 +2810,16 @@
} }
}, },
"node_modules/react-dom": { "node_modules/react-dom": {
"version": "19.2.6", "version": "19.2.7",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.6.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
"integrity": "sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==", "integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"scheduler": "^0.27.0" "scheduler": "^0.27.0"
}, },
"peerDependencies": { "peerDependencies": {
"react": "^19.2.6" "react": "^19.2.7"
} }
}, },
"node_modules/react-lazy-with-preload": { "node_modules/react-lazy-with-preload": {
@@ -2822,9 +2869,9 @@
} }
}, },
"node_modules/react-router": { "node_modules/react-router": {
"version": "7.15.1", "version": "7.17.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.15.1.tgz", "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.17.0.tgz",
"integrity": "sha512-R8rl9HhgikFYoPJymnUtPXWbnDb3oget6lQnfIoupbt61aT9aOhRkDsY2XRhZRyX1Z/8a5sL74fXmFNm3NRK5A==", "integrity": "sha512-FDELK7rTMlCHO5+reyXsPlmfr7N1F91lPHsWYfMEGQm/KQ+F4JFM8jGoeQDmDvdTs93Fw9aSilH+uKRb4/jXvQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -2845,13 +2892,13 @@
} }
}, },
"node_modules/react-router-dom": { "node_modules/react-router-dom": {
"version": "7.15.1", "version": "7.17.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.15.1.tgz", "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.17.0.tgz",
"integrity": "sha512-AzF62gjY6U9rkMq4RfP/r2EVtQ7DMfNMjyOp/flLTCrtRylLiK4wT4pSq6O8rOXZ2eXdZYJPEYe+ifomiv+Igg==", "integrity": "sha512-fyU2yjGups/hE6Xz0I5ZYbVL8Gx29eCjgpHaRaTaVU+OOAdfRX05KsvyRm0GO8YQwOkhpU3MurW1jyMUJn+zSw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"react-router": "7.15.1" "react-router": "7.17.0"
}, },
"engines": { "engines": {
"node": ">=20.0.0" "node": ">=20.0.0"
@@ -3011,12 +3058,13 @@
} }
}, },
"node_modules/remark-cjk-friendly": { "node_modules/remark-cjk-friendly": {
"version": "2.0.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.0.1.tgz", "resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.3.1.tgz",
"integrity": "sha512-6WwkoQyZf/4j5k53zdFYrR8Ca+UVn992jXdLUSBDZR4eBpFhKyVxmA4gUHra/5fesjGIxrDhHesNr/sVoiiysA==", "integrity": "sha512-f+pKZRxCRwNEGFBKNRAZAqU91GIK1SAo3ZyFHWRUgC9zcxRR0BXKd6YwqgSsxtW0rNpUDtONj7H5nje2WL3fcA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"mdast-util-to-markdown-cjk-friendly": "1.0.0",
"micromark-extension-cjk-friendly": "2.0.1" "micromark-extension-cjk-friendly": "2.0.1"
}, },
"engines": { "engines": {
@@ -3033,12 +3081,13 @@
} }
}, },
"node_modules/remark-cjk-friendly-gfm-strikethrough": { "node_modules/remark-cjk-friendly-gfm-strikethrough": {
"version": "2.0.1", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/remark-cjk-friendly-gfm-strikethrough/-/remark-cjk-friendly-gfm-strikethrough-2.0.1.tgz", "resolved": "https://registry.npmjs.org/remark-cjk-friendly-gfm-strikethrough/-/remark-cjk-friendly-gfm-strikethrough-2.1.0.tgz",
"integrity": "sha512-pWKj25O2eLXIL1aBupayl1fKhco+Brw8qWUWJPVB9EBzbQNd7nGLj0nLmJpggWsGLR5j5y40PIdjxby9IEYTuA==", "integrity": "sha512-3Kyq2hjY7V7eU8MbVbWW6QQLN81pjJcIvKHvPxr8hZZmcq/9wqm3MJ3iUG34Ch9QTM4WHN+a1JVAVC1fSi5mig==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": "1.0.0",
"micromark-extension-cjk-friendly-gfm-strikethrough": "2.0.1" "micromark-extension-cjk-friendly-gfm-strikethrough": "2.0.1"
}, },
"engines": { "engines": {
@@ -3164,18 +3213,18 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/shiki": { "node_modules/shiki": {
"version": "4.1.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/shiki/-/shiki-4.1.0.tgz", "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.2.0.tgz",
"integrity": "sha512-l/ABZPUR5v70jI10EzqfMS/I96vjSGv2y0ihUV+WYFzv0EfvW4s54m0Lg8wCrrL+2IkwBzFTuxkZjPf8b2NX9Q==", "integrity": "sha512-hjNax6o/ylDy9lefQEaSDtzaT3iVNtZ3WmpQnbuQNoG4xvnSKf2kSKbihZVO4JRG1TTMejs7CmNRYlWgAL66pQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@shikijs/core": "4.1.0", "@shikijs/core": "4.2.0",
"@shikijs/engine-javascript": "4.1.0", "@shikijs/engine-javascript": "4.2.0",
"@shikijs/engine-oniguruma": "4.1.0", "@shikijs/engine-oniguruma": "4.2.0",
"@shikijs/langs": "4.1.0", "@shikijs/langs": "4.2.0",
"@shikijs/themes": "4.1.0", "@shikijs/themes": "4.2.0",
"@shikijs/types": "4.1.0", "@shikijs/types": "4.2.0",
"@shikijs/vscode-textmate": "^10.0.2", "@shikijs/vscode-textmate": "^10.0.2",
"@types/hast": "^3.0.4" "@types/hast": "^3.0.4"
}, },
+1 -1
View File
@@ -10,7 +10,7 @@
[toolchain] [toolchain]
profile = "minimal" profile = "minimal"
channel = "1.95.0" channel = "1.96.0"
components = [ components = [
# For rust-analyzer # For rust-analyzer
"rust-src", "rust-src",
+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
+59 -63
View File
@@ -1,80 +1,76 @@
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<'_> {
pub(super) async fn register(&self) -> Result {
let body = &self.body;
let body_len = self.body.len();
if body_len < 2
|| !body[0].trim().starts_with("```")
|| body.last().unwrap_or(&"").trim() != "```"
{
return Err!("Expected code block in command body. Add --help for details.");
}
#[admin_command] let range = 1..checked!(body_len - 1)?;
pub(super) async fn register(&self) -> Result { let appservice_config_body = body[range].join("\n");
let body = &self.body; let parsed_config = serde_saphyr::from_str(&appservice_config_body);
let body_len = self.body.len(); match parsed_config {
if body_len < 2 | Err(e) => return Err!("Could not parse appservice config as YAML: {e}"),
|| !body[0].trim().starts_with("```") | Ok(registration) => match self
|| body.last().unwrap_or(&"").trim() != "```" .services
{ .appservice
return Err!("Expected code block in command body. Add --help for details."); .register_appservice(&registration, &appservice_config_body)
.await
.map(|()| registration.id)
{
| Err(e) => return Err!("Failed to register appservice: {e}"),
| Ok(id) => write!(self, "Appservice registered with ID: {id}"),
},
}
.await
} }
let range = 1..checked!(body_len - 1)?; pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
let appservice_config_body = body[range].join("\n"); match self
let parsed_config = serde_saphyr::from_str(&appservice_config_body);
match parsed_config {
| Err(e) => return Err!("Could not parse appservice config as YAML: {e}"),
| Ok(registration) => match self
.services .services
.appservice .appservice
.register_appservice(&registration, &appservice_config_body) .unregister_appservice(&appservice_identifier)
.await .await
.map(|()| registration.id)
{ {
| Err(e) => return Err!("Failed to register appservice: {e}"), | Err(e) => return Err!("Failed to unregister appservice: {e}"),
| Ok(id) => write!(self, "Appservice registered with ID: {id}"), | Ok(()) => write!(self, "Appservice unregistered."),
}, }
}
.await
}
#[admin_command]
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
match self
.services
.appservice
.unregister_appservice(&appservice_identifier)
.await .await
{
| Err(e) => return Err!("Failed to unregister appservice: {e}"),
| Ok(()) => write!(self, "Appservice unregistered."),
} }
.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 .appservice
.appservice .get_registration(&appservice_identifier)
.get_registration(&appservice_identifier) .await
{
| None => return Err!("Appservice does not exist."),
| Some(config) => {
let config_str = serde_saphyr::to_string(&config)?;
write!(self, "Config for {appservice_identifier}:\n\n```yaml\n{config_str}\n```")
},
}
.await .await
{
| None => return Err!("Appservice does not exist."),
| Some(config) => {
let config_str = serde_saphyr::to_string(&config)?;
write!(self, "Config for {appservice_identifier}:\n\n```yaml\n{config_str}\n```")
},
} }
.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 .iter_ids()
.iter_ids() .collect()
.collect() .map(Ok)
.map(Ok) .and_then(|appservices: Vec<_>| {
.and_then(|appservices: Vec<_>| { let len = appservices.len();
let len = appservices.len(); let list = appservices.join(", ");
let list = appservices.join(", "); write!(self, "Appservices ({len}): {list}")
write!(self, "Appservices ({len}): {list}") })
}) .await
.await }
} }
+15 -15
View File
@@ -1,23 +1,23 @@
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;
let query_time = timer.elapsed(); let query_time = timer.elapsed();
let total = users.len(); let total = users.len();
let err_count = users.iter().filter(|_user| false).count(); let err_count = users.iter().filter(|_user| false).count();
let ok_count = users.iter().filter(|_user| true).count(); let ok_count = users.iter().filter(|_user| true).count();
self.write_str(&format!( self.write_str(&format!(
"Database query completed in {query_time:?}:\n\n```\nTotal entries: \ "Database query completed in {query_time:?}:\n\n```\nTotal entries: \
{total:?}\nFailure/Invalid user count: {err_count:?}\nSuccess/Valid user count: \ {total:?}\nFailure/Invalid user count: {err_count:?}\nSuccess/Valid user count: \
{ok_count:?}\n```" {ok_count:?}\n```"
)) ))
.await .await
}
} }
File diff suppressed because it is too large. Load diff
+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>,
+23 -28
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,37 +11,32 @@ pub enum TesterCommand {
Timer, Timer,
} }
#[rustfmt::skip] impl crate::Context<'_> {
#[admin_command] #[rustfmt::skip]
async fn panic(&self) -> Result { async fn panic(&self) -> Result {
panic!("panicked")
}
panic!("panicked") #[rustfmt::skip]
} async fn failure(&self) -> Result {
Err!("failed")
}
#[rustfmt::skip] #[inline(never)]
#[admin_command] #[rustfmt::skip]
async fn failure(&self) -> Result { async fn tester(&self) -> Result {
self.write_str("Ok").await
}
Err!("failed") #[inline(never)]
} #[rustfmt::skip]
async fn timer(&self) -> Result {
let started = std::time::Instant::now();
timed(self.body);
#[inline(never)] let elapsed = started.elapsed();
#[rustfmt::skip] self.write_str(&format!("completed in {elapsed:#?}")).await
#[admin_command] }
async fn tester(&self) -> Result {
self.write_str("Ok").await
}
#[inline(never)]
#[rustfmt::skip]
#[admin_command]
async fn timer(&self) -> Result {
let started = std::time::Instant::now();
timed(self.body);
let elapsed = started.elapsed();
self.write_str(&format!("completed in {elapsed:#?}")).await
} }
#[inline(never)] #[inline(never)]
+116 -112
View File
@@ -4,127 +4,131 @@ 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 .services
.rooms
.event_handler
.federation_handletime
.read();
let mut msg = format!(
"Handling {} incoming PDUs across {} active transactions:\n",
map.len(),
self.services.transactions.txn_active_handle_count()
);
for (r, (e, i)) in map.iter() {
let elapsed = i.elapsed();
writeln!(
msg,
"{} {}: {}m{}s",
r,
e,
elapsed.as_secs() / 60,
elapsed.as_secs() % 60
)?;
}
msg
};
self.write_str(&msg).await
}
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
let response = self
.services
.client
.default
.get(format!("https://{server_name}/.well-known/matrix/support"))
.send()
.await?;
let text = response
.limit_read_text(
self.services
.config
.max_request_size
.try_into()
.expect("u64 fits into usize"),
)
.await?;
if text.is_empty() {
return Err!("Response text/body is empty.");
}
if text.len() > 1500 {
return Err!(
"Response text/body is over 1500 characters, assuming no support well-known.",
);
}
let json: serde_json::Value = match serde_json::from_str(&text) {
| Ok(json) => json,
| Err(_) => {
return Err!("Response text/body is not valid JSON.",);
},
};
let pretty_json: String = match serde_json::to_string_pretty(&json) {
| Ok(json) => json,
| Err(_) => {
return Err!("Response text/body is not valid JSON.",);
},
};
self.write_str(&format!("Got JSON response:\n\n```json\n{pretty_json}\n```"))
.await
}
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
if user_id.server_name() == self.services.server.name {
return Err!(
"User belongs to our server, please use `list-joined-rooms` user admin command \
instead.",
);
}
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
.services .services
.rooms .rooms
.event_handler .state_cache
.federation_handletime .rooms_joined(&user_id)
.read(); .then(async |room_id| get_room_info(self.services, &room_id).await)
.collect()
.await;
let mut msg = format!( if rooms.is_empty() {
"Handling {} incoming PDUs across {} active transactions:\n", return Err!("User is not in any rooms.");
map.len(),
self.services.transactions.txn_active_handle_count()
);
for (r, (e, i)) in map.iter() {
let elapsed = i.elapsed();
writeln!(msg, "{} {}: {}m{}s", r, e, elapsed.as_secs() / 60, elapsed.as_secs() % 60)?;
} }
msg
};
self.write_str(&msg).await rooms.sort_by_key(|r| r.1);
} rooms.reverse();
#[admin_command] let num = rooms.len();
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result { let body = rooms
let response = self .iter()
.services .map(|(id, members, name)| format!("{id} | Members: {members} | Name: {name}"))
.client .collect::<Vec<_>>()
.default .join("\n");
.get(format!("https://{server_name}/.well-known/matrix/support"))
.send()
.await?;
let text = response self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
.limit_read_text( .await
self.services
.config
.max_request_size
.try_into()
.expect("u64 fits into usize"),
)
.await?;
if text.is_empty() {
return Err!("Response text/body is empty.");
}
if text.len() > 1500 {
return Err!(
"Response text/body is over 1500 characters, assuming no support well-known.",
);
}
let json: serde_json::Value = match serde_json::from_str(&text) {
| Ok(json) => json,
| Err(_) => {
return Err!("Response text/body is not valid JSON.",);
},
};
let pretty_json: String = match serde_json::to_string_pretty(&json) {
| Ok(json) => json,
| Err(_) => {
return Err!("Response text/body is not valid JSON.",);
},
};
self.write_str(&format!("Got JSON response:\n\n```json\n{pretty_json}\n```"))
.await
}
#[admin_command]
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
if user_id.server_name() == self.services.server.name {
return Err!(
"User belongs to our server, please use `list-joined-rooms` user admin command \
instead.",
);
}
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
.services
.rooms
.state_cache
.rooms_joined(&user_id)
.then(async |room_id| get_room_info(self.services, &room_id).await)
.collect()
.await;
if rooms.is_empty() {
return Err!("User is not in any rooms.");
} }
rooms.sort_by_key(|r| r.1);
rooms.reverse();
let num = rooms.len();
let body = rooms
.iter()
.map(|(id, members, name)| format!("{id} | Members: {members} | Name: {name}"))
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
.await
} }
+336 -334
View File
@@ -9,401 +9,403 @@ 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>,
event_id: Option<OwnedEventId>, event_id: Option<OwnedEventId>,
) -> Result { ) -> Result {
self.bail_restricted()?; self.bail_restricted()?;
if event_id.is_some() && mxc.is_some() { if event_id.is_some() && mxc.is_some() {
return Err!("Please specify either an MXC or an event ID, not both.",); return Err!("Please specify either an MXC or an event ID, not both.",);
} }
if let Some(mxc) = mxc { if let Some(mxc) = mxc {
trace!("Got MXC URL: {mxc}"); trace!("Got MXC URL: {mxc}");
self.services self.services
.media .media
.delete(&mxc.as_str().try_into()?) .delete(&mxc.as_str().try_into()?)
.await?; .await?;
return self return self
.write_str("Deleted the MXC from our database and on our filesystem.") .write_str("Deleted the MXC from our database and on our filesystem.")
.await; .await;
} }
if let Some(event_id) = event_id { if let Some(event_id) = event_id {
trace!("Got event ID to delete media from: {event_id}"); trace!("Got event ID to delete media from: {event_id}");
let mut mxc_urls = Vec::with_capacity(4); let mut mxc_urls = Vec::with_capacity(4);
// parsing the PDU for any MXC URLs begins here // parsing the PDU for any MXC URLs begins here
match self.services.rooms.timeline.get_pdu_json(&event_id).await { match self.services.rooms.timeline.get_pdu_json(&event_id).await {
| Ok(event_json) => { | Ok(event_json) => {
if let Some(content_key) = event_json.get("content") { if let Some(content_key) = event_json.get("content") {
debug!("Event ID has \"content\"."); debug!("Event ID has \"content\".");
let content_obj = content_key.as_object(); let content_obj = content_key.as_object();
if let Some(content) = content_obj { if let Some(content) = content_obj {
// 1. attempts to parse the "url" key // 1. attempts to parse the "url" key
debug!("Attempting to go into \"url\" key for main media file"); debug!("Attempting to go into \"url\" key for main media file");
if let Some(url) = content.get("url") { if let Some(url) = content.get("url") {
debug!("Got a URL in the event ID {event_id}: {url}"); debug!("Got a URL in the event ID {event_id}: {url}");
if url.to_string().starts_with("\"mxc://") { if url.to_string().starts_with("\"mxc://") {
debug!("Pushing URL {url} to list of MXCs to delete"); debug!("Pushing URL {url} to list of MXCs to delete");
let final_url = url.to_string().replace('"', ""); let final_url = url.to_string().replace('"', "");
mxc_urls.push(final_url); mxc_urls.push(final_url);
} else {
info!(
"Found a URL in the event ID {event_id} but did not start \
with mxc://, ignoring"
);
}
}
// 2. attempts to parse the "info" key
debug!("Attempting to go into \"info\" key for thumbnails");
if let Some(info_key) = content.get("info") {
debug!("Event ID has \"info\".");
let info_obj = info_key.as_object();
if let Some(info) = info_obj {
if let Some(thumbnail_url) = info.get("thumbnail_url") {
debug!("Found a thumbnail_url in info key: {thumbnail_url}");
if thumbnail_url.to_string().starts_with("\"mxc://") {
debug!(
"Pushing thumbnail URL {thumbnail_url} to list of \
MXCs to delete"
);
let final_thumbnail_url =
thumbnail_url.to_string().replace('"', "");
mxc_urls.push(final_thumbnail_url);
} else {
info!(
"Found a thumbnail URL in the event ID {event_id} \
but did not start with mxc://, ignoring"
);
}
} else { } else {
info!( info!(
"No \"thumbnail_url\" key in \"info\" key, assuming no \ "Found a URL in the event ID {event_id} but did not \
thumbnails." start with mxc://, ignoring"
); );
} }
} }
}
// 3. attempts to parse the "file" key // 2. attempts to parse the "info" key
debug!("Attempting to go into \"file\" key"); debug!("Attempting to go into \"info\" key for thumbnails");
if let Some(file_key) = content.get("file") { if let Some(info_key) = content.get("info") {
debug!("Event ID has \"file\"."); debug!("Event ID has \"info\".");
let file_obj = file_key.as_object(); let info_obj = info_key.as_object();
if let Some(file) = file_obj { if let Some(info) = info_obj {
if let Some(url) = file.get("url") { if let Some(thumbnail_url) = info.get("thumbnail_url") {
debug!("Found url in file key: {url}"); debug!(
"Found a thumbnail_url in info key: {thumbnail_url}"
);
if url.to_string().starts_with("\"mxc://") { if thumbnail_url.to_string().starts_with("\"mxc://") {
debug!("Pushing URL {url} to list of MXCs to delete"); debug!(
let final_url = url.to_string().replace('"', ""); "Pushing thumbnail URL {thumbnail_url} to list \
mxc_urls.push(final_url); of MXCs to delete"
);
let final_thumbnail_url =
thumbnail_url.to_string().replace('"', "");
mxc_urls.push(final_thumbnail_url);
} else {
info!(
"Found a thumbnail URL in the event ID \
{event_id} but did not start with mxc://, \
ignoring"
);
}
} else { } else {
warn!( info!(
"Found a URL in the event ID {event_id} but did not \ "No \"thumbnail_url\" key in \"info\" key, assuming \
start with mxc://, ignoring" no thumbnails."
); );
} }
} else {
error!("No \"url\" key in \"file\" key.");
} }
} }
// 3. attempts to parse the "file" key
debug!("Attempting to go into \"file\" key");
if let Some(file_key) = content.get("file") {
debug!("Event ID has \"file\".");
let file_obj = file_key.as_object();
if let Some(file) = file_obj {
if let Some(url) = file.get("url") {
debug!("Found url in file key: {url}");
if url.to_string().starts_with("\"mxc://") {
debug!("Pushing URL {url} to list of MXCs to delete");
let final_url = url.to_string().replace('"', "");
mxc_urls.push(final_url);
} else {
warn!(
"Found a URL in the event ID {event_id} but did \
not start with mxc://, ignoring"
);
}
} else {
error!("No \"url\" key in \"file\" key.");
}
}
}
} else {
return Err!(
"Event ID does not have a \"content\" key or failed parsing the \
event ID JSON.",
);
} }
} else { } else {
return Err!( return Err!(
"Event ID does not have a \"content\" key or failed parsing the \ "Event ID does not have a \"content\" key, this is not a message or \
event ID JSON.", an event type that contains media.",
); );
} }
} else { },
return Err!( | _ => {
"Event ID does not have a \"content\" key, this is not a message or an \ return Err!("Event ID does not exist or is not known to us.",);
event type that contains media.", },
); }
if mxc_urls.is_empty() {
return Err!("Parsed event ID but found no MXC URLs.",);
}
let mut mxc_deletion_count: usize = 0;
for mxc_url in mxc_urls {
match self
.services
.media
.delete(&mxc_url.as_str().try_into()?)
.await
{
| Ok(()) => {
debug_info!(
"Successfully deleted {mxc_url} from filesystem and database"
);
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
},
| Err(e) => {
debug_warn!(
"Failed to delete {mxc_url}, ignoring error and skipping: {e}"
);
continue;
},
} }
}, }
| _ => {
return Err!("Event ID does not exist or is not known to us.",); return self
}, .write_str(&format!(
"Deleted {mxc_deletion_count} total MXCs from our database and the \
filesystem from event ID {event_id}."
))
.await;
} }
if mxc_urls.is_empty() { Err!(
return Err!("Parsed event ID but found no MXC URLs.",); "Please specify either an MXC using --mxc or an event ID using --event-id of the \
message containing an image. See --help for details."
)
}
pub(super) async fn delete_list(&self) -> Result {
self.bail_restricted()?;
if self.body.len() < 2
|| !self.body[0].trim().starts_with("```")
|| self.body.last().unwrap_or(&"").trim() != "```"
{
return Err!("Expected code block in command body. Add --help for details.",);
} }
let mut failed_parsed_mxcs: usize = 0;
let mxc_list = self
.body
.to_vec()
.drain(1..self.body.len().checked_sub(1).unwrap())
.filter_map(|mxc_s| {
mxc_s
.try_into()
.inspect_err(|e| {
debug_warn!("Failed to parse user-provided MXC URI: {e}");
failed_parsed_mxcs = failed_parsed_mxcs.saturating_add(1);
})
.ok()
})
.collect::<Vec<Mxc<'_>>>();
let mut mxc_deletion_count: usize = 0; let mut mxc_deletion_count: usize = 0;
for mxc_url in mxc_urls { for mxc in &mxc_list {
match self trace!(%failed_parsed_mxcs, %mxc_deletion_count, "Deleting MXC {mxc} in bulk");
.services match self.services.media.delete(mxc).await {
.media
.delete(&mxc_url.as_str().try_into()?)
.await
{
| Ok(()) => { | Ok(()) => {
debug_info!("Successfully deleted {mxc_url} from filesystem and database"); debug_info!("Successfully deleted {mxc} 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}, ignoring error and skipping: {e}");
continue; continue;
}, },
} }
} }
return self self.write_str(&format!(
.write_str(&format!( "Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our \
"Deleted {mxc_deletion_count} total MXCs from our database and the filesystem \ database and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from \
from event ID {event_id}." the database.",
)) ))
.await; .await
} }
Err!( pub(super) async fn delete_past_remote_media(
"Please specify either an MXC using --mxc or an event ID using --event-id of the \ &self,
message containing an image. See --help for details." duration: String,
) before: bool,
} after: bool,
yes_i_want_to_delete_local_media: bool,
) -> Result {
self.bail_restricted()?;
#[admin_command] if before && after {
pub(super) async fn delete_list(&self) -> Result { return Err!("Please only pick one argument, --before or --after.",);
self.bail_restricted()?;
if self.body.len() < 2
|| !self.body[0].trim().starts_with("```")
|| self.body.last().unwrap_or(&"").trim() != "```"
{
return Err!("Expected code block in command body. Add --help for details.",);
}
let mut failed_parsed_mxcs: usize = 0;
let mxc_list = self
.body
.to_vec()
.drain(1..self.body.len().checked_sub(1).unwrap())
.filter_map(|mxc_s| {
mxc_s
.try_into()
.inspect_err(|e| {
debug_warn!("Failed to parse user-provided MXC URI: {e}");
failed_parsed_mxcs = failed_parsed_mxcs.saturating_add(1);
})
.ok()
})
.collect::<Vec<Mxc<'_>>>();
let mut mxc_deletion_count: usize = 0;
for mxc in &mxc_list {
trace!(%failed_parsed_mxcs, %mxc_deletion_count, "Deleting MXC {mxc} in bulk");
match self.services.media.delete(mxc).await {
| Ok(()) => {
debug_info!("Successfully deleted {mxc} from filesystem and database");
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
},
| Err(e) => {
debug_warn!("Failed to delete {mxc}, ignoring error and skipping: {e}");
continue;
},
} }
} assert!(!(before && after), "--before and --after should not be specified together");
self.write_str(&format!( let direction = if after {
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our database \ TimeDirection::After
and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from the database.", } else {
)) TimeDirection::Before
.await
}
#[admin_command]
pub(super) async fn delete_past_remote_media(
&self,
duration: String,
before: bool,
after: bool,
yes_i_want_to_delete_local_media: bool,
) -> Result {
self.bail_restricted()?;
if before && after {
return Err!("Please only pick one argument, --before or --after.",);
}
assert!(!(before && after), "--before and --after should not be specified together");
let direction = if after {
TimeDirection::After
} else {
TimeDirection::Before
};
let time_boundary = parse_timepoint_ago(&duration)?;
let deleted_count = self
.services
.media
.delete_all_media_within_timeframe(
time_boundary,
direction,
yes_i_want_to_delete_local_media,
)
.await?;
self.write_str(&format!("Deleted {deleted_count} total files."))
.await
}
#[admin_command]
pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
let user_id = parse_local_user_id(self.services, &username)?;
let deleted_count = self.services.media.delete_from_user(&user_id).await?;
self.write_str(&format!("Deleted {deleted_count} total files."))
.await
}
#[admin_command]
pub(super) async fn delete_all_from_server(
&self,
server_name: OwnedServerName,
yes_i_want_to_delete_local_media: bool,
) -> Result {
self.bail_restricted()?;
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.",);
}
let Ok(all_mxcs) = self
.services
.media
.get_all_mxcs()
.await
.inspect_err(|e| error!("Failed to get MXC URIs from our database: {e}"))
else {
return Err!("Failed to get MXC URIs from our database",);
};
let mut deleted_count: usize = 0;
for mxc in all_mxcs {
let Ok(mxc_server_name) = mxc.server_name().inspect_err(|e| {
debug_warn!(
"Failed to parse MXC {mxc} server name from database, ignoring error and \
skipping: {e}"
);
}) else {
continue;
}; };
if mxc_server_name != server_name let time_boundary = parse_timepoint_ago(&duration)?;
|| (self.services.globals.server_is_ours(mxc_server_name) let deleted_count = self
&& !yes_i_want_to_delete_local_media) .services
.media
.delete_all_media_within_timeframe(
time_boundary,
direction,
yes_i_want_to_delete_local_media,
)
.await?;
self.write_str(&format!("Deleted {deleted_count} total files."))
.await
}
pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
let user_id = parse_local_user_id(self.services, &username)?;
let deleted_count = self.services.media.delete_from_user(&user_id).await?;
self.write_str(&format!("Deleted {deleted_count} total files."))
.await
}
pub(super) async fn delete_all_from_server(
&self,
server_name: OwnedServerName,
yes_i_want_to_delete_local_media: bool,
) -> Result {
self.bail_restricted()?;
if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media
{ {
trace!("skipping MXC URI {mxc}"); return Err!("This command only works for remote media by default.",);
continue;
} }
let mxc: Mxc<'_> = mxc.as_str().try_into()?; let Ok(all_mxcs) = self
.services
.media
.get_all_mxcs()
.await
.inspect_err(|e| error!("Failed to get MXC URIs from our database: {e}"))
else {
return Err!("Failed to get MXC URIs from our database",);
};
match self.services.media.delete(&mxc).await { let mut deleted_count: usize = 0;
| Ok(()) => {
deleted_count = deleted_count.saturating_add(1); for mxc in all_mxcs {
}, let Ok(mxc_server_name) = mxc.server_name().inspect_err(|e| {
| Err(e) => { debug_warn!(
debug_warn!("Failed to delete {mxc}, ignoring error and skipping: {e}"); "Failed to parse MXC {mxc} server name from database, ignoring error and \
skipping: {e}"
);
}) else {
continue; continue;
}, };
if mxc_server_name != server_name
|| (self.services.globals.server_is_ours(mxc_server_name)
&& !yes_i_want_to_delete_local_media)
{
trace!("skipping MXC URI {mxc}");
continue;
}
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
match self.services.media.delete(&mxc).await {
| Ok(()) => {
deleted_count = deleted_count.saturating_add(1);
},
| Err(e) => {
debug_warn!("Failed to delete {mxc}, ignoring error and skipping: {e}");
continue;
},
}
} }
self.write_str(&format!("Deleted {deleted_count} total files."))
.await
} }
self.write_str(&format!("Deleted {deleted_count} total files.")) pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
.await let mxc: Mxc<'_> = mxc.as_str().try_into()?;
} let metadata = self.services.media.get_metadata(&mxc).await;
#[admin_command] self.write_str(&format!("```\n{metadata:#?}\n```")).await
pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
let metadata = self.services.media.get_metadata(&mxc).await;
self.write_str(&format!("```\n{metadata:#?}\n```")).await
}
#[admin_command]
pub(super) async fn get_remote_file(
&self,
mxc: OwnedMxcUri,
server: Option<OwnedServerName>,
timeout: u32,
) -> Result {
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
let timeout = Duration::from_millis(timeout.into());
let mut result = self
.services
.media
.fetch_remote_content(&mxc, None, server.as_deref(), timeout)
.await?;
// Grab the length of the content before clearing it to not flood the output
let len = result.content.as_ref().expect("content").len();
result.content.as_mut().expect("content").clear();
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
.await
}
#[admin_command]
pub(super) async fn get_remote_thumbnail(
&self,
mxc: OwnedMxcUri,
server: Option<OwnedServerName>,
timeout: u32,
width: u32,
height: u32,
) -> Result {
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
let timeout = Duration::from_millis(timeout.into());
let dim = Dim::new(width, height, None);
let mut result = self
.services
.media
.fetch_remote_thumbnail(&mxc, None, server.as_deref(), timeout, &dim)
.await?;
// Grab the length of the content before clearing it to not flood the output
let len = result.content.as_ref().expect("content").len();
result.content.as_mut().expect("content").clear();
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
.await
}
#[admin_command]
pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result {
if all {
self.services.media.clear_url_previews().await;
return self.write_str("Deleted all cached URL previews.").await;
} }
let url = url.expect("clap enforces url is required unless --all"); pub(super) async fn get_remote_file(
&self,
mxc: OwnedMxcUri,
server: Option<OwnedServerName>,
timeout: u32,
) -> Result {
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
let timeout = Duration::from_millis(timeout.into());
let mut result = self
.services
.media
.fetch_remote_content(&mxc, None, server.as_deref(), timeout)
.await?;
self.services.media.remove_url_preview(&url).await?; // Grab the length of the content before clearing it to not flood the output
let len = result.content.as_ref().expect("content").len();
result.content.as_mut().expect("content").clear();
self.write_str(&format!("Deleted cached URL preview for: {url}")) self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
.await .await
}
pub(super) async fn get_remote_thumbnail(
&self,
mxc: OwnedMxcUri,
server: Option<OwnedServerName>,
timeout: u32,
width: u32,
height: u32,
) -> Result {
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
let timeout = Duration::from_millis(timeout.into());
let dim = Dim::new(width, height, None);
let mut result = self
.services
.media
.fetch_remote_thumbnail(&mxc, None, server.as_deref(), timeout, &dim)
.await?;
// Grab the length of the content before clearing it to not flood the output
let len = result.content.as_ref().expect("content").len();
result.content.as_mut().expect("content").clear();
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
.await
}
pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result {
if all {
self.services.media.clear_url_previews().await;
return self.write_str("Deleted all cached URL previews.").await;
}
let url = url.expect("clap enforces url is required unless --all");
self.services.media.remove_url_preview(&url).await?;
self.write_str(&format!("Deleted cached URL preview for: {url}"))
.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};
+43 -43
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,50 +31,50 @@ pub enum AccountDataCommand {
}, },
} }
#[admin_command] impl crate::Context<'_> {
async fn changes_since( async fn changes_since(
&self, &self,
user_id: OwnedUserId, user_id: OwnedUserId,
since: u64, since: u64,
room_id: Option<OwnedRoomId>, room_id: Option<OwnedRoomId>,
) -> Result { ) -> Result {
let timer = tokio::time::Instant::now(); let timer = tokio::time::Instant::now();
let results: Vec<_> = self let results: Vec<_> = self
.services .services
.account_data .account_data
.changes_since(room_id.as_deref(), &user_id, Some(since), None) .changes_since(room_id.as_deref(), &user_id, Some(since), None)
.collect() .collect()
.await; .await;
let query_time = timer.elapsed(); let query_time = timer.elapsed();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```")) self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
.await .await
} }
#[admin_command] async fn account_data_get(
async fn account_data_get( &self,
&self, user_id: OwnedUserId,
user_id: OwnedUserId, kind: String,
kind: String, room_id: Option<OwnedRoomId>,
room_id: Option<OwnedRoomId>, ) -> Result {
) -> Result { let timer = tokio::time::Instant::now();
let timer = tokio::time::Instant::now(); let result = self
let result = self .services
.services .account_data
.account_data .get_raw(room_id.as_deref(), &user_id, &kind)
.get_raw(room_id.as_deref(), &user_id, &kind) .await;
.await; let query_time = timer.elapsed();
let query_time = timer.elapsed();
let json = serde_json::to_string_pretty(&match room_id { let json = serde_json::to_string_pretty(&match room_id {
| None => result | None => result
.deserialized::<ruma::serde::Raw<ruma::events::AnyGlobalAccountDataEvent>>()? .deserialized::<ruma::serde::Raw<ruma::events::AnyGlobalAccountDataEvent>>()?
.serialize(serde_json::value::Serializer)?, .serialize(serde_json::value::Serializer)?,
| Some(_) => result | Some(_) => result
.deserialized::<ruma::serde::Raw<ruma::events::AnyRoomAccountDataEvent>>()? .deserialized::<ruma::serde::Raw<ruma::events::AnyRoomAccountDataEvent>>()?
.serialize(serde_json::value::Serializer)?, .serialize(serde_json::value::Serializer)?,
})?; })?;
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
}
} }
+246 -238
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,279 +159,287 @@ 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>>,
start: Option<String>, start: Option<String>,
stop: Option<String>, stop: Option<String>,
from: Option<usize>, from: Option<usize>,
into: Option<usize>, into: Option<usize>,
parallelism: Option<usize>, parallelism: Option<usize>,
exhaustive: bool, exhaustive: bool,
) -> Result { ) -> Result {
use conduwuit_database::compact::Options; use conduwuit_database::compact::Options;
let default_all_maps: Option<_> = map.is_none().then(|| { let default_all_maps: Option<_> = map.is_none().then(|| {
self.services self.services
.db .db
.keys() .keys()
.map(Deref::deref) .map(Deref::deref)
.map(ToOwned::to_owned) .map(ToOwned::to_owned)
}); });
let maps: Vec<_> = map let maps: Vec<_> = map
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.chain(default_all_maps.into_iter().flatten()) .chain(default_all_maps.into_iter().flatten())
.map(|map| self.services.db.get(&map)) .map(|map| self.services.db.get(&map))
.filter_map(Result::ok) .filter_map(Result::ok)
.cloned() .cloned()
.collect(); .collect();
if maps.is_empty() { if maps.is_empty() {
return Err!("--map argument invalid. not found in database"); return Err!("--map argument invalid. not found in database");
}
let range = (
start.as_ref().map(String::as_bytes).map(Into::into),
stop.as_ref().map(String::as_bytes).map(Into::into),
);
let options = Options {
range,
level: (from, into),
exclusive: parallelism.is_some_and(is_zero!()),
exhaustive,
};
let runtime = self.services.server.runtime().clone();
let parallelism = parallelism.unwrap_or(1);
let results = maps
.into_iter()
.try_stream::<conduwuit::Error>()
.paralleln_and_then(runtime, parallelism, move |map| {
map.compact_blocking(options.clone())?;
Ok(map.name().to_owned())
})
.collect::<Vec<_>>();
let timer = Instant::now();
let results = results.await;
let query_time = timer.elapsed();
self.write_str(&format!("Jobs completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
.await
} }
let range = ( pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result {
start.as_ref().map(String::as_bytes).map(Into::into), let prefix = prefix.as_deref().unwrap_or(EMPTY);
stop.as_ref().map(String::as_bytes).map(Into::into),
);
let options = Options { let timer = Instant::now();
range, let count = with_maps_or(map.as_deref(), self.services)
level: (from, into), .then(|map| map.raw_count_prefix(&prefix))
exclusive: parallelism.is_some_and(is_zero!()), .ready_fold(0_usize, usize::saturating_add)
exhaustive, .await;
};
let runtime = self.services.server.runtime().clone(); let query_time = timer.elapsed();
let parallelism = parallelism.unwrap_or(1); self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{count:#?}\n```"))
let results = maps .await
.into_iter() }
.try_stream::<conduwuit::Error>()
.paralleln_and_then(runtime, parallelism, move |map| {
map.compact_blocking(options.clone())?;
Ok(map.name().to_owned())
})
.collect::<Vec<_>>();
let timer = Instant::now(); pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result {
let results = results.await; writeln!(self, "```").boxed().await?;
let query_time = timer.elapsed();
self.write_str(&format!("Jobs completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
.await
}
#[admin_command] let map = self.services.db.get(map.as_str())?;
pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result { let timer = Instant::now();
let prefix = prefix.as_deref().unwrap_or(EMPTY); prefix
.as_deref()
.map_or_else(|| map.raw_keys().boxed(), |prefix| map.raw_keys_prefix(prefix).boxed())
.map_ok(String::from_utf8_lossy)
.try_for_each(|str| writeln!(self, "{str:?}"))
.boxed()
.await?;
let timer = Instant::now(); let query_time = timer.elapsed();
let count = with_maps_or(map.as_deref(), self.services) self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
.then(|map| map.raw_count_prefix(&prefix)) .await
.ready_fold(0_usize, usize::saturating_add) }
.await;
let query_time = timer.elapsed(); pub(super) async fn raw_keys_sizes(
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{count:#?}\n```")) &self,
.await map: Option<String>,
} prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY);
#[admin_command] let timer = Instant::now();
pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result { let result = with_maps_or(map.as_deref(), self.services)
writeln!(self, "```").boxed().await?; .map(|map| map.raw_keys_prefix(&prefix))
.flatten()
.ignore_err()
.map(<[u8]>::len)
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
let entry = map.entry(len).or_default();
*entry = entry.saturating_add(1);
map
})
.await;
let map = self.services.db.get(map.as_str())?; let query_time = timer.elapsed();
let timer = Instant::now(); self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
prefix .await
.as_deref() }
.map_or_else(|| map.raw_keys().boxed(), |prefix| map.raw_keys_prefix(prefix).boxed())
.map_ok(String::from_utf8_lossy)
.try_for_each(|str| writeln!(self, "{str:?}"))
.boxed()
.await?;
let query_time = timer.elapsed(); pub(super) async fn raw_keys_total(
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}")) &self,
.await map: Option<String>,
} prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY);
#[admin_command] let timer = Instant::now();
pub(super) async fn raw_keys_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result { let result = with_maps_or(map.as_deref(), self.services)
let prefix = prefix.as_deref().unwrap_or(EMPTY); .map(|map| map.raw_keys_prefix(&prefix))
.flatten()
.ignore_err()
.map(<[u8]>::len)
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
.await;
let timer = Instant::now(); let query_time = timer.elapsed();
let result = with_maps_or(map.as_deref(), self.services) self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
.map(|map| map.raw_keys_prefix(&prefix)) .await
.flatten() }
.ignore_err()
.map(<[u8]>::len)
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
let entry = map.entry(len).or_default();
*entry = entry.saturating_add(1);
map
})
.await;
let query_time = timer.elapsed(); pub(super) async fn raw_vals_sizes(
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}")) &self,
.await map: Option<String>,
} prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY);
#[admin_command] let timer = Instant::now();
pub(super) async fn raw_keys_total(&self, map: Option<String>, prefix: Option<String>) -> Result { let result = with_maps_or(map.as_deref(), self.services)
let prefix = prefix.as_deref().unwrap_or(EMPTY); .map(|map| map.raw_stream_prefix(&prefix))
.flatten()
.ignore_err()
.map(at!(1))
.map(<[u8]>::len)
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
let entry = map.entry(len).or_default();
*entry = entry.saturating_add(1);
map
})
.await;
let timer = Instant::now(); let query_time = timer.elapsed();
let result = with_maps_or(map.as_deref(), self.services) self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
.map(|map| map.raw_keys_prefix(&prefix)) .await
.flatten() }
.ignore_err()
.map(<[u8]>::len)
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
.await;
let query_time = timer.elapsed(); pub(super) async fn raw_vals_total(
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}")) &self,
.await map: Option<String>,
} prefix: Option<String>,
) -> Result {
let prefix = prefix.as_deref().unwrap_or(EMPTY);
#[admin_command] let timer = Instant::now();
pub(super) async fn raw_vals_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result { let result = with_maps_or(map.as_deref(), self.services)
let prefix = prefix.as_deref().unwrap_or(EMPTY); .map(|map| map.raw_stream_prefix(&prefix))
.flatten()
.ignore_err()
.map(at!(1))
.map(<[u8]>::len)
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
.await;
let timer = Instant::now(); let query_time = timer.elapsed();
let result = with_maps_or(map.as_deref(), self.services) self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
.map(|map| map.raw_stream_prefix(&prefix)) .await
.flatten() }
.ignore_err()
.map(at!(1))
.map(<[u8]>::len)
.ready_fold_default(|mut map: BTreeMap<_, usize>, len| {
let entry = map.entry(len).or_default();
*entry = entry.saturating_add(1);
map
})
.await;
let query_time = timer.elapsed(); pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result {
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}")) writeln!(self, "```").await?;
.await
}
#[admin_command] let map = self.services.db.get(&map)?;
pub(super) async fn raw_vals_total(&self, map: Option<String>, prefix: Option<String>) -> Result { let timer = Instant::now();
let prefix = prefix.as_deref().unwrap_or(EMPTY); prefix
.as_deref()
.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, Cow::into_owned))
.try_for_each(|keyval| writeln!(self, "{keyval:?}"))
.boxed()
.await?;
let timer = Instant::now(); let query_time = timer.elapsed();
let result = with_maps_or(map.as_deref(), self.services) self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
.map(|map| map.raw_stream_prefix(&prefix)) .await
.flatten() }
.ignore_err()
.map(at!(1))
.map(<[u8]>::len)
.ready_fold_default(|acc: usize, len| acc.saturating_add(len))
.await;
let query_time = timer.elapsed(); pub(super) async fn raw_keys_from(
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}")) &self,
.await map: String,
} start: String,
limit: Option<usize>,
) -> Result {
writeln!(self, "```").await?;
#[admin_command] let map = self.services.db.get(&map)?;
pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result { let timer = Instant::now();
writeln!(self, "```").await?; map.raw_keys_from(&start)
.map_ok(String::from_utf8_lossy)
.take(limit.unwrap_or(usize::MAX))
.try_for_each(|str| writeln!(self, "{str:?}"))
.boxed()
.await?;
let map = self.services.db.get(&map)?; let query_time = timer.elapsed();
let timer = Instant::now(); self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}"))
prefix .await
.as_deref() }
.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, Cow::into_owned))
.try_for_each(|keyval| writeln!(self, "{keyval:?}"))
.boxed()
.await?;
let query_time = timer.elapsed(); pub(super) async fn raw_iter_from(
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}")) &self,
.await map: String,
} start: String,
limit: Option<usize>,
) -> Result {
let map = self.services.db.get(&map)?;
let timer = Instant::now();
let result = map
.raw_stream_from(&start)
.map_ok(apply!(2, String::from_utf8_lossy))
.map_ok(apply!(2, Cow::into_owned))
.take(limit.unwrap_or(usize::MAX))
.try_collect::<Vec<(String, String)>>()
.await?;
#[admin_command] let query_time = timer.elapsed();
pub(super) async fn raw_keys_from( self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
&self, .await
map: String, }
start: String,
limit: Option<usize>,
) -> Result {
writeln!(self, "```").await?;
let map = self.services.db.get(&map)?; pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
let timer = Instant::now(); let map = self.services.db.get(&map)?;
map.raw_keys_from(&start) let timer = Instant::now();
.map_ok(String::from_utf8_lossy) map.remove(&key);
.take(limit.unwrap_or(usize::MAX))
.try_for_each(|str| writeln!(self, "{str:?}"))
.boxed()
.await?;
let query_time = timer.elapsed(); let query_time = timer.elapsed();
self.write_str(&format!("\n```\n\nQuery completed in {query_time:?}")) self.write_str(&format!("Operation completed in {query_time:?}"))
.await .await
} }
#[admin_command] pub(super) async fn raw_get(&self, map: String, key: String) -> Result {
pub(super) async fn raw_iter_from( let map = self.services.db.get(&map)?;
&self, let timer = Instant::now();
map: String, let handle = map.get(&key).await?;
start: String,
limit: Option<usize>,
) -> Result {
let map = self.services.db.get(&map)?;
let timer = Instant::now();
let result = map
.raw_stream_from(&start)
.map_ok(apply!(2, String::from_utf8_lossy))
.map_ok(apply!(2, Cow::into_owned))
.take(limit.unwrap_or(usize::MAX))
.try_collect::<Vec<(String, String)>>()
.await?;
let query_time = timer.elapsed(); let query_time = timer.elapsed();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) let result = String::from_utf8_lossy(&handle);
.await self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```"))
} .await
}
#[admin_command] pub(super) async fn raw_maps(&self) -> Result {
pub(super) async fn raw_del(&self, map: String, key: String) -> Result { let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect();
let map = self.services.db.get(&map)?;
let timer = Instant::now();
map.remove(&key);
let query_time = timer.elapsed(); self.write_str(&format!("{list:#?}")).await
self.write_str(&format!("Operation completed in {query_time:?}")) }
.await
}
#[admin_command]
pub(super) async fn raw_get(&self, map: String, key: String) -> Result {
let map = self.services.db.get(&map)?;
let timer = Instant::now();
let handle = map.get(&key).await?;
let query_time = timer.elapsed();
let result = String::from_utf8_lossy(&handle);
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```"))
.await
}
#[admin_command]
pub(super) async fn raw_maps(&self) -> Result {
let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect();
self.write_str(&format!("{list:#?}")).await
} }
fn with_maps_or<'a>( fn with_maps_or<'a>(
+48 -47
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,67 +39,68 @@ 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;
writeln!(self, "| Server Name | Destination | Hostname | Expires |").await?; writeln!(self, "| Server Name | Destination | Hostname | Expires |").await?;
writeln!(self, "| ----------- | ----------- | -------- | ------- |").await?; writeln!(self, "| ----------- | ----------- | -------- | ------- |").await?;
let mut destinations = self.services.resolver.cache.destinations().boxed(); let mut destinations = self.services.resolver.cache.destinations().boxed();
while let Some((name, CachedDest { dest, host, expire })) = destinations.next().await { while let Some((name, CachedDest { dest, host, expire })) = destinations.next().await {
if let Some(server_name) = server_name.as_ref() { if let Some(server_name) = server_name.as_ref() {
if name != *server_name { if name != *server_name {
continue; continue;
}
} }
let expire = time::format(expire, "%+");
self.write_str(&format!("| {name} | {dest} | {host} | {expire} |\n"))
.await?;
} }
let expire = time::format(expire, "%+"); Ok(())
self.write_str(&format!("| {name} | {dest} | {host} | {expire} |\n"))
.await?;
} }
Ok(()) async fn overrides_cache(&self, server_name: Option<String>) -> Result {
} use service::resolver::cache::CachedOverride;
#[admin_command] writeln!(self, "| Server Name | IP | Port | Expires | Overriding |").await?;
async fn overrides_cache(&self, server_name: Option<String>) -> Result { writeln!(self, "| ----------- | --- | ----:| ------- | ---------- |").await?;
use service::resolver::cache::CachedOverride;
writeln!(self, "| Server Name | IP | Port | Expires | Overriding |").await?; let mut overrides = self.services.resolver.cache.overrides().boxed();
writeln!(self, "| ----------- | --- | ----:| ------- | ---------- |").await?;
let mut overrides = self.services.resolver.cache.overrides().boxed(); while let Some((name, CachedOverride { ips, port, expire, overriding })) =
overrides.next().await
while let Some((name, CachedOverride { ips, port, expire, overriding })) = {
overrides.next().await if let Some(server_name) = server_name.as_ref() {
{ if name != *server_name {
if let Some(server_name) = server_name.as_ref() { continue;
if name != *server_name { }
continue;
} }
let expire = time::format(expire, "%+");
self.write_str(&format!(
"| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n"
))
.await?;
} }
let expire = time::format(expire, "%+"); Ok(())
self.write_str(&format!("| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n"))
.await?;
} }
Ok(()) async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result {
} if all {
self.services.resolver.cache.clear().await;
#[admin_command] writeln!(self, "Resolver caches cleared!").await
async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result { } else if let Some(name) = name {
if all { self.services.resolver.cache.del_destination(&name);
self.services.resolver.cache.clear().await; self.services.resolver.cache.del_override(&name);
writeln!(self, "Resolver caches cleared!").await self.write_str(&format!("Cleared {name} from resolver caches!"))
} else if let Some(name) = name { .await
self.services.resolver.cache.del_destination(&name); } else {
self.services.resolver.cache.del_override(&name); Err!("Missing name. Supply a name or use --all to flush the whole cache.")
self.write_str(&format!("Cleared {name} from resolver caches!")) }
.await
} else {
Err!("Missing name. Supply a name or use --all to flush the whole cache.")
} }
} }
+30 -30
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,39 +23,39 @@ 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?;
let result = self let result = self
.services .services
.rooms .rooms
.timeline .timeline
.last_timeline_count(&room_id) .last_timeline_count(&room_id)
.await?; .await?;
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, from: Option<String>,
from: Option<String>, limit: Option<usize>,
limit: Option<usize>, ) -> Result {
) -> Result { let room_id = self.services.rooms.alias.resolve(&room_id).await?;
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
let from: Option<PduCount> = from.as_deref().map(str::parse).transpose()?; let from: Option<PduCount> = from.as_deref().map(str::parse).transpose()?;
let result: Vec<_> = self let result: Vec<_> = self
.services .services
.rooms .rooms
.timeline .timeline
.pdus_rev(&room_id, from) .pdus_rev(&room_id, from)
.try_take(limit.unwrap_or(3)) .try_take(limit.unwrap_or(3))
.try_collect() .try_collect()
.await?; .await?;
self.write_str(&format!("```\n{result:#?}\n```")).await self.write_str(&format!("```\n{result:#?}\n```")).await
}
} }
+16 -16
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,23 +17,23 @@ 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
.rooms .rooms
.short .short
.get_shorteventid(&event_id) .get_shorteventid(&event_id)
.await?; .await?;
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?;
let shortid = self.services.rooms.short.get_shortroomid(&room_id).await?; let shortid = self.services.rooms.short.get_shortroomid(&room_id).await?;
self.write_str(&format!("{shortid:#?}")).await self.write_str(&format!("{shortid:#?}")).await
}
} }
+255 -259
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,263 +92,259 @@ 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
.services .services
.rooms .rooms
.state_cache .state_cache
.get_shared_rooms(&user_a, &user_b) .get_shared_rooms(&user_a, &user_b)
.collect() .collect()
.await; .await;
let query_time = timer.elapsed(); let query_time = timer.elapsed();
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
} }
#[admin_command] async fn get_backup_session(
async fn get_backup_session( &self,
&self, user_id: OwnedUserId,
user_id: OwnedUserId, version: String,
version: String, room_id: OwnedRoomId,
room_id: OwnedRoomId, session_id: String,
session_id: String, ) -> Result {
) -> Result { let timer = tokio::time::Instant::now();
let timer = tokio::time::Instant::now(); let result = self
let result = self .services
.services .key_backups
.key_backups .get_session(&user_id, &version, &room_id, &session_id)
.get_session(&user_id, &version, &room_id, &session_id) .await;
.await; let query_time = timer.elapsed();
let query_time = timer.elapsed();
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 }
}
async fn get_room_backups(
#[admin_command] &self,
async fn get_room_backups( user_id: OwnedUserId,
&self, version: String,
user_id: OwnedUserId, room_id: OwnedRoomId,
version: String, ) -> Result {
room_id: OwnedRoomId, let timer = tokio::time::Instant::now();
) -> Result { let result = self
let timer = tokio::time::Instant::now(); .services
let result = self .key_backups
.services .get_room(&user_id, &version, &room_id)
.key_backups .await;
.get_room(&user_id, &version, &room_id) let query_time = timer.elapsed();
.await;
let query_time = timer.elapsed(); self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.await
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) }
.await
} async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result {
let timer = tokio::time::Instant::now();
#[admin_command] let result = self.services.key_backups.get_all(&user_id, &version).await;
async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result { let query_time = timer.elapsed();
let timer = tokio::time::Instant::now();
let result = self.services.key_backups.get_all(&user_id, &version).await; self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
let query_time = timer.elapsed(); .await
}
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.await async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> Result {
} let timer = tokio::time::Instant::now();
let result = self
#[admin_command] .services
async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> Result { .key_backups
let timer = tokio::time::Instant::now(); .get_backup(&user_id, &version)
let result = self .await;
.services let query_time = timer.elapsed();
.key_backups
.get_backup(&user_id, &version) self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.await; .await
let query_time = timer.elapsed(); }
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
.await let timer = tokio::time::Instant::now();
} let result = self
.services
#[admin_command] .key_backups
async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result { .get_latest_backup_version(&user_id)
let timer = tokio::time::Instant::now(); .await;
let result = self let query_time = timer.elapsed();
.services
.key_backups self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.get_latest_backup_version(&user_id) .await
.await; }
let query_time = timer.elapsed();
async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result {
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) let timer = tokio::time::Instant::now();
.await let result = self.services.key_backups.get_latest_backup(&user_id).await;
} let query_time = timer.elapsed();
#[admin_command] self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result { .await
let timer = tokio::time::Instant::now(); }
let result = self.services.key_backups.get_latest_backup(&user_id).await;
let query_time = timer.elapsed(); async fn iter_users(&self) -> Result {
let timer = tokio::time::Instant::now();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) let result: Vec<OwnedUserId> =
.await self.services.users.stream().map(Into::into).collect().await;
}
let query_time = timer.elapsed();
#[admin_command]
async fn iter_users(&self) -> Result { self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
let timer = tokio::time::Instant::now(); .await
let result: Vec<OwnedUserId> = self.services.users.stream().map(Into::into).collect().await; }
let query_time = timer.elapsed(); async fn iter_users2(&self) -> Result {
let timer = tokio::time::Instant::now();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) let result: Vec<_> = self.services.users.stream().collect().await;
.await let result: Vec<_> = result
} .into_iter()
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
#[admin_command] .collect();
async fn iter_users2(&self) -> Result {
let timer = tokio::time::Instant::now(); let query_time = timer.elapsed();
let result: Vec<_> = self.services.users.stream().collect().await;
let result: Vec<_> = result self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```"))
.into_iter() .await
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned()) }
.collect();
async fn count_users(&self) -> Result {
let query_time = timer.elapsed(); let timer = tokio::time::Instant::now();
let result = self.services.users.count().await;
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:?}\n```")) let query_time = timer.elapsed();
.await
} self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.await
#[admin_command] }
async fn count_users(&self) -> Result {
let timer = tokio::time::Instant::now(); async fn list_devices(&self, user_id: OwnedUserId) -> Result {
let result = self.services.users.count().await; let timer = tokio::time::Instant::now();
let query_time = timer.elapsed(); let devices = self
.services
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) .users
.await .all_device_ids(&user_id)
} .collect::<Vec<_>>()
.await;
#[admin_command]
async fn list_devices(&self, user_id: OwnedUserId) -> Result { let query_time = timer.elapsed();
let timer = tokio::time::Instant::now();
let devices = self self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
.services .await
.users }
.all_device_ids(&user_id)
.collect::<Vec<_>>() async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result {
.await; let timer = tokio::time::Instant::now();
let devices = self
let query_time = timer.elapsed(); .services
.users
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```")) .all_devices_metadata(&user_id)
.await .collect::<Vec<_>>()
} .await;
let query_time = timer.elapsed();
#[admin_command]
async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result { self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
let timer = tokio::time::Instant::now(); .await
let devices = self }
.services
.users async fn get_device_metadata(
.all_devices_metadata(&user_id) &self,
.collect::<Vec<_>>() user_id: OwnedUserId,
.await; device_id: OwnedDeviceId,
let query_time = timer.elapsed(); ) -> Result {
let timer = tokio::time::Instant::now();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```")) let device = self
.await .services
} .users
.get_device_metadata(&user_id, &device_id)
#[admin_command] .await;
async fn get_device_metadata(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { let query_time = timer.elapsed();
let timer = tokio::time::Instant::now();
let device = self self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
.services .await
.users }
.get_device_metadata(&user_id, &device_id)
.await; async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
let query_time = timer.elapsed(); let timer = tokio::time::Instant::now();
let device = self.services.users.get_devicelist_version(&user_id).await;
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```")) let query_time = timer.elapsed();
.await
} self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
.await
#[admin_command] }
async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); async fn count_one_time_keys(
let device = self.services.users.get_devicelist_version(&user_id).await; &self,
let query_time = timer.elapsed(); user_id: OwnedUserId,
device_id: OwnedDeviceId,
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```")) ) -> Result {
.await let timer = tokio::time::Instant::now();
} let result = self
.services
#[admin_command] .users
async fn count_one_time_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { .count_one_time_keys(&user_id, &device_id)
let timer = tokio::time::Instant::now(); .await;
let result = self let query_time = timer.elapsed();
.services
.users self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.count_one_time_keys(&user_id, &device_id) .await
.await; }
let query_time = timer.elapsed();
async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) let timer = tokio::time::Instant::now();
.await let result = self
} .services
.users
#[admin_command] .get_device_keys(&user_id, &device_id)
async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { .await;
let timer = tokio::time::Instant::now(); let query_time = timer.elapsed();
let result = self
.services self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.users .await
.get_device_keys(&user_id, &device_id) }
.await;
let query_time = timer.elapsed(); async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) let result = self.services.users.get_user_signing_key(&user_id).await;
.await let query_time = timer.elapsed();
}
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
#[admin_command] .await
async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result { }
let timer = tokio::time::Instant::now();
let result = self.services.users.get_user_signing_key(&user_id).await; async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
let query_time = timer.elapsed(); let timer = tokio::time::Instant::now();
let result = self
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) .services
.await .users
} .get_master_key(None, &user_id, &|_| true)
.await;
#[admin_command] let query_time = timer.elapsed();
async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now(); self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
let result = self .await
.services }
.users
.get_master_key(None, &user_id, &|_| true) async fn get_to_device_events(
.await; &self,
let query_time = timer.elapsed(); user_id: OwnedUserId,
device_id: OwnedDeviceId,
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```")) ) -> Result {
.await let timer = tokio::time::Instant::now();
} let result = self
.services
#[admin_command] .users
async fn get_to_device_events(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result { .get_to_device_events(&user_id, &device_id, None, None)
let timer = tokio::time::Instant::now(); .collect::<Vec<_>>()
let result = self .await;
.services let query_time = timer.elapsed();
.users
.get_to_device_events(&user_id, &device_id, None, None) self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.collect::<Vec<_>>() .await
.await; }
let query_time = timer.elapsed();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.await
} }
+72 -72
View File
@@ -2,83 +2,83 @@ 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};
#[allow(clippy::fn_params_excessive_bools)] impl crate::Context<'_> {
#[admin_command] #[allow(clippy::fn_params_excessive_bools)]
pub(super) async fn list_rooms( pub(super) async fn list_rooms(
&self, &self,
page: Option<usize>, page: Option<usize>,
exclude_disabled: bool, exclude_disabled: bool,
exclude_banned: bool, exclude_banned: bool,
include_empty: bool, include_empty: bool,
no_details: bool, no_details: bool,
) -> Result { ) -> Result {
// TODO: i know there's a way to do this with clap, but i can't seem to find it // TODO: i know there's a way to do this with clap, but i can't seem to find it
let page = page.unwrap_or(1); let page = page.unwrap_or(1);
let mut rooms = self let mut rooms = self
.services .services
.rooms .rooms
.metadata .metadata
.iter_ids() .iter_ids()
.filter_map(|room_id| async move { .filter_map(|room_id| async move {
(!exclude_disabled || !self.services.rooms.metadata.is_disabled(&room_id).await) (!exclude_disabled || !self.services.rooms.metadata.is_disabled(&room_id).await)
.then_some(room_id) .then_some(room_id)
}) })
.filter_map(|room_id| async move { .filter_map(|room_id| async move {
(!exclude_banned || !self.services.rooms.metadata.is_banned(&room_id).await) (!exclude_banned || !self.services.rooms.metadata.is_banned(&room_id).await)
.then_some(room_id) .then_some(room_id)
}) })
.then(async |room_id| get_room_info(self.services, &room_id).await) .then(async |room_id| get_room_info(self.services, &room_id).await)
.then(|(room_id, total_members, name)| async move { .then(|(room_id, total_members, name)| async move {
let local_members: Vec<_> = self let local_members: Vec<_> = self
.services .services
.rooms .rooms
.state_cache .state_cache
.active_local_users_in_room(&room_id) .active_local_users_in_room(&room_id)
.collect() .collect()
.await; .await;
let local_members = local_members.len(); let local_members = local_members.len();
(room_id, total_members, local_members, name) (room_id, total_members, local_members, name)
}) })
.filter_map(|(room_id, total_members, local_members, name)| async move { .filter_map(|(room_id, total_members, local_members, name)| async move {
(include_empty || local_members > 0).then_some((room_id, total_members, name)) (include_empty || local_members > 0).then_some((room_id, total_members, name))
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
.await; .await;
rooms.sort_by_key(|r| r.1); rooms.sort_by_key(|r| r.1);
rooms.reverse(); rooms.reverse();
let rooms = rooms let rooms = rooms
.into_iter() .into_iter()
.skip(page.saturating_sub(1).saturating_mul(PAGE_SIZE)) .skip(page.saturating_sub(1).saturating_mul(PAGE_SIZE))
.take(PAGE_SIZE) .take(PAGE_SIZE)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if rooms.is_empty() { if rooms.is_empty() {
return Err!("No more rooms."); return Err!("No more rooms.");
}
let body = rooms
.iter()
.map(|(id, members, name)| {
if no_details {
format!("{id}")
} else {
format!("{id}\tMembers: {members}\tName: {name}")
}
})
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len()))
.await
} }
let body = rooms pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result {
.iter() let result = self.services.rooms.metadata.exists(&room_id).await;
.map(|(id, members, name)| {
if no_details {
format!("{id}")
} else {
format!("{id}\tMembers: {members}\tName: {name}")
}
})
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len())) self.write_str(&format!("{result}")).await
.await }
}
#[admin_command]
pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result {
let result = self.services.rooms.metadata.exists(&room_id).await;
self.write_str(&format!("{result}")).await
} }
+54 -54
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,62 +26,62 @@ 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
.rooms .rooms
.state_accessor .state_accessor
.get_name(&room_id) .get_name(&room_id)
.await .await
.unwrap_or_else(|_| room_id.to_string()); .unwrap_or_else(|_| room_id.to_string());
let member_info: Vec<_> = self let member_info: Vec<_> = self
.services .services
.rooms .rooms
.state_cache .state_cache
.room_members(&room_id) .room_members(&room_id)
.ready_filter(|user_id| { .ready_filter(|user_id| {
local_only local_only
.then(|| self.services.globals.user_is_local(user_id)) .then(|| self.services.globals.user_is_local(user_id))
.unwrap_or(true) .unwrap_or(true)
}) })
.filter_map(|user_id| async move { .filter_map(|user_id| async move {
Some(( Some((
self.services self.services
.users .users
.displayname(&user_id) .displayname(&user_id)
.await .await
.unwrap_or_else(|_| user_id.to_string()), .unwrap_or_else(|_| user_id.to_string()),
user_id, user_id,
)) ))
}) })
.collect() .collect()
.await; .await;
let num = member_info.len(); let num = member_info.len();
let body = member_info let body = member_info
.into_iter() .into_iter()
.map(|(displayname, mxid)| format!("{mxid} | {displayname}")) .map(|(displayname, mxid)| format!("{mxid} | {displayname}"))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n"); .join("\n");
self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```")) self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```"))
.await .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 .rooms
.rooms .state_accessor
.state_accessor .get_room_topic(&room_id)
.get_room_topic(&room_id) .await
.await else {
else { return Err!("Room does not have a room topic set.");
return Err!("Room does not have a room topic set."); };
};
self.write_str(&format!("Room topic:\n```\n{room_topic}\n```")) self.write_str(&format!("Room topic:\n```\n{room_topic}\n```"))
.await .await
}
} }
+352 -351
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,238 +45,72 @@ 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);
let admin_room_alias = &self.services.globals.admin_alias; let admin_room_alias = &self.services.globals.admin_alias;
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_string().eq(&admin_room_id) || room.to_string().eq(admin_room_alias) { if room.to_string().eq(&admin_room_id) || room.to_string().eq(admin_room_alias) {
return Err!("Not allowed to ban the admin room."); return Err!("Not allowed to ban the admin room.");
}
} }
}
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}"
); );
}, },
};
debug!("Room specified is a room ID, banning room ID");
room_id.clone()
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
| Ok(room_alias) => room_alias,
| Err(e) => {
return Err!(
"Failed to parse room ID {room}. Please note that this requires a full \
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}"
);
},
};
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
locally, if not using get_alias_helper to fetch room ID remotely"
);
match self.services.rooms.alias.resolve_alias(&room_alias).await {
| Ok((room_id, servers)) => {
debug!(
%room_id,
?servers,
"Got federation response fetching room ID for room {room}"
);
room_id
},
| Err(e) => {
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
},
}
} else {
return Err!(
"Room specified is not a room ID or room alias. Please note that this requires \
a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`)",
);
}; };
debug!("Room specified is a room ID, banning room ID"); info!("Making all users leave the room {room_id} and forgetting it");
room_id.clone()
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
| Ok(room_alias) => room_alias,
| Err(e) => {
return Err!(
"Failed to parse room ID {room}. Please note that this requires a full room \
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}"
);
},
};
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
locally, if not using get_alias_helper to fetch room ID remotely"
);
match self.services.rooms.alias.resolve_alias(&room_alias).await {
| Ok((room_id, servers)) => {
debug!(
%room_id,
?servers,
"Got federation response fetching room ID for room {room}"
);
room_id
},
| Err(e) => {
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
},
}
} else {
return Err!(
"Room specified is not a room ID or room alias. Please note that this requires a \
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`)",
);
};
info!("Making all users leave the room {room_id} and forgetting it");
let mut users = self
.services
.rooms
.state_cache
.room_members(&room_id)
.ready_filter(|user| self.services.globals.user_is_local(user))
.boxed();
while let Some(ref user_id) = users.next().await {
info!(
"Attempting leave for user {user_id} in room {room_id} (ignoring all errors, \
evicting admins too)",
);
if let Err(e) = leave_room(self.services, user_id, &room_id, None)
.boxed()
.await
{
warn!("Failed to leave room: {e}");
}
self.services.rooms.state_cache.forget(&room_id, user_id);
}
self.services
.rooms
.alias
.local_aliases_for_room(&room_id)
.for_each(|local_alias| async move {
self.services
.rooms
.alias
.remove_alias(&local_alias, &self.services.globals.server_user)
.await
.ok();
})
.await;
self.services.rooms.directory.set_not_public(&room_id); // remove from the room directory
self.services.rooms.metadata.ban_room(&room_id, true); // prevent further joins
self.services.rooms.metadata.disable_room(&room_id, true); // disable federation
self.write_str(
"Room banned, removed all our local users, and disabled incoming federation with room.",
)
.await
}
#[admin_command]
async fn ban_list_of_rooms(&self) -> Result {
if self.body.len() < 2
|| !self.body[0].trim().starts_with("```")
|| self.body.last().unwrap_or(&"").trim() != "```"
{
return Err!("Expected code block in command body. Add --help for details.",);
}
let rooms_s = self
.body
.to_vec()
.drain(1..self.body.len().saturating_sub(1))
.collect::<Vec<_>>();
let admin_room_alias = &self.services.globals.admin_alias;
let mut room_ban_count: usize = 0;
let mut room_ids: Vec<OwnedRoomId> = Vec::new();
for &room in &rooms_s {
match <&RoomOrAliasId>::try_from(room) {
| Ok(room_alias_or_id) => {
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)
{
warn!("User specified admin room in bulk ban list, ignoring");
continue;
}
}
if room_alias_or_id.is_room_id() {
let room_id = match RoomId::parse(room_alias_or_id) {
| Ok(room_id) => room_id,
| Err(e) => {
// ignore rooms we failed to parse
warn!(
"Error parsing room \"{room}\" during bulk room banning, \
ignoring error and logging here: {e}"
);
continue;
},
};
room_ids.push(room_id.clone());
}
if room_alias_or_id.is_room_alias_id() {
match RoomAliasId::parse(room_alias_or_id) {
| Ok(room_alias) => {
let room_id = match self
.services
.rooms
.alias
.resolve_local_alias(&room_alias)
.await
{
| Ok(room_id) => room_id,
| _ => {
debug!(
"We don't have this room alias to a room ID locally, \
attempting to fetch room ID over federation"
);
match self
.services
.rooms
.alias
.resolve_alias(&room_alias)
.await
{
| Ok((room_id, servers)) => {
debug!(
%room_id,
?servers,
"Got federation response fetching room ID for \
{room}",
);
room_id
},
| Err(e) => {
warn!(
"Failed to resolve room alias {room} to a room \
ID: {e}"
);
continue;
},
}
},
};
room_ids.push(room_id);
},
| Err(e) => {
warn!(
"Error parsing room \"{room}\" during bulk room banning, \
ignoring error and logging here: {e}"
);
continue;
},
}
}
},
| Err(e) => {
warn!(
"Error parsing room \"{room}\" during bulk room banning, ignoring error and \
logging here: {e}"
);
continue;
},
}
}
for room_id in room_ids {
debug!("Banned {room_id} successfully");
room_ban_count = room_ban_count.saturating_add(1);
debug!("Making all users leave the room {room_id} and forgetting it");
let mut users = self let mut users = self
.services .services
.rooms .rooms
@@ -286,7 +120,7 @@ async fn ban_list_of_rooms(&self) -> Result {
.boxed(); .boxed();
while let Some(ref user_id) = users.next().await { while let Some(ref user_id) = users.next().await {
debug!( info!(
"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 errors, \
evicting admins too)", evicting admins too)",
); );
@@ -301,7 +135,6 @@ async fn ban_list_of_rooms(&self) -> Result {
self.services.rooms.state_cache.forget(&room_id, user_id); self.services.rooms.state_cache.forget(&room_id, user_id);
} }
// remove any local aliases, ignore errors
self.services self.services
.rooms .rooms
.alias .alias
@@ -316,139 +149,307 @@ async fn ban_list_of_rooms(&self) -> Result {
}) })
.await; .await;
self.services.rooms.metadata.ban_room(&room_id, true); self.services.rooms.directory.set_not_public(&room_id); // remove from the room directory
// unpublish from room directory, ignore errors self.services.rooms.metadata.ban_room(&room_id, true); // prevent further joins
self.services.rooms.directory.set_not_public(&room_id); self.services.rooms.metadata.disable_room(&room_id, true); // disable federation
self.services.rooms.metadata.disable_room(&room_id, true);
self.write_str(
"Room banned, removed all our local users, and disabled incoming federation with \
room.",
)
.await
} }
self.write_str(&format!( async fn ban_list_of_rooms(&self) -> Result {
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, and \ if self.body.len() < 2
disabled incoming federation with the room." || !self.body[0].trim().starts_with("```")
)) || self.body.last().unwrap_or(&"").trim() != "```"
.await {
} return Err!("Expected code block in command body. Add --help for details.",);
}
#[admin_command] let rooms_s = self
async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result { .body
let room_id = if room.is_room_id() { .to_vec()
let room_id = match RoomId::parse(&room) { .drain(1..self.body.len().saturating_sub(1))
| Ok(room_id) => room_id, .collect::<Vec<_>>();
| Err(e) => {
return Err!( let admin_room_alias = &self.services.globals.admin_alias;
"Failed to parse room ID {room}. Please note that this requires a full room \
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \ let mut room_ban_count: usize = 0;
(`#roomalias:example.com`): {e}" let mut room_ids: Vec<OwnedRoomId> = Vec::new();
for &room in &rooms_s {
match <&RoomOrAliasId>::try_from(room) {
| Ok(room_alias_or_id) => {
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)
{
warn!("User specified admin room in bulk ban list, ignoring");
continue;
}
}
if room_alias_or_id.is_room_id() {
let room_id = match RoomId::parse(room_alias_or_id) {
| Ok(room_id) => room_id,
| Err(e) => {
// ignore rooms we failed to parse
warn!(
"Error parsing room \"{room}\" during bulk room banning, \
ignoring error and logging here: {e}"
);
continue;
},
};
room_ids.push(room_id.clone());
}
if room_alias_or_id.is_room_alias_id() {
match RoomAliasId::parse(room_alias_or_id) {
| Ok(room_alias) => {
let room_id = match self
.services
.rooms
.alias
.resolve_local_alias(&room_alias)
.await
{
| Ok(room_id) => room_id,
| _ => {
debug!(
"We don't have this room alias to a room ID \
locally, attempting to fetch room ID over \
federation"
);
match self
.services
.rooms
.alias
.resolve_alias(&room_alias)
.await
{
| Ok((room_id, servers)) => {
debug!(
%room_id,
?servers,
"Got federation response fetching room ID for \
{room}",
);
room_id
},
| Err(e) => {
warn!(
"Failed to resolve room alias {room} to a \
room ID: {e}"
);
continue;
},
}
},
};
room_ids.push(room_id);
},
| Err(e) => {
warn!(
"Error parsing room \"{room}\" during bulk room banning, \
ignoring error and logging here: {e}"
);
continue;
},
}
}
},
| Err(e) => {
warn!(
"Error parsing room \"{room}\" during bulk room banning, ignoring error \
and logging here: {e}"
);
continue;
},
}
}
for room_id in room_ids {
debug!("Banned {room_id} successfully");
room_ban_count = room_ban_count.saturating_add(1);
debug!("Making all users leave the room {room_id} and forgetting it");
let mut users = self
.services
.rooms
.state_cache
.room_members(&room_id)
.ready_filter(|user| self.services.globals.user_is_local(user))
.boxed();
while let Some(ref user_id) = users.next().await {
debug!(
"Attempting leave for user {user_id} in room {room_id} (ignoring all \
errors, evicting admins too)",
); );
},
if let Err(e) = leave_room(self.services, user_id, &room_id, None)
.boxed()
.await
{
warn!("Failed to leave room: {e}");
}
self.services.rooms.state_cache.forget(&room_id, user_id);
}
// remove any local aliases, ignore errors
self.services
.rooms
.alias
.local_aliases_for_room(&room_id)
.for_each(|local_alias| async move {
self.services
.rooms
.alias
.remove_alias(&local_alias, &self.services.globals.server_user)
.await
.ok();
})
.await;
self.services.rooms.metadata.ban_room(&room_id, true);
// unpublish from room directory, ignore errors
self.services.rooms.directory.set_not_public(&room_id);
self.services.rooms.metadata.disable_room(&room_id, true);
}
self.write_str(&format!(
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, \
and disabled incoming federation with the room."
))
.await
}
async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
let room_id = if room.is_room_id() {
let room_id = match RoomId::parse(&room) {
| Ok(room_id) => room_id,
| Err(e) => {
return Err!(
"Failed to parse room ID {room}. Please note that this requires a full \
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}"
);
},
};
debug!("Room specified is a room ID, unbanning room ID");
self.services.rooms.metadata.ban_room(&room_id, false);
room_id.clone()
} else if room.is_room_alias_id() {
let room_alias = match RoomAliasId::parse(&room) {
| Ok(room_alias) => room_alias,
| Err(e) => {
return Err!(
"Failed to parse room ID {room}. Please note that this requires a full \
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}"
);
},
};
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
locally, if not using get_alias_helper to fetch room ID remotely"
);
let room_id = match self
.services
.rooms
.alias
.resolve_local_alias(&room_alias)
.await
{
| Ok(room_id) => room_id,
| _ => {
debug!(
"We don't have this room alias to a room ID locally, attempting to \
fetch room ID over federation"
);
match self.services.rooms.alias.resolve_alias(&room_alias).await {
| Ok((room_id, servers)) => {
debug!(
%room_id,
?servers,
"Got federation response fetching room ID for room {room}"
);
room_id
},
| Err(e) => {
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
},
}
},
};
self.services.rooms.metadata.ban_room(&room_id, false);
room_id
} else {
return Err!(
"Room specified is not a room ID or room alias. Please note that this requires \
a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`)",
);
}; };
debug!("Room specified is a room ID, unbanning room ID"); self.services.rooms.metadata.disable_room(&room_id, false);
self.services.rooms.metadata.ban_room(&room_id, false); self.write_str("Room unbanned and federation re-enabled.")
.await
}
room_id.clone() async fn list_banned_rooms(&self, no_details: bool) -> Result {
} else if room.is_room_alias_id() { let room_ids: Vec<OwnedRoomId> = self
let room_alias = match RoomAliasId::parse(&room) {
| Ok(room_alias) => room_alias,
| Err(e) => {
return Err!(
"Failed to parse room ID {room}. Please note that this requires a full room \
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`): {e}"
);
},
};
debug!(
"Room specified is not a room ID, attempting to resolve room alias to a room ID \
locally, if not using get_alias_helper to fetch room ID remotely"
);
let room_id = match self
.services .services
.rooms .rooms
.alias .metadata
.resolve_local_alias(&room_alias) .list_banned_rooms()
.await .map(Into::into)
{ .collect()
| Ok(room_id) => room_id, .await;
| _ => {
debug!(
"We don't have this room alias to a room ID locally, attempting to fetch \
room ID over federation"
);
match self.services.rooms.alias.resolve_alias(&room_alias).await { if room_ids.is_empty() {
| Ok((room_id, servers)) => { return Err!("No rooms are banned.");
debug!( }
%room_id,
?servers, let mut rooms = room_ids
"Got federation response fetching room ID for room {room}" .iter()
); .stream()
room_id .then(|room_id| get_room_info(self.services, room_id))
}, .collect::<Vec<_>>()
| Err(e) => { .await;
return Err!("Failed to resolve room alias {room} to a room ID: {e}");
}, rooms.sort_by_key(|r| r.1);
rooms.reverse();
let num = rooms.len();
let body = rooms
.iter()
.map(|(id, members, name)| {
if no_details {
format!("{id}")
} else {
format!("{id}\tMembers: {members}\tName: {name}")
} }
}, })
}; .collect::<Vec<_>>()
.join("\n");
self.services.rooms.metadata.ban_room(&room_id, false); self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
.await
room_id
} else {
return Err!(
"Room specified is not a room ID or room alias. Please note that this requires a \
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
(`#roomalias:example.com`)",
);
};
self.services.rooms.metadata.disable_room(&room_id, false);
self.write_str("Room unbanned and federation re-enabled.")
.await
}
#[admin_command]
async fn list_banned_rooms(&self, no_details: bool) -> Result {
let room_ids: Vec<OwnedRoomId> = self
.services
.rooms
.metadata
.list_banned_rooms()
.map(Into::into)
.collect()
.await;
if room_ids.is_empty() {
return Err!("No rooms are banned.");
} }
let mut rooms = room_ids
.iter()
.stream()
.then(|room_id| get_room_info(self.services, room_id))
.collect::<Vec<_>>()
.await;
rooms.sort_by_key(|r| r.1);
rooms.reverse();
let num = rooms.len();
let body = rooms
.iter()
.map(|(id, members, name)| {
if no_details {
format!("{id}")
} else {
format!("{id}\tMembers: {members}\tName: {name}")
}
})
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
.await
} }
+197 -210
View File
@@ -7,243 +7,230 @@ use conduwuit::{
}; };
use futures::TryStreamExt; use futures::TryStreamExt;
use crate::admin_command; impl crate::Context<'_> {
pub(super) async fn uptime(&self) -> Result {
let elapsed = self
.services
.server
.started
.elapsed()
.expect("standard duration");
#[admin_command] let result = time::pretty(elapsed);
pub(super) async fn uptime(&self) -> Result { self.write_str(&format!("{result}.")).await
let elapsed = self }
.services
.server
.started
.elapsed()
.expect("standard duration");
let result = time::pretty(elapsed); pub(super) async fn show_config(&self) -> Result {
self.write_str(&format!("{result}.")).await self.bail_restricted()?;
}
#[admin_command] self.write_str(&format!("{}", *self.services.server.config))
pub(super) async fn show_config(&self) -> Result { .await
self.bail_restricted()?; }
self.write_str(&format!("{}", *self.services.server.config)) pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
.await // 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.
let mut paths = Vec::new();
#[admin_command] // Add previously saved paths to the argument list
pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result { self.services
// The path argument is only what's optionally passed via the admin command, .config
// so we need to merge it with the existing paths if any were given at startup. .config_paths
let mut paths = Vec::new(); .clone()
.unwrap_or_default()
.iter()
.for_each(|p| paths.push(p.to_owned()));
// Add previously saved paths to the argument list // If a path is given, and it's not already in the list,
self.services // add it last, so that it overrides earlier files
.config if let Some(p) = path {
.config_paths if !paths.contains(&p) {
.clone() paths.push(p);
.unwrap_or_default() }
.iter()
.for_each(|p| paths.push(p.to_owned()));
// If a path is given, and it's not already in the list,
// add it last, so that it overrides earlier files
if let Some(p) = path {
if !paths.contains(&p) {
paths.push(p);
} }
self.services.config.reload(&paths)?;
self.write_str(&format!("Successfully reconfigured from paths: {paths:?}"))
.await
} }
self.services.config.reload(&paths)?; pub(super) async fn memory_usage(&self) -> Result {
let services_usage = self.services.memory_usage().await?;
let database_usage = self.services.db.db.memory_usage()?;
let allocator_usage = conduwuit::alloc::memory_usage()
.map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
self.write_str(&format!("Successfully reconfigured from paths: {paths:?}")) self.write_str(&format!(
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
))
.await .await
}
#[admin_command]
pub(super) async fn memory_usage(&self) -> Result {
let services_usage = self.services.memory_usage().await?;
let database_usage = self.services.db.db.memory_usage()?;
let allocator_usage =
conduwuit::alloc::memory_usage().map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
self.write_str(&format!(
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
))
.await
}
#[admin_command]
pub(super) async fn clear_caches(&self) -> Result {
self.services.clear_cache().await;
self.write_str("Done.").await
}
#[admin_command]
pub(super) async fn list_backups(&self) -> Result {
self.services
.db
.db
.backup_list()?
.try_stream()
.try_for_each(|result| writeln!(self, "{result}"))
.await
}
#[admin_command]
pub(super) async fn backup_database(&self) -> Result {
self.bail_restricted()?;
let db = Arc::clone(&self.services.db);
let result = self
.services
.server
.runtime()
.spawn_blocking(move || match db.db.backup() {
| Ok(()) => "Done".to_owned(),
| Err(e) => format!("Failed: {e}"),
})
.await?;
let count = self.services.db.db.backup_count()?;
self.write_str(&format!("{result}. Currently have {count} backups."))
.await
}
#[admin_command]
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
let message = message.join(" ");
self.services.admin.send_text(&message).await;
self.write_str("Notice was sent to #admins").await
}
#[admin_command]
pub(super) async fn reload_mods(&self) -> Result {
self.bail_restricted()?;
self.services.server.reload()?;
self.write_str("Reloading server...").await
}
#[admin_command]
#[cfg(unix)]
pub(super) async fn restart(&self, force: bool) -> Result {
use conduwuit::utils::sys::current_exe_deleted;
if !force && current_exe_deleted() {
return Err!(
"The server cannot be restarted because the executable changed. If this is expected \
use --force to override."
);
} }
self.services.server.restart()?; pub(super) async fn clear_caches(&self) -> Result {
self.services.clear_cache().await;
self.write_str("Restarting server...").await self.write_str("Done.").await
}
#[admin_command]
pub(super) async fn shutdown(&self) -> Result {
self.bail_restricted()?;
warn!("shutdown command");
self.services.server.shutdown()?;
self.write_str("Shutting down server...").await
}
#[admin_command]
pub(super) async fn list_features(&self) -> Result {
let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
.lock()
.expect("locked")
.values()
.flat_map(|f| f.iter())
.collect::<Vec<_>>();
enabled_features.sort_unstable();
enabled_features.dedup();
let mut available_features = conduwuit::build_metadata::WORKSPACE_FEATURES
.iter()
.flat_map(|(_, f)| f.iter())
.collect::<Vec<_>>();
available_features.sort_unstable();
available_features.dedup();
let mut features = String::new();
for feature in available_features {
let active = enabled_features.contains(&feature);
let emoji = if active { "✅" } else { "❌" };
let remark = if active { "[enabled]" } else { "" };
writeln!(features, "{emoji} {feature} {remark}")?;
} }
self.write_str(&features).await pub(super) async fn list_backups(&self) -> Result {
} self.services
.db
#[admin_command] .db
pub(super) async fn build_info(&self) -> Result { .backup_list()?
use conduwuit::build_metadata::built; .try_stream()
.try_for_each(|result| writeln!(self, "{result}"))
.await
}
let mut info = String::new(); pub(super) async fn backup_database(&self) -> Result {
self.bail_restricted()?;
let db = Arc::clone(&self.services.db);
let result = self
.services
.server
.runtime()
.spawn_blocking(move || match db.db.backup() {
| Ok(()) => "Done".to_owned(),
| Err(e) => format!("Failed: {e}"),
})
.await?;
let count = self.services.db.db.backup_count()?;
self.write_str(&format!("{result}. Currently have {count} backups."))
.await
}
// Version information pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
writeln!(info, "# Build Information\n")?; let message = message.join(" ");
writeln!(info, "**Version:** {}", built::PKG_VERSION)?; self.services.admin.send_text(&message).await;
writeln!(info, "**Package:** {}", built::PKG_NAME)?;
writeln!(info, "**Description:** {}", built::PKG_DESCRIPTION)?;
// Git information self.write_str("Notice was sent to #admins").await
writeln!(info, "\n## Git Information\n")?;
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH {
writeln!(info, "**Commit Hash:** {hash}")?;
}
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH_SHORT {
writeln!(info, "**Commit Hash (short):** {hash}")?;
}
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_WEB_URL {
writeln!(info, "**Repository:** {url}")?;
} }
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_COMMIT_URL {
writeln!(info, "**Commit URL:** {url}")?; pub(super) async fn reload_mods(&self) -> Result {
self.bail_restricted()?;
self.services.server.reload()?;
self.write_str("Reloading server...").await
} }
// Build environment #[cfg(unix)]
writeln!(info, "\n## Build Environment\n")?; pub(super) async fn restart(&self, force: bool) -> Result {
writeln!(info, "**Profile:** {}", built::PROFILE)?; use conduwuit::utils::sys::current_exe_deleted;
writeln!(info, "**Optimization Level:** {}", built::OPT_LEVEL)?;
writeln!(info, "**Debug:** {}", built::DEBUG)?;
writeln!(info, "**Target:** {}", built::TARGET)?;
writeln!(info, "**Host:** {}", built::HOST)?;
// Rust compiler information if !force && current_exe_deleted() {
writeln!(info, "\n## Compiler Information\n")?; return Err!(
writeln!(info, "**Rustc Version:** {}", built::RUSTC_VERSION)?; "The server cannot be restarted because the executable changed. If this is \
if !built::RUSTDOC_VERSION.is_empty() { expected use --force to override."
writeln!(info, "**Rustdoc Version:** {}", built::RUSTDOC_VERSION)?; );
}
self.services.server.restart()?;
self.write_str("Restarting server...").await
} }
// Target configuration pub(super) async fn shutdown(&self) -> Result {
writeln!(info, "\n## Target Configuration\n")?; self.bail_restricted()?;
writeln!(info, "**Architecture:** {}", built::CFG_TARGET_ARCH)?;
writeln!(info, "**OS:** {}", built::CFG_OS)?; warn!("shutdown command");
writeln!(info, "**Family:** {}", built::CFG_FAMILY)?; self.services.server.shutdown()?;
writeln!(info, "**Endianness:** {}", built::CFG_ENDIAN)?;
writeln!(info, "**Pointer Width:** {} bits", built::CFG_POINTER_WIDTH)?; self.write_str("Shutting down server...").await
if !built::CFG_ENV.is_empty() {
writeln!(info, "**Environment:** {}", built::CFG_ENV)?;
} }
// CI information pub(super) async fn list_features(&self) -> Result {
if let Some(ci) = built::CI_PLATFORM { let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
writeln!(info, "\n## CI Platform\n")?; .lock()
writeln!(info, "**Platform:** {ci}")?; .expect("locked")
.values()
.flat_map(|f| f.iter())
.collect::<Vec<_>>();
enabled_features.sort_unstable();
enabled_features.dedup();
let mut available_features = conduwuit::build_metadata::WORKSPACE_FEATURES
.iter()
.flat_map(|(_, f)| f.iter())
.collect::<Vec<_>>();
available_features.sort_unstable();
available_features.dedup();
let mut features = String::new();
for feature in available_features {
let active = enabled_features.contains(&feature);
let emoji = if active { "✅" } else { "❌" };
let remark = if active { "[enabled]" } else { "" };
writeln!(features, "{emoji} {feature} {remark}")?;
}
self.write_str(&features).await
} }
self.write_str(&info).await pub(super) async fn build_info(&self) -> Result {
use conduwuit::build_metadata::built;
let mut info = String::new();
// Version information
writeln!(info, "# Build Information\n")?;
writeln!(info, "**Version:** {}", built::PKG_VERSION)?;
writeln!(info, "**Package:** {}", built::PKG_NAME)?;
writeln!(info, "**Description:** {}", built::PKG_DESCRIPTION)?;
// Git information
writeln!(info, "\n## Git Information\n")?;
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH {
writeln!(info, "**Commit Hash:** {hash}")?;
}
if let Some(hash) = conduwuit::build_metadata::GIT_COMMIT_HASH_SHORT {
writeln!(info, "**Commit Hash (short):** {hash}")?;
}
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_WEB_URL {
writeln!(info, "**Repository:** {url}")?;
}
if let Some(url) = conduwuit::build_metadata::GIT_REMOTE_COMMIT_URL {
writeln!(info, "**Commit URL:** {url}")?;
}
// Build environment
writeln!(info, "\n## Build Environment\n")?;
writeln!(info, "**Profile:** {}", built::PROFILE)?;
writeln!(info, "**Optimization Level:** {}", built::OPT_LEVEL)?;
writeln!(info, "**Debug:** {}", built::DEBUG)?;
writeln!(info, "**Target:** {}", built::TARGET)?;
writeln!(info, "**Host:** {}", built::HOST)?;
// Rust compiler information
writeln!(info, "\n## Compiler Information\n")?;
writeln!(info, "**Rustc Version:** {}", built::RUSTC_VERSION)?;
if !built::RUSTDOC_VERSION.is_empty() {
writeln!(info, "**Rustdoc Version:** {}", built::RUSTDOC_VERSION)?;
}
// Target configuration
writeln!(info, "\n## Target Configuration\n")?;
writeln!(info, "**Architecture:** {}", built::CFG_TARGET_ARCH)?;
writeln!(info, "**OS:** {}", built::CFG_OS)?;
writeln!(info, "**Family:** {}", built::CFG_FAMILY)?;
writeln!(info, "**Endianness:** {}", built::CFG_ENDIAN)?;
writeln!(info, "**Pointer Width:** {} bits", built::CFG_POINTER_WIDTH)?;
if !built::CFG_ENV.is_empty() {
writeln!(info, "**Environment:** {}", built::CFG_ENV)?;
}
// CI information
if let Some(ci) = built::CI_PLATFORM {
writeln!(info, "\n## CI Platform\n")?;
writeln!(info, "**Platform:** {ci}")?;
}
self.write_str(&info).await
}
} }
+88 -65
View File
@@ -1,76 +1,99 @@
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 {
None None
} else if let Some(max_uses) = expires.max_uses { } else if let Some(max_uses) = expires.max_uses {
Some(TokenExpires::AfterUses(max_uses)) Some(TokenExpires::AfterUses(max_uses))
} else if expires.once { } else if expires.once {
Some(TokenExpires::AfterUses(1)) Some(TokenExpires::AfterUses(1))
} 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| {
.transpose()? utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?)
{ })
Some(TokenExpires::AfterTime(max_age)) .transpose()?
} else { {
unreachable!(); Some(TokenExpires::AfterTime(max_age))
} } else {
}; unreachable!();
}
};
let (token, info) = self let (token, info) = self
.services .services
.registration_tokens .registration_tokens
.issue_token(self.sender_or_service_user().into(), expires); .issue_token(self.sender_or_service_user().into(), expires);
self.write_str(&format!( self.write_str(&format!(
"New registration token issued: `{token}`. {}.", "New registration token issued: `{token}` . {}.",
if let Some(expires) = info.expires { if let Some(expires) = info.expires {
format!("{expires}") format!("{expires}")
} else { } else {
"Never expires".to_owned() "Never expires".to_owned()
} }
)) ))
.await
}
#[admin_command]
pub(super) async fn revoke_token(&self, token: String) -> Result {
let Some(token) = self
.services
.registration_tokens
.validate_token(token)
.await
else {
return Err!("This token does not exist or has already expired.");
};
self.services.registration_tokens.revoke_token(token)?;
self.write_str("Token revoked successfully.").await
}
#[admin_command]
pub(super) async fn list_tokens(&self) -> Result {
let tokens: Vec<_> = self
.services
.registration_tokens
.iterate_tokens()
.collect()
.await;
self.write_str(&format!("Found {} registration tokens:\n", tokens.len()))
.await?; .await?;
for token in tokens { if self
self.write_str(&format!("- {token}\n")).await?; .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(())
} }
Ok(()) pub(super) async fn revoke_token(&self, token: String) -> Result {
let Some(token) = self
.services
.registration_tokens
.validate_token(token)
.await
else {
return Err!("This token does not exist or has already expired.");
};
self.services.registration_tokens.revoke_token(token)?;
self.write_str("Token revoked successfully.").await
}
pub(super) async fn list_tokens(&self) -> Result {
let tokens: Vec<_> = self
.services
.registration_tokens
.iterate_tokens()
.collect()
.await;
self.write_str(&format!("Found {} registration tokens:\n", tokens.len()))
.await?;
for token in tokens {
self.write_str(&format!("- {token}\n")).await?;
}
Ok(())
}
} }
+1018 -1161
View File
File diff suppressed because it is too large. Load diff
-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,
+1 -1
View File
@@ -13,7 +13,7 @@ pub(crate) async fn ban_room(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<rooms::ban::v1::Request>, body: Ruma<rooms::ban::v1::Request>,
) -> Result<rooms::ban::v1::Response> { ) -> Result<rooms::ban::v1::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if !services.users.is_admin(sender_user).await { if !services.users.is_admin(sender_user).await {
return Err!(Request(Forbidden("Only server administrators can use this endpoint"))); return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
} }
+1 -1
View File
@@ -13,7 +13,7 @@ pub(crate) async fn list_rooms(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<rooms::list::v1::Request>, body: Ruma<rooms::list::v1::Request>,
) -> Result<rooms::list::v1::Response> { ) -> Result<rooms::list::v1::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if !services.users.is_admin(sender_user).await { if !services.users.is_admin(sender_user).await {
return Err!(Request(Forbidden("Only server administrators can use this endpoint"))); return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
} }
+46 -47
View File
@@ -24,10 +24,10 @@ 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; use crate::{Ruma, router::ClientIdentity};
pub(crate) mod register; pub(crate) mod register;
pub(crate) mod threepid; pub(crate) mod threepid;
@@ -49,41 +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(ref info) = body.appservice_info {
if !info.is_user_match(&user_id) {
return Err!(Request(Exclusive("Username is not in an appservice namespace.")));
}
}
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))
} }
@@ -111,7 +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(ref user_id) = body.sender_user { let identity = if let Some(identity) = body.identity.as_ref() {
// 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
@@ -121,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 {
@@ -157,7 +135,12 @@ pub(crate) async fn change_password_route(
services services
.users .users
.all_device_ids(&sender_user) .all_device_ids(&sender_user)
.ready_filter(|id| *id != body.sender_device()) .ready_filter(|id| {
body.identity
.as_ref()
.and_then(|identity| identity.sender_device())
.is_none_or(|sender_device| sender_device != *id)
})
.for_each(async |id| services.users.remove_device(&sender_user, &id).await) .for_each(async |id| services.users.remove_device(&sender_user, &id).await)
.await; .await;
@@ -173,7 +156,12 @@ pub(crate) async fn change_password_route(
.await .await
.ok() .ok()
.as_ref() .as_ref()
.is_some_and(|pusher_device| pusher_device != body.sender_device()) .is_some_and(|pusher_device| {
body.identity
.as_ref()
.and_then(|identity| identity.sender_device())
.is_none_or(|sender_device| sender_device != *pusher_device)
})
.then_some(pushkey) .then_some(pushkey)
}) })
.for_each(async |pushkey| { .for_each(async |pushkey| {
@@ -241,9 +229,11 @@ pub(crate) async fn whoami_route(
State(_): State<crate::State>, State(_): State<crate::State>,
body: Ruma<whoami::v3::Request>, body: Ruma<whoami::v3::Request>,
) -> Result<whoami::v3::Response> { ) -> Result<whoami::v3::Response> {
Ok(assign!(whoami::v3::Response::new(body.sender_user().to_owned(), false), { Ok(
device_id: body.sender_device, assign!(whoami::v3::Response::new(body.identity.expect_sender_user()?.to_owned(), false), {
})) device_id: body.identity.sender_device().map(ToOwned::to_owned),
}),
)
} }
/// # `POST /_matrix/client/r0/account/deactivate` /// # `POST /_matrix/client/r0/account/deactivate`
@@ -265,15 +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
.sender_user .identity
.as_ref() .as_ref()
.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
+57 -295
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,14 +43,12 @@ 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 =
services.config.allow_registration || services.firstrun.is_first_run(); services.config.allow_registration || services.firstrun.is_first_run();
if !allow_registration && body.appservice_info.is_none() { if !allow_registration && body.identity.is_none() {
info!( info!(
?body.username, ?body.username,
?body.initial_device_display_name, ?body.initial_device_display_name,
@@ -71,101 +60,59 @@ pub(crate) async fn register_route(
))); )));
} }
let identity = if body.appservice_info.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 } else {
return Err!(Request(InvalidParam("A password must be provided.")));
};
match body.appservice_info { let user_id = services
| Some(ref info) => .users
if !info.is_user_match(&user_id) && !emergency_mode_enabled { .determine_registration_user_id(body.username.clone(), identity.email.as_ref(), None)
return Err!(Request(Exclusive( .await?;
"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.appservice_info.is_some() { services
None .users
} else if let Some(password) = body.password.as_deref() { .create_local_account(&user_id, password, identity.email)
Some(HashedPassword::new(password)?) .await;
} else {
return Err!(Request(InvalidParam("A password must be provided"))); user_id
}; };
// Create user
services.users.create(&user_id, password).await?;
// Set an initial display name
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.appservice_info.is_none()
{
write!(displayname, " {}", services.server.config.new_user_displayname_suffix)?;
}
services
.users
.set_displayname(&user_id, Some(displayname.clone()));
// Initial account data
services
.account_data
.update(
None,
&user_id,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(PushRulesEvent::new(
push::Ruleset::server_default(&user_id).into(),
))
.expect("should be able to serialize push rules"),
)
.await?;
// Generate new device id if the user didn't specify one
let (token, device) = if !body.inhibit_login { let (token, device) = if !body.inhibit_login {
// If UIAA is disabled, we can't create a device. In that case only appservices
// can reach this point in the first place, so we return an error for them.
if !services.config.oauth.compatibility_mode.uiaa_available() {
return Err!(Request(AppserviceLoginUnsupported(
"User-interactive appservice registration is not available on this server."
)));
}
// Generate new device id if the user didn't specify one
let device_id = body let device_id = body
.device_id .device_id
.clone() .clone()
@@ -181,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()),
) )
@@ -191,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.appservice_info.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.appservice_info.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,
@@ -374,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,
}), }),
); );
@@ -421,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.
+23 -13
View File
@@ -11,9 +11,9 @@ use ruma::{
}, },
thirdparty::{Medium, ThirdPartyIdentifierInit}, thirdparty::{Medium, ThirdPartyIdentifierInit},
}; };
use service::{mailer::messages, uiaa::Identity}; use service::mailer::messages;
use crate::Ruma; use crate::{Ruma, router::ClientIdentity};
/// # `GET _matrix/client/v3/account/3pid` /// # `GET _matrix/client/v3/account/3pid`
/// ///
@@ -22,7 +22,7 @@ pub(crate) async fn third_party_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_3pids::v3::Request>, body: Ruma<get_3pids::v3::Request>,
) -> Result<get_3pids::v3::Response> { ) -> Result<get_3pids::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let mut threepids = vec![]; let mut threepids = vec![];
if let Some(email) = services if let Some(email) = services
@@ -53,6 +53,14 @@ pub(crate) async fn request_3pid_management_token_via_email_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<request_3pid_management_token_via_email::v3::Request>, body: Ruma<request_3pid_management_token_via_email::v3::Request>,
) -> Result<request_3pid_management_token_via_email::v3::Response> { ) -> Result<request_3pid_management_token_via_email::v3::Response> {
// Authentication for this endpoint is technically optional,
// but we require the user to be logged in
let sender_user = body
.identity
.as_ref()
.map(ClientIdentity::expect_sender_user)
.ok_or_else(|| err!(Request(MissingToken("Missing access token."))))??;
if !services.threepid.email_requirement().may_change() { if !services.threepid.email_requirement().may_change() {
return Err!(Request(Forbidden("You may not change your email address."))); return Err!(Request(Forbidden("You may not change your email address.")));
} }
@@ -76,7 +84,7 @@ pub(crate) async fn request_3pid_management_token_via_email_route(
Mailbox::new(None, email), Mailbox::new(None, email),
|verification_link| messages::ChangeEmail { |verification_link| messages::ChangeEmail {
server_name: services.config.server_name.as_str(), server_name: services.config.server_name.as_str(),
user_id: body.sender_user.as_deref(), user_id: Some(sender_user),
verification_link, verification_link,
}, },
&body.client_secret, &body.client_secret,
@@ -107,8 +115,6 @@ pub(crate) async fn add_3pid_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<add_3pid::v3::Request>, body: Ruma<add_3pid::v3::Request>,
) -> Result<add_3pid::v3::Response> { ) -> Result<add_3pid::v3::Response> {
let sender_user = body.sender_user();
if !services.threepid.email_requirement().may_change() { if !services.threepid.email_requirement().may_change() {
return Err!(Request(Forbidden("You may not change your email address."))); return Err!(Request(Forbidden("You may not change your email address.")));
} }
@@ -116,18 +122,24 @@ pub(crate) async fn add_3pid_route(
// Require password auth to add an email // Require password auth to add an email
let _ = services let _ = services
.uiaa .uiaa
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user))) .authenticate_password(
&body.auth,
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
.associate_localpart_email(sender_user.localpart(), &email) .associate_localpart_email(body.identity.expect_sender_user()?.localpart(), &email)
.await?; .await?;
Ok(add_3pid::v3::Response::new()) Ok(add_3pid::v3::Response::new())
@@ -138,8 +150,6 @@ pub(crate) async fn delete_3pid_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<delete_3pid::v3::Request>, body: Ruma<delete_3pid::v3::Request>,
) -> Result<delete_3pid::v3::Response> { ) -> Result<delete_3pid::v3::Response> {
let sender_user = body.sender_user();
if body.medium != Medium::Email { if body.medium != Medium::Email {
return Ok(delete_3pid::v3::Response::new(ThirdPartyIdRemovalStatus::NoSupport)); return Ok(delete_3pid::v3::Response::new(ThirdPartyIdRemovalStatus::NoSupport));
} }
@@ -150,7 +160,7 @@ pub(crate) async fn delete_3pid_route(
if services if services
.threepid .threepid
.disassociate_localpart_email(sender_user.localpart()) .disassociate_localpart_email(body.identity.expect_sender_user()?.localpart())
.await .await
.is_none() .is_none()
{ {
+8 -8
View File
@@ -22,9 +22,9 @@ pub(crate) async fn set_global_account_data_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<set_global_account_data::v3::Request>, body: Ruma<set_global_account_data::v3::Request>,
) -> Result<set_global_account_data::v3::Response> { ) -> Result<set_global_account_data::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if sender_user != body.user_id && body.appservice_info.is_none() { if sender_user != body.user_id && !body.identity.is_appservice() {
return Err!(Request(Forbidden("You cannot set account data for other users."))); return Err!(Request(Forbidden("You cannot set account data for other users.")));
} }
@@ -47,9 +47,9 @@ pub(crate) async fn set_room_account_data_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<set_room_account_data::v3::Request>, body: Ruma<set_room_account_data::v3::Request>,
) -> Result<set_room_account_data::v3::Response> { ) -> Result<set_room_account_data::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if sender_user != body.user_id && body.appservice_info.is_none() { if sender_user != body.user_id && !body.identity.is_appservice() {
return Err!(Request(Forbidden("You cannot set account data for other users."))); return Err!(Request(Forbidden("You cannot set account data for other users.")));
} }
@@ -72,9 +72,9 @@ pub(crate) async fn get_global_account_data_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_global_account_data::v3::Request>, body: Ruma<get_global_account_data::v3::Request>,
) -> Result<get_global_account_data::v3::Response> { ) -> Result<get_global_account_data::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if sender_user != body.user_id && body.appservice_info.is_none() { if sender_user != body.user_id && !body.identity.is_appservice() {
return Err!(Request(Forbidden("You cannot get account data of other users."))); return Err!(Request(Forbidden("You cannot get account data of other users.")));
} }
@@ -94,9 +94,9 @@ pub(crate) async fn get_room_account_data_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_room_account_data::v3::Request>, body: Ruma<get_room_account_data::v3::Request>,
) -> Result<get_room_account_data::v3::Response> { ) -> Result<get_room_account_data::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if sender_user != body.user_id && body.appservice_info.is_none() { if sender_user != body.user_id && !body.identity.is_appservice() {
return Err!(Request(Forbidden("You cannot get account data of other users."))); return Err!(Request(Forbidden("You cannot get account data of other users.")));
} }
+6 -5
View File
@@ -12,10 +12,11 @@ pub(crate) async fn get_suspended_status(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_suspended::v1::Request>, body: Ruma<get_suspended::v1::Request>,
) -> Result<get_suspended::v1::Response> { ) -> Result<get_suspended::v1::Response> {
let sender_user = body.sender_user(); let (admin, active) = join(
services.users.is_admin(body.identity.expect_sender_user()?),
let (admin, active) = services.users.is_active(&body.user_id),
join(services.users.is_admin(sender_user), services.users.is_active(&body.user_id)).await; )
.await;
if !admin { if !admin {
return Err!(Request(Forbidden("Only server administrators can use this endpoint"))); return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
} }
@@ -37,7 +38,7 @@ pub(crate) async fn put_suspended_status(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<set_suspended::v1::Request>, body: Ruma<set_suspended::v1::Request>,
) -> Result<set_suspended::v1::Response> { ) -> Result<set_suspended::v1::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let (sender_admin, active, target_admin) = join3( let (sender_admin, active, target_admin) = join3(
services.users.is_admin(sender_user), services.users.is_admin(sender_user),
+6 -4
View File
@@ -11,7 +11,8 @@ pub(crate) async fn create_alias_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<create_alias::v3::Request>, body: Ruma<create_alias::v3::Request>,
) -> Result<create_alias::v3::Response> { ) -> Result<create_alias::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
} }
@@ -19,7 +20,7 @@ pub(crate) async fn create_alias_route(
services services
.rooms .rooms
.alias .alias
.appservice_checks(&body.room_alias, &body.appservice_info) .appservice_checks(&body.room_alias, body.identity.appservice_info())
.await?; .await?;
// this isn't apart of alias_checks or delete alias route because we should // this isn't apart of alias_checks or delete alias route because we should
@@ -59,7 +60,8 @@ pub(crate) async fn delete_alias_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<delete_alias::v3::Request>, body: Ruma<delete_alias::v3::Request>,
) -> Result<delete_alias::v3::Response> { ) -> Result<delete_alias::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
} }
@@ -67,7 +69,7 @@ pub(crate) async fn delete_alias_route(
services services
.rooms .rooms
.alias .alias
.appservice_checks(&body.room_alias, &body.appservice_info) .appservice_checks(&body.room_alias, body.identity.appservice_info())
.await?; .await?;
services services
+2 -4
View File
@@ -1,5 +1,5 @@
use axum::extract::State; use axum::extract::State;
use conduwuit::{Err, Result, err}; use conduwuit::{Err, Result};
use ruma::{ use ruma::{
api::{appservice::ping, client::appservice::request_ping}, api::{appservice::ping, client::appservice::request_ping},
assign, assign,
@@ -15,9 +15,7 @@ pub(crate) async fn appservice_ping(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<request_ping::v1::Request>, body: Ruma<request_ping::v1::Request>,
) -> Result<request_ping::v1::Response> { ) -> Result<request_ping::v1::Response> {
let appservice_info = body.appservice_info.as_ref().ok_or_else(|| { let appservice_info = &body.identity;
err!(Request(Forbidden("This endpoint can only be called by appservices.")))
})?;
if body.appservice_id != appservice_info.registration.id { if body.appservice_id != appservice_info.registration.id {
return Err!(Request(Forbidden( return Err!(Request(Forbidden(
+47 -26
View File
@@ -25,7 +25,7 @@ pub(crate) async fn create_backup_version_route(
) -> Result<create_backup_version::v3::Response> { ) -> Result<create_backup_version::v3::Response> {
let version = services let version = services
.key_backups .key_backups
.create_backup(body.sender_user(), &body.algorithm)?; .create_backup(body.identity.expect_sender_user()?, &body.algorithm)?;
Ok(create_backup_version::v3::Response::new(version)) Ok(create_backup_version::v3::Response::new(version))
} }
@@ -40,7 +40,7 @@ pub(crate) async fn update_backup_version_route(
) -> Result<update_backup_version::v3::Response> { ) -> Result<update_backup_version::v3::Response> {
services services
.key_backups .key_backups
.update_backup(body.sender_user(), &body.version, &body.algorithm) .update_backup(body.identity.expect_sender_user()?, &body.version, &body.algorithm)
.await?; .await?;
Ok(update_backup_version::v3::Response::new()) Ok(update_backup_version::v3::Response::new())
@@ -53,13 +53,15 @@ pub(crate) async fn get_latest_backup_info_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_latest_backup_info::v3::Request>, body: Ruma<get_latest_backup_info::v3::Request>,
) -> Result<get_latest_backup_info::v3::Response> { ) -> Result<get_latest_backup_info::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
let (version, algorithm) = services let (version, algorithm) = services
.key_backups .key_backups
.get_latest_backup(body.sender_user()) .get_latest_backup(sender_user)
.await .await
.map_err(|_| err!(Request(NotFound("Key backup does not exist."))))?; .map_err(|_| err!(Request(NotFound("Key backup does not exist."))))?;
let (count, etag) = get_count_etag(&services, body.sender_user(), &version).await; let (count, etag) = get_count_etag(&services, sender_user, &version).await;
Ok(get_latest_backup_info::v3::Response::new(algorithm, count, etag, version)) Ok(get_latest_backup_info::v3::Response::new(algorithm, count, etag, version))
} }
@@ -71,15 +73,17 @@ pub(crate) async fn get_backup_info_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_backup_info::v3::Request>, body: Ruma<get_backup_info::v3::Request>,
) -> Result<get_backup_info::v3::Response> { ) -> Result<get_backup_info::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
let algorithm = services let algorithm = services
.key_backups .key_backups
.get_backup(body.sender_user(), &body.version) .get_backup(sender_user, &body.version)
.await .await
.map_err(|_| { .map_err(|_| {
err!(Request(NotFound("Key backup does not exist at version {:?}", body.version))) err!(Request(NotFound("Key backup does not exist at version {:?}", body.version)))
})?; })?;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await; let (count, etag) = get_count_etag(&services, sender_user, &body.version).await;
Ok(get_backup_info::v3::Response::new(algorithm, count, etag, body.version.clone())) Ok(get_backup_info::v3::Response::new(algorithm, count, etag, body.version.clone()))
} }
@@ -96,7 +100,7 @@ pub(crate) async fn delete_backup_version_route(
) -> Result<delete_backup_version::v3::Response> { ) -> Result<delete_backup_version::v3::Response> {
services services
.key_backups .key_backups
.delete_backup(body.sender_user(), &body.version) .delete_backup(body.identity.expect_sender_user()?, &body.version)
.await; .await;
Ok(delete_backup_version::v3::Response::new()) Ok(delete_backup_version::v3::Response::new())
@@ -114,9 +118,11 @@ pub(crate) async fn add_backup_keys_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<add_backup_keys::v3::Request>, body: Ruma<add_backup_keys::v3::Request>,
) -> Result<add_backup_keys::v3::Response> { ) -> Result<add_backup_keys::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
if services if services
.key_backups .key_backups
.get_latest_backup_version(body.sender_user()) .get_latest_backup_version(sender_user)
.await .await
.is_ok_and(|version| version != body.version) .is_ok_and(|version| version != body.version)
{ {
@@ -129,12 +135,12 @@ pub(crate) async fn add_backup_keys_route(
for (session_id, key_data) in &room.sessions { for (session_id, key_data) in &room.sessions {
services services
.key_backups .key_backups
.add_key(body.sender_user(), &body.version, room_id, session_id, key_data) .add_key(sender_user, &body.version, room_id, session_id, key_data)
.await?; .await?;
} }
} }
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await; let (count, etag) = get_count_etag(&services, sender_user, &body.version).await;
Ok(add_backup_keys::v3::Response::new(etag, count)) Ok(add_backup_keys::v3::Response::new(etag, count))
} }
@@ -151,9 +157,11 @@ pub(crate) async fn add_backup_keys_for_room_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<add_backup_keys_for_room::v3::Request>, body: Ruma<add_backup_keys_for_room::v3::Request>,
) -> Result<add_backup_keys_for_room::v3::Response> { ) -> Result<add_backup_keys_for_room::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
if services if services
.key_backups .key_backups
.get_latest_backup_version(body.sender_user()) .get_latest_backup_version(sender_user)
.await .await
.is_ok_and(|version| version != body.version) .is_ok_and(|version| version != body.version)
{ {
@@ -165,11 +173,11 @@ pub(crate) async fn add_backup_keys_for_room_route(
for (session_id, key_data) in &body.sessions { for (session_id, key_data) in &body.sessions {
services services
.key_backups .key_backups
.add_key(body.sender_user(), &body.version, &body.room_id, session_id, key_data) .add_key(sender_user, &body.version, &body.room_id, session_id, key_data)
.await?; .await?;
} }
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await; let (count, etag) = get_count_etag(&services, sender_user, &body.version).await;
Ok(add_backup_keys_for_room::v3::Response::new(etag, count)) Ok(add_backup_keys_for_room::v3::Response::new(etag, count))
} }
@@ -186,9 +194,11 @@ pub(crate) async fn add_backup_keys_for_session_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<add_backup_keys_for_session::v3::Request>, body: Ruma<add_backup_keys_for_session::v3::Request>,
) -> Result<add_backup_keys_for_session::v3::Response> { ) -> Result<add_backup_keys_for_session::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
if services if services
.key_backups .key_backups
.get_latest_backup_version(body.sender_user()) .get_latest_backup_version(sender_user)
.await .await
.is_ok_and(|version| version != body.version) .is_ok_and(|version| version != body.version)
{ {
@@ -201,7 +211,7 @@ pub(crate) async fn add_backup_keys_for_session_route(
let mut ok_to_replace = true; let mut ok_to_replace = true;
if let Some(old_key) = &services if let Some(old_key) = &services
.key_backups .key_backups
.get_session(body.sender_user(), &body.version, &body.room_id, &body.session_id) .get_session(sender_user, &body.version, &body.room_id, &body.session_id)
.await .await
.ok() .ok()
{ {
@@ -260,7 +270,7 @@ pub(crate) async fn add_backup_keys_for_session_route(
services services
.key_backups .key_backups
.add_key( .add_key(
body.sender_user(), sender_user,
&body.version, &body.version,
&body.room_id, &body.room_id,
&body.session_id, &body.session_id,
@@ -269,7 +279,7 @@ pub(crate) async fn add_backup_keys_for_session_route(
.await?; .await?;
} }
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await; let (count, etag) = get_count_etag(&services, sender_user, &body.version).await;
Ok(add_backup_keys_for_session::v3::Response::new(etag, count)) Ok(add_backup_keys_for_session::v3::Response::new(etag, count))
} }
@@ -283,7 +293,7 @@ pub(crate) async fn get_backup_keys_route(
) -> Result<get_backup_keys::v3::Response> { ) -> Result<get_backup_keys::v3::Response> {
let rooms = services let rooms = services
.key_backups .key_backups
.get_all(body.sender_user(), &body.version) .get_all(body.identity.expect_sender_user()?, &body.version)
.await; .await;
Ok(get_backup_keys::v3::Response::new(rooms)) Ok(get_backup_keys::v3::Response::new(rooms))
@@ -298,7 +308,7 @@ pub(crate) async fn get_backup_keys_for_room_route(
) -> Result<get_backup_keys_for_room::v3::Response> { ) -> Result<get_backup_keys_for_room::v3::Response> {
let sessions = services let sessions = services
.key_backups .key_backups
.get_room(body.sender_user(), &body.version, &body.room_id) .get_room(body.identity.expect_sender_user()?, &body.version, &body.room_id)
.await; .await;
Ok(get_backup_keys_for_room::v3::Response::new(sessions)) Ok(get_backup_keys_for_room::v3::Response::new(sessions))
@@ -313,7 +323,12 @@ pub(crate) async fn get_backup_keys_for_session_route(
) -> Result<get_backup_keys_for_session::v3::Response> { ) -> Result<get_backup_keys_for_session::v3::Response> {
let key_data = services let key_data = services
.key_backups .key_backups
.get_session(body.sender_user(), &body.version, &body.room_id, &body.session_id) .get_session(
body.identity.expect_sender_user()?,
&body.version,
&body.room_id,
&body.session_id,
)
.await .await
.map_err(|_| { .map_err(|_| {
err!(Request(NotFound(debug_error!("Backup key not found for this user's session.")))) err!(Request(NotFound(debug_error!("Backup key not found for this user's session."))))
@@ -329,12 +344,14 @@ pub(crate) async fn delete_backup_keys_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<delete_backup_keys::v3::Request>, body: Ruma<delete_backup_keys::v3::Request>,
) -> Result<delete_backup_keys::v3::Response> { ) -> Result<delete_backup_keys::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
services services
.key_backups .key_backups
.delete_all_keys(body.sender_user(), &body.version) .delete_all_keys(sender_user, &body.version)
.await; .await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await; let (count, etag) = get_count_etag(&services, sender_user, &body.version).await;
Ok(delete_backup_keys::v3::Response::new(etag, count)) Ok(delete_backup_keys::v3::Response::new(etag, count))
} }
@@ -346,12 +363,14 @@ pub(crate) async fn delete_backup_keys_for_room_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<delete_backup_keys_for_room::v3::Request>, body: Ruma<delete_backup_keys_for_room::v3::Request>,
) -> Result<delete_backup_keys_for_room::v3::Response> { ) -> Result<delete_backup_keys_for_room::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
services services
.key_backups .key_backups
.delete_room_keys(body.sender_user(), &body.version, &body.room_id) .delete_room_keys(sender_user, &body.version, &body.room_id)
.await; .await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await; let (count, etag) = get_count_etag(&services, sender_user, &body.version).await;
Ok(delete_backup_keys_for_room::v3::Response::new(etag, count)) Ok(delete_backup_keys_for_room::v3::Response::new(etag, count))
} }
@@ -363,12 +382,14 @@ pub(crate) async fn delete_backup_keys_for_session_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<delete_backup_keys_for_session::v3::Request>, body: Ruma<delete_backup_keys_for_session::v3::Request>,
) -> Result<delete_backup_keys_for_session::v3::Response> { ) -> Result<delete_backup_keys_for_session::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
services services
.key_backups .key_backups
.delete_room_key(body.sender_user(), &body.version, &body.room_id, &body.session_id) .delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)
.await; .await;
let (count, etag) = get_count_etag(&services, body.sender_user(), &body.version).await; let (count, etag) = get_count_etag(&services, sender_user, &body.version).await;
Ok(delete_backup_keys_for_session::v3::Response::new(etag, count)) Ok(delete_backup_keys_for_session::v3::Response::new(etag, count))
} }
+1 -1
View File
@@ -50,7 +50,7 @@ pub(crate) async fn get_capabilities_route(
if services if services
.users .users
.is_admin(body.sender_user.as_ref().unwrap()) .is_admin(body.identity.expect_sender_user()?)
.await .await
{ {
// Advertise suspension API // Advertise suspension API
+3 -3
View File
@@ -37,8 +37,8 @@ pub(crate) async fn get_context_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_context::v3::Request>, body: Ruma<get_context::v3::Request>,
) -> Result<get_context::v3::Response> { ) -> Result<get_context::v3::Response> {
let sender = body.sender(); let sender_user = body.identity.expect_sender_user()?;
let (sender_user, sender_device) = sender; let sender_device = body.identity.sender_device();
let room_id = &body.room_id; let room_id = &body.room_id;
let event_id = &body.event_id; let event_id = &body.event_id;
let filter = &body.filter; let filter = &body.filter;
@@ -143,7 +143,7 @@ pub(crate) async fn get_context_route(
let lazy_loading_context = lazy_loading::Context { let lazy_loading_context = lazy_loading::Context {
user_id: sender_user, user_id: sender_user,
device_id: Some(sender_device), device_id: sender_device,
room_id, room_id,
token: Some(base_count.into_unsigned()), token: Some(base_count.into_unsigned()),
options: Some(&filter.lazy_load_options), options: Some(&filter.lazy_load_options),
+5 -10
View File
@@ -25,16 +25,11 @@ pub(crate) async fn put_dehydrated_device_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<put_dehydrated_device::Request>, body: Ruma<put_dehydrated_device::Request>,
) -> Result<put_dehydrated_device::Response> { ) -> Result<put_dehydrated_device::Response> {
let sender_user = body let device_id = body.device_id.clone();
.sender_user
.as_deref()
.expect("AccessToken authentication required");
let device_id = body.body.device_id.clone();
services services
.users .users
.set_dehydrated_device(sender_user, body.body) .set_dehydrated_device(body.identity.expect_sender_user()?, body.body)
.await?; .await?;
Ok(put_dehydrated_device::Response::new(device_id)) Ok(put_dehydrated_device::Response::new(device_id))
@@ -49,7 +44,7 @@ pub(crate) async fn delete_dehydrated_device_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<delete_dehydrated_device::Request>, body: Ruma<delete_dehydrated_device::Request>,
) -> Result<delete_dehydrated_device::Response> { ) -> Result<delete_dehydrated_device::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let device_id = services.users.get_dehydrated_device_id(sender_user).await?; let device_id = services.users.get_dehydrated_device_id(sender_user).await?;
@@ -67,7 +62,7 @@ pub(crate) async fn get_dehydrated_device_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_dehydrated_device::Request>, body: Ruma<get_dehydrated_device::Request>,
) -> Result<get_dehydrated_device::Response> { ) -> Result<get_dehydrated_device::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let device = services.users.get_dehydrated_device(sender_user).await?; let device = services.users.get_dehydrated_device(sender_user).await?;
@@ -83,7 +78,7 @@ pub(crate) async fn get_dehydrated_events_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_events::Request>, body: Ruma<get_events::Request>,
) -> Result<get_events::Response> { ) -> Result<get_events::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let device_id = &body.body.device_id; let device_id = &body.body.device_id;
let existing_id = services.users.get_dehydrated_device_id(sender_user).await; let existing_id = services.users.get_dehydrated_device_id(sender_user).await;
+11 -13
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};
@@ -21,7 +20,7 @@ pub(crate) async fn get_devices_route(
) -> Result<get_devices::v3::Response> { ) -> Result<get_devices::v3::Response> {
let devices: Vec<device::Device> = services let devices: Vec<device::Device> = services
.users .users
.all_devices_metadata(body.sender_user()) .all_devices_metadata(body.identity.expect_sender_user()?)
.collect() .collect()
.await; .await;
@@ -37,7 +36,7 @@ pub(crate) async fn get_device_route(
) -> Result<get_device::v3::Response> { ) -> Result<get_device::v3::Response> {
let device = services let device = services
.users .users
.get_device_metadata(body.sender_user(), &body.body.device_id) .get_device_metadata(body.identity.expect_sender_user()?, &body.body.device_id)
.await .await
.map_err(|_| err!(Request(NotFound("Device not found."))))?; .map_err(|_| err!(Request(NotFound("Device not found."))))?;
@@ -53,8 +52,8 @@ pub(crate) async fn update_device_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<update_device::v3::Request>, body: Ruma<update_device::v3::Request>,
) -> Result<update_device::v3::Response> { ) -> Result<update_device::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let appservice = body.appservice_info.as_ref(); let appservice = body.identity.appservice_info();
match services match services
.users .users
@@ -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?;
@@ -118,15 +118,14 @@ pub(crate) async fn delete_device_route(
State(services): State<crate::State>, State(services): State<crate::State>,
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.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let appservice = body.appservice_info.as_ref();
// 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?;
} }
@@ -154,15 +153,14 @@ pub(crate) async fn delete_devices_route(
State(services): State<crate::State>, State(services): State<crate::State>,
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.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let appservice = body.appservice_info.as_ref();
// 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?;
} }
+2 -2
View File
@@ -112,7 +112,7 @@ pub(crate) async fn set_room_visibility_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<set_room_visibility::v3::Request>, body: Ruma<set_room_visibility::v3::Request>,
) -> Result<set_room_visibility::v3::Response> { ) -> Result<set_room_visibility::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if !services.rooms.metadata.exists(&body.room_id).await { if !services.rooms.metadata.exists(&body.room_id).await {
// Return 404 if the room doesn't exist // Return 404 if the room doesn't exist
@@ -130,7 +130,7 @@ pub(crate) async fn set_room_visibility_route(
| room::Visibility::Public => { | room::Visibility::Public => {
if services.server.config.lockdown_public_room_directory if services.server.config.lockdown_public_room_directory
&& !services.users.is_admin(sender_user).await && !services.users.is_admin(sender_user).await
&& body.appservice_info.is_none() && !body.identity.is_appservice()
{ {
info!( info!(
"Non-admin user {sender_user} tried to publish {0} to the room directory \ "Non-admin user {sender_user} tried to publish {0} to the room directory \
+2 -2
View File
@@ -15,7 +15,7 @@ pub(crate) async fn get_filter_route(
) -> Result<get_filter::v3::Response> { ) -> Result<get_filter::v3::Response> {
services services
.users .users
.get_filter(body.sender_user(), &body.filter_id) .get_filter(body.identity.expect_sender_user()?, &body.filter_id)
.await .await
.map(get_filter::v3::Response::new) .map(get_filter::v3::Response::new)
.map_err(|_| err!(Request(NotFound("Filter not found.")))) .map_err(|_| err!(Request(NotFound("Filter not found."))))
@@ -30,7 +30,7 @@ pub(crate) async fn create_filter_route(
) -> Result<create_filter::v3::Response> { ) -> Result<create_filter::v3::Response> {
let filter_id = services let filter_id = services
.users .users
.create_filter(body.sender_user(), &body.filter); .create_filter(body.identity.expect_sender_user()?, &body.filter);
Ok(create_filter::v3::Response::new(filter_id)) Ok(create_filter::v3::Response::new(filter_id))
} }
+13 -7
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;
@@ -41,7 +41,8 @@ pub(crate) async fn upload_keys_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<upload_keys::v3::Request>, body: Ruma<upload_keys::v3::Request>,
) -> Result<upload_keys::v3::Response> { ) -> Result<upload_keys::v3::Response> {
let (sender_user, sender_device) = body.sender(); let sender_user = body.identity.expect_sender_user()?;
let sender_device = body.identity.expect_sender_device()?;
for (key_id, one_time_key) in &body.one_time_keys { for (key_id, one_time_key) in &body.one_time_keys {
if one_time_key if one_time_key
@@ -154,7 +155,7 @@ pub(crate) async fn get_keys_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_keys::v3::Request>, body: Ruma<get_keys::v3::Request>,
) -> Result<get_keys::v3::Response> { ) -> Result<get_keys::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
get_keys_helper( get_keys_helper(
&services, &services,
@@ -191,7 +192,7 @@ pub(crate) async fn upload_signing_keys_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<upload_signing_keys::v3::Request>, body: Ruma<upload_signing_keys::v3::Request>,
) -> Result<upload_signing_keys::v3::Response> { ) -> Result<upload_signing_keys::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if uiaa_needed_to_upload_keys( if uiaa_needed_to_upload_keys(
services, services,
@@ -204,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?;
} }
@@ -287,7 +293,7 @@ pub(crate) async fn upload_signatures_route(
return Ok(upload_signatures::v3::Response::new()); return Ok(upload_signatures::v3::Response::new());
} }
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
for (user_id, keys) in &body.signed_keys { for (user_id, keys) in &body.signed_keys {
for (key_id, key) in keys { for (key_id, key) in keys {
@@ -340,7 +346,7 @@ pub(crate) async fn get_key_changes_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_key_changes::v3::Request>, body: Ruma<get_key_changes::v3::Request>,
) -> Result<get_key_changes::v3::Response> { ) -> Result<get_key_changes::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let mut device_list_updates = HashSet::new(); let mut device_list_updates = HashSet::new();
+5 -5
View File
@@ -53,7 +53,7 @@ pub(crate) async fn create_content_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<create_content::v3::Request>, body: Ruma<create_content::v3::Request>,
) -> Result<create_content::v3::Response> { ) -> Result<create_content::v3::Response> {
let user = body.sender_user(); let user = body.identity.expect_sender_user()?;
if services.users.is_suspended(user).await? { if services.users.is_suspended(user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
} }
@@ -92,7 +92,7 @@ pub(crate) async fn get_content_thumbnail_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_content_thumbnail::v1::Request>, body: Ruma<get_content_thumbnail::v1::Request>,
) -> Result<get_content_thumbnail::v1::Response> { ) -> Result<get_content_thumbnail::v1::Response> {
let user = body.sender_user(); let user = body.identity.expect_sender_user()?;
let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?; let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?;
let mxc = Mxc { let mxc = Mxc {
@@ -142,7 +142,7 @@ pub(crate) async fn get_content_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_content::v1::Request>, body: Ruma<get_content::v1::Request>,
) -> Result<get_content::v1::Response> { ) -> Result<get_content::v1::Response> {
let user = body.sender_user(); let user = body.identity.expect_sender_user()?;
let mxc = Mxc { let mxc = Mxc {
server_name: &body.server_name, server_name: &body.server_name,
@@ -189,7 +189,7 @@ pub(crate) async fn get_content_as_filename_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_content_as_filename::v1::Request>, body: Ruma<get_content_as_filename::v1::Request>,
) -> Result<get_content_as_filename::v1::Response> { ) -> Result<get_content_as_filename::v1::Response> {
let user = body.sender_user(); let user = body.identity.expect_sender_user()?;
let mxc = Mxc { let mxc = Mxc {
server_name: &body.server_name, server_name: &body.server_name,
@@ -240,7 +240,7 @@ pub(crate) async fn get_media_preview_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_media_preview::v1::Request>, body: Ruma<get_media_preview::v1::Request>,
) -> Result<get_media_preview::v1::Response> { ) -> Result<get_media_preview::v1::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let url = &body.url; let url = &body.url;
let url = Url::parse(&body.url).map_err(|e| { let url = Url::parse(&body.url).map_err(|e| {
+1 -1
View File
@@ -56,7 +56,7 @@ pub(crate) async fn get_media_preview_legacy_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<get_media_preview::v3::Request>, body: Ruma<get_media_preview::v3::Request>,
) -> Result<get_media_preview::v3::Response> { ) -> Result<get_media_preview::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let url = &body.url; let url = &body.url;
let url = Url::parse(&body.url).map_err(|e| { let url = Url::parse(&body.url).map_err(|e| {
+1 -1
View File
@@ -15,7 +15,7 @@ pub(crate) async fn ban_user_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<ban_user::v3::Request>, body: Ruma<ban_user::v3::Request>,
) -> Result<ban_user::v3::Response> { ) -> Result<ban_user::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if sender_user == body.user_id { if sender_user == body.user_id {
return Err!(Request(Forbidden("You cannot ban yourself."))); return Err!(Request(Forbidden("You cannot ban yourself.")));
+1 -1
View File
@@ -18,7 +18,7 @@ pub(crate) async fn forget_room_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<forget_room::v3::Request>, body: Ruma<forget_room::v3::Request>,
) -> Result<forget_room::v3::Response> { ) -> Result<forget_room::v3::Response> {
let user_id = body.sender_user(); let user_id = body.identity.expect_sender_user()?;
let room_id = &body.room_id; let room_id = &body.room_id;
let joined = services.rooms.state_cache.is_joined(user_id, room_id); let joined = services.rooms.state_cache.is_joined(user_id, room_id);
+1 -1
View File
@@ -29,7 +29,7 @@ pub(crate) async fn invite_user_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<invite_user::v3::Request>, body: Ruma<invite_user::v3::Request>,
) -> Result<invite_user::v3::Response> { ) -> Result<invite_user::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
} }
+2 -2
View File
@@ -28,7 +28,7 @@ pub(crate) async fn join_room_by_id_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<join_room_by_id::v3::Request>, body: Ruma<join_room_by_id::v3::Request>,
) -> Result<join_room_by_id::v3::Response> { ) -> Result<join_room_by_id::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
} }
@@ -97,7 +97,7 @@ pub(crate) async fn join_room_by_id_or_alias_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<join_room_by_id_or_alias::v3::Request>, body: Ruma<join_room_by_id_or_alias::v3::Request>,
) -> Result<join_room_by_id_or_alias::v3::Response> { ) -> Result<join_room_by_id_or_alias::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let body = &body.body; let body = &body.body;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
+1 -1
View File
@@ -15,7 +15,7 @@ pub(crate) async fn kick_user_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<kick_user::v3::Request>, body: Ruma<kick_user::v3::Request>,
) -> Result<kick_user::v3::Response> { ) -> Result<kick_user::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
} }
+1 -1
View File
@@ -51,7 +51,7 @@ pub(crate) async fn knock_room_route(
ClientIp(client): ClientIp, ClientIp(client): ClientIp,
body: Ruma<knock_room::v3::Request>, body: Ruma<knock_room::v3::Request>,
) -> Result<knock_room::v3::Response> { ) -> Result<knock_room::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let body = &body.body; let body = &body.body;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
+9 -4
View File
@@ -32,10 +32,15 @@ pub(crate) async fn leave_room_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<leave_room::v3::Request>, body: Ruma<leave_room::v3::Request>,
) -> Result<leave_room::v3::Response> { ) -> Result<leave_room::v3::Response> {
leave_room(&services, body.sender_user(), &body.room_id, body.reason.clone()) leave_room(
.boxed() &services,
.await body.identity.expect_sender_user()?,
.map(|()| leave_room::v3::Response::new()) &body.room_id,
body.reason.clone(),
)
.boxed()
.await
.map(|()| leave_room::v3::Response::new())
} }
// Make a user leave all their joined rooms, rescinds knocks, forgets all rooms, // Make a user leave all their joined rooms, rescinds knocks, forgets all rooms,
+2 -2
View File
@@ -30,7 +30,7 @@ pub(crate) async fn get_member_events_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_member_events::v3::Request>, body: Ruma<get_member_events::v3::Request>,
) -> Result<get_member_events::v3::Response> { ) -> Result<get_member_events::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let membership = body.membership.as_ref(); let membership = body.membership.as_ref();
let not_membership = body.not_membership.as_ref(); let not_membership = body.not_membership.as_ref();
@@ -72,7 +72,7 @@ pub(crate) async fn joined_members_route(
if !services if !services
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_state_events(body.sender_user(), &body.room_id) .user_can_see_state_events(body.identity.expect_sender_user()?, &body.room_id)
.await .await
{ {
return Err!(Request(Forbidden("You don't have permission to view this room."))); return Err!(Request(Forbidden("You don't have permission to view this room.")));
+1 -1
View File
@@ -40,7 +40,7 @@ pub(crate) async fn joined_rooms_route(
let joined_rooms = services let joined_rooms = services
.rooms .rooms
.state_cache .state_cache
.rooms_joined(body.sender_user()) .rooms_joined(body.identity.expect_sender_user()?)
.collect() .collect()
.await; .await;
+1 -1
View File
@@ -14,7 +14,7 @@ pub(crate) async fn unban_user_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<unban_user::v3::Request>, body: Ruma<unban_user::v3::Request>,
) -> Result<unban_user::v3::Response> { ) -> Result<unban_user::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if services.users.is_suspended(sender_user).await? { if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended."))); return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
} }
+4 -15
View File
@@ -23,7 +23,7 @@ use conduwuit_service::{
}; };
use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture, pin_mut}; use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture, pin_mut};
use ruma::{ use ruma::{
DeviceId, RoomId, UserId, RoomId, UserId,
api::{ api::{
Direction, Direction,
client::{filter::RoomEventFilter, message::get_message_events}, client::{filter::RoomEventFilter, message::get_message_events},
@@ -37,7 +37,6 @@ use ruma::{
serde::Raw, serde::Raw,
}; };
use ruminuwuity::invite_permission_config::FilterLevel; use ruminuwuity::invite_permission_config::FilterLevel;
use tracing::warn;
use crate::Ruma; use crate::Ruma;
@@ -76,8 +75,8 @@ pub(crate) async fn get_message_events_route(
ClientIp(client_ip): ClientIp, ClientIp(client_ip): ClientIp,
body: Ruma<get_message_events::v3::Request>, body: Ruma<get_message_events::v3::Request>,
) -> Result<get_message_events::v3::Response> { ) -> Result<get_message_events::v3::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
let sender_device = body.sender_device.as_deref(); let sender_device = body.identity.sender_device();
let room_id = &body.room_id; let room_id = &body.room_id;
let filter = &body.filter; let filter = &body.filter;
@@ -158,17 +157,7 @@ pub(crate) async fn get_message_events_route(
let lazy_loading_context = lazy_loading::Context { let lazy_loading_context = lazy_loading::Context {
user_id: sender_user, user_id: sender_user,
device_id: sender_device.or_else(|| { device_id: sender_device,
if let Some(registration) = body.appservice_info.as_ref() {
Some(<&DeviceId>::from(registration.registration.id.as_str()))
} else {
warn!(
"No device_id provided and no appservice registration found, this should be \
unreachable"
);
None
}
}),
room_id, room_id,
token: Some(from.into_unsigned()), token: Some(from.into_unsigned()),
options: Some(&filter.lazy_load_options), options: Some(&filter.lazy_load_options),
+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::*;
+1 -1
View File
@@ -15,7 +15,7 @@ pub(crate) async fn get_mutual_rooms_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<mutual_rooms::unstable::Request>, body: Ruma<mutual_rooms::unstable::Request>,
) -> Result<mutual_rooms::unstable::Response> { ) -> Result<mutual_rooms::unstable::Response> {
let sender_user = body.sender_user(); let sender_user = body.identity.expect_sender_user()?;
if sender_user == body.user_id { if sender_user == body.user_id {
return Err!(Request(Unknown("You cannot request rooms in common with yourself."))); return Err!(Request(Unknown("You cannot request rooms in common with yourself.")));
Loaded 100 of 361 files, more files were not shown because too many files have changed in this diff. Show more