mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-04 06:11:47 +00:00
Compare commits
238
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1b7710984 | ||
|
|
514c3bbcbf | ||
|
|
da7d8c9821 | ||
|
|
45809b7970 | ||
|
|
910925b906 | ||
|
|
28263982cd | ||
|
|
52a4b9d586 | ||
|
|
786890baa0 | ||
|
|
3282ba8eab | ||
|
|
f66c1d8f35 | ||
|
|
3d004b1923 | ||
|
|
06afe4f1a3 | ||
|
|
53d6887b86 | ||
|
|
8c77bd61e5 | ||
|
|
e649af33b9 | ||
|
|
e2fe166d63 | ||
|
|
4ee0bb7533 | ||
|
|
9a9cc94702 | ||
|
|
58a6e1232c | ||
|
|
c0cb4afd8a | ||
|
|
69163b5391 | ||
|
|
d4f6c053bc | ||
|
|
4f72326b07 | ||
|
|
b7e449f490 | ||
|
|
2a1d7e49d9 | ||
|
|
b7792f9e86 | ||
|
|
adfe9f9f53 | ||
|
|
8fe1715019 | ||
|
|
9a91dce600 | ||
|
|
eee4ef50d2 | ||
|
|
62e0b53f52 | ||
|
|
5fa3d5f6c8 | ||
|
|
9b80a99aa7 | ||
|
|
bd525c100f | ||
|
|
e6225f3265 | ||
|
|
54c94ca9ad | ||
|
|
017d4b3894 | ||
|
|
3b3eaf8744 | ||
|
|
0a634907f2 | ||
|
|
2f2848728f | ||
|
|
19a83c6891 | ||
|
|
2bfd678c71 | ||
|
|
e936d18324 | ||
|
|
90797fa3cd | ||
|
|
5eea8fe880 | ||
|
|
12491dcc26 | ||
|
|
2eff454787 | ||
|
|
e5dc5bedfc | ||
|
|
496ca52987 | ||
|
|
72f4c3cc53 | ||
|
|
6a8a114197 | ||
|
|
549864a052 | ||
|
|
52026bb0f1 | ||
|
|
aed8e7d769 | ||
|
|
32fb6f247a | ||
|
|
90e14abecb | ||
|
|
6ced2511e4 | ||
|
|
93407ade03 | ||
|
|
6742d9237a | ||
|
|
a32c7d0d9a | ||
|
|
761a6a53d0 | ||
|
|
c56c035c15 | ||
|
|
c804bf5780 | ||
|
|
b87afeef80 | ||
|
|
d0c7a62ce7 | ||
|
|
47582d1922 | ||
|
|
36a30f16b1 | ||
|
|
52ec6bc6da | ||
|
|
74788dcb19 | ||
|
|
b35b72c34a | ||
|
|
c1fc76040a | ||
|
|
d1449d6575 | ||
|
|
9fdeb61c1a | ||
|
|
7c7d6762e2 | ||
|
|
eda46d63a8 | ||
|
|
9fc9063c83 | ||
|
|
430347fc66 | ||
|
|
9df5c68d3c | ||
|
|
3ca068c985 | ||
|
|
138ec05cf2 | ||
|
|
c7e5c8df22 | ||
|
|
91afbd122f | ||
|
|
daaf09cb26 | ||
|
|
e8d6fa565e | ||
|
|
47af5d3a39 | ||
|
|
63b5fd04be | ||
|
|
d59a5c63f9 | ||
|
|
16aaeae21c | ||
|
|
e60310eacc | ||
|
|
7b98ae54b5 | ||
|
|
d67d6ca895 | ||
|
|
86d9e9e6a9 | ||
|
|
b37480d6b2 | ||
|
|
0d806a2038 | ||
|
|
19700a081e | ||
|
|
ed1b175fa4 | ||
|
|
a91fc7041a | ||
|
|
18c59e036f | ||
|
|
df3f646c92 | ||
|
|
fb6e5d2838 | ||
|
|
33be65a865 | ||
|
|
975ec24167 | ||
|
|
e8378e86fd | ||
|
|
57366ac90a | ||
|
|
9f8a716dc1 | ||
|
|
27367bac18 | ||
|
|
5199cde870 | ||
|
|
b6bc7dfc16 | ||
|
|
945ea5a78a | ||
|
|
d719fe2048 | ||
|
|
458e0b53ac | ||
|
|
2d65d47498 | ||
|
|
e4922814b9 | ||
|
|
064028689c | ||
|
|
124241238e | ||
|
|
967e2cc54f | ||
|
|
6fdeadc356 | ||
|
|
478560daae | ||
|
|
0310b4b2c5 | ||
|
|
3eb4257ae8 | ||
|
|
f1d3db0ea3 | ||
|
|
e7b302955f | ||
|
|
85122c62cd | ||
|
|
ba0ffee7cf | ||
|
|
86e1101b40 | ||
|
|
fdcb7e3957 | ||
|
|
c54e56a73e | ||
|
|
fed9a599d9 | ||
|
|
0bb97a53c5 | ||
|
|
9b76c9a085 | ||
|
|
6f20b7bc3f | ||
|
|
580d9b0318 | ||
|
|
ae572ec108 | ||
|
|
b1c5b3d000 | ||
|
|
0c9230f35e | ||
|
|
77dab8fd20 | ||
|
|
10b5ca8e3a | ||
|
|
f9eed42cb7 | ||
|
|
19f4c24c00 | ||
|
|
0a162b7bc4 | ||
|
|
0d1b130127 | ||
|
|
5e0e82e7e8 | ||
|
|
4bf0816bcc | ||
|
|
ecbe035b36 | ||
|
|
4d30ee5d33 | ||
|
|
4844c6ae3e | ||
|
|
6603798d60 | ||
|
|
199f6eb67b | ||
|
|
aa2f506996 | ||
|
|
a3994fe1a3 | ||
|
|
6312ff8088 | ||
|
|
17cff1fb36 | ||
|
|
aff6315ae1 | ||
|
|
574d3e9164 | ||
|
|
21e93f8feb | ||
|
|
4b2f032ae6 | ||
|
|
8a495a7d7f | ||
|
|
cee51d5717 | ||
|
|
0483d3e155 | ||
|
|
2a4b9f9323 | ||
|
|
63a1a3d9ab | ||
|
|
f19f5c71a5 | ||
|
|
b009ffd31c | ||
|
|
b6baf66399 | ||
|
|
6dac46e1ad | ||
|
|
4d40e20fdd | ||
|
|
3b6858e936 | ||
|
|
3b455218f5 | ||
|
|
7ca00e4ab9 | ||
|
|
b8ca06029f | ||
|
|
2efe8f2ec0 | ||
|
|
d1aa911739 | ||
|
|
4673282ca1 | ||
|
|
0c03195aec | ||
|
|
439bc2784d | ||
|
|
689a1ce59b | ||
|
|
c141503ccb | ||
|
|
bcadecdc3b | ||
|
|
ab3be337cb | ||
|
|
aa1281a9e0 | ||
|
|
115a2e802e | ||
|
|
968328d788 | ||
|
|
f1cde5f323 | ||
|
|
832ee8650b | ||
|
|
c0666a1793 | ||
|
|
ddb4ef539f | ||
|
|
3faedc4581 | ||
|
|
a3544353ba | ||
|
|
b0612397d3 | ||
|
|
31737e127e | ||
|
|
486dcd208c | ||
|
|
a945a4b2ad | ||
|
|
c28ea44e11 | ||
|
|
3e4d6b2565 | ||
|
|
29ce21cd2e | ||
|
|
d461c6977a | ||
|
|
5a0d6461d1 | ||
|
|
2ec7394785 | ||
|
|
8a5708b9f9 | ||
|
|
cd46070bd3 | ||
|
|
9930e549a0 | ||
|
|
36ed20cb04 | ||
|
|
3907589b6c | ||
|
|
2a598af888 | ||
|
|
f34f84832b | ||
|
|
0efa6ed1f2 | ||
|
|
2bf5876778 | ||
|
|
31982e84de | ||
|
|
970958652a | ||
|
|
c94a395bf0 | ||
|
|
43adff926f | ||
|
|
04fce56381 | ||
|
|
4df2097e6c | ||
|
|
8b85b04d10 | ||
|
|
9e0bcd3be8 | ||
|
|
9509080e0d | ||
|
|
61066bb0c6 | ||
|
|
573d5bc50e | ||
|
|
162e6eb92f | ||
|
|
cef4ebe38e | ||
|
|
316a0b7d58 | ||
|
|
2bcc56704b | ||
|
|
7f64de9727 | ||
|
|
aea03f2f99 | ||
|
|
8edf9552b8 | ||
|
|
d5f69c8a31 | ||
|
|
9ea9b0e04c | ||
|
|
e8db01fc8d | ||
|
|
f80e1e89a5 | ||
|
|
b9dca84acf | ||
|
|
e3ec1066c4 | ||
|
|
1445a8d446 | ||
|
|
9547c438d6 | ||
|
|
51d0e615f5 | ||
|
|
eeb937416c | ||
|
|
0d5aa7ede1 | ||
|
|
ba9dc27773 | ||
|
|
abf5a155ba |
No files matched your search
@@ -33,7 +33,7 @@ runs:
|
|||||||
echo "version=$(rustup --version)" >> $GITHUB_OUTPUT
|
echo "version=$(rustup --version)" >> $GITHUB_OUTPUT
|
||||||
- name: Cache rustup toolchains
|
- name: Cache rustup toolchains
|
||||||
if: steps.rustup-version.outputs.version == ''
|
if: steps.rustup-version.outputs.version == ''
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.rustup
|
~/.rustup
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ runs:
|
|||||||
|
|
||||||
- name: Check for LLVM cache
|
- name: Check for LLVM cache
|
||||||
id: cache
|
id: cache
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/usr/bin/clang-*
|
/usr/bin/clang-*
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ runs:
|
|||||||
|
|
||||||
- name: Cache toolchain binaries
|
- name: Cache toolchain binaries
|
||||||
id: toolchain-cache
|
id: toolchain-cache
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
.cargo/bin
|
.cargo/bin
|
||||||
@@ -76,7 +76,7 @@ runs:
|
|||||||
|
|
||||||
- name: Cache Cargo registry and git
|
- name: Cache Cargo registry and git
|
||||||
id: registry-cache
|
id: registry-cache
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
.cargo/registry/index
|
.cargo/registry/index
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ runs:
|
|||||||
|
|
||||||
- name: Restore binary cache
|
- name: Restore binary cache
|
||||||
id: binary-cache
|
id: binary-cache
|
||||||
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/usr/share/rust/.cargo/bin
|
/usr/share/rust/.cargo/bin
|
||||||
@@ -71,13 +71,13 @@ 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@9e1e5806d4a4822de933115878265be9aaa786d9 # v2
|
uses: https://github.com/taiki-e/install-action@9bcaee1dcae34154180f412e2fa69355a7cda9f6 # v2
|
||||||
with:
|
with:
|
||||||
tool: git-warp-time,timelord-cli@3.0.1
|
tool: git-warp-time,timelord-cli@3.0.1
|
||||||
|
|
||||||
- name: Save binary cache
|
- name: Save binary cache
|
||||||
if: steps.check-binaries.outputs.need-install == 'true'
|
if: steps.check-binaries.outputs.need-install == 'true'
|
||||||
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/usr/share/rust/.cargo/bin
|
/usr/share/rust/.cargo/bin
|
||||||
@@ -87,7 +87,7 @@ runs:
|
|||||||
|
|
||||||
- name: Restore timelord cache with fallbacks
|
- name: Restore timelord cache with fallbacks
|
||||||
id: timelord-restore
|
id: timelord-restore
|
||||||
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: ${{ env.TIMELORD_CACHE_PATH }}
|
path: ${{ env.TIMELORD_CACHE_PATH }}
|
||||||
key: ${{ env.TIMELORD_KEY }}
|
key: ${{ env.TIMELORD_KEY }}
|
||||||
@@ -114,7 +114,7 @@ runs:
|
|||||||
timelord sync --source-dir ${{ env.TIMELORD_PATH }} --cache-dir ${{ env.TIMELORD_CACHE_PATH }}
|
timelord sync --source-dir ${{ env.TIMELORD_PATH }} --cache-dir ${{ env.TIMELORD_CACHE_PATH }}
|
||||||
|
|
||||||
- name: Save updated timelord cache immediately
|
- name: Save updated timelord cache immediately
|
||||||
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: ${{ env.TIMELORD_CACHE_PATH }}
|
path: ${{ env.TIMELORD_CACHE_PATH }}
|
||||||
key: ${{ env.TIMELORD_KEY }}
|
key: ${{ env.TIMELORD_KEY }}
|
||||||
@@ -49,7 +49,7 @@ jobs:
|
|||||||
ref: ${{ github.ref_name }}
|
ref: ${{ github.ref_name }}
|
||||||
|
|
||||||
- name: Cache Cargo registry
|
- name: Cache Cargo registry
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.cargo/registry
|
~/.cargo/registry
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ jobs:
|
|||||||
|
|
||||||
|
|
||||||
- name: Cache DNF packages
|
- name: Cache DNF packages
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/var/cache/dnf
|
/var/cache/dnf
|
||||||
@@ -47,7 +47,7 @@ jobs:
|
|||||||
dnf-fedora${{ steps.fedora.outputs.version }}-
|
dnf-fedora${{ steps.fedora.outputs.version }}-
|
||||||
|
|
||||||
- name: Cache Cargo registry
|
- name: Cache Cargo registry
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.cargo/registry
|
~/.cargo/registry
|
||||||
@@ -57,7 +57,7 @@ jobs:
|
|||||||
cargo-fedora${{ steps.fedora.outputs.version }}-
|
cargo-fedora${{ steps.fedora.outputs.version }}-
|
||||||
|
|
||||||
- name: Cache Rust build dependencies
|
- name: Cache Rust build dependencies
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/rpmbuild/BUILD/*/target/release/deps
|
~/rpmbuild/BUILD/*/target/release/deps
|
||||||
|
|||||||
@@ -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@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
|
||||||
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"
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ jobs:
|
|||||||
node-version: 22
|
node-version: 22
|
||||||
|
|
||||||
- name: Cache npm dependencies
|
- name: Cache npm dependencies
|
||||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: ~/.npm
|
path: ~/.npm
|
||||||
key: continuwuity-rspress-${{ steps.runner-env.outputs.slug }}-${{ steps.runner-env.outputs.arch }}-node-${{ steps.runner-env.outputs.node_version }}-${{ hashFiles('package-lock.json') }}
|
key: continuwuity-rspress-${{ steps.runner-env.outputs.slug }}-${{ steps.runner-env.outputs.arch }}-node-${{ steps.runner-env.outputs.node_version }}-${{ hashFiles('package-lock.json') }}
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ jobs:
|
|||||||
# repositories: continuwuity
|
# repositories: continuwuity
|
||||||
|
|
||||||
- name: Install regsync
|
- name: Install regsync
|
||||||
uses: https://github.com/regclient/actions/regsync-installer@4b4db1dcc7dad75ad67a788a380f75a20cc8a040 # main
|
uses: https://github.com/regclient/actions/regsync-installer@9a2d4216180dbb3e2dccfa60d2dd4afd98e42ec5 # main
|
||||||
|
|
||||||
- name: Check what images need mirroring
|
- name: Check what images need mirroring
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ jobs:
|
|||||||
name: Renovate
|
name: Renovate
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container:
|
||||||
image: ghcr.io/renovatebot/renovate:43.234.0@sha256:bff111bfe347c559c615b658b28721eba5b7bb32a7b7901ea321336767209fe1
|
image: ghcr.io/renovatebot/renovate:43.246.1@sha256:5965c08f8ca5baff8dc9bf3a32c44ca71fef843ad94880e9696d46e1d722b0fa
|
||||||
options: --tmpfs /tmp:exec
|
options: --tmpfs /tmp:exec
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
@@ -55,7 +55,7 @@ jobs:
|
|||||||
run: /usr/local/renovate/node -e 'console.log(`node heap limit = ${require("v8").getHeapStatistics().heap_size_limit / (1024 * 1024)} Mb`)'
|
run: /usr/local/renovate/node -e 'console.log(`node heap limit = ${require("v8").getHeapStatistics().heap_size_limit / (1024 * 1024)} Mb`)'
|
||||||
|
|
||||||
- name: Restore renovate repo cache
|
- name: Restore renovate repo cache
|
||||||
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/tmp/renovate/cache/renovate/repository
|
/tmp/renovate/cache/renovate/repository
|
||||||
@@ -64,7 +64,7 @@ jobs:
|
|||||||
renovate-repo-cache-
|
renovate-repo-cache-
|
||||||
|
|
||||||
- name: Restore renovate package cache
|
- name: Restore renovate package cache
|
||||||
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/tmp/renovate/cache/renovate/renovate-cache-sqlite
|
/tmp/renovate/cache/renovate/renovate-cache-sqlite
|
||||||
@@ -73,7 +73,7 @@ jobs:
|
|||||||
renovate-package-cache-
|
renovate-package-cache-
|
||||||
|
|
||||||
- name: Restore renovate OSV cache
|
- name: Restore renovate OSV cache
|
||||||
uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/tmp/osv
|
/tmp/osv
|
||||||
@@ -117,7 +117,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Save renovate package cache
|
- name: Save renovate package cache
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/tmp/renovate/cache/renovate/renovate-cache-sqlite
|
/tmp/renovate/cache/renovate/renovate-cache-sqlite
|
||||||
@@ -125,7 +125,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Save renovate OSV cache
|
- name: Save renovate OSV cache
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
|
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
/tmp/osv
|
/tmp/osv
|
||||||
|
|||||||
Generated
+734
-119
File diff suppressed because it is too large.
Load diff
+9
-2
@@ -45,7 +45,7 @@ version = "1.0.6"
|
|||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
|
|
||||||
[workspace.dependencies.cargo_toml]
|
[workspace.dependencies.cargo_toml]
|
||||||
version = "0.22"
|
version = "1.0"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["features"]
|
features = ["features"]
|
||||||
|
|
||||||
@@ -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.27"
|
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]
|
||||||
@@ -356,6 +356,7 @@ features = [
|
|||||||
"ring-compat",
|
"ring-compat",
|
||||||
"compat-upload-signatures",
|
"compat-upload-signatures",
|
||||||
"compat-optional-txn-pdus",
|
"compat-optional-txn-pdus",
|
||||||
|
"compat-get-3pids",
|
||||||
"unstable-msc2666",
|
"unstable-msc2666",
|
||||||
"unstable-msc2867",
|
"unstable-msc2867",
|
||||||
"unstable-msc2870",
|
"unstable-msc2870",
|
||||||
@@ -402,6 +403,9 @@ default-features = false
|
|||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
|
[workspace.dependencies.openidconnect]
|
||||||
|
version = "4.0.1"
|
||||||
|
|
||||||
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
||||||
[workspace.dependencies.opentelemetry]
|
[workspace.dependencies.opentelemetry]
|
||||||
version = "0.32.0"
|
version = "0.32.0"
|
||||||
@@ -559,6 +563,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
|
||||||
#
|
#
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
Appservice device management as outlined in MSC4190 (part of Matrix 1.17) is now fully supported. Contributed by @ginger.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Users may now be forbidden from deactivating their own accounts with the new `allow_deactivation` config option. Contributed by @ginger.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Added support for authenticating clients using the new OAuth 2.0 login API. Contributed by @ginger.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
Improved the performance and reliability of fetching missing events, improving network partition recovery. Contributed
|
||||||
|
by @nex.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Added support for MSC4380 invite blocking, which has become part of the Matrix specification in v1.18. Contributed by @nex.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Added `!admin debug get-state-at` command
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Added support for linking an external identity provider with OIDC. Contributed by @ginger.
|
||||||
+144
-10
@@ -297,7 +297,7 @@
|
|||||||
|
|
||||||
# This item is undocumented. Please contribute documentation for it.
|
# This item is undocumented. Please contribute documentation for it.
|
||||||
#
|
#
|
||||||
#max_fetch_prev_events = 192
|
#max_fetch_prev_events = 1024
|
||||||
|
|
||||||
# How many incoming federation transactions the server is willing to be
|
# How many incoming federation transactions the server is willing to be
|
||||||
# processing at any given time before it becomes overloaded and starts
|
# processing at any given time before it becomes overloaded and starts
|
||||||
@@ -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.
|
||||||
#
|
#
|
||||||
@@ -645,6 +643,14 @@
|
|||||||
#
|
#
|
||||||
#default_room_acl_deny =
|
#default_room_acl_deny =
|
||||||
|
|
||||||
|
# The number of forward extremities to tolerate in a room before
|
||||||
|
# attempting to manually squash them with a "dummy event". Setting this
|
||||||
|
# above 20 will hinder its efficacy, and setting it below 5 will cause
|
||||||
|
# more dummy events to be sent than necessary (which increases federation
|
||||||
|
# traffic).
|
||||||
|
#
|
||||||
|
#dummy_event_threshold = 10
|
||||||
|
|
||||||
# Enable OpenTelemetry OTLP tracing export. This replaces the deprecated
|
# Enable OpenTelemetry OTLP tracing export. This replaces the deprecated
|
||||||
# Jaeger exporter. Traces will be sent via OTLP to a collector (such as
|
# Jaeger exporter. Traces will be sent via OTLP to a collector (such as
|
||||||
# Jaeger) that supports the OpenTelemetry Protocol.
|
# Jaeger) that supports the OpenTelemetry Protocol.
|
||||||
@@ -1428,6 +1434,11 @@
|
|||||||
#
|
#
|
||||||
#send_messages_from_ignored_users_to_client = false
|
#send_messages_from_ignored_users_to_client = false
|
||||||
|
|
||||||
|
# Send "org.matrix.dummy_event" events to the client. This is a debugging
|
||||||
|
# option.
|
||||||
|
#
|
||||||
|
#send_dummy_events_to_clients = false
|
||||||
|
|
||||||
# Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you
|
# Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you
|
||||||
# do not want continuwuity to send outbound requests to. Defaults to
|
# do not want continuwuity to send outbound requests to. Defaults to
|
||||||
# RFC1918, unroutable, loopback, multicast, and testnet addresses for
|
# RFC1918, unroutable, loopback, multicast, and testnet addresses for
|
||||||
@@ -1987,3 +1998,126 @@
|
|||||||
# `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"
|
||||||
|
|
||||||
|
#[global.oauth.oidc]
|
||||||
|
# Uncommenting this section will enable Continuwuity's support for
|
||||||
|
# authenticating users using an OpenID Connect-compatible identity provider.
|
||||||
|
# This is referred to as "delegated authentication".
|
||||||
|
#
|
||||||
|
# IMPORTANT NOTE: When delegated authentication is active, Continuwuity will behave as if
|
||||||
|
# the `global.oauth.compatibility_mode` setting is set to `exclusive`.
|
||||||
|
# Matrix clients which do not support OAuth login (also referred to as "next-gen auth") will NOT be able
|
||||||
|
# to log in while delegated authentication is active.
|
||||||
|
|
||||||
|
|
||||||
|
# The OIDC issuer URL. Continuwuity will use OpenID Connect Discovery to
|
||||||
|
# automatically fetch the identity provider's metadata from this URL.
|
||||||
|
# Generally you should set this to the base domain your identity provider
|
||||||
|
# runs on.
|
||||||
|
#
|
||||||
|
#discovery_url =
|
||||||
|
|
||||||
|
# The OAuth client ID for Continuwuity to use when communicating with the
|
||||||
|
# identity provider.
|
||||||
|
#
|
||||||
|
#client_id =
|
||||||
|
|
||||||
|
# The OAuth client secret for Continuwuity to use when communicating with
|
||||||
|
# the identity provider.
|
||||||
|
#
|
||||||
|
#client_secret =
|
||||||
|
|
||||||
|
# A path to a file which Continuwuity will read the client secret from.
|
||||||
|
# If this option is set, it will override `client_secret`.
|
||||||
|
#
|
||||||
|
# The server will fail to start if the file cannot be read.
|
||||||
|
#
|
||||||
|
#client_secret_file =
|
||||||
|
|
||||||
|
# Additional scopes Continuwuity should request from the IDP. This may be
|
||||||
|
# necessary to access certain claims. Continuwuity always requests the
|
||||||
|
# `openid` scope.
|
||||||
|
#
|
||||||
|
#additional_scopes = []
|
||||||
|
|
||||||
|
# Whether the user should be prompted to choose a localpart
|
||||||
|
# when signing in for the first time. If this is `false`, Continuwuity
|
||||||
|
# will attempt to use the value of the `preferred_username_claim`
|
||||||
|
# (see below) as the user's localpart. Authentication will
|
||||||
|
# fail if this claim is missing or is not a valid localpart.
|
||||||
|
#
|
||||||
|
#prompt_for_localpart = true
|
||||||
|
|
||||||
|
# The claim to use for the user's localpart, if `prompt_for_localpart` is
|
||||||
|
# false.
|
||||||
|
#
|
||||||
|
#preferred_username_claim = "preferred_username"
|
||||||
|
|
||||||
|
# The claim which will be used to set the user's email address,
|
||||||
|
# either on initial registration or on every login depending on
|
||||||
|
# the value of `profile_key_import_mode`. Continuwuity assumes that
|
||||||
|
# the IDP has taken care of verifying that the user controls the email
|
||||||
|
# address it provides.
|
||||||
|
#
|
||||||
|
# This option does nothing if SMTP is not configured.
|
||||||
|
#
|
||||||
|
# If this option is set, and `profile_key_import_mode` is `on_login`,
|
||||||
|
# users will not be able to change their email addresses themselves.
|
||||||
|
#
|
||||||
|
#email_claim = "email"
|
||||||
|
|
||||||
|
# Defines how claims returned from the IDP should be mapped to a user's
|
||||||
|
# profile data. The profile field named in each key will be set from the
|
||||||
|
# claim named in the corresponding value when the user first registers,
|
||||||
|
# and possibly on subsequent logins as well, depending on the value of
|
||||||
|
# `profile_key_import_mode` (see below).
|
||||||
|
#
|
||||||
|
# Per-room overrides to the user's display name or avatar will be
|
||||||
|
# preserved by the import process.
|
||||||
|
#
|
||||||
|
# SECURITY NOTE: If the `avatar_url` field is set, Continuwuity will
|
||||||
|
# perform a HTTP GET to the URL in the mapped claim and use the returned
|
||||||
|
# file as the user's profile picture. Make sure your users are not able
|
||||||
|
# to set the value of the mapped claim to an arbitrary URL.
|
||||||
|
#
|
||||||
|
#profile_key_map = { displayname = "name" }
|
||||||
|
|
||||||
|
# When profile keys should be imported from the IDP's claims.
|
||||||
|
#
|
||||||
|
# - "on_registration": Listed keys will be imported once, when the user
|
||||||
|
# logs in for the first time and their shadow account is created.
|
||||||
|
# - "on_login": Listed keys will be imported every time the user logs in.
|
||||||
|
# Additionally, users will not be able to manually edit any listed keys
|
||||||
|
# through their Matrix client.
|
||||||
|
#
|
||||||
|
#profile_key_import_mode = "on_registration"
|
||||||
@@ -10,7 +10,13 @@ Echo input of admin command
|
|||||||
|
|
||||||
## `!admin debug get-auth-chain`
|
## `!admin debug get-auth-chain`
|
||||||
|
|
||||||
Get the auth_chain of a PDU
|
Loads the auth_chain of a PDU, reporting how long it took
|
||||||
|
|
||||||
|
## `!admin debug show-auth-chain`
|
||||||
|
|
||||||
|
Walks & displays the auth_chain of a PDU in a mermaid graph format.
|
||||||
|
|
||||||
|
This is useless to basically anyone but developers, and is also probably slow and memory hungry.
|
||||||
|
|
||||||
## `!admin debug parse-pdu`
|
## `!admin debug parse-pdu`
|
||||||
|
|
||||||
@@ -44,6 +50,12 @@ This is functionally equivalent to `GET /_matrix/client/v3/rooms/{roomid}/state`
|
|||||||
|
|
||||||
Of course the check is still done on the actual client API.
|
Of course the check is still done on the actual client API.
|
||||||
|
|
||||||
|
## `!admin debug get-state-at`
|
||||||
|
|
||||||
|
Gets all the room state events at the specified event.
|
||||||
|
|
||||||
|
State at event might not be available for some PDUs, such as rejected ones.
|
||||||
|
|
||||||
## `!admin debug get-signing-keys`
|
## `!admin debug get-signing-keys`
|
||||||
|
|
||||||
Get and display signing keys from local cache or remote server
|
Get and display signing keys from local cache or remote server
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ Admin commands allow server administrators to manage the server from within thei
|
|||||||
- [`!admin appservices`](appservices/): Commands for managing appservices
|
- [`!admin appservices`](appservices/): Commands for managing appservices
|
||||||
- [`!admin users`](users/): Commands for managing local users
|
- [`!admin users`](users/): Commands for managing local users
|
||||||
- [`!admin token`](token/): Commands for managing registration tokens
|
- [`!admin token`](token/): Commands for managing registration tokens
|
||||||
|
- [`!admin oidc`](oidc/): Commands for managing OIDC
|
||||||
- [`!admin rooms`](rooms/): Commands for managing rooms
|
- [`!admin rooms`](rooms/): Commands for managing rooms
|
||||||
- [`!admin federation`](federation/): Commands for managing federation
|
- [`!admin federation`](federation/): Commands for managing federation
|
||||||
- [`!admin server`](server/): Commands for managing the server
|
- [`!admin server`](server/): Commands for managing the server
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!-- This file is generated by `cargo xtask generate-docs`. Do not edit. -->
|
||||||
|
# `!admin oidc`
|
||||||
|
|
||||||
|
Commands for managing OIDC
|
||||||
|
|
||||||
|
|
||||||
|
## `!admin oidc link`
|
||||||
|
|
||||||
|
Link a user ID to the given subject claim
|
||||||
|
|
||||||
|
## `!admin oidc unlink`
|
||||||
|
|
||||||
|
Unlink the given subject claim from its associated user ID
|
||||||
@@ -12,10 +12,6 @@ Create a new user
|
|||||||
|
|
||||||
Reset user password
|
Reset user password
|
||||||
|
|
||||||
## `!admin users issue-password-reset-link`
|
|
||||||
|
|
||||||
Issue a self-service password reset link for a user
|
|
||||||
|
|
||||||
## `!admin users get-email`
|
## `!admin users get-email`
|
||||||
|
|
||||||
Get a user's associated email address
|
Get a user's associated email address
|
||||||
@@ -96,6 +92,14 @@ Disables login for the specified user without deactivating or locking their acco
|
|||||||
|
|
||||||
List local users in the database
|
List local users in the database
|
||||||
|
|
||||||
|
## `!admin users list-invited-rooms`
|
||||||
|
|
||||||
|
Lists all the rooms (local and remote) that the specified user is invited to
|
||||||
|
|
||||||
|
## `!admin users reject-all-invites`
|
||||||
|
|
||||||
|
Manually make a user reject all current invites
|
||||||
|
|
||||||
## `!admin users list-joined-rooms`
|
## `!admin users list-joined-rooms`
|
||||||
|
|
||||||
Lists all the rooms (local and remote) that the specified user is joined in
|
Lists all the rooms (local and remote) that the specified user is joined in
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
+1
-1
@@ -9,7 +9,7 @@
|
|||||||
{
|
{
|
||||||
# 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 =
|
devShells.default =
|
||||||
(inputs.crane.mkLib pkgs).overrideToolchain (pkgs: self'.packages.stable-toolchain).devShell
|
((inputs.crane.mkLib pkgs).overrideToolchain (pkgs: self'.packages.stable-toolchain)).devShell
|
||||||
{
|
{
|
||||||
packages = [
|
packages = [
|
||||||
self'.packages.rocksdb
|
self'.packages.rocksdb
|
||||||
|
|||||||
+1
-1
@@ -12,7 +12,7 @@
|
|||||||
target:
|
target:
|
||||||
target.fromToolchainName {
|
target.fromToolchainName {
|
||||||
name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel;
|
name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel;
|
||||||
sha256 = "sha256-mvUGEOHYJpn3ikC5hckneuGixaC+yGrkMM/liDIDgoU=";
|
sha256 = "sha256-h+t2xTBz5yt2YIO+1VMIIGlCU7gyp2LYOFvaV1nwOXU=";
|
||||||
};
|
};
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
|
|||||||
Generated
+25
-25
@@ -383,18 +383,18 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rspress/core": {
|
"node_modules/@rspress/core": {
|
||||||
"version": "2.0.14",
|
"version": "2.0.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.14.tgz",
|
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.15.tgz",
|
||||||
"integrity": "sha512-k59i08zwBGgHrjHw8CK1m4CeTrKPvZRmV54bxubQl6AdDdmhJK6WrNg3UthwWmd38scKtqF40ATXDE8RMiNcNA==",
|
"integrity": "sha512-epLmUXYscNRw/GtQZx2oknoBE9wKbCrUGEOrQEDI4Qq8X32GdM4d7itzuHsliY7q3IbffKx8rMVbvlmygEocTQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@mdx-js/mdx": "^3.1.1",
|
"@mdx-js/mdx": "^3.1.1",
|
||||||
"@mdx-js/react": "^3.1.1",
|
"@mdx-js/react": "^3.1.1",
|
||||||
"@rsbuild/core": "^2.0.9",
|
"@rsbuild/core": "^2.0.15",
|
||||||
"@rsbuild/plugin-react": "~2.0.1",
|
"@rsbuild/plugin-react": "~2.0.1",
|
||||||
"@rspress/shared": "2.0.14",
|
"@rspress/shared": "2.0.15",
|
||||||
"@shikijs/rehype": "^4.0.2",
|
"@shikijs/rehype": "^4.2.0",
|
||||||
"@types/unist": "^3.0.3",
|
"@types/unist": "^3.0.3",
|
||||||
"@unhead/react": "^2.1.15",
|
"@unhead/react": "^2.1.15",
|
||||||
"body-scroll-lock": "4.0.0-beta.0",
|
"body-scroll-lock": "4.0.0-beta.0",
|
||||||
@@ -407,22 +407,22 @@
|
|||||||
"mdast-util-mdxjs-esm": "^2.0.1",
|
"mdast-util-mdxjs-esm": "^2.0.1",
|
||||||
"medium-zoom": "1.1.0",
|
"medium-zoom": "1.1.0",
|
||||||
"nprogress": "^0.2.0",
|
"nprogress": "^0.2.0",
|
||||||
"react": "^19.2.6",
|
"react": "^19.2.7",
|
||||||
"react-dom": "^19.2.6",
|
"react-dom": "^19.2.7",
|
||||||
"react-lazy-with-preload": "^2.2.1",
|
"react-lazy-with-preload": "^2.2.1",
|
||||||
"react-reconciler": "0.33.0",
|
"react-reconciler": "0.33.0",
|
||||||
"react-render-to-markdown": "19.1.0",
|
"react-render-to-markdown": "19.1.0",
|
||||||
"react-router-dom": "^7.15.1",
|
"react-router-dom": "^7.15.1",
|
||||||
"rehype-external-links": "^3.0.0",
|
"rehype-external-links": "^3.0.0",
|
||||||
"rehype-raw": "^7.0.0",
|
"rehype-raw": "^7.0.0",
|
||||||
"remark-cjk-friendly": "^2.0.1",
|
"remark-cjk-friendly": "^2.3.1",
|
||||||
"remark-cjk-friendly-gfm-strikethrough": "^2.0.1",
|
"remark-cjk-friendly-gfm-strikethrough": "^2.1.0",
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"remark-mdx": "^3.1.1",
|
"remark-mdx": "^3.1.1",
|
||||||
"remark-parse": "^11.0.0",
|
"remark-parse": "^11.0.0",
|
||||||
"remark-stringify": "^11.0.0",
|
"remark-stringify": "^11.0.0",
|
||||||
"scroll-into-view-if-needed": "^3.1.0",
|
"scroll-into-view-if-needed": "^3.1.0",
|
||||||
"shiki": "^4.0.2",
|
"shiki": "^4.2.0",
|
||||||
"unified": "^11.0.5",
|
"unified": "^11.0.5",
|
||||||
"unist-util-remove": "^4.0.0",
|
"unist-util-remove": "^4.0.0",
|
||||||
"unist-util-visit": "^5.1.0",
|
"unist-util-visit": "^5.1.0",
|
||||||
@@ -436,9 +436,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rspress/plugin-client-redirects": {
|
"node_modules/@rspress/plugin-client-redirects": {
|
||||||
"version": "2.0.14",
|
"version": "2.0.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.14.tgz",
|
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.15.tgz",
|
||||||
"integrity": "sha512-/WpbWUiepQglpPeplxCnELe2c7VdBUxPiICPAVnS1ZxAFdYkIpW0C+Vbk1t08kZqx8EAZGu+s6Zy43zyQpjdxg==",
|
"integrity": "sha512-bPf/KIHH7Y6huLTtK6JXwRfxM7zKjksoxm46+IBsF1wisw0doKkEKR9HwJydxWnykyKBbA2cuZOaoT4h174Z1w==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -449,9 +449,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rspress/plugin-sitemap": {
|
"node_modules/@rspress/plugin-sitemap": {
|
||||||
"version": "2.0.14",
|
"version": "2.0.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.14.tgz",
|
"resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.15.tgz",
|
||||||
"integrity": "sha512-Gpone22PvXGfGRSyi/WM8IXgsvKhNspXqHjtPD3g62jX8SJL3kpj2YZ2V28WEkg672fICauUYXrpre74Rddcsw==",
|
"integrity": "sha512-z1hbyGP79ZXdSGJxiWw7ZjmX8qW0q9nXMDxr14cVEg/wdj7ToVzGtZHw0wvTPE0YiKG3BMiGkVNfE1rdOaPXiQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -462,14 +462,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rspress/shared": {
|
"node_modules/@rspress/shared": {
|
||||||
"version": "2.0.14",
|
"version": "2.0.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.14.tgz",
|
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.15.tgz",
|
||||||
"integrity": "sha512-sCe9tAo+s9tR4DmFSjMyHOxQvhzTSYXkkMUfVEo5w+uMCNXXGAIC6D0xAVDMHq1jIFF9ix47VxzlCo+CYNS14g==",
|
"integrity": "sha512-o8aYwEzNuTmWnmKe91ntPv+34u3RbtAe+rcK9XC5MANOlgncwOaCs3bUa8/B1/llwyLoNgrpi+VB9bEiU11ZRQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@rsbuild/core": "^2.0.9",
|
"@rsbuild/core": "^2.0.15",
|
||||||
"@shikijs/rehype": "^4.0.2",
|
"@shikijs/rehype": "^4.2.0",
|
||||||
"unified": "^11.0.5"
|
"unified": "^11.0.5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -3058,9 +3058,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/remark-cjk-friendly": {
|
"node_modules/remark-cjk-friendly": {
|
||||||
"version": "2.1.0",
|
"version": "2.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.3.1.tgz",
|
||||||
"integrity": "sha512-ZWGDfTJNLEZ1gap+pd33K13ZhRAWgVDqxKA7JIlBs5IDu+qvbiWl/pEbeuxzRrWyrrkeFFoTnvNw00iW9mBcow==",
|
"integrity": "sha512-f+pKZRxCRwNEGFBKNRAZAqU91GIK1SAo3ZyFHWRUgC9zcxRR0BXKd6YwqgSsxtW0rNpUDtONj7H5nje2WL3fcA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
[toolchain]
|
[toolchain]
|
||||||
profile = "minimal"
|
profile = "minimal"
|
||||||
channel = "1.96.0"
|
channel = "1.96.1"
|
||||||
components = [
|
components = [
|
||||||
# For rust-analyzer
|
# For rust-analyzer
|
||||||
"rust-src",
|
"rust-src",
|
||||||
|
|||||||
+26
-11
@@ -1,5 +1,5 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use conduwuit::Result;
|
use conduwuit::{Err, Result};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
appservice::{self, AppserviceCommand},
|
appservice::{self, AppserviceCommand},
|
||||||
@@ -8,6 +8,7 @@ use crate::{
|
|||||||
debug::{self, DebugCommand},
|
debug::{self, DebugCommand},
|
||||||
federation::{self, FederationCommand},
|
federation::{self, FederationCommand},
|
||||||
media::{self, MediaCommand},
|
media::{self, MediaCommand},
|
||||||
|
oidc::{self, OidcCommand},
|
||||||
query::{self, QueryCommand},
|
query::{self, QueryCommand},
|
||||||
room::{self, RoomCommand},
|
room::{self, RoomCommand},
|
||||||
server::{self, ServerCommand},
|
server::{self, ServerCommand},
|
||||||
@@ -16,46 +17,50 @@ 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)]
|
|
||||||
/// Commands for managing appservices
|
/// Commands for managing appservices
|
||||||
|
#[command(subcommand)]
|
||||||
Appservices(AppserviceCommand),
|
Appservices(AppserviceCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Commands for managing local users
|
/// Commands for managing local users
|
||||||
|
#[command(subcommand)]
|
||||||
Users(UserCommand),
|
Users(UserCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Commands for managing registration tokens
|
/// Commands for managing registration tokens
|
||||||
|
#[command(subcommand)]
|
||||||
Token(TokenCommand),
|
Token(TokenCommand),
|
||||||
|
|
||||||
|
/// Commands for managing OIDC
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
Oidc(OidcCommand),
|
||||||
|
|
||||||
/// Commands for managing rooms
|
/// Commands for managing rooms
|
||||||
|
#[command(subcommand)]
|
||||||
Rooms(RoomCommand),
|
Rooms(RoomCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Commands for managing federation
|
/// Commands for managing federation
|
||||||
|
#[command(subcommand)]
|
||||||
Federation(FederationCommand),
|
Federation(FederationCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Commands for managing the server
|
/// Commands for managing the server
|
||||||
|
#[command(subcommand)]
|
||||||
Server(ServerCommand),
|
Server(ServerCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Commands for managing media
|
/// Commands for managing media
|
||||||
|
#[command(subcommand)]
|
||||||
Media(MediaCommand),
|
Media(MediaCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Commands for checking integrity
|
/// Commands for checking integrity
|
||||||
|
#[command(subcommand)]
|
||||||
Check(CheckCommand),
|
Check(CheckCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Commands for debugging things
|
/// Commands for debugging things
|
||||||
|
#[command(subcommand)]
|
||||||
Debug(DebugCommand),
|
Debug(DebugCommand),
|
||||||
|
|
||||||
#[command(subcommand)]
|
|
||||||
/// Low-level queries for database getters and iterators
|
/// Low-level queries for database getters and iterators
|
||||||
|
#[command(subcommand)]
|
||||||
Query(QueryCommand),
|
Query(QueryCommand),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,6 +85,16 @@ pub(super) async fn process(command: AdminCommand, context: &Context<'_>) -> Res
|
|||||||
context.bail_restricted()?;
|
context.bail_restricted()?;
|
||||||
token::process(command, context).await
|
token::process(command, context).await
|
||||||
},
|
},
|
||||||
|
| Oidc(command) => {
|
||||||
|
// OIDC commands are all restricted
|
||||||
|
context.bail_restricted()?;
|
||||||
|
|
||||||
|
if !context.services.oidc.enabled() {
|
||||||
|
return Err!("OIDC is not configured");
|
||||||
|
}
|
||||||
|
|
||||||
|
oidc::process(command, context).await
|
||||||
|
},
|
||||||
| Rooms(command) => room::process(command, context).await,
|
| Rooms(command) => room::process(command, context).await,
|
||||||
| Federation(command) => federation::process(command, context).await,
|
| Federation(command) => federation::process(command, context).await,
|
||||||
| Server(command) => server::process(command, context).await,
|
| Server(command) => server::process(command, context).await,
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
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 {
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn register(&self) -> Result {
|
|
||||||
let body = &self.body;
|
let body = &self.body;
|
||||||
let body_len = self.body.len();
|
let body_len = self.body.len();
|
||||||
if body_len < 2
|
if body_len < 2
|
||||||
@@ -31,10 +29,9 @@ pub(super) async fn register(&self) -> Result {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
|
||||||
pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
|
|
||||||
match self
|
match self
|
||||||
.services
|
.services
|
||||||
.appservice
|
.appservice
|
||||||
@@ -45,10 +42,9 @@ pub(super) async fn unregister(&self, appservice_identifier: String) -> Result {
|
|||||||
| Ok(()) => write!(self, "Appservice unregistered."),
|
| Ok(()) => write!(self, "Appservice unregistered."),
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result {
|
||||||
pub(super) async fn show_appservice_config(&self, appservice_identifier: String) -> Result {
|
|
||||||
match self
|
match self
|
||||||
.services
|
.services
|
||||||
.appservice
|
.appservice
|
||||||
@@ -62,10 +58,9 @@ pub(super) async fn show_appservice_config(&self, appservice_identifier: String)
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn list_registered(&self) -> Result {
|
||||||
pub(super) async fn list_registered(&self) -> Result {
|
|
||||||
self.services
|
self.services
|
||||||
.appservice
|
.appservice
|
||||||
.iter_ids()
|
.iter_ids()
|
||||||
@@ -77,4 +72,5 @@ pub(super) async fn list_registered(&self) -> Result {
|
|||||||
write!(self, "Appservices ({len}): {list}")
|
write!(self, "Appservices ({len}): {list}")
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,17 @@
|
|||||||
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_local_users()
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.await;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
let total = users.len();
|
let total = users.len();
|
||||||
@@ -20,4 +24,5 @@ pub(super) async fn check_all_users(&self) -> Result {
|
|||||||
{ok_count:?}\n```"
|
{ok_count:?}\n```"
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+235
-152
@@ -6,7 +6,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Err, Result, debug_error, err, info,
|
Err, Result, at, debug_error, err, info,
|
||||||
matrix::{
|
matrix::{
|
||||||
Event,
|
Event,
|
||||||
pdu::{PduEvent, PduId, RawPduId},
|
pdu::{PduEvent, PduId, RawPduId},
|
||||||
@@ -31,43 +31,7 @@ use service::rooms::{
|
|||||||
};
|
};
|
||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
use crate::admin_command;
|
use crate::PAGE_SIZE;
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn echo(&self, message: Vec<String>) -> Result {
|
|
||||||
let message = message.join(" ");
|
|
||||||
self.write_str(&message).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn get_auth_chain(&self, event_id: OwnedEventId) -> Result {
|
|
||||||
let Ok(event) = self.services.rooms.timeline.get_pdu_json(&event_id).await else {
|
|
||||||
return Err!("Event not found.");
|
|
||||||
};
|
|
||||||
|
|
||||||
let room_id_str = event
|
|
||||||
.get("room_id")
|
|
||||||
.and_then(CanonicalJsonValue::as_str)
|
|
||||||
.ok_or_else(|| err!(Database("Invalid event in database")))?;
|
|
||||||
|
|
||||||
let room_id = <&RoomId>::try_from(room_id_str)
|
|
||||||
.map_err(|_| err!(Database("Invalid room id field in event in database")))?;
|
|
||||||
|
|
||||||
let start = Instant::now();
|
|
||||||
let count = self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.auth_chain
|
|
||||||
.event_ids_iter(room_id, once(event_id.as_ref()))
|
|
||||||
.ready_filter_map(Result::ok)
|
|
||||||
.count()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let elapsed = start.elapsed();
|
|
||||||
let out = format!("Loaded auth chain with length {count} in {elapsed:?}");
|
|
||||||
|
|
||||||
self.write_str(&out).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||||
enum NodeStatus {
|
enum NodeStatus {
|
||||||
@@ -115,8 +79,42 @@ fn render_node(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
|
pub(super) async fn echo(&self, message: Vec<String>) -> Result {
|
||||||
|
let message = message.join(" ");
|
||||||
|
self.write_str(&message).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn get_auth_chain(&self, event_id: OwnedEventId) -> Result {
|
||||||
|
let Ok(event) = self.services.rooms.timeline.get_pdu_json(&event_id).await else {
|
||||||
|
return Err!("Event not found.");
|
||||||
|
};
|
||||||
|
|
||||||
|
let room_id_str = event
|
||||||
|
.get("room_id")
|
||||||
|
.and_then(CanonicalJsonValue::as_str)
|
||||||
|
.ok_or_else(|| err!(Database("Invalid event in database")))?;
|
||||||
|
|
||||||
|
let room_id = <&RoomId>::try_from(room_id_str)
|
||||||
|
.map_err(|_| err!(Database("Invalid room id field in event in database")))?;
|
||||||
|
|
||||||
|
let start = Instant::now();
|
||||||
|
let count = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.auth_chain
|
||||||
|
.event_ids_iter(room_id, once(event_id.as_ref()))
|
||||||
|
.ready_filter_map(Result::ok)
|
||||||
|
.count()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let elapsed = start.elapsed();
|
||||||
|
let out = format!("Loaded auth chain with length {count} in {elapsed:?}");
|
||||||
|
|
||||||
|
self.write_str(&out).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
|
||||||
let node_status = async |event_id: &EventId, missing: bool| -> NodeStatus {
|
let node_status = async |event_id: &EventId, missing: bool| -> NodeStatus {
|
||||||
if self
|
if self
|
||||||
.services
|
.services
|
||||||
@@ -184,7 +182,8 @@ pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let current_node_id = node_id_for(¤t_event_id, &mut node_ids, &mut next_node_id);
|
let current_node_id =
|
||||||
|
node_id_for(¤t_event_id, &mut node_ids, &mut next_node_id);
|
||||||
let current_status = node_status(¤t_event_id, false).await;
|
let current_status = node_status(¤t_event_id, false).await;
|
||||||
|
|
||||||
render_node(
|
render_node(
|
||||||
@@ -266,10 +265,9 @@ pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
|
|||||||
|
|
||||||
graph.push_str("```\n");
|
graph.push_str("```\n");
|
||||||
self.write_str(&graph).await
|
self.write_str(&graph).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn parse_pdu(&self) -> Result {
|
||||||
pub(super) async fn parse_pdu(&self) -> Result {
|
|
||||||
if self.body.len() < 2
|
if self.body.len() < 2
|
||||||
|| !self.body[0].trim().starts_with("```")
|
|| !self.body[0].trim().starts_with("```")
|
||||||
|| self.body.last().unwrap_or(&EMPTY).trim() != "```"
|
|| self.body.last().unwrap_or(&EMPTY).trim() != "```"
|
||||||
@@ -287,17 +285,17 @@ pub(super) async fn parse_pdu(&self) -> Result {
|
|||||||
| Ok(hash) => {
|
| Ok(hash) => {
|
||||||
let event_id = EventId::parse(format!("${hash}"));
|
let event_id = EventId::parse(format!("${hash}"));
|
||||||
match serde_json::from_value::<PduEvent>(serde_json::to_value(value)?) {
|
match serde_json::from_value::<PduEvent>(serde_json::to_value(value)?) {
|
||||||
| Err(e) => return Err!("EventId: {event_id:?}\nCould not parse event: {e}"),
|
| Err(e) =>
|
||||||
|
return Err!("EventId: {event_id:?}\nCould not parse event: {e}"),
|
||||||
| Ok(pdu) => write!(self, "EventId: {event_id:?}\n{pdu:#?}"),
|
| Ok(pdu) => write!(self, "EventId: {event_id:?}\n{pdu:#?}"),
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
|
||||||
pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
|
|
||||||
let mut outlier = false;
|
let mut outlier = false;
|
||||||
let mut pdu_json = self
|
let mut pdu_json = self
|
||||||
.services
|
.services
|
||||||
@@ -340,14 +338,13 @@ pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_short_pdu(
|
||||||
pub(super) async fn get_short_pdu(
|
|
||||||
&self,
|
&self,
|
||||||
shortroomid: ShortRoomId,
|
shortroomid: ShortRoomId,
|
||||||
shorteventid: ShortEventId,
|
shorteventid: ShortEventId,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let pdu_id: RawPduId = PduId {
|
let pdu_id: RawPduId = PduId {
|
||||||
shortroomid,
|
shortroomid,
|
||||||
shorteventid: shorteventid.into(),
|
shorteventid: shorteventid.into(),
|
||||||
@@ -369,10 +366,13 @@ pub(super) async fn get_short_pdu(
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_remote_pdu_list(
|
||||||
pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: bool) -> Result {
|
&self,
|
||||||
|
server: OwnedServerName,
|
||||||
|
force: bool,
|
||||||
|
) -> Result {
|
||||||
if !self.services.server.config.allow_federation {
|
if !self.services.server.config.allow_federation {
|
||||||
return Err!("Federation is disabled on this homeserver.",);
|
return Err!("Federation is disabled on this homeserver.",);
|
||||||
}
|
}
|
||||||
@@ -425,18 +425,18 @@ pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: b
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let out =
|
let out = format!(
|
||||||
format!("Fetched {success_count} remote PDUs successfully with {failed_count} failures");
|
"Fetched {success_count} remote PDUs successfully with {failed_count} failures"
|
||||||
|
);
|
||||||
|
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_remote_pdu(
|
||||||
pub(super) async fn get_remote_pdu(
|
|
||||||
&self,
|
&self,
|
||||||
event_id: OwnedEventId,
|
event_id: OwnedEventId,
|
||||||
server: OwnedServerName,
|
server: OwnedServerName,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
if !self.services.server.config.allow_federation {
|
if !self.services.server.config.allow_federation {
|
||||||
return Err!("Federation is disabled on this homeserver.");
|
return Err!("Federation is disabled on this homeserver.");
|
||||||
}
|
}
|
||||||
@@ -459,15 +459,17 @@ pub(super) async fn get_remote_pdu(
|
|||||||
{
|
{
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Remote server did not have PDU or failed sending request to remote server: {e}"
|
"Remote server did not have PDU or failed sending request to remote server: \
|
||||||
|
{e}"
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
| Ok(response) => {
|
| Ok(response) => {
|
||||||
let json: CanonicalJsonObject =
|
let json: CanonicalJsonObject = serde_json::from_str(response.pdu.get())
|
||||||
serde_json::from_str(response.pdu.get()).map_err(|e| {
|
.map_err(|e| {
|
||||||
warn!(
|
warn!(
|
||||||
"Requested event ID {event_id} from server but failed to convert from \
|
"Requested event ID {event_id} from server but failed to convert \
|
||||||
RawValue to CanonicalJsonObject (malformed event/response?): {e}"
|
from RawValue to CanonicalJsonObject (malformed event/response?): \
|
||||||
|
{e}"
|
||||||
);
|
);
|
||||||
err!(Request(Unknown(
|
err!(Request(Unknown(
|
||||||
"Received response from server but failed to parse PDU"
|
"Received response from server but failed to parse PDU"
|
||||||
@@ -489,7 +491,9 @@ pub(super) async fn get_remote_pdu(
|
|||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
warn!("Failed to parse PDU: {e}");
|
warn!("Failed to parse PDU: {e}");
|
||||||
info!("Full PDU: {:?}", &response.pdu);
|
info!("Full PDU: {:?}", &response.pdu);
|
||||||
return Err!("Failed to parse PDU remote server {server} sent us: {e}");
|
return Err!(
|
||||||
|
"Failed to parse PDU remote server {server} sent us: {e}"
|
||||||
|
);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -502,10 +506,46 @@ pub(super) async fn get_remote_pdu(
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_state_at(&self, event_id: OwnedEventId) -> Result {
|
||||||
pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result {
|
self.bail_restricted()?;
|
||||||
|
|
||||||
|
let shortstatehash = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.state_accessor
|
||||||
|
.pdu_shortstatehash(&event_id)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let state_ids: Vec<OwnedEventId> = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.state_accessor
|
||||||
|
.state_full_ids(shortstatehash)
|
||||||
|
.map(at!(1))
|
||||||
|
.collect()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let pdus: Vec<CanonicalJsonObject> = state_ids
|
||||||
|
.iter()
|
||||||
|
.try_stream()
|
||||||
|
.and_then(|id| self.services.rooms.timeline.get_pdu_json(id))
|
||||||
|
.try_collect()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let json = serde_json::to_string_pretty(&pdus).map_err(|e| {
|
||||||
|
err!(Database(
|
||||||
|
"Failed to convert room state events to pretty JSON, possible invalid room \
|
||||||
|
state events in our database {e}",
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let out = format!("```json\n{json}\n```");
|
||||||
|
self.write_str(&out).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
let room_id = self.services.rooms.alias.resolve(&room).await?;
|
let room_id = self.services.rooms.alias.resolve(&room).await?;
|
||||||
@@ -524,17 +564,16 @@ pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
|
|
||||||
let json = serde_json::to_string_pretty(&room_state).map_err(|e| {
|
let json = serde_json::to_string_pretty(&room_state).map_err(|e| {
|
||||||
err!(Database(
|
err!(Database(
|
||||||
"Failed to convert room state events to pretty JSON, possible invalid room state \
|
"Failed to convert room state events to pretty JSON, possible invalid room \
|
||||||
events in our database {e}",
|
state events in our database {e}",
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let out = format!("```json\n{json}\n```");
|
let out = format!("```json\n{json}\n```");
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
|
||||||
pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
|
|
||||||
if server == self.services.globals.server_name() {
|
if server == self.services.globals.server_name() {
|
||||||
return Err!("Not allowed to send federation requests to ourselves.");
|
return Err!("Not allowed to send federation requests to ourselves.");
|
||||||
}
|
}
|
||||||
@@ -567,22 +606,20 @@ pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn force_device_list_updates(&self) -> Result {
|
||||||
pub(super) async fn force_device_list_updates(&self) -> Result {
|
|
||||||
// Force E2EE device list updates for all users
|
// Force E2EE device list updates for all users
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.stream()
|
.stream_local_users()
|
||||||
.for_each(async |user_id| self.services.users.mark_device_key_update(&user_id).await)
|
.for_each(async |user_id| self.services.users.mark_device_key_update(&user_id).await)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
write!(self, "Marked all devices for all users as having new keys to update").await
|
write!(self, "Marked all devices for all users as having new keys to update").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result {
|
||||||
pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result {
|
|
||||||
let handles = &["console"];
|
let handles = &["console"];
|
||||||
|
|
||||||
if reset {
|
if reset {
|
||||||
@@ -603,7 +640,8 @@ pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool)
|
|||||||
},
|
},
|
||||||
| Ok(()) => {
|
| Ok(()) => {
|
||||||
let value = &self.services.server.config.log;
|
let value = &self.services.server.config.log;
|
||||||
let out = format!("Successfully changed log level back to config value {value}");
|
let out =
|
||||||
|
format!("Successfully changed log level back to config value {value}");
|
||||||
return self.write_str(&out).await;
|
return self.write_str(&out).await;
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -632,10 +670,9 @@ pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool)
|
|||||||
}
|
}
|
||||||
|
|
||||||
Err!("No log level was specified.")
|
Err!("No log level was specified.")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn verify_json(&self) -> Result {
|
||||||
pub(super) async fn verify_json(&self) -> Result {
|
|
||||||
if self.body.len() < 2
|
if self.body.len() < 2
|
||||||
|| !self.body[0].trim().starts_with("```")
|
|| !self.body[0].trim().starts_with("```")
|
||||||
|| self.body.last().unwrap_or(&"").trim() != "```"
|
|| self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
@@ -659,10 +696,9 @@ pub(super) async fn verify_json(&self) -> Result {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result {
|
||||||
pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result {
|
|
||||||
use ruma::signatures::Verified;
|
use ruma::signatures::Verified;
|
||||||
|
|
||||||
let mut event = self.services.rooms.timeline.get_pdu_json(&event_id).await?;
|
let mut event = self.services.rooms.timeline.get_pdu_json(&event_id).await?;
|
||||||
@@ -681,11 +717,10 @@ pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.write_str(msg).await
|
self.write_str(msg).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
#[tracing::instrument(skip(self), level = "info")]
|
||||||
#[tracing::instrument(skip(self), level = "info")]
|
pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
||||||
pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
if !self
|
if !self
|
||||||
@@ -695,7 +730,9 @@ pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
|||||||
.server_in_room(&self.services.server.name, &room_id)
|
.server_in_room(&self.services.server.name, &room_id)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
return Err!("We are not participating in the room / we don't know about the room ID.",);
|
return Err!(
|
||||||
|
"We are not participating in the room / we don't know about the room ID.",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let first_pdu = self
|
let first_pdu = self
|
||||||
@@ -708,11 +745,10 @@ pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
|||||||
|
|
||||||
let out = format!("{first_pdu:?}");
|
let out = format!("{first_pdu:?}");
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
#[tracing::instrument(skip(self), level = "info")]
|
||||||
#[tracing::instrument(skip(self), level = "info")]
|
pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
||||||
pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
if !self
|
if !self
|
||||||
@@ -722,7 +758,9 @@ pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
|||||||
.server_in_room(&self.services.server.name, &room_id)
|
.server_in_room(&self.services.server.name, &room_id)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
return Err!("We are not participating in the room / we don't know about the room ID.");
|
return Err!(
|
||||||
|
"We are not participating in the room / we don't know about the room ID."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let latest_pdu = self
|
let latest_pdu = self
|
||||||
@@ -735,16 +773,15 @@ pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
|
|||||||
|
|
||||||
let out = format!("{latest_pdu:?}");
|
let out = format!("{latest_pdu:?}");
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
#[tracing::instrument(skip(self), level = "info")]
|
||||||
#[tracing::instrument(skip(self), level = "info")]
|
pub(super) async fn force_set_room_state_from_server(
|
||||||
pub(super) async fn force_set_room_state_from_server(
|
|
||||||
&self,
|
&self,
|
||||||
room_id: OwnedRoomId,
|
room_id: OwnedRoomId,
|
||||||
server_name: OwnedServerName,
|
server_name: OwnedServerName,
|
||||||
at_event: Option<OwnedEventId>,
|
at_event: Option<OwnedEventId>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
if !self
|
if !self
|
||||||
@@ -754,7 +791,9 @@ pub(super) async fn force_set_room_state_from_server(
|
|||||||
.server_in_room(&self.services.server.name, &room_id)
|
.server_in_room(&self.services.server.name, &room_id)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
return Err!("We are not participating in the room / we don't know about the room ID.");
|
return Err!(
|
||||||
|
"We are not participating in the room / we don't know about the room ID."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let at_event_id = match at_event {
|
let at_event_id = match at_event {
|
||||||
@@ -811,7 +850,9 @@ pub(super) async fn force_set_room_state_from_server(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
|
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
|
||||||
debug_error!("Invalid PDU in fetching remote room state PDUs response: {value:#?}");
|
debug_error!(
|
||||||
|
"Invalid PDU in fetching remote room state PDUs response: {value:#?}"
|
||||||
|
);
|
||||||
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
|
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
@@ -894,15 +935,14 @@ pub(super) async fn force_set_room_state_from_server(
|
|||||||
|
|
||||||
self.write_str("Successfully forced the room state from the requested remote server.")
|
self.write_str("Successfully forced the room state from the requested remote server.")
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_signing_keys(
|
||||||
pub(super) async fn get_signing_keys(
|
|
||||||
&self,
|
&self,
|
||||||
server_name: Option<OwnedServerName>,
|
server_name: Option<OwnedServerName>,
|
||||||
notary: Option<OwnedServerName>,
|
notary: Option<OwnedServerName>,
|
||||||
query: bool,
|
query: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone());
|
let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone());
|
||||||
|
|
||||||
if let Some(notary) = notary {
|
if let Some(notary) = notary {
|
||||||
@@ -930,10 +970,9 @@ pub(super) async fn get_signing_keys(
|
|||||||
|
|
||||||
let out = format!("```rs\n{signing_keys:#?}\n```");
|
let out = format!("```rs\n{signing_keys:#?}\n```");
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_verify_keys(&self, server_name: Option<OwnedServerName>) -> Result {
|
||||||
pub(super) async fn get_verify_keys(&self, server_name: Option<OwnedServerName>) -> Result {
|
|
||||||
let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone());
|
let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone());
|
||||||
|
|
||||||
let keys = self
|
let keys = self
|
||||||
@@ -950,14 +989,13 @@ pub(super) async fn get_verify_keys(&self, server_name: Option<OwnedServerName>)
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn resolve_true_destination(
|
||||||
pub(super) async fn resolve_true_destination(
|
|
||||||
&self,
|
&self,
|
||||||
server_name: OwnedServerName,
|
server_name: OwnedServerName,
|
||||||
no_cache: bool,
|
no_cache: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
if !self.services.server.config.allow_federation {
|
if !self.services.server.config.allow_federation {
|
||||||
return Err!("Federation is disabled on this homeserver.",);
|
return Err!("Federation is disabled on this homeserver.",);
|
||||||
}
|
}
|
||||||
@@ -977,10 +1015,9 @@ pub(super) async fn resolve_true_destination(
|
|||||||
|
|
||||||
let msg = format!("Destination: {}\nHostname URI: {}", actual.dest, actual.host);
|
let msg = format!("Destination: {}\nHostname URI: {}", actual.dest, actual.host);
|
||||||
self.write_str(&msg).await
|
self.write_str(&msg).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn memory_stats(&self, opts: Option<String>) -> Result {
|
||||||
pub(super) async fn memory_stats(&self, opts: Option<String>) -> Result {
|
|
||||||
const OPTS: &str = "abcdefghijklmnopqrstuvwxyz";
|
const OPTS: &str = "abcdefghijklmnopqrstuvwxyz";
|
||||||
|
|
||||||
let opts: String = OPTS
|
let opts: String = OPTS
|
||||||
@@ -1000,11 +1037,11 @@ pub(super) async fn memory_stats(&self, opts: Option<String>) -> Result {
|
|||||||
self.write_str(&stats).await?;
|
self.write_str(&stats).await?;
|
||||||
self.write_str("\n```").await?;
|
self.write_str("\n```").await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(tokio_unstable)]
|
#[cfg(tokio_unstable)]
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn runtime_metrics(&self) -> Result {
|
pub(super) async fn runtime_metrics(&self) -> Result {
|
||||||
let out = self.services.server.metrics.runtime_metrics().map_or_else(
|
let out = self.services.server.metrics.runtime_metrics().map_or_else(
|
||||||
|| "Runtime metrics are not available.".to_owned(),
|
|| "Runtime metrics are not available.".to_owned(),
|
||||||
|metrics| {
|
|metrics| {
|
||||||
@@ -1018,47 +1055,43 @@ pub(super) async fn runtime_metrics(&self) -> Result {
|
|||||||
);
|
);
|
||||||
|
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(tokio_unstable))]
|
#[cfg(not(tokio_unstable))]
|
||||||
#[admin_command]
|
pub(super) async fn runtime_metrics(&self) -> Result {
|
||||||
pub(super) async fn runtime_metrics(&self) -> Result {
|
|
||||||
self.write_str("Runtime metrics require building with `tokio_unstable`.")
|
self.write_str("Runtime metrics require building with `tokio_unstable`.")
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(tokio_unstable)]
|
#[cfg(tokio_unstable)]
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn runtime_interval(&self) -> Result {
|
pub(super) async fn runtime_interval(&self) -> Result {
|
||||||
let out = self.services.server.metrics.runtime_interval().map_or_else(
|
let out = self.services.server.metrics.runtime_interval().map_or_else(
|
||||||
|| "Runtime metrics are not available.".to_owned(),
|
|| "Runtime metrics are not available.".to_owned(),
|
||||||
|metrics| format!("```rs\n{metrics:#?}\n```"),
|
|metrics| format!("```rs\n{metrics:#?}\n```"),
|
||||||
);
|
);
|
||||||
|
|
||||||
self.write_str(&out).await
|
self.write_str(&out).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(tokio_unstable))]
|
#[cfg(not(tokio_unstable))]
|
||||||
#[admin_command]
|
pub(super) async fn runtime_interval(&self) -> Result {
|
||||||
pub(super) async fn runtime_interval(&self) -> Result {
|
|
||||||
self.write_str("Runtime metrics require building with `tokio_unstable`.")
|
self.write_str("Runtime metrics require building with `tokio_unstable`.")
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn time(&self) -> Result {
|
||||||
pub(super) async fn time(&self) -> Result {
|
|
||||||
let now = SystemTime::now();
|
let now = SystemTime::now();
|
||||||
let now = utils::time::format(now, "%+");
|
let now = utils::time::format(now, "%+");
|
||||||
|
|
||||||
self.write_str(&now).await
|
self.write_str(&now).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn database_stats(
|
||||||
pub(super) async fn database_stats(
|
|
||||||
&self,
|
&self,
|
||||||
property: Option<String>,
|
property: Option<String>,
|
||||||
map: Option<String>,
|
map: Option<String>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let map_name = map.as_ref().map_or(EMPTY, String::as_str);
|
let map_name = map.as_ref().map_or(EMPTY, String::as_str);
|
||||||
let property = property.unwrap_or_else(|| "rocksdb.stats".to_owned());
|
let property = property.unwrap_or_else(|| "rocksdb.stats".to_owned());
|
||||||
self.services
|
self.services
|
||||||
@@ -1071,10 +1104,9 @@ pub(super) async fn database_stats(
|
|||||||
writeln!(self, "##### {name}:\n```\n{}\n```", res.trim())
|
writeln!(self, "##### {name}:\n```\n{}\n```", res.trim())
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn database_files(&self, map: Option<String>, level: Option<i32>) -> Result {
|
||||||
pub(super) async fn database_files(&self, map: Option<String>, level: Option<i32>) -> Result {
|
|
||||||
let mut files: Vec<_> = self.services.db.db.file_list().collect::<Result<_>>()?;
|
let mut files: Vec<_> = self.services.db.db.file_list().collect::<Result<_>>()?;
|
||||||
|
|
||||||
files.sort_by_key(|f| f.name.clone());
|
files.sort_by_key(|f| f.name.clone());
|
||||||
@@ -1102,17 +1134,15 @@ pub(super) async fn database_files(&self, map: Option<String>, level: Option<i32
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn trim_memory(&self) -> Result {
|
||||||
pub(super) async fn trim_memory(&self) -> Result {
|
|
||||||
conduwuit::alloc::trim(None)?;
|
conduwuit::alloc::trim(None)?;
|
||||||
|
|
||||||
writeln!(self, "done").await
|
writeln!(self, "done").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn send_test_email(&self) -> Result {
|
||||||
pub(super) async fn send_test_email(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
let mailer = self.services.mailer.expect_mailer()?;
|
let mailer = self.services.mailer.expect_mailer()?;
|
||||||
@@ -1137,4 +1167,57 @@ pub(super) async fn send_test_email(&self) -> Result {
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn rooms_by_extremity_count(&self, page: Option<usize>) -> Result {
|
||||||
|
let page = page.unwrap_or(1);
|
||||||
|
// My Giant Chain:tm:
|
||||||
|
let mapped: HashMap<OwnedRoomId, u64> = self
|
||||||
|
.services
|
||||||
|
.rooms
|
||||||
|
.state
|
||||||
|
.all_forward_extremities()
|
||||||
|
.ready_fold(HashMap::new(), move |mut map, (room_id, _)| {
|
||||||
|
let count: u64 = map.get(&room_id).copied().unwrap_or(0);
|
||||||
|
map.insert(room_id, count.saturating_add(1));
|
||||||
|
map
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(room_id, count)| (count >= 2).then_some((room_id, count)))
|
||||||
|
.collect();
|
||||||
|
if mapped.is_empty() {
|
||||||
|
return Err!("No more rooms.");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut rooms = mapped.keys().collect::<Vec<_>>();
|
||||||
|
rooms.sort_by_key(|room_id| {
|
||||||
|
mapped
|
||||||
|
.get(*room_id)
|
||||||
|
.copied()
|
||||||
|
.expect("keys must have values")
|
||||||
|
});
|
||||||
|
rooms.reverse();
|
||||||
|
|
||||||
|
let body = rooms
|
||||||
|
.into_iter()
|
||||||
|
.stream()
|
||||||
|
.skip(page.saturating_sub(1).saturating_mul(PAGE_SIZE))
|
||||||
|
.take(PAGE_SIZE)
|
||||||
|
.map(|room_id| {
|
||||||
|
format!(
|
||||||
|
"{room_id}: {}",
|
||||||
|
mapped.get(room_id).copied().expect("keys must have values")
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
self.write_str(&format!(
|
||||||
|
"Rooms by extremity count ({}):\n```\n{}\n```",
|
||||||
|
body.len(),
|
||||||
|
body.join("\n")
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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>,
|
||||||
@@ -237,6 +245,11 @@ pub enum DebugCommand {
|
|||||||
/// Send a test email to the invoking admin's email address
|
/// Send a test email to the invoking admin's email address
|
||||||
SendTestEmail,
|
SendTestEmail,
|
||||||
|
|
||||||
|
/// Lists room IDs by forward extremity count in descending order
|
||||||
|
RoomsByExtremityCount {
|
||||||
|
page: Option<usize>,
|
||||||
|
},
|
||||||
|
|
||||||
/// Developer test stubs
|
/// Developer test stubs
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
|
|||||||
+16
-21
@@ -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]
|
|
||||||
#[admin_command]
|
|
||||||
async fn failure(&self) -> Result {
|
|
||||||
|
|
||||||
|
#[rustfmt::skip]
|
||||||
|
async fn failure(&self) -> Result {
|
||||||
Err!("failed")
|
Err!("failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(never)]
|
|
||||||
#[rustfmt::skip]
|
|
||||||
#[admin_command]
|
|
||||||
async fn tester(&self) -> Result {
|
|
||||||
|
|
||||||
|
#[inline(never)]
|
||||||
|
#[rustfmt::skip]
|
||||||
|
async fn tester(&self) -> Result {
|
||||||
self.write_str("Ok").await
|
self.write_str("Ok").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
#[rustfmt::skip]
|
#[rustfmt::skip]
|
||||||
#[admin_command]
|
async fn timer(&self) -> Result {
|
||||||
async fn timer(&self) -> Result {
|
|
||||||
let started = std::time::Instant::now();
|
let started = std::time::Instant::now();
|
||||||
timed(self.body);
|
timed(self.body);
|
||||||
|
|
||||||
let elapsed = started.elapsed();
|
let elapsed = started.elapsed();
|
||||||
self.write_str(&format!("completed in {elapsed:#?}")).await
|
self.write_str(&format!("completed in {elapsed:#?}")).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
|
|||||||
@@ -4,24 +4,22 @@ 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
|
.services
|
||||||
@@ -37,16 +35,22 @@ pub(super) async fn incoming_federation(&self) -> Result {
|
|||||||
);
|
);
|
||||||
for (r, (e, i)) in map.iter() {
|
for (r, (e, i)) in map.iter() {
|
||||||
let elapsed = i.elapsed();
|
let elapsed = i.elapsed();
|
||||||
writeln!(msg, "{} {}: {}m{}s", r, e, elapsed.as_secs() / 60, elapsed.as_secs() % 60)?;
|
writeln!(
|
||||||
|
msg,
|
||||||
|
"{} {}: {}m{}s",
|
||||||
|
r,
|
||||||
|
e,
|
||||||
|
elapsed.as_secs() / 60,
|
||||||
|
elapsed.as_secs() % 60
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
msg
|
msg
|
||||||
};
|
};
|
||||||
|
|
||||||
self.write_str(&msg).await
|
self.write_str(&msg).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
|
||||||
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
|
|
||||||
let response = self
|
let response = self
|
||||||
.services
|
.services
|
||||||
.client
|
.client
|
||||||
@@ -91,10 +95,9 @@ pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName
|
|||||||
|
|
||||||
self.write_str(&format!("Got JSON response:\n\n```json\n{pretty_json}\n```"))
|
self.write_str(&format!("Got JSON response:\n\n```json\n{pretty_json}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
|
||||||
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
if user_id.server_name() == self.services.server.name {
|
if user_id.server_name() == self.services.server.name {
|
||||||
return Err!(
|
return Err!(
|
||||||
"User belongs to our server, please use `list-joined-rooms` user admin command \
|
"User belongs to our server, please use `list-joined-rooms` user admin command \
|
||||||
@@ -127,4 +130,5 @@ pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result
|
|||||||
|
|
||||||
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
|
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+54
-52
@@ -9,14 +9,14 @@ 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() {
|
||||||
@@ -59,8 +59,8 @@ pub(super) async fn delete(
|
|||||||
mxc_urls.push(final_url);
|
mxc_urls.push(final_url);
|
||||||
} else {
|
} else {
|
||||||
info!(
|
info!(
|
||||||
"Found a URL in the event ID {event_id} but did not start \
|
"Found a URL in the event ID {event_id} but did not \
|
||||||
with mxc://, ignoring"
|
start with mxc://, ignoring"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,26 +73,29 @@ pub(super) async fn delete(
|
|||||||
|
|
||||||
if let Some(info) = info_obj {
|
if let Some(info) = info_obj {
|
||||||
if let Some(thumbnail_url) = info.get("thumbnail_url") {
|
if let Some(thumbnail_url) = info.get("thumbnail_url") {
|
||||||
debug!("Found a thumbnail_url in info key: {thumbnail_url}");
|
debug!(
|
||||||
|
"Found a thumbnail_url in info key: {thumbnail_url}"
|
||||||
|
);
|
||||||
|
|
||||||
if thumbnail_url.to_string().starts_with("\"mxc://") {
|
if thumbnail_url.to_string().starts_with("\"mxc://") {
|
||||||
debug!(
|
debug!(
|
||||||
"Pushing thumbnail URL {thumbnail_url} to list of \
|
"Pushing thumbnail URL {thumbnail_url} to list \
|
||||||
MXCs to delete"
|
of MXCs to delete"
|
||||||
);
|
);
|
||||||
let final_thumbnail_url =
|
let final_thumbnail_url =
|
||||||
thumbnail_url.to_string().replace('"', "");
|
thumbnail_url.to_string().replace('"', "");
|
||||||
mxc_urls.push(final_thumbnail_url);
|
mxc_urls.push(final_thumbnail_url);
|
||||||
} else {
|
} else {
|
||||||
info!(
|
info!(
|
||||||
"Found a thumbnail URL in the event ID {event_id} \
|
"Found a thumbnail URL in the event ID \
|
||||||
but did not start with mxc://, ignoring"
|
{event_id} but did not start with mxc://, \
|
||||||
|
ignoring"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
info!(
|
info!(
|
||||||
"No \"thumbnail_url\" key in \"info\" key, assuming no \
|
"No \"thumbnail_url\" key in \"info\" key, assuming \
|
||||||
thumbnails."
|
no thumbnails."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -114,8 +117,8 @@ pub(super) async fn delete(
|
|||||||
mxc_urls.push(final_url);
|
mxc_urls.push(final_url);
|
||||||
} else {
|
} else {
|
||||||
warn!(
|
warn!(
|
||||||
"Found a URL in the event ID {event_id} but did not \
|
"Found a URL in the event ID {event_id} but did \
|
||||||
start with mxc://, ignoring"
|
not start with mxc://, ignoring"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -131,8 +134,8 @@ pub(super) async fn delete(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Event ID does not have a \"content\" key, this is not a message or an \
|
"Event ID does not have a \"content\" key, this is not a message or \
|
||||||
event type that contains media.",
|
an event type that contains media.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -155,11 +158,15 @@ pub(super) async fn delete(
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
| Ok(()) => {
|
| Ok(()) => {
|
||||||
debug_info!("Successfully deleted {mxc_url} from filesystem and database");
|
debug_info!(
|
||||||
|
"Successfully deleted {mxc_url} from filesystem and database"
|
||||||
|
);
|
||||||
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
mxc_deletion_count = mxc_deletion_count.saturating_add(1);
|
||||||
},
|
},
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
debug_warn!("Failed to delete {mxc_url}, ignoring error and skipping: {e}");
|
debug_warn!(
|
||||||
|
"Failed to delete {mxc_url}, ignoring error and skipping: {e}"
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -167,8 +174,8 @@ pub(super) async fn delete(
|
|||||||
|
|
||||||
return self
|
return self
|
||||||
.write_str(&format!(
|
.write_str(&format!(
|
||||||
"Deleted {mxc_deletion_count} total MXCs from our database and the filesystem \
|
"Deleted {mxc_deletion_count} total MXCs from our database and the \
|
||||||
from event ID {event_id}."
|
filesystem from event ID {event_id}."
|
||||||
))
|
))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
@@ -177,10 +184,9 @@ pub(super) async fn delete(
|
|||||||
"Please specify either an MXC using --mxc or an event ID using --event-id of the \
|
"Please specify either an MXC using --mxc or an event ID using --event-id of the \
|
||||||
message containing an image. See --help for details."
|
message containing an image. See --help for details."
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn delete_list(&self) -> Result {
|
||||||
pub(super) async fn delete_list(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
if self.body.len() < 2
|
if self.body.len() < 2
|
||||||
@@ -224,20 +230,20 @@ pub(super) async fn delete_list(&self) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our database \
|
"Finished bulk MXC deletion, deleted {mxc_deletion_count} total MXCs from our \
|
||||||
and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from the database.",
|
database and the filesystem. {failed_parsed_mxcs} MXCs failed to be parsed from \
|
||||||
|
the database.",
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn delete_past_remote_media(
|
||||||
pub(super) async fn delete_past_remote_media(
|
|
||||||
&self,
|
&self,
|
||||||
duration: String,
|
duration: String,
|
||||||
before: bool,
|
before: bool,
|
||||||
after: bool,
|
after: bool,
|
||||||
yes_i_want_to_delete_local_media: bool,
|
yes_i_want_to_delete_local_media: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
if before && after {
|
if before && after {
|
||||||
@@ -264,27 +270,26 @@ pub(super) async fn delete_past_remote_media(
|
|||||||
|
|
||||||
self.write_str(&format!("Deleted {deleted_count} total files."))
|
self.write_str(&format!("Deleted {deleted_count} total files."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
|
||||||
pub(super) async fn delete_all_from_user(&self, username: String) -> Result {
|
|
||||||
let user_id = parse_local_user_id(self.services, &username)?;
|
let user_id = parse_local_user_id(self.services, &username)?;
|
||||||
|
|
||||||
let deleted_count = self.services.media.delete_from_user(&user_id).await?;
|
let deleted_count = self.services.media.delete_from_user(&user_id).await?;
|
||||||
|
|
||||||
self.write_str(&format!("Deleted {deleted_count} total files."))
|
self.write_str(&format!("Deleted {deleted_count} total files."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn delete_all_from_server(
|
||||||
pub(super) async fn delete_all_from_server(
|
|
||||||
&self,
|
&self,
|
||||||
server_name: OwnedServerName,
|
server_name: OwnedServerName,
|
||||||
yes_i_want_to_delete_local_media: bool,
|
yes_i_want_to_delete_local_media: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media {
|
if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media
|
||||||
|
{
|
||||||
return Err!("This command only works for remote media by default.",);
|
return Err!("This command only works for remote media by default.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,23 +338,21 @@ pub(super) async fn delete_all_from_server(
|
|||||||
|
|
||||||
self.write_str(&format!("Deleted {deleted_count} total files."))
|
self.write_str(&format!("Deleted {deleted_count} total files."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
|
||||||
pub(super) async fn get_file_info(&self, mxc: OwnedMxcUri) -> Result {
|
|
||||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||||
let metadata = self.services.media.get_metadata(&mxc).await;
|
let metadata = self.services.media.get_metadata(&mxc).await;
|
||||||
|
|
||||||
self.write_str(&format!("```\n{metadata:#?}\n```")).await
|
self.write_str(&format!("```\n{metadata:#?}\n```")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_remote_file(
|
||||||
pub(super) async fn get_remote_file(
|
|
||||||
&self,
|
&self,
|
||||||
mxc: OwnedMxcUri,
|
mxc: OwnedMxcUri,
|
||||||
server: Option<OwnedServerName>,
|
server: Option<OwnedServerName>,
|
||||||
timeout: u32,
|
timeout: u32,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||||
let timeout = Duration::from_millis(timeout.into());
|
let timeout = Duration::from_millis(timeout.into());
|
||||||
let mut result = self
|
let mut result = self
|
||||||
@@ -364,17 +367,16 @@ pub(super) async fn get_remote_file(
|
|||||||
|
|
||||||
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_remote_thumbnail(
|
||||||
pub(super) async fn get_remote_thumbnail(
|
|
||||||
&self,
|
&self,
|
||||||
mxc: OwnedMxcUri,
|
mxc: OwnedMxcUri,
|
||||||
server: Option<OwnedServerName>,
|
server: Option<OwnedServerName>,
|
||||||
timeout: u32,
|
timeout: u32,
|
||||||
width: u32,
|
width: u32,
|
||||||
height: u32,
|
height: u32,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
let mxc: Mxc<'_> = mxc.as_str().try_into()?;
|
||||||
let timeout = Duration::from_millis(timeout.into());
|
let timeout = Duration::from_millis(timeout.into());
|
||||||
let dim = Dim::new(width, height, None);
|
let dim = Dim::new(width, height, None);
|
||||||
@@ -390,10 +392,9 @@ pub(super) async fn get_remote_thumbnail(
|
|||||||
|
|
||||||
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
self.write_str(&format!("```\n{result:#?}\nreceived {len} bytes for file content.\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result {
|
||||||
pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) -> Result {
|
|
||||||
if all {
|
if all {
|
||||||
self.services.media.clear_url_previews().await;
|
self.services.media.clear_url_previews().await;
|
||||||
|
|
||||||
@@ -406,4 +407,5 @@ pub(super) async fn delete_url_preview(&self, url: Option<String>, all: bool) ->
|
|||||||
|
|
||||||
self.write_str(&format!("Deleted cached URL preview for: {url}"))
|
self.write_str(&format!("Deleted cached URL preview for: {url}"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+2
-1
@@ -16,6 +16,7 @@ pub(crate) mod check;
|
|||||||
pub(crate) mod debug;
|
pub(crate) mod debug;
|
||||||
pub(crate) mod federation;
|
pub(crate) mod federation;
|
||||||
pub(crate) mod media;
|
pub(crate) mod media;
|
||||||
|
pub(crate) mod oidc;
|
||||||
pub(crate) mod query;
|
pub(crate) mod query;
|
||||||
pub(crate) mod room;
|
pub(crate) mod room;
|
||||||
pub(crate) mod server;
|
pub(crate) mod server;
|
||||||
@@ -26,7 +27,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};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
use conduwuit::Result;
|
||||||
|
|
||||||
|
use crate::utils::parse_active_local_user_id;
|
||||||
|
|
||||||
|
impl crate::Context<'_> {
|
||||||
|
pub(super) async fn oidc_link(&self, user_id: String, subject: String) -> Result {
|
||||||
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
|
self.services.oidc.link_user(&user_id, &subject);
|
||||||
|
|
||||||
|
self.write_str(&format!("Subject `{subject}` linked to account `{user_id}`."))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn oidc_unlink(&self, subject: String) -> Result {
|
||||||
|
self.services.oidc.unlink_user(&subject);
|
||||||
|
|
||||||
|
self.write_str(&format!("Subject `{subject}` unlinked."))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
mod commands;
|
||||||
|
|
||||||
|
use clap::Subcommand;
|
||||||
|
use conduwuit::Result;
|
||||||
|
use conduwuit_macros::admin_command_dispatch;
|
||||||
|
|
||||||
|
#[admin_command_dispatch]
|
||||||
|
#[derive(Debug, Subcommand)]
|
||||||
|
pub enum OidcCommand {
|
||||||
|
/// Link a user ID to the given subject claim.
|
||||||
|
#[clap(name = "link")]
|
||||||
|
OidcLink {
|
||||||
|
user_id: String,
|
||||||
|
subject: String,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// Unlink the given subject claim from its associated user ID.
|
||||||
|
#[clap(name = "unlink")]
|
||||||
|
OidcUnlink {
|
||||||
|
subject: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -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,13 +31,13 @@ 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
|
||||||
@@ -49,15 +49,14 @@ async fn changes_since(
|
|||||||
|
|
||||||
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
|
||||||
@@ -77,4 +76,5 @@ async fn account_data_get(
|
|||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{json}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{json}\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+51
-43
@@ -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,8 +159,8 @@ 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>,
|
||||||
@@ -169,7 +169,7 @@ pub(super) async fn compact(
|
|||||||
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(|| {
|
||||||
@@ -221,10 +221,9 @@ pub(super) async fn compact(
|
|||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("Jobs completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
|
self.write_str(&format!("Jobs completed in {query_time:?}:\n\n```rs\n{results:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
||||||
pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
@@ -236,10 +235,9 @@ pub(super) async fn raw_count(&self, map: Option<String>, prefix: Option<String>
|
|||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{count:#?}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{count:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result {
|
||||||
pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Result {
|
|
||||||
writeln!(self, "```").boxed().await?;
|
writeln!(self, "```").boxed().await?;
|
||||||
|
|
||||||
let map = self.services.db.get(map.as_str())?;
|
let map = self.services.db.get(map.as_str())?;
|
||||||
@@ -255,10 +253,13 @@ pub(super) async fn raw_keys(&self, map: String, prefix: Option<String>) -> Resu
|
|||||||
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!("\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_keys_sizes(
|
||||||
pub(super) async fn raw_keys_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
&self,
|
||||||
|
map: Option<String>,
|
||||||
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
@@ -277,10 +278,13 @@ pub(super) async fn raw_keys_sizes(&self, map: Option<String>, prefix: Option<St
|
|||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_keys_total(
|
||||||
pub(super) async fn raw_keys_total(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
&self,
|
||||||
|
map: Option<String>,
|
||||||
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
@@ -295,10 +299,13 @@ pub(super) async fn raw_keys_total(&self, map: Option<String>, prefix: Option<St
|
|||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_vals_sizes(
|
||||||
pub(super) async fn raw_vals_sizes(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
&self,
|
||||||
|
map: Option<String>,
|
||||||
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
@@ -318,10 +325,13 @@ pub(super) async fn raw_vals_sizes(&self, map: Option<String>, prefix: Option<St
|
|||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
self.write_str(&format!("```\n{result:#?}\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_vals_total(
|
||||||
pub(super) async fn raw_vals_total(&self, map: Option<String>, prefix: Option<String>) -> Result {
|
&self,
|
||||||
|
map: Option<String>,
|
||||||
|
prefix: Option<String>,
|
||||||
|
) -> Result {
|
||||||
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
let prefix = prefix.as_deref().unwrap_or(EMPTY);
|
||||||
|
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
@@ -337,17 +347,19 @@ pub(super) async fn raw_vals_total(&self, map: Option<String>, prefix: Option<St
|
|||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
self.write_str(&format!("```\n{result:#?}\n\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result {
|
||||||
pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Result {
|
|
||||||
writeln!(self, "```").await?;
|
writeln!(self, "```").await?;
|
||||||
|
|
||||||
let map = self.services.db.get(&map)?;
|
let map = self.services.db.get(&map)?;
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
prefix
|
prefix
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.map_or_else(|| map.raw_stream().boxed(), |prefix| map.raw_stream_prefix(prefix).boxed())
|
.map_or_else(
|
||||||
|
|| map.raw_stream().boxed(),
|
||||||
|
|prefix| map.raw_stream_prefix(prefix).boxed(),
|
||||||
|
)
|
||||||
.map_ok(apply!(2, String::from_utf8_lossy))
|
.map_ok(apply!(2, String::from_utf8_lossy))
|
||||||
.map_ok(apply!(2, Cow::into_owned))
|
.map_ok(apply!(2, Cow::into_owned))
|
||||||
.try_for_each(|keyval| writeln!(self, "{keyval:?}"))
|
.try_for_each(|keyval| writeln!(self, "{keyval:?}"))
|
||||||
@@ -357,15 +369,14 @@ pub(super) async fn raw_iter(&self, map: String, prefix: Option<String>) -> Resu
|
|||||||
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!("\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_keys_from(
|
||||||
pub(super) async fn raw_keys_from(
|
|
||||||
&self,
|
&self,
|
||||||
map: String,
|
map: String,
|
||||||
start: String,
|
start: String,
|
||||||
limit: Option<usize>,
|
limit: Option<usize>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
writeln!(self, "```").await?;
|
writeln!(self, "```").await?;
|
||||||
|
|
||||||
let map = self.services.db.get(&map)?;
|
let map = self.services.db.get(&map)?;
|
||||||
@@ -380,15 +391,14 @@ pub(super) async fn raw_keys_from(
|
|||||||
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!("\n```\n\nQuery completed in {query_time:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn raw_iter_from(
|
||||||
pub(super) async fn raw_iter_from(
|
|
||||||
&self,
|
&self,
|
||||||
map: String,
|
map: String,
|
||||||
start: String,
|
start: String,
|
||||||
limit: Option<usize>,
|
limit: Option<usize>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let map = self.services.db.get(&map)?;
|
let map = self.services.db.get(&map)?;
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
let result = map
|
let result = map
|
||||||
@@ -402,10 +412,9 @@ pub(super) async fn raw_iter_from(
|
|||||||
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]
|
pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
|
||||||
pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
|
|
||||||
let map = self.services.db.get(&map)?;
|
let map = self.services.db.get(&map)?;
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
map.remove(&key);
|
map.remove(&key);
|
||||||
@@ -413,10 +422,9 @@ pub(super) async fn raw_del(&self, map: String, key: String) -> Result {
|
|||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
self.write_str(&format!("Operation 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_get(&self, map: String, key: String) -> Result {
|
|
||||||
let map = self.services.db.get(&map)?;
|
let map = self.services.db.get(&map)?;
|
||||||
let timer = Instant::now();
|
let timer = Instant::now();
|
||||||
let handle = map.get(&key).await?;
|
let handle = map.get(&key).await?;
|
||||||
@@ -425,13 +433,13 @@ pub(super) async fn raw_get(&self, map: String, key: String) -> Result {
|
|||||||
let result = String::from_utf8_lossy(&handle);
|
let result = String::from_utf8_lossy(&handle);
|
||||||
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]
|
pub(super) async fn raw_maps(&self) -> Result {
|
||||||
pub(super) async fn raw_maps(&self) -> Result {
|
|
||||||
let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect();
|
let list: Vec<_> = self.services.db.iter().map(at!(0)).copied().collect();
|
||||||
|
|
||||||
self.write_str(&format!("{list:#?}")).await
|
self.write_str(&format!("{list:#?}")).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_maps_or<'a>(
|
fn with_maps_or<'a>(
|
||||||
|
|||||||
+11
-10
@@ -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,8 +39,8 @@ 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?;
|
||||||
@@ -61,10 +61,9 @@ async fn destinations_cache(&self, server_name: Option<OwnedServerName>) -> Resu
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn overrides_cache(&self, server_name: Option<String>) -> Result {
|
||||||
async fn overrides_cache(&self, server_name: Option<String>) -> Result {
|
|
||||||
use service::resolver::cache::CachedOverride;
|
use service::resolver::cache::CachedOverride;
|
||||||
|
|
||||||
writeln!(self, "| Server Name | IP | Port | Expires | Overriding |").await?;
|
writeln!(self, "| Server Name | IP | Port | Expires | Overriding |").await?;
|
||||||
@@ -82,15 +81,16 @@ async fn overrides_cache(&self, server_name: Option<String>) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let expire = time::format(expire, "%+");
|
let expire = time::format(expire, "%+");
|
||||||
self.write_str(&format!("| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n"))
|
self.write_str(&format!(
|
||||||
|
"| {name} | {ips:?} | {port} | {expire} | {overriding:?} |\n"
|
||||||
|
))
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result {
|
||||||
async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result {
|
|
||||||
if all {
|
if all {
|
||||||
self.services.resolver.cache.clear().await;
|
self.services.resolver.cache.clear().await;
|
||||||
writeln!(self, "Resolver caches cleared!").await
|
writeln!(self, "Resolver caches cleared!").await
|
||||||
@@ -102,4 +102,5 @@ async fn flush_cache(&self, name: Option<OwnedServerName>, all: bool) -> Result
|
|||||||
} else {
|
} else {
|
||||||
Err!("Missing name. Supply a name or use --all to flush the whole cache.")
|
Err!("Missing name. Supply a name or use --all to flush the whole cache.")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,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,8 +23,8 @@ 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
|
||||||
@@ -35,15 +35,14 @@ pub(super) async fn last(&self, room_id: OwnedRoomOrAliasId) -> Result {
|
|||||||
.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()?;
|
||||||
@@ -58,4 +57,5 @@ pub(super) async fn pdus(
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.write_str(&format!("```\n{result:#?}\n```")).await
|
self.write_str(&format!("```\n{result:#?}\n```")).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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,8 +17,8 @@ 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
|
||||||
@@ -27,13 +27,13 @@ pub(super) async fn short_event_id(&self, event_id: OwnedEventId) -> Result {
|
|||||||
.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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+62
-61
@@ -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,8 +92,8 @@ 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
|
||||||
@@ -106,16 +106,15 @@ async fn get_shared_rooms(&self, user_a: OwnedUserId, user_b: OwnedUserId) -> Re
|
|||||||
|
|
||||||
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
|
||||||
@@ -126,15 +125,14 @@ async fn get_backup_session(
|
|||||||
|
|
||||||
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_room_backups(
|
||||||
async fn get_room_backups(
|
|
||||||
&self,
|
&self,
|
||||||
user_id: OwnedUserId,
|
user_id: OwnedUserId,
|
||||||
version: String,
|
version: String,
|
||||||
room_id: OwnedRoomId,
|
room_id: OwnedRoomId,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
@@ -145,20 +143,18 @@ async fn get_room_backups(
|
|||||||
|
|
||||||
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_all_backups(&self, user_id: OwnedUserId, version: String) -> Result {
|
||||||
async fn get_all_backups(&self, user_id: OwnedUserId, version: String) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self.services.key_backups.get_all(&user_id, &version).await;
|
let result = self.services.key_backups.get_all(&user_id, &version).await;
|
||||||
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_algorithm(&self, user_id: OwnedUserId, version: String) -> Result {
|
||||||
async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
@@ -169,10 +165,9 @@ async fn get_backup_algorithm(&self, user_id: OwnedUserId, version: String) -> R
|
|||||||
|
|
||||||
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_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
|
||||||
async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
@@ -183,33 +178,36 @@ async fn get_latest_backup_version(&self, user_id: OwnedUserId) -> Result {
|
|||||||
|
|
||||||
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_latest_backup(&self, user_id: OwnedUserId) -> Result {
|
||||||
async fn get_latest_backup(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self.services.key_backups.get_latest_backup(&user_id).await;
|
let result = self.services.key_backups.get_latest_backup(&user_id).await;
|
||||||
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 iter_users(&self) -> Result {
|
||||||
async fn iter_users(&self) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result: Vec<OwnedUserId> = self.services.users.stream().map(Into::into).collect().await;
|
let result: Vec<OwnedUserId> = self
|
||||||
|
.services
|
||||||
|
.users
|
||||||
|
.stream_local_users()
|
||||||
|
.map(Into::into)
|
||||||
|
.collect()
|
||||||
|
.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 iter_users2(&self) -> Result {
|
||||||
async fn iter_users2(&self) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result: Vec<_> = self.services.users.stream().collect().await;
|
let result: Vec<_> = self.services.users.stream_local_users().collect().await;
|
||||||
let result: Vec<_> = result
|
let result: Vec<_> = result
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
|
.map(|user_id| String::from_utf8_lossy(user_id.as_bytes()).into_owned())
|
||||||
@@ -219,20 +217,18 @@ async fn iter_users2(&self) -> Result {
|
|||||||
|
|
||||||
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 count_users(&self) -> Result {
|
||||||
async fn count_users(&self) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self.services.users.count().await;
|
let result = self.services.users.count().await;
|
||||||
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 list_devices(&self, user_id: OwnedUserId) -> Result {
|
||||||
async fn list_devices(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let devices = self
|
let devices = self
|
||||||
.services
|
.services
|
||||||
@@ -245,10 +241,9 @@ async fn list_devices(&self, user_id: OwnedUserId) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result {
|
||||||
async fn list_devices_metadata(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let devices = self
|
let devices = self
|
||||||
.services
|
.services
|
||||||
@@ -260,10 +255,13 @@ 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```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{devices:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn get_device_metadata(
|
||||||
async fn get_device_metadata(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
&self,
|
||||||
|
user_id: OwnedUserId,
|
||||||
|
device_id: OwnedDeviceId,
|
||||||
|
) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let device = self
|
let device = self
|
||||||
.services
|
.services
|
||||||
@@ -274,20 +272,22 @@ async fn get_device_metadata(&self, user_id: OwnedUserId, device_id: OwnedDevice
|
|||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
|
||||||
async fn get_devices_version(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let device = self.services.users.get_devicelist_version(&user_id).await;
|
let device = self.services.users.get_devicelist_version(&user_id).await;
|
||||||
let query_time = timer.elapsed();
|
let query_time = timer.elapsed();
|
||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{device:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn count_one_time_keys(
|
||||||
async fn count_one_time_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
&self,
|
||||||
|
user_id: OwnedUserId,
|
||||||
|
device_id: OwnedDeviceId,
|
||||||
|
) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
@@ -298,10 +298,9 @@ async fn count_one_time_keys(&self, user_id: OwnedUserId, device_id: OwnedDevice
|
|||||||
|
|
||||||
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_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
||||||
async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
@@ -312,20 +311,18 @@ async fn get_device_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId)
|
|||||||
|
|
||||||
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_user_signing_key(&self, user_id: OwnedUserId) -> Result {
|
||||||
async fn get_user_signing_key(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self.services.users.get_user_signing_key(&user_id).await;
|
let result = self.services.users.get_user_signing_key(&user_id).await;
|
||||||
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_master_key(&self, user_id: OwnedUserId) -> Result {
|
||||||
async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
|
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
@@ -336,10 +333,13 @@ async fn get_master_key(&self, user_id: OwnedUserId) -> Result {
|
|||||||
|
|
||||||
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_to_device_events(
|
||||||
async fn get_to_device_events(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) -> Result {
|
&self,
|
||||||
|
user_id: OwnedUserId,
|
||||||
|
device_id: OwnedDeviceId,
|
||||||
|
) -> Result {
|
||||||
let timer = tokio::time::Instant::now();
|
let timer = tokio::time::Instant::now();
|
||||||
let result = self
|
let result = self
|
||||||
.services
|
.services
|
||||||
@@ -351,4 +351,5 @@ async fn get_to_device_events(&self, user_id: OwnedUserId, device_id: OwnedDevic
|
|||||||
|
|
||||||
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,18 +2,18 @@ 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
|
||||||
@@ -74,11 +74,11 @@ pub(super) async fn list_rooms(
|
|||||||
|
|
||||||
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len()))
|
self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len()))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result {
|
||||||
pub(super) async fn exists(&self, room_id: OwnedRoomId) -> Result {
|
|
||||||
let result = self.services.rooms.metadata.exists(&room_id).await;
|
let result = self.services.rooms.metadata.exists(&room_id).await;
|
||||||
|
|
||||||
self.write_str(&format!("{result}")).await
|
self.write_str(&format!("{result}")).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,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,8 +26,8 @@ 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
|
||||||
@@ -68,10 +68,9 @@ async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> R
|
|||||||
|
|
||||||
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
|
||||||
@@ -84,4 +83,5 @@ async fn view_room_topic(&self, room_id: OwnedRoomId) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("Room topic:\n```\n{room_topic}\n```"))
|
self.write_str(&format!("Room topic:\n```\n{room_topic}\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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,8 +45,8 @@ 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;
|
||||||
@@ -62,8 +62,8 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
| Ok(room_id) => room_id,
|
| Ok(room_id) => room_id,
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
(`#roomalias:example.com`): {e}"
|
(`#roomalias:example.com`): {e}"
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -77,8 +77,8 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
| Ok(room_alias) => room_alias,
|
| Ok(room_alias) => room_alias,
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
(`#roomalias:example.com`): {e}"
|
(`#roomalias:example.com`): {e}"
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -104,8 +104,8 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Room specified is not a room ID or room alias. Please note that this requires a \
|
"Room specified is not a room ID or room alias. Please note that this requires \
|
||||||
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
(`#roomalias:example.com`)",
|
(`#roomalias:example.com`)",
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -154,13 +154,13 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
self.services.rooms.metadata.disable_room(&room_id, true); // disable federation
|
self.services.rooms.metadata.disable_room(&room_id, true); // disable federation
|
||||||
|
|
||||||
self.write_str(
|
self.write_str(
|
||||||
"Room banned, removed all our local users, and disabled incoming federation with room.",
|
"Room banned, removed all our local users, and disabled incoming federation with \
|
||||||
|
room.",
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn ban_list_of_rooms(&self) -> Result {
|
||||||
async fn ban_list_of_rooms(&self) -> Result {
|
|
||||||
if self.body.len() < 2
|
if self.body.len() < 2
|
||||||
|| !self.body[0].trim().starts_with("```")
|
|| !self.body[0].trim().starts_with("```")
|
||||||
|| self.body.last().unwrap_or(&"").trim() != "```"
|
|| self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
@@ -183,7 +183,8 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
match <&RoomOrAliasId>::try_from(room) {
|
match <&RoomOrAliasId>::try_from(room) {
|
||||||
| Ok(room_alias_or_id) => {
|
| Ok(room_alias_or_id) => {
|
||||||
if let Ok(admin_room_id) = self.services.admin.get_admin_room().await {
|
if let Ok(admin_room_id) = self.services.admin.get_admin_room().await {
|
||||||
if room.to_owned().eq(&admin_room_id) || room.to_owned().eq(admin_room_alias)
|
if room.to_owned().eq(&admin_room_id)
|
||||||
|
|| room.to_owned().eq(admin_room_alias)
|
||||||
{
|
{
|
||||||
warn!("User specified admin room in bulk ban list, ignoring");
|
warn!("User specified admin room in bulk ban list, ignoring");
|
||||||
continue;
|
continue;
|
||||||
@@ -219,8 +220,9 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
| Ok(room_id) => room_id,
|
| Ok(room_id) => room_id,
|
||||||
| _ => {
|
| _ => {
|
||||||
debug!(
|
debug!(
|
||||||
"We don't have this room alias to a room ID locally, \
|
"We don't have this room alias to a room ID \
|
||||||
attempting to fetch room ID over federation"
|
locally, attempting to fetch room ID over \
|
||||||
|
federation"
|
||||||
);
|
);
|
||||||
|
|
||||||
match self
|
match self
|
||||||
@@ -241,8 +243,8 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
},
|
},
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
warn!(
|
warn!(
|
||||||
"Failed to resolve room alias {room} to a room \
|
"Failed to resolve room alias {room} to a \
|
||||||
ID: {e}"
|
room ID: {e}"
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
},
|
},
|
||||||
@@ -264,8 +266,8 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
},
|
},
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
warn!(
|
warn!(
|
||||||
"Error parsing room \"{room}\" during bulk room banning, ignoring error and \
|
"Error parsing room \"{room}\" during bulk room banning, ignoring error \
|
||||||
logging here: {e}"
|
and logging here: {e}"
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
},
|
},
|
||||||
@@ -287,8 +289,8 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
|
|
||||||
while let Some(ref user_id) = users.next().await {
|
while let Some(ref user_id) = users.next().await {
|
||||||
debug!(
|
debug!(
|
||||||
"Attempting leave for user {user_id} in room {room_id} (ignoring all errors, \
|
"Attempting leave for user {user_id} in room {room_id} (ignoring all \
|
||||||
evicting admins too)",
|
errors, evicting admins too)",
|
||||||
);
|
);
|
||||||
|
|
||||||
if let Err(e) = leave_room(self.services, user_id, &room_id, None)
|
if let Err(e) = leave_room(self.services, user_id, &room_id, None)
|
||||||
@@ -323,21 +325,20 @@ async fn ban_list_of_rooms(&self) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, and \
|
"Finished bulk room ban, banned {room_ban_count} total rooms, evicted all users, \
|
||||||
disabled incoming federation with the room."
|
and disabled incoming federation with the room."
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
||||||
async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|
||||||
let room_id = if room.is_room_id() {
|
let room_id = if room.is_room_id() {
|
||||||
let room_id = match RoomId::parse(&room) {
|
let room_id = match RoomId::parse(&room) {
|
||||||
| Ok(room_id) => room_id,
|
| Ok(room_id) => room_id,
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
(`#roomalias:example.com`): {e}"
|
(`#roomalias:example.com`): {e}"
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -352,8 +353,8 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
| Ok(room_alias) => room_alias,
|
| Ok(room_alias) => room_alias,
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Failed to parse room ID {room}. Please note that this requires a full room \
|
"Failed to parse room ID {room}. Please note that this requires a full \
|
||||||
ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
(`#roomalias:example.com`): {e}"
|
(`#roomalias:example.com`): {e}"
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -374,8 +375,8 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
| Ok(room_id) => room_id,
|
| Ok(room_id) => room_id,
|
||||||
| _ => {
|
| _ => {
|
||||||
debug!(
|
debug!(
|
||||||
"We don't have this room alias to a room ID locally, attempting to fetch \
|
"We don't have this room alias to a room ID locally, attempting to \
|
||||||
room ID over federation"
|
fetch room ID over federation"
|
||||||
);
|
);
|
||||||
|
|
||||||
match self.services.rooms.alias.resolve_alias(&room_alias).await {
|
match self.services.rooms.alias.resolve_alias(&room_alias).await {
|
||||||
@@ -399,8 +400,8 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
room_id
|
room_id
|
||||||
} else {
|
} else {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Room specified is not a room ID or room alias. Please note that this requires a \
|
"Room specified is not a room ID or room alias. Please note that this requires \
|
||||||
full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
a full room ID (`!awIh6gGInaS5wLQJwa:example.com`) or a room alias \
|
||||||
(`#roomalias:example.com`)",
|
(`#roomalias:example.com`)",
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -408,10 +409,9 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
|
|||||||
self.services.rooms.metadata.disable_room(&room_id, false);
|
self.services.rooms.metadata.disable_room(&room_id, false);
|
||||||
self.write_str("Room unbanned and federation re-enabled.")
|
self.write_str("Room unbanned and federation re-enabled.")
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
async fn list_banned_rooms(&self, no_details: bool) -> Result {
|
||||||
async fn list_banned_rooms(&self, no_details: bool) -> Result {
|
|
||||||
let room_ids: Vec<OwnedRoomId> = self
|
let room_ids: Vec<OwnedRoomId> = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
@@ -451,4 +451,5 @@ async fn list_banned_rooms(&self, no_details: bool) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
|
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,10 +7,8 @@ use conduwuit::{
|
|||||||
};
|
};
|
||||||
use futures::TryStreamExt;
|
use futures::TryStreamExt;
|
||||||
|
|
||||||
use crate::admin_command;
|
impl crate::Context<'_> {
|
||||||
|
pub(super) async fn uptime(&self) -> Result {
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn uptime(&self) -> Result {
|
|
||||||
let elapsed = self
|
let elapsed = self
|
||||||
.services
|
.services
|
||||||
.server
|
.server
|
||||||
@@ -20,18 +18,16 @@ pub(super) async fn uptime(&self) -> Result {
|
|||||||
|
|
||||||
let result = time::pretty(elapsed);
|
let result = time::pretty(elapsed);
|
||||||
self.write_str(&format!("{result}.")).await
|
self.write_str(&format!("{result}.")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn show_config(&self) -> Result {
|
||||||
pub(super) async fn show_config(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
self.write_str(&format!("{}", *self.services.server.config))
|
self.write_str(&format!("{}", *self.services.server.config))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
|
||||||
pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
|
|
||||||
// The path argument is only what's optionally passed via the admin command,
|
// The path argument is only what's optionally passed via the admin command,
|
||||||
// so we need to merge it with the existing paths if any were given at startup.
|
// so we need to merge it with the existing paths if any were given at startup.
|
||||||
let mut paths = Vec::new();
|
let mut paths = Vec::new();
|
||||||
@@ -57,30 +53,27 @@ pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("Successfully reconfigured from paths: {paths:?}"))
|
self.write_str(&format!("Successfully reconfigured from paths: {paths:?}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn memory_usage(&self) -> Result {
|
||||||
pub(super) async fn memory_usage(&self) -> Result {
|
|
||||||
let services_usage = self.services.memory_usage().await?;
|
let services_usage = self.services.memory_usage().await?;
|
||||||
let database_usage = self.services.db.db.memory_usage()?;
|
let database_usage = self.services.db.db.memory_usage()?;
|
||||||
let allocator_usage =
|
let allocator_usage = conduwuit::alloc::memory_usage()
|
||||||
conduwuit::alloc::memory_usage().map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
|
.map_or(String::new(), |s| format!("\nAllocator:\n{s}"));
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
|
"Services:\n{services_usage}\nDatabase:\n{database_usage}{allocator_usage}",
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn clear_caches(&self) -> Result {
|
||||||
pub(super) async fn clear_caches(&self) -> Result {
|
|
||||||
self.services.clear_cache().await;
|
self.services.clear_cache().await;
|
||||||
|
|
||||||
self.write_str("Done.").await
|
self.write_str("Done.").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn list_backups(&self) -> Result {
|
||||||
pub(super) async fn list_backups(&self) -> Result {
|
|
||||||
self.services
|
self.services
|
||||||
.db
|
.db
|
||||||
.db
|
.db
|
||||||
@@ -88,10 +81,9 @@ pub(super) async fn list_backups(&self) -> Result {
|
|||||||
.try_stream()
|
.try_stream()
|
||||||
.try_for_each(|result| writeln!(self, "{result}"))
|
.try_for_each(|result| writeln!(self, "{result}"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn backup_database(&self) -> Result {
|
||||||
pub(super) async fn backup_database(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
let db = Arc::clone(&self.services.db);
|
let db = Arc::clone(&self.services.db);
|
||||||
@@ -108,54 +100,49 @@ pub(super) async fn backup_database(&self) -> Result {
|
|||||||
let count = self.services.db.db.backup_count()?;
|
let count = self.services.db.db.backup_count()?;
|
||||||
self.write_str(&format!("{result}. Currently have {count} backups."))
|
self.write_str(&format!("{result}. Currently have {count} backups."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
|
||||||
pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
|
|
||||||
let message = message.join(" ");
|
let message = message.join(" ");
|
||||||
self.services.admin.send_text(&message).await;
|
self.services.admin.send_text(&message).await;
|
||||||
|
|
||||||
self.write_str("Notice was sent to #admins").await
|
self.write_str("Notice was sent to #admins").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn reload_mods(&self) -> Result {
|
||||||
pub(super) async fn reload_mods(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
self.services.server.reload()?;
|
self.services.server.reload()?;
|
||||||
|
|
||||||
self.write_str("Reloading server...").await
|
self.write_str("Reloading server...").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
#[cfg(unix)]
|
||||||
#[cfg(unix)]
|
pub(super) async fn restart(&self, force: bool) -> Result {
|
||||||
pub(super) async fn restart(&self, force: bool) -> Result {
|
|
||||||
use conduwuit::utils::sys::current_exe_deleted;
|
use conduwuit::utils::sys::current_exe_deleted;
|
||||||
|
|
||||||
if !force && current_exe_deleted() {
|
if !force && current_exe_deleted() {
|
||||||
return Err!(
|
return Err!(
|
||||||
"The server cannot be restarted because the executable changed. If this is expected \
|
"The server cannot be restarted because the executable changed. If this is \
|
||||||
use --force to override."
|
expected use --force to override."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.services.server.restart()?;
|
self.services.server.restart()?;
|
||||||
|
|
||||||
self.write_str("Restarting server...").await
|
self.write_str("Restarting server...").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn shutdown(&self) -> Result {
|
||||||
pub(super) async fn shutdown(&self) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
warn!("shutdown command");
|
warn!("shutdown command");
|
||||||
self.services.server.shutdown()?;
|
self.services.server.shutdown()?;
|
||||||
|
|
||||||
self.write_str("Shutting down server...").await
|
self.write_str("Shutting down server...").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn list_features(&self) -> Result {
|
||||||
pub(super) async fn list_features(&self) -> Result {
|
|
||||||
let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
|
let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES
|
||||||
.lock()
|
.lock()
|
||||||
.expect("locked")
|
.expect("locked")
|
||||||
@@ -184,10 +171,9 @@ pub(super) async fn list_features(&self) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&features).await
|
self.write_str(&features).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn build_info(&self) -> Result {
|
||||||
pub(super) async fn build_info(&self) -> Result {
|
|
||||||
use conduwuit::build_metadata::built;
|
use conduwuit::build_metadata::built;
|
||||||
|
|
||||||
let mut info = String::new();
|
let mut info = String::new();
|
||||||
@@ -246,4 +232,5 @@ pub(super) async fn build_info(&self) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.write_str(&info).await
|
self.write_str(&info).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+35
-12
@@ -1,10 +1,9 @@
|
|||||||
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
|
||||||
@@ -15,7 +14,9 @@ pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
|
|||||||
} else if let Some(max_age) = expires
|
} else if let Some(max_age) = expires
|
||||||
.max_age
|
.max_age
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.map(|max_age| utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?))
|
.map(|max_age| {
|
||||||
|
utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?)
|
||||||
|
})
|
||||||
.transpose()?
|
.transpose()?
|
||||||
{
|
{
|
||||||
Some(TokenExpires::AfterTime(max_age))
|
Some(TokenExpires::AfterTime(max_age))
|
||||||
@@ -30,18 +31,40 @@ pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
|
|||||||
.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
|
.await?;
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
if self
|
||||||
pub(super) async fn revoke_token(&self, token: String) -> Result {
|
.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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn revoke_token(&self, token: String) -> Result {
|
||||||
let Some(token) = self
|
let Some(token) = self
|
||||||
.services
|
.services
|
||||||
.registration_tokens
|
.registration_tokens
|
||||||
@@ -54,10 +77,9 @@ pub(super) async fn revoke_token(&self, token: String) -> Result {
|
|||||||
self.services.registration_tokens.revoke_token(token)?;
|
self.services.registration_tokens.revoke_token(token)?;
|
||||||
|
|
||||||
self.write_str("Token revoked successfully.").await
|
self.write_str("Token revoked successfully.").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn list_tokens(&self) -> Result {
|
||||||
pub(super) async fn list_tokens(&self) -> Result {
|
|
||||||
let tokens: Vec<_> = self
|
let tokens: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.registration_tokens
|
.registration_tokens
|
||||||
@@ -73,4 +95,5 @@ pub(super) async fn list_tokens(&self) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+162
-315
@@ -1,13 +1,10 @@
|
|||||||
use std::{
|
use std::collections::{BTreeMap, HashSet};
|
||||||
collections::{BTreeMap, HashSet},
|
|
||||||
fmt::Write as _,
|
|
||||||
};
|
|
||||||
|
|
||||||
use api::client::{
|
use api::client::{
|
||||||
full_user_deactivate, leave_room, recreate_push_rules_and_return, remote_leave_room,
|
full_user_deactivate, leave_room, recreate_push_rules_and_return, remote_leave_room,
|
||||||
};
|
};
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Err, Result, debug_warn, error, info,
|
Err, Result, debug_warn, info,
|
||||||
matrix::{Event, pdu::PartialPdu},
|
matrix::{Event, pdu::PartialPdu},
|
||||||
utils::{self, ReadyExt},
|
utils::{self, ReadyExt},
|
||||||
warn,
|
warn,
|
||||||
@@ -23,18 +20,18 @@ use ruma::{
|
|||||||
tag::{TagEvent, TagEventContent, TagInfo},
|
tag::{TagEvent, TagEventContent, TagInfo},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use service::users::HashedPassword;
|
use service::users::{AccountStatus, HashedPassword};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
admin_command, get_room_info,
|
get_room_info,
|
||||||
utils::{parse_active_local_user_id, parse_local_user_id},
|
utils::{parse_active_local_user_id, parse_local_user_id},
|
||||||
};
|
};
|
||||||
|
|
||||||
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
|
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
|
||||||
const BULK_JOIN_REASON: &str = "Bulk force joining this room as initiated by the server admin.";
|
const BULK_JOIN_REASON: &str = "Bulk force joining this room as initiated by the server admin.";
|
||||||
|
|
||||||
#[admin_command]
|
impl crate::Context<'_> {
|
||||||
pub(super) async fn list_users(&self) -> Result {
|
pub(super) async fn list_users(&self) -> Result {
|
||||||
let users: Vec<_> = self
|
let users: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.users
|
.users
|
||||||
@@ -48,139 +45,28 @@ pub(super) async fn list_users(&self) -> Result {
|
|||||||
plain_msg += "\n```";
|
plain_msg += "\n```";
|
||||||
|
|
||||||
self.write_str(&plain_msg).await
|
self.write_str(&plain_msg).await
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn create_user(&self, username: String, password: Option<String>) -> Result {
|
|
||||||
// Validate user id
|
|
||||||
let user_id = parse_local_user_id(self.services, &username)?;
|
|
||||||
|
|
||||||
if let Err(e) = user_id.validate_strict() {
|
|
||||||
if self.services.config.emergency_password.is_none() {
|
|
||||||
return Err!("Username {user_id} contains disallowed characters or spaces: {e}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.services.users.exists(&user_id).await {
|
pub(super) async fn create_user(&self, username: String, password: Option<String>) -> Result {
|
||||||
return Err!("User {user_id} already exists");
|
let user_id = self
|
||||||
}
|
.services
|
||||||
|
|
||||||
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
|
||||||
|
|
||||||
// Create user
|
|
||||||
self.services
|
|
||||||
.users
|
.users
|
||||||
.create(&user_id, Some(HashedPassword::new(&password)?))
|
.determine_registration_user_id(Some(username), None, None)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Default to pretty displayname
|
let password =
|
||||||
let mut displayname = user_id.localpart().to_owned();
|
&password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
||||||
|
|
||||||
// If `new_user_displayname_suffix` is set, registration will push whatever
|
|
||||||
// content is set to the user's display name with a space before it
|
|
||||||
if !self
|
|
||||||
.services
|
|
||||||
.server
|
|
||||||
.config
|
|
||||||
.new_user_displayname_suffix
|
|
||||||
.is_empty()
|
|
||||||
{
|
|
||||||
write!(displayname, " {}", self.services.server.config.new_user_displayname_suffix)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.set_displayname(&user_id, Some(displayname));
|
.create_local_account(&user_id, Some(HashedPassword::new(password)?), None)
|
||||||
|
|
||||||
// Initial account data
|
|
||||||
self.services
|
|
||||||
.account_data
|
|
||||||
.update(
|
|
||||||
None,
|
|
||||||
&user_id,
|
|
||||||
ruma::events::GlobalAccountDataEventType::PushRules
|
|
||||||
.to_string()
|
|
||||||
.into(),
|
|
||||||
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent::new(
|
|
||||||
ruma::events::push_rules::PushRulesEventContent::new(
|
|
||||||
ruma::push::Ruleset::server_default(&user_id),
|
|
||||||
),
|
|
||||||
))
|
|
||||||
.unwrap(),
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !self.services.server.config.auto_join_rooms.is_empty() {
|
self.write_str(&format!("Created user {user_id} with password `{password}`"))
|
||||||
for room in &self.services.server.config.auto_join_rooms {
|
|
||||||
let Ok(room_id) = self.services.rooms.alias.resolve(room).await else {
|
|
||||||
error!(
|
|
||||||
%user_id,
|
|
||||||
"Failed to resolve room alias to room ID when attempting to auto join {room}, skipping"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
if !self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.server_in_room(self.services.globals.server_name(), &room_id)
|
|
||||||
.await
|
.await
|
||||||
{
|
|
||||||
warn!(
|
|
||||||
"Skipping room {room} to automatically join as we have never joined before."
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(room_server_name) = room.server_name() {
|
pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result {
|
||||||
match self
|
|
||||||
.services
|
|
||||||
.rooms
|
|
||||||
.membership
|
|
||||||
.join_room(
|
|
||||||
&user_id,
|
|
||||||
&room_id,
|
|
||||||
Some("Automatically joining this room upon registration".to_owned()),
|
|
||||||
&[
|
|
||||||
self.services.globals.server_name().to_owned(),
|
|
||||||
room_server_name.to_owned(),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
| Ok(_response) => {
|
|
||||||
info!("Automatically joined room {room} for user {user_id}");
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
// don't return this error so we don't fail registrations
|
|
||||||
error!(
|
|
||||||
"Failed to automatically join room {room} for user {user_id}: {e}"
|
|
||||||
);
|
|
||||||
self.services
|
|
||||||
.admin
|
|
||||||
.send_text(&format!(
|
|
||||||
"Failed to automatically join room {room} for user {user_id}: \
|
|
||||||
{e}"
|
|
||||||
))
|
|
||||||
.await;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// we dont add a device since we're not the user, just the creator
|
|
||||||
|
|
||||||
// Make the first user to register an administrator and disable first-run mode.
|
|
||||||
self.services.firstrun.empower_first_user(&user_id).await?;
|
|
||||||
|
|
||||||
self.write_str(&format!("Created user with user_id: {user_id} and password: `{password}`"))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) -> Result {
|
|
||||||
// Validate user id
|
// Validate user id
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
@@ -213,20 +99,16 @@ pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) ->
|
|||||||
|
|
||||||
self.write_str(&format!("User {user_id} has been deactivated"))
|
self.write_str(&format!("User {user_id} has been deactivated"))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn suspend(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn suspend(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to suspend the server service account.",);
|
return Err!("Not allowed to suspend the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.services.users.exists(&user_id).await {
|
|
||||||
return Err!("User {user_id} does not exist.");
|
|
||||||
}
|
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("Admin users cannot be suspended.");
|
return Err!("Admin users cannot be suspended.");
|
||||||
}
|
}
|
||||||
@@ -238,52 +120,71 @@ pub(super) async fn suspend(&self, user_id: String) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("User {user_id} has been suspended."))
|
self.write_str(&format!("User {user_id} has been suspended."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn unsuspend(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn unsuspend(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to unsuspend the server service account.",);
|
return Err!("Not allowed to unsuspend the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.services.users.exists(&user_id).await {
|
|
||||||
return Err!("User {user_id} does not exist.");
|
|
||||||
}
|
|
||||||
self.services.users.unsuspend_account(&user_id).await;
|
self.services.users.unsuspend_account(&user_id).await;
|
||||||
|
|
||||||
self.write_str(&format!("User {user_id} has been unsuspended."))
|
self.write_str(&format!("User {user_id} has been unsuspended."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn reset_password(
|
||||||
pub(super) async fn reset_password(
|
|
||||||
&self,
|
&self,
|
||||||
logout: bool,
|
logout: bool,
|
||||||
username: String,
|
username: String,
|
||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
) -> Result {
|
convert_to_local_account: bool,
|
||||||
|
) -> Result {
|
||||||
let user_id = parse_local_user_id(self.services, &username)?;
|
let user_id = parse_local_user_id(self.services, &username)?;
|
||||||
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!(
|
return Err!(
|
||||||
"Not allowed to set the password for the server account. Please use the emergency \
|
"Not allowed to set the password for the server account. Please use the \
|
||||||
password config option.",
|
emergency password config option.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let new_password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
let new_password =
|
||||||
|
password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
||||||
|
let new_password_hash = HashedPassword::new(&new_password)?;
|
||||||
|
|
||||||
|
if convert_to_local_account {
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.set_password(&user_id, Some(HashedPassword::new(&new_password)?));
|
.convert_to_local_account(&user_id, new_password_hash)
|
||||||
|
.await?;
|
||||||
|
} else {
|
||||||
|
match self.services.users.status(&user_id).await {
|
||||||
|
| AccountStatus::Active if !self.services.users.is_shadow(&user_id).await => {
|
||||||
|
self.services
|
||||||
|
.users
|
||||||
|
.set_password(&user_id, new_password_hash)
|
||||||
|
.await?;
|
||||||
|
},
|
||||||
|
| AccountStatus::NotFound => {
|
||||||
|
return Err!("The provided user does not exist.");
|
||||||
|
},
|
||||||
|
| _ => {
|
||||||
|
return Err!(
|
||||||
|
"The provided user is a shadow or deactivated account. To convert it to \
|
||||||
|
a local account, pass the --convert-to-local-account flag."
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Successfully reset the password for user {user_id}: `{new_password}`"
|
"Successfully reset the password for user {user_id}: `{new_password}`"
|
||||||
))
|
))
|
||||||
.await?;
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
if logout {
|
if logout {
|
||||||
self.services
|
self.services
|
||||||
@@ -300,35 +201,9 @@ pub(super) async fn reset_password(
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) -> Result {
|
||||||
pub(super) async fn issue_password_reset_link(&self, username: String) -> Result {
|
|
||||||
use conduwuit_service::password_reset::{PASSWORD_RESET_PATH, RESET_TOKEN_QUERY_PARAM};
|
|
||||||
|
|
||||||
self.bail_restricted()?;
|
|
||||||
|
|
||||||
let mut reset_url = self
|
|
||||||
.services
|
|
||||||
.config
|
|
||||||
.get_client_domain()
|
|
||||||
.join(PASSWORD_RESET_PATH)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let user_id = parse_local_user_id(self.services, &username)?;
|
|
||||||
let token = self.services.password_reset.issue_token(user_id).await?;
|
|
||||||
reset_url
|
|
||||||
.query_pairs_mut()
|
|
||||||
.append_pair(RESET_TOKEN_QUERY_PARAM, &token.token);
|
|
||||||
|
|
||||||
self.write_str(&format!("Password reset link issued for {username}: {reset_url}"))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) -> Result {
|
|
||||||
if self.body.len() < 2
|
if self.body.len() < 2
|
||||||
|| !self.body[0].trim().starts_with("```")
|
|| !self.body[0].trim().starts_with("```")
|
||||||
|| self.body.last().unwrap_or(&"").trim() != "```"
|
|| self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
@@ -350,7 +225,9 @@ pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) ->
|
|||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
self.services
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_text(&format!("{username} is not a valid username, skipping over: {e}"))
|
.send_text(&format!(
|
||||||
|
"{username} is not a valid username, skipping over: {e}"
|
||||||
|
))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
@@ -398,7 +275,9 @@ pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) ->
|
|||||||
| Ok(()) => {
|
| Ok(()) => {
|
||||||
deactivation_count = deactivation_count.saturating_add(1);
|
deactivation_count = deactivation_count.saturating_add(1);
|
||||||
if !no_leave_rooms {
|
if !no_leave_rooms {
|
||||||
info!("Forcing user {user_id} to leave all rooms apart of deactivate-all");
|
info!(
|
||||||
|
"Forcing user {user_id} to leave all rooms apart of deactivate-all"
|
||||||
|
);
|
||||||
let all_joined_rooms: Vec<OwnedRoomId> = self
|
let all_joined_rooms: Vec<OwnedRoomId> = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
@@ -427,10 +306,9 @@ pub(super) async fn deactivate_all(&self, no_leave_rooms: bool, force: bool) ->
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn list_invited_rooms(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn list_invited_rooms(&self, user_id: String) -> Result {
|
|
||||||
// Validate user id
|
// Validate user id
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
@@ -468,12 +346,14 @@ pub(super) async fn list_invited_rooms(&self, user_id: String) -> Result {
|
|||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("\n");
|
.join("\n");
|
||||||
|
|
||||||
self.write_str(&format!("Rooms {user_id} is Invited to ({}):\n```\n{body}\n```", rooms.len()))
|
self.write_str(&format!(
|
||||||
|
"Rooms {user_id} is Invited to ({}):\n```\n{body}\n```",
|
||||||
|
rooms.len()
|
||||||
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn reject_all_invites(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn reject_all_invites(&self, user_id: String) -> Result {
|
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
assert!(
|
assert!(
|
||||||
@@ -503,10 +383,9 @@ pub(super) async fn reject_all_invites(&self, user_id: String) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.write_str("Successfully rejected all invites.").await
|
self.write_str("Successfully rejected all invites.").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
|
|
||||||
// Validate user id
|
// Validate user id
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
@@ -534,14 +413,13 @@ pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("Rooms {user_id} Joined ({}):\n```\n{body}\n```", rooms.len()))
|
self.write_str(&format!("Rooms {user_id} Joined ({}):\n```\n{body}\n```", rooms.len()))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn force_join_list_of_local_users(
|
||||||
pub(super) async fn force_join_list_of_local_users(
|
|
||||||
&self,
|
&self,
|
||||||
room_id: OwnedRoomOrAliasId,
|
room_id: OwnedRoomOrAliasId,
|
||||||
yes_i_want_to_do_this: bool,
|
yes_i_want_to_do_this: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
if self.body.len() < 2
|
if self.body.len() < 2
|
||||||
|| !self.body[0].trim().starts_with("```")
|
|| !self.body[0].trim().starts_with("```")
|
||||||
|| self.body.last().unwrap_or(&"").trim() != "```"
|
|| self.body.last().unwrap_or(&"").trim() != "```"
|
||||||
@@ -551,8 +429,8 @@ pub(super) async fn force_join_list_of_local_users(
|
|||||||
|
|
||||||
if !yes_i_want_to_do_this {
|
if !yes_i_want_to_do_this {
|
||||||
return Err!(
|
return Err!(
|
||||||
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to force \
|
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
|
||||||
bulk join all specified local users.",
|
force bulk join all specified local users.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -618,7 +496,9 @@ pub(super) async fn force_join_list_of_local_users(
|
|||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
self.services
|
self.services
|
||||||
.admin
|
.admin
|
||||||
.send_text(&format!("{username} is not a valid username, skipping over: {e}"))
|
.send_text(&format!(
|
||||||
|
"{username} is not a valid username, skipping over: {e}"
|
||||||
|
))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
@@ -641,7 +521,9 @@ pub(super) async fn force_join_list_of_local_users(
|
|||||||
successful_joins = successful_joins.saturating_add(1);
|
successful_joins = successful_joins.saturating_add(1);
|
||||||
},
|
},
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
debug_warn!("Failed force joining {user_id} to {room_id} during bulk join: {e}");
|
debug_warn!(
|
||||||
|
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
|
||||||
|
);
|
||||||
failed_joins = failed_joins.saturating_add(1);
|
failed_joins = failed_joins.saturating_add(1);
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -652,18 +534,17 @@ pub(super) async fn force_join_list_of_local_users(
|
|||||||
failed.",
|
failed.",
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn force_join_all_local_users(
|
||||||
pub(super) async fn force_join_all_local_users(
|
|
||||||
&self,
|
&self,
|
||||||
room_id: OwnedRoomOrAliasId,
|
room_id: OwnedRoomOrAliasId,
|
||||||
yes_i_want_to_do_this: bool,
|
yes_i_want_to_do_this: bool,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
if !yes_i_want_to_do_this {
|
if !yes_i_want_to_do_this {
|
||||||
return Err!(
|
return Err!(
|
||||||
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to force \
|
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
|
||||||
bulk join all local users.",
|
force bulk join all local users.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -722,7 +603,9 @@ pub(super) async fn force_join_all_local_users(
|
|||||||
successful_joins = successful_joins.saturating_add(1);
|
successful_joins = successful_joins.saturating_add(1);
|
||||||
},
|
},
|
||||||
| Err(e) => {
|
| Err(e) => {
|
||||||
debug_warn!("Failed force joining {user_id} to {room_id} during bulk join: {e}");
|
debug_warn!(
|
||||||
|
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
|
||||||
|
);
|
||||||
failed_joins = failed_joins.saturating_add(1);
|
failed_joins = failed_joins.saturating_add(1);
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -733,15 +616,14 @@ pub(super) async fn force_join_all_local_users(
|
|||||||
failed.",
|
failed.",
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn force_join_room(
|
||||||
pub(super) async fn force_join_room(
|
|
||||||
&self,
|
&self,
|
||||||
user_id: String,
|
user_id: String,
|
||||||
room_id: OwnedRoomOrAliasId,
|
room_id: OwnedRoomOrAliasId,
|
||||||
via: Option<String>,
|
via: Option<String>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
let (room_id, mut servers) = self
|
let (room_id, mut servers) = self
|
||||||
.services
|
.services
|
||||||
@@ -766,14 +648,13 @@ pub(super) async fn force_join_room(
|
|||||||
|
|
||||||
self.write_str(&format!("{user_id} has been joined to {room_id}."))
|
self.write_str(&format!("{user_id} has been joined to {room_id}."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn force_leave_room(
|
||||||
pub(super) async fn force_leave_room(
|
|
||||||
&self,
|
&self,
|
||||||
user_id: String,
|
user_id: String,
|
||||||
room_id: OwnedRoomOrAliasId,
|
room_id: OwnedRoomOrAliasId,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
||||||
|
|
||||||
@@ -798,10 +679,13 @@ pub(super) async fn force_leave_room(
|
|||||||
|
|
||||||
self.write_str(&format!("{user_id} has left {room_id}."))
|
self.write_str(&format!("{user_id} has left {room_id}."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn force_demote(
|
||||||
pub(super) async fn force_demote(&self, user_id: String, room_id: OwnedRoomOrAliasId) -> Result {
|
&self,
|
||||||
|
user_id: String,
|
||||||
|
room_id: OwnedRoomOrAliasId,
|
||||||
|
) -> Result {
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
|
||||||
|
|
||||||
@@ -849,10 +733,9 @@ pub(super) async fn force_demote(&self, user_id: String, room_id: OwnedRoomOrAli
|
|||||||
{event_id}"
|
{event_id}"
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn make_user_admin(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn make_user_admin(&self, user_id: String) -> Result {
|
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
assert!(
|
assert!(
|
||||||
self.services.globals.user_is_local(&user_id),
|
self.services.globals.user_is_local(&user_id),
|
||||||
@@ -867,15 +750,14 @@ pub(super) async fn make_user_admin(&self, user_id: String) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("{user_id} has been granted admin privileges."))
|
self.write_str(&format!("{user_id} has been granted admin privileges."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn put_room_tag(
|
||||||
pub(super) async fn put_room_tag(
|
|
||||||
&self,
|
&self,
|
||||||
user_id: String,
|
user_id: String,
|
||||||
room_id: OwnedRoomId,
|
room_id: OwnedRoomId,
|
||||||
tag: String,
|
tag: String,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
let mut tags_event = self
|
let mut tags_event = self
|
||||||
@@ -901,18 +783,18 @@ pub(super) async fn put_room_tag(
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Successfully updated room account data for {user_id} and room {room_id} with tag {tag}"
|
"Successfully updated room account data for {user_id} and room {room_id} with tag \
|
||||||
|
{tag}"
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn delete_room_tag(
|
||||||
pub(super) async fn delete_room_tag(
|
|
||||||
&self,
|
&self,
|
||||||
user_id: String,
|
user_id: String,
|
||||||
room_id: OwnedRoomId,
|
room_id: OwnedRoomId,
|
||||||
tag: String,
|
tag: String,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
let mut tags_event = self
|
let mut tags_event = self
|
||||||
@@ -935,14 +817,13 @@ pub(super) async fn delete_room_tag(
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"Successfully updated room account data for {user_id} and room {room_id}, deleting room \
|
"Successfully updated room account data for {user_id} and room {room_id}, deleting \
|
||||||
tag {tag}"
|
room tag {tag}"
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_room_tags(&self, user_id: String, room_id: OwnedRoomId) -> Result {
|
||||||
pub(super) async fn get_room_tags(&self, user_id: String, room_id: OwnedRoomId) -> Result {
|
|
||||||
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
let tags_event = self
|
let tags_event = self
|
||||||
@@ -954,10 +835,9 @@ pub(super) async fn get_room_tags(&self, user_id: String, room_id: OwnedRoomId)
|
|||||||
|
|
||||||
self.write_str(&format!("```\n{:#?}\n```", tags_event.content.tags))
|
self.write_str(&format!("```\n{:#?}\n```", tags_event.content.tags))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn redact_event(&self, event_id: OwnedEventId) -> Result {
|
||||||
pub(super) async fn redact_event(&self, event_id: OwnedEventId) -> Result {
|
|
||||||
let Ok(event) = self
|
let Ok(event) = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
@@ -1012,15 +892,14 @@ pub(super) async fn redact_event(&self, event_id: OwnedEventId) -> Result {
|
|||||||
"Successfully redacted event. Redaction event ID: {redaction_event_id}"
|
"Successfully redacted event. Redaction event ID: {redaction_event_id}"
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn force_leave_remote_room(
|
||||||
pub(super) async fn force_leave_remote_room(
|
|
||||||
&self,
|
&self,
|
||||||
user_id: String,
|
user_id: String,
|
||||||
room_id: OwnedRoomOrAliasId,
|
room_id: OwnedRoomOrAliasId,
|
||||||
via: Option<String>,
|
via: Option<String>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
let (room_id, vias_raw) = self
|
let (room_id, vias_raw) = self
|
||||||
.services
|
.services
|
||||||
@@ -1053,26 +932,20 @@ pub(super) async fn force_leave_remote_room(
|
|||||||
|
|
||||||
self.write_str(&format!("{user_id} successfully left {room_id} via remote server."))
|
self.write_str(&format!("{user_id} successfully left {room_id} via remote server."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn lock(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn lock(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
assert!(
|
|
||||||
self.services.globals.user_is_local(&user_id),
|
|
||||||
"Parsed user_id must be a local user"
|
|
||||||
);
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to lock the server service account.",);
|
return Err!("Not allowed to lock the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.services.users.exists(&user_id).await {
|
|
||||||
return Err!("User {user_id} does not exist.");
|
|
||||||
}
|
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("Admin users cannot be locked.");
|
return Err!("Admin users cannot be locked.");
|
||||||
}
|
}
|
||||||
|
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.lock_account(&user_id, self.sender_or_service_user())
|
.lock_account(&user_id, self.sender_or_service_user())
|
||||||
@@ -1080,40 +953,30 @@ pub(super) async fn lock(&self, user_id: String) -> Result {
|
|||||||
|
|
||||||
self.write_str(&format!("User {user_id} has been locked."))
|
self.write_str(&format!("User {user_id} has been locked."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn unlock(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn unlock(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
assert!(
|
|
||||||
self.services.globals.user_is_local(&user_id),
|
|
||||||
"Parsed user_id must be a local user"
|
|
||||||
);
|
|
||||||
self.services.users.unlock_account(&user_id).await;
|
self.services.users.unlock_account(&user_id).await;
|
||||||
|
|
||||||
self.write_str(&format!("User {user_id} has been unlocked."))
|
self.write_str(&format!("User {user_id} has been unlocked."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn logout(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn logout(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
assert!(
|
|
||||||
self.services.globals.user_is_local(&user_id),
|
|
||||||
"Parsed user_id must be a local user"
|
|
||||||
);
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to log out the server service account.",);
|
return Err!("Not allowed to log out the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.services.users.exists(&user_id).await {
|
|
||||||
return Err!("User {user_id} does not exist.");
|
|
||||||
}
|
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("You cannot forcefully log out admin users.");
|
return Err!("You cannot forcefully log out admin users.");
|
||||||
}
|
}
|
||||||
|
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
.all_device_ids(&user_id)
|
.all_device_ids(&user_id)
|
||||||
@@ -1126,23 +989,16 @@ pub(super) async fn logout(&self, user_id: String) -> Result {
|
|||||||
.await;
|
.await;
|
||||||
self.write_str(&format!("User {user_id} has been logged out from all devices."))
|
self.write_str(&format!("User {user_id} has been logged out from all devices."))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn disable_login(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn disable_login(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
assert!(
|
|
||||||
self.services.globals.user_is_local(&user_id),
|
|
||||||
"Parsed user_id must be a local user"
|
|
||||||
);
|
|
||||||
if user_id == self.services.globals.server_user {
|
if user_id == self.services.globals.server_user {
|
||||||
return Err!("Not allowed to disable login for the server service account.",);
|
return Err!("Not allowed to disable login for the server service account.",);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.services.users.exists(&user_id).await {
|
|
||||||
return Err!("User {user_id} does not exist.");
|
|
||||||
}
|
|
||||||
if self.services.users.is_admin(&user_id).await {
|
if self.services.users.is_admin(&user_id).await {
|
||||||
return Err!("Admin users cannot have their login disallowed.");
|
return Err!("Admin users cannot have their login disallowed.");
|
||||||
}
|
}
|
||||||
@@ -1152,26 +1008,18 @@ pub(super) async fn disable_login(&self, user_id: String) -> Result {
|
|||||||
"{user_id} can no longer log in. Their existing sessions remain unaffected."
|
"{user_id} can no longer log in. Their existing sessions remain unaffected."
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn enable_login(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
|
||||||
assert!(
|
|
||||||
self.services.globals.user_is_local(&user_id),
|
|
||||||
"Parsed user_id must be a local user"
|
|
||||||
);
|
|
||||||
if !self.services.users.exists(&user_id).await {
|
|
||||||
return Err!("User {user_id} does not exist.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) async fn enable_login(&self, user_id: String) -> Result {
|
||||||
|
self.bail_restricted()?;
|
||||||
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
self.services.users.enable_login(&user_id);
|
self.services.users.enable_login(&user_id);
|
||||||
|
|
||||||
self.write_str(&format!("{user_id} can now log in.")).await
|
self.write_str(&format!("{user_id} can now log in.")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_email(&self, user_id: String) -> Result {
|
||||||
pub(super) async fn get_email(&self, user_id: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
|
|
||||||
@@ -1188,10 +1036,9 @@ pub(super) async fn get_email(&self, user_id: String) -> Result {
|
|||||||
self.write_str(&format!("{user_id} has no associated email address."))
|
self.write_str(&format!("{user_id} has no associated email address."))
|
||||||
.await,
|
.await,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn get_user_by_email(&self, email: String) -> Result {
|
||||||
pub(super) async fn get_user_by_email(&self, email: String) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
let Ok(email) = Address::try_from(email) else {
|
let Ok(email) = Address::try_from(email) else {
|
||||||
@@ -1200,8 +1047,10 @@ pub(super) async fn get_user_by_email(&self, email: String) -> Result {
|
|||||||
|
|
||||||
match self.services.threepid.get_localpart_for_email(&email).await {
|
match self.services.threepid.get_localpart_for_email(&email).await {
|
||||||
| Some(localpart) => {
|
| Some(localpart) => {
|
||||||
let user_id =
|
let user_id = UserId::parse(format!(
|
||||||
UserId::parse(format!("@{localpart}:{}", self.services.globals.server_name()))
|
"@{localpart}:{}",
|
||||||
|
self.services.globals.server_name()
|
||||||
|
))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
self.write_str(&format!("{email} belongs to {user_id}."))
|
self.write_str(&format!("{email} belongs to {user_id}."))
|
||||||
@@ -1211,10 +1060,9 @@ pub(super) async fn get_user_by_email(&self, email: String) -> Result {
|
|||||||
self.write_str(&format!("No user has {email} as their email address."))
|
self.write_str(&format!("No user has {email} as their email address."))
|
||||||
.await,
|
.await,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[admin_command]
|
pub(super) async fn change_email(&self, user_id: String, email: Option<String>) -> Result {
|
||||||
pub(super) async fn change_email(&self, user_id: String, email: Option<String>) -> Result {
|
|
||||||
self.bail_restricted()?;
|
self.bail_restricted()?;
|
||||||
|
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||||
@@ -1246,8 +1094,8 @@ pub(super) async fn change_email(&self, user_id: String, email: Option<String>)
|
|||||||
|
|
||||||
if let Some(current_email) = current_email {
|
if let Some(current_email) = current_email {
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"The associated email of {user_id} has been changed from {current_email} to \
|
"The associated email of {user_id} has been changed from \
|
||||||
{new_email}."
|
{current_email} to {new_email}."
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
} else {
|
} else {
|
||||||
@@ -1264,20 +1112,19 @@ pub(super) async fn change_email(&self, user_id: String, email: Option<String>)
|
|||||||
.await;
|
.await;
|
||||||
|
|
||||||
self.write_str(&format!(
|
self.write_str(&format!(
|
||||||
"The associated email of {user_id} has been removed (it was {current_email})."
|
"The associated email of {user_id} has been removed (it was \
|
||||||
|
{current_email})."
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[admin_command]
|
|
||||||
pub(super) async fn reset_push_rules(&self, user_id: String) -> Result {
|
|
||||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
|
||||||
if !self.services.users.is_active(&user_id).await {
|
|
||||||
return Err!("User is not active.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) async fn reset_push_rules(&self, user_id: String) -> Result {
|
||||||
|
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
|
||||||
|
|
||||||
recreate_push_rules_and_return(self.services, &user_id).await?;
|
recreate_push_rules_and_return(self.services, &user_id).await?;
|
||||||
self.write_str("Reset user's push rules to the server default.")
|
self.write_str("Reset user's push rules to the server default.")
|
||||||
.await
|
.await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -27,12 +27,9 @@ pub enum UserCommand {
|
|||||||
username: String,
|
username: String,
|
||||||
/// New password for the user, if unspecified one is generated
|
/// New password for the user, if unspecified one is generated
|
||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
},
|
|
||||||
|
|
||||||
/// Issue a self-service password reset link for a user.
|
#[arg(long)]
|
||||||
IssuePasswordResetLink {
|
convert_to_local_account: bool,
|
||||||
/// 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.
|
||||||
|
|||||||
+1
-8
@@ -54,14 +54,7 @@ pub(crate) async fn parse_active_local_user_id(
|
|||||||
user_id: &str,
|
user_id: &str,
|
||||||
) -> Result<OwnedUserId> {
|
) -> Result<OwnedUserId> {
|
||||||
let user_id = parse_local_user_id(services, user_id)?;
|
let user_id = parse_local_user_id(services, user_id)?;
|
||||||
|
services.users.status(&user_id).await.ensure_active()?;
|
||||||
if !services.users.exists(&user_id).await {
|
|
||||||
return Err!("User {user_id:?} does not exist on this server.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if services.users.is_deactivated(&user_id).await? {
|
|
||||||
return Err!("User {user_id:?} is deactivated.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(user_id)
|
Ok(user_id)
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ use ruma::{
|
|||||||
power_levels::RoomPowerLevelsEventContent,
|
power_levels::RoomPowerLevelsEventContent,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use service::{mailer::messages, uiaa::Identity, users::HashedPassword};
|
use service::{mailer::messages, uiaa::UiaaInitiator, users::HashedPassword};
|
||||||
|
|
||||||
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
||||||
use crate::{Ruma, router::ClientIdentity};
|
use crate::{Ruma, router::ClientIdentity};
|
||||||
@@ -49,39 +49,16 @@ pub(crate) async fn get_register_available_route(
|
|||||||
ClientIp(client): ClientIp,
|
ClientIp(client): ClientIp,
|
||||||
body: Ruma<get_username_availability::v3::Request>,
|
body: Ruma<get_username_availability::v3::Request>,
|
||||||
) -> Result<get_username_availability::v3::Response> {
|
) -> Result<get_username_availability::v3::Response> {
|
||||||
// Validate user id
|
let _ = services
|
||||||
let user_id =
|
.users
|
||||||
match UserId::parse_with_server_name(&body.username, services.globals.server_name()) {
|
.determine_registration_user_id(
|
||||||
| Ok(user_id) => {
|
Some(body.username.clone()),
|
||||||
if let Err(e) = user_id.validate_strict() {
|
None,
|
||||||
return Err!(Request(InvalidUsername(debug_warn!(
|
body.identity
|
||||||
"Username {} contains disallowed characters or spaces: {e}",
|
.as_ref()
|
||||||
body.username
|
.and_then(ClientIdentity::appservice_info),
|
||||||
))));
|
)
|
||||||
}
|
.await?;
|
||||||
|
|
||||||
user_id
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
return Err!(Request(InvalidUsername(debug_warn!(
|
|
||||||
"Username {} is not valid: {e}",
|
|
||||||
body.username
|
|
||||||
))));
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check if username is creative enough
|
|
||||||
if services.users.exists(&user_id).await {
|
|
||||||
return Err!(Request(UserInUse("User ID is not available.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(ClientIdentity::Appservice { appservice_info, .. }) = &body.identity
|
|
||||||
&& !appservice_info.is_user_match(&user_id)
|
|
||||||
{
|
|
||||||
return Err!(Request(Exclusive("Username is not in an appservice namespace.")));
|
|
||||||
} else if services.appservice.is_exclusive_user_id(&user_id).await {
|
|
||||||
return Err!(Request(Exclusive("Username is reserved by an appservice.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(get_username_availability::v3::Response::new(true))
|
Ok(get_username_availability::v3::Response::new(true))
|
||||||
}
|
}
|
||||||
@@ -109,12 +86,7 @@ pub(crate) async fn change_password_route(
|
|||||||
ClientIp(client): ClientIp,
|
ClientIp(client): ClientIp,
|
||||||
body: Ruma<change_password::v3::Request>,
|
body: Ruma<change_password::v3::Request>,
|
||||||
) -> Result<change_password::v3::Response> {
|
) -> Result<change_password::v3::Response> {
|
||||||
let identity = if let Some(user_id) = body
|
let identity = if let Some(identity) = body.identity.as_ref() {
|
||||||
.identity
|
|
||||||
.as_ref()
|
|
||||||
.map(ClientIdentity::expect_sender_user)
|
|
||||||
.transpose()?
|
|
||||||
{
|
|
||||||
// A signed-in user is trying to change their password, prompt them for their
|
// A signed-in user is trying to change their password, prompt them for their
|
||||||
// existing one
|
// existing one
|
||||||
|
|
||||||
@@ -124,7 +96,10 @@ pub(crate) async fn change_password_route(
|
|||||||
&body.auth,
|
&body.auth,
|
||||||
vec![AuthFlow::new(vec![AuthType::Password])],
|
vec![AuthFlow::new(vec![AuthType::Password])],
|
||||||
Box::default(),
|
Box::default(),
|
||||||
Some(Identity::from_user_id(user_id)),
|
Some(UiaaInitiator::new(
|
||||||
|
identity.expect_sender_user()?,
|
||||||
|
identity.sender_device(),
|
||||||
|
)),
|
||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
@@ -153,7 +128,8 @@ pub(crate) async fn change_password_route(
|
|||||||
|
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.set_password(&sender_user, Some(HashedPassword::new(&body.new_password)?));
|
.set_password(&sender_user, HashedPassword::new(&body.new_password)?)
|
||||||
|
.await?;
|
||||||
|
|
||||||
if body.logout_devices {
|
if body.logout_devices {
|
||||||
// Logout all devices except the current one
|
// Logout all devices except the current one
|
||||||
@@ -280,16 +256,24 @@ pub(crate) async fn deactivate_route(
|
|||||||
) -> Result<deactivate::v3::Response> {
|
) -> Result<deactivate::v3::Response> {
|
||||||
// Authentication for this endpoint is technically optional,
|
// Authentication for this endpoint is technically optional,
|
||||||
// but we require the user to be logged in
|
// but we require the user to be logged in
|
||||||
let sender_user = body
|
let identity = body
|
||||||
.identity
|
.identity
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(ClientIdentity::expect_sender_user)
|
.ok_or_else(|| err!(Request(MissingToken("Missing access token."))))?;
|
||||||
.ok_or_else(|| err!(Request(MissingToken("Missing access token."))))??;
|
|
||||||
|
let sender_user = identity.expect_sender_user()?;
|
||||||
|
|
||||||
|
if !services.config.allow_deactivation {
|
||||||
|
return Err!(Request(Forbidden(
|
||||||
|
"You may not deactivate your own account. Contact your server's administrator for \
|
||||||
|
assistance."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
// Prompt the user to confirm with their password using UIAA
|
// Prompt the user to confirm with their password using UIAA
|
||||||
let _ = services
|
let _ = services
|
||||||
.uiaa
|
.uiaa
|
||||||
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
|
.authenticate_password(&body.auth, sender_user, identity.sender_device(), None)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Remove profile pictures and display name
|
// Remove profile pictures and display name
|
||||||
|
|||||||
@@ -1,17 +1,15 @@
|
|||||||
use std::{collections::HashMap, fmt::Write};
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use axum_client_ip::ClientIp;
|
use axum_client_ip::ClientIp;
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Err, Result, debug_info, error, info,
|
Err, Result, debug_info, info,
|
||||||
utils::{self},
|
utils::{self},
|
||||||
warn,
|
|
||||||
};
|
};
|
||||||
use conduwuit_service::Services;
|
use conduwuit_service::Services;
|
||||||
use futures::{FutureExt, StreamExt};
|
use futures::StreamExt;
|
||||||
use lettre::{Address, message::Mailbox};
|
use lettre::{Address, message::Mailbox};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedUserId, UserId,
|
|
||||||
api::client::{
|
api::client::{
|
||||||
account::{
|
account::{
|
||||||
register::{self, LoginType, RegistrationKind},
|
register::{self, LoginType, RegistrationKind},
|
||||||
@@ -20,11 +18,6 @@ use ruma::{
|
|||||||
uiaa::{AuthFlow, AuthType},
|
uiaa::{AuthFlow, AuthType},
|
||||||
},
|
},
|
||||||
assign,
|
assign,
|
||||||
events::{
|
|
||||||
GlobalAccountDataEventType, push_rules::PushRulesEvent,
|
|
||||||
room::message::RoomMessageEventContent,
|
|
||||||
},
|
|
||||||
push,
|
|
||||||
};
|
};
|
||||||
use serde_json::value::RawValue;
|
use serde_json::value::RawValue;
|
||||||
use service::{mailer::messages, users::HashedPassword};
|
use service::{mailer::messages, users::HashedPassword};
|
||||||
@@ -32,8 +25,6 @@ use service::{mailer::messages, users::HashedPassword};
|
|||||||
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
|
|
||||||
const RANDOM_USER_ID_LENGTH: usize = 10;
|
|
||||||
|
|
||||||
/// # `POST /_matrix/client/v3/register`
|
/// # `POST /_matrix/client/v3/register`
|
||||||
///
|
///
|
||||||
/// Register an account on this homeserver.
|
/// Register an account on this homeserver.
|
||||||
@@ -52,8 +43,6 @@ pub(crate) async fn register_route(
|
|||||||
return Err!(Request(GuestAccessForbidden("Guests may not register on this server.")));
|
return Err!(Request(GuestAccessForbidden("Guests may not register on this server.")));
|
||||||
}
|
}
|
||||||
|
|
||||||
let emergency_mode_enabled = services.config.emergency_password.is_some();
|
|
||||||
|
|
||||||
// Allow registration if it's enabled in the config file or if this is the first
|
// Allow registration if it's enabled in the config file or if this is the first
|
||||||
// run (so the first user account can be created)
|
// run (so the first user account can be created)
|
||||||
let allow_registration =
|
let allow_registration =
|
||||||
@@ -71,99 +60,59 @@ pub(crate) async fn register_route(
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let identity = if body.identity.is_some() {
|
let user_id = if body.body.login_type == Some(LoginType::ApplicationService) {
|
||||||
// Appservices can skip auth
|
let Some(appservice_info) = &body.identity else {
|
||||||
None
|
return Err!(Request(Forbidden(
|
||||||
|
"Only appservices can use the appservice login type."
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
|
||||||
|
let user_id = services
|
||||||
|
.users
|
||||||
|
.determine_registration_user_id(body.username.clone(), None, Some(appservice_info))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
services.users.create_shadow_account(&user_id).await?;
|
||||||
|
|
||||||
|
user_id
|
||||||
} else {
|
} else {
|
||||||
// Perform UIAA to determine the user's identity
|
// Perform UIAA to determine the user's identity
|
||||||
let (flows, params) = create_registration_uiaa_session(&services).await?;
|
let (flows, params) = create_registration_uiaa_session(&services).await?;
|
||||||
|
|
||||||
Some(
|
let identity = services
|
||||||
services
|
|
||||||
.uiaa
|
.uiaa
|
||||||
.authenticate(&body.auth, flows, params, None)
|
.authenticate(&body.auth, flows, params, None)
|
||||||
.await?,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
// If the user didn't supply a username but did supply an email, use
|
|
||||||
// the email's user as their initial localpart to avoid falling back to
|
|
||||||
// a randomly generated localpart
|
|
||||||
let supplied_username = body.username.clone().or_else(|| {
|
|
||||||
if let Some(identity) = &identity
|
|
||||||
&& let Some(email) = &identity.email
|
|
||||||
{
|
|
||||||
Some(email.user().to_owned())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let user_id =
|
|
||||||
determine_registration_user_id(&services, supplied_username, emergency_mode_enabled)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if body.body.login_type == Some(LoginType::ApplicationService) {
|
let password = if let Some(password) = &body.password {
|
||||||
// For appservice logins, make sure that the user ID is in the appservice's
|
HashedPassword::new(password)?
|
||||||
// namespace
|
|
||||||
|
|
||||||
match body.identity {
|
|
||||||
| Some(ref info) =>
|
|
||||||
if !info.is_user_match(&user_id) && !emergency_mode_enabled {
|
|
||||||
return Err!(Request(Exclusive(
|
|
||||||
"Username is not in an appservice namespace."
|
|
||||||
)));
|
|
||||||
},
|
|
||||||
| _ => {
|
|
||||||
return Err!(Request(MissingToken("Missing appservice token.")));
|
|
||||||
},
|
|
||||||
}
|
|
||||||
} else if services.appservice.is_exclusive_user_id(&user_id).await && !emergency_mode_enabled
|
|
||||||
{
|
|
||||||
// For non-appservice logins, ban user IDs which are in an appservice's
|
|
||||||
// namespace (unless emergency mode is enabled)
|
|
||||||
return Err!(Request(Exclusive("Username is reserved by an appservice.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
let password = if body.identity.is_some() {
|
|
||||||
None
|
|
||||||
} else if let Some(password) = body.password.as_deref() {
|
|
||||||
Some(HashedPassword::new(password)?)
|
|
||||||
} else {
|
} else {
|
||||||
return Err!(Request(InvalidParam("A password must be provided")));
|
return Err!(Request(InvalidParam("A password must be provided.")));
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create user
|
let user_id = services
|
||||||
services.users.create(&user_id, password).await?;
|
.users
|
||||||
|
.determine_registration_user_id(body.username.clone(), identity.email.as_ref(), None)
|
||||||
// Set an initial display name
|
.await?;
|
||||||
let mut displayname = user_id.localpart().to_owned();
|
|
||||||
|
|
||||||
// Apply the new user displayname suffix, if it's set
|
|
||||||
if !services.globals.new_user_displayname_suffix().is_empty() && body.identity.is_none() {
|
|
||||||
write!(displayname, " {}", services.server.config.new_user_displayname_suffix)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.set_displayname(&user_id, Some(displayname.clone()));
|
.create_local_account(&user_id, Some(password), identity.email)
|
||||||
|
|
||||||
// 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?;
|
.await?;
|
||||||
|
|
||||||
// Generate new device id if the user didn't specify one
|
user_id
|
||||||
|
};
|
||||||
|
|
||||||
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()
|
||||||
@@ -179,6 +128,7 @@ pub(crate) async fn register_route(
|
|||||||
&user_id,
|
&user_id,
|
||||||
&device_id,
|
&device_id,
|
||||||
&new_token,
|
&new_token,
|
||||||
|
None,
|
||||||
body.initial_device_display_name.clone(),
|
body.initial_device_display_name.clone(),
|
||||||
Some(client.to_string()),
|
Some(client.to_string()),
|
||||||
)
|
)
|
||||||
@@ -189,118 +139,7 @@ pub(crate) async fn register_route(
|
|||||||
(None, None)
|
(None, None)
|
||||||
};
|
};
|
||||||
|
|
||||||
debug_info!(%user_id, ?device, "User account was created");
|
debug_info!(%user_id, ?device, "New account created via legacy registration");
|
||||||
|
|
||||||
// If the user registered with an email, associate it with their account.
|
|
||||||
if let Some(identity) = identity
|
|
||||||
&& let Some(email) = identity.email
|
|
||||||
{
|
|
||||||
// This may fail if the email is already in use, but we already check for that
|
|
||||||
// in `/requestToken`, so ignoring the error is acceptable here in the rare case
|
|
||||||
// that an email is sniped by another user between the `/requestToken` request
|
|
||||||
// and the `/register` request.
|
|
||||||
let _ = services
|
|
||||||
.threepid
|
|
||||||
.associate_localpart_email(user_id.localpart(), &email)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
|
|
||||||
let device_display_name = body.initial_device_display_name.as_deref().unwrap_or("");
|
|
||||||
|
|
||||||
if body.identity.is_none() {
|
|
||||||
if !device_display_name.is_empty() {
|
|
||||||
let notice = format!(
|
|
||||||
"New user \"{user_id}\" registered on this server from IP {client} and device \
|
|
||||||
display name \"{device_display_name}\""
|
|
||||||
);
|
|
||||||
|
|
||||||
info!("{notice}");
|
|
||||||
if services.server.config.admin_room_notices {
|
|
||||||
services.admin.notice(¬ice).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(¬ice).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make the first user to register an administrator and disable first-run mode.
|
|
||||||
let was_first_user = services.firstrun.empower_first_user(&user_id).await?;
|
|
||||||
|
|
||||||
// If the registering user was not the first and we're suspending users on
|
|
||||||
// register, suspend them.
|
|
||||||
if !was_first_user && services.config.suspend_on_register {
|
|
||||||
// Note that we can still do auto joins for suspended users
|
|
||||||
services
|
|
||||||
.users
|
|
||||||
.suspend_account(&user_id, &services.globals.server_user)
|
|
||||||
.await;
|
|
||||||
// And send an @room notice to the admin room, to prompt admins to review the
|
|
||||||
// new user and ideally unsuspend them if deemed appropriate.
|
|
||||||
if services.server.config.admin_room_notices {
|
|
||||||
services
|
|
||||||
.admin
|
|
||||||
.send_loud_message(RoomMessageEventContent::text_plain(format!(
|
|
||||||
"User {user_id} has been suspended as they are not the first user on this \
|
|
||||||
server. Please review and unsuspend them if appropriate."
|
|
||||||
)))
|
|
||||||
.await
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if body.identity.is_none() && !services.server.config.auto_join_rooms.is_empty() {
|
|
||||||
for room in &services.server.config.auto_join_rooms {
|
|
||||||
let Ok(room_id) = services.rooms.alias.resolve(room).await else {
|
|
||||||
error!(
|
|
||||||
"Failed to resolve room alias to room ID when attempting to auto join \
|
|
||||||
{room}, skipping"
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
if !services
|
|
||||||
.rooms
|
|
||||||
.state_cache
|
|
||||||
.server_in_room(services.globals.server_name(), &room_id)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
warn!(
|
|
||||||
"Skipping room {room} to automatically join as we have never joined before."
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(room_server_name) = room.server_name() {
|
|
||||||
match services
|
|
||||||
.rooms
|
|
||||||
.membership
|
|
||||||
.join_room(
|
|
||||||
&user_id,
|
|
||||||
&room_id,
|
|
||||||
Some("Automatically joining this room upon registration".to_owned()),
|
|
||||||
&[services.globals.server_name().to_owned(), room_server_name.to_owned()],
|
|
||||||
)
|
|
||||||
.boxed()
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
| Err(e) => {
|
|
||||||
// don't return this error so we don't fail registrations
|
|
||||||
error!(
|
|
||||||
"Failed to automatically join room {room} for user {user_id}: {e}"
|
|
||||||
);
|
|
||||||
},
|
|
||||||
| _ => {
|
|
||||||
info!("Automatically joined room {room} for user {user_id}");
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(assign!(register::v3::Response::new(user_id), {
|
Ok(assign!(register::v3::Response::new(user_id), {
|
||||||
access_token: token,
|
access_token: token,
|
||||||
@@ -372,21 +211,21 @@ async fn create_registration_uiaa_session(
|
|||||||
|
|
||||||
// Require all users to agree to the terms and conditions, if configured
|
// Require all users to agree to the terms and conditions, if configured
|
||||||
let terms = &services.config.registration_terms;
|
let terms = &services.config.registration_terms;
|
||||||
if !terms.is_empty() {
|
if !terms.documents.is_empty() {
|
||||||
let mut terms =
|
let mut terms_map = HashMap::new();
|
||||||
serde_json::to_value(terms.clone()).expect("failed to serialize terms");
|
|
||||||
|
|
||||||
// Insert a dummy `version` field
|
for (id, document) in &terms.documents {
|
||||||
for (_, documents) in terms.as_object_mut().unwrap() {
|
terms_map.insert(id.to_owned(), serde_json::json!({
|
||||||
let documents = documents.as_object_mut().unwrap();
|
terms.language.clone(): serde_json::to_value(document).expect("should be able to serialize document")
|
||||||
|
}));
|
||||||
documents.insert("version".to_owned(), "latest".into());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
terms_map.insert("version".to_owned(), "latest".into());
|
||||||
|
|
||||||
params.insert(
|
params.insert(
|
||||||
AuthType::Terms.as_str().to_owned(),
|
AuthType::Terms.as_str().to_owned(),
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"policies": terms,
|
"policies": terms_map,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -419,81 +258,6 @@ async fn create_registration_uiaa_session(
|
|||||||
Ok((flows, params))
|
Ok((flows, params))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn determine_registration_user_id(
|
|
||||||
services: &Services,
|
|
||||||
supplied_username: Option<String>,
|
|
||||||
emergency_mode_enabled: bool,
|
|
||||||
) -> Result<OwnedUserId> {
|
|
||||||
if let Some(supplied_username) = supplied_username {
|
|
||||||
// The user gets to pick their username. Do some validation to make sure it's
|
|
||||||
// acceptable.
|
|
||||||
|
|
||||||
// Don't allow registration with forbidden usernames.
|
|
||||||
if services
|
|
||||||
.globals
|
|
||||||
.forbidden_usernames()
|
|
||||||
.is_match(&supplied_username)
|
|
||||||
&& !emergency_mode_enabled
|
|
||||||
{
|
|
||||||
return Err!(Request(Forbidden("Username is forbidden")));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create and validate the user ID
|
|
||||||
let user_id = match UserId::parse_with_server_name(
|
|
||||||
&supplied_username,
|
|
||||||
services.globals.server_name(),
|
|
||||||
) {
|
|
||||||
| Ok(user_id) => {
|
|
||||||
if let Err(e) = user_id.validate_strict() {
|
|
||||||
// Unless we are in emergency mode, we should follow synapse's behaviour on
|
|
||||||
// not allowing things like spaces and UTF-8 characters in usernames
|
|
||||||
if !emergency_mode_enabled {
|
|
||||||
return Err!(Request(InvalidUsername(debug_warn!(
|
|
||||||
"Username {supplied_username} contains disallowed characters or \
|
|
||||||
spaces: {e}"
|
|
||||||
))));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't allow registration with user IDs that aren't local
|
|
||||||
if !services.globals.user_is_local(&user_id) {
|
|
||||||
return Err!(Request(InvalidUsername(
|
|
||||||
"Username {supplied_username} is not local to this server"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
user_id
|
|
||||||
},
|
|
||||||
| Err(e) => {
|
|
||||||
return Err!(Request(InvalidUsername(debug_warn!(
|
|
||||||
"Username {supplied_username} is not valid: {e}"
|
|
||||||
))));
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
if services.users.exists(&user_id).await {
|
|
||||||
return Err!(Request(UserInUse("User ID is not available.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(user_id)
|
|
||||||
} else {
|
|
||||||
// The user didn't specify a username. Generate a username for
|
|
||||||
// them.
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let user_id = UserId::parse_with_server_name(
|
|
||||||
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
|
|
||||||
services.globals.server_name(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
if !services.users.exists(&user_id).await {
|
|
||||||
break Ok(user_id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # `POST /_matrix/client/v3/register/email/requestToken`
|
/// # `POST /_matrix/client/v3/register/email/requestToken`
|
||||||
///
|
///
|
||||||
/// Requests a validation email for the purpose of registering a new account.
|
/// Requests a validation email for the purpose of registering a new account.
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use ruma::{
|
|||||||
},
|
},
|
||||||
thirdparty::{Medium, ThirdPartyIdentifierInit},
|
thirdparty::{Medium, ThirdPartyIdentifierInit},
|
||||||
};
|
};
|
||||||
use service::{mailer::messages, uiaa::Identity};
|
use service::mailer::messages;
|
||||||
|
|
||||||
use crate::{Ruma, router::ClientIdentity};
|
use crate::{Ruma, router::ClientIdentity};
|
||||||
|
|
||||||
@@ -25,6 +25,10 @@ pub(crate) async fn third_party_route(
|
|||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
let mut threepids = vec![];
|
let mut threepids = vec![];
|
||||||
|
|
||||||
|
if !services.threepid.email_requirement().may_view() {
|
||||||
|
return Ok(get_3pids::v3::Response::new(vec![]));
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(email) = services
|
if let Some(email) = services
|
||||||
.threepid
|
.threepid
|
||||||
.get_email_for_localpart(sender_user.localpart())
|
.get_email_for_localpart(sender_user.localpart())
|
||||||
@@ -124,15 +128,18 @@ pub(crate) async fn add_3pid_route(
|
|||||||
.uiaa
|
.uiaa
|
||||||
.authenticate_password(
|
.authenticate_password(
|
||||||
&body.auth,
|
&body.auth,
|
||||||
Some(Identity::from_user_id(body.identity.expect_sender_user()?)),
|
body.identity.expect_sender_user()?,
|
||||||
|
body.identity.sender_device(),
|
||||||
|
None,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let email = services
|
let email = services
|
||||||
.threepid
|
.threepid
|
||||||
.consume_valid_session(&body.sid, &body.client_secret)
|
.get_valid_session(&body.sid, &body.client_secret)
|
||||||
.await
|
.await
|
||||||
.map_err(|message| err!(Request(ThreepidAuthFailed("{message}"))))?;
|
.map_err(|message| err!(Request(ThreepidAuthFailed("{message}"))))?
|
||||||
|
.consume();
|
||||||
|
|
||||||
services
|
services
|
||||||
.threepid
|
.threepid
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
use axum::extract::State;
|
||||||
|
use conduwuit::{Err, Result};
|
||||||
|
use futures::future::{join, join3};
|
||||||
|
use ruma::api::client::admin::{is_user_locked, lock_user};
|
||||||
|
|
||||||
|
use crate::Ruma;
|
||||||
|
|
||||||
|
/// # `GET /_matrix/client/v1/admin/lock/{userId}`
|
||||||
|
///
|
||||||
|
/// Check the account lock status of a target user
|
||||||
|
pub(crate) async fn get_lock_status(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
body: Ruma<is_user_locked::v1::Request>,
|
||||||
|
) -> Result<is_user_locked::v1::Response> {
|
||||||
|
let (admin, status) = join(
|
||||||
|
services.users.is_admin(body.identity.expect_sender_user()?),
|
||||||
|
services.users.status(&body.user_id),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if !admin {
|
||||||
|
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
||||||
|
}
|
||||||
|
|
||||||
|
status.ensure_active()?;
|
||||||
|
|
||||||
|
Ok(is_user_locked::v1::Response::new(
|
||||||
|
services.users.is_locked(&body.user_id).await?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # `PUT /_matrix/client/v1/admin/lock/{userId}`
|
||||||
|
///
|
||||||
|
/// Set the account lock status of a target user
|
||||||
|
pub(crate) async fn put_lock_status(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
body: Ruma<lock_user::v1::Request>,
|
||||||
|
) -> Result<lock_user::v1::Response> {
|
||||||
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
|
|
||||||
|
let (sender_admin, status, target_admin) = join3(
|
||||||
|
services.users.is_admin(sender_user),
|
||||||
|
services.users.status(&body.user_id),
|
||||||
|
services.users.is_admin(&body.user_id),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if !sender_admin {
|
||||||
|
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
||||||
|
}
|
||||||
|
|
||||||
|
status.ensure_active()?;
|
||||||
|
|
||||||
|
if body.user_id == *sender_user {
|
||||||
|
return Err!(Request(Forbidden("You cannot lock yourself")));
|
||||||
|
}
|
||||||
|
|
||||||
|
if target_admin {
|
||||||
|
return Err!(Request(Forbidden("You cannot lock another server administrator")));
|
||||||
|
}
|
||||||
|
|
||||||
|
if services.users.is_locked(&body.user_id).await? == body.locked {
|
||||||
|
// No change
|
||||||
|
return Ok(lock_user::v1::Response::new(body.locked));
|
||||||
|
}
|
||||||
|
|
||||||
|
let action = if body.locked {
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.suspend_account(&body.user_id, sender_user)
|
||||||
|
.await;
|
||||||
|
"locked"
|
||||||
|
} else {
|
||||||
|
services.users.unsuspend_account(&body.user_id).await;
|
||||||
|
"unlocked"
|
||||||
|
};
|
||||||
|
|
||||||
|
if services.config.admin_room_notices {
|
||||||
|
// Notify the admin room that an account has been un/suspended
|
||||||
|
services
|
||||||
|
.admin
|
||||||
|
.send_text(&format!("{} has been {} by {}.", body.user_id, action, sender_user))
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(lock_user::v1::Response::new(body.locked))
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
mod lock;
|
||||||
mod suspend;
|
mod suspend;
|
||||||
|
|
||||||
pub(crate) use self::suspend::*;
|
pub(crate) use self::{lock::*, suspend::*};
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use conduwuit::{Err, Result};
|
use conduwuit::{Err, Result};
|
||||||
use futures::future::{join, join3};
|
use futures::future::{join, join3};
|
||||||
use ruminuwuity::admin::{get_suspended, set_suspended};
|
use ruma::api::client::admin::{is_user_suspended, suspend_user};
|
||||||
|
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
|
|
||||||
@@ -10,23 +10,21 @@ use crate::Ruma;
|
|||||||
/// Check the suspension status of a target user
|
/// Check the suspension status of a target user
|
||||||
pub(crate) async fn get_suspended_status(
|
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<is_user_suspended::v1::Request>,
|
||||||
) -> Result<get_suspended::v1::Response> {
|
) -> Result<is_user_suspended::v1::Response> {
|
||||||
let (admin, active) = join(
|
let (admin, status) = join(
|
||||||
services.users.is_admin(body.identity.expect_sender_user()?),
|
services.users.is_admin(body.identity.expect_sender_user()?),
|
||||||
services.users.is_active(&body.user_id),
|
services.users.status(&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")));
|
||||||
}
|
}
|
||||||
if !services.globals.user_is_local(&body.user_id) {
|
|
||||||
return Err!(Request(InvalidParam("Can only check the suspended status of local users")));
|
status.ensure_active()?;
|
||||||
}
|
|
||||||
if !active {
|
Ok(is_user_suspended::v1::Response::new(
|
||||||
return Err!(Request(NotFound("Unknown user")));
|
|
||||||
}
|
|
||||||
Ok(get_suspended::v1::Response::new(
|
|
||||||
services.users.is_suspended(&body.user_id).await?,
|
services.users.is_suspended(&body.user_id).await?,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@@ -36,13 +34,13 @@ pub(crate) async fn get_suspended_status(
|
|||||||
/// Set the suspension status of a target user
|
/// Set the suspension status of a target user
|
||||||
pub(crate) async fn put_suspended_status(
|
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<suspend_user::v1::Request>,
|
||||||
) -> Result<set_suspended::v1::Response> {
|
) -> Result<suspend_user::v1::Response> {
|
||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
|
|
||||||
let (sender_admin, active, target_admin) = join3(
|
let (sender_admin, status, target_admin) = join3(
|
||||||
services.users.is_admin(sender_user),
|
services.users.is_admin(sender_user),
|
||||||
services.users.is_active(&body.user_id),
|
services.users.status(&body.user_id),
|
||||||
services.users.is_admin(&body.user_id),
|
services.users.is_admin(&body.user_id),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -50,21 +48,20 @@ pub(crate) async fn put_suspended_status(
|
|||||||
if !sender_admin {
|
if !sender_admin {
|
||||||
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
|
||||||
}
|
}
|
||||||
if !services.globals.user_is_local(&body.user_id) {
|
|
||||||
return Err!(Request(InvalidParam("Can only set the suspended status of local users")));
|
status.ensure_active()?;
|
||||||
}
|
|
||||||
if !active {
|
|
||||||
return Err!(Request(NotFound("Unknown user")));
|
|
||||||
}
|
|
||||||
if body.user_id == *sender_user {
|
if body.user_id == *sender_user {
|
||||||
return Err!(Request(Forbidden("You cannot suspend yourself")));
|
return Err!(Request(Forbidden("You cannot suspend yourself")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if target_admin {
|
if target_admin {
|
||||||
return Err!(Request(Forbidden("You cannot suspend another server administrator")));
|
return Err!(Request(Forbidden("You cannot suspend another server administrator")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if services.users.is_suspended(&body.user_id).await? == body.suspended {
|
if services.users.is_suspended(&body.user_id).await? == body.suspended {
|
||||||
// No change
|
// No change
|
||||||
return Ok(set_suspended::v1::Response::new(body.suspended));
|
return Ok(suspend_user::v1::Response::new(body.suspended));
|
||||||
}
|
}
|
||||||
|
|
||||||
let action = if body.suspended {
|
let action = if body.suspended {
|
||||||
@@ -86,5 +83,5 @@ pub(crate) async fn put_suspended_status(
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(set_suspended::v1::Response::new(body.suspended))
|
Ok(suspend_user::v1::Response::new(body.suspended))
|
||||||
}
|
}
|
||||||
@@ -7,12 +7,12 @@ use ruma::{
|
|||||||
api::client::discovery::get_capabilities::{
|
api::client::discovery::get_capabilities::{
|
||||||
self,
|
self,
|
||||||
v3::{
|
v3::{
|
||||||
Capabilities, GetLoginTokenCapability, RoomVersionStability, RoomVersionsCapability,
|
Capabilities, GetLoginTokenCapability, ProfileFieldsCapability, RoomVersionStability,
|
||||||
ThirdPartyIdChangesCapability,
|
RoomVersionsCapability, ThirdPartyIdChangesCapability,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
assign,
|
||||||
};
|
};
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
|
|
||||||
@@ -40,22 +40,20 @@ pub(crate) async fn get_capabilities_route(
|
|||||||
capabilities.get_login_token =
|
capabilities.get_login_token =
|
||||||
GetLoginTokenCapability::new(services.server.config.login_via_existing_session);
|
GetLoginTokenCapability::new(services.server.config.login_via_existing_session);
|
||||||
|
|
||||||
// MSC4133 capability
|
capabilities.forget_forced_upon_leave.enabled = true;
|
||||||
capabilities.set("uk.tcpip.msc4133.profile_fields", json!({"enabled": true}))?;
|
|
||||||
|
|
||||||
capabilities.set(
|
|
||||||
"org.matrix.msc4267.forget_forced_upon_leave",
|
|
||||||
json!({"enabled": services.config.forget_forced_upon_leave}),
|
|
||||||
)?;
|
|
||||||
|
|
||||||
if services
|
if services
|
||||||
.users
|
.users
|
||||||
.is_admin(body.identity.expect_sender_user()?)
|
.is_admin(body.identity.expect_sender_user()?)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
// Advertise suspension API
|
capabilities.account_moderation.lock = true;
|
||||||
capabilities.set("uk.timedout.msc4323", json!({"suspend": true, "lock": false}))?;
|
capabilities.account_moderation.suspend = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
capabilities.profile_fields = Some(
|
||||||
|
assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }),
|
||||||
|
);
|
||||||
|
|
||||||
Ok(get_capabilities::v3::Response::new(capabilities))
|
Ok(get_capabilities::v3::Response::new(capabilities))
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,6 @@ use ruma::{
|
|||||||
self, delete_device, delete_devices, get_device, get_devices, update_device,
|
self, delete_device, delete_devices, get_device, get_devices, update_device,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use service::uiaa::Identity;
|
|
||||||
|
|
||||||
use crate::{Ruma, client::DEVICE_ID_LENGTH};
|
use crate::{Ruma, client::DEVICE_ID_LENGTH};
|
||||||
|
|
||||||
@@ -95,6 +94,7 @@ pub(crate) async fn update_device_route(
|
|||||||
&device_id,
|
&device_id,
|
||||||
&appservice.registration.as_token,
|
&appservice.registration.as_token,
|
||||||
None,
|
None,
|
||||||
|
None,
|
||||||
Some(client.to_string()),
|
Some(client.to_string()),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -119,14 +119,15 @@ pub(crate) async fn delete_device_route(
|
|||||||
body: Ruma<delete_device::v3::Request>,
|
body: Ruma<delete_device::v3::Request>,
|
||||||
) -> Result<delete_device::v3::Response> {
|
) -> Result<delete_device::v3::Response> {
|
||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
let appservice = body.identity.appservice_info();
|
|
||||||
|
|
||||||
// Appservices get to skip UIAA for this endpoint
|
// Appservices get to skip UIAA for this endpoint
|
||||||
if appservice.is_none() {
|
if !body.identity.is_appservice() {
|
||||||
|
let sender_device = body.identity.expect_sender_device()?;
|
||||||
|
|
||||||
// Prompt the user to confirm with their password using UIAA
|
// Prompt the user to confirm with their password using UIAA
|
||||||
let _ = services
|
let _ = services
|
||||||
.uiaa
|
.uiaa
|
||||||
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
|
.authenticate_password(&body.auth, sender_user, Some(sender_device), None)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,14 +156,13 @@ pub(crate) async fn delete_devices_route(
|
|||||||
body: Ruma<delete_devices::v3::Request>,
|
body: Ruma<delete_devices::v3::Request>,
|
||||||
) -> Result<delete_devices::v3::Response> {
|
) -> Result<delete_devices::v3::Response> {
|
||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
let appservice = body.identity.appservice_info();
|
|
||||||
|
|
||||||
// Appservices get to skip UIAA for this endpoint
|
// Appservices get to skip UIAA for this endpoint
|
||||||
if appservice.is_none() {
|
if let Some(sender_device) = body.identity.sender_device() {
|
||||||
// Prompt the user to confirm with their password using UIAA
|
// Prompt the user to confirm with their password using UIAA
|
||||||
let _ = services
|
let _ = services
|
||||||
.uiaa
|
.uiaa
|
||||||
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
|
.authenticate_password(&body.auth, sender_user, Some(sender_device), None)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-2
@@ -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;
|
||||||
|
|
||||||
@@ -197,6 +197,7 @@ pub(crate) async fn upload_signing_keys_route(
|
|||||||
if uiaa_needed_to_upload_keys(
|
if uiaa_needed_to_upload_keys(
|
||||||
services,
|
services,
|
||||||
sender_user,
|
sender_user,
|
||||||
|
body.identity.is_appservice(),
|
||||||
body.self_signing_key.as_ref(),
|
body.self_signing_key.as_ref(),
|
||||||
body.user_signing_key.as_ref(),
|
body.user_signing_key.as_ref(),
|
||||||
body.master_key.as_ref(),
|
body.master_key.as_ref(),
|
||||||
@@ -205,7 +206,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?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,10 +232,16 @@ pub(crate) async fn upload_signing_keys_route(
|
|||||||
async fn uiaa_needed_to_upload_keys(
|
async fn uiaa_needed_to_upload_keys(
|
||||||
services: crate::State,
|
services: crate::State,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
|
is_appservice: bool,
|
||||||
self_signing_key: Option<&Raw<CrossSigningKey>>,
|
self_signing_key: Option<&Raw<CrossSigningKey>>,
|
||||||
user_signing_key: Option<&Raw<CrossSigningKey>>,
|
user_signing_key: Option<&Raw<CrossSigningKey>>,
|
||||||
master_signing_key: Option<&Raw<CrossSigningKey>>,
|
master_signing_key: Option<&Raw<CrossSigningKey>>,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
|
if is_appservice {
|
||||||
|
// Appservices can skip UIAA for this endpoint
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
let (self_signing_key, user_signing_key, master_signing_key) = (
|
let (self_signing_key, user_signing_key, master_signing_key) = (
|
||||||
self_signing_key.map(Raw::deserialize).flat_ok(),
|
self_signing_key.map(Raw::deserialize).flat_ok(),
|
||||||
user_signing_key.map(Raw::deserialize).flat_ok(),
|
user_signing_key.map(Raw::deserialize).flat_ok(),
|
||||||
|
|||||||
@@ -291,7 +291,9 @@ where
|
|||||||
{
|
{
|
||||||
// exclude Synapse's dummy events from bloating up response bodies. clients
|
// exclude Synapse's dummy events from bloating up response bodies. clients
|
||||||
// don't need to see this.
|
// don't need to see this.
|
||||||
if event.kind().to_string() == "org.matrix.dummy_event" {
|
if !services.config.send_dummy_events_to_clients
|
||||||
|
&& event.kind().to_string() == "org.matrix.dummy_event"
|
||||||
|
{
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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::*;
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
use axum::{
|
||||||
|
Json, Router,
|
||||||
|
extract::{Request, State},
|
||||||
|
middleware::{self, Next},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::method_routing::{get, post},
|
||||||
|
};
|
||||||
|
use const_str::concat;
|
||||||
|
use http::StatusCode;
|
||||||
|
use serde_json::json;
|
||||||
|
pub(crate) use server_metadata::*;
|
||||||
|
|
||||||
|
mod register_client;
|
||||||
|
mod server_metadata;
|
||||||
|
mod token;
|
||||||
|
|
||||||
|
const BASE_PATH: &str = concat!(conduwuit_core::ROUTE_PREFIX, "/oauth2/");
|
||||||
|
const AUTH_CODE_PATH: &str = "grant/authorization_code";
|
||||||
|
const JWKS_URI_PATH: &str = "client/keys.json";
|
||||||
|
const CLIENT_REGISTER_PATH: &str = "client/register";
|
||||||
|
const TOKEN_REVOKE_PATH: &str = "client/revoke";
|
||||||
|
const TOKEN_PATH: &str = "grant/token";
|
||||||
|
const ACCOUNT_MANAGEMENT_PATH: &str = concat!(conduwuit_core::ROUTE_PREFIX, "/account/deeplink");
|
||||||
|
|
||||||
|
pub(crate) fn router(state: crate::State) -> Router<crate::State> {
|
||||||
|
Router::new()
|
||||||
|
.nest(BASE_PATH, oauth_router())
|
||||||
|
.route(
|
||||||
|
"/.well-known/openid-configuration",
|
||||||
|
get(
|
||||||
|
// TODO(unspecced): used by old versions of the matrix-js-sdk
|
||||||
|
async |State(services): State<crate::State>| {
|
||||||
|
Json(authorization_server_metadata(&services).await)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state,
|
||||||
|
async |State(state): State<crate::State>, request: Request, next: Next| -> Response {
|
||||||
|
if state.config.oauth.compatibility_mode().oauth_available() {
|
||||||
|
next.run(request).await
|
||||||
|
} else {
|
||||||
|
(StatusCode::NOT_FOUND, "OAuth is unavailable on this server").into_response()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn oauth_router() -> Router<crate::State> {
|
||||||
|
Router::new()
|
||||||
|
.route(concat!("/", CLIENT_REGISTER_PATH), post(register_client::register_client_route))
|
||||||
|
// TODO(unspecced): used by old versions of the matrix-js-sdk
|
||||||
|
.route(concat!("/", JWKS_URI_PATH), get(async || Json(json!({"keys": []}))))
|
||||||
|
.route(concat!("/", TOKEN_PATH), post(token::token_route))
|
||||||
|
.route(concat!("/", TOKEN_REVOKE_PATH), post(token::revoke_token_route))
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
use axum::{
|
||||||
|
Json,
|
||||||
|
extract::State,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use http::StatusCode;
|
||||||
|
use serde::Serialize;
|
||||||
|
use service::oauth::client_metadata::ClientMetadata;
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct RegisteredClient {
|
||||||
|
client_id: String,
|
||||||
|
#[serde(flatten)]
|
||||||
|
metadata: ClientMetadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn register_client_route(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
Json(metadata): Json<ClientMetadata>,
|
||||||
|
) -> Result<Response, Response> {
|
||||||
|
let client_id = services
|
||||||
|
.oauth
|
||||||
|
.register_client(&metadata)
|
||||||
|
.await
|
||||||
|
.map_err(|err| (StatusCode::BAD_REQUEST, Json(err)).into_response())?;
|
||||||
|
|
||||||
|
Ok(Json(RegisteredClient { client_id, metadata }).into_response())
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
use axum::extract::State;
|
||||||
|
use conduwuit::{Err, Result};
|
||||||
|
use ruma::{
|
||||||
|
api::client::discovery::get_authorization_server_metadata::{
|
||||||
|
self, v1::AccountManagementAction,
|
||||||
|
},
|
||||||
|
serde::Raw,
|
||||||
|
};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use service::Services;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
Ruma,
|
||||||
|
client::oauth::{
|
||||||
|
ACCOUNT_MANAGEMENT_PATH, AUTH_CODE_PATH, CLIENT_REGISTER_PATH, JWKS_URI_PATH, TOKEN_PATH,
|
||||||
|
TOKEN_REVOKE_PATH,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) async fn get_authorization_server_metadata_route(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
_body: Ruma<get_authorization_server_metadata::v1::Request>,
|
||||||
|
) -> Result<get_authorization_server_metadata::v1::Response> {
|
||||||
|
if !services.config.oauth.compatibility_mode().oauth_available() {
|
||||||
|
return Err!(Request(Unrecognized("OAuth is unavailable on this server")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let metadata = Raw::new(&authorization_server_metadata(&services).await).unwrap();
|
||||||
|
|
||||||
|
Ok(get_authorization_server_metadata::v1::Response::new(metadata.cast_unchecked()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn authorization_server_metadata(services: &Services) -> Value {
|
||||||
|
let endpoint_base = services
|
||||||
|
.config
|
||||||
|
.get_client_domain()
|
||||||
|
.join(super::BASE_PATH)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
json!({
|
||||||
|
"account_management_uri": endpoint_base.join(ACCOUNT_MANAGEMENT_PATH).unwrap(),
|
||||||
|
"account_management_actions_supported": [
|
||||||
|
AccountManagementAction::AccountDeactivate,
|
||||||
|
AccountManagementAction::CrossSigningReset,
|
||||||
|
AccountManagementAction::DeviceDelete,
|
||||||
|
AccountManagementAction::DeviceView,
|
||||||
|
AccountManagementAction::DevicesList,
|
||||||
|
AccountManagementAction::Profile,
|
||||||
|
],
|
||||||
|
"authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(),
|
||||||
|
"code_challenge_methods_supported": ["S256"],
|
||||||
|
"grant_types_supported": ["authorization_code", "refresh_token"],
|
||||||
|
"issuer": services.config.get_client_domain(),
|
||||||
|
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
|
||||||
|
"prompt_values_supported": ["create"],
|
||||||
|
"registration_endpoint": endpoint_base.join(CLIENT_REGISTER_PATH).unwrap(),
|
||||||
|
"response_modes_supported": ["query", "fragment"],
|
||||||
|
"response_types_supported": ["code"],
|
||||||
|
"revocation_endpoint": endpoint_base.join(TOKEN_REVOKE_PATH).unwrap(),
|
||||||
|
"token_endpoint": endpoint_base.join(TOKEN_PATH).unwrap(),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
use axum::{Form, Json, extract::State, response::IntoResponse};
|
||||||
|
use http::StatusCode;
|
||||||
|
use service::oauth::grant::{RevokeTokenRequest, TokenRequest};
|
||||||
|
|
||||||
|
pub(crate) async fn token_route(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
Form(request): Form<TokenRequest>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
match services.oauth.issue_token(request).await {
|
||||||
|
| Ok(response) => Ok(Json(response)),
|
||||||
|
| Err(err) => Err((StatusCode::BAD_REQUEST, Json(err))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn revoke_token_route(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
Form(request): Form<RevokeTokenRequest>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
match services.oauth.revoke_token(request.token).await {
|
||||||
|
| Ok(()) => Ok(StatusCode::OK),
|
||||||
|
| Err(err) => Err((StatusCode::BAD_REQUEST, Json(err))),
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
-272
@@ -1,9 +1,8 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use conduwuit::{Err, Result, matrix::pdu::PartialPdu, utils::to_canonical_object};
|
use conduwuit::{Err, Result};
|
||||||
use conduwuit_service::Services;
|
use conduwuit_service::Services;
|
||||||
use futures::StreamExt;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
UserId,
|
UserId,
|
||||||
api::{
|
api::{
|
||||||
@@ -13,11 +12,10 @@ use ruma::{
|
|||||||
federation,
|
federation,
|
||||||
},
|
},
|
||||||
assign,
|
assign,
|
||||||
events::room::member::MembershipState,
|
|
||||||
presence::PresenceState,
|
|
||||||
profile::{ProfileFieldName, ProfileFieldValue},
|
profile::{ProfileFieldName, ProfileFieldValue},
|
||||||
};
|
};
|
||||||
use serde_json::{Value, to_value};
|
use serde_json::Value;
|
||||||
|
use service::users::ProfileFieldChange;
|
||||||
|
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
|
|
||||||
@@ -65,8 +63,19 @@ pub(crate) async fn set_profile_field_route(
|
|||||||
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
||||||
}
|
}
|
||||||
|
|
||||||
set_profile_field(
|
if services
|
||||||
&services,
|
.oidc
|
||||||
|
.restricted_profile_fields()
|
||||||
|
.contains(&body.value.field_name())
|
||||||
|
{
|
||||||
|
return Err!(Request(Forbidden(
|
||||||
|
"This profile field is controlled by your identity provider."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.set_profile_field(
|
||||||
&body.user_id,
|
&body.user_id,
|
||||||
ProfileFieldChange::Set(body.value.clone()),
|
ProfileFieldChange::Set(body.value.clone()),
|
||||||
body.propagate_to.clone(),
|
body.propagate_to.clone(),
|
||||||
@@ -94,8 +103,19 @@ pub(crate) async fn delete_profile_field_route(
|
|||||||
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
return Err!(Request(InvalidParam("You may not change a remote user's profile data.")));
|
||||||
}
|
}
|
||||||
|
|
||||||
set_profile_field(
|
if services
|
||||||
&services,
|
.oidc
|
||||||
|
.restricted_profile_fields()
|
||||||
|
.contains(&body.field)
|
||||||
|
{
|
||||||
|
return Err!(Request(Forbidden(
|
||||||
|
"This profile field is controlled by your identity provider."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.set_profile_field(
|
||||||
&body.user_id,
|
&body.user_id,
|
||||||
ProfileFieldChange::Delete(body.field.clone()),
|
ProfileFieldChange::Delete(body.field.clone()),
|
||||||
body.propagate_to.clone(),
|
body.propagate_to.clone(),
|
||||||
@@ -110,8 +130,8 @@ async fn fetch_full_profile(
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
) -> Option<BTreeMap<String, Value>> {
|
) -> Option<BTreeMap<String, Value>> {
|
||||||
// If the user exists locally, fetch their local profile
|
// If the user exists locally, fetch their local profile
|
||||||
if services.users.exists(user_id).await {
|
if services.users.status(user_id).await.is_found() {
|
||||||
return Some(get_local_profile(services, user_id).await);
|
return Some(services.users.get_local_profile(user_id).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise ask their homeserver
|
// Otherwise ask their homeserver
|
||||||
@@ -135,12 +155,9 @@ async fn fetch_full_profile(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
let _ = set_profile_field(
|
let _ = services
|
||||||
services,
|
.users
|
||||||
user_id,
|
.set_profile_field(user_id, ProfileFieldChange::Set(value), PropagateTo::None)
|
||||||
ProfileFieldChange::Set(value),
|
|
||||||
PropagateTo::None,
|
|
||||||
)
|
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +171,7 @@ async fn fetch_profile_field(
|
|||||||
) -> Result<Option<ProfileFieldValue>> {
|
) -> Result<Option<ProfileFieldValue>> {
|
||||||
// If the user exists locally, fetch their local profile field
|
// If the user exists locally, fetch their local profile field
|
||||||
if services.globals.user_is_local(user_id) {
|
if services.globals.user_is_local(user_id) {
|
||||||
return Ok(get_local_profile_field(services, user_id, field).await);
|
return Ok(services.users.get_local_profile_field(user_id, field).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise ask their homeserver
|
// Otherwise ask their homeserver
|
||||||
@@ -175,8 +192,9 @@ async fn fetch_profile_field(
|
|||||||
|
|
||||||
if let Some(value) = response.get(field.as_str()).map(ToOwned::to_owned) {
|
if let Some(value) = response.get(field.as_str()).map(ToOwned::to_owned) {
|
||||||
if let Ok(value) = ProfileFieldValue::new(field.as_str(), value) {
|
if let Ok(value) = ProfileFieldValue::new(field.as_str(), value) {
|
||||||
let _ = set_profile_field(
|
let _ = services
|
||||||
services,
|
.users
|
||||||
|
.set_profile_field(
|
||||||
user_id,
|
user_id,
|
||||||
ProfileFieldChange::Set(value.clone()),
|
ProfileFieldChange::Set(value.clone()),
|
||||||
PropagateTo::None,
|
PropagateTo::None,
|
||||||
@@ -190,260 +208,11 @@ async fn fetch_profile_field(
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let _ = set_profile_field(
|
let _ = services
|
||||||
services,
|
.users
|
||||||
user_id,
|
.set_profile_field(user_id, ProfileFieldChange::Delete(field), PropagateTo::None)
|
||||||
ProfileFieldChange::Delete(field),
|
|
||||||
PropagateTo::None,
|
|
||||||
)
|
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn get_local_profile(
|
|
||||||
services: &Services,
|
|
||||||
user_id: &UserId,
|
|
||||||
) -> BTreeMap<String, Value> {
|
|
||||||
let mut profile = BTreeMap::new();
|
|
||||||
|
|
||||||
// Get displayname and avatar_url independently because `all_profile_keys`
|
|
||||||
// doesn't include them
|
|
||||||
for field in [ProfileFieldName::AvatarUrl, ProfileFieldName::DisplayName] {
|
|
||||||
let key = field.as_str().to_owned();
|
|
||||||
|
|
||||||
if let Some(value) = get_local_profile_field(services, user_id, field).await {
|
|
||||||
profile.insert(key, value.value().into_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert all other profile fields
|
|
||||||
let mut all_fields = services.users.all_profile_keys(user_id);
|
|
||||||
|
|
||||||
while let Some((key, value)) = all_fields.next().await {
|
|
||||||
profile.insert(key, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
profile
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn get_local_profile_field(
|
|
||||||
services: &Services,
|
|
||||||
user_id: &UserId,
|
|
||||||
field: ProfileFieldName,
|
|
||||||
) -> Option<ProfileFieldValue> {
|
|
||||||
let value = match field.clone() {
|
|
||||||
| ProfileFieldName::AvatarUrl => services
|
|
||||||
.users
|
|
||||||
.avatar_url(user_id)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.map(to_value)
|
|
||||||
.transpose()
|
|
||||||
.expect("converting avatar url to value should succeed"),
|
|
||||||
| ProfileFieldName::DisplayName => services
|
|
||||||
.users
|
|
||||||
.displayname(user_id)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.map(to_value)
|
|
||||||
.transpose()
|
|
||||||
.expect("converting displayname to value should succeed"),
|
|
||||||
| other => services
|
|
||||||
.users
|
|
||||||
.profile_key(user_id, other.as_str())
|
|
||||||
.await
|
|
||||||
.ok(),
|
|
||||||
}?;
|
|
||||||
|
|
||||||
Some(
|
|
||||||
ProfileFieldValue::new(field.as_str(), value)
|
|
||||||
.expect("local profile field should be valid"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
enum ProfileFieldChange {
|
|
||||||
Set(ProfileFieldValue),
|
|
||||||
Delete(ProfileFieldName),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ProfileFieldChange {
|
|
||||||
fn field_name(&self) -> ProfileFieldName {
|
|
||||||
match self {
|
|
||||||
| &Self::Delete(ref name) => name.clone(),
|
|
||||||
| &Self::Set(ref value) => value.field_name(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn value(&self) -> Option<Value> {
|
|
||||||
if let Self::Set(value) = self {
|
|
||||||
Some(value.value().into_owned())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn set_profile_field(
|
|
||||||
services: &Services,
|
|
||||||
user_id: &UserId,
|
|
||||||
change: ProfileFieldChange,
|
|
||||||
propagate_to: PropagateTo,
|
|
||||||
) -> Result<()> {
|
|
||||||
const MAX_KEY_LENGTH_BYTES: usize = 255;
|
|
||||||
const MAX_PROFILE_LENGTH_BYTES: usize = 65536;
|
|
||||||
|
|
||||||
let field_name = change.field_name();
|
|
||||||
|
|
||||||
// TODO: The spec mentions special error codes (M_PROFILE_TOO_LARGE,
|
|
||||||
// M_KEY_TOO_LARGE) for profile field size limits, but they're not in its list
|
|
||||||
// of error codes and Ruma doesn't have them. Should we return those, or is
|
|
||||||
// M_TOO_LARGE okay?
|
|
||||||
if field_name.as_str().len() > MAX_KEY_LENGTH_BYTES {
|
|
||||||
return Err!(Request(TooLarge(
|
|
||||||
"Individual profile keys must not exceed {MAX_KEY_LENGTH_BYTES} bytes in length."
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serialize the entire profile as canonical JSON, including the new change,
|
|
||||||
// to check if it exceeds 64 KiB
|
|
||||||
{
|
|
||||||
let mut full_profile = get_local_profile(services, user_id).await;
|
|
||||||
|
|
||||||
match &change {
|
|
||||||
| ProfileFieldChange::Set(value) => {
|
|
||||||
full_profile.insert(
|
|
||||||
value.field_name().as_str().to_owned(),
|
|
||||||
value.value().clone().into_owned(),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(key) => {
|
|
||||||
full_profile.remove(key.as_str());
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(canonical_profile) = to_canonical_object(full_profile) {
|
|
||||||
if serde_json::to_string(&canonical_profile)
|
|
||||||
.expect("should be able to serialize to string")
|
|
||||||
.len() > MAX_PROFILE_LENGTH_BYTES
|
|
||||||
{
|
|
||||||
return Err!(
|
|
||||||
"Profile data must not exceed {MAX_PROFILE_LENGTH_BYTES} bytes in length."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err!(Request(BadJson("Failed to canonicalize profile.")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the user is local and changed their displayname or avatar_url, update it
|
|
||||||
// in all their joined rooms. This is done before updating their profile data
|
|
||||||
// so we can check the old value of the field if `propagate_to` is `unchanged`.
|
|
||||||
if matches!(field_name, ProfileFieldName::AvatarUrl | ProfileFieldName::DisplayName)
|
|
||||||
&& matches!(propagate_to, PropagateTo::All | PropagateTo::Unchanged)
|
|
||||||
&& services.globals.user_is_local(user_id)
|
|
||||||
{
|
|
||||||
let current_displayname = services.users.displayname(user_id).await.ok();
|
|
||||||
let current_avatar_url = services.users.avatar_url(user_id).await.ok();
|
|
||||||
|
|
||||||
let mut all_joined_rooms = services.rooms.state_cache.rooms_joined(user_id);
|
|
||||||
|
|
||||||
while let Some(room_id) = all_joined_rooms.next().await {
|
|
||||||
// TODO: this clobbers any custom fields on the event content
|
|
||||||
let mut current_membership = services
|
|
||||||
.rooms
|
|
||||||
.state_accessor
|
|
||||||
.get_member(&room_id, user_id)
|
|
||||||
.await
|
|
||||||
.expect("should be able to fetch membership event for joined room");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
current_membership.membership,
|
|
||||||
MembershipState::Join,
|
|
||||||
"user should be joined"
|
|
||||||
);
|
|
||||||
|
|
||||||
// If `propagate_to` is `unchanged`, and the current value of the field we're
|
|
||||||
// updating was changed from its global value in this room, skip it.
|
|
||||||
if matches!(propagate_to, PropagateTo::Unchanged) {
|
|
||||||
let field_changed_from_global = match field_name {
|
|
||||||
| ProfileFieldName::AvatarUrl =>
|
|
||||||
current_membership.avatar_url.as_ref() != current_avatar_url.as_ref(),
|
|
||||||
| ProfileFieldName::DisplayName =>
|
|
||||||
current_membership.displayname.as_ref() != current_displayname.as_ref(),
|
|
||||||
| _ => unreachable!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
if field_changed_from_global {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let state_lock = services.rooms.state.mutex.lock(room_id.as_str()).await;
|
|
||||||
|
|
||||||
// Preserve keys in accordance with the key copying rules
|
|
||||||
current_membership.reason = None;
|
|
||||||
current_membership.join_authorized_via_users_server = None;
|
|
||||||
match &change {
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::AvatarUrl(avatar_url)) => {
|
|
||||||
current_membership.avatar_url = Some(avatar_url.clone());
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)) => {
|
|
||||||
current_membership.displayname = Some(displayname.clone());
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::AvatarUrl) => {
|
|
||||||
current_membership.avatar_url = None;
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::DisplayName) => {
|
|
||||||
current_membership.displayname = None;
|
|
||||||
},
|
|
||||||
| _ => unreachable!(),
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = services
|
|
||||||
.rooms
|
|
||||||
.timeline
|
|
||||||
.build_and_append_pdu(
|
|
||||||
PartialPdu::state(user_id.to_string(), ¤t_membership),
|
|
||||||
user_id,
|
|
||||||
Some(&room_id),
|
|
||||||
&state_lock,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
|
|
||||||
if services.config.allow_local_presence {
|
|
||||||
// Send a presence EDU to indicate the profile changed
|
|
||||||
let _ = services
|
|
||||||
.presence
|
|
||||||
.ping_presence(user_id, &PresenceState::Online)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match change {
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::DisplayName(displayname)) => {
|
|
||||||
services
|
|
||||||
.users
|
|
||||||
.set_displayname(user_id, Some(displayname).filter(|dn| !dn.is_empty()));
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Set(ProfileFieldValue::AvatarUrl(avatar_url)) => {
|
|
||||||
services
|
|
||||||
.users
|
|
||||||
.set_avatar_url(user_id, Some(avatar_url).filter(|av| av.is_valid()));
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::DisplayName) => {
|
|
||||||
services.users.set_displayname(user_id, None);
|
|
||||||
},
|
|
||||||
| ProfileFieldChange::Delete(ProfileFieldName::AvatarUrl) => {
|
|
||||||
services.users.set_avatar_url(user_id, None);
|
|
||||||
},
|
|
||||||
| other =>
|
|
||||||
services
|
|
||||||
.users
|
|
||||||
.set_profile_key(user_id, other.field_name().as_str(), other.value()),
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -149,7 +149,7 @@ pub(crate) async fn report_user_route(
|
|||||||
|
|
||||||
delay_response().await;
|
delay_response().await;
|
||||||
|
|
||||||
if !services.users.is_active_local(&body.user_id).await {
|
if !services.users.status(&body.user_id).await.is_found() {
|
||||||
// return 200 as to not reveal if the user exists. Recommended by spec.
|
// return 200 as to not reveal if the user exists. Recommended by spec.
|
||||||
return Ok(report_user::v3::Response::new());
|
return Ok(report_user::v3::Response::new());
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-24
@@ -21,7 +21,7 @@ use ruma::{
|
|||||||
},
|
},
|
||||||
login::{
|
login::{
|
||||||
self,
|
self,
|
||||||
v3::{DiscoveryInfo, HomeserverInfo},
|
v3::{DiscoveryInfo, HomeserverInfo, LoginInfo},
|
||||||
},
|
},
|
||||||
logout, logout_all,
|
logout, logout_all,
|
||||||
},
|
},
|
||||||
@@ -29,7 +29,6 @@ use ruma::{
|
|||||||
},
|
},
|
||||||
assign,
|
assign,
|
||||||
};
|
};
|
||||||
use service::uiaa::Identity;
|
|
||||||
|
|
||||||
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
@@ -44,6 +43,12 @@ pub(crate) async fn get_login_types_route(
|
|||||||
ClientIp(client): ClientIp,
|
ClientIp(client): ClientIp,
|
||||||
_body: Ruma<get_login_types::v3::Request>,
|
_body: Ruma<get_login_types::v3::Request>,
|
||||||
) -> Result<get_login_types::v3::Response> {
|
) -> Result<get_login_types::v3::Response> {
|
||||||
|
if !services.config.oauth.compatibility_mode().uiaa_available() {
|
||||||
|
return Err!(Request(Unrecognized(
|
||||||
|
"User-interactive authentication is not available on this server."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(get_login_types::v3::Response::new(vec![
|
Ok(get_login_types::v3::Response::new(vec![
|
||||||
get_login_types::v3::LoginType::Password(PasswordLoginType::default()),
|
get_login_types::v3::LoginType::Password(PasswordLoginType::default()),
|
||||||
get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()),
|
get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()),
|
||||||
@@ -53,7 +58,7 @@ pub(crate) async fn get_login_types_route(
|
|||||||
]))
|
]))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn handle_login(
|
pub async fn handle_login(
|
||||||
services: &Services,
|
services: &Services,
|
||||||
identifier: Option<&UserIdentifier>,
|
identifier: Option<&UserIdentifier>,
|
||||||
password: &str,
|
password: &str,
|
||||||
@@ -83,14 +88,6 @@ pub(crate) async fn handle_login(
|
|||||||
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
|
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
|
||||||
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
|
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
|
||||||
|
|
||||||
if !services.globals.user_is_local(&user_id) {
|
|
||||||
return Err!(Request(InvalidParam("User ID does not belong to this homeserver")));
|
|
||||||
}
|
|
||||||
|
|
||||||
if services.users.is_deactivated(&user_id).await? {
|
|
||||||
return Err!(Request(UserDeactivated("This account has been deactivated.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
if services.users.is_locked(&user_id).await? {
|
if services.users.is_locked(&user_id).await? {
|
||||||
return Err!(Request(UserLocked("This account has been locked.")));
|
return Err!(Request(UserLocked("This account has been locked.")));
|
||||||
}
|
}
|
||||||
@@ -123,19 +120,29 @@ pub(crate) async fn login_route(
|
|||||||
ClientIp(client): ClientIp,
|
ClientIp(client): ClientIp,
|
||||||
body: Ruma<login::v3::Request>,
|
body: Ruma<login::v3::Request>,
|
||||||
) -> Result<login::v3::Response> {
|
) -> Result<login::v3::Response> {
|
||||||
|
if !services.config.oauth.compatibility_mode().uiaa_available() {
|
||||||
|
return match body.login_info {
|
||||||
|
| LoginInfo::ApplicationService(_) => {
|
||||||
|
Err!(Request(AppserviceLoginUnsupported(
|
||||||
|
"User-interactive appservice login is not available on this server."
|
||||||
|
)))
|
||||||
|
},
|
||||||
|
| _ => {
|
||||||
|
Err!(Request(Unrecognized(
|
||||||
|
"User-interactive authentication is not available on this server."
|
||||||
|
)))
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
let emergency_mode_enabled = services.config.emergency_password.is_some();
|
let emergency_mode_enabled = services.config.emergency_password.is_some();
|
||||||
|
|
||||||
// Validate login method
|
// Validate login method
|
||||||
// TODO: Other login methods
|
|
||||||
let user_id = match &body.login_info {
|
let user_id = match &body.login_info {
|
||||||
#[allow(deprecated)]
|
#[allow(deprecated)]
|
||||||
| login::v3::LoginInfo::Password(login::v3::Password {
|
| LoginInfo::Password(login::v3::Password { identifier, password, user, .. }) =>
|
||||||
identifier,
|
handle_login(&services, identifier.as_ref(), password, user.as_ref()).await?,
|
||||||
password,
|
| LoginInfo::Token(login::v3::Token { token, .. }) => {
|
||||||
user,
|
|
||||||
..
|
|
||||||
}) => handle_login(&services, identifier.as_ref(), password, user.as_ref()).await?,
|
|
||||||
| login::v3::LoginInfo::Token(login::v3::Token { token, .. }) => {
|
|
||||||
debug!("Got token login type");
|
debug!("Got token login type");
|
||||||
if !services.server.config.login_via_existing_session {
|
if !services.server.config.login_via_existing_session {
|
||||||
return Err!(Request(Unknown("Token login is not enabled.")));
|
return Err!(Request(Unknown("Token login is not enabled.")));
|
||||||
@@ -143,7 +150,7 @@ pub(crate) async fn login_route(
|
|||||||
services.users.find_from_login_token(token).await?
|
services.users.find_from_login_token(token).await?
|
||||||
},
|
},
|
||||||
#[allow(deprecated)]
|
#[allow(deprecated)]
|
||||||
| login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
|
| LoginInfo::ApplicationService(login::v3::ApplicationService {
|
||||||
identifier,
|
identifier,
|
||||||
user,
|
user,
|
||||||
..
|
..
|
||||||
@@ -177,7 +184,6 @@ pub(crate) async fn login_route(
|
|||||||
user_id
|
user_id
|
||||||
},
|
},
|
||||||
| _ => {
|
| _ => {
|
||||||
debug!("/login json_body: {:?}", &body.json_body);
|
|
||||||
return Err!(Request(Unknown(
|
return Err!(Request(Unknown(
|
||||||
debug_warn!(?body.login_info, "Invalid or unsupported login type")
|
debug_warn!(?body.login_info, "Invalid or unsupported login type")
|
||||||
)));
|
)));
|
||||||
@@ -207,7 +213,7 @@ pub(crate) async fn login_route(
|
|||||||
if device_exists {
|
if device_exists {
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.set_token(&user_id, &device_id, &token)
|
.set_token(&user_id, &device_id, &token, None)
|
||||||
.await?;
|
.await?;
|
||||||
} else {
|
} else {
|
||||||
services
|
services
|
||||||
@@ -216,6 +222,7 @@ pub(crate) async fn login_route(
|
|||||||
&user_id,
|
&user_id,
|
||||||
&device_id,
|
&device_id,
|
||||||
&token,
|
&token,
|
||||||
|
None,
|
||||||
body.initial_device_display_name.clone(),
|
body.initial_device_display_name.clone(),
|
||||||
Some(client.to_string()),
|
Some(client.to_string()),
|
||||||
)
|
)
|
||||||
@@ -254,7 +261,7 @@ pub(crate) async fn login_token_route(
|
|||||||
ClientIp(client): ClientIp,
|
ClientIp(client): ClientIp,
|
||||||
body: Ruma<get_login_token::v1::Request>,
|
body: Ruma<get_login_token::v1::Request>,
|
||||||
) -> Result<get_login_token::v1::Response> {
|
) -> Result<get_login_token::v1::Response> {
|
||||||
if !services.server.config.login_via_existing_session {
|
if !services.config.login_via_existing_session {
|
||||||
return Err!(Request(Forbidden("Login via an existing session is not enabled")));
|
return Err!(Request(Forbidden("Login via an existing session is not enabled")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,7 +270,7 @@ pub(crate) async fn login_token_route(
|
|||||||
// Prompt the user to confirm with their password using UIAA
|
// Prompt the user to confirm with their password using UIAA
|
||||||
let _ = services
|
let _ = services
|
||||||
.uiaa
|
.uiaa
|
||||||
.authenticate_password(&body.auth, Some(Identity::from_user_id(sender_user)))
|
.authenticate_password(&body.auth, sender_user, body.identity.sender_device(), None)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let login_token = utils::random_string(TOKEN_LENGTH);
|
let login_token = utils::random_string(TOKEN_LENGTH);
|
||||||
|
|||||||
@@ -70,7 +70,6 @@ pub(crate) async fn sync_events_v5_route(
|
|||||||
ClientIp(client_ip): ClientIp,
|
ClientIp(client_ip): ClientIp,
|
||||||
body: Ruma<sync_events::v5::Request>,
|
body: Ruma<sync_events::v5::Request>,
|
||||||
) -> Result<sync_events::v5::Response> {
|
) -> Result<sync_events::v5::Response> {
|
||||||
debug_assert!(DEFAULT_BUMP_TYPES.is_sorted(), "DEFAULT_BUMP_TYPES is not sorted");
|
|
||||||
let sender_user = body.identity.expect_sender_user()?;
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
let sender_device = body.identity.expect_sender_device()?;
|
let sender_device = body.identity.expect_sender_device()?;
|
||||||
|
|
||||||
|
|||||||
@@ -35,8 +35,8 @@ pub(crate) async fn get_supported_versions_route(
|
|||||||
/// `/_matrix/federation/v1/version`
|
/// `/_matrix/federation/v1/version`
|
||||||
pub(crate) async fn conduwuit_server_version() -> Result<impl IntoResponse> {
|
pub(crate) async fn conduwuit_server_version() -> Result<impl IntoResponse> {
|
||||||
Ok(Json(serde_json::json!({
|
Ok(Json(serde_json::json!({
|
||||||
"name": conduwuit::version::name(),
|
"name": conduwuit::BRANDING,
|
||||||
"version": conduwuit::version::version(),
|
"version": conduwuit::version(),
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,12 @@ pub(crate) async fn search_users_route(
|
|||||||
.min(LIMIT_MAX);
|
.min(LIMIT_MAX);
|
||||||
|
|
||||||
let search_term = body.search_term.to_lowercase();
|
let search_term = body.search_term.to_lowercase();
|
||||||
let mut users = services.users.stream().broad_filter_map(async |user_id| {
|
|
||||||
|
let mut users = services
|
||||||
|
.users
|
||||||
|
.stream_local_users()
|
||||||
|
.chain(services.users.stream_remote_users())
|
||||||
|
.broad_filter_map(async |user_id| {
|
||||||
let display_name = services.users.displayname(&user_id).await.ok();
|
let display_name = services.users.displayname(&user_id).await.ok();
|
||||||
|
|
||||||
let user_id_matches = user_id.as_str().to_lowercase().contains(&search_term);
|
let user_id_matches = user_id.as_str().to_lowercase().contains(&search_term);
|
||||||
@@ -46,8 +51,7 @@ pub(crate) async fn search_users_route(
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let user_in_public_room =
|
let user_in_public_room = services
|
||||||
services
|
|
||||||
.rooms
|
.rooms
|
||||||
.state_cache
|
.state_cache
|
||||||
.rooms_joined(&user_id)
|
.rooms_joined(&user_id)
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ use conduwuit::{Err, Result};
|
|||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::discovery::{
|
api::client::discovery::{
|
||||||
discover_homeserver::{self, HomeserverInfo},
|
discover_homeserver::{self, HomeserverInfo},
|
||||||
discover_policy_server,
|
discover_policy_server, discover_support,
|
||||||
discover_support::{self, Contact, ContactRole},
|
|
||||||
},
|
},
|
||||||
assign,
|
assign,
|
||||||
};
|
};
|
||||||
@@ -67,46 +66,7 @@ pub(crate) async fn well_known_support(
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(ToString::to_string);
|
.map(ToString::to_string);
|
||||||
|
|
||||||
let email_address = services.config.well_known.support_email.clone();
|
let contacts = services.admin.get_support_contacts().await;
|
||||||
let matrix_id = services.config.well_known.support_mxid.clone();
|
|
||||||
let pgp_key = services.config.well_known.support_pgp_key.clone();
|
|
||||||
|
|
||||||
// TODO: support defining multiple contacts in the config
|
|
||||||
let mut contacts: Vec<Contact> = vec![];
|
|
||||||
|
|
||||||
let role = services
|
|
||||||
.config
|
|
||||||
.well_known
|
|
||||||
.support_role
|
|
||||||
.clone()
|
|
||||||
.unwrap_or(ContactRole::Admin);
|
|
||||||
|
|
||||||
// Add configured contact if at least one contact method is specified
|
|
||||||
let configured_contact = match (matrix_id, email_address) {
|
|
||||||
| (Some(matrix_id), email_address) =>
|
|
||||||
Some(assign!(Contact::with_matrix_id(role, matrix_id), { email_address })),
|
|
||||||
| (None, Some(email_address)) => Some(Contact::with_email_address(role, email_address)),
|
|
||||||
| (None, None) => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(mut configured_contact) = configured_contact {
|
|
||||||
configured_contact.pgp_key = pgp_key;
|
|
||||||
|
|
||||||
contacts.push(configured_contact);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to add admin users as contacts if no contacts are configured
|
|
||||||
if contacts.is_empty() {
|
|
||||||
let admin_users = services.admin.get_admins().await;
|
|
||||||
|
|
||||||
for user_id in &admin_users {
|
|
||||||
if *user_id == services.globals.server_user {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
contacts.push(Contact::with_matrix_id(ContactRole::Admin, user_id.to_owned()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if contacts.is_empty() && support_page.is_none() {
|
if contacts.is_empty() && support_page.is_none() {
|
||||||
// No admin room, no configured contacts, and no support page
|
// No admin room, no configured contacts, and no support page
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#![type_length_limit = "16384"] //TODO: reduce me
|
#![type_length_limit = "16384"] //TODO: reduce me
|
||||||
|
#![recursion_limit = "256"] // My Giant Async Function
|
||||||
#![allow(clippy::toplevel_ref_arg)]
|
#![allow(clippy::toplevel_ref_arg)]
|
||||||
|
|
||||||
extern crate conduwuit_core as conduwuit;
|
extern crate conduwuit_core as conduwuit;
|
||||||
|
|||||||
+7
-3
@@ -10,7 +10,7 @@ use axum::{
|
|||||||
response::{IntoResponse, Redirect},
|
response::{IntoResponse, Redirect},
|
||||||
routing::{any, get, post},
|
routing::{any, get, post},
|
||||||
};
|
};
|
||||||
use conduwuit::{Server, err};
|
use conduwuit::err;
|
||||||
pub(super) use conduwuit_service::state::State;
|
pub(super) use conduwuit_service::state::State;
|
||||||
use http::{Uri, uri};
|
use http::{Uri, uri};
|
||||||
|
|
||||||
@@ -18,8 +18,8 @@ use self::handler::RouterExt;
|
|||||||
pub(super) use self::{args::Args as Ruma, auth::ClientIdentity, response::RumaResponse};
|
pub(super) use self::{args::Args as Ruma, auth::ClientIdentity, response::RumaResponse};
|
||||||
use crate::{admin, client, server};
|
use crate::{admin, client, server};
|
||||||
|
|
||||||
pub fn build(router: Router<State>, server: &Server) -> Router<State> {
|
pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||||
let config = &server.config;
|
let config = &state.server.config;
|
||||||
let mut router = router
|
let mut router = router
|
||||||
.ruma_route(&client::appservice_ping)
|
.ruma_route(&client::appservice_ping)
|
||||||
.ruma_route(&client::get_supported_versions_route)
|
.ruma_route(&client::get_supported_versions_route)
|
||||||
@@ -181,11 +181,15 @@ pub fn build(router: Router<State>, server: &Server) -> Router<State> {
|
|||||||
.ruma_route(&client::get_room_summary)
|
.ruma_route(&client::get_room_summary)
|
||||||
.ruma_route(&client::get_suspended_status)
|
.ruma_route(&client::get_suspended_status)
|
||||||
.ruma_route(&client::put_suspended_status)
|
.ruma_route(&client::put_suspended_status)
|
||||||
|
.ruma_route(&client::get_lock_status)
|
||||||
|
.ruma_route(&client::put_lock_status)
|
||||||
.ruma_route(&client::well_known_support)
|
.ruma_route(&client::well_known_support)
|
||||||
.ruma_route(&client::well_known_client)
|
.ruma_route(&client::well_known_client)
|
||||||
.ruma_route(&client::well_known_policy_server)
|
.ruma_route(&client::well_known_policy_server)
|
||||||
.ruma_route(&client::get_rtc_transports)
|
.ruma_route(&client::get_rtc_transports)
|
||||||
.ruma_route(&client::room_initial_sync_route)
|
.ruma_route(&client::room_initial_sync_route)
|
||||||
|
.ruma_route(&client::get_authorization_server_metadata_route)
|
||||||
|
.merge(client::oauth::router(state))
|
||||||
.route("/_conduwuit/server_version", get(client::conduwuit_server_version))
|
.route("/_conduwuit/server_version", get(client::conduwuit_server_version))
|
||||||
.route("/_continuwuity/server_version", get(client::conduwuit_server_version))
|
.route("/_continuwuity/server_version", get(client::conduwuit_server_version))
|
||||||
.ruma_route(&admin::rooms::ban::ban_room)
|
.ruma_route(&admin::rooms::ban::ban_room)
|
||||||
|
|||||||
+25
-4
@@ -1,6 +1,7 @@
|
|||||||
use std::any::{Any, TypeId};
|
use std::any::{Any, TypeId};
|
||||||
|
|
||||||
use conduwuit::{Err, Result, err};
|
use conduwuit::{Err, Error, Result, err};
|
||||||
|
use http::StatusCode;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
DeviceId, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
|
DeviceId, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
|
||||||
api::{
|
api::{
|
||||||
@@ -10,12 +11,15 @@ use ruma::{
|
|||||||
AuthScheme, NoAccessToken, NoAuthentication,
|
AuthScheme, NoAccessToken, NoAuthentication,
|
||||||
},
|
},
|
||||||
client,
|
client,
|
||||||
|
error::{ErrorKind, UnknownTokenErrorData},
|
||||||
federation::authentication::ServerSignatures,
|
federation::authentication::ServerSignatures,
|
||||||
},
|
},
|
||||||
|
assign,
|
||||||
};
|
};
|
||||||
use service::{
|
use service::{
|
||||||
Services,
|
Services,
|
||||||
server_keys::{PubKeyMap, PubKeys},
|
server_keys::{PubKeyMap, PubKeys},
|
||||||
|
users::AccessTokenStatus,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{router::args::AuthQueryParams, service::appservice::RegistrationInfo};
|
use crate::{router::args::AuthQueryParams, service::appservice::RegistrationInfo};
|
||||||
@@ -165,7 +169,20 @@ impl CheckAuth for AccessToken {
|
|||||||
if output.is_empty() {
|
if output.is_empty() {
|
||||||
return Err!(Request(Unauthorized("Missing access token.")));
|
return Err!(Request(Unauthorized("Missing access token.")));
|
||||||
}
|
}
|
||||||
if let Ok((sender_user, sender_device)) = services.users.find_from_token(&output).await {
|
if let Some((sender_user, sender_device, status)) =
|
||||||
|
services.users.find_from_token(&output).await
|
||||||
|
{
|
||||||
|
// If the token is expired we return a soft logout
|
||||||
|
if matches!(status, AccessTokenStatus::Expired) {
|
||||||
|
return Err(Error::Request(
|
||||||
|
ErrorKind::UnknownToken(
|
||||||
|
assign!(UnknownTokenErrorData::new(), { soft_logout: true }),
|
||||||
|
),
|
||||||
|
"This token has expired".into(),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
// Locked users can only use /logout and /logout/all
|
// Locked users can only use /logout and /logout/all
|
||||||
if services
|
if services
|
||||||
.users
|
.users
|
||||||
@@ -176,7 +193,7 @@ impl CheckAuth for AccessToken {
|
|||||||
if !(route == TypeId::of::<client::session::logout::v3::Request>()
|
if !(route == TypeId::of::<client::session::logout::v3::Request>()
|
||||||
|| route == TypeId::of::<client::session::logout_all::v3::Request>())
|
|| route == TypeId::of::<client::session::logout_all::v3::Request>())
|
||||||
{
|
{
|
||||||
return Err!(Request(Unauthorized("Your account is locked.")));
|
return Err!(Request(UserLocked("Your account is locked.")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +244,11 @@ impl CheckAuth for AccessToken {
|
|||||||
appservice_info: Box::new(appservice_info),
|
appservice_info: Box::new(appservice_info),
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
Err!(Request(Unauthorized("Invalid access token.")))
|
Err(Error::Request(
|
||||||
|
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
|
||||||
|
"Invalid token".into(),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ pub(crate) async fn get_backfill_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
if !services
|
if !services
|
||||||
.rooms
|
.rooms
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ pub(crate) async fn get_event_route(
|
|||||||
room_id,
|
room_id,
|
||||||
event_id: Some(&body.event_id),
|
event_id: Some(&body.event_id),
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !services
|
if !services
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ pub(crate) async fn get_event_authorization_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if services
|
if services
|
||||||
|
|||||||
@@ -4,15 +4,11 @@ use axum::extract::State;
|
|||||||
use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn};
|
use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn};
|
||||||
use ruma::{OwnedEventId, api::federation::event::get_missing_events};
|
use ruma::{OwnedEventId, api::federation::event::get_missing_events};
|
||||||
use serde_json::{json, value::RawValue};
|
use serde_json::{json, value::RawValue};
|
||||||
|
use service::rooms::event_handler::GET_MISSING_EVENTS_MAX_BATCH_SIZE;
|
||||||
|
|
||||||
use super::AccessCheck;
|
use super::AccessCheck;
|
||||||
use crate::Ruma;
|
use crate::Ruma;
|
||||||
|
|
||||||
/// arbitrary number but synapse's is 20 and we can handle lots of these anyways
|
|
||||||
const LIMIT_MAX: usize = 50;
|
|
||||||
/// spec says default is 10
|
|
||||||
const LIMIT_DEFAULT: usize = 10;
|
|
||||||
|
|
||||||
/// # `POST /_matrix/federation/v1/get_missing_events/{roomId}`
|
/// # `POST /_matrix/federation/v1/get_missing_events/{roomId}`
|
||||||
///
|
///
|
||||||
/// Retrieves events that the sender is missing.
|
/// Retrieves events that the sender is missing.
|
||||||
@@ -26,7 +22,7 @@ pub(crate) async fn get_missing_events_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !services
|
if !services
|
||||||
@@ -45,8 +41,8 @@ pub(crate) async fn get_missing_events_route(
|
|||||||
let limit = body
|
let limit = body
|
||||||
.limit
|
.limit
|
||||||
.try_into()
|
.try_into()
|
||||||
.unwrap_or(LIMIT_DEFAULT)
|
.unwrap_or(10)
|
||||||
.min(LIMIT_MAX);
|
.min(GET_MISSING_EVENTS_MAX_BATCH_SIZE);
|
||||||
|
|
||||||
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
|
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -7,10 +7,7 @@ use ruma::{
|
|||||||
api::federation::query::{get_profile_information, get_room_information},
|
api::federation::query::{get_profile_information, get_room_information},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::Ruma;
|
||||||
Ruma,
|
|
||||||
client::{get_local_profile, get_local_profile_field},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// # `GET /_matrix/federation/v1/query/directory`
|
/// # `GET /_matrix/federation/v1/query/directory`
|
||||||
///
|
///
|
||||||
@@ -75,15 +72,19 @@ pub(crate) async fn get_profile_information_route(
|
|||||||
let response = if let Some(field) = &body.field {
|
let response = if let Some(field) = &body.field {
|
||||||
let mut response = get_profile_information::v1::Response::new();
|
let mut response = get_profile_information::v1::Response::new();
|
||||||
|
|
||||||
if let Some(value) =
|
if let Some(value) = services
|
||||||
get_local_profile_field(&services, &body.user_id, field.to_owned()).await
|
.users
|
||||||
|
.get_local_profile_field(&body.user_id, field.to_owned())
|
||||||
|
.await
|
||||||
{
|
{
|
||||||
response.set(value.field_name().as_str().to_owned(), value.value().into_owned());
|
response.set(value.field_name().as_str().to_owned(), value.value().into_owned());
|
||||||
}
|
}
|
||||||
|
|
||||||
response
|
response
|
||||||
} else {
|
} else {
|
||||||
get_local_profile(&services, &body.user_id)
|
services
|
||||||
|
.users
|
||||||
|
.get_local_profile(&body.user_id)
|
||||||
.await
|
.await
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.collect()
|
.collect()
|
||||||
|
|||||||
+27
-85
@@ -1,5 +1,5 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, HashMap, HashSet},
|
collections::{BTreeMap, HashMap},
|
||||||
net::IpAddr,
|
net::IpAddr,
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
@@ -7,9 +7,8 @@ use std::{
|
|||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use axum_client_ip::ClientIp;
|
use axum_client_ip::ClientIp;
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Err, Error, Result, debug, debug_warn, err, error,
|
Err, Error, Result, debug, debug_error, debug_warn, err, error,
|
||||||
result::LogErr,
|
result::LogErr,
|
||||||
state_res::lexicographical_topological_sort,
|
|
||||||
trace,
|
trace,
|
||||||
utils::{
|
utils::{
|
||||||
IterStream, ReadyExt, millis_since_unix_epoch,
|
IterStream, ReadyExt, millis_since_unix_epoch,
|
||||||
@@ -25,8 +24,7 @@ use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
|||||||
use http::StatusCode;
|
use http::StatusCode;
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId,
|
CanonicalJsonObject, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, ServerName, UserId,
|
||||||
OwnedUserId, RoomId, ServerName, UInt, UserId,
|
|
||||||
api::{
|
api::{
|
||||||
error::{ErrorKind, LimitExceededErrorData},
|
error::{ErrorKind, LimitExceededErrorData},
|
||||||
federation::transactions::{
|
federation::transactions::{
|
||||||
@@ -39,12 +37,12 @@ use ruma::{
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
events::receipt::{ReceiptEvent, ReceiptEventContent, ReceiptType},
|
events::receipt::{ReceiptEvent, ReceiptEventContent, ReceiptType},
|
||||||
int,
|
|
||||||
serde::Raw,
|
serde::Raw,
|
||||||
to_device::DeviceIdOrAllDevices,
|
to_device::DeviceIdOrAllDevices,
|
||||||
};
|
};
|
||||||
use service::transactions::{
|
use service::{
|
||||||
FederationTxnState, TransactionError, TxnKey, WrappedTransactionResponse,
|
rooms::event_handler::build_local_dag,
|
||||||
|
transactions::{FederationTxnState, TransactionError, TxnKey, WrappedTransactionResponse},
|
||||||
};
|
};
|
||||||
use tokio::sync::watch::{Receiver, Sender};
|
use tokio::sync::watch::{Receiver, Sender};
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
@@ -133,6 +131,7 @@ async fn wait_for_result(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(
|
#[instrument(
|
||||||
|
name="transaction"
|
||||||
skip_all,
|
skip_all,
|
||||||
fields(
|
fields(
|
||||||
id = ?body.transaction_id.as_str(),
|
id = ?body.transaction_id.as_str(),
|
||||||
@@ -174,8 +173,14 @@ async fn process_inbound_transaction(
|
|||||||
|
|
||||||
for (id, result) in &results {
|
for (id, result) in &results {
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
if matches!(e, Error::BadRequest(ErrorKind::NotFound, _)) {
|
match e {
|
||||||
debug_warn!("Incoming PDU failed {id}: {e:?}");
|
| Error::BadRequest(
|
||||||
|
ErrorKind::Forbidden | ErrorKind::InvalidParam | ErrorKind::BadJson,
|
||||||
|
..,
|
||||||
|
) => {
|
||||||
|
debug_warn!("Incoming PDU {id} failed: {e:?}");
|
||||||
|
},
|
||||||
|
| _ => debug_error!("Incoming PDU {id} failed: {e:?}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -269,74 +274,6 @@ async fn handle(
|
|||||||
Ok(results)
|
Ok(results)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attempts to build a localised directed acyclic graph out of the given PDUs,
|
|
||||||
/// returning them in a topologically sorted order.
|
|
||||||
///
|
|
||||||
/// This is used to attempt to process PDUs in an order that respects their
|
|
||||||
/// dependencies, however it is ultimately the sender's responsibility to send
|
|
||||||
/// them in a processable order, so this is just a best effort attempt. It does
|
|
||||||
/// not account for power levels or other tie breaks.
|
|
||||||
async fn build_local_dag(
|
|
||||||
pdu_map: &HashMap<OwnedEventId, CanonicalJsonObject>,
|
|
||||||
) -> Result<Vec<OwnedEventId>> {
|
|
||||||
debug_assert!(pdu_map.len() >= 2, "needless call to build_local_dag with less than 2 PDUs");
|
|
||||||
let mut dag: HashMap<OwnedEventId, HashSet<OwnedEventId>> =
|
|
||||||
HashMap::with_capacity(pdu_map.len());
|
|
||||||
let mut id_origin_ts: HashMap<OwnedEventId, _> = HashMap::with_capacity(pdu_map.len());
|
|
||||||
|
|
||||||
for (event_id, value) in pdu_map {
|
|
||||||
// We already checked that these properties are correct in parse_incoming_pdu,
|
|
||||||
// so it's safe to unwrap here.
|
|
||||||
// We also filter to remove any prev_events that are not in this pdu_map, as we
|
|
||||||
// need to have at least one event with zero out degrees for the lexico-topo
|
|
||||||
// sort below. If there are multiple events with omitted prevs, they will be
|
|
||||||
// ordered by timestamp, then event ID. At that point though, it's unlikely to
|
|
||||||
// matter.
|
|
||||||
let prev_events = value
|
|
||||||
.get("prev_events")
|
|
||||||
.unwrap()
|
|
||||||
.as_array()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.map(|v| EventId::parse(v.as_str().unwrap()).unwrap())
|
|
||||||
.filter(|id| pdu_map.contains_key(id))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
dag.insert(event_id.clone(), prev_events);
|
|
||||||
let origin_server_ts = value
|
|
||||||
.get("origin_server_ts")
|
|
||||||
.and_then(ruma::CanonicalJsonValue::as_integer)
|
|
||||||
.unwrap_or_default();
|
|
||||||
id_origin_ts.insert(event_id.clone(), origin_server_ts);
|
|
||||||
}
|
|
||||||
|
|
||||||
debug!(count = dag.len(), "Sorting incoming events with partial graph");
|
|
||||||
lexicographical_topological_sort(&dag, &async |node_id| {
|
|
||||||
// Note: we don't bother fetching power levels because that would massively slow
|
|
||||||
// this function down. This is a best-effort attempt to order events correctly
|
|
||||||
// for processing, however ultimately that should be the sender's job.
|
|
||||||
let ts = id_origin_ts
|
|
||||||
.get(&node_id)
|
|
||||||
.copied()
|
|
||||||
.unwrap_or_else(|| int!(0))
|
|
||||||
.to_string()
|
|
||||||
.parse::<u64>()
|
|
||||||
.ok()
|
|
||||||
.and_then(UInt::new)
|
|
||||||
.unwrap_or_default();
|
|
||||||
Ok((int!(0), MilliSecondsSinceUnixEpoch(ts)))
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.inspect(|sorted| {
|
|
||||||
debug_assert_eq!(
|
|
||||||
sorted.len(),
|
|
||||||
pdu_map.len(),
|
|
||||||
"Sorted graph was not the same size as the input graph"
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.map_err(|e| err!("failed to resolve local graph: {e}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_room(
|
async fn handle_room(
|
||||||
services: &Services,
|
services: &Services,
|
||||||
_client: &IpAddr,
|
_client: &IpAddr,
|
||||||
@@ -352,7 +289,7 @@ async fn handle_room(
|
|||||||
.await;
|
.await;
|
||||||
|
|
||||||
let room_id = &room_id;
|
let room_id = &room_id;
|
||||||
let pdu_map: HashMap<OwnedEventId, CanonicalJsonObject> = pdus
|
let mut pdu_map: HashMap<OwnedEventId, CanonicalJsonObject> = pdus
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(_, event_id, value)| (event_id, value))
|
.map(|(_, event_id, value)| (event_id, value))
|
||||||
.collect();
|
.collect();
|
||||||
@@ -360,7 +297,11 @@ async fn handle_room(
|
|||||||
// failure (e.g., cycles). This is best-effort; proper ordering is the sender's
|
// failure (e.g., cycles). This is best-effort; proper ordering is the sender's
|
||||||
// responsibility.
|
// responsibility.
|
||||||
let sorted_event_ids = if pdu_map.len() >= 2 {
|
let sorted_event_ids = if pdu_map.len() >= 2 {
|
||||||
build_local_dag(&pdu_map).await.unwrap_or_else(|e| {
|
let refmap = pdu_map
|
||||||
|
.iter()
|
||||||
|
.map(|(event_id, obj)| (event_id.clone(), obj))
|
||||||
|
.collect();
|
||||||
|
build_local_dag(&refmap).await.unwrap_or_else(|e| {
|
||||||
debug_warn!("Failed to build local DAG for room {room_id}: {e}");
|
debug_warn!("Failed to build local DAG for room {room_id}: {e}");
|
||||||
pdu_map.keys().cloned().collect()
|
pdu_map.keys().cloned().collect()
|
||||||
})
|
})
|
||||||
@@ -370,9 +311,8 @@ async fn handle_room(
|
|||||||
let mut results = Vec::with_capacity(sorted_event_ids.len());
|
let mut results = Vec::with_capacity(sorted_event_ids.len());
|
||||||
for event_id in sorted_event_ids {
|
for event_id in sorted_event_ids {
|
||||||
let value = pdu_map
|
let value = pdu_map
|
||||||
.get(&event_id)
|
.remove(&event_id)
|
||||||
.expect("sorted event IDs must be from the original map")
|
.expect("sorted event IDs must be from the original map");
|
||||||
.clone();
|
|
||||||
services
|
services
|
||||||
.server
|
.server
|
||||||
.check_running()
|
.check_running()
|
||||||
@@ -380,7 +320,8 @@ async fn handle_room(
|
|||||||
let result = services
|
let result = services
|
||||||
.rooms
|
.rooms
|
||||||
.event_handler
|
.event_handler
|
||||||
.handle_incoming_pdu(origin, room_id, &event_id, value, true)
|
.handle_incoming_pdu(origin, room_id, &event_id, value.clone(), true)
|
||||||
|
.boxed()
|
||||||
.await
|
.await
|
||||||
.map(|_| ());
|
.map(|_| ());
|
||||||
results.push((event_id, result));
|
results.push((event_id, result));
|
||||||
@@ -679,8 +620,9 @@ async fn handle_edu_direct_to_device(
|
|||||||
.broad_filter_map(|(target_user_id, map)| async move {
|
.broad_filter_map(|(target_user_id, map)| async move {
|
||||||
services
|
services
|
||||||
.users
|
.users
|
||||||
.is_active_local(&target_user_id)
|
.status(&target_user_id)
|
||||||
.await
|
.await
|
||||||
|
.is_active()
|
||||||
.then_some((target_user_id, map))
|
.then_some((target_user_id, map))
|
||||||
})
|
})
|
||||||
.for_each_concurrent(automatic_width(), |(target_user_id, map)| {
|
.for_each_concurrent(automatic_width(), |(target_user_id, map)| {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ pub(crate) async fn get_room_state_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if services
|
if services
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ pub(crate) async fn get_room_state_ids_route(
|
|||||||
room_id: &body.room_id,
|
room_id: &body.room_id,
|
||||||
event_id: None,
|
event_id: None,
|
||||||
}
|
}
|
||||||
.check()
|
.assert()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if services
|
if services
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use conduwuit::{Err, Result, implement, is_false};
|
use conduwuit::{Err, Result, is_false};
|
||||||
use conduwuit_service::Services;
|
use conduwuit_service::Services;
|
||||||
use futures::{FutureExt, future::OptionFuture, join};
|
use futures::{FutureExt, future::OptionFuture, join};
|
||||||
use ruma::{EventId, RoomId, ServerName};
|
use ruma::{EventId, RoomId, ServerName};
|
||||||
@@ -10,8 +10,11 @@ pub(super) struct AccessCheck<'a> {
|
|||||||
pub(super) event_id: Option<&'a EventId>,
|
pub(super) event_id: Option<&'a EventId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(AccessCheck, params = "<'_>")]
|
impl AccessCheck<'_> {
|
||||||
pub(super) async fn check(&self) -> Result {
|
/// Asserts that the server has access to the room and event (if any).
|
||||||
|
/// If the server is permitted, `Ok(())` is returned. Otherwise, a Forbidden
|
||||||
|
/// error is returned.
|
||||||
|
pub(super) async fn assert(&self) -> Result {
|
||||||
let acl_check = self
|
let acl_check = self
|
||||||
.services
|
.services
|
||||||
.rooms
|
.rooms
|
||||||
@@ -58,4 +61,5 @@ pub(super) async fn check(&self) -> Result {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -11,8 +11,8 @@ pub(crate) async fn get_server_version_route(
|
|||||||
) -> Result<get_server_version::v1::Response> {
|
) -> Result<get_server_version::v1::Response> {
|
||||||
Ok(assign!(get_server_version::v1::Response::new(), {
|
Ok(assign!(get_server_version::v1::Response::new(), {
|
||||||
server: Some(assign!(get_server_version::v1::Server::new(), {
|
server: Some(assign!(get_server_version::v1::Server::new(), {
|
||||||
name: Some(conduwuit::version::name().into()),
|
name: Some(conduwuit::BRANDING.into()),
|
||||||
version: Some(conduwuit::version::version().into()),
|
version: Some(conduwuit::version().into()),
|
||||||
})),
|
})),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,7 @@ repository.workspace = true
|
|||||||
version.workspace = true
|
version.workspace = true
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
|
doctest = false
|
||||||
path = "mod.rs"
|
path = "mod.rs"
|
||||||
crate-type = [
|
crate-type = [
|
||||||
"rlib",
|
"rlib",
|
||||||
@@ -117,6 +118,7 @@ url.workspace = true
|
|||||||
parking_lot.workspace = true
|
parking_lot.workspace = true
|
||||||
lock_api.workspace = true
|
lock_api.workspace = true
|
||||||
hyper-util.workspace = true
|
hyper-util.workspace = true
|
||||||
|
openidconnect.workspace = true
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
nix.workspace = true
|
nix.workspace = true
|
||||||
|
|||||||
@@ -289,6 +289,15 @@ pub fn check(config: &Config) -> Result {
|
|||||||
| _ => (),
|
| _ => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(oidc) = &config.oauth.oidc
|
||||||
|
&& oidc.client_secret.is_none()
|
||||||
|
&& oidc.client_secret_file.is_none()
|
||||||
|
{
|
||||||
|
return Err!(
|
||||||
|
"Either `client_secret` or `client_secret_file` must be set if OIDC is configured."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+23
-25
@@ -10,7 +10,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use super::Config;
|
use super::Config;
|
||||||
use crate::{Result, implement};
|
use crate::Result;
|
||||||
|
|
||||||
/// The configuration manager is an indirection to reload the configuration for
|
/// The configuration manager is an indirection to reload the configuration for
|
||||||
/// the server while it is running. In order to not burden or clutter the many
|
/// the server while it is running. In order to not burden or clutter the many
|
||||||
@@ -39,28 +39,10 @@ impl Manager {
|
|||||||
active: AtomicPtr::new(Arc::into_raw(config).cast_mut()),
|
active: AtomicPtr::new(Arc::into_raw(config).cast_mut()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for Manager {
|
/// Update the active configuration, returning prior configuration.
|
||||||
fn drop(&mut self) {
|
#[tracing::instrument(skip_all, level = "info")]
|
||||||
let config = self.active.swap(null_mut(), Ordering::AcqRel);
|
pub fn update(&self, config: Config) -> Result<Arc<Config>> {
|
||||||
|
|
||||||
// SAFETY: The active pointer was set using an Arc::into_raw(). We're obliged to
|
|
||||||
// reconstitute that into Arc otherwise it will leak.
|
|
||||||
unsafe { Arc::from_raw(config) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for Manager {
|
|
||||||
type Target = Arc<Config>;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the active configuration, returning prior configuration.
|
|
||||||
#[implement(Manager)]
|
|
||||||
#[tracing::instrument(skip_all, level = "info")]
|
|
||||||
pub fn update(&self, config: Config) -> Result<Arc<Config>> {
|
|
||||||
let config = Arc::new(config);
|
let config = Arc::new(config);
|
||||||
let new = Arc::into_raw(config);
|
let new = Arc::into_raw(config);
|
||||||
let old = self.active.swap(new.cast_mut(), Ordering::AcqRel);
|
let old = self.active.swap(new.cast_mut(), Ordering::AcqRel);
|
||||||
@@ -68,10 +50,9 @@ pub fn update(&self, config: Config) -> Result<Arc<Config>> {
|
|||||||
// SAFETY: The old active pointer was set using an Arc::into_raw(). We're
|
// SAFETY: The old active pointer was set using an Arc::into_raw(). We're
|
||||||
// obliged to reconstitute that into Arc otherwise it will leak.
|
// obliged to reconstitute that into Arc otherwise it will leak.
|
||||||
Ok(unsafe { Arc::from_raw(old) })
|
Ok(unsafe { Arc::from_raw(old) })
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(Manager)]
|
fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
|
||||||
fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
|
|
||||||
let config = self.active.load(Ordering::Acquire);
|
let config = self.active.load(Ordering::Acquire);
|
||||||
|
|
||||||
// Branch taken after config reload or first access by this thread.
|
// Branch taken after config reload or first access by this thread.
|
||||||
@@ -99,6 +80,23 @@ fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
|
|||||||
// of old configs rather than discarding at the earliest opportunity; the odds
|
// of old configs rather than discarding at the earliest opportunity; the odds
|
||||||
// of this scenario are thus astronomical.
|
// of this scenario are thus astronomical.
|
||||||
unsafe { std::mem::transmute(config) }
|
unsafe { std::mem::transmute(config) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Manager {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let config = self.active.swap(null_mut(), Ordering::AcqRel);
|
||||||
|
|
||||||
|
// SAFETY: The active pointer was set using an Arc::into_raw(). We're obliged to
|
||||||
|
// reconstitute that into Arc otherwise it will leak.
|
||||||
|
unsafe { Arc::from_raw(config) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for Manager {
|
||||||
|
type Target = Arc<Config>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
|
|||||||
+236
-14
@@ -17,10 +17,12 @@ use either::{
|
|||||||
use figment::providers::{Env, Format, Toml};
|
use figment::providers::{Env, Format, Toml};
|
||||||
pub use figment::{Figment, value::Value as FigmentValue};
|
pub use figment::{Figment, value::Value as FigmentValue};
|
||||||
use lettre::message::Mailbox;
|
use lettre::message::Mailbox;
|
||||||
|
use openidconnect::{ClientId, ClientSecret, Scope};
|
||||||
use regex::RegexSet;
|
use regex::RegexSet;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId,
|
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId,
|
||||||
api::client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
|
api::client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
|
||||||
|
profile::ProfileFieldName,
|
||||||
serde::Base64,
|
serde::Base64,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize, de::IgnoredAny};
|
use serde::{Deserialize, Serialize, de::IgnoredAny};
|
||||||
@@ -375,7 +377,7 @@ pub struct Config {
|
|||||||
#[serde(default = "default_max_request_size")]
|
#[serde(default = "default_max_request_size")]
|
||||||
pub max_request_size: usize,
|
pub max_request_size: usize,
|
||||||
|
|
||||||
/// default: 192
|
/// default: 1024
|
||||||
#[serde(default = "default_max_fetch_prev_events")]
|
#[serde(default = "default_max_fetch_prev_events")]
|
||||||
pub max_fetch_prev_events: u16,
|
pub max_fetch_prev_events: u16,
|
||||||
|
|
||||||
@@ -655,19 +657,25 @@ pub struct Config {
|
|||||||
/// even if `recaptcha_site_key` is set.
|
/// even if `recaptcha_site_key` is set.
|
||||||
pub recaptcha_private_site_key: Option<String>,
|
pub recaptcha_private_site_key: Option<String>,
|
||||||
|
|
||||||
/// Policy documents, such as terms and conditions or a privacy policy,
|
/// display: nested
|
||||||
/// which users must agree to when registering an account.
|
|
||||||
///
|
|
||||||
/// Example:
|
|
||||||
/// ```ignore
|
|
||||||
/// [global.registration_terms.privacy_policy]
|
|
||||||
/// en = { name = "Privacy Policy", url = "https://homeserver.example/en/privacy_policy.html" }
|
|
||||||
/// es = { name = "Política de Privacidad", url = "https://homeserver.example/es/privacy_policy.html" }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// default: {}
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub registration_terms: HashMap<String, HashMap<String, TermsDocument>>,
|
pub registration_terms: RegistrationTerms,
|
||||||
|
|
||||||
|
/// display: nested
|
||||||
|
#[serde(default)]
|
||||||
|
pub oauth: OauthConfig,
|
||||||
|
|
||||||
|
/// Controls whether users are allowed to deactivate their own accounts
|
||||||
|
/// through the account management panel or their Matrix clients. Server
|
||||||
|
/// admins can always deactivate users using the relevant admin commands.
|
||||||
|
///
|
||||||
|
/// Note that, in some jurisdictions, you may be legally required to honor
|
||||||
|
/// users who request to deactivate their accounts if you set this option
|
||||||
|
/// to `false`.
|
||||||
|
///
|
||||||
|
/// default: true
|
||||||
|
#[serde(default = "true_fn")]
|
||||||
|
pub allow_deactivation: bool,
|
||||||
|
|
||||||
/// Controls whether encrypted rooms and events are allowed.
|
/// Controls whether encrypted rooms and events are allowed.
|
||||||
#[serde(default = "true_fn")]
|
#[serde(default = "true_fn")]
|
||||||
@@ -781,6 +789,16 @@ pub struct Config {
|
|||||||
/// a substitute for moderation bots.
|
/// a substitute for moderation bots.
|
||||||
pub default_room_acl_deny: Option<Vec<String>>,
|
pub default_room_acl_deny: Option<Vec<String>>,
|
||||||
|
|
||||||
|
/// The number of forward extremities to tolerate in a room before
|
||||||
|
/// attempting to manually squash them with a "dummy event". Setting this
|
||||||
|
/// above 20 will hinder its efficacy, and setting it below 5 will cause
|
||||||
|
/// more dummy events to be sent than necessary (which increases federation
|
||||||
|
/// traffic).
|
||||||
|
///
|
||||||
|
/// default: 10
|
||||||
|
#[serde(default = "default_extremity_threshold")]
|
||||||
|
pub dummy_event_threshold: u8,
|
||||||
|
|
||||||
/// display: nested
|
/// display: nested
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub well_known: WellKnownConfig,
|
pub well_known: WellKnownConfig,
|
||||||
@@ -1651,6 +1669,11 @@ pub struct Config {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub send_messages_from_ignored_users_to_client: bool,
|
pub send_messages_from_ignored_users_to_client: bool,
|
||||||
|
|
||||||
|
/// Send "org.matrix.dummy_event" events to the client. This is a debugging
|
||||||
|
/// option.
|
||||||
|
#[serde(default)]
|
||||||
|
pub send_dummy_events_to_clients: bool,
|
||||||
|
|
||||||
/// Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you
|
/// Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you
|
||||||
/// do not want continuwuity to send outbound requests to. Defaults to
|
/// do not want continuwuity to send outbound requests to. Defaults to
|
||||||
/// RFC1918, unroutable, loopback, multicast, and testnet addresses for
|
/// RFC1918, unroutable, loopback, multicast, and testnet addresses for
|
||||||
@@ -2351,6 +2374,29 @@ pub struct SmtpConfig {
|
|||||||
pub require_email_for_token_registration: bool,
|
pub require_email_for_token_registration: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||||
|
#[config_example_generator(
|
||||||
|
filename = "conduwuit-example.toml",
|
||||||
|
section = "global.registration_terms",
|
||||||
|
optional = "true"
|
||||||
|
)]
|
||||||
|
pub struct RegistrationTerms {
|
||||||
|
/// The language code to provide to clients along with the policy documents.
|
||||||
|
///
|
||||||
|
/// default: "en"
|
||||||
|
#[serde(default = "default_terms_language")]
|
||||||
|
pub language: String,
|
||||||
|
/// Policy documents, such as terms and conditions or a privacy policy,
|
||||||
|
/// which users must agree to when registering an account.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```ignore
|
||||||
|
/// [global.registration_terms.documents]
|
||||||
|
/// privacy_policy = { name = "Privacy Policy", url = "https://homeserver.example/en/privacy_policy.html" }
|
||||||
|
/// ```
|
||||||
|
pub documents: BTreeMap<String, TermsDocument>,
|
||||||
|
}
|
||||||
|
|
||||||
/// A policy document for use with a m.login.terms stage.
|
/// A policy document for use with a m.login.terms stage.
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
pub struct TermsDocument {
|
pub struct TermsDocument {
|
||||||
@@ -2358,6 +2404,172 @@ pub struct TermsDocument {
|
|||||||
pub url: String,
|
pub url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, Deserialize)]
|
||||||
|
#[config_example_generator(
|
||||||
|
filename = "conduwuit-example.toml",
|
||||||
|
section = "global.oauth",
|
||||||
|
optional = "true"
|
||||||
|
)]
|
||||||
|
pub struct OauthConfig {
|
||||||
|
/// The compatibility mode to use for OAuth.
|
||||||
|
///
|
||||||
|
/// - "disabled": OAuth will be unavailable. Users will only be able to log
|
||||||
|
/// in using legacy authentication.
|
||||||
|
/// - "hybrid": OAuth and legacy authentication will both be available. Some
|
||||||
|
/// clients may only use one or the other.
|
||||||
|
/// - "exclusive": Only OAuth will be available. Clients which require
|
||||||
|
/// legacy authentication will be unable to log in.
|
||||||
|
///
|
||||||
|
/// default: "hybrid"
|
||||||
|
compatibility_mode: OAuthMode,
|
||||||
|
|
||||||
|
/// display: hidden
|
||||||
|
pub oidc: Option<OidcConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OauthConfig {
|
||||||
|
#[must_use]
|
||||||
|
pub fn compatibility_mode(&self) -> OAuthMode {
|
||||||
|
if self.oidc.is_some() {
|
||||||
|
OAuthMode::Exclusive
|
||||||
|
} else {
|
||||||
|
self.compatibility_mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum OAuthMode {
|
||||||
|
Disabled,
|
||||||
|
#[default]
|
||||||
|
Hybrid,
|
||||||
|
Exclusive,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OAuthMode {
|
||||||
|
#[must_use]
|
||||||
|
pub fn uiaa_available(&self) -> bool { matches!(self, Self::Disabled | Self::Hybrid) }
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn oauth_available(&self) -> bool { matches!(self, Self::Hybrid | Self::Exclusive) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
|
#[config_example_generator(
|
||||||
|
filename = "conduwuit-example.toml",
|
||||||
|
section = "global.oauth.oidc",
|
||||||
|
optional = "true",
|
||||||
|
subheader = "\
|
||||||
|
# Uncommenting this section will enable Continuwuity's support for
|
||||||
|
# authenticating users using an OpenID Connect-compatible identity provider.
|
||||||
|
# This is referred to as \"delegated authentication\".
|
||||||
|
#
|
||||||
|
# IMPORTANT NOTE: When delegated authentication is active, Continuwuity will behave as if
|
||||||
|
# the `global.oauth.compatibility_mode` setting is set to `exclusive`.
|
||||||
|
# Matrix clients which do not support OAuth login (also referred to as \"next-gen auth\") will \
|
||||||
|
NOT be able
|
||||||
|
# to log in while delegated authentication is active."
|
||||||
|
)]
|
||||||
|
pub struct OidcConfig {
|
||||||
|
/// The OIDC issuer URL. Continuwuity will use OpenID Connect Discovery to
|
||||||
|
/// automatically fetch the identity provider's metadata from this URL.
|
||||||
|
/// Generally you should set this to the base domain your identity provider
|
||||||
|
/// runs on.
|
||||||
|
pub discovery_url: Url,
|
||||||
|
|
||||||
|
/// The OAuth client ID for Continuwuity to use when communicating with the
|
||||||
|
/// identity provider.
|
||||||
|
pub client_id: ClientId,
|
||||||
|
|
||||||
|
/// The OAuth client secret for Continuwuity to use when communicating with
|
||||||
|
/// the identity provider.
|
||||||
|
pub client_secret: Option<ClientSecret>,
|
||||||
|
|
||||||
|
/// A path to a file which Continuwuity will read the client secret from.
|
||||||
|
/// If this option is set, it will override `client_secret`.
|
||||||
|
///
|
||||||
|
/// The server will fail to start if the file cannot be read.
|
||||||
|
pub client_secret_file: Option<PathBuf>,
|
||||||
|
|
||||||
|
/// Additional scopes Continuwuity should request from the IDP. This may be
|
||||||
|
/// necessary to access certain claims. Continuwuity always requests the
|
||||||
|
/// `openid` scope.
|
||||||
|
///
|
||||||
|
/// default: []
|
||||||
|
#[serde(default)]
|
||||||
|
pub additional_scopes: Vec<Scope>,
|
||||||
|
|
||||||
|
/// Whether the user should be prompted to choose a localpart
|
||||||
|
/// when signing in for the first time. If this is `false`, Continuwuity
|
||||||
|
/// will attempt to use the value of the `preferred_username_claim`
|
||||||
|
/// (see below) as the user's localpart. Authentication will
|
||||||
|
/// fail if this claim is missing or is not a valid localpart.
|
||||||
|
///
|
||||||
|
/// default: true
|
||||||
|
#[serde(default = "true_fn")]
|
||||||
|
pub prompt_for_localpart: bool,
|
||||||
|
|
||||||
|
/// The claim to use for the user's localpart, if `prompt_for_localpart` is
|
||||||
|
/// false.
|
||||||
|
///
|
||||||
|
/// default: "preferred_username"
|
||||||
|
#[serde(default = "default_preferred_username_claim")]
|
||||||
|
pub preferred_username_claim: String,
|
||||||
|
|
||||||
|
/// The claim which will be used to set the user's email address,
|
||||||
|
/// either on initial registration or on every login depending on
|
||||||
|
/// the value of `profile_key_import_mode`. Continuwuity assumes that
|
||||||
|
/// the IDP has taken care of verifying that the user controls the email
|
||||||
|
/// address it provides.
|
||||||
|
///
|
||||||
|
/// This option does nothing if SMTP is not configured.
|
||||||
|
///
|
||||||
|
/// If this option is set, and `profile_key_import_mode` is `on_login`,
|
||||||
|
/// users will not be able to change their email addresses themselves.
|
||||||
|
///
|
||||||
|
/// default: "email"
|
||||||
|
pub email_claim: Option<String>,
|
||||||
|
|
||||||
|
/// Defines how claims returned from the IDP should be mapped to a user's
|
||||||
|
/// profile data. The profile field named in each key will be set from the
|
||||||
|
/// claim named in the corresponding value when the user first registers,
|
||||||
|
/// and possibly on subsequent logins as well, depending on the value of
|
||||||
|
/// `profile_key_import_mode` (see below).
|
||||||
|
///
|
||||||
|
/// Per-room overrides to the user's display name or avatar will be
|
||||||
|
/// preserved by the import process.
|
||||||
|
///
|
||||||
|
/// SECURITY NOTE: If the `avatar_url` field is set, Continuwuity will
|
||||||
|
/// perform a HTTP GET to the URL in the mapped claim and use the returned
|
||||||
|
/// file as the user's profile picture. Make sure your users are not able
|
||||||
|
/// to set the value of the mapped claim to an arbitrary URL.
|
||||||
|
///
|
||||||
|
/// default: { displayname = "name" }
|
||||||
|
#[serde(default = "default_profile_key_map")]
|
||||||
|
pub profile_key_map: HashMap<String, String>,
|
||||||
|
|
||||||
|
/// When profile keys should be imported from the IDP's claims.
|
||||||
|
///
|
||||||
|
/// - "on_registration": Listed keys will be imported once, when the user
|
||||||
|
/// logs in for the first time and their shadow account is created.
|
||||||
|
/// - "on_login": Listed keys will be imported every time the user logs in.
|
||||||
|
/// Additionally, users will not be able to manually edit any listed keys
|
||||||
|
/// through their Matrix client.
|
||||||
|
///
|
||||||
|
/// default: "on_registration"
|
||||||
|
#[serde(default)]
|
||||||
|
pub profile_key_import_mode: OidcProfileKeyImportMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum OidcProfileKeyImportMode {
|
||||||
|
#[default]
|
||||||
|
OnRegistration,
|
||||||
|
OnLogin,
|
||||||
|
}
|
||||||
|
|
||||||
const DEPRECATED_KEYS: &[&str] = &[
|
const DEPRECATED_KEYS: &[&str] = &[
|
||||||
"cache_capacity",
|
"cache_capacity",
|
||||||
"conduit_cache_capacity_modifier",
|
"conduit_cache_capacity_modifier",
|
||||||
@@ -2549,7 +2761,7 @@ fn default_pusher_timeout() -> u64 { 60 }
|
|||||||
|
|
||||||
fn default_pusher_idle_timeout() -> u64 { 15 }
|
fn default_pusher_idle_timeout() -> u64 { 15 }
|
||||||
|
|
||||||
fn default_max_fetch_prev_events() -> u16 { 192_u16 }
|
fn default_max_fetch_prev_events() -> u16 { 1024 }
|
||||||
|
|
||||||
fn default_max_concurrent_inbound_transactions() -> usize { 150 }
|
fn default_max_concurrent_inbound_transactions() -> usize { 150 }
|
||||||
|
|
||||||
@@ -2652,6 +2864,8 @@ fn default_rocksdb_stats_level() -> u8 { 1 }
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn default_default_room_version() -> RoomVersionId { RoomVersionId::V12 }
|
pub fn default_default_room_version() -> RoomVersionId { RoomVersionId::V12 }
|
||||||
|
|
||||||
|
fn default_extremity_threshold() -> u8 { 10 }
|
||||||
|
|
||||||
fn default_ip_range_denylist() -> Vec<String> {
|
fn default_ip_range_denylist() -> Vec<String> {
|
||||||
vec![
|
vec![
|
||||||
"127.0.0.0/8".to_owned(),
|
"127.0.0.0/8".to_owned(),
|
||||||
@@ -2738,3 +2952,11 @@ fn default_client_response_timeout() -> u64 { 120 }
|
|||||||
fn default_client_shutdown_timeout() -> u64 { 15 }
|
fn default_client_shutdown_timeout() -> u64 { 15 }
|
||||||
|
|
||||||
fn default_sender_shutdown_timeout() -> u64 { 5 }
|
fn default_sender_shutdown_timeout() -> u64 { 5 }
|
||||||
|
|
||||||
|
fn default_terms_language() -> String { "en".to_owned() }
|
||||||
|
|
||||||
|
fn default_preferred_username_claim() -> String { "preferred_username".to_owned() }
|
||||||
|
|
||||||
|
fn default_profile_key_map() -> HashMap<String, String> {
|
||||||
|
HashMap::from_iter([(ProfileFieldName::DisplayName.to_string(), "name".to_owned())])
|
||||||
|
}
|
||||||
@@ -161,6 +161,7 @@ impl Error {
|
|||||||
match self {
|
match self {
|
||||||
| Self::Federation(origin, error) => format!("Answer from {origin}: {error}"),
|
| Self::Federation(origin, error) => format!("Answer from {origin}: {error}"),
|
||||||
| Self::Ruma(error) => response::ruma_error_message(error),
|
| Self::Ruma(error) => response::ruma_error_message(error),
|
||||||
|
| Self::Request(_, message, _) => message.clone().into_owned(),
|
||||||
| _ => format!("{self}"),
|
| _ => format!("{self}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,11 +73,8 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
|
|||||||
// 413
|
// 413
|
||||||
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
|
||||||
// 405
|
|
||||||
| Unrecognized => StatusCode::METHOD_NOT_ALLOWED,
|
|
||||||
|
|
||||||
// 404
|
// 404
|
||||||
| NotFound => StatusCode::NOT_FOUND,
|
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
||||||
|
|
||||||
// 403
|
// 403
|
||||||
| GuestAccessForbidden
|
| GuestAccessForbidden
|
||||||
|
|||||||
@@ -7,19 +7,16 @@
|
|||||||
|
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
static BRANDING: &str = "continuwuity";
|
pub const BRANDING: &str = "continuwuity";
|
||||||
static WEBSITE: &str = "https://continuwuity.org";
|
pub const ROUTE_PREFIX: &str = "/_continuwuity";
|
||||||
static SEMANTIC: &str = env!("CARGO_PKG_VERSION");
|
pub const WEBSITE: &str = "https://continuwuity.org";
|
||||||
|
pub const SEMANTIC: &str = env!("CARGO_PKG_VERSION");
|
||||||
|
|
||||||
static VERSION: OnceLock<String> = OnceLock::new();
|
static VERSION: OnceLock<String> = OnceLock::new();
|
||||||
static VERSION_UA: OnceLock<String> = OnceLock::new();
|
static VERSION_UA: OnceLock<String> = OnceLock::new();
|
||||||
static USER_AGENT: OnceLock<String> = OnceLock::new();
|
static USER_AGENT: OnceLock<String> = OnceLock::new();
|
||||||
static USER_AGENT_MEDIA: OnceLock<String> = OnceLock::new();
|
static USER_AGENT_MEDIA: OnceLock<String> = OnceLock::new();
|
||||||
|
|
||||||
#[inline]
|
|
||||||
#[must_use]
|
|
||||||
pub fn name() -> &'static str { BRANDING }
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn version() -> &'static str { VERSION.get_or_init(init_version) }
|
pub fn version() -> &'static str { VERSION.get_or_init(init_version) }
|
||||||
|
|
||||||
@@ -32,10 +29,10 @@ pub fn user_agent() -> &'static str { USER_AGENT.get_or_init(init_user_agent) }
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn user_agent_media() -> &'static str { USER_AGENT_MEDIA.get_or_init(init_user_agent_media) }
|
pub fn user_agent_media() -> &'static str { USER_AGENT_MEDIA.get_or_init(init_user_agent_media) }
|
||||||
|
|
||||||
fn init_user_agent() -> String { format!("{}/{} (bot; +{WEBSITE})", name(), version_ua()) }
|
fn init_user_agent() -> String { format!("{BRANDING}/{} (bot; +{WEBSITE})", version_ua()) }
|
||||||
|
|
||||||
fn init_user_agent_media() -> String {
|
fn init_user_agent_media() -> String {
|
||||||
format!("{}/{} (embedbot; facebookexternalhit/1.1; +{WEBSITE})", name(), version_ua())
|
format!("{BRANDING}/{} (embedbot; facebookexternalhit/1.1; +{WEBSITE})", version_ua())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init_version_ua() -> String {
|
fn init_version_ua() -> String {
|
||||||
|
|||||||
@@ -5,7 +5,10 @@ use ruma::{
|
|||||||
events::{MessageLikeEventContent, StateEventContent, TimelineEventType},
|
events::{MessageLikeEventContent, StateEventContent, TimelineEventType},
|
||||||
};
|
};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
|
use serde_json::{
|
||||||
|
json,
|
||||||
|
value::{RawValue as RawJsonValue, to_raw_value},
|
||||||
|
};
|
||||||
|
|
||||||
use super::StateKey;
|
use super::StateKey;
|
||||||
|
|
||||||
@@ -62,7 +65,7 @@ impl Default for PartialPdu {
|
|||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
event_type: "m.room.message".into(),
|
event_type: "m.room.message".into(),
|
||||||
content: Box::<RawJsonValue>::default(),
|
content: to_raw_value(&json!({})).unwrap(),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
state_key: None,
|
state_key: None,
|
||||||
redacts: None,
|
redacts: None,
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
use ruma::{RoomVersionId, canonical_json::redact_content_in_place};
|
use ruma::{RoomVersionId, canonical_json::redact_content_in_place};
|
||||||
use serde_json::{Value as JsonValue, json, value::to_raw_value};
|
use serde_json::{Value as JsonValue, json, value::to_raw_value};
|
||||||
|
|
||||||
use crate::{Err, Result, err, implement};
|
use crate::{Err, Result, err};
|
||||||
|
|
||||||
#[implement(super::Pdu)]
|
impl super::Pdu {
|
||||||
pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) -> Result {
|
pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) -> Result {
|
||||||
let Some(rules) = room_version_id.rules() else {
|
let Some(rules) = room_version_id.rules() else {
|
||||||
return Err!("Cannot redact event for unknown room version {room_version_id}");
|
return Err!("Cannot redact event for unknown room version {room_version_id}");
|
||||||
};
|
};
|
||||||
|
|
||||||
self.unsigned = None;
|
self.unsigned = None;
|
||||||
|
|
||||||
let mut content = serde_json::from_str(self.content.get())
|
let mut content = serde_json::from_str(self.content.get()).map_err(|e| {
|
||||||
.map_err(|e| err!(Request(BadJson("Failed to deserialize content into type: {e}"))))?;
|
err!(Request(BadJson("Failed to deserialize content into type: {e}")))
|
||||||
|
})?;
|
||||||
|
|
||||||
redact_content_in_place(&mut content, &rules.redaction, self.kind.to_string());
|
redact_content_in_place(&mut content, &rules.redaction, self.kind.to_string());
|
||||||
|
|
||||||
@@ -29,4 +30,5 @@ pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) ->
|
|||||||
self.content = to_raw_value(&content).expect("Failed to serialize content");
|
self.content = to_raw_value(&content).expect("Failed to serialize content");
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,23 +4,22 @@ use ruma::MilliSecondsSinceUnixEpoch;
|
|||||||
use serde_json::value::{RawValue as RawJsonValue, Value as JsonValue, to_raw_value};
|
use serde_json::value::{RawValue as RawJsonValue, Value as JsonValue, to_raw_value};
|
||||||
|
|
||||||
use super::Pdu;
|
use super::Pdu;
|
||||||
use crate::{Result, err, implement, result::LogErr};
|
use crate::{Result, err, result::LogErr};
|
||||||
|
|
||||||
/// Set the `unsigned` field of the PDU using only information in the PDU.
|
impl Pdu {
|
||||||
/// Some unsigned data is already set within the database (eg. prev events,
|
/// Set the `unsigned` field of the PDU using only information in the PDU.
|
||||||
/// threads). Once this is done, other data must be calculated from the database
|
/// Some unsigned data is already set within the database (eg. prev events,
|
||||||
/// (eg. relations) This is for server-to-client events.
|
/// threads). Once this is done, other data must be calculated from the
|
||||||
/// Backfill handles this itself.
|
/// database (eg. relations) This is for server-to-client events.
|
||||||
#[implement(Pdu)]
|
/// Backfill handles this itself.
|
||||||
pub fn set_unsigned(&mut self, user_id: Option<&ruma::UserId>) {
|
pub fn set_unsigned(&mut self, user_id: Option<&ruma::UserId>) {
|
||||||
if Some(self.sender.borrow()) != user_id {
|
if Some(self.sender.borrow()) != user_id {
|
||||||
self.remove_transaction_id().log_err().ok();
|
self.remove_transaction_id().log_err().ok();
|
||||||
}
|
}
|
||||||
self.add_age().log_err().ok();
|
self.add_age().log_err().ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(Pdu)]
|
pub fn remove_transaction_id(&mut self) -> Result {
|
||||||
pub fn remove_transaction_id(&mut self) -> Result {
|
|
||||||
use BTreeMap as Map;
|
use BTreeMap as Map;
|
||||||
|
|
||||||
let Some(unsigned) = &self.unsigned else {
|
let Some(unsigned) = &self.unsigned else {
|
||||||
@@ -36,10 +35,9 @@ pub fn remove_transaction_id(&mut self) -> Result {
|
|||||||
.expect("unsigned is valid");
|
.expect("unsigned is valid");
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(Pdu)]
|
pub fn add_age(&mut self) -> Result {
|
||||||
pub fn add_age(&mut self) -> Result {
|
|
||||||
use BTreeMap as Map;
|
use BTreeMap as Map;
|
||||||
|
|
||||||
let mut unsigned: Map<&str, Box<RawJsonValue>> = self
|
let mut unsigned: Map<&str, Box<RawJsonValue>> = self
|
||||||
@@ -58,10 +56,9 @@ pub fn add_age(&mut self) -> Result {
|
|||||||
self.unsigned = Some(to_raw_value(&unsigned)?);
|
self.unsigned = Some(to_raw_value(&unsigned)?);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[implement(Pdu)]
|
pub fn add_relation(&mut self, name: &str, pdu: Option<&Self>) -> Result {
|
||||||
pub fn add_relation(&mut self, name: &str, pdu: Option<&Pdu>) -> Result {
|
|
||||||
use serde_json::Map;
|
use serde_json::Map;
|
||||||
|
|
||||||
let mut unsigned: Map<String, JsonValue> = self
|
let mut unsigned: Map<String, JsonValue> = self
|
||||||
@@ -85,4 +82,5 @@ pub fn add_relation(&mut self, name: &str, pdu: Option<&Pdu>) -> Result {
|
|||||||
self.unsigned = Some(to_raw_value(&unsigned)?);
|
self.unsigned = Some(to_raw_value(&unsigned)?);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Loaded 100 of 301 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user