From 255ea88bcbf6c87b0adc8905bfd228d1388e43ba Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 3 Nov 2026 23:00:42 +0100 Subject: [PATCH 01/11] feat(ui): overhaul every page on one shell, with a sidebar, themes, an overview and a red admin dashboard The account pages and the admin dashboard share a sidebar shell with a collapsible rail, a phone drawer, a theme toggle kept in a cookie, a crumb top bar and a status bar; the sign-in pages share its style in a narrow column. The account gains an overview, the dashboard an overview with alerts, events in words, numbered pages and confirmations in dialogs. Co-Authored-By: Claude Fable 5.1 --- README.md | 7 +- apps/auth-service/src/admin/mod.rs | 3 + apps/auth-service/src/admin/overview.rs | 195 ++ apps/auth-service/src/admin/service.rs | 48 +- apps/auth-service/src/admin/tests.rs | 2 +- apps/auth-service/src/assets.rs | 24 +- apps/auth-service/src/cli/audit.rs | 15 +- apps/auth-service/src/cli/console.rs | 16 +- apps/auth-service/src/cli/user.rs | 14 +- apps/auth-service/src/history/mod.rs | 75 + apps/auth-service/src/routes.rs | 15 +- apps/auth-service/src/security/mod.rs | 37 + apps/auth-service/src/web/account.rs | 63 +- .../src/web/admin/administrators.rs | 23 +- apps/auth-service/src/web/admin/audit.rs | 2 +- .../auth-service/src/web/admin/invitations.rs | 26 +- apps/auth-service/src/web/admin/lists.rs | 56 +- apps/auth-service/src/web/admin/mod.rs | 195 +- apps/auth-service/src/web/admin/origins.rs | 26 +- apps/auth-service/src/web/admin/overview.rs | 85 + apps/auth-service/src/web/admin/settings.rs | 17 +- apps/auth-service/src/web/admin/tests.rs | 9 +- apps/auth-service/src/web/admin/users.rs | 169 +- apps/auth-service/src/web/auth/handoff.rs | 10 +- apps/auth-service/src/web/auth/login/mod.rs | 17 +- apps/auth-service/src/web/auth/login/tests.rs | 15 +- apps/auth-service/src/web/auth/oidc.rs | 4 +- .../auth-service/src/web/auth/recovery/mod.rs | 11 +- .../src/web/auth/recovery/tests.rs | 19 +- apps/auth-service/src/web/developers/mod.rs | 1 + apps/auth-service/src/web/developers/tests.rs | 6 +- apps/auth-service/src/web/mod.rs | 108 +- apps/auth-service/src/web/settings/data.rs | 7 +- apps/auth-service/src/web/settings/emails.rs | 13 +- apps/auth-service/src/web/settings/history.rs | 25 +- apps/auth-service/src/web/settings/mod.rs | 113 +- .../auth-service/src/web/settings/overview.rs | 115 + .../auth-service/src/web/settings/sessions.rs | 13 +- apps/auth-service/src/web/settings/sign_in.rs | 33 +- apps/auth-service/src/web/settings/tests.rs | 42 +- apps/auth-service/src/web/tests.rs | 10 +- apps/web/src/pages.rs | 79 +- apps/web/src/site.rs | 72 +- crates/common/src/admin.rs | 87 +- ...66b0ae45b53c82b45ba2631a80c361136d7ac.json | 20 + ...892c66240420e28eabb7332e8c699770b8a5b.json | 23 + ...85332469fb3ac689124792c3d63e6eedc0498.json | 24 + ...8114dbb517fd075bba227d471d8a70a1186fc.json | 20 + ...91bc1c7c0a2bc1604ddd12cb92ccdc39d36c7.json | 46 + ...397eb01375e2b162ee0f2758174a59130beb.json} | 7 +- ...36db4286b11f8d9e6c5cd997e8369c6054e7.json} | 6 +- ...947f5aae4bbc1992682b86ace7dd8afb04135.json | 23 + .../database/migrations/0026_event_counts.sql | 4 + .../database/src/repositories/events/mod.rs | 63 +- crates/database/src/repositories/sessions.rs | 18 + crates/database/src/repositories/users/mod.rs | 104 +- crates/ui/assets/fonts/OFL-DM-Mono.txt | 93 + crates/ui/assets/fonts/OFL-DM-Sans.txt | 93 + .../assets/fonts/dm-mono-v16-latin-400.woff2 | Bin 0 -> 14820 bytes .../assets/fonts/dm-mono-v16-latin-500.woff2 | Bin 0 -> 14988 bytes .../ui/assets/fonts/dm-sans-v17-latin.woff2 | Bin 0 -> 36932 bytes crates/ui/assets/style.css | 1945 ++++++++++++++--- crates/ui/src/admin/audit.rs | 117 +- crates/ui/src/admin/events.rs | 486 ++++ crates/ui/src/admin/lists.rs | 321 +-- crates/ui/src/admin/mod.rs | 538 +++-- crates/ui/src/admin/overview.rs | 224 ++ crates/ui/src/admin/recoveries.rs | 2 +- crates/ui/src/admin/users.rs | 320 +-- crates/ui/src/asset.rs | 70 +- crates/ui/src/clients.rs | 60 +- crates/ui/src/developers.rs | 266 ++- crates/ui/src/form.rs | 17 +- crates/ui/src/icons.rs | 118 + crates/ui/src/layout.rs | 889 ++++++-- crates/ui/src/lib.rs | 44 +- crates/ui/src/login.rs | 152 +- crates/ui/src/oidc.rs | 90 +- crates/ui/src/recovery.rs | 156 +- crates/ui/src/settings/connected.rs | 110 +- crates/ui/src/settings/data.rs | 68 +- crates/ui/src/settings/emails.rs | 214 +- crates/ui/src/settings/mod.rs | 33 +- crates/ui/src/settings/overview.rs | 171 ++ crates/ui/src/settings/sessions.rs | 82 +- crates/ui/src/settings/sign_in.rs | 327 +-- crates/ui/src/settings/timeline.rs | 136 +- docs/architecture/rust-conventions.md | 33 +- docs/architecture/surfaces.md | 13 +- tests/browser/admin.spec.ts | 6 +- tests/browser/deletion.spec.ts | 1 + tests/browser/developers.spec.ts | 4 +- tests/browser/layout.spec.ts | 76 + tests/browser/recovery.spec.ts | 3 +- tests/browser/settings.spec.ts | 10 +- tests/browser/sign-in.spec.ts | 1 + 96 files changed, 7085 insertions(+), 2484 deletions(-) create mode 100644 apps/auth-service/src/admin/overview.rs create mode 100644 apps/auth-service/src/web/admin/overview.rs create mode 100644 apps/auth-service/src/web/settings/overview.rs create mode 100644 crates/database/.sqlx/query-1cb84dab947b206a5fcdd97a0aa66b0ae45b53c82b45ba2631a80c361136d7ac.json create mode 100644 crates/database/.sqlx/query-62e2741405b6723c771f2dc5330892c66240420e28eabb7332e8c699770b8a5b.json create mode 100644 crates/database/.sqlx/query-6d190647cf9e876fe4cd8783bd385332469fb3ac689124792c3d63e6eedc0498.json create mode 100644 crates/database/.sqlx/query-780556e46140dd1c1d9385ff28e8114dbb517fd075bba227d471d8a70a1186fc.json create mode 100644 crates/database/.sqlx/query-ad1ee3783685d255e0948da4a8191bc1c7c0a2bc1604ddd12cb92ccdc39d36c7.json rename crates/database/.sqlx/{query-541618e02510feb91705bd2a2b159a72deb3c100b617b192255cf984b4fee39b.json => query-aed5f8e218471c67765fcb0d02da397eb01375e2b162ee0f2758174a59130beb.json} (95%) rename crates/database/.sqlx/{query-2440eb772a9a0ea8b575fe1f401abdd37353e649c73408fbc25aaf95a743d682.json => query-bb3adf0970a2c3ddf13850f6d9b836db4286b11f8d9e6c5cd997e8369c6054e7.json} (87%) create mode 100644 crates/database/.sqlx/query-d10405842b08a5d2a6143d7e664947f5aae4bbc1992682b86ace7dd8afb04135.json create mode 100644 crates/database/migrations/0026_event_counts.sql create mode 100644 crates/ui/assets/fonts/OFL-DM-Mono.txt create mode 100644 crates/ui/assets/fonts/OFL-DM-Sans.txt create mode 100644 crates/ui/assets/fonts/dm-mono-v16-latin-400.woff2 create mode 100644 crates/ui/assets/fonts/dm-mono-v16-latin-500.woff2 create mode 100644 crates/ui/assets/fonts/dm-sans-v17-latin.woff2 create mode 100644 crates/ui/src/admin/events.rs create mode 100644 crates/ui/src/admin/overview.rs create mode 100644 crates/ui/src/icons.rs create mode 100644 crates/ui/src/settings/overview.rs create mode 100644 tests/browser/layout.spec.ts diff --git a/README.md b/README.md index 4921b9223..d08b903ce 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,10 @@ just build ``` The executables are `target/release/auth-service` and `target/release/piquel-web`. -Auth embeds the stylesheet (`crates/ui/assets/style.css`) and the passkey script -(`apps/auth-service/assets/passkey.js`) as they are, and piquel-web the stylesheet -and the policies (`apps/web/assets/policies/`); rebuild Rust after changing them. +Both embed the stylesheet (`crates/ui/assets/style.css`) and its typefaces +(`crates/ui/assets/fonts`, under the SIL Open Font License); auth also embeds the +passkey script (`apps/auth-service/assets/passkey.js`), and piquel-web the +policies (`apps/web/assets/policies/`). Rebuild Rust after changing them. ## Development diff --git a/apps/auth-service/src/admin/mod.rs b/apps/auth-service/src/admin/mod.rs index 3f4216ef6..6ff6a69b5 100644 --- a/apps/auth-service/src/admin/mod.rs +++ b/apps/auth-service/src/admin/mod.rs @@ -11,6 +11,8 @@ mod error; mod operation; /// Who runs an administrative operation. mod operator; +/// The dashboard's overview. +mod overview; /// The service shared by the dashboard and the CLI. mod service; /// Signing administrators in to the dashboard. @@ -22,6 +24,7 @@ pub use error::AdminError; pub(crate) use operation::AdminOperation; use operator::AdminSession; pub use operator::Operator; +pub(crate) use overview::Problem; pub use service::AdminService; pub(crate) use sign_in::{DashboardSignIn, SignedInAdmin}; pub use types::{GracePeriod, HandleProblem, InvalidLifetime, InviteExpiry, Reason, UserRef}; diff --git a/apps/auth-service/src/admin/overview.rs b/apps/auth-service/src/admin/overview.rs new file mode 100644 index 000000000..838989949 --- /dev/null +++ b/apps/auth-service/src/admin/overview.rs @@ -0,0 +1,195 @@ +//! The dashboard's overview: what the service is doing now, against what it +//! usually does, and what needs an administrator's attention. + +use super::{AdminError, AdminService, Operator}; +use chrono::{DateTime, Duration, Utc}; +use piquel_common::admin::{Event, EventSearch, User}; +use piquel_repository::{DeliveryBacklog, Email}; + +/// How many of the newest events the overview shows. +const EVENTS_SHOWN: usize = 8; +/// How many of the newest accounts the overview shows. +const NEWEST_SHOWN: u16 = 6; +/// The hours of the week a rate is averaged over. +const HOURS_PER_WEEK: u64 = 7 * 24; +/// How long a message may wait before its backlog needs attention. +const DELIVERY_PATIENCE: Duration = Duration::minutes(15); + +/// The kinds of event the overview counts, by the serde tags +/// [`DomainEvent`](piquel_common::events::DomainEvent) stores them under. +struct Kinds; + +impl Kinds { + /// A rejected passkey or provider authentication. + const FAILED: &'static str = "sign_in_failed"; + /// A browser signed in. + const SIGNED_IN: &'static str = "signed_in"; + /// A client exchanged a code for tokens. + const GRANT: &'static str = "grant_issued"; +} + +/// How often something happened in the last hour, against an hour's usual +/// count over the last week. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Rate { + /// In the last hour. + pub last_hour: u64, + /// Per hour, averaged over the week before, rounded up. + pub usual: u64, +} + +impl Rate { + /// The rate of `last_hour` against `week`, a week's total. + const fn new(last_hour: u64, week: u64) -> Self { + Self { + last_hour, + usual: week.div_ceil(HOURS_PER_WEEK), + } + } + + /// Whether the last hour is a spike: at least ten, and more than three times + /// usual, so a quiet service's first failures raise nothing. + const fn spikes(self) -> bool { + self.last_hour >= 10 && self.last_hour > self.usual.saturating_mul(3) + } +} + +/// What needs an administrator's attention. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Problem { + /// Far more sign-ins failed in the last hour than usually do. + FailedSignIns(Rate), + /// Messages wait to be delivered, the oldest for longer than they should. + DeliveriesWaiting { + /// How many wait. + pending: u64, + /// Since when the oldest waits. + oldest: DateTime, + }, +} + +/// What the overview shows. +#[derive(Clone, Debug)] +pub struct Overview { + /// Rejected passkey and provider authentications. + pub failed_sign_ins: Rate, + /// Browsers signing in. + pub sign_ins: Rate, + /// Clients exchanging codes for tokens. + pub app_sign_ins: Rate, + /// Sessions signed in now. + pub active_sessions: u64, + /// Every account. + pub accounts: u64, + /// The accounts administering Piquel. + pub administrators: u64, + /// The newest events. + pub events: Vec, + /// The newest accounts. + pub newest: Vec, + /// The emails waiting to be sent. + pub email_backlog: DeliveryBacklog, + /// When it was read. + pub now: DateTime, +} + +impl Overview { + /// What needs attention, most pressing first. + #[must_use] + pub fn problems(&self) -> Vec { + let mut problems = Vec::new(); + if self.failed_sign_ins.spikes() { + problems.push(Problem::FailedSignIns(self.failed_sign_ins)); + } + if let Some(oldest) = self.email_backlog.oldest + && self.now - oldest > DELIVERY_PATIENCE + { + problems.push(Problem::DeliveriesWaiting { + pending: self.email_backlog.pending, + oldest, + }); + } + problems + } +} + +impl AdminService { + /// Reads the overview: the last hour's rates against the week's, what is + /// signed in now, the newest events and accounts, and the email backlog. + /// + /// # Errors + /// Fails when the operator may not read, or a query fails. + pub(crate) async fn overview(&self, operator: &Operator) -> Result { + operator.authorize_read(&self.database).await?; + let now = Utc::now(); + let (hour, week) = (now - Duration::hours(1), now - Duration::days(7)); + let mut events = self.database.events(); + let mut rate = async |kind: &str| -> Result { + let kinds = [kind.to_owned()]; + let last_hour = events.count_since(None, &kinds, hour).await?; + let weekly = events.count_since(None, &kinds, week).await?; + Ok(Rate::new(last_hour, weekly)) + }; + let failed_sign_ins = rate(Kinds::FAILED).await?; + let sign_ins = rate(Kinds::SIGNED_IN).await?; + let app_sign_ins = rate(Kinds::GRANT).await?; + let mut newest_events = self.events(operator, EventSearch::default()).await?.events; + newest_events.truncate(EVENTS_SHOWN); + Ok(Overview { + failed_sign_ins, + sign_ins, + app_sign_ins, + active_sessions: self.database.sessions().count_active().await?, + accounts: self.database.users().count().await?, + administrators: u64::try_from(self.database.administrators().list().await?.len()) + .unwrap_or(u64::MAX), + events: newest_events, + newest: self.database.users().newest(NEWEST_SHOWN).await?, + email_backlog: self.database.deliveries().backlog::().await?, + now, + }) + } +} + +#[cfg(test)] +mod tests { + //! The overview's arithmetic. + use super::*; + use piquel_common::{ + AuthenticationMethod, SessionId, + events::{DomainEvent, SignInFailure}, + }; + + /// The kinds counted are the tags the events are stored under. + #[test] + fn the_counted_kinds_are_the_stored_tags() { + let failed = DomainEvent::SignInFailed { + method: AuthenticationMethod::Passkey, + reason: SignInFailure::InvalidCredential, + }; + assert_eq!(failed.kind(), Kinds::FAILED); + let signed_in = DomainEvent::SignedIn { + session_id: SessionId::new(), + method: AuthenticationMethod::Passkey, + inline: None, + }; + assert_eq!(signed_in.kind(), Kinds::SIGNED_IN); + let grant = DomainEvent::GrantIssued { + client_id: "notes".parse().expect("client ID"), + family_id: None, + scopes: Vec::new(), + }; + assert_eq!(grant.kind(), Kinds::GRANT); + } + + /// A spike needs both a floor and a multiple of usual: a quiet week's first + /// failures are no alarm, and a busy service's usual failures are none either. + #[test] + fn a_spike_is_at_least_ten_and_over_three_times_usual() { + assert!(!Rate::new(9, 0).spikes()); + assert!(Rate::new(10, 0).spikes()); + assert!(!Rate::new(30, HOURS_PER_WEEK * 10).spikes()); + assert!(Rate::new(31, HOURS_PER_WEEK * 10).spikes()); + assert_eq!(Rate::new(0, 1).usual, 1, "a week's one failure rounds up"); + } +} diff --git a/apps/auth-service/src/admin/service.rs b/apps/auth-service/src/admin/service.rs index 36f87f1a5..f9ac96f3a 100644 --- a/apps/auth-service/src/admin/service.rs +++ b/apps/auth-service/src/admin/service.rs @@ -17,7 +17,7 @@ use piquel_common::{ AccountStatus, ClientId, DeliveryId, Handle, Personal, RecoveryId, SessionId, TokenId, UserId, admin::{ Administrator, ApprovedOrigin, Client, CreatedInvitation, Email, Event, EventPage, - EventSearch, Invitation, ScheduledDeletion, UserDetail, UserPage, + EventSearch, Invitation, Paging, ScheduledDeletion, UserDetail, UserPage, }, clients::{ClientField, ClientOwner, ClientRegistration, RelatedOrigin}, config::Origin, @@ -35,7 +35,7 @@ use url::Url; /// Accounts per search page. const USER_PAGE_SIZE: u16 = 50; /// Events per page. -const EVENT_PAGE_SIZE: u16 = 100; +const EVENT_PAGE_SIZE: u16 = 50; /// Owns each administrative operation. Dashboard pages and CLI commands are thin /// adapters that say which [`Operator`] acts. Every mutation, and viewing an @@ -56,7 +56,7 @@ const EVENT_PAGE_SIZE: u16 = 100; #[derive(Clone)] pub struct AdminService { /// Accounts, sessions, invitations, clients, events, deliveries and administrators. - database: Database, + pub(super) database: Database, /// Whether email is enabled, so a recovery link can be mailed. mails: bool, } @@ -125,23 +125,21 @@ impl AdminService { found.ok_or(AdminError::UserNotFound) } - /// Lists accounts matching `query`, by ID, after the `cursor` of a previous page. + /// Lists `page` of the accounts matching `query`, by handle: the first page + /// when `None`. pub(crate) async fn search_users( &self, operator: &Operator, query: &str, - cursor: Option, + page: Option, ) -> Result { operator.authorize_read(&self.database).await?; - let users = self - .database - .users() - .search(query.trim(), cursor, USER_PAGE_SIZE) - .await?; - let next = (users.len() == usize::from(USER_PAGE_SIZE)) - .then(|| users.last().map(|user| user.id)) - .flatten(); - Ok(UserPage { users, next }) + let query = query.trim(); + let mut users = self.database.users(); + let total = users.count_matching(query).await?; + let paging = Paging::new(page, total, u32::from(USER_PAGE_SIZE)); + let users = users.search(query, paging.offset(), USER_PAGE_SIZE).await?; + Ok(UserPage { users, paging }) } /// Returns an account's profile, emails, status, passkey labels, identities, @@ -802,27 +800,23 @@ impl AdminService { .await } - /// Returns a page of the events matching `search`, newest first. + /// Returns the page of the events matching `search`, newest first. pub(crate) async fn events( &self, operator: &Operator, search: EventSearch, ) -> Result { operator.authorize_read(&self.database).await?; - let filter = EventFilter { + let mut filter = EventFilter { subject: search.user, kind: search.kind, - before: search.before, - id: None, + ..EventFilter::default() }; - let stored = self - .database - .events() - .list(&filter, u32::from(EVENT_PAGE_SIZE)) - .await?; - let next = (stored.len() == usize::from(EVENT_PAGE_SIZE)) - .then(|| stored.last().map(|event| event.id)) - .flatten(); + let mut events = self.database.events(); + let total = events.count(&filter).await?; + let paging = Paging::new(search.page, total, u32::from(EVENT_PAGE_SIZE)); + filter.offset = u32::try_from(paging.offset()).unwrap_or(u32::MAX); + let stored = events.list(&filter, u32::from(EVENT_PAGE_SIZE)).await?; let events = stored .into_iter() .map(|stored| { @@ -836,7 +830,7 @@ impl AdminService { }) }) .collect::>()?; - Ok(EventPage { events, next }) + Ok(EventPage { events, paging }) } /// Lists the accounts whose current handle is reserved, by handle: ones an diff --git a/apps/auth-service/src/admin/tests.rs b/apps/auth-service/src/admin/tests.rs index 9a56059bf..c193dbc8d 100644 --- a/apps/auth-service/src/admin/tests.rs +++ b/apps/auth-service/src/admin/tests.rs @@ -253,7 +253,7 @@ async fn disabling_ends_sessions_and_is_recorded() { EventSearch { user: Some(user.user_id), kind: Some("account_disabled".into()), - before: None, + page: None, }, ) .await diff --git a/apps/auth-service/src/assets.rs b/apps/auth-service/src/assets.rs index 7d629d8c3..c0e09df6d 100644 --- a/apps/auth-service/src/assets.rs +++ b/apps/auth-service/src/assets.rs @@ -1,5 +1,6 @@ -//! The stylesheet and passkey script of auth's pages, embedded under paths naming -//! their content, so browsers and shared caches keep them forever. +//! The stylesheet, typefaces and passkey script of auth's pages, embedded under +//! paths that never serve other content, so browsers and shared caches keep them +//! forever. use crate::security::{ApiError, CacheClass, Cached}; use axum::{ @@ -32,12 +33,21 @@ impl EmbeddedAssets { /// The passkey script, the one script of auth's pages. pub(crate) const SCRIPT: Asset = Asset::script("passkey", include_bytes!("../assets/passkey.js")); + /// The files the admin dashboard serves too: the stylesheet and the + /// typefaces it links. + pub(crate) const SHARED: [Asset; 4] = [ + Self::STYLESHEET, + piquel_ui::FONTS[0], + piquel_ui::FONTS[1], + piquel_ui::FONTS[2], + ]; /// Serves the embedded file at exactly `path`. A file's path changes with its - /// content, so nothing needs revalidating. + /// content, or its version, so nothing needs revalidating. pub(crate) fn serve(path: &str) -> Result { - let asset = [Self::STYLESHEET, Self::SCRIPT] + let asset = Self::SHARED .into_iter() + .chain([Self::SCRIPT]) .find(|asset| asset.path() == path) .ok_or(AssetError::NotFound)?; let headers = [(header::CONTENT_TYPE, asset.content_type())]; @@ -50,13 +60,15 @@ mod tests { //! Focused coverage of embedded file serving. use super::*; - /// The pages' stylesheet and passkey script are served at the paths naming their - /// content, as their own type, so they are cached forever. + /// The pages' stylesheet, typefaces and passkey script are served at the paths + /// naming their content or version, as their own type, so they are cached + /// forever. #[test] fn the_pages_files_are_immutable() { for (asset, content_type) in [ (EmbeddedAssets::STYLESHEET, "text/css; charset=utf-8"), (EmbeddedAssets::SCRIPT, "text/javascript; charset=utf-8"), + (piquel_ui::FONTS[0], "font/woff2"), ] { let response = EmbeddedAssets::serve(&asset.path()).expect("found"); assert_eq!(response.headers()[header::CONTENT_TYPE], content_type); diff --git a/apps/auth-service/src/cli/audit.rs b/apps/auth-service/src/cli/audit.rs index 3a570b4d4..32e9ec260 100644 --- a/apps/auth-service/src/cli/audit.rs +++ b/apps/auth-service/src/cli/audit.rs @@ -8,7 +8,6 @@ use crate::{ }; use clap::{Args, Subcommand}; use piquel_common::{ - EventId, admin::{EventPage, EventSearch}, events::Actor, }; @@ -17,7 +16,7 @@ use std::path::PathBuf; /// Paging through, verifying and pruning the audit history. #[derive(Subcommand)] pub(super) enum AuditCommand { - /// Page through recorded events, newest first, 100 at a time. + /// Page through recorded events, newest first. List(ListEvents), /// Recompute the chain and check every checkpoint against it. Exits non-zero, /// naming the first position that does not match, when the chain is broken. @@ -131,7 +130,7 @@ impl AuditCommand { } } -/// Page through recorded events, newest first, 100 at a time. +/// Page through recorded events, newest first. #[derive(Args)] pub(super) struct ListEvents { /// Only events concerning this account: its handle, ID or verified email. @@ -140,9 +139,9 @@ pub(super) struct ListEvents { /// Only events of this kind, e.g. `session_revoked`. #[arg(long)] kind: Option, - /// Continue with events older than this one, the last one listed. + /// The page to list, counting from 1 at the newest events. #[arg(long)] - before: Option, + page: Option, /// Output format. #[command(flatten)] output: Output, @@ -158,7 +157,7 @@ impl ListEvents { let search = EventSearch { user, kind: self.kind, - before: self.before, + page: self.page, }; self.output.print( &console.service.events(&console.operator, search).await?, @@ -181,9 +180,7 @@ impl ListEvents { event.event["kind"].as_str().unwrap_or("-"), ); } - if let Some(next) = page.next { - eprintln!("More may follow: --before {next}"); - } + Output::paging(page.paging, "events"); } /// Names who acted in a few words, or as the stored JSON when this release diff --git a/apps/auth-service/src/cli/console.rs b/apps/auth-service/src/cli/console.rs index c42882462..4baf47540 100644 --- a/apps/auth-service/src/cli/console.rs +++ b/apps/auth-service/src/cli/console.rs @@ -5,7 +5,7 @@ use super::CliError; use crate::{AdminService, AuthConfig, Operator, UserRef, account::AccountService}; use clap::{Args, ValueEnum}; -use piquel_common::UserId; +use piquel_common::{UserId, admin::Paging}; use piquel_repository::Database; use serde::Serialize; use std::io::{BufRead, IsTerminal}; @@ -74,6 +74,20 @@ impl Output { } Ok(()) } + + /// Says where a page of `what` stands, and how to go on, after a table. + pub(super) fn paging(paging: Paging, what: &str) { + eprintln!( + "Page {} of {}: {} {what} in all.{}", + paging.page, + paging.pages, + paging.total, + paging + .next() + .map(|next| format!(" Next: --page {next}")) + .unwrap_or_default() + ); + } } /// The `--yes` option of commands that cut off a whole account, administrator or diff --git a/apps/auth-service/src/cli/user.rs b/apps/auth-service/src/cli/user.rs index 6e922c728..1b98b0fe3 100644 --- a/apps/auth-service/src/cli/user.rs +++ b/apps/auth-service/src/cli/user.rs @@ -6,7 +6,7 @@ use crate::{AdminError, AuthConfig, Reason, UserRef, recovery::Revoke}; use chrono::{DateTime, Utc}; use clap::Subcommand; use piquel_common::{ - PasskeyId, UserId, + PasskeyId, admin::{UserDetail, UserPage}, }; use piquel_repository::{RecentRecovery, RecoveryState}; @@ -20,9 +20,9 @@ pub(super) enum UserCommand { /// What to look for. Lists every account when empty. #[arg(default_value = "")] query: String, - /// Continue after this account ID, the last one listed. + /// The page to list, counting from 1. #[arg(long)] - cursor: Option, + page: Option, /// Output format. #[command(flatten)] output: Output, @@ -141,10 +141,10 @@ impl UserCommand { match self { Self::Search { query, - cursor, + page, output, } => output.print( - &service.search_users(operator, &query, cursor).await?, + &service.search_users(operator, &query, page).await?, Self::print_page, )?, Self::Show { user, output } => { @@ -327,9 +327,7 @@ impl UserCommand { user.display_name ); } - if let Some(next) = page.next { - eprintln!("More may follow: --cursor {next}"); - } + Output::paging(page.paging, "accounts"); } /// Prints an account's facts, then one section per kind of record. diff --git a/apps/auth-service/src/history/mod.rs b/apps/auth-service/src/history/mod.rs index a19ca61a1..058d16586 100644 --- a/apps/auth-service/src/history/mod.rs +++ b/apps/auth-service/src/history/mod.rs @@ -178,6 +178,81 @@ impl HistoryItem { } } +/// What happened to the account over a period, as its overview counts it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Activity { + /// How many times apps exchanged a code for tokens: sign-ins through apps. + pub(crate) app_sign_ins: u64, + /// How many security events were recorded: sign-ins, failures and changes. + pub(crate) security_events: u64, +} + +impl Activity { + /// The kind of event counted as a sign-in through an app, by the tag + /// [`DomainEvent`] stores it under. + const APP_SIGN_INS: [&'static str; 1] = ["grant_issued"]; + /// The kinds counted as security events: sign-ins and their failures, and + /// every change to how the account is reached. + const SECURITY: [&'static str; 20] = [ + "signed_in", + "sign_in_failed", + "session_revoked", + "passkey_added", + "passkey_removed", + "identity_linked", + "identity_unlinked", + "email_added", + "email_removed", + "primary_email_changed", + "consent_granted", + "consent_revoked", + "code_replayed", + "compromise_reported", + "recovery_started", + "recovery_completed", + "recovery_undone", + "handle_changed", + "account_disabled", + "account_deletion_scheduled", + ]; +} + +impl AccountService { + /// Counts what happened to the account since `since`. + pub(crate) async fn activity( + &self, + viewer: &Viewer, + since: DateTime, + ) -> Result { + viewer.authorize(&self.database).await?; + let kinds = |kinds: &[&str]| { + kinds + .iter() + .map(|kind| (*kind).to_owned()) + .collect::>() + }; + let mut events = self.database.events(); + Ok(Activity { + app_sign_ins: events + .count_since(Some(viewer.user()), &kinds(&Activity::APP_SIGN_INS), since) + .await?, + security_events: events + .count_since(Some(viewer.user()), &kinds(&Activity::SECURITY), since) + .await?, + }) + } + + /// Whether the account administers Piquel, which its pages mark. + pub(crate) async fn is_administrator(&self, viewer: &Viewer) -> Result { + viewer.authorize(&self.database).await?; + Ok(self + .database + .administrators() + .contains(viewer.user()) + .await?) + } +} + impl HistoryApplication { /// Serves the history from `database`. pub(crate) const fn new(database: Database) -> Self { diff --git a/apps/auth-service/src/routes.rs b/apps/auth-service/src/routes.rs index ed3d0336c..12fca86f5 100644 --- a/apps/auth-service/src/routes.rs +++ b/apps/auth-service/src/routes.rs @@ -139,12 +139,15 @@ pub(crate) mod oidc { pub(crate) mod dashboard { /// Redeems auth's handoff code, signing the browser in to the dashboard. pub(crate) const SIGN_IN: &str = "/sign-in"; + /// Keeps the theme and sidebar preferences a page's forms post, in cookies. + pub(crate) const PREFERENCES: &str = "/preferences"; /// Every path the dashboard serves is one of these, or under one: the admin /// listener mounts the pages on them, and nowhere else. - pub(crate) const PREFIXES: [&str; 10] = [ + pub(crate) const PREFIXES: [&str; 11] = [ "/", SIGN_IN, "/sign-out", + PREFERENCES, "/assets", "/users", "/administrators", @@ -175,12 +178,16 @@ pub(crate) mod page { pub(crate) const RECOVER_UNDO: &str = "/recover/undo"; /// Hands an administrator's passkey session off to the admin dashboard. pub(crate) const ADMIN: &str = "/admin"; + /// Keeps the theme and sidebar preferences a page's forms post, in cookies. + pub(crate) const PREFERENCES: &str = "/preferences"; /// The account's settings, at the paths piquel.fr served them on, so its redirect /// keeps old links and sent emails working. pub(crate) mod settings { - /// Sign-in methods: passkeys and social sign-in. + /// The account at a glance. pub(crate) const HOME: &str = "/settings"; + /// Sign-in methods: passkeys and social sign-in. + pub(crate) const SIGN_IN: &str = "/settings/sign-in"; /// Email addresses. pub(crate) const EMAILS: &str = "/settings/emails"; /// Confirming an address, from its verification link. @@ -220,13 +227,15 @@ pub(crate) mod page { /// Every server-rendered page's route, which the security layer classifies as /// pages. - pub(crate) const ALL: [&str; 19] = [ + pub(crate) const ALL: [&str; 21] = [ LOGIN, REGISTER, CONSENT, LOGOUT, ADMIN, + PREFERENCES, settings::HOME, + settings::SIGN_IN, settings::EMAILS, settings::VERIFY, settings::SESSIONS, diff --git a/apps/auth-service/src/security/mod.rs b/apps/auth-service/src/security/mod.rs index 607940f7f..77f0004a1 100644 --- a/apps/auth-service/src/security/mod.rs +++ b/apps/auth-service/src/security/mod.rs @@ -36,6 +36,7 @@ use piquel_repository::{ SessionAuthentication, SessionScope, StoredSession, }; use piquel_telemetry::{Counter, HttpTelemetry, Label}; +use piquel_ui::{PreferenceChange, Preferences}; use std::{ borrow::Cow, net::{IpAddr, SocketAddr}, @@ -251,9 +252,16 @@ piquel_common::str_enum! { /// A sign-in to the admin dashboard awaiting auth's handoff, on the /// dashboard's origin. DashboardState = "__Host-piquel_dashboard_state", + /// The theme the browser chose, on each origin. + Theme = "__Host-piquel_theme", + /// The sidebar's width the browser chose, on each origin. + Sidebar = "__Host-piquel_sidebar", } } +/// How long a preference is kept: a year. +const PREFERENCE_MAX_AGE: u32 = 365 * 24 * 60 * 60; + impl BrowserCookie { /// Lifetime in seconds. Flow cookies outlive their server-side state slightly; a /// notice is shown on the page its change goes to, at once. @@ -266,9 +274,38 @@ impl BrowserCookie { | Self::DashboardState | Self::Restore => FLOW_COOKIE_MAX_AGE, Self::Notice => 60, + Self::Theme | Self::Sidebar => PREFERENCE_MAX_AGE, + } + } + + /// The theme and sidebar preferences the browser's cookies carry. A value + /// that is none counts as unset. + pub(crate) fn read_preferences(headers: &HeaderMap) -> Preferences { + Preferences { + theme: Self::Theme + .value(headers) + .and_then(|value| value.parse().ok()), + sidebar: Self::Sidebar + .value(headers) + .and_then(|value| value.parse().ok()), } } + /// Adds the `Set-Cookie` headers keeping what `change` chose, to the answer of + /// the preference page. + pub(crate) fn set_preferences_on( + response: &mut axum::http::Response, + change: &PreferenceChange, + ) -> Result<(), InvalidHeaderValue> { + if let Some(theme) = change.theme { + Self::Theme.append(response, theme.as_str(), Self::Theme.max_age())?; + } + if let Some(sidebar) = change.sidebar { + Self::Sidebar.append(response, sidebar.as_str(), Self::Sidebar.max_age())?; + } + Ok(()) + } + /// Reads this cookie's value. A duplicated cookie counts as absent, so an /// injected value can never shadow the browser's own. fn value(self, headers: &HeaderMap) -> Option<&str> { diff --git a/apps/auth-service/src/web/account.rs b/apps/auth-service/src/web/account.rs index 66df419d2..03bec50c8 100644 --- a/apps/auth-service/src/web/account.rs +++ b/apps/auth-service/src/web/account.rs @@ -17,9 +17,13 @@ use crate::{ federation::FlowCookie, routes::page, security::{ApiError, BrowserCookie, SessionError}, + web::settings::TABS, }; use piquel_common::ErrorChain; -use piquel_ui::{Alert, Area, FieldError, LoginQuery, Messages, Notice, Query, Recovery, Section}; +use piquel_telemetry::HttpTelemetry; +use piquel_ui::{ + AccountNav, Alert, FieldError, LoginQuery, Messages, Notice, Query, Recovery, Section, Tab, Who, +}; use serde::{Deserialize, de::DeserializeOwned}; use topcoat::{ Error, @@ -36,12 +40,6 @@ use topcoat::{ }; use url::Url; -/// Each section of the account's pages and the page the account's bar links. -const SECTIONS: [(Section, &str); 2] = [ - (Section::Account, page::settings::HOME), - (Section::Developers, page::developers::HOME), -]; - /// A page of the signed-in account: its section and path, the change its form /// posts, its query, what a change does, and how the page renders. /// [`WebApplication::show`] and [`WebApplication::submit`] serve it. @@ -223,9 +221,11 @@ impl Reader { pub(super) struct Framed<'a> { /// The section it belongs to. pub(super) section: Section, + /// The settings tab it is, if it is one, which the sidebar marks. + pub(super) tab: Option, /// Its title in the browser. pub(super) title: &'a str, - /// What opens it, above its messages: the settings tabs, or an app's header. + /// What opens it, above its messages, such as an app's header. pub(super) head: Child<'a>, /// The page. pub(super) page: Child<'a>, @@ -350,6 +350,7 @@ impl WebApplication { let head = view! { cx => piquel_ui::back_to_apps(home: page::developers::HOME) }; let framed = Framed { section: P::SECTION, + tab: None, title: P::TITLE, head: Child::new(head), page: Child::default(), @@ -389,9 +390,9 @@ impl WebApplication { } /// Answers with the account page `framed`, at the status and with the messages - /// of `outcome`, in its section's frame, below the account's bar and what the - /// account's recovery that can still be undone asks, if any. Its forms may - /// redirect to `targets`. + /// of `outcome`, in the account's shell: the sidebar of its sections, then + /// what the account's recovery that can still be undone asks, if any. Its + /// forms may redirect to `targets`. pub(super) async fn account_page( &self, cx: &Cx, @@ -402,11 +403,13 @@ impl WebApplication { ) -> Result { let Framed { section, + tab, title, head, page, } = framed; - let profile = match self.account.profile(&reader.viewer()).await { + let viewer = reader.viewer(); + let profile = match self.account.profile(&viewer).await { Ok(profile) => profile, Err(AccountError::Owner(SessionError::Missing)) => { return self @@ -415,16 +418,36 @@ impl WebApplication { } Err(error) => return Err(error.into()), }; + let administrator = self.account.is_administrator(&viewer).await?; let session = reader.owner().session_id(); let confirmed = reader.owner().was_passkey_confirmed(); + let here = uri(cx) + .path_and_query() + .map_or(page::settings::HOME, |path| path.as_str()); + let who = Who { + user: Some(reader.owner().user()), + name: &profile.display_name, + handle: profile.handle.as_str(), + administrator, + }; + let nav = AccountNav { + section, + tabs: &TABS, + current: tab, + developers: page::developers::HOME, + }; let page = view! { cx => piquel_ui::account( - section: section, - user: reader.owner().user(), - display_name: &profile.display_name, - handle: profile.handle.as_str(), - sections: &SECTIONS, + nav: nav, + who: who, + title: title, + home: page::settings::HOME, sign_out: page::LOGOUT, + preferences: BrowserCookie::read_preferences(headers(cx)), + preferences_action: page::PREFERENCES, + here: here, + policies: self.policies.links(), + reference: HttpTelemetry::trace_id(status), recovery: view! { if let Some(recovery) = reader.recovery() { piquel_ui::recovery_banner( @@ -441,7 +464,7 @@ impl WebApplication { ) }; Ok(self - .render(cx, status, title, Area::Section(section), targets, page) + .render_document(cx, status, title, targets, false, page) .await?) } @@ -464,8 +487,6 @@ impl WebApplication { } .on(page::LOGIN)?; let page = view! { cx => piquel_ui::signed_out(section: section, sign_in: &sign_in) }; - Ok(self - .render(cx, status, title, Area::Section(section), &[], page) - .await?) + Ok(self.render(cx, status, title, &[], page).await?) } } diff --git a/apps/auth-service/src/web/admin/administrators.rs b/apps/auth-service/src/web/admin/administrators.rs index f46dc65c8..c234b892e 100644 --- a/apps/auth-service/src/web/admin/administrators.rs +++ b/apps/auth-service/src/web/admin/administrators.rs @@ -2,7 +2,7 @@ use super::AdminApplication as App; use piquel_common::{UserId, admin::GrantAdministrator}; -use piquel_ui::AdministratorRow; +use piquel_ui::{Action, AdministratorRow, Change}; use serde::de::IgnoredAny; use topcoat::{ Result, @@ -23,6 +23,7 @@ pub(super) async fn list(cx: &Cx) -> Result { .await?; // The viewer is an active administrator, so revoking anyone else's rights // leaves one; the service refuses the last active administrator's anyway. + let inline = admin.operator.is_confirmed(super::FORM_TIME); let rows: Vec<_> = administrators .iter() .map(|administrator| AdministratorRow { @@ -31,7 +32,10 @@ pub(super) async fn list(cx: &Cx) -> Result { revoke: if administrator.user_id == admin.user_id { Err("You cannot change your own rights.") } else { - Ok(href!(revoke, Administrator(administrator.user_id)).resolve(cx)) + Ok(Action { + href: href!(revoke, Administrator(administrator.user_id)).resolve(cx), + inline, + }) }, }) .collect(); @@ -39,7 +43,7 @@ pub(super) async fn list(cx: &Cx) -> Result { let page = view! { cx => piquel_ui::administrator_list(rows: rows, grant: granting.as_str()) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Administrators", page).await } /// `/administrators/grant`: makes an active account an administrator. @@ -58,9 +62,7 @@ pub(super) async fn grant(cx: &Cx, form: Option>) -> Re .map(|refused| refused.form.user_id.to_string()); let page = view! { cx => piquel_ui::dashboard_change( - title: "Grant administrator rights", - description: "The account can use this dashboard and every admin operation. The dashboard cannot change it afterwards, until its rights are revoked.", - button: "Grant", + change: Change::GrantAdministrator, back: back.as_str(), refusal: refusal.as_deref(), ) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Grant rights", page).await } /// `/administrators/{administrator}/revoke`: removes another administrator's @@ -87,13 +89,10 @@ pub(super) async fn revoke(cx: &Cx, form: Option>) -> Result piquel_ui::dashboard_change( - title: "Revoke administrator rights", - description: "The account keeps its sessions, but can no longer use this dashboard.", - button: "Revoke", + change: Change::RevokeAdministrator, back: back.as_str(), refusal: refusal.as_deref(), - danger: true, ) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Revoke rights", page).await } diff --git a/apps/auth-service/src/web/admin/audit.rs b/apps/auth-service/src/web/admin/audit.rs index 5cf6b72d2..69b3da496 100644 --- a/apps/auth-service/src/web/admin/audit.rs +++ b/apps/auth-service/src/web/admin/audit.rs @@ -34,5 +34,5 @@ pub(super) async fn verify(cx: &Cx) -> Result { .next .map(|after| format!("{}?after={after}", href!(verify).resolve(cx))); let view = view! { cx => piquel_ui::audit_page(page: page, later: later) }; - App::render(cx, StatusCode::OK, view).await + App::render(cx, StatusCode::OK, "Audit", view).await } diff --git a/apps/auth-service/src/web/admin/invitations.rs b/apps/auth-service/src/web/admin/invitations.rs index 2cead0da5..c2b98881a 100644 --- a/apps/auth-service/src/web/admin/invitations.rs +++ b/apps/auth-service/src/web/admin/invitations.rs @@ -4,7 +4,7 @@ use super::AdminApplication as App; use crate::{AdminError, InviteExpiry}; use chrono::Utc; use piquel_common::{TokenId, admin::CreateInvitation}; -use piquel_ui::InvitationRow; +use piquel_ui::{Action, Change, InvitationRow}; use serde::de::IgnoredAny; use topcoat::{ Result, @@ -39,13 +39,18 @@ pub(super) async fn list(cx: &Cx) -> Result { } else { None }; + let inline = admin.operator.is_confirmed(super::FORM_TIME); let rows: Option> = invitations.as_ref().map(|invitations| { invitations .iter() .map(|invitation| InvitationRow { invitation, - revoke: (invitation.redeemed_at.is_none() && invitation.revoked_at.is_none()) - .then(|| href!(revoke, Invitation(invitation.id)).resolve(cx)), + revoke: (invitation.redeemed_at.is_none() && invitation.revoked_at.is_none()).then( + || Action { + href: href!(revoke, Invitation(invitation.id)).resolve(cx), + inline, + }, + ), }) .collect() }); @@ -53,7 +58,7 @@ pub(super) async fn list(cx: &Cx) -> Result { let page = view! { cx => piquel_ui::invitation_list(rows: rows, create: creating.as_str(), now: Utc::now()) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Invitations", page).await } /// `/invitations/new`: creates an invitation and shows its link, once. @@ -98,9 +103,7 @@ pub(super) async fn create(cx: &Cx, form: Option>) -> Res }, None => { piquel_ui::dashboard_change( - title: "Invite someone", - description: "Creates a single-use signup link.", - button: "Create link", + change: Change::Invite, back: back.as_str(), refusal: refused,