Skip to main content

mas_handlers/oauth2/device/
link.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2023, 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 axum::{
9    Form,
10    extract::State,
11    response::{Html, IntoResponse, Response},
12};
13use axum_extra::extract::Query;
14use mas_axum_utils::{
15    InternalError,
16    cookies::CookieJar,
17    csrf::{CsrfExt, ProtectedForm},
18};
19use mas_data_model::{BoxClock, BoxRng};
20use mas_i18n::DataLocale;
21use mas_router::UrlBuilder;
22use mas_storage::BoxRepository;
23use mas_templates::{
24    DeviceLinkContext, DeviceLinkFormField, FieldError, FormState, TemplateContext, Templates,
25};
26use serde::{Deserialize, Serialize};
27
28use crate::{PreferredLanguage, SiteConfig};
29
30#[derive(Serialize, Deserialize)]
31pub struct Params {
32    #[serde(default)]
33    code: Option<String>,
34}
35
36#[tracing::instrument(name = "handlers.oauth2.device.link.get", skip_all)]
37pub(crate) async fn get(
38    mut rng: BoxRng,
39    clock: BoxClock,
40    repo: BoxRepository,
41    PreferredLanguage(locale): PreferredLanguage,
42    State(templates): State<Templates>,
43    State(url_builder): State<UrlBuilder>,
44    State(site_config): State<SiteConfig>,
45    cookie_jar: CookieJar,
46    Query(mut query): Query<Params>,
47) -> Result<Response, InternalError> {
48    if !site_config.device_code_grant_enabled {
49        return Err(InternalError::from_anyhow(anyhow::anyhow!(
50            "The Device Authorization Grant is disabled"
51        )));
52    }
53    // When the auto-fill flow is disabled, ignore the `code` query parameter
54    // entirely — users must type their user code into the form.
55    if !site_config.device_code_user_code_auto_fill_enabled {
56        query.code = None;
57    }
58
59    handle_code(
60        &mut rng,
61        &clock,
62        repo,
63        &locale,
64        &templates,
65        &url_builder,
66        cookie_jar,
67        query,
68    )
69    .await
70}
71
72#[tracing::instrument(name = "handlers.oauth2.device.link.post", skip_all)]
73pub(crate) async fn post(
74    mut rng: BoxRng,
75    clock: BoxClock,
76    repo: BoxRepository,
77    PreferredLanguage(locale): PreferredLanguage,
78    State(templates): State<Templates>,
79    State(url_builder): State<UrlBuilder>,
80    State(site_config): State<SiteConfig>,
81    cookie_jar: CookieJar,
82    Form(form): Form<ProtectedForm<Params>>,
83) -> Result<Response, InternalError> {
84    if !site_config.device_code_grant_enabled {
85        return Err(InternalError::from_anyhow(anyhow::anyhow!(
86            "The Device Authorization Grant is disabled"
87        )));
88    }
89
90    let form = cookie_jar.verify_form(&clock, form)?;
91
92    handle_code(
93        &mut rng,
94        &clock,
95        repo,
96        &locale,
97        &templates,
98        &url_builder,
99        cookie_jar,
100        form,
101    )
102    .await
103}
104
105async fn handle_code(
106    rng: &mut BoxRng,
107    clock: &BoxClock,
108    mut repo: BoxRepository,
109    locale: &DataLocale,
110    templates: &Templates,
111    url_builder: &UrlBuilder,
112    cookie_jar: CookieJar,
113    params: Params,
114) -> Result<Response, InternalError> {
115    let mut form_state = FormState::from_form(&params);
116
117    // If we have a code, find it in the database
118    if let Some(code) = &params.code {
119        let code = code.to_uppercase();
120        let grant = repo
121            .oauth2_device_code_grant()
122            .find_by_user_code(&code)
123            .await?
124            // XXX: We should have different error messages for already exchanged and expired
125            .filter(|grant| grant.is_pending())
126            .filter(|grant| grant.expires_at > clock.now());
127
128        if let Some(grant) = grant {
129            // This is a valid code, redirect to the consent page
130            // This will in turn redirect to the login page if the user is not logged in
131            let destination = url_builder.redirect(&mas_router::DeviceCodeConsent::new(grant.id));
132
133            return Ok((cookie_jar, destination).into_response());
134        }
135
136        // The code isn't valid, set an error on the form
137        form_state = form_state.with_error_on_field(DeviceLinkFormField::Code, FieldError::Invalid);
138    }
139
140    let (csrf_token, cookie_jar) = cookie_jar.csrf_token(clock, rng);
141
142    // Render the form
143    let ctx = DeviceLinkContext::new()
144        .with_form_state(form_state)
145        .with_csrf(csrf_token.form_value())
146        .with_language(*locale);
147
148    let content = templates.render_device_link(&ctx)?;
149
150    Ok((cookie_jar, Html(content)).into_response())
151}