OXYGENHUB
◆ v0.5.0 oxygenhub / crates / hub / src / web / settings.rs
28.9 KiB · Rust · last changed Notifications that reach you, and 2FA without the password twice 21 days ago source blame history raw
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, Response};
12
use oxy_core::identity::{Identity, Signature};
13
use serde::Deserialize;
14
15
/// The signed-in account, or a redirect to sign in.
16
pub fn require(viewer: &Viewer, shell: &Shell) -> Result<ViewerAccount, Error> {
17
    viewer.0.clone().ok_or_else(|| Error::redirect(format!("/login?next={}", urlencode(&shell.path))))
18
}
19
20
pub fn urlencode(s: &str) -> String {
21
    let mut out = String::new();
22
    for b in s.bytes() {
23
        match b {
24
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char),
25
            _ => out.push_str(&format!("%{b:02X}")),
26
        }
27
    }
28
    out
29
}
30
31
pub fn csrf(viewer: &Viewer, token: &str, shell: &Shell) -> Result<(), Error> {
32
    if viewer.csrf_ok(token) {
33
        Ok(())
34
    } else {
35
        Err(Error::bad(shell.clone(), "This form has expired; reload the page and try again."))
36
    }
37
}
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.
63
fn backdrop_of(headers: &HeaderMap) -> &'static str {
64
    let v = auth::viewer::cookie(headers, "backdrop").unwrap_or_default();
65
    BACKDROPS.iter().map(|(t, _)| *t).find(|t| *t == v).unwrap_or("moving")
66
}
67
68
/// The theme the request's cookie asks for; light when unset or unknown.
69
fn theme_of(headers: &HeaderMap) -> &'static str {
70
    let v = auth::viewer::cookie(headers, "theme").unwrap_or_default();
71
    THEMES.iter().map(|(t, _)| *t).find(|t| *t == v).unwrap_or("light")
72
}
73
74
impl SettingsPage {
75
    fn new(shell: Shell, me: accounts::Account, headers: &HeaderMap) -> SettingsPage {
76
        SettingsPage {
77
            shell,
78
            me,
79
            notice: None,
80
            error: None,
81
            theme: theme_of(headers),
82
            themes: THEMES,
83
            backdrop: backdrop_of(headers),
84
            backdrops: BACKDROPS,
85
            mail: false,
86
        }
87
    }
88
89
    fn with_mail(mut self, app: &Shared) -> Self {
90
        self.mail = crate::mail::enabled(app);
91
        self
92
    }
93
94
    fn notice(mut self, n: impl Into<String>) -> Self {
95
        self.notice = Some(n.into());
96
        self
97
    }
98
99
    fn error(mut self, e: impl Into<String>) -> Self {
100
        self.error = Some(e.into());
101
        self
102
    }
103
}
104
105
pub async fn profile(State(app): State<Shared>, viewer: Viewer, headers: HeaderMap) -> Result<Page<SettingsPage>, Error> {
106
    let shell = Shell::new(&app, "/settings", &viewer);
107
    let me = require(&viewer, &shell)?;
108
    Ok(Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app)))
109
}
110
111
/// `POST /settings/avatar`: upload or remove the profile picture.
112
pub async fn avatar(
113
    State(app): State<Shared>,
114
    viewer: Viewer,
115
    headers: HeaderMap,
116
    multipart: Multipart,
117
) -> Result<Page<SettingsPage>, Error> {
118
    let shell = Shell::new(&app, "/settings", &viewer);
119
    let me = require(&viewer, &shell)?;
120
    let upload = super::avatar::read_upload(multipart).await;
121
    csrf(&viewer, &upload.csrf, &shell)?;
122
    let result = super::avatar::apply(&app, "account", me.account.id, upload).await;
123
    if result.is_ok() {
124
        accounts::audit(&app.db, Some(&me.account), "profile.picture", &me.account.username, "").await.ok();
125
    }
126
    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);
127
    let page = SettingsPage::new(shell, fresh, &headers).with_mail(&app);
128
    Ok(Page(match result {
129
        Ok(m) => page.notice(m),
130
        Err(e) => page.error(e),
131
    }))
132
}
133
134
/// `POST /settings/email/verify`: send a new verification link.
135
pub async fn resend_verification(
136
    State(app): State<Shared>,
137
    viewer: Viewer,
138
    headers: HeaderMap,
139
    Form(f): Form<super::session::CsrfForm>,
140
) -> Result<Page<SettingsPage>, Error> {
141
    let shell = Shell::new(&app, "/settings", &viewer);
142
    let me = require(&viewer, &shell)?;
143
    csrf(&viewer, &f.csrf, &shell)?;
144
    let page = SettingsPage::new(shell, me.account.clone(), &headers).with_mail(&app);
145
    Ok(Page(match super::recovery::send_verification(&app, &me.account).await {
146
        Ok(()) if me.account.email_verified => page.notice("Your email is already verified."),
147
        Ok(()) => page.notice(format!("A verification link is on its way to {}.", me.account.email)),
148
        Err(e) => page.error(e),
149
    }))
150
}
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.
163
pub async fn appearance(State(app): State<Shared>, viewer: Viewer, Form(f): Form<AppearanceForm>) -> Result<Response, Error> {
164
    let shell = Shell::new(&app, "/settings", &viewer);
165
    require(&viewer, &shell)?;
166
    csrf(&viewer, &f.csrf_token, &shell)?;
167
    let Some((theme, _)) = THEMES.iter().find(|(t, _)| *t == f.theme) else {
168
        return Err(Error::bad(shell, "Pick dark, light or match the system."));
169
    };
170
    let backdrop = if f.backdrop.is_empty() { "moving" } else { f.backdrop.as_str() };
171
    let Some((backdrop, _)) = BACKDROPS.iter().find(|(b, _)| *b == backdrop) else {
172
        return Err(Error::bad(shell, "Pick a moving, still or no background."));
173
    };
174
    Ok((
175
        StatusCode::SEE_OTHER,
176
        axum::response::AppendHeaders([
177
            (header::SET_COOKIE, format!("theme={theme}; Path=/; Max-Age=31536000; SameSite=Lax")),
178
            (header::SET_COOKIE, format!("backdrop={backdrop}; Path=/; Max-Age=31536000; SameSite=Lax")),
179
            (header::LOCATION, "/settings".to_string()),
180
        ]),
181
    )
182
        .into_response())
183
}
184
185
#[derive(Deserialize)]
186
pub struct ProfileForm {
187
    #[serde(rename = "_csrf")]
188
    csrf_token: String,
189
    display_name: String,
190
    email: String,
191
    #[serde(default)]
192
    bio: String,
193
    #[serde(default)]
194
    website: String,
195
    #[serde(default)]
196
    location: String,
197
    #[serde(default)]
198
    bluesky: String,
199
    #[serde(default)]
200
    mastodon: String,
201
    #[serde(default)]
202
    github: String,
203
}
204
205
pub async fn update_profile(
206
    State(app): State<Shared>,
207
    viewer: Viewer,
208
    headers: HeaderMap,
209
    Form(f): Form<ProfileForm>,
210
) -> Result<Page<SettingsPage>, Error> {
211
    let shell = Shell::new(&app, "/settings", &viewer);
212
    let me = require(&viewer, &shell)?;
213
    csrf(&viewer, &f.csrf_token, &shell)?;
214
    let website = f.website.trim();
215
    if !(website.is_empty() || website.starts_with("https://") || website.starts_with("http://")) || website.len() > 200 {
216
        return Ok(Page(
217
            SettingsPage::new(shell, me.account, &headers).with_mail(&app).error("The website must be an http:// or https:// address."),
218
        ));
219
    }
220
    // Accounts elsewhere: checked and normalised, or refused by name.
221
    let link = |given: &str, what: &str, parse: fn(&str) -> Option<String>| -> Result<String, String> {
222
        if given.trim().is_empty() {
223
            Ok(String::new())
224
        } else {
225
            parse(given).ok_or_else(|| format!("That is not a {what}."))
226
        }
227
    };
228
    let links = (|| {
229
        Ok::<_, String>((
230
            link(&f.bluesky, "Bluesky handle (such as andy.bsky.social)", crate::social::bluesky)?,
231
            link(&f.mastodon, "Mastodon address (such as @[email protected])", crate::social::mastodon)?,
232
            link(&f.github, "GitHub username", crate::social::github)?,
233
        ))
234
    })();
235
    let (bluesky, mastodon, github) = match links {
236
        Ok(l) => l,
237
        Err(msg) => return Ok(Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app).error(&msg))),
238
    };
239
    let bio: String = f.bio.trim().chars().take(280).collect();
240
    let location: String = f.location.trim().chars().take(80).collect();
241
    accounts::set_profile(&app.db, me.account.id, f.display_name.trim(), f.email.trim())
242
        .await
243
        .map_err(|e| Error::from_db(shell.clone(), e))?;
244
    accounts::set_bio(&app.db, me.account.id, &bio, website, &location).await.map_err(|e| Error::from_db(shell.clone(), e))?;
245
    accounts::set_links(&app.db, me.account.id, &bluesky, &mastodon, &github).await.map_err(|e| Error::from_db(shell.clone(), e))?;
246
    let changed = me.account.email != f.email.trim();
247
    let updated =
248
        accounts::account_by_id(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(me.account);
249
    let mut notice = "Profile saved.".to_string();
250
    if changed && !updated.email.is_empty() {
251
        accounts::audit(&app.db, Some(&updated), "email.changed", &updated.username, "").await.ok();
252
        match super::recovery::send_verification(&app, &updated).await {
253
            Ok(()) => notice = format!("Profile saved. A verification link is on its way to {}.", updated.email),
254
            Err(e) => notice = format!("Profile saved. {e}"),
255
        }
256
    }
257
    Ok(Page(SettingsPage::new(shell, updated, &headers).with_mail(&app).notice(notice)))
258
}
259
260
#[derive(Deserialize)]
261
pub struct PasswordForm {
262
    #[serde(rename = "_csrf")]
263
    csrf_token: String,
264
    current: String,
265
    password: String,
266
}
267
268
pub async fn change_password(
269
    State(app): State<Shared>,
270
    viewer: Viewer,
271
    headers: HeaderMap,
272
    Form(f): Form<PasswordForm>,
273
) -> Result<Response, Error> {
274
    let shell = Shell::new(&app, "/settings", &viewer);
275
    let me = require(&viewer, &shell)?;
276
    csrf(&viewer, &f.csrf_token, &shell)?;
277
    if !auth::verify_password(&me.account.password_hash, &f.current) {
278
        return Ok(
279
            Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app).error("Your current password is wrong.")).into_response()
280
        );
281
    }
282
    if let Err(e) = auth::password_ok(&f.password) {
283
        return Ok(Page(SettingsPage::new(shell, me.account, &headers).with_mail(&app).error(e)).into_response());
284
    }
285
    let hash = auth::hash_password(&f.password).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
286
    // A new session salt signs out every other session; this one is renewed.
287
    accounts::set_password(&app.db, me.account.id, &hash, &auth::random_hex(16)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
288
    accounts::audit(&app.db, Some(&me.account), "password.changed", &me.account.username, "").await.ok();
289
    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);
290
    Ok(super::session::signed_in(&app, &fresh, "/settings/security"))
291
}
292
293
#[derive(Template)]
294
#[template(path = "settings_security.html")]
295
pub struct SecurityPage {
296
    shell: Shell,
297
    me: accounts::Account,
298
    notice: Option<String>,
299
    error: Option<String>,
300
    /// Enrolment in progress: secret, URI and QR.
301
    enrol: Option<(String, String, String)>,
302
    recovery: Vec<String>,
303
    /// Providers on this hub and the login connected, if any (#106).
304
    connected: Vec<(&'static str, &'static str, Option<String>)>,
305
}
306
307
#[derive(Deserialize)]
308
pub struct SecurityQuery {
309
    notice: Option<String>,
310
    error: Option<String>,
311
}
312
313
pub async fn security(State(app): State<Shared>, viewer: Viewer, Query(q): Query<SecurityQuery>) -> Result<Page<SecurityPage>, Error> {
314
    let shell = Shell::new(&app, "/settings/security", &viewer);
315
    let me = require(&viewer, &shell)?;
316
    let connected = connected_of(&app, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
317
    Ok(Page(SecurityPage { shell, me: me.account, notice: q.notice, error: q.error, enrol: None, recovery: vec![], connected }))
318
}
319
320
/// Each sign-in provider this hub offers, with the login connected to the account.
321
pub async fn connected_of(app: &Shared, account_id: i64) -> sqlx::Result<Vec<(&'static str, &'static str, Option<String>)>> {
322
    let links = crate::signin::links_of(&app.db, account_id).await?;
323
    let mut out = vec![];
324
    for p in crate::signin::enabled(app).await {
325
        out.push((p.id, p.name, links.iter().find(|l| l.provider == p.id).map(|l| l.login.clone())));
326
    }
327
    Ok(out)
328
}
329
330
#[derive(Deserialize)]
331
pub struct TotpForm {
332
    #[serde(rename = "_csrf")]
333
    csrf_token: String,
334
    #[serde(default)]
335
    secret: String,
336
    #[serde(default)]
337
    code: String,
338
    #[serde(default)]
339
    password: String,
340
}
341
342
/// Step one: show a fresh secret to scan.
343
pub async fn totp_begin(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> {
344
    let shell = Shell::new(&app, "/settings/security", &viewer);
345
    let me = require(&viewer, &shell)?;
346
    csrf(&viewer, &f.csrf_token, &shell)?;
347
    let secret = totp::new_secret();
348
    let uri = totp::uri(&app.config.site.name, &me.account.username, &secret);
349
    let qr = totp::qr_svg(&uri).unwrap_or_default();
350
    Ok(Page(SecurityPage {
351
        shell,
352
        me: me.account,
353
        notice: None,
354
        error: None,
355
        enrol: Some((secret, uri, qr)),
356
        recovery: vec![],
357
        connected: vec![],
358
    }))
359
}
360
361
/// Step two: the first code proves the app holds the secret.
362
pub async fn totp_enable(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> {
363
    let shell = Shell::new(&app, "/settings/security", &viewer);
364
    let me = require(&viewer, &shell)?;
365
    csrf(&viewer, &f.csrf_token, &shell)?;
366
    let now = (db::now_ms() / 1000) as u64;
367
    if f.secret.is_empty() || !totp::verify(&f.secret, &f.code, now) {
368
        let uri = totp::uri(&app.config.site.name, &me.account.username, &f.secret);
369
        let qr = totp::qr_svg(&uri).unwrap_or_default();
370
        return Ok(Page(SecurityPage {
371
            shell,
372
            me: me.account,
373
            notice: None,
374
            error: Some("That code did not match; scan again and enter the current code.".into()),
375
            enrol: Some((f.secret, uri, qr)),
376
            recovery: vec![],
377
            connected: vec![],
378
        }));
379
    }
380
    let (codes, stored) = totp::new_recovery_codes();
381
    accounts::set_totp(&app.db, me.account.id, Some(&f.secret), &stored).await.map_err(|e| Error::from_db(shell.clone(), e))?;
382
    accounts::audit(&app.db, Some(&me.account), "totp.enabled", &me.account.username, "").await.ok();
383
    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);
384
    Ok(Page(SecurityPage {
385
        shell,
386
        me: fresh,
387
        notice: Some("Two-factor authentication is on. Keep these recovery codes somewhere safe; each works once.".into()),
388
        error: None,
389
        enrol: None,
390
        recovery: codes,
391
        connected: vec![],
392
    }))
393
}
394
395
pub async fn totp_disable(State(app): State<Shared>, viewer: Viewer, Form(f): Form<TotpForm>) -> Result<Page<SecurityPage>, Error> {
396
    let shell = Shell::new(&app, "/settings/security", &viewer);
397
    let me = require(&viewer, &shell)?;
398
    csrf(&viewer, &f.csrf_token, &shell)?;
399
    if !auth::verify_password(&me.account.password_hash, &f.password) {
400
        return Ok(Page(SecurityPage {
401
            shell,
402
            me: me.account,
403
            notice: None,
404
            error: Some("Your password is wrong.".into()),
405
            enrol: None,
406
            recovery: vec![],
407
            connected: vec![],
408
        }));
409
    }
410
    accounts::set_totp(&app.db, me.account.id, None, "").await.map_err(|e| Error::from_db(shell.clone(), e))?;
411
    accounts::audit(&app.db, Some(&me.account), "totp.disabled", &me.account.username, "").await.ok();
412
    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);
413
    Ok(Page(SecurityPage {
414
        shell,
415
        me: fresh,
416
        notice: Some("Two-factor authentication is off.".into()),
417
        error: None,
418
        enrol: None,
419
        recovery: vec![],
420
        connected: vec![],
421
    }))
422
}
423
424
/// Sign out everywhere: a new session salt invalidates every cookie, then
425
/// this browser gets a fresh one.
426
pub async fn sessions_reset(State(app): State<Shared>, viewer: Viewer, Form(f): Form<super::session::CsrfForm>) -> Result<Response, Error> {
427
    let shell = Shell::new(&app, "/settings/security", &viewer);
428
    let me = require(&viewer, &shell)?;
429
    csrf(&viewer, &f.csrf, &shell)?;
430
    accounts::set_session_salt(&app.db, me.account.id, &auth::random_hex(16)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
431
    accounts::audit(&app.db, Some(&me.account), "sessions.reset", &me.account.username, "").await.ok();
432
    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);
433
    Ok(super::session::signed_in(&app, &fresh, "/settings/security"))
434
}
435
436
// ------------------------------------------------------------------- keys
437
438
#[derive(Template)]
439
#[template(path = "settings_keys.html")]
440
pub struct KeysPage {
441
    shell: Shell,
442
    me: accounts::Account,
443
    keys: Vec<accounts::LinkedIdentity>,
444
    notice: Option<String>,
445
    error: Option<String>,
446
    /// A pending challenge: id, hex bytes, identity name.
447
    pending: Option<(i64, String, String)>,
448
}
449
450
async fn keys_page(
451
    app: &Shared,
452
    shell: Shell,
453
    me: accounts::Account,
454
    notice: Option<String>,
455
    error: Option<String>,
456
    pending: Option<(i64, String, String)>,
457
) -> Result<Page<KeysPage>, Error> {
458
    let keys = accounts::identities_of(&app.db, me.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
459
    Ok(Page(KeysPage { shell, me, keys, notice, error, pending }))
460
}
461
462
pub async fn keys(State(app): State<Shared>, viewer: Viewer) -> Result<Page<KeysPage>, Error> {
463
    let shell = Shell::new(&app, "/settings/keys", &viewer);
464
    let me = require(&viewer, &shell)?;
465
    keys_page(&app, shell, me.account, None, None, None).await
466
}
467
468
/// Upload an identity object (`oxy identity export`): the hub issues a
469
/// challenge to sign with that key.
470
pub async fn keys_upload(State(app): State<Shared>, viewer: Viewer, mut multipart: Multipart) -> Result<Page<KeysPage>, Error> {
471
    let shell = Shell::new(&app, "/settings/keys", &viewer);
472
    let me = require(&viewer, &shell)?;
473
    let mut token = String::new();
474
    let mut object: Vec<u8> = Vec::new();
475
    while let Ok(Some(field)) = multipart.next_field().await {
476
        match field.name() {
477
            Some("_csrf") => token = field.text().await.unwrap_or_default(),
478
            Some("identity") => object = field.bytes().await.map(|b| b.to_vec()).unwrap_or_default(),
479
            _ => {}
480
        }
481
    }
482
    csrf(&viewer, &token, &shell)?;
483
    let identity = match Identity::decode(&object) {
484
        Ok(i) => i,
485
        Err(e) => return keys_page(&app, shell, me.account, None, Some(format!("That is not an identity file: {e}")), None).await,
486
    };
487
    let key = identity.hash().to_hex();
488
    if let Some(existing) = accounts::identity_by_key(&app.db, &key).await.map_err(|e| Error::from_db(shell.clone(), e))? {
489
        let msg = if existing.account_id == me.account.id {
490
            "That key is already linked to you."
491
        } else {
492
            "That key is linked to another account."
493
        };
494
        return keys_page(&app, shell, me.account, None, Some(msg.into()), None).await;
495
    }
496
    let bytes = auth::random_hex(32);
497
    let id = accounts::create_challenge(&app.db, me.account.id, &bytes).await.map_err(|e| Error::from_db(shell.clone(), e))?;
498
    sqlx::query("UPDATE challenges SET object = ? WHERE id = ?")
499
        .bind(&object)
500
        .bind(id)
501
        .execute(&app.db)
502
        .await
503
        .map_err(|e| Error::from_db(shell.clone(), e))?;
504
    keys_page(&app, shell, me.account, None, None, Some((id, bytes, identity.name))).await
505
}
506
507
#[derive(Deserialize)]
508
pub struct KeyVerifyForm {
509
    #[serde(rename = "_csrf")]
510
    csrf_token: String,
511
    challenge: i64,
512
    signature: String,
513
}
514
515
pub async fn keys_verify(State(app): State<Shared>, viewer: Viewer, Form(f): Form<KeyVerifyForm>) -> Result<Page<KeysPage>, Error> {
516
    let shell = Shell::new(&app, "/settings/keys", &viewer);
517
    let me = require(&viewer, &shell)?;
518
    csrf(&viewer, &f.csrf_token, &shell)?;
519
    let object: Option<Vec<u8>> = sqlx::query_scalar("SELECT object FROM challenges WHERE id = ? AND account_id = ?")
520
        .bind(f.challenge)
521
        .bind(me.account.id)
522
        .fetch_optional(&app.db)
523
        .await
524
        .map_err(|e| Error::from_db(shell.clone(), e))?;
525
    let bytes = accounts::take_challenge(&app.db, me.account.id, f.challenge).await.map_err(|e| Error::from_db(shell.clone(), e))?;
526
    let (Some(object), Some(bytes)) = (object, bytes) else {
527
        return keys_page(&app, shell, me.account, None, Some("That challenge has expired; upload the identity again.".into()), None).await;
528
    };
529
    let Ok(identity) = Identity::decode(&object) else {
530
        return keys_page(&app, shell, me.account, None, Some("The stored identity is unreadable.".into()), None).await;
531
    };
532
    let sig_bytes = hex::decode(f.signature.trim()).unwrap_or_default();
533
    let sigs = Signature::decode_list(&sig_bytes).unwrap_or_default();
534
    let challenge = hex::decode(&bytes).unwrap_or_default();
535
    let ok = sigs.first().is_some_and(|sig| oxy_core::identity::verify_challenge(&identity, sig, &challenge).is_ok());
536
    if !ok {
537
        return keys_page(
538
            &app,
539
            shell,
540
            me.account,
541
            None,
542
            Some("The signature does not verify against that identity and challenge.".into()),
543
            None,
544
        )
545
        .await;
546
    }
547
    let key = identity.hash().to_hex();
548
    accounts::link_identity(&app.db, me.account.id, &key, &identity.name, &identity.email, &object)
549
        .await
550
        .map_err(|e| Error::from_db(shell.clone(), e))?;
551
    accounts::audit(&app.db, Some(&me.account), "identity.linked", &key, &identity.name).await.ok();
552
    keys_page(&app, shell, me.account, Some("Key linked. Changes signed with it are now yours on every page.".into()), None, None).await
553
}
554
555
#[derive(Deserialize)]
556
pub struct KeyForm {
557
    #[serde(rename = "_csrf")]
558
    csrf_token: String,
559
    key: String,
560
}
561
562
pub async fn keys_unlink(State(app): State<Shared>, viewer: Viewer, Form(f): Form<KeyForm>) -> Result<Page<KeysPage>, Error> {
563
    let shell = Shell::new(&app, "/settings/keys", &viewer);
564
    let me = require(&viewer, &shell)?;
565
    csrf(&viewer, &f.csrf_token, &shell)?;
566
    accounts::unlink_identity(&app.db, me.account.id, &f.key).await.map_err(|e| Error::from_db(shell.clone(), e))?;
567
    accounts::audit(&app.db, Some(&me.account), "identity.unlinked", &f.key, "").await.ok();
568
    keys_page(&app, shell, me.account, Some("Key unlinked.".into()), None, None).await
569
}
570
571
// ----------------------------------------------------------------- tokens
572
573
#[derive(Template)]
574
#[template(path = "settings_tokens.html")]
575
pub struct TokensPage {
576
    shell: Shell,
577
    scopes: &'static [(&'static str, &'static str)],
578
    me: accounts::Account,
579
    tokens: Vec<accounts::Token>,
580
    /// A freshly created token, shown once.
581
    fresh: Option<String>,
582
    notice: Option<String>,
583
    error: Option<String>,
584
}
585
586
async fn tokens_page(
587
    app: &Shared,
588
    shell: Shell,
589
    me: accounts::Account,
590
    fresh: Option<String>,
591
    notice: Option<String>,
592
    error: Option<String>,
593
) -> Result<Page<TokensPage>, Error> {
594
    let tokens = accounts::tokens_of(&app.db, me.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
595
    Ok(Page(TokensPage { shell, scopes: SCOPES, me, tokens, fresh, notice, error }))
596
}
597
598
pub async fn tokens(State(app): State<Shared>, viewer: Viewer) -> Result<Page<TokensPage>, Error> {
599
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
600
    let me = require(&viewer, &shell)?;
601
    tokens_page(&app, shell, me.account, None, None, None).await
602
}
603
604
#[derive(Deserialize)]
605
pub struct TokenForm {
606
    #[serde(rename = "_csrf")]
607
    csrf_token: String,
608
    name: String,
609
    #[serde(default)]
610
    scopes: Vec<String>,
611
    #[serde(default)]
612
    repos: String,
613
    #[serde(default)]
614
    expires_days: String,
615
    /// An agent uses it: tell me what it does (oxygenhub#183).
616
    #[serde(default)]
617
    agent: String,
618
}
619
620
/// Every scope the hub checks, with what it grants. The tokens page lists
621
/// exactly these, so a scope cannot exist without a checkbox.
622
pub const SCOPES: &[(&str, &str)] = &[
623
    ("repo:read", "read repositories you can see: clone, fetch, pull, and the read API"),
624
    ("repo:write", "push to repositories you can write to; also covers proposals, issues and checks"),
625
    ("repo:admin", "create repositories and change settings through the API"),
626
    ("proposals:write", "open, comment on and review proposals, without push access"),
627
    ("issues:write", "open, comment on and close issues, without push access"),
628
    ("checks:write", "report checks on states, for CI systems, without push access"),
629
    ("hooks:admin", "manage webhooks through the API"),
630
    ("user:read", "read your own profile through the API"),
631
];
632
633
pub async fn tokens_create(
634
    State(app): State<Shared>,
635
    viewer: Viewer,
636
    axum_extra::extract::Form(f): axum_extra::extract::Form<TokenForm>,
637
) -> Result<Page<TokensPage>, Error> {
638
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
639
    let me = require(&viewer, &shell)?;
640
    csrf(&viewer, &f.csrf_token, &shell)?;
641
    let name = f.name.trim();
642
    if name.is_empty() {
643
        return tokens_page(&app, shell, me.account, None, None, Some("Give the token a name.".into())).await;
644
    }
645
    let scopes: Vec<&str> = f.scopes.iter().map(String::as_str).filter(|s| SCOPES.iter().any(|(k, _)| k == s)).collect();
646
    if scopes.is_empty() {
647
        return tokens_page(&app, shell, me.account, None, None, Some("Pick at least one scope.".into())).await;
648
    }
649
    let expires_ms = f.expires_days.trim().parse::<i64>().ok().filter(|d| *d > 0).map(|d| db::now_ms() + d * 86_400_000);
650
    let repos = f.repos.split(',').map(str::trim).filter(|r| !r.is_empty()).collect::<Vec<_>>().join(",");
651
    let (secret, hash) = auth::new_token();
652
    accounts::create_token(&app.db, me.account.id, name, &hash, &scopes.join(","), &repos, expires_ms)
653
        .await
654
        .map_err(|e| Error::from_db(shell.clone(), e))?;
655
    if !f.agent.is_empty() {
656
        if let Ok(Some(t)) = accounts::token_by_hash(&app.db, &hash).await {
657
            accounts::set_token_agent(&app.db, me.account.id, t.id, true).await.map_err(|e| Error::from_db(shell.clone(), e))?;
658
        }
659
    }
660
    accounts::audit(&app.db, Some(&me.account), "token.created", name, &scopes.join(",")).await.ok();
661
    tokens_page(&app, shell, me.account, Some(secret), Some("Copy the token now; it is not shown again.".into()), None).await
662
}
663
664
/// Mark a token as an agent's, or not (oxygenhub#183): what is done with
665
/// an agent's token is told to its owner, as anyone else's doing is.
666
pub async fn tokens_agent(
667
    State(app): State<Shared>,
668
    viewer: Viewer,
669
    Path(id): Path<i64>,
670
    Form(f): Form<super::session::CsrfForm>,
671
) -> Result<Page<TokensPage>, Error> {
672
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
673
    let me = require(&viewer, &shell)?;
674
    csrf(&viewer, &f.csrf, &shell)?;
675
    let tokens = accounts::tokens_of(&app.db, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
676
    let Some(t) = tokens.iter().find(|t| t.id == id) else {
677
        return tokens_page(&app, shell, me.account, None, None, Some("No such token.".into())).await;
678
    };
679
    accounts::set_token_agent(&app.db, me.account.id, id, !t.agent).await.map_err(|e| Error::from_db(shell.clone(), e))?;
680
    accounts::audit(&app.db, Some(&me.account), "token.agent", &t.name, if t.agent { "off" } else { "on" }).await.ok();
681
    let notice = if t.agent {
682
        format!("{} is no longer marked as an agent's.", t.name)
683
    } else {
684
        format!("{} is an agent's: you will hear what it does.", t.name)
685
    };
686
    tokens_page(&app, shell, me.account, None, Some(notice), None).await
687
}
688
689
pub async fn tokens_delete(
690
    State(app): State<Shared>,
691
    viewer: Viewer,
692
    Path(id): Path<i64>,
693
    Form(f): Form<super::session::CsrfForm>,
694
) -> Result<Page<TokensPage>, Error> {
695
    let shell = Shell::new(&app, "/settings/tokens", &viewer);
696
    let me = require(&viewer, &shell)?;
697
    csrf(&viewer, &f.csrf, &shell)?;
698
    accounts::delete_token(&app.db, me.account.id, id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
699
    accounts::audit(&app.db, Some(&me.account), "token.deleted", &id.to_string(), "").await.ok();
700
    tokens_page(&app, shell, me.account, None, Some("Token deleted.".into()), None).await
701
}