diff --git a/crates/dizey-web/Cargo.toml b/crates/dizey-web/Cargo.toml index d9310a8..f8392d2 100644 --- a/crates/dizey-web/Cargo.toml +++ b/crates/dizey-web/Cargo.toml @@ -15,9 +15,10 @@ leptos_router = { version = "0.9.0-beta1" } leptos_meta = { version = "0.9.0-beta" } leptos_axum = { version = "0.9.0-beta", optional = true } serde.workspace = true +time.workspace = true thiserror.workspace = true -dizey-core = { workspace = true, optional = true } +dizey-core = { workspace = true } axum = { version = "0.8.9", optional = true } tokio = { workspace = true, optional = true } tower = { version = "0.5.2", optional = true } @@ -43,6 +44,6 @@ ssr = [ "dep:tokio", "dep:tower", "dep:tower-http", - "dep:dizey-core", + "dizey-core/server", "dep:turso", ] diff --git a/crates/dizey-web/src/app.rs b/crates/dizey-web/src/app.rs index 6c077c3..b060bb8 100644 --- a/crates/dizey-web/src/app.rs +++ b/crates/dizey-web/src/app.rs @@ -3,6 +3,8 @@ use leptos_meta::{MetaTags, Stylesheet, Title, provide_meta_context}; use leptos_router::components::{Route, Router, Routes}; use leptos_router::path; +use crate::pages::{Join, Landing}; + /// The HTML document the server streams. `cargo-leptos` writes the bundle to /// `/pkg/dizey.{js,wasm,css}`, which is what the tags below point at. pub fn shell(options: LeptosOptions) -> impl IntoView { @@ -38,31 +40,13 @@ pub fn App() -> impl IntoView { <Router> <Routes fallback=NotFound> - <Route path=path!("/") view=BoardPlaceholder/> + <Route path=path!("/") view=Landing/> + <Route path=path!("/join/:token") view=Join/> </Routes> </Router> } } -/// The top bar from the Main artboard. The board itself lands in a later slice; -/// this exists so the scaffold renders something real rather than "hello". -#[component] -fn BoardPlaceholder() -> impl IntoView { - view! { - <header class="topbar"> - <div class="wordmark"> - <span class="wordmark-text">"dizey"</span> - <span class="wordmark-dot"></span> - </div> - <div class="topbar-divider"></div> - <span class="board-name">"Launch — Q3"</span> - </header> - <main class="scaffold-note"> - <p>"The board is not wired up yet."</p> - </main> - } -} - #[component] fn NotFound() -> impl IntoView { #[cfg(feature = "ssr")] diff --git a/crates/dizey-web/src/auth.rs b/crates/dizey-web/src/auth.rs new file mode 100644 index 0000000..409d21f --- /dev/null +++ b/crates/dizey-web/src/auth.rs @@ -0,0 +1,257 @@ +//! The account surface: claiming the workspace, first sign-in from an invited +//! link, signing in and out, and changing a password. +//! +//! The public forms answer identically whether or not an address has an +//! account. The honest, specific wording belongs to the admin-side calls. + +use leptos::prelude::*; +use serde::{Deserialize, Serialize}; + +/// Everything a refused call is allowed to say. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Refusal { + /// Wrong address, wrong password, or no account at all — deliberately one + /// answer for all three. + Rejected, + RateLimited, + /// A password broke a stated rule. Only reachable once we know who the + /// person is, so it gives nothing away. + Password(String), + Forbidden, + SignInFirst, + AlreadyClaimed, + /// Admin-side wording, shown on the member list and nowhere public. + AddressTaken, + /// The link is spent, expired, or was never real. + LinkNotUsable, + Unavailable, +} + +impl Refusal { + pub fn message(&self) -> String { + match self { + Refusal::Rejected => "That did not work.".to_string(), + Refusal::RateLimited => { + "Too many attempts — wait a few minutes and try again.".to_string() + } + Refusal::Password(problem) => problem.clone(), + Refusal::Forbidden => "Not permitted.".to_string(), + Refusal::SignInFirst => "Sign in first.".to_string(), + Refusal::AlreadyClaimed => "This workspace already has an owner.".to_string(), + Refusal::AddressTaken => "That address already has an account.".to_string(), + Refusal::LinkNotUsable => { + "This link no longer works. Ask the admin to send another." + .to_string() + } + Refusal::Unavailable => "Something went wrong. Try again.".to_string(), + } + } +} + +/// The person the current browser is signed in as. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Me { + pub display_name: String, + pub email: String, + pub role: dizey_core::Role, +} + +/// Which of the three doors this browser is standing at. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Gate { + /// Nobody has signed in yet: the next account administers the workspace. + NeedsSetup, + NeedsSignIn, + SignedIn(Me), +} + +/// The name and address an invitation was made out to. Only the holder of the +/// link can ask, and the link is a 128-bit secret, so answering is safe. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Invited { + pub display_name: String, + pub email: String, +} + +/// The workspace has exactly one name and no screen that sets it, so it is a +/// constant rather than a field nobody was shown. +pub const WORKSPACE_NAME: &str = "Dizey"; + +/// Which door to show. (The `#[server]` macro names a struct after the +/// function, so the call is `current_gate` and the answer is a `Gate`.) +#[server] +pub async fn current_gate() -> Result<Gate, ServerFnError> { + use crate::server::{accounts, current_user}; + + if let Some(user) = current_user().await { + return Ok(Gate::SignedIn(Me { + display_name: user.display_name, + email: user.email, + role: user.role, + })); + } + let claimed = accounts() + .store() + .owner() + .await + .map_err(|e| ServerFnError::new(e.to_string()))? + .is_some(); + Ok(if claimed { + Gate::NeedsSignIn + } else { + Gate::NeedsSetup + }) +} + +/// The first account. It becomes the admin and owns the workspace. +#[server] +pub async fn claim_workspace( + display_name: String, + email: String, + password: String, +) -> Result<Option<Refusal>, ServerFnError> { + use crate::server::{accounts, set_session_cookie}; + use dizey_core::accounts::SESSION_LIFETIME; + + match accounts() + .claim_workspace(WORKSPACE_NAME, &email, &display_name, &password) + .await + { + Ok((_workspace, signed_in)) => { + set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME); + Ok(None) + } + Err(error) => Ok(Some(error.into())), + } +} + +/// Who an invitation was made out to, for the "signing in as" line. +#[server] +pub async fn invitation(token: String) -> Result<Option<Invited>, ServerFnError> { + use crate::server::accounts; + use dizey_core::auth::hash_token; + use time::OffsetDateTime; + + let store = accounts().store().clone(); + let digest = hash_token(&token); + let Some(link) = store + .signin_link_by_hash(&digest) + .await + .map_err(|e| ServerFnError::new(e.to_string()))? + else { + return Ok(None); + }; + if !link.is_usable(OffsetDateTime::now_utc()) { + return Ok(None); + } + let Some(user) = store + .user(&link.user_id) + .await + .map_err(|e| ServerFnError::new(e.to_string()))? + else { + return Ok(None); + }; + Ok(Some(Invited { + display_name: user.display_name, + email: user.email, + })) +} + +/// The invited member's first sign-in: they pick their own password. The admin +/// can neither read nor set it. +#[server] +pub async fn redeem_link( + token: String, + password: String, +) -> Result<Option<Refusal>, ServerFnError> { + use crate::server::{accounts, set_session_cookie}; + use dizey_core::accounts::SESSION_LIFETIME; + + match accounts().redeem_signin_link(&token, &password).await { + Ok(signed_in) => { + set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME); + Ok(None) + } + Err(error) => Ok(Some(error.into())), + } +} + +/// Signing in. Answers the same whether the address is unknown, has no password +/// yet, or the password is wrong. +#[server] +pub async fn sign_in( + email: String, + password: String, +) -> Result<Option<Refusal>, ServerFnError> { + use crate::server::{accounts, client_label, set_session_cookie}; + use dizey_core::accounts::SESSION_LIFETIME; + + match accounts() + .sign_in(&email, &password, &client_label()) + .await + { + Ok(signed_in) => { + set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME); + Ok(None) + } + Err(error) => Ok(Some(error.into())), + } +} + +/// Ends this browser's session. Other browsers keep theirs. +#[server] +pub async fn sign_out() -> Result<(), ServerFnError> { + use crate::server::{accounts, clear_session_cookie, presented_session}; + + if let Some(presented) = presented_session() { + let _ = accounts().sign_out(&presented).await; + } + clear_session_cookie(); + Ok(()) +} + +/// Changes the password and signs the other devices out, as the pane promises. +/// The browser that asked gets a fresh cookie. +#[server] +pub async fn change_password( + current: String, + new: String, +) -> Result<Option<Refusal>, ServerFnError> { + use crate::server::{require_user, set_session_cookie}; + use dizey_core::accounts::SESSION_LIFETIME; + + let user = match require_user().await { + Ok(user) => user, + Err(refusal) => return Ok(Some(refusal)), + }; + match crate::server::accounts() + .change_password(&user.id, ¤t, &new) + .await + { + Ok(signed_in) => { + set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME); + Ok(None) + } + Err(error) => Ok(Some(error.into())), + } +} + +/// Admin creates an account with a name and an address and no password, and +/// gets the first-sign-in link back exactly once. +#[server] +pub async fn invite_member( + email: String, + display_name: String, + role: dizey_core::Role, +) -> Result<Result<String, Refusal>, ServerFnError> { + use crate::server::{accounts, require_admin}; + + let admin = match require_admin().await { + Ok(admin) => admin, + Err(refusal) => return Ok(Err(refusal)), + }; + match accounts().invite(&admin, &email, &display_name, role).await { + Ok(invitation) => Ok(Ok(format!("/join/{}", invitation.token.expose()))), + Err(error) => Ok(Err(error.into())), + } +} diff --git a/crates/dizey-web/src/lib.rs b/crates/dizey-web/src/lib.rs index ee1a637..da368eb 100644 --- a/crates/dizey-web/src/lib.rs +++ b/crates/dizey-web/src/lib.rs @@ -1,4 +1,8 @@ pub mod app; +pub mod auth; +pub mod pages; +#[cfg(feature = "ssr")] +pub mod server; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] diff --git a/crates/dizey-web/src/main.rs b/crates/dizey-web/src/main.rs index 47cb279..13160d9 100644 --- a/crates/dizey-web/src/main.rs +++ b/crates/dizey-web/src/main.rs @@ -2,9 +2,21 @@ #[tokio::main] async fn main() { use axum::Router; + use dizey_core::accounts::Accounts; + use dizey_core::store::TursoStore; use dizey_web::app::{App, shell}; use leptos::prelude::*; use leptos_axum::{LeptosRoutes, generate_route_list}; + use std::sync::Arc; + + // One process per database file: Turso is a single-writer engine and a + // second process on the same file loses writes rather than queueing. + let database = std::env::var("DIZEY_DATABASE").unwrap_or_else(|_| "dizey.db".to_string()); + // `open` applies any unapplied migration before it returns. + let store = TursoStore::open(&database) + .await + .expect("failed to open the database"); + let accounts = Accounts::new(Arc::new(store)); let conf = get_configuration(None).expect("failed to read leptos configuration"); let leptos_options = conf.leptos_options; @@ -13,10 +25,20 @@ async fn main() { let app = Router::new() .route("/healthz", axum::routing::get(|| async { "ok" })) - .leptos_routes(&leptos_options, routes, { - let leptos_options = leptos_options.clone(); - move || shell(leptos_options.clone()) - }) + .leptos_routes_with_context( + &leptos_options, + routes, + { + // Provided here *and* to the server-function handler, which + // `leptos_routes_with_context` registers with the same closure. + let accounts = accounts.clone(); + move || provide_context(accounts.clone()) + }, + { + let leptos_options = leptos_options.clone(); + move || shell(leptos_options.clone()) + }, + ) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); @@ -24,7 +46,10 @@ async fn main() { .await .expect("failed to bind"); println!("dizey listening on http://{addr}"); - axum::serve(listener, app.into_make_service()) + axum::serve( + listener, + app.into_make_service_with_connect_info::<std::net::SocketAddr>(), + ) .await .expect("server error"); } diff --git a/crates/dizey-web/src/pages.rs b/crates/dizey-web/src/pages.rs new file mode 100644 index 0000000..ad084f0 --- /dev/null +++ b/crates/dizey-web/src/pages.rs @@ -0,0 +1,338 @@ +//! The account screens, from the FirstLogin artboard: setting up the first +//! account, an invited member picking a password, and signing in. + +use leptos::prelude::*; +use leptos_router::hooks::use_params_map; + +use crate::auth::{ + ClaimWorkspace, Gate, Invited, RedeemLink, Refusal, SignIn, current_gate, invitation, +}; + +/// The front door. Which screen this is depends on the workspace, and the +/// server decides — an empty workspace offers setup, a claimed one offers a +/// sign-in, a signed-in browser gets the board. +#[component] +pub fn Landing() -> impl IntoView { + let gate = Resource::new(|| (), |_| async move { current_gate().await }); + + view! { + <Topbar/> + <Suspense fallback=|| view! { <main class="auth-stage"></main> }> + {move || Suspend::new(async move { + match gate.await { + Ok(Gate::NeedsSetup) => { + view! { <SetupCard on_done=move || gate.refetch()/> }.into_any() + } + Ok(Gate::NeedsSignIn) => { + view! { <SignInCard on_done=move || gate.refetch()/> }.into_any() + } + Ok(Gate::SignedIn(me)) => { + view! { + <main class="scaffold-note"> + <p> + "Signed in as " {me.display_name} " (" {me.email} ")." + </p> + <p>"The board is not wired up yet."</p> + </main> + } + .into_any() + } + Err(_) => { + view! { + <main class="scaffold-note"> + <p>"Something went wrong. Reload the page."</p> + </main> + } + .into_any() + } + } + })} + </Suspense> + } +} + +#[component] +fn Topbar() -> impl IntoView { + view! { + <header class="topbar"> + <div class="wordmark"> + <span class="wordmark-text">"dizey"</span> + <span class="wordmark-dot"></span> + </div> + </header> + } +} + +/// "Set up Dizey" — the first account in an empty workspace. +#[component] +fn SetupCard(on_done: impl Fn() + Copy + Send + Sync + 'static) -> impl IntoView { + let action = ServerAction::<ClaimWorkspace>::new(); + let value = action.value(); + Effect::new(move |_| { + if matches!(value.get(), Some(Ok(None))) { + on_done(); + } + }); + + view! { + <main class="auth-stage"> + <div class="auth-column"> + <span class="auth-kicker">"FIRST ACCOUNT — EMPTY WORKSPACE"</span> + <div class="auth-card"> + <div class="auth-head"> + <div class="auth-title">"Set up Dizey"</div> + <div class="auth-sub"> + "Nobody has signed in yet, so this account administers the workspace: the mail sender, the limits and the member list are yours." + </div> + </div> + <ActionForm action=action> + <label class="auth-field"> + <span class="auth-label">"YOUR NAME"</span> + <input + class="auth-input" + type="text" + name="display_name" + autocomplete="name" + required + /> + </label> + <label class="auth-field"> + <span class="auth-label">"EMAIL"</span> + <input + class="auth-input auth-input-mono" + type="email" + name="email" + autocomplete="email" + required + /> + </label> + <label class="auth-field"> + <span class="auth-label">"PASSWORD"</span> + <input + class="auth-input auth-input-mono" + type="password" + name="password" + autocomplete="new-password" + required + /> + </label> + <PasswordRules/> + <button class="auth-submit" type="submit" disabled=move || action.pending().get()> + <span class="auth-submit-text">"Create workspace"</span> + <span class="auth-key">"↵"</span> + </button> + </ActionForm> + <Problem value=value/> + <div class="auth-foot"> + "Mail rules stay quiet until you connect a sender in Settings. Nothing leaves the machine before that." + </div> + </div> + </div> + </main> + } +} + +/// "Pick a password" — the invited member's first sign-in, reached from the +/// emailed link. The address was set by the admin and cannot be edited here. +#[component] +pub fn Join() -> impl IntoView { + let params = use_params_map(); + let token = move || params.read().get("token").unwrap_or_default(); + let who = Resource::new(token, |token| async move { invitation(token).await }); + + view! { + <Topbar/> + <Suspense fallback=|| view! { <main class="auth-stage"></main> }> + {move || Suspend::new(async move { + match who.await { + Ok(Some(person)) => view! { <JoinCard token=token() person=person/> }.into_any(), + _ => { + view! { + <main class="auth-stage"> + <div class="auth-column"> + <div class="auth-card"> + <div class="auth-title">"This link no longer works"</div> + <div class="auth-sub"> + "Sign-in links last seven days. Ask the admin to send another — it opens the same account, with the same history." + </div> + </div> + </div> + </main> + } + .into_any() + } + } + })} + </Suspense> + } +} + +#[component] +fn JoinCard(token: String, person: Invited) -> impl IntoView { + let action = ServerAction::<RedeemLink>::new(); + let value = action.value(); + let navigate = leptos_router::hooks::use_navigate(); + Effect::new(move |_| { + if matches!(value.get(), Some(Ok(None))) { + navigate("/", Default::default()); + } + }); + + let repeat = RwSignal::new(String::new()); + let chosen = RwSignal::new(String::new()); + let matches_yet = move || { + let repeat = repeat.get(); + !repeat.is_empty() && repeat == chosen.get() + }; + let invited_by = person.display_name.clone(); + + view! { + <main class="auth-stage"> + <div class="auth-column"> + <span class="auth-kicker">"INVITED MEMBER — FIRST SIGN-IN"</span> + <div class="auth-card"> + <div class="auth-head"> + <div class="auth-title">"Pick a password"</div> + <div class="auth-sub"> + {invited_by} " made you an account. It has no password yet." + </div> + </div> + <div class="auth-field"> + <span class="auth-label">"SIGNING IN AS"</span> + <div class="auth-locked"> + <span class="auth-locked-value">{person.email}</span> + <span class="auth-locked-note">"set by the admin"</span> + </div> + </div> + <ActionForm action=action> + <input type="hidden" name="token" value=token/> + <label class="auth-field"> + <span class="auth-label">"NEW PASSWORD"</span> + <input + class="auth-input auth-input-mono" + type="password" + name="password" + autocomplete="new-password" + required + on:input=move |ev| chosen.set(event_target_value(&ev)) + /> + </label> + <label class="auth-field"> + <span class="auth-label">"REPEAT IT"</span> + <input + class="auth-input auth-input-mono" + type="password" + autocomplete="new-password" + on:input=move |ev| repeat.set(event_target_value(&ev)) + /> + <Show when=move || !repeat.get().is_empty() && !matches_yet()> + <span class="auth-warn">"not the same yet"</span> + </Show> + </label> + <PasswordRules/> + <button + class="auth-submit" + type="submit" + disabled=move || !matches_yet() || action.pending().get() + > + <span class="auth-submit-text">"Set password and sign in"</span> + </button> + <Show when=move || !matches_yet()> + <div class="auth-warn">"Waiting for the repeated password to match."</div> + </Show> + </ActionForm> + <Problem value=value/> + <div class="auth-foot"> + "Name and photo can wait — you land on the board straight after this. The admin cannot see or set your password." + </div> + </div> + </div> + </main> + } +} + +/// The sign-in form for an account that already has a password. It answers the +/// same whether the address is unknown, has no password yet, or the password is +/// wrong — the difference is not the browser's business. +#[component] +fn SignInCard(on_done: impl Fn() + Copy + Send + Sync + 'static) -> impl IntoView { + let action = ServerAction::<SignIn>::new(); + let value = action.value(); + Effect::new(move |_| { + if matches!(value.get(), Some(Ok(None))) { + on_done(); + } + }); + + view! { + <main class="auth-stage"> + <div class="auth-column"> + <span class="auth-kicker">"SIGN IN"</span> + <div class="auth-card"> + <div class="auth-head"> + <div class="auth-title">"Sign in to Dizey"</div> + <div class="auth-sub"> + "Accounts are made by the admin. If you were invited, use the link you were sent — it is where you choose your password." + </div> + </div> + <ActionForm action=action> + <label class="auth-field"> + <span class="auth-label">"EMAIL"</span> + <input + class="auth-input auth-input-mono" + type="email" + name="email" + autocomplete="username" + required + /> + </label> + <label class="auth-field"> + <span class="auth-label">"PASSWORD"</span> + <input + class="auth-input auth-input-mono" + type="password" + name="password" + autocomplete="current-password" + required + /> + </label> + <button class="auth-submit" type="submit" disabled=move || action.pending().get()> + <span class="auth-submit-text">"Sign in"</span> + <span class="auth-key">"↵"</span> + </button> + </ActionForm> + <Problem value=value/> + </div> + </div> + </main> + } +} + +/// The two rules, stated where the password is chosen. The server checks them +/// again and is the one that decides. +#[component] +fn PasswordRules() -> impl IntoView { + view! { + <ul class="auth-rules"> + <li>"at least 10 characters"</li> + <li>"not your address or your name"</li> + </ul> + } +} + +/// Whatever the server refused with, in its own words. +#[component] +fn Problem( + #[prop(into)] value: Signal<Option<Result<Option<Refusal>, ServerFnError>>>, +) -> impl IntoView { + let message = move || match value.get() { + Some(Ok(Some(refusal))) => Some(refusal.message()), + Some(Err(_)) => Some(Refusal::Unavailable.message()), + _ => None, + }; + view! { + <Show when=move || message().is_some()> + <div class="auth-problem">{move || message().unwrap_or_default()}</div> + </Show> + } +} diff --git a/crates/dizey-web/src/server.rs b/crates/dizey-web/src/server.rs new file mode 100644 index 0000000..7120f8c --- /dev/null +++ b/crates/dizey-web/src/server.rs @@ -0,0 +1,148 @@ +//! Server-side plumbing for the auth surface: the session cookie, the person +//! behind the current request, and the role guards. +//! +//! Every guard here is the real one. The UI hides what a role may not do, but +//! the answer that matters is the one given in this module, on the server. + +use axum::http::HeaderValue; +use axum::http::header::{COOKIE, SET_COOKIE}; +use axum::http::request::Parts; +use dizey_core::accounts::{AccountError, Accounts}; +use dizey_core::store::User; +use leptos::prelude::*; +use leptos_axum::ResponseOptions; + +/// The session cookie's name. One cookie, one browser, one session row. +pub const SESSION_COOKIE: &str = "dizey_session"; + +/// The workspace's account service, put into context by the router. +pub fn accounts() -> Accounts { + expect_context::<Accounts>() +} + +/// The cookie value this request presented, if it presented one. +pub fn presented_session() -> Option<String> { + let parts = use_context::<Parts>()?; + for header in parts.headers.get_all(COOKIE) { + let Ok(raw) = header.to_str() else { continue }; + for pair in raw.split(';') { + let pair = pair.trim(); + if let Some(value) = pair.strip_prefix(SESSION_COOKIE) + && let Some(value) = value.strip_prefix('=') + { + return Some(value.to_string()); + } + } + } + None +} + +/// A stable-enough label for the client, for rate limiting. A proxy header is +/// only trusted because Dizey is meant to sit behind one; the address bucket is +/// the limit that actually protects the Argon2 work either way. +pub fn client_label() -> String { + let Some(parts) = use_context::<Parts>() else { + return "unknown".to_string(); + }; + if let Some(forwarded) = parts.headers.get("x-forwarded-for") + && let Ok(raw) = forwarded.to_str() + && let Some(first) = raw.split(',').next() + && !first.trim().is_empty() + { + return first.trim().to_string(); + } + parts + .extensions + .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>() + .map(|info| info.0.ip().to_string()) + .unwrap_or_else(|| "unknown".to_string()) +} + +/// Writes the session cookie. `HttpOnly` so script cannot read it, `Secure` so +/// it never crosses plain HTTP, `SameSite=Lax` so another site's form cannot +/// post with it. +pub fn set_session_cookie(token: &str, lifetime: time::Duration) { + let value = format!( + "{SESSION_COOKIE}={token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={}", + lifetime.whole_seconds().max(0) + ); + write_cookie(&value); +} + +/// Removes the session cookie from this browser. The server-side revocation is +/// what actually ends the session; this only tidies the client. +pub fn clear_session_cookie() { + write_cookie(&format!( + "{SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0" + )); +} + +fn write_cookie(value: &str) { + let Some(response) = use_context::<ResponseOptions>() else { + return; + }; + match HeaderValue::from_str(value) { + Ok(header) => response.append_header(SET_COOKIE, header), + Err(_) => { + // A token is hex, and the rest is a literal, so this cannot happen + // from user input; refusing to send a malformed header is still the + // right failure. + eprintln!("refusing to set a malformed session cookie"); + } + } +} + +/// The person behind this request, or nobody. +pub async fn current_user() -> Option<User> { + let presented = presented_session()?; + accounts().authenticate(&presented).await.ok().flatten() +} + +/// The person behind this request, or a refusal the caller can return as-is. +pub async fn require_user() -> Result<User, Refusal> { + current_user().await.ok_or(Refusal::SignInFirst) +} + +/// The admin behind this request. A member or a viewer is refused *here*, not +/// merely hidden from in the UI. +pub async fn require_admin() -> Result<User, Refusal> { + let user = require_user().await?; + if user.role.can_administer() { + Ok(user) + } else { + Err(Refusal::Forbidden) + } +} + +/// The person behind this request if they may change the board. +pub async fn require_writer() -> Result<User, Refusal> { + let user = require_user().await?; + if user.role.can_write_tasks() { + Ok(user) + } else { + Err(Refusal::Forbidden) + } +} + +use crate::auth::Refusal; + +impl From<AccountError> for Refusal { + fn from(error: AccountError) -> Self { + match error { + AccountError::Rejected => Refusal::Rejected, + AccountError::RateLimited => Refusal::RateLimited, + AccountError::Password(problem) => Refusal::Password(problem.to_string()), + AccountError::Forbidden => Refusal::Forbidden, + AccountError::AlreadyClaimed => Refusal::AlreadyClaimed, + AccountError::AddressTaken => Refusal::AddressTaken, + AccountError::Store(error) => { + eprintln!("store error: {error}"); + Refusal::Unavailable + } + AccountError::Auth(error) => { + eprintln!("auth error: {error}"); + Refusal::Unavailable + } + } + } +} diff --git a/style/main.scss b/style/main.scss index 92fcccf..f5f4b5a 100644 --- a/style/main.scss +++ b/style/main.scss @@ -79,3 +79,184 @@ a { padding: 32px 24px; color: var(--muted); } + +// --- Account screens (FirstLogin artboard) --------------------------------- + +.auth-stage { + min-height: calc(100vh - var(--topbar-height)); + display: flex; + align-items: center; + justify-content: center; + padding: 0 40px 40px; +} + +.auth-column { + width: 520px; + max-width: 100%; + display: flex; + flex-direction: column; + gap: 10px; +} + +.auth-kicker { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + color: var(--muted-soft); +} + +.auth-card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 12px; + padding: 28px 30px; + display: flex; + flex-direction: column; + gap: 18px; + box-shadow: 0 4px 16px rgba(28, 27, 24, 0.04); + + form { + display: flex; + flex-direction: column; + gap: 18px; + } +} + +.auth-head { + display: flex; + flex-direction: column; + gap: 6px; +} + +.auth-title { + font-size: 19px; + font-weight: 600; +} + +.auth-sub { + font-size: 13px; + color: var(--muted); + line-height: 1.5; +} + +.auth-field { + display: flex; + flex-direction: column; + gap: 6px; +} + +.auth-label { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + color: var(--muted-soft); +} + +.auth-input { + height: 40px; + padding: 0 12px; + background: #faf9f6; + border: 1px solid var(--border-strong); + border-radius: var(--radius); + font-family: var(--font-sans); + font-size: 13px; + color: var(--ink); + + &:focus { + outline: none; + background: var(--surface); + border-color: var(--accent); + } +} + +.auth-input-mono { + font-family: var(--font-mono); +} + +// The address an invited member signs in as: shown, never edited. +.auth-locked { + display: flex; + align-items: center; + gap: 8px; + height: 40px; + padding: 0 12px; + background: #f2f0ea; + border: 1px solid var(--border-strong); + border-radius: var(--radius); +} + +.auth-locked-value { + font-family: var(--font-mono); + font-size: 13px; + color: var(--muted); + flex-grow: 1; +} + +.auth-locked-note { + font-size: 12px; + color: var(--muted-soft); +} + +.auth-rules { + margin: 0; + padding-left: 18px; + display: flex; + flex-direction: column; + gap: 4px; + font-size: 12px; + color: #5c7b46; +} + +.auth-submit { + height: 42px; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + background: var(--accent); + color: var(--surface); + border: 0; + border-radius: var(--radius); + cursor: pointer; + font-family: var(--font-sans); + + &:disabled { + opacity: 0.45; + cursor: default; + } +} + +.auth-submit-text { + font-size: 14px; + font-weight: 600; +} + +.auth-key { + font-family: var(--font-mono); + font-size: 10px; + background: #5a6a94; + border-radius: 4px; + padding: 1px 5px; +} + +.auth-warn { + font-size: 12px; + color: #a04a24; +} + +.auth-problem { + font-size: 13px; + color: #a04a24; + background: #fbf1ec; + border: 1px solid #eddcd3; + border-radius: var(--radius); + padding: 10px 12px; +} + +.auth-foot { + font-size: 12px; + color: var(--muted-soft); + line-height: 1.5; + border-top: 1px solid #f0eee7; + padding-top: 12px; +}