OXYGENHUB

Coverage / crates/hub/src/web/settings.rs 72.8%

440 of 604 lines run, 70 of 225 functions · run #482 on proposal/333 · run missed

1
//! Account settings (hub spec §6.3 `/settings/*`): profile, security,
2
//! linked identities, tokens.
3
4
use super::{filters, Error, Page, Shell};
5
use crate::auth::{self, totp, Viewer, ViewerAccount};
6
use crate::db::{self, accounts};
7
use crate::Shared;
8
use askama::Template;
9
use axum::extract::{Form, Multipart, Path, Query, State};
10
use axum::http::{header, HeaderMap, StatusCode};
11
use axum::response::{IntoResponse, Redirect, Response};
12
use oxy_core::identity::{Identity, Signature};
13
use serde::Deserialize;
14
15
/// The signed-in account, or a redirect to sign in.
16422×
pub fn require(viewer: &Viewer, shell: &Shell) -> Result<ViewerAccount, Error> {
17422×
    viewer.0.clone().ok_or_else(|| Error::redirect(format!("/login?next={}", urlencode(&shell.path))))
18422×
}
19
20370×
pub fn urlencode(s: &str) -> String {
21370×
    let mut out = String::new();
228243×
    for b in s.bytes() {
238243×
        match b {
247388×
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char),
25855×
            _ => out.push_str(&format!("%{b:02X}")),
26
        }
27
    }
28370×
    out
29370×
}
30
31460×
pub fn csrf(viewer: &Viewer, token: &str, shell: &Shell) -> Result<(), Error> {
32460×
    if viewer.csrf_ok(token) {
33457×
        Ok(())
34
    } else {
353×
        Err(Error::bad(shell.clone(), "This form has expired; reload the page and try again."))
36
    }
37460×
}
38
39
#[derive(Template)]
40
#[template(path = "settings.html")]
41
pub struct SettingsPage {
42
    shell: Shell,
43
    me: accounts::Account,
44
    notice: Option<String>,
45
    error: Option<String>,
46
    /// The theme cookie's value, for the Appearance form.
47
    theme: &'static str,
48
    themes: &'static [(&'static str, &'static str)],
49
    /// The backdrop cookie's value and the choices (docs/backgrounds.md §7).
50
    backdrop: &'static str,
51
    backdrops: &'static [(&'static str, &'static str)],
52
    /// Whether the hub sends mail, for the "send a new link" button.
53
    mail: bool,
54
}
55
56
/// The themes (hub spec §6.1): the cookie value and its label.
57
const THEMES: &[(&str, &str)] = &[("light", "Light"), ("dark", "Dark"), ("auto", "Match the system")];
58
59
/// Backdrops (docs/backgrounds.md §7): the cookie value and its label.
60
const BACKDROPS: &[(&str, &str)] = &[("moving", "Moving"), ("still", "Still"), ("off", "Off")];
61
62
/// The backdrop the request's cookie asks for; moving when unset.
6325×
fn backdrop_of(headers: &HeaderMap) -> &'static str {
6425×
    let v = auth::viewer::cookie(headers, "backdrop").unwrap_or_default();
6575×
    BACKDROPS.iter().map(|(t, _)| *t).find(|t| *t == v).unwrap_or("moving")
6625×
}
67
68
/// The theme the request's cookie asks for; light when unset or unknown.
6925×
fn theme_of(headers: &HeaderMap) -> &'static str {
7025×
    let v = auth::viewer::cookie(headers, "theme").unwrap_or_default();
7174×
    THEMES.iter().map(|(t, _)| *t).find(|t| *t == v).unwrap_or("light")
7225×
}
73
74
impl SettingsPage {
7525×
    fn new(shell: Shell, me: accounts::Account, headers: &HeaderMap) -> SettingsPage {
7625×
        SettingsPage {
7725×
            shell,
7825×
            me,
7925×
            notice: None,
8025×
            error: None,
8125×
            theme: theme_of(headers),
8225×
            themes: THEMES,
8325×
            backdrop: backdrop_of(headers),
8425×
            backdrops: BACKDROPS,
8525×
            mail: false,
8625×
        }
8725×
    }
88
8925×
    fn with_mail(mut self, app: &Shared) -> Self {
9025×
        self.mail = crate::mail::enabled(app);
9125×
        self
9225×
    }
93
948×
    fn notice(mut self, n: impl Into<String>) -> Self {
958×
        self.notice = Some(n.into());
968×
        self
978×
    }
98
994×
    fn error(mut self, e: impl Into<String>) -> Self {
1004×
        self.error = Some(e.into());
1014×
        self
1024×
    }
103
}
104
10518×
pub async fn profile(State(app): State<Shared>, viewer: Viewer, headers: HeaderMap) -> Result<Page<SettingsPage>, Error> {
10618×
    let shell = Shell::new(&app, "/settings", &viewer);
10718×
    let me = require(&viewer, &shell)?;
10813×
    Ok(Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app)))
10918×
}
110
111
/// `POST /settings/avatar`: upload or remove the profile picture.
1124×
pub async fn avatar(
1134×
    State(app): State<Shared>,
1144×
    viewer: Viewer,
1154×
    headers: HeaderMap,
1164×
    multipart: Multipart,
1174×
) -> Result<Page<SettingsPage>, Error> {
1184×
    let shell = Shell::new(&app, "/settings", &viewer);
1194×
    let me = require(&viewer, &shell)?;
1204×
    let upload = super::avatar::read_upload(multipart).await;
1214×
    csrf(&viewer, &upload.csrf, &shell)?;
1223×
    let result = super::avatar::apply(&app, "account", me.account.id, upload).await;
1233×
    if result.is_ok() {
1242×
        accounts::audit(&app.db, Some(&me.account), "profile.picture", &me.account.username, "").await.ok();
1251×
    }
1263×
    let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account);
1273×
    let page = SettingsPage::new(shell, fresh, &headers).with_mail(&app);
1283×
    Ok(Page(match result {
1292×
        Ok(m) => page.notice(m),
1301×
        Err(e) => page.error(e),
131
    }))
1324×
}
133
134
/// `POST /settings/email/verify`: send a new verification link.
1351×
pub async fn resend_verification(
1361×
    State(app): State<Shared>,
1371×
    viewer: Viewer,
1381×
    headers: HeaderMap,
1391×
    Form(f): Form<super::session::CsrfForm>,
1401×
) -> Result<Page<SettingsPage>, Error> {
1411×
    let shell = Shell::new(&app, "/settings", &viewer);
1421×
    let me = require(&viewer, &shell)?;
1431×
    csrf(&viewer, &f.csrf, &shell)?;
1441×
    let page = SettingsPage::new(shell, me.account.clone(), &headers).with_mail(&app);
1451×
    Ok(Page(match super::recovery::send_verification(&app, &me.account).await {
1460×
        Ok(()) if me.account.email_verified => page.notice("Your email is already verified."),
1470×
        Ok(()) => page.notice(format!("A verification link is on its way to {}.", me.account.email)),
1481×
        Err(e) => page.error(e),
149
    }))
1501×
}
151
152
#[derive(Deserialize)]
153
pub struct AppearanceForm {
154
    #[serde(rename = "_csrf")]
155
    csrf_token: String,
156
    theme: String,
157
    #[serde(default)]
158
    backdrop: String,
159
}
160
161
/// Remember the theme and the backdrop in cookies for a year; the page
162
/// scripts apply them.
1635×
pub async fn appearance(State(app): State<Shared>, viewer: Viewer, Form(f): Form<AppearanceForm>) -> Result<Response, Error> {
1645×
    let shell = Shell::new(&app, "/settings", &viewer);
1655×
    require(&viewer, &shell)?;
1665×
    csrf(&viewer, &f.csrf_token, &shell)?;
1677×
    let Some((theme, _)) = THEMES.iter().find(|(t, _)| *t == f.theme) else {
1681×
        return Err(Error::bad(shell, "Pick dark, light or match the system."));
169
    };
1703×
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
1713×
    let backdrop = if f.backdrop.is_empty() { "moving" } else { f.backdrop.as_str() };
1726×
    let Some((backdrop, _)) = BACKDROPS.iter().find(|(b, _)| *b == backdrop) else {
1731×
        return Err(Error::bad(shell, "Pick a moving, still or no background."));
174
    };
1752×
    Ok((
1762×
        StatusCode::SEE_OTHER,
1772×
        axum::response::AppendHeaders([
1782×
            (header::SET_COOKIE, format!("theme={theme}; Path=/; Max-Age=31536000; SameSite=Lax{secure}")),
1792×
            (header::SET_COOKIE, format!("backdrop={backdrop}; Path=/; Max-Age=31536000; SameSite=Lax{secure}")),
1802×
            (header::LOCATION, "/settings".to_string()),
1812×
        ]),
1822×
    )
1832×
        .into_response())
1845×
}
185
186
#[derive(Deserialize)]
187
pub struct ProfileForm {
188
    #[serde(rename = "_csrf")]
189
    csrf_token: String,
190
    display_name: String,
191
    email: String,
192
    #[serde(default)]
193
    bio: String,
194
    #[serde(default)]
195
    website: String,
196
    #[serde(default)]
197
    location: String,
198
    #[serde(default)]
199
    bluesky: String,
200
    #[serde(default)]
201
    mastodon: String,
202
    #[serde(default)]
203
    github: String,
204
}
205
2069×
pub async fn update_profile(
2079×
    State(app): State<Shared>,
2089×
    viewer: Viewer,
2099×
    headers: HeaderMap,
2109×
    Form(f): Form<ProfileForm>,
2119×
) -> Result<Page<SettingsPage>, Error> {
2129×
    let shell = Shell::new(&app, "/settings", &viewer);
2139×
    let me = require(&viewer, &shell)?;
2149×
    csrf(&viewer, &f.csrf_token, &shell)?;
2158×
    let website = f.website.trim();
2168×
    if !(website.is_empty() || website.starts_with("https://") || website.starts_with("http://")) || website.len() > 200 {
2171×
        return Ok(Page(
2181×
            SettingsPage::new(shell, me.account, &headers).with_mail(&app).error("The website must be an http:// or https:// address."),
2191×
        ));
2207×
    }
221
    // Accounts elsewhere: checked and normalised, or refused by name.
22219×
    let link = |given: &str, what: &str, parse: fn(&str) -> Option<String>| -> Result<String, String> {
22319×
        if given.trim().is_empty() {
22415×
            Ok(String::new())
225
        } else {
2264×
            parse(given).ok_or_else(|| format!("That is not a {what}."))
227
        }
22819×
    };
2297×
    let links = (|| {
230
        Ok::<_, String>((
2317×
            link(&f.bluesky, "Bluesky handle (such as andy.bsky.social)", crate::social::bluesky)?,
2326×
            link(&f.mastodon, "Mastodon address (such as @[email protected])", crate::social::mastodon)?,
2336×
            link(&f.github, "GitHub username", crate::social::github)?,
234
        ))
235
    })();
2367×
    let (bluesky, mastodon, github) = match links {
2376×
        Ok(l) => l,
2381×
        Err(msg) => return Ok(Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app).error(&msg))),
239
    };
2406×
    let bio: String = f.bio.trim().chars().take(280).collect();
2416×
    let location: String = f.location.trim().chars().take(80).collect();
2426×
    accounts::set_profile(&app.db, me.account.id, f.display_name.trim(), f.email.trim())
2436×
        .await
2446×
        .map_err(|e| Error::from_db(shell.clone(), e))?;
2456×
    accounts::set_bio(&app.db, me.account.id, &bio, website, &location).await.map_err(|e| Error::from_db(shell.clone(), e))?;
2466×
    accounts::set_links(&app.db, me.account.id, &bluesky, &mastodon, &github).await.map_err(|e| Error::from_db(shell.clone(), e))?;
2476×
    let changed = me.account.email != f.email.trim();
2486×
    let updated =
2496×
        accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account);
2506×
    let mut notice = "Profile saved.".to_string();
2516×
    if changed && !updated.email.is_empty() {
2524×
        accounts::audit(&app.db, Some(&updated), "email.changed", &updated.username, "").await.ok();
2534×
        match super::recovery::send_verification(&app, &updated).await {
2543×
            Ok(()) => notice = format!("Profile saved. A verification link is on its way to {}.", updated.email),
2551×
            Err(e) => notice = format!("Profile saved. {e}"),
256
        }
2572×
    }
2586×
    Ok(Page(SettingsPage::new(shell, updated, &headers).with_mail(&app).notice(notice)))
2599×
}
260
261
#[derive(Deserialize)]
262
pub struct PasswordForm {
263
    #[serde(rename = "_csrf")]
264
    csrf_token: String,
265
    current: String,
266
    password: String,
267
}
268
2690×
pub async fn change_password(
2700×
    State(app): State<Shared>,
2710×
    viewer: Viewer,
2720×
    headers: HeaderMap,
2730×
    Form(f): Form<PasswordForm>,
2740×
) -> Result<Response, Error> {
2750×
    let shell = Shell::new(&app, "/settings", &viewer);
2760×
    let me = require(&viewer, &shell)?;
2770×
    csrf(&viewer, &f.csrf_token, &shell)?;
2780×
    if !auth::verify_password(&me.account.password_hash, &f.current) {
2790×
        return Ok(
2800×
            Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app).error("Your current password is wrong.")).into_response()
2810×
        );
2820×
    }
2830×
    if let Err(e) = auth::password_ok(&f.password) {
2840×
        return Ok(Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app).error(e)).into_response());
2850×
    }
2860×
    let hash = auth::hash_password(&f.password).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
287
    // A new session salt signs out every other session; this one is renewed.
2880×
    accounts::set_password(&app.db, me.account.id, &hash, &auth::random_hex(16)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
2890×
    accounts::audit(&app.db, Some(&me.account), "password.changed", &me.account.username, "").await.ok();
2900×
    let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account);
2910×
    Ok(super::session::signed_in(&app, &fresh, "/settings/security").await)
2920×
}
293
294
#[derive(Template)]
295
#[template(path = "settings_security.html")]
296
pub struct SecurityPage {
297
    shell: Shell,
298
    me: accounts::Account,
299
    notice: Option<String>,
300
    error: Option<String>,
301
    /// Enrolment in progress: secret, URI and QR.
302
    enrol: Option<(String, String, String)>,
303
    recovery: Vec<String>,
304
    /// Providers on this hub and the login connected, if any (#106).
305
    connected: Vec<(&'static str, &'static str, Option<String>)>,
306
    /// Where the account is signed in (oxygenhub#223).
307
    sessions: Vec<SessionView>,
308
}
309
310
/// One signed-in browser, as Settings › Security lists it.
311
pub struct SessionView {
312
    pub id: i64,
313
    pub current: bool,
314
    pub browser: String,
315
    pub address: String,
316
    pub seen_ms: i64,
317
    pub created_ms: i64,
318
}
319
320
/// "Firefox on Linux" from a User-Agent; "Unknown browser" when it says nothing useful.
32115×
pub fn browser_of(agent: &str) -> String {
322198×
    let has = |s: &str| agent.contains(s);
32315×
    let browser = if has("Edg/") {
3241×
        "Edge"
32514×
    } else if has("OPR/") {
3260×
        "Opera"
32714×
    } else if has("Firefox/") {
3281×
        "Firefox"
32913×
    } else if has("Chrome/") || has("Chromium/") {
3301×
        "Chrome"
33112×
    } else if has("Safari/") {
3321×
        "Safari"
33311×
    } else if has("curl/") {
3340×
        "curl"
335
    } else {
33611×
        ""
337
    };
33815×
    let os = if has("Android") {
3390×
        "Android"
34015×
    } else if has("iPhone") || has("iPad") {
3411×
        "iOS"
34214×
    } else if has("Windows") {
3431×
        "Windows"
34413×
    } else if has("Mac OS X") || has("Macintosh") {
3451×
        "macOS"
34612×
    } else if has("CrOS") {
3470×
        "ChromeOS"
34812×
    } else if has("Linux") {
3491×
        "Linux"
350
    } else {
35111×
        ""
352
    };
35315×
    match (browser, os) {
35415×
        ("", "") => "Unknown browser".into(),
3554×
        (b, "") => b.into(),
3564×
        ("", o) => format!("A browser on {o}"),
3574×
        (b, o) => format!("{b} on {o}"),
358
    }
35915×
}
360
3617×
async fn sessions_of(app: &Shared, me: &crate::auth::ViewerAccount) -> sqlx::Result<Vec<SessionView>> {
3627×
    Ok(crate::db::sessions::of_account(&app.db, me.account.id, &me.account.session_salt)
3637×
        .await?
3647×
        .into_iter()
3657×
        .map(|s| SessionView {
36610×
            id: s.id,
36710×
            current: s.id == me.session_id,
36810×
            browser: browser_of(&s.agent),
36910×
            address: s.address,
37010×
            seen_ms: s.seen_ms,
37110×
            created_ms: s.created_ms,
37210×
        })
3737×
        .collect())
3747×
}
375
376
#[derive(Deserialize)]
377
pub struct SecurityQuery {
378
    notice: Option<String>,
379
    error: Option<String>,
380
}
381
38211×
pub async fn security(State(app): State<Shared>, viewer: Viewer, Query(q): Query<SecurityQuery>) -> Result<Page<SecurityPage>, Error> {
38311×
    let shell = Shell::new(&app, "/settings/security", &viewer);
38411×
    let me = require(&viewer, &shell)?;
3857×
    let connected = connected_of(&app, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
3867×
    let sessions = sessions_of(&app, &me).await.map_err(|e| Error::from_db(shell.clone(), e))?;
3877×
    Ok(Page(SecurityPage { shell, me: me.account, notice: q.notice, error: q.error, enrol: None, recovery: vec![], connected, sessions }))
38811×
}
389
390
/// Each sign-in provider this hub offers, with the login connected to the account.
3917×
pub async fn connected_of(app: &Shared, account_id: i64) -> sqlx::Result<Vec<(&'static str, &'static str, Option<String>)>> {
3927×
    let links = crate::signin::links_of(&app.db, account_id).await?;
3937×
    let mut out = vec![];
3947×
    for p in crate::signin::enabled(app).await {
3956×
        out.push((p.id, p.name, links.iter().find(|l| l.provider == p.id).map(|l| l.login.clone())));
396
    }
3977×
    Ok(out)
3987×
}
399
400
#[derive(Deserialize)]
401
pub struct TotpForm {
402
    #[serde(rename = "_csrf")]
403
    csrf_token: String,
404
    #[serde(default)]
405
    secret: String,
406
    #[serde(default)]
407
    code: String,
408
    #[serde(default)]
409
    password: String,
410
}
411
412
/// Step one: show a fresh secret to scan.
4131×
pub async fn totp_begin(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> {
4141×
    let shell = Shell::new(&app, "/settings/security", &viewer);
4151×
    let me = require(&viewer, &shell)?;
4161×
    csrf(&viewer, &f.csrf_token, &shell)?;
4171×
    let secret = totp::new_secret();
4181×
    let uri = totp::uri(&app.config.site.name, &me.account.username, &secret);
4191×
    let qr = totp::qr_svg(&uri).unwrap_or_default();
4201×
    Ok(Page(SecurityPage {
4211×
        shell,
4221×
        me: me.account,
4231×
        notice: None,
4241×
        error: None,
4251×
        enrol: Some((secret, uri, qr)),
4261×
        recovery: vec![],
4271×
        connected: vec![],
4281×
        sessions: vec![],
4291×
    }))
4301×
}
431
432
/// Step two: the first code proves the app holds the secret.
4331×
pub async fn totp_enable(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> {
4341×
    let shell = Shell::new(&app, "/settings/security", &viewer);
4351×
    let me = require(&viewer, &shell)?;
4361×
    csrf(&viewer, &f.csrf_token, &shell)?;
4371×
    let now = (db::now_ms() / 1000) as u64;
4381×
    if f.secret.is_empty() || !totp::verify(&f.secret, &f.code, now) {
4390×
        let uri = totp::uri(&app.config.site.name, &me.account.username, &f.secret);
4400×
        let qr = totp::qr_svg(&uri).unwrap_or_default();
4410×
        return Ok(Page(SecurityPage {
4420×
            shell,
4430×
            me: me.account,
4440×
            notice: None,
4450×
            error: Some("That code did not match; scan again and enter the current code.".into()),
4460×
            enrol: Some((f.secret, uri, qr)),
4470×
            recovery: vec![],
4480×
            connected: vec![],
4490×
            sessions: vec![],
4500×
        }));
4511×
    }
4521×
    let (codes, stored) = totp::new_recovery_codes();
4531×
    accounts::set_totp(&app.db, me.account.id, Some(&f.secret), &stored).await.map_err(|e| Error::from_db(shell.clone(), e))?;
4541×
    accounts::audit(&app.db, Some(&me.account), "totp.enabled", &me.account.username, "").await.ok();
4551×
    let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account);
4561×
    Ok(Page(SecurityPage {
4571×
        shell,
4581×
        me: fresh,
4591×
        notice: Some("Two-factor authentication is on. Keep these recovery codes somewhere safe; each works once.".into()),
4601×
        error: None,
4611×
        enrol: None,
4621×
        recovery: codes,
4631×
        connected: vec![],
4641×
        sessions: vec![],
4651×
    }))
4661×
}
467
4680×
pub async fn totp_disable(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> {
4690×
    let shell = Shell::new(&app, "/settings/security", &viewer);
4700×
    let me = require(&viewer, &shell)?;
4710×
    csrf(&viewer, &f.csrf_token, &shell)?;
4720×
    if !auth::verify_password(&me.account.password_hash, &f.password) {
4730×
        return Ok(Page(SecurityPage {
4740×
            shell,
4750×
            me: me.account,
4760×
            notice: None,
4770×
            error: Some("Your password is wrong.".into()),
4780×
            enrol: None,
4790×
            recovery: vec![],
4800×
            connected: vec![],
4810×
            sessions: vec![],
4820×
        }));
4830×
    }
4840×
    accounts::set_totp(&app.db, me.account.id, None, "").await.map_err(|e| Error::from_db(shell.clone(), e))?;
4850×
    accounts::audit(&app.db, Some(&me.account), "totp.disabled", &me.account.username, "").await.ok();
4860×
    let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account);
4870×
    Ok(Page(SecurityPage {
4880×
        shell,
4890×
        me: fresh,
4900×
        notice: Some("Two-factor authentication is off.".into()),
4910×
        error: None,
4920×
        enrol: None,
4930×
        recovery: vec![],
4940×
        connected: vec![],
4950×
        sessions: vec![],
4960×
    }))
4970×
}
498
499
/// Sign out everywhere: a new session salt invalidates every cookie, then
500
/// this browser gets a fresh one.
5011×
pub async fn sessions_reset(State(app): State<Shared>, viewer: Viewer, Form(f): Form<super::session::CsrfForm>) -> Result<Response, Error> {
5021×
    let shell = Shell::new(&app, "/settings/security", &viewer);
5031×
    let me = require(&viewer, &shell)?;
5041×
    csrf(&viewer, &f.csrf, &shell)?;
5051×
    accounts::set_session_salt(&app.db, me.account.id, &auth::random_hex(16)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5061×
    accounts::audit(&app.db, Some(&me.account), "sessions.reset", &me.account.username, "").await.ok();
5071×
    let fresh = accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account);
5081×
    Ok(super::session::signed_in(&app, &fresh, "/settings/security").await)
5091×
}
510
511
/// `POST /settings/security/sessions/{id}/end`: sign one browser out.
5121×
pub async fn session_end(
5131×
    State(app): State<Shared>,
5141×
    viewer: Viewer,
5151×
    Path(id): Path<i64>,
5161×
    Form(f): Form<super::session::CsrfForm>,
5171×
) -> Result<Response, Error> {
5181×
    let shell = Shell::new(&app, "/settings/security", &viewer);
5191×
    let me = require(&viewer, &shell)?;
5201×
    csrf(&viewer, &f.csrf, &shell)?;
5211×
    let ended = crate::db::sessions::end(&app.db, me.account.id, id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5221×
    if ended {
5231×
        accounts::audit(&app.db, Some(&me.account), "session.ended", &me.account.username, &id.to_string()).await.ok();
5240×
    }
5251×
    let to = if id == me.session_id { "/" } else { "/settings/security?notice=That+browser+is+signed+out." };
5261×
    Ok(Redirect::to(to).into_response())
5271×
}
528
529
// ------------------------------------------------------------------- keys
530
531
#[derive(Template)]
532
#[template(path = "settings_keys.html")]
533
pub struct KeysPage {
534
    shell: Shell,
535
    me: accounts::Account,
536
    keys: Vec<accounts::LinkedIdentity>,
537
    notice: Option<String>,
538
    error: Option<String>,
539
    /// A pending challenge: id, hex bytes, identity name.
540
    pending: Option<(i64, String, String)>,
541
}
542
5439×
async fn keys_page(
5449×
    app: &Shared,
5459×
    shell: Shell,
5469×
    me: accounts::Account,
5479×
    notice: Option<String>,
5489×
    error: Option<String>,
5499×
    pending: Option<(i64, String, String)>,
5509×
) -> Result<Page<KeysPage>, Error> {
5519×
    let keys = accounts::identities_of(&app.db, me.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5529×
    Ok(Page(KeysPage { shell, me, keys, notice, error, pending }))
5539×
}
554
5553×
pub async fn keys(State(app): State<Shared>, viewer: Viewer) -> Result<Page<KeysPage>, Error> {
5563×
    let shell = Shell::new(&app, "/settings/keys", &viewer);
5573×
    let me = require(&viewer, &shell)?;
5583×
    keys_page(&app, shell, me.account, None, None, None).await
5593×
}
560
561
/// Upload an identity object (`oxy identity export`): the hub issues a
562
/// challenge to sign with that key.
5633×
pub async fn keys_upload(State(app): State<Shared>, viewer: Viewer, mut multipart: Multipart) -> Result<Page<KeysPage>, Error> {
5643×
    let shell = Shell::new(&app, "/settings/keys", &viewer);
5653×
    let me = require(&viewer, &shell)?;
5663×
    let mut token = String::new();
5673×
    let mut object: Vec<u8> = Vec::new();
5689×
    while let Ok(Some(field)) = multipart.next_field().await {
5696×
        match field.name() {
5706×
            Some("_csrf") => token = field.text().await.unwrap_or_default(),
5713×
            Some("identity") => object = field.bytes().await.map(|b| b.to_vec()).unwrap_or_default(),
5720×
            _ => {}
573
        }
574
    }
5753×
    csrf(&viewer, &token, &shell)?;
5763×
    let identity = match Identity::decode(&object) {
5773×
        Ok(i) => i,
5780×
        Err(e) => return keys_page(&app, shell, me.account, None, Some(format!("That is not an identity file: {e}")), None).await,
579
    };
5803×
    if identity.hash() == app.hub_key.key {
5811×
        let msg = "That is this hub's own key, which only the hub holds. Upload your identity: after `oxy identity delegate add` with the hub's key, run `oxy identity export` in that checkout and upload the file it writes.";
5821×
        return keys_page(&app, shell, me.account, None, Some(msg.into()), None).await;
5832×
    }
5842×
    let key = identity.hash().to_hex();
5852×
    if let Some(existing) = accounts::identity_by_key(&app.db, &key).await.map_err(|e| Error::from_db(shell.clone(), e))? {
5860×
        let msg = if existing.account_id == me.account.id {
5870×
            "That key is already linked to you. If you have delegated since (`oxy identity delegate add`), export again: a delegation makes a new version of your identity."
588
        } else {
5890×
            "That key is linked to another account."
590
        };
5910×
        return keys_page(&app, shell, me.account, None, Some(msg.into()), None).await;
5922×
    }
5932×
    let bytes = auth::random_hex(32);
5942×
    let id = accounts::create_challenge(&app.db, me.account.id, &bytes).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5952×
    sqlx::query("UPDATE challenges SET object = $1 WHERE id = $2")
5962×
        .bind(&object)
5972×
        .bind(id)
5982×
        .execute(&app.db)
5992×
        .await
6002×
        .map_err(|e| Error::from_db(shell.clone(), e))?;
6012×
    keys_page(&app, shell, me.account, None, None, Some((id, bytes, identity.name))).await
6023×
}
603
604
#[derive(Deserialize)]
605
pub struct KeyVerifyForm {
606
    #[serde(rename = "_csrf")]
607
    csrf_token: String,
608
    challenge: i64,
609
    signature: String,
610
}
611
6123×
pub async fn keys_verify(State(app): State<Shared>, viewer: Viewer, Form(f): Form<KeyVerifyForm>) -> Result<Page<KeysPage>, Error> {
6133×
    let shell = Shell::new(&app, "/settings/keys", &viewer);
6143×
    let me = require(&viewer, &shell)?;
6153×
    csrf(&viewer, &f.csrf_token, &shell)?;
6163×
    let object: Option<Vec<u8>> = sqlx::query_scalar("SELECT object FROM challenges WHERE id = $1 AND account_id = $2")
6173×
        .bind(f.challenge)
6183×
        .bind(me.account.id)
6193×
        .fetch_optional(&app.db)
6203×
        .await
6213×
        .map_err(|e| Error::from_db(shell.clone(), e))?;
6223×
    let bytes = accounts::take_challenge(&app.db, me.account.id, f.challenge).await.map_err(|e| Error::from_db(shell.clone(), e))?;
6233×
    let (Some(object), Some(bytes)) = (object, bytes) else {
6241×
        return keys_page(&app, shell, me.account, None, Some("That challenge has expired; upload the identity again.".into()), None).await;
625
    };
6262×
    let Ok(identity) = Identity::decode(&object) else {
6270×
        return keys_page(&app, shell, me.account, None, Some("The stored identity is unreadable.".into()), None).await;
628
    };
6292×
    let sig_bytes = hex::decode(f.signature.trim()).unwrap_or_default();
6302×
    let sigs = Signature::decode_list(&sig_bytes).unwrap_or_default();
6312×
    let challenge = hex::decode(&bytes).unwrap_or_default();
6322×
    let ok = sigs.first().is_some_and(|sig| oxy_core::identity::verify_challenge(&identity, sig, &challenge).is_ok());
6332×
    if !ok {
634
        // Signed by another key than the one uploaded: say which, as it is
635
        // usually the wrong checkout or an `author.signer` set there.
6361×
        let msg = match sigs.first() {
6371×
            Some(sig) if sig.key != identity.hash() => format!(
638
                "That signature is by key {}, but the identity uploaded is {} ({}). Sign in a checkout whose `oxy identity export` gives that identity, without an `author.signer` set, or upload the identity that checkout exports.",
6391×
                sig.key.short(12),
6401×
                identity.hash().short(12),
641
                identity.name
642
            ),
6430×
            _ => "The signature does not verify against that identity and challenge.".into(),
644
        };
6451×
        return keys_page(&app, shell, me.account, None, Some(msg), None).await;
6461×
    }
6471×
    let key = identity.hash().to_hex();
6481×
    accounts::link_identity(&app.db, me.account.id, &key, &identity.name, &identity.email, &object)
6491×
        .await
6501×
        .map_err(|e| Error::from_db(shell.clone(), e))?;
6511×
    accounts::audit(&app.db, Some(&me.account), "identity.linked", &key, &identity.name).await.ok();
6521×
    keys_page(&app, shell, me.account, Some("Key linked. Changes signed with it are now yours on every page.".into()), None, None).await
6533×
}
654
655
#[derive(Deserialize)]
656
pub struct KeyForm {
657
    #[serde(rename = "_csrf")]
658
    csrf_token: String,
659
    key: String,
660
}
661
6620×
pub async fn keys_unlink(State(app): State<Shared>, viewer: Viewer, Form(f): Form<KeyForm>) -> Result<Page<KeysPage>, Error> {
6630×
    let shell = Shell::new(&app, "/settings/keys", &viewer);
6640×
    let me = require(&viewer, &shell)?;
6650×
    csrf(&viewer, &f.csrf_token, &shell)?;
6660×
    accounts::unlink_identity(&app.db, me.account.id, &f.key).await.map_err(|e| Error::from_db(shell.clone(), e))?;
6670×
    accounts::audit(&app.db, Some(&me.account), "identity.unlinked", &f.key, "").await.ok();
6680×
    keys_page(&app, shell, me.account, Some("Key unlinked.".into()), None, None).await
6690×
}
670
671
// ----------------------------------------------------------------- tokens
672
673
#[derive(Template)]
674
#[template(path = "settings_tokens.html")]
675
pub struct TokensPage {
676
    shell: Shell,
677
    scopes: &'static [(&'static str, &'static str)],
678
    me: accounts::Account,
679
    tokens: Vec<accounts::Token>,
680
    /// A freshly created token, shown once.
681
    fresh: Option<String>,
682
    notice: Option<String>,
683
    error: Option<String>,
684
}
685
68639×
async fn tokens_page(
68739×
    app: &Shared,
68839×
    shell: Shell,
68939×
    me: accounts::Account,
69039×
    fresh: Option<String>,
69139×
    notice: Option<String>,
69239×
    error: Option<String>,
69339×
) -> Result<Page<TokensPage>, Error> {
69439×
    let tokens = accounts::tokens_of(&app.db, me.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
69539×
    Ok(Page(TokensPage { shell, scopes: SCOPES, me, tokens, fresh, notice, error }))
69639×
}
697
69819×
pub async fn tokens(State(app): State<Shared>, viewer: Viewer) -> Result<Page<TokensPage>, Error> {
69919×
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
70019×
    let me = require(&viewer, &shell)?;
70119×
    tokens_page(&app, shell, me.account, None, None, None).await
70219×
}
703
704
#[derive(Deserialize)]
705
pub struct TokenForm {
706
    #[serde(rename = "_csrf")]
707
    csrf_token: String,
708
    name: String,
709
    #[serde(default)]
710
    scopes: Vec<String>,
711
    #[serde(default)]
712
    repos: String,
713
    #[serde(default)]
714
    expires_days: String,
715
    /// An agent uses it: tell me what it does (oxygenhub#183).
716
    #[serde(default)]
717
    agent: String,
718
}
719
720
/// Every scope the hub checks, with what it grants. The tokens page lists
721
/// exactly these, so a scope cannot exist without a checkbox.
722
pub const SCOPES: &[(&str, &str)] = &[
723
    ("repo:read", "read repositories you can see: clone, fetch, pull, and the read API"),
724
    ("repo:write", "push to repositories you can write to; also covers proposals, issues and checks"),
725
    ("repo:admin", "create repositories and change settings through the API"),
726
    ("proposals:write", "open, comment on and review proposals, without push access"),
727
    ("issues:write", "open, comment on and close issues, without push access"),
728
    ("checks:write", "report checks on states, for CI systems, without push access"),
729
    ("hooks:admin", "manage webhooks through the API"),
730
    ("user:read", "read your own profile through the API"),
731
];
732
73320×
pub async fn tokens_create(
73420×
    State(app): State<Shared>,
73520×
    viewer: Viewer,
73620×
    axum_extra::extract::Form(f): axum_extra::extract::Form<TokenForm>,
73720×
) -> Result<Page<TokensPage>, Error> {
73820×
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
73920×
    let me = require(&viewer, &shell)?;
74020×
    csrf(&viewer, &f.csrf_token, &shell)?;
74120×
    let name = f.name.trim();
74220×
    if name.is_empty() {
7430×
        return tokens_page(&app, shell, me.account, None, None, Some("Give the token a name.".into())).await;
74420×
    }
74577×
    let scopes: Vec<&str> = f.scopes.iter().map(String::as_str).filter(|s| SCOPES.iter().any(|(k, _)| k == s)).collect();
74620×
    if scopes.is_empty() {
7470×
        return tokens_page(&app, shell, me.account, None, None, Some("Pick at least one scope.".into())).await;
74820×
    }
74920×
    let expires_ms = f.expires_days.trim().parse::<i64>().ok().filter(|d| *d > 0).map(|d| db::now_ms() + d * 86_400_000);
75020×
    let repos = f.repos.split(',').map(str::trim).filter(|r| !r.is_empty()).collect::<Vec<_>>().join(",");
75120×
    let (secret, hash) = auth::new_token();
75220×
    accounts::create_token(&app.db, me.account.id, name, &hash, &scopes.join(","), &repos, expires_ms)
75320×
        .await
75420×
        .map_err(|e| Error::from_db(shell.clone(), e))?;
75520×
    if !f.agent.is_empty() {
7560×
        if let Ok(Some(t)) = accounts::token_by_hash(&app.db, &hash).await {
7570×
            accounts::set_token_agent(&app.db, me.account.id, t.id, true).await.map_err(|e| Error::from_db(shell.clone(), e))?;
7580×
        }
75920×
    }
76020×
    accounts::audit(&app.db, Some(&me.account), "token.created", name, &scopes.join(",")).await.ok();
76120×
    tokens_page(&app, shell, me.account, Some(secret), Some("Copy the token now; it is not shown again.".into()), None).await
76220×
}
763
764
/// Mark a token as an agent's, or not (oxygenhub#183): what is done with
765
/// an agent's token is told to its owner, as anyone else's doing is.
7660×
pub async fn tokens_agent(
7670×
    State(app): State<Shared>,
7680×
    viewer: Viewer,
7690×
    Path(id): Path<i64>,
7700×
    Form(f): Form<super::session::CsrfForm>,
7710×
) -> Result<Page<TokensPage>, Error> {
7720×
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
7730×
    let me = require(&viewer, &shell)?;
7740×
    csrf(&viewer, &f.csrf, &shell)?;
7750×
    let tokens = accounts::tokens_of(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
7760×
    let Some(t) = tokens.iter().find(|t| t.id == id) else {
7770×
        return tokens_page(&app, shell, me.account, None, None, Some("No such token.".into())).await;
778
    };
7790×
    accounts::set_token_agent(&app.db, me.account.id, id, !t.agent).await.map_err(|e| Error::from_db(shell.clone(), e))?;
7800×
    accounts::audit(&app.db, Some(&me.account), "token.agent", &t.name, if t.agent { "off" } else { "on" }).await.ok();
7810×
    let notice = if t.agent {
7820×
        format!("{} is no longer marked as an agent's.", t.name)
783
    } else {
7840×
        format!("{} is an agent's: you will hear what it does.", t.name)
785
    };
7860×
    tokens_page(&app, shell, me.account, None, Some(notice), None).await
7870×
}
788
7890×
pub async fn tokens_delete(
7900×
    State(app): State<Shared>,
7910×
    viewer: Viewer,
7920×
    Path(id): Path<i64>,
7930×
    Form(f): Form<super::session::CsrfForm>,
7940×
) -> Result<Page<TokensPage>, Error> {
7950×
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
7960×
    let me = require(&viewer, &shell)?;
7970×
    csrf(&viewer, &f.csrf, &shell)?;
7980×
    accounts::delete_token(&app.db, me.account.id, id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
7990×
    accounts::audit(&app.db, Some(&me.account), "token.deleted", &id.to_string(), "").await.ok();
8000×
    tokens_page(&app, shell, me.account, None, Some("Token deleted.".into()), None).await
8010×
}
802
803
#[cfg(test)]
804
mod tests {
805
    use super::browser_of;
806
807
    #[test]
8081×
    fn browsers_are_named_from_their_agent() {
8091×
        let ff = "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0";
8101×
        let chrome_mac =
8111×
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0 Safari/537.36";
8121×
        let edge = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0 Safari/537.36 Edg/129.0";
8131×
        let iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1";
8141×
        assert_eq!(browser_of(ff), "Firefox on Linux");
8151×
        assert_eq!(browser_of(chrome_mac), "Chrome on macOS");
8161×
        assert_eq!(browser_of(edge), "Edge on Windows");
8171×
        assert_eq!(browser_of(iphone), "Safari on iOS");
8181×
        assert_eq!(browser_of(""), "Unknown browser");
8191×
    }
820
}