Skip to main content

mas_router/
endpoints.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2022-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8use serde::{Deserialize, Serialize};
9use serde_with::{DeserializeFromStr, SerializeDisplay};
10use ulid::Ulid;
11
12use crate::UrlBuilder;
13pub use crate::traits::*;
14
15#[derive(Deserialize, Serialize, Clone, Debug)]
16#[serde(rename_all = "snake_case", tag = "kind")]
17pub enum PostAuthAction {
18    ContinueAuthorizationGrant {
19        id: Ulid,
20    },
21    ContinueDeviceCodeGrant {
22        id: Ulid,
23    },
24    ContinueCompatSsoLogin {
25        id: Ulid,
26    },
27    ChangePassword,
28    LinkUpstream {
29        id: Ulid,
30    },
31    ManageAccount {
32        #[serde(flatten)]
33        action: Option<AccountAction>,
34    },
35}
36
37impl PostAuthAction {
38    #[must_use]
39    pub const fn continue_grant(id: Ulid) -> Self {
40        PostAuthAction::ContinueAuthorizationGrant { id }
41    }
42
43    #[must_use]
44    pub const fn continue_device_code_grant(id: Ulid) -> Self {
45        PostAuthAction::ContinueDeviceCodeGrant { id }
46    }
47
48    #[must_use]
49    pub const fn continue_compat_sso_login(id: Ulid) -> Self {
50        PostAuthAction::ContinueCompatSsoLogin { id }
51    }
52
53    #[must_use]
54    pub const fn link_upstream(id: Ulid) -> Self {
55        PostAuthAction::LinkUpstream { id }
56    }
57
58    #[must_use]
59    pub const fn manage_account(action: Option<AccountAction>) -> Self {
60        PostAuthAction::ManageAccount { action }
61    }
62
63    pub fn go_next(&self, url_builder: &UrlBuilder) -> axum::response::Redirect {
64        match self {
65            Self::ContinueAuthorizationGrant { id } => url_builder.redirect(&Consent(*id)),
66            Self::ContinueDeviceCodeGrant { id } => {
67                url_builder.redirect(&DeviceCodeConsent::new(*id))
68            }
69            Self::ContinueCompatSsoLogin { id } => {
70                url_builder.redirect(&CompatLoginSsoComplete::new(*id, None))
71            }
72            Self::ChangePassword => url_builder.redirect(&AccountPasswordChange),
73            Self::LinkUpstream { id } => url_builder.redirect(&UpstreamOAuth2Link::new(*id)),
74            Self::ManageAccount { action } => url_builder.redirect(&Account {
75                action: action.clone(),
76            }),
77        }
78    }
79}
80
81/// `GET /.well-known/openid-configuration`
82#[derive(Default, Debug, Clone)]
83pub struct OidcConfiguration;
84
85impl SimpleRoute for OidcConfiguration {
86    const PATH: &'static str = "/.well-known/openid-configuration";
87}
88
89/// `GET /.well-known/webfinger`
90#[derive(Default, Debug, Clone)]
91pub struct Webfinger;
92
93impl SimpleRoute for Webfinger {
94    const PATH: &'static str = "/.well-known/webfinger";
95}
96
97/// `GET /.well-known/change-password`
98pub struct ChangePasswordDiscovery;
99
100impl SimpleRoute for ChangePasswordDiscovery {
101    const PATH: &'static str = "/.well-known/change-password";
102}
103
104/// `GET /oauth2/keys.json`
105#[derive(Default, Debug, Clone)]
106pub struct OAuth2Keys;
107
108impl SimpleRoute for OAuth2Keys {
109    const PATH: &'static str = "/oauth2/keys.json";
110}
111
112/// `GET /oauth2/userinfo`
113#[derive(Default, Debug, Clone)]
114pub struct OidcUserinfo;
115
116impl SimpleRoute for OidcUserinfo {
117    const PATH: &'static str = "/oauth2/userinfo";
118}
119
120/// `POST /oauth2/introspect`
121#[derive(Default, Debug, Clone)]
122pub struct OAuth2Introspection;
123
124impl SimpleRoute for OAuth2Introspection {
125    const PATH: &'static str = "/oauth2/introspect";
126}
127
128/// `POST /oauth2/revoke`
129#[derive(Default, Debug, Clone)]
130pub struct OAuth2Revocation;
131
132impl SimpleRoute for OAuth2Revocation {
133    const PATH: &'static str = "/oauth2/revoke";
134}
135
136/// `POST /oauth2/token`
137#[derive(Default, Debug, Clone)]
138pub struct OAuth2TokenEndpoint;
139
140impl SimpleRoute for OAuth2TokenEndpoint {
141    const PATH: &'static str = "/oauth2/token";
142}
143
144/// `POST /oauth2/registration`
145#[derive(Default, Debug, Clone)]
146pub struct OAuth2RegistrationEndpoint;
147
148impl SimpleRoute for OAuth2RegistrationEndpoint {
149    const PATH: &'static str = "/oauth2/registration";
150}
151
152/// `GET /authorize`
153#[derive(Default, Debug, Clone)]
154pub struct OAuth2AuthorizationEndpoint;
155
156impl SimpleRoute for OAuth2AuthorizationEndpoint {
157    const PATH: &'static str = "/authorize";
158}
159
160/// `GET /`
161#[derive(Default, Debug, Clone)]
162pub struct Index;
163
164impl SimpleRoute for Index {
165    const PATH: &'static str = "/";
166}
167
168/// `GET /health`
169#[derive(Default, Debug, Clone)]
170pub struct Healthcheck;
171
172impl SimpleRoute for Healthcheck {
173    const PATH: &'static str = "/health";
174}
175
176/// The wire prefix of the [`LoginMethodHint::UpstreamOAuth2`] value space.
177const UPSTREAM_OAUTH2_PREFIX: &str = "upstream-oauth2:";
178
179/// A login method a client asked us to use, as carried by the
180/// `io.element.login_method` parameter.
181///
182/// The variants mirror `mas_data_model::AuthenticationMethod` and
183/// `mas_policy::RegistrationMethod`, which record how a session was
184/// authenticated; this type carries the client's request, keyed by provider
185/// id.
186#[derive(Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
187pub enum LoginMethodHint {
188    /// The local password method.
189    Password,
190
191    /// The upstream OAuth 2.0 provider with the given id.
192    UpstreamOAuth2(Ulid),
193
194    /// A value we don't know about, kept verbatim so that it can be logged.
195    Unknown(String),
196}
197
198impl std::fmt::Display for LoginMethodHint {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        match self {
201            LoginMethodHint::Password => f.write_str("password"),
202            LoginMethodHint::UpstreamOAuth2(id) => write!(f, "{UPSTREAM_OAUTH2_PREFIX}{id}"),
203            LoginMethodHint::Unknown(value) => f.write_str(value),
204        }
205    }
206}
207
208impl std::str::FromStr for LoginMethodHint {
209    type Err = std::convert::Infallible;
210
211    /// The keyword and the prefix are lowercase-only; the ULID is parsed by the
212    /// `ulid` crate, which is case-insensitive.
213    fn from_str(s: &str) -> Result<Self, Self::Err> {
214        if s == "password" {
215            return Ok(LoginMethodHint::Password);
216        }
217
218        if let Some(id) = s.strip_prefix(UPSTREAM_OAUTH2_PREFIX)
219            && let Ok(id) = Ulid::from_str(id)
220        {
221            return Ok(LoginMethodHint::UpstreamOAuth2(id));
222        }
223
224        Ok(LoginMethodHint::Unknown(s.to_owned()))
225    }
226}
227
228/// `GET|POST /login`
229#[expect(
230    clippy::struct_field_names,
231    reason = "`login_hint` and `login_method` mirror their query parameter names"
232)]
233#[derive(Default, Debug, Clone, Serialize, Deserialize)]
234pub struct Login {
235    #[serde(flatten)]
236    post_auth_action: Option<PostAuthAction>,
237
238    #[serde(skip_serializing_if = "Option::is_none")]
239    login_hint: Option<String>,
240
241    #[serde(
242        rename = "io.element.login_method",
243        skip_serializing_if = "Option::is_none"
244    )]
245    login_method: Option<LoginMethodHint>,
246}
247
248impl Route for Login {
249    type Query = Self;
250
251    fn route() -> &'static str {
252        "/login"
253    }
254
255    fn query(&self) -> Option<&Self::Query> {
256        Some(self)
257    }
258}
259
260impl Login {
261    #[must_use]
262    pub const fn and_then(action: PostAuthAction) -> Self {
263        Self {
264            post_auth_action: Some(action),
265            login_hint: None,
266            login_method: None,
267        }
268    }
269
270    #[must_use]
271    pub const fn and_continue_grant(id: Ulid) -> Self {
272        Self {
273            post_auth_action: Some(PostAuthAction::continue_grant(id)),
274            login_hint: None,
275            login_method: None,
276        }
277    }
278
279    #[must_use]
280    pub const fn and_continue_device_code_grant(id: Ulid) -> Self {
281        Self {
282            post_auth_action: Some(PostAuthAction::continue_device_code_grant(id)),
283            login_hint: None,
284            login_method: None,
285        }
286    }
287
288    #[must_use]
289    pub const fn and_continue_compat_sso_login(id: Ulid) -> Self {
290        Self {
291            post_auth_action: Some(PostAuthAction::continue_compat_sso_login(id)),
292            login_hint: None,
293            login_method: None,
294        }
295    }
296
297    #[must_use]
298    pub const fn and_link_upstream(id: Ulid) -> Self {
299        Self {
300            post_auth_action: Some(PostAuthAction::link_upstream(id)),
301            login_hint: None,
302            login_method: None,
303        }
304    }
305
306    #[must_use]
307    pub fn with_login_hint(mut self, login_hint: String) -> Self {
308        self.login_hint = Some(login_hint);
309        self
310    }
311
312    #[must_use]
313    pub fn with_login_method(mut self, login_method: LoginMethodHint) -> Self {
314        self.login_method = Some(login_method);
315        self
316    }
317
318    /// Get a reference to the login method the client asked for.
319    #[must_use]
320    pub fn login_method(&self) -> Option<&LoginMethodHint> {
321        self.login_method.as_ref()
322    }
323
324    /// Get a reference to the login's post auth action.
325    #[must_use]
326    pub fn post_auth_action(&self) -> Option<&PostAuthAction> {
327        self.post_auth_action.as_ref()
328    }
329
330    pub fn go_next(&self, url_builder: &UrlBuilder) -> axum::response::Redirect {
331        match &self.post_auth_action {
332            Some(action) => action.go_next(url_builder),
333            None => url_builder.redirect(&Index),
334        }
335    }
336}
337
338impl From<Option<PostAuthAction>> for Login {
339    fn from(post_auth_action: Option<PostAuthAction>) -> Self {
340        Self {
341            post_auth_action,
342            login_hint: None,
343            login_method: None,
344        }
345    }
346}
347
348/// `POST /logout`
349#[derive(Default, Debug, Clone)]
350pub struct Logout;
351
352impl SimpleRoute for Logout {
353    const PATH: &'static str = "/logout";
354}
355
356/// `GET|POST /register`
357#[derive(Default, Debug, Clone)]
358pub struct Register {
359    post_auth_action: Option<PostAuthAction>,
360}
361
362impl Register {
363    #[must_use]
364    pub fn and_then(action: PostAuthAction) -> Self {
365        Self {
366            post_auth_action: Some(action),
367        }
368    }
369
370    #[must_use]
371    pub fn and_continue_grant(data: Ulid) -> Self {
372        Self {
373            post_auth_action: Some(PostAuthAction::continue_grant(data)),
374        }
375    }
376
377    #[must_use]
378    pub fn and_continue_compat_sso_login(data: Ulid) -> Self {
379        Self {
380            post_auth_action: Some(PostAuthAction::continue_compat_sso_login(data)),
381        }
382    }
383
384    /// Get a reference to the reauth's post auth action.
385    #[must_use]
386    pub fn post_auth_action(&self) -> Option<&PostAuthAction> {
387        self.post_auth_action.as_ref()
388    }
389
390    pub fn go_next(&self, url_builder: &UrlBuilder) -> axum::response::Redirect {
391        match &self.post_auth_action {
392            Some(action) => action.go_next(url_builder),
393            None => url_builder.redirect(&Index),
394        }
395    }
396}
397
398impl Route for Register {
399    type Query = PostAuthAction;
400
401    fn route() -> &'static str {
402        "/register"
403    }
404
405    fn query(&self) -> Option<&Self::Query> {
406        self.post_auth_action.as_ref()
407    }
408}
409
410impl From<Option<PostAuthAction>> for Register {
411    fn from(post_auth_action: Option<PostAuthAction>) -> Self {
412        Self { post_auth_action }
413    }
414}
415
416/// `GET|POST /register/steps/{id}/token`
417#[derive(Debug, Clone)]
418pub struct RegisterToken {
419    id: Ulid,
420}
421
422impl RegisterToken {
423    #[must_use]
424    pub fn new(id: Ulid) -> Self {
425        Self { id }
426    }
427}
428
429impl Route for RegisterToken {
430    type Query = ();
431    fn route() -> &'static str {
432        "/register/steps/{id}/token"
433    }
434
435    fn path(&self) -> std::borrow::Cow<'static, str> {
436        format!("/register/steps/{}/token", self.id).into()
437    }
438}
439
440/// `GET|POST /register/steps/{id}/display-name`
441#[derive(Debug, Clone)]
442pub struct RegisterDisplayName {
443    id: Ulid,
444}
445
446impl RegisterDisplayName {
447    #[must_use]
448    pub fn new(id: Ulid) -> Self {
449        Self { id }
450    }
451}
452
453impl Route for RegisterDisplayName {
454    type Query = ();
455    fn route() -> &'static str {
456        "/register/steps/{id}/display-name"
457    }
458
459    fn path(&self) -> std::borrow::Cow<'static, str> {
460        format!("/register/steps/{}/display-name", self.id).into()
461    }
462}
463
464/// `GET|POST /register/steps/{id}/verify-email`
465#[derive(Debug, Clone)]
466pub struct RegisterVerifyEmail {
467    id: Ulid,
468}
469
470impl RegisterVerifyEmail {
471    #[must_use]
472    pub fn new(id: Ulid) -> Self {
473        Self { id }
474    }
475}
476
477impl Route for RegisterVerifyEmail {
478    type Query = ();
479    fn route() -> &'static str {
480        "/register/steps/{id}/verify-email"
481    }
482
483    fn path(&self) -> std::borrow::Cow<'static, str> {
484        format!("/register/steps/{}/verify-email", self.id).into()
485    }
486}
487
488/// `GET /register/steps/{id}/finish`
489#[derive(Debug, Clone)]
490pub struct RegisterFinish {
491    id: Ulid,
492}
493
494impl RegisterFinish {
495    #[must_use]
496    pub const fn new(id: Ulid) -> Self {
497        Self { id }
498    }
499}
500
501impl Route for RegisterFinish {
502    type Query = ();
503    fn route() -> &'static str {
504        "/register/steps/{id}/finish"
505    }
506
507    fn path(&self) -> std::borrow::Cow<'static, str> {
508        format!("/register/steps/{}/finish", self.id).into()
509    }
510}
511
512/// Actions parameters as defined by MSC4191
513#[derive(Debug, Clone, Serialize, Deserialize)]
514#[serde(tag = "action")]
515pub enum AccountAction {
516    #[serde(rename = "org.matrix.profile")]
517    OrgMatrixProfile,
518    /// DEPRECATED: Use `OrgMatrixProfile` instead
519    #[serde(rename = "profile")]
520    Profile,
521
522    #[serde(rename = "org.matrix.devices_list")]
523    OrgMatrixDevicesList,
524    /// DEPRECATED: Use `OrgMatrixDevicesList` instead
525    #[serde(rename = "org.matrix.sessions_list")]
526    OrgMatrixSessionsList,
527    /// DEPRECATED: Use `OrgMatrixDevicesList` instead
528    #[serde(rename = "sessions_list")]
529    SessionsList,
530
531    #[serde(rename = "org.matrix.device_view")]
532    OrgMatrixDeviceView { device_id: String },
533    /// DEPRECATED: Use `OrgMatrixDeviceView` instead
534    #[serde(rename = "org.matrix.session_view")]
535    OrgMatrixSessionView { device_id: String },
536    /// DEPRECATED: Use `OrgMatrixDeviceView` instead
537    #[serde(rename = "session_view")]
538    SessionView { device_id: String },
539
540    #[serde(rename = "org.matrix.device_delete")]
541    OrgMatrixDeviceDelete { device_id: String },
542    /// DEPRECATED: Use `OrgMatrixDeviceDelete` instead
543    #[serde(rename = "org.matrix.session_end")]
544    OrgMatrixSessionEnd { device_id: String },
545    /// DEPRECATED: Use `OrgMatrixDeviceDelete` instead
546    #[serde(rename = "session_end")]
547    SessionEnd { device_id: String },
548
549    #[serde(rename = "org.matrix.cross_signing_reset")]
550    OrgMatrixCrossSigningReset,
551}
552
553/// `GET /account/`
554#[derive(Default, Debug, Clone)]
555pub struct Account {
556    action: Option<AccountAction>,
557}
558
559impl Route for Account {
560    type Query = AccountAction;
561
562    fn route() -> &'static str {
563        "/account/"
564    }
565
566    fn query(&self) -> Option<&Self::Query> {
567        self.action.as_ref()
568    }
569}
570
571/// `GET /account/*`
572#[derive(Default, Debug, Clone)]
573pub struct AccountWildcard;
574
575impl SimpleRoute for AccountWildcard {
576    const PATH: &'static str = "/account/{*rest}";
577}
578
579/// `GET /account/password/change`
580///
581/// Handled by the React frontend; this struct definition is purely for
582/// redirects.
583#[derive(Default, Debug, Clone)]
584pub struct AccountPasswordChange;
585
586impl SimpleRoute for AccountPasswordChange {
587    const PATH: &'static str = "/account/password/change";
588}
589
590/// `GET /consent/{grant_id}`
591#[derive(Debug, Clone)]
592pub struct Consent(pub Ulid);
593
594impl Route for Consent {
595    type Query = ();
596    fn route() -> &'static str {
597        "/consent/{grant_id}"
598    }
599
600    fn path(&self) -> std::borrow::Cow<'static, str> {
601        format!("/consent/{}", self.0).into()
602    }
603}
604
605/// `GET|POST /_matrix/client/v3/login`
606pub struct CompatLogin;
607
608impl SimpleRoute for CompatLogin {
609    const PATH: &'static str = "/_matrix/client/{version}/login";
610}
611
612/// `POST /_matrix/client/v3/logout`
613pub struct CompatLogout;
614
615impl SimpleRoute for CompatLogout {
616    const PATH: &'static str = "/_matrix/client/{version}/logout";
617}
618
619/// `POST /_matrix/client/v3/logout/all`
620pub struct CompatLogoutAll;
621
622impl SimpleRoute for CompatLogoutAll {
623    const PATH: &'static str = "/_matrix/client/{version}/logout/all";
624}
625
626/// `POST /_matrix/client/v3/refresh`
627pub struct CompatRefresh;
628
629impl SimpleRoute for CompatRefresh {
630    const PATH: &'static str = "/_matrix/client/{version}/refresh";
631}
632
633/// `GET /_matrix/client/v3/login/sso/redirect`
634pub struct CompatLoginSsoRedirect;
635
636impl SimpleRoute for CompatLoginSsoRedirect {
637    const PATH: &'static str = "/_matrix/client/{version}/login/sso/redirect";
638}
639
640/// `GET /_matrix/client/v3/login/sso/redirect/`
641///
642/// This is a workaround for the fact some clients (Element iOS) sends a
643/// trailing slash, even though it's not in the spec.
644pub struct CompatLoginSsoRedirectSlash;
645
646impl SimpleRoute for CompatLoginSsoRedirectSlash {
647    const PATH: &'static str = "/_matrix/client/{version}/login/sso/redirect/";
648}
649
650/// `GET /_matrix/client/v3/login/sso/redirect/{idp}`
651pub struct CompatLoginSsoRedirectIdp;
652
653impl SimpleRoute for CompatLoginSsoRedirectIdp {
654    const PATH: &'static str = "/_matrix/client/{version}/login/sso/redirect/{idp}";
655}
656
657#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
658#[serde(rename_all = "lowercase")]
659pub enum CompatLoginSsoAction {
660    Login,
661    Register,
662    #[serde(other)]
663    Unknown,
664}
665
666impl CompatLoginSsoAction {
667    /// Returns true if the action is a known action.
668    #[must_use]
669    pub fn is_known(&self) -> bool {
670        !matches!(self, Self::Unknown)
671    }
672}
673
674#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
675pub struct CompatLoginSsoActionParams {
676    action: CompatLoginSsoAction,
677    /// DEPRECATED: Use `action` instead. We will remove this once enough
678    /// clients support the stable name.
679    #[serde(rename = "org.matrix.msc3824.action")]
680    unstable_action: CompatLoginSsoAction,
681}
682
683/// `GET|POST /complete-compat-sso/{id}`
684pub struct CompatLoginSsoComplete {
685    id: Ulid,
686    query: Option<CompatLoginSsoActionParams>,
687}
688
689impl CompatLoginSsoComplete {
690    #[must_use]
691    pub fn new(id: Ulid, action: Option<CompatLoginSsoAction>) -> Self {
692        Self {
693            id,
694            query: action.map(|action| CompatLoginSsoActionParams {
695                action,
696                unstable_action: action,
697            }),
698        }
699    }
700}
701
702impl Route for CompatLoginSsoComplete {
703    type Query = CompatLoginSsoActionParams;
704
705    fn query(&self) -> Option<&Self::Query> {
706        self.query.as_ref()
707    }
708
709    fn route() -> &'static str {
710        "/complete-compat-sso/{grant_id}"
711    }
712
713    fn path(&self) -> std::borrow::Cow<'static, str> {
714        format!("/complete-compat-sso/{}", self.id).into()
715    }
716}
717
718/// `GET /upstream/authorize/{id}`
719pub struct UpstreamOAuth2Authorize {
720    id: Ulid,
721    post_auth_action: Option<PostAuthAction>,
722}
723
724impl UpstreamOAuth2Authorize {
725    #[must_use]
726    pub const fn new(id: Ulid) -> Self {
727        Self {
728            id,
729            post_auth_action: None,
730        }
731    }
732
733    #[must_use]
734    pub fn and_then(mut self, action: PostAuthAction) -> Self {
735        self.post_auth_action = Some(action);
736        self
737    }
738}
739
740impl Route for UpstreamOAuth2Authorize {
741    type Query = PostAuthAction;
742    fn route() -> &'static str {
743        "/upstream/authorize/{provider_id}"
744    }
745
746    fn path(&self) -> std::borrow::Cow<'static, str> {
747        format!("/upstream/authorize/{}", self.id).into()
748    }
749
750    fn query(&self) -> Option<&Self::Query> {
751        self.post_auth_action.as_ref()
752    }
753}
754
755/// `GET /upstream/callback/{id}`
756pub struct UpstreamOAuth2Callback {
757    id: Ulid,
758}
759
760impl UpstreamOAuth2Callback {
761    #[must_use]
762    pub const fn new(id: Ulid) -> Self {
763        Self { id }
764    }
765}
766
767impl Route for UpstreamOAuth2Callback {
768    type Query = ();
769    fn route() -> &'static str {
770        "/upstream/callback/{provider_id}"
771    }
772
773    fn path(&self) -> std::borrow::Cow<'static, str> {
774        format!("/upstream/callback/{}", self.id).into()
775    }
776}
777
778/// `GET /upstream/link/{id}`
779pub struct UpstreamOAuth2Link {
780    id: Ulid,
781}
782
783impl UpstreamOAuth2Link {
784    #[must_use]
785    pub const fn new(id: Ulid) -> Self {
786        Self { id }
787    }
788}
789
790impl Route for UpstreamOAuth2Link {
791    type Query = ();
792    fn route() -> &'static str {
793        "/upstream/link/{link_id}"
794    }
795
796    fn path(&self) -> std::borrow::Cow<'static, str> {
797        format!("/upstream/link/{}", self.id).into()
798    }
799}
800
801/// `POST /upstream/backchannel-logout/{id}`
802pub struct UpstreamOAuth2BackchannelLogout {
803    id: Ulid,
804}
805
806impl UpstreamOAuth2BackchannelLogout {
807    #[must_use]
808    pub const fn new(id: Ulid) -> Self {
809        Self { id }
810    }
811}
812
813impl Route for UpstreamOAuth2BackchannelLogout {
814    type Query = ();
815    fn route() -> &'static str {
816        "/upstream/backchannel-logout/{provider_id}"
817    }
818
819    fn path(&self) -> std::borrow::Cow<'static, str> {
820        format!("/upstream/backchannel-logout/{}", self.id).into()
821    }
822}
823
824/// `GET|POST /link`
825#[derive(Default, Serialize, Deserialize, Debug, Clone)]
826pub struct DeviceCodeLink {
827    code: Option<String>,
828}
829
830impl DeviceCodeLink {
831    #[must_use]
832    pub fn with_code(code: String) -> Self {
833        Self { code: Some(code) }
834    }
835}
836
837impl Route for DeviceCodeLink {
838    type Query = DeviceCodeLink;
839    fn route() -> &'static str {
840        "/link"
841    }
842
843    fn query(&self) -> Option<&Self::Query> {
844        Some(self)
845    }
846}
847
848/// `GET|POST /device/{device_code_id}`
849#[derive(Default, Serialize, Deserialize, Debug, Clone)]
850pub struct DeviceCodeConsent {
851    id: Ulid,
852}
853
854impl Route for DeviceCodeConsent {
855    type Query = ();
856    fn route() -> &'static str {
857        "/device/{device_code_id}"
858    }
859
860    fn path(&self) -> std::borrow::Cow<'static, str> {
861        format!("/device/{}", self.id).into()
862    }
863}
864
865impl DeviceCodeConsent {
866    #[must_use]
867    pub fn new(id: Ulid) -> Self {
868        Self { id }
869    }
870}
871
872/// `POST /oauth2/device`
873#[derive(Default, Serialize, Deserialize, Debug, Clone)]
874pub struct OAuth2DeviceAuthorizationEndpoint;
875
876impl SimpleRoute for OAuth2DeviceAuthorizationEndpoint {
877    const PATH: &'static str = "/oauth2/device";
878}
879
880/// `GET|POST /recover`
881#[derive(Default, Serialize, Deserialize, Debug, Clone)]
882pub struct AccountRecoveryStart;
883
884impl SimpleRoute for AccountRecoveryStart {
885    const PATH: &'static str = "/recover";
886}
887
888/// `GET|POST /recover/progress/{session_id}`
889#[derive(Default, Serialize, Deserialize, Debug, Clone)]
890pub struct AccountRecoveryProgress {
891    session_id: Ulid,
892}
893
894impl AccountRecoveryProgress {
895    #[must_use]
896    pub fn new(session_id: Ulid) -> Self {
897        Self { session_id }
898    }
899}
900
901impl Route for AccountRecoveryProgress {
902    type Query = ();
903    fn route() -> &'static str {
904        "/recover/progress/{session_id}"
905    }
906
907    fn path(&self) -> std::borrow::Cow<'static, str> {
908        format!("/recover/progress/{}", self.session_id).into()
909    }
910}
911
912/// `GET /account/password/recovery?ticket=:ticket`
913/// Rendered by the React frontend
914#[derive(Default, Serialize, Deserialize, Debug, Clone)]
915pub struct AccountRecoveryFinish {
916    ticket: String,
917}
918
919impl AccountRecoveryFinish {
920    #[must_use]
921    pub fn new(ticket: String) -> Self {
922        Self { ticket }
923    }
924}
925
926impl Route for AccountRecoveryFinish {
927    type Query = AccountRecoveryFinish;
928
929    fn route() -> &'static str {
930        "/account/password/recovery"
931    }
932
933    fn query(&self) -> Option<&Self::Query> {
934        Some(self)
935    }
936}
937
938/// `GET /assets`
939pub struct StaticAsset {
940    path: String,
941}
942
943impl StaticAsset {
944    #[must_use]
945    pub fn new(path: String) -> Self {
946        Self { path }
947    }
948}
949
950impl Route for StaticAsset {
951    type Query = ();
952    fn route() -> &'static str {
953        "/assets/"
954    }
955
956    fn path(&self) -> std::borrow::Cow<'static, str> {
957        format!("/assets/{}", self.path).into()
958    }
959}
960
961/// `GET|POST /graphql`
962pub struct GraphQL;
963
964impl SimpleRoute for GraphQL {
965    const PATH: &'static str = "/graphql";
966}
967
968/// `GET /api/spec.json`
969pub struct ApiSpec;
970
971impl SimpleRoute for ApiSpec {
972    const PATH: &'static str = "/api/spec.json";
973}
974
975/// `GET /api/doc/`
976pub struct ApiDoc;
977
978impl SimpleRoute for ApiDoc {
979    const PATH: &'static str = "/api/doc/";
980}
981
982/// `GET /api/doc/oauth2-callback`
983pub struct ApiDocCallback;
984
985impl SimpleRoute for ApiDocCallback {
986    const PATH: &'static str = "/api/doc/oauth2-callback";
987}
988
989#[cfg(test)]
990mod tests {
991    use std::str::FromStr as _;
992
993    use super::*;
994
995    const PROVIDER_ID: &str = "01HFRQFT5QFMJFGF01P7JAV2ME";
996
997    #[test]
998    fn login_method_hint_password() {
999        let hint = LoginMethodHint::from_str("password").unwrap();
1000        assert_eq!(hint, LoginMethodHint::Password);
1001        assert_eq!(hint.to_string(), "password");
1002    }
1003
1004    #[test]
1005    fn login_method_hint_upstream_oauth2() {
1006        let hint = LoginMethodHint::from_str(&format!("upstream-oauth2:{PROVIDER_ID}")).unwrap();
1007        assert_eq!(
1008            hint,
1009            LoginMethodHint::UpstreamOAuth2(Ulid::from_str(PROVIDER_ID).unwrap())
1010        );
1011        assert_eq!(hint.to_string(), format!("upstream-oauth2:{PROVIDER_ID}"));
1012    }
1013
1014    #[test]
1015    fn login_method_hint_unknown_values() {
1016        for value in [
1017            &format!("upstream-oauth2:{}", "not-a-ulid"),
1018            PROVIDER_ID,
1019            "",
1020        ] {
1021            let hint = LoginMethodHint::from_str(value).unwrap();
1022            assert_eq!(hint, LoginMethodHint::Unknown(value.to_owned()));
1023            assert_eq!(hint.to_string(), value);
1024        }
1025    }
1026}