mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-03 22:01:50 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
35f0904b6f | ||
|
|
750b067344 | ||
|
|
7c90e4b121 | ||
|
|
81336c5e7f | ||
|
|
0714e8674d | ||
|
|
5339cead10 | ||
|
|
c647d9d197 | ||
|
|
cdd6082f28 | ||
|
|
67c96f3626 | ||
|
|
1e74e1b445 | ||
|
|
91d64e63e4 |
No files matched your search
@@ -56,7 +56,7 @@ repos:
|
||||
hooks:
|
||||
- id: cargo-clippy
|
||||
name: cargo clippy
|
||||
entry: cargo clippy --
|
||||
entry: cargo clippy -- -D warnings
|
||||
language: system
|
||||
pass_filenames: false
|
||||
types: [ rust ]
|
||||
|
||||
+1
-2
@@ -385,7 +385,6 @@ features = [
|
||||
"unstable-msc4203",
|
||||
"unstable-msc4310",
|
||||
"unstable-msc4380",
|
||||
"unstable-msc4140",
|
||||
"unstable-msc4143",
|
||||
"unstable-msc4293",
|
||||
"unstable-msc4363",
|
||||
@@ -597,7 +596,7 @@ version = "0.3.18"
|
||||
version = "0.3.0"
|
||||
|
||||
[workspace.dependencies.resolvematrix]
|
||||
version = "1.6.0"
|
||||
version = "1.5.0"
|
||||
features = ["unstable-msc4188"]
|
||||
|
||||
[workspace.dependencies.serde_urlencoded]
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
Add support for delayed events (MSC4140), including the stable endpoints and the `m.delayed_events` capability. The limits can be configured with `delayed_events_max_delay_ms` and `delayed_events_max_scheduled`. Contributed by @eve and @Henry-Hiles.
|
||||
@@ -0,0 +1 @@
|
||||
Continuwuity now understands [MSC4198](https://github.com/matrix-org/matrix-spec-proposals/pull/4198) login hints. With a supported client, this will keep you from being prompted for your user ID redundantly when logging in, and will allow you to easily switch accounts if you open the account manager while logged into your client as a different user. Contributed by @ginger.
|
||||
@@ -0,0 +1 @@
|
||||
When logging in with an OIDC identity provider, if Continuwuity knows the ID of the user trying to log in, it will pass their localpart on to the IDP with the `login_hint` query parameter.
|
||||
+17
-16
@@ -813,19 +813,6 @@
|
||||
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
|
||||
#forget_forced_upon_leave = false
|
||||
|
||||
# The maximum delay in milliseconds for delayed events (MSC4140). Setting
|
||||
# this or `delayed_events_max_scheduled` to 0 disables delayed events.
|
||||
#
|
||||
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_DELAY_MS
|
||||
#delayed_events_max_delay_ms = 604800000
|
||||
|
||||
# The maximum number of delayed events each user can have scheduled at
|
||||
# once. Setting this or `delayed_events_max_delay_ms` to 0 disables
|
||||
# delayed events.
|
||||
#
|
||||
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_SCHEDULED
|
||||
#delayed_events_max_scheduled = 100
|
||||
|
||||
# Set this to true to require authentication when looking up user profiles
|
||||
# through this server.
|
||||
#
|
||||
@@ -2592,9 +2579,10 @@
|
||||
|
||||
# Additional scopes Continuwuity should request from the IDP. This may be
|
||||
# necessary to access certain claims. Continuwuity always requests the
|
||||
# `openid` scope, regardless of the contents of this option,
|
||||
# and will also request the `profile` scope by default if this option is
|
||||
# not set.
|
||||
# `openid` scope, regardless of the value of this option.
|
||||
#
|
||||
# Defaults to only the `profile` scope, as recommended by the OIDC
|
||||
# specification.
|
||||
#
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
|
||||
#additional_scopes = ["profile"]
|
||||
@@ -2610,6 +2598,19 @@
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_TRUSTED_AUDIENCES
|
||||
#additional_trusted_audiences = []
|
||||
|
||||
# If `true`, Continuwuity will pass on the Matrix ID of the user trying to
|
||||
# log in to the identity provider where applicable.
|
||||
#
|
||||
# If Continuwuity knows the Matrix ID of the user trying to log in, it
|
||||
# will set the authorization URL's `login_hint` query parameter to the
|
||||
# _localpart_ of that ID (everything between the @ sign and the colon).
|
||||
#
|
||||
# Defaults to `true`. Set this to `false` if supplying the `login_hint`
|
||||
# causes your identity provider to behave undesirably.
|
||||
#
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__SUPPLY_LOGIN_HINT
|
||||
#supply_login_hint = true
|
||||
|
||||
# The name of the identity provider. If this is set, the login page's
|
||||
# button reads "Continue with <name>" instead of just "Continue".
|
||||
#
|
||||
|
||||
Generated
+132
-95
@@ -16,35 +16,38 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "2.0.0-beta.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.3.tgz",
|
||||
"integrity": "sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==",
|
||||
"version": "1.11.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz",
|
||||
"integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "2.2.0",
|
||||
"@emnapi/wasi-threads": "1.2.3",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "2.0.0-beta.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.3.tgz",
|
||||
"integrity": "sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==",
|
||||
"version": "1.11.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
|
||||
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/wasi-threads": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
|
||||
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",
|
||||
"integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
@@ -128,13 +131,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rsbuild/core": {
|
||||
"version": "2.3.6",
|
||||
"resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.6.tgz",
|
||||
"integrity": "sha512-IVuWh/0DO6XT8075eCAzxWIcVGA7c4xKggf/VEePq3yXqEiU302n6OVGD7uCxQwPaB4R9ViX4cAqalcQV/sxKQ==",
|
||||
"version": "2.3.7",
|
||||
"resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.7.tgz",
|
||||
"integrity": "sha512-IvJZFEeVGcjeSiSHfMlRxJbyL5+xLGcvkNmD34wmIXo85n0va6b8cnqShmprdUKjvXyzE4dPPB9trRunaUY+mA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@rspack/core": "~2.3.4",
|
||||
"@rspack/core": "~2.3.5",
|
||||
"@swc/helpers": "^0.5.24"
|
||||
},
|
||||
"bin": {
|
||||
@@ -172,32 +175,32 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rspack/binding": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.4.tgz",
|
||||
"integrity": "sha512-wSOT16LVITL/IKeIiLXgN5Q5jZIDqnQ7Gmk+wzKOSZ6OHYNfEBXAKhSJuYtCBq8ovJuGl8cJjdqatAlHE5XKIA==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.5.tgz",
|
||||
"integrity": "sha512-W3x7zw5d/mIH9WhWt4pO9RKYURoqgdUxeLSV5IhDCajnhXdRr7R59u5S2j5ZXzSk3eMGUC0PenfKIIdW7t0ufQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optionalDependencies": {
|
||||
"@rspack/binding-darwin-arm64": "2.3.4",
|
||||
"@rspack/binding-darwin-x64": "2.3.4",
|
||||
"@rspack/binding-linux-arm64-gnu": "2.3.4",
|
||||
"@rspack/binding-linux-arm64-musl": "2.3.4",
|
||||
"@rspack/binding-linux-ppc64-gnu": "2.3.4",
|
||||
"@rspack/binding-linux-riscv64-gnu": "2.3.4",
|
||||
"@rspack/binding-linux-riscv64-musl": "2.3.4",
|
||||
"@rspack/binding-linux-s390x-gnu": "2.3.4",
|
||||
"@rspack/binding-linux-x64-gnu": "2.3.4",
|
||||
"@rspack/binding-linux-x64-musl": "2.3.4",
|
||||
"@rspack/binding-wasm32-wasi": "2.3.4",
|
||||
"@rspack/binding-win32-arm64-msvc": "2.3.4",
|
||||
"@rspack/binding-win32-ia32-msvc": "2.3.4",
|
||||
"@rspack/binding-win32-x64-msvc": "2.3.4"
|
||||
"@rspack/binding-darwin-arm64": "2.3.5",
|
||||
"@rspack/binding-darwin-x64": "2.3.5",
|
||||
"@rspack/binding-linux-arm64-gnu": "2.3.5",
|
||||
"@rspack/binding-linux-arm64-musl": "2.3.5",
|
||||
"@rspack/binding-linux-ppc64-gnu": "2.3.5",
|
||||
"@rspack/binding-linux-riscv64-gnu": "2.3.5",
|
||||
"@rspack/binding-linux-riscv64-musl": "2.3.5",
|
||||
"@rspack/binding-linux-s390x-gnu": "2.3.5",
|
||||
"@rspack/binding-linux-x64-gnu": "2.3.5",
|
||||
"@rspack/binding-linux-x64-musl": "2.3.5",
|
||||
"@rspack/binding-wasm32-wasi": "2.3.5",
|
||||
"@rspack/binding-win32-arm64-msvc": "2.3.5",
|
||||
"@rspack/binding-win32-ia32-msvc": "2.3.5",
|
||||
"@rspack/binding-win32-x64-msvc": "2.3.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@rspack/binding-darwin-arm64": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.4.tgz",
|
||||
"integrity": "sha512-eBD71fbmoJKnxcHD03bukbAIOP5r7nD0Ehs+mUrUQlZ6N53EhuJsTeJ1oYdg5L4GoSeQ+KecCqME81Nm0COLrA==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.5.tgz",
|
||||
"integrity": "sha512-A5XnBdSoJvcYV4t2Y+XJiCF0UZ42nOKE2D0ZlegfErGhzlQG1t3hDOzskSB2fPD3z+w5QeREoclqQ0zFOZyBpw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -209,9 +212,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-darwin-x64": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.4.tgz",
|
||||
"integrity": "sha512-CqdfzTLPVFQCniOy/GDVWbg+rqg31qfdzbFf8NYCzdDkCQg+p15hU2HsckD/1sLsaNB8Y55EjGz4ZyGDny0cHg==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.5.tgz",
|
||||
"integrity": "sha512-iZrweqTIj2cM4f0ADRj6FXn9a0FOpD1Mx/++zrsbrQzmnY0c8wmfpvZ5xA5Zfcq9O6nuUBS6GnhkmoFTgviHwQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -223,9 +226,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-arm64-gnu": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.4.tgz",
|
||||
"integrity": "sha512-T/Y1FYiSegcNc+oHuDOLRGIcc+eSdBnfbS70d51EWQj4+0TG/tlfuqFKeAIL3mnKUV5lDLaTz3vsoD0Sws5Fxw==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.5.tgz",
|
||||
"integrity": "sha512-aWE9V0ZhmclKsJNuO37cxUMLtXMjhLtFzrWDWC82mksUX6qM2rzOpPuye9i/c9NGqyrIH7EFQre8bskJvNHGuQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -240,9 +243,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-arm64-musl": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.4.tgz",
|
||||
"integrity": "sha512-WZHCzZ532UfXFXNU8XyM8jb+I6wddegbs/7IXsyw7xiPwwZX1D/M6iKFVpBYdvKcupUM8bS8Uw2REirR/cERVw==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.5.tgz",
|
||||
"integrity": "sha512-I8ENTXdv7Th/OHEYhL7uu3B7DA9r1oTWSifkGHJtuT1XJ0KDsxoA6ORpYz1R2qIs87l+8+5QUnRH7iWyZrnroA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -257,9 +260,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-ppc64-gnu": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.4.tgz",
|
||||
"integrity": "sha512-WeizqeI6HIh7Ax9w2tlmpTtipJWxXcdgt3QqI3N9LOixymlMD5yMBMZNPqwZ6cHXT9gOQ69SvPcVgMwxsdmceQ==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.5.tgz",
|
||||
"integrity": "sha512-ps5do0cKf4aTBWd+LHqvwm8Gdn7J/gvzmx9pWJhAIThvzii45wJREFjGOzJNxdQl+pzKq8JFuzbShNskCN9k2w==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@@ -274,9 +277,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-riscv64-gnu": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.4.tgz",
|
||||
"integrity": "sha512-h+001Vbq8LyGwPMNkeRWidPOVKwlAbwNPskY3CjNlSw3euHkVchfhM3uo6+1h0GyTtb3rzsWqsfm1kar7m/tiQ==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.5.tgz",
|
||||
"integrity": "sha512-3XXIEMS4SSr1/9wIAGgPT1oj1SzhnlejAG5xeVbGJR5y6iFp/oFKYzUPqyuuzZCkWph2/hJ+Q16sa+BJn1YIkg==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
@@ -291,9 +294,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-riscv64-musl": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.4.tgz",
|
||||
"integrity": "sha512-S1rlaCnNVG5s4WZ9odLsqN3ySh5TEdNTLXWapEK8x3iQl56aLtdvqXTfbJWHWnYLJuS7M1WqnQGdJNdjy2NDsA==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.5.tgz",
|
||||
"integrity": "sha512-z2DbQNcLbUEY9OvUa3gahsHey+dW4acLc9d3QlyJm7TJE//rL9C/XBk4kETvCgtdhqrwBSfWrZfislBPKODjvA==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
@@ -308,9 +311,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-s390x-gnu": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.4.tgz",
|
||||
"integrity": "sha512-0SkgGrgulVMam3xel5dMNKQ+U7BEpCczhF1avGT1DzDVIbMfIOsbb32gApQNSz0E7RfAQ/Pa5eWiA9oyRq7ZMQ==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.5.tgz",
|
||||
"integrity": "sha512-n2UudDpzt9G2AOmycVS7uWRMcNMd2k4ubU4b4SX3FfU/uT6mfSNzuwhBhCi0RSZQAGBU0ombJ+sqw8vKXjGGbw==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
@@ -325,9 +328,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-x64-gnu": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.4.tgz",
|
||||
"integrity": "sha512-q7E6x3rJJ/9fJyLuRe5+KyEPi23BF/xkAU4xCM5VwLkTf+rVyOkDZfu0qOkxmILjrxllQPV+b/ojBL/ZaIeQPw==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.5.tgz",
|
||||
"integrity": "sha512-1sxASGJXg9luaYsFSmAQxSFbUbnMnPA5Mr94yIlLsq4q94sHUIn5YjG1XGcT+cPhUYF9fHkCsKRmQlzrN9fR8A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -342,9 +345,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-linux-x64-musl": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.4.tgz",
|
||||
"integrity": "sha512-rey4Tyasui/WeMn6KfhH5xyZGOMt+Ny+GDK7nGh9TSz/cb3/bisxqGzpbu6GJK8leDmTUDD5ZdpODexytA5rzQ==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.5.tgz",
|
||||
"integrity": "sha512-/S4pe1wAo8CBTs0X8DNKu1ZOJ2vQcnThLBKS2CxOPiuQXI7UfAsJCEABBoa8yCrZANWh63fJ90UwLb/s245Gsw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -359,9 +362,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-wasm32-wasi": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.4.tgz",
|
||||
"integrity": "sha512-sDt2MSXZrIaMBa6UaEqmXEqebwpTOPAXLdo9CYJ2Fa9FJWP4TCYbn30mbvV38ZC2n5YX411DRbjck+s97CceIg==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.5.tgz",
|
||||
"integrity": "sha512-GQnswrv6AyBdDCcTy8dTVhD0JqnvmgewzPz6qnOYWGKxpCY99Bv6FL4jvxI1yh64Uk3ykEfbwhrPnaA8Px4KJA==",
|
||||
"cpu": [
|
||||
"wasm32"
|
||||
],
|
||||
@@ -369,15 +372,49 @@
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/core": "2.0.0-beta.3",
|
||||
"@emnapi/runtime": "2.0.0-beta.3",
|
||||
"@emnapi/core": "2.0.0-beta.4",
|
||||
"@emnapi/runtime": "2.0.0-beta.4",
|
||||
"@napi-rs/wasm-runtime": "1.2.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@rspack/binding-wasm32-wasi/node_modules/@emnapi/core": {
|
||||
"version": "2.0.0-beta.4",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.4.tgz",
|
||||
"integrity": "sha512-AhU/vMMXtGgLCrWsL3PjZGSpCWXlGETabnyyB2pBUd6h7AMy2toffJO2T7yXOYXtw8FyD6dYK/5b3u5eRK3yhw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "2.2.0",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rspack/binding-wasm32-wasi/node_modules/@emnapi/runtime": {
|
||||
"version": "2.0.0-beta.4",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.4.tgz",
|
||||
"integrity": "sha512-UKxc3beuftD67T1mPCVf0mnwRKOBsq9XrhLCDGGQKsbG9jx6osvGyjIbJm9DsucyUtFSMTV2ZxsjiuTMjEqWkA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rspack/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
|
||||
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rspack/binding-win32-arm64-msvc": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.4.tgz",
|
||||
"integrity": "sha512-24YC1YSodLAJ8VsMQJmJSHCNvHTqK9JP5hj50T50WE8lCHNsNl/rIYXO9V0VlCYT/HshE6EHHzAeKdahiEOtcw==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.5.tgz",
|
||||
"integrity": "sha512-XVKu3Zs5KGr+P5Seh6NtSNU0UQ1GSgSDFANQRZlT1uFZ1NpBCX+9NB8FVZB0hBBoBKI1kU4b0Cr6Df1Xx0K4nQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -389,9 +426,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-win32-ia32-msvc": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.4.tgz",
|
||||
"integrity": "sha512-xmUNu6kgV9lLEkRP1Zb+t6i1Z1ZMEWXmLlMalPx8tHqndz2RflNMBBx6kjB2nAPQBIZgWufwm7dVGS0HKomCmw==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.5.tgz",
|
||||
"integrity": "sha512-ejCqSuctPcOev2dyi0ayZyfIUY3fJdYHYvrTfSVrrGC19TspuRATXu+RLyu3xvB6TrQF3+JEF4KeG4/ZeWuXOg==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@@ -403,9 +440,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/binding-win32-x64-msvc": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.4.tgz",
|
||||
"integrity": "sha512-WY+AkJqpbLtLEZiG1fE7CVJZ54y0qHeCiVmLxGBsh4OOGIDCs6v2Ub5COcPrYVzGJFGyeHUS29dV7JAs93qIHw==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.5.tgz",
|
||||
"integrity": "sha512-IPvkjM3xAwL1z2N4Jp/GBcZUme703uDy5vrP1IMtXJEl/EOLLfwl7cRb4sSzdeOYGDDHs5dPYDcpgP5eRSRauA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -417,13 +454,13 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@rspack/core": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.4.tgz",
|
||||
"integrity": "sha512-T8HGkIjPVDlGlIN8st/ICe8Gfixq8te75g/8crSdNSf8F+6884sBcKNky0CRdfPxao1C5SXV+Vjv1XJTjyu83w==",
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.5.tgz",
|
||||
"integrity": "sha512-4TG6zGTemEU/FU7bymDgeFOO7CRdd7ucn0CmXo+3cG6EhYmY5+hpAFYBRgxDbDuL4Bwo/s5GsgUvZuI7rLqVbQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@rspack/binding": "2.3.4"
|
||||
"@rspack/binding": "2.3.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
@@ -458,22 +495,22 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rspress/core": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.5.tgz",
|
||||
"integrity": "sha512-kzTqrfJ4UiW+RLLHLunoW/rET5Vjb6Qz4YjhEhiWEp4HYM+KxLVhfyYB5aL8af9+mdnwiTaqlu1s+BZGrMD2zw==",
|
||||
"version": "2.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.6.tgz",
|
||||
"integrity": "sha512-a+CBJcslana9Zmr6j2o3RP6O19y+rcyfa8jeDToC1b29e/RGiD+xpAQJF2eBvnjNUHouXARTaFa7pE1myyV0Rg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mdx-js/mdx": "^3.1.1",
|
||||
"@mdx-js/react": "^3.1.1",
|
||||
"@rsbuild/core": "^2.3.3",
|
||||
"@rsbuild/core": "^2.3.7",
|
||||
"@rsbuild/plugin-react": "~2.1.1",
|
||||
"@rspress/shared": "2.1.5",
|
||||
"@rspress/shared": "2.1.6",
|
||||
"@shikijs/rehype": "^4.2.0",
|
||||
"@shikijs/transformers": "^4.2.0",
|
||||
"@types/mdast": "^4.0.4",
|
||||
"@types/react": "^19.3.0",
|
||||
"@unhead/react": "^2.1.18",
|
||||
"@types/react": "^19.3.3",
|
||||
"@unhead/react": "^2.1.19",
|
||||
"body-scroll-lock": "4.0.0-beta.0",
|
||||
"clsx": "2.1.1",
|
||||
"copy-to-clipboard": "^3.3.3",
|
||||
@@ -490,7 +527,7 @@
|
||||
"react-dom": "^19.3.1",
|
||||
"react-lazy-with-preload": "^2.2.1",
|
||||
"react-render-to-markdown": "19.2.0",
|
||||
"react-router-dom": "^7.18.6",
|
||||
"react-router-dom": "^7.18.7",
|
||||
"rehype-external-links": "^3.0.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"remark-cjk-friendly": "^2.3.4",
|
||||
@@ -514,9 +551,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rspress/plugin-client-redirects": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.5.tgz",
|
||||
"integrity": "sha512-vqAi7ynOgVsuwJi7cXwWEF5UgoNhXqGOyBfQubeZHZKWRtdNHRU42P9rG9DZLTss2dZUiDKlVrM2/vNY40t5hw==",
|
||||
"version": "2.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.6.tgz",
|
||||
"integrity": "sha512-lnSIA3oD44PZa0o0r4gvTBBGWeImD3T7D28FRJlzCdrWQX3kOHpyhxd9fCcK9mE32DYItlu/ipsmpSozmDN9ZA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -527,15 +564,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rspress/shared": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.5.tgz",
|
||||
"integrity": "sha512-XXxegxRZ7VPADS2veN9FTNmmLlA65ieydKH0tOhOZbMJC4OJpKbr/d/JS2jxxAO4u+ZmZxbDyEEir83NQHLKIw==",
|
||||
"version": "2.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.6.tgz",
|
||||
"integrity": "sha512-ecHmNItlMsMU5FEf0CeBKZa4XNCE5fpwCED+1/lmcwIhozyBvd4j4Ook/8IyTT3UqgruJDZ2DwQqfyvCW7zmLg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@rsbuild/core": "^2.3.3",
|
||||
"@rsbuild/core": "^2.3.7",
|
||||
"@shikijs/rehype": "^4.2.0",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react": "^19.3.3",
|
||||
"mdast-util-mdx-jsx": "^3.2.2",
|
||||
"unified": "^11.0.5"
|
||||
}
|
||||
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
#-------------------------------------------------------------------------------#
|
||||
# Qodana analysis is configured by qodana.yaml file #
|
||||
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
|
||||
#-------------------------------------------------------------------------------#
|
||||
|
||||
#################################################################################
|
||||
# WARNING: Do not store sensitive information in this file, #
|
||||
# as its contents will be included in the Qodana report. #
|
||||
#################################################################################
|
||||
version: "1.0"
|
||||
|
||||
#Specify inspection profile for code analysis
|
||||
profile:
|
||||
name: qodana.starter
|
||||
|
||||
#Enable inspections
|
||||
#include:
|
||||
# - name: <SomeEnabledInspectionId>
|
||||
|
||||
#Disable inspections
|
||||
#exclude:
|
||||
# - name: <SomeDisabledInspectionId>
|
||||
# paths:
|
||||
# - <path/where/not/run/inspection>
|
||||
|
||||
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
|
||||
#bootstrap: sh ./prepare-qodana.sh
|
||||
|
||||
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
|
||||
#plugins:
|
||||
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
|
||||
|
||||
# Quality gate. Will fail the CI/CD pipeline if any condition is not met
|
||||
# severityThresholds - configures maximum thresholds for different problem severities
|
||||
# testCoverageThresholds - configures minimum code coverage on a whole project and newly added code
|
||||
# Code Coverage is available in Ultimate and Ultimate Plus plans
|
||||
#failureConditions:
|
||||
# severityThresholds:
|
||||
# any: 15
|
||||
# critical: 5
|
||||
# testCoverageThresholds:
|
||||
# fresh: 70
|
||||
# total: 50
|
||||
|
||||
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
|
||||
linter: jetbrains/qodana-<linter>:2026.2
|
||||
@@ -1,20 +1,16 @@
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
time::Duration,
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use axum::extract::State;
|
||||
use conduwuit::{Result, Server, config::experiments::ToggledExperiment};
|
||||
use ruma::{
|
||||
RoomVersionId, UInt,
|
||||
RoomVersionId,
|
||||
api::{
|
||||
OAuthClientScope,
|
||||
client::discovery::get_capabilities::{
|
||||
self,
|
||||
v3::{
|
||||
AdminCapability, Capabilities, DelayedEventsCapability, GetLoginTokenCapability,
|
||||
ProfileFieldsCapability, RoomVersionStability, RoomVersionsCapability,
|
||||
ThirdPartyIdChangesCapability,
|
||||
AdminCapability, Capabilities, GetLoginTokenCapability, ProfileFieldsCapability,
|
||||
RoomVersionStability, RoomVersionsCapability, ThirdPartyIdChangesCapability,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -68,11 +64,6 @@ pub(crate) async fn get_capabilities_route(
|
||||
assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }),
|
||||
);
|
||||
|
||||
capabilities.delayed_events = Some(assign!(DelayedEventsCapability::new(), {
|
||||
max_delay_ms: Some(Duration::from_millis(services.config.delayed_events_max_delay_ms)),
|
||||
max_scheduled: Some(UInt::new_saturating(services.config.delayed_events_max_scheduled)),
|
||||
}));
|
||||
|
||||
capabilities.set(
|
||||
"org.matrix.msc4174.webpush",
|
||||
json!({
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
use axum::extract::State;
|
||||
use conduwuit::{Err, Result};
|
||||
use ruma::{
|
||||
api::client::delayed_events::{
|
||||
get_delayed_event, schedule_delayed_event,
|
||||
update_delayed_event::{self, UpdateAction},
|
||||
},
|
||||
events::TimelineEventType,
|
||||
signatures::MAX_PDU_BYTES,
|
||||
};
|
||||
use serde_json::{Map as JsonMap, Value as JsonValue};
|
||||
use service::rooms::delayed_events::NewDelayedEvent;
|
||||
|
||||
use crate::{Ruma, client_ip::ClientIp};
|
||||
|
||||
/// The largest content we accept for a delayed event, leaving 4 KiB of the PDU
|
||||
/// size limit for the rest of the event (IDs, hashes, signatures, etc).
|
||||
const MAX_CONTENT_BYTES: usize = MAX_PDU_BYTES - 4096;
|
||||
|
||||
/// # `PUT /_matrix/client/v3/rooms/{roomId}/delayed_event/{eventType}/{txnId}`
|
||||
///
|
||||
/// Schedules an event to be sent into a room after a delay.
|
||||
pub(crate) async fn schedule_delayed_event_route(
|
||||
State(services): State<crate::State>,
|
||||
ClientIp(client_ip): ClientIp,
|
||||
body: Ruma<schedule_delayed_event::v3::Request>,
|
||||
) -> Result<schedule_delayed_event::v3::Response> {
|
||||
let sender_user = body.identity.expect_sender_user()?;
|
||||
let sender_device = body.identity.sender_device();
|
||||
|
||||
if services.users.is_suspended(sender_user).await? {
|
||||
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
|
||||
}
|
||||
|
||||
services
|
||||
.users
|
||||
.update_device_last_seen(sender_user, sender_device, client_ip)
|
||||
.await;
|
||||
|
||||
let Some(max_delay) = services.rooms.delayed_events.max_delay() else {
|
||||
return Err!(Request(Forbidden("Delayed events are disabled on this server.")));
|
||||
};
|
||||
|
||||
if body.delay_ms.is_zero() {
|
||||
return Err!(Request(BadJson("delay_ms must be greater than 0.")));
|
||||
}
|
||||
|
||||
if body.delay_ms > max_delay {
|
||||
return Err!(Request(DelayTooLarge(
|
||||
"The requested delay exceeds the maximum of {}ms.",
|
||||
max_delay.as_millis()
|
||||
)));
|
||||
}
|
||||
|
||||
if serde_json::from_str::<JsonMap<String, JsonValue>>(body.content.json().get()).is_err() {
|
||||
return Err!(Request(BadJson("The event content must be a JSON object.")));
|
||||
}
|
||||
|
||||
// The full PDU is size checked again when it is sent.
|
||||
if body.content.json().get().len() > MAX_CONTENT_BYTES {
|
||||
return Err!(Request(TooLarge(
|
||||
"The event content exceeds the maximum of {MAX_CONTENT_BYTES} bytes."
|
||||
)));
|
||||
}
|
||||
|
||||
// Auth is checked again when the event is sent
|
||||
let is_own_membership = body.event_type == TimelineEventType::RoomMember
|
||||
&& body.state_key.as_deref() == Some(sender_user.as_str());
|
||||
if !is_own_membership
|
||||
&& !services
|
||||
.rooms
|
||||
.state_cache
|
||||
.is_joined(sender_user, &body.room_id)
|
||||
.await
|
||||
{
|
||||
return Err!(Request(Forbidden("You are not joined to this room.")));
|
||||
}
|
||||
|
||||
let timestamp =
|
||||
if body.identity.is_appservice() || services.admin.user_is_admin(sender_user).await {
|
||||
body.timestamp
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let body = body.body;
|
||||
let delay_id = services
|
||||
.rooms
|
||||
.delayed_events
|
||||
.schedule(sender_user, sender_device, &body.txn_id, NewDelayedEvent {
|
||||
room_id: body.room_id,
|
||||
event_type: body.event_type,
|
||||
state_key: body.state_key,
|
||||
content: body.content,
|
||||
delay: body.delay_ms,
|
||||
timestamp,
|
||||
sticky_duration_ms: body.sticky_duration_ms,
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(schedule_delayed_event::v3::Response::new(delay_id))
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/client/v1/delayed_events/{delayId}/{action}`
|
||||
///
|
||||
/// Restarts, sends or cancels a scheduled delayed event.
|
||||
pub(crate) async fn update_delayed_event_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<update_delayed_event::v1::Request>,
|
||||
) -> Result<update_delayed_event::v1::Response> {
|
||||
let sender_user = body.identity.expect_sender_user()?;
|
||||
let update_delayed_event::v1::Request { delay_id, action, .. } = body.body;
|
||||
|
||||
// Cancelling is still allowed, since it only stops activity.
|
||||
if action != UpdateAction::Cancel && services.users.is_suspended(sender_user).await? {
|
||||
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
|
||||
}
|
||||
|
||||
services
|
||||
.rooms
|
||||
.delayed_events
|
||||
.update(sender_user, &delay_id, action)
|
||||
.await?;
|
||||
|
||||
Ok(update_delayed_event::v1::Response::new())
|
||||
}
|
||||
|
||||
/// # `GET /_matrix/client/v1/delayed_events/{delayId}`
|
||||
///
|
||||
/// Returns a scheduled or finalized delayed event.
|
||||
pub(crate) async fn get_delayed_event_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_delayed_event::v1::Request>,
|
||||
) -> Result<get_delayed_event::v1::Response> {
|
||||
let sender_user = body.identity.expect_sender_user()?;
|
||||
|
||||
let delayed_event = services
|
||||
.rooms
|
||||
.delayed_events
|
||||
.get(sender_user, &body.delay_id)
|
||||
.await?;
|
||||
|
||||
Ok(get_delayed_event::v1::Response::new(delayed_event))
|
||||
}
|
||||
@@ -7,7 +7,6 @@ pub(super) mod backup;
|
||||
pub(super) mod capabilities;
|
||||
pub(super) mod context;
|
||||
pub(super) mod dehydrated_device;
|
||||
pub(super) mod delayed_events;
|
||||
pub(super) mod device;
|
||||
pub(super) mod directory;
|
||||
pub(super) mod filter;
|
||||
@@ -53,7 +52,6 @@ pub(super) use backup::*;
|
||||
pub(super) use capabilities::*;
|
||||
pub(super) use context::*;
|
||||
pub(super) use dehydrated_device::*;
|
||||
pub(super) use delayed_events::*;
|
||||
pub(super) use device::*;
|
||||
pub(super) use directory::*;
|
||||
pub(super) use filter::*;
|
||||
@@ -77,7 +75,6 @@ pub(super) use report::*;
|
||||
pub(super) use room::*;
|
||||
pub(super) use search::*;
|
||||
pub(super) use send::*;
|
||||
pub use session::handle_login;
|
||||
pub(super) use session::*;
|
||||
pub(super) use space::*;
|
||||
pub(super) use state::*;
|
||||
|
||||
@@ -70,5 +70,9 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value
|
||||
"response_types_supported": ["code"],
|
||||
"revocation_endpoint": endpoint_base.join(TOKEN_REVOKE_PATH).unwrap(),
|
||||
"token_endpoint": endpoint_base.join(TOKEN_PATH).unwrap(),
|
||||
// NOTE: This isn't gated behind an experiment because MSC4198 is extremely simple, only specifying
|
||||
// a couple query parameters and a syntax for login hints.
|
||||
// The actual account-switching behavior it enables is implementation-defined and thus at no risk of drifting away from the MSC.
|
||||
"org.matrix.msc4198.login_hint_types_supported": ["mxid"],
|
||||
})
|
||||
}
|
||||
@@ -29,10 +29,18 @@ pub(crate) async fn get_profile_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_profile::v3::Request>,
|
||||
) -> Result<get_profile::v3::Response> {
|
||||
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
|
||||
return Err!(Request(Unauthorized(
|
||||
"This server requires authentication to access user profiles."
|
||||
)));
|
||||
let querying_user = body
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.sender_user())
|
||||
.into();
|
||||
|
||||
if !services
|
||||
.users
|
||||
.user_can_see_profile(&body.user_id, querying_user)
|
||||
.await
|
||||
{
|
||||
return Err!(Request(Unauthorized("You cannot access this user's profile.")));
|
||||
}
|
||||
|
||||
let Some(profile) = fetch_full_profile(&services, &body.user_id).await else {
|
||||
@@ -46,10 +54,18 @@ pub(crate) async fn get_profile_field_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_profile_field::v3::Request>,
|
||||
) -> Result<get_profile_field::v3::Response> {
|
||||
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
|
||||
return Err!(Request(Unauthorized(
|
||||
"This server requires authentication to access user profiles."
|
||||
)));
|
||||
let querying_user = body
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.sender_user())
|
||||
.into();
|
||||
|
||||
if !services
|
||||
.users
|
||||
.user_can_see_profile(&body.user_id, querying_user)
|
||||
.await
|
||||
{
|
||||
return Err!(Request(Unauthorized("You cannot access this user's profile.")));
|
||||
}
|
||||
|
||||
let value = fetch_profile_field(&services, &body.user_id, body.field.clone()).await?;
|
||||
|
||||
@@ -9,7 +9,7 @@ use service::Services;
|
||||
|
||||
use crate::{Ruma, router::ClientIdentity};
|
||||
|
||||
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous`
|
||||
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous`
|
||||
pub(crate) async fn discover_rendezvous_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<discover_rendezvous::msc4388::Request>,
|
||||
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
|
||||
)))
|
||||
}
|
||||
|
||||
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous`
|
||||
/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
|
||||
pub(crate) async fn create_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<create_rendezvous_session::msc4388::Request>,
|
||||
@@ -32,7 +32,7 @@ pub(crate) async fn create_rendezvous_session_route(
|
||||
services.rendezvous.create_session(body.data.clone())
|
||||
}
|
||||
|
||||
/// `PUT /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}`
|
||||
/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}`
|
||||
pub(crate) async fn update_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<update_rendezvous_session::msc4388::Request>,
|
||||
@@ -45,30 +45,16 @@ pub(crate) async fn update_rendezvous_session_route(
|
||||
)
|
||||
}
|
||||
|
||||
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
|
||||
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
|
||||
pub(crate) async fn get_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
body: Ruma<get_rendezvous_session::msc4388::Request>,
|
||||
) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||
let is_navigation_mode = headers
|
||||
.get_all("Sec-Fetch-Mode")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.any(|mode| {
|
||||
mode.eq_ignore_ascii_case("navigate") || mode.eq_ignore_ascii_case("nested-navigate")
|
||||
});
|
||||
let is_navigation_dest = headers
|
||||
.get_all("Sec-Fetch-Dest")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.any(|dest| {
|
||||
matches!(
|
||||
dest.to_ascii_lowercase().as_str(),
|
||||
"document" | "iframe" | "frame" | "object" | "embed" | "fencedframe"
|
||||
)
|
||||
});
|
||||
if is_navigation_mode || is_navigation_dest {
|
||||
if let Some(mode) = headers.get("Sec-Fetch-Mode")
|
||||
&& let Ok(mode) = mode.to_str()
|
||||
&& mode == "navigate"
|
||||
{
|
||||
return Err!(Request(Forbidden(
|
||||
"Rendezvous sessions do not accept browser navigation requests."
|
||||
)));
|
||||
@@ -77,7 +63,7 @@ pub(crate) async fn get_rendezvous_session_route(
|
||||
services.rendezvous.get_session(&body.id)
|
||||
}
|
||||
|
||||
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
|
||||
/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
|
||||
pub(crate) async fn delete_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<delete_rendezvous_session::msc4388::Request>,
|
||||
|
||||
@@ -559,16 +559,15 @@ pub(crate) async fn create_room_route(
|
||||
match services
|
||||
.rooms
|
||||
.timeline
|
||||
.send_timeline_event(
|
||||
PartialPdu {
|
||||
event_type: event_type.to_string().into(),
|
||||
content: content.into_json(),
|
||||
state_key: Some(state_key.into()),
|
||||
..Default::default()
|
||||
},
|
||||
.send_state_event_for_key(
|
||||
sender_user,
|
||||
&room_id,
|
||||
&state_lock,
|
||||
&event_type,
|
||||
&content,
|
||||
&state_key,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.boxed()
|
||||
.await
|
||||
|
||||
+14
-2
@@ -40,8 +40,20 @@ pub(crate) async fn send_message_event_route(
|
||||
.update_device_last_seen(sender_user, sender_device, client_ip)
|
||||
.await;
|
||||
|
||||
// Forbid m.room.encrypted if encryption is disabled
|
||||
if MessageLikeEventType::RoomEncrypted == body.event_type && !services.config.allow_encryption
|
||||
{
|
||||
return Err!(Request(Forbidden("Encryption has been disabled")));
|
||||
}
|
||||
|
||||
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
|
||||
|
||||
if body.event_type == MessageLikeEventType::CallInvite
|
||||
&& services.rooms.directory.is_public_room(&body.room_id).await
|
||||
{
|
||||
return Err!(Request(Forbidden("Room call invites are not allowed in public rooms")));
|
||||
}
|
||||
|
||||
// Check if this is a new transaction id
|
||||
if let Ok(response) = services
|
||||
.transactions
|
||||
@@ -79,7 +91,7 @@ pub(crate) async fn send_message_event_route(
|
||||
let event_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.send_timeline_event(
|
||||
.build_and_append_pdu(
|
||||
PartialPdu {
|
||||
event_type: body.event_type.clone().into(),
|
||||
content,
|
||||
@@ -96,7 +108,7 @@ pub(crate) async fn send_message_event_route(
|
||||
..Default::default()
|
||||
},
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
Some(&body.room_id),
|
||||
&state_lock,
|
||||
)
|
||||
.await?;
|
||||
|
||||
+14
-29
@@ -8,7 +8,6 @@ use conduwuit::{
|
||||
};
|
||||
use conduwuit_service::Services;
|
||||
use futures::StreamExt;
|
||||
use lettre::Address;
|
||||
use ruma::{
|
||||
OwnedUserId, UserId,
|
||||
api::client::{
|
||||
@@ -24,7 +23,7 @@ use ruma::{
|
||||
},
|
||||
logout, logout_all,
|
||||
},
|
||||
uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
||||
uiaa::{MatrixUserIdentifier, UserIdentifier},
|
||||
},
|
||||
assign,
|
||||
};
|
||||
@@ -56,43 +55,29 @@ pub(crate) async fn get_login_types_route(
|
||||
]))
|
||||
}
|
||||
|
||||
pub async fn handle_login(
|
||||
async fn handle_login(
|
||||
services: &Services,
|
||||
identifier: Option<&UserIdentifier>,
|
||||
identifier: Option<UserIdentifier>,
|
||||
password: &str,
|
||||
user: Option<&String>,
|
||||
) -> Result<OwnedUserId> {
|
||||
debug!("Got password login type");
|
||||
|
||||
let user_id_or_localpart = match (identifier, user) {
|
||||
| (Some(UserIdentifier::Matrix(MatrixUserIdentifier { user, .. })), _)
|
||||
| (None, Some(user)) => user,
|
||||
| (Some(UserIdentifier::Email(EmailUserIdentifier { address, .. })), _) => {
|
||||
let email = Address::try_from(address.to_owned())
|
||||
.map_err(|_| err!(Request(InvalidParam("Email is malformed"))))?;
|
||||
|
||||
&services
|
||||
.threepid
|
||||
.get_localpart_for_email(&email)
|
||||
.await
|
||||
.ok_or_else(|| err!(Request(Forbidden("Invalid identifier or password"))))?
|
||||
},
|
||||
| _ => {
|
||||
return Err!(Request(InvalidParam("Identifier type not recognized")));
|
||||
},
|
||||
let user_id = if let Some(identifier) = identifier {
|
||||
services.users.lookup_by_identifier(identifier).await
|
||||
} else if let Some(user) = user {
|
||||
UserId::parse_with_server_name(user, &services.config.server_name).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let user_id =
|
||||
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
|
||||
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
|
||||
|
||||
if services.users.is_locked(&user_id).await? {
|
||||
return Err!(Request(UserLocked("This account has been locked.")));
|
||||
}
|
||||
let Some(user_id) = user_id else {
|
||||
return Err!(Request(InvalidUsername("User ID is malformed.")));
|
||||
};
|
||||
|
||||
if services.users.is_login_disabled(&user_id).await {
|
||||
warn!(%user_id, "user attempted to log in with a login-disabled account");
|
||||
return Err!(Request(Forbidden("This account is not permitted to log in.")));
|
||||
return Err!(Request(Forbidden("This account is blocked from logging in.")));
|
||||
}
|
||||
|
||||
services.users.check_password(&user_id, password).await
|
||||
@@ -139,7 +124,7 @@ pub(crate) async fn login_route(
|
||||
let user_id = match &body.login_info {
|
||||
#[allow(deprecated)]
|
||||
| LoginInfo::Password(login::v3::Password { identifier, password, user, .. }) =>
|
||||
handle_login(&services, identifier.as_ref(), password, user.as_ref()).await?,
|
||||
handle_login(&services, identifier.to_owned(), password, user.as_ref()).await?,
|
||||
| LoginInfo::Token(login::v3::Token { token, .. }) => {
|
||||
debug!("Got token login type");
|
||||
if !services.server.config.login_via_existing_session {
|
||||
|
||||
+11
-20
@@ -1,13 +1,7 @@
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
use axum::extract::State;
|
||||
use conduwuit::{
|
||||
Err, Result, err,
|
||||
matrix::{
|
||||
Event,
|
||||
pdu::{PartialPdu, sticky},
|
||||
},
|
||||
};
|
||||
use conduwuit::{Err, Result, err, matrix::Event};
|
||||
use futures::{FutureExt, TryStreamExt};
|
||||
use ruma::{
|
||||
RoomId,
|
||||
@@ -48,22 +42,19 @@ pub(crate) async fn send_state_event_for_key_route(
|
||||
let event_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.send_timeline_event(
|
||||
PartialPdu {
|
||||
event_type: body.event_type.to_string().into(),
|
||||
content: body.body.body.clone().into_json(),
|
||||
state_key: Some(body.state_key.as_str().into()),
|
||||
sticky: body.sticky_duration_ms.map(sticky::object),
|
||||
timestamp: if body.identity.is_appservice() {
|
||||
body.timestamp
|
||||
} else {
|
||||
None
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
.send_state_event_for_key(
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&state_lock,
|
||||
&body.event_type,
|
||||
&body.body.body,
|
||||
&body.state_key,
|
||||
body.sticky_duration_ms,
|
||||
if body.identity.is_appservice() {
|
||||
body.timestamp
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
.boxed()
|
||||
.await?;
|
||||
|
||||
+5
-20
@@ -163,9 +163,6 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&client::update_device_route)
|
||||
.ruma_route(&client::delete_device_route)
|
||||
.ruma_route(&client::delete_devices_route)
|
||||
.ruma_route(&client::schedule_delayed_event_route)
|
||||
.ruma_route(&client::update_delayed_event_route)
|
||||
.ruma_route(&client::get_delayed_event_route)
|
||||
.ruma_route(&client::get_tags_route)
|
||||
.ruma_route(&client::update_tag_route)
|
||||
.ruma_route(&client::delete_tag_route)
|
||||
@@ -194,23 +191,11 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&client::get_rtc_transports)
|
||||
.ruma_route(&client::get_rtc_transports_unstable)
|
||||
.ruma_route(&client::room_initial_sync_route)
|
||||
.merge(
|
||||
Router::new()
|
||||
.ruma_route(&client::discover_rendezvous_route)
|
||||
.ruma_route(&client::create_rendezvous_session_route)
|
||||
.ruma_route(&client::update_rendezvous_session_route)
|
||||
.ruma_route(&client::get_rendezvous_session_route)
|
||||
.ruma_route(&client::delete_rendezvous_session_route)
|
||||
.layer(axum::middleware::map_response(
|
||||
async |mut response: axum::response::Response| {
|
||||
response.headers_mut().insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
http::HeaderValue::from_static("no-store"),
|
||||
);
|
||||
response
|
||||
},
|
||||
)),
|
||||
)
|
||||
.ruma_route(&client::discover_rendezvous_route)
|
||||
.ruma_route(&client::create_rendezvous_session_route)
|
||||
.ruma_route(&client::update_rendezvous_session_route)
|
||||
.ruma_route(&client::get_rendezvous_session_route)
|
||||
.ruma_route(&client::delete_rendezvous_session_route)
|
||||
.ruma_route(&client::get_authorization_server_metadata_route)
|
||||
.merge(client::oauth::router(state))
|
||||
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
|
||||
|
||||
+3
-17
@@ -11,11 +11,7 @@ use axum::{
|
||||
use conduwuit::{Error, Result, err, error};
|
||||
use ruma::{
|
||||
CanonicalJsonObject,
|
||||
api::{
|
||||
IncomingRequest, IncomingRequestExt,
|
||||
auth_scheme::AuthScheme,
|
||||
error::{DeserializationError, FromHttpRequestError},
|
||||
},
|
||||
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -118,18 +114,8 @@ where
|
||||
.await?;
|
||||
|
||||
// Deserialize the body
|
||||
let body_is_empty = body.is_empty();
|
||||
let body = R::try_from_http_request(request, &borrowed_path).map_err(|e| match e {
|
||||
| FromHttpRequestError::Deserialization(DeserializationError::Json(ref json_err))
|
||||
if body_is_empty || json_err.is_syntax() || json_err.is_eof() =>
|
||||
err!(Request(NotJson(debug_warn!("{e}")))),
|
||||
| FromHttpRequestError::Deserialization(DeserializationError::Utf8(_)) =>
|
||||
err!(Request(NotJson(debug_warn!("{e}")))),
|
||||
| FromHttpRequestError::Deserialization(
|
||||
DeserializationError::Ident(_) | DeserializationError::Query(_),
|
||||
) => err!(Request(InvalidParam(debug_warn!("{e}")))),
|
||||
| _ => err!(Request(BadJson(debug_warn!("{e}")))),
|
||||
})?;
|
||||
let body = R::try_from_http_request(request, &borrowed_path)
|
||||
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
|
||||
|
||||
Ok(Self { body, json_body, identity })
|
||||
}
|
||||
|
||||
+1
-24
@@ -194,10 +194,6 @@ impl CheckAuth for AccessTokenOptional {
|
||||
authentication: Self::Output,
|
||||
query: AuthQueryParams,
|
||||
) -> Result<Self::Identity> {
|
||||
if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::<R>()) {
|
||||
services.rendezvous.check_create_ratelimit(request_ip)?;
|
||||
}
|
||||
|
||||
if let Some(authentication) = authentication {
|
||||
check_access_token(
|
||||
services,
|
||||
@@ -282,11 +278,6 @@ impl CheckAuth for NoAccessToken {
|
||||
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
|
||||
})?;
|
||||
|
||||
let is_rendezvous_session = is_rendezvous_session_route(TypeId::of::<R>());
|
||||
if R::RATE_LIMITED && is_rendezvous_session {
|
||||
services.rendezvous.check_session_ratelimit(request_ip)?;
|
||||
}
|
||||
|
||||
if let Some(authentication) = authentication {
|
||||
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
||||
OAuthClientScope::ApiFullAccess,
|
||||
@@ -294,7 +285,7 @@ impl CheckAuth for NoAccessToken {
|
||||
.await
|
||||
.map(Some)
|
||||
} else {
|
||||
if R::RATE_LIMITED && !is_rendezvous_session {
|
||||
if R::RATE_LIMITED {
|
||||
check_unauthenticated_request_ratelimiting(services, request_ip)?;
|
||||
}
|
||||
|
||||
@@ -460,20 +451,6 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result<Regi
|
||||
Ok(appservice_info)
|
||||
}
|
||||
|
||||
fn is_rendezvous_create_route(route: TypeId) -> bool {
|
||||
route == TypeId::of::<client::rendezvous::discover_rendezvous::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::create_rendezvous_session::msc4388::Request>()
|
||||
}
|
||||
|
||||
fn is_rendezvous_session_route(route: TypeId) -> bool {
|
||||
route == TypeId::of::<client::rendezvous::get_rendezvous_session::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::update_rendezvous_session::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::delete_rendezvous_session::msc4388::Request>()
|
||||
}
|
||||
|
||||
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
|
||||
if services
|
||||
.config
|
||||
|
||||
+33
-42
@@ -920,21 +920,6 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub forget_forced_upon_leave: bool,
|
||||
|
||||
/// The maximum delay in milliseconds for delayed events (MSC4140). Setting
|
||||
/// this or `delayed_events_max_scheduled` to 0 disables delayed events.
|
||||
///
|
||||
/// default: 604800000
|
||||
#[serde(default = "default_delayed_events_max_delay_ms")]
|
||||
pub delayed_events_max_delay_ms: u64,
|
||||
|
||||
/// The maximum number of delayed events each user can have scheduled at
|
||||
/// once. Setting this or `delayed_events_max_delay_ms` to 0 disables
|
||||
/// delayed events.
|
||||
///
|
||||
/// default: 100
|
||||
#[serde(default = "default_delayed_events_max_scheduled")]
|
||||
pub delayed_events_max_scheduled: u64,
|
||||
|
||||
/// Set this to true to require authentication when looking up user profiles
|
||||
/// through this server.
|
||||
///
|
||||
@@ -2835,9 +2820,10 @@ pub struct OidcConfig {
|
||||
|
||||
/// Additional scopes Continuwuity should request from the IDP. This may be
|
||||
/// necessary to access certain claims. Continuwuity always requests the
|
||||
/// `openid` scope, regardless of the contents of this option,
|
||||
/// and will also request the `profile` scope by default if this option is
|
||||
/// not set.
|
||||
/// `openid` scope, regardless of the value of this option.
|
||||
///
|
||||
/// Defaults to only the `profile` scope, as recommended by the OIDC
|
||||
/// specification.
|
||||
///
|
||||
/// default: ["profile"]
|
||||
#[serde(default = "default_additional_scopes")]
|
||||
@@ -2855,6 +2841,20 @@ pub struct OidcConfig {
|
||||
#[serde(default)]
|
||||
pub additional_trusted_audiences: BTreeSet<Audience>,
|
||||
|
||||
/// If `true`, Continuwuity will pass on the Matrix ID of the user trying to
|
||||
/// log in to the identity provider where applicable.
|
||||
///
|
||||
/// If Continuwuity knows the Matrix ID of the user trying to log in, it
|
||||
/// will set the authorization URL's `login_hint` query parameter to the
|
||||
/// _localpart_ of that ID (everything between the @ sign and the colon).
|
||||
///
|
||||
/// Defaults to `true`. Set this to `false` if supplying the `login_hint`
|
||||
/// causes your identity provider to behave undesirably.
|
||||
///
|
||||
/// default: true
|
||||
#[serde(default = "true_fn")]
|
||||
pub supply_login_hint: bool,
|
||||
|
||||
/// The name of the identity provider. If this is set, the login page's
|
||||
/// button reads "Continue with <name>" instead of just "Continue".
|
||||
///
|
||||
@@ -3155,41 +3155,41 @@ fn default_database_backups_to_keep() -> i16 { 1 }
|
||||
|
||||
fn default_db_write_buffer_capacity_mb() -> f64 { 48.0 + parallelism_scaled_f64(4.0) }
|
||||
|
||||
fn default_db_cache_capacity_mb() -> f64 { 512.0 + parallelism_scaled_f64(512.0) }
|
||||
fn default_db_cache_capacity_mb() -> f64 { 128.0 + parallelism_scaled_f64(64.0) }
|
||||
|
||||
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(50_000).saturating_add(100_000) }
|
||||
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(10_000).saturating_add(100_000) }
|
||||
|
||||
fn default_cache_capacity_modifier() -> f64 { 1.0 }
|
||||
|
||||
fn default_auth_chain_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(10_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_shorteventid_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(100_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_eventidshort_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(25_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_eventid_pdu_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(25_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_shortstatekey_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(100_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(10_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_statekeyshort_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(10_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_servernameevent_data_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(100_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(100_000).saturating_add(500_000)
|
||||
}
|
||||
|
||||
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(500).clamp(100, 12000) }
|
||||
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(100) }
|
||||
|
||||
fn default_dns_cache_entries() -> u32 { 32768 }
|
||||
|
||||
@@ -3411,20 +3411,15 @@ fn default_admin_log_capture() -> String {
|
||||
|
||||
fn default_admin_room_tag() -> String { "m.server_notice".to_owned() }
|
||||
|
||||
#[must_use]
|
||||
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
|
||||
pub fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
|
||||
fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
|
||||
|
||||
#[must_use]
|
||||
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
|
||||
pub fn parallelism_scaled_u32(val: u32) -> u32 {
|
||||
val.saturating_mul(sys::available_parallelism() as u32)
|
||||
fn parallelism_scaled_u32(val: u32) -> u32 {
|
||||
let val = val.try_into().expect("failed to cast u32 to usize");
|
||||
parallelism_scaled(val).try_into().unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn parallelism_scaled(val: usize) -> usize {
|
||||
val.saturating_mul(sys::available_parallelism())
|
||||
}
|
||||
fn parallelism_scaled(val: usize) -> usize { val.saturating_mul(sys::available_parallelism()) }
|
||||
|
||||
fn default_db_pool_workers() -> usize {
|
||||
sys::available_parallelism()
|
||||
@@ -3464,10 +3459,6 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
|
||||
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
|
||||
}
|
||||
|
||||
fn default_delayed_events_max_delay_ms() -> u64 { 7 * 24 * 60 * 60 * 1000 }
|
||||
|
||||
fn default_delayed_events_max_scheduled() -> u64 { 100 }
|
||||
|
||||
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
|
||||
|
||||
// NOTE: This must be declared *after* every config struct in this file. The
|
||||
|
||||
@@ -171,14 +171,13 @@ impl Error {
|
||||
/// Returns the Matrix error code / error kind
|
||||
#[inline]
|
||||
pub fn kind(&self) -> ErrorKind {
|
||||
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
|
||||
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
|
||||
|
||||
match self {
|
||||
| Self::Federation(_, error) | Self::Ruma(error) =>
|
||||
response::ruma_error_kind(error).clone(),
|
||||
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
||||
| Self::FeatureDisabled(..) => Unrecognized,
|
||||
| Self::Path(_) | Self::Query(_) => InvalidParam,
|
||||
| _ => Unknown,
|
||||
}
|
||||
}
|
||||
@@ -195,7 +194,6 @@ impl Error {
|
||||
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
||||
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
| Self::Conflict(_) => StatusCode::CONFLICT,
|
||||
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
|
||||
| Self::Io(error) => response::io_error_code(error.kind()),
|
||||
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
|
||||
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
|
||||
@@ -73,9 +73,6 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
|
||||
// 413
|
||||
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
|
||||
// 409
|
||||
| ConcurrentWrite => StatusCode::CONFLICT,
|
||||
|
||||
// 404
|
||||
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
||||
|
||||
|
||||
@@ -69,11 +69,9 @@ impl Pdu {
|
||||
|
||||
if context.user_id.is_none_or(|u| u != self.sender()) {
|
||||
unsigned.remove("transaction_id");
|
||||
unsigned.remove("delay_id");
|
||||
}
|
||||
} else {
|
||||
unsigned.remove("transaction_id");
|
||||
unsigned.remove("delay_id");
|
||||
}
|
||||
|
||||
if let Some(expires_at) = self
|
||||
|
||||
@@ -53,9 +53,5 @@ pub fn unstable_features(experiments: &Experiments) -> BTreeMap<String, bool> {
|
||||
// Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354)
|
||||
// Proposal merged, expected for spec v1.20/v2.0
|
||||
("org.matrix.msc4354".to_owned(), true),
|
||||
// Delayed events (https://github.com/matrix-org/matrix-spec-proposals/pull/4140)
|
||||
// Proposal merged, expected for spec v1.20/v2.0
|
||||
("org.matrix.msc4140".to_owned(), true),
|
||||
("org.matrix.msc4140.stable".to_owned(), true),
|
||||
])
|
||||
}
|
||||
@@ -5,7 +5,6 @@ pub type DigestOut = [u8; 256 / 8];
|
||||
/// Sha256 hash (input gather joined by 0xFF bytes)
|
||||
#[must_use]
|
||||
#[tracing::instrument(skip(inputs), level = "trace")]
|
||||
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||
pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut
|
||||
where
|
||||
I: Iterator<Item = T> + 'a,
|
||||
@@ -26,7 +25,6 @@ where
|
||||
/// Sha256 hash (input gather)
|
||||
#[must_use]
|
||||
#[tracing::instrument(skip(inputs), level = "trace")]
|
||||
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||
pub fn concat<'a, T, I>(inputs: I) -> DigestOut
|
||||
where
|
||||
I: Iterator<Item = T> + 'a,
|
||||
@@ -45,7 +43,6 @@ where
|
||||
#[inline]
|
||||
#[must_use]
|
||||
#[tracing::instrument(skip(input), level = "trace")]
|
||||
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||
pub fn hash<T>(input: T) -> DigestOut
|
||||
where
|
||||
T: AsRef<[u8]>,
|
||||
|
||||
@@ -29,7 +29,7 @@ fn descriptor_cf_options(
|
||||
let mut opts = set_table_options(opts, &desc, cache)?;
|
||||
|
||||
opts.set_min_write_buffer_number(1);
|
||||
opts.set_max_write_buffer_number(3);
|
||||
opts.set_max_write_buffer_number(2);
|
||||
opts.set_write_buffer_size(desc.write_size);
|
||||
|
||||
opts.set_target_file_size_base(desc.file_size);
|
||||
|
||||
@@ -543,20 +543,4 @@ pub(super) static MAPS: &[Descriptor] = &[
|
||||
name: "websessionid_session",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "delayid_scheduleddelayedevent",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "delayid_finalizeddelayedevent",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "useriddelayid",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "useridfinalizedtsdelayid",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
];
|
||||
@@ -15,7 +15,6 @@ use opentelemetry_instrumentation_tower::http::server::LayerBuilder as OtelHttpL
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::{
|
||||
catch_panic::CatchPanicLayer,
|
||||
cors::{self, CorsLayer},
|
||||
sensitive_headers::SetSensitiveHeadersLayer,
|
||||
set_header::SetResponseHeaderLayer,
|
||||
timeout::{RequestBodyTimeoutLayer, ResponseBodyTimeoutLayer, TimeoutLayer},
|
||||
@@ -101,7 +100,6 @@ pub(crate) fn build(services: &Arc<Services>) -> Result<(Router, Guard)> {
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
HeaderValue::from_str(&CONDUWUIT_CSP.join(";"))?,
|
||||
))
|
||||
.layer(cors_layer(server))
|
||||
.layer(body_limit_layer(server))
|
||||
.layer(CatchPanicLayer::custom(move |panic| catch_panic(panic, services_.clone())));
|
||||
|
||||
@@ -147,32 +145,6 @@ fn compression_layer(server: &Server) -> tower_http::compression::CompressionLay
|
||||
compression_layer
|
||||
}
|
||||
|
||||
fn cors_layer(_server: &Server) -> CorsLayer {
|
||||
const METHODS: [Method; 7] = [
|
||||
Method::GET,
|
||||
Method::HEAD,
|
||||
Method::PATCH,
|
||||
Method::POST,
|
||||
Method::PUT,
|
||||
Method::DELETE,
|
||||
Method::OPTIONS,
|
||||
];
|
||||
|
||||
let headers: [HeaderName; 5] = [
|
||||
header::ORIGIN,
|
||||
HeaderName::from_lowercase(b"x-requested-with").unwrap(),
|
||||
header::CONTENT_TYPE,
|
||||
header::ACCEPT,
|
||||
header::AUTHORIZATION,
|
||||
];
|
||||
|
||||
CorsLayer::new()
|
||||
.allow_origin(cors::Any)
|
||||
.allow_methods(METHODS)
|
||||
.allow_headers(headers)
|
||||
.max_age(Duration::from_hours(24))
|
||||
}
|
||||
|
||||
/// Methods outside the standard set can never match a route; record them as
|
||||
/// `_OTHER`, as the semantic conventions ask, so clients cannot create new
|
||||
/// metric attribute values.
|
||||
|
||||
@@ -8,7 +8,7 @@ use axum::{
|
||||
extract::State,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use conduwuit::{Result, debug_warn, err, error, info, trace};
|
||||
use conduwuit::{Result, debug, debug_error, debug_warn, err, error, trace};
|
||||
use conduwuit_service::Services;
|
||||
use futures::FutureExt;
|
||||
use http::{Method, StatusCode, Uri};
|
||||
@@ -106,11 +106,11 @@ fn handle_result(method: &Method, uri: &Uri, result: Response) -> Result<Respons
|
||||
let reason = status.canonical_reason().unwrap_or("Unknown Reason");
|
||||
|
||||
if status.is_server_error() {
|
||||
info!(%method, %uri, "{code} {reason}");
|
||||
error!(%method, %uri, "{code} {reason}");
|
||||
} else if status.is_client_error() {
|
||||
info!(%method, %uri, "{code} {reason}");
|
||||
debug_error!(%method, %uri, "{code} {reason}");
|
||||
} else if status.is_redirection() {
|
||||
trace!(%method, %uri, "{code} {reason}");
|
||||
debug!(%method, %uri, "{code} {reason}");
|
||||
} else {
|
||||
trace!(%method, %uri, "{code} {reason}");
|
||||
}
|
||||
|
||||
+30
-2
@@ -1,10 +1,11 @@
|
||||
use std::sync::Arc;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use axum::{Router, response::IntoResponse};
|
||||
use conduwuit::Error;
|
||||
use conduwuit_service::{Services, state, state::Guard};
|
||||
use http::{StatusCode, Uri};
|
||||
use http::{HeaderName, Method, StatusCode, Uri, header};
|
||||
use ruma::api::error::ErrorKind;
|
||||
use tower_http::cors::{self, CorsLayer};
|
||||
|
||||
pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
|
||||
let router = Router::<state::State>::new();
|
||||
@@ -14,6 +15,7 @@ pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
|
||||
// is dropped.
|
||||
let (state, guard) = unsafe { state::create(services.clone()) };
|
||||
let router = conduwuit_api::router::build(router, state)
|
||||
.layer(api_cors_layer())
|
||||
.merge(conduwuit_web::build(services))
|
||||
.fallback(not_found)
|
||||
.with_state(state);
|
||||
@@ -24,3 +26,29 @@ pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
|
||||
async fn not_found(_uri: Uri) -> impl IntoResponse {
|
||||
Error::Request(ErrorKind::Unrecognized, "not found :(".into(), StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
fn api_cors_layer() -> CorsLayer {
|
||||
const METHODS: [Method; 7] = [
|
||||
Method::GET,
|
||||
Method::HEAD,
|
||||
Method::PATCH,
|
||||
Method::POST,
|
||||
Method::PUT,
|
||||
Method::DELETE,
|
||||
Method::OPTIONS,
|
||||
];
|
||||
|
||||
let headers: [HeaderName; 5] = [
|
||||
header::ORIGIN,
|
||||
HeaderName::from_lowercase(b"x-requested-with").unwrap(),
|
||||
header::CONTENT_TYPE,
|
||||
header::ACCEPT,
|
||||
header::AUTHORIZATION,
|
||||
];
|
||||
|
||||
CorsLayer::new()
|
||||
.allow_origin(cors::Any)
|
||||
.allow_methods(METHODS)
|
||||
.allow_headers(headers)
|
||||
.max_age(Duration::from_hours(24))
|
||||
}
|
||||
@@ -3,10 +3,11 @@ use std::{
|
||||
collections::BTreeSet,
|
||||
error::Error,
|
||||
fmt::{Debug, Display},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use regex::regex;
|
||||
use ruma::{OwnedDeviceId, api::OAuthClientScope};
|
||||
use ruma::{OwnedDeviceId, OwnedUserId, api::OAuthClientScope};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
@@ -26,6 +27,8 @@ pub struct AuthorizationCodeQuery {
|
||||
pub code_challenge_method: CodeChallengeMethod,
|
||||
#[serde(default)]
|
||||
pub prompt: Option<Prompt>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -38,6 +41,8 @@ pub struct AuthorizationCodeResponse {
|
||||
pub struct DeviceCodeRequest {
|
||||
pub client_id: String,
|
||||
pub scope: RawScopes,
|
||||
#[serde(default, rename = "org.matrix.msc4198.login_hint")]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -53,6 +58,8 @@ pub struct DeviceCodeResponse {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct DeviceCodeVerifyQuery {
|
||||
pub user_code: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "core::ops::Not::not")]
|
||||
pub ignore_login_hint: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
@@ -174,6 +181,30 @@ impl RawScopes {
|
||||
}
|
||||
}
|
||||
|
||||
pub enum LoginHint {
|
||||
Mxid(OwnedUserId),
|
||||
}
|
||||
|
||||
impl FromStr for LoginHint {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.split_once(':') {
|
||||
| Some(("mxid", user_id)) if let Ok(user_id) = user_id.parse::<OwnedUserId>() =>
|
||||
Ok(Self::Mxid(user_id)),
|
||||
| _ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for LoginHint {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
| Self::Mxid(user_id) => write!(f, "mxid:{user_id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
pub struct OAuthError {
|
||||
pub error: ErrorCode,
|
||||
|
||||
@@ -135,6 +135,7 @@ struct PendingDeviceCodeGrant {
|
||||
requested_scopes: RequestedScopes,
|
||||
client_name: Option<String>,
|
||||
client_id: String,
|
||||
login_hint: Option<String>,
|
||||
requested_at: SystemTime,
|
||||
}
|
||||
|
||||
@@ -165,6 +166,7 @@ pub struct DeviceCodeGrantInfo {
|
||||
pub device_code: String,
|
||||
pub client_metadata: ClientMetadata,
|
||||
pub requested_scopes: RequestedScopes,
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
/// A time-limited grant for a client to perform some sensitive action.
|
||||
@@ -422,6 +424,7 @@ impl Service {
|
||||
requested_scopes,
|
||||
client_name: client_metadata.client_name,
|
||||
client_id: query.client_id,
|
||||
login_hint: query.login_hint,
|
||||
requested_at: SystemTime::now(),
|
||||
};
|
||||
|
||||
@@ -442,7 +445,7 @@ impl Service {
|
||||
&self,
|
||||
supplied_user_code: &str,
|
||||
) -> Option<DeviceCodeGrantInfo> {
|
||||
let (device_code, client_id, requested_scopes) = {
|
||||
let (device_code, client_id, requested_scopes, login_hint) = {
|
||||
let pending_grants = self.pending_device_code_grants.lock();
|
||||
|
||||
let (device_code, grant) = pending_grants
|
||||
@@ -451,7 +454,12 @@ impl Service {
|
||||
matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code)
|
||||
})?;
|
||||
|
||||
(device_code.clone(), grant.client_id.clone(), grant.requested_scopes.clone())
|
||||
(
|
||||
device_code.clone(),
|
||||
grant.client_id.clone(),
|
||||
grant.requested_scopes.clone(),
|
||||
grant.login_hint.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
let client_metadata = self
|
||||
@@ -463,6 +471,7 @@ impl Service {
|
||||
device_code,
|
||||
client_metadata,
|
||||
requested_scopes,
|
||||
login_hint,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+12
-1
@@ -256,7 +256,11 @@ impl Service {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn begin_session(&self, prompt: Option<CoreAuthPrompt>) -> (PendingSession, Url) {
|
||||
pub async fn begin_session(
|
||||
&self,
|
||||
prompt: Option<CoreAuthPrompt>,
|
||||
login_hint: Option<&UserId>,
|
||||
) -> (PendingSession, Url) {
|
||||
let OidcClient { machine, config, .. } =
|
||||
self.client.as_ref().expect("oidc should be configured");
|
||||
let machine = machine.wait().await.read().clone();
|
||||
@@ -276,6 +280,13 @@ impl Service {
|
||||
auth_url = auth_url.add_prompt(prompt);
|
||||
}
|
||||
|
||||
if let Some(user_id) = login_hint
|
||||
&& config.supply_login_hint
|
||||
{
|
||||
auth_url = auth_url
|
||||
.set_login_hint(openidconnect::LoginHint::new(user_id.localpart().to_owned()));
|
||||
}
|
||||
|
||||
let (auth_url, csrf_token, nonce) = auth_url.url();
|
||||
|
||||
(PendingSession { pkce_verifier, nonce, csrf_token }, auth_url)
|
||||
|
||||
@@ -1,38 +1,25 @@
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
use conduwuit::{
|
||||
Err, Error, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils,
|
||||
};
|
||||
use governor::{
|
||||
DefaultKeyedRateLimiter, Quota, RateLimiter,
|
||||
clock::{Clock, DefaultClock},
|
||||
};
|
||||
use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils};
|
||||
use lru_cache::LruCache;
|
||||
use nonzero_ext::nonzero;
|
||||
use ruma::{
|
||||
OwnedTransactionId,
|
||||
api::{
|
||||
client::rendezvous::{
|
||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||
update_rendezvous_session,
|
||||
},
|
||||
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
|
||||
api::client::rendezvous::{
|
||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||
update_rendezvous_session,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct Service {
|
||||
sessions: SyncMutex<LruCache<String, Session>>,
|
||||
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||
}
|
||||
|
||||
struct Session {
|
||||
data: String,
|
||||
created_at: Instant,
|
||||
created_at: SystemTime,
|
||||
last_sequence_token: String,
|
||||
transaction_sequences: LruCache<OwnedTransactionId, String>,
|
||||
}
|
||||
@@ -40,31 +27,20 @@ struct Session {
|
||||
impl Session {
|
||||
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
|
||||
|
||||
fn new(data: String, sequence_token: String, now: Instant) -> Self {
|
||||
fn new(data: String, sequence_token: String) -> Self {
|
||||
Self {
|
||||
data,
|
||||
created_at: now,
|
||||
created_at: SystemTime::now(),
|
||||
last_sequence_token: sequence_token,
|
||||
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
|
||||
}
|
||||
}
|
||||
|
||||
fn time_remaining(&self, now: Instant) -> Option<Duration> {
|
||||
let age = now.saturating_duration_since(self.created_at);
|
||||
(age < Service::SESSION_MAX_AGE)
|
||||
.then(|| Service::SESSION_MAX_AGE.saturating_sub(age))
|
||||
.filter(|remaining| !remaining.is_zero())
|
||||
}
|
||||
|
||||
fn is_expired(&self, now: Instant) -> bool { self.time_remaining(now).is_none() }
|
||||
}
|
||||
|
||||
impl crate::Service for Service {
|
||||
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
Ok(Arc::new(Self {
|
||||
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
|
||||
create_ratelimiter: RateLimiter::keyed(Self::CREATE_RATELIMIT),
|
||||
session_ratelimiter: RateLimiter::keyed(Self::SESSION_RATELIMIT),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -72,64 +48,25 @@ impl crate::Service for Service {
|
||||
}
|
||||
|
||||
impl Service {
|
||||
const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32));
|
||||
const MAX_DATA_SIZE_BYTES: usize = 4096;
|
||||
const MAX_SESSIONS: usize = 256;
|
||||
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
|
||||
const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32));
|
||||
const TOKEN_LENGTH: usize = 32;
|
||||
|
||||
pub fn check_create_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||
Self::check_ratelimiter(&self.create_ratelimiter, ip)
|
||||
}
|
||||
|
||||
pub fn check_session_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||
Self::check_ratelimiter(&self.session_ratelimiter, ip)
|
||||
}
|
||||
|
||||
fn check_ratelimiter(
|
||||
ratelimiter: &DefaultKeyedRateLimiter<IpAddr>,
|
||||
ip: IpAddr,
|
||||
) -> Result<()> {
|
||||
if let Err(not_until) = ratelimiter.check_key(&ip) {
|
||||
let wait_time = not_until.wait_time_from(DefaultClock::default().now());
|
||||
let mut data = LimitExceededErrorData::new();
|
||||
data.retry_after = Some(RetryAfter::Delay(wait_time));
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::LimitExceeded(data),
|
||||
"Rate limit exceeded.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) }
|
||||
|
||||
fn is_valid_opaque_id(id: &str) -> bool {
|
||||
!id.is_empty()
|
||||
&& id.len() <= 255
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
|
||||
}
|
||||
|
||||
/// Lock and fetch an unexpired rendezvous session.
|
||||
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||
self.lock_session_at(id, Instant::now())
|
||||
}
|
||||
|
||||
fn lock_session_at(
|
||||
&self,
|
||||
id: &str,
|
||||
now: Instant,
|
||||
) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||
// We don't clear out expired sessions manually, the LRU cache will
|
||||
// evict them over time
|
||||
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
|
||||
sessions
|
||||
.get_mut(id)
|
||||
.filter(|session| !session.is_expired(now))
|
||||
.filter(|session| {
|
||||
SystemTime::now()
|
||||
.duration_since(session.created_at)
|
||||
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
|
||||
})
|
||||
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
|
||||
})
|
||||
.map_err(at!(1))
|
||||
@@ -149,7 +86,7 @@ impl Service {
|
||||
|
||||
self.sessions
|
||||
.lock()
|
||||
.insert(id.clone(), Session::new(data, sequence_token.clone(), Instant::now()));
|
||||
.insert(id.clone(), Session::new(data, sequence_token.clone()));
|
||||
|
||||
Ok(create_rendezvous_session::msc4388::Response::new(
|
||||
id,
|
||||
@@ -166,12 +103,6 @@ impl Service {
|
||||
sequence_token: String,
|
||||
data: String,
|
||||
) -> Result<update_rendezvous_session::msc4388::Response> {
|
||||
if !Self::is_valid_opaque_id(transaction.as_str()) {
|
||||
return Err!(Request(InvalidParam(
|
||||
"Transaction ID does not comply with the opaque identifier grammar"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut session = self.lock_session(id)?;
|
||||
|
||||
// If the provided transaction ID was used already, we have to return
|
||||
@@ -206,12 +137,13 @@ impl Service {
|
||||
|
||||
/// Look up a rendezvous session by ID.
|
||||
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||
let now = Instant::now();
|
||||
let session = self.lock_session_at(id, now)?;
|
||||
let session = self.lock_session(id)?;
|
||||
|
||||
let session_time_remaining = session
|
||||
.time_remaining(now)
|
||||
.unwrap_or_else(|| Duration::from_millis(1));
|
||||
let session_age = SystemTime::now()
|
||||
.duration_since(session.created_at)
|
||||
.unwrap_or(Duration::MAX);
|
||||
|
||||
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
|
||||
|
||||
Ok(get_rendezvous_session::msc4388::Response::new(
|
||||
session.last_sequence_token.clone(),
|
||||
@@ -226,12 +158,8 @@ impl Service {
|
||||
id: &str,
|
||||
) -> Result<delete_rendezvous_session::msc4388::Response> {
|
||||
let mut sessions = self.sessions.lock();
|
||||
let now = Instant::now();
|
||||
|
||||
if sessions
|
||||
.remove(id)
|
||||
.is_some_and(|session| !session.is_expired(now))
|
||||
{
|
||||
if sessions.remove(id).is_some() {
|
||||
Ok(delete_rendezvous_session::msc4388::Response::new())
|
||||
} else {
|
||||
Err!(Request(NotFound("Unknown session")))
|
||||
|
||||
@@ -1,584 +0,0 @@
|
||||
mod submission_queue;
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fmt::Write,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use conduwuit::{
|
||||
Err, Error, Result, Server, debug_warn, err, error,
|
||||
matrix::pdu::{PartialPdu, sticky},
|
||||
utils::{
|
||||
self, MutexMap,
|
||||
stream::{ReadyExt, TryIgnore},
|
||||
},
|
||||
};
|
||||
use database::{Deserialized, Ignore, Interfix, Json, Map};
|
||||
use futures::StreamExt;
|
||||
use http::StatusCode;
|
||||
use loole::Sender;
|
||||
use ruma::{
|
||||
DeviceId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedTransactionId,
|
||||
OwnedUserId, TransactionId, UserId,
|
||||
api::{
|
||||
client::delayed_events::{
|
||||
DelayedEvent, DelayedEventCancelled, DelayedEventError, DelayedEventOutcome,
|
||||
DelayedEventSent, FinalizedDelayedEvent as FinalizedDelayedEventData,
|
||||
update_delayed_event::UpdateAction,
|
||||
},
|
||||
error::{ErrorKind, LimitExceededErrorData, RetryAfter, StandardErrorBody},
|
||||
},
|
||||
events::{AnyTimelineEventContent, TimelineEventType, sticky::StickyDurationMs},
|
||||
serde::Raw,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use submission_queue::SubmissionQueue;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{Dep, config, rooms, transactions, users};
|
||||
|
||||
const DELAY_ID_LENGTH: usize = 32;
|
||||
|
||||
/// The retention limits for finalized delayed events recommended by MSC4140.
|
||||
const FINALIZED_RETENTION: Duration = Duration::from_hours(7 * 24);
|
||||
const MAX_FINALIZED_PER_USER: usize = 1000;
|
||||
|
||||
struct Data {
|
||||
delayid_scheduleddelayedevent: Arc<Map>,
|
||||
delayid_finalizeddelayedevent: Arc<Map>,
|
||||
useriddelayid: Arc<Map>,
|
||||
useridfinalizedtsdelayid: Arc<Map>,
|
||||
}
|
||||
|
||||
struct Services {
|
||||
server: Arc<Server>,
|
||||
config: Dep<config::Service>,
|
||||
state: Dep<rooms::state::Service>,
|
||||
timeline: Dep<rooms::timeline::Service>,
|
||||
transactions: Dep<transactions::Service>,
|
||||
users: Dep<users::Service>,
|
||||
}
|
||||
|
||||
pub struct Service {
|
||||
db: Data,
|
||||
services: Services,
|
||||
|
||||
/// Ensures each delayed event is only finalized once.
|
||||
event_locks: MutexMap<String, ()>,
|
||||
transaction_locks: MutexMap<OwnedUserId, ()>,
|
||||
submission_queue: Mutex<SubmissionQueue>,
|
||||
submission_queue_sender: Sender<(SystemTime, String)>,
|
||||
interrupt: Sender<()>,
|
||||
mem_usage: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Service for Service {
|
||||
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
let (sender, receiver) = loole::unbounded();
|
||||
let (interrupt_sender, interrupt_receiver) = loole::bounded(1);
|
||||
|
||||
Ok(Arc::new(Self {
|
||||
db: Data {
|
||||
delayid_scheduleddelayedevent: args.db["delayid_scheduleddelayedevent"].clone(),
|
||||
delayid_finalizeddelayedevent: args.db["delayid_finalizeddelayedevent"].clone(),
|
||||
useriddelayid: args.db["useriddelayid"].clone(),
|
||||
useridfinalizedtsdelayid: args.db["useridfinalizedtsdelayid"].clone(),
|
||||
},
|
||||
services: Services {
|
||||
server: args.server.clone(),
|
||||
config: args.depend::<config::Service>("config"),
|
||||
state: args.depend::<rooms::state::Service>("rooms::state"),
|
||||
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
|
||||
transactions: args.depend::<transactions::Service>("transactions"),
|
||||
users: args.depend::<users::Service>("users"),
|
||||
},
|
||||
event_locks: MutexMap::new(),
|
||||
transaction_locks: MutexMap::new(),
|
||||
submission_queue: Mutex::new(SubmissionQueue::new(receiver, interrupt_receiver)),
|
||||
submission_queue_sender: sender,
|
||||
interrupt: interrupt_sender,
|
||||
mem_usage: AtomicUsize::new(0),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn worker(self: Arc<Self>) -> Result { submission_queue::worker(&self).await }
|
||||
|
||||
fn interrupt(&self) { self.interrupt.try_send(()).ok(); }
|
||||
|
||||
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
|
||||
|
||||
async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result {
|
||||
let mem_usage = self.mem_usage.load(Ordering::Relaxed);
|
||||
writeln!(out, "submission_queue: {mem_usage} bytes")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NewDelayedEvent {
|
||||
pub room_id: OwnedRoomId,
|
||||
pub event_type: TimelineEventType,
|
||||
pub state_key: Option<String>,
|
||||
pub content: Raw<AnyTimelineEventContent>,
|
||||
pub delay: Duration,
|
||||
pub timestamp: Option<MilliSecondsSinceUnixEpoch>,
|
||||
pub sticky_duration_ms: Option<StickyDurationMs>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct ScheduledDelayedEvent {
|
||||
user_id: OwnedUserId,
|
||||
room_id: OwnedRoomId,
|
||||
event_type: TimelineEventType,
|
||||
state_key: Option<String>,
|
||||
content: Raw<AnyTimelineEventContent>,
|
||||
delay: Duration,
|
||||
delayed_since: SystemTime,
|
||||
timestamp: Option<MilliSecondsSinceUnixEpoch>,
|
||||
sticky_duration_ms: Option<StickyDurationMs>,
|
||||
}
|
||||
|
||||
impl ScheduledDelayedEvent {
|
||||
fn send_time(&self) -> SystemTime {
|
||||
self.delayed_since
|
||||
.checked_add(self.delay)
|
||||
.unwrap_or(self.delayed_since)
|
||||
}
|
||||
|
||||
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
|
||||
DelayedEvent::new(
|
||||
delay_id,
|
||||
self.room_id,
|
||||
self.event_type,
|
||||
self.state_key,
|
||||
self.content,
|
||||
self.delay,
|
||||
MilliSecondsSinceUnixEpoch::from_system_time(self.delayed_since)
|
||||
.unwrap_or_else(MilliSecondsSinceUnixEpoch::now),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct FinalizedDelayedEvent {
|
||||
event: ScheduledDelayedEvent,
|
||||
finalized: FinalizedDelayedEventData,
|
||||
}
|
||||
|
||||
impl FinalizedDelayedEvent {
|
||||
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
|
||||
let mut event = self.event.into_delayed_event(delay_id);
|
||||
event.finalized = Some(self.finalized);
|
||||
event
|
||||
}
|
||||
|
||||
fn satisfies(&self, action: &UpdateAction) -> bool {
|
||||
matches!(
|
||||
(action, &self.finalized.outcome),
|
||||
(UpdateAction::Send, DelayedEventOutcome::Sent(_))
|
||||
| (
|
||||
UpdateAction::Cancel,
|
||||
DelayedEventOutcome::Cancelled(_) | DelayedEventOutcome::Error(_)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Service {
|
||||
/// Returns the maximum delay users may request, or `None` if delayed events
|
||||
/// are disabled.
|
||||
#[must_use]
|
||||
pub fn max_delay(&self) -> Option<Duration> {
|
||||
let config = &self.services.config;
|
||||
(config.delayed_events_max_delay_ms > 0 && config.delayed_events_max_scheduled > 0)
|
||||
.then(|| Duration::from_millis(config.delayed_events_max_delay_ms))
|
||||
}
|
||||
|
||||
/// Stores a new delayed event and queues it for sending, returning its
|
||||
/// delay ID. Retries with the same transaction ID return the same delay ID.
|
||||
pub async fn schedule(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
device_id: Option<&DeviceId>,
|
||||
txn_id: &TransactionId,
|
||||
event: NewDelayedEvent,
|
||||
) -> Result<String> {
|
||||
let txn_id: OwnedTransactionId = format!("delayed_event/{txn_id}").into();
|
||||
let _lock = self.transaction_locks.lock(user_id).await;
|
||||
|
||||
if let Ok(response) = self
|
||||
.services
|
||||
.transactions
|
||||
.get_client_txn(user_id, device_id, &txn_id)
|
||||
.await
|
||||
{
|
||||
return utils::string_from_bytes(&response)
|
||||
.map_err(|e| err!(Database("Invalid delay ID in transaction data: {e}")));
|
||||
}
|
||||
|
||||
self.check_scheduled_limit(user_id).await?;
|
||||
|
||||
let delay_id = utils::random_string(DELAY_ID_LENGTH);
|
||||
let event = ScheduledDelayedEvent {
|
||||
user_id: user_id.to_owned(),
|
||||
room_id: event.room_id,
|
||||
event_type: event.event_type,
|
||||
state_key: event.state_key,
|
||||
content: event.content,
|
||||
delay: event.delay,
|
||||
delayed_since: SystemTime::now(),
|
||||
timestamp: event.timestamp,
|
||||
sticky_duration_ms: event.sticky_duration_ms,
|
||||
};
|
||||
let send_time = event.send_time();
|
||||
|
||||
self.db
|
||||
.delayid_scheduleddelayedevent
|
||||
.raw_put(&delay_id, Json(&event));
|
||||
self.db
|
||||
.useriddelayid
|
||||
.put_raw((user_id, delay_id.as_str()), []);
|
||||
self.services.transactions.add_client_txnid(
|
||||
user_id,
|
||||
device_id,
|
||||
&txn_id,
|
||||
delay_id.as_bytes(),
|
||||
);
|
||||
|
||||
self.submission_queue_sender
|
||||
.send((send_time, delay_id.clone()))
|
||||
.map_err(|_| err!("The delayed events worker is not running"))?;
|
||||
|
||||
Ok(delay_id)
|
||||
}
|
||||
|
||||
/// Returns `M_LIMIT_EXCEEDED` if the user already has the maximum number of
|
||||
/// delayed events scheduled, with `Retry-After` set to when the next one is
|
||||
/// due.
|
||||
async fn check_scheduled_limit(&self, user_id: &UserId) -> Result {
|
||||
let max_scheduled = usize::try_from(self.services.config.delayed_events_max_scheduled)
|
||||
.unwrap_or(usize::MAX);
|
||||
|
||||
let send_times: Vec<SystemTime> = self
|
||||
.user_delay_ids(user_id)
|
||||
.filter_map(async |delay_id| {
|
||||
self.get_scheduled(&delay_id)
|
||||
.await
|
||||
.map(|event| event.send_time())
|
||||
})
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
if send_times.len() < max_scheduled {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let retry_after = send_times
|
||||
.iter()
|
||||
.min()
|
||||
.and_then(|time| time.duration_since(SystemTime::now()).ok())
|
||||
.unwrap_or_default();
|
||||
let retry_after = Duration::from_secs(
|
||||
retry_after
|
||||
.as_millis()
|
||||
// MSC4140 requires rounding up to the nearest second.
|
||||
.div_ceil(1000)
|
||||
.try_into()
|
||||
.unwrap_or(u64::MAX),
|
||||
);
|
||||
|
||||
let mut data = LimitExceededErrorData::new();
|
||||
data.retry_after = Some(RetryAfter::Delay(retry_after));
|
||||
|
||||
Err(Error::Request(
|
||||
ErrorKind::LimitExceeded(data),
|
||||
"The maximum number of delayed events has been reached.".into(),
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
))
|
||||
}
|
||||
|
||||
/// Restarts, sends or cancels one of the user's delayed events. Repeating
|
||||
/// an action on an event that was already finalized the same way succeeds,
|
||||
/// and conflicting actions return 409.
|
||||
pub async fn update(&self, user_id: &UserId, delay_id: &str, action: UpdateAction) -> Result {
|
||||
let _lock = self.event_locks.lock(delay_id).await;
|
||||
|
||||
if let Some(mut event) = self.get_scheduled(delay_id).await {
|
||||
if event.user_id != user_id {
|
||||
return Err!(Request(NotFound("No delayed event with this ID was found.")));
|
||||
}
|
||||
|
||||
return match action {
|
||||
| UpdateAction::Restart => {
|
||||
// The worker requeues it when the old send time is reached.
|
||||
event.delayed_since = SystemTime::now();
|
||||
self.db
|
||||
.delayid_scheduleddelayedevent
|
||||
.raw_put(delay_id, Json(&event));
|
||||
Ok(())
|
||||
},
|
||||
| UpdateAction::Send => {
|
||||
// On error, the event stays scheduled, as recommended by
|
||||
// MSC4140.
|
||||
let event_id = self.send(delay_id, &event).await?;
|
||||
self.finalize(
|
||||
delay_id,
|
||||
event,
|
||||
DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
|
||||
)
|
||||
.await;
|
||||
Ok(())
|
||||
},
|
||||
| UpdateAction::Cancel => {
|
||||
self.finalize(
|
||||
delay_id,
|
||||
event,
|
||||
DelayedEventOutcome::Cancelled(DelayedEventCancelled::new()),
|
||||
)
|
||||
.await;
|
||||
Ok(())
|
||||
},
|
||||
| _ => Err!(Request(InvalidParam("Unknown delayed event action."))),
|
||||
};
|
||||
}
|
||||
|
||||
match self.get_finalized(delay_id).await {
|
||||
| Some(finalized) if finalized.event.user_id == user_id =>
|
||||
if finalized.satisfies(&action) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Request(
|
||||
ErrorKind::Unknown,
|
||||
"The delayed event has already been finalized with a different outcome."
|
||||
.into(),
|
||||
StatusCode::CONFLICT,
|
||||
))
|
||||
},
|
||||
| _ => Err!(Request(NotFound("No delayed event with this ID was found."))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one of the user's delayed events, whether scheduled or
|
||||
/// finalized.
|
||||
pub async fn get(&self, user_id: &UserId, delay_id: &str) -> Result<DelayedEvent> {
|
||||
if let Some(event) = self.get_scheduled(delay_id).await
|
||||
&& event.user_id == user_id
|
||||
{
|
||||
return Ok(event.into_delayed_event(delay_id.to_owned()));
|
||||
}
|
||||
|
||||
if let Some(finalized) = self.get_finalized(delay_id).await
|
||||
&& finalized.event.user_id == user_id
|
||||
{
|
||||
return Ok(finalized.into_delayed_event(delay_id.to_owned()));
|
||||
}
|
||||
|
||||
Err!(Request(NotFound("No delayed event with this ID was found.")))
|
||||
}
|
||||
|
||||
/// Removes a user's scheduled delayed events without keeping them for
|
||||
/// lookup, for account deactivation.
|
||||
pub async fn remove_all_for_user(&self, user_id: &UserId) {
|
||||
self.user_delay_ids(user_id)
|
||||
.for_each(async |delay_id| {
|
||||
let _lock = self.event_locks.lock(delay_id.as_str()).await;
|
||||
self.db
|
||||
.delayid_scheduleddelayedevent
|
||||
.remove(delay_id.as_str());
|
||||
self.db.useriddelayid.del((user_id, delay_id.as_str()));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Sends the delayed event if it is due, otherwise returns its send time.
|
||||
/// Called by the worker, which records any error on the finalized event as
|
||||
/// there is no client to return it to.
|
||||
async fn send_if_due(&self, delay_id: &str) -> Option<SystemTime> {
|
||||
let _lock = self.event_locks.lock(delay_id).await;
|
||||
|
||||
let event = self.get_scheduled(delay_id).await?;
|
||||
|
||||
let send_time = event.send_time();
|
||||
if send_time > SystemTime::now() {
|
||||
return Some(send_time);
|
||||
}
|
||||
|
||||
let outcome = match self.send(delay_id, &event).await {
|
||||
| Ok(event_id) => DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
|
||||
| Err(error) => {
|
||||
debug_warn!(%delay_id, %error, "Failed to send delayed event");
|
||||
let error = StandardErrorBody::new(error.kind(), error.message());
|
||||
DelayedEventOutcome::Error(DelayedEventError::new(error))
|
||||
},
|
||||
};
|
||||
self.finalize(delay_id, event, outcome).await;
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Sends the delayed event into its room with the same checks as a normal
|
||||
/// send, using the room state at the time of sending.
|
||||
async fn send(&self, delay_id: &str, event: &ScheduledDelayedEvent) -> Result<OwnedEventId> {
|
||||
if self.services.users.is_suspended(&event.user_id).await? {
|
||||
return Err!(Request(UserSuspended(
|
||||
"You cannot perform this action while suspended."
|
||||
)));
|
||||
}
|
||||
|
||||
let content = event.content.clone().into_json();
|
||||
|
||||
let redacts = (event.event_type == TimelineEventType::RoomRedaction)
|
||||
.then(|| serde_json::from_str::<MaybeRedaction>(content.get()).ok())
|
||||
.flatten()
|
||||
.and_then(|redaction| redaction.redacts);
|
||||
|
||||
let mut unsigned = BTreeMap::new();
|
||||
unsigned.insert("delay_id".to_owned(), delay_id.into());
|
||||
|
||||
let partial_pdu = PartialPdu {
|
||||
event_type: event.event_type.clone(),
|
||||
content,
|
||||
state_key: event.state_key.clone().map(Into::into),
|
||||
timestamp: event.timestamp,
|
||||
sticky: event.sticky_duration_ms.map(sticky::object),
|
||||
unsigned: Some(unsigned),
|
||||
redacts,
|
||||
};
|
||||
|
||||
let state_lock = self.services.state.mutex.lock(&event.room_id).await;
|
||||
self.services
|
||||
.timeline
|
||||
.send_timeline_event(partial_pdu, &event.user_id, &event.room_id, &state_lock)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Moves a scheduled delayed event to the finalized events, where it can
|
||||
/// still be looked up until it is pruned.
|
||||
async fn finalize(
|
||||
&self,
|
||||
delay_id: &str,
|
||||
event: ScheduledDelayedEvent,
|
||||
outcome: DelayedEventOutcome,
|
||||
) {
|
||||
let user_id = event.user_id.clone();
|
||||
let finalized_ts = MilliSecondsSinceUnixEpoch::now();
|
||||
|
||||
self.db.useriddelayid.del((&user_id, delay_id));
|
||||
self.db.delayid_scheduleddelayedevent.remove(delay_id);
|
||||
self.db
|
||||
.useridfinalizedtsdelayid
|
||||
.put_raw((&user_id, u64::from(finalized_ts.get()), delay_id), []);
|
||||
self.db.delayid_finalizeddelayedevent.raw_put(
|
||||
delay_id,
|
||||
Json(FinalizedDelayedEvent {
|
||||
event,
|
||||
finalized: FinalizedDelayedEventData::new(outcome, finalized_ts),
|
||||
}),
|
||||
);
|
||||
|
||||
self.limit_finalized(&user_id).await;
|
||||
}
|
||||
|
||||
/// Removes the user's oldest finalized delayed events beyond
|
||||
/// [`MAX_FINALIZED_PER_USER`].
|
||||
async fn limit_finalized(&self, user_id: &UserId) {
|
||||
let prefix = (user_id, Interfix);
|
||||
let count = self
|
||||
.db
|
||||
.useridfinalizedtsdelayid
|
||||
.keys_prefix_raw(&prefix)
|
||||
.count()
|
||||
.await;
|
||||
|
||||
self.db
|
||||
.useridfinalizedtsdelayid
|
||||
.keys_prefix(&prefix)
|
||||
.ignore_err()
|
||||
.take(count.saturating_sub(MAX_FINALIZED_PER_USER))
|
||||
.ready_for_each(|(_, finalized_ts, delay_id): (Ignore, u64, &str)| {
|
||||
self.remove_finalized(user_id, finalized_ts, delay_id);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
fn remove_finalized(&self, user_id: &UserId, finalized_ts: u64, delay_id: &str) {
|
||||
self.db
|
||||
.useridfinalizedtsdelayid
|
||||
.del((user_id, finalized_ts, delay_id));
|
||||
self.db.delayid_finalizeddelayedevent.remove(delay_id);
|
||||
}
|
||||
|
||||
/// Removes finalized delayed events older than [`FINALIZED_RETENTION`].
|
||||
/// Called periodically by the worker.
|
||||
async fn prune_finalized(&self) {
|
||||
let Some(cutoff) = SystemTime::now()
|
||||
.checked_sub(FINALIZED_RETENTION)
|
||||
.and_then(MilliSecondsSinceUnixEpoch::from_system_time)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.db
|
||||
.delayid_finalizeddelayedevent
|
||||
.stream::<'_, &str, FinalizedDelayedEvent>()
|
||||
.ignore_err()
|
||||
.ready_filter(|(_, event)| event.finalized.finalized_ts < cutoff)
|
||||
.ready_for_each(|(delay_id, event)| {
|
||||
let finalized_ts = u64::from(event.finalized.finalized_ts.get());
|
||||
self.remove_finalized(&event.event.user_id, finalized_ts, delay_id);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn get_scheduled(&self, delay_id: &str) -> Option<ScheduledDelayedEvent> {
|
||||
self.db
|
||||
.delayid_scheduleddelayedevent
|
||||
.get(delay_id)
|
||||
.await
|
||||
.deserialized()
|
||||
.inspect_err(|e| {
|
||||
if !e.is_not_found() {
|
||||
error!(%delay_id, "Invalid scheduled delayed event in the database: {e}");
|
||||
}
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
async fn get_finalized(&self, delay_id: &str) -> Option<FinalizedDelayedEvent> {
|
||||
self.db
|
||||
.delayid_finalizeddelayedevent
|
||||
.get(delay_id)
|
||||
.await
|
||||
.deserialized()
|
||||
.inspect_err(|e| {
|
||||
if !e.is_not_found() {
|
||||
error!(%delay_id, "Invalid finalized delayed event in the database: {e}");
|
||||
}
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Streams the delay IDs of the user's scheduled delayed events.
|
||||
fn user_delay_ids<'a>(
|
||||
&'a self,
|
||||
user_id: &'a UserId,
|
||||
) -> impl futures::Stream<Item = String> + Send + 'a {
|
||||
self.db
|
||||
.useriddelayid
|
||||
.keys_prefix(&(user_id, Interfix))
|
||||
.ignore_err()
|
||||
.map(|(_, delay_id): (Ignore, &str)| delay_id.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MaybeRedaction {
|
||||
redacts: Option<OwnedEventId>,
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
use std::{
|
||||
cmp::Reverse,
|
||||
collections::BinaryHeap,
|
||||
sync::{Arc, atomic::Ordering},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
use conduwuit::{Result, utils::stream::TryIgnore};
|
||||
use futures::StreamExt;
|
||||
use loole::Receiver;
|
||||
use tokio::{
|
||||
select,
|
||||
time::{MissedTickBehavior, interval, sleep},
|
||||
};
|
||||
|
||||
use super::{DELAY_ID_LENGTH, ScheduledDelayedEvent, Service};
|
||||
|
||||
const PRUNE_INTERVAL: Duration = Duration::from_hours(1);
|
||||
|
||||
pub(super) struct SubmissionQueue {
|
||||
receiver: Receiver<(SystemTime, String)>,
|
||||
interrupt: Receiver<()>,
|
||||
queue: BinaryHeap<(Reverse<SystemTime>, String)>,
|
||||
}
|
||||
|
||||
impl SubmissionQueue {
|
||||
pub(super) fn new(receiver: Receiver<(SystemTime, String)>, interrupt: Receiver<()>) -> Self {
|
||||
Self {
|
||||
receiver,
|
||||
interrupt,
|
||||
queue: BinaryHeap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn worker(service: &Arc<Service>) -> Result {
|
||||
let mut queue = service
|
||||
.submission_queue
|
||||
.try_lock()
|
||||
.expect("only one delayed events worker should be running");
|
||||
let receiver = queue.receiver.clone();
|
||||
let interrupt = queue.interrupt.clone();
|
||||
|
||||
let scheduled: Vec<_> = service
|
||||
.db
|
||||
.delayid_scheduleddelayedevent
|
||||
.stream::<'_, &str, ScheduledDelayedEvent>()
|
||||
.ignore_err()
|
||||
.map(|(delay_id, event)| (Reverse(event.send_time()), delay_id.to_owned()))
|
||||
.collect()
|
||||
.await;
|
||||
queue.queue.extend(scheduled);
|
||||
|
||||
let mut prune = interval(PRUNE_INTERVAL);
|
||||
prune.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
|
||||
loop {
|
||||
let mem_usage = queue
|
||||
.queue
|
||||
.len()
|
||||
.saturating_mul(DELAY_ID_LENGTH.saturating_add(size_of::<SystemTime>()));
|
||||
service.mem_usage.store(mem_usage, Ordering::Relaxed);
|
||||
|
||||
let next_due = async {
|
||||
let (Reverse(time), _) = queue.queue.peek()?;
|
||||
if let Ok(wait) = time.duration_since(SystemTime::now()) {
|
||||
sleep(wait).await;
|
||||
}
|
||||
|
||||
queue.queue.pop().map(|(_, delay_id)| delay_id)
|
||||
};
|
||||
|
||||
// All of these are cancellation-safe
|
||||
select! {
|
||||
Some(delay_id) = next_due => {
|
||||
// Sent in the background so one slow room doesn't hold up the others.
|
||||
// Events that were restarted come back through the receiver.
|
||||
let task_service = service.clone();
|
||||
service.services.server.runtime().spawn(async move {
|
||||
if let Some(time) = task_service.send_if_due(&delay_id).await {
|
||||
task_service.submission_queue_sender.send((time, delay_id)).ok();
|
||||
}
|
||||
});
|
||||
},
|
||||
Ok((time, delay_id)) = receiver.recv_async() => {
|
||||
queue.queue.push((Reverse(time), delay_id));
|
||||
},
|
||||
_ = prune.tick() => service.prune_finalized().await,
|
||||
_ = interrupt.recv_async() => break,
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
pub mod alias;
|
||||
pub mod auth_chain;
|
||||
pub mod delayed_events;
|
||||
pub mod directory;
|
||||
pub mod event_handler;
|
||||
pub mod lazy_loading;
|
||||
@@ -27,7 +26,6 @@ pub struct Service {
|
||||
pub alias: Arc<alias::Service>,
|
||||
pub auth_chain: Arc<auth_chain::Service>,
|
||||
pub directory: Arc<directory::Service>,
|
||||
pub delayed_events: Arc<delayed_events::Service>,
|
||||
pub event_handler: Arc<event_handler::Service>,
|
||||
pub lazy_loading: Arc<lazy_loading::Service>,
|
||||
pub membership: Arc<membership::Service>,
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
pub(crate) use conduwuit::{
|
||||
Err, Event, Result, err,
|
||||
matrix::pdu::{PartialPdu, UnsignedContext},
|
||||
matrix::pdu::{PartialPdu, UnsignedContext, sticky},
|
||||
trace,
|
||||
};
|
||||
use ruma::{
|
||||
OwnedEventId, RoomId, UserId,
|
||||
MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId,
|
||||
events::{
|
||||
AnyStateEventContent, AnyTimelineEvent, MessageLikeEventType, StateEventType,
|
||||
AnyStateEventContent, AnyTimelineEvent, StateEventType,
|
||||
room::{
|
||||
canonical_alias::RoomCanonicalAliasEventContent,
|
||||
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
|
||||
@@ -16,6 +16,7 @@ use ruma::{
|
||||
member::RoomMemberEventContent,
|
||||
server_acl::RoomServerAclEventContent,
|
||||
},
|
||||
sticky::StickyDurationMs,
|
||||
},
|
||||
serde::Raw,
|
||||
};
|
||||
@@ -23,43 +24,42 @@ use ruma::{
|
||||
use crate::rooms::state::RoomMutexGuard;
|
||||
|
||||
impl super::Service {
|
||||
/// Checks that a local user may send an event, then sends it.
|
||||
pub async fn send_timeline_event(
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn send_state_event_for_key(
|
||||
&self,
|
||||
mut partial_pdu: PartialPdu,
|
||||
sender: &UserId,
|
||||
room_id: &RoomId,
|
||||
state_lock: &RoomMutexGuard,
|
||||
event_type: &StateEventType,
|
||||
content: &Raw<AnyStateEventContent>,
|
||||
state_key: &str,
|
||||
sticky_duration_ms: Option<StickyDurationMs>,
|
||||
timestamp: Option<MilliSecondsSinceUnixEpoch>,
|
||||
) -> Result<OwnedEventId> {
|
||||
if let Some(state_key) = &partial_pdu.state_key {
|
||||
let content = Raw::<AnyStateEventContent>::from_json(partial_pdu.content);
|
||||
self.assert_allowed_to_send_state_event(
|
||||
room_id,
|
||||
&partial_pdu.event_type.to_string().into(),
|
||||
state_key,
|
||||
&content,
|
||||
let content: Raw<AnyStateEventContent> = content.clone();
|
||||
self.assert_allowed_to_send_state_event(room_id, event_type, state_key, &content)
|
||||
.await?;
|
||||
|
||||
let content = serde_json::from_str(content.json().get())
|
||||
.map_err(|e| err!(Request(BadJson("Invalid JSON body: {e}"))))?;
|
||||
|
||||
let event_id = self
|
||||
.build_and_append_pdu(
|
||||
PartialPdu {
|
||||
event_type: event_type.to_string().into(),
|
||||
content,
|
||||
sticky: sticky_duration_ms.map(sticky::object),
|
||||
state_key: Some(state_key.into()),
|
||||
timestamp,
|
||||
..Default::default()
|
||||
},
|
||||
sender,
|
||||
Some(room_id),
|
||||
state_lock,
|
||||
)
|
||||
.await?;
|
||||
partial_pdu.content = content.into_json();
|
||||
} else {
|
||||
self.assert_allowed_to_send_message_event(
|
||||
&partial_pdu.event_type.to_string().into(),
|
||||
)?;
|
||||
}
|
||||
|
||||
self.build_and_append_pdu(partial_pdu, sender, Some(room_id), state_lock)
|
||||
.await
|
||||
}
|
||||
|
||||
fn assert_allowed_to_send_message_event(&self, event_type: &MessageLikeEventType) -> Result {
|
||||
// Forbid m.room.encrypted if encryption is disabled
|
||||
if *event_type == MessageLikeEventType::RoomEncrypted
|
||||
&& !self.services.config.allow_encryption
|
||||
{
|
||||
return Err!(Request(Forbidden("Encryption has been disabled")));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(event_id)
|
||||
}
|
||||
|
||||
async fn assert_allowed_to_send_state_event(
|
||||
|
||||
@@ -1003,8 +1003,6 @@ impl Service {
|
||||
}
|
||||
}
|
||||
|
||||
let mut first_push_error = None;
|
||||
|
||||
for pdu in pdus {
|
||||
// Redacted events are not notification targets (we don't send push
|
||||
// for them)
|
||||
@@ -1030,27 +1028,15 @@ impl Service {
|
||||
.try_into()
|
||||
.expect("notification count can't go that high");
|
||||
|
||||
let response = self
|
||||
let _response = self
|
||||
.services
|
||||
.pusher
|
||||
.send_push_notice(&user_id, unread, &pusher, rules_for_user, &pdu)
|
||||
.await
|
||||
.map_err(|e| (Destination::Push(user_id.clone(), pushkey.clone()), Box::new(e)));
|
||||
|
||||
if let Err(err) = response {
|
||||
error!(event = %pdu.event_id, pusher = %pusher.app_display_name, "Failed to deliver push notification: {err:?}");
|
||||
|
||||
if first_push_error.is_none() {
|
||||
first_push_error = Some(err);
|
||||
}
|
||||
}
|
||||
.map_err(|e| (Destination::Push(user_id.clone(), pushkey.clone()), e));
|
||||
}
|
||||
|
||||
if let Some(err) = first_push_error {
|
||||
Err(err)
|
||||
} else {
|
||||
Ok(Destination::Push(user_id, pushkey))
|
||||
}
|
||||
Ok(Destination::Push(user_id, pushkey))
|
||||
}
|
||||
|
||||
async fn send_events_dest_federation(
|
||||
|
||||
@@ -94,7 +94,6 @@ impl Services {
|
||||
rooms: rooms::Service {
|
||||
alias: build!(rooms::alias::Service),
|
||||
auth_chain: build!(rooms::auth_chain::Service),
|
||||
delayed_events: build!(rooms::delayed_events::Service),
|
||||
directory: build!(rooms::directory::Service),
|
||||
event_handler: build!(rooms::event_handler::Service),
|
||||
lazy_loading: build!(rooms::lazy_loading::Service),
|
||||
|
||||
@@ -15,7 +15,10 @@ use futures::{FutureExt, Stream, StreamExt};
|
||||
use lettre::Address;
|
||||
use ruma::{
|
||||
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId,
|
||||
api::client::profile::PropagateTo,
|
||||
api::client::{
|
||||
profile::PropagateTo,
|
||||
uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
||||
},
|
||||
events::{
|
||||
GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent,
|
||||
invite_permission_config::InvitePermissionAction, push_rules::PushRulesEvent,
|
||||
@@ -466,12 +469,6 @@ impl super::Service {
|
||||
// Mark user as deactivated
|
||||
self.db.userid_deactivated.insert(user_id, "");
|
||||
|
||||
// Delayed events must not be sent after deactivation
|
||||
self.services
|
||||
.delayed_events
|
||||
.remove_all_for_user(user_id)
|
||||
.await;
|
||||
|
||||
// TODO: Unhook 3PID
|
||||
Ok(())
|
||||
}
|
||||
@@ -727,6 +724,33 @@ impl super::Service {
|
||||
Ok(user_id)
|
||||
}
|
||||
|
||||
/// Look up a user identifier. If a user ID is returned, it will be local to
|
||||
/// this server, but may refer to a nonexistent account.
|
||||
pub async fn lookup_by_identifier(&self, identifier: UserIdentifier) -> Option<OwnedUserId> {
|
||||
match identifier {
|
||||
| UserIdentifier::Email(EmailUserIdentifier { address, .. }) => {
|
||||
let address = address.parse().ok()?;
|
||||
|
||||
let localpart = self
|
||||
.services
|
||||
.threepid
|
||||
.get_localpart_for_email(&address)
|
||||
.await?;
|
||||
|
||||
Some(
|
||||
UserId::parse(format!(
|
||||
"@{localpart}:{}",
|
||||
self.services.globals.server_name()
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
},
|
||||
| UserIdentifier::Matrix(MatrixUserIdentifier { user, .. }) =>
|
||||
UserId::parse_with_server_name(user, self.services.globals.server_name()).ok(),
|
||||
| _ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an OpenID token, which can be used to prove that a user has
|
||||
/// access to an account (primarily for integrations)
|
||||
pub fn create_openid_token(&self, user_id: &UserId, token: &str) -> Result<u64> {
|
||||
|
||||
@@ -12,7 +12,7 @@ pub use account::{AccessTokenStatus, AccountStatus};
|
||||
use conduwuit::{Err, Error, Result, err, utils};
|
||||
use database::Map;
|
||||
pub use device::{DeviceToken, PreviousTokenAction};
|
||||
pub use profile::ProfileFieldChange;
|
||||
pub use profile::{ProfileFieldChange, ProfileQuerier};
|
||||
use ruma::{UserId, api::error::ErrorKind, encryption::CrossSigningKey, serde::Raw};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -57,7 +57,6 @@ struct Services {
|
||||
alias: Dep<alias::Service>,
|
||||
appservice: Dep<appservice::Service>,
|
||||
config: Dep<config::Service>,
|
||||
delayed_events: Dep<rooms::delayed_events::Service>,
|
||||
firstrun: Dep<firstrun::Service>,
|
||||
globals: Dep<globals::Service>,
|
||||
membership: Dep<membership::Service>,
|
||||
@@ -111,8 +110,6 @@ impl crate::Service for Service {
|
||||
alias: args.depend::<alias::Service>("rooms::alias"),
|
||||
appservice: args.depend::<appservice::Service>("appservice"),
|
||||
config: args.depend::<config::Service>("config"),
|
||||
delayed_events: args
|
||||
.depend::<rooms::delayed_events::Service>("rooms::delayed_events"),
|
||||
firstrun: args.depend::<firstrun::Service>("firstrun"),
|
||||
globals: args.depend::<globals::Service>("globals"),
|
||||
membership: args.depend::<membership::Service>("rooms::membership"),
|
||||
|
||||
@@ -39,6 +39,30 @@ impl ProfileFieldChange {
|
||||
}
|
||||
}
|
||||
|
||||
/// The entity querying a user's profile.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub enum ProfileQuerier<'id> {
|
||||
/// The user owning the profile. This variant exists to improve the
|
||||
/// ergonomics of code that looks up a user's own profile, so the user's
|
||||
/// ID doesn't need to be passed twice.
|
||||
Owner,
|
||||
/// Another user, possibly but not necessarily the user owning the profile.
|
||||
Other(&'id UserId),
|
||||
/// An anonymous entity.
|
||||
#[default]
|
||||
Anonymous,
|
||||
}
|
||||
|
||||
impl<'id> From<Option<&'id UserId>> for ProfileQuerier<'id> {
|
||||
fn from(value: Option<&'id UserId>) -> Self {
|
||||
if let Some(user_id) = value {
|
||||
Self::Other(user_id)
|
||||
} else {
|
||||
Self::Anonymous
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Service {
|
||||
pub async fn set_profile_field(
|
||||
&self,
|
||||
@@ -360,4 +384,31 @@ impl super::Service {
|
||||
.ready_for_each(|(key, _)| self.set_profile_key(user_id, &key, None))
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Check if a user can access another user's profile.
|
||||
// This function doesn't do much of anything right now, but future MSCs that
|
||||
// add profile access controls should be implemented here.
|
||||
pub fn user_can_see_profile(
|
||||
&self,
|
||||
target_user: &UserId,
|
||||
querying_user: ProfileQuerier<'_>,
|
||||
) -> impl Future<Output = bool> {
|
||||
std::future::ready(match querying_user {
|
||||
| ProfileQuerier::Anonymous => {
|
||||
// For unauthenticated requests we check the relevant config
|
||||
// option.
|
||||
!self.services.config.require_auth_for_profile_requests
|
||||
},
|
||||
| ProfileQuerier::Other(querying_user) if querying_user != target_user => {
|
||||
// Currently users can't control their own profile visibility,
|
||||
// so we always return true for authenticated
|
||||
// requests from other users.
|
||||
true
|
||||
},
|
||||
| ProfileQuerier::Owner | ProfileQuerier::Other(_) => {
|
||||
// Users can always query their own profile.
|
||||
true
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use axum::{Extension, Router, extract::State, routing::on};
|
||||
use conduwuit_service::oauth::OAuthTicket;
|
||||
use conduwuit_service::{oauth::OAuthTicket, users::ProfileQuerier};
|
||||
|
||||
use crate::{
|
||||
extract::PostForm,
|
||||
@@ -33,7 +33,8 @@ async fn route_cross_signing_reset(
|
||||
PostForm(form): PostForm<()>,
|
||||
) -> Result {
|
||||
let user_id = user.expect_recent(LoginTarget::CrossSigningReset)?;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
if form.is_some() {
|
||||
services
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use axum::{Extension, Router, extract::State, routing::on};
|
||||
use conduwuit_api::client::full_user_deactivate;
|
||||
use conduwuit_service::users::ProfileQuerier;
|
||||
use futures::StreamExt;
|
||||
use ruma::{OwnedRoomId, OwnedUserId, UserId};
|
||||
use tower_sessions::Session;
|
||||
@@ -65,7 +66,8 @@ async fn route_deactivate(
|
||||
PostForm(form): PostForm<DeactivateForm>,
|
||||
) -> Result {
|
||||
let user_id = user.expect_recent(LoginTarget::Deactivate)?;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
let body = {
|
||||
if !services.config.allow_deactivation || services.oidc.enabled() {
|
||||
|
||||
@@ -4,7 +4,9 @@ use axum::{
|
||||
routing::{get, on, post},
|
||||
};
|
||||
use conduwuit_core::warn;
|
||||
use conduwuit_service::{mailer::messages, threepid::session::ValidationSessions};
|
||||
use conduwuit_service::{
|
||||
mailer::messages, threepid::session::ValidationSessions, users::ProfileQuerier,
|
||||
};
|
||||
use lettre::{Address, message::Mailbox};
|
||||
use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -88,7 +90,7 @@ async fn route_change_email(
|
||||
let Some(form) = form else {
|
||||
return response!(ChangeEmail::new(
|
||||
context.clone(),
|
||||
UserCard::for_local_user(&services, user_id.clone()).await,
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await,
|
||||
services
|
||||
.threepid
|
||||
.get_email_for_localpart(user_id.localpart())
|
||||
@@ -134,7 +136,7 @@ async fn route_change_email(
|
||||
|
||||
response!(ChangeEmailValidate::new(
|
||||
context,
|
||||
UserCard::for_local_user(&services, user_id).await,
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await,
|
||||
ChangeEmailValidateBody::ValidationPending {
|
||||
session_id,
|
||||
client_secret,
|
||||
@@ -158,7 +160,8 @@ async fn get_change_email_validate(
|
||||
user: User,
|
||||
) -> Result {
|
||||
let user_id = user.expect(LoginTarget::ChangeEmail)?;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
if !services.threepid.email_requirement().may_change() {
|
||||
return Err(WebError::Forbidden("You may not change your email address.".to_owned()));
|
||||
@@ -198,7 +201,8 @@ async fn post_delete_email(
|
||||
user: User,
|
||||
) -> Result {
|
||||
let user_id = user.expect(LoginTarget::ChangeEmail)?;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
if !services.threepid.email_requirement().may_remove() {
|
||||
return Err(WebError::Forbidden("You may not remove your email address.".to_owned()));
|
||||
|
||||
@@ -6,7 +6,8 @@ use axum::{
|
||||
response::{IntoResponse, Redirect},
|
||||
routing::{get, on},
|
||||
};
|
||||
use conduwuit_api::client::handle_login;
|
||||
use conduwuit_core::{error, result::FlatOk};
|
||||
use conduwuit_service::{oauth::grant::LoginHint, users::ProfileQuerier};
|
||||
use openidconnect::core::CoreAuthPrompt;
|
||||
use ruma::{
|
||||
OwnedUserId,
|
||||
@@ -75,27 +76,44 @@ struct LoginForm {
|
||||
async fn route_login(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
Expect(Query(LoginQuery { next, reauthenticate, intent })): Expect<Query<LoginQuery>>,
|
||||
Expect(Query(LoginQuery { next, reauthenticate, intent, login_hint })): Expect<
|
||||
Query<LoginQuery>,
|
||||
>,
|
||||
session_store: Session,
|
||||
user: User<true>,
|
||||
PostForm(form): PostForm<LoginForm>,
|
||||
) -> Result {
|
||||
let user_id = user.into_session().map(|session| session.user_id);
|
||||
let current_user = user.into_session().map(|session| session.user_id);
|
||||
let login_hint = login_hint.as_deref().map(str::parse::<LoginHint>).flat_ok();
|
||||
|
||||
if let Some(LoginHint::Mxid(hint_user)) = &login_hint
|
||||
&& !services.globals.user_is_local(hint_user)
|
||||
{
|
||||
return Err(WebError::BadRequest("Login hint is not a local user.".to_owned()));
|
||||
}
|
||||
|
||||
let login_type = if services.oidc.enabled() {
|
||||
let (session, redirect_url) = services
|
||||
.oidc
|
||||
.begin_session(match intent {
|
||||
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
|
||||
| _ if reauthenticate => Some(CoreAuthPrompt::Consent),
|
||||
| _ => None,
|
||||
})
|
||||
.await;
|
||||
let prompt = match intent {
|
||||
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
|
||||
| _ if reauthenticate => Some(CoreAuthPrompt::Consent),
|
||||
| _ => None,
|
||||
};
|
||||
|
||||
let login_hint = if let Some(LoginHint::Mxid(user_id)) = &login_hint {
|
||||
Some(user_id.as_ref())
|
||||
} else {
|
||||
current_user.as_deref()
|
||||
};
|
||||
|
||||
let (session, redirect_url) = services.oidc.begin_session(prompt, login_hint).await;
|
||||
|
||||
session_store
|
||||
.insert(OIDC_SESSION_ID_KEY, OidcSession {
|
||||
next: next.clone().unwrap_or_default(),
|
||||
state: OidcSessionState::CodeExchange { expected_user: user_id.clone(), session },
|
||||
state: OidcSessionState::CodeExchange {
|
||||
expected_user: current_user.clone(),
|
||||
session,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("should be able to serialize OIDC session");
|
||||
@@ -115,17 +133,28 @@ async fn route_login(
|
||||
}
|
||||
};
|
||||
|
||||
let body = match &user_id {
|
||||
| None => LoginBody::Unauthenticated {
|
||||
let body = match (¤t_user, &login_hint) {
|
||||
| (None, None) => LoginBody::Unauthenticated {
|
||||
server_name: services.globals.server_name().to_string(),
|
||||
next: next.clone(),
|
||||
},
|
||||
| Some(user_id) => {
|
||||
| (None, Some(LoginHint::Mxid(new_user))) => {
|
||||
let user_card = UserCard::for_local_user(
|
||||
&services,
|
||||
new_user.to_owned(),
|
||||
ProfileQuerier::Anonymous,
|
||||
)
|
||||
.await;
|
||||
|
||||
LoginBody::Authenticated { user_card }
|
||||
},
|
||||
| (Some(user_id), _) => {
|
||||
if !reauthenticate {
|
||||
return response!(Redirect::to(&next.unwrap_or_default().target_path()));
|
||||
}
|
||||
|
||||
let user_card = UserCard::for_local_user(&services, user_id.to_owned()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
LoginBody::Authenticated { user_card }
|
||||
},
|
||||
@@ -134,41 +163,10 @@ async fn route_login(
|
||||
let mut template = Login::new(context, body, login_type, None);
|
||||
|
||||
if let Some(form) = form {
|
||||
let login_result = match (user_id, form.identifier) {
|
||||
| (Some(user_id), _) => {
|
||||
// The user is already authenticated, we need to check their
|
||||
// password
|
||||
services
|
||||
.users
|
||||
.check_password(&user_id, &form.password)
|
||||
.await
|
||||
},
|
||||
| (None, Some(identifier)) => {
|
||||
// The user isn't authenticated, we need to log them in
|
||||
let identifier = if identifier.parse::<lettre::Address>().is_ok() {
|
||||
UserIdentifier::Email(EmailUserIdentifier::new(identifier))
|
||||
} else {
|
||||
UserIdentifier::Matrix(MatrixUserIdentifier::new(identifier))
|
||||
};
|
||||
|
||||
handle_login(&services, Some(&identifier), &form.password, None).await
|
||||
},
|
||||
| (None, None) => {
|
||||
// The user isn't authenticated and didn't supply an identity
|
||||
return response!(WebError::BadRequest("No identity provided".to_owned()));
|
||||
},
|
||||
};
|
||||
|
||||
let user_id = match login_result {
|
||||
let user_id = match perform_login(&services, current_user, login_hint, form).await {
|
||||
| Ok(user_id) => user_id,
|
||||
| Err(err) => {
|
||||
let error_message = if let conduwuit_core::Error::Request(_, message, _) = err {
|
||||
message.into_owned()
|
||||
} else {
|
||||
"Internal login error".to_owned()
|
||||
};
|
||||
|
||||
template.login_error = Some(error_message);
|
||||
template.login_error = Some(err);
|
||||
return response!(template);
|
||||
},
|
||||
};
|
||||
@@ -186,6 +184,50 @@ async fn route_login(
|
||||
response!(template)
|
||||
}
|
||||
|
||||
async fn perform_login(
|
||||
services: &crate::State,
|
||||
current_user: Option<OwnedUserId>,
|
||||
login_hint: Option<LoginHint>,
|
||||
form: LoginForm,
|
||||
) -> Result<OwnedUserId, String> {
|
||||
let logging_in_user = if let Some(current_user) = current_user {
|
||||
current_user
|
||||
} else if let Some(LoginHint::Mxid(hint_user)) = login_hint {
|
||||
hint_user
|
||||
} else if let Some(identifier) = form.identifier {
|
||||
let identifier = if identifier.parse::<lettre::Address>().is_ok() {
|
||||
UserIdentifier::Email(EmailUserIdentifier::new(identifier))
|
||||
} else {
|
||||
UserIdentifier::Matrix(MatrixUserIdentifier::new(identifier))
|
||||
};
|
||||
|
||||
if let Some(identified_user) = services.users.lookup_by_identifier(identifier).await {
|
||||
identified_user
|
||||
} else {
|
||||
return Err("Failed to parse username or email address.".to_owned());
|
||||
}
|
||||
} else {
|
||||
return Err("No identity provided.".to_owned());
|
||||
};
|
||||
|
||||
if services.users.is_login_disabled(&logging_in_user).await {
|
||||
return Err("This account is blocked from logging in.".to_owned());
|
||||
}
|
||||
|
||||
match services
|
||||
.users
|
||||
.check_password(&logging_in_user, &form.password)
|
||||
.await
|
||||
{
|
||||
| Ok(user_id) => Ok(user_id),
|
||||
| Err(conduwuit_core::Error::Request(_, message, _)) => Err(message.into_owned()),
|
||||
| Err(err) => {
|
||||
error!(?logging_in_user, "Internal error logging in: {err}");
|
||||
Err("Internal error.".to_owned())
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_logout(session: Session, RawQuery(query): RawQuery) -> impl IntoResponse {
|
||||
let _ = session.remove::<OwnedUserId>(User::KEY).await;
|
||||
|
||||
|
||||
@@ -5,11 +5,12 @@ use axum::{
|
||||
routing::get,
|
||||
};
|
||||
use conduwuit_core::utils::{IterStream, ReadyExt, stream::TryExpect};
|
||||
use conduwuit_service::threepid::EmailRequirement;
|
||||
use conduwuit_service::{threepid::EmailRequirement, users::ProfileQuerier};
|
||||
use futures::StreamExt;
|
||||
use ruma::{
|
||||
OwnedClientSecret, OwnedDeviceId, OwnedSessionId,
|
||||
api::client::discovery::get_authorization_server_metadata::v1::AccountManagementAction,
|
||||
assign,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -19,9 +20,10 @@ use crate::{
|
||||
pages::{
|
||||
Result, TemplateContext,
|
||||
components::{DeviceCard, DeviceCardStyle, UserCard},
|
||||
switch_account::{LoginHintQuery, prompt_to_switch_account},
|
||||
},
|
||||
response,
|
||||
session::{LoginTarget, User},
|
||||
session::{LoginQuery, LoginTarget, User},
|
||||
template,
|
||||
};
|
||||
|
||||
@@ -82,7 +84,8 @@ async fn get_account(
|
||||
) -> Result {
|
||||
let user_id = user.expect(LoginTarget::Account)?;
|
||||
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
if services.users.is_locked(&user_id).await.unwrap() {
|
||||
return response!(Account::new(context, user_card, AccountBody::Locked));
|
||||
@@ -138,15 +141,49 @@ async fn get_account(
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AccountDeeplinkQuery {
|
||||
action: Option<AccountManagementAction>,
|
||||
device_id: Option<OwnedDeviceId>,
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub(crate) struct AccountDeeplinkQuery {
|
||||
pub action: Option<AccountManagementAction>,
|
||||
pub device_id: Option<OwnedDeviceId>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
impl LoginHintQuery for AccountDeeplinkQuery {
|
||||
fn into_login_target(self) -> LoginTarget { LoginTarget::AccountDeeplink(self) }
|
||||
|
||||
fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { login_hint: None }) }
|
||||
}
|
||||
|
||||
async fn get_account_deeplink(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
Expect(Query(query)): Expect<Query<AccountDeeplinkQuery>>,
|
||||
user: User<true>,
|
||||
) -> Result {
|
||||
if let Some(current_user) = user.into_session() {
|
||||
if let Some(switcher) = prompt_to_switch_account(
|
||||
&services,
|
||||
context,
|
||||
¤t_user.user_id,
|
||||
query.login_hint.as_deref(),
|
||||
&query,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(switcher);
|
||||
}
|
||||
} else {
|
||||
// We redirect to the login page ourselves instead of letting the
|
||||
// handler for the deeplink's target do it so that we can pass the login
|
||||
// hint to the login page.
|
||||
return Err(WebError::LoginRequired(LoginQuery {
|
||||
next: Some(LoginTarget::AccountDeeplink(query.suppress_login_hint())),
|
||||
login_hint: query.login_hint,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
|
||||
let redirect_target = match query.action.unwrap_or(AccountManagementAction::Profile) {
|
||||
| AccountManagementAction::AccountDeactivate => "deactivate".to_owned(),
|
||||
| AccountManagementAction::CrossSigningReset => "cross_signing_reset".to_owned(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use axum::{Extension, Router, extract::State, routing::on};
|
||||
use conduwuit_service::users::HashedPassword;
|
||||
use conduwuit_service::users::{HashedPassword, ProfileQuerier};
|
||||
use ruma::UserId;
|
||||
use validator::{Validate, ValidationError, ValidationErrors};
|
||||
|
||||
@@ -73,7 +73,8 @@ async fn route_change_password(
|
||||
}
|
||||
|
||||
let user_id = user.expect(LoginTarget::ChangePassword)?;
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
let body = if let Some(form) = form {
|
||||
match change_password(&services, &user_id, form).await? {
|
||||
|
||||
@@ -5,7 +5,9 @@ use axum::{
|
||||
};
|
||||
use conduwuit_core::warn;
|
||||
use conduwuit_service::{
|
||||
mailer::messages, threepid::session::ValidationSessions, users::HashedPassword,
|
||||
mailer::messages,
|
||||
threepid::session::ValidationSessions,
|
||||
users::{HashedPassword, ProfileQuerier},
|
||||
};
|
||||
use lettre::{Address, message::Mailbox};
|
||||
use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId, UserId};
|
||||
@@ -207,7 +209,8 @@ async fn route_reset_password_validate(
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
if let Some(form) = form {
|
||||
if let Err(err) = form.validate() {
|
||||
|
||||
@@ -2,7 +2,9 @@ use std::{collections::BTreeSet, time::SystemTime};
|
||||
|
||||
use askama::{Template, filters::HtmlSafe};
|
||||
use conduwuit_core::utils;
|
||||
use conduwuit_service::{Services, oauth::client_metadata::ClientMetadata};
|
||||
use conduwuit_service::{
|
||||
Services, oauth::client_metadata::ClientMetadata, users::ProfileQuerier,
|
||||
};
|
||||
use ruma::{
|
||||
OwnedDeviceId, OwnedUserId, UserId,
|
||||
api::{OAuthClientScope, client::device::Device},
|
||||
@@ -25,18 +27,39 @@ pub(super) struct Avatar {
|
||||
impl HtmlSafe for Avatar {}
|
||||
|
||||
impl Avatar {
|
||||
pub(super) async fn for_local_user(services: &Services, user_id: &UserId) -> Self {
|
||||
let display_name = services.users.displayname(user_id).await.ok();
|
||||
pub(super) async fn for_local_user(
|
||||
services: &Services,
|
||||
user_id: &UserId,
|
||||
querying_user: ProfileQuerier<'_>,
|
||||
) -> Self {
|
||||
let avatar_type = {
|
||||
let localpart_initial = user_id
|
||||
.localpart()
|
||||
.chars()
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_ascii_uppercase();
|
||||
|
||||
let avatar_type = if services.users.avatar_url(user_id).await.is_ok() {
|
||||
AvatarType::Image(profile_media_url(user_id, "avatar_url"))
|
||||
} else if let Some(initial) = display_name
|
||||
.as_ref()
|
||||
.and_then(|display_name| display_name.chars().next())
|
||||
{
|
||||
AvatarType::Initial(initial)
|
||||
} else {
|
||||
AvatarType::Initial(user_id.localpart().chars().next().unwrap())
|
||||
if services
|
||||
.users
|
||||
.user_can_see_profile(user_id, querying_user)
|
||||
.await
|
||||
{
|
||||
let display_name = services.users.displayname(user_id).await.ok();
|
||||
|
||||
if services.users.avatar_url(user_id).await.is_ok() {
|
||||
AvatarType::Image(profile_media_url(user_id, "avatar_url"))
|
||||
} else if let Some(initial) = display_name
|
||||
.as_ref()
|
||||
.and_then(|display_name| display_name.chars().next())
|
||||
{
|
||||
AvatarType::Initial(initial)
|
||||
} else {
|
||||
AvatarType::Initial(localpart_initial)
|
||||
}
|
||||
} else {
|
||||
AvatarType::Initial(localpart_initial)
|
||||
}
|
||||
};
|
||||
|
||||
Self { avatar_type }
|
||||
@@ -97,14 +120,30 @@ impl HtmlSafe for UserCard {}
|
||||
impl UserCard {
|
||||
const BANNER_KEY: &str = "chat.commet.profile_banner";
|
||||
|
||||
pub(super) async fn for_local_user(services: &Services, user_id: OwnedUserId) -> Self {
|
||||
let display_name = services.users.displayname(&user_id).await.ok();
|
||||
let avatar = Avatar::for_local_user(services, &user_id).await;
|
||||
let banner = if services
|
||||
pub(super) async fn for_local_user(
|
||||
services: &Services,
|
||||
user_id: OwnedUserId,
|
||||
querying_user: ProfileQuerier<'_>,
|
||||
) -> Self {
|
||||
let can_see_profile = services
|
||||
.users
|
||||
.get_local_profile_field(&user_id, Self::BANNER_KEY.into())
|
||||
.await
|
||||
.is_some()
|
||||
.user_can_see_profile(&user_id, querying_user)
|
||||
.await;
|
||||
|
||||
let avatar = Avatar::for_local_user(services, &user_id, querying_user).await;
|
||||
|
||||
let display_name = if can_see_profile {
|
||||
services.users.displayname(&user_id).await.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let banner = if can_see_profile
|
||||
&& services
|
||||
.users
|
||||
.get_local_profile_field(&user_id, Self::BANNER_KEY.into())
|
||||
.await
|
||||
.is_some()
|
||||
{
|
||||
Some(profile_media_url(&user_id, Self::BANNER_KEY))
|
||||
} else {
|
||||
|
||||
@@ -25,13 +25,14 @@ async fn get_profile_media(
|
||||
State(services): State<crate::State>,
|
||||
Expect(Path(ProfileMediaPath { user_id, field })): Expect<Path<ProfileMediaPath>>,
|
||||
headers: HeaderMap,
|
||||
requesting_user: User<true>,
|
||||
querying_user: User<true>,
|
||||
) -> Result {
|
||||
if requesting_user
|
||||
.into_session()
|
||||
.map(|session| session.user_id)
|
||||
.as_ref()
|
||||
!= Some(&user_id)
|
||||
let querying_user = querying_user.into_session().map(|session| session.user_id);
|
||||
|
||||
if !services
|
||||
.users
|
||||
.user_can_see_profile(&user_id, querying_user.as_deref().into())
|
||||
.await
|
||||
{
|
||||
return Err(WebError::Forbidden(
|
||||
"You may not access this user's profile media.".to_owned(),
|
||||
|
||||
@@ -20,6 +20,7 @@ pub(super) mod media;
|
||||
pub(super) mod oauth;
|
||||
pub(super) mod oidc;
|
||||
pub(super) mod resources;
|
||||
mod switch_account;
|
||||
pub(super) mod threepid;
|
||||
|
||||
type Result<T = Response, E = WebError> = std::result::Result<T, E>;
|
||||
|
||||
@@ -4,12 +4,15 @@ use axum::{
|
||||
response::Redirect,
|
||||
routing::on,
|
||||
};
|
||||
use conduwuit_service::oauth::{
|
||||
SessionInfo,
|
||||
client_metadata::ClientMetadata,
|
||||
grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery, Prompt, RequestedScopes},
|
||||
use conduwuit_service::{
|
||||
oauth::{
|
||||
SessionInfo,
|
||||
client_metadata::ClientMetadata,
|
||||
grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery, Prompt, RequestedScopes},
|
||||
},
|
||||
users::ProfileQuerier,
|
||||
};
|
||||
use ruma::{OwnedUserId, api::OAuthClientScope};
|
||||
use ruma::{OwnedUserId, api::OAuthClientScope, assign};
|
||||
use serde::{Deserialize, de::IgnoredAny};
|
||||
|
||||
use crate::{
|
||||
@@ -19,6 +22,7 @@ use crate::{
|
||||
GET_POST, Result, TemplateContext,
|
||||
account::register::{RegisterQuery, RequestedRegistrationFlow},
|
||||
components::{Avatar, ClientScopes, UserCard},
|
||||
switch_account::{LoginHintQuery, prompt_to_switch_account},
|
||||
},
|
||||
response,
|
||||
session::{LoginIntent, LoginQuery, LoginTarget, User},
|
||||
@@ -43,6 +47,12 @@ template! {
|
||||
}
|
||||
}
|
||||
|
||||
impl LoginHintQuery for AuthorizationCodeQuery {
|
||||
fn into_login_target(self) -> LoginTarget { LoginTarget::AuthorizationCode(self) }
|
||||
|
||||
fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { login_hint: None }) }
|
||||
}
|
||||
|
||||
async fn route_authorization_code(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
@@ -54,7 +64,7 @@ async fn route_authorization_code(
|
||||
user.user_id
|
||||
} else {
|
||||
let is_first_run = services.firstrun.is_first_run();
|
||||
let next = LoginTarget::AuthorizationCode(query.clone());
|
||||
let next = LoginTarget::AuthorizationCode(query.suppress_login_hint());
|
||||
|
||||
let uri = if query
|
||||
.prompt
|
||||
@@ -81,6 +91,7 @@ async fn route_authorization_code(
|
||||
ROUTE_PREFIX,
|
||||
serde_urlencoded::to_string(LoginQuery {
|
||||
next: Some(next),
|
||||
login_hint: query.login_hint,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
@@ -90,6 +101,18 @@ async fn route_authorization_code(
|
||||
return response!(Redirect::to(&uri));
|
||||
};
|
||||
|
||||
if let Some(switcher) = prompt_to_switch_account(
|
||||
&services,
|
||||
context.clone(),
|
||||
&user_id,
|
||||
query.login_hint.as_deref(),
|
||||
&query,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(switcher);
|
||||
}
|
||||
|
||||
if form.is_some() {
|
||||
let redirect_uri = services
|
||||
.oauth
|
||||
@@ -122,7 +145,7 @@ async fn route_authorization_code(
|
||||
scopes.retain(|scope| !existing_scopes.contains(scope));
|
||||
}
|
||||
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id).await;
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id, ProfileQuerier::Owner).await;
|
||||
|
||||
response!(Grant::new(
|
||||
context,
|
||||
@@ -167,6 +190,12 @@ enum DeviceCodeGrantBody {
|
||||
Success,
|
||||
}
|
||||
|
||||
impl LoginHintQuery for DeviceCodeVerifyQuery {
|
||||
fn into_login_target(self) -> LoginTarget { LoginTarget::DeviceCode(self) }
|
||||
|
||||
fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { ignore_login_hint: true }) }
|
||||
}
|
||||
|
||||
async fn route_device_code(
|
||||
State(services): State<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
@@ -177,19 +206,32 @@ async fn route_device_code(
|
||||
let user_id = if let Some(user) = user.into_session() {
|
||||
user.user_id
|
||||
} else {
|
||||
let next = LoginTarget::DeviceCode(query.clone());
|
||||
let next = LoginTarget::DeviceCode(query.suppress_login_hint());
|
||||
|
||||
let login_hint = if let Some(user_code) = &query.user_code
|
||||
&& let Some(grant_info) = services.oauth.grant_info_for_user_code(user_code).await
|
||||
{
|
||||
grant_info.login_hint
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let uri = format!(
|
||||
"{}/account/login?{}",
|
||||
ROUTE_PREFIX,
|
||||
serde_urlencoded::to_string(LoginQuery { next: Some(next), ..Default::default() })
|
||||
.unwrap()
|
||||
serde_urlencoded::to_string(LoginQuery {
|
||||
next: Some(next),
|
||||
login_hint,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
return response!(Redirect::to(&uri));
|
||||
};
|
||||
|
||||
let user_card = UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await;
|
||||
|
||||
match (form, query.user_code.clone()) {
|
||||
| (None, Some(user_code)) | (Some(DeviceCodeForm::Lookup { user_code }), _) => {
|
||||
@@ -202,6 +244,19 @@ async fn route_device_code(
|
||||
));
|
||||
};
|
||||
|
||||
if !query.ignore_login_hint
|
||||
&& let Some(switcher) = prompt_to_switch_account(
|
||||
&services,
|
||||
context.clone(),
|
||||
&user_id,
|
||||
grant_info.login_hint.as_deref(),
|
||||
&query,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(switcher);
|
||||
}
|
||||
|
||||
let RequestedScopes { device_id, mut scopes } = grant_info.requested_scopes;
|
||||
|
||||
let existing_session_info = if let Some(device_id) = &device_id {
|
||||
@@ -220,7 +275,8 @@ async fn route_device_code(
|
||||
scopes.retain(|scope| !existing_scopes.contains(scope));
|
||||
}
|
||||
|
||||
let user_avatar = Avatar::for_local_user(&services, &user_id).await;
|
||||
let user_avatar =
|
||||
Avatar::for_local_user(&services, &user_id, ProfileQuerier::Owner).await;
|
||||
|
||||
response!(Grant::new(
|
||||
context,
|
||||
|
||||
@@ -10,6 +10,7 @@ use conduwuit_api::client_ip::ClientIp;
|
||||
use conduwuit_service::{
|
||||
oauth::grant::AuthorizationCodeResponse,
|
||||
oidc::{ClaimedLocalUser, SessionCompletionStatus},
|
||||
users::ProfileQuerier,
|
||||
};
|
||||
use futures::FutureExt;
|
||||
use ruma::OwnedServerName;
|
||||
@@ -119,8 +120,12 @@ async fn route_complete(
|
||||
.await
|
||||
{
|
||||
| Ok(ClaimedLocalUser::Existing(user_id)) => {
|
||||
let user_card =
|
||||
UserCard::for_local_user(&services, user_id.clone()).await;
|
||||
let user_card = UserCard::for_local_user(
|
||||
&services,
|
||||
user_id.clone(),
|
||||
ProfileQuerier::Owner,
|
||||
)
|
||||
.await;
|
||||
|
||||
if let Some(password) = form.password {
|
||||
if services
|
||||
@@ -180,6 +185,12 @@ async fn route_complete(
|
||||
.remove::<IgnoredAny>(OIDC_SESSION_ID_KEY)
|
||||
.await;
|
||||
|
||||
if services.users.is_login_disabled(&user_id).await {
|
||||
return Err(WebError::Forbidden(
|
||||
"This account is blocked from logging in.".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
let user_session = UserSession { user_id, last_login: SystemTime::now() };
|
||||
|
||||
session_store
|
||||
|
||||
@@ -392,6 +392,17 @@ ul.list-group {
|
||||
}
|
||||
}
|
||||
|
||||
.button-group {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
|
||||
> a, button {
|
||||
text-align: center;
|
||||
flex: 1 fit-content;
|
||||
}
|
||||
}
|
||||
|
||||
.bi {
|
||||
display: inline-block;
|
||||
vertical-align: -.125em;
|
||||
|
||||
@@ -43,6 +43,11 @@
|
||||
font-weight: normal;
|
||||
font-size: small;
|
||||
font-family: monospace;
|
||||
|
||||
&:only-child {
|
||||
color: var(--text-color);
|
||||
font-size: inherit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,3 +97,23 @@
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.avatar-pair {
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
.separator {
|
||||
align-self: center;
|
||||
margin-inline: 1em;
|
||||
color: var(--secondary);
|
||||
font-size: x-large;
|
||||
user-select: none;
|
||||
|
||||
svg {
|
||||
vertical-align: middle;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,3 @@
|
||||
.avatars {
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
.separator {
|
||||
align-self: center;
|
||||
margin-inline: 1em;
|
||||
color: var(--secondary);
|
||||
font-size: x-large;
|
||||
user-select: none;
|
||||
|
||||
svg {
|
||||
vertical-align: middle;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.identity {
|
||||
margin-block: 1em;
|
||||
color: var(--secondary);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
.account-chooser {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 425px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
a {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
text-align: center;
|
||||
color: var(--text-color);
|
||||
|
||||
border: 1px solid var(--c1);
|
||||
border-radius: var(--border-radius-sm);
|
||||
|
||||
padding: 1rem 0;
|
||||
|
||||
.avatar {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
code {
|
||||
font-size: small;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: var(--card-bg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use conduwuit_core::result::FlatOk;
|
||||
use conduwuit_service::{oauth::grant::LoginHint, users::ProfileQuerier};
|
||||
use ruma::UserId;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
pages::{TemplateContext, components::Avatar},
|
||||
session::{LoginQuery, LoginTarget},
|
||||
template,
|
||||
};
|
||||
|
||||
template! {
|
||||
struct SwitchAccount<'a> use "switch_account.html.j2" {
|
||||
current_user_avatar: Avatar,
|
||||
new_user_avatar: Avatar,
|
||||
current_user_name: String,
|
||||
new_user_name: String,
|
||||
current_user_id: &'a UserId,
|
||||
new_user_id: &'a UserId,
|
||||
switch_account_query: String,
|
||||
continue_query: String
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn prompt_to_switch_account<Query: LoginHintQuery>(
|
||||
services: &crate::State,
|
||||
context: TemplateContext,
|
||||
current_user: &UserId,
|
||||
login_hint: Option<&str>,
|
||||
query: &Query,
|
||||
) -> Option<Response> {
|
||||
let Some(LoginHint::Mxid(new_user)) = login_hint.map(str::parse).flat_ok() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
if current_user == new_user {
|
||||
return None;
|
||||
}
|
||||
|
||||
let switch_account_query = serde_urlencoded::to_string(LoginQuery {
|
||||
next: Some(query.suppress_login_hint().into_login_target()),
|
||||
login_hint: Some(LoginHint::Mxid(new_user.clone()).to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let continue_query = serde_urlencoded::to_string(query.suppress_login_hint()).unwrap();
|
||||
|
||||
let can_see_new_user_profile = services
|
||||
.users
|
||||
.user_can_see_profile(&new_user, ProfileQuerier::Other(current_user))
|
||||
.await;
|
||||
|
||||
let current_user_name = services
|
||||
.users
|
||||
.displayname(current_user)
|
||||
.await
|
||||
.unwrap_or_else(|_| current_user.localpart().to_owned());
|
||||
let current_user_avatar =
|
||||
Avatar::for_local_user(services, current_user, ProfileQuerier::Owner).await;
|
||||
|
||||
let new_user_name = if can_see_new_user_profile {
|
||||
services
|
||||
.users
|
||||
.displayname(&new_user)
|
||||
.await
|
||||
.unwrap_or_else(|_| new_user.localpart().to_owned())
|
||||
} else {
|
||||
new_user.localpart().to_owned()
|
||||
};
|
||||
|
||||
let new_user_avatar =
|
||||
Avatar::for_local_user(services, &new_user, ProfileQuerier::Other(current_user)).await;
|
||||
|
||||
Some(
|
||||
SwitchAccount::new(
|
||||
context,
|
||||
current_user_avatar,
|
||||
new_user_avatar,
|
||||
current_user_name,
|
||||
new_user_name,
|
||||
current_user,
|
||||
&new_user,
|
||||
switch_account_query,
|
||||
continue_query,
|
||||
)
|
||||
.into_response(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A trait for query parameter structs that have a login hint.
|
||||
pub(super) trait LoginHintQuery: Serialize + Sync {
|
||||
/// Modify this query parameter struct to suppress
|
||||
/// the login hint. The resulting query should keep the
|
||||
/// page it belongs to from prompting the user to switch accounts.
|
||||
fn suppress_login_hint(&self) -> Self;
|
||||
|
||||
/// Wrap this query parameter struct in its particular variant of
|
||||
/// [`LoginTarget`].
|
||||
fn into_login_target(self) -> LoginTarget;
|
||||
}
|
||||
@@ -23,3 +23,10 @@
|
||||
<path fill-rule="evenodd" d="M1 11.5a.5.5 0 0 0 .5.5h11.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 11H1.5a.5.5 0 0 0-.5.5m14-7a.5.5 0 0 1-.5.5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H14.5a.5.5 0 0 1 .5.5"/>
|
||||
</svg>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro box_arrow_right() %}
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-box-arrow-right" viewBox="0 0 16 16">
|
||||
<path fill-rule="evenodd" d="M10 12.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v2a.5.5 0 0 0 1 0v-2A1.5 1.5 0 0 0 9.5 2h-8A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h8a1.5 1.5 0 0 0 1.5-1.5v-2a.5.5 0 0 0-1 0z"/>
|
||||
<path fill-rule="evenodd" d="M15.854 8.354a.5.5 0 0 0 0-.708l-3-3a.5.5 0 0 0-.708.708L14.293 7.5H5.5a.5.5 0 0 0 0 1h8.793l-2.147 2.146a.5.5 0 0 0 .708.708z"/>
|
||||
</svg>
|
||||
{% endmacro %}
|
||||
@@ -13,7 +13,7 @@ Authorize client
|
||||
{% let client_name = client_metadata.client_name.as_deref().unwrap_or("Unknown application") %}
|
||||
<div class="panel narrow">
|
||||
<h1>Authorize {{ client_name }}</h1>
|
||||
<div class="avatars">
|
||||
<div class="avatar-pair">
|
||||
<div class="red-avatar">
|
||||
{{ user_avatar }}
|
||||
</div>
|
||||
@@ -24,7 +24,7 @@ Authorize client
|
||||
</div>
|
||||
|
||||
<div class="identity">
|
||||
Signed in as <code>{{ user_id }}</code>. <a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ logout_query }}">Switch accounts</a>
|
||||
Logged in as <code>{{ user_id }}</code>. <a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ logout_query }}">Switch accounts</a>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
{% extends "_layout.html.j2" %}
|
||||
{% import "_icons.html.j2" as icons %}
|
||||
|
||||
{%- block head -%}
|
||||
<link rel="stylesheet" href="{{ crate::ROUTE_PREFIX }}/resources/switch-account.css">
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block title -%}
|
||||
Select an account
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block content -%}
|
||||
<div class="panel narrow">
|
||||
<h1>Select an account</h1>
|
||||
|
||||
<p>
|
||||
Welcome back! Which account would you like to continue with?
|
||||
</p>
|
||||
|
||||
<div class="account-chooser red-avatar">
|
||||
<a href="?{{ continue_query }}">
|
||||
{{ current_user_avatar }}
|
||||
<span>Continue as <b>{{ current_user_name }}</b></span>
|
||||
<code>{{ current_user_id }}</code>
|
||||
</a>
|
||||
<a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ switch_account_query }}">
|
||||
{{ new_user_avatar }}
|
||||
<span>Continue as <b>{{ new_user_name }}</b></span>
|
||||
<code>{{ new_user_id }}</code>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{%- endblock -%}
|
||||
+11
-6
@@ -15,7 +15,10 @@ use ruma::{OwnedUserId, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tower_sessions::Session;
|
||||
|
||||
use crate::{ROUTE_PREFIX, WebError, pages::account::device::DevicePath};
|
||||
use crate::{
|
||||
ROUTE_PREFIX, WebError,
|
||||
pages::account::{AccountDeeplinkQuery, device::DevicePath},
|
||||
};
|
||||
|
||||
pub(crate) mod store;
|
||||
|
||||
@@ -27,6 +30,8 @@ pub(crate) struct LoginQuery {
|
||||
pub reauthenticate: bool,
|
||||
#[serde(default)]
|
||||
pub intent: Option<LoginIntent>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
@@ -35,6 +40,7 @@ pub(crate) enum LoginTarget {
|
||||
AuthorizationCode(AuthorizationCodeQuery),
|
||||
#[default]
|
||||
Account,
|
||||
AccountDeeplink(AccountDeeplinkQuery),
|
||||
ChangePassword,
|
||||
ChangeEmail,
|
||||
CrossSigningReset,
|
||||
@@ -57,6 +63,8 @@ impl LoginTarget {
|
||||
)
|
||||
.into(),
|
||||
| Self::Account => "account/".into(),
|
||||
| Self::AccountDeeplink(query) =>
|
||||
format!("account/deeplink?{}", serde_urlencoded::to_string(query).unwrap()).into(),
|
||||
| Self::ChangePassword => "account/password/change".into(),
|
||||
| Self::ChangeEmail => "account/email/change/".into(),
|
||||
| Self::CrossSigningReset => "account/cross_signing_reset".into(),
|
||||
@@ -117,14 +125,11 @@ impl<const ALLOW_LOCKED: bool> User<ALLOW_LOCKED> {
|
||||
|
||||
/// Extract the user ID, redirecting to the login page if the user isn't
|
||||
/// logged in.
|
||||
pub(crate) fn expect(self, or_else: LoginTarget) -> Result<OwnedUserId, WebError> {
|
||||
pub(crate) fn expect(self, or: LoginTarget) -> Result<OwnedUserId, WebError> {
|
||||
if let Some(session) = self.0 {
|
||||
Ok(session.user_id)
|
||||
} else {
|
||||
Err(WebError::LoginRequired(LoginQuery {
|
||||
next: Some(or_else),
|
||||
..Default::default()
|
||||
}))
|
||||
Err(WebError::LoginRequired(LoginQuery { next: Some(or), ..Default::default() }))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user