Compare commits

..
45 changed files with 1012 additions and 585 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
Continuwuity now supports the OAuth 2.0 client credentials grant type, allowing secure automated access to the Matrix homeserver admin API, as well as future administrative functionality. Contributed by @ginger.
@@ -0,0 +1 @@
Fixed read receipts for all but one of a user's threads not being sent over federation. Contributed by @eleboucher.
+1
View File
@@ -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.
+1
View File
@@ -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 -45
View File
@@ -2579,9 +2579,10 @@
# Additional scopes Continuwuity should request from the IDP. This may be # Additional scopes Continuwuity should request from the IDP. This may be
# necessary to access certain claims. Continuwuity always requests the # necessary to access certain claims. Continuwuity always requests the
# `openid` scope, regardless of the contents of this option, # `openid` scope, regardless of the value of this option.
# and will also request the `profile` scope by default if this option is #
# not set. # Defaults to only the `profile` scope, as recommended by the OIDC
# specification.
# #
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES # env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
#additional_scopes = ["profile"] #additional_scopes = ["profile"]
@@ -2597,6 +2598,19 @@
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_TRUSTED_AUDIENCES # env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_TRUSTED_AUDIENCES
#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 # The name of the identity provider. If this is set, the login page's
# button reads "Continue with <name>" instead of just "Continue". # button reads "Continue with <name>" instead of just "Continue".
# #
@@ -2675,48 +2689,6 @@
# env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE # env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE
#profile_key_import_mode = "on_registration" #profile_key_import_mode = "on_registration"
#[global.oauth.clients."$id"]
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available.
# The client's client secret.
#
# This must be supplied as the `client_secret` parameter when requesting
# an access token with the OAuth 2.0 token endpoint. Continuwuity does
# not check the `Authorization` header for requests to this endpoint.
#
#client_secret =
# A list of scopes that the client may request. Continuwuity allows static
# clients to request the following scopes:
#
# - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
# This scope grants access to the Matrix server administration APIs, as
# well as Continuwuity's internal admin API (currently a work in
# progress).
# - "urn:matrix:client:api:*": This scope grants access to the Matrix
# client-server API. Most endpoints require an authenticated Matrix user
# and thus will not be usable by static clients.
#
# The `urn:matrix:client:device:<id>` scope may not be requested by static
# clients.
#
# Scopes listed here are not granted by default. The client must
# explicitly include them in the `scope` parameter of its access token
# request.
#
#scopes = []
[global.experiments] [global.experiments]
# Continuwuity's experimental features are frequently updated. # Continuwuity's experimental features are frequently updated.
# If you got this configuration via a package manager, chances are it's outdated. # If you got this configuration via a package manager, chances are it's outdated.
+132 -95
View File
@@ -16,35 +16,38 @@
} }
}, },
"node_modules/@emnapi/core": { "node_modules/@emnapi/core": {
"version": "2.0.0-beta.3", "version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz",
"integrity": "sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==", "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true,
"dependencies": { "dependencies": {
"@emnapi/wasi-threads": "2.2.0", "@emnapi/wasi-threads": "1.2.3",
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@emnapi/runtime": { "node_modules/@emnapi/runtime": {
"version": "2.0.0-beta.3", "version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
"integrity": "sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==", "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@emnapi/wasi-threads": { "node_modules/@emnapi/wasi-threads": {
"version": "2.2.0", "version": "1.2.3",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
@@ -128,13 +131,13 @@
} }
}, },
"node_modules/@rsbuild/core": { "node_modules/@rsbuild/core": {
"version": "2.3.6", "version": "2.3.7",
"resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.6.tgz", "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.7.tgz",
"integrity": "sha512-IVuWh/0DO6XT8075eCAzxWIcVGA7c4xKggf/VEePq3yXqEiU302n6OVGD7uCxQwPaB4R9ViX4cAqalcQV/sxKQ==", "integrity": "sha512-IvJZFEeVGcjeSiSHfMlRxJbyL5+xLGcvkNmD34wmIXo85n0va6b8cnqShmprdUKjvXyzE4dPPB9trRunaUY+mA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rspack/core": "~2.3.4", "@rspack/core": "~2.3.5",
"@swc/helpers": "^0.5.24" "@swc/helpers": "^0.5.24"
}, },
"bin": { "bin": {
@@ -172,32 +175,32 @@
} }
}, },
"node_modules/@rspack/binding": { "node_modules/@rspack/binding": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.5.tgz",
"integrity": "sha512-wSOT16LVITL/IKeIiLXgN5Q5jZIDqnQ7Gmk+wzKOSZ6OHYNfEBXAKhSJuYtCBq8ovJuGl8cJjdqatAlHE5XKIA==", "integrity": "sha512-W3x7zw5d/mIH9WhWt4pO9RKYURoqgdUxeLSV5IhDCajnhXdRr7R59u5S2j5ZXzSk3eMGUC0PenfKIIdW7t0ufQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optionalDependencies": { "optionalDependencies": {
"@rspack/binding-darwin-arm64": "2.3.4", "@rspack/binding-darwin-arm64": "2.3.5",
"@rspack/binding-darwin-x64": "2.3.4", "@rspack/binding-darwin-x64": "2.3.5",
"@rspack/binding-linux-arm64-gnu": "2.3.4", "@rspack/binding-linux-arm64-gnu": "2.3.5",
"@rspack/binding-linux-arm64-musl": "2.3.4", "@rspack/binding-linux-arm64-musl": "2.3.5",
"@rspack/binding-linux-ppc64-gnu": "2.3.4", "@rspack/binding-linux-ppc64-gnu": "2.3.5",
"@rspack/binding-linux-riscv64-gnu": "2.3.4", "@rspack/binding-linux-riscv64-gnu": "2.3.5",
"@rspack/binding-linux-riscv64-musl": "2.3.4", "@rspack/binding-linux-riscv64-musl": "2.3.5",
"@rspack/binding-linux-s390x-gnu": "2.3.4", "@rspack/binding-linux-s390x-gnu": "2.3.5",
"@rspack/binding-linux-x64-gnu": "2.3.4", "@rspack/binding-linux-x64-gnu": "2.3.5",
"@rspack/binding-linux-x64-musl": "2.3.4", "@rspack/binding-linux-x64-musl": "2.3.5",
"@rspack/binding-wasm32-wasi": "2.3.4", "@rspack/binding-wasm32-wasi": "2.3.5",
"@rspack/binding-win32-arm64-msvc": "2.3.4", "@rspack/binding-win32-arm64-msvc": "2.3.5",
"@rspack/binding-win32-ia32-msvc": "2.3.4", "@rspack/binding-win32-ia32-msvc": "2.3.5",
"@rspack/binding-win32-x64-msvc": "2.3.4" "@rspack/binding-win32-x64-msvc": "2.3.5"
} }
}, },
"node_modules/@rspack/binding-darwin-arm64": { "node_modules/@rspack/binding-darwin-arm64": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.5.tgz",
"integrity": "sha512-eBD71fbmoJKnxcHD03bukbAIOP5r7nD0Ehs+mUrUQlZ6N53EhuJsTeJ1oYdg5L4GoSeQ+KecCqME81Nm0COLrA==", "integrity": "sha512-A5XnBdSoJvcYV4t2Y+XJiCF0UZ42nOKE2D0ZlegfErGhzlQG1t3hDOzskSB2fPD3z+w5QeREoclqQ0zFOZyBpw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -209,9 +212,9 @@
] ]
}, },
"node_modules/@rspack/binding-darwin-x64": { "node_modules/@rspack/binding-darwin-x64": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.5.tgz",
"integrity": "sha512-CqdfzTLPVFQCniOy/GDVWbg+rqg31qfdzbFf8NYCzdDkCQg+p15hU2HsckD/1sLsaNB8Y55EjGz4ZyGDny0cHg==", "integrity": "sha512-iZrweqTIj2cM4f0ADRj6FXn9a0FOpD1Mx/++zrsbrQzmnY0c8wmfpvZ5xA5Zfcq9O6nuUBS6GnhkmoFTgviHwQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -223,9 +226,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-arm64-gnu": { "node_modules/@rspack/binding-linux-arm64-gnu": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.5.tgz",
"integrity": "sha512-T/Y1FYiSegcNc+oHuDOLRGIcc+eSdBnfbS70d51EWQj4+0TG/tlfuqFKeAIL3mnKUV5lDLaTz3vsoD0Sws5Fxw==", "integrity": "sha512-aWE9V0ZhmclKsJNuO37cxUMLtXMjhLtFzrWDWC82mksUX6qM2rzOpPuye9i/c9NGqyrIH7EFQre8bskJvNHGuQ==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -240,9 +243,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-arm64-musl": { "node_modules/@rspack/binding-linux-arm64-musl": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.5.tgz",
"integrity": "sha512-WZHCzZ532UfXFXNU8XyM8jb+I6wddegbs/7IXsyw7xiPwwZX1D/M6iKFVpBYdvKcupUM8bS8Uw2REirR/cERVw==", "integrity": "sha512-I8ENTXdv7Th/OHEYhL7uu3B7DA9r1oTWSifkGHJtuT1XJ0KDsxoA6ORpYz1R2qIs87l+8+5QUnRH7iWyZrnroA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -257,9 +260,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-ppc64-gnu": { "node_modules/@rspack/binding-linux-ppc64-gnu": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.5.tgz",
"integrity": "sha512-WeizqeI6HIh7Ax9w2tlmpTtipJWxXcdgt3QqI3N9LOixymlMD5yMBMZNPqwZ6cHXT9gOQ69SvPcVgMwxsdmceQ==", "integrity": "sha512-ps5do0cKf4aTBWd+LHqvwm8Gdn7J/gvzmx9pWJhAIThvzii45wJREFjGOzJNxdQl+pzKq8JFuzbShNskCN9k2w==",
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
@@ -274,9 +277,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-riscv64-gnu": { "node_modules/@rspack/binding-linux-riscv64-gnu": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.5.tgz",
"integrity": "sha512-h+001Vbq8LyGwPMNkeRWidPOVKwlAbwNPskY3CjNlSw3euHkVchfhM3uo6+1h0GyTtb3rzsWqsfm1kar7m/tiQ==", "integrity": "sha512-3XXIEMS4SSr1/9wIAGgPT1oj1SzhnlejAG5xeVbGJR5y6iFp/oFKYzUPqyuuzZCkWph2/hJ+Q16sa+BJn1YIkg==",
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
@@ -291,9 +294,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-riscv64-musl": { "node_modules/@rspack/binding-linux-riscv64-musl": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.5.tgz",
"integrity": "sha512-S1rlaCnNVG5s4WZ9odLsqN3ySh5TEdNTLXWapEK8x3iQl56aLtdvqXTfbJWHWnYLJuS7M1WqnQGdJNdjy2NDsA==", "integrity": "sha512-z2DbQNcLbUEY9OvUa3gahsHey+dW4acLc9d3QlyJm7TJE//rL9C/XBk4kETvCgtdhqrwBSfWrZfislBPKODjvA==",
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
@@ -308,9 +311,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-s390x-gnu": { "node_modules/@rspack/binding-linux-s390x-gnu": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.5.tgz",
"integrity": "sha512-0SkgGrgulVMam3xel5dMNKQ+U7BEpCczhF1avGT1DzDVIbMfIOsbb32gApQNSz0E7RfAQ/Pa5eWiA9oyRq7ZMQ==", "integrity": "sha512-n2UudDpzt9G2AOmycVS7uWRMcNMd2k4ubU4b4SX3FfU/uT6mfSNzuwhBhCi0RSZQAGBU0ombJ+sqw8vKXjGGbw==",
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
@@ -325,9 +328,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-x64-gnu": { "node_modules/@rspack/binding-linux-x64-gnu": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.5.tgz",
"integrity": "sha512-q7E6x3rJJ/9fJyLuRe5+KyEPi23BF/xkAU4xCM5VwLkTf+rVyOkDZfu0qOkxmILjrxllQPV+b/ojBL/ZaIeQPw==", "integrity": "sha512-1sxASGJXg9luaYsFSmAQxSFbUbnMnPA5Mr94yIlLsq4q94sHUIn5YjG1XGcT+cPhUYF9fHkCsKRmQlzrN9fR8A==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -342,9 +345,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-x64-musl": { "node_modules/@rspack/binding-linux-x64-musl": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.5.tgz",
"integrity": "sha512-rey4Tyasui/WeMn6KfhH5xyZGOMt+Ny+GDK7nGh9TSz/cb3/bisxqGzpbu6GJK8leDmTUDD5ZdpODexytA5rzQ==", "integrity": "sha512-/S4pe1wAo8CBTs0X8DNKu1ZOJ2vQcnThLBKS2CxOPiuQXI7UfAsJCEABBoa8yCrZANWh63fJ90UwLb/s245Gsw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -359,9 +362,9 @@
] ]
}, },
"node_modules/@rspack/binding-wasm32-wasi": { "node_modules/@rspack/binding-wasm32-wasi": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.5.tgz",
"integrity": "sha512-sDt2MSXZrIaMBa6UaEqmXEqebwpTOPAXLdo9CYJ2Fa9FJWP4TCYbn30mbvV38ZC2n5YX411DRbjck+s97CceIg==", "integrity": "sha512-GQnswrv6AyBdDCcTy8dTVhD0JqnvmgewzPz6qnOYWGKxpCY99Bv6FL4jvxI1yh64Uk3ykEfbwhrPnaA8Px4KJA==",
"cpu": [ "cpu": [
"wasm32" "wasm32"
], ],
@@ -369,15 +372,49 @@
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
"@emnapi/core": "2.0.0-beta.3", "@emnapi/core": "2.0.0-beta.4",
"@emnapi/runtime": "2.0.0-beta.3", "@emnapi/runtime": "2.0.0-beta.4",
"@napi-rs/wasm-runtime": "1.2.7" "@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": { "node_modules/@rspack/binding-win32-arm64-msvc": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.5.tgz",
"integrity": "sha512-24YC1YSodLAJ8VsMQJmJSHCNvHTqK9JP5hj50T50WE8lCHNsNl/rIYXO9V0VlCYT/HshE6EHHzAeKdahiEOtcw==", "integrity": "sha512-XVKu3Zs5KGr+P5Seh6NtSNU0UQ1GSgSDFANQRZlT1uFZ1NpBCX+9NB8FVZB0hBBoBKI1kU4b0Cr6Df1Xx0K4nQ==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -389,9 +426,9 @@
] ]
}, },
"node_modules/@rspack/binding-win32-ia32-msvc": { "node_modules/@rspack/binding-win32-ia32-msvc": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.5.tgz",
"integrity": "sha512-xmUNu6kgV9lLEkRP1Zb+t6i1Z1ZMEWXmLlMalPx8tHqndz2RflNMBBx6kjB2nAPQBIZgWufwm7dVGS0HKomCmw==", "integrity": "sha512-ejCqSuctPcOev2dyi0ayZyfIUY3fJdYHYvrTfSVrrGC19TspuRATXu+RLyu3xvB6TrQF3+JEF4KeG4/ZeWuXOg==",
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
@@ -403,9 +440,9 @@
] ]
}, },
"node_modules/@rspack/binding-win32-x64-msvc": { "node_modules/@rspack/binding-win32-x64-msvc": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.5.tgz",
"integrity": "sha512-WY+AkJqpbLtLEZiG1fE7CVJZ54y0qHeCiVmLxGBsh4OOGIDCs6v2Ub5COcPrYVzGJFGyeHUS29dV7JAs93qIHw==", "integrity": "sha512-IPvkjM3xAwL1z2N4Jp/GBcZUme703uDy5vrP1IMtXJEl/EOLLfwl7cRb4sSzdeOYGDDHs5dPYDcpgP5eRSRauA==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -417,13 +454,13 @@
] ]
}, },
"node_modules/@rspack/core": { "node_modules/@rspack/core": {
"version": "2.3.4", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.4.tgz", "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.5.tgz",
"integrity": "sha512-T8HGkIjPVDlGlIN8st/ICe8Gfixq8te75g/8crSdNSf8F+6884sBcKNky0CRdfPxao1C5SXV+Vjv1XJTjyu83w==", "integrity": "sha512-4TG6zGTemEU/FU7bymDgeFOO7CRdd7ucn0CmXo+3cG6EhYmY5+hpAFYBRgxDbDuL4Bwo/s5GsgUvZuI7rLqVbQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rspack/binding": "2.3.4" "@rspack/binding": "2.3.5"
}, },
"engines": { "engines": {
"node": "^20.19.0 || >=22.12.0" "node": "^20.19.0 || >=22.12.0"
@@ -458,22 +495,22 @@
} }
}, },
"node_modules/@rspress/core": { "node_modules/@rspress/core": {
"version": "2.1.5", "version": "2.1.6",
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.5.tgz", "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.6.tgz",
"integrity": "sha512-kzTqrfJ4UiW+RLLHLunoW/rET5Vjb6Qz4YjhEhiWEp4HYM+KxLVhfyYB5aL8af9+mdnwiTaqlu1s+BZGrMD2zw==", "integrity": "sha512-a+CBJcslana9Zmr6j2o3RP6O19y+rcyfa8jeDToC1b29e/RGiD+xpAQJF2eBvnjNUHouXARTaFa7pE1myyV0Rg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@mdx-js/mdx": "^3.1.1", "@mdx-js/mdx": "^3.1.1",
"@mdx-js/react": "^3.1.1", "@mdx-js/react": "^3.1.1",
"@rsbuild/core": "^2.3.3", "@rsbuild/core": "^2.3.7",
"@rsbuild/plugin-react": "~2.1.1", "@rsbuild/plugin-react": "~2.1.1",
"@rspress/shared": "2.1.5", "@rspress/shared": "2.1.6",
"@shikijs/rehype": "^4.2.0", "@shikijs/rehype": "^4.2.0",
"@shikijs/transformers": "^4.2.0", "@shikijs/transformers": "^4.2.0",
"@types/mdast": "^4.0.4", "@types/mdast": "^4.0.4",
"@types/react": "^19.3.0", "@types/react": "^19.3.3",
"@unhead/react": "^2.1.18", "@unhead/react": "^2.1.19",
"body-scroll-lock": "4.0.0-beta.0", "body-scroll-lock": "4.0.0-beta.0",
"clsx": "2.1.1", "clsx": "2.1.1",
"copy-to-clipboard": "^3.3.3", "copy-to-clipboard": "^3.3.3",
@@ -490,7 +527,7 @@
"react-dom": "^19.3.1", "react-dom": "^19.3.1",
"react-lazy-with-preload": "^2.2.1", "react-lazy-with-preload": "^2.2.1",
"react-render-to-markdown": "19.2.0", "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-external-links": "^3.0.0",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"remark-cjk-friendly": "^2.3.4", "remark-cjk-friendly": "^2.3.4",
@@ -514,9 +551,9 @@
} }
}, },
"node_modules/@rspress/plugin-client-redirects": { "node_modules/@rspress/plugin-client-redirects": {
"version": "2.1.5", "version": "2.1.6",
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.5.tgz", "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.6.tgz",
"integrity": "sha512-vqAi7ynOgVsuwJi7cXwWEF5UgoNhXqGOyBfQubeZHZKWRtdNHRU42P9rG9DZLTss2dZUiDKlVrM2/vNY40t5hw==", "integrity": "sha512-lnSIA3oD44PZa0o0r4gvTBBGWeImD3T7D28FRJlzCdrWQX3kOHpyhxd9fCcK9mE32DYItlu/ipsmpSozmDN9ZA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -527,15 +564,15 @@
} }
}, },
"node_modules/@rspress/shared": { "node_modules/@rspress/shared": {
"version": "2.1.5", "version": "2.1.6",
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.5.tgz", "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.6.tgz",
"integrity": "sha512-XXxegxRZ7VPADS2veN9FTNmmLlA65ieydKH0tOhOZbMJC4OJpKbr/d/JS2jxxAO4u+ZmZxbDyEEir83NQHLKIw==", "integrity": "sha512-ecHmNItlMsMU5FEf0CeBKZa4XNCE5fpwCED+1/lmcwIhozyBvd4j4Ook/8IyTT3UqgruJDZ2DwQqfyvCW7zmLg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rsbuild/core": "^2.3.3", "@rsbuild/core": "^2.3.7",
"@shikijs/rehype": "^4.2.0", "@shikijs/rehype": "^4.2.0",
"@types/react": "^19.3.0", "@types/react": "^19.3.3",
"mdast-util-mdx-jsx": "^3.2.2", "mdast-util-mdx-jsx": "^3.2.2",
"unified": "^11.0.5" "unified": "^11.0.5"
} }
-1
View File
@@ -75,7 +75,6 @@ pub(super) use report::*;
pub(super) use room::*; pub(super) use room::*;
pub(super) use search::*; pub(super) use search::*;
pub(super) use send::*; pub(super) use send::*;
pub use session::handle_login;
pub(super) use session::*; pub(super) use session::*;
pub(super) use space::*; pub(super) use space::*;
pub(super) use state::*; pub(super) use state::*;
+5 -1
View File
@@ -61,7 +61,7 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value
"authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(), "authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(),
"code_challenge_methods_supported": ["S256"], "code_challenge_methods_supported": ["S256"],
"device_authorization_endpoint": endpoint_base.join(DEVICE_AUTHORIZATION_PATH).unwrap(), "device_authorization_endpoint": endpoint_base.join(DEVICE_AUTHORIZATION_PATH).unwrap(),
"grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "client_credentials"], "grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"],
"issuer": services.config.get_client_domain(), "issuer": services.config.get_client_domain(),
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(), "jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
"prompt_values_supported": prompt_values_supported, "prompt_values_supported": prompt_values_supported,
@@ -70,5 +70,9 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value
"response_types_supported": ["code"], "response_types_supported": ["code"],
"revocation_endpoint": endpoint_base.join(TOKEN_REVOKE_PATH).unwrap(), "revocation_endpoint": endpoint_base.join(TOKEN_REVOKE_PATH).unwrap(),
"token_endpoint": endpoint_base.join(TOKEN_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"],
}) })
} }
+24 -8
View File
@@ -29,10 +29,18 @@ pub(crate) async fn get_profile_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<get_profile::v3::Request>, body: Ruma<get_profile::v3::Request>,
) -> Result<get_profile::v3::Response> { ) -> Result<get_profile::v3::Response> {
if services.config.require_auth_for_profile_requests && body.identity.is_none() { let querying_user = body
return Err!(Request(Unauthorized( .identity
"This server requires authentication to access user profiles." .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 { 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>, State(services): State<crate::State>,
body: Ruma<get_profile_field::v3::Request>, body: Ruma<get_profile_field::v3::Request>,
) -> Result<get_profile_field::v3::Response> { ) -> Result<get_profile_field::v3::Response> {
if services.config.require_auth_for_profile_requests && body.identity.is_none() { let querying_user = body
return Err!(Request(Unauthorized( .identity
"This server requires authentication to access user profiles." .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?; let value = fetch_profile_field(&services, &body.user_id, body.field.clone()).await?;
+14 -29
View File
@@ -8,7 +8,6 @@ use conduwuit::{
}; };
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::StreamExt; use futures::StreamExt;
use lettre::Address;
use ruma::{ use ruma::{
OwnedUserId, UserId, OwnedUserId, UserId,
api::client::{ api::client::{
@@ -24,7 +23,7 @@ use ruma::{
}, },
logout, logout_all, logout, logout_all,
}, },
uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier}, uiaa::{MatrixUserIdentifier, UserIdentifier},
}, },
assign, assign,
}; };
@@ -56,43 +55,29 @@ pub(crate) async fn get_login_types_route(
])) ]))
} }
pub async fn handle_login( async fn handle_login(
services: &Services, services: &Services,
identifier: Option<&UserIdentifier>, identifier: Option<UserIdentifier>,
password: &str, password: &str,
user: Option<&String>, user: Option<&String>,
) -> Result<OwnedUserId> { ) -> Result<OwnedUserId> {
debug!("Got password login type"); debug!("Got password login type");
let user_id_or_localpart = match (identifier, user) { let user_id = if let Some(identifier) = identifier {
| (Some(UserIdentifier::Matrix(MatrixUserIdentifier { user, .. })), _) services.users.lookup_by_identifier(identifier).await
| (None, Some(user)) => user, } else if let Some(user) = user {
| (Some(UserIdentifier::Email(EmailUserIdentifier { address, .. })), _) => { UserId::parse_with_server_name(user, &services.config.server_name).ok()
let email = Address::try_from(address.to_owned()) } else {
.map_err(|_| err!(Request(InvalidParam("Email is malformed"))))?; None
&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 = let Some(user_id) = user_id else {
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name) return Err!(Request(InvalidUsername("User ID is malformed.")));
.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.")));
}
if services.users.is_login_disabled(&user_id).await { if services.users.is_login_disabled(&user_id).await {
warn!(%user_id, "user attempted to log in with a login-disabled account"); 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 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 { let user_id = match &body.login_info {
#[allow(deprecated)] #[allow(deprecated)]
| LoginInfo::Password(login::v3::Password { identifier, password, user, .. }) => | 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, .. }) => { | LoginInfo::Token(login::v3::Token { token, .. }) => {
debug!("Got token login type"); debug!("Got token login type");
if !services.server.config.login_via_existing_session { if !services.server.config.login_via_existing_session {
+1 -25
View File
@@ -47,7 +47,6 @@ pub(crate) enum ClientIdentity {
sender_device: Option<OwnedDeviceId>, sender_device: Option<OwnedDeviceId>,
appservice_info: Box<RegistrationInfo>, appservice_info: Box<RegistrationInfo>,
}, },
StaticClient,
} }
impl ClientIdentity { impl ClientIdentity {
@@ -55,7 +54,6 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } => | Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Some(sender_user), Some(sender_user),
| Self::StaticClient => None,
} }
} }
@@ -63,8 +61,6 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } => | Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Ok(sender_user), Ok(sender_user),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
} }
} }
@@ -72,7 +68,6 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_device, .. } => Some(sender_device), | Self::User { sender_device, .. } => Some(sender_device),
| Self::Appservice { sender_device, .. } => sender_device.as_deref(), | Self::Appservice { sender_device, .. } => sender_device.as_deref(),
| Self::StaticClient => None,
} }
} }
@@ -82,14 +77,12 @@ impl ClientIdentity {
| Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device), | Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device),
| Self::Appservice { sender_device: None, .. } => | Self::Appservice { sender_device: None, .. } =>
Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))), Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
} }
} }
pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> { pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> {
match self { match self {
| Self::User { .. } | Self::StaticClient => None, | Self::User { .. } => None,
| Self::Appservice { appservice_info, .. } => Some(appservice_info), | Self::Appservice { appservice_info, .. } => Some(appservice_info),
} }
} }
@@ -432,23 +425,6 @@ async fn check_access_token(
sender_device, sender_device,
appservice_info: Box::new(appservice_info), appservice_info: Box::new(appservice_info),
}) })
} else if let Some(session) = services.oauth.get_client_credentials_session(token) {
if !required_scopes
.iter()
.any(|scope| session.scopes.contains(scope))
{
return Err(Error::Request(
ErrorKind::InsufficientUserAuthentication(Box::new(
assign!(InsufficientUserAuthenticationErrorData::new(), {
scope: required_scopes.iter().cloned().collect()
}),
)),
"You do not have permission to access this endpoint.".into(),
StatusCode::UNAUTHORIZED,
));
}
Ok(ClientIdentity::StaticClient)
} else if services.users.is_previous_token(token).await { } else if services.users.is_previous_token(token).await {
// Return a soft-logout for previous tokens. This is necessary // Return a soft-logout for previous tokens. This is necessary
// to make token refreshing idempotent. // to make token refreshing idempotent.
-9
View File
@@ -346,15 +346,6 @@ pub fn check(config: &Config) -> Result {
} }
})?; })?;
for (id, client) in &config.oauth.clients {
if client.scopes.is_empty() {
warn!(
"The static OAuth client `{id}` has no scopes configured. It will not be able \
to access any API endpoints."
);
}
}
Ok(()) Ok(())
} }
+18 -57
View File
@@ -29,7 +29,6 @@ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
RoomVersionId, ServerName, RoomVersionId, ServerName,
api::{ api::{
OAuthClientScope,
client::{discovery::discover_support::ContactRole, rtc::RtcTransport}, client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
federation::discovery::OldVerifyKey, federation::discovery::OldVerifyKey,
}, },
@@ -2751,12 +2750,7 @@ pub struct OauthConfig {
compatibility_mode: OAuthMode, compatibility_mode: OAuthMode,
/// display: hidden /// display: hidden
#[serde(default)]
pub oidc: Option<OidcConfig>, pub oidc: Option<OidcConfig>,
/// display: hidden
#[serde(default)]
pub clients: HashMap<String, OAuthClient>,
} }
impl OauthConfig { impl OauthConfig {
@@ -2826,9 +2820,10 @@ pub struct OidcConfig {
/// Additional scopes Continuwuity should request from the IDP. This may be /// Additional scopes Continuwuity should request from the IDP. This may be
/// necessary to access certain claims. Continuwuity always requests the /// necessary to access certain claims. Continuwuity always requests the
/// `openid` scope, regardless of the contents of this option, /// `openid` scope, regardless of the value of this option.
/// and will also request the `profile` scope by default if this option is ///
/// not set. /// Defaults to only the `profile` scope, as recommended by the OIDC
/// specification.
/// ///
/// default: ["profile"] /// default: ["profile"]
#[serde(default = "default_additional_scopes")] #[serde(default = "default_additional_scopes")]
@@ -2846,6 +2841,20 @@ pub struct OidcConfig {
#[serde(default)] #[serde(default)]
pub additional_trusted_audiences: BTreeSet<Audience>, 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 /// The name of the identity provider. If this is set, the login page's
/// button reads "Continue with <name>" instead of just "Continue". /// button reads "Continue with <name>" instead of just "Continue".
/// ///
@@ -2998,54 +3007,6 @@ impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter<K> {
} }
} }
#[derive(Clone, Debug, Deserialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.oauth.clients.\"$id\"",
optional = "true",
subheader = "\
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available."
)]
pub struct OAuthClient {
/// The client's client secret.
///
/// This must be supplied as the `client_secret` parameter when requesting
/// an access token with the OAuth 2.0 token endpoint. Continuwuity does
/// not check the `Authorization` header for requests to this endpoint.
pub client_secret: String,
/// A list of scopes that the client may request. Continuwuity allows static
/// clients to request the following scopes:
///
/// - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
/// This scope grants access to the Matrix server administration APIs, as
/// well as Continuwuity's internal admin API (currently a work in
/// progress).
/// - "urn:matrix:client:api:*": This scope grants access to the Matrix
/// client-server API. Most endpoints require an authenticated Matrix user
/// and thus will not be usable by static clients.
///
/// The `urn:matrix:client:device:<id>` scope may not be requested by static
/// clients.
///
/// Scopes listed here are not granted by default. The client must
/// explicitly include them in the `scope` parameter of its access token
/// request.
///
/// default: []
pub scopes: BTreeSet<OAuthClientScope>,
}
const DEPRECATED_KEYS: &[&str] = &[ const DEPRECATED_KEYS: &[&str] = &[
"allow_check_for_updates", "allow_check_for_updates",
"allow_moderators_to_view_redacted_content", "allow_moderators_to_view_redacted_content",
-28
View File
@@ -15,7 +15,6 @@ use opentelemetry_instrumentation_tower::http::server::LayerBuilder as OtelHttpL
use tower::ServiceBuilder; use tower::ServiceBuilder;
use tower_http::{ use tower_http::{
catch_panic::CatchPanicLayer, catch_panic::CatchPanicLayer,
cors::{self, CorsLayer},
sensitive_headers::SetSensitiveHeadersLayer, sensitive_headers::SetSensitiveHeadersLayer,
set_header::SetResponseHeaderLayer, set_header::SetResponseHeaderLayer,
timeout::{RequestBodyTimeoutLayer, ResponseBodyTimeoutLayer, TimeoutLayer}, timeout::{RequestBodyTimeoutLayer, ResponseBodyTimeoutLayer, TimeoutLayer},
@@ -101,7 +100,6 @@ pub(crate) fn build(services: &Arc<Services>) -> Result<(Router, Guard)> {
header::CONTENT_SECURITY_POLICY, header::CONTENT_SECURITY_POLICY,
HeaderValue::from_str(&CONDUWUIT_CSP.join(";"))?, HeaderValue::from_str(&CONDUWUIT_CSP.join(";"))?,
)) ))
.layer(cors_layer(server))
.layer(body_limit_layer(server)) .layer(body_limit_layer(server))
.layer(CatchPanicLayer::custom(move |panic| catch_panic(panic, services_.clone()))); .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 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 /// Methods outside the standard set can never match a route; record them as
/// `_OTHER`, as the semantic conventions ask, so clients cannot create new /// `_OTHER`, as the semantic conventions ask, so clients cannot create new
/// metric attribute values. /// metric attribute values.
+30 -2
View File
@@ -1,10 +1,11 @@
use std::sync::Arc; use std::{sync::Arc, time::Duration};
use axum::{Router, response::IntoResponse}; use axum::{Router, response::IntoResponse};
use conduwuit::Error; use conduwuit::Error;
use conduwuit_service::{Services, state, state::Guard}; use conduwuit_service::{Services, state, state::Guard};
use http::{StatusCode, Uri}; use http::{HeaderName, Method, StatusCode, Uri, header};
use ruma::api::error::ErrorKind; use ruma::api::error::ErrorKind;
use tower_http::cors::{self, CorsLayer};
pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) { pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
let router = Router::<state::State>::new(); let router = Router::<state::State>::new();
@@ -14,6 +15,7 @@ pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
// is dropped. // is dropped.
let (state, guard) = unsafe { state::create(services.clone()) }; let (state, guard) = unsafe { state::create(services.clone()) };
let router = conduwuit_api::router::build(router, state) let router = conduwuit_api::router::build(router, state)
.layer(api_cors_layer())
.merge(conduwuit_web::build(services)) .merge(conduwuit_web::build(services))
.fallback(not_found) .fallback(not_found)
.with_state(state); .with_state(state);
@@ -24,3 +26,29 @@ pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
async fn not_found(_uri: Uri) -> impl IntoResponse { async fn not_found(_uri: Uri) -> impl IntoResponse {
Error::Request(ErrorKind::Unrecognized, "not found :(".into(), StatusCode::NOT_FOUND) 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))
}
-7
View File
@@ -125,12 +125,6 @@ impl ClientMetadata {
} }
} }
if self.grant_types.contains(&GrantType::ClientCredentials) {
return Err(
"Dynamically registered clients may not use the client credentials grant."
);
}
Ok(()) Ok(())
} }
} }
@@ -150,7 +144,6 @@ pub enum GrantType {
#[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")] #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
DeviceCode, DeviceCode,
RefreshToken, RefreshToken,
ClientCredentials,
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
+34 -9
View File
@@ -3,10 +3,11 @@ use std::{
collections::BTreeSet, collections::BTreeSet,
error::Error, error::Error,
fmt::{Debug, Display}, fmt::{Debug, Display},
str::FromStr,
}; };
use regex::regex; use regex::regex;
use ruma::{OwnedDeviceId, api::OAuthClientScope}; use ruma::{OwnedDeviceId, OwnedUserId, api::OAuthClientScope};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use url::Url; use url::Url;
@@ -26,6 +27,8 @@ pub struct AuthorizationCodeQuery {
pub code_challenge_method: CodeChallengeMethod, pub code_challenge_method: CodeChallengeMethod,
#[serde(default)] #[serde(default)]
pub prompt: Option<Prompt>, pub prompt: Option<Prompt>,
#[serde(default)]
pub login_hint: Option<String>,
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
@@ -38,6 +41,8 @@ pub struct AuthorizationCodeResponse {
pub struct DeviceCodeRequest { pub struct DeviceCodeRequest {
pub client_id: String, pub client_id: String,
pub scope: RawScopes, pub scope: RawScopes,
#[serde(default, rename = "org.matrix.msc4198.login_hint")]
pub login_hint: Option<String>,
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
@@ -53,6 +58,8 @@ pub struct DeviceCodeResponse {
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DeviceCodeVerifyQuery { pub struct DeviceCodeVerifyQuery {
pub user_code: Option<String>, 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)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
@@ -102,7 +109,7 @@ impl Display for RequestedScopes {
} }
} }
#[derive(Debug, Clone, Default, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RawScopes(String); pub struct RawScopes(String);
impl RawScopes { impl RawScopes {
@@ -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)] #[derive(Serialize, Debug, Clone)]
pub struct OAuthError { pub struct OAuthError {
pub error: ErrorCode, pub error: ErrorCode,
@@ -257,11 +288,6 @@ pub enum TokenRequestType {
RefreshToken { RefreshToken {
refresh_token: String, refresh_token: String,
}, },
ClientCredentials {
client_secret: String,
#[serde(default)]
scope: RawScopes,
},
} }
impl TokenRequestType { impl TokenRequestType {
@@ -271,7 +297,6 @@ impl TokenRequestType {
| Self::AuthorizationCode { .. } => GrantType::AuthorizationCode, | Self::AuthorizationCode { .. } => GrantType::AuthorizationCode,
| Self::DeviceCode { .. } => GrantType::DeviceCode, | Self::DeviceCode { .. } => GrantType::DeviceCode,
| Self::RefreshToken { .. } => GrantType::RefreshToken, | Self::RefreshToken { .. } => GrantType::RefreshToken,
| Self::ClientCredentials { .. } => GrantType::ClientCredentials,
} }
} }
} }
@@ -281,7 +306,7 @@ pub struct TokenResponse {
pub access_token: String, pub access_token: String,
pub token_type: TokenType, pub token_type: TokenType,
pub expires_in: u64, pub expires_in: u64,
pub refresh_token: Option<String>, pub refresh_token: String,
pub scope: String, pub scope: String,
} }
+20 -118
View File
@@ -7,10 +7,10 @@ use std::{
use base64::Engine; use base64::Engine;
use conduwuit::{ use conduwuit::{
Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, Result, SyncMutex,
config::experiments::ToggledExperiment, config::experiments::ToggledExperiment,
error, info, error, info,
utils::{self, MutexMap, hash::sha256, string::constant_time_eq}, utils::{self, MutexMap, hash::sha256},
warn, warn,
}; };
use database::{Deserialized, Json, Map}; use database::{Deserialized, Json, Map};
@@ -27,9 +27,8 @@ use crate::{
client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType}, client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType},
grant::{ grant::{
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod, AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RawScopes, DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RequestedScopes,
RequestedScopes, ResponseMode, TokenRequest, TokenRequestType, TokenResponse, ResponseMode, TokenRequest, TokenRequestType, TokenResponse, TokenType,
TokenType,
}, },
}, },
users::{self, DeviceToken, PreviousTokenAction}, users::{self, DeviceToken, PreviousTokenAction},
@@ -54,7 +53,6 @@ pub struct Service {
tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>, tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>,
pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>, pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>,
pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>, pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>,
client_credential_sessions: SyncMutex<HashMap<String, ClientCredentialsSession>>,
} }
struct Data { struct Data {
@@ -108,12 +106,6 @@ struct RefreshTokenInfo {
device_id: OwnedDeviceId, device_id: OwnedDeviceId,
} }
pub struct ClientCredentialsSession {
pub client_id: String,
pub scopes: BTreeSet<OAuthClientScope>,
created_at: SystemTime,
}
struct PendingAuthCodeGrant { struct PendingAuthCodeGrant {
authorizing_user: OwnedUserId, authorizing_user: OwnedUserId,
requested_scopes: RequestedScopes, requested_scopes: RequestedScopes,
@@ -143,6 +135,7 @@ struct PendingDeviceCodeGrant {
requested_scopes: RequestedScopes, requested_scopes: RequestedScopes,
client_name: Option<String>, client_name: Option<String>,
client_id: String, client_id: String,
login_hint: Option<String>,
requested_at: SystemTime, requested_at: SystemTime,
} }
@@ -173,6 +166,7 @@ pub struct DeviceCodeGrantInfo {
pub device_code: String, pub device_code: String,
pub client_metadata: ClientMetadata, pub client_metadata: ClientMetadata,
pub requested_scopes: RequestedScopes, pub requested_scopes: RequestedScopes,
pub login_hint: Option<String>,
} }
/// A time-limited grant for a client to perform some sensitive action. /// A time-limited grant for a client to perform some sensitive action.
@@ -209,7 +203,6 @@ impl crate::Service for Service {
tickets: SyncMutex::default(), tickets: SyncMutex::default(),
pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
client_credential_sessions: SyncMutex::default(),
})) }))
} }
@@ -431,6 +424,7 @@ impl Service {
requested_scopes, requested_scopes,
client_name: client_metadata.client_name, client_name: client_metadata.client_name,
client_id: query.client_id, client_id: query.client_id,
login_hint: query.login_hint,
requested_at: SystemTime::now(), requested_at: SystemTime::now(),
}; };
@@ -451,7 +445,7 @@ impl Service {
&self, &self,
supplied_user_code: &str, supplied_user_code: &str,
) -> Option<DeviceCodeGrantInfo> { ) -> 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 pending_grants = self.pending_device_code_grants.lock();
let (device_code, grant) = pending_grants let (device_code, grant) = pending_grants
@@ -460,7 +454,12 @@ impl Service {
matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code) 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 let client_metadata = self
@@ -472,6 +471,7 @@ impl Service {
device_code, device_code,
client_metadata, client_metadata,
requested_scopes, requested_scopes,
login_hint,
}) })
} }
@@ -506,25 +506,12 @@ impl Service {
pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> { pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> {
let TokenRequest { client_id, request } = request; let TokenRequest { client_id, request } = request;
if !matches!(request, TokenRequestType::ClientCredentials { .. }) {
// The client credentials grant can only be used by statically
// registered clients, and the other grant types can
// only be used by dynamically registered clients, so we
// don't look up the dynamic client metadata if the token request is
// for the client credentials grant.
let Some(client_metadata) = self.get_client_metadata(&client_id).await else { let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
return Err(OAuthError::new_static( return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Invalid client ID"));
ErrorCode::InvalidClient,
"Invalid client ID",
));
}; };
if !client_metadata.grant_types.contains(&request.grant_type()) { if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::unauthorized_client( return Err(OAuthError::unauthorized_client("Client cannot request this grant type"));
"Client cannot request this grant type",
));
}
} }
match request { match request {
@@ -596,8 +583,6 @@ impl Service {
}, },
| TokenRequestType::RefreshToken { refresh_token } => | TokenRequestType::RefreshToken { refresh_token } =>
self.refresh_session(client_id, refresh_token).await, self.refresh_session(client_id, refresh_token).await,
| TokenRequestType::ClientCredentials { client_secret, scope: scopes } =>
self.create_client_credentials_token(&client_id, &client_secret, &scopes),
} }
} }
@@ -614,12 +599,8 @@ impl Service {
self.services.users.find_from_token(&token).await self.services.users.find_from_token(&token).await
{ {
(user_id, device_id) (user_id, device_id)
} else if self.get_client_credentials_session(&token).is_some() {
return Err(OAuthError::invalid_grant(
"Access tokens for static clients cannot be revoked.",
));
} else { } else {
return Err(OAuthError::invalid_grant("Invalid access or refresh token.")); return Err(OAuthError::invalid_grant("Invalid access or refersh token"));
}; };
// This will also call [`Self::remove_session`] // This will also call [`Self::remove_session`]
@@ -756,7 +737,7 @@ impl Service {
token_type: TokenType::Bearer, token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(), expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope: response_scope, scope: response_scope,
refresh_token: Some(refresh_token), refresh_token,
}) })
} }
@@ -883,89 +864,10 @@ impl Service {
token_type: TokenType::Bearer, token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(), expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope, scope,
refresh_token: Some(new_refresh_token), refresh_token: new_refresh_token,
}) })
} }
fn create_client_credentials_token(
&self,
client_id: &str,
client_secret: &str,
scopes: &RawScopes,
) -> Result<TokenResponse, OAuthError> {
let now = SystemTime::now();
let Some(client) = self.services.config.oauth.clients.get(client_id) else {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Unknown client ID"));
};
let RequestedScopes { device_id, scopes } = scopes
.to_scopes()
.map_err(|err| OAuthError::new(ErrorCode::InvalidGrant, err))?;
if device_id.is_some() {
return Err(OAuthError::new_static(
ErrorCode::InvalidGrant,
"Static clients may not request a device ID",
));
}
if !constant_time_eq(client_secret, &client.client_secret) {
return Err(OAuthError::new_static(
ErrorCode::InvalidClient,
"Client secret does not match",
));
}
if !scopes.is_subset(&client.scopes) {
return Err(OAuthError::new_static(
ErrorCode::InvalidScope,
"This client may not request those scopes",
));
}
let mut sessions = self.client_credential_sessions.lock();
// Clear expired sessions while we're at it
sessions.retain(|_, session| {
now.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
});
let access_token = Self::generate_token();
let scope = scopes.iter().join(" ");
sessions.insert(access_token.clone(), ClientCredentialsSession {
client_id: client_id.to_owned(),
scopes,
created_at: now,
});
Ok(TokenResponse {
access_token,
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
refresh_token: None,
scope,
})
}
pub fn get_client_credentials_session(
&self,
token: &str,
) -> Option<SyncMappedMutexGuard<'_, ClientCredentialsSession>> {
let sessions = self.client_credential_sessions.lock();
SyncMutexGuard::try_map(sessions, |sessions| {
sessions.get_mut(token).filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
})
})
.ok()
}
pub async fn remove_session(&self, user_id: &UserId, device_id: &DeviceId) { pub async fn remove_session(&self, user_id: &UserId, device_id: &DeviceId) {
let _lock = self.session_mutex.lock(&(user_id, device_id)).await; let _lock = self.session_mutex.lock(&(user_id, device_id)).await;
let session_info = self.get_session_info_for_device(user_id, device_id).await; let session_info = self.get_session_info_for_device(user_id, device_id).await;
+12 -1
View File
@@ -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, .. } = let OidcClient { machine, config, .. } =
self.client.as_ref().expect("oidc should be configured"); self.client.as_ref().expect("oidc should be configured");
let machine = machine.wait().await.read().clone(); let machine = machine.wait().await.read().clone();
@@ -276,6 +280,13 @@ impl Service {
auth_url = auth_url.add_prompt(prompt); 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(); let (auth_url, csrf_token, nonce) = auth_url.url();
(PendingSession { pkce_verifier, nonce, csrf_token }, auth_url) (PendingSession { pkce_verifier, nonce, csrf_token }, auth_url)
+84 -27
View File
@@ -522,13 +522,6 @@ impl Service {
let device_changes = let device_changes =
self.select_edus_device_changes(server_name, batch, &max_edu_count, &events_len); self.select_edus_device_changes(server_name, batch, &max_edu_count, &events_len);
let receipts: OptionFuture<_> = self
.server
.config
.allow_outgoing_read_receipts
.then(|| self.select_edus_receipts(server_name, batch, &max_edu_count))
.into();
let presence: OptionFuture<_> = self let presence: OptionFuture<_> = self
.server .server
.config .config
@@ -536,11 +529,20 @@ impl Service {
.then(|| self.select_edus_presence(server_name, batch, &max_edu_count)) .then(|| self.select_edus_presence(server_name, batch, &max_edu_count))
.into(); .into();
let (device_changes, receipts, presence) = join!(device_changes, receipts, presence); let (device_changes, presence) = join!(device_changes, presence);
let mut events = device_changes; let mut events = device_changes;
events.extend(presence.into_iter().flatten()); events.extend(presence.into_iter().flatten());
events.extend(receipts.into_iter().flatten());
// leave a slot for the queued event, but always allow one receipt EDU
let edu_limit = (EDU_LIMIT - 1).saturating_sub(events.len()).max(1);
if self.server.config.allow_outgoing_read_receipts {
// must be selected last, as it may lower max_edu_count
events.extend(
self.select_edus_receipts(server_name, batch, &max_edu_count, edu_limit)
.await,
);
}
// TODO(nex): some EDUs like typing need flattening // TODO(nex): some EDUs like typing need flattening
@@ -616,9 +618,11 @@ impl Service {
server_name: &ServerName, server_name: &ServerName,
since: (u64, u64), since: (u64, u64),
max_edu_count: &AtomicU64, max_edu_count: &AtomicU64,
) -> Option<EduBuf> { edu_limit: usize,
) -> EduVec {
let num = AtomicUsize::new(0); let num = AtomicUsize::new(0);
let receipts: BTreeMap<OwnedRoomId, ReceiptMap> = self let deferred = AtomicU64::new(u64::MAX);
let rooms: Vec<_> = self
.services .services
.state_cache .state_cache
.server_rooms(server_name) .server_rooms(server_name)
@@ -627,33 +631,54 @@ impl Service {
return None; return None;
} }
let receipt_map = self let maps = self
.select_edus_receipts_room(&room_id, since, max_edu_count, &num) .select_edus_receipts_room(
&room_id,
since,
max_edu_count,
&num,
edu_limit,
&deferred,
)
.await; .await;
(!receipt_map.read.is_empty()).then_some((room_id, receipt_map)) (!maps.is_empty()).then_some((room_id, maps))
}) })
.collect() .collect()
.await; .await;
if receipts.is_empty() { // the next transaction starts at the first receipt that did not fit
return None; max_edu_count
.fetch_min(deferred.load(Ordering::Relaxed).saturating_sub(1), Ordering::Relaxed);
let mut contents = Vec::<BTreeMap<OwnedRoomId, ReceiptMap>>::new();
for (room_id, maps) in rooms {
for (index, read) in maps.into_iter().enumerate() {
if index == contents.len() {
contents.push(BTreeMap::new());
}
contents[index].insert(room_id.clone(), ReceiptMap::new(read));
}
} }
let receipt_content = Edu::Receipt(ReceiptContent::new(receipts)); contents
.into_iter()
.map(|content| {
let edu = Edu::Receipt(ReceiptContent::new(content));
let mut buf = EduBuf::new(); let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &receipt_content) serde_json::to_writer(&mut buf, &edu)
.expect("Failed to serialize Receipt EDU to JSON vec"); .expect("Failed to serialize Receipt EDU to JSON vec");
buf
Some(buf) })
.collect()
} }
/// Look for read receipts in this room /// Look for read receipts in this room
#[tracing::instrument( #[tracing::instrument(
name = "receipts", name = "receipts",
level = "trace", level = "trace",
skip(self, since, max_edu_count, num) skip(self, since, max_edu_count, num, deferred)
)] )]
async fn select_edus_receipts_room( async fn select_edus_receipts_room(
&self, &self,
@@ -661,14 +686,16 @@ impl Service {
since: (u64, u64), since: (u64, u64),
max_edu_count: &AtomicU64, max_edu_count: &AtomicU64,
num: &AtomicUsize, num: &AtomicUsize,
) -> ReceiptMap { edu_limit: usize,
deferred: &AtomicU64,
) -> Vec<BTreeMap<OwnedUserId, ReceiptData>> {
let receipts = self let receipts = self
.services .services
.read_receipt .read_receipt
.readreceipts_since(room_id, Some(since.0)); .readreceipts_since(room_id, Some(since.0));
pin_mut!(receipts); pin_mut!(receipts);
let mut read = BTreeMap::<OwnedUserId, ReceiptData>::new(); let mut maps = Vec::new();
while let Some((user_id, count, read_receipt)) = receipts.next().await { while let Some((user_id, count, read_receipt)) = receipts.next().await {
if count > since.1 { if count > since.1 {
break; break;
@@ -704,14 +731,20 @@ impl Service {
let receipt_data = ReceiptData::new(receipt, vec![event_id]); let receipt_data = ReceiptData::new(receipt, vec![event_id]);
if read.insert(user_id, receipt_data).is_none() { let Some(index) = add_receipt(&mut maps, user_id, receipt_data, edu_limit) else {
if num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT { deferred.fetch_min(count, Ordering::Relaxed);
break;
};
// only a user's first receipt counts towards the limit
if index == 0
&& num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT
{
break; break;
} }
} }
}
ReceiptMap::new(read) maps
} }
/// Look for presence /// Look for presence
@@ -1110,3 +1143,27 @@ impl Service {
) )
} }
} }
/// Adds the receipt to the first map without one from the user and returns
/// that map's index, or `None` if all `limit` maps have one.
fn add_receipt(
maps: &mut Vec<BTreeMap<OwnedUserId, ReceiptData>>,
user_id: OwnedUserId,
receipt: ReceiptData,
limit: usize,
) -> Option<usize> {
let index = maps
.iter()
.position(|map| !map.contains_key(&user_id))
.unwrap_or(maps.len());
if index >= limit {
return None;
}
if index == maps.len() {
maps.push(BTreeMap::new());
}
maps[index].insert(user_id, receipt);
Some(index)
}
+22 -3
View File
@@ -1,14 +1,19 @@
use std::iter::once; use std::{collections::BTreeMap, iter::once};
use conduwuit::{ use conduwuit::{
Error, Error,
matrix::{PartialPdu, pdu::sticky}, matrix::{PartialPdu, pdu::sticky},
}; };
use futures::{StreamExt, stream::FuturesUnordered}; use futures::{StreamExt, stream::FuturesUnordered};
use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name}; use ruma::{
RoomId, UserId,
api::federation::transactions::edu::ReceiptData,
events::{receipt::Receipt, sticky::StickyDurationMs},
server_name, user_id,
};
use serde_json::{json, value::to_raw_value}; use serde_json::{json, value::to_raw_value};
use super::{CurTransactionStatus, TransactionStatus}; use super::{CurTransactionStatus, TransactionStatus, add_receipt};
use crate::{ use crate::{
sending::{Destination, EduBuf, SendingEvent}, sending::{Destination, EduBuf, SendingEvent},
test_utils::{test_services, test_services_with}, test_utils::{test_services, test_services_with},
@@ -196,3 +201,17 @@ async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled(
assert_eq!(active_after_startup, 0); assert_eq!(active_after_startup, 0);
assert_eq!(sending_after_startup, 0); assert_eq!(sending_after_startup, 0);
} }
#[test]
fn add_receipt_separates_receipts_of_one_user() {
let alice = user_id!("@alice:example.org");
let bob = user_id!("@bob:example.org");
let receipt = || ReceiptData::new(Receipt::default(), vec![]);
let mut maps = Vec::new();
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(0));
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(1));
assert_eq!(add_receipt(&mut maps, bob.to_owned(), receipt(), 2), Some(0));
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), None);
assert_eq!(maps.iter().map(BTreeMap::len).collect::<Vec<_>>(), [2, 1]);
}
+31 -1
View File
@@ -15,7 +15,10 @@ use futures::{FutureExt, Stream, StreamExt};
use lettre::Address; use lettre::Address;
use ruma::{ use ruma::{
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId,
api::client::profile::PropagateTo, api::client::{
profile::PropagateTo,
uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
},
events::{ events::{
GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent, GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent,
invite_permission_config::InvitePermissionAction, push_rules::PushRulesEvent, invite_permission_config::InvitePermissionAction, push_rules::PushRulesEvent,
@@ -721,6 +724,33 @@ impl super::Service {
Ok(user_id) 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 /// Creates an OpenID token, which can be used to prove that a user has
/// access to an account (primarily for integrations) /// access to an account (primarily for integrations)
pub fn create_openid_token(&self, user_id: &UserId, token: &str) -> Result<u64> { pub fn create_openid_token(&self, user_id: &UserId, token: &str) -> Result<u64> {
+1 -1
View File
@@ -12,7 +12,7 @@ pub use account::{AccessTokenStatus, AccountStatus};
use conduwuit::{Err, Error, Result, err, utils}; use conduwuit::{Err, Error, Result, err, utils};
use database::Map; use database::Map;
pub use device::{DeviceToken, PreviousTokenAction}; 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 ruma::{UserId, api::error::ErrorKind, encryption::CrossSigningKey, serde::Raw};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
+51
View File
@@ -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 { impl super::Service {
pub async fn set_profile_field( pub async fn set_profile_field(
&self, &self,
@@ -360,4 +384,31 @@ impl super::Service {
.ready_for_each(|(key, _)| self.set_profile_key(user_id, &key, None)) .ready_for_each(|(key, _)| self.set_profile_key(user_id, &key, None))
.await; .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
},
})
}
} }
+3 -2
View File
@@ -1,5 +1,5 @@
use axum::{Extension, Router, extract::State, routing::on}; use axum::{Extension, Router, extract::State, routing::on};
use conduwuit_service::oauth::OAuthTicket; use conduwuit_service::{oauth::OAuthTicket, users::ProfileQuerier};
use crate::{ use crate::{
extract::PostForm, extract::PostForm,
@@ -33,7 +33,8 @@ async fn route_cross_signing_reset(
PostForm(form): PostForm<()>, PostForm(form): PostForm<()>,
) -> Result { ) -> Result {
let user_id = user.expect_recent(LoginTarget::CrossSigningReset)?; 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() { if form.is_some() {
services services
+3 -1
View File
@@ -1,5 +1,6 @@
use axum::{Extension, Router, extract::State, routing::on}; use axum::{Extension, Router, extract::State, routing::on};
use conduwuit_api::client::full_user_deactivate; use conduwuit_api::client::full_user_deactivate;
use conduwuit_service::users::ProfileQuerier;
use futures::StreamExt; use futures::StreamExt;
use ruma::{OwnedRoomId, OwnedUserId, UserId}; use ruma::{OwnedRoomId, OwnedUserId, UserId};
use tower_sessions::Session; use tower_sessions::Session;
@@ -65,7 +66,8 @@ async fn route_deactivate(
PostForm(form): PostForm<DeactivateForm>, PostForm(form): PostForm<DeactivateForm>,
) -> Result { ) -> Result {
let user_id = user.expect_recent(LoginTarget::Deactivate)?; 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 = { let body = {
if !services.config.allow_deactivation || services.oidc.enabled() { if !services.config.allow_deactivation || services.oidc.enabled() {
+9 -5
View File
@@ -4,7 +4,9 @@ use axum::{
routing::{get, on, post}, routing::{get, on, post},
}; };
use conduwuit_core::warn; 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 lettre::{Address, message::Mailbox};
use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId}; use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -88,7 +90,7 @@ async fn route_change_email(
let Some(form) = form else { let Some(form) = form else {
return response!(ChangeEmail::new( return response!(ChangeEmail::new(
context.clone(), context.clone(),
UserCard::for_local_user(&services, user_id.clone()).await, UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await,
services services
.threepid .threepid
.get_email_for_localpart(user_id.localpart()) .get_email_for_localpart(user_id.localpart())
@@ -134,7 +136,7 @@ async fn route_change_email(
response!(ChangeEmailValidate::new( response!(ChangeEmailValidate::new(
context, context,
UserCard::for_local_user(&services, user_id).await, UserCard::for_local_user(&services, user_id.clone(), ProfileQuerier::Owner).await,
ChangeEmailValidateBody::ValidationPending { ChangeEmailValidateBody::ValidationPending {
session_id, session_id,
client_secret, client_secret,
@@ -158,7 +160,8 @@ async fn get_change_email_validate(
user: User, user: User,
) -> Result { ) -> Result {
let user_id = user.expect(LoginTarget::ChangeEmail)?; 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() { if !services.threepid.email_requirement().may_change() {
return Err(WebError::Forbidden("You may not change your email address.".to_owned())); return Err(WebError::Forbidden("You may not change your email address.".to_owned()));
@@ -198,7 +201,8 @@ async fn post_delete_email(
user: User, user: User,
) -> Result { ) -> Result {
let user_id = user.expect(LoginTarget::ChangeEmail)?; 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() { if !services.threepid.email_requirement().may_remove() {
return Err(WebError::Forbidden("You may not remove your email address.".to_owned())); return Err(WebError::Forbidden("You may not remove your email address.".to_owned()));
+88 -46
View File
@@ -6,7 +6,8 @@ use axum::{
response::{IntoResponse, Redirect}, response::{IntoResponse, Redirect},
routing::{get, on}, 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 openidconnect::core::CoreAuthPrompt;
use ruma::{ use ruma::{
OwnedUserId, OwnedUserId,
@@ -75,27 +76,44 @@ struct LoginForm {
async fn route_login( async fn route_login(
State(services): State<crate::State>, State(services): State<crate::State>,
Extension(context): Extension<TemplateContext>, 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, session_store: Session,
user: User<true>, user: User<true>,
PostForm(form): PostForm<LoginForm>, PostForm(form): PostForm<LoginForm>,
) -> Result { ) -> 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 login_type = if services.oidc.enabled() {
let (session, redirect_url) = services let prompt = match intent {
.oidc
.begin_session(match intent {
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount), | Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
| _ if reauthenticate => Some(CoreAuthPrompt::Consent), | _ if reauthenticate => Some(CoreAuthPrompt::Consent),
| _ => None, | _ => None,
}) };
.await;
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 session_store
.insert(OIDC_SESSION_ID_KEY, OidcSession { .insert(OIDC_SESSION_ID_KEY, OidcSession {
next: next.clone().unwrap_or_default(), 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 .await
.expect("should be able to serialize OIDC session"); .expect("should be able to serialize OIDC session");
@@ -115,17 +133,28 @@ async fn route_login(
} }
}; };
let body = match &user_id { let body = match (&current_user, &login_hint) {
| None => LoginBody::Unauthenticated { | (None, None) => LoginBody::Unauthenticated {
server_name: services.globals.server_name().to_string(), server_name: services.globals.server_name().to_string(),
next: next.clone(), 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 { if !reauthenticate {
return response!(Redirect::to(&next.unwrap_or_default().target_path())); 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 } LoginBody::Authenticated { user_card }
}, },
@@ -134,41 +163,10 @@ async fn route_login(
let mut template = Login::new(context, body, login_type, None); let mut template = Login::new(context, body, login_type, None);
if let Some(form) = form { if let Some(form) = form {
let login_result = match (user_id, form.identifier) { let user_id = match perform_login(&services, current_user, login_hint, form).await {
| (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 {
| Ok(user_id) => user_id, | Ok(user_id) => user_id,
| Err(err) => { | Err(err) => {
let error_message = if let conduwuit_core::Error::Request(_, message, _) = err { template.login_error = Some(err);
message.into_owned()
} else {
"Internal login error".to_owned()
};
template.login_error = Some(error_message);
return response!(template); return response!(template);
}, },
}; };
@@ -186,6 +184,50 @@ async fn route_login(
response!(template) 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 { async fn get_logout(session: Session, RawQuery(query): RawQuery) -> impl IntoResponse {
let _ = session.remove::<OwnedUserId>(User::KEY).await; let _ = session.remove::<OwnedUserId>(User::KEY).await;
+44 -7
View File
@@ -5,11 +5,12 @@ use axum::{
routing::get, routing::get,
}; };
use conduwuit_core::utils::{IterStream, ReadyExt, stream::TryExpect}; use conduwuit_core::utils::{IterStream, ReadyExt, stream::TryExpect};
use conduwuit_service::threepid::EmailRequirement; use conduwuit_service::{threepid::EmailRequirement, users::ProfileQuerier};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
OwnedClientSecret, OwnedDeviceId, OwnedSessionId, OwnedClientSecret, OwnedDeviceId, OwnedSessionId,
api::client::discovery::get_authorization_server_metadata::v1::AccountManagementAction, api::client::discovery::get_authorization_server_metadata::v1::AccountManagementAction,
assign,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -19,9 +20,10 @@ use crate::{
pages::{ pages::{
Result, TemplateContext, Result, TemplateContext,
components::{DeviceCard, DeviceCardStyle, UserCard}, components::{DeviceCard, DeviceCardStyle, UserCard},
switch_account::{LoginHintQuery, prompt_to_switch_account},
}, },
response, response,
session::{LoginTarget, User}, session::{LoginQuery, LoginTarget, User},
template, template,
}; };
@@ -82,7 +84,8 @@ async fn get_account(
) -> Result { ) -> Result {
let user_id = user.expect(LoginTarget::Account)?; 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() { if services.users.is_locked(&user_id).await.unwrap() {
return response!(Account::new(context, user_card, AccountBody::Locked)); return response!(Account::new(context, user_card, AccountBody::Locked));
@@ -138,15 +141,49 @@ async fn get_account(
})) }))
} }
#[derive(Deserialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
struct AccountDeeplinkQuery { pub(crate) struct AccountDeeplinkQuery {
action: Option<AccountManagementAction>, pub action: Option<AccountManagementAction>,
device_id: Option<OwnedDeviceId>, 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( async fn get_account_deeplink(
State(services): State<crate::State>,
Extension(context): Extension<TemplateContext>,
Expect(Query(query)): Expect<Query<AccountDeeplinkQuery>>, Expect(Query(query)): Expect<Query<AccountDeeplinkQuery>>,
user: User<true>,
) -> Result { ) -> Result {
if let Some(current_user) = user.into_session() {
if let Some(switcher) = prompt_to_switch_account(
&services,
context,
&current_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) { let redirect_target = match query.action.unwrap_or(AccountManagementAction::Profile) {
| AccountManagementAction::AccountDeactivate => "deactivate".to_owned(), | AccountManagementAction::AccountDeactivate => "deactivate".to_owned(),
| AccountManagementAction::CrossSigningReset => "cross_signing_reset".to_owned(), | AccountManagementAction::CrossSigningReset => "cross_signing_reset".to_owned(),
+3 -2
View File
@@ -1,5 +1,5 @@
use axum::{Extension, Router, extract::State, routing::on}; use axum::{Extension, Router, extract::State, routing::on};
use conduwuit_service::users::HashedPassword; use conduwuit_service::users::{HashedPassword, ProfileQuerier};
use ruma::UserId; use ruma::UserId;
use validator::{Validate, ValidationError, ValidationErrors}; use validator::{Validate, ValidationError, ValidationErrors};
@@ -73,7 +73,8 @@ async fn route_change_password(
} }
let user_id = user.expect(LoginTarget::ChangePassword)?; 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 { let body = if let Some(form) = form {
match change_password(&services, &user_id, form).await? { match change_password(&services, &user_id, form).await? {
+5 -2
View File
@@ -5,7 +5,9 @@ use axum::{
}; };
use conduwuit_core::warn; use conduwuit_core::warn;
use conduwuit_service::{ use conduwuit_service::{
mailer::messages, threepid::session::ValidationSessions, users::HashedPassword, mailer::messages,
threepid::session::ValidationSessions,
users::{HashedPassword, ProfileQuerier},
}; };
use lettre::{Address, message::Mailbox}; use lettre::{Address, message::Mailbox};
use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId, UserId}; use ruma::{ClientSecret, OwnedClientSecret, OwnedSessionId, UserId};
@@ -207,7 +209,8 @@ async fn route_reset_password_validate(
return Ok(response); 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 Some(form) = form {
if let Err(err) = form.validate() { if let Err(err) = form.validate() {
+47 -8
View File
@@ -2,7 +2,9 @@ use std::{collections::BTreeSet, time::SystemTime};
use askama::{Template, filters::HtmlSafe}; use askama::{Template, filters::HtmlSafe};
use conduwuit_core::utils; use conduwuit_core::utils;
use conduwuit_service::{Services, oauth::client_metadata::ClientMetadata}; use conduwuit_service::{
Services, oauth::client_metadata::ClientMetadata, users::ProfileQuerier,
};
use ruma::{ use ruma::{
OwnedDeviceId, OwnedUserId, UserId, OwnedDeviceId, OwnedUserId, UserId,
api::{OAuthClientScope, client::device::Device}, api::{OAuthClientScope, client::device::Device},
@@ -25,10 +27,27 @@ pub(super) struct Avatar {
impl HtmlSafe for Avatar {} impl HtmlSafe for Avatar {}
impl Avatar { impl Avatar {
pub(super) async fn for_local_user(services: &Services, user_id: &UserId) -> Self { 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();
if services
.users
.user_can_see_profile(user_id, querying_user)
.await
{
let display_name = services.users.displayname(user_id).await.ok(); let display_name = services.users.displayname(user_id).await.ok();
let avatar_type = if services.users.avatar_url(user_id).await.is_ok() { if services.users.avatar_url(user_id).await.is_ok() {
AvatarType::Image(profile_media_url(user_id, "avatar_url")) AvatarType::Image(profile_media_url(user_id, "avatar_url"))
} else if let Some(initial) = display_name } else if let Some(initial) = display_name
.as_ref() .as_ref()
@@ -36,7 +55,11 @@ impl Avatar {
{ {
AvatarType::Initial(initial) AvatarType::Initial(initial)
} else { } else {
AvatarType::Initial(user_id.localpart().chars().next().unwrap()) AvatarType::Initial(localpart_initial)
}
} else {
AvatarType::Initial(localpart_initial)
}
}; };
Self { avatar_type } Self { avatar_type }
@@ -97,10 +120,26 @@ impl HtmlSafe for UserCard {}
impl UserCard { impl UserCard {
const BANNER_KEY: &str = "chat.commet.profile_banner"; const BANNER_KEY: &str = "chat.commet.profile_banner";
pub(super) async fn for_local_user(services: &Services, user_id: OwnedUserId) -> Self { pub(super) async fn for_local_user(
let display_name = services.users.displayname(&user_id).await.ok(); services: &Services,
let avatar = Avatar::for_local_user(services, &user_id).await; user_id: OwnedUserId,
let banner = if services querying_user: ProfileQuerier<'_>,
) -> Self {
let can_see_profile = services
.users
.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 .users
.get_local_profile_field(&user_id, Self::BANNER_KEY.into()) .get_local_profile_field(&user_id, Self::BANNER_KEY.into())
.await .await
+7 -6
View File
@@ -25,13 +25,14 @@ async fn get_profile_media(
State(services): State<crate::State>, State(services): State<crate::State>,
Expect(Path(ProfileMediaPath { user_id, field })): Expect<Path<ProfileMediaPath>>, Expect(Path(ProfileMediaPath { user_id, field })): Expect<Path<ProfileMediaPath>>,
headers: HeaderMap, headers: HeaderMap,
requesting_user: User<true>, querying_user: User<true>,
) -> Result { ) -> Result {
if requesting_user let querying_user = querying_user.into_session().map(|session| session.user_id);
.into_session()
.map(|session| session.user_id) if !services
.as_ref() .users
!= Some(&user_id) .user_can_see_profile(&user_id, querying_user.as_deref().into())
.await
{ {
return Err(WebError::Forbidden( return Err(WebError::Forbidden(
"You may not access this user's profile media.".to_owned(), "You may not access this user's profile media.".to_owned(),
+1
View File
@@ -20,6 +20,7 @@ pub(super) mod media;
pub(super) mod oauth; pub(super) mod oauth;
pub(super) mod oidc; pub(super) mod oidc;
pub(super) mod resources; pub(super) mod resources;
mod switch_account;
pub(super) mod threepid; pub(super) mod threepid;
type Result<T = Response, E = WebError> = std::result::Result<T, E>; type Result<T = Response, E = WebError> = std::result::Result<T, E>;
+64 -8
View File
@@ -4,12 +4,15 @@ use axum::{
response::Redirect, response::Redirect,
routing::on, routing::on,
}; };
use conduwuit_service::oauth::{ use conduwuit_service::{
oauth::{
SessionInfo, SessionInfo,
client_metadata::ClientMetadata, client_metadata::ClientMetadata,
grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery, Prompt, RequestedScopes}, grant::{AuthorizationCodeQuery, DeviceCodeVerifyQuery, Prompt, RequestedScopes},
},
users::ProfileQuerier,
}; };
use ruma::{OwnedUserId, api::OAuthClientScope}; use ruma::{OwnedUserId, api::OAuthClientScope, assign};
use serde::{Deserialize, de::IgnoredAny}; use serde::{Deserialize, de::IgnoredAny};
use crate::{ use crate::{
@@ -19,6 +22,7 @@ use crate::{
GET_POST, Result, TemplateContext, GET_POST, Result, TemplateContext,
account::register::{RegisterQuery, RequestedRegistrationFlow}, account::register::{RegisterQuery, RequestedRegistrationFlow},
components::{Avatar, ClientScopes, UserCard}, components::{Avatar, ClientScopes, UserCard},
switch_account::{LoginHintQuery, prompt_to_switch_account},
}, },
response, response,
session::{LoginIntent, LoginQuery, LoginTarget, User}, 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( async fn route_authorization_code(
State(services): State<crate::State>, State(services): State<crate::State>,
Extension(context): Extension<TemplateContext>, Extension(context): Extension<TemplateContext>,
@@ -54,7 +64,7 @@ async fn route_authorization_code(
user.user_id user.user_id
} else { } else {
let is_first_run = services.firstrun.is_first_run(); 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 let uri = if query
.prompt .prompt
@@ -81,6 +91,7 @@ async fn route_authorization_code(
ROUTE_PREFIX, ROUTE_PREFIX,
serde_urlencoded::to_string(LoginQuery { serde_urlencoded::to_string(LoginQuery {
next: Some(next), next: Some(next),
login_hint: query.login_hint,
..Default::default() ..Default::default()
}) })
.unwrap() .unwrap()
@@ -90,6 +101,18 @@ async fn route_authorization_code(
return response!(Redirect::to(&uri)); 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() { if form.is_some() {
let redirect_uri = services let redirect_uri = services
.oauth .oauth
@@ -122,7 +145,7 @@ async fn route_authorization_code(
scopes.retain(|scope| !existing_scopes.contains(scope)); 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( response!(Grant::new(
context, context,
@@ -167,6 +190,12 @@ enum DeviceCodeGrantBody {
Success, 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( async fn route_device_code(
State(services): State<crate::State>, State(services): State<crate::State>,
Extension(context): Extension<TemplateContext>, Extension(context): Extension<TemplateContext>,
@@ -177,19 +206,32 @@ async fn route_device_code(
let user_id = if let Some(user) = user.into_session() { let user_id = if let Some(user) = user.into_session() {
user.user_id user.user_id
} else { } 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!( let uri = format!(
"{}/account/login?{}", "{}/account/login?{}",
ROUTE_PREFIX, ROUTE_PREFIX,
serde_urlencoded::to_string(LoginQuery { next: Some(next), ..Default::default() }) serde_urlencoded::to_string(LoginQuery {
next: Some(next),
login_hint,
..Default::default()
})
.unwrap() .unwrap()
); );
return response!(Redirect::to(&uri)); 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()) { match (form, query.user_code.clone()) {
| (None, Some(user_code)) | (Some(DeviceCodeForm::Lookup { user_code }), _) => { | (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 RequestedScopes { device_id, mut scopes } = grant_info.requested_scopes;
let existing_session_info = if let Some(device_id) = &device_id { 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)); 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( response!(Grant::new(
context, context,
+13 -2
View File
@@ -10,6 +10,7 @@ use conduwuit_api::client_ip::ClientIp;
use conduwuit_service::{ use conduwuit_service::{
oauth::grant::AuthorizationCodeResponse, oauth::grant::AuthorizationCodeResponse,
oidc::{ClaimedLocalUser, SessionCompletionStatus}, oidc::{ClaimedLocalUser, SessionCompletionStatus},
users::ProfileQuerier,
}; };
use futures::FutureExt; use futures::FutureExt;
use ruma::OwnedServerName; use ruma::OwnedServerName;
@@ -119,8 +120,12 @@ async fn route_complete(
.await .await
{ {
| Ok(ClaimedLocalUser::Existing(user_id)) => { | Ok(ClaimedLocalUser::Existing(user_id)) => {
let user_card = let user_card = UserCard::for_local_user(
UserCard::for_local_user(&services, user_id.clone()).await; &services,
user_id.clone(),
ProfileQuerier::Owner,
)
.await;
if let Some(password) = form.password { if let Some(password) = form.password {
if services if services
@@ -180,6 +185,12 @@ async fn route_complete(
.remove::<IgnoredAny>(OIDC_SESSION_ID_KEY) .remove::<IgnoredAny>(OIDC_SESSION_ID_KEY)
.await; .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() }; let user_session = UserSession { user_id, last_login: SystemTime::now() };
session_store session_store
+11
View File
@@ -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 { .bi {
display: inline-block; display: inline-block;
vertical-align: -.125em; vertical-align: -.125em;
+25
View File
@@ -43,6 +43,11 @@
font-weight: normal; font-weight: normal;
font-size: small; font-size: small;
font-family: monospace; font-family: monospace;
&:only-child {
color: var(--text-color);
font-size: inherit;
}
} }
} }
@@ -92,3 +97,23 @@
gap: 10px; gap: 10px;
margin-top: 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;
}
}
}
-20
View File
@@ -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 { .identity {
margin-block: 1em; margin-block: 1em;
color: var(--secondary); 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);
}
}
}
+102
View File
@@ -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;
}
+7
View File
@@ -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"/> <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> </svg>
{% endmacro %} {% 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 %}
+2 -2
View File
@@ -13,7 +13,7 @@ Authorize client
{% let client_name = client_metadata.client_name.as_deref().unwrap_or("Unknown application") %} {% let client_name = client_metadata.client_name.as_deref().unwrap_or("Unknown application") %}
<div class="panel narrow"> <div class="panel narrow">
<h1>Authorize {{ client_name }}</h1> <h1>Authorize {{ client_name }}</h1>
<div class="avatars"> <div class="avatar-pair">
<div class="red-avatar"> <div class="red-avatar">
{{ user_avatar }} {{ user_avatar }}
</div> </div>
@@ -24,7 +24,7 @@ Authorize client
</div> </div>
<div class="identity"> <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> </div>
<p> <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
View File
@@ -15,7 +15,10 @@ use ruma::{OwnedUserId, UserId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tower_sessions::Session; 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; pub(crate) mod store;
@@ -27,6 +30,8 @@ pub(crate) struct LoginQuery {
pub reauthenticate: bool, pub reauthenticate: bool,
#[serde(default)] #[serde(default)]
pub intent: Option<LoginIntent>, pub intent: Option<LoginIntent>,
#[serde(default)]
pub login_hint: Option<String>,
} }
#[derive(Clone, Debug, Default, Deserialize, Serialize)] #[derive(Clone, Debug, Default, Deserialize, Serialize)]
@@ -35,6 +40,7 @@ pub(crate) enum LoginTarget {
AuthorizationCode(AuthorizationCodeQuery), AuthorizationCode(AuthorizationCodeQuery),
#[default] #[default]
Account, Account,
AccountDeeplink(AccountDeeplinkQuery),
ChangePassword, ChangePassword,
ChangeEmail, ChangeEmail,
CrossSigningReset, CrossSigningReset,
@@ -57,6 +63,8 @@ impl LoginTarget {
) )
.into(), .into(),
| Self::Account => "account/".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::ChangePassword => "account/password/change".into(),
| Self::ChangeEmail => "account/email/change/".into(), | Self::ChangeEmail => "account/email/change/".into(),
| Self::CrossSigningReset => "account/cross_signing_reset".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 /// Extract the user ID, redirecting to the login page if the user isn't
/// logged in. /// 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 { if let Some(session) = self.0 {
Ok(session.user_id) Ok(session.user_id)
} else { } else {
Err(WebError::LoginRequired(LoginQuery { Err(WebError::LoginRequired(LoginQuery { next: Some(or), ..Default::default() }))
next: Some(or_else),
..Default::default()
}))
} }
} }