From 61a539e9a2cce8af6b785a2e8bb07d6b505aef25 Mon Sep 17 00:00:00 2001 From: Samuel Van der Stappen Date: Mon, 5 Oct 2026 23:28:32 +0200 Subject: [PATCH] Add optional password login (MAILGREP_PASSWORD) A single shared password gates every /api route except login, logout and auth status. Sessions are stateless HMAC-signed HttpOnly SameSite=Strict cookies (30 days), keyed on the password and MAILGREP_KEY, so changing either signs everyone out. Failed attempts are serialised and delayed. Unset keeps today's behaviour, with a startup warning. The SPA shows a sign-in screen whenever /api/auth or any request returns 401, and settings gets a sign-out button. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 11 ++++ Cargo.toml | 1 + README.md | 13 +++-- SECURITY.md | 8 +-- docker-compose.yml | 2 + src/api.rs | 93 ++++++++++++++++++++++++++++++-- src/api_types.rs | 13 +++++ src/auth.rs | 96 +++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 8 ++- tests/api.rs | 63 ++++++++++++++++++++++ web/src/components/login.tsx | 36 +++++++++++++ web/src/generated/AuthStatus.ts | 3 ++ web/src/generated/LoginBody.ts | 3 ++ web/src/lib/auth.ts | 7 +++ web/src/main.tsx | 11 +++- web/src/routes/__root.tsx | 7 ++- web/src/routes/settings.tsx | 5 ++ 18 files changed, 367 insertions(+), 14 deletions(-) create mode 100644 src/auth.rs create mode 100644 web/src/components/login.tsx create mode 100644 web/src/generated/AuthStatus.ts create mode 100644 web/src/generated/LoginBody.ts create mode 100644 web/src/lib/auth.ts diff --git a/Cargo.lock b/Cargo.lock index a9ae58f..7d9622c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -537,6 +537,7 @@ dependencies = [ "block-buffer", "const-oid", "crypto-common", + "ctutils", ] [[package]] @@ -809,6 +810,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + [[package]] name = "home" version = "0.5.12" @@ -1306,6 +1316,7 @@ dependencies = [ "chacha20poly1305", "chrono", "hex", + "hmac", "http-body-util", "imap", "imap-proto", diff --git a/Cargo.toml b/Cargo.toml index 5760802..937b3c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ axum = "0.8.9" chacha20poly1305 = "0.11.0" chrono = "0.4.45" hex = "0.4.3" +hmac = "0.13.0" imap = "2" imap-proto = "0.10" libsql = { version = "0.9.30", default-features = false, features = ["core"] } diff --git a/README.md b/README.md index 381e564..f51795e 100644 --- a/README.md +++ b/README.md @@ -40,9 +40,11 @@ the accumulated damage of clients that disagree about dates and folder names. ## Self-hosting (Docker) -Requirements: Docker (or Podman) with compose, and an always-on box. mailgrep -has **no authentication**; the network is the trust boundary. Run it on a -private network (Tailscale, WireGuard, LAN) and never expose it publicly. +Requirements: Docker (or Podman) with compose, and an always-on box. Set +`MAILGREP_PASSWORD` to require a login; without it, the network is the only +trust boundary. Either way, run it on a private network (Tailscale, WireGuard, +LAN) and never expose it publicly: a single shared password is a second lock, +not a public-internet login. ```sh mkdir mailgrep && cd mailgrep @@ -51,6 +53,8 @@ curl -O https://raw.githubusercontent.com/samvdst/mailgrep/main/docker-compose.y # The key that encrypts your IMAP credentials at rest. Generate once and keep it: # losing it means re-entering your accounts. echo "MAILGREP_KEY=$(openssl rand -hex 32)" > .env +# The login password (optional; omit to run without a login). +echo "MAILGREP_PASSWORD=$(openssl rand -base64 18)" >> .env docker compose up -d # pulls ghcr.io/samvdst/mailgrep ``` @@ -127,6 +131,7 @@ rather than pretending to a unified relevance. | Env var | Default | Purpose | |---|---|---| | `MAILGREP_KEY` | - | 64 hex chars; encrypts IMAP credentials at rest (required to add accounts) | +| `MAILGREP_PASSWORD` | - | login password; unset means no login. Sessions last 30 days; changing it (or `MAILGREP_KEY`) signs everyone out | | `MAILGREP_DATA` | `/data` (image) | state directory | | `MAILGREP_BIND` | `0.0.0.0:8025` | listen address | | `MAILGREP_WEB` | `/app/web/dist` | SPA assets | @@ -175,7 +180,7 @@ regenerates them and CI rejects stale bindings. No IMAP writes (skewed dates are flagged, never "repaired"), no OCR or attachment content indexing (use something like Paperless-ngx for that), no -LLM query parsing, no auth (private network only), no real-time IDLE sync. +LLM query parsing, no user accounts (one shared password at most), no real-time IDLE sync. Semantic search is designed for as a future separate mode: the tables exist, nothing is generated yet. diff --git a/SECURITY.md b/SECURITY.md index e9da801..24fcf5e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -13,9 +13,11 @@ security problems before a fix is released. ## Design notes relevant to security - mailgrep is **read-only against IMAP**: it never writes to your mailbox. -- v1 ships **without authentication**: the network is the trust boundary. - Run it only on a private network (Tailscale, WireGuard, LAN). Do not - expose it to the public internet. +- Authentication is a single optional password (`MAILGREP_PASSWORD`); the + session is a stateless HMAC-signed `HttpOnly`, `SameSite=Strict` cookie. + Without it, the network is the only trust boundary. Either way, run it only + on a private network (Tailscale, WireGuard, LAN). Do not expose it to the + public internet. - IMAP credentials are encrypted at rest (XChaCha20-Poly1305) with a key supplied via `MAILGREP_KEY`, never stored beside the ciphertext. - Message HTML is sanitised server-side (ammonia) and rendered in a diff --git a/docker-compose.yml b/docker-compose.yml index c5589e1..fdfd335 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,6 +11,8 @@ services: # 64 hex chars; encrypts IMAP credentials at rest. Generate with: # openssl rand -hex 32 MAILGREP_KEY: "${MAILGREP_KEY:?set MAILGREP_KEY in .env}" + # login password; leave unset to run without a login + MAILGREP_PASSWORD: "${MAILGREP_PASSWORD:-}" volumes: - mailgrep-data:/data diff --git a/src/api.rs b/src/api.rs index 702cba3..f777cc0 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,6 +1,7 @@ //! JSON HTTP API. One screen, everything is a query. use crate::api_types::*; +use crate::auth::{self, Auth}; use crate::crypto::Crypto; use crate::index::{Indexes, SearchOptions}; use crate::queryparse::{Clause, FilterField}; @@ -8,8 +9,9 @@ use crate::source::{FixtureSource, MailSource}; use crate::store::{Account, Store}; use crate::sync::ProgressMap; use anyhow::{Context, Result}; -use axum::extract::{Path, Query, State}; -use axum::http::{StatusCode, header}; +use axum::extract::{Path, Query, Request, State}; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post}; use axum::{Json, Router}; @@ -21,6 +23,8 @@ pub struct App { pub store: Store, pub indexes: Indexes, pub crypto: Option, + /// `None` when no MAILGREP_PASSWORD is configured. + pub auth: Option, pub progress: ProgressMap, } @@ -75,7 +79,11 @@ pub fn make_source(account: &Account, crypto: &Option) -> Result Router { - Router::new() + let public = Router::new() + .route("/api/auth", get(auth_status)) + .route("/api/login", post(login)) + .route("/api/logout", post(logout)); + let protected = Router::new() .route("/api/status", get(status)) .route("/api/accounts", get(list_accounts).post(add_account)) .route("/api/accounts/{id}", delete(remove_account)) @@ -104,7 +112,84 @@ pub fn router(app: SharedApp) -> Router { .route("/api/merge", post(merge)) .route("/api/unmerge", post(unmerge)) .route("/api/merges", get(merges)) - .with_state(app) + .route_layer(middleware::from_fn_with_state(app.clone(), require_session)); + public.merge(protected).with_state(app) +} + +// ---------- auth ---------- + +fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64 +} + +fn session_cookie(headers: &HeaderMap) -> Option<&str> { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .find_map(|c| c.trim().strip_prefix(auth::COOKIE)?.strip_prefix('=')) +} + +fn authenticated(app: &App, headers: &HeaderMap) -> bool { + match &app.auth { + None => true, + Some(auth) => session_cookie(headers).is_some_and(|t| auth.verify(t, now_secs())), + } +} + +async fn require_session(State(app): State, request: Request, next: Next) -> Response { + if authenticated(&app, request.headers()) { + next.run(request).await + } else { + ApiError(StatusCode::UNAUTHORIZED, "login required".into()).into_response() + } +} + +/// Set-Cookie value; `Secure` when the request came in over HTTPS via a proxy, +/// so plain-HTTP access on a LAN still works. +fn set_cookie(headers: &HeaderMap, value: &str, max_age: i64) -> String { + let https = headers + .get("x-forwarded-proto") + .is_some_and(|v| v.as_bytes().eq_ignore_ascii_case(b"https")); + format!( + "{}={value}; Path=/; Max-Age={max_age}; HttpOnly; SameSite=Strict{}", + auth::COOKIE, + if https { "; Secure" } else { "" } + ) +} + +async fn auth_status(State(app): State, headers: HeaderMap) -> Json { + Json(AuthStatus { + required: app.auth.is_some(), + authenticated: authenticated(&app, &headers), + }) +} + +async fn login( + State(app): State, + headers: HeaderMap, + Json(body): Json, +) -> ApiResult { + let Some(auth) = &app.auth else { + return Ok(Json(OkResponse { ok: true }).into_response()); + }; + let _serialised = auth.attempts.lock().await; + if !auth.check_password(&body.password) { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + tracing::warn!("failed login attempt"); + return Err(ApiError(StatusCode::UNAUTHORIZED, "wrong password".into())); + } + let cookie = set_cookie(&headers, &auth.issue(now_secs()), auth::SESSION_SECS); + Ok(([(header::SET_COOKIE, cookie)], Json(OkResponse { ok: true })).into_response()) +} + +async fn logout(headers: HeaderMap) -> Response { + let cookie = set_cookie(&headers, "", 0); + ([(header::SET_COOKIE, cookie)], Json(OkResponse { ok: true })).into_response() } // ---------- status ---------- diff --git a/src/api_types.rs b/src/api_types.rs index 44da73b..a735e82 100644 --- a/src/api_types.rs +++ b/src/api_types.rs @@ -12,6 +12,19 @@ pub struct ErrorResponse { pub error: String, } +#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[ts(export)] +pub struct AuthStatus { + pub required: bool, + pub authenticated: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize, TS)] +#[ts(export)] +pub struct LoginBody { + pub password: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, TS)] #[ts(export)] pub struct StatusResponse { diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..7c4a7d6 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,96 @@ +//! Optional single-password login (MAILGREP_PASSWORD). Sessions are +//! stateless signed cookies, `.`, keyed on the password and +//! MAILGREP_KEY: changing either signs everyone out. + +use hmac::{Hmac, KeyInit, Mac}; +use sha2::{Digest, Sha256}; + +pub const COOKIE: &str = "mailgrep_session"; +pub const SESSION_SECS: i64 = 30 * 24 * 3600; + +pub struct Auth { + key: [u8; 32], + password_mac: Vec, + /// Held across failed attempts so guessing is serialised and slowed. + pub attempts: tokio::sync::Mutex<()>, +} + +impl Auth { + /// `None` when MAILGREP_PASSWORD is unset or empty: no login required. + pub fn from_env() -> Option { + let password = std::env::var("MAILGREP_PASSWORD").ok().filter(|p| !p.is_empty())?; + let secret = std::env::var("MAILGREP_KEY").unwrap_or_default(); + Some(Self::new(&password, secret.as_bytes())) + } + + pub fn new(password: &str, secret: &[u8]) -> Self { + let mut hasher = Sha256::new(); + hasher.update(b"mailgrep-session\0"); + hasher.update(secret); + hasher.update(b"\0"); + hasher.update(password.as_bytes()); + let key: [u8; 32] = hasher.finalize().into(); + let mut auth = Self { + key, + password_mac: Vec::new(), + attempts: Default::default(), + }; + auth.password_mac = auth.mac(b"password", password.as_bytes()).finalize().into_bytes().to_vec(); + auth + } + + fn mac(&self, domain: &[u8], data: &[u8]) -> Hmac { + let mut mac = Hmac::::new_from_slice(&self.key).expect("hmac takes any key length"); + mac.update(domain); + mac.update(b"\0"); + mac.update(data); + mac + } + + /// Constant-time password check. + pub fn check_password(&self, candidate: &str) -> bool { + self.mac(b"password", candidate.as_bytes()) + .verify_slice(&self.password_mac) + .is_ok() + } + + pub fn issue(&self, now: i64) -> String { + let expiry = (now + SESSION_SECS).to_string(); + let sig = self.mac(b"session", expiry.as_bytes()).finalize().into_bytes(); + format!("{expiry}.{}", hex::encode(sig)) + } + + pub fn verify(&self, token: &str, now: i64) -> bool { + let Some((expiry, sig)) = token.split_once('.') else { + return false; + }; + let (Ok(exp), Ok(sig)) = (expiry.parse::(), hex::decode(sig)) else { + return false; + }; + exp > now && self.mac(b"session", expiry.as_bytes()).verify_slice(&sig).is_ok() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn password_and_sessions() { + let auth = Auth::new("hunter2", b"key"); + assert!(auth.check_password("hunter2")); + assert!(!auth.check_password("hunter3")); + assert!(!auth.check_password("")); + + let token = auth.issue(1_000); + assert!(auth.verify(&token, 1_000)); + assert!(!auth.verify(&token, 1_000 + SESSION_SECS)); + assert!(!auth.verify(&token.replace('.', ".0"), 1_000)); + assert!(!auth.verify("garbage", 1_000)); + + let (_, sig) = token.split_once('.').unwrap(); + assert!(!auth.verify(&format!("{}.{sig}", 1_000 + 10 * SESSION_SECS), 1_000)); + assert!(!Auth::new("other", b"key").verify(&token, 1_000)); + assert!(!Auth::new("hunter2", b"other").verify(&token, 1_000)); + } +} diff --git a/src/lib.rs b/src/lib.rs index 396aadc..f9b226a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod api; pub mod api_types; +pub mod auth; pub mod config; pub mod crypto; pub mod imapsource; diff --git a/src/main.rs b/src/main.rs index 08b2629..38f717e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use mailgrep::{api, crypto, index, store}; +use mailgrep::{api, auth, crypto, index, store}; use axum::Router; use std::path::PathBuf; use std::sync::Arc; @@ -29,10 +29,16 @@ async fn main() -> Result<()> { } }; + let auth = auth::Auth::from_env(); + if auth.is_none() { + tracing::warn!("MAILGREP_PASSWORD not set: no login required, the network is the only protection"); + } + let app = Arc::new(api::App { store, indexes, crypto, + auth, progress: Default::default(), }); diff --git a/tests/api.rs b/tests/api.rs index 129f807..aed0fdc 100644 --- a/tests/api.rs +++ b/tests/api.rs @@ -128,6 +128,7 @@ async fn setup() -> TestApp { store, indexes, crypto: None, + auth: None, progress: Default::default(), }); let router = api::router(app.clone()); @@ -503,6 +504,7 @@ async fn bounded_subset_and_account_removal() { store, indexes: Indexes::new(data.join("index")), crypto: None, + auth: None, progress: Default::default(), }); let router = api::router(app.clone()); @@ -533,3 +535,64 @@ async fn bounded_subset_and_account_removal() { let (_, body) = req(&router, "GET", "/api/status", None).await; assert_eq!(body["accounts"].as_array().unwrap().len(), 0); } + +#[tokio::test(flavor = "multi_thread")] +async fn password_login_gates_the_api() { + let tmp = tempfile::tempdir().unwrap(); + let store = Store::open(tmp.path().join("db.sqlite").to_str().unwrap()).await.unwrap(); + let app: SharedApp = Arc::new(App { + store, + indexes: Indexes::new(tmp.path().join("index")), + crypto: None, + auth: Some(mailgrep::auth::Auth::new("hunter2", b"key")), + progress: Default::default(), + }); + let router = api::router(app); + + let (s, body) = req(&router, "GET", "/api/auth", None).await; + assert_eq!(s, StatusCode::OK); + assert_eq!(body, serde_json::json!({"required": true, "authenticated": false})); + let (s, _) = req(&router, "GET", "/api/status", None).await; + assert_eq!(s, StatusCode::UNAUTHORIZED); + let (s, _, _) = raw_req(&router, "/api/message/1/raw").await; + assert_eq!(s, StatusCode::UNAUTHORIZED); + + let (s, _) = req(&router, "POST", "/api/login", Some(serde_json::json!({"password": "nope"}))).await; + assert_eq!(s, StatusCode::UNAUTHORIZED); + + let login = Request::builder() + .method("POST") + .uri("/api/login") + .header("content-type", "application/json") + .header("x-forwarded-proto", "https") + .body(Body::from(r#"{"password":"hunter2"}"#)) + .unwrap(); + let resp = router.clone().oneshot(login).await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let set_cookie = resp.headers()["set-cookie"].to_str().unwrap().to_string(); + assert!(set_cookie.contains("HttpOnly") && set_cookie.contains("Secure"), "{set_cookie}"); + let cookie = set_cookie.split(';').next().unwrap().to_string(); + + let with_cookie = |uri: &str| { + Request::builder() + .uri(uri) + .header("cookie", format!("theme=dark; {cookie}")) + .body(Body::empty()) + .unwrap() + }; + let resp = router.clone().oneshot(with_cookie("/api/status")).await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let resp = router.clone().oneshot(with_cookie("/api/auth")).await.unwrap(); + let body: Value = serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap(); + assert_eq!(body["authenticated"], true); + + let tampered = Request::builder() + .uri("/api/status") + .header("cookie", format!("{cookie}0")) + .body(Body::empty()) + .unwrap(); + assert_eq!(router.clone().oneshot(tampered).await.unwrap().status(), StatusCode::UNAUTHORIZED); + + let (s, _) = req(&router, "POST", "/api/logout", None).await; + assert_eq!(s, StatusCode::OK); +} diff --git a/web/src/components/login.tsx b/web/src/components/login.tsx new file mode 100644 index 0000000..5acf6b5 --- /dev/null +++ b/web/src/components/login.tsx @@ -0,0 +1,36 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { Inbox, LoaderCircle } from "lucide-react"; +import { useState, type FormEvent } from "react"; +import type { LoginBody } from "@/generated/LoginBody"; +import type { OkResponse } from "@/generated/OkResponse"; +import { post } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; + +export function Login() { + const client = useQueryClient(); + const [password, setPassword] = useState(""); + const login = useMutation({ + mutationFn: (body: LoginBody) => post("/api/login", body), + onSuccess: () => void client.invalidateQueries(), + }); + const submit = (event: FormEvent) => { + event.preventDefault(); + if (password) login.mutate({ password }); + }; + + return ( +
+
+
+ + mailgrep +
+ + setPassword(event.target.value)} /> + {login.error &&

{login.error.message}

} + +
+
+ ); +} diff --git a/web/src/generated/AuthStatus.ts b/web/src/generated/AuthStatus.ts new file mode 100644 index 0000000..ac4b5a1 --- /dev/null +++ b/web/src/generated/AuthStatus.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AuthStatus = { required: boolean, authenticated: boolean, }; diff --git a/web/src/generated/LoginBody.ts b/web/src/generated/LoginBody.ts new file mode 100644 index 0000000..3603612 --- /dev/null +++ b/web/src/generated/LoginBody.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type LoginBody = { password: string, }; diff --git a/web/src/lib/auth.ts b/web/src/lib/auth.ts new file mode 100644 index 0000000..b8b3b85 --- /dev/null +++ b/web/src/lib/auth.ts @@ -0,0 +1,7 @@ +import { queryOptions } from "@tanstack/react-query"; +import type { AuthStatus } from "@/generated/AuthStatus"; +import { api } from "@/lib/api"; + +export const authQuery = queryOptions({ queryKey: ["auth"], queryFn: ({ signal }) => api("/api/auth", { signal }), staleTime: Infinity }); + +export const signedOut: AuthStatus = { required: true, authenticated: false }; diff --git a/web/src/main.tsx b/web/src/main.tsx index 27acc08..629da38 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,11 +1,20 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { MutationCache, QueryCache, QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { createRouter, RouterProvider } from "@tanstack/react-router"; import { routeTree } from "./routeTree.gen"; +import { ApiError } from "@/lib/api"; +import { authQuery, signedOut } from "@/lib/auth"; import "./index.css"; +// Any 401 means the session is gone: flip the root route to the login screen. +const onError = (error: Error) => { + if (error instanceof ApiError && error.status === 401) queryClient.setQueryData(authQuery.queryKey, signedOut); +}; + const queryClient = new QueryClient({ + queryCache: new QueryCache({ onError }), + mutationCache: new MutationCache({ onError }), defaultOptions: { queries: { staleTime: 30_000, diff --git a/web/src/routes/__root.tsx b/web/src/routes/__root.tsx index 36b1047..11d2c4d 100644 --- a/web/src/routes/__root.tsx +++ b/web/src/routes/__root.tsx @@ -1,8 +1,10 @@ import { createRootRouteWithContext, Outlet } from "@tanstack/react-router"; -import type { QueryClient } from "@tanstack/react-query"; +import { useQuery, type QueryClient } from "@tanstack/react-query"; import { useEffect } from "react"; import { SearchX } from "lucide-react"; import { Button } from "@/components/ui/button"; +import { Login } from "@/components/login"; +import { authQuery } from "@/lib/auth"; import { useUiStore } from "@/store/ui"; export type RouterContext = { queryClient: QueryClient }; @@ -23,6 +25,7 @@ export const Route = createRootRouteWithContext()({ function Root() { const theme = useUiStore((state) => state.theme); + const auth = useQuery(authQuery); useEffect(() => { const media = matchMedia("(prefers-color-scheme: dark)"); @@ -32,5 +35,7 @@ function Root() { return () => media.removeEventListener("change", apply); }, [theme]); + if (auth.isPending) return null; + if (auth.data?.required && !auth.data.authenticated) return ; return ; } diff --git a/web/src/routes/settings.tsx b/web/src/routes/settings.tsx index a36cb44..eeec1b3 100644 --- a/web/src/routes/settings.tsx +++ b/web/src/routes/settings.tsx @@ -10,6 +10,7 @@ import { Database, FolderCog, HardDrive, + LogOut, ImageOff, Inbox, LoaderCircle, @@ -41,6 +42,7 @@ import type { RenameBody } from "@/generated/RenameBody"; import type { RevokeBody } from "@/generated/RevokeBody"; import type { MergeBody } from "@/generated/MergeBody"; import { api, del, post, put } from "@/lib/api"; +import { authQuery } from "@/lib/auth"; import { cn, formatBytes, formatLocalDate } from "@/lib/utils"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; @@ -65,6 +67,8 @@ function SettingsPage() { ...statusQuery, refetchInterval: (query) => query.state.data?.accounts.some((account) => account.progress?.running) ? 2_000 : false, }); + const auth = useQuery(authQuery); + const logout = () => void post("/api/logout").finally(() => location.assign("/")); const setTab = (next: SettingsTab) => void navigate({ search: next === "accounts" ? {} : { tab: next }, replace: true }); useEffect(() => { @@ -81,6 +85,7 @@ function SettingsPage() {
mailgrep settings
{status.data && v{status.data.version}} + {auth.data?.required && }